Repository navigation
Expand file tree
/
Copy pathorphans_test.go
More file actions
1013 lines (859 loc) · 36.3 KB
/
Copy pathorphans_test.go
File metadata and controls
1013 lines (859 loc) · 36.3 KB
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
package mark
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"github.com/kovetskiy/mark/v17/confluence"
"github.com/kovetskiy/mark/v17/confluence/confluencetest"
"github.com/kovetskiy/mark/v17/manifest"
"github.com/kovetskiy/mark/v17/report"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// orphanFixture publishes two documents under Parent and then removes one of
// them from disk, which is what makes its page an orphan.
func orphanFixture(t *testing.T, onOrphan report.OnOrphan, under string) (*confluencetest.Server, string, string) {
t.Helper()
server := confluencetest.New(t)
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
server.AddPage("DOCS", "Parent", "page", home.ID)
dir := t.TempDir()
header := "<!-- Space: DOCS -->\n<!-- Parent: Parent -->\n"
writeFile(t, dir, "keep.md", header+"<!-- Title: Keep -->\n\nKeep.\n")
writeFile(t, dir, "gone.md", header+"<!-- Title: Gone -->\n\nGone.\n")
config := Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
Tracking: TrackingConfig{
TrackPages: true,
OnOrphan: onOrphan,
OrphanUnder: under,
},
}
require.NoError(t, Run(context.Background(), config))
api := confluence.NewAPI(server.URL, confluence.Options{Username: "user", Password: "token"})
gone, err := api.FindPage(context.Background(), "DOCS", "Gone", "page")
require.NoError(t, err)
require.NotNil(t, gone)
require.NoError(t, os.Remove(filepath.Join(dir, "gone.md")))
require.NoError(t, Run(context.Background(), config))
return server, gone.ID, dir
}
func TestOnOrphanReportLeavesThePage(t *testing.T) {
server, id, _ := orphanFixture(t, "report", "")
page := server.Page(id)
require.NotNil(t, page)
assert.False(t, page.Trashed, "report must not remove anything")
assert.False(t, page.Archived)
}
func TestOnOrphanDeleteTrashesThePage(t *testing.T) {
server, id, _ := orphanFixture(t, "delete", "")
page := server.Page(id)
require.NotNil(t, page, "the page must be trashed, not purged")
assert.True(t, page.Trashed)
}
func TestOnOrphanArchiveArchivesThePage(t *testing.T) {
server, id, _ := orphanFixture(t, "archive", "")
page := server.Page(id)
require.NotNil(t, page)
assert.True(t, page.Archived)
assert.False(t, page.Trashed, "archiving is not trashing")
}
// TestOnOrphanForgetsAPageDeletedByHand: once the page is gone the orphan is
// dealt with, so the run succeeds and the next one is not asked about it again.
func TestOnOrphanForgetsAPageDeletedByHand(t *testing.T) {
for _, action := range []report.OnOrphan{report.OnOrphanDelete, report.OnOrphanArchive} {
t.Run(string(action), func(t *testing.T) {
ctx := context.Background()
server := confluencetest.New(t)
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
server.AddPage("DOCS", "Parent", "page", home.ID)
dir := t.TempDir()
header := "<!-- Space: DOCS -->\n<!-- Parent: Parent -->\n"
writeFile(t, dir, "keep.md", header+"<!-- Title: Keep -->\n\nKeep.\n")
writeFile(t, dir, "gone.md", header+"<!-- Title: Gone -->\n\nGone.\n")
config := Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{Features: []string{"mention"}},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
Tracking: TrackingConfig{TrackPages: true, OnOrphan: action},
}
require.NoError(t, Run(ctx, config))
api := confluence.NewAPI(server.URL, confluence.Options{Username: "user", Password: "token"})
gone, err := api.FindPage(ctx, "DOCS", "Gone", "page")
require.NoError(t, err)
require.NotNil(t, gone)
require.NoError(t, api.DeletePage(ctx, gone.ID))
require.NoError(t, os.Remove(filepath.Join(dir, "gone.md")))
require.NoError(t, Run(ctx, config))
_, known, err := manifest.NewStore(api).Lookup(ctx, "DOCS", filepath.Join(dir, "gone.md"))
require.NoError(t, err)
assert.False(t, known, "a page already gone is no longer tracked")
require.NoError(t, Run(ctx, config))
})
}
}
// TestOnOrphanRequiresTrackPages: without the manifest there is no way to know
// mark put the page there, which is not a guess to make about deletion.
func TestOnOrphanRequiresTrackPages(t *testing.T) {
server := confluencetest.New(t)
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
dir := t.TempDir()
writeFile(t, dir, "doc.md", "<!-- Space: DOCS -->\n<!-- Title: Doc -->\n\nBody.\n")
err := Run(context.Background(), Config{
PublishConfig: PublishConfig{
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
Tracking: TrackingConfig{
OnOrphan: "delete",
},
})
require.Error(t, err)
assert.Contains(t, err.Error(), "--track-pages")
}
func TestOnOrphanRejectsAnUnknownAction(t *testing.T) {
err := Run(context.Background(), Config{
PublishConfig: PublishConfig{
Output: io.Discard,
},
Files: "none",
Connection: ConnectionConfig{
BaseURL: "http://127.0.0.1:1",
Username: "user",
Password: "token",
},
Tracking: TrackingConfig{
OnOrphan: "incinerate",
TrackPages: true,
},
})
require.Error(t, err)
assert.Contains(t, err.Error(), "report")
}
// TestOnOrphanDryRunActsOnNothing.
func TestOnOrphanDryRunActsOnNothing(t *testing.T) {
server := confluencetest.New(t)
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
server.AddPage("DOCS", "Parent", "page", home.ID)
dir := t.TempDir()
header := "<!-- Space: DOCS -->\n<!-- Parent: Parent -->\n"
writeFile(t, dir, "keep.md", header+"<!-- Title: Keep -->\n\nKeep.\n")
writeFile(t, dir, "gone.md", header+"<!-- Title: Gone -->\n\nGone.\n")
config := Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
Tracking: TrackingConfig{
TrackPages: true,
OnOrphan: "delete",
},
}
require.NoError(t, Run(context.Background(), config))
api := confluence.NewAPI(server.URL, confluence.Options{Username: "user", Password: "token"})
gone, err := api.FindPage(context.Background(), "DOCS", "Gone", "page")
require.NoError(t, err)
require.NotNil(t, gone)
require.NoError(t, os.Remove(filepath.Join(dir, "gone.md")))
config.Mode.DryRun = true
require.NoError(t, Run(context.Background(), config))
assert.False(t, server.Page(gone.ID).Trashed, "a dry run must remove nothing")
}
// TestOnOrphanLeavesAPageWithChildren: trashing a page takes its children with
// it, and those may be pages nobody in this repository ever wrote.
func TestOnOrphanLeavesAPageWithChildren(t *testing.T) {
server, id, _ := orphanFixtureWithChild(t)
page := server.Page(id)
require.NotNil(t, page)
assert.False(t, page.Trashed,
"a page holding children must be left alone")
}
// orphanFixtureWithChild returns the server, the orphan's page id, and the
// json report of the run that found it orphaned.
func orphanFixtureWithChild(t *testing.T) (*confluencetest.Server, string, string) {
t.Helper()
server := confluencetest.New(t)
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
server.AddPage("DOCS", "Parent", "page", home.ID)
dir := t.TempDir()
header := "<!-- Space: DOCS -->\n<!-- Parent: Parent -->\n"
writeFile(t, dir, "keep.md", header+"<!-- Title: Keep -->\n\nKeep.\n")
writeFile(t, dir, "gone.md", header+"<!-- Title: Gone -->\n\nGone.\n")
config := Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
Tracking: TrackingConfig{
TrackPages: true,
OnOrphan: "delete",
},
}
require.NoError(t, Run(context.Background(), config))
api := confluence.NewAPI(server.URL, confluence.Options{Username: "user", Password: "token"})
gone, err := api.FindPage(context.Background(), "DOCS", "Gone", "page")
require.NoError(t, err)
require.NotNil(t, gone)
// Somebody adds a child page under it in Confluence.
server.AddPage("DOCS", "Written by hand", "page", gone.ID)
require.NoError(t, os.Remove(filepath.Join(dir, "gone.md")))
var out bytes.Buffer
config.Output = &out
config.Report.OutputFormat = report.FormatJSON
require.NoError(t, Run(context.Background(), config))
return server, gone.ID, out.String()
}
// TestOnOrphanReportsAPageItLeftAlone: a page --on-orphan delete did not
// remove is in the report, as left where it is and why, not missing from it.
func TestOnOrphanReportsAPageItLeftAlone(t *testing.T) {
_, id, out := orphanFixtureWithChild(t)
var got report.Report
require.NoError(t, json.Unmarshal([]byte(out), &got))
require.Len(t, got.Orphans, 1)
orphan := got.Orphans[0]
assert.Equal(t, id, orphan.PageID)
assert.Equal(t, report.OnOrphanReport, orphan.Action)
assert.Equal(t, "it has 1 child page(s), which removing it would take too", orphan.Reason)
}
// TestOnOrphanLeavesEverythingWhenNothingPublished pins the property rather
// than any one mechanism: a run that publishes nothing must remove nothing.
//
// Today an empty file set stops the run before orphans are even considered, so
// this passes with the guard in actOnOrphans removed. It is written against the
// behaviour on purpose -- whichever check is doing the work, moving orphan
// handling ahead of the other one should fail here rather than quietly enable
// mass deletion from a failed checkout.
func TestOnOrphanLeavesEverythingWhenNothingPublished(t *testing.T) {
server := confluencetest.New(t)
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
server.AddPage("DOCS", "Parent", "page", home.ID)
dir := t.TempDir()
header := "<!-- Space: DOCS -->\n<!-- Parent: Parent -->\n"
writeFile(t, dir, "one.md", header+"<!-- Title: One -->\n\nOne.\n")
writeFile(t, dir, "two.md", header+"<!-- Title: Two -->\n\nTwo.\n")
config := Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
Tracking: TrackingConfig{
TrackPages: true,
OnOrphan: "delete",
},
}
require.NoError(t, Run(context.Background(), config))
api := confluence.NewAPI(server.URL, confluence.Options{Username: "user", Password: "token"})
one, err := api.FindPage(context.Background(), "DOCS", "One", "page")
require.NoError(t, err)
require.NotNil(t, one)
// The checkout is empty this time, but the pattern is the same.
require.NoError(t, os.Remove(filepath.Join(dir, "one.md")))
require.NoError(t, os.Remove(filepath.Join(dir, "two.md")))
config.CI = true // so that no files matched is not itself an error
require.NoError(t, Run(context.Background(), config))
assert.False(t, server.Page(one.ID).Trashed,
"a run that published nothing must remove nothing")
}
// TestOrphanUnderLimitsScope: only pages below the named parent are in scope.
func TestOrphanUnderLimitsScope(t *testing.T) {
server := confluencetest.New(t)
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
server.AddPage("DOCS", "Inside", "page", home.ID)
server.AddPage("DOCS", "Outside", "page", home.ID)
dir := t.TempDir()
writeFile(t, dir, "in.md",
"<!-- Space: DOCS -->\n<!-- Parent: Inside -->\n<!-- Title: In -->\n\nIn.\n")
writeFile(t, dir, "out.md",
"<!-- Space: DOCS -->\n<!-- Parent: Outside -->\n<!-- Title: Out -->\n\nOut.\n")
writeFile(t, dir, "keep.md",
"<!-- Space: DOCS -->\n<!-- Parent: Inside -->\n<!-- Title: Keep -->\n\nKeep.\n")
config := Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
Tracking: TrackingConfig{
TrackPages: true,
OnOrphan: "delete",
OrphanUnder: "Inside",
},
}
require.NoError(t, Run(context.Background(), config))
api := confluence.NewAPI(server.URL, confluence.Options{Username: "user", Password: "token"})
in, err := api.FindPage(context.Background(), "DOCS", "In", "page")
require.NoError(t, err)
require.NotNil(t, in)
out, err := api.FindPage(context.Background(), "DOCS", "Out", "page")
require.NoError(t, err)
require.NotNil(t, out)
// Both source files go; only the one under "Inside" is in scope.
require.NoError(t, os.Remove(filepath.Join(dir, "in.md")))
require.NoError(t, os.Remove(filepath.Join(dir, "out.md")))
require.NoError(t, Run(context.Background(), config))
assert.True(t, server.Page(in.ID).Trashed, "the page below Inside is in scope")
assert.False(t, server.Page(out.ID).Trashed, "the page below Outside is not")
}
// TestOrphanUnderScopesReportingToo is the inconsistency this fixes. The scope
// narrowed what was archived or deleted, while reporting named everything and
// forgetting dropped everything -- so a page deliberately put out of scope was
// announced and then lost track of anyway.
func TestOrphanUnderScopesReportingToo(t *testing.T) {
ctx := t.Context()
server := confluencetest.New(t)
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
server.AddPage("DOCS", "Inside", "page", home.ID)
server.AddPage("DOCS", "Outside", "page", home.ID)
dir := t.TempDir()
writeFile(t, dir, "in.md",
"<!-- Space: DOCS -->\n<!-- Parent: Inside -->\n<!-- Title: In -->\n\nIn.\n")
writeFile(t, dir, "out.md",
"<!-- Space: DOCS -->\n<!-- Parent: Outside -->\n<!-- Title: Out -->\n\nOut.\n")
writeFile(t, dir, "keep.md",
"<!-- Space: DOCS -->\n<!-- Parent: Inside -->\n<!-- Title: Keep -->\n\nKeep.\n")
config := Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
Tracking: TrackingConfig{
TrackPages: true,
OnOrphan: "report",
OrphanUnder: "Inside",
},
}
require.NoError(t, Run(context.Background(), config))
api := confluence.NewAPI(server.URL, confluence.Options{Username: "user", Password: "token"})
out, err := api.FindPage(context.Background(), "DOCS", "Out", "page")
require.NoError(t, err)
require.NotNil(t, out)
// Both documents go. Only the one under "Inside" is mark's business.
require.NoError(t, os.Remove(filepath.Join(dir, "in.md")))
require.NoError(t, os.Remove(filepath.Join(dir, "out.md")))
require.NoError(t, Run(context.Background(), config))
store := manifest.NewStore(api)
_, inKnown, err := store.Lookup(ctx, "DOCS", filepath.Join(dir, "in.md"))
require.NoError(t, err)
assert.False(t, inKnown, "an in-scope orphan is reported once and forgotten")
_, outKnown, err := store.Lookup(ctx, "DOCS", filepath.Join(dir, "out.md"))
require.NoError(t, err)
assert.True(t, outKnown,
"a page put out of scope must still be remembered, not quietly dropped")
}
// TestOrphanUnderWithoutScopeIsUnchanged: with no scope every tracked page is
// mark's business, which is what it has always been.
func TestOrphanUnderWithoutScopeIsUnchanged(t *testing.T) {
ctx := t.Context()
server := confluencetest.New(t)
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
server.AddPage("DOCS", "Parent", "page", home.ID)
dir := t.TempDir()
header := "<!-- Space: DOCS -->\n<!-- Parent: Parent -->\n"
writeFile(t, dir, "keep.md", header+"<!-- Title: Keep -->\n\nKeep.\n")
writeFile(t, dir, "gone.md", header+"<!-- Title: Gone -->\n\nGone.\n")
config := Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
Tracking: TrackingConfig{
TrackPages: true,
},
}
require.NoError(t, Run(context.Background(), config))
require.NoError(t, os.Remove(filepath.Join(dir, "gone.md")))
require.NoError(t, Run(context.Background(), config))
api := confluence.NewAPI(server.URL, confluence.Options{Username: "user", Password: "token"})
_, known, err := manifest.NewStore(api).Lookup(ctx, "DOCS", filepath.Join(dir, "gone.md"))
require.NoError(t, err)
assert.False(t, known, "reported once and then forgotten, as before")
}
// TestOnOrphanCompileOnlyActsOnNothing: --compile-only prints the body it would
// have sent and stops, so it may not delete either. Only --dry-run got the
// read-only manifest, so a compile took the writable one and then returned
// before publishing -- which made every tracked page an orphan.
//
// The guard that keeps a space from being emptied counts what the run saw, and
// a document that has opted out of synchronising is looked up purely to mark it
// seen. One such document is therefore enough to carry the run past the guard
// and on to trashing a page whose source file is still sitting on disk.
func TestOnOrphanCompileOnlyActsOnNothing(t *testing.T) {
server := confluencetest.New(t)
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
server.AddPage("DOCS", "Parent", "page", home.ID)
dir := t.TempDir()
header := "<!-- Space: DOCS -->\n<!-- Parent: Parent -->\n"
writeFile(t, dir, "keep.md", header+"<!-- Title: Keep -->\n\nKeep.\n")
writeFile(t, dir, "gone.md", header+"<!-- Title: Gone -->\n\nGone.\n")
config := Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
Tracking: TrackingConfig{
TrackPages: true,
OnOrphan: "delete",
},
}
require.NoError(t, Run(context.Background(), config))
api := confluence.NewAPI(server.URL, confluence.Options{Username: "user", Password: "token"})
gone, err := api.FindPage(context.Background(), "DOCS", "Gone", "page")
require.NoError(t, err)
require.NotNil(t, gone)
// keep.md stays exactly where it is and merely stops synchronising.
writeFile(t, dir, "keep.md", header+"<!-- Title: Keep -->\n<!-- Synchronized: false -->\n\nKeep.\n")
require.NoError(t, os.Remove(filepath.Join(dir, "gone.md")))
config.Mode.CompileOnly = true
require.NoError(t, Run(context.Background(), config))
assert.False(t, server.Page(gone.ID).Trashed, "a compile must remove nothing")
}
// TestOnOrphanLeavesAPageWithChildFolders: the child listing that guards the
// deletion is a listing of pages, and a folder is not one. mark puts folders
// under pages itself, so a page whose children are all folders read as
// childless -- and trashing it takes the folders, and every page inside them,
// along with it.
func TestOnOrphanLeavesAPageWithChildFolders(t *testing.T) {
server := confluencetest.New(t)
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
server.AddPage("DOCS", "Parent", "page", home.ID)
dir := t.TempDir()
header := "<!-- Space: DOCS -->\n<!-- Parent: Parent -->\n"
writeFile(t, dir, "keep.md", header+"<!-- Title: Keep -->\n\nKeep.\n")
writeFile(t, dir, "gone.md", header+"<!-- Title: Gone -->\n\nGone.\n")
config := Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
Tracking: TrackingConfig{
TrackPages: true,
OnOrphan: "delete",
},
}
require.NoError(t, Run(context.Background(), config))
api := confluence.NewAPI(server.URL, confluence.Options{Username: "user", Password: "token"})
gone, err := api.FindPage(context.Background(), "DOCS", "Gone", "page")
require.NoError(t, err)
require.NotNil(t, gone)
// A folder beneath it, holding a page nobody in this repository wrote.
folder := server.AddFolder("DOCS", "Manuals", gone.ID, "page")
server.AddFolder("DOCS", "Nested", folder.ID, "folder")
require.NoError(t, os.Remove(filepath.Join(dir, "gone.md")))
require.NoError(t, Run(context.Background(), config))
page := server.Page(gone.ID)
require.NotNil(t, page)
assert.False(t, page.Trashed, "a page holding folders must be left alone")
}
// getsFor counts the GETs the fake received for exactly one content path,
// which is what a scope check costs: one GetPageByIDExpanded per orphan.
func getsFor(server *confluencetest.Server, pageID string) int {
var n int
for _, request := range server.Requests() {
if request.Method == http.MethodGet && request.Path == "/rest/api/content/"+pageID {
n++
}
}
return n
}
// TestOrphanScopeIsCheckedOnce pins the class of bug where the same remote
// question is asked twice. handleOrphans filtered its candidates with InScope
// and HandleOrphans then asked again about every survivor, so the one operation
// in mark that trashes pages cost twice the API calls it needed -- for an
// answer that had just been computed.
func TestOrphanScopeIsCheckedOnce(t *testing.T) {
server := confluencetest.New(t)
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
server.AddPage("DOCS", "Inside", "page", home.ID)
dir := t.TempDir()
writeFile(t, dir, "gone.md",
"<!-- Space: DOCS -->\n<!-- Parent: Inside -->\n<!-- Title: Gone -->\n\nGone.\n")
writeFile(t, dir, "keep.md",
"<!-- Space: DOCS -->\n<!-- Parent: Inside -->\n<!-- Title: Keep -->\n\nKeep.\n")
config := Config{
PublishConfig: PublishConfig{
Rendering: RenderingConfig{
Features: []string{"mention"},
},
Output: io.Discard,
},
Files: filepath.Join(dir, "*.md"),
Connection: ConnectionConfig{
BaseURL: server.URL,
Username: "user",
Password: "token",
},
Tracking: TrackingConfig{
TrackPages: true,
OnOrphan: "delete",
OrphanUnder: "Inside",
},
}
require.NoError(t, Run(context.Background(), config))
api := confluence.NewAPI(server.URL, confluence.Options{Username: "user", Password: "token"})
gone, err := api.FindPage(context.Background(), "DOCS", "Gone", "page")
require.NoError(t, err)
require.NotNil(t, gone)
require.NoError(t, os.Remove(filepath.Join(dir, "gone.md")))
server.ResetRequests()
require.NoError(t, Run(context.Background(), config))
assert.True(t, server.Page(gone.ID).Trashed, "the orphan is still acted on")
assert.Equal(t, 1, getsFor(server, gone.ID),
"an orphan's ancestry should be read once, not once per caller that wants the scope")
}
// writesTo lists the requests that could have changed something on the server:
// anything that is not a read. A dry run must send none of them.
func writesTo(server *confluencetest.Server) []string {
var writes []string
for _, r := range server.Requests() {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
writes = append(writes, r.Method+" "+r.Path)
}
}
return writes
}
// publishTracked publishes every *.md in dir with tracking on and
// --on-orphan delete, returning the config so a dry run can repeat it.
func publishTracked(t *testing.T, server *confluencetest.Server, dir string) Config {
t.Helper()
config := trackingConfig(server, filepath.Join(dir, "*.md"))
config.Tracking.OnOrphan = "delete"
require.NoError(t, Run(context.Background(), config))
return config
}
// TestDryRunDoesNotReportPublishedPagesAsOrphans: a dry run over documents that
// are all still present, after a tracked publish, must not read them as gone.
// The dry run found each page by title and returned before recording it, so
// every tracked path looked unseen: it reported the whole set as orphans, and
// with --on-orphan delete only the "nothing was published" guard in mark.go
// stopped it from listing each one as to be deleted.
func TestDryRunDoesNotReportPublishedPagesAsOrphans(t *testing.T) {
server, api := docsSpace(t)
dir := t.TempDir()
a := writeFile(t, dir, "a.md", markdownWithTitle("A"))
b := writeFile(t, dir, "b.md", markdownWithTitle("B"))
config := publishTracked(t, server, dir)
pageA, err := api.FindPage(context.Background(), "DOCS", "A", "page")
require.NoError(t, err)
require.NotNil(t, pageA)
pageB, err := api.FindPage(context.Background(), "DOCS", "B", "page")
require.NoError(t, err)
require.NotNil(t, pageB)
server.ResetRequests()
dry := config
dry.Mode.DryRun = true
logged := captureLog(t, func() { require.NoError(t, Run(context.Background(), dry)) })
// The capture works, at the level the orphan report is written at: without
// this, a quieter logger would make the assertions below pass vacuously.
assert.Contains(t, logged, "processing "+inLog(a))
assert.Contains(t, logged, "processing "+inLog(b))
// What the dry run used to log: every page reported as an orphan, then the
// "nothing was published" guard holding the deletion back.
assert.NotContains(t, logged, "had no matching source file",
"every document is still there")
assert.NotContains(t, logged, "nothing was published in this run")
// The guard above stopped the original bug short of this line; this
// assertion guards against a regression that gets past it. The text comes
// from the "page %q would be %sd" format in page/orphan.go.
assert.NotContains(t, logged, "would be deleted")
assert.Empty(t, writesTo(server), "a dry run must not change anything")
assert.False(t, server.Page(pageA.ID).Trashed)
assert.False(t, server.Page(pageB.ID).Trashed)
}
// TestDryRunStillReportsRealOrphans is the other half: recording the pages a dry
// run finds must not hide the one that is really gone. It is reported, and
// would be deleted, but the dry run leaves it where it is.
func TestDryRunStillReportsRealOrphans(t *testing.T) {
server, api := docsSpace(t)
dir := t.TempDir()
a := writeFile(t, dir, "a.md", markdownWithTitle("A"))
b := writeFile(t, dir, "b.md", markdownWithTitle("B"))
config := publishTracked(t, server, dir)
pageA, err := api.FindPage(context.Background(), "DOCS", "A", "page")
require.NoError(t, err)
require.NotNil(t, pageA)
pageB, err := api.FindPage(context.Background(), "DOCS", "B", "page")
require.NoError(t, err)
require.NotNil(t, pageB)
require.NoError(t, os.Remove(b))
server.ResetRequests()
dry := config
dry.Mode.DryRun = true
logged := captureLog(t, func() { require.NoError(t, Run(context.Background(), dry)) })
assert.Contains(t, logged, "processing "+inLog(a))
assert.Contains(t, logged, "1 tracked page(s) had no matching source file in this run: "+filepath.ToSlash(b),
"b.md is gone, and only b.md")
// "page %q would be %sd" in page/orphan.go; the quotes are escaped because
// zerolog writes the message as JSON.
assert.Contains(t, logged, `page \"B\" would be deleted`)
assert.NotContains(t, logged, `page \"A\" would be deleted`)
assert.Empty(t, writesTo(server), "a dry run must not change anything")
assert.False(t, server.Page(pageA.ID).Trashed)
assert.False(t, server.Page(pageB.ID).Trashed, "a dry run only says what it would delete")
}
// inLog is s as it reads in the captured log, which zerolog writes as JSON: a
// Windows path has its backslashes doubled.
func inLog(s string) string {
b, _ := json.Marshal(s)
return string(b[1 : len(b)-1])
}
// TestTrackingReportsOrphansWithoutDeleting: a file that disappears from the
// glob is reported, and the page it published to is left completely alone.
// Phase 1 never deletes.
func TestTrackingReportsOrphansWithoutDeleting(t *testing.T) {
server, api := docsSpace(t)
dir := t.TempDir()
writeFile(t, dir, "keep.md", markdownWithTitle("Keep"))
writeFile(t, dir, "drop.md", markdownWithTitle("Drop"))
require.NoError(t, Run(context.Background(), trackingConfig(server, filepath.Join(dir, "*.md"))))
dropped, err := api.FindPage(context.Background(), "DOCS", "Drop", "page")
require.NoError(t, err)
require.NotNil(t, dropped)
require.NoError(t, os.Remove(filepath.Join(dir, "drop.md")))
require.NoError(t, Run(context.Background(), trackingConfig(server, filepath.Join(dir, "*.md"))))
assert.NotNil(t, server.Page(dropped.ID),
"the page of a deleted file must survive: phase 1 reports, it does not prune")
}
// TestTrackingSuppressesOrphanReportOnFailedRuns pins the branch that used to be
// unreachable. A file that failed to process is indistinguishable from one that
// was deleted, so reporting it as missing would be actively misleading.
func TestTrackingSuppressesOrphanReportOnFailedRuns(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
writeFile(t, dir, "a.md", markdownWithTitle("A"))
writeFile(t, dir, "b.md", markdownWithTitle("B"))
require.NoError(t, Run(context.Background(), trackingConfig(server, filepath.Join(dir, "*.md"))))
// b.md now fails to process rather than disappearing.
writeFile(t, dir, "b.md", "# Broken\n\nNo metadata.\n")
var logged bytes.Buffer
restore := log.Logger
log.Logger = zerolog.New(&logged)
defer func() { log.Logger = restore }()
config := trackingConfig(server, filepath.Join(dir, "*.md"))
config.ContinueOnError = true
require.Error(t, Run(context.Background(), config))
assert.NotContains(t, logged.String(), "had no matching source file",
"a run with errors must not report unpublished pages as missing")
}
// TestOrphansAreScopedToTheGlob: a run narrowed with --files says nothing about
// files outside it. Reporting them as missing buries the handful of genuine
// deletions in a list of files that are perfectly present.
func TestOrphansAreScopedToTheGlob(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
require.NoError(t, os.MkdirAll(filepath.Join(dir, "guides"), 0o750))
require.NoError(t, os.MkdirAll(filepath.Join(dir, "notes"), 0o750))
writeFile(t, dir, "guides/a.md", markdownWithTitle("A"))
writeFile(t, dir, "notes/b.md", markdownWithTitle("B"))
// Publish each subtree with its own glob.
require.NoError(t, Run(context.Background(), trackingConfig(server, filepath.Join(dir, "guides", "*.md"))))
require.NoError(t, Run(context.Background(), trackingConfig(server, filepath.Join(dir, "notes", "*.md"))))
var logged bytes.Buffer
restore := log.Logger
log.Logger = zerolog.New(&logged)
defer func() { log.Logger = restore }()
// Re-run only the guides. notes/b.md is untouched and still present.
require.NoError(t, Run(context.Background(), trackingConfig(server, filepath.Join(dir, "guides", "*.md"))))
assert.NotContains(t, logged.String(), "had no matching source file",
"a run scoped to one directory must not report another's files as missing")
}
// TestDeletedFileIsReportedOnceThenForgotten: left in place, a deletion is
// reported on every run forever, which teaches people to ignore the one message
// worth reading.
func TestDeletedFileIsReportedOnceThenForgotten(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
writeFile(t, dir, "keep.md", markdownWithTitle("Keep"))
writeFile(t, dir, "drop.md", markdownWithTitle("Drop"))
glob := filepath.Join(dir, "*.md")
require.NoError(t, Run(context.Background(), trackingConfig(server, glob)))
require.NoError(t, os.Remove(filepath.Join(dir, "drop.md")))
first := captureLog(t, func() { require.NoError(t, Run(context.Background(), trackingConfig(server, glob))) })
assert.Contains(t, first, "had no matching source file",
"the deletion should be reported the first time it is noticed")
second := captureLog(t, func() { require.NoError(t, Run(context.Background(), trackingConfig(server, glob))) })
assert.NotContains(t, second, "had no matching source file",
"and not on every run thereafter")
}
// TestOnOrphanLeavesAPageAnotherPatternPublishes: a file moved from one run's
// pattern into another's keeps its page, which the second run records under
// the new path. The first run finds its own path gone, but the page is still
// published, so it is neither removed nor reported, and the first run stops
// tracking it.
func TestOnOrphanLeavesAPageAnotherPatternPublishes(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
writeAt(t, dir, "guides/doc.md", markdownWithTitle("Doc"))
writeAt(t, dir, "guides/keep.md", markdownWithTitle("Keep"))
writeAt(t, dir, "notes/other.md", markdownWithTitle("Other"))
guides := trackingConfig(server, filepath.Join(dir, "guides", "*.md"))
guides.Tracking.OnOrphan = report.OnOrphanDelete
notes := trackingConfig(server, filepath.Join(dir, "notes", "*.md"))
notes.Tracking.OnOrphan = report.OnOrphanDelete
require.NoError(t, Run(context.Background(), guides))
require.NoError(t, Run(context.Background(), notes))
docID := pageIDTitled(t, server, "Doc")
require.NotEmpty(t, docID)
require.NoError(t, os.Rename(filepath.Join(dir, "guides", "doc.md"), filepath.Join(dir, "notes", "doc.md")))
require.NoError(t, Run(context.Background(), notes))
require.Equal(t, docID, pageIDTitled(t, server, "Doc"), "the moved file publishes to the page it had")
var out bytes.Buffer
guides.Output = &out
guides.Report.OutputFormat = report.FormatJSON
logged := captureLog(t, func() { require.NoError(t, Run(context.Background(), guides)) })
assert.Equal(t, docID, pageIDTitled(t, server, "Doc"), "a page another pattern's file publishes is left where it is")
assert.NotContains(t, logged, "had no matching source file")
assert.NotContains(t, out.String(), "guides/doc.md", "the run reports no orphan for it")
// Neither run takes the page for an orphan afterwards.
require.NoError(t, Run(context.Background(), notes))
second := captureLog(t, func() { require.NoError(t, Run(context.Background(), guides)) })
assert.Equal(t, docID, pageIDTitled(t, server, "Doc"))
assert.NotContains(t, second, "had no matching source file")
}
// TestOnOrphanStillRemovesAPageOfAFileMovedOutOfEveryPattern: a file moved
// where no run publishes it leaves no other path recording its page, so the
// page is removed as any orphan is.
func TestOnOrphanStillRemovesAPageOfAFileMovedOutOfEveryPattern(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
writeAt(t, dir, "guides/doc.md", markdownWithTitle("Doc"))
writeAt(t, dir, "guides/keep.md", markdownWithTitle("Keep"))
writeAt(t, dir, "notes/other.md", markdownWithTitle("Other"))
guides := trackingConfig(server, filepath.Join(dir, "guides", "*.md"))
guides.Tracking.OnOrphan = report.OnOrphanDelete
notes := trackingConfig(server, filepath.Join(dir, "notes", "*.md"))
require.NoError(t, Run(context.Background(), guides))
require.NoError(t, Run(context.Background(), notes))
require.NotEmpty(t, pageIDTitled(t, server, "Doc"))
// Moved where no run publishes it: nothing else records the page.
require.NoError(t, os.MkdirAll(filepath.Join(dir, "drafts"), 0o750))
require.NoError(t, os.Rename(filepath.Join(dir, "guides", "doc.md"), filepath.Join(dir, "drafts", "doc.md")))
require.NoError(t, Run(context.Background(), notes))
require.NoError(t, Run(context.Background(), guides))
assert.Empty(t, pageIDTitled(t, server, "Doc"), "a page no other path records is removed")
}
// TestOnOrphanRemovesThePageADocumentLeftInItsOldSpace: a document whose
// Space changed is still among the run's files, but publishes nothing to the
// space it left, so the page it had there is an orphan of that space.
func TestOnOrphanRemovesThePageADocumentLeftInItsOldSpace(t *testing.T) {
server, _ := docsSpace(t)
home := server.AddPage("OPS", "Home", "page", "")
server.SetHomepage("OPS", home.ID)
server.AddPage("OPS", "Parent", "page", home.ID)
dir := t.TempDir()
writeFile(t, dir, "doc.md", markdownWithTitle("Doc"))