Files
loom-cli/internal/lock/lock.go
T
jeffryandClaude Opus 5 1543df0a0c loomctl external: list, add, check — and its first run found two changed documents
Go, standard library only, with git shelled out for list alone. list enumerates a
publisher's .loom/published by partial clone and ls-tree; add fetches one document,
writes it under .loom/externals and records the resolved origin and the publisher's
ETag in .loom/externals/.locks; check asks conditionally and reports.

The first real run did what the tool exists for. All eight documents adopted by
hand before it existed reported unlocked — the tool refuses to invent a lock by
adopting whatever the remote currently serves, since that would assert the local
copy is the one being served, which is the thing it was about to check. Locking
them fetched two that had moved: bedrock/starting.md, which now says the worked
example is private and will not link to something you cannot fetch, and cart.md,
which went to v1.

cart v1 changes a role we cast: a cart is not committed, because a committed cart
grows a third file by itself — version control does not require anybody to ask, so
the two-file rule is never invoked — and because ignored, gone means gone. Adds
.loom/cart/ to .gitignore and supersedes the isolation entry rather than editing
it. osprey and marmalade are already in history and are left there: rewriting to
honour a rule adopted afterwards costs more than it buys.

Records the conflict this creates rather than settling it: the annotation protocol
here says commit before dissolving because git is the only archive, and an ignored
cart has no archive, so dissolving would destroy the annotations outright.

Credentials are read-only, per host, and passed to git through the environment
rather than argv, because argv is visible to every process on the machine.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018UTxuSizozEA8yDitPuris
2026-09-07 14:48:29 -04:00

123 lines
3.5 KiB
Go

// Package lock reads and writes .loom/externals/.locks.
//
// One record per adopted document: where it was fetched from, resolved, and the
// ETag the publisher served with it. The ETag is opaque and is never a hash we
// compute — on gitea it happens to equal the git blob hash and on GitHub it does
// not, so a design that compares a local hash to a remote ETag works on exactly
// one host by coincidence. See .loom/event-log.md.
package lock
import (
"bufio"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
)
// Dir is where adopted documents live, relative to the repository root.
const Dir = ".loom/externals"
// File is the lock file, inside Dir.
const File = ".locks"
const header = "# loomctl locks — one record per adopted document.\n" +
"# path<TAB>url<TAB>etag The url is resolved: a short form would follow\n" +
"# whatever the default branch is at the time you ask.\n"
// Record is one adopted document.
type Record struct {
// Path is relative to Dir, and is for a person to read. The origin is the
// URL: the path does not round-trip, because it drops the route, the
// branch, and .loom/published/.
Path string
// URL is the resolved origin, branch and all.
URL string
// ETag is the publisher's, verbatim, including its quotes.
ETag string
}
// Set is every lock, keyed by path.
type Set struct {
root string
recs map[string]Record
}
func path(root string) string { return filepath.Join(root, Dir, File) }
// Load reads the lock file for the repository at root. A missing file is an
// empty set, not an error: a repository whose externals were fetched by hand has
// no locks, and reporting that is the point.
func Load(root string) (*Set, error) {
s := &Set{root: root, recs: map[string]Record{}}
f, err := os.Open(path(root))
if errors.Is(err, fs.ErrNotExist) {
return s, nil
}
if err != nil {
return nil, err
}
defer f.Close()
sc := bufio.NewScanner(f)
for n := 1; sc.Scan(); n++ {
line := sc.Text()
if strings.TrimSpace(line) == "" || strings.HasPrefix(line, "#") {
continue
}
parts := strings.Split(line, "\t")
if len(parts) != 3 {
return nil, fmt.Errorf("%s:%d: want 3 tab-separated fields, got %d", path(root), n, len(parts))
}
s.recs[parts[0]] = Record{Path: parts[0], URL: parts[1], ETag: parts[2]}
}
return s, sc.Err()
}
// Get returns the record for a path, and whether there was one.
func (s *Set) Get(p string) (Record, bool) { r, ok := s.recs[p]; return r, ok }
// Put adds or replaces a record.
func (s *Set) Put(r Record) { s.recs[r.Path] = r }
// All returns every record, ordered by path so the file diffs cleanly.
func (s *Set) All() []Record {
out := make([]Record, 0, len(s.recs))
for _, r := range s.recs {
out = append(out, r)
}
sort.Slice(out, func(i, j int) bool { return out[i].Path < out[j].Path })
return out
}
// Save writes the lock file, replacing it atomically so an interrupted write
// cannot leave a repository holding half a lock.
func (s *Set) Save() error {
p := path(s.root)
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return err
}
var b strings.Builder
b.WriteString(header)
for _, r := range s.All() {
fmt.Fprintf(&b, "%s\t%s\t%s\n", r.Path, r.URL, r.ETag)
}
tmp, err := os.CreateTemp(filepath.Dir(p), ".locks-*")
if err != nil {
return err
}
if _, err := tmp.WriteString(b.String()); err != nil {
tmp.Close()
os.Remove(tmp.Name())
return err
}
if err := tmp.Close(); err != nil {
os.Remove(tmp.Name())
return err
}
return os.Rename(tmp.Name(), p)
}