-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathcli_test.go
More file actions
3418 lines (2911 loc) · 96.8 KB
/
Copy pathcli_test.go
File metadata and controls
3418 lines (2911 loc) · 96.8 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
// PARALLEL SAFETY: Tests in this file MUST NOT use t.Parallel().
// They mutate process-global state: os.Chdir (working directory),
// os.Stdout (for output capture), and logger (for log assertions).
// Running these tests in parallel would cause data races and flaky failures.
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/charmbracelet/log"
"github.com/unbound-force/dewey/v3/client"
"github.com/unbound-force/dewey/v3/source"
"github.com/unbound-force/dewey/v3/store"
"github.com/unbound-force/dewey/v3/types"
"github.com/unbound-force/dewey/v3/vault"
)
// TestRootCmd_Version verifies the root command reports the correct version.
func TestRootCmd_Version(t *testing.T) {
cmd := newRootCmd()
buf := new(bytes.Buffer)
cmd.SetOut(buf)
cmd.SetArgs([]string{"version"})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute(version) failed: %v", err)
}
got := strings.TrimSpace(buf.String())
if got != version {
t.Errorf("version output = %q, want %q", got, version)
}
}
// TestRootCmd_VersionSubcommand verifies `dewey version` subcommand works.
// NOTE: --version flag was removed to avoid conflict with --verbose/-v.
// Version is available via the `dewey version` subcommand.
func TestRootCmd_VersionSubcommand(t *testing.T) {
cmd := newRootCmd()
buf := new(bytes.Buffer)
cmd.SetOut(buf)
cmd.SetArgs([]string{"version"})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute(version) failed: %v", err)
}
got := strings.TrimSpace(buf.String())
if !strings.Contains(got, version) {
t.Errorf("version output = %q, should contain %q", got, version)
}
}
// TestRootCmd_Help verifies the root command produces help output.
func TestRootCmd_Help(t *testing.T) {
cmd := newRootCmd()
buf := new(bytes.Buffer)
cmd.SetOut(buf)
cmd.SetErr(buf)
cmd.SetArgs([]string{"--help"})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute(--help) failed: %v", err)
}
got := buf.String()
// Verify key subcommands are listed in help.
for _, sub := range []string{"serve", "journal", "add", "search", "version"} {
if !strings.Contains(got, sub) {
t.Errorf("help output missing subcommand %q", sub)
}
}
}
// TestServeCmd_HasFlags verifies the serve subcommand has all expected flags.
func TestServeCmd_HasFlags(t *testing.T) {
cmd := newServeCmd()
expectedFlags := []string{"read-only", "backend", "vault", "daily-folder", "http"}
for _, name := range expectedFlags {
if cmd.Flags().Lookup(name) == nil {
t.Errorf("serve command missing flag --%s", name)
}
}
}
// TestJournalCmd_HasFlags verifies the journal subcommand has expected flags.
func TestJournalCmd_HasFlags(t *testing.T) {
cmd := newJournalCmd()
if cmd.Flags().Lookup("date") == nil {
t.Error("journal command missing flag --date")
}
// Verify short flag -d exists.
if cmd.Flags().ShorthandLookup("d") == nil {
t.Error("journal command missing short flag -d")
}
}
// TestAddCmd_HasFlags verifies the add subcommand has expected flags.
func TestAddCmd_HasFlags(t *testing.T) {
cmd := newAddCmd()
if cmd.Flags().Lookup("page") == nil {
t.Error("add command missing flag --page")
}
// Verify short flag -p exists.
if cmd.Flags().ShorthandLookup("p") == nil {
t.Error("add command missing short flag -p")
}
}
// TestSearchCmd_HasFlags verifies the search subcommand has expected flags.
func TestSearchCmd_HasFlags(t *testing.T) {
cmd := newSearchCmd()
if cmd.Flags().Lookup("limit") == nil {
t.Error("search command missing flag --limit")
}
}
// TestSearchCmd_NoQuery verifies search fails without a query.
func TestSearchCmd_NoQuery(t *testing.T) {
cmd := newSearchCmd()
cmd.SetArgs([]string{})
err := cmd.Execute()
if err == nil {
t.Fatal("search with no query should fail")
}
if !strings.Contains(err.Error(), "query is required") {
t.Errorf("error = %q, want to contain 'query is required'", err.Error())
}
}
// TestAddCmd_NoPage verifies add fails without --page.
func TestAddCmd_NoPage(t *testing.T) {
cmd := newAddCmd()
cmd.SetArgs([]string{"some content"})
err := cmd.Execute()
if err == nil {
t.Fatal("add without --page should fail")
}
if !strings.Contains(err.Error(), "--page is required") {
t.Errorf("error = %q, want to contain '--page is required'", err.Error())
}
}
// TestRootCmd_UnknownSubcommand verifies unknown subcommands produce an error.
func TestRootCmd_UnknownSubcommand(t *testing.T) {
cmd := newRootCmd()
cmd.SetArgs([]string{"nonexistent"})
err := cmd.Execute()
if err == nil {
t.Fatal("unknown subcommand should fail")
}
}
// TestOrdinalDate_Formats verifies the ordinal date formatting helper.
func TestOrdinalDate_Formats(t *testing.T) {
tests := []struct {
name string
date string
want string
}{
{"1st", "2026-01-01", "Jan 1st, 2026"},
{"2nd", "2026-01-02", "Jan 2nd, 2026"},
{"3rd", "2026-01-03", "Jan 3rd, 2026"},
{"4th", "2026-01-04", "Jan 4th, 2026"},
{"11th", "2026-01-11", "Jan 11th, 2026"},
{"21st", "2026-01-21", "Jan 21st, 2026"},
{"22nd", "2026-01-22", "Jan 22nd, 2026"},
{"23rd", "2026-01-23", "Jan 23rd, 2026"},
{"31st", "2026-01-31", "Jan 31st, 2026"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
parsed, err := time.Parse("2006-01-02", tt.date)
if err != nil {
t.Fatalf("parse date %q: %v", tt.date, err)
}
got := ordinalDate(parsed)
if got != tt.want {
t.Errorf("ordinalDate(%s) = %q, want %q", tt.date, got, tt.want)
}
})
}
}
// TestReadContentFromArgs_WithArgs verifies content reading from positional args.
func TestReadContentFromArgs_WithArgs(t *testing.T) {
got := readContentFromArgs([]string{"hello", "world"})
if got != "hello world" {
t.Errorf("readContentFromArgs = %q, want %q", got, "hello world")
}
}
// TestReadContentFromArgs_Empty verifies empty args returns empty string.
func TestReadContentFromArgs_Empty(t *testing.T) {
got := readContentFromArgs(nil)
// When stdin is a terminal (not piped), should return empty.
// In test context, stdin behavior varies, so we just verify no panic.
_ = got
}
// --- Init command tests ---
// TestInitCmd_CreatesDirectory verifies dewey init creates .uf/dewey/ directory.
func TestInitCmd_CreatesDirectory(t *testing.T) {
tmpDir := t.TempDir()
cmd := newInitCmd()
cmd.SetArgs([]string{"--vault", tmpDir})
if err := cmd.Execute(); err != nil {
t.Fatalf("init failed: %v", err)
}
deweyDir := filepath.Join(tmpDir, deweyWorkspaceDir)
if _, err := os.Stat(deweyDir); os.IsNotExist(err) {
t.Fatal(".uf/dewey/ directory was not created")
}
}
// TestInitCmd_DefaultConfig verifies config.yaml has expected content.
func TestInitCmd_DefaultConfig(t *testing.T) {
tmpDir := t.TempDir()
cmd := newInitCmd()
cmd.SetArgs([]string{"--vault", tmpDir})
if err := cmd.Execute(); err != nil {
t.Fatalf("init failed: %v", err)
}
configPath := filepath.Join(tmpDir, deweyWorkspaceDir, "config.yaml")
content, err := os.ReadFile(configPath)
if err != nil {
t.Fatalf("read config.yaml: %v", err)
}
configStr := string(content)
if !strings.Contains(configStr, "granite-embedding:30m") {
t.Error("config.yaml should contain default embedding model")
}
if !strings.Contains(configStr, "embedding") {
t.Error("config.yaml should contain embedding section")
}
}
// TestInitCmd_DefaultSources verifies sources.yaml has expected content.
func TestInitCmd_DefaultSources(t *testing.T) {
tmpDir := t.TempDir()
cmd := newInitCmd()
cmd.SetArgs([]string{"--vault", tmpDir})
if err := cmd.Execute(); err != nil {
t.Fatalf("init failed: %v", err)
}
sourcesPath := filepath.Join(tmpDir, deweyWorkspaceDir, "sources.yaml")
content, err := os.ReadFile(sourcesPath)
if err != nil {
t.Fatalf("read sources.yaml: %v", err)
}
sourcesStr := string(content)
if !strings.Contains(sourcesStr, "disk-local") {
t.Error("sources.yaml should contain disk-local source")
}
if !strings.Contains(sourcesStr, "type: disk") {
t.Error("sources.yaml should contain type: disk")
}
}
// TestInitCmd_Idempotent verifies running init twice does not error.
func TestInitCmd_Idempotent(t *testing.T) {
tmpDir := t.TempDir()
// First init.
cmd1 := newInitCmd()
cmd1.SetArgs([]string{"--vault", tmpDir})
if err := cmd1.Execute(); err != nil {
t.Fatalf("first init failed: %v", err)
}
// Second init should succeed (idempotent).
cmd2 := newInitCmd()
cmd2.SetArgs([]string{"--vault", tmpDir})
if err := cmd2.Execute(); err != nil {
t.Fatalf("second init should not fail: %v", err)
}
}
// TestInitCmd_GitignoreAppend verifies granular .uf/dewey/ patterns are added to .gitignore.
func TestInitCmd_GitignoreAppend(t *testing.T) {
tmpDir := t.TempDir()
// Create a .gitignore without any dewey patterns.
gitignorePath := filepath.Join(tmpDir, ".gitignore")
if err := os.WriteFile(gitignorePath, []byte("node_modules/\n"), 0o644); err != nil {
t.Fatalf("write .gitignore: %v", err)
}
cmd := newInitCmd()
cmd.SetArgs([]string{"--vault", tmpDir})
if err := cmd.Execute(); err != nil {
t.Fatalf("init failed: %v", err)
}
content, err := os.ReadFile(gitignorePath)
if err != nil {
t.Fatalf("read .gitignore: %v", err)
}
text := string(content)
// Verify granular runtime artifact patterns.
for _, pattern := range []string{".uf/dewey/graph.db", ".uf/dewey/graph.db-shm", ".uf/dewey/graph.db-wal", ".uf/dewey/dewey.log", ".uf/dewey/dewey.lock"} {
if !strings.Contains(text, pattern) {
t.Errorf(".gitignore should contain %q, got:\n%s", pattern, text)
}
}
// Verify the blanket .uf/dewey/ is NOT written.
// Check that ".uf/dewey/" only appears as part of the granular patterns, not standalone.
lines := strings.Split(text, "\n")
for _, line := range lines {
if strings.TrimSpace(line) == ".uf/dewey/" {
t.Errorf(".gitignore should NOT contain blanket '.uf/dewey/', got:\n%s", text)
}
}
}
// TestInitCmd_GitignoreAlreadyPresent verifies granular patterns are not duplicated.
func TestInitCmd_GitignoreAlreadyPresent(t *testing.T) {
tmpDir := t.TempDir()
// Create a .gitignore that already has the new granular patterns.
gitignorePath := filepath.Join(tmpDir, ".gitignore")
existing := ".uf/dewey/graph.db\n.uf/dewey/graph.db-shm\n.uf/dewey/graph.db-wal\n.uf/dewey/dewey.log\n.uf/dewey/dewey.lock\n"
if err := os.WriteFile(gitignorePath, []byte(existing), 0o644); err != nil {
t.Fatalf("write .gitignore: %v", err)
}
cmd := newInitCmd()
cmd.SetArgs([]string{"--vault", tmpDir})
if err := cmd.Execute(); err != nil {
t.Fatalf("init failed: %v", err)
}
content, err := os.ReadFile(gitignorePath)
if err != nil {
t.Fatalf("read .gitignore: %v", err)
}
// Count occurrences of the key pattern — should be exactly 1 (no duplicate).
count := strings.Count(string(content), ".uf/dewey/graph.db\n")
if count != 1 {
t.Errorf(".uf/dewey/graph.db appears %d times in .gitignore, want 1", count)
}
}
// TestInitCmd_GitignoreLegacyPattern verifies that the old .dewey/ pattern
// is preserved and an informational message is logged.
func TestInitCmd_GitignoreLegacyPattern(t *testing.T) {
tmpDir := t.TempDir()
// Create a .gitignore with the legacy blanket pattern.
gitignorePath := filepath.Join(tmpDir, ".gitignore")
if err := os.WriteFile(gitignorePath, []byte(".dewey/\n"), 0o644); err != nil {
t.Fatalf("write .gitignore: %v", err)
}
cmd := newInitCmd()
cmd.SetArgs([]string{"--vault", tmpDir})
if err := cmd.Execute(); err != nil {
t.Fatalf("init failed: %v", err)
}
content, err := os.ReadFile(gitignorePath)
if err != nil {
t.Fatalf("read .gitignore: %v", err)
}
text := string(content)
// Legacy pattern should be preserved — not modified.
if !strings.Contains(text, ".dewey/\n") {
t.Errorf("legacy .dewey/ pattern should be preserved, got:\n%s", text)
}
// New .uf/dewey/ patterns should NOT be added alongside legacy.
if strings.Contains(text, ".uf/dewey/graph.db") {
t.Errorf("granular patterns should NOT be added when legacy pattern exists, got:\n%s", text)
}
}
// TestInitCmd_ScaffoldsSlashCommands verifies that dewey init creates
// slash command files in .opencode/command/ when .opencode/ exists.
func TestInitCmd_ScaffoldsSlashCommands(t *testing.T) {
tmpDir := t.TempDir()
// Create .opencode/ directory (simulating an OpenCode-initialized repo).
if err := os.MkdirAll(filepath.Join(tmpDir, ".opencode"), 0o755); err != nil {
t.Fatalf("create .opencode: %v", err)
}
// Create .gitignore so init doesn't error.
if err := os.WriteFile(filepath.Join(tmpDir, ".gitignore"), []byte(""), 0o644); err != nil {
t.Fatalf("write .gitignore: %v", err)
}
cmd := newInitCmd()
cmd.SetArgs([]string{"--vault", tmpDir})
if err := cmd.Execute(); err != nil {
t.Fatalf("init failed: %v", err)
}
// Verify all 5 Dewey slash commands were scaffolded.
for _, name := range []string{"dewey-store.md", "dewey-index.md", "dewey-reindex.md", "dewey-compile.md", "dewey-lint.md"} {
path := filepath.Join(tmpDir, ".opencode", "command", name)
if _, err := os.Stat(path); err != nil {
t.Errorf("slash command %s was not scaffolded", name)
}
}
}
// TestInitCmd_SkipsExistingSlashCommands verifies that dewey init does
// not overwrite existing slash command files (preserves user customizations).
func TestInitCmd_SkipsExistingSlashCommands(t *testing.T) {
tmpDir := t.TempDir()
// Create .opencode/command/ with a custom dewey-store.md.
cmdDir := filepath.Join(tmpDir, ".opencode", "command")
if err := os.MkdirAll(cmdDir, 0o755); err != nil {
t.Fatalf("create command dir: %v", err)
}
customContent := "# My custom dewey-store command\n"
if err := os.WriteFile(filepath.Join(cmdDir, "dewey-store.md"), []byte(customContent), 0o644); err != nil {
t.Fatalf("write custom command: %v", err)
}
if err := os.WriteFile(filepath.Join(tmpDir, ".gitignore"), []byte(""), 0o644); err != nil {
t.Fatalf("write .gitignore: %v", err)
}
cmd := newInitCmd()
cmd.SetArgs([]string{"--vault", tmpDir})
if err := cmd.Execute(); err != nil {
t.Fatalf("init failed: %v", err)
}
// Verify custom content was preserved (not overwritten).
content, err := os.ReadFile(filepath.Join(cmdDir, "dewey-store.md"))
if err != nil {
t.Fatalf("read command: %v", err)
}
if string(content) != customContent {
t.Errorf("dewey-store.md was overwritten, got:\n%s", string(content))
}
// Other commands should still be scaffolded.
if _, err := os.Stat(filepath.Join(cmdDir, "dewey-index.md")); err != nil {
t.Error("dewey-index.md should have been scaffolded (it didn't exist)")
}
}
// TestInitCmd_NoOpenCodeDir verifies that dewey init gracefully skips
// slash command scaffolding when .opencode/ doesn't exist.
func TestInitCmd_NoOpenCodeDir(t *testing.T) {
tmpDir := t.TempDir()
if err := os.WriteFile(filepath.Join(tmpDir, ".gitignore"), []byte(""), 0o644); err != nil {
t.Fatalf("write .gitignore: %v", err)
}
cmd := newInitCmd()
cmd.SetArgs([]string{"--vault", tmpDir})
if err := cmd.Execute(); err != nil {
t.Fatalf("init failed: %v", err)
}
// Verify no .opencode/command/ directory was created.
if _, err := os.Stat(filepath.Join(tmpDir, ".opencode", "command")); err == nil {
t.Error(".opencode/command/ should NOT exist when .opencode/ was not present")
}
}
// TestInitCmd_ReInitScaffoldsNewCommands verifies that running dewey init
// on an already-initialized repo still scaffolds missing slash commands.
func TestInitCmd_ReInitScaffoldsNewCommands(t *testing.T) {
tmpDir := t.TempDir()
// Create .opencode/ and .gitignore.
if err := os.MkdirAll(filepath.Join(tmpDir, ".opencode"), 0o755); err != nil {
t.Fatalf("create .opencode: %v", err)
}
if err := os.WriteFile(filepath.Join(tmpDir, ".gitignore"), []byte(""), 0o644); err != nil {
t.Fatalf("write .gitignore: %v", err)
}
// First init — creates everything.
cmd := newInitCmd()
cmd.SetArgs([]string{"--vault", tmpDir})
if err := cmd.Execute(); err != nil {
t.Fatalf("first init failed: %v", err)
}
// Verify slash commands were created.
storePath := filepath.Join(tmpDir, ".opencode", "command", "dewey-store.md")
if _, err := os.Stat(storePath); err != nil {
t.Fatalf("dewey-store.md not created on first init")
}
// Delete one slash command to simulate upgrading dewey with a new command.
if err := os.Remove(storePath); err != nil {
t.Fatalf("remove dewey-store.md: %v", err)
}
// Second init — should re-scaffold the deleted command.
cmd2 := newInitCmd()
cmd2.SetArgs([]string{"--vault", tmpDir})
if err := cmd2.Execute(); err != nil {
t.Fatalf("second init failed: %v", err)
}
// Verify the deleted command was re-scaffolded.
if _, err := os.Stat(storePath); err != nil {
t.Error("dewey-store.md should have been re-scaffolded on second init")
}
}
// --- Status command tests ---
// TestStatusCmd_Uninitialized verifies status fails when .uf/dewey/ doesn't exist.
func TestStatusCmd_Uninitialized(t *testing.T) {
tmpDir := t.TempDir()
// Change to temp dir for the status command.
oldDir, _ := os.Getwd()
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("chdir: %v", err)
}
defer func() { _ = os.Chdir(oldDir) }()
cmd := newStatusCmd()
err := cmd.Execute()
if err == nil {
t.Fatal("status should fail when not initialized")
}
if !strings.Contains(err.Error(), "not initialized") {
t.Errorf("error = %q, want to contain 'not initialized'", err.Error())
}
}
// TestStatusCmd_TextOutput verifies human-readable status output.
func TestStatusCmd_TextOutput(t *testing.T) {
tmpDir := t.TempDir()
// Initialize.
deweyDir := filepath.Join(tmpDir, deweyWorkspaceDir)
if err := os.MkdirAll(deweyDir, 0o755); err != nil {
t.Fatalf("mkdir: %v", err)
}
oldDir, _ := os.Getwd()
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("chdir: %v", err)
}
defer func() { _ = os.Chdir(oldDir) }()
cmd := newStatusCmd()
buf := new(bytes.Buffer)
cmd.SetOut(buf)
if err := cmd.Execute(); err != nil {
t.Fatalf("status failed: %v", err)
}
output := buf.String()
if !strings.Contains(output, "Dewey Index Status") {
t.Error("status output should contain 'Dewey Index Status'")
}
if !strings.Contains(output, "Pages:") {
t.Error("status output should contain 'Pages:'")
}
if !strings.Contains(output, "Blocks:") {
t.Error("status output should contain 'Blocks:'")
}
}
// TestStatusCmd_JSONOutput verifies JSON status output.
func TestStatusCmd_JSONOutput(t *testing.T) {
tmpDir := t.TempDir()
// Initialize.
deweyDir := filepath.Join(tmpDir, deweyWorkspaceDir)
if err := os.MkdirAll(deweyDir, 0o755); err != nil {
t.Fatalf("mkdir: %v", err)
}
oldDir, _ := os.Getwd()
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("chdir: %v", err)
}
defer func() { _ = os.Chdir(oldDir) }()
cmd := newStatusCmd()
buf := new(bytes.Buffer)
cmd.SetOut(buf)
cmd.SetArgs([]string{"--json"})
if err := cmd.Execute(); err != nil {
t.Fatalf("status --json failed: %v", err)
}
var result map[string]any
if err := json.Unmarshal(buf.Bytes(), &result); err != nil {
t.Fatalf("invalid JSON output: %v\noutput: %s", err, buf.String())
}
// Verify expected fields.
if _, ok := result["pages"]; !ok {
t.Error("JSON output missing 'pages' field")
}
if _, ok := result["blocks"]; !ok {
t.Error("JSON output missing 'blocks' field")
}
if _, ok := result["path"]; !ok {
t.Error("JSON output missing 'path' field")
}
}
// TestInitCmd_HasFlags verifies the init subcommand has expected flags.
func TestInitCmd_HasFlags(t *testing.T) {
cmd := newInitCmd()
if cmd.Flags().Lookup("vault") == nil {
t.Error("init command missing flag --vault")
}
}
// TestStatusCmd_HasFlags verifies the status subcommand has expected flags.
func TestStatusCmd_HasFlags(t *testing.T) {
cmd := newStatusCmd()
if cmd.Flags().Lookup("json") == nil {
t.Error("status command missing flag --json")
}
}
// TestRootCmd_Help_IncludesNewSubcommands verifies init and status appear in help.
func TestRootCmd_Help_IncludesNewSubcommands(t *testing.T) {
cmd := newRootCmd()
buf := new(bytes.Buffer)
cmd.SetOut(buf)
cmd.SetErr(buf)
cmd.SetArgs([]string{"--help"})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute(--help) failed: %v", err)
}
got := buf.String()
for _, sub := range []string{"init", "status", "index", "source"} {
if !strings.Contains(got, sub) {
t.Errorf("help output missing subcommand %q", sub)
}
}
}
// --- Index command tests (T058B) ---
// TestIndexCmd_Uninitialized verifies index fails when .uf/dewey/ doesn't exist.
func TestIndexCmd_Uninitialized(t *testing.T) {
tmpDir := t.TempDir()
oldDir, _ := os.Getwd()
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("chdir: %v", err)
}
defer func() { _ = os.Chdir(oldDir) }()
cmd := newIndexCmd()
err := cmd.Execute()
if err == nil {
t.Fatal("index should fail when not initialized")
}
if !strings.Contains(err.Error(), "not initialized") {
t.Errorf("error = %q, want to contain 'not initialized'", err.Error())
}
}
// TestIndexCmd_HasFlags verifies the index subcommand has expected flags.
func TestIndexCmd_HasFlags(t *testing.T) {
cmd := newIndexCmd()
if cmd.Flags().Lookup("source") == nil {
t.Error("index command missing flag --source")
}
if cmd.Flags().Lookup("force") == nil {
t.Error("index command missing flag --force")
}
}
// TestIndexCmd_WithDiskSource verifies indexing with a disk source.
func TestIndexCmd_WithDiskSource(t *testing.T) {
tmpDir := t.TempDir()
// Create .uf/dewey/ with sources.yaml.
deweyDir := filepath.Join(tmpDir, deweyWorkspaceDir)
if err := os.MkdirAll(deweyDir, 0o755); err != nil {
t.Fatalf("mkdir: %v", err)
}
sourcesContent := `sources:
- id: disk-local
type: disk
name: local
config:
path: "` + tmpDir + `"
`
if err := os.WriteFile(filepath.Join(deweyDir, "sources.yaml"), []byte(sourcesContent), 0o644); err != nil {
t.Fatalf("write sources.yaml: %v", err)
}
// Create a test .md file.
if err := os.WriteFile(filepath.Join(tmpDir, "test.md"), []byte("# Test\nContent"), 0o644); err != nil {
t.Fatalf("write test.md: %v", err)
}
oldDir, _ := os.Getwd()
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("chdir: %v", err)
}
defer func() { _ = os.Chdir(oldDir) }()
cmd := newIndexCmd()
// Pass --no-embeddings because Ollama is not running in test env.
cmd.SetArgs([]string{"--no-embeddings"})
if err := cmd.Execute(); err != nil {
t.Fatalf("index failed: %v", err)
}
}
// --- Source add command tests (T058B) ---
// TestSourceAddCmd_Uninitialized verifies source add fails when not initialized.
func TestSourceAddCmd_Uninitialized(t *testing.T) {
tmpDir := t.TempDir()
oldDir, _ := os.Getwd()
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("chdir: %v", err)
}
defer func() { _ = os.Chdir(oldDir) }()
cmd := newSourceCmd()
cmd.SetArgs([]string{"add", "github", "--org", "test", "--repos", "repo1"})
err := cmd.Execute()
if err == nil {
t.Fatal("source add should fail when not initialized")
}
if !strings.Contains(err.Error(), "not initialized") {
t.Errorf("error = %q, want to contain 'not initialized'", err.Error())
}
}
// TestSourceAddCmd_GitHub verifies adding a GitHub source.
func TestSourceAddCmd_GitHub(t *testing.T) {
tmpDir := t.TempDir()
// Initialize.
deweyDir := filepath.Join(tmpDir, deweyWorkspaceDir)
if err := os.MkdirAll(deweyDir, 0o755); err != nil {
t.Fatalf("mkdir: %v", err)
}
sourcesContent := `sources:
- id: disk-local
type: disk
name: local
config:
path: "."
`
if err := os.WriteFile(filepath.Join(deweyDir, "sources.yaml"), []byte(sourcesContent), 0o644); err != nil {
t.Fatalf("write sources.yaml: %v", err)
}
oldDir, _ := os.Getwd()
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("chdir: %v", err)
}
defer func() { _ = os.Chdir(oldDir) }()
cmd := newSourceCmd()
cmd.SetArgs([]string{"add", "github", "--org", "unbound-force", "--repos", "gaze,website"})
if err := cmd.Execute(); err != nil {
t.Fatalf("source add github failed: %v", err)
}
// Verify source was added to sources.yaml.
content, _ := os.ReadFile(filepath.Join(deweyDir, "sources.yaml"))
if !strings.Contains(string(content), "github-unbound-force") {
t.Error("sources.yaml should contain github-unbound-force")
}
}
// TestSourceAddCmd_Web verifies adding a web source.
func TestSourceAddCmd_Web(t *testing.T) {
tmpDir := t.TempDir()
deweyDir := filepath.Join(tmpDir, deweyWorkspaceDir)
if err := os.MkdirAll(deweyDir, 0o755); err != nil {
t.Fatalf("mkdir: %v", err)
}
sourcesContent := `sources:
- id: disk-local
type: disk
name: local
config:
path: "."
`
if err := os.WriteFile(filepath.Join(deweyDir, "sources.yaml"), []byte(sourcesContent), 0o644); err != nil {
t.Fatalf("write sources.yaml: %v", err)
}
oldDir, _ := os.Getwd()
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("chdir: %v", err)
}
defer func() { _ = os.Chdir(oldDir) }()
cmd := newSourceCmd()
cmd.SetArgs([]string{"add", "web", "--url", "https://pkg.go.dev/std", "--name", "go-stdlib"})
if err := cmd.Execute(); err != nil {
t.Fatalf("source add web failed: %v", err)
}
content, _ := os.ReadFile(filepath.Join(deweyDir, "sources.yaml"))
if !strings.Contains(string(content), "web-go-stdlib") {
t.Error("sources.yaml should contain web-go-stdlib")
}
}
// TestSourceAddCmd_DuplicateRejection verifies duplicate source rejection.
func TestSourceAddCmd_DuplicateRejection(t *testing.T) {
tmpDir := t.TempDir()
deweyDir := filepath.Join(tmpDir, deweyWorkspaceDir)
if err := os.MkdirAll(deweyDir, 0o755); err != nil {
t.Fatalf("mkdir: %v", err)
}
sourcesContent := `sources:
- id: disk-local
type: disk
name: local
config:
path: "."
- id: github-test
type: github
name: test
config:
org: test
repos:
- repo1
`
if err := os.WriteFile(filepath.Join(deweyDir, "sources.yaml"), []byte(sourcesContent), 0o644); err != nil {
t.Fatalf("write sources.yaml: %v", err)
}
oldDir, _ := os.Getwd()
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("chdir: %v", err)
}
defer func() { _ = os.Chdir(oldDir) }()
cmd := newSourceCmd()
cmd.SetArgs([]string{"add", "github", "--org", "test", "--repos", "repo1"})
err := cmd.Execute()
if err == nil {
t.Fatal("should reject duplicate source")
}
if !strings.Contains(err.Error(), "already exists") {
t.Errorf("error = %q, want to contain 'already exists'", err.Error())
}
}
// TestSourceAddCmd_InvalidType verifies unknown source type rejection.
func TestSourceAddCmd_InvalidType(t *testing.T) {
tmpDir := t.TempDir()
deweyDir := filepath.Join(tmpDir, deweyWorkspaceDir)
if err := os.MkdirAll(deweyDir, 0o755); err != nil {
t.Fatalf("mkdir: %v", err)
}
if err := os.WriteFile(filepath.Join(deweyDir, "sources.yaml"), []byte("sources: []\n"), 0o644); err != nil {
t.Fatalf("write sources.yaml: %v", err)
}
oldDir, _ := os.Getwd()
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("chdir: %v", err)
}
defer func() { _ = os.Chdir(oldDir) }()
cmd := newSourceCmd()
cmd.SetArgs([]string{"add", "ftp"})
err := cmd.Execute()
if err == nil {
t.Fatal("should reject unknown source type")
}
}
// TestFormatDuration verifies the duration formatting helper.
func TestFormatDuration(t *testing.T) {
tests := []struct {
d time.Duration
want string
}{
{30 * time.Second, "30s"},
{5 * time.Minute, "5m"},
{4 * time.Hour, "4h"},
{3 * 24 * time.Hour, "3d"},
}
for _, tt := range tests {
got := formatDuration(tt.d)
if got != tt.want {
t.Errorf("formatDuration(%v) = %q, want %q", tt.d, got, tt.want)
}
}
}
// --- findJournalPage tests (T020) ---
// newTestLogseqServer creates an httptest server that simulates the Logseq API.
// pageNames is the set of page names that exist. GetPage returns a result for
// any name in the set; other names get a null response.
func newTestLogseqServer(t *testing.T, pageNames map[string]bool) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req struct {
Method string `json:"method"`
Args []any `json:"args"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
switch req.Method {
case "logseq.Editor.getPage":
if len(req.Args) > 0 {
name := fmt.Sprintf("%v", req.Args[0])
if pageNames[name] {
_ = json.NewEncoder(w).Encode(map[string]any{
"name": name,
"uuid": "page-uuid",
"id": 1,
})
return
}
}
// Page not found — Logseq returns null.
_, _ = w.Write([]byte("null"))
case "logseq.App.getCurrentGraph":
// Return a graph at a temp path — tests override this if needed.
_ = json.NewEncoder(w).Encode(map[string]any{
"name": "test-graph",
"path": t.TempDir(),
})
default:
_, _ = w.Write([]byte("null"))
}
}))
}
// TestFindJournalPage_OrdinalFormat verifies findJournalPage returns the
// ordinal date format name when that page exists.
func TestFindJournalPage_OrdinalFormat(t *testing.T) {
date := time.Date(2026, 1, 29, 0, 0, 0, 0, time.UTC)
ordinal := ordinalDate(date) // "Jan 29th, 2026"
srv := newTestLogseqServer(t, map[string]bool{ordinal: true})
defer srv.Close()
c := client.New(srv.URL, "")
ctx := context.Background()
got := findJournalPage(ctx, c, date)
if got != ordinal {
t.Errorf("findJournalPage() = %q, want %q", got, ordinal)
}