| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "io/fs" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "regexp" |
| 13 | "sort" |
| 14 | "strings" |
| 15 | |
| 16 | "the-valley/change" |
| 17 | "the-valley/rebase" |
| 18 | ) |
| 19 | |
| 20 | // The journal is every write the restacker intends and has not yet seen |
| 21 | // through, kept in the state directory before the first of them is |
| 22 | // pushed, so a pass that ends part way can tell afterwards what it did. It |
| 23 | // is the restacker's own, local file, journal.json, in the format |
| 24 | // valley-restack-journal/v1: |
| 25 | // |
| 26 | // { |
| 27 | // "schema": "valley-restack-journal/v1", |
| 28 | // "repository": "<--repo>", "target": "main", "principal": "<--principal>", |
| 29 | // "families": [ |
| 30 | // {"operation": "20261020T120400Z-1a2b3c4d", |
| 31 | // "tip": "<main's tip as captured>", |
| 32 | // "evidence": "<the evidence fingerprint as captured>", |
| 33 | // "observed": { the whole observation: Observation }, |
| 34 | // "branches": { the branch push, as rebase.PendingBranches keeps it } or null, |
| 35 | // "versions": [ each version, as rebase.PendingVersion keeps it, lower layers first ], |
| 36 | // "reports": [ {"pending": { as rebase.PendingReport keeps it }, |
| 37 | // "omitted": [ what the report leaves out of the observation ]} ], |
| 38 | // "replacements": [ each report of what did happen, in the form of a report ]} |
| 39 | // ] |
| 40 | // } |
| 41 | // |
| 42 | // Each family carries the operation that built it, and main's tip and the |
| 43 | // evidence fingerprint that operation captured, since a journal can hold |
| 44 | // families of several operations: a family stays in the journal while it |
| 45 | // is open (publish.go), and a later pass adds the families it builds. No |
| 46 | // two families share a change or a branch, since the planner has a family |
| 47 | // that would wait (waits). A |
| 48 | // family has a branch push and versions only when its operation would |
| 49 | // restack it. A replacement is a report of what did happen to a family |
| 50 | // whose branches moved, built when origin's report says otherwise |
| 51 | // (publish.go). |
| 52 | // Each version is leased on the record commit the capture read, and each |
| 53 | // report and replacement on the report origin held. Every write names the |
| 54 | // object it would push by its full ID, and every one of those objects is |
| 55 | // kept reachable in the scratch repository, under |
| 56 | // refs/valley-restack/<operation>/<object>, for as long as the journal |
| 57 | // names it (keep). |
| 58 | // |
| 59 | // The journal is read as strictly as it is written: a field missing, |
| 60 | // unknown or named twice, a form that does not agree with itself, or a |
| 61 | // journal another repository, target or principal wrote is refused, and |
| 62 | // nothing it names is decided (loadJournal). A family agrees with itself |
| 63 | // only when every write it holds is about one of its layers. A family |
| 64 | // that would restack adds exactly one version of each of its changes. |
| 65 | // Each report gives the family's result, and says published exactly what |
| 66 | // the family's versions add: nothing, for a family that adds none. Each |
| 67 | // replacement says complete or partial, says each change was published at |
| 68 | // its prepared head, and names a version only as the family adds it. A |
| 69 | // journal that would not read back as written is never kept (keep). A |
| 70 | // journal that is missing is never inferred: what origin shows of a write |
| 71 | // no journal names is left for the planner, which holds a change whose |
| 72 | // branch is not at its recorded head. |
| 73 | |
| 74 | // journalSchema names the journal's format. |
| 75 | const journalSchema = "valley-restack-journal/v1" |
| 76 | |
| 77 | // journalFile is the journal's name in the state directory. |
| 78 | const journalFile = "journal.json" |
| 79 | |
| 80 | // retainPrefix is where the scratch repository keeps every object a |
| 81 | // journaled operation would push. |
| 82 | const retainPrefix = "refs/valley-restack/" |
| 83 | |
| 84 | // Journal is the writes of every family still to be seen through. |
| 85 | type Journal struct { |
| 86 | Schema string `json:"schema"` |
| 87 | Repository string `json:"repository"` |
| 88 | Target string `json:"target"` |
| 89 | Principal string `json:"principal"` |
| 90 | Families []JournalFamily `json:"families"` |
| 91 | } |
| 92 | |
| 93 | // JournalFamily is one family's observation and the writes it would make. |
| 94 | type JournalFamily struct { |
| 95 | Operation string `json:"operation"` // the operation that built it |
| 96 | Tip string `json:"tip"` // main's tip as that operation captured it |
| 97 | Evidence string `json:"evidence"` // change.EvidenceFingerprint as captured |
| 98 | Observed Observation `json:"observed"` |
| 99 | Branches *rebase.PendingBranches `json:"branches"` |
| 100 | Versions []*rebase.PendingVersion `json:"versions"` |
| 101 | Reports []JournalReport `json:"reports"` |
| 102 | Replacements []JournalReport `json:"replacements"` // reports of what did happen, at most one a change |
| 103 | } |
| 104 | |
| 105 | // JournalReport is one change's report, and what it leaves out of the |
| 106 | // observation it was cut from: nothing for a report that holds it whole. |
| 107 | type JournalReport struct { |
| 108 | Pending *rebase.PendingReport `json:"pending"` |
| 109 | Omitted []string `json:"omitted"` |
| 110 | } |
| 111 | |
| 112 | // operationName is the shape of an operation's name, as a report's |
| 113 | // operation field takes it. |
| 114 | var operationName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._:-]*$`) |
| 115 | |
| 116 | // check refuses a journal that does not agree with itself, or that |
| 117 | // another repository, target or principal wrote. |
| 118 | func (j *Journal) check(b binding) error { |
| 119 | switch { |
| 120 | case j.Schema != journalSchema: |
| 121 | return fmt.Errorf("its schema is %q, where %q is expected", j.Schema, journalSchema) |
| 122 | case j.Repository != b.Repository || j.Target != b.Target || j.Principal != b.Principal: |
| 123 | return fmt.Errorf("it belongs to %s on %s as %s, and this pass is for %s on %s as %s", |
| 124 | j.Target, j.Repository, j.Principal, b.Target, b.Repository, b.Principal) |
| 125 | } |
| 126 | whose := map[string]int{} // the family each change and branch is in |
| 127 | for i, f := range j.Families { |
| 128 | if err := f.check(j.Target); err != nil { |
| 129 | return fmt.Errorf("its family %d: %w", i, err) |
| 130 | } |
| 131 | for _, l := range f.Observed.Layers { |
| 132 | for _, key := range layerKeys(l.ID, l.Branch) { |
| 133 | if k, found := whose[key]; found && k != i { |
| 134 | return fmt.Errorf("its families %d and %d share the %s", k, i, key) |
| 135 | } |
| 136 | whose[key] = i |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | return nil |
| 141 | } |
| 142 | |
| 143 | // layerKeys names what a layer is, for telling whether two families |
| 144 | // share it: "change <ID>" for a change, and "branch <name>" for the |
| 145 | // branch it is on. |
| 146 | func layerKeys(id, branch string) []string { |
| 147 | var keys []string |
| 148 | if id != "" { |
| 149 | keys = append(keys, "change "+id) |
| 150 | } |
| 151 | if branch != "" { |
| 152 | keys = append(keys, "branch "+branch) |
| 153 | } |
| 154 | return keys |
| 155 | } |
| 156 | |
| 157 | func (f *JournalFamily) check(target string) error { |
| 158 | o := f.Observed |
| 159 | switch { |
| 160 | case !operationName.MatchString(f.Operation) || len(f.Operation) > change.MaxOperation: |
| 161 | return fmt.Errorf("its operation %q is not a report's operation name", f.Operation) |
| 162 | case !rebase.IsObjectID(f.Tip): |
| 163 | return fmt.Errorf("its tip %q is not a full object ID", f.Tip) |
| 164 | case !hexOf(f.Evidence, 16): |
| 165 | return fmt.Errorf("its evidence %q is not an evidence fingerprint", f.Evidence) |
| 166 | case o.Action != restack && o.Action != hold: |
| 167 | return fmt.Errorf("its action is %q, where %q or %q is expected", o.Action, restack, hold) |
| 168 | case o.Result != change.RestackComplete && o.Result != change.RestackConflict && o.Result != change.RestackBlocked: |
| 169 | return fmt.Errorf("its result is %q", o.Result) |
| 170 | case len(o.Layers) == 0: |
| 171 | return errors.New("it observed no layer") |
| 172 | } |
| 173 | layers := map[string]ObservedLayer{} // change layers by ID |
| 174 | order := map[string]int{} |
| 175 | branches := map[string]ObservedLayer{} |
| 176 | for i, l := range o.Layers { |
| 177 | switch { |
| 178 | case l.Name == "": |
| 179 | return fmt.Errorf("its layer %d has no name", i) |
| 180 | case l.ID != "" && !change.ValidID(l.ID): |
| 181 | return fmt.Errorf("its layer %s names the change ID %q", l.Name, l.ID) |
| 182 | case l.ID != "" && (!rebase.IsObjectID(l.Record) || l.Version < 1): |
| 183 | return fmt.Errorf("its layer %s names no record commit and version", l.Name) |
| 184 | case l.ID == "" && (l.Record != "" || l.Version != 0): |
| 185 | return fmt.Errorf("its plain branch %s names a record", l.Name) |
| 186 | case !rebase.IsObjectID(l.Head): |
| 187 | return fmt.Errorf("its layer %s names the head %q", l.Name, l.Head) |
| 188 | case l.Branch != "" && !change.ValidBranch(l.Branch): |
| 189 | return fmt.Errorf("its layer %s names the branch %q", l.Name, l.Branch) |
| 190 | case l.BranchTip != "" && !rebase.IsObjectID(l.BranchTip): |
| 191 | return fmt.Errorf("its layer %s names the branch tip %q", l.Name, l.BranchTip) |
| 192 | case l.ID != "" && layers[l.ID].ID != "": |
| 193 | return fmt.Errorf("it observed %s twice", l.ID) |
| 194 | } |
| 195 | if l.ID != "" { |
| 196 | layers[l.ID], order[l.ID] = l, i |
| 197 | } |
| 198 | if l.Branch != "" { |
| 199 | branches[l.Branch] = l |
| 200 | } |
| 201 | } |
| 202 | if o.Failing != "" && layers[o.Failing].ID == "" { |
| 203 | return fmt.Errorf("its failing layer %s is none of its changes", o.Failing) |
| 204 | } |
| 205 | |
| 206 | if (f.Branches != nil) != (o.Result == change.RestackComplete) || (f.Branches == nil) != (len(f.Versions) == 0) { |
| 207 | return errors.New("it has a branch push and versions exactly when it would restack") |
| 208 | } |
| 209 | news := map[string]string{} |
| 210 | if b := f.Branches; b != nil { |
| 211 | if b.Tip != f.Tip { |
| 212 | return fmt.Errorf("its branch push was prepared on %s, not the captured tip %s", b.Tip, f.Tip) |
| 213 | } |
| 214 | for _, u := range b.Updates { |
| 215 | l, ok := branches[u.Branch] |
| 216 | if !ok || l.BranchTip != u.Old { |
| 217 | return fmt.Errorf("its branch push moves %s from %s, which it did not observe", u.Branch, u.Old) |
| 218 | } |
| 219 | news[u.Branch] = u.New |
| 220 | } |
| 221 | if len(b.Updates) != len(o.Layers) { |
| 222 | return errors.New("its branch push does not move every layer") |
| 223 | } |
| 224 | } |
| 225 | last := -1 |
| 226 | written := map[string]*rebase.PendingVersion{} // each version by change ID |
| 227 | for _, v := range f.Versions { |
| 228 | if v == nil { |
| 229 | return errors.New("it holds an empty version") |
| 230 | } |
| 231 | l, ok := layers[v.ID] |
| 232 | switch { |
| 233 | case !ok: |
| 234 | return fmt.Errorf("it adds a version to %s, which is none of its changes", v.ID) |
| 235 | case !v.Restack(): |
| 236 | return fmt.Errorf("its version of %s is not a restack's", v.ID) |
| 237 | case v.Old != l.Record || v.Branch != l.Branch || v.Head != news[l.Branch]: |
| 238 | return fmt.Errorf("its version of %s is not leased on the record it observed, or does not record the head prepared for %s", v.ID, l.Branch) |
| 239 | case order[v.ID] <= last: |
| 240 | return fmt.Errorf("its versions are not lower layers first") |
| 241 | } |
| 242 | last = order[v.ID] |
| 243 | written[v.ID] = v |
| 244 | } |
| 245 | if f.Branches != nil && len(written) != len(layers) { |
| 246 | return fmt.Errorf("it would restack %d changes and adds a version to %d of them, where each change gets exactly one", len(layers), len(written)) |
| 247 | } |
| 248 | reported := map[string]bool{} |
| 249 | for _, r := range f.Reports { |
| 250 | p := r.Pending |
| 251 | switch { |
| 252 | case p == nil: |
| 253 | return errors.New("it holds an empty report") |
| 254 | case layers[p.ID].ID == "": |
| 255 | return fmt.Errorf("it reports on %s, which is none of its changes", p.ID) |
| 256 | case reported[p.ID]: |
| 257 | return fmt.Errorf("it reports on %s twice", p.ID) |
| 258 | case !f.ours(p.Report, target): |
| 259 | return fmt.Errorf("its report on %s is not this operation's, on %s at %s", p.ID, target, f.Tip) |
| 260 | case p.Report.Result != o.Result: |
| 261 | return fmt.Errorf("its report on %s says %s, and the family's result is %s", p.ID, p.Report.Result, o.Result) |
| 262 | } |
| 263 | if err := checkClaims(p.Report, layers, written); err != nil { |
| 264 | return fmt.Errorf("its report on %s %w", p.ID, err) |
| 265 | } |
| 266 | reported[p.ID] = true |
| 267 | } |
| 268 | replaced := map[string]bool{} |
| 269 | for _, r := range f.Replacements { |
| 270 | p := r.Pending |
| 271 | switch { |
| 272 | case p == nil: |
| 273 | return errors.New("it holds an empty replacement") |
| 274 | case f.Branches == nil: |
| 275 | return fmt.Errorf("it replaces the report on %s, and moved no branch", p.ID) |
| 276 | case layers[p.ID].ID == "": |
| 277 | return fmt.Errorf("it replaces a report on %s, which is none of its changes", p.ID) |
| 278 | case replaced[p.ID]: |
| 279 | return fmt.Errorf("it replaces the report on %s twice", p.ID) |
| 280 | case !f.ours(p.Report, target): |
| 281 | return fmt.Errorf("its replacement on %s is not this operation's, on %s at %s", p.ID, target, f.Tip) |
| 282 | } |
| 283 | if err := checkHappened(p.Report, layers, written, news); err != nil { |
| 284 | return fmt.Errorf("its replacement on %s %w", p.ID, err) |
| 285 | } |
| 286 | replaced[p.ID] = true |
| 287 | } |
| 288 | return nil |
| 289 | } |
| 290 | |
| 291 | // ours reports whether a report is the family's operation's, on the |
| 292 | // target at the tip the operation captured. |
| 293 | func (f *JournalFamily) ours(r *change.RestackReport, target string) bool { |
| 294 | return r.Operation == f.Operation && r.Target == target && r.TargetTip == change.HeadPrefix+f.Tip |
| 295 | } |
| 296 | |
| 297 | // checkHappened refuses a replacement that says other than what could |
| 298 | // have happened to a family whose branches moved: each of its layers is |
| 299 | // one of the family's changes, published at the head prepared for its |
| 300 | // branch, with a version only as the family adds it. It says complete |
| 301 | // when it names every change's version, and partial otherwise. |
| 302 | func checkHappened(r *change.RestackReport, layers map[string]ObservedLayer, written map[string]*rebase.PendingVersion, news map[string]string) error { |
| 303 | all := true |
| 304 | for _, l := range r.Layers { |
| 305 | v, p := written[l.ChangeID], l.Published |
| 306 | switch { |
| 307 | case layers[l.ChangeID].ID == "": |
| 308 | return fmt.Errorf("has a layer for %s, which is none of the family's changes", l.ChangeID) |
| 309 | case p == nil || p.Head != change.HeadPrefix+news[layers[l.ChangeID].Branch]: |
| 310 | return fmt.Errorf("does not say %s was published at the head prepared for it", l.ChangeID) |
| 311 | case p.Version == nil && p.Record == nil: |
| 312 | all = false |
| 313 | case v == nil || p.Version == nil || *p.Version != v.Version || p.Record == nil || *p.Record != change.HeadPrefix+v.Commit: |
| 314 | return fmt.Errorf("says %s was published as a version the family does not add", l.ChangeID) |
| 315 | } |
| 316 | } |
| 317 | switch { |
| 318 | case r.Result == change.RestackComplete && !all: |
| 319 | return errors.New("says complete, and names a change with no version") |
| 320 | case r.Result == change.RestackPartial && all: |
| 321 | return errors.New("says partial, and names every change's version") |
| 322 | case r.Result != change.RestackComplete && r.Result != change.RestackPartial: |
| 323 | return fmt.Errorf("says %s, where complete or partial is expected", r.Result) |
| 324 | } |
| 325 | return nil |
| 326 | } |
| 327 | |
| 328 | // checkClaims refuses a report that says something was published other |
| 329 | // than what the family's versions add. Each of the report's layers is one |
| 330 | // of the family's changes. A layer says it was published exactly when the |
| 331 | // family adds a version of that change, and then names that version's |
| 332 | // head, number and record commit. |
| 333 | func checkClaims(r *change.RestackReport, layers map[string]ObservedLayer, written map[string]*rebase.PendingVersion) error { |
| 334 | for _, l := range r.Layers { |
| 335 | v, p := written[l.ChangeID], l.Published |
| 336 | switch { |
| 337 | case layers[l.ChangeID].ID == "": |
| 338 | return fmt.Errorf("has a layer for %s, which is none of the family's changes", l.ChangeID) |
| 339 | case v == nil && p != nil: |
| 340 | return fmt.Errorf("says %s was published, and the family adds no version of it", l.ChangeID) |
| 341 | case v != nil && p == nil: |
| 342 | return fmt.Errorf("says nothing was published for %s, and the family adds v%d of it", l.ChangeID, v.Version) |
| 343 | case v != nil && (p.Head != change.HeadPrefix+v.Head || p.Version == nil || *p.Version != v.Version || |
| 344 | p.Record == nil || *p.Record != change.HeadPrefix+v.Commit): |
| 345 | return fmt.Errorf("says %s was published as other than v%d at %s, record %s, which the family adds", l.ChangeID, v.Version, short(v.Head), short(v.Commit)) |
| 346 | } |
| 347 | } |
| 348 | return nil |
| 349 | } |
| 350 | |
| 351 | func hexOf(s string, n int) bool { |
| 352 | return len(s) == n && strings.Trim(s, "0123456789abcdef") == "" |
| 353 | } |
| 354 | |
| 355 | // loadJournal reads the journal in the state directory: nil when there is |
| 356 | // none. A journal that does not read, or that is another's, is an error, |
| 357 | // and nothing it names is decided. |
| 358 | func loadJournal(dir string, b binding) (*Journal, error) { |
| 359 | path := filepath.Join(dir, journalFile) |
| 360 | data, err := os.ReadFile(path) |
| 361 | switch { |
| 362 | case errors.Is(err, fs.ErrNotExist): |
| 363 | return nil, nil |
| 364 | case err != nil: |
| 365 | return nil, fmt.Errorf("reading the journal %s: %w", path, err) |
| 366 | } |
| 367 | var j Journal |
| 368 | if err := strictly(data, &j); err != nil { |
| 369 | return nil, fmt.Errorf("the journal %s does not read, so nothing it names is decided: %w", path, err) |
| 370 | } |
| 371 | if err := j.check(b); err != nil { |
| 372 | return nil, fmt.Errorf("the journal %s is refused, so nothing it names is decided: %w", path, err) |
| 373 | } |
| 374 | return &j, nil |
| 375 | } |
| 376 | |
| 377 | // strictly reads data into v, and takes only what json.Marshal writes of |
| 378 | // v, as rebase's kept forms are read: space between tokens is all that may |
| 379 | // differ. |
| 380 | func strictly(data []byte, v any) error { |
| 381 | dec := json.NewDecoder(bytes.NewReader(data)) |
| 382 | dec.DisallowUnknownFields() |
| 383 | if err := dec.Decode(v); err != nil { |
| 384 | return err |
| 385 | } |
| 386 | var compact bytes.Buffer |
| 387 | if err := json.Compact(&compact, data); err != nil { |
| 388 | return err |
| 389 | } |
| 390 | again, err := json.Marshal(v) |
| 391 | if err != nil { |
| 392 | return err |
| 393 | } |
| 394 | if !bytes.Equal(compact.Bytes(), again) { |
| 395 | return errors.New("it is not in the form it is kept in: a field is missing or named twice, or a value is written another way") |
| 396 | } |
| 397 | return nil |
| 398 | } |
| 399 | |
| 400 | // retained is every object the journal's writes would push, each by the |
| 401 | // ref the scratch repository keeps it under: each prepared head, each |
| 402 | // record commit, each report commit and each replacement's. |
| 403 | func (j *Journal) retained() map[string]string { |
| 404 | refs := map[string]string{} |
| 405 | for _, f := range j.Families { |
| 406 | var oids []string |
| 407 | if f.Branches != nil { |
| 408 | for _, u := range f.Branches.Updates { |
| 409 | oids = append(oids, u.New) |
| 410 | } |
| 411 | } |
| 412 | for _, v := range f.Versions { |
| 413 | oids = append(oids, v.Commit) |
| 414 | } |
| 415 | for _, r := range append(append([]JournalReport{}, f.Reports...), f.Replacements...) { |
| 416 | oids = append(oids, r.Pending.Commit) |
| 417 | } |
| 418 | for _, oid := range oids { |
| 419 | refs[retainPrefix+f.Operation+"/"+oid] = oid |
| 420 | } |
| 421 | } |
| 422 | return refs |
| 423 | } |
| 424 | |
| 425 | // keep makes the journal durable before any of its writes is pushed: it |
| 426 | // keeps every object the writes would push reachable in the scratch |
| 427 | // repository, under refs/valley-restack/<operation>/<object>, and then |
| 428 | // writes the journal to the state directory, synced, in place of any |
| 429 | // before it. Only then does it let go of each object the journal no |
| 430 | // longer names. A journal that would not read back as written is refused |
| 431 | // before anything is kept, since a later pass would refuse it in turn. |
| 432 | func keep(ctx context.Context, g rebase.Git, dir string, j *Journal) error { |
| 433 | if err := j.check(binding{Repository: j.Repository, Target: j.Target, Principal: j.Principal}); err != nil { |
| 434 | return fmt.Errorf("the journal cannot be kept: %w", err) |
| 435 | } |
| 436 | data, err := json.MarshalIndent(j, "", " ") |
| 437 | if err != nil { |
| 438 | return err |
| 439 | } |
| 440 | if err := strictly(data, &Journal{}); err != nil { |
| 441 | return fmt.Errorf("the journal cannot be kept, since it would not read back as written: %w", err) |
| 442 | } |
| 443 | refs := j.retained() |
| 444 | var names []string |
| 445 | for ref := range refs { |
| 446 | names = append(names, ref) |
| 447 | } |
| 448 | sort.Strings(names) |
| 449 | var stdin strings.Builder |
| 450 | for _, ref := range names { |
| 451 | fmt.Fprintf(&stdin, "update %s %s\n", ref, refs[ref]) |
| 452 | } |
| 453 | if err := updateRefs(ctx, g, stdin.String()); err != nil { |
| 454 | return fmt.Errorf("could not keep the objects of the journal: %w", err) |
| 455 | } |
| 456 | if err := writeDurably(dir, journalFile, append(data, '\n')); err != nil { |
| 457 | return err |
| 458 | } |
| 459 | return letGo(ctx, g, refs) |
| 460 | } |
| 461 | |
| 462 | // letGo lets go of every object the scratch repository keeps for the |
| 463 | // journal, but those kept names: nil lets go of them all. |
| 464 | func letGo(ctx context.Context, g rebase.Git, kept map[string]string) error { |
| 465 | out, err := gitOut(ctx, g, "for-each-ref", "--format=%(refname)", retainPrefix) |
| 466 | if err != nil { |
| 467 | return err |
| 468 | } |
| 469 | var stdin strings.Builder |
| 470 | for _, ref := range strings.Fields(out) { |
| 471 | if _, ok := kept[ref]; !ok { |
| 472 | fmt.Fprintf(&stdin, "delete %s\n", ref) |
| 473 | } |
| 474 | } |
| 475 | if err := updateRefs(ctx, g, stdin.String()); err != nil { |
| 476 | return fmt.Errorf("could not let go of the objects the journal no longer names: %w", err) |
| 477 | } |
| 478 | return nil |
| 479 | } |
| 480 | |
| 481 | // updateRefs runs git update-ref --stdin with the instructions given, all |
| 482 | // in one transaction. |
| 483 | func updateRefs(ctx context.Context, g rebase.Git, instructions string) error { |
| 484 | if instructions == "" { |
| 485 | return nil |
| 486 | } |
| 487 | cmd := g.Command(ctx, "update-ref", "--stdin") |
| 488 | cmd.Stdin = strings.NewReader(instructions) |
| 489 | if out, err := cmd.CombinedOutput(); err != nil { |
| 490 | return fmt.Errorf("%v: %s", err, strings.TrimSpace(string(out))) |
| 491 | } |
| 492 | return nil |
| 493 | } |
| 494 | |
| 495 | // forget removes the journal from the state directory, durably, and then |
| 496 | // lets go of every object kept for it. |
| 497 | func forget(ctx context.Context, g rebase.Git, dir string) error { |
| 498 | if err := os.Remove(filepath.Join(dir, journalFile)); err != nil && !errors.Is(err, fs.ErrNotExist) { |
| 499 | return err |
| 500 | } |
| 501 | d, err := os.Open(dir) |
| 502 | if err != nil { |
| 503 | return err |
| 504 | } |
| 505 | err = d.Sync() |
| 506 | d.Close() |
| 507 | if err != nil { |
| 508 | return err |
| 509 | } |
| 510 | return letGo(ctx, g, nil) |
| 511 | } |
| 512 | |
| 513 | // writeDurably writes a file in dir through a synced temporary file, and |
| 514 | // renames it into place, so a crash leaves the old file or the new one, |
| 515 | // whole. The directory is synced after, so the rename is durable too. |
| 516 | func writeDurably(dir, name string, data []byte) error { |
| 517 | tmp, err := os.CreateTemp(dir, name+".*") |
| 518 | if err != nil { |
| 519 | return err |
| 520 | } |
| 521 | defer os.Remove(tmp.Name()) |
| 522 | _, err = tmp.Write(data) |
| 523 | if serr := tmp.Sync(); err == nil { |
| 524 | err = serr |
| 525 | } |
| 526 | if cerr := tmp.Close(); err == nil { |
| 527 | err = cerr |
| 528 | } |
| 529 | if err != nil { |
| 530 | return fmt.Errorf("writing %s in %s: %w", name, dir, err) |
| 531 | } |
| 532 | if err := os.Rename(tmp.Name(), filepath.Join(dir, name)); err != nil { |
| 533 | return err |
| 534 | } |
| 535 | d, err := os.Open(dir) |
| 536 | if err != nil { |
| 537 | return err |
| 538 | } |
| 539 | defer d.Close() |
| 540 | return d.Sync() |
| 541 | } |