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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
#![cfg(test)]

//! Stress tests for Python semantic analysis

use std::fs;
use tempfile::TempDir;

/// Test Python with hundreds of imports
#[test]
fn test_python_massive_imports() {
    let temp_dir = TempDir::new().unwrap();
    let src_dir = temp_dir.path().join("src");
    fs::create_dir_all(&src_dir).unwrap();

    // Create many modules
    let module_count = 200;
    for i in 0..module_count {
        fs::write(
            src_dir.join(format!("module_{i}.py")),
            format!(
                r#"
def function_{i}():
    return {i}

class Class{i}:
    value = {i}

CONSTANT_{i} = {i}
"#
            ),
        )
        .unwrap();
    }

    // Create main file that imports everything
    let mut content = String::new();

    // Add imports
    for i in 0..module_count {
        content.push_str(&format!(
            "from module_{i} import function_{i}, Class{i}, CONSTANT_{i}\n"
        ));
    }

    // Add main function that uses some imports
    content.push_str("\ndef main():\n    total = 0\n");
    for i in 0..10 {
        content.push_str(&format!("    total += function_{i}()\n"));
        content.push_str(&format!("    obj = Class{i}()\n"));
        content.push_str(&format!("    total += CONSTANT_{i}\n"));
    }
    content.push_str("    return total\n\nif __name__ == '__main__':\n    print(main())\n");

    fs::write(src_dir.join("main.py"), content).unwrap();

    let output = std::process::Command::new(env!("CARGO_BIN_EXE_context-creator"))
        .arg(&src_dir)
        .arg("--trace-imports")
        .arg("--include-callers")
        .arg("--include-types")
        .output()
        .expect("Failed to execute context-creator");

    assert!(output.status.success(), "Should handle 200+ imports");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("main.py"));
    assert!(stdout.contains("Imports:"));
}

/// Test Python with deeply nested function calls
#[test]
fn test_python_deep_call_chain() {
    let temp_dir = TempDir::new().unwrap();
    let src_dir = temp_dir.path().join("src");
    fs::create_dir_all(&src_dir).unwrap();

    // Create a chain of modules calling each other
    let depth = 50;

    for i in 0..depth {
        let content = if i == depth - 1 {
            // Last function in chain
            format!(
                r#"
def function_{i}(n):
    print(f"Reached depth {i}")
    return n + {i}
"#
            )
        } else {
            // Function that imports and calls the next one
            format!(
                r#"
from level_{} import function_{}

def function_{i}(n):
    return function_{}(n + {i})
"#,
                i + 1,
                i + 1,
                i + 1
            )
        };

        fs::write(src_dir.join(format!("level_{i}.py")), content).unwrap();
    }

    // Create entry point
    fs::write(
        src_dir.join("main.py"),
        r#"
from level_0 import function_0

def main():
    result = function_0(0)
    print(f"Final result: {result}")

if __name__ == "__main__":
    main()
"#,
    )
    .unwrap();

    let output = std::process::Command::new(env!("CARGO_BIN_EXE_context-creator"))
        .arg(&src_dir)
        .arg("--trace-imports")
        .arg("--include-callers")
        .output()
        .expect("Failed to execute context-creator");

    assert!(
        output.status.success(),
        "Should handle 50-level deep call chain"
    );
}

