churn_vs_complexity 1.8.0 → 2.0.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 (103) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +95 -0
  3. data/README.md +46 -23
  4. data/bin/churn_vs_complexity +6 -1
  5. data/lib/churn_vs_complexity/analysis_scope.rb +20 -0
  6. data/lib/churn_vs_complexity/churn.rb +41 -8
  7. data/lib/churn_vs_complexity/cli/main.rb +58 -19
  8. data/lib/churn_vs_complexity/cli/parser.rb +85 -121
  9. data/lib/churn_vs_complexity/cli.rb +2 -3
  10. data/lib/churn_vs_complexity/complexity/flog_calculator.rb +0 -3
  11. data/lib/churn_vs_complexity/complexity/lizard_calculator.rb +64 -0
  12. data/lib/churn_vs_complexity/complexity.rb +1 -7
  13. data/lib/churn_vs_complexity/complexity_validator.rb +1 -16
  14. data/lib/churn_vs_complexity/concurrent_calculator.rb +20 -23
  15. data/lib/churn_vs_complexity/delta/checker.rb +35 -21
  16. data/lib/churn_vs_complexity/delta/commit_hydrator.rb +1 -1
  17. data/lib/churn_vs_complexity/delta/complexity_annotator.rb +23 -5
  18. data/lib/churn_vs_complexity/delta/config.rb +15 -16
  19. data/lib/churn_vs_complexity/delta/factory.rb +2 -2
  20. data/lib/churn_vs_complexity/delta/multi_checker.rb +24 -25
  21. data/lib/churn_vs_complexity/delta/serializer.rb +7 -4
  22. data/lib/churn_vs_complexity/delta.rb +11 -49
  23. data/lib/churn_vs_complexity/diff/checker.rb +10 -3
  24. data/lib/churn_vs_complexity/diff/config.rb +29 -20
  25. data/lib/churn_vs_complexity/file_selector.rb +63 -114
  26. data/lib/churn_vs_complexity/focus/config.rb +42 -32
  27. data/lib/churn_vs_complexity/focus/serializer.rb +17 -4
  28. data/lib/churn_vs_complexity/gate/config.rb +35 -25
  29. data/lib/churn_vs_complexity/gate/serializer.rb +9 -2
  30. data/lib/churn_vs_complexity/git_strategy.rb +29 -10
  31. data/lib/churn_vs_complexity/hotspots/config.rb +29 -25
  32. data/lib/churn_vs_complexity/language_registry.rb +108 -0
  33. data/lib/churn_vs_complexity/language_validator.rb +1 -3
  34. data/lib/churn_vs_complexity/normal/config.rb +31 -100
  35. data/lib/churn_vs_complexity/normal/serializer/graph.rb +3 -2
  36. data/lib/churn_vs_complexity/normal/serializer/summary.rb +18 -14
  37. data/lib/churn_vs_complexity/normal/serializer/summary_hash.rb +36 -21
  38. data/lib/churn_vs_complexity/normal/serializer.rb +2 -1
  39. data/lib/churn_vs_complexity/normal.rb +17 -13
  40. data/lib/churn_vs_complexity/risk_classifier.rb +3 -19
  41. data/lib/churn_vs_complexity/timetravel/config.rb +34 -47
  42. data/lib/churn_vs_complexity/timetravel/schedule.rb +15 -0
  43. data/lib/churn_vs_complexity/timetravel/serializer/stats_calculator.rb +36 -32
  44. data/lib/churn_vs_complexity/timetravel/serializer.rb +16 -24
  45. data/lib/churn_vs_complexity/timetravel/traveller.rb +46 -15
  46. data/lib/churn_vs_complexity/timetravel.rb +36 -14
  47. data/lib/churn_vs_complexity/triage/checker.rb +24 -28
  48. data/lib/churn_vs_complexity/triage/collaborator_set.rb +11 -0
  49. data/lib/churn_vs_complexity/triage/config.rb +29 -26
  50. data/lib/churn_vs_complexity/triage.rb +1 -0
  51. data/lib/churn_vs_complexity/validator_set.rb +9 -0
  52. data/lib/churn_vs_complexity/version.rb +1 -1
  53. data/lib/churn_vs_complexity.rb +3 -0
  54. metadata +18 -59
  55. data/.devcontainer/devcontainer.json +0 -26
  56. data/.rubocop.yml +0 -25
  57. data/CLAUDE.md +0 -60
  58. data/Dockerfile +0 -34
  59. data/Dockerfile.dev +0 -27
  60. data/Rakefile +0 -6
  61. data/TODO +0 -11
  62. data/lib/churn_vs_complexity/complexity/eslint_calculator.rb +0 -40
  63. data/lib/churn_vs_complexity/complexity/go_calculator.rb +0 -48
  64. data/lib/churn_vs_complexity/complexity/kotlin_calculator.rb +0 -54
  65. data/lib/churn_vs_complexity/complexity/pmd/files_calculator.rb +0 -26
  66. data/lib/churn_vs_complexity/complexity/pmd/folder_calculator.rb +0 -20
  67. data/lib/churn_vs_complexity/complexity/pmd.rb +0 -54
  68. data/lib/churn_vs_complexity/complexity/python_calculator.rb +0 -50
  69. data/lib/churn_vs_complexity/complexity/rust_calculator.rb +0 -54
  70. data/lib/churn_vs_complexity/complexity/swift_calculator.rb +0 -54
  71. data/package-lock.json +0 -6
  72. data/tmp/eslint-support/complexity-calculator.js +0 -51
  73. data/tmp/eslint-support/package.json +0 -11
  74. data/tmp/pmd-support/ruleset.xml +0 -21
  75. data/tmp/test-support/delta/ruby-summary.txt +0 -55
  76. data/tmp/test-support/delta/ruby.csv +0 -12
  77. data/tmp/test-support/go/main.go +0 -11
  78. data/tmp/test-support/go/utils.go +0 -13
  79. data/tmp/test-support/java/small-example/src/main/java/org/example/Main.java +0 -10
  80. data/tmp/test-support/java/small-example/src/main/java/org/example/spice/Checker.java +0 -28
  81. data/tmp/test-support/javascript/complex.js +0 -43
  82. data/tmp/test-support/javascript/moderate.js +0 -12
  83. data/tmp/test-support/javascript/simple.js +0 -5
  84. data/tmp/test-support/javascript/typescript-example.ts +0 -26
  85. data/tmp/test-support/kotlin/Main.kt +0 -7
  86. data/tmp/test-support/kotlin/Utils.kt +0 -11
  87. data/tmp/test-support/python/example.py +0 -6
  88. data/tmp/test-support/python/utils.py +0 -9
  89. data/tmp/test-support/rust/main.rs +0 -7
  90. data/tmp/test-support/rust/utils.rs +0 -20
  91. data/tmp/test-support/swift/main.swift +0 -7
  92. data/tmp/test-support/swift/utils.swift +0 -24
  93. data/tmp/test-support/txt/abc.txt +0 -0
  94. data/tmp/test-support/txt/d.txt +0 -0
  95. data/tmp/test-support/txt/ef.txt +0 -0
  96. data/tmp/test-support/txt/ghij.txt +0 -0
  97. data/tmp/test-support/txt/klm.txt +0 -0
  98. data/tmp/test-support/txt/nopq.txt +0 -0
  99. data/tmp/test-support/txt/r.txt +0 -0
  100. data/tmp/test-support/txt/st.txt +0 -0
  101. data/tmp/test-support/txt/uvx.txt +0 -0
  102. data/tmp/test-support/txt/yz.txt +0 -0
  103. data/tmp/timetravel/.keep +0 -0
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b5a149d026d33ac7319cc78d8c57af7e03113edf42d69f35612bbd72be708c77
4
- data.tar.gz: c87fb3252fc699c681fd8da590fe02fe2d06e47b85fd5b7667fe314bd8ce3393
3
+ metadata.gz: fead91605b8e6bb82370f0b7265622cf42ea15a19ec322ed5f44643912e2cfb4
4
+ data.tar.gz: b6bce4c0b63b52533c6e6bfb6b1816c16a12b9c53d1c69f6cacb781a65d45165
5
5
  SHA512:
