gunk-dev/the-valley

journal.go

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