gunk-dev/the-valley

journal.go

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