auryn-bash 0.1.0__py3-none-any.whl

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.
File without changes
@@ -0,0 +1,195 @@
1
+ """parse_file(path) -> RawFile: the parallelizable phase-1 unit (pure function, no shared
2
+ state -- safe under a ProcessPoolExecutor; only picklable raw_model dataclasses are returned,
3
+ no tree-sitter node crosses the boundary). parse_source(source, path_label) holds the logic and
4
+ takes raw bytes, so a git blob can be parsed without touching disk.
5
+
6
+ Every node type / field name below was confirmed empirically against tree-sitter-bash 0.25.1
7
+ (see the package's grammar probe), not assumed:
8
+
9
+ - top level (`program` children): `comment` (incl. the `#!` shebang), `function_definition`,
10
+ `command` (a simple command), `if_statement`/`for_statement`/`while_statement`/`pipeline`/
11
+ `variable_assignment` (which may nest `command`s / `command_substitution`), etc.
12
+ - `function_definition`: field `name` (a `word`; both `foo() { ... }` and `function foo { ... }`
13
+ spellings expose it) and field `body` (a `compound_statement` `{ ... }`, or a subshell `( ... )`).
14
+ - `command`: field `name` = `command_name`, whose sole child (for a static command) is a `word`;
15
+ a command whose name involves an expansion (`$cmd`) has no plain `word` child -> unnameable.
16
+ - `source`/`.`: a `command` whose command word is `source` or `.`; the include path is the first
17
+ argument child (`word` | `string` | `raw_string` | `concatenation`).
18
+
19
+ Calls are collected by walking a function body for `command` nodes (so a command inside a
20
+ `command_substitution`, pipeline, loop or conditional still counts), but the walk does NOT descend
21
+ into a *nested* `function_definition` -- those inner commands belong to the nested function, which
22
+ is captured as its own RawFunction."""
23
+
24
+ from __future__ import annotations
25
+
26
+ from pathlib import Path
27
+
28
+ from auryn.core.docstrings import leading_comment
29
+ from auryn.ingestors.bash.raw_model import RawCall, RawFile, RawFunction, RawSource
30
+
31
+ # Shell builtins / keywords: a bare call to one of these is never a project function or a real
32
+ # external command, so it gets no CALLS edge (the exact analog of Go's _BUILTIN_FUNCS). `source`
33
+ # and `.` are handled separately (they become IMPORTS, not calls) and are listed here too so they
34
+ # are never mistaken for a command call.
35
+ _BUILTIN_COMMANDS = frozenset(
36
+ {
37
+ "source", ".", ":", "true", "false",
38
+ "echo", "printf", "print", "read", "mapfile", "readarray",
39
+ "cd", "pwd", "pushd", "popd", "dirs",
40
+ "local", "declare", "typeset", "readonly", "export", "unset", "set",
41
+ "shift", "getopts", "return", "exit", "break", "continue",
42
+ "eval", "exec", "trap", "wait", "kill", "jobs", "bg", "fg", "disown",
43
+ "test", "[", "[[", "alias", "unalias", "type", "hash", "help",
44
+ "command", "builtin", "enable", "let", "history", "fc", "bind",
45
+ "caller", "complete", "compgen", "compopt", "logout", "times",
46
+ "ulimit", "umask", "suspend", "shopt", "unalias",
47
+ }
48
+ )
49
+
50
+ # Node types that mark a value/command as dynamic (a name/path we cannot resolve statically).
51
+ _EXPANSION_TYPES = frozenset(
52
+ {"simple_expansion", "expansion", "command_substitution", "arithmetic_expansion", "process_substitution"}
53
+ )
54
+
55
+
56
+ def parse_file(path: str) -> RawFile:
57
+ return parse_source(Path(path).read_bytes(), path)
58
+
59
+
60
+ def parse_source(source: bytes, path_label: str) -> RawFile:
61
+ from auryn.ingestors.bash.grammar import new_parser
62
+
63
+ tree = new_parser().parse(source)
64
+ rf = RawFile(path=path_label)
65
+
66
+ def txt(node) -> str:
67
+ return source[node.start_byte : node.end_byte].decode("utf-8", "replace") if node else ""
68
+
69
+ def lines(node) -> tuple[int, int]:
70
+ return node.start_point[0] + 1, node.end_point[0] + 1
71
+
72
+ def fieldn(node, name):
73
+ return node.child_by_field_name(name) if node is not None else None
74
+
75
+ def has_expansion(node) -> bool:
76
+ stack = [node]
77
+ while stack:
78
+ n = stack.pop()
79
+ if n.type in _EXPANSION_TYPES:
80
+ return True
81
+ stack.extend(n.children)
82
+ return False
83
+
84
+ def command_word(cmd) -> str | None:
85
+ """The static command name of a `command` node -- the single `word` under its
86
+ `command_name` field -- or None when the name is an expansion (`$cmd`) or otherwise not a
87
+ plain word (unnameable, so no CALLS edge, mirroring Go's chained-selector calls)."""
88
+ name_node = fieldn(cmd, "name")
89
+ if name_node is None or name_node.type != "command_name":
90
+ return None
91
+ words = [c for c in name_node.children if c.type == "word"]
92
+ if len(name_node.named_children) != 1 or len(words) != 1:
93
+ return None
94
+ return txt(words[0])
95
+
96
+ def first_argument(cmd):
97
+ """The first argument node of a `command` (the child after its `command_name`, skipping
98
+ any leading variable assignments/redirects), or None. Compared by node *type*, not object
99
+ identity: tree-sitter's Python bindings hand out fresh Node wrappers per access, so `is`
100
+ against a field lookup never matches."""
101
+ seen_name = False
102
+ for c in cmd.children:
103
+ if c.type == "command_name":
104
+ seen_name = True
105
+ continue
106
+ if not seen_name:
107
+ continue
108
+ if c.type in ("word", "string", "raw_string", "concatenation", "expansion", "simple_expansion"):
109
+ return c
110
+ return None
111
+
112
+ # -- calls ------------------------------------------------------------------------------
113
+
114
+ def collect_calls(body) -> list[RawCall]:
115
+ """Command invocations inside a function body (deduped by name). Walks the whole subtree
116
+ so calls nested in pipelines/conditionals/loops/command-substitutions are captured, but
117
+ stops at a nested `function_definition` (its calls belong to it, not the enclosing func)."""
118
+ calls: list[RawCall] = []
119
+ seen: set[str] = set()
120
+ if body is None:
121
+ return calls
122
+ stack = [(body, True)]
123
+ while stack:
124
+ n, is_root = stack.pop()
125
+ if not is_root and n.type == "function_definition":
126
+ continue # nested function's body belongs to the nested function
127
+ if n.type == "command":
128
+ name = command_word(n)
129
+ if name and name not in _BUILTIN_COMMANDS and name not in seen:
130
+ seen.add(name)
131
+ ls, _ = lines(n)
132
+ calls.append(RawCall(name=name, line_start=ls))
133
+ for c in n.children:
134
+ stack.append((c, False))
135
+ return calls
136
+
137
+ def build_function(node) -> RawFunction:
138
+ name_node = fieldn(node, "name")
139
+ body = fieldn(node, "body")
140
+ ls, le = lines(node)
141
+ doc = _strip_shebang(leading_comment(node, source))
142
+ return RawFunction(
143
+ name=txt(name_node),
144
+ calls=collect_calls(body),
145
+ source=txt(node),
146
+ doc=doc,
147
+ line_start=ls,
148
+ line_end=le,
149
+ )
150
+
151
+ # -- source / . includes ----------------------------------------------------------------
152
+
153
+ def build_source(cmd) -> RawSource | None:
154
+ arg = first_argument(cmd)
155
+ if arg is None:
156
+ return None
157
+ dynamic = arg.type in _EXPANSION_TYPES or has_expansion(arg)
158
+ raw = txt(arg)
159
+ path = raw.strip().strip('"').strip("'")
160
+ if not path:
161
+ return None
162
+ ls, _ = lines(cmd)
163
+ return RawSource(path=path, is_dynamic=dynamic, line_start=ls)
164
+
165
+ # -- whole-tree walk --------------------------------------------------------------------
166
+ # Functions are found at ANY depth (bash allows a function defined inside another). `source`
167
+ # directives are collected wherever they appear (top level or inside a function): a `source`
168
+ # brings definitions into the file's scope regardless of where it sits, so it is modelled as a
169
+ # file-level include.
170
+
171
+ stack = [tree.root_node]
172
+ while stack:
173
+ n = stack.pop()
174
+ for child in n.children:
175
+ if child.type == "function_definition":
176
+ rf.functions.append(build_function(child))
177
+ elif child.type == "command":
178
+ cw = command_word(child)
179
+ if cw in ("source", "."):
180
+ src = build_source(child)
181
+ if src is not None:
182
+ rf.sources.append(src)
183
+ stack.append(child)
184
+
185
+ return rf
186
+
187
+
188
+ def _strip_shebang(doc: str) -> str:
189
+ """A `#!/usr/bin/env bash` shebang directly above a declaration is captured as a leading
190
+ comment; `clean_comment` strips the `#`, leaving a line beginning with `!`. Drop such lines so
191
+ a shebang never masquerades as a function's doc."""
192
+ if not doc:
193
+ return doc
194
+ kept = [ln for ln in doc.split("\n") if not ln.lstrip().startswith("!")]
195
+ return "\n".join(kept).strip()
@@ -0,0 +1,178 @@
1
+ """Git-tracked (and directory) Bash ingestion: moves a project's Bash subgraph to a target
2
+ commit/tree by fully recomputing the target state and diffing it against the graph
3
+ (graph_sync.compute_delta) -- the same recompute-and-delta model as the Go/Java/C/Python
4
+ ingestors (resolution is global -- the project-wide function index -- so a file-level diff can't
5
+ tell which untouched files a change affects).
6
+
7
+ Fast engine only for now: tree-sitter-bash streams each `.sh`/`.bash` blob (no disk
8
+ materialization) -> RawFile -> resolution.resolve(). A deep pass (a real shell resolver that
9
+ tracks `source` scope / `PATH` / aliases / dynamic command names) would be added as the
10
+ GitLanguage's `deep_sync` (see plugin.py). Registered as the `bash` GitLanguage for the
11
+ multi-language endpoint (core/ingest.py) in both ingest_repository (git) and ingest_directory
12
+ (local)."""
13
+
14
+ from __future__ import annotations
15
+
16
+ import itertools
17
+ import logging
18
+ import time
19
+ from dataclasses import dataclass
20
+
21
+ from auryn.core.parallel import parse_blobs_ordered
22
+ from auryn.core.graph_model import GraphNode
23
+ from auryn.core.graph_sync import stream_apply
24
+ from auryn.core.registry import LanguageIngestResult
25
+ from auryn.ingestors.bash import resolution
26
+ from auryn.ingestors.bash.file_parser import parse_source
27
+ from auryn.ingestors.bash.ids import project_id
28
+ from auryn.ingestors.bash.plugin import EXCLUDED_DIR_NAMES as _EXCLUDED_DIR_NAMES
29
+ from auryn.ingestors.bash.plugin import FILE_SUFFIXES as _FILE_SUFFIXES
30
+ from auryn.ingestors.bash.schema import NODE_SCHEMAS
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+
35
+ @dataclass
36
+ class SyncStats:
37
+ nodes_added: int = 0
38
+ nodes_updated: int = 0
39
+ nodes_removed: int = 0
40
+ edges_added: int = 0
41
+ edges_updated: int = 0
42
+ edges_removed: int = 0
43
+ commit_sha: str = ""
44
+ elapsed_seconds: float = 0.0
45
+ files_parsed: int = 0
46
+ files_cached: int = 0
47
+
48
+
49
+ def sync_at(writer, source, target_sha: str, project_name: str, repo_uri: str, ref: str | None) -> SyncStats:
50
+ """Recompute the whole Bash subgraph at `target_sha` and delta it onto the graph. `source` is
51
+ duck-typed (GitRepoCache or LocalDirectorySource): only list_files/read_blob used."""
52
+ started = time.monotonic()
53
+ proj_id = project_id(project_name)
54
+
55
+ writer.setup_schema(NODE_SCHEMAS) # brings the graph key into existence before the first read
56
+ current_sha = writer.get_property("Project", {"id": proj_id}, "commit_sha")
57
+ if current_sha == target_sha:
58
+ return SyncStats(commit_sha=target_sha, elapsed_seconds=time.monotonic() - started)
59
+
60
+ # Incremental resync (ADR 0002): when a prior graph already exists at a *different, reachable*
61
+ # commit, move it by processing only the git diff + its graph-derived blast radius instead of
62
+ # recomputing the whole tree (Bash is file-scoped, so it fits the shared engine -- see
63
+ # incremental.py). Any failure (the old commit unreachable in a shallow clone, a source that
64
+ # can't diff, a plain non-git directory) falls straight back to the full recompute below, which
65
+ # leaves the graph untouched until it writes.
66
+ if current_sha and current_sha != target_sha:
67
+ incr = _route(writer, source, target_sha, ref, current_sha,
68
+ project_name=project_name, repo_uri=repo_uri)
69
+ if incr is not None:
70
+ return _finish(writer, proj_id, source, incr)
71
+
72
+ entries = [
73
+ (path, blob_sha)
74
+ for suffix in _FILE_SUFFIXES
75
+ for path, blob_sha in source.list_files(target_sha, suffix, set(_EXCLUDED_DIR_NAMES))
76
+ ]
77
+ files = parse_blobs_ordered(
78
+ entries, source.read_blob, parse_source,
79
+ preload=["auryn.ingestors.bash.file_parser"], logger=logger,
80
+ )
81
+
82
+ project_node = GraphNode(
83
+ "Project", {"id": proj_id}, {"name": project_name, "repo_uri": repo_uri, "commit_sha": target_sha, "ref": ref}
84
+ )
85
+
86
+ def make_target(): # re-iterable: stream_apply runs it once for nodes, once for edges
87
+ return itertools.chain([project_node], resolution.resolve(files, proj_id))
88
+
89
+ return _finish(writer, proj_id, source, _apply(writer, proj_id, make_target, target_sha, started, files_parsed=len(files)))
90
+
91
+
92
+ def _route(writer, source, target_sha, ref, current_sha, *, project_name, repo_uri) -> SyncStats | None:
93
+ """Attempt an incremental resync via the shared engine's git routing (working-tree or bare-clone
94
+ producer, ADR 0002); return SyncStats or None to fall back to the full recompute."""
95
+ from auryn.core.incremental_scoped import route_incremental
96
+ from auryn.ingestors.bash.incremental import BASH_SPEC
97
+
98
+ s = route_incremental(
99
+ writer, BASH_SPEC, source, target_sha, ref, current_sha,
100
+ project_name=project_name, repo_uri=repo_uri, logger=logger,
101
+ )
102
+ if s is None:
103
+ return None
104
+ return SyncStats(
105
+ nodes_added=s.nodes_added, nodes_updated=s.nodes_updated, nodes_removed=s.nodes_removed,
106
+ edges_added=s.edges_added, edges_updated=s.edges_updated, edges_removed=s.edges_removed,
107
+ commit_sha=s.commit_sha, elapsed_seconds=s.elapsed_seconds,
108
+ files_parsed=s.files_parsed, files_cached=s.files_cached,
109
+ )
110
+
111
+
112
+ def _finish(writer, proj_id: str, source, result: SyncStats) -> SyncStats:
113
+ """After any non-short-circuit sync, record the working-tree base for the next save-triggered
114
+ incremental resync (a no-op for git/plain-dir sources)."""
115
+ from auryn.core.incremental_scoped import stamp_worktree
116
+ from auryn.core.local_source import WorkingTreeSource
117
+
118
+ if isinstance(source, WorkingTreeSource):
119
+ stamp_worktree(writer, proj_id, source, _FILE_SUFFIXES)
120
+ return result
121
+
122
+
123
+ def _apply(writer, proj_id: str, make_target, target_sha: str, started: float, files_parsed: int) -> SyncStats:
124
+ # Cross-repo reconciliation (ADR 0004): fold placeholder<->definer pairs among the linkages
125
+ # this ingest touched -- targeted index seeks, no scan. No-op unless the graph holds >1 repo.
126
+ from auryn.core.linkage import reconcile_linkages
127
+
128
+ # stream_apply writes the delta without materialising the target graph, and returns the
129
+ # linkage strings collected inline (see graph_sync.stream_apply / core.linkage).
130
+ labels = [s.label for s in NODE_SCHEMAS]
131
+ stats, reals, placeholders = stream_apply(writer, proj_id, labels, make_target)
132
+ reconcile_linkages(writer, reals, placeholders)
133
+
134
+ return SyncStats(
135
+ nodes_added=stats.nodes_added,
136
+ nodes_updated=stats.nodes_updated,
137
+ nodes_removed=stats.nodes_removed,
138
+ edges_added=stats.edges_added,
139
+ edges_updated=stats.edges_updated,
140
+ edges_removed=stats.edges_removed,
141
+ commit_sha=target_sha,
142
+ elapsed_seconds=time.monotonic() - started,
143
+ files_parsed=files_parsed,
144
+ files_cached=0,
145
+ )
146
+
147
+
148
+ def _git_language_sync(
149
+ writer,
150
+ source,
151
+ target_sha: str,
152
+ *,
153
+ repo_uri: str,
154
+ project_name: str,
155
+ solution_name: str | None,
156
+ ref: str | None,
157
+ cache_root=None,
158
+ ) -> LanguageIngestResult:
159
+ """GitLanguage adapter for the multi-language endpoint (Bash has no solution/cache knobs --
160
+ accepted for the shared interface and ignored)."""
161
+ s = sync_at(writer, source, target_sha, project_name=project_name, repo_uri=repo_uri, ref=ref)
162
+ return LanguageIngestResult(
163
+ nodes_added=s.nodes_added,
164
+ nodes_updated=s.nodes_updated,
165
+ nodes_removed=s.nodes_removed,
166
+ edges_added=s.edges_added,
167
+ edges_updated=s.edges_updated,
168
+ edges_removed=s.edges_removed,
169
+ files_parsed=s.files_parsed,
170
+ files_cached=s.files_cached,
171
+ commit_sha=s.commit_sha,
172
+ elapsed_seconds=s.elapsed_seconds,
173
+ )
174
+
175
+
176
+ # The GitLanguage is registered by the import-light plugin.py (the entry-point target), whose
177
+ # lazy `sync` thunk calls `_git_language_sync` above -- so importing this tree-sitter engine
178
+ # module is deferred until a source actually contains Bash files.
@@ -0,0 +1,15 @@
1
+ """tree-sitter-bash Language/Parser setup, in one place so file_parser.py and tests always
2
+ get the exact same configured parser. Like tree-sitter-go/-rust/-java, it ships a pre-built
3
+ PyPI package -- no codegen/vendoring (contrast PL/SQL's vendored ANTLR grammar). The language
4
+ entry point is `tree_sitter_bash.language()` (verified against tree-sitter-bash 0.25.1)."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import tree_sitter_bash as tsbash
9
+ from tree_sitter import Language, Parser
10
+
11
+ LANGUAGE = Language(tsbash.language())
12
+
13
+
14
+ def new_parser() -> Parser:
15
+ return Parser(LANGUAGE)
@@ -0,0 +1,47 @@
1
+ """Canonical id scheme for the Bash graph, mirroring the other ingestors' shape (root at
2
+ `bash://<project>`, ids embed names/positions) so a single graph can hold every language with
3
+ interchangeable node ids. A future deep engine (a real shell resolver) would key nodes by these
4
+ same functions, so its output stays a pure delta over the fast pass.
5
+
6
+ Bash-specific choices:
7
+
8
+ - **No package/module tier and no type tier.** Bash has neither namespaces nor classes/types, so
9
+ a `Function` hangs directly off the `File` that defines it (`File -[HAS_FUNCTION]-> Function`).
10
+ A function is therefore keyed off its defining *file*, not a package.
11
+ - **Case-preserving.** Bash identifiers are case-sensitive (`Deploy` and `deploy` are two
12
+ different functions), so ids are NOT lowercased (unlike Java/Rust, which can).
13
+ - **No parameter signature.** Bash functions declare no parameter list (arguments arrive as
14
+ `$1`, `$2`, ...), so a function id carries only its name -- there is nothing to disambiguate."""
15
+
16
+ from __future__ import annotations
17
+
18
+
19
+ def project_id(project_name: str) -> str:
20
+ return f"bash://{project_name}"
21
+
22
+
23
+ def file_id(proj_id: str, rel_path: str) -> str:
24
+ return f"{proj_id}/file/{rel_path.replace(chr(92), '/').lstrip('./')}"
25
+
26
+
27
+ def function_id(file_id_: str, name: str) -> str:
28
+ return f"{file_id_}.func.{name}"
29
+
30
+
31
+ # -- cross-repo linkage (ADR 0004) -------------------------------------------------------
32
+ # Project-INDEPENDENT identity for a callable as an external *consumer* names it. In Bash a
33
+ # function is reachable simply by its name once its defining file is `source`d, so the linkage is
34
+ # just the bare function/command name (there is no package/type qualifier). It is BOTH the id of
35
+ # the placeholder that stands in for an unresolved external command AND the `linkage_key` property
36
+ # stamped on every real, locally-defined function -- so ingesting a repo that defines `deploy`
37
+ # into the same graph lets reconciliation match `extern://bash/deploy` (a caller's placeholder)
38
+ # against the real `deploy` and upgrade the CALLS edge in place (e.g. across `source`d libraries).
39
+ def extern_function_key(name: str) -> str:
40
+ return f"extern://bash/{name}"
41
+
42
+
43
+ def extern_file_key(path: str) -> str:
44
+ """Placeholder id for a `source`d file that is not part of the ingested project (a system
45
+ file like `/etc/profile`, or a path we cannot resolve to a project file). Distinct namespace
46
+ from `extern_function_key` so a command name and a file path can never collide."""
47
+ return f"extern://bash/file/{path.replace(chr(92), '/')}"
@@ -0,0 +1,141 @@
1
+ """Bash binding for the generic incremental resync engine (core/incremental_scoped.py, ADR 0002).
2
+
3
+ Bash is the simplest file-scoped language on the roster: a script IS a file, every `Function`
4
+ nests under its defining `File`'s id (`<file_id>.func.<name>`), and the only cross-file edges are
5
+ `CALLS` (Function→Function, resolved by bare name project-wide) and `IMPORTS` (File→File, from a
6
+ `source`/`.` include). So every entity of a file lives under a single per-file id prefix -- exactly
7
+ the invariant the engine requires -- and this module supplies only the Bash-specific glue via
8
+ `BASH_SPEC`: id↔scope mapping, edge classification, and the two genuinely language-specific pieces
9
+ -- reconstructing the resolution symbol table from the graph (`read_graph_index`) and emitting a
10
+ subset against it (`resolution.resolve_incremental`).
11
+
12
+ Correctness (an incremental resync == a full recompute, node-for-node/edge-for-edge, including the
13
+ reclamation of now-orphaned `extern://` command placeholders) is enforced by
14
+ tests/ingestors/bash/test_bash_incremental.py.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from auryn.core.graph_client import GraphWriter
20
+ from auryn.core.graph_model import GraphNode
21
+ from auryn.core.incremental_scoped import ChangeSet, ScopedSpec, incremental_sync
22
+ from auryn.ingestors.bash import ids, resolution
23
+ from auryn.ingestors.bash.file_parser import parse_source
24
+ from auryn.ingestors.bash.plugin import EXCLUDED_DIR_NAMES as _EXCLUDED_DIR_NAMES
25
+ from auryn.ingestors.bash.plugin import FILE_SUFFIXES as _FILE_SUFFIXES
26
+ from auryn.ingestors.bash.schema import NODE_SCHEMAS
27
+
28
+ __all__ = ["ChangeSet", "BASH_SPEC", "read_graph_index", "incremental_bash_sync"]
29
+
30
+ # Edge classification for the engine (see core/incremental_scoped.read_scoped_fingerprints):
31
+ # - containment (target-owned): the structural spine. HAS_FILE's target File and HAS_FUNCTION's
32
+ # target Function both nest under the emit scope, so a file re-emits exactly the containment
33
+ # edges whose target it owns.
34
+ # - symbol-ref (source-owned): CALLS points at a Function symbol -- walked for the reverse-dep
35
+ # closure (a caller of a changed function must be re-resolved).
36
+ # - lateral (source-owned): CALLS + IMPORTS, both sourced at a node in the emit scope.
37
+ _CONTAINMENT_RELS = ("HAS_FILE", "HAS_FUNCTION")
38
+ _SYMBOL_REF_RELS = ("CALLS",)
39
+
40
+
41
+ def _range(prefix: str) -> tuple[str, str]:
42
+ return prefix, prefix + chr(0xFFFF)
43
+
44
+
45
+ def _scope_key(path: str) -> str:
46
+ """A file's stable scope key = its normalized path -- the exact string `File.path` stores and
47
+ `file_id` is built from, so it agrees with the id-prefix the engine scopes by."""
48
+ return path.replace("\\", "/").lstrip("./")
49
+
50
+
51
+ def _bash_project_node(project_name, repo_uri, proj_id, target_sha, ref) -> GraphNode:
52
+ return GraphNode(
53
+ "Project", {"id": proj_id},
54
+ {"name": project_name, "repo_uri": repo_uri, "commit_sha": target_sha, "ref": ref},
55
+ )
56
+
57
+
58
+ def _bash_satisfied_linkage_keys(raws) -> set[str]:
59
+ """The command-placeholder linkages the emit set's function definitions can satisfy: every
60
+ function a just-parsed file DEFINES is reachable project-wide by bare name, so an untouched
61
+ caller that currently points at `extern://bash/<name>` should be re-resolved onto it. Drives
62
+ the engine's placeholder-satisfaction closure (bare-name resolution has no dependency edge for
63
+ the standard closures to follow)."""
64
+ return {ids.extern_function_key(fn.name) for rf in raws for fn in rf.functions}
65
+
66
+
67
+ def _bash_referenced_names(rf) -> set[str]:
68
+ """The bare command names this file's functions invoke -- the only names it can resolve to a
69
+ project function cross-file. (Source paths are matched against the full file list, not by name,
70
+ so they need no name seed.) Over-collecting is safe; the equivalence oracle catches an
71
+ under-collection."""
72
+ return {call.name for fn in rf.functions for call in fn.calls}
73
+
74
+
75
+ def read_graph_index(
76
+ writer: GraphWriter, proj_id: str, exclude_keys: set[str], names: set[str]
77
+ ) -> resolution.GraphIndex:
78
+ """Reconstruct Bash resolution's symbol tables from the graph for every file EXCEPT
79
+ `exclude_keys` (the emit + removed set): the full file list (for `source`/IMPORTS resolution,
80
+ which matches by path/suffix/basename) and the project functions whose bare name is in `names`
81
+ (what the blast radius calls). A node belongs to an excluded file iff its id is that file's id
82
+ or nests under it (`<file_id>.…`) -- robust to dotted filenames. `extern://` placeholders sort
83
+ outside the project id range, so the range scan skips them for free."""
84
+ exclude_prefixes = [ids.file_id(proj_id, k) for k in exclude_keys]
85
+
86
+ def excluded(node_id: str) -> bool:
87
+ return any(node_id == p or node_id.startswith(p + ".") for p in exclude_prefixes)
88
+
89
+ lo, hi = _range(proj_id)
90
+ index = resolution.GraphIndex()
91
+
92
+ for path, fid in writer.ro_query(
93
+ "MATCH (f:File) WHERE f.id >= $lo AND f.id < $hi RETURN f.path, f.id", {"lo": lo, "hi": hi}
94
+ ).result_set:
95
+ if not excluded(fid):
96
+ index.files_by_norm.append((_scope_key(path), fid))
97
+
98
+ name_list = list(names)
99
+ if name_list:
100
+ for name, fid in writer.ro_query(
101
+ "MATCH (f:Function) WHERE f.id >= $lo AND f.id < $hi AND f.name IN $names RETURN f.name, f.id",
102
+ {"lo": lo, "hi": hi, "names": name_list},
103
+ ).result_set:
104
+ if not excluded(fid):
105
+ index.func_ids_by_name.setdefault(name, []).append(fid)
106
+ return index
107
+
108
+
109
+ BASH_SPEC = ScopedSpec(
110
+ language="bash",
111
+ node_schemas=tuple(NODE_SCHEMAS),
112
+ node_labels=tuple(s.label for s in NODE_SCHEMAS),
113
+ file_suffixes=tuple(_FILE_SUFFIXES),
114
+ excluded_dir_names=frozenset(_EXCLUDED_DIR_NAMES),
115
+ symbol_ref_rels=_SYMBOL_REF_RELS,
116
+ lateral_rels=_SYMBOL_REF_RELS + ("IMPORTS",),
117
+ containment_rels=_CONTAINMENT_RELS,
118
+ targetable_labels=("Function",),
119
+ import_rel="IMPORTS",
120
+ import_target_labels=("File",),
121
+ project_id=ids.project_id,
122
+ scope_id_for_path=ids.file_id,
123
+ scope_key_for_path=_scope_key,
124
+ parse=parse_source,
125
+ # tree-sitter-bash recovers from errors and the RawFile carries no error flag, so a "broken"
126
+ # file is just its best-effort parse -- identical in both engines, so accepting it keeps
127
+ # incremental == full recompute.
128
+ is_broken=lambda rf: False,
129
+ referenced_names=_bash_referenced_names,
130
+ read_index=read_graph_index,
131
+ resolve_incremental=resolution.resolve_incremental,
132
+ project_node=_bash_project_node,
133
+ satisfied_linkage_keys=_bash_satisfied_linkage_keys,
134
+ )
135
+
136
+
137
+ def incremental_bash_sync(writer, source, target_sha, changes, *, project_name, repo_uri, ref=None):
138
+ """Thin wrapper over the shared engine used by the equivalence oracle (the git_sync routing
139
+ goes through core.route_incremental → the same engine)."""
140
+ return incremental_sync(writer, BASH_SPEC, source, target_sha, changes,
141
+ project_name=project_name, repo_uri=repo_uri, ref=ref)
@@ -0,0 +1,41 @@
1
+ """Import-light Bash/Shell language registration -- the `auryn.languages` entry-point target.
2
+
3
+ Importing this module registers the Bash GitLanguage without importing tree-sitter: the
4
+ GitLanguage's `sync` is a lazy thunk that imports auryn.ingestors.bash.git_sync only when a
5
+ source actually contains `.sh`/`.bash` files. Single-phase today (fast tree-sitter-bash).
6
+
7
+ Bash has NO types and NO classes, so there is no class/type model to build: the useful graph is
8
+ structural and flat -- the functions a script defines, the local functions and external commands
9
+ each one invokes (CALLS), and the files it pulls in with `source`/`.` (IMPORTS). A deep pass -- a
10
+ real shell resolver that tracks `source` scope, `PATH`, aliases and dynamic command names -- would
11
+ slot in here as `deep_sync` (making Bash two-phase like Python), but the fast pass deliberately
12
+ guesses nothing it cannot read straight off the syntax tree.
13
+
14
+ Suffix/exclude constants live here (single source of truth); git_sync imports them back."""
15
+
16
+ from __future__ import annotations
17
+
18
+ from auryn.core.registry import GitLanguage, register_git_language
19
+
20
+ LANGUAGE = "bash"
21
+ # Suffix-based detection (the common, unambiguous case). Shebang-only scripts with no extension
22
+ # are intentionally out of scope for the fast pass -- keeping detection cheap and deterministic.
23
+ FILE_SUFFIXES = (".sh", ".bash")
24
+ EXCLUDED_DIR_NAMES = frozenset({".git", "node_modules", "vendor", "dist", ".idea", ".vscode"})
25
+
26
+
27
+ def _sync(*args, **kwargs):
28
+ """Deferred until a source has Bash files -- imports the tree-sitter-bash engine."""
29
+ from auryn.ingestors.bash.git_sync import _git_language_sync
30
+
31
+ return _git_language_sync(*args, **kwargs)
32
+
33
+
34
+ register_git_language(
35
+ GitLanguage(
36
+ language=LANGUAGE,
37
+ file_suffixes=FILE_SUFFIXES,
38
+ excluded_dir_names=EXCLUDED_DIR_NAMES,
39
+ sync=_sync,
40
+ )
41
+ )