churn_vs_complexity 1.9.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 (64) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +56 -0
  3. data/README.md +46 -23
  4. data/lib/churn_vs_complexity/analysis_scope.rb +20 -0
  5. data/lib/churn_vs_complexity/churn.rb +27 -9
  6. data/lib/churn_vs_complexity/cli/main.rb +58 -19
  7. data/lib/churn_vs_complexity/cli/parser.rb +85 -121
  8. data/lib/churn_vs_complexity/cli.rb +2 -3
  9. data/lib/churn_vs_complexity/complexity/flog_calculator.rb +0 -3
  10. data/lib/churn_vs_complexity/complexity/lizard_calculator.rb +64 -0
  11. data/lib/churn_vs_complexity/complexity.rb +1 -7
  12. data/lib/churn_vs_complexity/complexity_validator.rb +1 -16
  13. data/lib/churn_vs_complexity/concurrent_calculator.rb +20 -23
  14. data/lib/churn_vs_complexity/delta/checker.rb +35 -21
  15. data/lib/churn_vs_complexity/delta/commit_hydrator.rb +1 -1
  16. data/lib/churn_vs_complexity/delta/complexity_annotator.rb +23 -5
  17. data/lib/churn_vs_complexity/delta/config.rb +15 -16
  18. data/lib/churn_vs_complexity/delta/factory.rb +2 -2
  19. data/lib/churn_vs_complexity/delta/multi_checker.rb +24 -25
  20. data/lib/churn_vs_complexity/delta/serializer.rb +6 -4
  21. data/lib/churn_vs_complexity/delta.rb +11 -49
  22. data/lib/churn_vs_complexity/diff/checker.rb +10 -3
  23. data/lib/churn_vs_complexity/diff/config.rb +29 -20
  24. data/lib/churn_vs_complexity/file_selector.rb +63 -114
  25. data/lib/churn_vs_complexity/focus/config.rb +42 -32
  26. data/lib/churn_vs_complexity/focus/serializer.rb +17 -4
  27. data/lib/churn_vs_complexity/gate/config.rb +28 -25
  28. data/lib/churn_vs_complexity/git_strategy.rb +17 -12
  29. data/lib/churn_vs_complexity/hotspots/config.rb +29 -25
  30. data/lib/churn_vs_complexity/language_registry.rb +108 -0
  31. data/lib/churn_vs_complexity/language_validator.rb +1 -3
  32. data/lib/churn_vs_complexity/normal/config.rb +31 -100
  33. data/lib/churn_vs_complexity/normal/serializer/graph.rb +3 -2
  34. data/lib/churn_vs_complexity/normal/serializer/summary.rb +18 -14
  35. data/lib/churn_vs_complexity/normal/serializer/summary_hash.rb +15 -13
  36. data/lib/churn_vs_complexity/normal/serializer.rb +2 -1
  37. data/lib/churn_vs_complexity/normal.rb +17 -13
  38. data/lib/churn_vs_complexity/risk_classifier.rb +3 -19
  39. data/lib/churn_vs_complexity/timetravel/config.rb +34 -47
  40. data/lib/churn_vs_complexity/timetravel/schedule.rb +15 -0
  41. data/lib/churn_vs_complexity/timetravel/serializer/stats_calculator.rb +36 -32
  42. data/lib/churn_vs_complexity/timetravel/serializer.rb +16 -24
  43. data/lib/churn_vs_complexity/timetravel/traveller.rb +44 -15
  44. data/lib/churn_vs_complexity/timetravel.rb +36 -14
  45. data/lib/churn_vs_complexity/triage/checker.rb +24 -28
  46. data/lib/churn_vs_complexity/triage/collaborator_set.rb +11 -0
  47. data/lib/churn_vs_complexity/triage/config.rb +29 -26
  48. data/lib/churn_vs_complexity/triage.rb +1 -0
  49. data/lib/churn_vs_complexity/validator_set.rb +9 -0
  50. data/lib/churn_vs_complexity/version.rb +1 -1
  51. data/lib/churn_vs_complexity.rb +3 -0
  52. metadata +18 -22
  53. data/lib/churn_vs_complexity/complexity/eslint_calculator.rb +0 -40
  54. data/lib/churn_vs_complexity/complexity/go_calculator.rb +0 -48
  55. data/lib/churn_vs_complexity/complexity/kotlin_calculator.rb +0 -54
  56. data/lib/churn_vs_complexity/complexity/pmd/files_calculator.rb +0 -26
  57. data/lib/churn_vs_complexity/complexity/pmd/folder_calculator.rb +0 -20
  58. data/lib/churn_vs_complexity/complexity/pmd.rb +0 -54
  59. data/lib/churn_vs_complexity/complexity/python_calculator.rb +0 -50
  60. data/lib/churn_vs_complexity/complexity/rust_calculator.rb +0 -54
  61. data/lib/churn_vs_complexity/complexity/swift_calculator.rb +0 -54
  62. data/tmp/eslint-support/complexity-calculator.js +0 -51
  63. data/tmp/eslint-support/package.json +0 -11
  64. data/tmp/pmd-support/ruleset.xml +0 -21
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 612c6e1945c04f5be2c72cdbdfbd4bc91157da01c6d4ab66f5a502a7e109c805
4
- data.tar.gz: c84417b6b7eeeeb4fac050e32c89f037b010977c342e8db14762d28b2f63d557
3
+ metadata.gz: fead91605b8e6bb82370f0b7265622cf42ea15a19ec322ed5f44643912e2cfb4
4
+ data.tar.gz: b6bce4c0b63b52533c6e6bfb6b1816c16a12b9c53d1c69f6cacb781a65d45165
5
5
  SHA512:
