diff --git a/CHANGELOG.md b/CHANGELOG.md index c61e7f40..ed44f946 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,10 @@ When `patchbook track` failed after its sync, such as when `.patchbook/config.to `patchbook sync` used to stop with a stack trace when a change's `base/.pb` or `ours/.pb` was missing. Now it fails with a `patchbook:` message that names each change, file and missing copy, both copies when both are gone, and changes nothing. Restore the copies, or remove the edit from the change, and sync again (#10). +### An edited copy keeps following upstream + +Copy an upstream file, commit so `record` writes `copy skills/a -> skills/b`, then edit `skills/b/SKILL.md` and commit. `record` and the commit hook used to write `replace skills/b/SKILL.md`, a frozen copy, so `skills/b` missed every later upstream change to `skills/a`, and `status` said nothing. Now they write `file skills/b/SKILL.md`, a file edit on the copy's own path whose base is upstream's `skills/a/SKILL.md`. `sync` merges upstream's changes to `skills/a` into it. An upstream change that overlaps your edit is a conflict, which `sync` reports and `status`, `build` and the commit hook refuse, as for any file edit. `skills/a` still builds from upstream, without your edit. The file edit applies where the `replace` did in the series, so a later hand-written `copy` or `move` of `skills/b` still builds your edit, and `record` writes it only into the change with the `copy` or a later one. An edited rename of a file that a copy still builds from is now `move` plus a `file` edit on the new path, where it was `delete` plus `add`. Once a copy has its own file edit, an edit to its source is a `file` edit as well, where it was a `replace`. Deleting the edited copy takes its file edit out of the change and records a `delete`, unless a later copy or move reads it, when the edit stays. An edited copy that isn't text, or whose source upstream makes binary, keeps your bytes and builds, as the `replace` did, since `sync` merges only text. `sync` then moves its base to upstream's file, lists it in `replacedUpstreamChanged` and says on stderr that it kept yours. To take upstream's file instead, write it over the copy and run `patchbook record`. A copy's file edit now needs its base copy, and `status` and `build` refuse and name the change and the missing copy when it is gone, where the `replace` built the frozen copy without one. A copy recorded as a `replace` before this release stays one (#317). + ### A partial commit can't move the upstream pin without its vendored copy `git commit -- note.txt .patchbook/upstream.lock` after a `patchbook sync` used to commit the new pin and leave the vendored copy at the old one, and a clone's `status` then failed with `vendor/extra (tree ...) differs from the pin`. The hook now refuses that commit before it records or builds anything, and names the upstream, the lock and the vendor folder. Add the lock and the folder to the paths you name, or run `git add` on the lock, and on the file it points to when it is a link, and make a full commit, where the hook stages the pinned copy. When the lock is a link to a file in the repo, name that file too. When git doesn't know a path yet, such as the folder of a first vendoring, the message says to `git add` it first, since `git commit -- ` fails on a path git doesn't know. A refused commit leaves HEAD, your index and your working files as they were. A partial commit that doesn't move the pin, such as one that only names `note.txt`, is not refused by this check, including when HEAD's lock is a link that leads out of the repo. A copy that differs from the pin still gets the message that it differs from the pin. The message for an unstaged `upstream.lock` gives the same advice. It names the lock, the file a linked lock points to, the copies, and any other unstaged build input, where it said that naming the lock alone was enough (#227). diff --git a/DESIGN.md b/DESIGN.md index 941669f2..c0a85922 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -77,7 +77,7 @@ Edit kinds: | Edit | Stores | Use | | --- | --- | --- | -| `file ` | base and ours | Changing an upstream file. | +| `file ` | base and ours | Changing an upstream file, at its own path or at the destination of a copy or move. | | `add ` | ours | A file upstream doesn't have. | | `replace ` | ours | Our version wins outright, with no merge. For binaries and full rewrites. | | `delete ` | nothing | A file or folder we don't want. | @@ -104,7 +104,7 @@ Under `core.fileMode=false`, `git add` keeps an entry's mode and gives a new one 1. Stage upstream at the pin. 2. Apply content edits on upstream paths: block entries, then `file` edits in series order. A `file` edit whose base differs from the staged upstream file is **stale**, since sync should have merged it. -3. Apply structural edits in series order: add, replace, delete, move, copy. +3. Apply structural edits in series order: add, replace, delete, move, copy. A `file` edit on a path upstream doesn't have applies here too, in its place in the series. It edits the upstream file that an earlier `copy` or `move` stages at its path, and is **stale** when its base differs from that file. From there on its ours copy is that path's file, as a `replace` would be, so a later `copy` or `move` of the path reads the edit, and the source and its other copies keep upstream's text. One on a path that no earlier copy or move of an upstream file reaches is **gone**. Once every structural edit applies, an edit whose ours copy no staged path reads, as after a later `replace` or `delete` of its path that no `copy` or `move` reads first, builds nothing. The build doesn't check it for **stale** or conflict markers, and sync doesn't merge it. 4. Run the hooks: fill placeholders, then `finish(out)`. 5. Run the checks on the output. 6. Write the output: the configured folder (folder layout), or the repo root (fork). @@ -160,7 +160,7 @@ Patchbook would follow a link inside `.patchbook/` out of the repo, or into anot - `patchbook check` compares each upstream's head with its pin. It exits 0 when all are up to date and 10 when any has moved, and prints JSON. A fork's upstream moved only if a file outside upstream's own `.patchbook/` changed, so a commit that touches nothing else exits 0. `sync` still pins such a commit when asked, since the pin is the raw commit and tree, and it reports no changed files for it. - `patchbook sync [name] [ref]` fetches each upstream (or the named one, at a ref) into the store, and updates its pin and its vendored copy, if it keeps one. Then it carries every change on that upstream's files forward: - - **file edits**: `git merge-file` with base, ours, and the new upstream file. A clean merge updates ours and sets base to the new upstream file. Upstream's mode moves into both copies, unless the change set a mode of its own on ours. A conflict leaves markers in ours and reports **conflict**. A clean merge can still put an edit of a repeated paragraph on another copy than the one ours edits, once upstream moves what lies around that copy. So sync tells the copies apart as occurrence entries do (see Changes), and when the merge edits other copies than ours does, or leaves out ours's edit of a copy, it reports **conflict** instead. An edit counts for the paragraph on each side of it too, since an insert there may be meant for that copy. Upstream making the same edit to a copy also leaves ours's edit out, so that is a conflict as well. Ours then holds our text and upstream's between markers wherever the two differ, and sync names the file on stderr. A copy is told apart by its place among the copies and by the paragraphs between it and the next copy on each side, so when upstream adds or removes a copy, or edits a paragraph in that stretch, an edit of the copy or next to it is a conflict too. An edit that reaches no copy merges as usual. A clean merge can also get the number of a paragraph's copies wrong, in any file. `git merge-file` reads a moved paragraph as a delete and an insert, so it brings back a paragraph ours deletes once upstream moves it, and keeps one copy where both sides insert the same paragraph in one place. So for each paragraph that both base and the new upstream file hold, when the merge adds or removes a different number of copies than ours does, sync reports **conflict** too, unless upstream already made the same change. Text only one side holds is an edit, which `git merge-file` already checks. A file upstream deleted or moved reports **gone**, with likely new paths. + - **file edits**: `git merge-file` with base, ours, and the new upstream file, which for a `file` edit on a copy's or move's destination is the file the copy or move stages there at the pins. Sync skips a destination's `file` edit that builds nothing (see Build). When base, ours or the new upstream file of a destination's `file` edit isn't text, sync can't merge it, so it keeps ours, as the `replace` it stands for kept ours, sets base to the new upstream file, lists the edit in `replacedUpstreamChanged` and names the file on stderr. Such a `file` edit on an upstream path reports **conflict** and keeps its base. A clean merge updates ours and sets base to the new upstream file. Upstream's mode moves into both copies, unless the change set a mode of its own on ours. A conflict leaves markers in ours and reports **conflict**. A clean merge can still put an edit of a repeated paragraph on another copy than the one ours edits, once upstream moves what lies around that copy. So sync tells the copies apart as occurrence entries do (see Changes), and when the merge edits other copies than ours does, or leaves out ours's edit of a copy, it reports **conflict** instead. An edit counts for the paragraph on each side of it too, since an insert there may be meant for that copy. Upstream making the same edit to a copy also leaves ours's edit out, so that is a conflict as well. Ours then holds our text and upstream's between markers wherever the two differ, and sync names the file on stderr. A copy is told apart by its place among the copies and by the paragraphs between it and the next copy on each side, so when upstream adds or removes a copy, or edits a paragraph in that stretch, an edit of the copy or next to it is a conflict too. An edit that reaches no copy merges as usual. A clean merge can also get the number of a paragraph's copies wrong, in any file. `git merge-file` reads a moved paragraph as a delete and an insert, so it brings back a paragraph ours deletes once upstream moves it, and keeps one copy where both sides insert the same paragraph in one place. So for each paragraph that both base and the new upstream file hold, when the merge adds or removes a different number of copies than ours does, sync reports **conflict** too, unless upstream already made the same change. Text only one side holds is an edit, which `git merge-file` already checks. A file upstream deleted or moved reports **gone**, with likely new paths. - **block entries**: an entry whose paragraph changed reports **orphan**, with the nearest new paragraphs. - When upstream still matches the pin, `sync` hashes the vendored copy. If the copy does not match the pin, such as one that is empty, missing, edited by hand, half written, or a symlink in place of the folder, `sync` writes it again and says so. A symlink is moved into the folder with the old copy, never followed, and comes back as a link if the rewrite fails or is killed. As in a sync that moves the pin, the old copy waits in `.patchbook/sync-/` until the new one checks out. It leaves the change files, `last-sync.json` and the lock alone. A failed or killed rewrite puts the copy back as it was, and the next `sync` writes it again. If the lock has changed since a kill, the folder is left for the user, as for a killed sync that moves the pin. - **`last-sync.json` is ignored, not committed.** It holds each upstream's latest report (`{version: 1, upstreams: {: {from, to, ...}}}`, see JSON output), kept across runs, so it is state of one checkout. Every `sync` that ends with the file on disk, even one with nothing to do, makes sure `.patchbook/.gitignore` lists `last-sync.json` and `.gitignore`, appending what is missing and leaving the bytes already there as they are. Writing the rules is best effort: if the file can't be read or written, `sync` prints a `patchbook:` warning that `last-sync.json` stays untracked, and its own result and exit code are unchanged. A repo made before this gets the ignore on its next sync, with no step for the user. The file ignores itself, so while neither file is tracked a sync leaves nothing untracked and `git add -A` adds neither; a repo that committed either one sees it modified. Why ignored: @@ -169,8 +169,8 @@ Patchbook would follow a link inside `.patchbook/` out of the repo, or into anot - The sync journal already treats it as local state: it saves the file and puts it back when a sync fails, and keeps its own folder out of git the same way. - A repo that already committed the file keeps it tracked, since an ignore does not untrack a file. `git rm --cached .patchbook/last-sync.json` ends that, and sync does not run it for the user. - `patchbook status [--json]` lists the problems, what sync merged on its own, and how much upstream changed in each file we touch. Plain `status` also prints a `note` line for each change whose intent patchbook wrote, with the command that replaces it. It prints the same kind of note, `the output is behind the patchbook`, naming up to five files when a build would change an output file that no hand edit explains, as after a `sync`, or a pull or checkout that skipped the post hooks below. A note is not a problem: it doesn't change the exit code or the summary. -- `patchbook record [change] [--intent ...]` takes the output files in the working tree edited by hand since the last build (per `build.lock`) and moves each edit into the patchbook. In a file with block entries, each changed paragraph updates its entry, or gets a new `policy` entry; a new paragraph joins the one before it, and a paragraph put back as upstream had it loses its entry. If an edited paragraph's entry uses a placeholder with an empty value, it records none of that file's paragraph edits and says so, since the edit can't show where that placeholder goes; edit that entry by hand. Other edits become `file`, `add` or `delete` edits based on the pinned upstream. A new output that builds byte for byte and mode for mode as a staged upstream file builds is a `copy` of that file instead, so it follows upstream. `record` writes the copy for the widest folder whose staged files all went the same way into a folder that held nothing staged, as in `copy extra/skills/x -> skills/x`, so a file upstream adds to that folder later ships too. An empty file joins such a folder copy but never picks a copy by itself. A new output stays an `add` when it matches files at two upstream paths, when this recording also edits or deletes the file it matches, or when it was edited before the copy was recorded. A deleted upstream output and a new output are a `move` of that file instead, as after `git mv`, when the new output builds as the deleted one did. They are a `move` too when what still differs records as a `file` edit or as block entries, and the two texts keep, in order, at least half of the longer one's non-blank lines and two lines with a letter or digit. `record` widens the move to folders the same way as a copy, empty files included, and writes the content edit after it on the file's upstream path, as in `move skills/a -> skills/a2` and `file skills/a/SKILL.md`, so the moved file keeps following upstream and keeps its block entries. An exact move wins over an exact copy, and an exact copy over an edited move. A new output that deleted outputs of two upstream files match equally well stays an `add`. `record ` refuses a copy or a move when a change later in the series edits its source or its destination. After it saves a copy or a move, `record` builds again, and if the build differs from the files on disk, as when a `finish` hook rewrites a copied file or writes a moved one back, `record` fails and puts `.patchbook` back. A mode change is recorded too, as `chmod +x` on an upstream file with no other edit, or beside a content edit, by the rule in [The executable bit](#the-executable-bit). A file with block entries holds no mode, so a mode change there is skipped, with a reason that says how to set it in a `finish` hook, and its content edits still record. An edit to a file a change already owns goes to that change. When an edit joins a change that already exists, whether that change owns the file, you named it, or the model picked it, or rewrites a paragraph that already has a block entry, the model writes that change's or entry's intent again: from its whole diff with the edit in it and without any edit this record takes out of it, or, for a change the model picks, from its old intent and the new edits' diff. It does this in the same call that writes the record's other intents, so `record` asks the model at most once. If you gave the intent, or no model answers (see below), each one it doesn't set keeps its intent, and `record` prints one `intent may be stale` note that names them. A change whose intent patchbook wrote, or that has none, is the exception: `record` writes it again from all the change's edits. Taking an edit out of a change doesn't join it, so a change left with fewer edits keeps its intent. A given intent is for the change being recorded. When no edit goes to that change and no block entry needs it, `record` says the intent wasn't used, and names the changes the edits went to. Naming a change that exists with `--intent` still sets its intent, so then it says nothing. For the other edits, a model reads their diff and writes the intent if you didn't. If the model call fails, whether the CLI is missing or can't start, it exits non-zero, it takes longer than `intent.timeout` or its reply has no usable name and intent, or `intent.provider` is `none`, `record` still records. An edit that needs a change name goes to the change you named, or else to a new change named from the first edit, as `rename-skills-a-to-skills-a2` for `move skills/a -> skills/a2`, kept within 40 characters and given the next free suffix (`-2`, `-3`, ...) when the name is taken. It never joins another change, since picking one is the model's call. Patchbook writes the change's intent from its edits once they apply: a sentence for each kind of edit, in the order the edits come, that names the first three paths and counts the rest, as in `Renames skills/a to skills/a2. Edits skills/a/SKILL.md.` A move within one folder is a rename, and a move or a copy to the same path under another folder says only the folder it comes from, as in `Copies skills/x from extra.` for `copy extra/skills/x -> skills/x`. `CHANGE.md` labels that intent `intent (by patchbook):`, and `status` lists the change as a note, not a problem, so `build` and the hook's build go ahead. `record` prints one `intent by patchbook` note with the failure's first line and the two ways to replace the intent, `patchbook intent ` or an edit of its line to `intent: ...`, and exits 0. The intent stays patchbook's while its line keeps the label, so a later record that changes the change's edits writes it again. A new block entry gets an intent written the same way, from its paragraph edit and labelled `intent (by patchbook):` in the entries file, so `build` goes ahead. `status` lists each as a note, and `record` names it in its one `intent by patchbook for` line, beside any change patchbook wrote the intent of. A block entry that `record` updates again with no model gets its patchbook-written intent written again; one whose intent someone wrote keeps it, and `record` names it in the `may be stale` note. An existing block entry whose intent is empty keeps it empty (#349). A record that needs no new or rewritten intent, and a given `--intent`, never call the model. A timeout kills the model and everything it started. When the model picks an existing change, its intent replaces that change's. Without a change name, the model also picks one: an existing change the edits serve, or a new name. If you give an intent but no name, the model isn't called: the change is named from the intent's first four words, dropping any that would take the name past 40 characters. Any intent is kept on one line, with each run of whitespace a single space, and a blank intent counts as none. A name given to `record` must follow the change-name rule (see Change names), and `record` refuses before it writes while `series` holds a name that breaks it. Anything under `changes/` that `series` doesn't list is a stray, and `record` never writes into one: `record ` refuses a stray name before it writes, and a name from an intent or the model takes the next free suffix (`-2`, `-3`, ...) instead. Deleting the output of a `replace` takes the `replace` and its copy out of the change that owns it and records a `delete` of the path in the change being recorded, as does deleting an output that a `move` or `copy` made or a copy another output is still built from, and a change left with no edits stays, with its intent and an empty `edits:` list. A failed record leaves the patchbook as it was, though not for a write through a symlink inside `.patchbook` (#169): `record` puts `.patchbook` back to what it was before its first write and prints no note of what it saved, so the same command run again records the same edits with the same `--intent`. If a file can't be put back, `record` names it on stderr. -- `record` writes an edit to an output as a `replace` of that output when its source also builds another output still on disk, as a `copy` does. An edit to the source would change the other output too. This holds for a file that a change owns or that has block entries, so the edit doesn't go to the owner. When `record` replaces every output of a file with block entries, it deletes the entries file. Each `add`, `delete` or `replace` that `record` writes goes at the end of its change, so no change later in the series may have a structural edit on the same path, on a folder above it or on a path under it. A later `file` edit doesn't count, since the build applies content edits before structural ones. An `add` or `replace` also can't go into a change that already keeps its own copy of the path. `record ` refuses a change that breaks either rule before it writes, and names the file and the change to use. `record` offers the model only the changes that can take the edits, and a reply that names another change starts a new one. +- `patchbook record [change] [--intent ...]` takes the output files in the working tree edited by hand since the last build (per `build.lock`) and moves each edit into the patchbook. In a file with block entries, each changed paragraph updates its entry, or gets a new `policy` entry; a new paragraph joins the one before it, and a paragraph put back as upstream had it loses its entry. If an edited paragraph's entry uses a placeholder with an empty value, it records none of that file's paragraph edits and says so, since the edit can't show where that placeholder goes; edit that entry by hand. Other edits become `file`, `add` or `delete` edits based on the pinned upstream. A new output that builds byte for byte and mode for mode as a staged upstream file builds is a `copy` of that file instead, so it follows upstream. `record` writes the copy for the widest folder whose staged files all went the same way into a folder that held nothing staged, as in `copy extra/skills/x -> skills/x`, so a file upstream adds to that folder later ships too. An empty file joins such a folder copy but never picks a copy by itself. A new output stays an `add` when it matches files at two upstream paths, when this recording also edits or deletes the file it matches, or when it was edited before the copy was recorded. A deleted upstream output and a new output are a `move` of that file instead, as after `git mv`, when the new output builds as the deleted one did. They are a `move` too when what still differs records as a `file` edit or as block entries, and the two texts keep, in order, at least half of the longer one's non-blank lines and two lines with a letter or digit. `record` widens the move to folders the same way as a copy, empty files included, and writes the content edit after it on the file's upstream path, as in `move skills/a -> skills/a2` and `file skills/a/SKILL.md`, so the moved file keeps following upstream and keeps its block entries. When a copy of the file is still on disk, the content edit goes on the new path instead, as in `file skills/a2/SKILL.md`, so it doesn't reach the copy. An exact move wins over an exact copy, and an exact copy over an edited move. A new output that deleted outputs of two upstream files match equally well stays an `add`. `record ` refuses a copy or a move when a change later in the series edits its source or its destination. After it saves a copy or a move, `record` builds again, and if the build differs from the files on disk, as when a `finish` hook rewrites a copied file or writes a moved one back, `record` fails and puts `.patchbook` back. A mode change is recorded too, as `chmod +x` on an upstream file with no other edit, or beside a content edit, by the rule in [The executable bit](#the-executable-bit). A file with block entries holds no mode, so a mode change there is skipped, with a reason that says how to set it in a `finish` hook, and its content edits still record. An edit to a file a change already owns goes to that change. When an edit joins a change that already exists, whether that change owns the file, you named it, or the model picked it, or rewrites a paragraph that already has a block entry, the model writes that change's or entry's intent again: from its whole diff with the edit in it and without any edit this record takes out of it, or, for a change the model picks, from its old intent and the new edits' diff. It does this in the same call that writes the record's other intents, so `record` asks the model at most once. If you gave the intent, or no model answers (see below), each one it doesn't set keeps its intent, and `record` prints one `intent may be stale` note that names them. A change whose intent patchbook wrote, or that has none, is the exception: `record` writes it again from all the change's edits. Taking an edit out of a change doesn't join it, so a change left with fewer edits keeps its intent. A given intent is for the change being recorded. When no edit goes to that change and no block entry needs it, `record` says the intent wasn't used, and names the changes the edits went to. Naming a change that exists with `--intent` still sets its intent, so then it says nothing. For the other edits, a model reads their diff and writes the intent if you didn't. If the model call fails, whether the CLI is missing or can't start, it exits non-zero, it takes longer than `intent.timeout` or its reply has no usable name and intent, or `intent.provider` is `none`, `record` still records. An edit that needs a change name goes to the change you named, or else to a new change named from the first edit, as `rename-skills-a-to-skills-a2` for `move skills/a -> skills/a2`, kept within 40 characters and given the next free suffix (`-2`, `-3`, ...) when the name is taken. It never joins another change, since picking one is the model's call. Patchbook writes the change's intent from its edits once they apply: a sentence for each kind of edit, in the order the edits come, that names the first three paths and counts the rest, as in `Renames skills/a to skills/a2. Edits skills/a/SKILL.md.` A move within one folder is a rename, and a move or a copy to the same path under another folder says only the folder it comes from, as in `Copies skills/x from extra.` for `copy extra/skills/x -> skills/x`. `CHANGE.md` labels that intent `intent (by patchbook):`, and `status` lists the change as a note, not a problem, so `build` and the hook's build go ahead. `record` prints one `intent by patchbook` note with the failure's first line and the two ways to replace the intent, `patchbook intent ` or an edit of its line to `intent: ...`, and exits 0. The intent stays patchbook's while its line keeps the label, so a later record that changes the change's edits writes it again. A new block entry gets an intent written the same way, from its paragraph edit and labelled `intent (by patchbook):` in the entries file, so `build` goes ahead. `status` lists each as a note, and `record` names it in its one `intent by patchbook for` line, beside any change patchbook wrote the intent of. A block entry that `record` updates again with no model gets its patchbook-written intent written again; one whose intent someone wrote keeps it, and `record` names it in the `may be stale` note. An existing block entry whose intent is empty keeps it empty (#349). A record that needs no new or rewritten intent, and a given `--intent`, never call the model. A timeout kills the model and everything it started. When the model picks an existing change, its intent replaces that change's. Without a change name, the model also picks one: an existing change the edits serve, or a new name. If you give an intent but no name, the model isn't called: the change is named from the intent's first four words, dropping any that would take the name past 40 characters. Any intent is kept on one line, with each run of whitespace a single space, and a blank intent counts as none. A name given to `record` must follow the change-name rule (see Change names), and `record` refuses before it writes while `series` holds a name that breaks it. Anything under `changes/` that `series` doesn't list is a stray, and `record` never writes into one: `record ` refuses a stray name before it writes, and a name from an intent or the model takes the next free suffix (`-2`, `-3`, ...) instead. Deleting the output of a `replace` takes the `replace` and its copy out of the change that owns it and records a `delete` of the path in the change being recorded, as does deleting an output that a `move` or `copy` made or a copy another output is still built from, and a change left with no edits stays, with its intent and an empty `edits:` list. A failed record leaves the patchbook as it was, though not for a write through a symlink inside `.patchbook` (#169): `record` puts `.patchbook` back to what it was before its first write and prints no note of what it saved, so the same command run again records the same edits with the same `--intent`. If a file can't be put back, `record` names it on stderr. +- `record` writes an edit to an output for that output alone when its source also builds another output still on disk, as a `copy` does, since an edit to the source would change the other output too. At the destination of a `copy` or `move` of an upstream file, it is a `file` edit on the destination's path, whose base is the upstream file, so the output keeps following that file: `sync` merges upstream's changes into it and reports a conflict as for any `file` edit. Anywhere else, as for the source itself while an unedited output still builds from it, or a copy of an `add`, it is a `replace`. A destination with a `file` edit of its own no longer builds from the source, so an edit to the source after it, or in the same recording, is a content edit as usual. This holds for a file that a change owns or that has block entries, so the edit doesn't go to the owner, and the destination's ours copy keeps the owner's text or the patched paragraphs it had, without following later edits to them. When no output reads a file's block entries after a recording, `record` deletes the entries file. Deleting a destination that has its own `file` edit takes the edit out of its change and records a `delete`. When a later `copy` or `move` reads the destination, the edit stays, so that output keeps it, and `record` writes only the `delete`. Each `add`, `delete` or `replace` that `record` writes goes at the end of its change, so no change later in the series may have a structural edit on the same path, on a folder above it or on a path under it. A `file` edit on the destination of a copy or move counts as a structural edit here, both one that `record` writes and one in a later change, since the build applies it in series order with them. So `record` writes one only into the change with the `copy` or `move`, or a later one. A later `file` edit on an upstream path doesn't count, since the build applies content edits on upstream paths before structural ones. An `add` or `replace` also can't go into a change that already keeps its own copy of the path. `record ` refuses a change that breaks either rule before it writes, and names the file and the change to use. `record` offers the model only the changes that can take the edits, and a reply that names another change starts a new one. - `patchbook intent [change] [--intent ...]` fills empty intents and replaces the ones patchbook wrote. With a change name it fills that change, with `--intent` or else with a model that reads the change's edits. With no name it fills every change and every block entry with an empty intent, and every change and block entry whose intent patchbook wrote, through the model. `--intent` needs a change name: with none, the command exits 1 and writes nothing, since one intent would land on unrelated changes. The model is asked once per change and once per file of block entries. If it fails, the command exits 1 and writes nothing. It never touches an intent the user or the model wrote, and it never renames a change, so a change named from its edits keeps its name. - A pre-commit hook does `record` and `build` on each commit, and stages what they change, so the usual loop is: edit, stage, commit. It records what is staged, not the working tree, so unstaged changes and untracked files stay out of the commit, and `git commit ` records only that path. The build reads the patchbook on disk, so the commit stops if a patchbook file it reads (`blocks/`, `changes/`, `series`, `build.lock`, `config.toml`, `upstream.lock`, `hooks.ts`, or a `[placeholders.] file` outside the output) has changes that aren't in the commit. It stops too on a placeholder file in the output whose unstaged changes the last build didn't write. A staged output file is the build's when it matches its entry in HEAD's `build.lock` or the index's, and a hand edit otherwise. A staged file that matches neither, while its working copy matches the last build and the commit changes the patchbook, may be an older build's output, so the hook stops. Its message gives a `git add` that commits the last build and a `git checkout` that records the staged copy. The hook writes the build to disk wherever the disk differs, except over unstaged work that matches neither the index nor the last build: it leaves that alone, and stops if the build would stage that file. It also stops on a file removed from the index but kept on disk, as `git rm --cached` does. Output that git ignores goes to disk but not into the commit, as with `build --commit`. A mode you stage is recorded by the rule in [The executable bit](#the-executable-bit). The hook is a short script that runs `patchbook hook run` from `PATH`, so upgrading patchbook upgrades the hook. If `patchbook` isn't on `PATH`, it says so and lets the commit through. While git runs hooks from `.git/hooks`, `clone`, `init`, `record`, `build`, `sync` and `track` install it in the repo if it's missing, so a fresh clone gets it on first use. They skip a patchbook that sits in another git repo than the one you're in. A file is patchbook's own only when its text is exactly one patchbook writes: the current script, or the one from before it checked for `.patchbook/config.toml`, which they rewrite to the current one. A hook that differs by a byte, with lines added or with the paths of another install written into it, is another tool's. If the file is patchbook's own and isn't executable, they make it executable again; another tool's file they leave alone, and `hook install` says git ignores it. `clone` says the hook records only when it does, and otherwise names the setting that turned it off. `status`, `check`, `show`, `upstream` and `config` never write a hook, and nothing installs one while `hook.enabled` is off. `patchbook hook install` installs it by hand. A hook manager moves the hook git runs. Vite+ and husky set `core.hooksPath` to their own folder, and lefthook and the pre-commit framework put their dispatcher in `.git/hooks`. So `clone`, `init` and `hook install` find the hook git will run. In a Vite+ (`.vite-hooks/pre-commit`) or husky (`.husky/pre-commit`) script, they put lines first that call `patchbook hook run`, and in a fork record that edit as the change `patchbook-hook`. For lefthook, the pre-commit framework and any other hook, they print the lines to add. For lefthook they print them in the format of its config file (`lefthook.yml`, `.yaml`, `.toml`, `.json` or `.jsonc`, also under a leading dot or in `.config/`), and for the pre-commit framework as an entry with `stages: [commit]`, so it records on a commit and not after a merge (pre-commit 3.1 and older reject the newer `pre-commit` spelling, and pre-commit 4 warns on each commit that `commit` is deprecated). They read the config and print only what it lacks (an entry that makes the event's call, `patchbook hook run` or `patchbook hook build`, counts under any name, while a different entry named `patchbook` gets a merge by hand instead), in the file's own indent and with the separators its format needs, and say where it goes: at the end of the file, directly below a line they name, or as the first member of a JSON object, with the comma that follows it. They check each paste first: the config with the text added must parse and hold patchbook's hook, and when it can't, they print the whole block to merge by hand. Patchbook runs first. A lefthook command gets a priority below every other command's, because lefthook runs equal priorities in no set order, and in a hook that uses `jobs` patchbook is the first job. The pre-commit entry names the `pre-commit` stage, so it doesn't also run in a post stage. The lefthook command and the pre-commit entry run the same guarded lines as a script, through `sh`. They never edit a config file, and never write into the `_` dispatcher folder that Vite+ and husky point git at, or into another tool's hooks folder. They don't write through a symlink either; a script reached through a link gets the lines printed. What patchbook adds to a manager stops the commit when `patchbook` isn't on `PATH`, because a commit that skips recording leaves the output and `build.lock` out of step. That holds for the lines in a script, the lefthook command and the pre-commit entry alike. They say how to install patchbook and how to skip the hook once, and `PATCHBOOK_HOOK=0` skips under every manager. They do nothing in a repo without a patchbook, so they are safe in a hooks folder every repo shares. When it puts the lines in a script, patchbook inserts them as bytes, so the rest of the file is as it was, including bytes that aren't UTF-8. `patchbook hook install` stops with an error in a git repo that sits inside another repo's patchbook, because it would install the other repo's hook. `patchbook status` warns on stderr when git runs no hook, or the hook it runs doesn't call patchbook. A manager that hasn't installed its hook in this checkout, as in a new git worktree before `npm install`, leaves git running nothing, and the warning names the manager's install command (`npx husky`, `vp config`). `patchbook hook status` prints the same facts on stdout: whether `hook.enabled` is on and where that setting came from, the file git runs, and whether it calls patchbook. It never writes. A failed hook run puts the patchbook and the output back as it found them, so the retry records from scratch; like every command that reads the patchbook, the hook stops before it writes anything on a link in `blocks/`, `changes/`, `series` or `build.lock` other than a recorded symlink (see Trust). A linked `config.toml` or `upstream.lock` is fine once the link is staged or committed, since the hook never writes them. If the patchbook has problems, it records but doesn't build, and says so. Unresolved conflict markers are an exception. A marker line starts with seven `<` or seven `>`, then a space or the end of the line. The hook checks every change's file, add and replace copy, even when a later edit hides that copy, and every paragraph entry's patched text, even when the entry is orphaned. It refuses a copy that `.patchbook/last-sync.json` lists as conflicted while the copy holds a conflict block that its base copy holds fewer times, and only until the sync is committed: once HEAD's `upstream.lock` pins the report's `to` commit for that upstream, the copy counts as any other. A block runs from a `<<<<<<<` line through the next `>>>>>>>` line, or to the end of the file when none follows, and a `>>>>>>>` line with no `<<<<<<<` line before it is a block by itself. It refuses any other copy that holds more marker lines than its base copy, and a copy with no base copy, such as an add copy, counts against none. It refuses a paragraph entry whose patched text holds more marker lines than its upstream text. With no `last-sync.json`, or one it can't read, it counts marker lines in every copy. A HEAD with no commit, no `upstream.lock`, an `upstream.lock` that is a link or doesn't parse, or no entry for that upstream pins nothing, so a listed copy gets the block rule. So markers that upstream itself holds don't stop a commit, and neither does an edit inside them, unless `last-sync.json` lists that copy and HEAD doesn't yet pin its sync. The sync commit is the one the block rule guards. After you resolve the copy and commit, a later edit inside upstream's literal block commits. A sync committed with `PATCHBOOK_HOOK=0` while a copy is unresolved pins its commit, so that copy falls back to the count rule. The hook names the copy or entries file to resolve. Resolve the markers, stage the file and commit again. If recording staged output introduces markers, the hook restores the patchbook before it stages anything, refuses, and names each staged output file it built from a refused copy or entries file. Other exceptions are a change whose output lands in `.patchbook` or at a part git reads as `.git`, an edit path that isn't a clean path inside the tree (a backslash makes it unclean, so `record` also refuses a hand edit to a file whose name has one), and a change name outside `[a-z0-9][a-z0-9-]*`. The hook refuses the commit before it records, builds or stages anything, and names the problem. It does the same for a new file you add by hand in the output at a path that lands in `.patchbook` in another letter case, or at a part git reads as `.git`, such as `.PATCHBOOK/x.md` on a case-sensitive filesystem or `a/.GIT/y`. The book's own `.patchbook/` folder is the book, not output, and commits normally. Any other problem that `status` reports, a destination in a vendored copy included, only skips the build with a warning. The build's own safety checks still stop a commit. A change whose file really goes outside the output through a link makes the hook fail and leaves everything as it was, while `status` reports no problems. `PATCHBOOK_HOOK=0 git commit` skips it once, and `PATCHBOOK_INTENT="..."` gives the intent instead of the model. - `post-merge`, `post-checkout` and `post-rewrite` hooks run `patchbook hook build` when git brings in changed patchbook data, so a plain `git pull`, `git checkout ` or `git rebase` rebuilds the output and `build.lock` without a `patchbook build`. `post-checkout` builds only for a branch checkout (its third argument is 1), not for `git checkout -- `, and `post-rewrite` only for a rebase, since the pre-commit hook has built an amend. They are installed beside the pre-commit hook by `clone`, `init`, `build` and `hook install`, which leaves a post hook of another tool alone and prints the lines to add to it. With a hook manager, `hook install` puts the same lines into the manager's `post-merge`, `post-checkout` and `post-rewrite` scripts as it does for `pre-commit`, or, for a config file, prints a command (lefthook) or a hook (the pre-commit framework) that runs them, written with the arguments that manager gives its scripts: `{1}`, `{2}` and `{3}` in lefthook, and `PRE_COMMIT_FROM_REF`, `PRE_COMMIT_TO_REF`, `PRE_COMMIT_CHECKOUT_TYPE` and `PRE_COMMIT_REWRITE_COMMAND` in pre-commit. For a hook file of another tool it names the file. `PATCHBOOK_HOOK=0` or `hook.enabled` turns them off, as for the pre-commit hook. Git ignores a post hook's exit code, so a build that can't run, such as one that finds problems or hand edits it won't overwrite, prints why, says the output is behind the patchbook, and leaves the git command done. `patchbook hook build` is quiet unless it changed a file or `build.lock`. @@ -333,7 +333,7 @@ A problem always has `problem`, its kind, first. The other fields depend on the | --- | --- | --- | | `invalid` | any location, `detail` | Something in the patchbook is malformed, or an edit can't apply. | | `gone` | edit or change, `detail` | The file an edit names isn't in upstream. | -| `stale` | change, `detail` | The change's base differs from upstream at the pin. Run `sync`. | +| `stale` | edit or change, `detail` | The change's base differs from upstream at the pin. Run `sync`. | | `conflict` | file or change, `detail` | Conflict markers in our copy, or in the output. | | `placeholder` | output or block, `detail` | A `{{kind:name}}` that neither the `placeholder` hook nor the placeholder source gives a value. | | `leak` | output with `line`, or block, then `terms` | Text that a `[[check]]` pattern or `blockTerms` flags is still in the output. Without `hash`, `line` is the 1-based line in the output where the paragraph starts. `terms` is a string list. | @@ -359,7 +359,7 @@ Written by `patchbook sync`. It has an entry for each upstream in the config tha | `upstreams[].merged` | list | `{change, path}` for each file edit that merged without conflict. | | `upstreams[].conflicts` | list | `{change, path, count}` for a text file with `count` conflicts in our copy, or `{change, path, detail}` for a binary file. | | `upstreams[].gone` | list | `{change, path, maybe}` for a file edit whose file upstream no longer has. `maybe` is up to three added paths with similar names, most similar first. | -| `upstreams[].replacedUpstreamChanged` | string list | `: ` for each `replace` edit whose file changed upstream. | +| `upstreams[].replacedUpstreamChanged` | string list | `: ` for each `replace` edit whose file changed upstream, and each `file` edit on a copy's or move's destination that sync kept as is because it can't merge a file that isn't text. | ### Placeholder files diff --git a/src/api.ts b/src/api.ts index 120d12a1..4adf848e 100644 --- a/src/api.ts +++ b/src/api.ts @@ -14,7 +14,7 @@ export type Problem = | ({ problem: "invalid" } & (InFile | InEdit | InChange | InOutput | InBlock) & Detail) | ({ problem: "invalid" } & (InFile | InEdit | InChange) & Detail & Refuse) | ({ problem: "gone" } & (InEdit | InChange) & Detail) - | ({ problem: "stale" } & InChange & Detail) + | ({ problem: "stale" } & (InEdit | InChange) & Detail) | ({ problem: "conflict" } & (InFile | InChange) & Detail) | ({ problem: "conflict" } & (InFile | InChange) & Detail & Refuse) | ({ problem: "placeholder" } & (InOutput | InBlock) & Detail) diff --git a/src/assemble.ts b/src/assemble.ts index 7b3df8ac..8644dc62 100644 --- a/src/assemble.ts +++ b/src/assemble.ts @@ -8,7 +8,7 @@ import { } from "./blocks.ts"; import { ATTRIBUTES_FILE, Book, buildInputs, GIT, PB, type Reserved, under } from "./book.ts"; import { - Change, CHANGE_NAME, editText, isMergeMarker, readChanges, replaceIntent, strayProblems, + Change, CHANGE_NAME, type Edit, editText, isMergeMarker, readChanges, replaceIntent, strayProblems, } from "./changes.ts"; import { installHookOrWarn, stageModes, upstreamModes, warnUnhooked } from "./githook.ts"; import { Fail } from "./lib/fail.ts"; @@ -112,19 +112,30 @@ function intoReserved(where: InEdit, path: string, { place, refuse }: Reserved): return refuse ? { problem: "invalid", ...where, detail, refuse: true } : { problem: "invalid", ...where, detail }; } -/** Apply add, replace, delete, move and copy to a map of staged path to source, and count the edits that applied. */ +/** Apply add, replace, delete, move and copy, and each `file` edit on a path upstream doesn't have, to a map of staged path to source, + * and count the structural edits that applied. */ export function applyStructure( changes: readonly Change[], upstream: ReadonlyMap, problems: Problem[], reservedHolding: (staged: string) => Reserved | null, dropped = new Set(), -): { tree: Map; applied: number } { +): { tree: Map; applied: number; upstreamOf: Map; unread: Set } { const tree = new Map(Array.from(upstream.keys(), (p) => [p, { kind: "up", path: p }])); + const upstreamOf = new Map(); + const placed: string[] = []; let applied = 0; for (const c of changes) { for (const e of c.edits) { - if (e.kind === "file") continue; + if (e.kind === "file") { + const src = upstream.has(e.path) ? undefined : tree.get(e.path); + if (src?.kind !== "up") continue; + upstreamOf.set(e.path, src.path); + if (c.read("ours", e.path) === null) continue; + tree.set(e.path, { kind: "ours", change: c.name, path: e.path }); + placed.push(`${c.name}\0${e.path}`); + continue; + } const where: InEdit = { file: `changes/${c.name}`, edit: editText(e) }; const matched = Array.from(tree.keys()).filter((p) => under(p, e.path)); if (e.kind === "add") { @@ -170,7 +181,8 @@ export function applyStructure( } } } - return { tree, applied }; + const read = new Set(Array.from(tree.values()).flatMap((s) => (s.kind === "ours" ? [`${s.change}\0${s.path}`] : []))); + return { tree, applied, upstreamOf, unread: new Set(placed.filter((k) => !read.has(k))) }; } export function blockFiles(book: Book): string[] { @@ -183,12 +195,16 @@ export function assemble(book: Book): Assembly { let applied = 0; const changes = readChanges(book, problems); const byName = new Map(changes.map((c) => [c.name, c])); + const structure: Problem[] = []; + const lost = new Set(); + const { tree: staged, applied: structural, upstreamOf, unread } = applyStructure(changes, upstream, structure, (p) => book.reservedHolding(p), lost); const conflicted = syncConflicts(book); for (const name of foldersWith(book.data("changes"), "CHANGE.md").filter((name) => CHANGE_NAME.test(name))) { const c = byName.get(name) ?? new Change(name, book.data("changes", name)); for (const copy of nonFolders(join(c.dir, "ours")).filter((p) => p.endsWith(".pb"))) { const path = copy.slice(0, -".pb".length); + if (unread.has(`${c.name}\0${path}`)) continue; const adds = conflicted.has(`${c.name}\0${path}`) ? addsConflictBlock : addsConflictMarker; if (adds(textOf(c.file("ours", path)), textOf(c.file("base", path)))) { problems.push({ problem: "conflict", file: path, change: c.name, detail: "ours has conflict markers", refuse: true }); @@ -199,6 +215,23 @@ export function assemble(book: Book): Assembly { // Content edits, keyed by upstream path. One owner per path. const content = new Map(upstream); const owner = new Map(); + const copiesOver = (c: Change, path: string, up: File, at?: InEdit): { base: File; ours: File } | null => { + const where: InChange | InEdit = at ?? { file: path, change: c.name }; + const base = c.file("base", path); + const ours = c.file("ours", path); + if (base === null || ours === null) { + const lost = [base === null ? "base" : "", ours === null ? "ours" : ""].filter(Boolean); + const detail = !at ? "its base or ours copy is missing" : `its ${lost.join(" and ")} ${lost.length > 1 ? "copies are" : "copy is"} missing`; + problems.push({ problem: "invalid", ...where, detail }); + return null; + } + if (!bytesEqual(base.data, up.data)) { + problems.push({ problem: "stale", ...where, detail: "its base differs from upstream at the pin; run sync" }); + } + applied++; + return { base, ours }; + }; + const destinations: { c: Change; e: Edit }[] = []; for (const c of changes) { for (const e of c.edits) { if (e.kind !== "file") continue; @@ -211,20 +244,11 @@ export function assemble(book: Book): Assembly { owner.set(e.path, `change ${c.name}`); const up = upstream.get(e.path); if (!up) { - problems.push({ problem: "gone", ...where, detail: "upstream no longer has it" }); + destinations.push({ c, e }); continue; } - const base = c.file("base", e.path); - const ours = c.file("ours", e.path); - if (base === null || ours === null) { - problems.push({ problem: "invalid", ...where, detail: "its base or ours copy is missing" }); - continue; - } - if (!bytesEqual(base.data, up.data)) { - problems.push({ problem: "stale", ...where, detail: "its base differs from upstream at the pin; run sync" }); - } - content.set(e.path, { data: ours.data, mode: outputMode(ours, base, up) }); - applied++; + const copies = copiesOver(c, e.path, up); + if (copies) content.set(e.path, { data: copies.ours.data, mode: outputMode(copies.ours, copies.base, up) }); } } const blocks = new Map>(); @@ -241,9 +265,15 @@ export function assemble(book: Book): Assembly { blocks.set(rel, entries); } - const lost = new Set(); - const { tree: staged, applied: structural } = applyStructure(changes, upstream, problems, (p) => book.reservedHolding(p), lost); + problems.push(...structure); applied += structural; + for (const { c, e } of destinations) { + const at: InEdit = { file: `changes/${c.name}`, edit: editText(e) }; + const from = upstreamOf.get(e.path); + if (from === undefined) problems.push({ problem: "gone", ...at, detail: "no earlier copy or move of an upstream file reaches it" }); + else if (unread.has(`${c.name}\0${e.path}`)) applied++; + else copiesOver(c, e.path, upstream.get(from)!, at); + } const prefix = book.layout.kind === "folder" ? book.layout.from : ""; const atOutput = (p: string) => (!prefix ? [p] : p.startsWith(prefix + "/") ? [p.slice(prefix.length + 1)] : []); const selected = new Map(Array.from(staged).flatMap(([p, s]) => atOutput(p).map((at) => [at, s] as const))); diff --git a/src/record.ts b/src/record.ts index d7f62f79..98062096 100644 --- a/src/record.ts +++ b/src/record.ts @@ -31,11 +31,11 @@ type Data = { "add": { staged: string; now: Seen }; "follow": { edit: Follow }; "delete-upstream": { staged: string; entries: string | null }; - "replace": { staged: string; now: Seen; built: Mode; up: File | undefined; entries: string | null }; + "replace": { staged: string; now: Seen; built: Mode; up: File | undefined }; "unadd": Copy; - "unreplace": Copy; + "unreplace": Copy & { drops: "replace" | "file" }; "update-ours": Copy & { now: Seen; built: File; up: File | undefined }; - "file-edit": { rel: string; now: Seen; built: Mode; to: Destination }; + "file-edit": { rel: string; now: Seen; built: File; to: Destination; entries: string | null }; "paragraph-edit": { plan: Plan; modeNotRecorded: string | null }; "skip": { reason: string }; }; @@ -43,14 +43,12 @@ type Data = { type Kind = keyof Data; export type Edited = { [P in K]: { kind: P; path: string } & Data[P] }[K]; -/** The edit a row adds to the change it records into. A delete that stands in for a replace names the change it drops the replace from. */ type Written = Edit & { drops?: Change }; /** A change a row writes a copy into without naming it, with the copy's new bytes. */ type Join = { change: Change; path: string; data: Uint8Array }; -/** An add or replace a row takes out of the change that has it. */ -type Dropped = { change: Change; kind: "add" | "replace"; path: string }; +type Dropped = { change: Change; kind: "add" | "replace" | "file"; path: string }; /** `updates` are the existing entries a row rewrites, by their label. */ type Need = { named: boolean; drafts: readonly Draft[]; updates?: readonly [string, Draft][]; writes?: Written; joins?: Join; dropped?: Dropped }; @@ -100,9 +98,7 @@ const KINDS: { readonly [K in Kind]: Row } = { const c = r.target!; c.edits.push({ kind: "replace", path: e.staged }); const copies = writeCopy(c, e.staged, e.now, e.built, e.up); - const entries = e.entries; - const afterSave = () => { if (entries !== null && exists(entries)) unlinkSync(entries); }; - return { touched: [c], notes: [`replace ${e.path}`], copies, afterSave }; + return { touched: [c], notes: [`replace ${e.path}`], copies }; }, }, "unadd": { @@ -114,13 +110,13 @@ const KINDS: { readonly [K in Kind]: Row } = { }, }, "unreplace": { - needs: (e) => ({ ...NAMED, writes: { kind: "delete", path: e.staged, drops: e.change }, dropped: { change: e.change, kind: "replace", path: e.staged } }), + needs: (e) => ({ ...NAMED, writes: { kind: "delete", path: e.staged, drops: e.change }, dropped: { change: e.change, kind: e.drops, path: e.staged } }), apply: (e, r) => { const c = r.target!; - e.change.edits = e.change.edits.filter((x) => !(x.kind === "replace" && x.path === e.staged)); + e.change.edits = e.change.edits.filter((x) => !(x.kind === e.drops && x.path === e.staged)); c.edits.push({ kind: "delete", path: e.staged }); const afterSave = () => dropCopies(e.change, e.staged); - return { touched: [e.change, c], notes: [`delete ${e.path} (replace removed from ${e.change.name})`], afterSave }; + return { touched: [e.change, c], notes: [`delete ${e.path} (${e.drops === "file" ? "file edit" : "replace"} removed from ${e.change.name})`], afterSave }; }, }, "update-ours": { @@ -135,14 +131,16 @@ const KINDS: { readonly [K in Kind]: Row } = { apply: (e, r) => { if (e.to.kind === "owned") { const c = e.to.change; - const copies = writeCopy(c, e.rel, e.now, e.built, e.to.up); + const copies = writeCopy(c, e.rel, e.now, e.built.mode, e.to.up); return { touched: [c], notes: [`file ${e.path}` + (c !== r.target ? ` (in ${c.name})` : "")], copies }; } const c = r.target!; c.edits.push({ kind: "file", path: e.rel }); c.write("base", e.rel, e.to.base.data, e.to.base.mode); - const copies = writeCopy(c, e.rel, e.now, e.built, e.to.base); - return { touched: [c], notes: [`file ${e.path}`], copies: [[c.content("base", e.rel), e.to.base.mode], ...copies] }; + const copies = writeCopy(c, e.rel, e.now, e.built.mode, e.to.base); + const entries = e.entries; + const afterSave = () => { if (entries !== null && exists(entries)) unlinkSync(entries); }; + return { touched: [c], notes: [`file ${e.path}`], copies: [[c.content("base", e.rel), e.to.base.mode], ...copies], afterSave }; }, }, "paragraph-edit": { @@ -211,25 +209,32 @@ export type Snapshot = { build(src: Source, at: string): File; }; -/** An edit to an output whose source builds another output still on disk is a replace of that output alone: an edit to the source - * would change the other output too. A new output that builds as a copy of a staged file is recorded as that copy. A new output that - * a deleted output's upstream file builds, as is or with a content edit that keeps at least half its lines, is recorded as a move of - * that file plus the edit. */ +/** A new output that builds as a copy of a staged file is recorded as that copy. A new output that a deleted output's upstream file + * builds, as is or with a content edit that keeps at least half its lines, is recorded as a move of that file plus the edit. */ export function classify(s: Snapshot, paths: readonly string[]): Edited[] { return follow(s, each(s, paths)); } function each(s: Snapshot, paths: readonly string[]): Edited[] { + const edited = new Set(paths); + const isDestination = (p: string, src: Source) => src.kind === "up" && src.path !== s.prefix + p; return paths.map((path) => { const now = s.current.get(path); const built = s.out.get(path); const src = now && built ? s.sources.get(path) : undefined; - const outputs = src ? builtFrom(s, src) : []; - if (!now || !built || !src || !outputs.some((p) => p !== path && s.current.has(p))) return classifyOne(s, path); - // Once every output of a file with block entries is replaced, nothing reads its entries. - const entries = src.kind === "up" && s.blocks.has(src.path) && outputs.every((p) => paths.includes(p)) ? s.entriesAt(src.path) : null; + if (!now || !built || !src) return classifyOne(s, path); + const outputs = builtFrom(s, src); + const others = outputs.filter((p) => p !== path && s.current.has(p)); const staged = s.prefix + path; - return { kind: "replace", path, staged, now, built: built.mode, up: s.upstream.get(staged), entries }; + if (isDestination(path, src)) { + if (!others.length) return classifyOne(s, path); + const nothingReadsEntries = outputs.every((p) => edited.has(p) && (isDestination(p, src) || !s.current.has(p))); + const entries = s.blocks.has(src.path) && nothingReadsEntries ? s.entriesAt(src.path) : null; + return { kind: "file-edit", path, rel: staged, now, built, to: { kind: "recorded", base: s.upstream.get(src.path)! }, entries }; + } + const editedDestination = (p: string) => edited.has(p) && isDestination(p, src); + if (others.every(editedDestination)) return classifyOne(s, path); + return { kind: "replace", path, staged, now, built: built.mode, up: s.upstream.get(staged) }; }); } @@ -258,13 +263,16 @@ function classifyOne(s: Snapshot, path: string): Edited { if (src.kind === "ours") { const change = s.changes.get(src.change)!; const copy = { path, change, staged: src.path }; + const onDestination = change.edits.some((e) => e.kind === "file" && e.path === src.path); if (now === undefined) { const staged = s.prefix + path; // A moved or copied output, or a copy another output still needs, is deleted. Dropping its add or replace would break the move or copy. if (src.path !== staged || readByMoveOrCopy(s, src.path)) return { kind: "delete-upstream", path, staged, entries: null }; - return { kind: change.edits.some((e) => e.kind === "add" && e.path === src.path) ? "unadd" : "unreplace", ...copy }; + if (onDestination) return { kind: "unreplace", ...copy, drops: "file" }; + return change.edits.some((e) => e.kind === "add" && e.path === src.path) ? { kind: "unadd", ...copy } : { kind: "unreplace", ...copy, drops: "replace" }; } if (s.uses(change.read("ours", src.path))) return skipPlaceholders(path, change); + if (onDestination) return { kind: "file-edit", path, rel: src.path, now, built, to: { kind: "owned", change }, entries: null }; return { kind: "update-ours", ...copy, now, built, up: s.upstream.get(src.path) }; } if (now === undefined) return { kind: "delete-upstream", path, staged: s.prefix + path, entries: s.blocks.has(src.path) && !stillBuilt(s, src.path) ? s.entriesAt(src.path) : null }; @@ -279,7 +287,7 @@ function classifyOne(s: Snapshot, path: string): Edited { const owner = s.owners.get(src.path); if (owner && s.uses(owner.read("ours", src.path))) return skipPlaceholders(path, owner); const to: Destination = owner ? { kind: "owned", change: owner, up: s.upstream.get(src.path) } : { kind: "recorded", base: s.upstream.get(src.path)! }; - return { kind: "file-edit", path, rel: src.path, now, built: built.mode, to }; + return { kind: "file-edit", path, rel: src.path, now, built, to, entries: null }; } const skipPlaceholders = (path: string, change: Change): Edited => @@ -488,7 +496,7 @@ function asked(edits: readonly Edited[]): Asked { /** The edits that need a change name, as the model reads them: a move or copy as its line with no diff, and every other edit by its output * path. A file edited after a move is diffed against the moved file as the build writes it at its new path, so only the edit shows. */ function pendingEdits(a: Assembly, current: ReadonlyMap, edits: readonly Edited[]): Part[] { - const moved = new Map(edits.flatMap((e): [string, File][] => (e.kind === "file-edit" && !a.out.has(e.path) ? [[e.path, a.build({ kind: "up", path: e.rel }, e.path)]] : []))); + const moved = new Map(edits.flatMap((e): [string, File][] => (e.kind === "file-edit" && !a.out.has(e.path) ? [[e.path, e.built]] : []))); const built = { ...a, out: new Map([...a.out, ...moved]) }; return edits.filter((e) => needOf(e).named).flatMap((e): Part[] => (e.kind === "follow" ? [{ line: editText(e.edit), diff: "" }] : pendingParts(built, current, [e.path]))); } @@ -514,13 +522,15 @@ function joined(ask: Asked, known: Change | null, newParts: () => Part[]): Joine type Misfit = { edit: Edit; in: string } | "own"; /** Why the change `name` can't take `w`: an edit on its path, a folder above it or a path under it, in a change later in the series, - * which has to apply first; or, for an add or a replace, a copy of that path the change already keeps. Any change takes a file edit. */ -function misfit(roster: Roster, name: string, w: Written): Misfit | null { - if (w.kind === "file") return null; + * which has to apply first; or, for an add or a replace, a copy of that path the change already keeps. Any change takes a file edit on + * an upstream path. */ +function misfit(roster: Roster, upstream: ReadonlyMap, name: string, w: Written): Misfit | null { + const inSeries = (e: Edit) => e.kind !== "file" || !upstream.has(e.path); + if (!inSeries(w)) return null; const ends = "dest" in w ? [w.path, w.dest] : [w.path]; const overlaps = (p: string) => ends.some((q) => under(p, q) || under(q, p)); for (const later of roster.after(name).toReversed()) { - const edit = later.edits.findLast((e) => e.kind !== "file" && !(later === w.drops && e.kind === "replace" && e.path === w.path) + const edit = later.edits.findLast((e) => inSeries(e) && !(later === w.drops && (e.kind === "replace" || e.kind === "file") && e.path === w.path) && (overlaps(e.path) || ("dest" in e && overlaps(e.dest)))); if (edit) return { edit, in: later.name }; } @@ -559,12 +569,12 @@ function newIntent(n: Naming): string | null { } function nameAndIntent( - ask: Asked, name: string | null, given: string | null, roster: Roster, joins: readonly Joined[], + ask: Asked, name: string | null, given: string | null, roster: Roster, upstream: ReadonlyMap, joins: readonly Joined[], model: (fresh: Omit | null, offered: ReadonlyMap) => Reply, ): Naming { const changes = roster.parsed; const misfits = (c: string) => ask.writes.flatMap((w): [Written, Misfit][] => { - const why = misfit(roster, c, w); + const why = misfit(roster, upstream, c, w); return why ? [[w, why]] : []; }); @@ -693,7 +703,7 @@ export function record( const ask = asked(edits); const newParts = () => [...pendingEdits(a, current, edits), ...ask.drafts.map(([p, d]) => entryPart(p, d.upstream, d.patched))]; const joins = joined(ask, change === null ? null : changes.get(change) ?? null, newParts); - const naming = nameAndIntent(ask, change, given, roster, joins, (fresh, offered) => + const naming = nameAndIntent(ask, change, given, roster, a.upstream, joins, (fresh, offered) => writeIntents(book, offered, fresh && { ...fresh, parts: newParts() }, joins.map((j) => ({ key: j.key, was: j.was, parts: j.parts() })))); const fresh = newIntent(naming); const target = naming.name ? changes.get(naming.name) ?? new Change(naming.name, join(book.dir, "changes", naming.name), fresh ? byAuthor(fresh) : null) : null; diff --git a/src/sync.ts b/src/sync.ts index 26231e38..809e7f19 100644 --- a/src/sync.ts +++ b/src/sync.ts @@ -3,6 +3,7 @@ import { appendFileSync, chmodSync, lstatSync, mkdtempSync, readdirSync, readFil import { tmpdir } from "node:os"; import { dirname, join, relative, sep } from "node:path"; import type { CheckJson, LastSync, SyncReport, UpstreamCheck } from "./api.ts"; +import { applyStructure } from "./assemble.ts"; import { type Lost, lostEdit } from "./blocks.ts"; import { Book, GIT, parseLock, PB, refuseNestedGit, refuseUpstreamGit, segmentNamesGit, under, unsafeVendor } from "./book.ts"; import { type Change, readChanges, type Side } from "./changes.ts"; @@ -186,6 +187,20 @@ function writeLastSync(book: Book, reports: ReadonlyMap): vo writeText(join(book.dir, REPORT), lastSyncText({ version: 2, upstreams })); } +function pinnedFiles(book: Book, u: Upstream): Map { + const pin = u.pin(); + return pin.tree ? book.buildable(u, u.mounted(u.files(u.heal(pinned(u, pin)))), false) : new Map(); +} + +function destinationSources( + book: Book, changes: readonly Change[], atPin: (u: Upstream) => ReadonlyMap, +): { upstreamOf: ReadonlyMap; unread: ReadonlySet } { + const ends = changes.flatMap((c) => c.edits.flatMap((e) => (e.kind === "copy" || e.kind === "move" ? [e.dest] : []))); + if (!changes.some((c) => c.edits.some((e) => e.kind === "file" && ends.some((d) => under(e.path, d))))) return { upstreamOf: new Map(), unread: new Set() }; + const upstream = new Map(book.upstreams.flatMap((u) => [...atPin(u)])); + return applyStructure(changes, upstream, [], (p) => book.reservedHolding(p)); +} + /** Move one upstream's pin and carry every change on its files forward. Returns the report, or null. */ export function syncUpstream(book: Book, u: Upstream, ref: string | null, changes: readonly Change[], beforePin?: (report: SyncReport) => void): SyncReport | null { recoverAll(book); @@ -204,7 +219,7 @@ export function syncUpstream(book: Book, u: Upstream, ref: string | null, change const raw = u.files(commit); if (u.vendor) refuseUpstreamGit(u.name, relative(book.root, u.vendor), raw.keys()); if (u.vendor) refuseUserFiles(book, u, u.vendor, pin.tree ? u.files(u.heal(pinned(u, pin))) : raw, !pin.tree); - const old = pin.tree ? book.buildable(u, u.mounted(u.files(u.heal(pinned(u, pin)))), false) : new Map(); + const old = pinnedFiles(book, u); const fresh = book.buildable(u, u.mounted(raw)); const report: SyncReport = { name: u.name, from: pin.commit ?? null, to: commit, upstream: upstreamDelta(old, fresh), merged: [], conflicts: [], gone: [], @@ -213,25 +228,28 @@ export function syncUpstream(book: Book, u: Upstream, ref: string | null, change const writes: Write[] = []; const unsure: { c: Change; path: string; lost: Lost }[] = []; + const kept: { c: Change; path: string; from: string }[] = []; const missing: string[] = []; let copies = 0; const added = Array.from(fresh.keys()).filter((p) => !old.has(p)); + const { upstreamOf, unread } = destinationSources(book, changes, (x) => (x === u ? old : pinnedFiles(book, x))); for (const c of changes) { for (const e of c.edits) { - if (book.upstreamFor(e.path) !== u) continue; - if (e.kind === "replace" && old.has(e.path) && !sameFile(old.get(e.path), fresh.get(e.path))) { + if (e.kind === "replace" && book.upstreamFor(e.path) === u && old.has(e.path) && !sameFile(old.get(e.path), fresh.get(e.path))) { report.replacedUpstreamChanged.push(`${c.name}: ${e.path}`); } - if (e.kind !== "file") continue; + if (e.kind !== "file" || unread.has(`${c.name}\0${e.path}`)) continue; + const from = upstreamOf.get(e.path) ?? e.path; + if (book.upstreamFor(from) !== u) continue; const base = c.read("base", e.path); const ours = c.read("ours", e.path); - const theirs = fresh.get(e.path)?.data; + const theirs = fresh.get(from)?.data; if (theirs === undefined) { - const maybe = added.map((p) => [similarity(p, e.path), p] as const).sort((x, y) => y[0] - x[0]).slice(0, 3).map(([, p]) => p); + const maybe = added.map((p) => [similarity(p, from), p] as const).sort((x, y) => y[0] - x[0]).slice(0, 3).map(([, p]) => p); report.gone.push({ change: c.name, path: e.path, maybe }); continue; } - if (base !== null && ours !== null) writes.push(...carryMode(c, e.path, fresh.get(e.path)!.mode)); + if (base !== null && ours !== null) writes.push(...carryMode(c, e.path, fresh.get(from)!.mode)); if (base !== null && bytesEqual(theirs, base)) continue; if (base === null || ours === null) { const sides = (["base", "ours"] as const).filter((side) => (side === "base" ? base : ours) === null); @@ -240,7 +258,13 @@ export function syncUpstream(book: Book, u: Upstream, ref: string | null, change continue; } if (!(isText(base) && isText(ours) && isText(theirs))) { - report.conflicts.push({ change: c.name, path: e.path, detail: "binary file changed upstream" }); + if (!upstreamOf.has(e.path)) { + report.conflicts.push({ change: c.name, path: e.path, detail: "binary file changed upstream" }); + continue; + } + writes.push({ c, side: "base", path: e.path, data: theirs }); + report.replacedUpstreamChanged.push(`${c.name}: ${e.path}`); + kept.push({ c, path: e.path, from }); continue; } const merge = mergeFile(ours, base, theirs); @@ -282,6 +306,10 @@ export function syncUpstream(book: Book, u: Upstream, ref: string | null, change warn(`patchbook: ${path} (change ${c.name}): ${why}. ${relative(book.root, c.content("ours", path))} holds our text ` + `and upstream's between conflict markers. Resolve them with ${fix}, then run patchbook build.\n`); } + for (const { c, path, from } of kept) { + warn(`patchbook: ${path} (change ${c.name}): upstream changed ${from}, and sync merges only text, so it kept ours. ` + + "To take upstream's file instead, write it over the output and run patchbook record.\n"); + } warnLeft(book, u); return report; } diff --git a/test/e2e.test.ts b/test/e2e.test.ts index eaad5f6d..577e1692 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -7735,7 +7735,7 @@ describe("ForkTest", () => { expect(t.pb(["status"], { cwd: t.fork.path, code: 1 }).stdout).toContain("unrecorded docs/guide.md"); }); - forkTest("record replaces each of two outputs that share one upstream file when both are edited", (t) => { + forkTest("record edits each of two outputs of one upstream file at its own path when both are edited", (t) => { mkdirSync(join(t.fork.path, ".patchbook/changes/twin"), { recursive: true }); writeFileSync(join(t.fork.path, ".patchbook/changes/twin/CHANGE.md"), "# twin\n\nintent: Two guides.\n\nedits:\n- copy docs/guide.md -> docs/guide2.md\n"); const series = join(t.fork.path, ".patchbook/series"); @@ -7743,8 +7743,8 @@ describe("ForkTest", () => { t.pb(["build"], { cwd: t.fork.path }); t.fork.write("docs/guide.md", "a guide!\n"); t.fork.write("docs/guide2.md", "a second guide\n"); - expect(t.pb(["record", "--intent", "Shout."], { cwd: t.fork.path }).stdout).toBe("shout: Shout.\nreplace docs/guide.md\nreplace docs/guide2.md\n"); - expect(read(join(t.fork.path, ".patchbook/changes/shout/CHANGE.md"))).toContain("edits:\n- replace docs/guide.md\n- replace docs/guide2.md\n"); + expect(t.pb(["record", "--intent", "Shout."], { cwd: t.fork.path }).stdout).toBe("shout: Shout.\nfile docs/guide.md\nfile docs/guide2.md\n"); + expect(read(join(t.fork.path, ".patchbook/changes/shout/CHANGE.md"))).toContain("edits:\n- file docs/guide.md\n- file docs/guide2.md\n"); expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); t.pb(["build"], { cwd: t.fork.path }); expect([t.fork.read("docs/guide.md"), t.fork.read("docs/guide2.md")]).toEqual(["a guide!\n", "a second guide\n"]); @@ -10580,20 +10580,341 @@ echo "patchbook isn't installed, so this commit doesn't record hand edits." >&2 expect(snapshot(join(t.fork.path, ".patchbook"))).toEqual(before); }); - for (const [what, path] of [["destination", "docs/guide2.md"], ["source", "docs/guide.md"]] as const) { - forkTest(`recording an edit to the ${what} of an upstream copy replaces only that output`, (t) => { - handChange(t, "second", "Copy the guide.", ["copy docs/guide.md -> docs/guide2.md"]); + forkTest("recording an edit to the source of an upstream copy replaces only that output", (t) => { + handChange(t, "second", "Copy the guide.", ["copy docs/guide.md -> docs/guide2.md"]); + t.pb(["build"], { cwd: t.fork.path }); + t.fork.write("docs/guide.md", "a copied guide\n"); + const disk = outputs(t); + expect(t.pb(["record", "copyedit", "--intent", "Change one guide."], { cwd: t.fork.path }).stdout).toBe("replace docs/guide.md\n"); + expect(changeText(t, "copyedit")).toBe("# copyedit\n\nintent: Change one guide.\n\nedits:\n- replace docs/guide.md\n"); + expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); + t.pb(["build"], { cwd: t.fork.path }); + expect(outputs(t)).toEqual(disk); + }); + + const copiedApp = (t: ForkCase): void => { + handChange(t, "second", "Copy the app.", ["copy app.txt -> app2.txt"]); + t.pb(["build"], { cwd: t.fork.path }); + t.fork.commit("copy"); + }; + const editedCopy = (t: ForkCase): void => { + copiedApp(t); + t.fork.write("app2.txt", t.fork.read("app2.txt").replace("six", "SIX")); + expect(t.pb(["record", "copyedit", "--intent", "Shout six in the copy."], { cwd: t.fork.path }).stdout).toBe("file app2.txt\n"); + t.pb(["build"], { cwd: t.fork.path }); + t.fork.commit("copyedit"); + }; + const upstreamApp = (t: ForkCase, from: string, to: string): void => { + t.up.write("app.txt", t.up.read("app.txt").replace(from, to)); + t.up.commit(to); + }; + + forkTest("recording an edit to the destination of an upstream copy records a file edit there that follows upstream", (t) => { + editedCopy(t); + expect(changeText(t, "copyedit")).toBe("# copyedit\n\nintent: Shout six in the copy.\n\nedits:\n- file app2.txt\n"); + expect(read(join(t.fork.path, ".patchbook/changes/copyedit/base/app2.txt.pb"))).toBe(t.up.read("app.txt")); + expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); + upstreamApp(t, "one", "ONE"); + expect(t.pb(["sync"], { cwd: t.fork.path }).stdout).toContain("1 of ours merged cleanly, 0 conflicts, 0 gone."); + t.pb(["build"], { cwd: t.fork.path }); + expect(t.fork.read("app2.txt")).toBe(t.up.read("app.txt").replace("six", "SIX")); + expect(t.fork.read("app.txt")).toBe(t.up.read("app.txt")); + expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); + }); + + forkTest("sync names an edited copy's file edit whose base copy is missing, changes nothing, and works again once it is back", (t) => { + editedCopy(t); + const book = join(t.fork.path, ".patchbook"); + const copy = join(book, "changes/copyedit/base/app2.txt.pb"); + const saved = read(copy); + rmSync(copy); + upstreamApp(t, "one", "ONE"); + const before = snapshot(book); + const failed = t.pb(["sync"], { cwd: t.fork.path, code: 1 }); + expect(failed.stderr).toContain("patchbook: can't sync upstream: change copyedit has no base copy of app2.txt (.patchbook/changes/copyedit/base/app2.txt.pb). "); + expect(failed.stderr).toContain("Nothing was changed."); + expect(failed.stderr).not.toContain(" at "); + expect(snapshot(book)).toEqual(before); + writeFileSync(copy, saved); + expect(t.pb(["sync"], { cwd: t.fork.path }).stdout).toContain("1 of ours merged cleanly, 0 conflicts, 0 gone."); + }); + + for (const [lost, sides] of [["base", ["base"]], ["ours", ["ours"]], ["both", ["base", "ours"]]] as const) { + forkTest(`status and build name the change and the ${lost} copy of an edited copy that is missing`, (t) => { + editedCopy(t); + for (const side of sides) rmSync(join(t.fork.path, `.patchbook/changes/copyedit/${side}/app2.txt.pb`)); + const detail = `its ${sides.join(" and ")} ${sides.length > 1 ? "copies are" : "copy is"} missing`; + const status = t.pb(["status"], { cwd: t.fork.path, code: 1 }).stdout; + expect(status).toContain(`invalid changes/copyedit file app2.txt: ${detail}\n`); + expect(t.pb(["build"], { cwd: t.fork.path, code: 1 }).stderr).toContain(`invalid changes/copyedit file app2.txt: ${detail}\n`); + const problems = JSON.parse(t.pb(["status", "--json"], { cwd: t.fork.path, code: 1 }).stdout).problems; + expect(problems).toContainEqual({ problem: "invalid", file: "changes/copyedit", edit: "file app2.txt", detail }); + }); + } + + forkTest("status names the change and the edit of an edited copy whose base differs from its source", (t) => { + editedCopy(t); + writeFileSync(join(t.fork.path, ".patchbook/changes/copyedit/base/app2.txt.pb"), "not the source\n"); + const detail = "its base differs from upstream at the pin; run sync"; + expect(t.pb(["status"], { cwd: t.fork.path, code: 1 }).stdout).toContain(`stale changes/copyedit file app2.txt: ${detail}\n`); + const problems = JSON.parse(t.pb(["status", "--json"], { cwd: t.fork.path, code: 1 }).stdout).problems; + expect(problems).toContainEqual({ problem: "stale", file: "changes/copyedit", edit: "file app2.txt", detail }); + }); + + forkTest("sync reports a conflict in an edited copy when upstream edits the same line, and the build refuses until it is resolved", (t) => { + editedCopy(t); + upstreamApp(t, "six", "6"); + expect(t.pb(["sync"], { cwd: t.fork.path }).stdout).toContain("0 of ours merged cleanly, 1 conflicts, 0 gone."); + const before = outputs(t); + expect(t.pb(["status"], { cwd: t.fork.path, code: 1 }).stdout).toContain("conflict app2.txt: ours has conflict markers"); + t.pb(["build"], { cwd: t.fork.path, code: 1 }); + expect(outputs(t)).toEqual(before); + const ours = join(t.fork.path, ".patchbook/changes/copyedit/ours/app2.txt.pb"); + expect(read(ours)).toContain("<<<<<<< ours\nSIX\n=======\n6\n>>>>>>> upstream\n"); + writeFileSync(ours, t.up.read("app.txt").replace("6", "SIX")); + t.pb(["build"], { cwd: t.fork.path }); + expect([t.fork.read("app.txt"), t.fork.read("app2.txt")]).toEqual([t.up.read("app.txt"), t.up.read("app.txt").replace("6", "SIX")]); + }); + + forkTest("record updates an edited copy in its change, and deleting the copy drops the file edit", (t) => { + editedCopy(t); + t.fork.write("app2.txt", t.fork.read("app2.txt").replace("two", "TWO")); + expect(t.pb(["record", "copyedit", "--intent", "Shout two and six in the copy."], { cwd: t.fork.path }).stdout).toBe("file app2.txt\n"); + expect(changeText(t, "copyedit")).toBe("# copyedit\n\nintent: Shout two and six in the copy.\n\nedits:\n- file app2.txt\n"); + const copy = (side: string) => join(t.fork.path, `.patchbook/changes/copyedit/${side}/app2.txt.pb`); + expect([read(copy("base")), read(copy("ours"))]).toEqual([t.up.read("app.txt"), t.up.read("app.txt").replace("two", "TWO").replace("six", "SIX")]); + t.pb(["build"], { cwd: t.fork.path }); + t.fork.rm("app2.txt"); + expect(t.pb(["record", "dropcopy", "--intent", "Drop the copy."], { cwd: t.fork.path }).stdout).toBe("delete app2.txt (file edit removed from copyedit)\n"); + expect(changeText(t, "copyedit")).toBe("# copyedit\n\nintent: Shout two and six in the copy.\n\nedits:\n"); + expect([existsSync(copy("base")), existsSync(copy("ours"))]).toEqual([false, false]); + expect(changeText(t, "dropcopy")).toContain("- delete app2.txt"); + expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); + t.pb(["build"], { cwd: t.fork.path }); + expect(existsSync(join(t.fork.path, "app2.txt"))).toBe(false); + }); + + forkTest("record edits the source of a copy that has its own file edit as a file edit, and both outputs follow upstream", (t) => { + editedCopy(t); + t.fork.write("app.txt", t.fork.read("app.txt").replace("four", "FOUR")); + expect(t.pb(["record", "srcedit", "--intent", "Shout four in the source."], { cwd: t.fork.path }).stdout).toBe("file app.txt\n"); + expect(changeText(t, "srcedit")).toBe("# srcedit\n\nintent: Shout four in the source.\n\nedits:\n- file app.txt\n"); + t.pb(["build"], { cwd: t.fork.path }); + t.fork.commit("srcedit"); + upstreamApp(t, "one", "ONE"); + expect(t.pb(["sync"], { cwd: t.fork.path }).stdout).toContain("2 of ours merged cleanly, 0 conflicts, 0 gone."); + t.pb(["build"], { cwd: t.fork.path }); + expect([t.fork.read("app.txt"), t.fork.read("app2.txt")]).toEqual([t.up.read("app.txt").replace("four", "FOUR"), t.up.read("app.txt").replace("six", "SIX")]); + expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); + }); + + for (const kind of ["copy", "move"] as const) { + forkTest(`a later ${kind} of an edited copy builds the copy's edit, which keeps following upstream`, (t) => { + editedCopy(t); + handChange(t, "again", "Ship the copy as app3.", [`${kind} app2.txt -> app3.txt`]); + t.pb(["build"], { cwd: t.fork.path }); + expect(t.fork.read("app3.txt")).toBe(t.up.read("app.txt").replace("six", "SIX")); + expect(existsSync(join(t.fork.path, "app2.txt"))).toBe(kind === "copy"); + expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); + t.fork.commit(kind); + upstreamApp(t, "one", "ONE"); + expect(t.pb(["sync"], { cwd: t.fork.path }).stdout).toContain("1 of ours merged cleanly, 0 conflicts, 0 gone."); t.pb(["build"], { cwd: t.fork.path }); - t.fork.write(path, "a copied guide\n"); - const disk = outputs(t); - expect(t.pb(["record", "copyedit", "--intent", "Change one guide."], { cwd: t.fork.path }).stdout).toBe(`replace ${path}\n`); - expect(changeText(t, "copyedit")).toBe(`# copyedit\n\nintent: Change one guide.\n\nedits:\n- replace ${path}\n`); + expect(t.fork.read("app3.txt")).toBe(t.up.read("app.txt").replace("six", "SIX")); + expect(t.fork.read("app.txt")).toBe(t.up.read("app.txt")); expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); + }); + } + + forkTest("deleting an edited copy that a later copy reads keeps the edit in that copy", (t) => { + editedCopy(t); + handChange(t, "again", "Ship the copy as app3.", ["copy app2.txt -> app3.txt"]); + t.pb(["build"], { cwd: t.fork.path }); + t.fork.rm("app2.txt"); + expect(t.pb(["record", "dropcopy", "--intent", "Drop the copy."], { cwd: t.fork.path }).stdout).toBe("delete app2.txt\n"); + expect(changeText(t, "copyedit")).toContain("- file app2.txt\n"); + expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); + t.pb(["build"], { cwd: t.fork.path }); + expect(t.fork.read("app3.txt")).toBe(t.up.read("app.txt").replace("six", "SIX")); + expect(existsSync(join(t.fork.path, "app2.txt"))).toBe(false); + t.fork.commit("dropcopy"); + upstreamApp(t, "one", "ONE"); + expect(t.pb(["sync"], { cwd: t.fork.path }).stdout).toContain("1 of ours merged cleanly, 0 conflicts, 0 gone."); + t.pb(["build"], { cwd: t.fork.path }); + expect(t.fork.read("app3.txt")).toBe(t.up.read("app.txt").replace("six", "SIX")); + expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); + }); + + for (const kind of ["replace", "delete"] as const) { + forkTest(`a hand-written ${kind} of an edited copy builds after upstream changes the line the copy's edit changed`, (t) => { + editedCopy(t); + handChange(t, "over", "Write the copy by hand.", [`${kind} app2.txt`], kind === "replace" ? { "app2.txt": "by hand\n" } : {}); t.pb(["build"], { cwd: t.fork.path }); - expect(outputs(t)).toEqual(disk); + t.fork.commit(kind); + const copy = (side: string) => read(join(t.fork.path, `.patchbook/changes/copyedit/${side}/app2.txt.pb`)); + const copies = [copy("base"), copy("ours")]; + upstreamApp(t, "six", "6"); + expect(t.pb(["sync"], { cwd: t.fork.path }).stdout).toContain("0 of ours merged cleanly, 0 conflicts, 0 gone."); + expect([copy("base"), copy("ours")]).toEqual(copies); + t.pb(["build"], { cwd: t.fork.path }); + expect(t.fork.read("app.txt")).toBe(t.up.read("app.txt")); + if (kind === "replace") expect(t.fork.read("app2.txt")).toBe("by hand\n"); + else expect(existsSync(join(t.fork.path, "app2.txt"))).toBe(false); + expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); }); } + forkTest("the hook commits a hand-written replace of an edited copy whose edit holds sync's conflict", (t) => { + editedCopy(t); + upstreamApp(t, "six", "6"); + expect(t.pb(["sync"], { cwd: t.fork.path }).stdout).toContain("0 of ours merged cleanly, 1 conflicts, 0 gone."); + handChange(t, "over", "Write the copy by hand.", ["replace app2.txt"], { "app2.txt": "by hand\n" }); + sh(["git", "add", "-A"], { cwd: t.fork.path }); + sh(["git", "commit", "-qm", "by hand"], { cwd: t.fork.path, env: withHook(t) }); + expect(t.fork.read("app2.txt")).toBe("by hand\n"); + expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); + }); + + forkTest("an edited copy whose source upstream deletes is gone, since no copy reaches it", (t) => { + editedCopy(t); + t.up.rm("app.txt"); + t.up.commit("drop app"); + t.pb(["sync"], { cwd: t.fork.path }); + expect(reportOf(t.fork.path).gone).toEqual([{ change: "copyedit", path: "app2.txt", maybe: [] }]); + const status = t.pb(["status"], { cwd: t.fork.path, code: 1 }).stdout; + expect(status).toContain("gone changes/second copy app.txt -> app2.txt: app.txt no longer exists\n"); + expect(status).toContain("gone changes/copyedit file app2.txt: no earlier copy or move of an upstream file reaches it\n"); + const problems = JSON.parse(t.pb(["status", "--json"], { cwd: t.fork.path, code: 1 }).stdout).problems; + expect(problems).toContainEqual({ + problem: "gone", file: "changes/copyedit", edit: "file app2.txt", detail: "no earlier copy or move of an upstream file reaches it", + }); + }); + + const LOGO = Buffer.from([0, 1, 2, 0xff]); + const keptOurs = (path: string, from: string) => `patchbook: ${path} (change copyedit): upstream changed ${from}, and sync merges only text, ` + + "so it kept ours. To take upstream's file instead, write it over the output and run patchbook record.\n"; + + for (const edit of ["bytes", "mode"] as const) { + forkTest(`an edited binary copy keeps our ${edit} and builds after upstream changes its source`, (t) => { + writeFileSync(join(t.up.path, "logo.bin"), LOGO); + t.up.commit("logo"); + t.pb(["sync"], { cwd: t.fork.path }); + handChange(t, "second", "Copy the logo.", ["copy logo.bin -> logo2.bin"]); + t.pb(["build"], { cwd: t.fork.path }); + t.fork.commit("copy"); + const logo2 = join(t.fork.path, "logo2.bin"); + if (edit === "bytes") writeFileSync(logo2, Buffer.from([0, 9, 2, 0xfe])); + else chmodSync(logo2, 0o755); + const ours = readFileSync(logo2); + expect(t.pb(["record", "copyedit", "--intent", "Change the copy's logo."], { cwd: t.fork.path }).stdout).toBe("file logo2.bin\n"); + expect(changeText(t, "copyedit")).toBe("# copyedit\n\nintent: Change the copy's logo.\n\nedits:\n- file logo2.bin\n"); + t.pb(["build"], { cwd: t.fork.path }); + t.fork.commit("copyedit"); + writeFileSync(join(t.up.path, "logo.bin"), Buffer.from([0, 5, 2, 0xfd])); + t.up.commit("new logo"); + const sync = t.pb(["sync"], { cwd: t.fork.path }); + expect(sync.stdout).toContain("0 of ours merged cleanly, 0 conflicts, 0 gone."); + expect(sync.stderr).toContain(keptOurs("logo2.bin", "logo.bin")); + expect(reportOf(t.fork.path).replacedUpstreamChanged).toEqual(["copyedit: logo2.bin"]); + t.pb(["build"], { cwd: t.fork.path }); + expect(readFileSync(logo2)).toEqual(ours); + expect(statSync(logo2).mode & 0o111).toBe(edit === "mode" ? 0o111 : 0); + expect(readFileSync(join(t.fork.path, "logo.bin"))).toEqual(Buffer.from([0, 5, 2, 0xfd])); + expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); + }); + } + + forkTest("an edited copy keeps its text when upstream makes its source binary, and takes upstream's file once it is recorded", (t) => { + editedCopy(t); + const ours = t.fork.read("app2.txt"); + writeFileSync(join(t.up.path, "app.txt"), LOGO); + t.up.commit("binary app"); + const sync = t.pb(["sync"], { cwd: t.fork.path }); + expect(sync.stdout).toContain("0 of ours merged cleanly, 0 conflicts, 0 gone."); + expect(sync.stderr).toContain(keptOurs("app2.txt", "app.txt")); + t.pb(["build"], { cwd: t.fork.path }); + expect(t.fork.read("app2.txt")).toBe(ours); + expect(readFileSync(join(t.fork.path, "app.txt"))).toEqual(LOGO); + expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); + writeFileSync(join(t.fork.path, "app2.txt"), LOGO); + expect(t.pb(["record", "copyedit", "--intent", "Take upstream's app."], { cwd: t.fork.path }).stdout).toBe("file app2.txt\n"); + t.pb(["build"], { cwd: t.fork.path }); + expect(readFileSync(join(t.fork.path, "app2.txt"))).toEqual(LOGO); + expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); + }); + + forkTest("a mode-only edit to a copy keeps its mode and follows upstream", (t) => { + copiedApp(t); + chmodSync(join(t.fork.path, "app2.txt"), 0o755); + expect(t.pb(["record", "copyedit", "--intent", "Make the copy executable."], { cwd: t.fork.path }).stdout).toBe("file app2.txt\n"); + t.pb(["build"], { cwd: t.fork.path }); + t.fork.commit("copyedit"); + upstreamApp(t, "one", "ONE"); + expect(t.pb(["sync"], { cwd: t.fork.path }).stdout).toContain("1 of ours merged cleanly, 0 conflicts, 0 gone."); + t.pb(["build"], { cwd: t.fork.path }); + expect(t.fork.read("app2.txt")).toBe(t.up.read("app.txt")); + expect(statSync(join(t.fork.path, "app2.txt")).mode & 0o111).toBe(0o111); + expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); + }); + + forkTest("record refuses an edit to a copy's destination into a change before the copy", (t) => { + handChange(t, "early", "Add an early file.", ["add early.txt"], { "early.txt": "early\n" }); + copiedApp(t); + const early = changeText(t, "early"); + t.fork.write("app2.txt", t.fork.read("app2.txt").replace("six", "SIX")); + expect(t.pb(["record", "early"], { cwd: t.fork.path, code: 1 }).stderr).toContain("patchbook: can't record into early:\n" + + " file app2.txt: copy app.txt -> app2.txt in second, later in the series, has to come before it\n" + + "Record into second or a change after it, or into a new change.\n"); + expect(changeText(t, "early")).toBe(early); + t.pb(["record", "second"], { cwd: t.fork.path }); + expect(changeText(t, "second")).toContain("edits:\n- copy app.txt -> app2.txt\n- file app2.txt\n"); + expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); + t.pb(["build"], { cwd: t.fork.path }); + expect(t.fork.read("app2.txt")).toBe(t.up.read("app.txt").replace("six", "SIX")); + }); + + forkTest("record keeps an edited rename of a file that a copy still builds from following upstream", (t) => { + copiedApp(t); + sh(["git", "mv", "app.txt", "app3.txt"], { cwd: t.fork.path }); + t.fork.write("app3.txt", t.fork.read("app3.txt").replace("six", "SIX")); + expect(t.pb(["record", "rename", "--intent", "Rename the app."], { cwd: t.fork.path }).stdout).toBe("move app.txt -> app3.txt\nfile app3.txt\n"); + expect(changeText(t, "rename")).toBe("# rename\n\nintent: Rename the app.\n\nedits:\n- move app.txt -> app3.txt\n- file app3.txt\n"); + t.pb(["build"], { cwd: t.fork.path }); + t.fork.commit("rename"); + upstreamApp(t, "one", "ONE"); + expect(t.pb(["sync"], { cwd: t.fork.path }).stdout).toContain("1 of ours merged cleanly, 0 conflicts, 0 gone."); + t.pb(["build"], { cwd: t.fork.path }); + expect([t.fork.read("app2.txt"), t.fork.read("app3.txt")]).toEqual([t.up.read("app.txt"), t.up.read("app.txt").replace("six", "SIX")]); + expect(existsSync(join(t.fork.path, "app.txt"))).toBe(false); + expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); + }); + + forkTest("an edited copy of another upstream's file follows that upstream through a hooked commit and a sync of both", (t) => { + const NOTES = "one\ntwo\nthree\nfour\nfive\n"; + const lib = new Repo(join(t.tmp, "lib")); + lib.write("notes.txt", NOTES); + lib.commit("lib"); + t.pb(["track", "lib", lib.path], { cwd: t.fork.path }); + handChange(t, "second", "Ship lib's notes at the root.", ["copy lib/notes.txt -> notes.txt"]); + t.pb(["build"], { cwd: t.fork.path }); + t.fork.commit("copy"); + t.fork.write("notes.txt", NOTES.replace("five", "FIVE")); + sh(["git", "add", "-A"], { cwd: t.fork.path }); + const commit = sh(["git", "commit", "-qm", "shout five"], { cwd: t.fork.path, env: { ...t.env, PATCHBOOK_HOOK: "1", PATCHBOOK_INTENT: "Shout five." } }); + expect(commit.stderr).toContain("shout-five: Shout five.\nfile notes.txt\n"); + expect(changeText(t, "shout-five")).toBe("# shout-five\n\nintent: Shout five.\n\nedits:\n- file notes.txt\n"); + expect(read(join(t.fork.path, ".patchbook/changes/shout-five/base/notes.txt.pb"))).toBe(NOTES); + upstreamApp(t, "one", "ONE"); + lib.write("notes.txt", NOTES.replace("one", "ONE")); + lib.commit("shout one"); + const sync = t.pb(["sync"], { cwd: t.fork.path }).stdout; + expect(sync).toMatch(/^upstream: pinned \w+\. 1 upstream files changed, 0 of ours merged cleanly, 0 conflicts, 0 gone\.$/m); + expect(sync).toMatch(/^lib: pinned \w+\. 1 upstream files changed, 1 of ours merged cleanly, 0 conflicts, 0 gone\.$/m); + t.pb(["build"], { cwd: t.fork.path }); + expect([t.fork.read("lib/notes.txt"), t.fork.read("notes.txt")]).toEqual([NOTES.replace("one", "ONE"), NOTES.replace("one", "ONE").replace("five", "FIVE")]); + expect(t.pb(["status"], { cwd: t.fork.path }).stdout).toContain("no problems"); + }); + forkTest("record refuses a replace into the change whose file edit it would overwrite", (t) => { t.fork.write("docs/guide.md", "my guide\n"); t.pb(["record", "own", "--intent", "Own the guide."], { cwd: t.fork.path }); @@ -12771,6 +13092,54 @@ describe("VendorTest", () => { expect(prompt.split("a2/SKILL.md: ")).toHaveLength(2); }); + vendorTest("record of a renamed and edited skill that a copy still builds from writes the edit on the new path and shows the model the edit alone", (t) => { + committedSkillA(t); + t.repo.write("skills/b/SKILL.md", SKILL_A); + t.repo.write("skills/b/notes.md", "Notes on a.\n"); + expect(t.pb(["record", "twin", "--intent", "Ship a as b too."], { cwd: t.repo.path }).stdout).toBe("copy skills/a -> skills/b\n"); + sh(["git", "add", "-A"], { cwd: t.repo.path }); + sh(["git", "commit", "-qm", "twin"], { cwd: t.repo.path, env: { ...t.env, PATCHBOOK_HOOK: "0" } }); + sh(["git", "mv", "skills/a", "skills/a2"], { cwd: t.repo.path }); + t.repo.write("skills/a2/SKILL.md", t.repo.read("skills/a2/SKILL.md").replace("name: a\n", "name: a2\n")); + expect(t.pb(["record"], { cwd: t.repo.path }).stdout).toBe("shout: Shout the second line.\nmove skills/a -> skills/a2\nfile a2/SKILL.md\n"); + expect(read(join(t.tmp, "prompt.txt"))).toContain("Changed paths:\nmove skills/a -> skills/a2\na2/SKILL.md: changed, +1 -1 lines\n\n" + + "--- built/a2/SKILL.md\n+++ disk/a2/SKILL.md\n@@ -1,5 +1,5 @@\n ---\n-name: a\n+name: a2\n ---\n \n First paragraph of a.\n"); + expect(read(join(t.repo.path, ".patchbook/changes/shout/CHANGE.md"))).toContain("edits:\n- move skills/a -> skills/a2\n- file skills/a2/SKILL.md\n"); + t.up.write("plugin/skills/a/SKILL.md", REVISED(SKILL_A)); + t.up.commit("revise"); + expect(t.pb(["sync"], { cwd: t.repo.path }).stdout).toContain("1 of ours merged cleanly, 0 conflicts, 0 gone."); + t.pb(["build"], { cwd: t.repo.path }); + expect([t.repo.read("skills/a2/SKILL.md"), t.repo.read("skills/b/SKILL.md")]).toEqual([REVISED(SKILL_A).replace("name: a\n", "name: a2\n"), REVISED(SKILL_A)]); + expect(existsSync(join(t.repo.path, "skills/a"))).toBe(false); + expect(t.pb(["status"], { cwd: t.repo.path }).stdout).toContain("no problems"); + }); + + vendorTest("hook records an edit to a copy of a skill with block entries as a file edit on the copy, which follows upstream", (t) => { + const entries = t.missingScaffoldPatchBuild(); + const skill = t.repo.read("skills/hello/SKILL.md"); + t.repo.write("skills/hello2/SKILL.md", skill); + expect(t.pb(["record", "twin", "--intent", "Ship hello twice."], { cwd: t.repo.path }).stdout).toBe("copy skills/hello -> skills/hello2\n"); + t.pb(["hook", "install"], { cwd: t.repo.path }); + sh(["git", "add", "-A"], { cwd: t.repo.path }); + sh(["git", "commit", "-qm", "twin"], { cwd: t.repo.path, env: { ...t.env, PATCHBOOK_HOOK: "0" } }); + t.repo.write("skills/hello2/SKILL.md", skill.replace("Then wave.", "Then wave twice.")); + sh(["git", "add", "-A"], { cwd: t.repo.path }); + const commit = sh(["git", "commit", "-qm", "wave"], { cwd: t.repo.path, env: { ...t.env, PATCHBOOK_HOOK: "1", PATCHBOOK_INTENT: "Wave twice." } }); + expect(commit.stderr).toContain("wave-twice: Wave twice.\nfile hello2/SKILL.md\n"); + const change = join(t.repo.path, ".patchbook/changes/wave-twice"); + expect(read(join(change, "CHANGE.md"))).toContain("edits:\n- file skills/hello2/SKILL.md\n"); + expect(read(join(change, "base/skills/hello2/SKILL.md.pb"))).toBe(t.up.read("plugin/skills/hello/SKILL.md")); + expect(existsSync(entries)).toBe(true); + expect(sh(["git", "status", "--porcelain"], { cwd: t.repo.path }).stdout).toBe(""); + t.up.write("plugin/skills/hello/SKILL.md", t.up.read("plugin/skills/hello/SKILL.md").replace("# Hello", "# Hello there")); + t.up.commit("there"); + expect(t.pb(["sync"], { cwd: t.repo.path }).stdout).toContain("1 of ours merged cleanly, 0 conflicts, 0 gone."); + t.pb(["build"], { cwd: t.repo.path }); + expect([t.repo.read("skills/hello/SKILL.md"), t.repo.read("skills/hello2/SKILL.md")]) + .toEqual([skill.replace("# Hello", "# Hello there"), skill.replace("# Hello", "# Hello there").replace("Then wave.", "Then wave twice.")]); + expect(t.pb(["status"], { cwd: t.repo.path }).stdout).toContain("no problems"); + }); + vendorTest("record of a renamed skill with no edit shows the model the move and no diff", (t) => { committedSkillA(t); sh(["git", "mv", "skills/a", "skills/a2"], { cwd: t.repo.path }); diff --git a/test/units.test.ts b/test/units.test.ts index 7a370dfc..8fc9cc21 100644 --- a/test/units.test.ts +++ b/test/units.test.ts @@ -1857,7 +1857,7 @@ describe("classify", () => { const w = twins([["new.md", ours(added, "skills/new.md")], ["new2.md", ours(added, "skills/new.md")], ["new3.md", ours(added, "skills/new.md")]], { "new.md": "a", "new2.md": null, "new3.md": "built" }); expect(classify(w, ["new.md", "new2.md"])).toMatchObject([ - { kind: "replace", path: "new.md", staged: "skills/new.md", entries: null }, + { kind: "replace", path: "new.md", staged: "skills/new.md" }, { kind: "delete-upstream", path: "new2.md", staged: "skills/new2.md" }, ]); expect(needOf(classify(w, ["new.md"])[0]!)).toEqual({ named: true, drafts: [], writes: { kind: "replace", path: "skills/new.md" } }); @@ -1873,26 +1873,49 @@ describe("classify", () => { expect(classify(alone, ["new.md"])).toMatchObject([{ kind: "unadd", path: "new.md" }]); }); - test("edits to outputs built from one upstream file are replaces while another output is on disk, and a delete stands alone", () => { + test("an edit to a copy's destination is a file edit there while another output of its upstream file is on disk, and a delete stands alone", () => { const w = twins([["plain.md", up("skills/plain.md")], ["plain2.md", up("skills/plain.md")], ["plain3.md", up("skills/plain.md")]], - { "plain.md": "a", "plain2.md": "b", "plain3.md": null }); - expect(classify(w, ["plain.md", "plain2.md", "plain3.md"])).toMatchObject([ - { kind: "replace", path: "plain.md", staged: "skills/plain.md" }, - { kind: "replace", path: "plain2.md", staged: "skills/plain2.md" }, + { "plain.md": "built", "plain2.md": "b", "plain3.md": null }); + expect(classify(w, ["plain2.md", "plain3.md"])).toMatchObject([ + { kind: "file-edit", path: "plain2.md", rel: "skills/plain2.md", to: { kind: "recorded", base: f("upstream") }, entries: null }, { kind: "delete-upstream", path: "plain3.md", staged: "skills/plain3.md" }, ]); - const one = twins([["plain.md", up("skills/plain.md")], ["plain3.md", up("skills/plain.md")]], { "plain.md": "a", "plain3.md": null }); - expect(classify(one, ["plain.md", "plain3.md"])).toMatchObject([{ kind: "file-edit", path: "plain.md" }, { kind: "delete-upstream", path: "plain3.md" }]); + expect(needOf(classify(w, ["plain2.md"])[0]!)).toMatchObject({ named: true, writes: { kind: "file", path: "skills/plain2.md" } }); + const one = twins([["plain.md", up("skills/plain.md")], ["plain3.md", up("skills/plain.md")]], { "plain3.md": "a", "plain.md": null }); + expect(classify(one, ["plain3.md", "plain.md"])).toMatchObject([{ kind: "file-edit", path: "plain3.md", rel: "skills/plain.md" }, { kind: "delete-upstream", path: "plain.md" }]); }); - test("a replace takes the block entries of its upstream file with it only when it replaces every output of that file", () => { - const w = { ...twins([["plain.md", up("skills/plain.md")], ["plain2.md", up("skills/plain.md")]], { "plain.md": "a", "plain2.md": "b" }), - blocks: new Set(["skills/plain.md"]) }; + test("an edit to the source of a copy is a replace while a destination on disk still builds from it, and a file edit once each one is edited too", () => { + const w = twins([["plain.md", up("skills/plain.md")], ["plain2.md", up("skills/plain.md")], ["plain3.md", up("skills/plain.md")]], + { "plain.md": "a", "plain2.md": "b", "plain3.md": "built" }); expect(classify(w, ["plain.md", "plain2.md"])).toMatchObject([ - { kind: "replace", path: "plain.md", entries: "blocks/skills/plain.md.entries" }, - { kind: "replace", path: "plain2.md", entries: "blocks/skills/plain.md.entries" }, + { kind: "replace", path: "plain.md", staged: "skills/plain.md" }, + { kind: "file-edit", path: "plain2.md", rel: "skills/plain2.md" }, + ]); + expect(classify(w, ["plain.md", "plain2.md", "plain3.md"])).toMatchObject([ + { kind: "file-edit", path: "plain.md", rel: "skills/plain.md" }, + { kind: "file-edit", path: "plain2.md", rel: "skills/plain2.md" }, + { kind: "file-edit", path: "plain3.md", rel: "skills/plain3.md" }, + ]); + }); + + test("a file edit on a copy's destination takes the block entries of its upstream file with it only when no output reads them after the record", () => { + const sources: [string, Source][] = [["plain.md", up("skills/plain.md")], ["plain2.md", up("skills/plain.md")], ["plain3.md", up("skills/plain.md")]]; + const w = (edits: Record) => ({ ...twins(sources, edits), blocks: new Set(["skills/plain.md"]) }); + const entries = "blocks/skills/plain.md.entries"; + expect(classify(w({ "plain.md": null, "plain2.md": "b", "plain3.md": "c" }), ["plain.md", "plain2.md", "plain3.md"])).toMatchObject([ + { kind: "delete-upstream", path: "plain.md", entries: null }, + { kind: "file-edit", path: "plain2.md", entries }, + { kind: "file-edit", path: "plain3.md", entries }, + ]); + expect(classify(w({ "plain.md": null, "plain2.md": "b", "plain3.md": "built" }), ["plain.md", "plain2.md"])).toMatchObject([ + { kind: "delete-upstream", path: "plain.md" }, + { kind: "file-edit", path: "plain2.md", entries: null }, + ]); + expect(classify(w({ "plain.md": "built", "plain2.md": "b", "plain3.md": "c" }), ["plain2.md", "plain3.md"])).toMatchObject([ + { kind: "file-edit", path: "plain2.md", entries: null }, + { kind: "file-edit", path: "plain3.md", entries: null }, ]); - expect(classify(w, ["plain2.md"])).toMatchObject([{ kind: "replace", path: "plain2.md", entries: null }]); }); test("a mode change to a file with block entries names the file as a string literal", () => {