6
- metadata.gz: '09d8eddfd30cd8c56abbd200d5f4e31529ac5fc1171837e3420ccfe2536bf203e3d003a8fbebe7c4c6b0fb54be9a84d71071ca447b9526538edd814953c8b436'
7
- data.tar.gz: ad11518d39553ff5b03fb6c8ea0bc44989ba47d034cbd3b82582279055cad86806612cf0f71c1888b6ecf2aa312a20afce3ad80c8d36b5ab85480152e213e570
6
+ metadata.gz: 03b64889da02cd18e0ae7320f67763505d3f8ceb767acf55e362c96a9841df9b27ee033f6e87374a4499a5b2beb56e61e55b1f066d2e569b05ee26ebcb67baf9
7
+ data.tar.gz: b16173fbdcdb886b912e99ea551b431d3ec91274e5c45eb4659d5c7b69bd22319a340a001f8bfacff74795d52869538810438eaeb461e966669a74470550e975
data/CHANGELOG.md CHANGED
@@ -1,3 +1,98 @@
1
+ ## [2.0.0] - 2026-12-06
2
+
3
+ ### Changed
4
+ - Breaking change: all non-Ruby languages now use Lizard (`pip install lizard`)
5
+ for cyclomatic complexity instead of separate per-language tools. PMD (Java),
6
+ ESLint (JavaScript/TypeScript), Radon (Python), and gocognit (Go) are
7
+ removed, along with their bundled helper assets. Ruby continues to use the
8
+ bundled Flog gem.
9
+ - Breaking change: Go risk thresholds now use the standard Lizard defaults
10
+ (low=10, high=25) instead of the previous gocognit override (15/40). Only
11
+ Ruby uses separate thresholds (30/70).
12
+ - JavaScript and TypeScript analysis now includes `.cjs` and `.mjs` files,
13
+ accepts `--jsx` and `--tsx` flag aliases, and excludes `node_modules` by
14
+ default.
15
+ - Runtime dependencies move to `flog ~> 4.10` and `git ~> 6.0` (Ruby >= 3.3, git >= 2.43).
16
+
17
+ ### Added
18
+ - Support for 17 additional languages via Lizard (25 languages total): C/C++
19
+ (`--cpp`, `--c++`, `--c`), C# (`--csharp`, `--cs`), Objective-C (`--objc`,
20
+ `--objective-c`, `--objectivec`), PHP (`--php`), Scala (`--scala`), GDScript
21
+ (`--gdscript`), Lua (`--lua`), Fortran (`--fortran`), Solidity (`--solidity`),
22
+ Erlang (`--erlang`, requires Pygments), Zig (`--zig`), Vue (`--vue`,
23
+ `--vuejs`), Perl (`--perl`), TTCN-3 (`--ttcn`, `--ttcn3`), Structured Text
24
+ (`--st`, `--structured-text`), R (`--r`), and PL/SQL (`--plsql`).
25
+
26
+ ### Fixed
27
+ - `--triage` now accepts one or more file paths on the command line instead
28
+ of rejecting non-directory arguments.
29
+ - Running any mode against a repository subdirectory (such as `lib` or a file
30
+ path inside a repository) previously reported zero churn because git lookup
31
+ assumed `.git` lived inside the target folder. Git discovery now resolves the
32
+ repository root.
33
+ - `--triage` now supports Kotlin, Rust, and Swift alongside all other
34
+ registered languages.
35
+ - Worktrees created by `--diff`, `--delta`, and `--timetravel` now run detached
36
+ (`--detach`), stopping permanent `worktree_*` local branches from
37
+ accumulating in the analysed repository, and timetravel waits for worker
38
+ cleanup before returning.
39
+ - Timetravel with no `--since` date previously passed `1970-01-01T00:00:00` in
40
+ local time, which resolved to a negative Unix timestamp in UTC+ timezones
41
+ and returned zero commits.
42
+ - Replaced deprecated `Git::GitExecuteError` rescue with `Git::Error` for `git`
43
+ 6.0 compatibility.
44
+ - Relative folder paths analysed from outside the target repository (such as
45
+ `churn_vs_complexity --ruby --csv my_project`) resolved against the working
46
+ directory's work-tree and reported zero churn. Paths are now expanded before
47
+ invoking git.
48
+ - Relative period flags (`-m`, `-q`, `-y`) now apply in `--hotspots`,
49
+ `--triage`, `--gate`, `--focus`, and `--diff` instead of being silently
50
+ ignored.
51
+ - Passing an unsupported output format flag to `--diff`, `--hotspots`,
52
+ `--gate`, `--triage`, `--focus`, or `--delta` now raises a validation error
53
+ (exit 1) instead of crashing with `NoMethodError`.
54
+ - Timetravel now closes the parent's pipe write handle after forking so a
55
+ failing worker cannot deadlock the parent waiting for EOF.
56
+
57
+ ## [1.9.0] - 2026-09-20
58
+
59
+ ### Fixed
60
+ - Churn counted only the commits made since the 30th most recent commit. The
61
+ underlying `git` gem caps a log at 30 entries by default, and the clamp that
62
+ is meant to stop `--since` reaching past the first commit was reading that cap
63
+ as the first commit. Any repository with more than 30 commits was undercounted.
64
+ - Timetravel built its commit window from bare dates, which git treats as
65
+ approximate and resolves against the clock and the timezone. Commits on the
66
+ first and last day of the period were included or dropped depending on when
67
+ and where the command ran. Both ends are now given an explicit time.
68
+ - Running any mode against a repository with no commits raised
69
+ `NoMethodError: undefined method 'date' for nil`. It now says which folder has
70
+ no commits.
71
+ - Errors the tool raises on purpose, such as telling you which analyser to
72
+ install, were printed underneath a backtrace. The backtrace is now kept for
73
+ genuinely unexpected failures. These still exit 2, so a gate failure (exit 1)
74
+ stays distinguishable from a tool that could not run.
75
+ - `--gate --max-gamma 0` crashed with `FloatDomainError: Infinity`, because the
76
+ percentage by which a score exceeds the threshold divided by it. Violations are
77
+ now reported against a zero threshold with `exceeds_by` set to null.
78
+ - A negative `--max-gamma` is now rejected instead of reporting every file as a
79
+ violation with a negative excess.
80
+ - Timetravel raised `ArgumentError: invalid slice size` when no commits fell in
81
+ the requested period. An empty period now produces an empty result.
82
+ - The `churn_vs_complexity` executable failed with a `LoadError` when run from
83
+ inside a project that uses Bundler, which is most of the repositories the tool
84
+ exists to analyse. It required `bundler/setup`, so it resolved against the
85
+ analysed project's Gemfile instead of its own installed gems.
86
+
87
+ ### Changed
88
+ - The `git` dependency moves from 2.x to 5.x and `flog` from 4.8 to 4.9.
89
+ - The published gem no longer carries the test fixtures, the Dockerfiles or the
90
+ other development files it had been shipping.
91
+
92
+ ### Documentation
93
+ - The README told Go users to install gocyclo. The Go calculator runs gocognit,
94
+ and has since Go support was added.
95
+
1
96
  ## [1.8.0] - 2026-04-05
