Artifact e5074eaf11f59a71ebc6f4dbf76e15db3a7b25a1decb300ea93a8624b48f387d:
- File
internal/branch/branch.go
— part of check-in
[d810a8118f]
at
2026-10-18 20:01:53
on branch main
— fix: handle time exactly as fossil does (#442)
* fix(manifest): round a caller's check-in and tag time as fossil does
Fossil reads a --date-override through SQLite's strftime, which rounds the seconds to the millisecond (holding a fraction past .999 in its second) rather than truncating them. A caller time finer than a millisecond now gets the D card fossil would write for it; the default clock time is still truncated, as fossil reads its clock.
fsltype.CardTime and CardTimeNow are the one place both rules live, and the checkout commit path and branch creation take their default time through them.
* fix(repo): stamp config and user rows in seconds since 1970
Fossil writes config.mtime and user.mtime with its now() SQL function, time(0). SetConfig, SetHashPolicy and CreateUser wrote julianday('now') instead, so fossil read those rows as dating from 1970 when comparing times in a configuration merge, and SetCaps and SetPassword left the user's mtime alone where fossil's user command restamps it.
* fix(auth): read and write user.cexpire as a Julian day
Fossil keeps user.cexpire as a Julian day (src/login.c). A sync login parsed it as RFC 3339 or 'YYYY-MM-DD HH:MM:SS' text, so any value fossil had written failed to parse and the login was refused as expired. The expiry is now read through julianday(), which takes both forms, and repo invite --ttl writes a Julian day; its write error is now checked.
* fix(checkout): set file times as fossil's --setmtime does
Fossil's --setmtime gives each unedited file the time of the newest check-in, among the version and its primary ancestors, that recorded the file's content, truncated to whole seconds (mtime_of_manifest_file), and it does so for every unedited file of the version once the checkout is up to date (vfile_check_signature with CKSIG_SETMTIME). SetMTime gave every written file the target check-in's time to the millisecond, and an update left the files it did not write alone.
* fix(stash): keep and show stash and bisect times as fossil does
Fossil stores stash.ctime as julianday('now') and lists it with datetime(ctime); go-libfossil stored CURRENT_TIMESTAMP text, which the two drivers returned in different forms, and showed a fossil-written time as a bare number. bisect's list now shows datetime(event.mtime), as fossil's bisect ls does, instead of the Julian day.
* test(verify): fossil rebuild keeps the times go-libfossil stores
A repository go-libfossil wrote, with check-ins at caller and clock times, a tag and a branch, is rebuilt by the fossil binary, and every check-in event, plink and tagxref time must come back unchanged.
* test(sync): a fossil clone and push agree on every synced time
The fossil binary clones a go-libfossil server, unversioned files included, commits at a time finer than a millisecond and pushes back. Each side derives check-in event, plink and tagxref times from the artifacts itself, and the unversioned time travels on the wire; both repositories must then hold the same values.
* fix(resolve): bound NAME:TIMESTAMP with julianday() as fossil does
Fossil resolves BRANCH:TIMESTAMP with event.mtime<=julianday(BOUND). The bound was computed in the text form event rows hold, so on a millisecond where that form is larger than julianday()'s, a check-in at the bound itself resolved here and not in fossil.
* fix(manifest): round a caller's card time with integer arithmetic
CardTime followed SQLite's printing of the seconds as a double, which is not a well-defined rounding: at exact half-millisecond ties fossil 2.28's SQLite gives .124 for .1245 but .020 for .0195, and other SQLite versions differ again. A caller time is now rounded to the nearest millisecond on its nanoseconds, ties up, held at .999 as fossil holds it. The fossil binary test compares every non-tie value, across second, minute, day and year ends; ties are asserted on their own.
* fix(auth): ignore user.cexpire at sync login, as fossil does
user.cexpire is the expiry of fossil's web-login cookie: fossil sets it at web login, writes 0 at logout, and its sync login (check_login) never reads it. Refusing a sync login on it locked out anyone who had logged into or out of fossil's web UI, or whose cookie had lapsed.
The invite TTL that relied on it now lives in a config row of its own, invite-expire:LOGIN, as a UTC instant checked at sync login; repo invite no longer writes cexpire, and the expiry is no longer written in local time and read as UTC. Deleting a user drops its invite expiry.
Tracked in #441.
* fix(repo): convert Julian config and user mtimes on open
Repositories go-libfossil wrote before config and user rows were stamped in seconds since 1970 still hold Julian days there, which fossil reads as January 1970. Open converts those rows to the seconds they stand for. It checks first and writes only when a row needs it, so it converts once and takes no write lock on an up-to-date repository.
* fix(checkout): set a file no check-in recorded to 1970, as fossil does
With no mlink row for a file's artifact in the version's ancestry, fossil's max(event.mtime) is NULL, which mtime_of_manifest_file reads as 0, so --setmtime sets the file to 1970. SetMTime skipped the file.
* fix(stash): list stashes by creation time, as fossil's stash ls does
fossil stash ls orders by ctime, oldest first. List ordered by stash id, newest first; it now orders by ctime with the id breaking a tie.
* fix(auth): clear a login's invite expiry with the user, atomically
DeleteUser removed the user and its invite expiry in two statements; a failure between them left the user's expiry behind or the user without it. Both now go in one transaction. A user fossil deleted leaves its invite-expire row behind, so CreateUser clears it in the same transaction as the insert; repo invite sets its own expiry afterwards.
The on-open conversion of Julian config and user mtimes is now best-effort: while another connection holds the write lock, Open skips it and a later open converts the rows, instead of failing. (user: [email protected], size: 7245) [annotate] [blame] [check-ins using] [more...]
package branch import ( "database/sql" "errors" "fmt" "time" "github.com/danmestas/go-libfossil/db" "github.com/danmestas/go-libfossil/internal/content" "github.com/danmestas/go-libfossil/internal/deck" libfossil "github.com/danmestas/go-libfossil/internal/fsltype" "github.com/danmestas/go-libfossil/internal/manifest" "github.com/danmestas/go-libfossil/internal/repo" "github.com/danmestas/go-libfossil/internal/tag" ) type CreateOpts struct { Name string Parent libfossil.FslID User string Time time.Time Color string } type Branch struct { Name string LastMTime float64 IsClosed bool CheckinCount int LatestUUID string } func Create(r *repo.Repo, opts CreateOpts) (libfossil.FslID, string, error) { if r == nil { panic("branch.Create: r must not be nil") } if opts.Name == "" { panic("branch.Create: opts.Name must not be empty") } if opts.Parent <= 0 { panic("branch.Create: opts.Parent must be positive") } if opts.User == "" { panic("branch.Create: opts.User must not be empty") } // 1. Get parent's file list. entries, err := manifest.ListFiles(r, opts.Parent) if err != nil { return 0, "", fmt.Errorf("branch.Create list files: %w", err) } var files []manifest.File for _, e := range entries { frid, ok := content.AvailableByUUID(r.DB(), e.UUID) if !ok { return 0, "", fmt.Errorf("branch.Create: file blob %s not found", e.UUID) } // Bare Expand: each file of the single parent checkin is expanded // exactly once to seed the new branch commit. There is no repeated or // overlapping-chain access here for a cache to amortize. data, err := content.Expand(r.DB(), frid) if err != nil { return 0, "", fmt.Errorf("branch.Create: expand %s: %w", e.Name, err) } files = append(files, manifest.File{Name: e.Name, Content: data, Perm: e.Perm}) } // 2. Query existing sym-* tags on parent for cancel cards. rows, err := r.DB().Query( "SELECT tag.tagname FROM tagxref JOIN tag USING(tagid) WHERE tagxref.rid=? AND tagxref.tagtype>0 AND tag.tagname GLOB 'sym-*'", opts.Parent, ) if err != nil { return 0, "", fmt.Errorf("branch.Create query sym tags: %w", err) } defer rows.Close() var oldSyms []string for rows.Next() { var name string if err := rows.Scan(&name); err != nil { return 0, "", err } oldSyms = append(oldSyms, name) } if err := rows.Err(); err != nil { return 0, "", err } // 3. Build T-cards. var tags []deck.TagCard tags = append(tags, deck.TagCard{Type: deck.TagPropagating, Name: "branch", UUID: "*", Value: opts.Name}) tags = append(tags, deck.TagCard{Type: deck.TagPropagating, Name: "sym-" + opts.Name, UUID: "*"}) for _, old := range oldSyms { tags = append(tags, deck.TagCard{Type: deck.TagCancel, Name: old, UUID: "*"}) } if opts.Color != "" { tags = append(tags, deck.TagCard{Type: deck.TagPropagating, Name: "bgcolor", UUID: "*", Value: opts.Color}) } // 4. Create the checkin with its branch tags. Checkin applies them in its // own transaction, and refuses there a name an open branch already // carries, as `fossil branch new` does (src/branch.c branch_is_open): the // check and the write are one transaction, so of two concurrent Creates of // one name only the first commits, and a refused Create stores nothing. rid, uuid, err := manifest.Checkin(r, manifest.CheckinOpts{ Files: files, Comment: fmt.Sprintf("Create branch %s", opts.Name), User: opts.User, Parent: opts.Parent, Time: opts.Time, Tags: tags, Precheck: func(q db.Querier) error { open, err := branchIsOpen(q, opts.Name) if err != nil { return err } if open { return fmt.Errorf("an open branch named %q already exists", opts.Name) } return nil }, }) if err != nil { return 0, "", fmt.Errorf("branch.Create: %w", err) } return rid, uuid, nil } // branchIsOpen reports whether some open leaf's active branch tag is name: // a leaf (in the leaf table) whose propagating branch tag (tagtype=2) has the // value name and that carries no singleton closed tag (tagtype=1). This is // fossil's branch_is_open (src/branch.c), which uses those exact tag types. // // Create runs it on the check-in's own transaction (CheckinOpts.Precheck), so // the check and the new branch's write see one state. func branchIsOpen(q db.Querier, name string) (bool, error) { var one int err := q.QueryRow(` SELECT 1 FROM tagxref ox JOIN tag t ON t.tagid = ox.tagid WHERE t.tagname = 'branch' AND ox.value = ? AND ox.tagtype = 2 AND ox.rid IN (SELECT rid FROM leaf) AND NOT EXISTS ( SELECT 1 FROM tagxref ix JOIN tag ct ON ct.tagid = ix.tagid WHERE ct.tagname = 'closed' AND ix.rid = ox.rid AND ix.tagtype = 1 ) LIMIT 1`, name).Scan(&one) if errors.Is(err, sql.ErrNoRows) { return false, nil } if err != nil { return false, fmt.Errorf("branch.branchIsOpen %q: %w", name, err) } return true, nil } func List(r *repo.Repo) ([]Branch, error) { if r == nil { panic("branch.List: r must not be nil") } rows, err := r.DB().Query(` SELECT tagxref.value AS branch_name, max(event.mtime) AS last_mtime, count(*) AS checkin_count, (SELECT EXISTS(SELECT 1 FROM tagxref cx JOIN tag ct ON cx.tagid=ct.tagid WHERE ct.tagname='closed' AND cx.rid=ev.objid AND cx.tagtype>0) FROM tagxref bx JOIN tag bt ON bx.tagid=bt.tagid JOIN event ev ON ev.objid=bx.rid WHERE bt.tagname='branch' AND bx.value=tagxref.value AND bx.tagtype>0 ORDER BY ev.mtime DESC LIMIT 1) AS isclosed, (SELECT b.uuid FROM blob b JOIN tagxref tx4 ON b.rid=tx4.rid JOIN tag t4 ON tx4.tagid=t4.tagid JOIN event e ON e.objid=tx4.rid WHERE t4.tagname='branch' AND tx4.value=tagxref.value AND tx4.tagtype>0 ORDER BY e.mtime DESC LIMIT 1) AS latest FROM tagxref JOIN tag ON tagxref.tagid=tag.tagid JOIN event ON event.objid=tagxref.rid WHERE tag.tagname='branch' AND tagxref.tagtype>0 GROUP BY tagxref.value `) if err != nil { return nil, fmt.Errorf("branch.List: %w", err) } defer rows.Close() var branches []Branch for rows.Next() { var b Branch var isClosed *int if err := rows.Scan(&b.Name, &b.LastMTime, &b.CheckinCount, &isClosed, &b.LatestUUID); err != nil { return nil, fmt.Errorf("branch.List scan: %w", err) } b.IsClosed = isClosed != nil && *isClosed == 1 branches = append(branches, b) } return branches, rows.Err() } func Close(r *repo.Repo, name string, user string) error { if r == nil { panic("branch.Close: r must not be nil") } if name == "" { panic("branch.Close: name must not be empty") } var tipRID int64 err := r.DB().QueryRow(` SELECT tagxref.rid FROM tagxref JOIN tag ON tagxref.tagid=tag.tagid JOIN event ON event.objid=tagxref.rid WHERE tag.tagname='branch' AND tagxref.value=? AND tagxref.tagtype>0 ORDER BY event.mtime DESC LIMIT 1`, name, ).Scan(&tipRID) if err != nil { return fmt.Errorf("branch.Close: find tip for %q: %w", name, err) } _, err = tag.AddTag(r, tag.TagOpts{ TargetRID: libfossil.FslID(tipRID), TagName: "closed", TagType: tag.TagSingleton, User: user, }) if err != nil { return fmt.Errorf("branch.Close: add closed tag: %w", err) } return nil }