-
-
Notifications
You must be signed in to change notification settings - Fork 335
Expand file tree
/
Copy pathregression_test.go
More file actions
634 lines (590 loc) · 26.7 KB
/
Copy pathregression_test.go
File metadata and controls
634 lines (590 loc) · 26.7 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
// SPDX-License-Identifier: MIT
package main
import (
"bytes"
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/spf13/pflag"
)
// The tests in this file guard against regressions to pre-existing behaviour
// introduced by the config-dotfile work (spec/01-config-dotfile). They focus on
// functionality that existed before the feature and could have been silently
// changed by the registerFlags refactor, the shared @file tokenizer and the
// config discovery/merge pipeline - cases the feature's own tests do not cover.
//
// They run with noGlobalConfig (defined in config_test.go) so a SCC_CONFIG_PATH
// in the developer's environment cannot pollute the results.
// TestRegressionExcludeDirPreservesDefaults exercises the phase-02 slice-default
// change on the ordinary no-config CLI path (the ~99% case). pflag replaces a
// slice's default on the first Set, so before this work `--exclude-dir vendor`
// dropped the built-in .git/.hg/.svn and scc descended into them. The post-parse
// union must keep the defaults as a non-removable safety net. .svn is the canary:
// nothing else skips it, so if preservation breaks it reappears in the output.
func TestRegressionExcludeDirPreservesDefaults(t *testing.T) {
dir := t.TempDir()
layout := map[string]string{".svn": "x.go", "vendor": "y.go", "keep": "z.go"}
for sub, file := range layout {
if err := os.Mkdir(filepath.Join(dir, sub), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, sub, file), []byte("package x\n"), 0644); err != nil {
t.Fatal(err)
}
}
out, err := runSCCDir(t, dir, noGlobalConfig, "-f", "csv", "--by-file", "--exclude-dir", "vendor")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(out, "z.go") {
t.Errorf("keep/z.go should be counted, output:\n%s", out)
}
if strings.Contains(out, "y.go") {
t.Errorf("vendor/y.go should be excluded by --exclude-dir, output:\n%s", out)
}
if strings.Contains(out, "x.go") {
t.Errorf(".svn/x.go reappeared: a CLI --exclude-dir must not replace the built-in defaults (union, not replace), output:\n%s", out)
}
}
// TestRegressionExcludeFilePreservesDefaults is the --exclude-file counterpart of
// the above: adding one ignored filename on the CLI must not drop the built-in
// lockfile defaults. package-lock.json is the canary - before the fix pflag's
// replace-on-first-Set would have let it through.
func TestRegressionExcludeFilePreservesDefaults(t *testing.T) {
dir := t.TempDir()
files := map[string]string{
"main.go": "package main\n",
"package-lock.json": "{\"a\":1}\n",
"myignore.txt": "hello\n",
}
for name, body := range files {
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0644); err != nil {
t.Fatal(err)
}
}
out, err := runSCCDir(t, dir, noGlobalConfig, "-f", "csv", "--by-file", "--exclude-file", "myignore.txt")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(out, "main.go") {
t.Errorf("main.go should be counted, output:\n%s", out)
}
if strings.Contains(out, "myignore.txt") {
t.Errorf("myignore.txt should be excluded by --exclude-file, output:\n%s", out)
}
if strings.Contains(out, "package-lock.json") {
t.Errorf("package-lock.json reappeared: a CLI --exclude-file must not replace the built-in lockfile defaults, output:\n%s", out)
}
}
// TestRegressionGeneratedMarkersPreservesDefaults is the --generated-markers
// counterpart of the exclude-dir/exclude-file default-preservation tests above -
// the third (and easiest-to-miss) StringSlice flag with a non-empty built-in
// default. Supplying a custom marker on the CLI must not replace the built-in
// "do not edit" / "<auto-generated />" markers (pflag's replace-on-first-Set),
// so a file carrying only a default marker must still be flagged generated.
// examples/generated/test.h ("DO NOT EDIT") and test.cs ("<auto-generated />")
// are the canaries: both should remain "(gen)" despite the custom marker.
func TestRegressionGeneratedMarkersPreservesDefaults(t *testing.T) {
t.Parallel()
out, err := runSCC("-z", "--generated-markers", "zzz-not-a-real-marker", "--no-scc-ignore", "examples/generated/")
if err != nil {
t.Fatal(err)
}
if strings.Count(out, "(gen)") < 2 {
t.Errorf("a custom --generated-markers must not drop the built-in default markers; both example files should still be flagged (gen), output:\n%s", out)
}
}
// TestRegressionConfigWithPositionalDir guards the merged argument ordering: a
// positional path must still be scanned when a project .sccconfig is present. Config
// tokens are prepended and the genuine CLI (including the path) comes last, so
// cobra must still receive the path as a positional. The .sccconfig sets --by-file, so
// the per-file row for the scanned path proves both that config applied and that
// the positional argument survived the prepend.
func TestRegressionConfigWithPositionalDir(t *testing.T) {
dir := t.TempDir()
if err := os.Mkdir(filepath.Join(dir, "code"), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "code", "a.go"), []byte("package a\n"), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, ".sccconfig"), []byte("--by-file\n"), 0644); err != nil {
t.Fatal(err)
}
out, err := runSCCDir(t, dir, noGlobalConfig, "-f", "csv", "code")
if err != nil {
t.Fatal(err)
}
// a.go only appears in --by-file output, so its presence proves both the
// config (--by-file) applied and the positional 'code' dir was scanned.
if !strings.Contains(out, "a.go") {
t.Errorf("positional 'code' dir should be scanned with a project .sccconfig present, output:\n%s", out)
}
}
// TestRegressionAtFileCommentsAndMultiToken confirms the shared tokenizer's new
// capabilities reach the existing @file syntax: multiple tokens per line, plus
// whole-line and inline '#' comments. Under the old whole-line splitter "-f csv"
// was a single unknown token and "main.go # x" an unreadable path, so this both
// proves the improvement and pins the new @file contract.
func TestRegressionAtFileCommentsAndMultiToken(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte("package main\n"), 0644); err != nil {
t.Fatal(err)
}
atFile := filepath.Join(dir, "flags.txt")
content := "# count the project\n\n-f csv\n--by-file\nmain.go # the entrypoint\n"
if err := os.WriteFile(atFile, []byte(content), 0644); err != nil {
t.Fatal(err)
}
// @file must be the sole argument; the sole-argument trigger is preserved.
out, err := runSCCDir(t, dir, noGlobalConfig, "@"+atFile)
if err != nil {
t.Fatalf("@file errored: %v\n%s", err, out)
}
if strings.Contains(out, "could not be read") {
t.Errorf("inline '#' comment was not stripped from the path line, output:\n%s", out)
}
if !strings.Contains(out, "main.go") {
t.Errorf("@file multi-token (-f csv --by-file) + main.go path not honoured, output:\n%s", out)
}
}
// TestRegressionHelpShowsSliceDefaults guards the user-visible default display.
// The three slice flags are registered with an empty runtime default (to defuse
// pflag's replace-on-first-Set); their "(default ...)" text is restored via
// DefValue. Skipping that restoration would silently drop the signal of what scc
// excludes out of the box, so assert --help still advertises the defaults.
func TestRegressionHelpShowsSliceDefaults(t *testing.T) {
out, err := runSCC("--help")
if err != nil {
t.Fatalf("--help should exit 0: %v\n%s", err, out)
}
wants := []string{
"[.git,.hg,.svn]",
"[package-lock.json,Cargo.lock,yarn.lock,pubspec.lock,Podfile.lock,pnpm-lock.yaml]",
"[do not edit,<auto-generated />]",
}
for _, w := range wants {
if !strings.Contains(out, w) {
t.Errorf("--help should display slice default %q, output:\n%s", w, out)
}
}
}
// TestRegressionCommentOnlyConfigAllowsWrite documents an edge of the security
// model: a .sccconfig that contributes zero tokens (only comments/blanks) must not
// engage the write-blocking config path. With nothing injected there is nothing
// to defend against, so the no-config fast path runs and a CLI -o still writes.
func TestRegressionCommentOnlyConfigAllowsWrite(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte("package main\n"), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, ".sccconfig"), []byte("# just a comment\n\n"), 0644); err != nil {
t.Fatal(err)
}
target := filepath.Join(dir, "out.csv")
if _, err := runSCCDir(t, dir, noGlobalConfig, "-f", "csv", "-o", target); err != nil {
t.Fatal(err)
}
if info, statErr := os.Stat(target); statErr != nil || info.Size() == 0 {
t.Errorf("a comment-only .sccconfig should not block a genuine CLI -o write")
}
}
// TestRegressionShorthandsPreserved guards the phase-02 registerFlags refactor.
// ~60 flag registrations were lifted out of main() into registerFlags; the
// existing exhaustive test only checks long names, so a shorthand silently
// dropped or rebound to the wrong flag during the move would slip through except
// for the handful of shorthands the integration tests happen to exercise. This
// pins the complete shorthand -> long-name map. The config-control flags
// (registered separately by registerConfigControlFlags) carry no shorthand: -r
// is deliberately unbound, reserved for a future find-root that relocates the
// scan directory like cs.
func TestRegressionShorthandsPreserved(t *testing.T) {
t.Parallel()
fs := pflag.NewFlagSet("test", pflag.ContinueOnError)
var out, report, multi string
registerFlags(fs, &flagBindings{output: &out, report: &report, formatMulti: &multi, inert: true})
registerConfigControlFlags(fs)
want := map[string]string{
"m": "character",
"p": "percent",
"u": "uloc",
"a": "dryness",
"f": "format",
"i": "include-ext",
"x": "exclude-ext",
"n": "exclude-file",
"l": "languages",
"c": "no-complexity",
"d": "no-duplicates",
"z": "min-gen",
"M": "not-match",
"o": "output",
"s": "sort",
"t": "trace",
"v": "verbose",
"w": "wide",
}
for short, longName := range want {
f := fs.ShorthandLookup(short)
if f == nil {
t.Errorf("shorthand -%s is not registered (expected --%s)", short, longName)
continue
}
if f.Name != longName {
t.Errorf("shorthand -%s bound to --%s, want --%s", short, f.Name, longName)
}
}
// Inverse guard: no shorthand exists that the map above does not account for,
// so a stray/renamed shorthand introduced by the refactor is also caught.
fs.VisitAll(func(f *pflag.Flag) {
if f.Shorthand == "" {
return
}
if _, ok := want[f.Shorthand]; !ok {
t.Errorf("unexpected shorthand -%s on --%s (not in the locked map)", f.Shorthand, f.Name)
}
})
}
// TestRegressionScalarDefaultsPreserved locks a representative sample of scalar
// flag defaults through the registerFlags refactor (the slice defaults are
// covered by TestRegisterFlagsSliceDefValue). It also pins the three write
// flags' empty defaults and, crucially, the --report NoOptDefVal: runReport
// compares ReportOut to that sentinel to tell a bare --report from --report=path,
// so a refactor that dropped it would silently break the bare-flag form.
func TestRegressionScalarDefaultsPreserved(t *testing.T) {
t.Parallel()
fs := pflag.NewFlagSet("test", pflag.ContinueOnError)
var out, report, multi string
registerFlags(fs, &flagBindings{output: &out, report: &report, formatMulti: &multi, inert: true})
wantDef := map[string]string{
"format": "tabular",
"sort": "files",
"size-unit": "si",
"currency-symbol": "$",
"cocomo-project-type": "organic",
"avg-wage": "56286",
"large-line-count": "40000",
"large-byte-count": "1000000",
"output": "",
"report": "",
"format-multi": "",
}
for name, def := range wantDef {
f := fs.Lookup(name)
if f == nil {
t.Errorf("--%s missing after refactor", name)
continue
}
if f.DefValue != def {
t.Errorf("--%s DefValue = %q, want %q", name, f.DefValue, def)
}
}
if f := fs.Lookup("report"); f == nil || f.NoOptDefVal != processorDefaultReportName() {
got := "<nil flag>"
if f != nil {
got = f.NoOptDefVal
}
t.Errorf("--report NoOptDefVal = %q, want %q (bare --report relies on it)", got, processorDefaultReportName())
}
}
// processorDefaultReportName mirrors the sentinel used to wire --report's
// NoOptDefVal, kept as a tiny indirection so the test reads clearly.
func processorDefaultReportName() string {
fs := pflag.NewFlagSet("probe", pflag.ContinueOnError)
var out, report, multi string
registerFlags(fs, &flagBindings{output: &out, report: &report, formatMulti: &multi, inert: true})
return fs.Lookup("report").NoOptDefVal
}
// TestRegressionGenuineReportWritesWithConfig fills the spec-04 checklist gap:
// "Genuine CLI ... --report ... -> do write" is only exercised for -o and
// --format-multi. With a project .sccconfig present the two-mode write split engages
// (write flags bound to discards in the merged parse, resolved from the genuine
// CLI alone), so this proves the --report arm of resolveWriteFlags still sources
// the real ReportOut from the command line. --report=path overwrites silently,
// avoiding the bare-flag interactive prompt.
func TestRegressionGenuineReportWritesWithConfig(t *testing.T) {
dir := writeSccConfig(t, "--no-cocomo\n")
target := filepath.Join(dir, "report.html")
out, err := runSCCDir(t, dir, noGlobalConfig, "--report="+target)
if err != nil {
t.Fatalf("scc errored: %v\n%s", err, out)
}
if info, statErr := os.Stat(target); statErr != nil || info.Size() == 0 {
t.Errorf("genuine CLI --report=path should write the report even with config present, output:\n%s", out)
}
// The genuine CLI set --report, so the "ignoring --report from config" notice
// must NOT fire.
if strings.Contains(out, "ignoring --report from config") {
t.Errorf("genuine CLI --report was wrongly treated as config-sourced, output:\n%s", out)
}
}
// TestRegressionAtFileWritesWithProjectConfigPresent locks the spec-§6 @file ⨉
// config interaction. Running `scc @file` rewrites os.Args before discovery, so
// a ./.sccconfig in the directory is still discovered and layered beneath the @file
// tokens - and because the genuine-CLI slice is captured AFTER @file expansion,
// the @file is allowed to write even though config is present (config is not).
// Here the project .sccconfig supplies --format csv (proving config layered into the
// merged parse) while the @file supplies -o target (proving @file kept its write
// capability): a single CSV-content assertion on the written file proves both.
func TestRegressionAtFileWritesWithProjectConfigPresent(t *testing.T) {
dir := writeSccConfig(t, "--format csv\n")
target := filepath.Join(dir, "out.txt")
atFile := filepath.Join(dir, "flags.txt")
if err := os.WriteFile(atFile, []byte("-o "+target+"\n"), 0644); err != nil {
t.Fatal(err)
}
out, err := runSCCDir(t, dir, noGlobalConfig, "@"+atFile)
if err != nil {
t.Fatalf("scc errored: %v\n%s", err, out)
}
info, statErr := os.Stat(target)
if statErr != nil || info.Size() == 0 {
t.Fatalf("@file -o should write even with a project .sccconfig present, stdout:\n%s", out)
}
body, err := os.ReadFile(target)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(body), "Language,Lines,Code") {
t.Errorf("project .sccconfig --format csv should have layered into the @file run, file contents:\n%s", body)
}
}
// TestRegressionMcpSkipsConfigDiscovery guards the run-order guarantee that the
// --mcp short-circuit fires before any config discovery (spec §3.3 step 0 / the
// "--mcp does not load config" checklist item). If discovery ran first, an
// unreadable explicit SCC_CONFIG_PATH global would exit non-zero with a "could
// not read config" error before the server ever started. With the correct
// ordering --mcp wins, the server starts, reads the empty stdin, hits EOF and
// exits - never touching config. Empty stdin guarantees a prompt EOF so the
// process cannot hang; a context deadline is a belt-and-suspenders backstop.
func TestRegressionMcpSkipsConfigDiscovery(t *testing.T) {
bin, err := filepath.Abs(sccBinPath)
if err != nil {
t.Fatal(err)
}
missing := filepath.Join(t.TempDir(), "does-not-exist.sccconfig")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, bin, sccTestFlag, "--mcp")
cmd.Env = append(os.Environ(), SccConfigEnv+"="+missing)
cmd.Stdin = bytes.NewReader(nil) // immediate EOF -> server exits cleanly
out, _ := cmd.CombinedOutput()
if ctx.Err() == context.DeadlineExceeded {
t.Fatalf("scc --mcp did not exit on EOF, output:\n%s", out)
}
if strings.Contains(string(out), "could not read config") {
t.Errorf("--mcp must short-circuit before config discovery; config was read, output:\n%s", out)
}
}
// TestRegressionVersionFlagWithConfig guards cobra's built-in meta flags through
// the new arg pipeline. main() no longer hands the genuine argv to cobra; it
// builds a merged list and passes it via rootCmd.SetArgs(merged[1:]). A bug in
// that wiring (e.g. an off-by-one slice, or config tokens shifting the version
// flag) could break --version even though it is not a real scc flag. The output
// must be byte-identical with and without a project .sccconfig present, and a .sccconfig
// must never leak a config error onto the version path.
func TestRegressionVersionFlagWithConfig(t *testing.T) {
bare := t.TempDir()
noCfg, err := runSCCDir(t, bare, noGlobalConfig, "--version")
if err != nil {
t.Fatalf("scc --version should exit 0 with no config: %v\n%s", err, noCfg)
}
if !strings.Contains(noCfg, "scc version") {
t.Fatalf("--version output missing version banner, output:\n%s", noCfg)
}
dir := writeSccConfig(t, "--format csv\n--no-cocomo\n")
withCfg, err := runSCCDir(t, dir, noGlobalConfig, "--version")
if err != nil {
t.Fatalf("scc --version should exit 0 with a project .sccconfig present: %v\n%s", err, withCfg)
}
if withCfg != noCfg {
t.Errorf("--version output changed when a project .sccconfig was present\nno config:\n%s\nwith config:\n%s", noCfg, withCfg)
}
}
// TestRegressionSccDirectoryDoesNotBreakRun guards the no-panics / robustness
// policy against a real-world surprise the feature introduces: a path named
// ".sccconfig" that is a *directory* (another tool's data dir, an accidental mkdir).
// Project discovery does os.Stat("./.sccconfig"), which succeeds for a directory, then
// os.ReadFile fails with "is a directory". That is the non-explicit project arm,
// so it must degrade to a stderr warning and let the run finish (exit 0 with
// real output) - never abort, panic, or swallow the scan.
func TestRegressionSccDirectoryDoesNotBreakRun(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte("package main\n"), 0644); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(filepath.Join(dir, ".sccconfig"), 0755); err != nil {
t.Fatal(err)
}
out, err := runSCCDir(t, dir, noGlobalConfig, "-f", "csv", "--by-file")
if err != nil {
t.Fatalf("a .sccconfig *directory* must not make scc exit non-zero: %v\n%s", err, out)
}
if !strings.Contains(out, "main.go") {
t.Errorf("scc should still scan and emit output when ./.sccconfig is a directory, output:\n%s", out)
}
}
// TestRegressionConfigGlobalProjectPrecedence locks the middle rung of the
// precedence ladder (global < project) for a scalar flag. The existing suite
// proves CLI beats config and that each source loads, but not that the project
// .sccconfig overrides the SCC_CONFIG_PATH global when the two disagree - the ordering
// that falls out of prepending global tokens ahead of project tokens. Asserted
// in both directions so a swapped prepend order cannot pass.
func TestRegressionConfigGlobalProjectPrecedence(t *testing.T) {
check := func(globalContent, projectContent string, wantCSV bool) {
t.Helper()
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte("package main\n"), 0644); err != nil {
t.Fatal(err)
}
global := filepath.Join(dir, "global.sccconfig")
if err := os.WriteFile(global, []byte(globalContent), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, ".sccconfig"), []byte(projectContent), 0644); err != nil {
t.Fatal(err)
}
out, err := runSCCDir(t, dir, []string{SccConfigEnv + "=" + global})
if err != nil {
t.Fatal(err)
}
isCSV := strings.Contains(out, "Language,Lines,Code")
if isCSV != wantCSV {
t.Errorf("global=%q project=%q: wantCSV=%v gotCSV=%v, output:\n%s", globalContent, projectContent, wantCSV, isCSV, out)
}
}
// project (json) overrides global (csv) -> not CSV
check("--format csv\n", "--format json\n", false)
// project (csv) overrides global (json) -> CSV
check("--format json\n", "--format csv\n", true)
}
// TestRegressionConfigGlobalProjectSliceUnion extends the §7 union semantics to
// the global+project pair. TestConfigSliceUnion covers project ∪ CLI ∪ defaults;
// this proves a slice flag set in the SCC_CONFIG_PATH global unions with the same
// flag set in the project .sccconfig (rather than one source replacing the other),
// which is the natural pflag append behaviour that the empty-default mechanism
// must preserve across both config sources.
func TestRegressionConfigGlobalProjectSliceUnion(t *testing.T) {
dir := t.TempDir()
for _, d := range []string{"ga", "pb", "keep"} {
if err := os.Mkdir(filepath.Join(dir, d), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, d, "f.go"), []byte("package x\n"), 0644); err != nil {
t.Fatal(err)
}
}
global := filepath.Join(dir, "global.sccconfig")
if err := os.WriteFile(global, []byte("--exclude-dir ga\n"), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, ".sccconfig"), []byte("--exclude-dir pb\n"), 0644); err != nil {
t.Fatal(err)
}
out, err := runSCCDir(t, dir, []string{SccConfigEnv + "=" + global}, "-f", "csv", "--by-file")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(out, "keep/f.go") {
t.Errorf("keep/f.go should be counted, output:\n%s", out)
}
// Both the global-excluded (ga) and project-excluded (pb) dirs must be gone:
// a union, not one source clobbering the other. Key on the path column so the
// shared basename (f.go) doesn't mask a leak.
if strings.Contains(out, "ga/f.go") || strings.Contains(out, "pb/f.go") {
t.Errorf("global+project --exclude-dir should union (ga and pb both excluded), output:\n%s", out)
}
}
// TestRegressionConfigFormatMultiIgnoredForStdout hardens the §5.3 guarantee
// that --format-multi is ignored *entirely* when it comes from config, not just
// blocked from writing files. TestConfigNeverWritesFile only proves no file
// appears; this proves config cannot even change the on-screen format via a
// stdout-only --format-multi. The merged parse binds --format-multi to a discard,
// so processor.FormatMulti stays empty and output keeps the default tabular form.
func TestRegressionConfigFormatMultiIgnoredForStdout(t *testing.T) {
dir := writeSccConfig(t, "--format-multi json:stdout\n")
out, err := runSCCDir(t, dir, noGlobalConfig)
if err != nil {
t.Fatalf("scc errored: %v\n%s", err, out)
}
// JSON would start with '[{'; tabular has the box-drawing header rule.
if strings.Contains(out, "[{\"Name\"") {
t.Errorf("config --format-multi must be ignored; output switched to JSON, output:\n%s", out)
}
if !strings.Contains(out, "Language") {
t.Errorf("expected the default tabular output, got:\n%s", out)
}
}
// TestRegressionConfigMinFlagClassifies fills a behavioural gap the existing
// suite leaves open. TestConfigCoupledMinFlags only asserts the run does not
// error; nothing proves a coupled min/gen flag (-z/--min/--gen, registered as
// BoolFuncs whose closures mutate processor state during parse) actually reaches
// Process when it comes from config. These are the flags spec-04 repeatedly
// flags as fragile under the two-mode write split. With a project .sccconfig present
// the split engages: the merged parse fires the -z closure (real binding), then
// resolveWriteFlags re-parses the genuine CLI with the closures made inert so it
// cannot undo that. A long single line trips the minified heuristic, so the file
// must surface as "(min)" - proving config's coupled flag survived end to end.
func TestRegressionConfigMinFlagClassifies(t *testing.T) {
dir := t.TempDir()
// One ~415-byte line: avg bytes/line well over the 255 default, so -z flags
// it minified.
long := "var x = '" + strings.Repeat("a", 400) + "';\n"
if err := os.WriteFile(filepath.Join(dir, "app.js"), []byte(long), 0644); err != nil {
t.Fatal(err)
}
// Everything needed is in the config; the genuine CLI is empty, so the
// effect is purely config-sourced. -f csv keeps the "(min)" suffix off the
// truncating tabular language column.
if err := os.WriteFile(filepath.Join(dir, ".sccconfig"), []byte("-z\n-i js\n--no-scc-ignore\n-f csv\n"), 0644); err != nil {
t.Fatal(err)
}
out, err := runSCCDir(t, dir, noGlobalConfig)
if err != nil {
t.Fatalf("scc errored: %v\n%s", err, out)
}
if !strings.Contains(out, "(min)") {
t.Errorf("config-supplied -z should flag the minified file as (min) through the two-mode pipeline, output:\n%s", out)
}
}
// TestRegressionConfigCannotStartMcpServer guards a security invariant that
// parallels the "config can never write a file" tests: a --mcp inside a project
// .sccconfig must NOT hijack stdio and start an MCP server. The interception reads
// os.Args ONLY (before config is discovered), so config's --mcp lands in the
// merged parse as the inert dummy flag registerFlags registers and the normal
// scan runs instead. This pins that ordering so a future refactor that moves the
// --mcp detection after the config merge - letting a checked-out .sccconfig silently
// turn a scan into a server - is caught. Empty stdin means even the bad case
// EOFs rather than hanging; the context deadline is a backstop.
func TestRegressionConfigCannotStartMcpServer(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte("package main\n"), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, ".sccconfig"), []byte("--mcp\n"), 0644); err != nil {
t.Fatal(err)
}
bin, err := filepath.Abs(sccBinPath)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, bin, sccTestFlag, "-f", "csv", "--by-file")
cmd.Dir = dir
cmd.Env = append(os.Environ(), noGlobalConfig...)
cmd.Stdin = bytes.NewReader(nil) // a started server would EOF, not hang
out, _ := cmd.CombinedOutput()
if ctx.Err() == context.DeadlineExceeded {
t.Fatalf("config --mcp appears to have started a server (timed out), output:\n%s", out)
}
// The by-file scan ran: the source file appears in the CSV. An MCP server
// would speak JSON-RPC and never emit this.
if !strings.Contains(string(out), "main.go") {
t.Errorf("config --mcp must be an inert dummy flag and let the scan run, output:\n%s", string(out))
}
}