This repository has been archived by the owner on Feb 12, 2019. It is now read-only.
/
ops.go
1589 lines (1406 loc) · 42.7 KB
/
ops.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"context"
"fmt"
"reflect"
"strings"
"time"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/go-codec/codec"
"github.com/keybase/kbfs/kbfscodec"
"github.com/keybase/kbfs/kbfscrypto"
"github.com/keybase/kbfs/kbfsedits"
"github.com/keybase/kbfs/kbfsmd"
"github.com/keybase/kbfs/tlf"
"github.com/pkg/errors"
)
// op represents a single file-system remote-sync operation
type op interface {
AddRefBlock(ptr BlockPointer)
DelRefBlock(ptr BlockPointer)
AddUnrefBlock(ptr BlockPointer)
DelUnrefBlock(ptr BlockPointer)
AddUpdate(oldPtr BlockPointer, newPtr BlockPointer)
SizeExceptUpdates() uint64
allUpdates() []blockUpdate
Refs() []BlockPointer
Unrefs() []BlockPointer
String() string
StringWithRefs(indent string) string
setWriterInfo(writerInfo)
getWriterInfo() writerInfo
setFinalPath(p path)
getFinalPath() path
setLocalTimestamp(t time.Time)
getLocalTimestamp() time.Time
checkValid() error
deepCopy() op
// checkConflict compares the function's target op with the given
// op, and returns a resolution if one is needed (or nil
// otherwise). The resulting action (if any) assumes that this
// method's target op is the unmerged op, and the given op is the
// merged op.
checkConflict(ctx context.Context,
renamer ConflictRenamer, mergedOp op, isFile bool) (
crAction, error)
// getDefaultAction should be called on an unmerged op only after
// all conflicts with the corresponding change have been checked,
// and it returns the action to take against the merged branch
// given that there are no conflicts.
getDefaultAction(mergedPath path) crAction
// AddSelfUpdate adds an update from the given pointer to itself.
// This should be used when the caller doesn't yet know what the
// new block ID will be, but wants to "complete" the update as a
// signal to a future prepping process that the block needs to be
// processed/readied, at which point the real new pointer will be
// filled in.
AddSelfUpdate(ptr BlockPointer)
// ToEditNotification returns an edit notification if this op
// needs one, otherwise it returns nil.
ToEditNotification(
rev kbfsmd.Revision, revTime time.Time, device kbfscrypto.VerifyingKey,
uid keybase1.UID, tlfID tlf.ID) *kbfsedits.NotificationMessage
}
// op codes
const (
createOpCode kbfscodec.ExtCode = iota + kbfscodec.ExtCodeOpsRangeStart
rmOpCode
renameOpCode
syncOpCode
setAttrOpCode
resolutionOpCode
rekeyOpCode
gcOpCode // for deleting old blocks during an MD history truncation
)
// blockUpdate represents a block that was updated to have a new
// BlockPointer.
//
// NOTE: Don't add or modify anything in this struct without
// considering how old clients will handle them.
type blockUpdate struct {
// TODO: Ideally, we'd omit Unref or Ref if they're
// empty. However, we'd first have to verify that there's
// nothing that relies on either one of these fields to always
// be filled (e.g., see similar comments for the Info field on
// BlockChanges.)
Unref BlockPointer `codec:"u"`
Ref BlockPointer `codec:"r"`
}
func makeBlockUpdate(unref, ref BlockPointer) (blockUpdate, error) {
bu := blockUpdate{}
err := bu.setUnref(unref)
if err != nil {
return blockUpdate{}, err
}
err = bu.setRef(ref)
if err != nil {
return blockUpdate{}, err
}
return bu, nil
}
func (u blockUpdate) checkValid() error {
if u.Unref == (BlockPointer{}) {
return errors.New("nil unref")
}
if u.Ref == (BlockPointer{}) {
return errors.New("nil ref")
}
return nil
}
func (u *blockUpdate) setUnref(ptr BlockPointer) error {
if ptr == (BlockPointer{}) {
return errors.Errorf("setUnref called with nil ptr")
}
u.Unref = ptr
return nil
}
func (u *blockUpdate) setRef(ptr BlockPointer) error {
if ptr == (BlockPointer{}) {
return errors.Errorf("setRef called with nil ptr")
}
u.Ref = ptr
return nil
}
// list codes
const (
opsListCode kbfscodec.ExtCode = iota + kbfscodec.ExtCodeListRangeStart
)
type opsList []op
// OpCommon are data structures needed by all ops. It is only
// exported for serialization purposes.
type OpCommon struct {
RefBlocks []BlockPointer `codec:"r,omitempty"`
UnrefBlocks []BlockPointer `codec:"u,omitempty"`
Updates []blockUpdate `codec:"o,omitempty"`
codec.UnknownFieldSetHandler
// writerInfo is the keybase username and device that generated this
// operation.
// Not exported; only used during conflict resolution.
writerInfo writerInfo
// finalPath is the final resolved path to the node that this
// operation affects in a set of MD updates. Not exported; only
// used locally.
finalPath path
// localTimestamp should be set to the localTimestamp of the
// corresponding ImmutableRootMetadata when ops need individual
// timestamps. Not exported; only used locally.
localTimestamp time.Time
}
func (oc OpCommon) deepCopy() OpCommon {
ocCopy := OpCommon{}
ocCopy.RefBlocks = make([]BlockPointer, len(oc.RefBlocks))
copy(ocCopy.RefBlocks, oc.RefBlocks)
ocCopy.UnrefBlocks = make([]BlockPointer, len(oc.UnrefBlocks))
copy(ocCopy.UnrefBlocks, oc.UnrefBlocks)
ocCopy.Updates = make([]blockUpdate, len(oc.Updates))
copy(ocCopy.Updates, oc.Updates)
// TODO: if we ever need to copy the unknown fields in this
// method, we'll have to change the codec interface to make it
// possible.
ocCopy.writerInfo = oc.writerInfo
ocCopy.finalPath = oc.finalPath
ocCopy.finalPath.path = make([]pathNode, len(oc.finalPath.path))
copy(ocCopy.finalPath.path, oc.finalPath.path)
ocCopy.localTimestamp = oc.localTimestamp
return ocCopy
}
// AddRefBlock adds this block to the list of newly-referenced blocks
// for this op.
func (oc *OpCommon) AddRefBlock(ptr BlockPointer) {
oc.RefBlocks = append(oc.RefBlocks, ptr)
}
// DelRefBlock removes the first reference of the given block from the
// list of newly-referenced blocks for this op.
func (oc *OpCommon) DelRefBlock(ptr BlockPointer) {
for i, ref := range oc.RefBlocks {
if ptr == ref {
oc.RefBlocks = append(oc.RefBlocks[:i], oc.RefBlocks[i+1:]...)
break
}
}
}
// AddUnrefBlock adds this block to the list of newly-unreferenced blocks
// for this op.
func (oc *OpCommon) AddUnrefBlock(ptr BlockPointer) {
oc.UnrefBlocks = append(oc.UnrefBlocks, ptr)
}
// DelUnrefBlock removes the first unreference of the given block from
// the list of unreferenced blocks for this op.
func (oc *OpCommon) DelUnrefBlock(ptr BlockPointer) {
for i, unref := range oc.UnrefBlocks {
if ptr == unref {
oc.UnrefBlocks = append(oc.UnrefBlocks[:i], oc.UnrefBlocks[i+1:]...)
break
}
}
}
// AddUpdate adds a mapping from an old block to the new version of
// that block, for this op.
func (oc *OpCommon) AddUpdate(oldPtr BlockPointer, newPtr BlockPointer) {
// Either pointer may be zero, if we're building an op that
// will be fixed up later.
bu := blockUpdate{oldPtr, newPtr}
oc.Updates = append(oc.Updates, bu)
}
// AddSelfUpdate implements the op interface for OpCommon -- see the
// comment in op.
func (oc *OpCommon) AddSelfUpdate(ptr BlockPointer) {
oc.AddUpdate(ptr, ptr)
}
// Refs returns a slice containing all the blocks that were initially
// referenced during this op.
func (oc *OpCommon) Refs() []BlockPointer {
return oc.RefBlocks
}
// Unrefs returns a slice containing all the blocks that were
// unreferenced during this op.
func (oc *OpCommon) Unrefs() []BlockPointer {
return oc.UnrefBlocks
}
func (oc *OpCommon) setWriterInfo(info writerInfo) {
oc.writerInfo = info
}
func (oc *OpCommon) getWriterInfo() writerInfo {
return oc.writerInfo
}
func (oc *OpCommon) setFinalPath(p path) {
oc.finalPath = p
}
func (oc *OpCommon) getFinalPath() path {
return oc.finalPath
}
func (oc *OpCommon) setLocalTimestamp(t time.Time) {
oc.localTimestamp = t
}
func (oc *OpCommon) getLocalTimestamp() time.Time {
return oc.localTimestamp
}
func (oc *OpCommon) checkUpdatesValid() error {
for i, update := range oc.Updates {
err := update.checkValid()
if err != nil {
return errors.Errorf(
"update[%d]=%v got error: %v", i, update, err)
}
}
return nil
}
func (oc *OpCommon) stringWithRefs(indent string) string {
res := ""
for i, update := range oc.Updates {
res += indent + fmt.Sprintf(
"Update[%d]: %v -> %v\n", i, update.Unref, update.Ref)
}
for i, ref := range oc.RefBlocks {
res += indent + fmt.Sprintf("Ref[%d]: %v\n", i, ref)
}
for i, unref := range oc.UnrefBlocks {
res += indent + fmt.Sprintf("Unref[%d]: %v\n", i, unref)
}
return res
}
// ToEditNotification implements the op interface for OpCommon.
func (oc *OpCommon) ToEditNotification(
_ kbfsmd.Revision, _ time.Time, _ kbfscrypto.VerifyingKey,
_ keybase1.UID, _ tlf.ID) *kbfsedits.NotificationMessage {
// Ops embedding this that can be converted should override this.
return nil
}
// createOp is an op representing a file or subdirectory creation
type createOp struct {
OpCommon
NewName string `codec:"n"`
Dir blockUpdate `codec:"d"`
Type EntryType `codec:"t"`
// If true, this create op represents half of a rename operation.
// This op should never be persisted.
renamed bool
// If true, during conflict resolution the blocks of the file will
// be copied.
forceCopy bool
// If this is set, ths create op needs to be turned has been
// turned into a symlink creation locally to avoid a cycle during
// conflict resolution, and the following field represents the
// text of the symlink. This op should never be persisted.
crSymPath string
}
func newCreateOp(name string, oldDir BlockPointer, t EntryType) (*createOp, error) {
co := &createOp{
NewName: name,
}
err := co.Dir.setUnref(oldDir)
if err != nil {
return nil, err
}
co.Type = t
return co, nil
}
func (co *createOp) deepCopy() op {
coCopy := *co
coCopy.OpCommon = co.OpCommon.deepCopy()
return &coCopy
}
func newCreateOpForRootDir() *createOp {
return &createOp{
Type: Dir,
}
}
func (co *createOp) AddUpdate(oldPtr BlockPointer, newPtr BlockPointer) {
if co.Dir == (blockUpdate{}) {
panic("AddUpdate called on create op with empty Dir " +
"(probably create op for root dir)")
}
if oldPtr == co.Dir.Unref {
err := co.Dir.setRef(newPtr)
if err != nil {
panic(err)
}
return
}
co.OpCommon.AddUpdate(oldPtr, newPtr)
}
// AddSelfUpdate implements the op interface for createOp -- see the
// comment in op.
func (co *createOp) AddSelfUpdate(ptr BlockPointer) {
co.AddUpdate(ptr, ptr)
}
func (co *createOp) SizeExceptUpdates() uint64 {
return uint64(len(co.NewName))
}
func (co *createOp) allUpdates() []blockUpdate {
updates := make([]blockUpdate, len(co.Updates))
copy(updates, co.Updates)
return append(updates, co.Dir)
}
func (co *createOp) checkValid() error {
if co.NewName == "" {
// Must be for root dir.
return nil
}
err := co.Dir.checkValid()
if err != nil {
return errors.Errorf("createOp.Dir=%v got error: %v", co.Dir, err)
}
return co.checkUpdatesValid()
}
func (co *createOp) String() string {
res := fmt.Sprintf("create %s (%s)", co.NewName, co.Type)
if co.renamed {
res += " (renamed)"
}
return res
}
func (co *createOp) StringWithRefs(indent string) string {
res := co.String() + "\n"
res += indent + fmt.Sprintf("Dir: %v -> %v\n", co.Dir.Unref, co.Dir.Ref)
res += co.stringWithRefs(indent)
return res
}
func (co *createOp) checkConflict(
ctx context.Context, renamer ConflictRenamer, mergedOp op,
isFile bool) (crAction, error) {
switch realMergedOp := mergedOp.(type) {
case *createOp:
// Conflicts if this creates the same name and one of them
// isn't creating a directory.
sameName := (realMergedOp.NewName == co.NewName)
if sameName && (realMergedOp.Type != Dir || co.Type != Dir) {
if realMergedOp.Type != Dir &&
(co.Type == Dir || co.crSymPath != "") {
// Rename the merged entry only if the unmerged one is
// a directory (or to-be-sympath'd directory) and the
// merged one is not.
toName, err := renamer.ConflictRename(
ctx, mergedOp, co.NewName)
if err != nil {
return nil, err
}
return &renameMergedAction{
fromName: co.NewName,
toName: toName,
symPath: co.crSymPath,
}, nil
}
// Otherwise rename the unmerged entry (guaranteed to be a file).
toName, err := renamer.ConflictRename(
ctx, co, co.NewName)
if err != nil {
return nil, err
}
return &renameUnmergedAction{
fromName: co.NewName,
toName: toName,
symPath: co.crSymPath,
}, nil
}
// If they are both directories, and one of them is a rename,
// then we have a conflict and need to rename the renamed one.
//
// TODO: Implement a better merging strategy for when an
// existing directory gets into a rename conflict with another
// existing or new directory.
if sameName && realMergedOp.Type == Dir && co.Type == Dir &&
(realMergedOp.renamed || co.renamed) {
// Always rename the unmerged one
toName, err := renamer.ConflictRename(
ctx, co, co.NewName)
if err != nil {
return nil, err
}
return ©UnmergedEntryAction{
fromName: co.NewName,
toName: toName,
symPath: co.crSymPath,
unique: true,
}, nil
}
}
// Doesn't conflict with any rmOps, because the default action
// will just re-create it in the merged branch as necessary.
return nil, nil
}
func (co *createOp) getDefaultAction(mergedPath path) crAction {
if co.forceCopy {
return &renameUnmergedAction{
fromName: co.NewName,
toName: co.NewName,
symPath: co.crSymPath,
}
}
return ©UnmergedEntryAction{
fromName: co.NewName,
toName: co.NewName,
symPath: co.crSymPath,
}
}
func makeBaseEditNotification(
rev kbfsmd.Revision, revTime time.Time, device kbfscrypto.VerifyingKey,
uid keybase1.UID, tlfID tlf.ID,
et EntryType) kbfsedits.NotificationMessage {
var t kbfsedits.EntryType
switch et {
case File, Exec:
t = kbfsedits.EntryTypeFile
case Dir:
t = kbfsedits.EntryTypeDir
case Sym:
t = kbfsedits.EntryTypeSym
}
return kbfsedits.NotificationMessage{
Version: kbfsedits.NotificationV2,
FileType: t,
Time: revTime,
Revision: rev,
Device: device,
UID: uid,
FolderID: tlfID,
}
}
func (co *createOp) ToEditNotification(
rev kbfsmd.Revision, revTime time.Time, device kbfscrypto.VerifyingKey,
uid keybase1.UID, tlfID tlf.ID) *kbfsedits.NotificationMessage {
n := makeBaseEditNotification(rev, revTime, device, uid, tlfID, co.Type)
n.Filename = co.getFinalPath().ChildPathNoPtr(co.NewName).
CanonicalPathString()
n.Type = kbfsedits.NotificationCreate
return &n
}
// rmOp is an op representing a file or subdirectory removal
type rmOp struct {
OpCommon
OldName string `codec:"n"`
Dir blockUpdate `codec:"d"`
RemovedType EntryType `codec:"rt"`
// Indicates that the resolution process should skip this rm op.
// Likely indicates the rm half of a cycle-creating rename.
dropThis bool
}
func newRmOp(name string, oldDir BlockPointer, removedType EntryType) (
*rmOp, error) {
ro := &rmOp{
OldName: name,
RemovedType: removedType,
}
err := ro.Dir.setUnref(oldDir)
if err != nil {
return nil, err
}
return ro, nil
}
func (ro *rmOp) deepCopy() op {
roCopy := *ro
roCopy.OpCommon = ro.OpCommon.deepCopy()
return &roCopy
}
func (ro *rmOp) AddUpdate(oldPtr BlockPointer, newPtr BlockPointer) {
if oldPtr == ro.Dir.Unref {
err := ro.Dir.setRef(newPtr)
if err != nil {
panic(err)
}
return
}
ro.OpCommon.AddUpdate(oldPtr, newPtr)
}
// AddSelfUpdate implements the op interface for rmOp -- see the
// comment in op.
func (ro *rmOp) AddSelfUpdate(ptr BlockPointer) {
ro.AddUpdate(ptr, ptr)
}
func (ro *rmOp) SizeExceptUpdates() uint64 {
return uint64(len(ro.OldName))
}
func (ro *rmOp) allUpdates() []blockUpdate {
updates := make([]blockUpdate, len(ro.Updates))
copy(updates, ro.Updates)
return append(updates, ro.Dir)
}
func (ro *rmOp) checkValid() error {
err := ro.Dir.checkValid()
if err != nil {
return errors.Errorf("rmOp.Dir=%v got error: %v", ro.Dir, err)
}
return ro.checkUpdatesValid()
}
func (ro *rmOp) String() string {
return fmt.Sprintf("rm %s", ro.OldName)
}
func (ro *rmOp) StringWithRefs(indent string) string {
res := ro.String() + "\n"
res += indent + fmt.Sprintf("Dir: %v -> %v\n", ro.Dir.Unref, ro.Dir.Ref)
res += ro.stringWithRefs(indent)
return res
}
func (ro *rmOp) checkConflict(
ctx context.Context, renamer ConflictRenamer, mergedOp op,
isFile bool) (crAction, error) {
switch realMergedOp := mergedOp.(type) {
case *createOp:
if realMergedOp.NewName == ro.OldName {
// Conflicts if this creates the same name. This can only
// happen if the merged branch deleted the old node and
// re-created it, in which case it is totally fine to drop
// this rm op for the original node.
return &dropUnmergedAction{op: ro}, nil
}
case *rmOp:
if realMergedOp.OldName == ro.OldName {
// Both removed the same file.
return &dropUnmergedAction{op: ro}, nil
}
}
return nil, nil
}
func (ro *rmOp) getDefaultAction(mergedPath path) crAction {
if ro.dropThis {
return &dropUnmergedAction{op: ro}
}
return &rmMergedEntryAction{name: ro.OldName}
}
func (ro *rmOp) ToEditNotification(
rev kbfsmd.Revision, revTime time.Time, device kbfscrypto.VerifyingKey,
uid keybase1.UID, tlfID tlf.ID) *kbfsedits.NotificationMessage {
n := makeBaseEditNotification(
rev, revTime, device, uid, tlfID, ro.RemovedType)
n.Filename = ro.getFinalPath().ChildPathNoPtr(ro.OldName).
CanonicalPathString()
n.Type = kbfsedits.NotificationDelete
return &n
}
// renameOp is an op representing a rename of a file/subdirectory from
// one directory to another. If this is a rename within the same
// directory, NewDir will be equivalent to blockUpdate{}. renameOp
// records the moved pointer, even though it doesn't change as part of
// the operation, to make it possible to track the full path of
// directories for the purposes of conflict resolution.
type renameOp struct {
OpCommon
OldName string `codec:"on"`
OldDir blockUpdate `codec:"od"`
NewName string `codec:"nn"`
NewDir blockUpdate `codec:"nd"`
Renamed BlockPointer `codec:"re"`
RenamedType EntryType `codec:"rt"`
// oldFinalPath is the final resolved path to the old directory
// containing the renamed node. Not exported; only used locally.
oldFinalPath path
}
func newRenameOp(oldName string, oldOldDir BlockPointer,
newName string, oldNewDir BlockPointer, renamed BlockPointer,
renamedType EntryType) (*renameOp, error) {
ro := &renameOp{
OldName: oldName,
NewName: newName,
Renamed: renamed,
RenamedType: renamedType,
}
err := ro.OldDir.setUnref(oldOldDir)
if err != nil {
return nil, err
}
// If we are renaming within a directory, let the NewDir remain empty.
if oldOldDir != oldNewDir {
err := ro.NewDir.setUnref(oldNewDir)
if err != nil {
return nil, err
}
}
return ro, nil
}
func (ro *renameOp) deepCopy() op {
roCopy := *ro
roCopy.OpCommon = ro.OpCommon.deepCopy()
return &roCopy
}
func (ro *renameOp) AddUpdate(oldPtr BlockPointer, newPtr BlockPointer) {
if oldPtr == ro.OldDir.Unref {
err := ro.OldDir.setRef(newPtr)
if err != nil {
panic(err)
}
return
}
if ro.NewDir != (blockUpdate{}) && oldPtr == ro.NewDir.Unref {
err := ro.NewDir.setRef(newPtr)
if err != nil {
panic(err)
}
return
}
ro.OpCommon.AddUpdate(oldPtr, newPtr)
}
// AddSelfUpdate implements the op interface for renameOp -- see the
// comment in op.
func (ro *renameOp) AddSelfUpdate(ptr BlockPointer) {
ro.AddUpdate(ptr, ptr)
}
func (ro *renameOp) SizeExceptUpdates() uint64 {
return uint64(len(ro.NewName) + len(ro.NewName))
}
func (ro *renameOp) allUpdates() []blockUpdate {
updates := make([]blockUpdate, len(ro.Updates))
copy(updates, ro.Updates)
if ro.NewDir != (blockUpdate{}) {
return append(updates, ro.NewDir, ro.OldDir)
}
return append(updates, ro.OldDir)
}
func (ro *renameOp) checkValid() error {
err := ro.OldDir.checkValid()
if err != nil {
return errors.Errorf("renameOp.OldDir=%v got error: %v",
ro.OldDir, err)
}
if ro.NewDir != (blockUpdate{}) {
err = ro.NewDir.checkValid()
if err != nil {
return errors.Errorf("renameOp.NewDir=%v got error: %v",
ro.NewDir, err)
}
}
return ro.checkUpdatesValid()
}
func (ro *renameOp) String() string {
return fmt.Sprintf("rename %s -> %s (%s)",
ro.OldName, ro.NewName, ro.RenamedType)
}
func (ro *renameOp) StringWithRefs(indent string) string {
res := ro.String() + "\n"
res += indent + fmt.Sprintf("OldDir: %v -> %v\n",
ro.OldDir.Unref, ro.OldDir.Ref)
if ro.NewDir != (blockUpdate{}) {
res += indent + fmt.Sprintf("NewDir: %v -> %v\n",
ro.NewDir.Unref, ro.NewDir.Ref)
} else {
res += indent + fmt.Sprintf("NewDir: same as above\n")
}
res += indent + fmt.Sprintf("Renamed: %v\n", ro.Renamed)
res += ro.stringWithRefs(indent)
return res
}
func (ro *renameOp) checkConflict(
ctx context.Context, renamer ConflictRenamer, mergedOp op,
isFile bool) (crAction, error) {
return nil, errors.Errorf("Unexpected conflict check on a rename op: %s", ro)
}
func (ro *renameOp) getDefaultAction(mergedPath path) crAction {
return nil
}
func (ro *renameOp) ToEditNotification(
rev kbfsmd.Revision, revTime time.Time, device kbfscrypto.VerifyingKey,
uid keybase1.UID, tlfID tlf.ID) *kbfsedits.NotificationMessage {
n := makeBaseEditNotification(
rev, revTime, device, uid, tlfID, ro.RenamedType)
n.Filename = ro.getFinalPath().ChildPathNoPtr(ro.NewName).
CanonicalPathString()
n.Type = kbfsedits.NotificationRename
n.Params = &kbfsedits.NotificationParams{
OldFilename: ro.oldFinalPath.ChildPathNoPtr(ro.OldName).
CanonicalPathString(),
}
return &n
}
// WriteRange represents a file modification. Len is 0 for a
// truncate.
type WriteRange struct {
Off uint64 `codec:"o"`
Len uint64 `codec:"l,omitempty"` // 0 for truncates
codec.UnknownFieldSetHandler
}
func (w WriteRange) isTruncate() bool {
return w.Len == 0
}
// End returns the index of the largest byte not affected by this
// write. It only makes sense to call this for non-truncates.
func (w WriteRange) End() uint64 {
if w.isTruncate() {
panic("Truncates don't have an end")
}
return w.Off + w.Len
}
// Affects returns true if the regions affected by this write
// operation and `other` overlap in some way. Specifically, it
// returns true if:
//
// - both operations are writes and their write ranges overlap;
// - one operation is a write and one is a truncate, and the truncate is
// within the write's range or before it; or
// - both operations are truncates.
func (w WriteRange) Affects(other WriteRange) bool {
if w.isTruncate() {
if other.isTruncate() {
return true
}
// A truncate affects a write if it lands inside or before the
// write.
return other.End() > w.Off
} else if other.isTruncate() {
return w.End() > other.Off
}
// Both are writes -- do their ranges overlap?
return (w.Off <= other.End() && other.End() <= w.End()) ||
(other.Off <= w.End() && w.End() <= other.End())
}
// syncOp is an op that represents a series of writes to a file.
type syncOp struct {
OpCommon
File blockUpdate `codec:"f"`
Writes []WriteRange `codec:"w"`
// If true, this says that if there is a conflict involving this
// op, we should keep the unmerged name rather than construct a
// conflict name (probably because the new name already
// diverges from the name in the other branch).
keepUnmergedTailName bool
}
func newSyncOp(oldFile BlockPointer) (*syncOp, error) {
so := &syncOp{}
err := so.File.setUnref(oldFile)
if err != nil {
return nil, err
}
so.resetUpdateState()
return so, nil
}
func (so *syncOp) deepCopy() op {
soCopy := *so
soCopy.OpCommon = so.OpCommon.deepCopy()
soCopy.Writes = make([]WriteRange, len(so.Writes))
copy(soCopy.Writes, so.Writes)
return &soCopy
}
func (so *syncOp) resetUpdateState() {
so.Updates = nil
}
func (so *syncOp) AddUpdate(oldPtr BlockPointer, newPtr BlockPointer) {
if oldPtr == so.File.Unref {
err := so.File.setRef(newPtr)
if err != nil {
panic(err)
}
return
}
so.OpCommon.AddUpdate(oldPtr, newPtr)
}
// AddSelfUpdate implements the op interface for syncOp -- see the
// comment in op.
func (so *syncOp) AddSelfUpdate(ptr BlockPointer) {
so.AddUpdate(ptr, ptr)
}
func (so *syncOp) addWrite(off uint64, length uint64) WriteRange {
latestWrite := WriteRange{Off: off, Len: length}
so.Writes = append(so.Writes, latestWrite)
return latestWrite
}
func (so *syncOp) addTruncate(off uint64) WriteRange {
latestWrite := WriteRange{Off: off, Len: 0}
so.Writes = append(so.Writes, latestWrite)
return latestWrite
}
func (so *syncOp) SizeExceptUpdates() uint64 {
return uint64(len(so.Writes) * 16)
}
func (so *syncOp) allUpdates() []blockUpdate {
updates := make([]blockUpdate, len(so.Updates))
copy(updates, so.Updates)
return append(updates, so.File)
}
func (so *syncOp) checkValid() error {
err := so.File.checkValid()
if err != nil {
return errors.Errorf("syncOp.File=%v got error: %v", so.File, err)
}
return so.checkUpdatesValid()
}
func (so *syncOp) String() string {
var writes []string
for _, r := range so.Writes {
writes = append(writes, fmt.Sprintf("{off=%d, len=%d}", r.Off, r.Len))
}
return fmt.Sprintf("sync [%s]", strings.Join(writes, ", "))
}
func (so *syncOp) StringWithRefs(indent string) string {
res := so.String() + "\n"
res += indent + fmt.Sprintf("File: %v -> %v\n", so.File.Unref, so.File.Ref)
res += so.stringWithRefs(indent)
return res
}
func (so *syncOp) checkConflict(
ctx context.Context, renamer ConflictRenamer, mergedOp op,
isFile bool) (crAction, error) {
switch mergedOp.(type) {
case *syncOp:
// Any sync on the same file is a conflict. (TODO: add
// type-specific intelligent conflict resolvers for file
// contents?)
toName, err := renamer.ConflictRename(
ctx, so, mergedOp.getFinalPath().tailName())
if err != nil {
return nil, err
}
if so.keepUnmergedTailName {
toName = so.getFinalPath().tailName()
}
return &renameUnmergedAction{
fromName: so.getFinalPath().tailName(),
toName: toName,
unmergedParentMostRecent: so.getFinalPath().parentPath().tailPointer(),
mergedParentMostRecent: mergedOp.getFinalPath().parentPath().
tailPointer(),
}, nil
case *setAttrOp:
// Someone on the merged path explicitly set an attribute, so
// just copy the size and blockpointer over.
return ©UnmergedAttrAction{
fromName: so.getFinalPath().tailName(),
toName: mergedOp.getFinalPath().tailName(),
attr: []attrChange{sizeAttr},
}, nil
}
return nil, nil
}
func (so *syncOp) getDefaultAction(mergedPath path) crAction {
return ©UnmergedEntryAction{
fromName: so.getFinalPath().tailName(),
toName: mergedPath.tailName(),
symPath: "",
}
}
func (so *syncOp) ToEditNotification(
rev kbfsmd.Revision, revTime time.Time, device kbfscrypto.VerifyingKey,
uid keybase1.UID, tlfID tlf.ID) *kbfsedits.NotificationMessage {
n := makeBaseEditNotification(rev, revTime, device, uid, tlfID, File)
n.Filename = so.getFinalPath().CanonicalPathString()
n.Type = kbfsedits.NotificationModify
var mods []kbfsedits.ModifyRange
for _, w := range so.Writes {
mods = append(mods, kbfsedits.ModifyRange{
Offset: w.Off,
Length: w.Len,
})
}
n.Params = &kbfsedits.NotificationParams{
Modifies: mods,
}
return &n
}