context-creator 1.5.0

High-performance CLI tool to convert codebases to Markdown for LLM context
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! Helper functions for semantic analysis tests

use context_creator::cli::Config;
use context_creator::core::cache::FileCache;
use context_creator::core::walker::{walk_directory, FileInfo, WalkOptions};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tempfile::TempDir;

/// Test project builder for creating file structures
pub struct TestProjectBuilder {
    temp_dir: TempDir,
    files: Vec<(PathBuf, String)>,
}

impl TestProjectBuilder {
    /// Create a new test project builder
    pub fn new() -> Self {
        Self {
            temp_dir: TempDir::new().unwrap(),
            files: Vec::new(),
        }
    }

    /// Add a file to the test project
    pub fn add_file<P: AsRef<Path>>(mut self, path: P, content: &str) -> Self {
        self.files
            .push((path.as_ref().to_path_buf(), content.to_string()));
        self
    }

    /// Build the test project and return the root path
    pub fn build(self) -> (TempDir, PathBuf) {
        let root = self.temp_dir.path().to_path_buf();

        for (path, content) in self.files {
            let full_path = root.join(&path);
            if let Some(parent) = full_path.parent() {
                fs::create_dir_all(parent).unwrap();
            }
            fs::write(full_path, content).unwrap();
        }

        (self.temp_dir, root)
    }
}

impl Default for TestProjectBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Analyze a test project with semantic analysis enabled
pub fn analyze_project_with_options(
    root: &Path,
    trace_imports: bool,
    include_callers: bool,
    include_types: bool,
    semantic_depth: usize,
) -> Vec<FileInfo> {
    let config = Config {
        paths: Some(vec![root.to_path_buf()]),
        trace_imports,
        include_callers,
        include_types,
        semantic_depth,
        ..Config::default()
    };

    let walk_options = WalkOptions::from_config(&config).unwrap();
    let cache = Arc::new(FileCache::new());

    let mut files = walk_directory(root, walk_options).unwrap();
    context_creator::core::walker::perform_semantic_analysis(&mut files, &config, &cache).unwrap();

    files
}

/// Analyze a test project with all semantic features enabled
pub fn analyze_test_project(root: &Path) -> Vec<FileInfo> {
    analyze_project_with_options(root, true, true, true, 3)
}

/// Find a file by its relative path in the results
pub fn find_file<'a>(files: &'a [FileInfo], path: &str) -> Option<&'a FileInfo> {
    files.iter().find(|f| {
        let path_str = f.relative_path.to_str().unwrap();
        // Handle both Unix and Windows path separators
        let normalized_path = path_str.replace('\\', "/");
        normalized_path == path || path_str == path
    })
}

/// Find a file by name (without caring about the directory)
#[allow(dead_code)]
pub fn find_file_by_name<'a>(files: &'a [FileInfo], name: &str) -> Option<&'a FileInfo> {
    files.iter().find(|f| {
        f.relative_path
            .file_name()
            .and_then(|n| n.to_str())
            .map(|n| n == name)
            .unwrap_or(false)
    })
}

/// Assert that a file has specific imports
pub fn assert_has_imports(file: &FileInfo, expected_imports: &[&str]) {
    for expected in expected_imports {
        let found = file.imports.iter().any(|import| {
            import
                .file_name()
                .and_then(|n| n.to_str())
                .map(|n| n == *expected)
                .unwrap_or(false)
        });
        assert!(
            found,
            "Expected import '{}' not found in {:?}. Actual imports: {:?}",
            expected,
            file.relative_path,
            file.imports
                .iter()
                .filter_map(|p| p.file_name())
                .filter_map(|n| n.to_str())
                .collect::<Vec<_>>()
        );
    }
}

/// Assert that a file is imported by specific files
pub fn assert_imported_by(file: &FileInfo, expected_importers: &[&str]) {
    for expected in expected_importers {
        let found = file.imported_by.iter().any(|importer| {
            importer
                .file_name()
                .and_then(|n| n.to_str())
                .map(|n| n == *expected)
                .unwrap_or(false)
        });
        assert!(
            found,
            "Expected to be imported by '{}' but wasn't. Actual importers: {:?}",
            expected,
            file.imported_by
                .iter()
                .filter_map(|p| p.file_name())
                .filter_map(|n| n.to_str())
                .collect::<Vec<_>>()
        );
    }
}

