jscpd-rs 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/Cargo.lock +1323 -0
  3. package/Cargo.toml +54 -0
  4. package/LICENSE +21 -0
  5. package/README.md +372 -0
  6. package/docs/api-parity.md +49 -0
  7. package/docs/cloning-plan.md +281 -0
  8. package/docs/compat-baseline.md +535 -0
  9. package/docs/format-porting.md +86 -0
  10. package/docs/junior-task-template.md +62 -0
  11. package/docs/junior-workflow.md +87 -0
  12. package/docs/migrating-from-jscpd.md +193 -0
  13. package/docs/npm-release.md +116 -0
  14. package/docs/public-benchmark-suite.md +81 -0
  15. package/docs/release-checklist.md +200 -0
  16. package/docs/release-decisions.md +103 -0
  17. package/docs/release-readiness.md +51 -0
  18. package/docs/upstream-bugs.md +501 -0
  19. package/docs/upstream-issue-drafts.md +393 -0
  20. package/docs/user-guide.md +309 -0
  21. package/examples/dump_oxc_tokens.rs +112 -0
  22. package/examples/library_api.rs +42 -0
  23. package/npm/bin/jscpd-rs.js +6 -0
  24. package/npm/bin/jscpd-server.js +6 -0
  25. package/npm/lib/run-binary.js +68 -0
  26. package/npm/scripts/postinstall.js +50 -0
  27. package/package.json +53 -0
  28. package/skills/dry-refactoring/SKILL.md +63 -0
  29. package/skills/jscpd/SKILL.md +85 -0
  30. package/src/app.rs +512 -0
  31. package/src/bin/jscpd-server.rs +429 -0
  32. package/src/blame.rs +130 -0
  33. package/src/cli/config.rs +543 -0
  34. package/src/cli/parsing.rs +301 -0
  35. package/src/cli/tests.rs +543 -0
  36. package/src/cli.rs +671 -0
  37. package/src/detector/matching/secondary.rs +387 -0
  38. package/src/detector/matching.rs +274 -0
  39. package/src/detector/model.rs +190 -0
  40. package/src/detector/prepare.rs +71 -0
  41. package/src/detector/skip_local.rs +40 -0
  42. package/src/detector/statistics.rs +138 -0
  43. package/src/detector/store.rs +96 -0
  44. package/src/detector/tests.rs +238 -0
  45. package/src/detector.rs +265 -0
  46. package/src/files/discovery.rs +508 -0
  47. package/src/files/gitignore.rs +203 -0
  48. package/src/files/paths.rs +68 -0
  49. package/src/files/shebang.rs +106 -0
  50. package/src/files/tests.rs +523 -0
  51. package/src/files.rs +25 -0
  52. package/src/formats.rs +570 -0
  53. package/src/lib.rs +433 -0
  54. package/src/main.rs +26 -0
  55. package/src/report/ai.rs +125 -0
  56. package/src/report/badge.rs +238 -0
  57. package/src/report/console.rs +180 -0
  58. package/src/report/console_common.rs +37 -0
  59. package/src/report/console_full.rs +139 -0
  60. package/src/report/csv.rs +65 -0
  61. package/src/report/escape.rs +8 -0
  62. package/src/report/file_output.rs +28 -0
  63. package/src/report/html/assets.rs +47 -0
  64. package/src/report/html.rs +336 -0
  65. package/src/report/json.rs +119 -0
  66. package/src/report/markdown.rs +125 -0
  67. package/src/report/sarif.rs +302 -0
  68. package/src/report/silent.rs +22 -0
  69. package/src/report/source.rs +38 -0
  70. package/src/report/summary.rs +50 -0
  71. package/src/report/test_support.rs +133 -0
  72. package/src/report/threshold.rs +76 -0
  73. package/src/report/xcode.rs +90 -0
  74. package/src/report/xml.rs +119 -0
  75. package/src/report.rs +250 -0
  76. package/src/server/mcp.rs +942 -0
  77. package/src/server.rs +1081 -0
  78. package/src/tokenizer/apex.rs +97 -0
  79. package/src/tokenizer/blocks.rs +532 -0
  80. package/src/tokenizer/embedded.rs +106 -0
  81. package/src/tokenizer/generic.rs +511 -0
  82. package/src/tokenizer/hash.rs +27 -0
  83. package/src/tokenizer/ignore.rs +33 -0
  84. package/src/tokenizer/line_index.rs +33 -0
  85. package/src/tokenizer/markdown.rs +289 -0
  86. package/src/tokenizer/markup_attrs.rs +289 -0
  87. package/src/tokenizer/oxc/fallback.rs +275 -0
  88. package/src/tokenizer/oxc/jsx.rs +168 -0
  89. package/src/tokenizer/oxc/kind.rs +177 -0
  90. package/src/tokenizer/oxc/lexical.rs +67 -0
  91. package/src/tokenizer/oxc.rs +659 -0
  92. package/src/tokenizer/scan.rs +88 -0
  93. package/src/tokenizer/tap.rs +150 -0
  94. package/src/tokenizer/tests.rs +915 -0
  95. package/src/tokenizer.rs +328 -0
  96. package/src/verbose.rs +195 -0
