Documentation
¶
Overview ¶
Package edit rewrites identifiers in source files under one project root.
It is the only package in GraphLume that writes to a user's source tree, so it is built to refuse: an identifier it cannot find, or cannot tell apart from a same-named neighbour on the same line, is an error, never a guess.
Index ¶
- Constants
- Variables
- func Locate(src []byte, line int, old string, cols []int) ([]int, error)
- func Occurrences(line []byte, name string) []int
- func Splice(src []byte, old, repl string, offsets []int) ([]byte, error)
- type Editor
- func (e *Editor) Commit(ctx context.Context, prepared []Prepared) error
- func (e *Editor) CommitChecked(ctx context.Context, prepared []Prepared, check func(context.Context) error) (err error)
- func (e *Editor) Create(f File, content []byte, like File) (Prepared, *Problem)
- func (e *Editor) Load(path string) (File, *Problem, error)
- func (e *Editor) LoadDir(dir string, keep func(name string) bool) ([]File, []Problem, error)
- func (e *Editor) Prepare(ctx context.Context, edits []FileEdit) ([]Prepared, []Problem, error)
- func (e *Editor) PrepareDirect(ctx context.Context, filePath, wantHash string, newData []byte) (Prepared, []Problem, error)
- func (e *Editor) Rewrite(f File, after []byte) (Prepared, *Problem)
- type File
- type FileEdit
- type Option
- type Prepared
- type Problem
- type Source
Constants ¶
const DefaultMaxFileBytes int64 = 8 << 20
DefaultMaxFileBytes bounds one file the editor reads. A source file larger than this is almost certainly generated, and a rename has no business rewriting it unattended.
Variables ¶
var ( // ErrNotFound: the line does not contain the identifier. The file no longer // says what the index says it does. ErrNotFound = errors.New("edit: identifier not found on the line") // ErrAmbiguous: the identifier occurs more than once on the line and no // recorded column singles out which occurrence the site is. ErrAmbiguous = errors.New("edit: identifier occurs more than once on the line and no column singles out the site") // ErrStale: the file's bytes are not the ones that were indexed or planned. ErrStale = errors.New("edit: file changed since it was indexed") // ErrOverlap: two replacements claim the same bytes. ErrOverlap = errors.New("edit: replacements overlap") )
Errors a caller branches on.
var ErrCheckFailed = errors.New("edit: the check of the written files failed")
ErrCheckFailed: every file was written, the caller's check of the result then failed, and the files were restored. Joined with ErrRollbackIncomplete if they could not all be.
var ErrLockRelease = errors.New("edit: release lock")
ErrLockRelease: the lock could not be removed after a Commit. It is joined to whatever else Commit returns; on its own it means every file was written and only the lock was left behind.
var ErrLocked = errors.New("edit: another edit is in progress")
ErrLocked: another Commit holds the project root's lock, or one crashed and left it behind. The lock is never stolen — a stale one has to be deleted by a person who has checked no edit is running.
var ErrRollbackIncomplete = errors.New("edit: rollback incomplete")
ErrRollbackIncomplete: a Commit failed and at least one file it had already written could not be restored. It is the one Commit error after which the tree may hold some of the new text; the joined errors name each such file.
Functions ¶
func Locate ¶
Locate finds the absolute byte offsets in src at which old must be replaced for the sites recorded on one line.
cols holds the evidence column of every site on the line, -1 where none was recorded. Stored columns are unreliable in two ways: tree-sitter edges record the start of the call expression rather than the name, and SCIP indexers for the JVM and TypeScript count UTF-16 code units where tree-sitter counts bytes. So a column is trusted only if old, as a whole identifier, starts exactly there under BOTH readings — which is to say the line before it is plain ASCII. Otherwise f("é", Save, Save) would let the UTF-16 column of the second Save select the first.
- old occurs once on the line: that occurrence.
- more than once: exactly the occurrences the columns select, provided every distinct column selects one. Anything else is ErrAmbiguous: a line holding a.Save() and b.Save() names two methods, and guessing which one is the target is how a rename corrupts code.
- not at all: ErrNotFound.
func Occurrences ¶
Occurrences returns the offsets, relative to line, at which name occurs as a whole identifier — the rule every edit uses, so a caller looking for what a rename left behind counts exactly what a rename would have matched.
Types ¶
type Editor ¶
type Editor struct {
// contains filtered or unexported fields
}
Editor rewrites files under one root and nowhere else.
Every filesystem operation goes through an os.Root opened on the project root, so no path component — including one swapped for a symlink between a check and a use — can lead the editor outside it. On top of that the editor refuses any path with a symlinked component at all, inside the root or not: a rename edits the file the index saw, and a link is a second name for some other file.
func (*Editor) Commit ¶
Commit writes every prepared file atomically: a temp file in the same directory, fsync, a re-check that the target still holds exactly the bytes Prepare read, then a rename over it. If any file fails — stale, unwritable, cancelled — nothing more is written and every file already replaced is restored, newest first.
Rollback deliberately ignores ctx: a cancelled commit must still put back what it changed.
Only one Commit runs per project root at a time; see ErrLocked.
func (*Editor) CommitChecked ¶
func (e *Editor) CommitChecked(ctx context.Context, prepared []Prepared, check func(context.Context) error) (err error)
CommitChecked is Commit followed by check, run while the root's lock is still held so no other edit can land between the write and its verification. If check returns an error — a build that no longer passes, say — every file is restored exactly as after a failed write, and the error wraps ErrCheckFailed and what check returned. A nil check makes this Commit.
Files are written in the order given. A caller whose edit moves text from one file to another lists the receiving file first: an interruption between the two writes then leaves the text in both files, never in neither.
func (*Editor) Create ¶
Create prepares the creation of f, which Load found absent, holding content with like's permissions (a new file beside the one its text came from should be as readable and writable as that one). Commit refuses if anything has appeared at the path in the meantime; it never overwrites.
func (*Editor) Load ¶
Load reads path under every rule Prepare applies: inside the root, no symlinked component, a regular file, within the size limit. A path with nothing at it is not a problem: it comes back with Exists false, provided the directory it would be created in is a real directory inside the root. A problem is data; the error is non-nil only when the root itself cannot be opened.
func (*Editor) LoadDir ¶
LoadDir loads every regular entry of dir (relative to the root, "." for the root itself) whose name keep accepts, sorted by name. Subdirectories are skipped. An accepted entry that cannot be read safely — a symlink, a FIFO, a file over the limit — is a problem, not a silent omission: the caller asked for the whole set.
func (*Editor) Prepare ¶
Prepare reads each file inside the root, checks it against the hash the index recorded, locates every site and computes the new bytes. It writes nothing. A file with any problem contributes no Prepared entry. The error is non-nil only when ctx is done or the root itself cannot be opened.
func (*Editor) PrepareDirect ¶
func (e *Editor) PrepareDirect(ctx context.Context, filePath, wantHash string, newData []byte) (Prepared, []Problem, error)
PrepareDirect prepares an in-place full-file replacement of filePath with newData. It verifies that the file inside the project root matches wantHash (if non-empty), is regular and writable, and does not exceed maxBytes.
type File ¶
type File struct {
// Path is relative to the project root, forward slashes, spelled as the
// directory spells it.
Path string
// Data is the file's content; nil when Exists is false.
Data []byte
// Exists is false when nothing is at Path and its directory is a real
// directory inside the root, so the file could be created.
Exists bool
// contains filtered or unexported fields
}
File is one file as the editor read it, or the finding that the path is free. Only Load and LoadDir make one that Rewrite and Create accept.
type FileEdit ¶
type FileEdit struct {
// Path is relative to the project root, forward slashes, as the index
// records it.
Path string
// WantHash is model.File.ContentHash for this path in the indexed run.
WantHash string
Old, New string
// Lines maps a 1-indexed line to the evidence column hints of every site
// on it (-1 = none). See Locate.
Lines map[int][]int
}
FileEdit is every replacement of Old by New in one file.
type Option ¶
type Option func(*Editor)
Option configures an Editor.
func WithMaxFileBytes ¶
WithMaxFileBytes overrides DefaultMaxFileBytes. Values <= 0 are ignored.
type Problem ¶
type Problem struct {
Path string `json:"path"`
Line int `json:"line,omitempty"` // 0 for a whole-file problem
Reason string `json:"reason"`
Err error `json:"-"`
}
Problem is a site or file that cannot be edited safely. Problems are data, not errors: the caller lists every one and writes nothing.
type Source ¶
type Source struct {
// contains filtered or unexported fields
}
Source is one file's bytes with its line starts indexed once, so locating every site in a file costs O(file size + total line length) rather than a scan from the top for each line.