Skip to content

API Reference

Main Module

load_config(root_dir)

Carica la configurazione dal file .deepbase.toml. Ritorna: (config, toml_found, user_ignore_dirs, user_ignore_files)

Source code in src/deepbase/main.py
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
def load_config(root_dir: str) -> Tuple[Dict[str, Any], bool, List[str], List[str]]:
    """
    Carica la configurazione dal file .deepbase.toml.
    Ritorna: (config, toml_found, user_ignore_dirs, user_ignore_files)
    """
    config_path = os.path.join(root_dir, ".deepbase.toml")
    config = DEFAULT_CONFIG.copy()
    config["ignore_dirs"] = set(config["ignore_dirs"])
    config["ignore_files"] = set(config["ignore_files"])
    config["significant_extensions"] = set(config["significant_extensions"])

    toml_found = False
    user_ignore_dirs = []
    user_ignore_files = []

    # DEBUG: stampa dove stiamo cercando
    console.print(f"[dim]  Looking for config at: {config_path}[/dim]")
    console.print(f"[dim]  Absolute path: {os.path.abspath(config_path)}[/dim]")
    console.print(f"[dim]  File exists: {os.path.exists(config_path)}[/dim]")

    if os.path.exists(config_path):
        toml_found = True
        try:
            with open(config_path, "rb") as f:
                user_config = tomli.load(f)

            # Salva le configurazioni utente prima di mergiarle
            user_dirs = user_config.get("ignore_dirs", [])
            user_files = user_config.get("ignore_files", [])
            user_ignore_dirs.extend(user_dirs)
            user_ignore_files.extend(user_files)

            # Merge con i default
            config["ignore_dirs"].update(user_dirs)
            config["ignore_files"].update(user_files)
            config["significant_extensions"].update(user_config.get("significant_extensions", []))

        except tomli.TOMLDecodeError as e:
            console.print(f"[bold yellow]Warning:[/bold yellow] Error parsing '.deepbase.toml': {e}")

    return config, toml_found, user_ignore_dirs, user_ignore_files

main(target=typer.Argument(None, help='The file or directory to scan.'), help=typer.Option(False, '--help', '-h', is_eager=True, help='Show this help message and exit.'), version=typer.Option(None, '--version', '-v', callback=version_callback, is_eager=True, help='Show version and exit.'), output=typer.Option('llm_context.md', '--output', '-o', help='The output file.'), verbose=typer.Option(False, '--verbose', '-V', help='Show detailed output.'), include_all=typer.Option(False, '--all', '-a', help='Include full content of ALL files.'), light_mode=typer.Option(False, '--light', '-l', help='Token-saving mode (signatures only).'), focus=typer.Option(None, '--focus', '-f', help='Pattern to focus on (repeatable).'), focus_file=typer.Option(None, '--focus-file', '-ff', help='Path to focus patterns file.'))

Analyzes a directory OR a single file. Default: structure tree only.