6
- metadata.gz: a8d9617c65744a1b04910c0e9206d788cddcc02133820a05d9bad5bdc160d9c11e05552080bee72d2a1a9b53c765e884cd249095e54a866e38cdb6f3b803880e
7
- data.tar.gz: 7174c9a6d71d2db643b83b72c49973aef249b09aafacc41112e25407b58a3a46675af29f968c5f84226b8e53fb114c3546664f4f9c2b35940277d68d8f9e5fda
6
+ metadata.gz: 03b64889da02cd18e0ae7320f67763505d3f8ceb767acf55e362c96a9841df9b27ee033f6e87374a4499a5b2beb56e61e55b1f066d2e569b05ee26ebcb67baf9
7
+ data.tar.gz: b16173fbdcdb886b912e99ea551b431d3ec91274e5c45eb4659d5c7b69bd22319a340a001f8bfacff74795d52869538810438eaeb461e966669a74470550e975
data/CHANGELOG.md CHANGED
@@ -1,3 +1,59 @@
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
+
1
57
  ## [1.9.0] - 2026-09-20
2
58
 
3
59
  ### Fixed
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 [gocognit](https://github.com/uudashr/gocognit) on the search path. Install with `go install github.com/uudashr/gocognit/cmd/gocognit@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
 
@@ -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,11 +15,12 @@ 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:)
@@ -34,21 +35,38 @@ module ChurnVsComplexity
34
35
  # Asks git for the root commits directly. Reading it off `repo(folder).log`
35
36
  # instead would silently answer with the 30th most recent commit, because
36
37
  # that is where the git gem caps a log by default.