/// Create a simple Rust project for testing
pub fn create_rust_test_project() -> (TempDir, PathBuf) {
    TestProjectBuilder::new()
        .add_file(
            "main.rs",
            r#"
mod lib;
mod utils;

use crate::utils::helper;

fn main() {
    lib::greet("World");
    helper();
    let user = lib::User::new("Alice");
    println!("{}", user.name);
}
"#,
        )
        .add_file(
            "lib.rs",
            r#"
pub struct User {
    pub name: String,
}

impl User {
    pub fn new(name: &str) -> Self {
        User { name: name.to_string() }
    }
}

pub fn greet(name: &str) {
    println!("Hello, {}!", name);
}
"#,
        )
        .add_file(
            "utils.rs",
            r#"
pub fn helper() {
    println!("Helper function");
}

pub fn unused() {
    println!("This function is not called");
}
"#,
        )
        .build()
}

/// Create a Python test project
#[allow(dead_code)]
pub fn create_python_test_project() -> (TempDir, PathBuf) {
    TestProjectBuilder::new()
        .add_file(
            "main.py",
            r#"
import os
from lib import greet, User
from utils import helper

def main():
    greet("World")
    helper()
    user = User("Alice")
    print(user.name)

if __name__ == "__main__":
    main()
"#,
        )
        .add_file(
            "lib.py",
            r#"
class User:
    def __init__(self, name):
        self.name = name

def greet(name):
    print(f"Hello, {name}!")
"#,
        )
        .add_file(
            "utils.py",
            r#"
def helper():
    print("Helper function")

def unused():
    print("This function is not called")
"#,
        )
        .build()
}

/// Create a JavaScript test project
#[allow(dead_code)]
pub fn create_javascript_test_project() -> (TempDir, PathBuf) {
    TestProjectBuilder::new()
        .add_file(
            "main.js",
            r#"
import { greet, User } from './lib.js';
import { helper } from './utils.js';

function main() {
    greet("World");
    helper();
    const user = new User("Alice");
    console.log(user.name);
}

main();
"#,
        )
        .add_file(
            "lib.js",
            r#"
export class User {
    constructor(name) {
        this.name = name;
    }
}

export function greet(name) {
    console.log(`Hello, ${name}!`);
}
"#,
        )
        .add_file(
            "utils.js",
            r#"
export function helper() {
    console.log("Helper function");
}

export function unused() {
    console.log("This function is not called");
}
"#,
        )
        .build()
}

/// Create a TypeScript test project
pub fn create_typescript_test_project() -> (TempDir, PathBuf) {
    TestProjectBuilder::new()
        .add_file(
            "main.ts",
            r#"
import { greet, User } from './lib';
import { helper } from './utils';
import type { Config } from './types';

const config: Config = {
    debug: true,
    name: "test"
};

function main(): void {
    greet("World");
    helper();
    const user = new User("Alice");
    console.log(user.name);
}

main();
"#,
        )
        .add_file(
            "lib.ts",
            r#"
export class User {
    constructor(public name: string) {}
}

export function greet(name: string): void {
    console.log(`Hello, ${name}!`);
}
"#,
        )
        .add_file(
            "utils.ts",
            r#"
export function helper(): void {
    console.log("Helper function");
}

export function unused(): void {
    console.log("This function is not called");
}
"#,
        )
        .add_file(
            "types.ts",
            r#"
export interface Config {
    debug: boolean;
    name: string;
}

export type Status = 'active' | 'inactive';
"#,
        )
        .build()
}

/// Create a project with circular dependencies
pub fn create_circular_deps_project() -> (TempDir, PathBuf) {
    TestProjectBuilder::new()
        .add_file(
            "a.rs",
            r#"
mod b;
use crate::b::func_b;

pub fn func_a() {
    println!("In func_a");
    func_b();
}
"#,
        )
        .add_file(
            "b.rs",
            r#"
mod c;
use crate::c::func_c;

pub fn func_b() {
    println!("In func_b");
    func_c();
}
"#,
        )
        .add_file(
            "c.rs",
            r#"
mod a;
use crate::a::func_a;

pub fn func_c() {
    println!("In func_c");
    // Would cause infinite recursion if called
    // func_a();
}
"#,
        )
        .build()
}

/// Create a deep dependency chain project
pub fn create_deep_dependency_chain(depth: usize) -> (TempDir, PathBuf) {
    let mut builder = TestProjectBuilder::new();

    for i in 0..depth {
        let content = if i == 0 {
            r#"
mod mod1;
use crate::mod1::func1;

fn main() {
    func1();
}
"#
            .to_string()
        } else if i < depth - 1 {
            format!(
                r#"
mod mod{};
use crate::mod{}::func{};

pub fn func{}() {{
    func{}();
}}
"#,
                i + 1,
                i + 1,
                i + 1,
                i,
                i + 1
            )
        } else {
            format!(
                r#"
pub fn func{i}() {{
    println!("End of chain at depth {i}");
}}
"#
            )
        };

        builder = builder.add_file(format!("mod{i}.rs"), &content);
    }

    builder.build()
}