-
-
Notifications
You must be signed in to change notification settings - Fork 246
Expand file tree
/
Copy pathcli.rs
More file actions
2504 lines (2255 loc) · 79.7 KB
/
Copy pathcli.rs
File metadata and controls
2504 lines (2255 loc) · 79.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
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
// cli.rs — CLI argument definitions and config file loading for cpd
use clap::Parser;
use serde::Deserialize;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
/// Parse a human-readable size string (e.g. "1kb", "1mb", "100kb", "102400") into bytes.
/// Supports: b, kb, k, mb, m, gb, g (case-insensitive). Returns None on parse failure.
pub fn parse_size(input: &str) -> Option<u64> {
let s = input.trim().to_lowercase();
if s.is_empty() {
return None;
}
let (num_part, multiplier): (&str, u64) = if s.ends_with("gb") {
(&s[..s.len() - 2], 1024 * 1024 * 1024)
} else if s.ends_with('g') {
(&s[..s.len() - 1], 1024 * 1024 * 1024)
} else if s.ends_with("mb") {
(&s[..s.len() - 2], 1024 * 1024)
} else if s.ends_with('m') {
(&s[..s.len() - 1], 1024 * 1024)
} else if s.ends_with("kb") {
(&s[..s.len() - 2], 1024)
} else if s.ends_with('k') {
(&s[..s.len() - 1], 1024)
} else if s.ends_with('b') {
(&s[..s.len() - 1], 1)
} else {
(s.as_str(), 1)
};
let num: f64 = num_part.parse().ok()?;
if num < 0.0 {
return None;
}
Some((num * multiplier as f64).round() as u64)
}
/// Parse format mappings string like "javascript:es,es6;dart:dt" into a HashMap.
pub fn parse_format_mappings(input: &str) -> HashMap<String, Vec<String>> {
let mut result = HashMap::new();
for group in input.split(';') {
let group = group.trim();
if group.is_empty() {
continue;
}
if let Some((format, exts)) = group.split_once(':') {
let format = format.trim().to_string();
let exts: Vec<String> = exts.split(',').map(|e| e.trim().to_string()).collect();
if !format.is_empty() && !exts.is_empty() {
result.insert(format, exts);
}
}
}
result
}
#[derive(Parser, Debug)]
#[command(
name = "cpd",
about = "Copy/Paste Detector — find duplicated code",
version
)]
pub struct Cli {
/// Paths to scan for duplicates
#[arg(value_name = "PATH")]
pub paths: Vec<PathBuf>,
/// Minimum number of tokens to consider a duplicate
#[arg(long, short = 'k')]
pub min_tokens: Option<usize>,
/// Minimum number of lines to consider a duplicate
#[arg(long, short = 'l')]
pub min_lines: Option<usize>,
/// Maximum number of lines per block to consider
#[arg(long, short = 'x')]
pub max_lines: Option<usize>,
/// Detection mode: mild, weak, strict
#[arg(long, short = 'm')]
pub mode: Option<String>,
/// Alias for --mode weak (skip comment tokens)
#[arg(long)]
pub skip_comments: bool,
/// List of file extensions/formats to check (comma-separated)
#[arg(long, short = 'f', value_delimiter = ',')]
pub format: Vec<String>,
/// File-level glob patterns to ignore, e.g. "**/node_modules/**" (comma-separated)
#[arg(long, short = 'i', value_delimiter = ',')]
pub ignore: Vec<String>,
/// Code-level regex patterns to skip matching tokens during detection, e.g. "//\\s*cpd-disable" (comma-separated)
#[arg(long, value_delimiter = ',')]
pub ignore_pattern: Vec<String>,
/// Output reporters (comma-separated): console,json,xml,csv,html,markdown,badge,sarif,ai,xcode,threshold,silent,console-full
/// Aliases: "full" and "consoleFull" are accepted for "console-full"
#[arg(long, short = 'r', value_delimiter = ',')]
pub reporters: Vec<String>,
/// Output directory for file reporters
#[arg(long, short = 'o')]
pub output: Option<PathBuf>,
/// Path to config file (.jscpd.json)
#[arg(long, short = 'c')]
pub config: Option<PathBuf>,
/// Exit with code if duplicates found (default code: 1)
#[arg(long, num_args(0..=1), default_missing_value = "1")]
pub exit_code: Option<i32>,
/// Maximum duplication percentage before exit 1
#[arg(long, short = 't')]
pub threshold: Option<f64>,
/// Enrich clones with git blame data
#[arg(long, short = 'b')]
pub blame: bool,
/// Do not respect .gitignore files
#[arg(long)]
pub no_gitignore: bool,
/// Follow symbolic links
#[arg(long)]
pub follow_symlinks: bool,
/// Skip files larger than SIZE (e.g. 1kb, 1mb, 100kb, or raw bytes). Default: 1mb
#[arg(long, short = 'z')]
pub max_size: Option<String>,
/// Number of worker threads (default: auto)
#[arg(long)]
pub workers: Option<usize>,
/// Disable ANSI color output
#[arg(long)]
pub no_colors: bool,
/// Use absolute paths in reports
#[arg(long, short = 'a')]
pub absolute: bool,
/// Ignore case of symbols in code (experimental)
#[arg(long)]
pub ignore_case: bool,
/// Custom format-to-extension mappings (e.g. javascript:es,es6;dart:dt)
#[arg(long)]
pub formats_exts: Option<String>,
/// Custom format-to-filename mappings (e.g. makefile:Makefile,GNUmakefile;docker:Dockerfile)
#[arg(long)]
pub formats_names: Option<String>,
/// Accepted for compatibility; external store backend not supported in V1
#[arg(long, hide = true)]
pub store: Option<String>,
/// Accepted for compatibility; external store path not supported in V1
#[arg(long, hide = true)]
pub store_path: Option<PathBuf>,
/// Glob pattern to find files to scan (e.g. **/*.ts, **/*.{js,ts})
#[arg(long, short = 'p')]
pub pattern: Option<String>,
/// List all supported formats and exit
#[arg(long)]
pub list: bool,
/// Skip clones where both fragments are in the same directory
#[arg(long, visible_alias = "skipLocal")]
pub skip_local: bool,
/// Minimum percentage of duplication to report (0-100)
#[arg(long, default_value = "0")]
pub min_duplicated_lines: f64,
/// Do not write detection progress and result to console
#[arg(long, short = 's')]
pub silent: bool,
/// Do not print tips and promotional messages after detection
#[arg(long)]
pub no_tips: bool,
/// Print merged config (CLI + config file) as JSON and exit without running detection
#[arg(long)]
pub debug: bool,
}
#[derive(Deserialize, Default, Debug, Clone)]
#[serde(rename_all = "camelCase", default)]
pub struct ConfigFile {
pub path: Option<Vec<String>>,
#[serde(alias = "min-tokens")]
pub min_tokens: Option<usize>,
#[serde(alias = "min-lines")]
pub min_lines: Option<usize>,
#[serde(alias = "max-lines")]
pub max_lines: Option<usize>,
pub mode: Option<String>,
#[serde(alias = "formats")]
pub format: Option<Vec<String>>,
#[serde(alias = "ignore-pattern")]
pub ignore_pattern: Option<Vec<String>>,
#[serde(alias = "ignore")]
pub ignore: Option<Vec<String>>,
pub pattern: Option<String>,
pub reporters: Option<Vec<String>>,
pub output: Option<String>,
pub threshold: Option<f64>,
pub blame: Option<bool>,
#[serde(alias = "no-gitignore")]
pub no_gitignore: Option<bool>,
#[serde(alias = "follow-symlinks")]
pub follow_symlinks: Option<bool>,
#[serde(alias = "max-size")]
pub max_size: Option<String>,
#[serde(alias = "no-colors")]
pub no_colors: Option<bool>,
pub absolute: Option<bool>,
#[serde(alias = "ignore-case")]
pub ignore_case: Option<bool>,
#[serde(alias = "formats-exts")]
pub formats_exts: Option<String>,
#[serde(alias = "formats-names")]
pub formats_names: Option<String>,
#[serde(alias = "skip-local")]
pub skip_local: Option<bool>,
#[serde(alias = "exit-code")]
pub exit_code: Option<i32>,
#[serde(alias = "no-tips")]
pub no_tips: Option<bool>,
pub silent: Option<bool>,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum ConfigSource {
Explicit(PathBuf),
AutoJscpdJson,
AutoPackageJson,
}
#[derive(Debug, Clone)]
pub(crate) enum ConfigDiagnostic {
IoError {
source: PathBuf,
error: String,
},
ParseError {
source: PathBuf,
line: Option<usize>,
error: String,
},
UnknownField {
source: PathBuf,
field: String,
migration_hint: Option<String>,
},
InvalidValue {
source: PathBuf,
field: String,
value: String,
reason: String,
},
}
impl ConfigDiagnostic {
pub fn is_fatal(&self) -> bool {
matches!(
self,
ConfigDiagnostic::IoError { .. } | ConfigDiagnostic::ParseError { .. }
)
}
}
impl std::fmt::Display for ConfigDiagnostic {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ConfigDiagnostic::IoError { source, error } => {
write!(f, "config file {}: {}", source.display(), error)
}
ConfigDiagnostic::ParseError {
source,
line: Some(line),
error,
} => {
write!(
f,
"config file {} line {}: {}",
source.display(),
line,
error
)
}
ConfigDiagnostic::ParseError {
source,
line: None,
error,
} => {
write!(f, "config file {}: {}", source.display(), error)
}
ConfigDiagnostic::UnknownField {
source,
field,
migration_hint: Some(hint),
} => {
write!(
f,
"config file {}: unknown field '{}' — {}",
source.display(),
field,
hint
)
}
ConfigDiagnostic::UnknownField {
source,
field,
migration_hint: None,
} => {
write!(
f,
"config file {}: unknown field '{}'",
source.display(),
field
)
}
ConfigDiagnostic::InvalidValue {
source,
field,
value,
reason,
} => {
write!(
f,
"config file {}: invalid value for '{}': {} ({})",
source.display(),
field,
value,
reason
)
}
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct ConfigResult {
pub config: ConfigFile,
pub source: Option<ConfigSource>,
pub diagnostics: Vec<ConfigDiagnostic>,
}
impl ConfigResult {
#[allow(dead_code)]
pub fn has_diagnostics(&self) -> bool {
!self.diagnostics.is_empty()
}
}
pub(crate) fn print_diagnostics(diagnostics: &[ConfigDiagnostic]) {
for d in diagnostics {
eprintln!("{}", d);
}
}
pub(crate) fn validate_config(config: &ConfigFile, source: &Path) -> Vec<ConfigDiagnostic> {
let mut diagnostics = Vec::new();
if let Some(ref mode) = config.mode {
match mode.as_str() {
"mild" | "weak" | "strict" => {}
_ => diagnostics.push(ConfigDiagnostic::InvalidValue {
source: source.to_path_buf(),
field: "mode".to_string(),
value: mode.clone(),
reason: "must be one of: mild, weak, strict".to_string(),
}),
}
}
diagnostics
}
pub(crate) static KNOWN_CONFIG_FIELDS: &[&str] = &[
"path",
"minTokens",
"minLines",
"maxLines",
"mode",
"format",
"formats",
"ignorePattern",
"ignore",
"pattern",
"reporters",
"output",
"threshold",
"blame",
"noGitignore",
"followSymlinks",
"noSymlinks",
"noSymLinks",
"maxSize",
"noColors",
"absolute",
"ignoreCase",
"formatsExts",
"formatsNames",
"skipLocal",
"exitCode",
"noTips",
"silent",
// kebab-case aliases (v4 compat)
"min-tokens",
"min-lines",
"max-lines",
"max-size",
"ignore-case",
"no-gitignore",
"follow-symlinks",
"skip-local",
"exit-code",
"no-colors",
"no-tips",
"formats-exts",
"formats-names",
"ignore-pattern",
];
pub(crate) static V4_SILENT_IGNORE: &[&str] = &[
"gitignore",
"debug",
"verbose",
"config",
"xslHref",
"//",
"",
];
pub(crate) static V4_MIGRATIONS: &[(&str, &str)] = &[
("executionId", "removed from config file in v5"),
(
"store",
"removed from config file in v5, use --store CLI flag",
),
(
"storePath",
"removed from config file in v5, use --store-path CLI flag",
),
("cache", "removed from config file in v5"),
("list", "removed from config file in v5"),
("reportersOptions", "removed from config file in v5"),
("listeners", "removed from config file in v5"),
("tokensToSkip", "removed from config file in v5"),
("hashFunction", "removed from config file in v5"),
];
pub(crate) fn scan_unknown_fields(
value: &serde_json::Value,
source: &Path,
) -> Vec<ConfigDiagnostic> {
let obj = match value.as_object() {
Some(o) => o,
None => return vec![],
};
obj.keys()
.filter(|k| !KNOWN_CONFIG_FIELDS.contains(&k.as_str()))
.filter(|k| !V4_SILENT_IGNORE.contains(&k.as_str()))
.map(|k| {
let hint = check_v4_migration(k);
ConfigDiagnostic::UnknownField {
source: source.to_path_buf(),
field: k.clone(),
migration_hint: hint,
}
})
.collect()
}
fn check_v4_migration(field: &str) -> Option<String> {
V4_MIGRATIONS
.iter()
.find(|(k, _)| *k == field)
.map(|(_, v)| v.to_string())
}
/// Normalize v4 config fields in a JSON value before deserializing to ConfigFile.
///
/// Handles:
/// - `"//"` and `""` (JSONC-style comment keys) → removed
/// - `"ignore"` and `"ignorePattern"` are kept as separate fields:
/// `"ignore"` = file-level glob patterns, `"ignorePattern"` = code-level regex
/// - `"noSymlinks"` / `"noSymLinks"` (bool) → inverted and merged into `"followSymlinks"`
/// - `"formatsExts"` / `"formats-exts"` as array or object → converted to string
/// - `"format"` / `"formats"` as string → wrapped in array
/// - `"threshold"` as string → converted to number
fn normalize_v4_config(value: &mut serde_json::Value) {
let obj = match value.as_object_mut() {
Some(o) => o,
None => return,
};
// Remove JSONC-style comment keys ("//" and "")
obj.remove("//");
obj.remove("");
// Coerce "threshold" from string to number
if let Some(threshold) = obj.remove("threshold") {
let coerced = match &threshold {
serde_json::Value::String(s) => s
.parse::<f64>()
.ok()
.map(|f| {
serde_json::Number::from_f64(f)
.map(serde_json::Value::from)
.unwrap_or_else(|| serde_json::Value::from(0))
})
.unwrap_or(threshold),
_ => threshold,
};
obj.insert("threshold".to_string(), coerced);
}
// Coerce "format" from string to array
for key in &["format", "formats"] {
if let Some(val) = obj.remove(*key) {
let coerced = match val {
serde_json::Value::String(s) => {
serde_json::Value::Array(vec![serde_json::Value::String(s)])
}
other => other,
};
obj.insert(key.to_string(), coerced);
}
}
// v4 compat: "ignore" is file-level glob patterns (handled separately from
// "ignorePattern" which is code-level regex). Both are kept as distinct fields
// in ConfigFile — no merging needed.
// "noSymlinks" / "noSymLinks" (bool) → inverted "followSymlinks"
let no_symlinks_val = obj
.remove("noSymlinks")
.or_else(|| obj.remove("noSymLinks"));
if let Some(val) = no_symlinks_val {
let inverted = match val {
serde_json::Value::Bool(b) => !b,
_ => true,
};
obj.entry("followSymlinks".to_string())
.and_modify(|e| {
if let serde_json::Value::Bool(existing) = e {
*existing = *existing && inverted;
}
})
.or_insert_with(|| serde_json::Value::Bool(inverted));
}
// "formatsExts" / "formats-exts" type coercion: accept array or object, convert to string
for key in &["formatsExts", "formats-exts"] {
coerce_formats_mapping(obj, key);
}
// "formatsNames" / "formats-names" same treatment
for key in &["formatsNames", "formats-names"] {
coerce_formats_mapping(obj, key);
}
}
/// Coerce a formats mapping field (formatsExts/formatsNames) from array or object to string.
///
/// Accepted forms:
/// - String: "javascript:es,es6;dart:dt" (v5 canonical, no conversion needed)
/// - Array of strings: ["javascript:es,es6"] → "javascript:es,es6"
/// - Object: {"javascript": ["es","es6"], "dart": ["dt"]} → "javascript:es,es6;dart:dt"
fn coerce_formats_mapping(obj: &mut serde_json::Map<String, serde_json::Value>, key: &str) {
if let Some(val) = obj.remove(key) {
let coerced = match val {
serde_json::Value::String(s) => serde_json::Value::String(s),
serde_json::Value::Array(arr) => {
let s: String = arr
.into_iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect::<Vec<_>>()
.join(";");
serde_json::Value::String(s)
}
serde_json::Value::Object(map) => {
let parts: Vec<String> = map
.into_iter()
.filter_map(|(format, exts)| {
let ext_names: Vec<String> = match exts {
serde_json::Value::Array(arr) => arr
.into_iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect(),
serde_json::Value::String(s) => vec![s],
_ => return None,
};
if ext_names.is_empty() {
None
} else {
Some(format!("{}:{}", format, ext_names.join(",")))
}
})
.collect();
serde_json::Value::String(parts.join(";"))
}
other => other,
};
obj.insert(key.to_string(), coerced);
}
}
fn resolve_config_paths(cfg: &mut ConfigFile, config_dir: &Path) {
if let Some(ref mut paths) = cfg.path {
*paths = paths
.iter()
.map(|p| {
let path = PathBuf::from(p);
if path.is_relative() {
config_dir.join(path).to_string_lossy().to_string()
} else {
p.clone()
}
})
.collect();
}
if let Some(ref mut patterns) = cfg.ignore_pattern {
*patterns = patterns
.iter()
.map(|p| {
let path = PathBuf::from(p);
if path.is_relative() && !p.contains('*') && !p.contains('?') {
config_dir.join(path).to_string_lossy().to_string()
} else {
p.clone()
}
})
.collect();
}
}
/// Load config from file if specified, or from .jscpd.json / package.json jscpd key.
/// Reports diagnostics for any errors encountered (IO, parse, unknown fields, invalid values).
/// For explicit --config paths, all diagnostics are fatal (caller should exit with code 1).
/// For auto-discovered configs, diagnostics are warnings and the cascade falls through
/// to the next source on IO/parse errors.
/// Paths in the config file are resolved relative to the config file's directory,
/// matching jscpd v4 behavior.
pub fn load_config(path: Option<&Path>) -> ConfigResult {
if let Some(p) = path {
return load_explicit_config(p);
}
let mut auto_diagnostics = Vec::new();
if let Some(result) = try_load_jscpd_json(&mut auto_diagnostics) {
return result;
}
if let Some(result) = try_load_package_json(&mut auto_diagnostics) {
return result;
}
ConfigResult {
config: ConfigFile::default(),
source: None,
diagnostics: auto_diagnostics,
}
}
fn load_explicit_config(p: &Path) -> ConfigResult {
let mut diagnostics = Vec::new();
match std::fs::read_to_string(p) {
Ok(content) => {
let value: serde_json::Value = match serde_json::from_str(&content) {
Ok(v) => v,
Err(e) => {
let line = extract_line_number(&e);
diagnostics.push(ConfigDiagnostic::ParseError {
source: p.to_path_buf(),
line,
error: e.to_string(),
});
return ConfigResult {
config: ConfigFile::default(),
source: Some(ConfigSource::Explicit(p.to_path_buf())),
diagnostics,
};
}
};
diagnostics.extend(scan_unknown_fields(&value, p));
let mut value = value;
normalize_v4_config(&mut value);
match serde_json::from_value::<ConfigFile>(value) {
Ok(mut cfg) => {
let config_dir = p.parent().unwrap_or(Path::new(".")).to_path_buf();
resolve_config_paths(&mut cfg, &config_dir);
diagnostics.extend(validate_config(&cfg, p));
ConfigResult {
config: cfg,
source: Some(ConfigSource::Explicit(p.to_path_buf())),
diagnostics,
}
}
Err(e) => {
let line = extract_line_number(&e);
diagnostics.push(ConfigDiagnostic::ParseError {
source: p.to_path_buf(),
line,
error: e.to_string(),
});
ConfigResult {
config: ConfigFile::default(),
source: Some(ConfigSource::Explicit(p.to_path_buf())),
diagnostics,
}
}
}
}
Err(e) => {
diagnostics.push(ConfigDiagnostic::IoError {
source: p.to_path_buf(),
error: e.to_string(),
});
ConfigResult {
config: ConfigFile::default(),
source: Some(ConfigSource::Explicit(p.to_path_buf())),
diagnostics,
}
}
}
}
fn try_load_jscpd_json(auto_diagnostics: &mut Vec<ConfigDiagnostic>) -> Option<ConfigResult> {
let path = PathBuf::from(".jscpd.json");
match std::fs::read_to_string(&path) {
Ok(content) => {
let value: serde_json::Value = match serde_json::from_str(&content) {
Ok(v) => v,
Err(e) => {
let line = extract_line_number(&e);
auto_diagnostics.push(ConfigDiagnostic::ParseError {
source: path.clone(),
line,
error: e.to_string(),
});
return None;
}
};
let mut field_diagnostics = scan_unknown_fields(&value, &path);
let mut value = value;
normalize_v4_config(&mut value);
match serde_json::from_value::<ConfigFile>(value) {
Ok(mut cfg) => {
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
resolve_config_paths(&mut cfg, &cwd);
let mut validation_diagnostics = validate_config(&cfg, &path);
field_diagnostics.append(&mut validation_diagnostics);
Some(ConfigResult {
config: cfg,
source: Some(ConfigSource::AutoJscpdJson),
diagnostics: field_diagnostics,
})
}
Err(e) => {
let line = extract_line_number(&e);
auto_diagnostics.push(ConfigDiagnostic::ParseError {
source: path.clone(),
line,
error: e.to_string(),
});
None
}
}
}
Err(_) => None,
}
}
fn try_load_package_json(auto_diagnostics: &mut Vec<ConfigDiagnostic>) -> Option<ConfigResult> {
let path = PathBuf::from("package.json");
match std::fs::read_to_string(&path) {
Ok(content) => {
let pkg: serde_json::Value = match serde_json::from_str(&content) {
Ok(v) => v,
Err(e) => {
let line = extract_line_number(&e);
auto_diagnostics.push(ConfigDiagnostic::ParseError {
source: path.clone(),
line,
error: e.to_string(),
});
return None;
}
};
let jscpd_cfg = pkg.get("jscpd")?;
let mut field_diagnostics = scan_unknown_fields(jscpd_cfg, &path);
let mut jscpd_value = jscpd_cfg.clone();
normalize_v4_config(&mut jscpd_value);
match serde_json::from_value::<ConfigFile>(jscpd_value) {
Ok(mut cfg) => {
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
resolve_config_paths(&mut cfg, &cwd);
let mut validation_diagnostics = validate_config(&cfg, &path);
field_diagnostics.append(&mut validation_diagnostics);
Some(ConfigResult {
config: cfg,
source: Some(ConfigSource::AutoPackageJson),
diagnostics: field_diagnostics,
})
}
Err(e) => {
let line = extract_line_number(&e);
auto_diagnostics.push(ConfigDiagnostic::ParseError {
source: path.clone(),
line,
error: e.to_string(),
});
None
}
}
}
Err(_) => None,
}
}
fn extract_line_number(error: &serde_json::Error) -> Option<usize> {
Some(error.line())
}
#[cfg(test)]
mod tests {
use super::*;
use clap::Parser;
#[test]
fn default_min_tokens_is_50() {
let cli = Cli::parse_from(["cpd", "."]);
assert_eq!(cli.min_tokens, None);
}
#[test]
fn min_tokens_override() {
let cli = Cli::parse_from(["cpd", "--min-tokens", "30", "."]);
assert_eq!(cli.min_tokens, Some(30));
}
#[test]
fn list_flag() {
let cli = Cli::parse_from(["cpd", "--list"]);
assert!(cli.list);
}
#[test]
fn skip_comments_sets_mode_weak_in_options() {
let cli = Cli::parse_from(["cpd", "--skip-comments", "."]);
let config = ConfigFile::default();
let opts = crate::options::Options::from_cli_and_config(&cli, &config);
assert_eq!(opts.mode, cpd_tokenizer::tokenizer::Mode::Weak);
}
#[test]
fn config_file_min_tokens_overrides_default() {
let config = ConfigFile {
min_tokens: Some(30),
..Default::default()
};
let _ = config;
}
#[test]
fn config_path_used_when_cli_paths_empty() {
let cli = Cli::parse_from(["cpd"]);
let config = ConfigFile {
path: Some(vec!["./fixtures".to_string()]),
..Default::default()
};
let opts = crate::options::Options::from_cli_and_config(&cli, &config);
assert_eq!(opts.paths, vec![PathBuf::from("./fixtures")]);
}
#[test]
fn cli_paths_override_config_path() {
let cli = Cli::parse_from(["cpd", "/tmp/project"]);
let config = ConfigFile {
path: Some(vec!["./fixtures".to_string()]),
..Default::default()
};
let opts = crate::options::Options::from_cli_and_config(&cli, &config);
assert_eq!(opts.paths, vec![PathBuf::from("/tmp/project")]);
}
#[test]
fn store_flag_accepted_without_error() {
let result = Cli::try_parse_from(["cpd", "--store", "leveldb", "."]);
assert!(result.is_ok(), "--store flag must be accepted");
}
#[test]
fn reporters_split_by_comma() {
let cli = Cli::parse_from(["cpd", "--reporters", "console,json", "."]);
assert_eq!(cli.reporters, vec!["console", "json"]);
}
// Short alias tests
#[test]
fn short_alias_l_for_min_lines() {
let cli = Cli::parse_from(["cpd", "-l", "10", "."]);
assert_eq!(cli.min_lines, Some(10));
}
#[test]
fn short_alias_k_for_min_tokens() {
let cli = Cli::parse_from(["cpd", "-k", "30", "."]);
assert_eq!(cli.min_tokens, Some(30));
}
#[test]
fn short_alias_r_for_reporters() {
let cli = Cli::parse_from(["cpd", "-r", "json,xml", "."]);
assert_eq!(cli.reporters, vec!["json", "xml"]);
}
#[test]
fn short_alias_o_for_output() {
let cli = Cli::parse_from(["cpd", "-o", "dist", "."]);
assert_eq!(cli.output, Some(PathBuf::from("dist")));
}
#[test]
fn short_alias_t_for_threshold() {
let cli = Cli::parse_from(["cpd", "-t", "5.5", "."]);
assert_eq!(cli.threshold, Some(5.5));
}
#[test]
fn short_alias_m_for_mode() {
let cli = Cli::parse_from(["cpd", "-m", "strict", "."]);
assert_eq!(cli.mode, Some("strict".to_string()));
}
#[test]
fn short_alias_f_for_format() {
let cli = Cli::parse_from(["cpd", "-f", "rust,typescript", "."]);
assert_eq!(cli.format, vec!["rust", "typescript"]);
}
#[test]
fn short_alias_i_for_ignore() {
let cli = Cli::parse_from(["cpd", "-i", "*.test.js,*.spec.ts", "."]);
assert_eq!(cli.ignore, vec!["*.test.js", "*.spec.ts"]);
}
#[test]
fn ignore_pattern_cli_flag() {
let cli = Cli::parse_from(["cpd", "--ignore-pattern", "function", "."]);
assert_eq!(cli.ignore_pattern, vec!["function"]);
assert!(cli.ignore.is_empty());
}
#[test]
fn ignore_and_ignore_pattern_work_together() {
let cli = Cli::parse_from([
"cpd",
"--ignore",
"*.test.js",
"--ignore-pattern",
"function",
".",
]);
assert_eq!(cli.ignore, vec!["*.test.js"]);
assert_eq!(cli.ignore_pattern, vec!["function"]);
}