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(languages): parse shell to AST (functions, source edges, complexity) (#768)

Raghav Chamadiya72f242839714
diff --git a/README.md b/README.md
index 41956f75a..943fd8b50 100644
--- a/README.md
+++ b/README.md
@@ -363,7 +363,8 @@ Install from the Marketplace (search **Repowise**) or Open VSX, then run
| **Full** | Python · TypeScript · JavaScript · Java · Kotlin · Go · Rust · C++ · C# · Scala · Ruby | AST parsing, import resolution, named bindings, call resolution, heritage extraction, docstrings; multi-project workspace resolvers; framework-aware edges; per-language dynamic-hint extractors; **code-health markers** |
| **Good** | C · Swift · PHP · Dart | AST parsing, import resolution, named bindings, call resolution, heritage (mixins / derive / extensions / traits), docstrings; dedicated workspace-aware resolvers; Laravel / TYPO3 / Flutter framework edges; dynamic-hint extractors; Dart adds code-health + perf markers |
| **SQL / dbt** | `.sql` via sqlglot (postgres, mysql, tsql, clickhouse, ...) | Tables / views / functions / procedures as symbols with wiki pages; dbt projects get real `ref()` / `source()` lineage edges: model-level DAG, hotspots, co-change, ownership |
-| **Config / data** | OpenAPI · Protobuf · GraphQL · Dockerfile · Makefile · YAML · JSON · TOML · Terraform · Markdown · Shell | Included in the file tree; special handlers extract endpoints / targets where applicable |
+| **Shell** | `.sh` · `.bash` · `.zsh` | Functions as symbols, `source` / `.` import edges (`$SCRIPT_DIR` / `dirname` idioms), and function-level code-health complexity. No class metrics, heritage, or dead-code flagging |
+| **Config / data** | OpenAPI · Protobuf · GraphQL · Dockerfile · Makefile · YAML · JSON · TOML · Terraform · Markdown | Included in the file tree; special handlers extract endpoints / targets where applicable |
| **Git-blame only** | Objective-C · Elixir · Erlang · Zig · Julia · Clojure · Haskell · OCaml · F# · … | Tracked in git history (blame, hotspots, co-change); no AST parsing yet |
Adding a language needs **one `.scm` query file and one config entry**, with no
diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.md
index c552d53f1..465547cdc 100644
--- a/docs/LANGUAGE_SUPPORT.md
+++ b/docs/LANGUAGE_SUPPORT.md
@@ -1,6 +1,6 @@
# Language Support
-repowise parses **15 languages to a full AST**, resolves imports and call
+repowise parses **16 languages to a full AST**, resolves imports and call
graphs across them, and scores **11 at the Full tier** with code-health markers.
Everything else in your repo is still tracked through git history and appears in
the wiki. This page is the "what works for my language today" reference.
@@ -22,7 +22,8 @@ produce meaningful output.
| **Full** | Python · TypeScript · JavaScript · Java · Kotlin · Go · Rust · C++ · C# · Scala · Ruby | AST parsing, import resolution, named bindings, call resolution, heritage, docstrings, framework-aware edges, dynamic-hint extractors, and **code-health markers** |
| **Good** | C · Swift · PHP · Dart | Everything above except code-health markers (C, Swift, PHP; Dart *does* get health markers). Dedicated workspace resolvers and framework edges per language |
| **SQL / dbt** | `.sql` via sqlglot | Tables / views / functions / procedures as symbols with wiki pages; dbt projects get real `ref()` / `source()` lineage |
-| **Config / data** | OpenAPI · Protobuf · GraphQL · Dockerfile · Makefile · YAML · JSON · TOML · Terraform · Markdown · Shell | In the file tree and wiki; special handlers extract endpoints / targets where applicable |
+| **Shell** | `.sh` `.bash` `.zsh` | Function definitions as symbols, `source` / `.` import edges (incl. `$SCRIPT_DIR` / `dirname` / `$BATS_ROOT` idioms), and function-level code-health complexity (CCN, nesting, cognitive). No class metrics, heritage, bindings, or dead-code flagging |
+| **Config / data** | OpenAPI · Protobuf · GraphQL · Dockerfile · Makefile · YAML · JSON · TOML · Terraform · Markdown | In the file tree and wiki; special handlers extract endpoints / targets where applicable |
| **Lightweight** | Elixir · Clojure · Haskell · Lean 4 · Erlang · F# | Regex-tier file-level import graph (no symbols/calls). Honest file-to-file dependencies, no symbol-level claims |
| **Partial** | Luau / Roblox | AST symbols + `require()` resolution (Rojo / `.luaurc` aware); no health markers yet |
| **Structural** | Objective-C · R · Zig · Julia · Elm · OCaml · Crystal · Nim · D | Git history only (blame, hotspots, co-change). No AST parsing |
@@ -150,6 +151,20 @@ instance paths (including `:WaitForChild` idioms), absolute Roblox paths via
Rojo's `default.project.json`, and `@alias` requires via `.luaurc`. No health
markers yet.
+**Shell** (`.sh` / `.bash` / `.zsh`), function definitions (both `foo()` and
+`function foo` forms) become symbols, `source` / `.` statements become import
+edges, and calls to functions defined in the same or a sourced file resolve to
+call edges (external binaries like `grep` mint no edge). Import resolution
+covers literal relative paths plus the common directory-anchor idioms
+(`$SCRIPT_DIR/x.sh`, `$(dirname "$0")/x.sh`, `${BASH_SOURCE%/*}/x.sh`) and
+project-root anchors (`$BATS_ROOT/$LIBDIR/lib/x.sh`) via a unique path-suffix
+match; genuinely dynamic paths (`source "$1"`) stay external. Shell also gets
+**function-level complexity** markers (CCN / nesting / cognitive, with `&&` /
+`||` command lists counted). tree-sitter-bash parses the bash/POSIX subset, so
+zsh mostly works and fish does not; any parse error degrades that file to
+passthrough. No class metrics, heritage, bindings, or dead-code flagging (shell
+scripts are invoked by name, so static reachability is meaningless).
+
**Structural** (Objective-C, R, Zig, Julia, Elm, OCaml, Crystal, Nim, D) -
tracked in git history (blame, hotspots, co-change) but no AST parsing. Files
appear in the wiki as traversal-level entries, and the knowledge graph runs in
@@ -178,6 +193,7 @@ is "Full" vs "Good".
| Dart | ✅ | n/a³ | ✅ | later | ✅ |
| Scala | ✅ | ✅ | ✅⁴ | later | ✅⁵ |
| Ruby | ✅ | ✅⁶ | ✅⁷ | later | ✅⁸ |
+| Shell | ✅⁹ | n/a | n/a | n/a | n/a |
¹ Go methods attach to a type via an external receiver rather than nesting in a
class body, so class-level metrics aren't computable; Go gets the function- and
@@ -216,6 +232,11 @@ keeps in-memory `Registry.find(name)` lookups silent. Backticks / `system` /
`Open3` are subprocess sinks; `s += "…"` in a loop is flagged while `s << x`
(amortized append) never is.
+⁹ Shell gets function-level complexity only (CCN / nesting / cognitive / NLOC).
+`&&` / `||` command lists count toward CCN (`cmd || exit 1` is +1), which is
+honest: shell branching is chained command lists. There are no classes,
+assertions, dataflow, or perf dialect for shell.
+
The **performance** signal (`io_in_loop`, `string_concat_in_loop`,
`resource_construction_in_loop`, language-specific markers like Go
`defer_in_loop` and C# sync-over-async) and the **dataflow** layer (powering
@@ -237,6 +258,7 @@ where a dialect isn't wired yet. Per-marker mechanics and precision hazards:
| Elixir | Good | Lightweight tier shipped; AST upgrade planned (`tree-sitter-elixir` available) |
| F# | Good | Lightweight tier shipped; AST upgrade planned (`tree-sitter-f-sharp` available) |
| SQL / dbt | - | DDL symbols, dbt lineage, app-to-database contracts, health markers shipped. Next: column-level blast radius |
+| Shell | - | Function symbols, `source` import edges, function-level complexity shipped. Next: shebang-based detection of extensionless executables (a traverser capability) |
---
diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.py
index fe5c768af..5df6995c6 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -20,6 +20,13 @@ _NON_CODE_LANGUAGES: frozenset[str] = frozenset(
# Patterns that should never be flagged as dead.
_NEVER_FLAG_PATTERNS: tuple[str, ...] = (
+ # Shell scripts are invoked by name from CI configs, Makefiles, and humans
+ # — static reachability is meaningless, so they are never flagged as dead.
+ # (Shell parses to a real AST now, so it left the passthrough-derived
+ # ``_NON_CODE_LANGUAGES`` exemption below; these globs restore it.)
+ "*.sh",
+ "*.bash",
+ "*.zsh",
"*__init__.py",
"*__main__.py",
"*conftest.py",
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
index 38c663139..613d592ec 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -664,6 +664,34 @@ _RUBY = LanguageNodeMap(
)
+_SHELL = LanguageNodeMap(
+ # Both `foo() {}` and `function foo {}` parse as function_definition; its
+ # body is a sibling `compound_statement` the shared walker measures.
+ function_kinds=frozenset({"function_definition"}),
+ # Shell has no anonymous-function literal.
+ lambda_kinds=frozenset(),
+ # `elif` is its own clause (a branch); `else_clause` is not a decision.
+ branch_kinds=frozenset({"if_statement", "elif_clause"}),
+ # `until ...` parses as `while_statement` in tree-sitter-bash, so it is
+ # covered here; `for ((;;))` is `c_style_for_statement`.
+ loop_kinds=frozenset(
+ {"for_statement", "c_style_for_statement", "while_statement"}
+ ),
+ # No exceptions in shell (`trap` is not `try`).
+ try_kinds=frozenset(),
+ catch_kinds=frozenset(),
+ switch_kinds=frozenset({"case_statement"}),
+ case_kinds=frozenset({"case_item"}),
+ boolean_operator_kinds=frozenset(),
+ # `cmd && other` / `cmd || exit 1` parse as a `list` node carrying the
+ # operator as a direct `&&` / `||` token — the walker sniffs that token.
+ # This counts the guard idiom (`cmd || exit 1`) as +1 CCN, which is honest:
+ # shell branching IS chained command lists.
+ boolean_operator_text_kinds=frozenset({"list"}),
+ # No classes, no assertions, no perf/dataflow dialect for shell.
+)
+
+
LANGUAGE_MAPS: dict[str, LanguageNodeMap] = {
"python": _PY,
"typescript": _TS,
@@ -679,6 +707,7 @@ LANGUAGE_MAPS: dict[str, LanguageNodeMap] = {
"dart": _DART,
"scala": _SCALA,
"ruby": _RUBY,
+ "shell": _SHELL,
}
diff --git a/packages/core/src/repowise/core/ingestion/language_configs.py b/packages/core/src/repowise/core/ingestion/language_configs.py
index 05758f224..6b8d8c436 100644
--- a/packages/core/src/repowise/core/ingestion/language_configs.py
+++ b/packages/core/src/repowise/core/ingestion/language_configs.py
@@ -355,4 +355,16 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
parent_extraction="none",
parent_class_types=frozenset(),
),
+ "shell": LanguageConfig(
+ # Both `foo() {}` and `function foo {}` parse as function_definition.
+ # Shell has no classes, so no parent tracking.
+ symbol_node_types={
+ "function_definition": "function",
+ },
+ import_node_types=["command"], # `source` / `.` — see queries/shell.scm
+ export_node_types=[],
+ visibility_fn=public_by_default,
+ parent_extraction="none",
+ parent_class_types=frozenset(),
+ ),
}
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/shell.py b/packages/core/src/repowise/core/ingestion/languages/specs/shell.py
index a6bc6a07c..a9170c534 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/shell.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/shell.py
@@ -2,12 +2,71 @@
from ..spec import LanguageSpec
+# Shell builtins and no-op keywords that show up as `command` invocations but
+# are never user-defined functions — suppressed as call targets so the graph
+# only records edges to real functions (defined here or in a sourced file).
+_SHELL_BUILTINS = frozenset(
+ {
+ ".",
+ ":",
+ "[",
+ "[[",
+ "alias",
+ "bg",
+ "break",
+ "builtin",
+ "cd",
+ "command",
+ "continue",
+ "declare",
+ "echo",
+ "eval",
+ "exec",
+ "exit",
+ "export",
+ "false",
+ "fg",
+ "getopts",
+ "hash",
+ "let",
+ "local",
+ "logout",
+ "printf",
+ "pushd",
+ "popd",
+ "pwd",
+ "read",
+ "readonly",
+ "return",
+ "set",
+ "shift",
+ "shopt",
+ "source",
+ "test",
+ "trap",
+ "true",
+ "type",
+ "typeset",
+ "ulimit",
+ "umask",
+ "unalias",
+ "unset",
+ "wait",
+ }
+)
+
SPEC = LanguageSpec(
tag="shell",
display_name="Shell",
extensions=frozenset({".sh", ".bash", ".zsh"}),
+ # Shell is code *and* infra: files still promote to CI/infra presentation
+ # by name/path (see registry.non_infra_code_extensions), but they now get a
+ # real AST (functions, source edges, function-level complexity).
is_infra=True,
- is_passthrough=True,
- shebang_tokens=("bash", " sh"),
+ import_support="partial",
+ grammar_package="tree_sitter_bash",
+ scm_file="shell.scm",
+ shebang_tokens=("bash", " sh", "zsh"),
+ builtin_calls=_SHELL_BUILTINS,
color_hex="#89E051",
)
diff --git a/packages/core/src/repowise/core/ingestion/queries/shell.scm b/packages/core/src/repowise/core/ingestion/queries/shell.scm
new file mode 100644
index 000000000..14096f293
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/queries/shell.scm
@@ -0,0 +1,44 @@
+; =============================================================================
+; repowise — Shell (bash/sh/zsh) symbol, import, and call queries
+; tree-sitter-bash (install separately if needed)
+;
+; Scope is deliberately small: function definitions as symbols, `source` / `.`
+; as import edges, and command invocations as call targets. External binaries
+; (grep, awk, …) are captured as call targets too, but resolve to nothing when
+; no matching function symbol exists — the three-tier call resolver drops them.
+;
+; tree-sitter-bash represents both function forms with `function_definition`
+; carrying a `name:` field:
+; foo() { ... }
+; function foo { ... }
+; =============================================================================
+
+; ---------------------------------------------------------------------------
+; Symbols — function definitions (both `foo()` and `function foo` forms).
+; ---------------------------------------------------------------------------
+(function_definition
+ name: (word) @symbol.name
+) @symbol.def
+
+; ---------------------------------------------------------------------------
+; Imports — `source <file>` and `. <file>`.
+;
+; The argument is captured as raw text (a string, word, or concatenation); the
+; parser strips surrounding quotes before handing it to resolvers/shell.py,
+; which resolves the common `$SCRIPT_DIR/x.sh` / `$(dirname "$0")/x.sh` idioms
+; against the sourcing file's directory.
+; ---------------------------------------------------------------------------
+(command
+ name: (command_name) @_src_cmd
+ argument: (_) @import.module
+ (#match? @_src_cmd "^(source|\\.)$")
+) @import.statement
+
+; ---------------------------------------------------------------------------
+; Calls — every command invocation's name. Only resolves for calls to
+; functions defined in the same file or a sourced file; builtins are filtered
+; via `builtin_calls` on the spec, external binaries drop during resolution.
+; ---------------------------------------------------------------------------
+(command
+ name: (command_name) @call.target
+) @call.site
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py b/packages/core/src/repowise/core/ingestion/resolvers/__init__.py
index 6c47deaa5..7b49a774b 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/__init__.py
@@ -24,6 +24,7 @@ from .python import resolve_python_import
from .ruby import resolve_ruby_import
from .rust import resolve_rust_import
from .scala import resolve_scala_import
+from .shell import resolve_shell_import
from .sql import resolve_dbt_import
from .swift import resolve_swift_import
from .typescript import resolve_ts_js_import
@@ -46,6 +47,8 @@ _RESOLVERS: dict[str, ResolverFn] = {
"swift": resolve_swift_import,
"scala": resolve_scala_import,
"php": resolve_php_import,
+ # source ./lib.sh + the $SCRIPT_DIR/$(dirname "$0") idioms.
+ "shell": resolve_shell_import,
# Lightweight regex-tier resolvers (import_support="partial")
"elixir": resolve_elixir_import,
"dart": resolve_dart_import,
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/shell.py b/packages/core/src/repowise/core/ingestion/resolvers/shell.py
new file mode 100644
index 000000000..5a08e565b
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/shell.py
@@ -0,0 +1,132 @@
+"""Shell ``source`` / ``.`` import resolution.
+
+A sourced path reaches this resolver after the parser has stripped the
+surrounding quotes (see ``resolvers/luau.py`` for the same contract), so
+``source "$SCRIPT_DIR/lib/util.sh"`` arrives as ``$SCRIPT_DIR/lib/util.sh``.
+
+Handled forms:
+
+1. Literal relative path — ``./lib/util.sh``, ``lib/util.sh``, ``../x.sh`` —
+ resolved against the *sourcing* file's directory.
+2. Script-directory idioms — a leading variable/command-substitution segment
+ that evaluates to the script's own directory is stripped and the remainder
+ resolved relatively::
+
+ $SCRIPT_DIR/x.sh
+ $(dirname "$0")/x.sh
+ ${BASH_SOURCE%/*}/x.sh
+ `dirname "$0"`/x.sh
+
+3. Project-root idioms — one or more leading variable segments that point at a
+ project root rather than the script's dir::
+
+ $BATS_ROOT/$BATS_LIBDIR/bats-core/warnings.bash
+
+ After stripping every leading variable segment, the literal tail
+ (``bats-core/warnings.bash``) is matched against repo paths by *unique*
+ multi-segment suffix. The uniqueness + multi-segment guards keep this
+ precise — a bare ``$X/common.sh`` (single-segment tail) is never linked.
+4. Anything still carrying interpolation, an absolute system path, or a
+ ``~`` home path is recorded as an external node so the reference still
+ appears in the graph, never silently matched.
+
+Unresolved literals are *not* guessed by bare filename — a wrong source edge is
+worse than no edge for a graph that feeds docs and dead-code detection.
+"""
+
+from __future__ import annotations
+
+import posixpath
+import re
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+_SHELL_SUFFIXES: tuple[str, ...] = (".sh", ".bash", ".zsh")
+
+# A single leading directory-anchor segment: ``${...}``, ``$(...)``,
+# `` `...` ``, or ``$NAME`` — the part that evaluates to a directory in the
+# idioms above. Matched only at the very start of the path.
+_DIR_ANCHOR = re.compile(r"^(?:\$\{[^}]*\}|\$\([^)]*\)|`[^`]*`|\$\w+)/")
+
+# Any remaining shell interpolation after prefix-stripping — such a path can't
+# be resolved statically.
+_DYNAMIC = re.compile(r"[$`]")
+
+
+def resolve_shell_import(
+ module_path: str,
+ importer_path: str,
+ ctx: ResolverContext,
+) -> str | None:
+ """Resolve a ``source``/``.`` argument to a repo-relative file path."""
+ raw = module_path.strip()
+ if not raw:
+ return None
+
+ # Strip every leading directory-anchor segment ($SCRIPT_DIR/, $(dirname
+ # "$0")/, ${BASH_SOURCE%/*}/, and multi-var $BATS_ROOT/$LIBDIR/…).
+ tail = raw
+ stripped = 0
+ while True:
+ shorter = _DIR_ANCHOR.sub("", tail, count=1)
+ if shorter == tail:
+ break
+ tail = shorter
+ stripped += 1
+
+ # Interior interpolation, a home path, or an absolute system path — none
+ # resolvable to a repo file.
+ if _DYNAMIC.search(tail) or tail.startswith(("~", "/")):
+ return ctx.add_external_node(raw)
+
+ importer_dir = posixpath.dirname(importer_path)
+
+ # Literal-relative (no anchor) or the script-dir idiom (anchor == the
+ # sourcing file's own directory): resolve the tail relative to the importer.
+ resolved = _resolve_relative(tail, importer_dir, ctx)
+ if resolved is not None:
+ return resolved
+
+ # Project-root idiom: the anchor was not the script's dir, so relative
+ # resolution missed. Fall back to a UNIQUE multi-segment path-suffix match
+ # — a single bare filename is too ambiguous to link safely.
+ if stripped and "/" in tail:
+ match = _unique_suffix_match(tail, ctx)
+ if match is not None:
+ return match
+
+ return ctx.add_external_node(raw)
+
+
+def _candidate_paths(tail: str) -> tuple[str, ...]:
+ """The tail plus shell-suffixed variants when the extension is omitted."""
+ if any(tail.endswith(s) for s in _SHELL_SUFFIXES):
+ return (tail,)
+ return (tail, *(f"{tail}{s}" for s in _SHELL_SUFFIXES))
+
+
+def _resolve_relative(tail: str, importer_dir: str, ctx: ResolverContext) -> str | None:
+ """Resolve *tail* against the importing file's directory."""
+ for cand in _candidate_paths(tail):
+ resolved = posixpath.normpath(posixpath.join(importer_dir, cand))
+ if resolved in ctx.path_set:
+ return resolved
+ return None
+
+
+def _unique_suffix_match(tail: str, ctx: ResolverContext) -> str | None:
+ """Return the single repo path ending in ``/<tail>`` (or ``tail``), else None.
+
+ Precision guard: only an unambiguous (exactly one) match links. A tie
+ resolves to no edge rather than a guessed one.
+ """
+ for cand in _candidate_paths(tail):
+ needle = f"/{cand}"
+ hits = [p for p in ctx.sorted_paths if p == cand or p.endswith(needle)]
+ if len(hits) == 1:
+ return hits[0]
+ if len(hits) > 1:
+ return None
+ return None
diff --git a/pyproject.toml b/pyproject.toml
index 93b5eb0d3..020fd9c19 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -50,6 +50,7 @@ dependencies = [
"tree-sitter-scala>=0.23,<1",
"tree-sitter-php>=0.23,<1",
"tree-sitter-luau>=1.2,<2",
+ "tree-sitter-bash>=0.23,<1",
# SQL parsing (multi-dialect, error-tolerant, pure Python)
"sqlglot>=26,<28",
# Dependency graph
diff --git a/tests/fixtures/lang_samples/shell/control_flow.sh b/tests/fixtures/lang_samples/shell/control_flow.sh
new file mode 100644
index 000000000..58c7a0079
--- /dev/null
+++ b/tests/fixtures/lang_samples/shell/control_flow.sh
@@ -0,0 +1,40 @@
+#!/usr/bin/env bash
+# A control-flow-heavy function for the complexity walker: if/elif, for,
+# c-style for, while, until, case, and && / || command lists.
+
+process() {
+ local mode="$1"
+ if [[ -z "$mode" ]]; then
+ echo "no mode" || exit 1
+ elif [[ "$mode" == "fast" ]]; then
+ echo "fast"
+ else
+ echo "slow"
+ fi
+
+ for f in *.txt; do
+ cat "$f" && echo "ok"
+ done
+
+ for (( i = 0; i < 10; i++ )); do
+ echo "$i"
+ done
+
+ while read -r line; do
+ echo "$line"
+ done < input.txt
+
+ until check_done; do
+ step
+ done
+
+ case "$mode" in
+ fast) echo A ;;
+ slow) echo B ;;
+ *) echo C ;;
+ esac
+}
+
+trivial() {
+ echo "nothing to see"
+}
diff --git a/tests/fixtures/lang_samples/shell/functions.sh b/tests/fixtures/lang_samples/shell/functions.sh
new file mode 100644
index 000000000..e1a08a405
--- /dev/null
+++ b/tests/fixtures/lang_samples/shell/functions.sh
@@ -0,0 +1,16 @@
+#!/usr/bin/env bash
+# Both function definition forms plus a nested call.
+
+greet() {
+ local name="$1"
+ echo "hello $name"
+}
+
+function deploy {
+ greet "world"
+ build_step
+}
+
+build_step() {
+ echo "building"
+}
diff --git a/tests/fixtures/lang_samples/shell/sourcing.sh b/tests/fixtures/lang_samples/shell/sourcing.sh
new file mode 100644
index 000000000..b476a244e
--- /dev/null
+++ b/tests/fixtures/lang_samples/shell/sourcing.sh
@@ -0,0 +1,15 @@
+#!/usr/bin/env bash
+# Source chains: literal relative + the $SCRIPT_DIR / dirname idioms.
+
+SCRIPT_DIR="$(dirname "$0")"
+
+source "$SCRIPT_DIR/lib/util.sh"
+. ./helpers.sh
+source "${BASH_SOURCE%/*}/lib/log.sh"
+
+main() {
+ util_init
+ helper_run
+}
+
+main "$@"
diff --git a/tests/fixtures/lang_samples/shell/zero_functions.sh b/tests/fixtures/lang_samples/shell/zero_functions.sh
new file mode 100644
index 000000000..fcd17a649
--- /dev/null
+++ b/tests/fixtures/lang_samples/shell/zero_functions.sh
@@ -0,0 +1,8 @@
+#!/bin/sh
+# A script with no function definitions — must not crash the walker.
+
+echo "starting"
+for f in *.log; do
+ rm -f "$f"
+done
+echo "done"
diff --git a/tests/fixtures/lang_samples/shell/zshisms.zsh b/tests/fixtures/lang_samples/shell/zshisms.zsh
new file mode 100644
index 000000000..1c182edc2
--- /dev/null
+++ b/tests/fixtures/lang_samples/shell/zshisms.zsh
@@ -0,0 +1,13 @@
+#!/usr/bin/env zsh
+# Mild zsh-isms: tree-sitter-bash parses the bash/POSIX subset. A parse error
+# on a zsh-only construct must degrade per-file, never crash — the plain
+# function below must still be extracted.
+
+autoload -Uz compinit
+
+typeset -A colors
+colors[red]="31"
+
+setup() {
+ echo "configured"
+}
diff --git a/tests/unit/health/test_shell_complexity.py b/tests/unit/health/test_shell_complexity.py
new file mode 100644
index 000000000..8faa5de77
--- /dev/null
+++ b/tests/unit/health/test_shell_complexity.py
@@ -0,0 +1,68 @@
+"""Complexity-walker coverage for shell functions.
+
+Shell gets function-level complexity only (no class metrics, no perf/dataflow
+dialect). The novel piece is that ``&&`` / ``||`` command lists count toward
+CCN via the ``list`` boolean-operator-text node.
+"""
+
+from __future__ import annotations
+
+from repowise.core.analysis.health.complexity.walker import walk_file
+
+
+def _ccn(body: str) -> int:
+ src = f"f() {{\n {body}\n}}\n".encode()
+ fc = walk_file("t.sh", "shell", src)
+ assert fc.functions, "expected one function"
+ return fc.functions[0].ccn
+
+
+class TestBooleanLists:
+ def test_no_operators(self) -> None:
+ assert _ccn("echo hi") == 1
+
+ def test_single_or_guard(self) -> None:
+ # `cmd || exit 1` is the guard idiom — one decision point.
+ assert _ccn("run || exit 1") == 2
+
+ def test_and_or_chain(self) -> None:
+ assert _ccn("a && b || c") == 3
+
+
+class TestControlFlow:
+ def test_if_elif(self) -> None:
+ assert _ccn("if [[ $x ]]; then echo a; elif [[ $y ]]; then echo b; fi") == 3
+
+ def test_for_loop(self) -> None:
+ assert _ccn("for f in *.txt; do echo $f; done") == 2
+
+ def test_c_style_for(self) -> None:
+ assert _ccn("for (( i=0; i<3; i++ )); do echo $i; done") == 2
+
+ def test_while_and_until(self) -> None:
+ # `until` parses as while_statement in tree-sitter-bash.
+ assert _ccn("while true; do break; done") == 2
+ assert _ccn("until false; do break; done") == 2
+
+ def test_case_flat_dispatch_counts_once(self) -> None:
+ # A case whose arms are all simple single commands is a "flat" match:
+ # it counts 1 CCN point for the dispatch, not one per arm.
+ assert _ccn("case $x in a) echo A ;; b) echo B ;; esac") == 2
+
+ def test_case_with_nested_branch_is_not_flat(self) -> None:
+ # An arm carrying nested control flow makes the case non-flat, so the
+ # arms and the nested branch each count.
+ nonflat = _ccn("case $x in a) if [[ $y ]]; then echo A; fi ;; b) echo B ;; esac")
+ assert nonflat > 2
+
+
+class TestWalkerRobustness:
+ def test_zero_function_file_does_not_crash(self) -> None:
+ src = b'#!/bin/sh\necho "hi"\nfor f in *.log; do rm "$f"; done\n'
+ fc = walk_file("t.sh", "shell", src)
+ assert fc.functions == []
+
+ def test_both_function_forms_walked(self) -> None:
+ src = b"foo() {\n echo a\n}\nfunction bar {\n echo b\n}\n"
+ fc = walk_file("t.sh", "shell", src)
+ assert {f.name for f in fc.functions} == {"foo", "bar"}
diff --git a/tests/unit/ingestion/test_language_capabilities.py b/tests/unit/ingestion/test_language_capabilities.py
index 4441c257e..47e6fff78 100644
--- a/tests/unit/ingestion/test_language_capabilities.py
+++ b/tests/unit/ingestion/test_language_capabilities.py
@@ -159,6 +159,8 @@ _PARTIAL = {
"fsharp",
# dbt ref()/source() lineage (model-name index gated on dbt_project.yml).
"sql",
+ # source ./lib.sh + $SCRIPT_DIR / dirname idioms.
+ "shell",
}
diff --git a/tests/unit/ingestion/test_shell_extractors.py b/tests/unit/ingestion/test_shell_extractors.py
new file mode 100644
index 000000000..660dfbb71
--- /dev/null
+++ b/tests/unit/ingestion/test_shell_extractors.py
@@ -0,0 +1,122 @@
+"""Unit tests for shell AST extraction: functions, source imports, calls."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import pytest
+
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+_FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "lang_samples" / "shell"
+
+
+def _file(path: str = "scripts/run.sh") -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=f"/tmp/{path}",
+ language="shell",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
[email protected](scope="module")
+def parser() -> ASTParser:
+ return ASTParser()
+
+
+class TestShellSymbols:
+ def test_both_function_forms(self, parser: ASTParser) -> None:
+ src = b"foo() {\n echo a\n}\nfunction bar {\n echo b\n}\n"
+ result = parser.parse_file(_file(), src)
+ names = {s.name for s in result.symbols}
+ assert names == {"foo", "bar"}
+ assert all(s.kind == "function" for s in result.symbols)
+
+ def test_function_with_parens_keyword_form(self, parser: ASTParser) -> None:
+ src = b"function baz() {\n echo hi\n}\n"
+ result = parser.parse_file(_file(), src)
+ assert {s.name for s in result.symbols} == {"baz"}
+
+ def test_zero_functions_no_symbols(self, parser: ASTParser) -> None:
+ src = b'#!/bin/sh\necho "hi"\nfor f in *.log; do rm "$f"; done\n'
+ result = parser.parse_file(_file(), src)
+ assert result.symbols == []
+
+
+class TestShellImports:
+ def test_source_and_dot(self, parser: ASTParser) -> None:
+ src = b'source "./lib/util.sh"\n. ./helpers.sh\n'
+ result = parser.parse_file(_file(), src)
+ modules = [i.module_path for i in result.imports]
+ assert modules == ["./lib/util.sh", "./helpers.sh"]
+
+ def test_script_dir_idiom_captured_raw(self, parser: ASTParser) -> None:
+ src = b'source "$SCRIPT_DIR/lib/util.sh"\n'
+ result = parser.parse_file(_file(), src)
+ assert [i.module_path for i in result.imports] == ["$SCRIPT_DIR/lib/util.sh"]
+
+ def test_plain_command_is_not_an_import(self, parser: ASTParser) -> None:
+ src = b'echo "not an import"\ngrep foo bar\n'
+ result = parser.parse_file(_file(), src)
+ assert result.imports == []
+
+
+class TestShellCalls:
+ def test_user_function_call_captured(self, parser: ASTParser) -> None:
+ src = b'deploy() {\n greet "world"\n}\n'
+ result = parser.parse_file(_file(), src)
+ targets = {c.target_name for c in result.calls}
+ assert "greet" in targets
+
+ def test_builtins_are_suppressed(self, parser: ASTParser) -> None:
+ src = b"run() {\n echo hi\n cd /tmp\n local x=1\n exit 0\n}\n"
+ result = parser.parse_file(_file(), src)
+ targets = {c.target_name for c in result.calls}
+ assert not ({"echo", "cd", "local", "exit"} & targets)
+
+ def test_external_binary_captured_but_resolves_to_nothing(self, parser: ASTParser) -> None:
+ # grep is captured as a call target; it has no matching function
+ # symbol, so the call resolver drops it (verified at the graph level).
+ src = b"scan() {\n grep foo bar\n}\n"
+ result = parser.parse_file(_file(), src)
+ assert "grep" in {c.target_name for c in result.calls}
+
+
+class TestShellFixtures:
+ def _parse(self, parser: ASTParser, name: str):
+ src = (_FIXTURES / name).read_bytes()
+ return parser.parse_file(_file(name), src)
+
+ def test_functions_fixture(self, parser: ASTParser) -> None:
+ result = self._parse(parser, "functions.sh")
+ assert {s.name for s in result.symbols} == {"greet", "deploy", "build_step"}
+
+ def test_sourcing_fixture(self, parser: ASTParser) -> None:
+ result = self._parse(parser, "sourcing.sh")
+ modules = [i.module_path for i in result.imports]
+ assert "./helpers.sh" in modules
+ assert "$SCRIPT_DIR/lib/util.sh" in modules
+ assert "${BASH_SOURCE%/*}/lib/log.sh" in modules
+
+ def test_control_flow_fixture_walks(self, parser: ASTParser) -> None:
+ result = self._parse(parser, "control_flow.sh")
+ assert {"process", "trivial"} <= {s.name for s in result.symbols}
+
+ def test_zero_function_fixture(self, parser: ASTParser) -> None:
+ result = self._parse(parser, "zero_functions.sh")
+ assert result.symbols == []
+
+ def test_zsh_degrades_but_still_extracts(self, parser: ASTParser) -> None:
+ # zsh-only constructs may parse imperfectly; extraction must degrade
+ # per-file (never crash) and still surface the plain function.
+ result = self._parse(parser, "zshisms.zsh")
+ assert "setup" in {s.name for s in result.symbols}
diff --git a/tests/unit/ingestion/test_shell_resolver.py b/tests/unit/ingestion/test_shell_resolver.py
new file mode 100644
index 000000000..953989476
--- /dev/null
+++ b/tests/unit/ingestion/test_shell_resolver.py
@@ -0,0 +1,89 @@
+"""Unit tests for the shell ``source`` / ``.`` import resolver.
+
+Parser contract: ``parser.py`` strips the surrounding quotes from the captured
+``@import.module`` text before the resolver runs, so every input below is
+unquoted — ``source "$SCRIPT_DIR/x.sh"`` reaches the resolver as
+``$SCRIPT_DIR/x.sh``.
+"""
+
+from __future__ import annotations
+
+import networkx as nx
+
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.ingestion.resolvers.shell import resolve_shell_import
+
+
+def _ctx(paths: set[str]) -> ResolverContext:
+ return ResolverContext(path_set=set(paths), stem_map={}, graph=nx.DiGraph())
+
+
+class TestLiteralRelative:
+ def test_dot_slash_sibling(self) -> None:
+ ctx = _ctx({"scripts/helpers.sh", "scripts/run.sh"})
+ assert resolve_shell_import("./helpers.sh", "scripts/run.sh", ctx) == "scripts/helpers.sh"
+
+ def test_subdir(self) -> None:
+ ctx = _ctx({"scripts/lib/util.sh", "scripts/run.sh"})
+ assert resolve_shell_import("lib/util.sh", "scripts/run.sh", ctx) == "scripts/lib/util.sh"
+
+ def test_parent_relative(self) -> None:
+ ctx = _ctx({"a/b/x.sh", "scripts/run.sh"})
+ assert resolve_shell_import("../a/b/x.sh", "scripts/run.sh", ctx) == "a/b/x.sh"
+
+ def test_extension_omitted(self) -> None:
+ # `source lib/util` with no extension — probe the shell suffixes.
+ ctx = _ctx({"scripts/lib/util.sh", "scripts/run.sh"})
+ assert resolve_shell_import("lib/util", "scripts/run.sh", ctx) == "scripts/lib/util.sh"
+
+
+class TestDirAnchorIdioms:
+ def test_script_dir_variable(self) -> None:
+ ctx = _ctx({"scripts/lib/util.sh", "scripts/run.sh"})
+ got = resolve_shell_import("$SCRIPT_DIR/lib/util.sh", "scripts/run.sh", ctx)
+ assert got == "scripts/lib/util.sh"
+
+ def test_dirname_command_substitution(self) -> None:
+ ctx = _ctx({"scripts/helpers.sh", "scripts/run.sh"})
+ got = resolve_shell_import('$(dirname "$0")/helpers.sh', "scripts/run.sh", ctx)
+ assert got == "scripts/helpers.sh"
+
+ def test_bash_source_parameter_expansion(self) -> None:
+ # ${BASH_SOURCE%/*} contains a `/` inside the braces — the resolver
+ # must strip the whole ${...} segment, not split on the first slash.
+ ctx = _ctx({"scripts/lib/log.sh", "scripts/run.sh"})
+ got = resolve_shell_import("${BASH_SOURCE%/*}/lib/log.sh", "scripts/run.sh", ctx)
+ assert got == "scripts/lib/log.sh"
+
+ def test_backtick_dirname(self) -> None:
+ ctx = _ctx({"scripts/lib/util.sh", "scripts/run.sh"})
+ got = resolve_shell_import('`dirname "$0"`/lib/util.sh', "scripts/run.sh", ctx)
+ assert got == "scripts/lib/util.sh"
+
+
+class TestExternalFallback:
+ def test_absolute_path_is_external(self) -> None:
+ ctx = _ctx({"scripts/run.sh"})
+ got = resolve_shell_import("/usr/lib/system.sh", "scripts/run.sh", ctx)
+ assert got == "external:/usr/lib/system.sh"
+
+ def test_remaining_interpolation_is_external(self) -> None:
+ ctx = _ctx({"scripts/run.sh"})
+ got = resolve_shell_import("$ROOT/$SUB/x.sh", "scripts/run.sh", ctx)
+ assert got == "external:$ROOT/$SUB/x.sh"
+
+ def test_unresolved_relative_is_external(self) -> None:
+ # A wrong source edge is worse than none — unmatched literals go
+ # external rather than a stem guess.
+ ctx = _ctx({"scripts/run.sh"})
+ got = resolve_shell_import("./missing.sh", "scripts/run.sh", ctx)
+ assert got == "external:./missing.sh"
+
+ def test_home_relative_is_external(self) -> None:
+ ctx = _ctx({"scripts/run.sh"})
+ got = resolve_shell_import("~/dotfiles/env.sh", "scripts/run.sh", ctx)
+ assert got == "external:~/dotfiles/env.sh"
+
+ def test_empty_returns_none(self) -> None:
+ ctx = _ctx({"scripts/run.sh"})
+ assert resolve_shell_import("", "scripts/run.sh", ctx) is None