/// Test Python with complex cross-module dependencies
#[test]
fn test_python_complex_dependencies() {
    let temp_dir = TempDir::new().unwrap();
    let src_dir = temp_dir.path().join("src");
    fs::create_dir_all(&src_dir).unwrap();

    // Create interconnected modules
    fs::write(
        src_dir.join("models.py"),
        r#"
from typing import List, Optional
from database import Database
from validators import validate_email, validate_age

class User:
    def __init__(self, name: str, email: str, age: int):
        self.name = name
        self.email = validate_email(email)
        self.age = validate_age(age)
        self.db = Database()
    
    def save(self):
        self.db.save_user(self)

class Group:
    def __init__(self, name: str):
        self.name = name
        self.users: List[User] = []
        self.db = Database()
    
    def add_user(self, user: User):
        self.users.append(user)
        self.db.save_group(self)
"#,
    )
    .unwrap();

    fs::write(
        src_dir.join("database.py"),
        r#"
from typing import TYPE_CHECKING
import json

if TYPE_CHECKING:
    from models import User, Group

class Database:
    def __init__(self):
        self.data = {"users": [], "groups": []}
    
    def save_user(self, user: 'User'):
        self.data["users"].append({"name": user.name, "email": user.email})
    
    def save_group(self, group: 'Group'):
        self.data["groups"].append({
            "name": group.name,
            "users": [u.name for u in group.users]
        })
    
    def export(self):
        from exporters import JSONExporter, XMLExporter
        json_exp = JSONExporter()
        xml_exp = XMLExporter()
        return json_exp.export(self.data), xml_exp.export(self.data)
"#,
    )
    .unwrap();

    fs::write(
        src_dir.join("validators.py"),
        r#"
import re
from exceptions import ValidationError

def validate_email(email: str) -> str:
    pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
    if not re.match(pattern, email):
        raise ValidationError(f"Invalid email: {email}")
    return email

def validate_age(age: int) -> int:
    if age < 0 or age > 150:
        raise ValidationError(f"Invalid age: {age}")
    return age

def validate_username(username: str) -> str:
    from models import User  # Circular import
    if len(username) < 3:
        raise ValidationError("Username too short")
    return username
"#,
    )
    .unwrap();

    fs::write(
        src_dir.join("exceptions.py"),
        r#"
class ValidationError(Exception):
    pass

class DatabaseError(Exception):
    pass

class ExportError(Exception):
    pass
"#,
    )
    .unwrap();

    fs::write(
        src_dir.join("exporters.py"),
        r#"
import json
import xml.etree.ElementTree as ET
from exceptions import ExportError

class JSONExporter:
    def export(self, data):
        try:
            return json.dumps(data, indent=2)
        except Exception as e:
            raise ExportError(f"JSON export failed: {e}")

class XMLExporter:
    def export(self, data):
        try:
            root = ET.Element("data")
            # Simplified XML export
            return ET.tostring(root, encoding='unicode')
        except Exception as e:
            raise ExportError(f"XML export failed: {e}")
"#,
    )
    .unwrap();

    fs::write(
        src_dir.join("main.py"),
        r#"
from models import User, Group
from database import Database
from validators import validate_username

def main():
    # Create users
    user1 = User("Alice", "alice@example.com", 25)
    user2 = User("Bob", "bob@example.com", 30)
    
    # Create group
    group = Group("Developers")
    group.add_user(user1)
    group.add_user(user2)
    
    # Save to database
    user1.save()
    user2.save()
    
    # Export data
    db = Database()
    json_data, xml_data = db.export()
    
    print("Data exported successfully")

if __name__ == "__main__":
    main()
"#,
    )
    .unwrap();

    let output = std::process::Command::new(env!("CARGO_BIN_EXE_context-creator"))
        .arg(&src_dir)
        .arg("--trace-imports")
        .arg("--include-callers")
        .arg("--include-types")
        .output()
        .expect("Failed to execute context-creator");

    let stdout = String::from_utf8_lossy(&output.stdout);

    assert!(output.status.success());
    assert!(stdout.contains("main.py"));
    assert!(stdout.contains("models.py"));
    assert!(stdout.contains("database.py"));
    assert!(stdout.contains("validators.py"));
}

/// Test Python with thousands of functions in one file
#[test]
fn test_python_many_functions() {
    let temp_dir = TempDir::new().unwrap();
    let src_dir = temp_dir.path().join("src");
    fs::create_dir_all(&src_dir).unwrap();

    let mut content = String::new();
    content.push_str("# File with many functions\n\n");

    // Create 1000 functions
    let function_count = 1000;
    for i in 0..function_count {
        content.push_str(&format!(
            r#"
def func_{i}(x):
    """Function number {i}"""
    return x + {i}

"#
        ));
    }

    // Add a main function that calls some of them
    content.push_str("def main():\n    total = 0\n");
    for i in 0..20 {
        content.push_str(&format!("    total += func_{i}({i})\n"));
    }
    content.push_str("    return total\n\n");
    content.push_str("if __name__ == '__main__':\n    print(main())\n");

    fs::write(src_dir.join("many_functions.py"), content).unwrap();

    let output = std::process::Command::new(env!("CARGO_BIN_EXE_context-creator"))
        .arg(&src_dir)
        .arg("--include-callers")
        .output()
        .expect("Failed to execute context-creator");

    assert!(output.status.success(), "Should handle 1000 functions");
}

