snoot 0.1.0 → 0.2.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 2a358948bce28c9ff2446d748bbf7a387946f93acf7f332ec25eecc63a0f4700
4
- data.tar.gz: 0f11f20fe357b26d27fb29459188c958d5804ae64e86ffee6b112a584b28fd87
3
+ metadata.gz: e31d40a1e1c5e8d5d96de9878c3f3989e63f2718c3f824b6c0193d26e36aa6bf
4
+ data.tar.gz: ae99b1c6a2644488ddade1ec800d62b78feabe54599c8537dde1db4dea65e6c9
5
5
  SHA512:
6
- metadata.gz: 66266a46163b0b322ee44e2ad384fa1b3b44bd5e26c42bb3770cf0d2657dac72ef0da51deb1282d1367ffacfbd50bb1afa279ac2bbdbcab43a4b617d51918530
7
- data.tar.gz: 734c2edb2cbe119d6588e751e1ac1c2a9de4190b4ab2929412dbf584f6abeb2fa0c3f9b01ce632bdff71bb0a1094c29d9fac15948ff7845f959b0cc889dfb678
6
+ metadata.gz: e60781056fca74305533ab31f46dd1e286ed2ccd6b4f79f14dc5fd993467daa161b2d5f5c0834adad55f8094c916c9c2a2e3028c735e93ded4a9fee6e7b89838
7
+ data.tar.gz: 8e6d06e3de863347de9c9279fde3c12a333cc1850e32aca7ed9a0bbfb7eb3b7206010ca7f38f5a351c2b841dd9b6af6b5e38551d3bc45c7a11c8bda3e4e03581
data/CHANGELOG.md CHANGED
@@ -7,6 +7,93 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.2.0] - 2026-10-30
11
+
12
+ ### Added
13
+
14
+ - The README says reek, flog and flay can write their own diagnostics
15
+ to stderr (skipped files, timeouts), which snoot passes through
16
+ unchanged.
17
+ - Every report's doc opens with a `## Reference` heading, so an agent
18
+ can find where the reference material starts, or cut it there.
19
+ - flay skips files matched by `.flayignore` in the current directory,
20
+ as the `flay` command does. The README and `--help` say a whole
21
+ directory needs `dir/**/*.rb`, and that flog has no way to exclude
22
+ files.
23
+ - Every run that gets past argument checking ends stdout with a status
24
+ line for scripts: `snoot-status: <outcome>` followed by `key=value`
25
+ fields (`snoot-status: finding_rendered category=smell
26
+ type=FeatureEnvy remaining=4`, `snoot-status: nothing_to_report`,
27
+ `snoot-status: analysis_failed analyser=reek`). On an analysis
28
+ failure it is the only stdout output. `--help` and the README
29
+ describe the format, and the README says which exit codes mean
30
+ snoot could not judge the code.
31
+ - `snoot --help` and the README explain how snoot picks its one
32
+ finding: category priority, ranking and tie-breaks, significance
33
+ cutoffs, `.reek.yml` scope, and the fix-and-rerun loop.
34
+ - `snoot --help` and the README say a smell finding lists every
35
+ instance of its type, and that running reek, flog or flay directly
36
+ lists a different set.
37
+ - Every report's second line counts the significant findings snoot
38
+ isn't showing, per category, and states the significance cutoffs
39
+ that applied (`Also significant: 4 smell types, 0 duplication
40
+ clusters, 0 complexity hits (cutoffs: …)`). The nothing-to-report
41
+ line states the cutoffs too.
42
+ - The "Also significant" and nothing-to-report lines name the smell
43
+ types still below the cutoff (`; 1 smell type below cutoff:
44
+ TooManyStatements`), so a type shows up before it counts.
45
+ - Smell reports carry a fix-first tuning section between the instances
46
+ and reek's doc: fix and rerun, or configure the detector in
47
+ `.reek.yml` under `detectors:`, keyed by the smell type's name.
48
+
49
+ ### Changed
50
+
51
+ - Duplication reports lead with flay's own description instead of an
52
+ opaque signature (`Similar code (:defn) in 3 locations, mass 78 (26
53
+ per copy)`), list each copy's full line span (`sample.rb:2-10`
54
+ instead of `2-2`), and show the code: the first copy when the copies
55
+ are identical, otherwise up to three copies, each up to 20 lines.
56
+ - Complexity reports show the method's full line span (`sample.rb:4-24`
57
+ instead of `4-4`), round the score to two decimals, split it into
58
+ flog's three dimensions (assignments, branching, and calls and other)
59
+ with each one's top operations, and show the method's code: up to 50
60
+ lines, common indentation removed.
61
+ - Smell instances list every line reek flagged (`Lines 12, 15: …`)
62
+ instead of only the first, each followed by its source code
63
+ (`12 | x.foo(bar)`), so the agent sees the code without opening the
64
+ file. Up to five code lines are shown per instance; the rest are
65
+ listed by number, and lines over 160 characters are cut. Control
66
+ characters in the code are replaced with `�`, so a scanned file can't
67
+ send escape sequences to the terminal.
68
+ - Smell reports lead with a one-line header naming the smell type
69
+ with its instance and file counts, followed by the instances and
70
+ then reek's doc. Previously the doc came first and the instances
71
+ last.
72
+
73
+ - A rejected option is named on stderr (`snoot: unknown option:
74
+ <arg>`, then `Try 'snoot --help' for usage.`) instead of the full
75
+ usage text. Unknown options and missing paths are reported together.
76
+ - `--help` and `--version` print and exit 0 wherever they appear in
77
+ argv, and `--` ends options so later arguments are always paths.
78
+
79
+ ### Fixed
80
+
81
+ - A bug in snoot while translating reek, flog or flay output exits 70
82
+ as an internal error, with the error class and backtrace on stderr.
83
+ Previously it was reported as that analyser failing (exit 2), as if
84
+ the analysed code or the analyser were at fault.
85
+ - An analysis-failure message names the line and reason when a source
86
+ file can't be parsed or read (`… syntax error in the source file.
87
+ (lib/a.rb:2:9: error: unexpected token tINTEGER)`), and always fits on
88
+ one line. Previously reek's message named only the file.
89
+ - An unexpected internal error exits 70 with `snoot: internal error:
90
+ <class>: <message>` and the backtrace on stderr, and an
91
+ `internal_error` status line on stdout. Previously it exited 1, the
92
+ same code as a rendered finding.
93
+ - A path argument that doesn't exist is rejected with exit 64 and a
94
+ `snoot: no such file or directory: <path>` line on stderr. Previously
95
+ flog and flay silently scanned the current directory instead.
96
+
10
97
  ## [0.1.0] - 2026-05-14
11
98
 
12
99
  ### Added
@@ -16,5 +103,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
16
103
  set (or the current directory when no paths are given) and emits a
17
104
  single agent-targeted finding to stdout.
18
105
 
19
- [Unreleased]: https://github.com/bkudria/snoot/compare/v0.1.0...HEAD
106
+ [Unreleased]: https://github.com/bkudria/snoot/compare/v0.2.0...HEAD
107
+ [0.2.0]: https://github.com/bkudria/snoot/compare/v0.1.0...v0.2.0
20
108
  [0.1.0]: https://github.com/bkudria/snoot/releases/tag/v0.1.0
data/README.md CHANGED
@@ -2,11 +2,11 @@
2
2
 
3
3
  A Ruby gem that orchestrates `reek`, `flog`, and `flay` over a configured path set and emits a single agent-targeted report describing one finding.
4
4
 
5
- The report is centred on an LLM coding agent as the reader: each run produces one of two report shapes -- a doc + instances pair for smell findings, or a header + finding context + doc trio for complexity and duplication findings -- or acknowledges that nothing was worth reporting, or signals analyser failure.
5
+ The report is centred on an LLM coding agent as the reader: each run produces one of two report shapes -- header, remaining, instances, tuning and doc for smell findings, or header, remaining, finding context and doc for complexity and duplication findings (for complexity, the context splits the score into flog's dimensions and shows the method's code; for duplication, it lists every copy's span and shows the code of up to three copies) -- or acknowledges that nothing was worth reporting, or signals analyser failure. Every report's doc opens with a `## Reference` heading and runs from the first such line to the status line, so an agent can cut the reference material there. The remaining line counts the other significant findings snoot is holding back and states the significance cutoffs that applied; the nothing-to-report line states the cutoffs too.
6
6
 
