Repository navigation
Expand file tree
/
Copy pathmark_process_test.go
More file actions
1769 lines (1452 loc) · 64.6 KB
/
Copy pathmark_process_test.go
File metadata and controls
1769 lines (1452 loc) · 64.6 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"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"github.com/kovetskiy/mark/v16/confluence"
"github.com/kovetskiy/mark/v16/confluence/confluencetest"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// writeFile writes content into dir and returns its path.
func writeFile(t *testing.T, dir, name, content string) string {
t.Helper()
path := filepath.Join(dir, name)
require.NoError(t, os.WriteFile(path, []byte(content), 0o600))
return path
}
// TestProcessFileFetchesAttachmentsOnce pins the fix for the duplicate
// GetAttachments. ProcessFile resolves attachments twice per page -- declared
// attachments, then diagrams found while rendering -- and each pass used to
// issue its own paginated fetch of the same remote list.
func TestProcessFileFetchesAttachmentsOnce(t *testing.T) {
server := confluencetest.New(t)
api := confluence.NewAPI(server.URL, "user", "token", false)
// A parentless page is only valid as the space homepage, so build a
// realistic tree: Home is the homepage, Parent sits under it.
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
server.AddPage("DOCS", "Parent", "page", home.ID)
dir := t.TempDir()
// A 1x1 PNG so the image-dimension probe has something valid to read.
png := []byte{
0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a,
0x00, 0x00, 0x00, 0x0d, 'I', 'H', 'D', 'R',
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
0x89,
}
require.NoError(t, os.WriteFile(filepath.Join(dir, "logo.png"), png, 0o600))
file := writeFile(t, dir, "doc.md", `<!-- Space: DOCS -->
<!-- Parent: Parent -->
<!-- Title: Attachment Doc -->
<!-- Attachment: logo.png -->
# Attachment Doc

`)
config := Config{
BaseURL: server.URL,
Username: "user",
Password: "token",
Files: file,
Features: []string{"mention"},
Output: io.Discard,
}
server.ResetRequests()
target, err := ProcessFile(file, api, config)
require.NoError(t, err)
require.NotNil(t, target)
assert.Equal(t, 1, server.CountRequests("GET", "/child/attachment"),
"the remote attachment list should be fetched once per page")
stored := server.Attachments(target.ID)
require.Len(t, stored, 1)
assert.Equal(t, "logo.png", stored[0].Filename)
}
// TestProcessFileCreatesAndUpdatesPage is a smoke test for the whole
// orchestration path, which had no coverage at all: metadata, ancestry, page
// creation, body upload and labels in one run.
func TestProcessFileCreatesAndUpdatesPage(t *testing.T) {
server := confluencetest.New(t)
api := confluence.NewAPI(server.URL, "user", "token", false)
// A parentless page is only valid as the space homepage, so build a
// realistic tree: Home is the homepage, Parent sits under it.
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
server.AddPage("DOCS", "Parent", "page", home.ID)
dir := t.TempDir()
file := writeFile(t, dir, "doc.md", `<!-- Space: DOCS -->
<!-- Parent: Parent -->
<!-- Title: New Page -->
<!-- Label: alpha -->
# New Page
Some **content**.
`)
config := Config{
BaseURL: server.URL,
Username: "user",
Password: "token",
Files: file,
Features: []string{"mention"},
Output: io.Discard,
}
target, err := ProcessFile(file, api, config)
require.NoError(t, err)
require.NotNil(t, target)
stored := server.Page(target.ID)
require.NotNil(t, stored)
assert.Equal(t, "New Page", stored.Title)
assert.Contains(t, stored.Body, "<strong>content</strong>")
assert.Equal(t, []string{"alpha"}, stored.Labels)
// The page was created under the declared parent.
parent, err := api.FindPage("DOCS", "Parent", "page")
require.NoError(t, err)
assert.Equal(t, parent.ID, stored.ParentID)
}
// markdownWithTitle is the document under test, parameterised on its title.
func markdownWithTitle(title string) string {
return `<!-- Space: DOCS -->
<!-- Parent: Parent -->
<!-- Title: ` + title + ` -->
# ` + title + `
Some content.
`
}
// trackingConfig is a publish configured to remember page identity.
func trackingConfig(server *confluencetest.Server, files string) Config {
return Config{
BaseURL: server.URL,
Username: "user",
Password: "token",
Files: files,
Features: []string{"mention"},
TrackPages: true,
Output: io.Discard,
}
}
// docsSpace builds the minimal realistic tree the publish path expects.
func docsSpace(t *testing.T) (*confluencetest.Server, *confluence.API) {
t.Helper()
server := confluencetest.New(t)
api := confluence.NewAPI(server.URL, "user", "token", false)
home := server.AddPage("DOCS", "Home", "page", "")
server.SetHomepage("DOCS", home.ID)
server.AddPage("DOCS", "Parent", "page", home.ID)
return server, api
}
// countPagesTitled reports whether any page in the space carries a title, which
// is what tells a retitle apart from a duplicate.
//
// It builds its own client on purpose. confluence.API memoises FindPage by
// (space, title, type), so asking a client that has already looked this title up
// would be answered from that cache and report a page that has since been
// renamed out from under it.
func countPagesTitled(t *testing.T, server *confluencetest.Server, title string) int {
t.Helper()
fresh := confluence.NewAPI(server.URL, "user", "token", false)
page, err := fresh.FindPage("DOCS", title, "page")
require.NoError(t, err)
if page == nil {
return 0
}
return 1
}
// TestTrackedPageIsRetitledNotDuplicated is the behaviour the manifest exists
// for. mark finds a page by title, so changing the title makes the existing page
// unfindable and a second one is published beside it. With tracking on, the file
// path resolves to the page that was published last time and it is renamed in
// place.
func TestTrackedPageIsRetitledNotDuplicated(t *testing.T) {
server, api := docsSpace(t)
dir := t.TempDir()
file := writeFile(t, dir, "doc.md", markdownWithTitle("Original Title"))
require.NoError(t, Run(trackingConfig(server, file)))
before, err := api.FindPage("DOCS", "Original Title", "page")
require.NoError(t, err)
require.NotNil(t, before)
// The Title header changes; the file does not move.
writeFile(t, dir, "doc.md", markdownWithTitle("Renamed Title"))
require.NoError(t, Run(trackingConfig(server, file)))
after := server.Page(before.ID)
require.NotNil(t, after)
assert.Equal(t, "Renamed Title", after.Title,
"the original page should have been retitled in place")
assert.Equal(t, 0, countPagesTitled(t, server, "Original Title"),
"nothing should still be published under the old title")
}
// TestUntrackedTitleChangeStillDuplicates is the control: without the flag the
// old behaviour is unchanged, which is what makes the test above meaningful.
func TestUntrackedTitleChangeStillDuplicates(t *testing.T) {
server, api := docsSpace(t)
dir := t.TempDir()
config := trackingConfig(server, "")
config.TrackPages = false
file := writeFile(t, dir, "doc.md", markdownWithTitle("Original Title"))
config.Files = file
require.NoError(t, Run(config))
before, err := api.FindPage("DOCS", "Original Title", "page")
require.NoError(t, err)
require.NotNil(t, before)
writeFile(t, dir, "doc.md", markdownWithTitle("Renamed Title"))
require.NoError(t, Run(config))
assert.Equal(t, "Original Title", server.Page(before.ID).Title,
"without tracking the first page is left behind under its old title")
assert.Equal(t, 1, countPagesTitled(t, server, "Renamed Title"),
"and a second page now exists under the new one")
}
// TestTrackedRetitleHappensEvenWhenContentIsUnchanged covers the interaction
// with --changes-only: the content fingerprint matches, so the update would be
// skipped, and the page would keep its old title forever.
func TestTrackedRetitleHappensEvenWhenContentIsUnchanged(t *testing.T) {
server, api := docsSpace(t)
dir := t.TempDir()
body := `<!-- Space: DOCS -->
<!-- Parent: Parent -->
<!-- Title: %s -->
Body that does not change.
`
file := writeFile(t, dir, "doc.md", fmt.Sprintf(body, "First"))
config := trackingConfig(server, file)
config.ChangesOnly = true
require.NoError(t, Run(config))
before, err := api.FindPage("DOCS", "First", "page")
require.NoError(t, err)
require.NotNil(t, before)
// Only the title changes; the rendered body is byte-identical.
writeFile(t, dir, "doc.md", fmt.Sprintf(body, "Second"))
require.NoError(t, Run(config))
assert.Equal(t, "Second", server.Page(before.ID).Title,
"a retitle must not be skipped just because the content hash matched")
}
// 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(trackingConfig(server, filepath.Join(dir, "*.md"))))
dropped, err := api.FindPage("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(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")
}
// TestTrackedPageDeletedInConfluenceIsRecreated: someone removed the page from
// Confluence by hand. The manifest still names it, and pointing at a page that
// is not there must not wedge the run.
func TestTrackedPageDeletedInConfluenceIsRecreated(t *testing.T) {
server, api := docsSpace(t)
dir := t.TempDir()
file := writeFile(t, dir, "doc.md", markdownWithTitle("Doc"))
require.NoError(t, Run(trackingConfig(server, file)))
published, err := api.FindPage("DOCS", "Doc", "page")
require.NoError(t, err)
require.NotNil(t, published)
server.DeletePage(published.ID)
// Retitle too, so the title lookup also misses and resolution is forced
// through the manifest entry that now dangles.
writeFile(t, dir, "doc.md", markdownWithTitle("Doc Renamed"))
require.NoError(t, Run(trackingConfig(server, file)),
"a dangling manifest entry must not fail the run")
assert.Equal(t, 1, countPagesTitled(t, server, "Doc Renamed"),
"the page should have been created afresh")
}
// TestTrackingSavesManifestEvenWhenAFileFails covers the case --continue-on-error
// exists for. The manifest used to be written only after an early return on
// hasErrors, so one unpublishable file discarded the mapping for every page that
// had published perfectly well, and the next run had no protection at all.
func TestTrackingSavesManifestEvenWhenAFileFails(t *testing.T) {
server, api := docsSpace(t)
dir := t.TempDir()
good := writeFile(t, dir, "good.md", markdownWithTitle("Good"))
// No Space header and no --space, which fails in metadata rather than
// anywhere that could be mistaken for a manifest problem.
writeFile(t, dir, "bad.md", "# Orphan\n\nNo metadata at all.\n")
config := trackingConfig(server, filepath.Join(dir, "*.md"))
config.ContinueOnError = true
require.Error(t, Run(config), "the bad file should still fail the run")
published, err := api.FindPage("DOCS", "Good", "page")
require.NoError(t, err)
require.NotNil(t, published)
// The mapping for the file that did publish must have survived: retitle it
// and it should be found again rather than duplicated.
writeFile(t, dir, "good.md", markdownWithTitle("Good Renamed"))
config.Files = good
require.NoError(t, Run(config))
assert.Equal(t, "Good Renamed", server.Page(published.ID).Title,
"the mapping recorded on the failed run should have been saved")
assert.Equal(t, 0, countPagesTitled(t, server, "Good"),
"nothing should be left behind under the old title")
}
// 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(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(config))
assert.NotContains(t, logged.String(), "had no matching source file",
"a run with errors must not report unpublished pages as missing")
}
// TestTrackedPageLoadFailureDoesNotDuplicate covers the distinction flaw 6 was
// about. A recorded page that is genuinely gone falls through to being created
// again; any other failure to load it must stop the run instead, because
// treating a transient error as "the page is gone" publishes exactly the
// duplicate this feature exists to prevent.
func TestTrackedPageLoadFailureDoesNotDuplicate(t *testing.T) {
server, api := docsSpace(t)
dir := t.TempDir()
file := writeFile(t, dir, "doc.md", markdownWithTitle("Doc"))
require.NoError(t, Run(trackingConfig(server, file)))
published, err := api.FindPage("DOCS", "Doc", "page")
require.NoError(t, err)
require.NotNil(t, published)
// The page is still there, but loading it fails the way a proxy or an
// overloaded instance would.
server.SetFail(func(r *http.Request) (int, string, bool) {
if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/content/"+published.ID) {
return http.StatusInternalServerError, `{"message":"upstream exploded"}`, true
}
return 0, "", false
})
// Retitle so resolution is forced through the manifest entry.
writeFile(t, dir, "doc.md", markdownWithTitle("Doc Renamed"))
require.Error(t, Run(trackingConfig(server, file)),
"a page that cannot be loaded must stop the run, not be republished")
server.SetFail(nil)
assert.Equal(t, 0, countPagesTitled(t, server, "Doc Renamed"),
"no duplicate should have been created")
assert.Equal(t, "Doc", server.Page(published.ID).Title,
"the original page is untouched")
}
// markdownUnder is a document declaring the full ancestry Parent > parent.
// The whole chain has to be declared, not just the immediate parent, or mark
// rejects the page as sitting at a different depth than its headers claim.
func markdownUnder(parent, title string) string {
return `<!-- Space: DOCS -->
<!-- Parent: Parent -->
<!-- Parent: ` + parent + ` -->
<!-- Title: ` + title + ` -->
Body.
`
}
// TestRenamedParentIsFollowedNotRecreated is the reference half of the problem
// tracking exists for. mark names a parent by title and creates it when the
// title is not found, so renaming a page that other documents declare as their
// parent used to strand them under a fresh empty page carrying the old name --
// and tracking made that likelier, because the parent is now renamed in place
// rather than duplicated somewhere visible.
func TestRenamedParentIsFollowedNotRecreated(t *testing.T) {
server, api := docsSpace(t)
dir := t.TempDir()
// Named so the parent is processed first. With the child first it is
// resolved while the parent still carries its old title, and the stale
// reference is never exercised -- which is exactly how this test passed
// against the unfixed code the first time it was written.
writeFile(t, dir, "a-parent.md", markdownWithTitle("Guide"))
writeFile(t, dir, "b-child.md", markdownUnder("Guide", "Child"))
glob := filepath.Join(dir, "*.md")
require.NoError(t, Run(trackingConfig(server, glob)))
parentPage, err := api.FindPage("DOCS", "Guide", "page")
require.NoError(t, err)
require.NotNil(t, parentPage)
// The parent is renamed. The child still declares the old title.
writeFile(t, dir, "a-parent.md", markdownWithTitle("Guide Renamed"))
require.NoError(t, Run(trackingConfig(server, glob)))
assert.Equal(t, "Guide Renamed", server.Page(parentPage.ID).Title,
"the parent should have been renamed in place")
assert.Equal(t, 0, countPagesTitled(t, server, "Guide"),
"no empty page should have been created under the old title")
child, err := confluence.NewAPI(server.URL, "user", "token", false).
FindPage("DOCS", "Child", "page")
require.NoError(t, err)
require.NotNil(t, child)
assert.Equal(t, parentPage.ID, server.Page(child.ID).ParentID,
"the child should still sit under the same page it always did")
}
// TestUnknownParentTitleIsStillCreated is the control: a parent mark has never
// published is not a stale reference, and must still be created as before.
func TestUnknownParentTitleIsStillCreated(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
file := writeFile(t, dir, "child.md", markdownUnder("Brand New Parent", "Child"))
require.NoError(t, Run(trackingConfig(server, file)))
assert.Equal(t, 1, countPagesTitled(t, server, "Brand New Parent"),
"an unknown parent title is not stale and should still be created")
}
// handMadeParent puts a page under DOCS > Parent the way somebody would in the
// Confluence UI, and returns it. No document in the repository publishes it,
// which is what a parent usually is and what the title index cannot know about.
func handMadeParent(t *testing.T, server *confluencetest.Server, title string) *confluencetest.Page {
t.Helper()
under, err := confluence.NewAPI(server.URL, "user", "token", false).
FindPage("DOCS", "Parent", "page")
require.NoError(t, err)
require.NotNil(t, under)
return server.AddPage("DOCS", title, "page", under.ID)
}
// TestRenamedHandMadeParentIsFollowedNotRecreated is the case the title index
// could never answer. Following a stale parent used to mean asking which page
// mark had published under that title, and a parent nobody publishes -- made by
// hand, or created empty by mark to hold a hierarchy -- has never been in that
// index. The chain each document declares is recorded when it resolves, so the
// position is what is followed rather than the title.
func TestRenamedHandMadeParentIsFollowedNotRecreated(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
guide := handMadeParent(t, server, "Guide")
file := writeFile(t, dir, "child.md", markdownUnder("Guide", "Child"))
require.NoError(t, Run(trackingConfig(server, file)))
// Somebody renames it in the UI. The document still says "Guide".
server.RenamePage(guide.ID, "Guide Renamed")
require.NoError(t, Run(trackingConfig(server, file)))
assert.Equal(t, 0, countPagesTitled(t, server, "Guide"),
"no empty page should have been created under the old title")
child, err := confluence.NewAPI(server.URL, "user", "token", false).
FindPage("DOCS", "Child", "page")
require.NoError(t, err)
require.NotNil(t, child)
assert.Equal(t, guide.ID, server.Page(child.ID).ParentID,
"the child should still sit under the page it always did")
}
// TestRenamedHandMadeParentDuplicatesWithoutTracking is the control: without
// the flag the old behaviour stands, which is what makes the test above mean
// anything.
func TestRenamedHandMadeParentDuplicatesWithoutTracking(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
guide := handMadeParent(t, server, "Guide")
config := trackingConfig(server, writeFile(t, dir, "child.md", markdownUnder("Guide", "Child")))
config.TrackPages = false
require.NoError(t, Run(config))
server.RenamePage(guide.ID, "Guide Renamed")
require.NoError(t, Run(config))
assert.Equal(t, 1, countPagesTitled(t, server, "Guide"),
"without tracking an empty page appears under the old title")
child, err := confluence.NewAPI(server.URL, "user", "token", false).
FindPage("DOCS", "Child", "page")
require.NoError(t, err)
require.NotNil(t, child)
assert.NotEqual(t, guide.ID, server.Page(child.ID).ParentID,
"and the child is moved beneath it")
}
// TestParentCreatedByMarkIsFollowedAfterRename covers the other half of the
// recording: a parent mark created itself to hold the hierarchy is remembered
// at the moment it is created, not only when it is found again.
func TestParentCreatedByMarkIsFollowedAfterRename(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
file := writeFile(t, dir, "child.md", markdownUnder("Brand New Parent", "Child"))
require.NoError(t, Run(trackingConfig(server, file)))
created, err := confluence.NewAPI(server.URL, "user", "token", false).
FindPage("DOCS", "Brand New Parent", "page")
require.NoError(t, err)
require.NotNil(t, created)
server.RenamePage(created.ID, "Brand New Parent Renamed")
require.NoError(t, Run(trackingConfig(server, file)))
assert.Equal(t, 0, countPagesTitled(t, server, "Brand New Parent"),
"the parent mark created should have been followed, not made again")
}
// TestRenamedParentChainIsFollowedAtEveryLevel: the keys name the chain as the
// document declares it. Rewriting one level and then keying the next off the
// rewritten title would look up a chain that was never recorded, so a run where
// two levels were renamed at once would repair the first and recreate the
// second.
func TestRenamedParentChainIsFollowedAtEveryLevel(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
top, err := confluence.NewAPI(server.URL, "user", "token", false).
FindPage("DOCS", "Parent", "page")
require.NoError(t, err)
guide := handMadeParent(t, server, "Guide")
file := writeFile(t, dir, "child.md", markdownUnder("Guide", "Child"))
require.NoError(t, Run(trackingConfig(server, file)))
server.RenamePage(top.ID, "Parent Renamed")
server.RenamePage(guide.ID, "Guide Renamed")
require.NoError(t, Run(trackingConfig(server, file)))
assert.Equal(t, 0, countPagesTitled(t, server, "Parent"),
"the top of the chain should have been followed")
assert.Equal(t, 0, countPagesTitled(t, server, "Guide"),
"and so should the level below it, whose key is unaffected by the rewrite above")
child, err := confluence.NewAPI(server.URL, "user", "token", false).
FindPage("DOCS", "Child", "page")
require.NoError(t, err)
require.NotNil(t, child)
assert.Equal(t, guide.ID, server.Page(child.ID).ParentID,
"the child should not have moved")
}
// TestTwoFilesClaimingOnePageIsReported: nothing stops two documents resolving
// to the same page by title, and then a rename of either moves a page the other
// also believes is its own. mark cannot tell which was meant, so it says so.
func TestTwoFilesClaimingOnePageIsReported(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
// Same title, two files.
writeFile(t, dir, "one.md", markdownWithTitle("Shared"))
writeFile(t, dir, "two.md", markdownWithTitle("Shared"))
var logged bytes.Buffer
restore := log.Logger
log.Logger = zerolog.New(&logged)
defer func() { log.Logger = restore }()
require.NoError(t, Run(trackingConfig(server, filepath.Join(dir, "*.md"))))
assert.Contains(t, logged.String(), "both publish to page",
"two files resolving to one page should be reported")
}
// TestPageIDModeSaysTrackingDoesNotApply: the mapping is per space and per
// file, and a publish straight to a page id has neither. Better said once than
// discovered later as a manifest with holes in it.
func TestPageIDModeSaysTrackingDoesNotApply(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
existing := server.AddPage("DOCS", "Existing", "page", "")
file := writeFile(t, dir, "doc.md", "Just a body.\n")
var logged bytes.Buffer
restore := log.Logger
log.Logger = zerolog.New(&logged)
defer func() { log.Logger = restore }()
config := trackingConfig(server, file)
config.PageID = existing.ID
require.NoError(t, Run(config))
assert.Contains(t, logged.String(), "no effect together with a page id")
}
// TestDryRunWritesNothing pins the promise --dry-run makes. Tracking gave it a
// way to break that promise: resolving the hierarchy records what it finds, a
// recording marks the manifest dirty, and Save writes it -- so a dry run would
// modify Confluence.
func TestDryRunWritesNothing(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
file := writeFile(t, dir, "doc.md", markdownWithTitle("Doc"))
config := trackingConfig(server, file)
config.DryRun = true
require.NoError(t, Run(config))
for _, r := range server.Requests() {
assert.Equal(t, http.MethodGet, r.Method,
"a dry run must issue no writes, saw %s %s", r.Method, r.Path)
}
}
// markdownInFolder declares a folder hierarchy under the MARK_PARENTS anchor.
func markdownInFolder(folder, title string) string {
return `<!-- Space: DOCS -->
<!-- Parent: Parent -->
<!-- Folder: ` + folder + ` -->
<!-- Title: ` + title + ` -->
Body.
`
}
// TestFolderPublishWithoutTracking is the path that carried a latent panic: a
// nil *manifest.Store placed in a FolderTracker interface is a non-nil
// interface, so with tracking off mark would have called through a nil
// receiver. Nothing exercised it, because the fake had no folder endpoints.
func TestFolderPublishWithoutTracking(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
file := writeFile(t, dir, "doc.md", markdownInFolder("Guides", "Doc"))
config := trackingConfig(server, file)
config.TrackPages = false
require.NoError(t, Run(config), "publishing into a folder must work with tracking off")
folders := server.Folders()
require.Len(t, folders, 1)
assert.Equal(t, "Guides", folders[0].Title)
}
func TestFolderPublishWithTracking(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
file := writeFile(t, dir, "doc.md", markdownInFolder("Guides", "Doc"))
require.NoError(t, Run(trackingConfig(server, file)))
folders := server.Folders()
require.Len(t, folders, 1, "exactly one folder should exist")
assert.Equal(t, "Guides", folders[0].Title)
}
// TestRenamedFolderIsFollowedNotDuplicated is what folder tracking is for.
// Folders are found by title, so one renamed in Confluence stops matching the
// header that declares it and mark builds a second beside the first, splitting
// the hierarchy.
func TestRenamedFolderIsFollowedNotDuplicated(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
file := writeFile(t, dir, "doc.md", markdownInFolder("Guides", "Doc"))
require.NoError(t, Run(trackingConfig(server, file)))
original := server.Folders()
require.Len(t, original, 1)
// Somebody renames the folder in the Confluence UI. The header still says
// "Guides".
server.RenameFolder(original[0].ID, "Guides Renamed")
require.NoError(t, Run(trackingConfig(server, file)))
after := server.Folders()
assert.Len(t, after, 1,
"the renamed folder should have been reused, not duplicated")
assert.Equal(t, original[0].ID, after[0].ID)
}
// TestRenamedFolderDuplicatesWithoutTracking is the control: without the flag
// the old behaviour stands, which is what makes the test above mean anything.
func TestRenamedFolderDuplicatesWithoutTracking(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
config := trackingConfig(server, "")
config.TrackPages = false
file := writeFile(t, dir, "doc.md", markdownInFolder("Guides", "Doc"))
config.Files = file
require.NoError(t, Run(config))
original := server.Folders()
require.Len(t, original, 1)
server.RenameFolder(original[0].ID, "Guides Renamed")
require.NoError(t, Run(config))
assert.Len(t, server.Folders(), 2,
"without tracking the renamed folder is not recognised and a second appears")
}
// TestFolderRepublishWithoutTrackingUpdatesInPlace publishes a document into a
// folder twice with tracking off. v1 reports no ancestors for a page whose
// parent is a folder, and the page found by title was read as one somewhere
// else in the space, so the second run created it again -- which Confluence
// refuses, a title being unique within a space.
func TestFolderRepublishWithoutTrackingUpdatesInPlace(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
config := trackingConfig(server, "")
config.TrackPages = false
config.Files = writeFile(t, dir, "doc.md", markdownInFolder("Guides", "Doc"))
require.NoError(t, Run(config))
require.NoError(t, Run(config), "the second run must update the page it published")
assert.Equal(t, 1, server.CountRequests(http.MethodPost, "/api/v2/pages"),
"the page is created once and updated after that")
}
// TestFolderDocumentLeavesHomePageAlone is the limit on the above: the home
// page has no ancestors either, and a document that happens to share its title
// must not move it into a folder.
func TestFolderDocumentLeavesHomePageAlone(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
config := trackingConfig(server, "")
config.TrackPages = false
config.Files = writeFile(t, dir, "doc.md", markdownInFolder("Guides", "Home"))
// The create that follows fails on the duplicate title; what matters is
// that nothing was moved on the way there.
_ = Run(config)
assert.Zero(t, server.CountRequests(http.MethodPut, "/move/"),
"the home page must stay where it is")
}
// TestDryRunDoesNotRecordFolders covers the other defect the missing endpoints
// hid: resolving a hierarchy records what it finds, a recording marks the
// manifest dirty, and Save writes it -- so --dry-run wrote to Confluence.
func TestDryRunDoesNotRecordFolders(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
// A folder that already exists, so a dry run resolves rather than creates.
server.AddFolder("DOCS", "Guides", "", "page")
file := writeFile(t, dir, "doc.md", markdownInFolder("Guides", "Doc"))
config := trackingConfig(server, file)
config.DryRun = true
require.NoError(t, Run(config))
for _, r := range server.Requests() {
assert.Equal(t, http.MethodGet, r.Method,
"a dry run must issue no writes, saw %s %s", r.Method, r.Path)
}
}
// markdownTitledFromFilename has no Title header, so its title comes from the
// filename -- which is what makes a rename change the title too, and the case
// that duplicates without rename detection.
func markdownTitledFromFilename() string {
return `<!-- Space: DOCS -->
<!-- Parent: Parent -->
Body that does not change when the file moves.
`
}
func filenameTitleConfig(server *confluencetest.Server, files string) Config {
config := trackingConfig(server, files)
config.TitleFromFilename = true
return config
}
// TestRenamedFileIsFollowedNotDuplicated is the last of the three rename causes
// asked for. The path is the manifest key, so renaming a file is a miss; and
// when the title comes from the filename the title lookup misses too, and mark
// publishes a second page. The only thing tying the old page to the new file is
// what the file contains.
func TestRenamedFileIsFollowedNotDuplicated(t *testing.T) {
server, api := docsSpace(t)
dir := t.TempDir()
writeFile(t, dir, "old-name.md", markdownTitledFromFilename())
glob := filepath.Join(dir, "*.md")
require.NoError(t, Run(filenameTitleConfig(server, glob)))
original, err := api.FindPage("DOCS", "Old Name", "page")
require.NoError(t, err)
require.NotNil(t, original, "the first run publishes under the filename")
// The file is renamed. Its content is untouched.
require.NoError(t, os.Rename(
filepath.Join(dir, "old-name.md"), filepath.Join(dir, "new-name.md")))
require.NoError(t, Run(filenameTitleConfig(server, glob)))
assert.Equal(t, "New Name", server.Page(original.ID).Title,
"the existing page should have been renamed, not left behind")
assert.Equal(t, 0, countPagesTitled(t, server, "Old Name"),
"nothing should remain under the old name")
}
// TestRenamedFileDuplicatesWithoutTracking is the control.
func TestRenamedFileDuplicatesWithoutTracking(t *testing.T) {
server, api := docsSpace(t)
dir := t.TempDir()
config := filenameTitleConfig(server, filepath.Join(dir, "*.md"))
config.TrackPages = false
writeFile(t, dir, "old-name.md", markdownTitledFromFilename())
require.NoError(t, Run(config))
original, err := api.FindPage("DOCS", "Old Name", "page")
require.NoError(t, err)
require.NotNil(t, original)
require.NoError(t, os.Rename(
filepath.Join(dir, "old-name.md"), filepath.Join(dir, "new-name.md")))
require.NoError(t, Run(config))
assert.Equal(t, "Old Name", server.Page(original.ID).Title,
"without tracking the old page is stranded under its old name")
assert.Equal(t, 1, countPagesTitled(t, server, "New Name"),
"and a second page appears")
}
// TestRenamedFileStopsBeingReportedAsDeleted: a followed rename must take the
// old path with it, or it is reported as a missing file on every run from then
// on.
func TestRenamedFileStopsBeingReportedAsDeleted(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
writeFile(t, dir, "old-name.md", markdownTitledFromFilename())
glob := filepath.Join(dir, "*.md")
require.NoError(t, Run(filenameTitleConfig(server, glob)))
require.NoError(t, os.Rename(
filepath.Join(dir, "old-name.md"), filepath.Join(dir, "new-name.md")))
require.NoError(t, Run(filenameTitleConfig(server, glob)))
var logged bytes.Buffer
restore := log.Logger
log.Logger = zerolog.New(&logged)
defer func() { log.Logger = restore }()
require.NoError(t, Run(filenameTitleConfig(server, glob)))
assert.NotContains(t, logged.String(), "had no matching source file",
"the old path should have been dropped when the rename was followed")
}
// TestAmbiguousRenameCreatesRatherThanGuesses: two unpublished documents with
// identical content give no basis for choosing between them. A duplicate is a
// nuisance; rebinding onto the wrong page overwrites something nobody asked to
// change.
func TestAmbiguousRenameCreatesRatherThanGuesses(t *testing.T) {
server, _ := docsSpace(t)
dir := t.TempDir()
writeFile(t, dir, "one.md", markdownTitledFromFilename())
writeFile(t, dir, "two.md", markdownTitledFromFilename())
glob := filepath.Join(dir, "*.md")
require.NoError(t, Run(filenameTitleConfig(server, glob)))
// Both disappear and one appears with the same content.
require.NoError(t, os.Remove(filepath.Join(dir, "one.md")))
require.NoError(t, os.Rename(
filepath.Join(dir, "two.md"), filepath.Join(dir, "three.md")))
require.NoError(t, Run(filenameTitleConfig(server, glob)))
assert.Equal(t, 1, countPagesTitled(t, server, "Three"),
"an ambiguous match must create rather than rebind")
assert.Equal(t, 1, countPagesTitled(t, server, "One"),
"and must leave both candidates alone")
}
// 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(trackingConfig(server, filepath.Join(dir, "guides", "*.md"))))
require.NoError(t, Run(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(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(trackingConfig(server, glob)))
require.NoError(t, os.Remove(filepath.Join(dir, "drop.md")))
first := captureLog(t, func() { require.NoError(t, Run(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(trackingConfig(server, glob))) })
assert.NotContains(t, second, "had no matching source file",
"and not on every run thereafter")
}
// captureLog runs fn with the global logger redirected, returning what it wrote.
func captureLog(t *testing.T, fn func()) string {
t.Helper()
var buf bytes.Buffer
restore := log.Logger