loctree/lib.rs
1//! # loctree
2//!
3//! **AI-oriented Project Analyzer** - Static analysis tool designed for AI agents
4//! and developers building production-ready software.
5//!
6//! loctree helps overcome the common AI tendency to generate excessive artifacts
7//! that lead to re-export cascades, circular imports, and spaghetti dependencies.
8//!
9//! ## Features
10//!
11//! - **Holographic Slice** - Extract focused context (deps + consumers) for any file
12//! - **Handler Trace** - Follow Tauri commands through the entire pipeline
13//! - **Dead Export Detection** - Find unused exports and orphaned code
14//! - **Circular Import Detection** - Catch runtime bombs before they explode
15//! - **Auto-Detect Stack** - Automatically configure for Rust, TypeScript, Python, Tauri
16//! - **HTML Reports** - Interactive reports with Cytoscape.js dependency graphs
17//!
18//! ## Quick Start (Library Usage)
19//!
20//! ```rust,no_run
21//! use loctree::{detect, snapshot, slicer};
22//! use std::path::PathBuf;
23//!
24//! // Detect project stack
25//! let detected = detect::detect_stack(std::path::Path::new("."));
26//! println!("Detected: {}", detected.description);
27//! ```
28//!
29//! ## Running Import Analysis
30//!
31//! ```rust,no_run
32//! use loctree::{analyzer, args};
33//! use std::path::PathBuf;
34//!
35//! // Run the full import analyzer on a project
36//! let mut parsed = args::ParsedArgs::default();
37//! parsed.dead_exports = true;
38//! parsed.circular = true;
39//!
40//! let roots = vec![PathBuf::from(".")];
41//! analyzer::run_import_analyzer(&roots, &parsed).unwrap();
42//! ```
43//!
44//! ## CLI Usage
45//!
46//! For command-line usage, install with `cargo install loctree` and run:
47//!
48//! ```bash
49//! loctree # Scan and snapshot
50//! loctree slice src/App.tsx # Extract AI context
51//! loctree trace get_user # Trace Tauri handler
52//! loctree -A --circular # Find circular imports
53//! loctree --for-ai # AI-optimized JSON output
54//! ```
55//!
56//! See the [README](https://github.com/Loctree/Loctree) for full documentation.
57
58#![doc(html_root_url = "https://docs.rs/loctree/0.5.13")]
59#![doc(
60 html_favicon_url = "https://raw.githubusercontent.com/Loctree/Loctree/main/assets/loctree-logo.svg"
61)]
62#![doc(
63 html_logo_url = "https://raw.githubusercontent.com/Loctree/Loctree/main/assets/loctree-logo.svg"
64)]
65
66// ============================================================================
67// Core Modules
68// ============================================================================
69
70/// Import/export analyzer supporting TypeScript, JavaScript, Python, Rust, and CSS.
71///
72/// # Submodules
73///
74/// - [`analyzer::js`] - TypeScript/JavaScript analysis
75/// - [`analyzer::py`] - Python analysis
76/// - [`analyzer::rust`] - Rust analysis (Tauri commands)
77/// - [`analyzer::cycles`] - Circular import detection (Tarjan's SCC)
78/// - [`analyzer::dead_parrots`] - Dead export detection
79/// - [`analyzer::trace`] - Handler tracing for Tauri
80/// - [`analyzer::coverage`] - Tauri command coverage
81/// - [`analyzer::for_ai`] - AI-optimized output generation
82/// - [`analyzer::html`] - HTML report generation
83/// - [`analyzer::sarif`] - SARIF 2.1.0 output for CI
84pub mod analyzer;
85
86/// New CLI module for the subcommand-based interface.
87///
88/// Provides the canonical `loct <command> [options]` interface with:
89/// - [`Command`](cli::Command) enum as the source of truth for all commands
90/// - [`GlobalOptions`](cli::GlobalOptions) for shared flags
91/// - Per-command option structs
92/// - Legacy adapter for backward compatibility (until v1.0)
93///
94/// # Key Commands (Human Interface)
95///
96/// - `loct` / `loct auto` - Full auto-scan with stack detection (default)
97/// - `loct scan` - Build/update snapshot
98/// - `loct dead` - Detect unused exports
99/// - `loct commands` - Show Tauri command bridges
100/// - `loct events` - Show event flow
101/// - `loct slice <path>` - Extract holographic context
102///
103/// # Agent Interface
104///
105/// Agents should use `--json` output with regex filters on metadata:
106/// - `loct find --symbol '.*patient.*' --lang ts --json`
107/// - `loct dead --confidence high --json`
108pub mod cli;
109
110/// Command-line argument parsing.
111///
112/// Contains [`ParsedArgs`](args::ParsedArgs) struct and [`parse_args`](args::parse_args) function.
113pub mod args;
114
115/// Configuration file support.
116///
117/// Loads `.loctree/config.toml` for project-specific settings like custom Tauri command macros.
118pub mod config;
119
120/// Auto-detection of project stacks.
121///
122/// Detects Rust, TypeScript, Python, Tauri, Vite, and more based on marker files.
123///
124/// # Example
125///
126/// ```rust,no_run
127/// use loctree::detect;
128/// use std::path::Path;
129///
130/// let detected = detect::detect_stack(Path::new("."));
131/// if !detected.is_empty() {
132/// println!("Stack: {}", detected.description);
133/// println!("Extensions: {:?}", detected.extensions);
134/// }
135/// ```
136pub mod detect;
137
138/// Filesystem utilities.
139///
140/// - Gitignore handling with [`GitIgnoreChecker`](fs_utils::GitIgnoreChecker)
141/// - File gathering with extension/depth filters
142/// - Line counting
143/// - Pattern normalization
144pub mod fs_utils;
145
146/// String similarity using Levenshtein distance.
147///
148/// Used for fuzzy matching in `--check` mode to find similar component names.
149pub mod similarity;
150
151/// Holographic slice extraction.
152///
153/// Extracts a file's context in three layers:
154/// - **Core** - The target file itself
155/// - **Deps** - Files the target imports (transitive)
156/// - **Consumers** - Files that import the target
157///
158/// # Example
159///
160/// ```rust,no_run
161/// use loctree::slicer;
162/// use loctree::args::ParsedArgs;
163/// use std::path::Path;
164///
165/// let parsed = ParsedArgs::default();
166/// let root = Path::new(".");
167///
168/// // Extract slice for src/App.tsx with consumers, as JSON
169/// slicer::run_slice(root, "src/App.tsx", true, true, &parsed).unwrap();
170/// ```
171pub mod slicer;
172
173/// Incremental snapshot persistence.
174///
175/// Saves analysis results to `.loctree/snapshot.json` for faster subsequent runs.
176/// Uses file modification times to skip unchanged files.
177///
178/// # Key Types
179///
180/// - [`Snapshot`](snapshot::Snapshot) - The persisted analysis state
181/// - [`SnapshotMetadata`](snapshot::SnapshotMetadata) - Version and timestamp info
182/// - [`GraphEdge`](snapshot::GraphEdge) - Import relationship
183/// - [`CommandBridge`](snapshot::CommandBridge) - FE→BE command mapping
184pub mod snapshot;
185
186/// Directory tree with LOC counts.
187///
188/// Fast tree view similar to Unix `tree` command but with:
189/// - Line counts per file
190/// - Large file highlighting
191/// - Gitignore support
192/// - Build artifact detection (`--find-artifacts`)
193pub mod tree;
194
195/// Common types used throughout the crate.
196///
197/// # Key Types
198///
199/// - [`Mode`] - CLI mode (Tree, Slice, Trace, AnalyzeImports, ForAi, Git)
200/// - [`Options`] - Analysis configuration
201/// - [`FileAnalysis`] - Per-file analysis result
202/// - `ImportEntry` - Import statement representation
203/// - `ExportSymbol` - Export declaration
204/// - `CommandRef` - Tauri command reference
205pub mod types;
206
207/// Git operations for temporal awareness.
208///
209/// Native git operations using libgit2 for analyzing repository history.
210///
211/// # Key Types
212///
213/// - [`GitRepo`](git::GitRepo) - Git repository wrapper
214/// - [`CommitInfo`](git::CommitInfo) - Commit metadata
215/// - [`ChangedFile`](git::ChangedFile) - File change between commits
216///
217/// # Example
218///
219/// ```rust,no_run
220/// use loctree::git::GitRepo;
221/// use std::path::Path;
222///
223/// let repo = GitRepo::discover(Path::new(".")).unwrap();
224/// let head = repo.head_commit().unwrap();
225/// println!("HEAD: {}", head);
226/// ```
227pub mod git;
228
229/// Snapshot comparison engine for temporal analysis.
230///
231/// Compares loctree snapshots between commits to show semantic changes.
232///
233/// # Key Types
234///
235/// - [`SnapshotDiff`](diff::SnapshotDiff) - Result of comparing two snapshots
236/// - [`GraphDiff`](diff::GraphDiff) - Import graph changes
237/// - [`ExportsDiff`](diff::ExportsDiff) - Export changes
238/// - [`DeadCodeDiff`](diff::DeadCodeDiff) - Dead code changes
239/// - [`ImpactAnalysis`](diff::ImpactAnalysis) - Change impact assessment
240pub mod diff;
241
242/// Query API for fast lookups against the cached snapshot.
243///
244/// Provides interactive queries without re-scanning:
245/// - `who-imports <file>` - Find all files that import a given file
246/// - `where-symbol <symbol>` - Find where a symbol is defined
247/// - `component-of <file>` - Show what component/module a file belongs to
248///
249/// # Example
250///
251/// ```rust,no_run
252/// use loctree::{query, snapshot};
253/// use std::path::Path;
254///
255/// let snapshot = snapshot::Snapshot::load(Path::new(".")).unwrap();
256/// let result = query::query_who_imports(&snapshot, "src/utils.ts");
257/// println!("Found {} importers", result.results.len());
258/// ```
259pub mod query;
260
261// ============================================================================
262// Re-exports for convenience
263// ============================================================================
264
265/// CLI modes.
266pub use types::Mode;
267
268/// Analysis options.
269pub use types::Options;
270
271/// Output format (Text, Json, Jsonl).
272pub use types::OutputMode;
273
274/// Color mode (Auto, Always, Never).
275pub use types::ColorMode;
276
277/// Per-file analysis result with imports, exports, commands, etc.
278pub use types::FileAnalysis;
279
280/// Detected project stack with extensions and ignores.
281pub use detect::DetectedStack;
282
283/// Main stack detection function.
284pub use detect::detect_stack;
285
286/// Holographic slice result.
287pub use slicer::HolographicSlice;
288
289/// Slice configuration.
290pub use slicer::SliceConfig;
291
292/// Persisted analysis state.
293pub use snapshot::Snapshot;
294
295/// Run the import analyzer.
296pub use analyzer::run_import_analyzer;
297
298/// Report section for HTML output.
299pub use analyzer::ReportSection;
300
301/// Command gap (missing/unused handler).
302pub use analyzer::CommandGap;
303
304/// Ranked duplicate export.
305pub use analyzer::RankedDup;
306
307// ============================================================================
308// CLI types (new subcommand interface)
309// ============================================================================
310
311/// CLI command enum (source of truth for `loct <command>`).
312pub use cli::Command;
313
314/// Global CLI options (--json, --quiet, --verbose, --color).
315pub use cli::GlobalOptions;
316
317/// Parsed command result with deprecation warning support.
318pub use cli::ParsedCommand;