Source code in src/deepbase/main.py
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
def main(
    target: str = typer.Argument(None, help="The file or directory to scan."),
    help: bool = typer.Option(False, "--help", "-h", is_eager=True, help="Show this help message and exit."),
    version: Optional[bool] = typer.Option(None, "--version", "-v", callback=version_callback, is_eager=True, help="Show version and exit."),
    output: str = typer.Option("llm_context.md", "--output", "-o", help="The output file."),
    verbose: bool = typer.Option(False, "--verbose", "-V", help="Show detailed output."),
    include_all: bool = typer.Option(False, "--all", "-a", help="Include full content of ALL files."),
    light_mode: bool = typer.Option(False, "--light", "-l", help="Token-saving mode (signatures only)."),
    focus: Optional[List[str]] = typer.Option(None, "--focus", "-f", help="Pattern to focus on (repeatable)."),
    focus_file: Optional[str] = typer.Option(None, "--focus-file", "-ff", help="Path to focus patterns file.")
):
    """
    Analyzes a directory OR a single file.
    Default: structure tree only.
    """
    # 1. Custom HELP Logic
    if help or target is None:
        console.print(Panel.fit(
            "[bold cyan]DeepBase[/bold cyan] — Consolidate project context for LLMs\n\n"
            "[bold]Usage:[/bold] [green]deepbase[/green] [OPTIONS] [TARGET]\n\n"
            "[bold]Arguments:[/bold]\n"
            "  [cyan]TARGET[/cyan]  The file or directory to scan  [dim][default: current dir][/dim]\n",
            title="DeepBase v1.7.0", border_style="cyan"
        ))

        # Options Table
        options_table = Table(show_header=False, box=None, padding=(0, 2))
        options_table.add_column(style="cyan", no_wrap=True)
        options_table.add_column(style="green", no_wrap=True)
        options_table.add_column()

        options = [
            ("-v, --version", "", "Show version and exit"),
            ("-o, --output", "TEXT", "Output file [dim][default: llm_context.md][/dim]"),
            ("-V, --verbose", "", "Show detailed output"),
            ("-a, --all", "", "Include full content of ALL files"),
            ("-l, --light", "", "Token-saving mode (signatures only)"),
            ("-f, --focus", "TEXT", "Pattern to focus on (repeatable)"),
            ("-ff, --focus-file", "TEXT", "Path to focus patterns file"),
            ("-h, --help", "", "Show this message and exit"),
        ]
        for opt, meta, desc in options:
            options_table.add_row(opt, meta, desc)

        console.print(Panel(options_table, title="Options", border_style="green", title_align="left"))

        config_content = """Create a [cyan].deepbase.toml[/cyan] in your project root:

[dim]# Ignore additional directories (names or relative paths)[/dim]
[yellow]ignore_dirs = ["my_assets", "app/templates", "experimental"][/yellow]

[dim]# Ignore specific files (names, wildcards, or relative paths)[/dim]
[yellow]ignore_files = ["*.log", "secrets.env", "app/config/local.env"][/yellow]

[dim]# Add extra file extensions[/dim]
[yellow]significant_extensions = [".cfg", "Makefile", ".tsx"][/yellow]"""

        console.print(Panel(
            config_content,
            title="Configuration (.deepbase.toml)", 
            border_style="yellow",
            title_align="left"
        ))

        links_table = Table(show_header=False, box=None, padding=(0, 2))
        links_table.add_column(style="bold")
        links_table.add_column(style="blue")

        links_table.add_row("Documentation:", "https://follen99.github.io/DeepBase/")
        links_table.add_row("Repository:", "https://github.com/follen99/DeepBase")
        links_table.add_row("Issues:", "https://github.com/follen99/DeepBase/issues")
        links_table.add_row("PyPI:", "https://pypi.org/project/deepbase/")

        console.print(Panel(links_table, title="Links", border_style="blue", title_align="left"))

        raise typer.Exit()

    # 2. Main Logic Start
    if not os.path.exists(target):
        console.print(f"[bold red]Error:[/bold red] Target not found: '{target}'")
        raise typer.Exit(code=1)

    abs_output_path = os.path.abspath(output)

    active_focus_patterns = []
    if focus: active_focus_patterns.extend(focus)
    if focus_file:
        file_patterns = load_focus_patterns_from_file(focus_file)
        if file_patterns: active_focus_patterns.extend(file_patterns)
    active_focus_patterns = list(set(active_focus_patterns))

    mode_label = ""
    if light_mode:
        mode_label = " [bold yellow](LIGHT — signatures only)[/bold yellow]"
    elif include_all:
        mode_label = " [bold cyan](ALL — full content)[/bold cyan]"

    # Carica configurazione e stampa info
    if os.path.isdir(target):
        config, toml_found, user_ignore_dirs, user_ignore_files = load_config(target)
        print_config_info(toml_found, user_ignore_dirs, user_ignore_files)
    else:
        # Per singoli file, carica comunque la config dalla directory parent
        parent_dir = os.path.dirname(os.path.abspath(target)) or "."
        config, toml_found, user_ignore_dirs, user_ignore_files = load_config(parent_dir)
        if toml_found:
            print_config_info(toml_found, user_ignore_dirs, user_ignore_files)

    console.print(f"[bold green]Analyzing '{target}'...[/bold green]{mode_label}")

    if light_mode:
        def fmt_header(title): return f"### {title}\n\n"
        def fmt_file_start(path, icon=""): return f"> FILE: {icon}{path}\n"
        def fmt_file_end(path): return "\n"
        def fmt_separator(): return ""
    else:
        def fmt_header(title): return f"{'='*80}\n### {title} ###\n{'='*80}\n\n"
        def fmt_file_start(path, icon=""): return f"--- START OF FILE: {icon}{path} ---\n\n"
        def fmt_file_end(path): return f"\n\n--- END OF FILE: {path} ---\n"
        def fmt_separator(): return "-" * 40 + "\n\n"

    try:
        with open(output, "w", encoding="utf-8") as outfile:
            # CASO 1: Singolo file
            if os.path.isfile(target):
                filename = os.path.basename(target)
                is_db = is_sqlite_database(target)
                outfile.write(f"# Analysis: {filename}\n\n")
                if light_mode:
                    outfile.write(LIGHT_MODE_NOTICE + "\n")

                if is_db:
                    schema = get_database_schema(target)
                    focused_tables = extract_focused_tables(target, active_focus_patterns)
                    is_focused = bool(focused_tables) or (active_focus_patterns and any(
                        fnmatch.fnmatch(filename, p) or p in filename for p in active_focus_patterns
                    ))
                    outfile.write(fmt_header("DATABASE SCHEMA"))
                    if light_mode and not is_focused:
                        outfile.write(generate_light_representation(target, ""))
                    elif focused_tables:
                        outfile.write(generate_database_focused(target, focused_tables))
                    else:
                        outfile.write(generate_database_context_full(schema, filename))
                else:
                    content = read_file_content(target)
                    structure = get_document_structure(target, content)
                    outfile.write(fmt_header("STRUCTURE"))
                    outfile.write(structure or "N/A")
                    outfile.write("\n\n")
                    outfile.write(fmt_header("CONTENT"))
                    outfile.write(fmt_file_start(filename))
                    if light_mode:
                        outfile.write(generate_light_representation(target, content))
                    else:
                        outfile.write(content)
                    outfile.write(fmt_file_end(filename))

            # CASO 2: Directory
            elif os.path.isdir(target):
                outfile.write(f"# Project Context: {os.path.basename(os.path.abspath(target))}\n\n")
                if light_mode:
                    outfile.write(LIGHT_MODE_NOTICE + "\n")
                outfile.write(fmt_header("PROJECT STRUCTURE"))

                tree_str, total_bytes, total_tokens = generate_directory_tree(target, config, abs_output_path, light_mode=light_mode)

                if light_mode:
                    outfile.write(f"> Total Size (raw): {total_bytes/1024:.2f} KB | Est. Tokens (light): ~{total_tokens:,}\n")
                else:
                    outfile.write(f"> Total Size: {total_bytes/1024:.2f} KB | Est. Tokens: ~{total_tokens:,}\n")

                outfile.write(tree_str)
                outfile.write("\n\n")

                if include_all or light_mode or active_focus_patterns:
                    section_title = "FILE CONTENTS"
                    if light_mode: section_title += " (LIGHT — signatures only)"
                    outfile.write(fmt_header(section_title))
                    files = get_all_significant_files(target, config, abs_output_path)

                    with Progress(console=console) as progress:
                        task = progress.add_task("[cyan]Processing...", total=len(files))
                        for fpath in files:
                            rel_path = os.path.relpath(fpath, target).replace('\\', '/')
                            is_db = is_sqlite_database(fpath)
                            is_in_focus = active_focus_patterns and matches_focus(fpath, target, active_focus_patterns)
                            focused_tables = []
                            if is_db:
                                focused_tables = extract_focused_tables(fpath, active_focus_patterns)
                                if focused_tables: is_in_focus = True

                            should_write_full = include_all or is_in_focus
                            should_write_light = light_mode and not should_write_full

                            if not should_write_full and not should_write_light:
                                progress.update(task, advance=1)
                                continue

                            progress.update(task, advance=1, description=f"[cyan]{rel_path}[/cyan]")
                            marker = " [FOCUSED]" if (is_in_focus and light_mode) else ""
                            icon = "🗄️ " if is_db else ""
                            outfile.write(fmt_file_start(rel_path + marker, icon))

                            if is_db:
                                if should_write_full:
                                    if focused_tables:
                                        outfile.write(generate_database_focused(fpath, focused_tables))
                                    else:
                                        schema = get_database_schema(fpath)
                                        outfile.write(generate_database_context_full(schema, os.path.basename(fpath)))
                                else:
                                    outfile.write(generate_light_representation(fpath, ""))
                            else:
                                content = read_file_content(fpath)
                                if should_write_full:
                                    outfile.write(content)
                                elif should_write_light:
                                    light_output = generate_light_representation(fpath, content)
                                    outfile.write(light_output)

                            outfile.write(fmt_file_end(rel_path))
                            outfile.write(fmt_separator())
                else:
                    console.print("[dim]Directory tree generated. Use --light, --all, or --focus for content.[/dim]")

        console.print(f"\n[bold green]✔ SUCCESS[/bold green]: Context created in [cyan]'{output}'[/cyan]")

    except Exception as e:
        console.print(f"\n[bold red]Error:[/bold red] {e}")
        raise typer.Exit(code=1)