/// Test Python with very large classes
#[test]
fn test_python_large_classes() {
    let temp_dir = TempDir::new().unwrap();
    let src_dir = temp_dir.path().join("src");
    fs::create_dir_all(&src_dir).unwrap();

    let mut content = String::new();
    content.push_str("# File with very large classes\n\n");

    // Create a class with many methods
    content.push_str("class MegaClass:\n");
    content.push_str("    \"\"\"A class with many methods.\"\"\"\n\n");

    // Add 500 methods
    for i in 0..500 {
        content.push_str(&format!(
            r#"    def method_{i}(self):
        """Method number {i}"""
        return {i}

"#
        ));
    }

    // Add 500 class methods
    for i in 0..500 {
        content.push_str(&format!(
            r#"    @classmethod
    def class_method_{i}(cls):
        """Class method number {i}"""
        return {i}

"#
        ));
    }

    // Create instance and use some methods
    content.push_str("\n\ndef test_mega_class():\n");
    content.push_str("    obj = MegaClass()\n");
    for i in 0..10 {
        content.push_str(&format!("    obj.method_{i}()\n"));
        content.push_str(&format!("    MegaClass.class_method_{i}()\n"));
    }

    fs::write(src_dir.join("large_classes.py"), content).unwrap();

    let output = std::process::Command::new(env!("CARGO_BIN_EXE_context-creator"))
        .arg(&src_dir)
        .arg("--include-callers")
        .output()
        .expect("Failed to execute context-creator");

    assert!(output.status.success(), "Should handle large classes");
}

/// Test Python with extremely deep nesting
#[test]
fn test_python_deep_nesting() {
    let temp_dir = TempDir::new().unwrap();
    let src_dir = temp_dir.path().join("src");

    // Create deeply nested package structure
    let mut current_dir = src_dir.clone();
    let depth = 20;

    for i in 0..depth {
        current_dir = current_dir.join(format!("level{i}"));
        fs::create_dir_all(&current_dir).unwrap();

        // Add __init__.py
        fs::write(
            current_dir.join("__init__.py"),
            format!(
                r#"
"""Level {i} package"""
from .module import func_{i}
"#
            ),
        )
        .unwrap();

        // Add module.py
        fs::write(
            current_dir.join("module.py"),
            format!(
                r#"
def func_{i}():
    """Function at level {i}"""
    return {i}
"#
            ),
        )
        .unwrap();
    }

    // Create main file that imports from deep nesting
    fs::write(
        src_dir.join("main.py"),
        r#"
# Import from deeply nested module
from level0.level1.level2.level3.module import func_3

def main():
    result = func_3()
    print(f"Result from deep import: {result}")

if __name__ == "__main__":
    main()
"#,
    )
    .unwrap();

    let output = std::process::Command::new(env!("CARGO_BIN_EXE_context-creator"))
        .arg(&src_dir)
        .arg("--trace-imports")
        .output()
        .expect("Failed to execute context-creator");

    assert!(output.status.success(), "Should handle deep nesting");
}

/// Test Python with mixed file types
#[test]
fn test_python_mixed_files() {
    let temp_dir = TempDir::new().unwrap();
    let src_dir = temp_dir.path().join("src");
    fs::create_dir_all(&src_dir).unwrap();

    // Regular Python file
    fs::write(
        src_dir.join("regular.py"),
        r#"
def regular_function():
    return "regular"
"#,
    )
    .unwrap();

    // Python file with .pyw extension (Windows GUI scripts)
    fs::write(
        src_dir.join("gui_script.pyw"),
        r#"
import tkinter as tk

def create_window():
    root = tk.Tk()
    return root
"#,
    )
    .unwrap();

    // Cython-like file (though not compiled)
    fs::write(
        src_dir.join("cython_module.pyx"),
        r#"
# This would be Cython code
def fast_function(int x):
    cdef int result = x * 2
    return result
"#,
    )
    .unwrap();

    // Python stub file
    fs::write(
        src_dir.join("stubs.pyi"),
        r#"
# Type stub file
def typed_function(x: int) -> str: ...

class TypedClass:
    def method(self) -> None: ...
"#,
    )
    .unwrap();

    // Setup.py
    fs::write(
        src_dir.join("setup.py"),
        r#"
from setuptools import setup, find_packages

setup(
    name="test-package",
    version="0.1.0",
    packages=find_packages(),
)
"#,
    )
    .unwrap();

    // __main__.py for package execution
    fs::write(
        src_dir.join("__main__.py"),
        r#"
from regular import regular_function

if __name__ == "__main__":
    print(regular_function())
"#,
    )
    .unwrap();

    let output = std::process::Command::new(env!("CARGO_BIN_EXE_context-creator"))
        .arg(&src_dir)
        .arg("--trace-imports")
        .output()
        .expect("Failed to execute context-creator");

    assert!(output.status.success());
}