7
7
  ## Status
8
8
 
9
- Pre-1.0. Three analysers (Reek / Flog / Flay) are used, and `snoot <paths>` drives the full pipeline end-to-end: it reports a single finding to stdout, an acknowledgement when nothing is worth reporting, or a failure line on stderr. With no positional arguments, `snoot` scans the current directory. The exit code is `1` when a finding is rendered, `0` when there is nothing to report, and `2` when analysis fails.
9
+ Pre-1.0. Three analysers (Reek / Flog / Flay) are used, and `snoot <paths>` drives the full pipeline end-to-end: it reports a single finding to stdout, an acknowledgement when nothing is worth reporting, or a failure line on stderr. With no positional arguments, `snoot` scans the current directory. The exit code is `1` when a finding is rendered, `0` when there is nothing to report, `2` when analysis fails, `64` for a usage error, and `70` for an internal error. The last stdout line is a status line for scripts (see [Output for scripts](#output-for-scripts)).
10
10
 
11
11
  ## Specification
12
12
 
@@ -29,12 +29,91 @@ After install, the `snoot` executable is available on PATH:
29
29
  snoot --help
30
30
  snoot lib/foo.rb # analyse a specific path
31
31
  snoot # scan the current directory
32
+ snoot -- -odd-name.rb # arguments after -- are always paths
32
33
 
33
34
  `snoot` emits a single agent-targeted finding to stdout and exits with:
34
35
 
35
36
  - `0` — nothing worth reporting,
36
37
  - `1` — a finding was rendered,
37
- - `2` — analysis failed (failure line on stderr).
38
+ - `2` — analysis failed (failure line on stderr),
39
+ - `64` — usage error (unknown flag or missing path; details on stderr),
40
+ - `70` — internal error (a bug in snoot; details and backtrace on stderr).
41
+
42
+ At any outcome, reek, flog and flay can write their own diagnostics to stderr
43
+ as they run, such as a file they skipped (unreadable, unparseable, or
44
+ slow to parse) or flog's advice to rerun with `--continue`, which
45
+ does not apply to snoot. snoot passes these through unchanged; for flay
46
+ and some flog parse errors they are the only sign that a file went
47
+ unanalysed.
48
+
49
+ ## Output for scripts
50
+
51
+ Every run that gets past argument checking ends stdout with one status
52
+ line: `snoot-status: `, the outcome, then `key=value` fields whose values
53
+ never contain spaces.
54
+
55
+ snoot-status: finding_rendered category=smell type=FeatureEnvy remaining=4
56
+ snoot-status: finding_rendered category=duplication remaining=2
57
+ snoot-status: finding_rendered category=complexity remaining=0
58
+ snoot-status: nothing_to_report
59
+ snoot-status: analysis_failed analyser=reek
60
+ snoot-status: internal_error error=NoMethodError
61
+
62
+ `category` is `smell`, `duplication` or `complexity`; `type` names the
63
+ smell type and appears only for smells; `remaining` counts the
64
+ significant findings behind this one (the "Also significant" totals).
65
+ On `analysis_failed` the status line is all of stdout. Usage errors,
66
+ `--help` and `--version` print no status line. A gate can read the exit
67
+ code or `tail -n 1` of stdout:
68
+
69
+ snoot lib | tail -n 1
70
+
71
+ Exit `1` means a finding is waiting;
72
+ `2`, `64` and `70` mean snoot could not judge the code, so a gate
73
+ should read them as neither clean nor a finding.
74
+
75
+ ## How snoot picks a finding
76
+
77
+ Each run reports one finding. A smell finding lists
78
+ every instance of its type across the scanned files, so one run is a
79
+ batch of same-type fixes. Fix them, then run `snoot` again to see the next finding; the
80
+ report's "Also significant" line counts what is still waiting.
81
+
82
+ Running reek, flog or flay directly skips the cutoffs and the doc-less
83
+ skip described below, so it lists a different set from the one snoot
84
+ draws its finding from.
85
+
86
+ Only findings above snoot's significance cutoffs are candidates --
87
+ cutoffs: smell types need 2+ instances; complexity hits need score 25+; duplication clusters have no cutoff.
88
+ Duplication still passes through flay's own mass threshold (16).
89
+
90
+ Among the candidates, smells outrank duplication clusters, which outrank
91
+ complexity hits. Within a category the largest wins:
92
+
93
+ - smells: the smell type with the most instances; ties break by smell
94
+ type name, then path, then line;
95
+ - duplication clusters: the most locations; ties break by signature,
96
+ then first path, then first line;
97
+ - complexity hits: the highest score; ties break by path, then line.
98
+
99
+ Smell types with no bundled reek documentation are skipped. When the
100
+ skipped type would have been the top finding, snoot prints a warning on
101
+ stderr.
102
+
103
+ Reek reads `.reek.yml` from the current directory or its nearest
104
+ ancestor, falling back to `~/.reek.yml`; it configures reek's detectors
105
+ and `exclude_paths`. flog and flay do not read it.
106
+
107
+ flay skips files matched by `.flayignore` in the current directory,
108
+ using flay's own patterns: a whole directory needs `dir/**/*.rb`, since
109
+ `dir` or `dir/` alone does not exclude its subdirectories.
110
+ flog has no way to exclude files.
111
+
112
+ The "Also significant" line and the "nothing to report" line both name
113
+ the smell types below the cutoff, so a type shows up before it counts.
114
+ After its instances, a smell report says how to configure that smell's
115
+ detector: under `detectors:` in `.reek.yml`, keyed by the smell type's
116
+ name.
38
117
 
39
118
  ## Privacy
40
119
 
@@ -12,19 +12,34 @@ module Snoot
12
12
  end
13
13
 
14
14
  def resolve(run)
15
- selected = selected_candidate
15
+ pool = candidates
16
+ selected = AnalyseRun.select_top_finding(pool)
16
17
  terminal = if selected
17
18
  run.transition_to(:finding_rendered, selected_finding: selected)
18
19
  else
19
20
  run.transition_to(:nothing_to_report)
20
21
  end
21
- Result.new(run: terminal, events: doc_less_events(terminal), smells: @sources.smells)
22
+ Result.new(run: terminal, events: doc_less_events(terminal), smells: @sources.smells,
23
+ remaining: remaining(pool, selected))
22
24
  end
23
25
 
24
26
  private
25
27
 
26
- def selected_candidate
27
- AnalyseRun.select_top_finding(candidates)
28
+ def remaining(pool, selected)
29
+ others = pool - [selected]
30
+ selected_type = selected.smell_type if selected.is_a?(Smell)
31
+ RemainingFindings.new(
32
+ smell_types: (others.grep(Smell).map(&:smell_type).uniq - [selected_type]).size,
33
+ duplication_clusters: others.grep(DuplicationCluster).size,
34
+ complexity_hits: others.grep(ComplexityHit).size,
35
+ below_cutoff_smell_types: below_cutoff_smell_types
36
+ )
37
+ end
38
+
39
+ def below_cutoff_smell_types
40
+ smells = @sources.smells
41
+ significant = @orchestration.significant_smells(smells).map(&:smell_type)
42
+ (smells.map(&:smell_type).uniq - significant).sort_by(&:name)
28
43
  end
29
44
 
30
45
  def candidates
@@ -6,7 +6,10 @@ module Snoot
6
6
  # the audit events emitted along the way, and the smells the
7
7
  # orchestration produced (forwarded to RenderReport, which filters
8
8
  # by selected smell_type when building the per-file Instances list).
9
- # smells is empty when analysis failed (no Sources were produced).
10
- Result = Data.define(:run, :events, :smells)
9
+ # remaining counts the candidates the selected finding left
10
+ # unreported, for the report's remaining section. smells is empty
11
+ # and remaining is nil when analysis failed (no Sources were
12
+ # produced).
13
+ Result = Data.define(:run, :events, :smells, :remaining)
11
14
  end
12
15
  end
@@ -23,7 +23,7 @@ module Snoot
23
23
 
24
24
  def analysis_failure(run, failure)
25
25
  failed = run.transition_to(:analysis_failed, failure: failure)
26
- Result.new(run: failed, events: [], smells: Set[])
26
+ Result.new(run: failed, events: [], smells: Set[], remaining: nil)
27
27
  end
28
28
 
29
29
  def select_top_finding(findings)
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "flay"
4
+ require "flog"
5
+ require "path_expander"
6
+ require "reek"
7
+ require "reek/cli/options"
8
+ require "reek/configuration/app_configuration"
9
+ require "reek/source/source_locator"
10
+
11
+ module Snoot
12
+ module AnalyserOrchestration
13
+ # AnalyserRuns runs reek, flog and flay over a path set and returns
14
+ # each one's raw output untranslated, so an error raised here comes
15
+ # from the analyser or its inputs rather than from snoot's mapping.
16
+ #
17
+ # Directory expansion mirrors each tool's own CLI default rather than
18
+ # imposing a snoot-wide glob, so a directory Path resolves exactly as
19
+ # that tool would resolve it on the command line. Reek defers to
20
+ # `Reek::Source::SourceLocator` (which also honours `.reek.yml
21
+ # exclude_paths`); Flog uses `**/*.{rb,rake}` to match `Flog::CLI`
22
+ # and, like it, has no way to exclude files; Flay uses `**/*.rb` and
23
+ # drops files matched by the current directory's `.flayignore`, as
24
+ # `Flay.run` does (Flay's CLI additionally appends extensions
25
+ # advertised by installed Flay plugins, which snoot does not load).
26
+ module AnalyserRuns
27
+ FLAY_IGNORE = ".flayignore"
28
+
29
+ module_function
30
+
31
+ # Examiner#smells is where reek reads and parses the file, so it is
32
+ # called here rather than left for the caller to trigger.
33
+ def reek(paths)
34
+ config = Reek::Configuration::AppConfiguration.from_default_path
35
+ Reek::Source::SourceLocator.new(paths.map(&:raw), configuration: config).sources.map do |pathname|
36
+ [pathname, Reek::Examiner.new(pathname, configuration: config).smells]
37
+ end
38
+ end
39
+
40
+ def flog(paths)
41
+ Flog.new.tap { |flog| flog.flog(*expand_paths(paths, "**/*.{rb,rake}")) }
42
+ end
43
+
44
+ def flay(paths)
45
+ flay = Flay.new
46
+ flay.process(*expand_paths(paths, "**/*.rb", ignore: FLAY_IGNORE))
47
+ [flay, flay.analyze]
48
+ end
49
+
50
+ # PathExpander#process is avoided: it drops arguments that don't
51
+ # exist and then scans "." when none remain, so flog and flay would
52
+ # analyse a directory nobody named.
53
+ def expand_paths(paths, glob, ignore: nil)
54
+ raws = paths.map(&:raw)
55
+ expander = PathExpander.new(raws, glob)
56
+ files = expander.expand_dirs_to_files(*raws).uniq
57
+ ignore ? expander.filter_files(files, ignore) : files
58
+ end
59
+
60
+ private_class_method :expand_paths
61
+ end
62
+ end
63
+ end
@@ -1,13 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "bigdecimal"
4
- require "flay"
5
- require "flog"
6
- require "path_expander"
7
- require "reek"
8
- require "reek/cli/options"
9
- require "reek/configuration/app_configuration"
10
- require "reek/source/source_locator"
11
4
 
12
5
  module Snoot
13
6
  module AnalyserOrchestration
@@ -24,24 +17,12 @@ module Snoot
24
17
  # (16). Stateless: implemented as a module of module functions, used
25
18
  # as the orchestration value directly (no `.new`).
26
19
  #
27
- # Default's public surface is exactly the five contracted methods
20
+ # Default's public surface is exactly the six contracted methods
28
21
  # (vendored_doc, significant_smells, significant_complexities,
29
- # significant_duplications, analyse). The per-analyser drivers
30
- # (reek_analyse, flog_analyse, flay_analyse) and the per-pathname
31
- # helper (reek_smells_for) are private; their behaviour is observed
32
- # through analyse. Pure third-party-output translation is delegated
33
- # to the sibling module ResultMapping.
34
- #
35
- # Per-analyser directory expansion mirrors each tool's own CLI
36
- # default rather than imposing a snoot-wide glob, so a directory
37
- # Path resolves exactly as that tool would resolve it on the command
38
- # line. Reek defers to `Reek::Source::SourceLocator` (which also
39
- # honours `.reek.yml exclude_paths`); Flog uses `**/*.{rb,rake}` to
40
- # match `Flog::CLI`; Flay uses `**/*.rb` (Flay's CLI additionally
41
- # appends extensions advertised by installed Flay plugins, which
42
- # snoot does not load). The orchestration contract is path-abstract
43
- # (snoot.allium:150), so this is implementation policy each adapter
44
- # owns.
22
+ # significant_duplications, significance_cutoffs, analyse). The
23
+ # sibling module AnalyserRuns runs the analysers and returns their
24
+ # raw output; Default's private map steps translate it, delegating
25
+ # the pure per-item translation to the sibling module ResultMapping.
45
26
  module Default
46
27
  DOCS_ROOT = File.expand_path("../../../data/reek_docs", __dir__).freeze
47
28
  DOC_FILENAME_PATTERN = /([a-z])([A-Z])/
@@ -49,11 +30,13 @@ module Snoot
49
30
  SMELL_TYPE_INSTANCE_FLOOR = 2
50
31
  COMPLEXITY_SCORE_FLOOR = BigDecimal("25")
51
32
 
52
- ANALYSER_PROBES = [
53
- %i[reek reek_analyse],
54
- %i[flog flog_analyse],
55
- %i[flay flay_analyse]
56
- ].freeze
33
+ # Each analyser's AnalyserRuns method, keyed by tag, paired with the
34
+ # map step that translates its raw output.
35
+ ANALYSERS = {
36
+ reek: :smells_from_reek,
37
+ flog: :complexities_from_flog,
38
+ flay: :duplications_from_flay
39
+ }.freeze
57
40
 
58
41
  # Memoises vendored_doc results by smell_type.name. The corpus is
59
42
  # fixed at gem build time (DOCS_ROOT, pinned to bundled reek) and
@@ -64,40 +47,42 @@ module Snoot
64
47
 
65
48
  module_function
66
49
 
67
- def reek_analyse(paths)
68
- config = Reek::Configuration::AppConfiguration.from_default_path
69
- Reek::Source::SourceLocator.new(paths.map(&:raw), configuration: config).sources
70
- .flat_map { |pathname| reek_smells_for(pathname, config) }
71
- .to_set
50
+ def smells_from_reek(warnings_by_file)
51
+ warnings_by_file.flat_map { |pathname, warnings| smells_for(pathname, warnings) }.to_set
72
52
  end
73
53
 
74
- def reek_smells_for(pathname, config)
75
- examiner = Reek::Examiner.new(pathname, configuration: config)
76
- examiner.smells.filter_map do |warning|
54
+ def smells_for(pathname, warnings)
55
+ file_lines = read_source_lines(pathname)
56
+ warnings.filter_map do |warning|
77
57
  next unless warning.lines&.any?
78
58
 
79
- ResultMapping.smell_from_reek_warning(warning)
59
+ ResultMapping.smell_from_reek_warning(warning, file_lines)
80
60
  end
81
61
  end
82
62
 
83
- def flog_analyse(paths)
84
- files = PathExpander.new(paths.map(&:raw), "**/*.{rb,rake}").process
85
- flog = Flog.new
86
- flog.flog(*files)
87
- flog.totals.filter_map do |class_method, score|
88
- ResultMapping.complexity_hit_from_flog_entry(
89
- class_method: class_method, score: score,
90
- raw_location: flog.method_locations[class_method]
91
- )
92
- end.to_set
63
+ def read_source_lines(pathname)
64
+ File.binread(pathname).force_encoding(Encoding::UTF_8).scrub.lines(chomp: true)
65
+ rescue SystemCallError
66
+ nil
67
+ end
68
+
69
+ def complexities_from_flog(flog)
70
+ file_lines = Hash.new { |cache, file| cache[file] = read_source_lines(file) }
71
+ flog.totals.filter_map { |method, score| complexity_hit_for(flog, method, score, file_lines) }.to_set
72
+ end
73
+
74
+ def complexity_hit_for(flog, class_method, score, file_lines)
75
+ raw_location = flog.method_locations[class_method]
76
+ ResultMapping.complexity_hit_from_flog_entry(
77
+ class_method:, score:, raw_location:, calls: flog.calls[class_method],
78
+ file_lines: raw_location && file_lines[raw_location.split(":", 2).first]
79
+ )
93
80
  end
94
81
 
95
- def flay_analyse(paths)
96
- files = PathExpander.new(paths.map(&:raw), "**/*.rb").process
97
- flay = Flay.new
98
- flay.process(*files)
99
- flay.analyze.each_with_object(Set[]) do |item, clusters|
100
- clusters << ResultMapping.duplication_cluster_from_flay_item(item)
82
+ def duplications_from_flay((flay, items))
83
+ file_lines = Hash.new { |cache, file| cache[file] = read_source_lines(file) }
84
+ items.to_set do |item|
85
+ ResultMapping.duplication_cluster_from_flay_item(item, nodes: flay.hashes[item.structural_hash], file_lines:)
101
86
  end
102
87
  end
103
88
 
@@ -120,10 +105,18 @@ module Snoot
120
105
 
121
106
  def significant_duplications(duplications) = duplications
122
107
 
108
+ def significance_cutoffs
109
+ SignificanceCutoffs.new(
110
+ smell_type_instances: SMELL_TYPE_INSTANCE_FLOOR,
111
+ complexity_score: COMPLEXITY_SCORE_FLOOR,
112
+ duplication_locations: nil
113
+ )
114
+ end
115
+
123
116
  # analyse runs the three analysers in canonical order (Reek ->
124
117
  # Flog -> Flay), capturing each result as it succeeds. On the
125
- # first failure it returns an AnalyserFailure tagged with that
126
- # analyser and does not invoke the remaining ones. On full
118
+ # first analyser failure it returns an AnalyserFailure tagged with
119
+ # that analyser and does not invoke the remaining ones. On full
127
120
  # success it returns a Sources bundling the three result sets.
128
121
  def analyse(paths)
129
122
  outputs = collect_outputs(paths)
@@ -135,15 +128,24 @@ module Snoot
135
128
  end
136
129
 
137
130
  def collect_outputs(paths)
138
- ANALYSER_PROBES.each_with_object({}) do |(tag, method), outputs|
139
- outputs[tag] = send(method, paths)
140
- rescue StandardError => error
141
- return AnalyserFailure.new(analyser: tag, message: error.message)
131
+ ANALYSERS.each_with_object({}) do |(tag, map), outputs|
132
+ output = run_analyser(tag, paths)
133
+ return output if output.is_a?(AnalyserFailure)
134
+
135
+ outputs[tag] = send(map, output)
142
136
  end
143
137
  end
144
138
 
145
- private_class_method :reek_analyse, :reek_smells_for, :flog_analyse, :flay_analyse,
146
- :collect_outputs
139
+ # Only the analyser's own run is an analyser failure; an error while
140
+ # mapping its output is a bug in snoot, so it propagates.
141
+ def run_analyser(tag, paths)
142
+ AnalyserRuns.public_send(tag, paths)
143
+ rescue StandardError => error
144
+ AnalyserFailure.new(analyser: tag, message: FailureMessage.for(error))
145
+ end
146
+
147
+ private_class_method :smells_from_reek, :smells_for, :complexities_from_flog, :complexity_hit_for,
148
+ :duplications_from_flay, :collect_outputs, :run_analyser
147
149
  end
148
150
  end
149
151
  end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Snoot
4
+ module AnalyserOrchestration
5
+ # FailureMessage turns an analyser's exception into the one-line
6
+ # message an AnalyserFailure carries.
7
+ module FailureMessage
8
+ module_function
9
+
10
+ def for(error)
11
+ detail = cause_detail(error.cause)
12
+ message = error.message
13
+ message = "#{message} (#{detail})" if detail && !message.include?(detail)
14
+ message.gsub(/\s*\n\s*/, " ")
15
+ end
16
+
17
+ # reek wraps parser and IO errors in its own, which name the file but
18
+ # not the line or reason; the wrapped cause carries those.
19
+ def cause_detail(cause)
20
+ return unless cause
21
+
22
+ cause.respond_to?(:diagnostic) ? cause.diagnostic.render.first : cause.message
23
+ end
24
+ end
25
+ end
26
+ end
@@ -12,40 +12,84 @@ module Snoot
12
12
  module ResultMapping
13
13
  module_function
14
14
 
15
- def smell_from_reek_warning(warning)
15
+ def smell_from_reek_warning(warning, file_lines = nil)
16
16
  lines = warning.lines
17
17
  Smell.new(
18
18
  smell_type: SmellType.new(name: warning.smell_type),
19
- location: Location.new(
20
- path: Path.new(raw: warning.source),
21
- line_start: lines.first,
22
- line_end: lines.last
23
- ),
24
- message: "#{warning.context} #{warning.message}"
19
+ location: Location.new(path: Path.new(raw: warning.source), line_start: lines.first, line_end: lines.last),
20
+ message: "#{warning.context} #{warning.message}",
21
+ source_lines: source_lines_for(lines, file_lines)
25
22
  )
26
23
  end
27
24
 
25
+ def source_lines_for(numbers, file_lines)
26
+ numbers.uniq.sort.map { |number| SourceLine.new(number:, text: file_lines&.[](number - 1)) }
27
+ end
28
+
28
29
  # Flog stores method locations as "file:line" or "file:line-line_max".
29
30
  # Returns nil when the entry is missing (e.g. main#none) so callers
30
31
  # can skip top-level expressions that lack a method-level location.
31
- def complexity_hit_from_flog_entry(class_method:, score:, raw_location:)
32
+ def complexity_hit_from_flog_entry(class_method:, score:, raw_location:, calls: {}, file_lines: nil)
32
33
  file, range = raw_location.to_s.split(":", 2)
33
34
  return unless file && range
34
35
 
35
- line_start, = range.split("-", 2).map(&:to_i)
36
+ line_start, line_max = range.split("-", 2).map(&:to_i)
37
+ line_end = line_max || line_start
36
38
  ComplexityHit.new(
37
- location: Location.new(path: Path.new(raw: file), line_start: line_start, line_end: line_start),
38
- method_name: class_method,
39
- score: BigDecimal(score.to_s)
39
+ location: Location.new(path: Path.new(raw: file), line_start:, line_end:),
40
+ method_name: class_method, score: BigDecimal(score.to_s),
41
+ breakdown: breakdown_from_flog_calls(calls),
42
+ source_lines: source_lines_for((line_start..line_end).to_a, file_lines)
40
43
  )
41
44
  end
42
45
 
43
- def duplication_cluster_from_flay_item(item)
44
- locations = item.locations.each_with_object(Set[]) do |loc, set|
45
- line = loc.line
46
- set << Location.new(path: Path.new(raw: loc.file), line_start: line, line_end: line)
46
+ BRANCHING_OPERATIONS = %w[branch block_call].freeze
47
+
48
+ # Mirrors Flog#score_method's grouping of operations into A, B and C.
49
+ def breakdown_from_flog_calls(calls)
50
+ branching, others = score_contributions(calls).partition do |contribution|
51
+ BRANCHING_OPERATIONS.include?(contribution.operation)
47
52
  end
48
- DuplicationCluster.new(signature: item.structural_hash.to_s, locations: locations)
53
+ assignments, calls_and_other = others.partition { |contribution| contribution.operation == "assignment" }
54
+ ComplexityBreakdown.new(assignments:, branching:, calls: calls_and_other)
55
+ end
56
+
57
+ def score_contributions(calls)
58
+ calls.map { |operation, score| ScoreContribution.new(operation: operation.to_s, score: BigDecimal(score.to_s)) }
59
+ .sort_by { |contribution| [-contribution.score, contribution.operation] }
60
+ end
61
+
62
+ def duplication_cluster_from_flay_item(item, nodes: [], file_lines: {})
63
+ copies = duplicate_copies(item.locations, nodes, file_lines)
64
+ identical = !item.identical?.nil?
65
+ DuplicationCluster.new(
66
+ signature: item.structural_hash.to_s, node_type: item.name.to_s, identical:,
67
+ mass: item.mass, copy_mass: copy_mass(item.mass, item.locations.size, identical),
68
+ locations: copies.to_set(&:location), copies:
69
+ )
70
+ end
71
+
72
+ def duplicate_copies(flay_locations, nodes, file_lines)
73
+ line_maxes = nodes.to_h { |node| [[node.file, node.line], node.line_max] }
74
+ copies = flay_locations.map { |flay_location| duplicate_copy(flay_location, line_maxes, file_lines) }
75
+ copies.uniq(&:location).sort_by { |copy| [copy.location.path.raw, copy.location.line_start] }
76
+ end
77
+
78
+ def duplicate_copy(flay_location, line_maxes, file_lines)
79
+ file = flay_location.file
80
+ line_start = flay_location.line
81
+ line_end = line_maxes.fetch([file, line_start], line_start)
82
+ DuplicateCopy.new(
83
+ location: Location.new(path: Path.new(raw: file), line_start:, line_end:),
84
+ source_lines: source_lines_for((line_start..line_end).to_a, file_lines[file])
85
+ )
86
+ end
87
+
88
+ # Flay totals a cluster's mass as one copy's mass times the copy
89
+ # count, and multiplies by the count again when the copies are
90
+ # identical.
91
+ def copy_mass(mass, count, identical)
92
+ identical ? mass / count / count : mass / count
49
93
  end
50
94
  end
51
95
  end