package/src/lib.rs ADDED
@@ -0,0 +1,433 @@
1
+ #![doc(html_root_url = "https://docs.rs/jscpd-rs/0.1.0")]
2
+
3
+ //! Native Rust API for `jscpd-rs`, a high-performance Rust clone of
4
+ //! [`jscpd`](https://github.com/kucherenko/jscpd).
5
+ //!
6
+ //! The crate exposes the same detector core used by the `jscpd` and
7
+ //! `jscpd-server` binaries: option parsing, file discovery, tokenization,
8
+ //! duplicate detection, statistics, and in-memory source checks.
9
+ //!
10
+ //! # Quick Start
11
+ //!
12
+ //! Scan paths using the same option model as the CLI:
13
+ //!
14
+ //! ```no_run
15
+ //! use std::path::PathBuf;
16
+ //!
17
+ //! # fn main() -> anyhow::Result<()> {
18
+ //! let mut options = jscpd_rs::get_default_options();
19
+ //! options.paths = vec![PathBuf::from("src")];
20
+ //! options.reporters.clear();
21
+ //! options.silent = true;
22
+ //!
23
+ //! let result = jscpd_rs::detect_clones_and_statistics(&options)?;
24
+ //! println!("{} clones", result.clones.len());
25
+ //! # Ok(())
26
+ //! # }
27
+ //! ```
28
+ //!
29
+ //! Check prepared in-memory sources without touching the filesystem:
30
+ //!
31
+ //! ```
32
+ //! let mut options = jscpd_rs::get_default_options();
33
+ //! options.reporters.clear();
34
+ //! options.min_lines = 2;
35
+ //! options.min_tokens = 5;
36
+ //!
37
+ //! let files = vec![
38
+ //! jscpd_rs::SourceFile {
39
+ //! source_id: "a.js".to_string(),
40
+ //! format: "javascript".to_string(),
41
+ //! content: "const a = 1;\nconst b = 2;\nconst c = a + b;\n".to_string(),
42
+ //! },
43
+ //! jscpd_rs::SourceFile {
44
+ //! source_id: "b.js".to_string(),
45
+ //! format: "javascript".to_string(),
46
+ //! content: "const a = 1;\nconst b = 2;\nconst c = a + b;\n".to_string(),
47
+ //! },
48
+ //! ];
49
+ //!
50
+ //! let result = jscpd_rs::detect_source_files(files, &options);
51
+ //! assert!(!result.clones.is_empty());
52
+ //! ```
53
+ //!
54
+ //! # Main Entry Points
55
+ //!
56
+ //! - [`get_options_from_args`] parses upstream-style CLI arguments into
57
+ //! [`Options`].
58
+ //! - [`detect_clones`] and [`detect_clones_and_statistics`] run discovery,
59
+ //! tokenization, duplicate detection, statistics, and optional Git blame.
60
+ //! - [`detect_source_files`] runs detection against caller-provided
61
+ //! [`SourceFile`] values and is the best entry point for editors, servers,
62
+ //! and tests.
63
+ //! - [`Tokenizer`] exposes the native token map generator used by the detector.
64
+ //! - [`Detector`] and [`MemoryStore`] provide Rust counterparts for the main
65
+ //! upstream core classes.
66
+ //! - [`jscpd`] and [`jscpd_with_exit_callback`] provide an embeddable argv
67
+ //! runner similar to upstream `jscpd(argv, exitCallback?)`.
68
+ //!
69
+ //! # Compatibility Model
70
+ //!
71
+ //! The release gate is coverage-first: for the same inputs and options, this
72
+ //! crate must not miss duplicated source lines reported by upstream `jscpd`.
73
+ //! Extra Rust findings remain visible in compatibility reports while the
74
+ //! implementation converges on exact parity.
75
+ //!
76
+ //! The first release intentionally keeps the detector native-only. Dynamic npm
77
+ //! reporters, stores, listeners, and plugins are not loaded by this crate.
78
+ //!
79
+ //! See the
80
+ //! [README](https://github.com/vv-bogdanov/jscpd-rs#readme) and
81
+ //! [User Guide](https://github.com/vv-bogdanov/jscpd-rs/blob/main/docs/user-guide.md)
82
+ //! for CLI, configuration, reporter, server, and CI examples.
83
+
84
+ pub mod app;
85
+ pub mod blame;
86
+ pub mod cli;
87
+ pub mod detector;
88
+ pub mod files;
89
+ pub mod formats;
90
+ pub mod report;
91
+ pub mod server;
92
+ pub mod tokenizer;
93
+ pub mod verbose;
94
+
95
+ use std::{ffi::OsString, path::Path};
96
+
97
+ use anyhow::Result;
98
+
99
+ pub use app::{JscpdOutcome, jscpd, jscpd_with_exit_callback, run_cli_args};
100
+ pub use cli::{FormatMappings, Options};
101
+ pub use detector::{
102
+ CloneMatch, DetectionResult, Detector, MemoryStore, MemoryStoreError, Statistic, StatisticRow,
103
+ Statistics,
104
+ };
105
+ pub use files::SourceFile;
106
+ pub use tokenizer::{DetectionToken, Location, SourceTokenMap, TokenMap, Tokenizer};
107
+
108
+ /// Return the upstream-compatible default option set.
109
+ ///
110
+ /// The defaults match the CLI defaults used by the `jscpd` binary: all
111
+ /// supported formats, `min_lines = 5`, `min_tokens = 50`, `max_lines = 1000`,
112
+ /// `max_size = 100kb`, Git ignore handling enabled, and the console reporter
113
+ /// selected.
114
+ pub fn get_default_options() -> Options {
115
+ Options::default()
116
+ }
117
+
118
+ /// Parse upstream-style command-line arguments into normalized [`Options`].
119
+ ///
120
+ /// The first argument should be the binary name, just like `std::env::args`.
121
+ /// This is useful for native integrations that want the same option semantics
122
+ /// as the CLI without spawning a process.
123
+ pub fn get_options_from_args<I, T>(args: I) -> Result<Options>
124
+ where
125
+ I: IntoIterator<Item = T>,
126
+ T: Into<OsString> + Clone,
127
+ {
128
+ Options::from_args(args)
129
+ }
130
+
131
+ /// Return the names of all formats known to the synchronized format registry.
132
+ ///
133
+ /// The first release keeps the registry aligned with upstream `jscpd`; high
134
+ /// volume JS/TS formats use native Oxc-backed tokenization and long-tail
135
+ /// formats use the generic native tokenizer unless promoted by compatibility
136
+ /// evidence.
137
+ pub fn get_supported_formats() -> Vec<&'static str> {
138
+ formats::supported_formats()
139
+ }
140
+
141
+ /// Resolve a source format from a path using the built-in extension and
142
+ /// filename registry.
143
+ pub fn get_format_by_file(path: impl AsRef<Path>) -> Option<String> {
144
+ get_format_by_file_with_mappings(path, &FormatMappings::default(), &FormatMappings::default())
145
+ }
146
+
147
+ /// Resolve a source format from a path with caller-provided extension and
148
+ /// filename mappings.
149
+ ///
150
+ /// This mirrors the CLI `--formats-exts` and `--formats-names` options.
151
+ pub fn get_format_by_file_with_mappings(
152
+ path: impl AsRef<Path>,
153
+ formats_exts: &FormatMappings,
154
+ formats_names: &FormatMappings,
155
+ ) -> Option<String> {
156
+ formats::format_for_path(path.as_ref(), formats_exts, formats_names).map(str::to_string)
157
+ }
158
+
159
+ /// Detect clones from files discovered through [`Options::paths`].
160
+ ///
161
+ /// This is the compact path-based API when callers only need clone matches and
162
+ /// not the full statistics object.
163
+ pub fn detect_clones(options: &Options) -> Result<Vec<CloneMatch>> {
164
+ Ok(detect_clones_and_statistics(options)?.clones)
165
+ }
166
+
167
+ /// Upstream-named alias for [`detect_clones_and_statistics`].
168
+ ///
169
+ /// The singular `statistic` spelling is kept for callers porting from upstream
170
+ /// JavaScript APIs and examples.
171
+ pub fn detect_clones_and_statistic(options: &Options) -> Result<DetectionResult> {
172
+ detect_clones_and_statistics(options)
173
+ }
174
+
175
+ /// Detect clones and return both clone matches and aggregate statistics.
176
+ ///
177
+ /// This entry point performs ignore-aware file discovery from [`Options::paths`]
178
+ /// before delegating to the native detector. Use [`detect_source_files`] when
179
+ /// the caller already has source contents in memory.
180
+ pub fn detect_clones_and_statistics(options: &Options) -> Result<DetectionResult> {
181
+ let files = files::discover(options)?;
182
+ Ok(detect_source_files(files, options))
183
+ }
184
+
185
+ /// Detect clones in prepared in-memory sources.
186
+ ///
187
+ /// This is the lowest-friction API for editor integrations, tests, snippets,
188
+ /// and services that already own source contents. The `format` field on each
189
+ /// [`SourceFile`] should contain one of the names returned by
190
+ /// [`get_supported_formats`].
191
+ pub fn detect_source_files(files: Vec<SourceFile>, options: &Options) -> DetectionResult {
192
+ let mut result = detector::detect(files, options);
193
+ if options.blame {
194
+ blame::apply_blame(&mut result);
195
+ }
196
+ result
197
+ }
198
+
199
+ #[cfg(test)]
200
+ mod tests {
201
+ use std::path::PathBuf;
202
+
203
+ use super::*;
204
+
205
+ const DUPLICATE_JS: &str = "const alpha = 1;\nconst beta = 2;\nconst gamma = alpha + beta;\n";
206
+
207
+ fn fixture_options(path: &str) -> Options {
208
+ Options {
209
+ paths: vec![PathBuf::from(path)],
210
+ reporters: Vec::new(),
211
+ silent: true,
212
+ no_tips: true,
213
+ min_tokens: 20,
214
+ min_lines: 3,
215
+ max_size_bytes: 1024 * 1024,
216
+ ..Options::default()
217
+ }
218
+ }
219
+
220
+ fn in_memory_options() -> Options {
221
+ Options {
222
+ reporters: Vec::new(),
223
+ silent: true,
224
+ no_tips: true,
225
+ min_tokens: 5,
226
+ min_lines: 2,
227
+ ..Options::default()
228
+ }
229
+ }
230
+
231
+ fn javascript_source(source_id: &str, content: &str) -> SourceFile {
232
+ SourceFile {
233
+ source_id: source_id.to_string(),
234
+ format: "javascript".to_string(),
235
+ content: content.to_string(),
236
+ }
237
+ }
238
+
239
+ #[test]
240
+ fn public_api_detects_clones_from_paths() {
241
+ let options = fixture_options("jscpd/fixtures/clike/file2.c");
242
+
243
+ let clones = detect_clones(&options).expect("detect clones");
244
+
245
+ assert_eq!(clones.len(), 1);
246
+ assert_eq!(clones[0].duplication_a.start.line, 18);
247
+ assert_eq!(clones[0].duplication_b.start.line, 8);
248
+ }
249
+
250
+ #[test]
251
+ fn public_api_returns_statistics() {
252
+ let options = fixture_options("jscpd/fixtures/clike/file2.c");
253
+
254
+ let result = detect_clones_and_statistics(&options).expect("detect with statistics");
255
+
256
+ assert_eq!(result.clones.len(), 1);
257
+ assert_eq!(result.statistics.total.clones, 1);
258
+ assert_eq!(result.statistics.total.sources, 1);
259
+ }
260
+
261
+ #[test]
262
+ fn public_api_statistic_alias_matches_upstream_name() {
263
+ let options = fixture_options("jscpd/fixtures/clike/file2.c");
264
+
265
+ let result = detect_clones_and_statistic(&options).expect("detect with statistic alias");
266
+
267
+ assert_eq!(result.clones.len(), 1);
268
+ assert_eq!(result.statistics.total.clones, 1);
269
+ }
270
+
271
+ #[test]
272
+ fn public_api_exposes_default_options() {
273
+ let options = get_default_options();
274
+
275
+ assert_eq!(options.min_lines, 5);
276
+ assert_eq!(options.min_tokens, 50);
277
+ assert_eq!(options.max_lines, 1000);
278
+ assert_eq!(options.max_size_bytes, 100 * 1024);
279
+ assert_eq!(options.reporters, vec!["console"]);
280
+ assert!(options.cache);
281
+ assert!(options.gitignore);
282
+ }
283
+
284
+ #[test]
285
+ fn public_api_parses_options_from_args() {
286
+ let options = get_options_from_args([
287
+ "jscpd",
288
+ "fixtures",
289
+ "--format",
290
+ "javascript,typescript",
291
+ "--reporters",
292
+ "json",
293
+ "--min-tokens",
294
+ "7",
295
+ "--min-lines",
296
+ "2",
297
+ "--max-size",
298
+ "1mb",
299
+ "--noTips",
300
+ ])
301
+ .expect("parse options from argv");
302
+
303
+ let expected_formats = vec!["javascript".to_string(), "typescript".to_string()];
304
+ assert_eq!(options.paths, vec![PathBuf::from("fixtures")]);
305
+ assert_eq!(
306
+ options.format_order.as_deref(),
307
+ Some(expected_formats.as_slice())
308
+ );
309
+ assert_eq!(options.reporters, vec!["json"]);
310
+ assert_eq!(options.min_tokens, 7);
311
+ assert_eq!(options.min_lines, 2);
312
+ assert_eq!(options.max_size_bytes, 1024 * 1024);
313
+ assert!(options.no_tips);
314
+ }
315
+
316
+ #[test]
317
+ fn public_api_arg_parser_preserves_runtime_option_errors() {
318
+ let error = get_options_from_args(["jscpd", "--mode", "zzz", "."]).unwrap_err();
319
+
320
+ assert_eq!(error.to_string(), "Mode zzz does not supported yet.");
321
+ }
322
+
323
+ #[test]
324
+ fn public_api_exposes_supported_formats() {
325
+ let formats = get_supported_formats();
326
+
327
+ assert_eq!(formats.len(), 223);
328
+ assert!(formats.contains(&"javascript"));
329
+ assert!(formats.contains(&"typescript"));
330
+ assert!(formats.contains(&"rust"));
331
+ }
332
+
333
+ #[test]
334
+ fn public_api_resolves_format_by_file() {
335
+ assert_eq!(
336
+ get_format_by_file("src/index.mts").as_deref(),
337
+ Some("typescript")
338
+ );
339
+ assert_eq!(
340
+ get_format_by_file("src/component.vue").as_deref(),
341
+ Some("vue")
342
+ );
343
+ }
344
+
345
+ #[test]
346
+ fn public_api_resolves_format_by_custom_mappings() {
347
+ let formats_exts = FormatMappings::from_pairs(vec![("custom", vec!["foo"])]);
348
+ let formats_names = FormatMappings::from_pairs(vec![("makefile", vec!["Buildfile"])]);
349
+
350
+ assert_eq!(
351
+ get_format_by_file_with_mappings("demo.foo", &formats_exts, &formats_names).as_deref(),
352
+ Some("custom")
353
+ );
354
+ assert_eq!(
355
+ get_format_by_file_with_mappings("Buildfile", &formats_exts, &formats_names).as_deref(),
356
+ Some("makefile")
357
+ );
358
+ assert_eq!(
359
+ get_format_by_file_with_mappings("src/index.ts", &formats_exts, &formats_names),
360
+ None
361
+ );
362
+ }
363
+
364
+ #[test]
365
+ fn public_api_detects_from_in_memory_sources() {
366
+ let files = vec![
367
+ javascript_source("snippet.js", DUPLICATE_JS),
368
+ javascript_source("src/match.js", DUPLICATE_JS),
369
+ ];
370
+
371
+ let result = detect_source_files(files, &in_memory_options());
372
+
373
+ assert_eq!(result.clones.len(), 1);
374
+ assert_eq!(result.statistics.total.sources, 2);
375
+ }
376
+
377
+ #[test]
378
+ fn public_api_exposes_streaming_detector() {
379
+ let mut detector = Detector::new(in_memory_options());
380
+
381
+ assert!(
382
+ detector
383
+ .detect("first.js", DUPLICATE_JS, "javascript")
384
+ .is_empty()
385
+ );
386
+ let clones = detector.detect("second.js", DUPLICATE_JS, "javascript");
387
+
388
+ assert_eq!(clones.len(), 1);
389
+ assert_eq!(detector.sources().len(), 2);
390
+ assert!(
391
+ clones[0].duplication_a.source_id == "second.js"
392
+ || clones[0].duplication_b.source_id == "second.js"
393
+ );
394
+ }
395
+
396
+ #[test]
397
+ fn public_api_exposes_statistic_collector() {
398
+ let result = detect_source_files(
399
+ vec![
400
+ javascript_source("first.js", DUPLICATE_JS),
401
+ javascript_source("second.js", DUPLICATE_JS),
402
+ ],
403
+ &in_memory_options(),
404
+ );
405
+ let mut statistic = Statistic::new();
406
+
407
+ statistic.match_source("first.js", "javascript", 3, 42);
408
+ statistic.match_source("second.js", "javascript", 3, 42);
409
+ statistic.clone_found(&result.clones[0]);
410
+
411
+ let stats = statistic.get_statistic();
412
+ assert_eq!(stats.total.sources, 2);
413
+ assert_eq!(stats.total.clones, 1);
414
+ assert_eq!(stats.formats["javascript"].sources["first.js"].sources, 1);
415
+ }
416
+
417
+ #[test]
418
+ fn public_api_exposes_memory_store() {
419
+ let mut store = MemoryStore::new();
420
+
421
+ store.namespace("javascript");
422
+ assert_eq!(*store.set("hash", 7usize), 7);
423
+ assert_eq!(*store.get("hash").expect("stored value"), 7);
424
+ store.namespace("typescript");
425
+ let error = store.get("hash").unwrap_err();
426
+
427
+ assert_eq!(error.namespace(), "typescript");
428
+ assert_eq!(error.key(), "hash");
429
+ assert_eq!(store.len(), 1);
430
+ store.close();
431
+ assert!(store.is_empty());
432
+ }
433
+ }
package/src/main.rs ADDED
@@ -0,0 +1,26 @@
1
+ use jscpd_rs::{app, report};
2
+
3
+ fn main() {
4
+ match app::run_current_process() {
5
+ Ok(outcome) => {
6
+ if let Some(code) = outcome.exit_code
7
+ && code != 0
8
+ {
9
+ std::process::exit(code);
10
+ }
11
+ }
12
+ Err(error) => {
13
+ if let Some(threshold) = error.downcast_ref::<report::ThresholdExceeded>() {
14
+ eprintln!("{}", threshold.message());
15
+ std::process::exit(1);
16
+ }
17
+ let message = error.to_string();
18
+ if let Some(stdout_error) = app::upstream_stdout_error(&message) {
19
+ println!("{stdout_error}");
20
+ std::process::exit(1);
21
+ }
22
+ eprintln!("error: {error:#}");
23
+ std::process::exit(1);
24
+ }
25
+ }
26
+ }
@@ -0,0 +1,125 @@
1
+ use crate::cli::Options;
2
+ use crate::detector::{CloneMatch, DetectionResult};
3
+
4
+ pub(super) fn write(result: &DetectionResult, options: &Options) {
5
+ if options.silent {
6
+ return;
7
+ }
8
+
9
+ println!("Clones:");
10
+ for clone in &result.clones {
11
+ println!("{}", clone_line(clone));
12
+ }
13
+ println!("---");
14
+ println!(
15
+ "{} clones · {:.1}% duplication",
16
+ result.clones.len(),
17
+ result.statistics.total.percentage
18
+ );
19
+ }
20
+
21
+ fn clone_line(clone: &CloneMatch) -> String {
22
+ compress_clone_line(
23
+ &clone.duplication_a.source_id,
24
+ &clone.duplication_b.source_id,
25
+ &format_range(clone.duplication_a.start.line, clone.duplication_a.end.line),
26
+ &format_range(clone.duplication_b.start.line, clone.duplication_b.end.line),
27
+ )
28
+ }
29
+
30
+ fn normalize_path(path: &str) -> String {
31
+ path.replace('\\', "/")
32
+ }
33
+
34
+ fn format_range(start: usize, end: usize) -> String {
35
+ format!("{start}-{end}")
36
+ }
37
+
38
+ fn compress_clone_line(path_a: &str, path_b: &str, range_a: &str, range_b: &str) -> String {
39
+ let norm_a = normalize_path(path_a);
40
+ let norm_b = normalize_path(path_b);
41
+
42
+ if norm_a == norm_b {
43
+ return format!("{norm_a} {range_a} ~ {range_b}");
44
+ }
45
+
46
+ let parts_a = norm_a.split('/').collect::<Vec<_>>();
47
+ let parts_b = norm_b.split('/').collect::<Vec<_>>();
48
+ let mut common_len = 0;
49
+ let min_len = parts_a.len().min(parts_b.len());
50
+ while common_len < min_len.saturating_sub(1) && parts_a[common_len] == parts_b[common_len] {
51
+ common_len += 1;
52
+ }
53
+
54
+ if common_len == 0 {
55
+ return format!("{norm_a}:{range_a} ~ {norm_b}:{range_b}");
56
+ }
57
+
58
+ let prefix = parts_a[..common_len].join("/");
59
+ let rem_a = parts_a[common_len..].join("/");
60
+ let rem_b = parts_b[common_len..].join("/");
61
+ format!("{prefix}/ {rem_a}:{range_a} ~ {rem_b}:{range_b}")
62
+ }
63
+
64
+ #[cfg(test)]
65
+ mod tests {
66
+ use super::*;
67
+ use crate::report::test_support::make_test_clone;
68
+
69
+ #[test]
70
+ fn compress_clone_line_same_file_matches_upstream() {
71
+ assert_eq!(
72
+ compress_clone_line("src/utils/auth.ts", "src/utils/auth.ts", "10-25", "80-95"),
73
+ "src/utils/auth.ts 10-25 ~ 80-95"
74
+ );
75
+ }
76
+
77
+ #[test]
78
+ fn compress_clone_line_same_directory_matches_upstream() {
79
+ assert_eq!(
80
+ compress_clone_line(
81
+ "src/utils/auth.ts",
82
+ "src/utils/helpers.ts",
83
+ "10-25",
84
+ "40-55"
85
+ ),
86
+ "src/utils/ auth.ts:10-25 ~ helpers.ts:40-55"
87
+ );
88
+ }
89
+
90
+ #[test]
91
+ fn compress_clone_line_cross_directory_matches_upstream() {
92
+ assert_eq!(
93
+ compress_clone_line("src/utils/auth.ts", "src/api/routes.ts", "10-25", "5-20"),
94
+ "src/ utils/auth.ts:10-25 ~ api/routes.ts:5-20"
95
+ );
96
+ }
97
+
98
+ #[test]
99
+ fn compress_clone_line_no_common_prefix_matches_upstream() {
100
+ assert_eq!(
101
+ compress_clone_line("apps/a/foo.ts", "packages/b/bar.ts", "1-10", "5-15"),
102
+ "apps/a/foo.ts:1-10 ~ packages/b/bar.ts:5-15"
103
+ );
104
+ }
105
+
106
+ #[test]
107
+ fn compress_clone_line_normalizes_windows_paths() {
108
+ assert_eq!(
109
+ compress_clone_line(
110
+ "src\\utils\\auth.ts",
111
+ "src\\utils\\helpers.ts",
112
+ "10-25",
113
+ "40-55"
114
+ ),
115
+ "src/utils/ auth.ts:10-25 ~ helpers.ts:40-55"
116
+ );
117
+ }
118
+
119
+ #[test]
120
+ fn clone_line_uses_clone_ranges() {
121
+ let clone = make_test_clone("src/a.js", "src/b.js");
122
+
123
+ assert_eq!(clone_line(&clone), "src/ a.js:2-5 ~ b.js:8-11");
124
+ }
125
+ }