/// Test Python with various string types and formats
#[test]
fn test_python_string_complexity() {
    let temp_dir = TempDir::new().unwrap();
    let src_dir = temp_dir.path().join("src");
    fs::create_dir_all(&src_dir).unwrap();

    fs::write(
        src_dir.join("strings.py"),
        r#"
# Various string formats and edge cases

# Triple quoted strings with quotes inside
sql_query = """
SELECT * FROM users
WHERE name = 'John' AND status = "active"
AND description = '''multiple quotes'''
"""

# Raw strings with backslashes
regex_pattern = r"C:\Users\(?P<username>\w+)\Documents\.*\.txt"
raw_multiline = r"""
Line 1\n is literal
Line 2\t has literal tabs
"""

# F-strings with complex expressions
name = "Alice"
age = 30
complex_fstring = f"""
User: {name.upper()}
Age in months: {age * 12}
Is adult: {age >= 18}
Nested: {f"Hello {name}"}
Expression: {[x**2 for x in range(5)]}
"""

# Unicode strings
unicode_art = """
╔═══════════════╗
║   Unicode Box ║
╚═══════════════╝
"""

# String with embedded code-like content
code_in_string = '''
def fake_function():
    # This looks like code but it's a string
    import os
    return "not real code"
'''

# Docstring that looks like it has imports
def tricky_function():
    """
    This function does something.
    
    Example:
        >>> import sys
        >>> from collections import defaultdict
        >>> tricky_function()
    
    Note: The above imports are in a docstring, not real imports.
    """
    pass

# Byte strings
byte_data = b"Binary \x00\x01\x02 data"
byte_multiline = b"""
Multi-line
byte string
"""

# Format strings
old_style = "Hello %s, you are %d years old" % (name, age)
new_style = "Hello {}, you are {} years old".format(name, age)
template = "{name} is {age} years old".format(name=name, age=age)
"#,
    )
    .unwrap();

    let output = std::process::Command::new(env!("CARGO_BIN_EXE_context-creator"))
        .arg(&src_dir)
        .arg("--trace-imports")
        .output()
        .expect("Failed to execute context-creator");

    assert!(output.status.success(), "Should handle complex strings");
}

/// Test Python with concurrent/parallel patterns
#[test]
fn test_python_concurrency_patterns() {
    let temp_dir = TempDir::new().unwrap();
    let src_dir = temp_dir.path().join("src");
    fs::create_dir_all(&src_dir).unwrap();

    fs::write(
        src_dir.join("concurrency.py"),
        r#"
import asyncio
import threading
import multiprocessing
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from typing import List, Callable
import queue

# Threading example
class ThreadedWorker(threading.Thread):
    def __init__(self, task_queue: queue.Queue):
        super().__init__()
        self.task_queue = task_queue
        self.daemon = True
    
    def run(self):
        while True:
            task = self.task_queue.get()
            if task is None:
                break
            task()
            self.task_queue.task_done()

# Multiprocessing example
def process_worker(data):
    return sum(data)

def parallel_sum(data_chunks: List[List[int]]) -> int:
    with ProcessPoolExecutor() as executor:
        results = executor.map(process_worker, data_chunks)
        return sum(results)

# Asyncio patterns
async def fetch_data(session, url):
    # Simulated async fetch
    await asyncio.sleep(0.1)
    return f"Data from {url}"

async def fetch_many(urls: List[str]):
    tasks = []
    for url in urls:
        task = asyncio.create_task(fetch_data(None, url))
        tasks.append(task)
    
    results = await asyncio.gather(*tasks)
    return results

# Thread pool pattern
def thread_pool_example(functions: List[Callable]):
    with ThreadPoolExecutor(max_workers=4) as executor:
        futures = [executor.submit(func) for func in functions]
        results = [f.result() for f in futures]
        return results

# Lock and synchronization
class SharedCounter:
    def __init__(self):
        self._value = 0
        self._lock = threading.Lock()
    
    def increment(self):
        with self._lock:
            self._value += 1
    
    @property
    def value(self):
        with self._lock:
            return self._value

# Asyncio with threading
def run_async_in_thread(coro):
    def thread_target():
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            return loop.run_until_complete(coro)
        finally:
            loop.close()
    
    thread = threading.Thread(target=thread_target)
    thread.start()
    thread.join()
"#,
    )
    .unwrap();

    let output = std::process::Command::new(env!("CARGO_BIN_EXE_context-creator"))
        .arg(&src_dir)
        .arg("--trace-imports")
        .arg("--include-callers")
        .output()
        .expect("Failed to execute context-creator");

    assert!(output.status.success());
}