calltally 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 500a5c27806a402198ff657275586756c3a3d004f01b03cdad133b13b119c1bf
4
+ data.tar.gz: 1f479fe7061ad208fb22d376519a6040d85bf93d80a92672e4ab01db51fdac59
5
+ SHA512:
6
+ metadata.gz: eaa590ed4f0c510b262597e1b89fd08f8e01940a4abc35a6dc768018b1c1ee2220cb8f4ca141e9190f1e09be956368ab8b7b9be8ec316b1ced685e2e9548ff9d
7
+ data.tar.gz: b9390cb686dbeb010039999fc4c93d53f2e0508468b3a4df2cb3a2fdeb06e0abbf7f8bb3da9948349ae82203ec9919cbfe21cce5792b2bba61762c1f4ea0d8c4
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ https://github.com/nsgc/calltally/issues.
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Naoki Nishiguchi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,216 @@
1
+ # Calltally
2
+
3
+ > Tally your method calls.
4
+
5
+ A simple yet powerful tool to analyze method usage in Ruby/Rails codebases. Quickly identify your most-used methods, understand code patterns, and make informed refactoring decisions.
6
+
7
+ ## Installation
8
+
9
+ Add to your Gemfile:
10
+
11
+ ```ruby
12
+ gem 'calltally', group: :development
13
+ ```
14
+
15
+ Or install globally:
16
+
17
+ ```bash
18
+ gem install calltally
19
+ ```
20
+
21
+ ## Quick Start
22
+
23
+ ```bash
24
+ # Analyze current directory
25
+ calltally
26
+
27
+ # Analyze specific directory
28
+ calltally app/models
29
+
30
+ # Show top 20 results
31
+ calltally --top 20
32
+
33
+ # Focus on specific classes
34
+ calltally --receivers User,Post --top 10
35
+ ```
36
+
37
+ ## Usage Examples
38
+
39
+ ### Rails Projects
40
+
41
+ Calltally automatically detects Rails projects and scans the right directories:
42
+
43
+ ```bash
44
+ # Auto-detects Rails and scans app/, lib/, config/
45
+ calltally
46
+
47
+ # Include ERB templates
48
+ calltally --erb
49
+
50
+ # Focus on ActiveRecord methods
51
+ calltally --methods where,find,joins --mode pairs
52
+ ```
53
+
54
+ ### Output Formats
55
+
56
+ ```bash
57
+ # Default table format
58
+ calltally
59
+
60
+ # JSON format for further processing
61
+ calltally --format json > analysis.json
62
+
63
+ # CSV for spreadsheet analysis
64
+ calltally --format csv -o results.csv
65
+ ```
66
+
67
+ ### Filtering and Analysis
68
+
69
+ ```bash
70
+ # Show only method names (no receivers)
71
+ calltally --mode methods
72
+
73
+ # Show only receivers (classes being called)
74
+ calltally --mode receivers
75
+
76
+ # Show receiver-method pairs (default)
77
+ calltally --mode pairs
78
+
79
+ # Include methods called without explicit receivers
80
+ calltally --include-nil-receiver
81
+ ```
82
+
83
+ ## Configuration
84
+
85
+ Create `.calltally.yml` in your project root for persistent settings:
86
+
87
+ ```yaml
88
+ # .calltally.yml
89
+ profile: rails # auto|rails|default
90
+ dirs: # Directories to scan
91
+ - app
92
+ - lib
93
+ exclude: # Patterns to exclude
94
+ - spec
95
+ - test
96
+ - vendor
97
+ top: 50 # Number of results to show
98
+ include_erb: true # Process ERB files
99
+ mode: pairs # pairs|methods|receivers
100
+ skip_operators: true # Skip operators like +, -, ==
101
+ ```
102
+
103
+ You can also use a custom config file:
104
+
105
+ ```bash
106
+ calltally --config config/calltally-production.yml
107
+ ```
108
+
109
+ ## Advanced Usage
110
+
111
+ <details>
112
+ <summary>Filter by Variable Types</summary>
113
+
114
+ ```bash
115
+ # Only local variables
116
+ calltally --only-locals
117
+
118
+ # Only instance variables
119
+ calltally --only-ivars
120
+
121
+ # Only class/module constants
122
+ calltally --only-constants
123
+
124
+ # Class variables
125
+ calltally --only-cvars
126
+
127
+ # Global variables
128
+ calltally --only-gvars
129
+
130
+ # Combine filters
131
+ calltally --only-locals --only-constants
132
+
133
+ # Show variable names instead of grouping
134
+ calltally --split-variables
135
+ # Shows: (var:user).name instead of (var).name
136
+ ```
137
+ </details>
138
+
139
+ <details>
140
+ <summary>All CLI Options</summary>
141
+
142
+ ```
143
+ calltally [PATH] [options]
144
+
145
+ Options:
146
+ --profile PROFILE auto|rails|default (default: auto)
147
+ -d, --dirs x,y Directories to include
148
+ -x, --exclude x,y Path parts to exclude
149
+ -n, --top N Show top N results (default: 100)
150
+ -v, --verbose Verbose output
151
+ --erb Include .erb files (requires erubi gem)
152
+
153
+ --mode MODE Output mode:
154
+ - pairs: receiver-method pairs (default)
155
+ - methods: method names only
156
+ - receivers: receiver names only
157
+
158
+ --receivers x,y Filter by receiver constants (e.g. User,Post)
159
+ --methods x,y Filter by method names (e.g. where,find)
160
+
161
+ --include-nil-receiver Count calls without explicit receiver
162
+ --split-variables Show variable names (e.g. '(var:user)' vs '(var)')
163
+
164
+ --only-locals Show only local variable receivers
165
+ --only-ivars Show only instance variable receivers
166
+ --only-cvars Show only class variable receivers
167
+ --only-gvars Show only global variable receivers
168
+ --only-constants Show only constant receivers
169
+
170
+ --[no-]skip-operators Skip operator methods like +, -, ==, [] (default: true)
171
+
172
+ --format FORMAT Output format: table|json|csv (default: table)
173
+ -o, --output PATH Write result to file instead of STDOUT
174
+ --config PATH Use a specific config file
175
+ -h, --help Show help
176
+ ```
177
+ </details>
178
+
179
+ ## Understanding the Output
180
+
181
+ Calltally shows method calls in your codebase with their receivers:
182
+
183
+ ```
184
+ 10 User.where # User class, where method, called 10 times
185
+ 5 (var).each # Local variable, each method, called 5 times
186
+ 3 (ivar).save # Instance variable, save method
187
+ 2 Post#.validate # validate called within Post class (implicit receiver)
188
+ ```
189
+
190
+ ### Receiver Types
191
+
192
+ - `User` - Class or module constant
193
+ - `(var)` - Local variable (use `--split-variables` to see names)
194
+ - `(ivar)` - Instance variable
195
+ - `(cvar)` - Class variable
196
+ - `(gvar)` - Global variable
197
+ - `(self)` - Explicit self receiver
198
+ - `(result)` - Method calls on results (e.g., `user.posts.first` → `(var).posts` + `(result).first`)
199
+ - `#` - Implicit receiver (when using `--include-nil-receiver`)
200
+
201
+ ## Use Cases
202
+
203
+ 1. **Find most-used methods** - Identify candidates for optimization
204
+ 2. **Understand code patterns** - See how your team uses APIs
205
+ 3. **Refactoring decisions** - Know what methods are heavily depended upon
206
+ 4. **API design** - Understand which methods are actually used
207
+ 5. **Code reviews** - Quickly analyze unfamiliar codebases
208
+ 6. **Gem development** - See how your gem's methods are used
209
+
210
+ ## Contributing
211
+
212
+ Bug reports and pull requests are welcome on GitHub at https://github.com/nsgc/calltally.
213
+
214
+ ## License
215
+
216
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ task default: :test
data/exe/calltally ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "calltally"
4
+
5
+ Calltally::CLI.start(ARGV)
@@ -0,0 +1,131 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "optparse"
4
+ require "yaml"
5
+
6
+ module Calltally
7
+ class CLI
8
+ def self.start(argv) = new.run(argv)
9
+
10
+ def run(argv)
11
+ sub = argv.first
12
+ return print_help if %w[-h --help help].include?(sub)
13
+
14
+ case sub
15
+ when "scan" then run_scan(argv.drop(1))
16
+ when nil then run_scan(argv) # Default to scan when no command specified
17
+ else
18
+ # If first arg doesn't look like a command, treat as scan with path
19
+ if sub.start_with?("-") || File.exist?(sub) || sub == "."
20
+ run_scan(argv)
21
+ else
22
+ warn "Unknown command: #{sub}"
23
+ print_help
24
+
25
+ exit 1
26
+ end
27
+ end
28
+ end
29
+
30
+ def print_help
31
+ puts <<~USAGE
32
+ calltally #{Calltally::VERSION}
33
+ Usage:
34
+ calltally [PATH] [options] # Defaults to scan command
35
+ calltally scan [PATH] [options]
36
+
37
+ Commands:
38
+ scan Scan a directory (default PATH='.') and summarize method usage. (default)
39
+
40
+ Options (scan):
41
+ --profile PROFILE auto(default)|rails|default
42
+ -d, --dirs x,y Directories to include
43
+ -x, --exclude x,y Path parts to exclude
44
+ -n, --top N Show top N (default: 100)
45
+ -v, --verbose
46
+ --erb Include .erb (requires 'erubi' gem)
47
+ --mode MODE Output mode:
48
+ - pairs (default): receiver-method pairs
49
+ - methods: method names only
50
+ - receivers: receiver names only
51
+ --receivers x,y Filter by receiver constants (e.g. User,Group)
52
+ --methods x,y Filter by method names (e.g. where,find)
53
+ --include-nil-receiver Count calls without constant receiver (as '(no recv)')
54
+ --split-variables Show variable names (e.g. '(var:user)' instead of '(var)')
55
+ --only-locals Show only local variable receivers
56
+ --only-ivars Show only instance variable receivers
57
+ --only-cvars Show only class variable receivers
58
+ --only-gvars Show only global variable receivers
59
+ --only-constants Show only constant receivers
60
+ --only-results Show only method results receivers
61
+ --[no-]skip-operators Skip operator methods like +, -, ==, [] (default: true)
62
+ --format F table(default)|json|csv
63
+ -o, --output PATH Write result to file instead of STDOUT
64
+ --config PATH Use a specific .calltally.yml
65
+ -h, --help
66
+ USAGE
67
+ end
68
+
69
+ def run_scan(argv)
70
+ base_dir = "."
71
+ cli_opts = {}
72
+ config_override = nil
73
+
74
+ opts = OptionParser.new do |opt|
75
+ opt.on("--profile PROFILE") { |v| cli_opts["profile"] = v }
76
+ opt.on("-d x,y", "--dirs x,y", Array) { |v| cli_opts["dirs"] = v }
77
+ opt.on("-x x,y", "--exclude x,y", Array) { |v| cli_opts["exclude"] = v }
78
+ opt.on("-n N", "--top N", Integer) { |v| cli_opts["top"] = v }
79
+ opt.on("-v", "--verbose") { cli_opts["verbose"] = true }
80
+ opt.on("--erb") { cli_opts["include_erb"] = true }
81
+ opt.on("--mode MODE", [:pairs, :methods, :receivers]) { |v| cli_opts["mode"] = v.to_s }
82
+ opt.on("--receivers x,y", Array) { |v| cli_opts["receivers"] = v }
83
+ opt.on("--methods x,y", Array) { |v| cli_opts["methods"] = v }
84
+ opt.on("--include-nil-receiver") { cli_opts["include_nil_receiver"] = true }
85
+ opt.on("--split-variables") { cli_opts["split_variables"] = true }
86
+ opt.on("--only-locals") { (cli_opts["receiver_types"] ||= []) << "locals" }
87
+ opt.on("--only-ivars") { (cli_opts["receiver_types"] ||= []) << "ivars" }
88
+ opt.on("--only-cvars") { (cli_opts["receiver_types"] ||= []) << "cvars" }
89
+ opt.on("--only-gvars") { (cli_opts["receiver_types"] ||= []) << "gvars" }
90
+ opt.on("--only-constants") { (cli_opts["receiver_types"] ||= []) << "constants" }
91
+ opt.on("--only-results") { (cli_opts["receiver_types"] ||= []) << "results" }
92
+ opt.on("--[no-]skip-operators") { |v| cli_opts["skip_operators"] = v }
93
+ opt.on("--format F", [:table, :json, :csv]) { |v| cli_opts["format"] = v.to_s }
94
+ opt.on("-o PATH", "--output PATH") { |v| cli_opts["output"] = v }
95
+ opt.on("--config PATH") { |v| config_override = v }
96
+ opt.on("-h", "--help") { puts opt; exit }
97
+ end
98
+
99
+ if argv.first && !argv.first.start_with?("-")
100
+ base_dir = argv.shift
101
+ end
102
+
103
+ opts.parse!(argv)
104
+
105
+ if config_override && File.file?(config_override)
106
+ yaml = YAML.load_file(config_override) || {}
107
+ yaml.each { |k, v| cli_opts[k.to_s] = v unless cli_opts.key?(k.to_s) }
108
+ end
109
+
110
+ config = Calltally::Config.load(base_dir: base_dir, cli_opts: cli_opts)
111
+
112
+ if config["profile"] == "rails" && config["include_erb"] && !Calltally::Config.erubi_available?
113
+ warn "[calltally] Rails profile detected but 'erubi' not found. ERB will be skipped. Install 'erubi' to include ERB."
114
+ config["include_erb"] = false
115
+ end
116
+
117
+ mode, rows = Calltally::Scanner.new(base_dir: base_dir, config: config).scan
118
+
119
+ out = config["output"] ? File.open(config["output"], "w") : $stdout
120
+ begin
121
+ case config["format"]
122
+ when "json" then Calltally::Formatter.print_json(mode: mode, data: rows, io: out)
123
+ when "csv" then Calltally::Formatter.print_csv(mode: mode, data: rows, io: out)
124
+ else Calltally::Formatter.print_table(mode: mode, data: rows, io: out)
125
+ end
126
+ ensure
127
+ out.close if out.is_a?(File)
128
+ end
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+ require "set"
5
+
6
+ module Calltally
7
+ class Config
8
+ DEFAULTS = {
9
+ "profile" => "auto", # auto|rails|default
10
+ "dirs" => %w[.],
11
+ "exclude" => %w[spec test vendor node_modules tmp log .git .bundle],
12
+ "top" => 100,
13
+ "verbose" => false,
14
+ "include_erb" => false,
15
+ "mode" => "pairs", # pairs|methods|receivers
16
+ "receivers" => nil, # ["User","Group"]
17
+ "methods" => nil, # ["where","find"]
18
+ "include_nil_receiver" => false,
19
+ "split_variables" => false, # Show variable names vs grouping
20
+ "receiver_types" => nil, # ["locals", "ivars", "constants"] etc.
21
+ "skip_operators" => true,
22
+ "format" => "table", # table|json|csv
23
+ "output" => nil
24
+ }.freeze
25
+
26
+ RAILS_DIR_PRESET = %w[app lib config].freeze
27
+
28
+ def self.load(base_dir:, cli_opts:)
29
+ config = DEFAULTS.dup
30
+
31
+ path = File.join(base_dir, ".calltally.yml")
32
+ if File.file?(path)
33
+ yaml = YAML.load_file(path) || {}
34
+ yaml.each { |k, v| config[k.to_s] = v }
35
+ end
36
+
37
+ cli_opts.compact.each { |k, v| config[k.to_s] = v }
38
+
39
+ config["profile"] = resolve_profile(base_dir, config["profile"])
40
+
41
+ if config["profile"] == "rails"
42
+ config["dirs"] = RAILS_DIR_PRESET if config["dirs"] == DEFAULTS["dirs"]
43
+ config["include_erb"] = config["include_erb"] || erubi_available?
44
+ end
45
+
46
+ config["receivers"] = to_set_or_nil(config["receivers"])
47
+ config["methods"] = to_set_or_nil(config["methods"]&.map(&:to_s))
48
+ config
49
+ end
50
+
51
+ def self.resolve_profile(base_dir, desired)
52
+ return desired unless desired == "auto"
53
+
54
+ gemfile_path = File.join(base_dir, "Gemfile")
55
+ if File.file?(gemfile_path) && File.read(gemfile_path).include?("rails")
56
+ "rails"
57
+ else
58
+ "default"
59
+ end
60
+ end
61
+
62
+ def self.erubi_available?
63
+ require "erubi"
64
+ true
65
+ rescue LoadError
66
+ false
67
+ end
68
+
69
+ def self.to_set_or_nil(v)
70
+ case v
71
+ when nil then nil
72
+ when Set then v
73
+ when Array then Set.new(v)
74
+ else Set.new([v])
75
+ end
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ begin
5
+ require "csv"
6
+ rescue LoadError
7
+ # CSV is optional for Ruby 3.4+
8
+ end
9
+
10
+ module Calltally
11
+ module Formatter
12
+ module_function
13
+
14
+ def print_table(mode:, data:, io: $stdout)
15
+ case mode
16
+ when :pairs
17
+ name_w = (data.map { |receiver, method, _| "#{receiver}.#{method}".length }.max || 0)
18
+ count_w = (data.map { |_, _, count| count.to_s.length }.max || 1)
19
+
20
+ data.each { |receiver, method, count|
21
+ io.puts "#{count.to_s.rjust(count_w)} #{(receiver + "." + method).ljust(name_w)}"
22
+ }
23
+ when :methods, :receivers
24
+ name_w = (data.map { |name, _| name.to_s.length }.max || 0)
25
+ count_w = (data.map { |_, count| count.to_s.length }.max || 1)
26
+
27
+ data.each { |name, count|
28
+ io.puts "#{count.to_s.rjust(count_w)} #{name.to_s.ljust(name_w)}"
29
+ }
30
+ end
31
+ end
32
+
33
+ def print_json(mode:, data:, io: $stdout)
34
+ payload =
35
+ case mode
36
+ when :pairs
37
+ { mode: "pairs", rows: data.map { |receiver, method, count| { receiver:, method:, count: } } }
38
+ when :methods
39
+ { mode: "methods", rows: data.map { |method, count| { method:, count: } } }
40
+ when :receivers
41
+ { mode: "receivers", rows: data.map { |receiver, count| { receiver:, count: } } }
42
+ end
43
+
44
+ io.puts JSON.pretty_generate(payload)
45
+ end
46
+
47
+ def print_csv(mode:, data:, io: $stdout)
48
+ case mode
49
+ when :pairs
50
+ io.puts CSV.generate_line(%w[receiver method count])
51
+ data.each { |receiver, method, count| io.puts CSV.generate_line([receiver, method, count]) }
52
+ when :methods
53
+ io.puts CSV.generate_line(%w[method count])
54
+ data.each { |method, count| io.puts CSV.generate_line([method, count]) }
55
+ when :receivers
56
+ io.puts CSV.generate_line(%w[receiver count])
57
+ data.each { |receiver, count| io.puts CSV.generate_line([receiver, count]) }
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,169 @@
1
+ # frozen_string_literal: true
2
+
3
+ begin
4
+ require "prism"
5
+ rescue LoadError
6
+ warn "[calltally] prism not found. Install 'prism' gem or use Ruby 3.3+."
7
+ raise
8
+ end
9
+
10
+ module Calltally
11
+ class PrismVisitor < ::Prism::Visitor
12
+ def initialize(config, pair_counts, method_counts, receiver_counts)
13
+ super()
14
+
15
+ @config = config
16
+ @pair_counts = pair_counts
17
+ @method_counts = method_counts
18
+ @receiver_counts = receiver_counts
19
+ @class_stack = []
20
+ end
21
+
22
+ def visit_class_node(node)
23
+ class_name = extract_class_name(node.constant_path)
24
+ @class_stack.push(class_name)
25
+
26
+ super
27
+ ensure
28
+ @class_stack.pop
29
+ end
30
+
31
+ def visit_module_node(node)
32
+ module_name = extract_class_name(node.constant_path)
33
+ @class_stack.push(module_name)
34
+
35
+ super
36
+ ensure
37
+ @class_stack.pop
38
+ end
39
+
40
+ def visit_call_node(node)
41
+ meth = node.name&.to_s
42
+ rname = receiver_name(node.receiver)
43
+ tally(rname, meth)
44
+
45
+ super
46
+ end
47
+
48
+ def visit_block_argument_node(node)
49
+ expr = node.expression
50
+
51
+ if expr.is_a?(::Prism::SymbolNode)
52
+ tally(nil, expr.value.to_s)
53
+ end
54
+
55
+ super
56
+ end
57
+
58
+ private
59
+
60
+ def operator_like?(name)
61
+ name = name.to_s
62
+ !!(name =~ /\A(\[\]|\[\]=|[!~]|\*\*|===|==|!=|<=|>=|<<|>>|<|>|\+|-|\*|\/|%|\^|&|\|)\z/)
63
+ end
64
+
65
+ def tally(receiver_name, method_name)
66
+ return if method_name.nil?
67
+ return if @config["skip_operators"] && operator_like?(method_name)
68
+ return if @config["methods"] && !@config["methods"].include?(method_name)
69
+
70
+ # Filter by receiver type if specified
71
+ if @config["receiver_types"] && !@config["receiver_types"].empty?
72
+ return unless receiver_type_matches?(receiver_name, @config["receiver_types"])
73
+ end
74
+
75
+ if receiver_name.nil? && @config["include_nil_receiver"]
76
+ receiver_name = current_context_with_hash
77
+ end
78
+
79
+ case @config["mode"].to_s.downcase.to_sym
80
+ when :pairs
81
+ if receiver_name
82
+ return if @config["receivers"] && !@config["receivers"].include?(receiver_name)
83
+
84
+ @pair_counts[[receiver_name, method_name]] += 1
85
+ @receiver_counts[receiver_name] += 1
86
+ else
87
+ @method_counts[method_name] += 1
88
+ end
89
+ when :methods
90
+ @method_counts[method_name] += 1
91
+ when :receivers
92
+ @receiver_counts[receiver_name] += 1 if receiver_name
93
+ end
94
+ end
95
+
96
+ def receiver_name(node)
97
+ return nil if node.nil?
98
+
99
+ case node
100
+ when ::Prism::ConstantReadNode, ::Prism::ConstantPathNode
101
+ node.full_name.to_s if node.respond_to?(:full_name)
102
+ when ::Prism::LocalVariableReadNode
103
+ @config["split_variables"] ? "(var:#{node.name})" : "(var)"
104
+ when ::Prism::InstanceVariableReadNode
105
+ @config["split_variables"] ? "(ivar:#{node.name})" : "(ivar)"
106
+ when ::Prism::ClassVariableReadNode
107
+ @config["split_variables"] ? "(cvar:#{node.name})" : "(cvar)"
108
+ when ::Prism::GlobalVariableReadNode
109
+ @config["split_variables"] ? "(gvar:#{node.name})" : "(gvar)"
110
+ when ::Prism::SelfNode
111
+ "(self)"
112
+ when ::Prism::CallNode
113
+ "(result)"
114
+ else
115
+ nil
116
+ end
117
+ end
118
+
119
+ def const_full_name(node)
120
+ return nil if node.nil?
121
+ return node.full_name.to_s if node.respond_to?(:full_name)
122
+ nil
123
+ end
124
+
125
+ def extract_class_name(node)
126
+ case node
127
+ when ::Prism::ConstantReadNode
128
+ node.name.to_s
129
+ when ::Prism::ConstantPathNode
130
+ node.full_name.to_s if node.respond_to?(:full_name)
131
+ else
132
+ nil
133
+ end
134
+ end
135
+
136
+ def current_context_with_hash
137
+ if @class_stack.empty?
138
+ "#"
139
+ else
140
+ "#{@class_stack.join('::')}#"
141
+ end
142
+ end
143
+
144
+ def receiver_type_matches?(rname, allowed_types)
145
+ return false if rname.nil?
146
+
147
+ if rname.start_with?("(var")
148
+ allowed_types.include?("locals")
149
+ elsif rname.start_with?("(ivar")
150
+ allowed_types.include?("ivars")
151
+ elsif rname.start_with?("(cvar")
152
+ allowed_types.include?("cvars")
153
+ elsif rname.start_with?("(gvar")
154
+ allowed_types.include?("gvars")
155
+ elsif rname.start_with?("(result)")
156
+ allowed_types.include?("results")
157
+ elsif rname.start_with?("(self)")
158
+ # For future --only-self option
159
+ allowed_types.include?("self")
160
+ elsif rname.start_with?("#")
161
+ # For nil receivers with include_nil_receiver
162
+ allowed_types.include?("implicit")
163
+ else
164
+ # Constants like User, Post, etc.
165
+ allowed_types.include?("constants")
166
+ end
167
+ end
168
+ end
169
+ end
@@ -0,0 +1,104 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "find"
4
+ require "calltally/prism_visitor"
5
+
6
+ module Calltally
7
+ class Scanner
8
+ def initialize(base_dir:, config:)
9
+ @base_dir = File.expand_path(base_dir)
10
+ @config = config
11
+ end
12
+
13
+ def scan
14
+ files = collect_paths
15
+ warn_verbose "Scan targets: #{files.size} files"
16
+ files.first(10).each { |file| warn_verbose " - #{file}" }
17
+
18
+ pair_counts = Hash.new(0)
19
+ method_counts = Hash.new(0)
20
+ receiver_counts = Hash.new(0)
21
+
22
+ visitor = PrismVisitor.new(@config, pair_counts, method_counts, receiver_counts)
23
+
24
+ files.each do |path|
25
+ begin
26
+ src = read_source(path)
27
+ result = ::Prism.parse(src)
28
+ if (root = result.value)
29
+ visitor.visit(root)
30
+ else
31
+ warn_verbose "Prism.parse returned nil: #{path}"
32
+ end
33
+ rescue => e
34
+ warn "Error: #{path}: #{e.class}: #{e.message}"
35
+ end
36
+ end
37
+
38
+ top = Integer(@config["top"])
39
+ mode_sym = @config["mode"].to_s.downcase.to_sym
40
+
41
+ case mode_sym
42
+ when :pairs
43
+ rows = pair_counts.sort_by { |(_, _), c| -c }.first(top).map { |(r, m), c| [r, m, c] }
44
+ when :methods
45
+ rows = method_counts.sort_by { |_, c| -c }.first(top).map { |m, c| [m, c] }
46
+ when :receivers
47
+ rows = receiver_counts.sort_by { |_, c| -c }.first(top).map { |r, c| [r, c] }
48
+ else
49
+ raise ArgumentError, "Unknown mode: #{@config['mode']}"
50
+ end
51
+
52
+ [mode_sym, rows]
53
+ end
54
+
55
+ private
56
+
57
+ def warn_verbose(msg)
58
+ return unless @config && @config["verbose"]
59
+ warn(msg)
60
+ end
61
+
62
+ def collect_paths
63
+ exts = %w[.rb .ru .rake]
64
+ exts << ".erb" if @config["include_erb"]
65
+
66
+ files = []
67
+ @config["dirs"].each do |dir|
68
+ absolute_path = File.expand_path(dir, @base_dir)
69
+ next unless Dir.exist?(absolute_path)
70
+
71
+ Find.find(absolute_path) do |path|
72
+ next if File.directory?(path)
73
+ next unless exts.include?(File.extname(path))
74
+ next if excluded?(path)
75
+
76
+ files << path
77
+ end
78
+ end
79
+
80
+ files.uniq
81
+ end
82
+
83
+ def excluded?(path)
84
+ rel = path.sub(@base_dir + "/", "")
85
+ @config["exclude"].any? { |ex| rel.include?("/#{ex}/") || File.basename(rel).start_with?("#{ex}.") }
86
+ end
87
+
88
+ def read_source(path)
89
+ src = File.binread(path)
90
+ src = src.encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: "")
91
+
92
+ if @config["include_erb"] && File.extname(path) == ".erb"
93
+ begin
94
+ require "erubi"
95
+ src = Erubi::Engine.new(src).src
96
+ rescue LoadError
97
+ warn "ERB requested but 'erubi' not installed. Skipping ERB compilation for #{path}."
98
+ end
99
+ end
100
+
101
+ src
102
+ end
103
+ end
104
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Calltally
4
+ VERSION = "0.1.0"
5
+ end
data/lib/calltally.rb ADDED
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "calltally/version"
4
+ require_relative "calltally/version"
5
+ require_relative "calltally/config"
6
+ require_relative "calltally/formatter"
7
+ require_relative "calltally/scanner"
8
+ require_relative "calltally/cli"
9
+
10
+ module Calltally
11
+ end
data/sig/calltally.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Calltally
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,114 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: calltally
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Naoki Nishiguchi
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: prism
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '1.0'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '1.0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: csv
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '3.0'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '3.0'
40
+ - !ruby/object:Gem::Dependency
41
+ name: rake
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - "~>"
45
+ - !ruby/object:Gem::Version
46
+ version: '13.0'
47
+ type: :development
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - "~>"
52
+ - !ruby/object:Gem::Version
53
+ version: '13.0'
54
+ - !ruby/object:Gem::Dependency
55
+ name: erubi
56
+ requirement: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: '0'
61
+ type: :development
62
+ prerelease: false
63
+ version_requirements: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '0'
68
+ description: A simple yet powerful tool to analyze method usage in Ruby/Rails codebases.
69
+ Track which methods are called most frequently, filter by receivers or method names,
70
+ and export results in table, JSON, or CSV format. Perfect for understanding code
71
+ patterns, refactoring decisions, and identifying heavily-used APIs.
72
+ executables:
73
+ - calltally
74
+ extensions: []
75
+ extra_rdoc_files: []
76
+ files:
77
+ - CODE_OF_CONDUCT.md
78
+ - LICENSE.txt
79
+ - README.md
80
+ - Rakefile
81
+ - exe/calltally
82
+ - lib/calltally.rb
83
+ - lib/calltally/cli.rb
84
+ - lib/calltally/config.rb
85
+ - lib/calltally/formatter.rb
86
+ - lib/calltally/prism_visitor.rb
87
+ - lib/calltally/scanner.rb
88
+ - lib/calltally/version.rb
89
+ - sig/calltally.rbs
90
+ homepage: https://github.com/nsgc/calltally
91
+ licenses:
92
+ - MIT
93
+ metadata:
94
+ homepage_uri: https://github.com/nsgc/calltally
95
+ source_code_uri: https://github.com/nsgc/calltally.git
96
+ rubygems_mfa_required: 'true'
97
+ rdoc_options: []
98
+ require_paths:
99
+ - lib
100
+ required_ruby_version: !ruby/object:Gem::Requirement
101
+ requirements:
102
+ - - ">="
103
+ - !ruby/object:Gem::Version
104
+ version: 3.2.0
105
+ required_rubygems_version: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - ">="
108
+ - !ruby/object:Gem::Version
109
+ version: '0'
110
+ requirements: []
111
+ rubygems_version: 3.6.9
112
+ specification_version: 4
113
+ summary: Tally your method calls
114
+ test_files: []