print_config_info(toml_found, user_ignore_dirs, user_ignore_files)

Stampa informazioni sulla configurazione caricata.

Source code in src/deepbase/main.py
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
def print_config_info(toml_found: bool, user_ignore_dirs: List[str], user_ignore_files: List[str]):
    """
    Stampa informazioni sulla configurazione caricata.
    """
    if toml_found:
        console.print(f"[bold green]✓[/bold green] Configuration file [cyan].deepbase.toml[/cyan] loaded")

        if user_ignore_dirs:
            dirs_str = ", ".join(f"[yellow]{d}[/yellow]" for d in user_ignore_dirs)
            console.print(f"  [dim]Ignored directories:[/dim] {dirs_str}")

        if user_ignore_files:
            files_str = ", ".join(f"[yellow]{f}[/yellow]" for f in user_ignore_files)
            console.print(f"  [dim]Ignored files:[/dim] {files_str}")

        if not user_ignore_dirs and not user_ignore_files:
            console.print("  [dim]No custom ignore patterns defined[/dim]")
    else:
        console.print(f"[dim]ℹ No .deepbase.toml found, using default configuration[/dim]")
        console.print(f"  [dim]Default ignored directories: {len(DEFAULT_CONFIG['ignore_dirs'])} patterns[/dim]")
        console.print(f"  [dim]Default ignored files: {len(DEFAULT_CONFIG['ignore_files'])} patterns[/dim]")