37
- def date_of_first_commit(folder:)
38
- git_dir = File.join(folder, '.git')
39
- cmd = %(git --git-dir #{git_dir} --work-tree #{folder} log --max-parents=0 --format=%ad --date=short)
40
- dates = `(#{cmd}) 2>/dev/null`.split("\n").filter_map { |line| parse_date(line) }
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
41
  dates.min || Time.at(0).to_date
42
42
  end
43
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
+
44
49
  def parse_date(line)
45
50
  Date.parse(line)
46
51
  rescue Date::Error
47
52
  nil
48
53
  end
49
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
61
+ end
62
+
50
63
  def repo(folder)
51
- 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
52
70
  end
53
71
 
54
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
@@ -5,155 +5,119 @@ require 'optparse'
5
5
  module ChurnVsComplexity
6
6
  module CLI
7
7
  module Parser
8
- def self.create
9
- options = { excluded: [] }
10
- parser = OptionParser.new do |opts|
11
- opts.banner = 'Usage: churn_vs_complexity [options] folder|file...'
8
+ TRIAGE_HELP = 'Assess risk of files based on churn and complexity. ' \
9
+ 'Accepts file paths or a folder as arguments.'
12
10
 
13
- opts.separator ''
14
- opts.separator 'Languages:'
11
+ SIMPLE_MODES = [
12
+ ['--triage', :triage, TRIAGE_HELP],
13
+ ['--hotspots', :hotspots, 'Generate ranked list of files by risk'],
14
+ ['--gate', :gate, 'Pass/fail quality check against gamma threshold (exits 0 on pass, 1 on fail)'],
15
+ ].freeze
15
16
 
16
- opts.on('--java', 'Check complexity of java classes') do
17
- options[:language] = :java
18
- end
17
+ FORMAT_FLAGS = [
18
+ ['--csv', :csv, 'Format output as CSV'],
19
+ ['--graph', :graph, 'Format output as HTML page with Churn vs Complexity graph'],
20
+ ['--summary', :summary, 'Output summary statistics (mean and median) for churn and complexity'],
21
+ ['--json', :json, 'Format output as JSON'],
22
+ ['--markdown', :markdown, 'Format output as Markdown'],
23
+ ].freeze
19
24
 
20
- opts.on('--ruby', 'Check complexity of ruby files') do
21
- options[:language] = :ruby
22
- end
25
+ PERIOD_FLAGS = [
26
+ ['-m', '--month', :month, 'Calculate churn for the month leading up to the most recent commit'],
27
+ ['-q', '--quarter', :quarter, 'Calculate churn for the quarter leading up to the most recent commit'],
28
+ ['-y', '--year', :year, 'Calculate churn for the year leading up to the most recent commit'],
29
+ ].freeze
23
30
 
24
- opts.on('--js', '--ts', '--javascript', '--typescript',
25
- 'Check complexity of javascript and typescript files',) do
26
- options[:language] = :javascript
27
- end
31
+ DELTA_HELP = 'Identify changes between the specified commit (SHA) and the previous commit and annotate ' \
32
+ 'changed files with complexity score. SHA can be a full or short commit hash, or the ' \
33
+ 'value HEAD. Can be used multiple times to specify multiple commits.'
28
34
 
29
- opts.on('--python', 'Check complexity of python files') do
30
- options[:language] = :python
31
- end
35
+ TIMETRAVEL_HELP = 'Calculate summary for all commits at intervals of N days throughout project history ' \
36
+ 'or from the date specified with --since'
32
37
 
33
- opts.on('--go', 'Check complexity of go files') do
34
- options[:language] = :go
35
- end
38
+ SINCE_HELP = 'Normal mode: Calculate churn after this date. Timetravel mode: calculate summaries from this date'
36
39
 
37
- opts.on('--kotlin', 'Check complexity of kotlin files') do
38
- options[:language] = :kotlin
39
- end
40
+ FOCUS_HELP = 'Capture complexity snapshot before (start) and after (end) a coding session'
40
41
 
41
- opts.on('--rust', 'Check complexity of rust files') do
42
- options[:language] = :rust
43
- end
42
+ DIFF_HELP = 'Compare codebase health between REF and HEAD'
44
43
 
45
- opts.on('--swift', 'Check complexity of swift files') do
46
- options[:language] = :swift
47
- end
44
+ EXCLUDED_HELP = 'Exclude file paths including this string. Can be used multiple times.'
48
45
 
49
- opts.separator ''
50
- opts.separator 'Modes (mutually exclusive):'
46
+ MAX_GAMMA_HELP = 'Maximum gamma score threshold for gate mode (default: 25)'
51
47
 
52
- opts.on('--timetravel N',
53
- 'Calculate summary for all commits at intervals of N days throughout project history or from the date specified with --since',) do |value|
54
- options[:mode] = :timetravel
55
- options[:jump_days] = value.to_i
48
+ class << self
49
+ def create
50
+ options = { excluded: [] }
51
+ parser = OptionParser.new do |opts|
52
+ opts.banner = 'Usage: churn_vs_complexity [options] folder|file...'
53
+ add_languages(opts, options)
54
+ add_modes(opts, options)
55
+ add_formats(opts, options)
56
+ add_modifiers(opts, options)
56
57
  end
58
+ [parser, options]
59
+ end
57
60
 
58
- opts.on('--triage',
59
- 'Assess risk of files based on churn and complexity. Accepts file paths or a folder as arguments.',) do
60
- options[:mode] = :triage
61
- end
61
+ private
62
62
 
63
- opts.on('--hotspots', 'Generate ranked list of files by risk') do
64
- options[:mode] = :hotspots
65
- end
66
-
67
- opts.on('--gate',
68
- 'Pass/fail quality check against gamma threshold (exits 0 on pass, 1 on fail)',) do
69
- options[:mode] = :gate
63
+ def add_languages(opts, options)
64
+ add_section(opts, 'Languages:')
65
+ LanguageRegistry.all.each do |entry|
66
+ opts.on(*entry.cli_flags, entry.description) { options[:language] = entry.key }
70
67
  end
68
+ end
71
69
 
72
- opts.on('--focus start|end',
73
- 'Capture complexity snapshot before (start) and after (end) a coding session',) do |value|
74
- options[:mode] = :focus
75
- options[:subcommand] = value.to_sym
76
- end
70
+ def add_modes(opts, options)
71
+ add_section(opts, 'Modes (mutually exclusive):')
72
+ opts.on('--timetravel N', TIMETRAVEL_HELP) { |v| options.merge!(mode: :timetravel, jump_days: v.to_i) }
73
+ SIMPLE_MODES.each { |flag, mode, desc| opts.on(flag, desc) { options[:mode] = mode } }
74
+ add_comparison_modes(opts, options)
75
+ end
77
76
 
78
- opts.on('--diff REF', 'Compare codebase health between REF and HEAD') do |value|
79
- options[:mode] = :diff
80
- options[:reference] = value
77
+ def add_comparison_modes(opts, options)
78
+ opts.on('--focus start|end', FOCUS_HELP) do |v|
79
+ options.merge!(mode: :focus, subcommand: v.to_sym)
81
80
  end
82
-
83
- opts.on('--delta SHA',
84
- 'Identify changes between the specified commit (SHA) and the previous commit and annotate changed files with complexity score. SHA can be a full or short commit hash, or the value HEAD. Can be used multiple times to specify multiple commits.',) do |value|
81
+ opts.on('--diff REF', DIFF_HELP) { |v| options.merge!(mode: :diff, reference: v) }
82
+ opts.on('--delta SHA', DELTA_HELP) do |v|
85
83
  options[:mode] = :delta
86
- (options[:commits] ||= []) << value
84
+ (options[:commits] ||= []) << v
87
85
  end
86
+ end
88
87
 
89
- opts.separator ''
90
- opts.separator 'Output formats:'
91
-
92
- opts.on('--csv', 'Format output as CSV') do
93
- options[:serializer] = :csv
94
- end
88
+ def add_formats(opts, options)
89
+ add_section(opts, 'Output formats:')
90
+ FORMAT_FLAGS.each { |flag, fmt, desc| opts.on(flag, desc) { options[:serializer] = fmt } }
91
+ end
95
92
 
96
- opts.on('--graph', 'Format output as HTML page with Churn vs Complexity graph') do
97
- options[:serializer] = :graph
98
- end
93
+ def add_modifiers(opts, options)
94
+ add_section(opts, 'Modifiers:')
95
+ add_filter_and_period_modifiers(opts, options)
96
+ add_exit_flags(opts, options)
97
+ end
99
98
 
100
- opts.on('--summary', 'Output summary statistics (mean and median) for churn and complexity') do
101
- options[:serializer] = :summary
102
- end
99
+ def add_filter_and_period_modifiers(opts, options)
100
+ opts.on('--excluded PATTERN', EXCLUDED_HELP) { |v| options[:excluded] << v }
101
+ opts.on('--since YYYY-MM-DD', SINCE_HELP) { |v| options[:since] = v }
102
+ PERIOD_FLAGS.each { |s, l, period, desc| opts.on(s, l, desc) { options[:relative_period] = period } }
103
+ opts.on('--max-gamma N', Float, MAX_GAMMA_HELP) { |v| options[:max_gamma] = v }
104
+ end
103
105
 
104
- opts.on('--json', 'Format output as JSON') do
105
- options[:serializer] = :json
106
- end
106
+ def add_exit_flags(opts, options)
107
+ opts.on('--dry-run', 'Echo the chosen options from the CLI') { print_and_exit(options) }
108
+ opts.on('-h', '--help', 'Display help') { print_and_exit(opts) }
109
+ opts.on('--version', 'Display version') { print_and_exit(ChurnVsComplexity::VERSION) }
110
+ end
107
111
 
108
- opts.on('--markdown', 'Format output as Markdown') do
109
- options[:serializer] = :markdown
110
- end
112
+ def print_and_exit(value)
113
+ puts value
114
+ exit
115
+ end
111
116
 
117
+ def add_section(opts, heading)
112
118
  opts.separator ''
113
- opts.separator 'Modifiers:'
114
-
115
- opts.on('--excluded PATTERN',
116
- 'Exclude file paths including this string. Can be used multiple times.',) do |value|
117
- options[:excluded] << value
118
- end
119
-
120
- opts.on('--since YYYY-MM-DD',
121
- 'Normal mode: Calculate churn after this date. Timetravel mode: calculate summaries from this date',) do |value|
122
- options[:since] = value
123
- end
124
-
125
- opts.on('-m', '--month', 'Calculate churn for the month leading up to the most recent commit') do
126
- options[:relative_period] = :month
127
- end
128
-
129
- opts.on('-q', '--quarter', 'Calculate churn for the quarter leading up to the most recent commit') do
130
- options[:relative_period] = :quarter
131
- end
132
-
133
- opts.on('-y', '--year', 'Calculate churn for the year leading up to the most recent commit') do
134
- options[:relative_period] = :year
135
- end
136
-
137
- opts.on('--max-gamma N', Float, 'Maximum gamma score threshold for gate mode (default: 25)') do |value|
138
- options[:max_gamma] = value
139
- end
140
-
141
- opts.on('--dry-run', 'Echo the chosen options from the CLI') do
142
- puts options
143
- exit
144
- end
145
-
146
- opts.on('-h', '--help', 'Display help') do
147
- puts opts
148
- exit
149
- end
150
-
151
- opts.on('--version', 'Display version') do
152
- puts ChurnVsComplexity::VERSION
153
- exit
154
- end
119
+ opts.separator heading
155
120
  end
156
- [parser, options]
157
121
  end
158
122
  end
159
123
  end
@@ -9,10 +9,9 @@ module ChurnVsComplexity
9
9
  def run!
10
10
  parser, options = Parser.create
11
11
  parser.parse!
12
- # First argument that is not an option is the folder
13
- folder = ARGV.first
12
+ targets = ARGV.dup
14
13
 
15
- result = Main.run!(options, folder)
14
+ result = Main.run!(options, targets.first, targets:)
16
15
  puts result
17
16
  exit 1 if result.respond_to?(:passed?) && !result.passed?
18
17
  end