Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(ruby): flag a gem's lib entry file and what it requires as public API (#3506) (#4526)

Aman3081b9d4bf06
diff --git a/packages/cli/src/repowise/cli/ui/progress.py b/packages/cli/src/repowise/cli/ui/progress.py
index 244a26f4c..d88b6c56f 100644
--- a/packages/cli/src/repowise/cli/ui/progress.py
+++ b/packages/cli/src/repowise/cli/ui/progress.py
@@ -94,6 +94,7 @@ _PHASE_LABELS: dict[str, str] = {
"graph.dotnet_index": " ↳ Indexing .NET projects",
"graph.go_index": " ↳ Indexing Go packages",
"graph.rust_targets": " ↳ Reading Rust crate targets",
+ "graph.ruby_gems": " ↳ Finding Ruby gem entry points",
"graph.cpp_index": " ↳ Indexing C and C++ includes",
"graph.swift_entry": " ↳ Finding Swift entry points",
"graph.composer_files": " ↳ Reading Composer autoload rules",
diff --git a/packages/core/src/repowise/core/analysis/public_api.py b/packages/core/src/repowise/core/analysis/public_api.py
index 75193851d..11c990474 100644
--- a/packages/core/src/repowise/core/analysis/public_api.py
+++ b/packages/core/src/repowise/core/analysis/public_api.py
@@ -422,6 +422,35 @@ def _sibling_owner(
return None
+def _enclosing_ruby_owner(
+ sym: Any, out: Mapping[str, str], containers: Sequence[Any]
+) -> str | None:
+ """The export root of the Ruby module or class that encloses *sym* in its file.
+
+ A Ruby symbol's id names only its immediate parent, so a method of
+ ``Mygem::Client`` is ``<file>::Client::get`` while the class is
+ ``<file>::Mygem::Client``, and ``<file>::<parent>`` is not a symbol. The
+ enclosing container is found by name and extent instead: the innermost one
+ whose lines hold *sym*, which also tells two ``Client`` classes in different
+ namespaces apart.
+ """
+ parent = (sym.parent_name or "").rsplit("::", 1)[-1]
+ best = None
+ for container in containers:
+ if (
+ container.name == parent
+ and container is not sym
+ and container.start_line <= sym.start_line
+ and container.end_line >= sym.end_line
+ and (
+ best is None
+ or container.end_line - container.start_line < best.end_line - best.start_line
+ )
+ ):
+ best = container
+ return out.get(best.id) if best is not None else None
+
+
def _local_id(sym: Any, path: str) -> str:
"""A top-level symbol's id within its file (``Box`1`` for a generic ``Box<T>``)."""
return sym.id[len(path) + 2 :]
@@ -508,8 +537,19 @@ def public_symbols(
_publish_partial_fragments(parsed, fragments, out)
for path, pf in parsed.items():
- for sym in pf.symbols:
- owner = out.get(f"{path}::{sym.parent_name}") if sym.parent_name else None
+ symbols: Sequence[Any] = pf.symbols
+ containers: list[Any] = []
+ if pf.file_info.language == "ruby":
+ # Parents before their members, so a nested class is exported
+ # before the methods it holds are looked up.
+ symbols = sorted(pf.symbols, key=lambda s: (s.start_line, -s.end_line))
+ containers = [s for s in symbols if s.kind in ("class", "module")]
+ for sym in symbols:
+ owner = None
+ if containers and sym.parent_name:
+ owner = _enclosing_ruby_owner(sym, out, containers)
+ if owner is None and sym.parent_name:
+ owner = out.get(f"{path}::{sym.parent_name}")
if owner is None and sym.parent_name and package_files:
owner = _sibling_owner(path, sym.parent_name, out, root_set, package_files)
if owner is not None and sym.visibility == "public":
@@ -533,6 +573,39 @@ def _partial_fragments(graph: Any, parsed: Mapping[str, Any]) -> dict[str, set[s
return out
+def _ruby_gem_files(graph: Any, parsed: Mapping[str, Any]) -> set[str]:
+ """The files a gem publishes: its entry and what that requires inside its own ``lib``.
+
+ The Ruby warmup stamps each gem's ``lib/<name>.rb`` with the ``lib`` root it
+ sits in (``ruby_gem_lib``). Requires are not resolved at warmup time, so the
+ closure is taken here over ``Import.resolved_file``. A file nothing in the
+ gem requires is not part of its surface, nor is a test file or anything
+ another gem's ``lib`` holds.
+ """
+ out: set[str] = set()
+ for entry in sorted(parsed):
+ lib_root = graph.nodes.get(entry, {}).get("ruby_gem_lib")
+ if not lib_root:
+ continue
+ prefix = f"{lib_root}/"
+ reached = {entry}
+ pending = [entry]
+ while pending:
+ for imp in parsed[pending.pop()].imports:
+ target = imp.resolved_file
+ if (
+ target in reached
+ or target not in parsed
+ or not target.startswith(prefix)
+ or parsed[target].file_info.is_test
+ ):
+ continue
+ reached.add(target)
+ pending.append(target)
+ out |= reached
+ return out
+
+
def stamp_public_api(
graph: Any,
parsed: Mapping[str, Any],
@@ -542,6 +615,7 @@ def stamp_public_api(
entries = {
path for path in parsed if graph.nodes.get(path, {}).get("package_export")
}
+ entries |= _ruby_gem_files(graph, parsed)
exported = public_symbols(parsed, entries, package_files, _partial_fragments(graph, parsed))
for pf in parsed.values():
for sym in pf.symbols:
diff --git a/packages/core/src/repowise/core/ingestion/extractors/visibility.py b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
index 0371945c8..f178eb95a 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/visibility.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
@@ -8,7 +8,8 @@ access specifier siblings, ``static`` storage class at file scope and
defaults, which differ by enclosing declaration; TS/JS export position;
Python's module-level ``__all__``, which can export a name the identifier
alone would call private; Rust's trait items, which may not write a modifier
-of their own. Each has a ``refine_*_visibility`` the parser calls after the
+of their own; Ruby's ``private`` / ``protected``, which are calls in the class
+body, not modifiers. Each has a ``refine_*_visibility`` the parser calls after the
generic ``visibility_fn``.
"""
@@ -16,8 +17,8 @@ from __future__ import annotations
import ast
import re
-from collections.abc import Callable
-from typing import TYPE_CHECKING
+from collections.abc import Callable, Iterable
+from typing import TYPE_CHECKING, Any
from repowise.core.pyparse import parse_python
@@ -598,6 +599,120 @@ _JAVA_ACCESS_KEYWORDS = ("private", "protected", "public")
_JAVA_PUBLIC_BODIES = frozenset({"interface_body", "annotation_type_body"})
+_RUBY_ACCESS = frozenset({"private", "protected", "public"})
+_RUBY_CLASS_ACCESS = {"private_class_method": "private", "public_class_method": "public"}
+_RUBY_BODIES = frozenset({"body_statement", "class", "module", "singleton_class"})
+# A body's index: the bare access in force at each def (by start byte), and the
+# ``(position, access)`` of every call naming a method, for instance and class methods.
+_RubyBody = tuple[
+ dict[int, str], dict[str, list[tuple[int, str]]], dict[str, list[tuple[int, str]]]
+]
+
+
+def _ruby_call_access(call: Node, src: str, names: Iterable[str]) -> tuple[str, list[str]] | None:
+ """``(keyword, [method names])`` of a ``private :a, :b`` style call, else None.
+
+ A call with no symbol or string arguments (``private def x``,
+ ``private attr_reader :y``) lists no names.
+ """
+ method = call.child_by_field_name("method")
+ keyword = node_text(method, src)
+ if call.type != "call" or call.child_by_field_name("receiver") is not None:
+ return None
+ if keyword not in names:
+ return None
+ args = call.child_by_field_name("arguments")
+ listed: list[str] = []
+ for arg in args.named_children if args is not None else ():
+ if arg.type == "simple_symbol":
+ listed.append(node_text(arg, src).lstrip(":"))
+ elif arg.type == "string":
+ parts = (node_text(c, src) for c in arg.named_children if c.type == "string_content")
+ listed.append("".join(parts))
+ return keyword, listed
+
+
+# The file whose class bodies are indexed, and the index: parsing visits every def of a
+# class, so each body is read once. The source is held by reference, which keeps its
+# identity from being recycled by another file while it is cached.
+_ruby_bodies: dict[str, Any] = {"src": None, "index": {}}
+
+_RUBY_ACCESS_CALLS = _RUBY_ACCESS | frozenset(_RUBY_CLASS_ACCESS)
+
+
+def _ruby_body_access(body: Node, src: str) -> _RubyBody:
+ """What a class or module body says about the access of the methods it defines."""
+ if _ruby_bodies["src"] is not src:
+ _ruby_bodies["src"], _ruby_bodies["index"] = src, {}
+ index: dict[tuple[int, int], _RubyBody] = _ruby_bodies["index"]
+ key = (body.start_byte, body.end_byte)
+ found = index.get(key)
+ if found is not None:
+ return found
+ defaults: dict[int, str] = {}
+ named: dict[str, list[tuple[int, str]]] = {}
+ class_named: dict[str, list[tuple[int, str]]] = {}
+ bare: str | None = None
+ for child in body.children:
+ if child.type == "identifier":
+ word = node_text(child, src)
+ if word in _RUBY_ACCESS:
+ bare = word
+ elif child.type == "method":
+ if bare is not None:
+ defaults[child.start_byte] = bare
+ elif child.type == "call":
+ hit = _ruby_call_access(child, src, _RUBY_ACCESS_CALLS)
+ if hit is None:
+ continue
+ keyword, names = hit
+ table, access = (
+ (class_named, _RUBY_CLASS_ACCESS[keyword])
+ if keyword in _RUBY_CLASS_ACCESS
+ else (named, keyword)
+ )
+ for name in names:
+ table.setdefault(name, []).append((child.start_byte, access))
+ found = index[key] = (defaults, named, class_named)
+ return found
+
+
+def refine_ruby_visibility(def_node: Node, current_visibility: str, src: str) -> str:
+ """Give a Ruby method the access its class body gives it.
+
+ ``private`` and ``protected`` are method calls, not modifiers: a bare one
+ sets the access of every ``def`` after it in the same body (``class << self``
+ bodies included), and ``private :a, :b`` or ``private def a`` names what it
+ covers. A later call naming the method wins over the bare default, and
+ ``def self.x`` ignores a bare ``private`` (``private_class_method`` is its
+ own). A ``def`` outside a class or module body keeps *current_visibility*.
+ """
+ if def_node.type not in ("method", "singleton_method"):
+ return current_visibility
+ parent = def_node.parent
+ if parent is None:
+ return current_visibility
+ # ``private def x`` wraps the definition in the call that names the access.
+ if parent.type == "argument_list" and parent.parent is not None:
+ wrapped = _ruby_call_access(parent.parent, src, _RUBY_ACCESS)
+ if wrapped is not None and def_node.type == "method":
+ return wrapped[0]
+ return current_visibility
+ if parent.type not in _RUBY_BODIES:
+ return current_visibility
+ defaults, named, class_named = _ruby_body_access(parent, src)
+ if def_node.type == "method":
+ visibility = defaults.get(def_node.start_byte, current_visibility)
+ later = named
+ else:
+ visibility, later = current_visibility, class_named
+ name = node_text(def_node.child_by_field_name("name"), src)
+ for position, access in later.get(name, ()):
+ if position > def_node.start_byte:
+ visibility = access
+ return visibility
+
+
def refine_java_visibility(def_node: Node) -> str:
"""Give a Java declaration the access it writes, else its scope's default.
diff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.py
index 043e66dcb..6462493b9 100644
--- a/packages/core/src/repowise/core/ingestion/graph_warmups.py
+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py
@@ -446,6 +446,28 @@ def _warmup_dotnet(ctx: ResolverContext) -> None:
node["package_export"] = True
+def _warmup_ruby(ctx: ResolverContext) -> None:
+ """Mark each gem's entry file as published, for the per-symbol public API
+ flag (``analysis.public_api``).
+
+ A gem's front door is ``lib/<name>.rb`` beside its gemspec. Only the entry
+ is stamped here, together with the ``lib`` root it sits in
+ (``ruby_gem_lib``): the files it requires are not resolved yet, so
+ ``stamp_public_api`` follows them once imports are. With no gemspec nothing
+ is stamped.
+ """
+ from .resolvers.ruby import gem_entry_files
+
+ graph = getattr(ctx, "graph", None)
+ if graph is None:
+ return
+ for path, lib_root in gem_entry_files(ctx).items():
+ node = graph.nodes.get(path)
+ if node is not None:
+ node["package_export"] = True
+ node["ruby_gem_lib"] = lib_root
+
+
def _warmup_rust(ctx: ResolverContext) -> None:
"""Stamp Cargo ``[[bin]]``/``[[test]]``/``[[bench]]``/``[[example]]``
targets that name an explicit ``path`` as live, so a file Cargo discovers
@@ -746,6 +768,7 @@ _WARMUPS: dict[str, tuple[str, Warmup]] = {
"csharp": ("graph.dotnet_index", _warmup_dotnet),
"go": ("graph.go_index", _warmup_go),
"rust": ("graph.rust_targets", _warmup_rust),
+ "ruby": ("graph.ruby_gems", _warmup_ruby),
"typescript": ("graph.ts_index", _warmup_typescript),
"javascript": ("graph.ts_index", _warmup_typescript),
"cpp": ("graph.cpp_index", _warmup_cpp),
diff --git a/packages/core/src/repowise/core/ingestion/parser/symbol_rules.py b/packages/core/src/repowise/core/ingestion/parser/symbol_rules.py
index c7b386717..d55df0469 100644
--- a/packages/core/src/repowise/core/ingestion/parser/symbol_rules.py
+++ b/packages/core/src/repowise/core/ingestion/parser/symbol_rules.py
@@ -23,6 +23,7 @@ from ..extractors.visibility import (
refine_csharp_visibility,
refine_java_visibility,
refine_py_visibility,
+ refine_ruby_visibility,
refine_rust_visibility,
refine_ts_visibility,
)
@@ -399,6 +400,10 @@ def _refine_visibility(
# trait's modifier is the only place their visibility is stated.
if language == "rust":
return refine_rust_visibility(def_node, visibility, src), False
+ # Ruby: ``private`` / ``protected`` are calls in the class body, so the
+ # def's own text says nothing; what precedes and follows it does.
+ if language == "ruby":
+ return refine_ruby_visibility(def_node, visibility, src), False
return visibility, False
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/ruby.py b/packages/core/src/repowise/core/ingestion/resolvers/ruby.py
index 7a3005e9e..bb7ba0fd7 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/ruby.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/ruby.py
@@ -27,6 +27,12 @@ _GEMFILE_GEM_RE = re.compile(r"^\s*gem\s+[\"']([A-Za-z0-9_.-]+)[\"']", re.MULTIL
_GEMSPEC_DEP_RE = re.compile(
r"\.add_(?:runtime_|development_)?dependency\s*\(?\s*[\"']([A-Za-z0-9_.-]+)[\"']"
)
+# gemspec name: spec.name = 'mygem' / s.name = "mygem" / spec.name = %q{mygem}, or the
+# first argument of ``Gem::Specification.new 'mygem', '1.0' do |s|``.
+_GEMSPEC_NAME_RE = re.compile(
+ r"^\s*\w+\.name\s*=\s*(?:%q[{(]|[\"'])([A-Za-z0-9_.-]+)", re.MULTILINE
+)
+_GEMSPEC_NEW_NAME_RE = re.compile(r"Specification\.new\s*\(?\s*[\"']([A-Za-z0-9_.-]+)[\"']")
# Ruby standard library require names (default + bundled gems shipping with
# the interpreter). Requires of these produce no node at all — same policy
@@ -53,8 +59,15 @@ def is_ruby_stdlib(module_path: str) -> bool:
return head in _RUBY_STDLIB
-def _scan_gem_metadata(ctx: ResolverContext) -> tuple[frozenset[str], tuple[str, ...]]:
- """Scan every Gemfile + *.gemspec once: dependency names + lib roots.
+def _scan_gem_metadata(
+ ctx: ResolverContext,
+) -> tuple[frozenset[str], tuple[str, ...], tuple[tuple[str, str], ...]]:
+ """Scan every Gemfile + *.gemspec once: dependency names, lib roots, gems.
+
+ The third element is ``(spec.name, lib root)`` per gemspec, which is what
+ names a gem's entry file (:func:`gem_entry_files`). A gemspec whose name is
+ not a literal (``spec.name = Mygem::NAME``) is named by its file, as
+ RubyGems expects it to be.
Monorepos (sinatra: rack-protection/, sinatra-contrib/) declare each
sub-gem's dependencies in its own gemspec — the walk covers them all.
@@ -66,6 +79,7 @@ def _scan_gem_metadata(ctx: ResolverContext) -> tuple[frozenset[str], tuple[str,
return cached
names: set[str] = set()
lib_roots: set[str] = set()
+ gems: set[tuple[str, str]] = set()
if ctx.repo_path is not None:
from repowise.core.fs_walk import glob_via
@@ -104,8 +118,11 @@ def _scan_gem_metadata(ctx: ResolverContext) -> tuple[frozenset[str], tuple[str,
rel_dir = f.parent.resolve().relative_to(repo).as_posix()
except (OSError, ValueError):
continue
- lib_roots.add("lib" if rel_dir == "." else f"{rel_dir}/lib")
- result = (frozenset(names), tuple(sorted(lib_roots)))
+ lib_root = "lib" if rel_dir == "." else f"{rel_dir}/lib"
+ lib_roots.add(lib_root)
+ declared = _GEMSPEC_NAME_RE.search(text) or _GEMSPEC_NEW_NAME_RE.search(text)
+ gems.add((declared.group(1) if declared else f.name[: -len(".gemspec")], lib_root))
+ result = (frozenset(names), tuple(sorted(lib_roots)), tuple(sorted(gems)))
ctx._ruby_gem_meta = result # type: ignore[attr-defined]
return result
@@ -114,6 +131,24 @@ def _get_or_build_gem_names(ctx: ResolverContext) -> frozenset[str]:
return _scan_gem_metadata(ctx)[0]
+def gem_entry_files(ctx: ResolverContext) -> dict[str, str]:
+ """``{entry file: the lib root it sits in}`` for every gem the repo ships.
+
+ A gem's front door is ``lib/<name>.rb`` beside its gemspec; with the file
+ absent, dashes in the name are path separators (``rack-protection`` ships
+ ``lib/rack/protection.rb``). A gemspec whose entry file is not in the repo
+ contributes nothing, and a repo with no gemspec has no gem.
+ """
+ entries: dict[str, str] = {}
+ for name, lib_root in _scan_gem_metadata(ctx)[2]:
+ for stem in dict.fromkeys((name, name.replace("-", "/"))):
+ candidate = f"{lib_root}/{stem}.rb"
+ if candidate in ctx.path_set:
+ entries.setdefault(candidate, lib_root)
+ break
+ return entries
+
+
def _is_declared_gem(module_path: str, ctx: ResolverContext) -> bool:
"""True when the require names a Gemfile/gemspec dependency.
@@ -145,7 +180,7 @@ def resolve_ruby_import(module_path: str, importer_path: str, ctx: ResolverConte
# joins are exact.
if not module_path.startswith("."):
# Repo-root lib/ + every sub-gem's lib/ (gemspec dirs) + root join.
- _gems, lib_roots = _scan_gem_metadata(ctx)
+ _gems, lib_roots, _specs = _scan_gem_metadata(ctx)
bases = dict.fromkeys(("lib", *lib_roots, ""))
for base in bases:
candidate = f"{base}/{module_path}.rb" if base else f"{module_path}.rb"
diff --git a/tests/unit/analysis/test_public_api_flag.py b/tests/unit/analysis/test_public_api_flag.py
index 758f0a59e..8c81b78c5 100644
--- a/tests/unit/analysis/test_public_api_flag.py
+++ b/tests/unit/analysis/test_public_api_flag.py
@@ -529,3 +529,148 @@ def test_partial_fragments_in_a_project_that_ships_nothing_stay_unflagged(tmp_pa
},
)
assert not {node for node, root in flags.items() if root}
+
+
+_GEMSPEC = "Gem::Specification.new do |spec|\n spec.name = '{name}'\n spec.version = '0.1'\nend\n"
+
+_RUBY_GEM = {
+ "mygem.gemspec": _GEMSPEC.format(name="mygem"),
+ "lib/mygem.rb": (
+ "require 'mygem/client'\n\n"
+ "module Mygem\n def self.new(url)\n Client.new(url)\n end\nend\n"
+ ),
+ "lib/mygem/client.rb": (
+ "module Mygem\n class Client\n def get(path)\n end\n\n"
+ " private\n\n def retry_once\n end\n end\nend\n"
+ ),
+ "lib/mygem/unloaded.rb": "module Mygem\n class Unloaded\n def run\n end\n end\nend\n",
+ "spec/client_spec.rb": "require 'mygem'\n\ndescribe 'client' do\nend\n",
+}
+
+
+def _stamped(flags: dict[str, str]) -> set[str]:
+ return {node for node, root in flags.items() if root}
+
+
+def test_a_gems_entry_and_what_it_requires_are_public_api(tmp_path: Path) -> None:
+ flags = build_files(tmp_path, _RUBY_GEM)
+ assert _stamped(flags) == {
+ "lib/mygem.rb::Mygem",
+ "lib/mygem.rb::Mygem::new",
+ "lib/mygem/client.rb::Mygem",
+ "lib/mygem/client.rb::Mygem::Client",
+ "lib/mygem/client.rb::Client::get",
+ }
+ # The file that exports a symbol is the file that declares it.
+ assert flags["lib/mygem/client.rb::Client::get"] == "lib/mygem/client.rb"
+ # A method below a bare ``private``, a file nothing requires and a spec stay out.
+ for node in (
+ "lib/mygem/client.rb::Client::retry_once",
+ "lib/mygem/unloaded.rb::Mygem",
+ "lib/mygem/unloaded.rb::Mygem::Unloaded",
+ "lib/mygem/unloaded.rb::Unloaded::run",
+ ):
+ assert flags[node] == "", node
+ assert not [node for node in flags if node.startswith("spec/") and flags[node]]
+
+
+def test_a_dashed_gem_name_reads_as_path_separators(tmp_path: Path) -> None:
+ flags = build_files(
+ tmp_path,
+ {
+ "rack-protection.gemspec": _GEMSPEC.format(name="rack-protection"),
+ "lib/rack/protection.rb": (
+ "module Rack\n module Protection\n def self.new\n end\n end\nend\n"
+ ),
+ },
+ )
+ assert flags["lib/rack/protection.rb::Rack"] == "lib/rack/protection.rb"
+ assert flags["lib/rack/protection.rb::Rack::Protection"] == "lib/rack/protection.rb"
+ assert flags["lib/rack/protection.rb::Protection::new"] == "lib/rack/protection.rb"
+
+
+def test_a_lib_without_a_gemspec_stamps_nothing(tmp_path: Path) -> None:
+ files = {rel: body for rel, body in _RUBY_GEM.items() if not rel.endswith(".gemspec")}
+ flags = build_files(tmp_path, files)
+ assert flags and not _stamped(flags)
+
+
+def test_a_gem_whose_entry_file_is_absent_stamps_nothing(tmp_path: Path) -> None:
+ files = {rel: body for rel, body in _RUBY_GEM.items() if rel != "lib/mygem.rb"}
+ assert not _stamped(build_files(tmp_path, files))
+
+
+def test_the_gem_name_is_read_from_specification_new_or_the_file(tmp_path: Path) -> None:
+ flags = build_files(
+ tmp_path,
+ {
+ "one/one.gemspec": "Gem::Specification.new 'one', '1.0' do |s|\nend\n",
+ "one/lib/one.rb": "module One\nend\n",
+ # A name that is not a literal falls back to the gemspec's file name.
+ "two/two.gemspec": "Gem::Specification.new do |s|\n s.name = Two::NAME\nend\n",
+ "two/lib/two.rb": "module Two\nend\n",
+ },
+ )
+ assert flags["one/lib/one.rb::One"] == "one/lib/one.rb"
+ assert flags["two/lib/two.rb::Two"] == "two/lib/two.rb"
+
+
+def test_a_gems_requires_are_followed_transitively_inside_its_own_lib(tmp_path: Path) -> None:
+ flags = build_files(
+ tmp_path,
+ {
+ "a/a.gemspec": _GEMSPEC.format(name="a"),
+ "a/lib/a.rb": "require_relative 'a/one'\nmodule A\nend\n",
+ "a/lib/a/one.rb": "require 'a/two'\nmodule A\n class One\n end\nend\n",
+ "a/lib/a/two.rb": "require 'b'\nmodule A\n class Two\n end\nend\n",
+ # Another gem's lib, reached by a require, is not this gem's surface.
+ "b/b.gemspec": _GEMSPEC.format(name="b-extra"),
+ "b/lib/b.rb": "module B\n class Helper\n end\nend\n",
+ },
+ )
+ assert flags["a/lib/a/one.rb::A::One"] == "a/lib/a/one.rb"
+ assert flags["a/lib/a/two.rb::A::Two"] == "a/lib/a/two.rb"
+ assert flags["b/lib/b.rb::B::Helper"] == ""
+
+
+def test_members_of_deeply_nested_ruby_modules_are_public_api(tmp_path: Path) -> None:
+ flags = build_files(
+ tmp_path,
+ {
+ "deep.gemspec": _GEMSPEC.format(name="deep"),
+ "lib/deep.rb": (
+ "module Deep\n module Http\n class Conn\n def run\n end\n\n"
+ " class Inner\n def go\n end\n end\n"
+ " end\n end\nend\n"
+ ),
+ },
+ )
+ assert _stamped(flags) == {
+ "lib/deep.rb::Deep",
+ "lib/deep.rb::Deep::Http",
+ "lib/deep.rb::Http::Conn",
+ "lib/deep.rb::Conn::run",
+ "lib/deep.rb::Conn::Inner",
+ "lib/deep.rb::Inner::go",
+ }
+
+
+def test_ruby_methods_made_private_after_their_definition_are_not_public_api(
+ tmp_path: Path,
+) -> None:
+ flags = build_files(
+ tmp_path,
+ {
+ "vis.gemspec": _GEMSPEC.format(name="vis"),
+ "lib/vis.rb": (
+ "module Vis\n class Box\n def open\n end\n\n def hidden\n end\n"
+ " private :hidden\n\n protected\n\n def guarded\n end\n"
+ " public\n\n def back\n end\n\n"
+ " private def wrapped\n end\n end\nend\n"
+ ),
+ },
+ )
+ assert {n for n in _stamped(flags) if "::Box::" in n} == {
+ "lib/vis.rb::Box::open",
+ "lib/vis.rb::Box::back",
+ }
diff --git a/tests/unit/health/test_plan_annotations.py b/tests/unit/health/test_plan_annotations.py
index 42f3b1d93..7ba92c32d 100644
--- a/tests/unit/health/test_plan_annotations.py
+++ b/tests/unit/health/test_plan_annotations.py
@@ -265,6 +265,21 @@ def test_changing_an_exported_symbol_warns_about_outside_callers() -> None:
assert not annotate_any(plan(file_path="svc/other.py", target_symbol="handle"), facts)
+def test_changing_an_exported_ruby_symbol_warns_about_outside_callers() -> None:
+ exported = {
+ "lib/mygem/client.rb": {"lib/mygem/client.rb::Client::get": "lib/mygem/client.rb"}
+ }
+ facts = AnnotationFacts(exported=exported)
+ notes = annotate(plan(file_path="lib/mygem/client.rb", target_symbol="Client.get"), facts)
+ assert notes.risks == (
+ PlanRisk(
+ "public_api",
+ "`Client.get` is exported from `lib/mygem/client.rb`; changing its signature "
+ "breaks consumers outside the repo.",
+ ),
+ )
+
+
def test_changing_an_exported_jvm_symbol_warns_about_outside_callers() -> None:
exported = {
"lib/src/main/java/a/Api.java": {
diff --git a/tests/unit/ingestion/parser/test_ruby_visibility.py b/tests/unit/ingestion/parser/test_ruby_visibility.py
new file mode 100644
index 000000000..36c5c5603
--- /dev/null
+++ b/tests/unit/ingestion/parser/test_ruby_visibility.py
@@ -0,0 +1,66 @@
+"""Ruby method visibility: ``private`` and ``protected`` are calls in the class body."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.ingestion.parser import ASTParser
+from tests.unit.ingestion.parser._helpers import _make_file_info
+
+
+def _visibility(parser: ASTParser, body: str) -> dict[str, str]:
+ result = parser.parse_file(_make_file_info("lib/box.rb", "ruby"), body.encode())
+ return {s.name: s.visibility for s in result.symbols if s.kind in ("method", "function")}
+
+
+ ("body", "expected"),
+ [
+ # A bare keyword sets the access of every def after it.
+ (
+ "class Box\n def a; end\n private\n def b; end\nend\n",
+ {"a": "public", "b": "private"},
+ ),
+ (
+ "class Box\n protected\n def a; end\n public\n def b; end\nend\n",
+ {"a": "protected", "b": "public"},
+ ),
+ # A call naming the method wins, whichever side of the def it sits on.
+ (
+ "class Box\n def a; end\n def b; end\n private :a\nend\n",
+ {"a": "private", "b": "public"},
+ ),
+ (
+ "class Box\n private\n def a; end\n public :a\nend\n",
+ {"a": "public"},
+ ),
+ ("class Box\n def a; end\n private 'a'\nend\n", {"a": "private"}),
+ # ``private def x`` covers that def only.
+ (
+ "class Box\n private def a; end\n def b; end\nend\n",
+ {"a": "private", "b": "public"},
+ ),
+ # A nested class starts public again.
+ (
+ "class Box\n private\n class Inner\n def a; end\n end\nend\n",
+ {"a": "public"},
+ ),
+ # ``def self.x`` ignores a bare ``private``; ``private_class_method`` is its own.
+ (
+ "class Box\n private\n def self.a; end\n def self.b; end\n"
+ " private_class_method :b\nend\n",
+ {"a": "public", "b": "private"},
+ ),
+ # ``class << self`` has a scope of its own.
+ (
+ "class Box\n class << self\n private\n def a; end\n end\n def b; end\nend\n",
+ {"a": "private", "b": "public"},
+ ),
+ # A def outside a class or module body is not touched.
+ ("def a; end\n", {"a": "public"}),
+ ],
+)
+def test_ruby_access_comes_from_the_class_body(
+ parser: ASTParser, body: str, expected: dict[str, str]
+) -> None:
+ assert _visibility(parser, body) == expected