2
97
 
3
98
  ### Added
data/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  # ChurnVsComplexity
4
4
 
5
- Correlates file churn (how often files change) with complexity scores to identify refactoring hotspots and track codebase health over time. Supports Ruby, JavaScript/TypeScript, Java, Python, Go, Kotlin, Rust, and Swift.
5
+ Correlates file churn (how often files change) with complexity scores to find refactoring hotspots and track codebase health over time. Supports Ruby (via Flog) and 24 languages via Lizard: Java, JavaScript/TypeScript, Python, Go, Kotlin, Rust, Swift, C/C++, C#, Objective-C, PHP, Scala, GDScript, Lua, Fortran, Solidity, Erlang, Zig, Vue, Perl, TTCN-3, Structured Text, R, and PL/SQL.
6
6
 
7
7
  Modes include hotspots ranking, triage assessment, CI quality gate, diff comparison, focus sessions, and timetravel history.
8
8
 
@@ -10,6 +10,8 @@ Inspired by [Michael Feathers' article "Getting Empirical about Refactoring"](ht
10
10
 
11
11
  ## Installation
12
12
 
13
+ Requires Ruby >= 3.3 and git >= 2.43 for churn analysis.
14
+
13
15
  Add this line to your application's Gemfile:
14
16
 
15
17
  ```ruby
@@ -24,22 +26,15 @@ Or install it yourself as:
24
26
 
25
27
  $ gem install churn_vs_complexity
26
28
 
27
- This gem depends on git for churn analysis.
28
-
29
- External tool dependencies per language:
29
+ Complexity tools by language:
30
30
 
31
- - **Ruby**: None (uses [Flog](https://rubygems.org/gems/flog), bundled as a gem dependency).
32
- - **Java**: Requires [PMD](https://pmd.github.io) on the search path as `pmd`. On macOS: `brew install pmd`.
33
- - **JavaScript/TypeScript**: Requires [Node.js](https://nodejs.org) (uses ESLint internally).
34
- - **Python**: Requires [Radon](https://radon.readthedocs.io) on the search path as `radon`. Install with `pip install radon`.
35
- - **Go**: Requires [gocyclo](https://github.com/fzipp/gocyclo) on the search path. Install with `go install github.com/fzipp/gocyclo/cmd/gocyclo@latest`.
36
- - **Kotlin**: Requires [lizard](https://github.com/terryyin/lizard) on the search path. Install with `pip install lizard`.
37
- - **Rust**: Requires [lizard](https://github.com/terryyin/lizard) on the search path. Install with `pip install lizard`.
38
- - **Swift**: Requires [lizard](https://github.com/terryyin/lizard) on the search path. Install with `pip install lizard`.
31
+ - Ruby uses the bundled [Flog](https://rubygems.org/gems/flog) gem (no external tool required).
32
+ - All other 24 supported languages use [Lizard](https://github.com/terryyin/lizard) on your `PATH`. Install it with `pip install lizard` or `pipx install lizard`.
33
+ - Erlang analysis through Lizard also requires Pygments (`pip install pygments`).
39
34
 
40
35
  ## Usage
41
36
 
42
- Execute `churn_vs_complexity` with the applicable arguments. Output in the requested format will be directed to stdout.
37
+ Execute `churn_vs_complexity` with the applicable arguments. Output in the requested format goes to stdout.
43
38
 
44
39
  ```
45
40
  Usage: churn_vs_complexity [options] folder|file...
@@ -47,13 +42,31 @@ Usage: churn_vs_complexity [options] folder|file...
47
42
  Languages:
48
43
  --java Check complexity of java classes
49
44
  --ruby Check complexity of ruby files
50
- --js, --ts, --javascript, --typescript
45
+ --js, --ts, --javascript, --typescript, --jsx, --tsx
51
46
  Check complexity of javascript and typescript files
52
47
  --python Check complexity of python files
53
48
  --go Check complexity of go files
54
49
  --kotlin Check complexity of kotlin files
55
50
  --rust Check complexity of rust files
56
51
  --swift Check complexity of swift files
52
+ --cpp, --c++, --c Check complexity of c/c++ files
53
+ --csharp, --cs Check complexity of c# files
54
+ --objc, --objective-c, --objectivec
55
+ Check complexity of objective-c files
56
+ --php Check complexity of php files
57
+ --scala Check complexity of scala files
58
+ --gdscript Check complexity of gdscript files
59
+ --lua Check complexity of lua files
60
+ --fortran Check complexity of fortran files
61
+ --solidity Check complexity of solidity files
62
+ --erlang Check complexity of erlang files
63
+ --zig Check complexity of zig files
64
+ --vue, --vuejs Check complexity of vue files
65
+ --perl Check complexity of perl files
66
+ --ttcn, --ttcn3 Check complexity of ttcn-3 files
67
+ --st, --structured-text Check complexity of structured text files
68
+ --r Check complexity of r files
69
+ --plsql Check complexity of pl/sql files
57
70
 
58
71
  Modes (mutually exclusive):
59
72
  --timetravel N Calculate summary for all commits at intervals of N days throughout project history or from the date specified with --since
@@ -83,16 +96,26 @@ Modifiers:
83
96
  --version Display version
84
97
  ```
85
98
 
86
- Note that when using the `--timetravel` mode, the semantics of some flags are subtly different from normal mode:
99
+ When using `--timetravel`, two flags change meaning compared to normal mode:
87
100
 
88
- * `--since YYYY-MM-DD`: Calculate summaries from this date
89
- * `--month`, `--quarter`, `--year`: Calculate churn for the period leading up to each commit being summarised
101
+ * `--since YYYY-MM-DD` calculates summaries from this date
102
+ * `--month`, `--quarter`, `--year` calculate churn for the period leading up to each commit being summarised
90
103
 
91
104
  Timetravel analysis can take many minutes for old and large repositories.
92
105
 
93
- Summaries in normal mode include a gamma score, which is an unnormalised harmonic mean of churn and complexity. This allows for comparison of summaries across different projects with the same language, or over time for a single project.
106
+ Summaries in normal mode include a gamma score, which is an unnormalised harmonic mean of churn and complexity. This lets you compare summaries across projects using the same language, or over time for a single project.
107
+
108
+ Summary points in timetravel mode instead include an alpha score, which is the same harmonic mean of churn and complexity with both values normalised to a 0 to 1 range so neither dominates the score. They also include a beta score, which is the geometric mean of those normalised values.
109
+
110
+ ## Risk Thresholds
111
+
112
+ Modes that classify risk (`--hotspots`, `--triage`, and `--focus`) group files into low, medium, and high risk from their gamma score.
113
+
114
+ | Language | Tool | Low | Medium | High |
115
+ |---|---|---|---|---|
116
+ | Ruby | Flog | `< 30` | `30` to `70` | `> 70` |
117
+ | All other 24 languages | Lizard (cyclomatic complexity) | `< 10` | `10` to `25` | `> 25` |
94
118
 
95
- Summary points in timetravel mode instead include an alpha score, which is the same harmonic mean of churn and complexity, where churn and complexity values are normalised to a 0-1 range to avoid either churn or complexity dominating the score. The summary points also include a beta score, which is the geometric mean of the normalised churn and complexity values.
96
119
  ## Examples
97
120
 
98
121
  ```bash
@@ -115,11 +138,11 @@ churn_vs_complexity --ruby --gate --max-gamma 30 my_ruby_project
115
138
  churn_vs_complexity --go --triage src/server.go src/handler.go
116
139
 
117
140
  # Compare codebase health between a branch and HEAD
118
- churn_vs_complexity --ruby --diff origin/main --summary my_ruby_project
141
+ churn_vs_complexity --ruby --diff origin/main my_ruby_project
119
142
 
120
143
  # Focus session: snapshot before and after a coding session
121
144
  churn_vs_complexity --ruby --focus start my_ruby_project
122
- # ... do some coding ...
145
+ # make your edits
123
146
  churn_vs_complexity --ruby --focus end my_ruby_project
124
147
 
125
148
  # Timetravel: track quality over time at 30-day intervals
@@ -140,9 +163,9 @@ churn_vs_complexity --swift --summary -q my_swift_project
140
163
 
141
164
  ## Development
142
165
 
143
- After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
166
+ After checking out the repo, run `bin/setup` to install dependencies. Run `bundle exec rake` to run the full test suite and RuboCop, `bundle exec rake fast` for unit and acceptance tests, `bundle exec rake integration` for integration tests, and `bundle exec rubocop` for linting alone. You can also run `bin/console` for an interactive prompt.
144
167
 
145
- To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
168
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `lib/churn_vs_complexity/version.rb`, and then run `bundle exec rake release`, which creates a git tag for the version, pushes git commits and tags, and pushes the `.gem` file to [rubygems.org](https://rubygems.org).
146
169
 
147
170
  ## Contributing
148
171
 
@@ -1,7 +1,6 @@
1
1
  #!/usr/bin/env ruby
2
2
  # frozen_string_literal: true
3
3
 
4
- require 'bundler/setup'
5
4
  require 'churn_vs_complexity'
6
5
 
7
6
  begin
@@ -9,6 +8,12 @@ begin
9
8
  rescue ChurnVsComplexity::ValidationError => e
10
9
  warn e.message
11
10
  exit 1
11
+ rescue ChurnVsComplexity::Error => e
12
+ # Raised deliberately, so the message is the point and a backtrace only
13
+ # buries it. Exit 2, because exit 1 is how the gate reports a codebase that
14
+ # failed its threshold.
15
+ warn e.message
16
+ exit 2
12
17
  rescue StandardError => e
13
18
  warn e.backtrace
14
19
  warn e.message
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ChurnVsComplexity
4
+ AnalysisScope = Data.define(:language, :excluded, :since, :relative_period) do
5
+ def initialize(language:, excluded: [], since: nil, relative_period: nil)
6
+ super(language:, excluded: Array(excluded).dup.freeze, since:, relative_period:)
7
+ end
8
+
9
+ def self.from_options(options)
10
+ new(
11
+ language: options[:language],
12
+ excluded: options.fetch(:excluded, []),
13
+ since: options[:since],
14
+ relative_period: options[:relative_period],
15
+ )
16
+ end
17
+
18
+ def effective_since = since || relative_period
19
+ end
20
+ end
@@ -15,25 +15,58 @@ module ChurnVsComplexity
15
15
  module GitCalculator
16
16
  class << self
17
17
  def calculate(folder:, file:, since:)
18
- git_dir = File.join(folder, '.git')
19
- earliest_date = [date_of_first_commit(folder:), since].max
18
+ git_repo = repo(folder)
19
+ earliest_date = [date_of_first_commit(git_repo), since].max
20
20
  formatted_date = earliest_date.strftime('%Y-%m-%dT00:00:00')
21
- cmd = %(git --git-dir #{git_dir} --work-tree #{folder} log --format="%H" --follow --since="#{formatted_date}" -- #{file} | wc -l)
22
- `(#{cmd}) 2>/dev/null`.to_i
21
+ path = pathspec_for(git_repo, file)
22
+ output = run_git(git_repo, 'log', '--format=%H', '--follow', "--since=#{formatted_date}", '--', path)
23
+ output.lines.size
23
24
  end
24
25
 
25
26
  def date_of_latest_commit(folder:)
26
- repo(folder).log.first.date
27
+ latest = repo(folder).log(1).execute.first
28
+ raise Error, "#{folder} has no commits to measure churn against" if latest.nil?
29
+
30
+ latest.date
27
31
  end
28
32
 
29
33
  private
30
34
 
31
- def date_of_first_commit(folder:)
32
- repo(folder).log.last&.date&.to_date || Time.at(0).to_date
35
+ # Asks git for the root commits directly. Reading it off `repo(folder).log`
36
+ # instead would silently answer with the 30th most recent commit, because
37
+ # that is where the git gem caps a log by default.
38
+ def date_of_first_commit(git_repo)
39
+ output = run_git(git_repo, 'log', '--max-parents=0', '--format=%ad', '--date=short')
40
+ dates = output.lines.filter_map { |line| parse_date(line.chomp) }
41
+ dates.min || Time.at(0).to_date
42
+ end
43
+
44
+ def run_git(git_repo, *args)
45
+ command = ['git', '--git-dir', git_repo.repo.to_s, '--work-tree', git_repo.dir.to_s, *args]
46
+ IO.popen(command, err: File::NULL, &:read)
47
+ end
48
+
49
+ def parse_date(line)
50
+ Date.parse(line)
51
+ rescue Date::Error
52
+ nil
53
+ end
54
+
55
+ def pathspec_for(git_repo, file)
56
+ return file unless File.exist?(file)
57
+
58
+ work_tree = File.realpath(git_repo.dir.to_s)
59
+ resolved = File.join(File.realpath(File.dirname(file)), File.basename(file))
60
+ resolved.start_with?("#{work_tree}/") ? resolved.delete_prefix("#{work_tree}/") : file
33
61
  end
34
62
 
35
63
  def repo(folder)
36
- repos[folder] ||= Git.open(folder)
64
+ key = File.expand_path(folder)
65
+ repo_mutex.synchronize { repos[key] ||= Git.open(folder) }
66
+ end
67
+
68
+ def repo_mutex
69
+ @repo_mutex ||= Mutex.new
37
70
  end
38
71
 
39
72
  def repos
@@ -5,17 +5,56 @@ require 'optparse'
5
5
  module ChurnVsComplexity
6
6
  module CLI
7
7
  module Main
8
+ MODES_WITHOUT_SERIALIZER = %i[triage hotspots gate focus diff].freeze
9
+
8
10
  class << self
9
- def run!(options, folder)
11
+ def run!(options, folder, targets: nil)
12
+ if triage_mode?(options)
13
+ triage_targets = resolve_targets(folder, targets)
14
+ return run_triage!(options, triage_targets)
15
+ end
16
+
17
+ run_folder_mode!(options, folder)
18
+ end
19
+
20
+ private
21
+
22
+ def triage_mode?(options)
23
+ options.is_a?(Hash) && options[:mode] == :triage
24
+ end
25
+
26
+ def resolve_targets(folder, targets)
27
+ raw = targets.nil? ? Array(folder) : targets
28
+ raw.reject { |path| path.nil? || path.empty? }
29
+ end
30
+
31
+ def run_triage!(options, targets)
32
+ validate_targets!(targets)
33
+ validate_options!(options)
34
+ triage_options = options.merge(targets:)
35
+ triage_config = config(triage_options)
36
+ triage_config.validate!
37
+ triage_config.checker.check
38
+ end
39
+
40
+ def run_folder_mode!(options, folder)
10
41
  validate_folder!(folder)
11
42
  validate_options!(options)
12
- config = config(options)
13
- config.validate!
43
+ mode_config = config(options)
44
+ mode_config.validate!
45
+ mode_config.checker.check(folder:)
46
+ end
47
+
48
+ def validate_targets!(targets)
49
+ raise ValidationError, 'No target selected. Use --help for usage information.' if targets.empty?
14
50
 
15
- config.checker.check(folder:)
51
+ missing = targets.find { |path| !valid_target?(path) }
52
+ raise ValidationError, "Path #{missing} does not exist" if missing
16
53
  end
17
54
 
18
- private
55
+ def valid_target?(path)
56
+ File.file?(path) || File.directory?(path)
57
+ end
19
58
 
20
59
  def validate_folder!(folder)
21
60
  raise ValidationError, 'No folder selected. Use --help for usage information.' if folder.nil? || folder.empty?
@@ -32,21 +71,21 @@ module ChurnVsComplexity
32
71
  raise ValidationError, 'No serializer selected. Use --help for usage information.'
33
72
  end
34
73
 
35
- MODES_WITHOUT_SERIALIZER = %i[triage hotspots gate focus diff].freeze
36
-
37
74
  def config(options)
38
- config_class =
39
- case options[:mode]
40
- when :timetravel then Timetravel::Config
41
- when :delta then Delta::Config
42
- when :triage then Triage::Config
43
- when :hotspots then Hotspots::Config
44
- when :gate then Gate::Config
45
- when :focus then Focus::Config
46
- when :diff then Diff::Config
47
- else Normal::Config
48
- end
49
- config_class.new(**options)
75
+ config_class = mode_configs.fetch(options[:mode], Normal::Config)
76
+ config_class.from_options(options)
77
+ end
78
+
79
+ def mode_configs
80
+ {
81
+ timetravel: Timetravel::Config,
82
+ delta: Delta::Config,
83
+ triage: Triage::Config,
84
+ hotspots: Hotspots::Config,
85
+ gate: Gate::Config,
86
+ focus: Focus::Config,
87
+ diff: Diff::Config,
88
+ }
50
89
  end
51
90
  end
52
91
  end