reposnap 0.3.1__py3-none-any.whl → 0.4.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.
- reposnap/__init__.py +0 -4
- reposnap/controllers/__init__.py +0 -0
- reposnap/controllers/project_controller.py +96 -0
- reposnap/core/file_system.py +8 -6
- reposnap/core/git_repo.py +11 -8
- reposnap/core/markdown_generator.py +18 -15
- reposnap/interfaces/cli.py +4 -25
- reposnap/interfaces/gui.py +155 -0
- reposnap/models/__init__.py +0 -0
- reposnap/models/file_tree.py +78 -0
- reposnap/utils/path_utils.py +7 -3
- reposnap-0.4.0.dist-info/METADATA +124 -0
- reposnap-0.4.0.dist-info/RECORD +19 -0
- reposnap-0.4.0.dist-info/entry_points.txt +3 -0
- reposnap/core/collector.py +0 -64
- reposnap-0.3.1.dist-info/METADATA +0 -88
- reposnap-0.3.1.dist-info/RECORD +0 -15
- reposnap-0.3.1.dist-info/entry_points.txt +0 -2
- {reposnap-0.3.1.dist-info → reposnap-0.4.0.dist-info}/WHEEL +0 -0
- {reposnap-0.3.1.dist-info → reposnap-0.4.0.dist-info}/licenses/LICENSE +0 -0
reposnap/__init__.py
CHANGED
File without changes
|
@@ -0,0 +1,96 @@
|
|
1
|
+
# src/reposnap/controllers/project_controller.py
|
2
|
+
|
3
|
+
import logging
|
4
|
+
from pathlib import Path
|
5
|
+
from reposnap.core.git_repo import GitRepo
|
6
|
+
from reposnap.core.file_system import FileSystem
|
7
|
+
from reposnap.core.markdown_generator import MarkdownGenerator
|
8
|
+
from reposnap.models.file_tree import FileTree
|
9
|
+
import pathspec
|
10
|
+
from typing import List, Optional
|
11
|
+
|
12
|
+
|
13
|
+
class ProjectController:
|
14
|
+
def __init__(self, args: Optional[object] = None):
|
15
|
+
self.logger = logging.getLogger(__name__)
|
16
|
+
self.root_dir: Path = Path(args.path).resolve() if args else Path('.').resolve()
|
17
|
+
self.output_file: Path = Path(args.output).resolve() if args else Path('output.md').resolve()
|
18
|
+
self.structure_only: bool = args.structure_only if args else False
|
19
|
+
self.args: object = args
|
20
|
+
self.file_tree: Optional[FileTree] = None
|
21
|
+
self.gitignore_patterns: List[str] = []
|
22
|
+
if self.root_dir:
|
23
|
+
self.gitignore_patterns = self._load_gitignore_patterns()
|
24
|
+
|
25
|
+
def set_root_dir(self, root_dir: Path) -> None:
|
26
|
+
self.root_dir = root_dir
|
27
|
+
self.gitignore_patterns = self._load_gitignore_patterns()
|
28
|
+
|
29
|
+
def get_file_tree(self) -> Optional[FileTree]:
|
30
|
+
return self.file_tree
|
31
|
+
|
32
|
+
def run(self) -> None:
|
33
|
+
self.collect_file_tree()
|
34
|
+
self.apply_filters()
|
35
|
+
self.generate_output()
|
36
|
+
|
37
|
+
def collect_file_tree(self) -> None:
|
38
|
+
self.logger.info("Collecting git files.")
|
39
|
+
git_repo: GitRepo = GitRepo(self.root_dir)
|
40
|
+
git_files: List[Path] = git_repo.get_git_files()
|
41
|
+
self.logger.debug(f"Git files before filtering: {git_files}")
|
42
|
+
|
43
|
+
self.logger.info("Building tree structure.")
|
44
|
+
file_system: FileSystem = FileSystem(self.root_dir)
|
45
|
+
tree_structure: dict = file_system.build_tree_structure(git_files)
|
46
|
+
|
47
|
+
self.file_tree = FileTree(tree_structure)
|
48
|
+
self.logger.debug(f"Tree structure: {self.file_tree.structure}")
|
49
|
+
|
50
|
+
def apply_filters(self) -> None:
|
51
|
+
self.logger.info("Applying filters to the file tree.")
|
52
|
+
spec: pathspec.PathSpec = pathspec.PathSpec.from_lines(pathspec.patterns.GitWildMatchPattern, self.gitignore_patterns)
|
53
|
+
self.logger.debug(f"Filter patterns: {self.gitignore_patterns}")
|
54
|
+
self.file_tree.filter_files(spec)
|
55
|
+
|
56
|
+
def generate_output(self) -> None:
|
57
|
+
self.logger.info("Starting markdown generation.")
|
58
|
+
markdown_generator: MarkdownGenerator = MarkdownGenerator(
|
59
|
+
root_dir=self.root_dir,
|
60
|
+
output_file=self.output_file,
|
61
|
+
structure_only=self.structure_only
|
62
|
+
)
|
63
|
+
markdown_generator.generate_markdown(self.file_tree.structure, self.file_tree.get_all_files())
|
64
|
+
self.logger.info(f"Markdown generated at {self.output_file}.")
|
65
|
+
|
66
|
+
def generate_output_from_selected(self, selected_files: set) -> None:
|
67
|
+
self.logger.info("Generating markdown from selected files.")
|
68
|
+
# Build a pruned tree structure based on selected files
|
69
|
+
pruned_tree = self.file_tree.prune_tree(selected_files)
|
70
|
+
markdown_generator: MarkdownGenerator = MarkdownGenerator(
|
71
|
+
root_dir=self.root_dir,
|
72
|
+
output_file=self.output_file,
|
73
|
+
structure_only=False,
|
74
|
+
hide_untoggled=True
|
75
|
+
)
|
76
|
+
markdown_generator.generate_markdown(pruned_tree, [Path(f) for f in selected_files])
|
77
|
+
self.logger.info(f"Markdown generated at {self.output_file}.")
|
78
|
+
|
79
|
+
def _load_gitignore_patterns(self) -> List[str]:
|
80
|
+
gitignore_path: Path = self.root_dir / '.gitignore'
|
81
|
+
if not gitignore_path.exists():
|
82
|
+
for parent in self.root_dir.parents:
|
83
|
+
gitignore_path = parent / '.gitignore'
|
84
|
+
if gitignore_path.exists():
|
85
|
+
break
|
86
|
+
else:
|
87
|
+
gitignore_path = None
|
88
|
+
|
89
|
+
if gitignore_path and gitignore_path.exists():
|
90
|
+
with gitignore_path.open('r') as gitignore:
|
91
|
+
patterns: List[str] = gitignore.readlines()
|
92
|
+
self.logger.debug(f"Patterns from .gitignore in {gitignore_path.parent}: {patterns}")
|
93
|
+
return patterns
|
94
|
+
else:
|
95
|
+
self.logger.debug(f"No .gitignore found starting from {self.root_dir}. Proceeding without patterns.")
|
96
|
+
return []
|
reposnap/core/file_system.py
CHANGED
@@ -2,29 +2,31 @@
|
|
2
2
|
|
3
3
|
import logging
|
4
4
|
from pathlib import Path
|
5
|
+
from typing import List, Dict, Any
|
6
|
+
|
5
7
|
|
6
8
|
class FileSystem:
|
7
9
|
def __init__(self, root_dir: Path):
|
8
|
-
self.root_dir = root_dir.resolve()
|
10
|
+
self.root_dir: Path = root_dir.resolve()
|
9
11
|
self.logger = logging.getLogger(__name__)
|
10
12
|
|
11
|
-
def build_tree_structure(self, files):
|
13
|
+
def build_tree_structure(self, files: List[Path]) -> Dict[str, Any]:
|
12
14
|
"""
|
13
15
|
Builds a hierarchical tree structure from the list of files.
|
14
16
|
|
15
17
|
Args:
|
16
|
-
files (
|
18
|
+
files (List[Path]): List of file paths relative to root_dir.
|
17
19
|
|
18
20
|
Returns:
|
19
|
-
|
21
|
+
Dict[str, Any]: Nested dictionary representing the directory structure.
|
20
22
|
"""
|
21
|
-
tree = {}
|
23
|
+
tree: Dict[str, Any] = {}
|
22
24
|
self.logger.debug("Building tree structure.")
|
23
25
|
for relative_path in files:
|
24
26
|
parts = relative_path.parts
|
25
27
|
current_level = tree
|
26
28
|
for part in parts[:-1]:
|
27
29
|
current_level = current_level.setdefault(part, {})
|
28
|
-
current_level[parts[-1]] =
|
30
|
+
current_level[parts[-1]] = None # Indicate a file node
|
29
31
|
self.logger.debug(f"Tree structure built: {tree}")
|
30
32
|
return tree
|
reposnap/core/git_repo.py
CHANGED
@@ -3,23 +3,25 @@
|
|
3
3
|
import logging
|
4
4
|
from pathlib import Path
|
5
5
|
from git import Repo, InvalidGitRepositoryError
|
6
|
+
from typing import List
|
7
|
+
|
6
8
|
|
7
9
|
class GitRepo:
|
8
10
|
def __init__(self, repo_path: Path):
|
9
|
-
self.repo_path = repo_path.resolve()
|
11
|
+
self.repo_path: Path = repo_path.resolve()
|
10
12
|
self.logger = logging.getLogger(__name__)
|
11
13
|
|
12
|
-
def get_git_files(self):
|
14
|
+
def get_git_files(self) -> List[Path]:
|
13
15
|
try:
|
14
|
-
repo = Repo(self.repo_path, search_parent_directories=True)
|
15
|
-
repo_root = Path(repo.working_tree_dir).resolve()
|
16
|
-
git_files = repo.git.ls_files().splitlines()
|
16
|
+
repo: Repo = Repo(self.repo_path, search_parent_directories=True)
|
17
|
+
repo_root: Path = Path(repo.working_tree_dir).resolve()
|
18
|
+
git_files: List[str] = repo.git.ls_files().splitlines()
|
17
19
|
self.logger.debug(f"Git files from {repo_root}: {git_files}")
|
18
|
-
git_files_relative = []
|
20
|
+
git_files_relative: List[Path] = []
|
19
21
|
for f in git_files:
|
20
|
-
absolute_path = (repo_root / f).resolve()
|
22
|
+
absolute_path: Path = (repo_root / f).resolve()
|
21
23
|
try:
|
22
|
-
relative_path = absolute_path.relative_to(self.repo_path)
|
24
|
+
relative_path: Path = absolute_path.relative_to(self.repo_path)
|
23
25
|
git_files_relative.append(relative_path)
|
24
26
|
except ValueError:
|
25
27
|
# Skip files not under root_dir
|
@@ -28,3 +30,4 @@ class GitRepo:
|
|
28
30
|
except InvalidGitRepositoryError:
|
29
31
|
self.logger.error(f"Invalid Git repository at: {self.repo_path}")
|
30
32
|
return []
|
33
|
+
|
@@ -2,28 +2,31 @@
|
|
2
2
|
|
3
3
|
import logging
|
4
4
|
from pathlib import Path
|
5
|
-
from
|
5
|
+
from reposnap.utils.path_utils import format_tree
|
6
|
+
from typing import List, Dict, Any
|
7
|
+
|
6
8
|
|
7
9
|
class MarkdownGenerator:
|
8
|
-
def __init__(self, root_dir: Path, output_file: Path, structure_only: bool = False):
|
9
|
-
self.root_dir = root_dir.resolve()
|
10
|
-
self.output_file = output_file.resolve()
|
11
|
-
self.structure_only = structure_only
|
10
|
+
def __init__(self, root_dir: Path, output_file: Path, structure_only: bool = False, hide_untoggled: bool = False):
|
11
|
+
self.root_dir: Path = root_dir.resolve()
|
12
|
+
self.output_file: Path = output_file.resolve()
|
13
|
+
self.structure_only: bool = structure_only
|
14
|
+
self.hide_untoggled: bool = hide_untoggled
|
12
15
|
self.logger = logging.getLogger(__name__)
|
13
16
|
|
14
|
-
def generate_markdown(self, tree_structure:
|
17
|
+
def generate_markdown(self, tree_structure: Dict[str, Any], files: List[Path]) -> None:
|
15
18
|
"""
|
16
19
|
Generates the Markdown file based on the provided tree structure and files.
|
17
20
|
|
18
21
|
Args:
|
19
|
-
tree_structure (
|
20
|
-
files (
|
22
|
+
tree_structure (Dict[str, Any]): The hierarchical structure of the project files.
|
23
|
+
files (List[Path]): List of file paths to include in the markdown.
|
21
24
|
"""
|
22
25
|
self._write_header(tree_structure)
|
23
26
|
if not self.structure_only:
|
24
27
|
self._write_file_contents(files)
|
25
28
|
|
26
|
-
def _write_header(self, tree_structure:
|
29
|
+
def _write_header(self, tree_structure: Dict[str, Any]) -> None:
|
27
30
|
"""
|
28
31
|
Writes the header and project structure to the Markdown file.
|
29
32
|
"""
|
@@ -32,7 +35,7 @@ class MarkdownGenerator:
|
|
32
35
|
with self.output_file.open('w', encoding='utf-8') as f:
|
33
36
|
f.write("# Project Structure\n\n")
|
34
37
|
f.write("```\n")
|
35
|
-
for line in format_tree(tree_structure):
|
38
|
+
for line in format_tree(tree_structure, hide_untoggled=self.hide_untoggled):
|
36
39
|
f.write(line)
|
37
40
|
f.write("```\n\n")
|
38
41
|
self.logger.debug("Header and project structure written successfully.")
|
@@ -40,16 +43,16 @@ class MarkdownGenerator:
|
|
40
43
|
self.logger.error(f"Failed to write header to {self.output_file}: {e}")
|
41
44
|
raise
|
42
45
|
|
43
|
-
def _write_file_contents(self, files:
|
46
|
+
def _write_file_contents(self, files: List[Path]) -> None:
|
44
47
|
"""
|
45
48
|
Writes the contents of each file to the Markdown file.
|
46
49
|
|
47
50
|
Args:
|
48
|
-
files (
|
51
|
+
files (List[Path]): List of file paths relative to root_dir.
|
49
52
|
"""
|
50
53
|
self.logger.debug("Writing file contents to Markdown.")
|
51
54
|
for relative_path in files:
|
52
|
-
file_path = self.root_dir / relative_path
|
55
|
+
file_path: Path = self.root_dir / relative_path
|
53
56
|
|
54
57
|
if not file_path.exists():
|
55
58
|
self.logger.debug(f"File not found: {file_path}. Skipping.")
|
@@ -57,13 +60,13 @@ class MarkdownGenerator:
|
|
57
60
|
|
58
61
|
self._write_file_content(file_path, relative_path.as_posix())
|
59
62
|
|
60
|
-
def _write_file_content(self, file_path: Path, relative_path: str):
|
63
|
+
def _write_file_content(self, file_path: Path, relative_path: str) -> None:
|
61
64
|
"""
|
62
65
|
Writes the content of a single file to the Markdown file with syntax highlighting.
|
63
66
|
"""
|
64
67
|
try:
|
65
68
|
with file_path.open('r', encoding='utf-8') as f:
|
66
|
-
content = f.read()
|
69
|
+
content: str = f.read()
|
67
70
|
with self.output_file.open('a', encoding='utf-8') as f:
|
68
71
|
f.write(f"## {relative_path}\n\n")
|
69
72
|
f.write("```python\n" if file_path.suffix == '.py' else "```\n")
|
reposnap/interfaces/cli.py
CHANGED
@@ -2,14 +2,12 @@
|
|
2
2
|
|
3
3
|
import argparse
|
4
4
|
import logging
|
5
|
-
import
|
6
|
-
from reposnap.core.collector import ProjectContentCollector
|
7
|
-
from pathlib import Path
|
5
|
+
from reposnap.controllers.project_controller import ProjectController
|
8
6
|
|
9
7
|
|
10
8
|
def main():
|
11
9
|
parser = argparse.ArgumentParser(description='Generate a Markdown representation of a Git repository.')
|
12
|
-
parser.add_argument('path', help='Path to the Git repository or subdirectory.')
|
10
|
+
parser.add_argument('path', nargs='?', default='.', help='Path to the Git repository or subdirectory.')
|
13
11
|
parser.add_argument('-o', '--output', help='Output Markdown file', default='output.md')
|
14
12
|
parser.add_argument('--structure-only', action='store_true',
|
15
13
|
help='Only include the file structure without content.')
|
@@ -20,27 +18,8 @@ def main():
|
|
20
18
|
log_level = logging.DEBUG if args.debug else logging.INFO
|
21
19
|
logging.basicConfig(level=log_level, format='%(asctime)s - %(levelname)s - %(message)s')
|
22
20
|
|
23
|
-
|
24
|
-
|
25
|
-
if not gitignore_path.exists():
|
26
|
-
# Search for .gitignore in parent directories
|
27
|
-
for parent in path.parents:
|
28
|
-
gitignore_path = parent / '.gitignore'
|
29
|
-
if gitignore_path.exists():
|
30
|
-
break
|
31
|
-
else:
|
32
|
-
gitignore_path = None
|
33
|
-
|
34
|
-
if gitignore_path and gitignore_path.exists():
|
35
|
-
with gitignore_path.open('r') as gitignore:
|
36
|
-
patterns = gitignore.readlines()
|
37
|
-
logging.debug(f"Patterns from .gitignore in {gitignore_path.parent}: {patterns}")
|
38
|
-
else:
|
39
|
-
patterns = []
|
40
|
-
logging.debug(f"No .gitignore found starting from {args.path}. Proceeding without patterns.")
|
41
|
-
|
42
|
-
collector = ProjectContentCollector(str(path), args.output, args.structure_only, patterns)
|
43
|
-
collector.collect_and_generate()
|
21
|
+
controller = ProjectController(args)
|
22
|
+
controller.run()
|
44
23
|
|
45
24
|
if __name__ == "__main__":
|
46
25
|
main()
|
@@ -0,0 +1,155 @@
|
|
1
|
+
# src/reposnap/interfaces/gui.py
|
2
|
+
|
3
|
+
import urwid
|
4
|
+
from pathlib import Path
|
5
|
+
from reposnap.controllers.project_controller import ProjectController
|
6
|
+
|
7
|
+
|
8
|
+
class MyCheckBox(urwid.CheckBox):
|
9
|
+
def __init__(self, label, user_data=None, **kwargs):
|
10
|
+
super().__init__(label, **kwargs)
|
11
|
+
self.user_data = user_data
|
12
|
+
|
13
|
+
|
14
|
+
class RepoSnapGUI:
|
15
|
+
def __init__(self):
|
16
|
+
self.controller = ProjectController()
|
17
|
+
self.root_dir = Path('.').resolve()
|
18
|
+
self.file_tree = None
|
19
|
+
self.selected_files = set()
|
20
|
+
|
21
|
+
self.main_loop = None
|
22
|
+
self.build_main_menu()
|
23
|
+
|
24
|
+
def build_main_menu(self):
|
25
|
+
self.root_dir_edit = urwid.Edit(('bold', "Root Directory: "), str(self.root_dir))
|
26
|
+
scan_button = urwid.Button("Scan", on_press=self.on_scan)
|
27
|
+
|
28
|
+
main_menu = urwid.Frame(
|
29
|
+
header=urwid.Text(('bold', "RepoSnap - Main Menu")),
|
30
|
+
body=urwid.Padding(
|
31
|
+
urwid.LineBox(
|
32
|
+
urwid.ListBox(
|
33
|
+
urwid.SimpleFocusListWalker([
|
34
|
+
self.root_dir_edit
|
35
|
+
])
|
36
|
+
),
|
37
|
+
title="Enter Root Directory"
|
38
|
+
),
|
39
|
+
left=2, right=2
|
40
|
+
),
|
41
|
+
footer=urwid.Padding(scan_button, align='center')
|
42
|
+
)
|
43
|
+
|
44
|
+
self.main_widget = main_menu
|
45
|
+
|
46
|
+
def on_scan(self, button):
|
47
|
+
self.root_dir = Path(self.root_dir_edit.edit_text).resolve()
|
48
|
+
self.controller.set_root_dir(self.root_dir)
|
49
|
+
self.controller.collect_file_tree()
|
50
|
+
self.file_tree = self.controller.get_file_tree()
|
51
|
+
self.build_file_tree_menu()
|
52
|
+
|
53
|
+
def build_file_tree_menu(self):
|
54
|
+
tree_widgets = self.build_tree_widget(self.file_tree.structure)
|
55
|
+
tree_listbox = urwid.ListBox(urwid.SimpleFocusListWalker(tree_widgets))
|
56
|
+
render_button = urwid.Button("Render", on_press=self.on_render)
|
57
|
+
|
58
|
+
tree_menu = urwid.Frame(
|
59
|
+
header=urwid.Text(('bold', f"File Tree of {self.root_dir}")),
|
60
|
+
body=urwid.LineBox(tree_listbox),
|
61
|
+
footer=urwid.Padding(render_button, align='center')
|
62
|
+
)
|
63
|
+
|
64
|
+
self.main_widget = tree_menu
|
65
|
+
self.refresh()
|
66
|
+
|
67
|
+
def build_tree_widget(self, tree_structure, parent_path="", level=0):
|
68
|
+
widgets = []
|
69
|
+
for key, value in sorted(tree_structure.items()):
|
70
|
+
node_path = f"{parent_path}/{key}".lstrip('/')
|
71
|
+
checkbox = MyCheckBox(
|
72
|
+
key,
|
73
|
+
user_data={'path': node_path, 'level': level},
|
74
|
+
state=False,
|
75
|
+
on_state_change=self.on_checkbox_change
|
76
|
+
)
|
77
|
+
indented_checkbox = urwid.Padding(checkbox, left=4*level)
|
78
|
+
widgets.append(indented_checkbox)
|
79
|
+
if isinstance(value, dict):
|
80
|
+
widgets.extend(self.build_tree_widget(value, node_path, level=level+1))
|
81
|
+
return widgets
|
82
|
+
|
83
|
+
def on_checkbox_change(self, checkbox, state):
|
84
|
+
user_data = checkbox.user_data
|
85
|
+
node_path = user_data['path']
|
86
|
+
level = user_data['level']
|
87
|
+
if state:
|
88
|
+
self.selected_files.add(node_path)
|
89
|
+
else:
|
90
|
+
self.selected_files.discard(node_path)
|
91
|
+
# Handle toggling all children
|
92
|
+
self.toggle_children(checkbox, state, level)
|
93
|
+
|
94
|
+
def toggle_children(self, checkbox, state, level):
|
95
|
+
listbox = self.main_widget.body.original_widget.body
|
96
|
+
walker = listbox
|
97
|
+
# Find the index of the Padding widget that contains the checkbox
|
98
|
+
idx = None
|
99
|
+
for i, widget in enumerate(walker):
|
100
|
+
if isinstance(widget, urwid.Padding) and widget.original_widget == checkbox:
|
101
|
+
idx = i
|
102
|
+
break
|
103
|
+
if idx is None:
|
104
|
+
return
|
105
|
+
idx += 1
|
106
|
+
while idx < len(walker):
|
107
|
+
widget = walker[idx]
|
108
|
+
if isinstance(widget, urwid.Padding):
|
109
|
+
checkbox_widget = widget.original_widget
|
110
|
+
widget_user_data = checkbox_widget.user_data
|
111
|
+
widget_level = widget_user_data['level']
|
112
|
+
if widget_level > level:
|
113
|
+
checkbox_widget.set_state(state, do_callback=False)
|
114
|
+
node_path = widget_user_data['path']
|
115
|
+
if state:
|
116
|
+
self.selected_files.add(node_path)
|
117
|
+
else:
|
118
|
+
self.selected_files.discard(node_path)
|
119
|
+
idx += 1
|
120
|
+
else:
|
121
|
+
break
|
122
|
+
else:
|
123
|
+
idx += 1
|
124
|
+
|
125
|
+
def on_render(self, button):
|
126
|
+
self.controller.generate_output_from_selected(self.selected_files)
|
127
|
+
message = urwid.Text(('bold', f"Markdown generated at {self.controller.output_file}"))
|
128
|
+
exit_button = urwid.Button("Exit", on_press=self.exit_program)
|
129
|
+
result_menu = urwid.Frame(
|
130
|
+
header=urwid.Text(('bold', "Success")),
|
131
|
+
body=urwid.Filler(message, valign='middle'),
|
132
|
+
footer=urwid.Padding(exit_button, align='center')
|
133
|
+
)
|
134
|
+
self.main_widget = result_menu
|
135
|
+
self.refresh()
|
136
|
+
|
137
|
+
def refresh(self):
|
138
|
+
if self.main_loop:
|
139
|
+
self.main_loop.widget = self.main_widget
|
140
|
+
|
141
|
+
def exit_program(self, button):
|
142
|
+
raise urwid.ExitMainLoop()
|
143
|
+
|
144
|
+
def run(self):
|
145
|
+
self.main_loop = urwid.MainLoop(self.main_widget)
|
146
|
+
self.main_loop.run()
|
147
|
+
|
148
|
+
|
149
|
+
def main():
|
150
|
+
app = RepoSnapGUI()
|
151
|
+
app.run()
|
152
|
+
|
153
|
+
|
154
|
+
if __name__ == "__main__":
|
155
|
+
main()
|
File without changes
|
@@ -0,0 +1,78 @@
|
|
1
|
+
# src/reposnap/models/file_tree.py
|
2
|
+
|
3
|
+
import logging
|
4
|
+
from pathlib import Path
|
5
|
+
from typing import Dict, List, Any
|
6
|
+
import pathspec
|
7
|
+
|
8
|
+
|
9
|
+
class FileTree:
|
10
|
+
def __init__(self, structure: Dict[str, Any]):
|
11
|
+
self.structure: Dict[str, Any] = structure
|
12
|
+
self.logger = logging.getLogger(__name__)
|
13
|
+
|
14
|
+
def get_all_files(self) -> List[Path]:
|
15
|
+
"""
|
16
|
+
Recursively retrieve all file paths from the tree.
|
17
|
+
Returns:
|
18
|
+
List[Path]: List of file paths relative to root_dir.
|
19
|
+
"""
|
20
|
+
return self._extract_files(self.structure)
|
21
|
+
|
22
|
+
def _extract_files(self, subtree: Dict[str, Any], path_prefix: str = '') -> List[Path]:
|
23
|
+
files: List[Path] = []
|
24
|
+
for key, value in subtree.items():
|
25
|
+
current_path: str = f"{path_prefix}/{key}".lstrip('/')
|
26
|
+
if isinstance(value, dict):
|
27
|
+
files.extend(self._extract_files(value, current_path))
|
28
|
+
else:
|
29
|
+
files.append(Path(current_path))
|
30
|
+
return files
|
31
|
+
|
32
|
+
def filter_files(self, spec: pathspec.PathSpec) -> None:
|
33
|
+
"""
|
34
|
+
Filters files in the tree structure based on the provided pathspec.
|
35
|
+
|
36
|
+
Args:
|
37
|
+
spec (pathspec.PathSpec): The pathspec for filtering files.
|
38
|
+
"""
|
39
|
+
self.logger.debug("Filtering files in the file tree.")
|
40
|
+
self.structure = self._filter_tree(self.structure, spec)
|
41
|
+
|
42
|
+
def _filter_tree(self, subtree: Dict[str, Any], spec: pathspec.PathSpec, path_prefix: str = '') -> Dict[str, Any]:
|
43
|
+
filtered_subtree: Dict[str, Any] = {}
|
44
|
+
for key, value in subtree.items():
|
45
|
+
current_path: str = f"{path_prefix}/{key}".lstrip('/')
|
46
|
+
if isinstance(value, dict):
|
47
|
+
filtered_value: Dict[str, Any] = self._filter_tree(value, spec, current_path)
|
48
|
+
if filtered_value:
|
49
|
+
filtered_subtree[key] = filtered_value
|
50
|
+
else:
|
51
|
+
if not spec.match_file(current_path):
|
52
|
+
filtered_subtree[key] = value
|
53
|
+
return filtered_subtree
|
54
|
+
|
55
|
+
def prune_tree(self, selected_files: set) -> Dict[str, Any]:
|
56
|
+
"""
|
57
|
+
Prunes the tree to include only the selected files and their directories.
|
58
|
+
|
59
|
+
Args:
|
60
|
+
selected_files (set): Set of selected file paths.
|
61
|
+
|
62
|
+
Returns:
|
63
|
+
Dict[str, Any]: Pruned tree structure.
|
64
|
+
"""
|
65
|
+
return self._prune_tree(self.structure, selected_files)
|
66
|
+
|
67
|
+
def _prune_tree(self, subtree: Dict[str, Any], selected_files: set, path_prefix: str = '') -> Dict[str, Any]:
|
68
|
+
pruned_subtree: Dict[str, Any] = {}
|
69
|
+
for key, value in subtree.items():
|
70
|
+
current_path: str = f"{path_prefix}/{key}".lstrip('/')
|
71
|
+
if isinstance(value, dict):
|
72
|
+
pruned_value: Dict[str, Any] = self._prune_tree(value, selected_files, current_path)
|
73
|
+
if pruned_value:
|
74
|
+
pruned_subtree[key] = pruned_value
|
75
|
+
else:
|
76
|
+
if current_path in selected_files:
|
77
|
+
pruned_subtree[key] = value
|
78
|
+
return pruned_subtree
|
reposnap/utils/path_utils.py
CHANGED
@@ -1,9 +1,13 @@
|
|
1
1
|
# src/reposnap/utils/path_utils.py
|
2
|
+
from typing import Dict, Generator, Any
|
2
3
|
|
3
|
-
|
4
|
+
|
5
|
+
def format_tree(tree: Dict[str, Any], indent: str = '', hide_untoggled: bool = False) -> Generator[str, None, None]:
|
4
6
|
for key, value in tree.items():
|
5
|
-
if
|
7
|
+
if value == '<hidden>':
|
8
|
+
yield f"{indent}<...>\n"
|
9
|
+
elif isinstance(value, dict):
|
6
10
|
yield f"{indent}{key}/\n"
|
7
|
-
yield from format_tree(value, indent + ' ')
|
11
|
+
yield from format_tree(value, indent + ' ', hide_untoggled)
|
8
12
|
else:
|
9
13
|
yield f"{indent}{key}\n"
|
@@ -0,0 +1,124 @@
|
|
1
|
+
Metadata-Version: 2.3
|
2
|
+
Name: reposnap
|
3
|
+
Version: 0.4.0
|
4
|
+
Summary: Generate a Markdown file with all contents of your project
|
5
|
+
Author: agoloborodko
|
6
|
+
License-File: LICENSE
|
7
|
+
Requires-Python: >=3.8
|
8
|
+
Requires-Dist: gitpython>=3.1.43
|
9
|
+
Requires-Dist: pathlib>=1.0.1
|
10
|
+
Requires-Dist: pathspec>=0.12.1
|
11
|
+
Requires-Dist: urwid>=2.6.15
|
12
|
+
Description-Content-Type: text/markdown
|
13
|
+
|
14
|
+
# RepoSnap
|
15
|
+
|
16
|
+
## Overview
|
17
|
+
|
18
|
+
`reposnap` is a Python tool designed to generate a Markdown file that documents the structure and contents of a Git project. It provides both a command-line interface (CLI) and a graphical user interface (GUI) for ease of use. This tool is particularly useful for creating a quick overview of a project's file hierarchy, including optional syntax-highlighted code snippets.
|
19
|
+
|
20
|
+
## Features
|
21
|
+
|
22
|
+
- **Command-Line Interface (CLI)**: Quickly generate documentation from the terminal.
|
23
|
+
- **Graphical User Interface (GUI)**: A user-friendly GUI if you want to select files and directories interactively.
|
24
|
+
- **Syntax Highlighting**: Includes syntax highlighting for known file types in the generated Markdown file.
|
25
|
+
- **Structure Only Option**: The `--structure-only` flag can be used to generate the Markdown file with just the directory structure, omitting the contents of the files.
|
26
|
+
- **Gitignore Support**: Automatically respects `.gitignore` patterns to exclude files and directories.
|
27
|
+
|
28
|
+
## Installation
|
29
|
+
|
30
|
+
You can install `reposnap` using pip:
|
31
|
+
|
32
|
+
```bash
|
33
|
+
pip install reposnap
|
34
|
+
```
|
35
|
+
|
36
|
+
Alternatively, you can clone the repository and install the required dependencies:
|
37
|
+
|
38
|
+
```bash
|
39
|
+
git clone https://github.com/username/reposnap.git
|
40
|
+
cd reposnap
|
41
|
+
pip install -r requirements.txt
|
42
|
+
```
|
43
|
+
|
44
|
+
## Usage
|
45
|
+
|
46
|
+
### Command-Line Interface
|
47
|
+
|
48
|
+
To use `reposnap` from the command line, run it with the following options:
|
49
|
+
|
50
|
+
```bash
|
51
|
+
reposnap [-h] [-o OUTPUT] [--structure-only] [--debug] path
|
52
|
+
```
|
53
|
+
|
54
|
+
- `path`: Path to the Git repository or subdirectory.
|
55
|
+
- `-h, --help`: Show help message and exit.
|
56
|
+
- `-o, --output`: The name of the output Markdown file. Defaults to `output.md`.
|
57
|
+
- `--structure-only`: Generate a Markdown file that includes only the project structure, without file contents.
|
58
|
+
- `--debug`: Enable debug-level logging.
|
59
|
+
|
60
|
+
#### Examples
|
61
|
+
|
62
|
+
1. **Generate a full project structure with file contents**:
|
63
|
+
|
64
|
+
```bash
|
65
|
+
reposnap .
|
66
|
+
```
|
67
|
+
|
68
|
+
2. **Generate a project structure only**:
|
69
|
+
|
70
|
+
```bash
|
71
|
+
reposnap my_project/ --structure-only
|
72
|
+
```
|
73
|
+
|
74
|
+
3. **Generate a Markdown file excluding certain files and directories**:
|
75
|
+
|
76
|
+
```bash
|
77
|
+
reposnap my_project/ -o output.md
|
78
|
+
```
|
79
|
+
|
80
|
+
### Graphical User Interface
|
81
|
+
|
82
|
+
`reposnap` also provides a GUI for users who prefer an interactive interface.
|
83
|
+
|
84
|
+
To launch the GUI, simply run:
|
85
|
+
|
86
|
+
```bash
|
87
|
+
reposnap-gui
|
88
|
+
```
|
89
|
+
|
90
|
+
#### Using the GUI
|
91
|
+
|
92
|
+
1. **Select Root Directory**: When the GUI opens, you can specify the root directory of your Git project. By default, it uses the current directory.
|
93
|
+
|
94
|
+
2. **Scan the Project**: Click the "Scan" button to analyze the project. The GUI will display the file tree of your project.
|
95
|
+
|
96
|
+
3. **Select Files and Directories**: Use the checkboxes to select which files and directories you want to include in the Markdown documentation. Toggling a directory checkbox will toggle all its child files and directories.
|
97
|
+
|
98
|
+
4. **Generate Markdown**: After selecting the desired files, click the "Render" button. The Markdown file will be generated and saved as `output.md` in the current directory.
|
99
|
+
|
100
|
+
5. **Exit**: Click the "Exit" button to close the GUI.
|
101
|
+
|
102
|
+
## Testing
|
103
|
+
|
104
|
+
To run the tests, use the following command:
|
105
|
+
|
106
|
+
```bash
|
107
|
+
pytest tests/
|
108
|
+
```
|
109
|
+
|
110
|
+
Ensure that you have the `pytest` library installed:
|
111
|
+
|
112
|
+
```bash
|
113
|
+
pip install pytest
|
114
|
+
```
|
115
|
+
|
116
|
+
## License
|
117
|
+
|
118
|
+
This project is licensed under the MIT License.
|
119
|
+
|
120
|
+
## Acknowledgments
|
121
|
+
|
122
|
+
- [GitPython](https://gitpython.readthedocs.io/) - Used for interacting with Git repositories.
|
123
|
+
- [pathspec](https://pathspec.readthedocs.io/) - Used for pattern matching file paths.
|
124
|
+
- [Urwid](https://urwid.org/) - Used for creating the GUI interface.
|
@@ -0,0 +1,19 @@
|
|
1
|
+
reposnap/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
2
|
+
reposnap/controllers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
3
|
+
reposnap/controllers/project_controller.py,sha256=JVxCc5MH_GOvEwTAaasuqxd1XSgKFbdQDjUEwmg4pUk,4211
|
4
|
+
reposnap/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
5
|
+
reposnap/core/file_system.py,sha256=82gwvmgrsWf63paMrIz-Z0eqIjbqt9_-vujdXlJJoFE,1074
|
6
|
+
reposnap/core/git_repo.py,sha256=2u_ILkV-Ur7qr1WHmHM2yg44Ggft61RsdbZLsZaQ5NU,1256
|
7
|
+
reposnap/core/markdown_generator.py,sha256=DkH7Gdo-fWevSyp9nqIyOG6qVOT6kk36xndR6X5vskM,3148
|
8
|
+
reposnap/interfaces/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
9
|
+
reposnap/interfaces/cli.py,sha256=fpJBTmGw8A8dVLdYEtERV7L2P-8lzBlmwIvD3NhTD-Q,985
|
10
|
+
reposnap/interfaces/gui.py,sha256=pzWQbW55gBNZu4tXRdBFic39upGtYxew91FSiEvalj0,5421
|
11
|
+
reposnap/models/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
12
|
+
reposnap/models/file_tree.py,sha256=SQ1cKW066uh1F1BcF8AXuw4Q-l6rkybxjdJEcLFjewg,3052
|
13
|
+
reposnap/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
14
|
+
reposnap/utils/path_utils.py,sha256=7072816LCP8Q8XBydn0iknmfrObPO_-2rFqpbAvPrjY,501
|
15
|
+
reposnap-0.4.0.dist-info/METADATA,sha256=rOGqK2qsMgpPeYzwrxn0p5trlPFSs0kFqVqMhZBi4KM,3929
|
16
|
+
reposnap-0.4.0.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
|
17
|
+
reposnap-0.4.0.dist-info/entry_points.txt,sha256=o3GyO7bpR0dujPCjsvvZMPv4pXNJlFwD49_pA1r5FOA,102
|
18
|
+
reposnap-0.4.0.dist-info/licenses/LICENSE,sha256=Aj7WCYBXi98pvi723HPn4GDRyjxToNWb3PC6j1_lnPk,1069
|
19
|
+
reposnap-0.4.0.dist-info/RECORD,,
|
reposnap/core/collector.py
DELETED
@@ -1,64 +0,0 @@
|
|
1
|
-
# src/reposnap/core/collector.py
|
2
|
-
|
3
|
-
import logging
|
4
|
-
from pathlib import Path
|
5
|
-
import pathspec
|
6
|
-
from .git_repo import GitRepo
|
7
|
-
from .file_system import FileSystem
|
8
|
-
from .markdown_generator import MarkdownGenerator
|
9
|
-
|
10
|
-
|
11
|
-
class ProjectContentCollector:
|
12
|
-
def __init__(self, root_dir: str, output_file: str, structure_only: bool, gitignore_patterns: list):
|
13
|
-
self.logger = logging.getLogger(__name__)
|
14
|
-
self.root_dir = Path(root_dir).resolve()
|
15
|
-
self.output_file = Path(output_file).resolve()
|
16
|
-
self.structure_only = structure_only
|
17
|
-
self.gitignore_patterns = gitignore_patterns
|
18
|
-
self.spec = pathspec.PathSpec.from_lines(pathspec.patterns.GitWildMatchPattern, gitignore_patterns)
|
19
|
-
|
20
|
-
# Initialize components
|
21
|
-
self.git_repo = GitRepo(self.root_dir)
|
22
|
-
self.file_system = FileSystem(self.root_dir)
|
23
|
-
self.markdown_generator = MarkdownGenerator(
|
24
|
-
root_dir=self.root_dir,
|
25
|
-
output_file=self.output_file,
|
26
|
-
structure_only=self.structure_only
|
27
|
-
)
|
28
|
-
|
29
|
-
# Collect files and build tree during initialization
|
30
|
-
self.files = self.collect_files()
|
31
|
-
self.tree_structure = self.build_tree_structure()
|
32
|
-
|
33
|
-
def collect_files(self):
|
34
|
-
"""
|
35
|
-
Collects and filters files to be included in the documentation.
|
36
|
-
"""
|
37
|
-
self.logger.info("Collecting git files.")
|
38
|
-
git_files = self.git_repo.get_git_files()
|
39
|
-
self.logger.debug(f"Git files before filtering: {git_files}")
|
40
|
-
|
41
|
-
# Filter files based on .gitignore patterns
|
42
|
-
filtered_files = [
|
43
|
-
f for f in git_files if not self.spec.match_file(str(f))
|
44
|
-
]
|
45
|
-
self.logger.debug(f"Git files after filtering: {filtered_files}")
|
46
|
-
|
47
|
-
return filtered_files # Paths relative to root_dir
|
48
|
-
|
49
|
-
def build_tree_structure(self):
|
50
|
-
"""
|
51
|
-
Builds the tree structure from the collected files.
|
52
|
-
"""
|
53
|
-
self.logger.info("Building tree structure.")
|
54
|
-
tree = self.file_system.build_tree_structure(self.files)
|
55
|
-
self.logger.debug(f"Tree structure: {tree}")
|
56
|
-
return tree
|
57
|
-
|
58
|
-
def collect_and_generate(self):
|
59
|
-
"""
|
60
|
-
Initiates the markdown generation process.
|
61
|
-
"""
|
62
|
-
self.logger.info("Starting markdown generation.")
|
63
|
-
self.markdown_generator.generate_markdown(self.tree_structure, self.files)
|
64
|
-
self.logger.info("Markdown generation completed.")
|
@@ -1,88 +0,0 @@
|
|
1
|
-
Metadata-Version: 2.3
|
2
|
-
Name: reposnap
|
3
|
-
Version: 0.3.1
|
4
|
-
Summary: Generate a Markdown file with all contents of your project
|
5
|
-
Author: agoloborodko
|
6
|
-
License-File: LICENSE
|
7
|
-
Requires-Python: >=3.8
|
8
|
-
Requires-Dist: gitpython>=3.1.43
|
9
|
-
Requires-Dist: pathlib>=1.0.1
|
10
|
-
Requires-Dist: pathspec>=0.12.1
|
11
|
-
Description-Content-Type: text/markdown
|
12
|
-
|
13
|
-
# RepoSnap
|
14
|
-
|
15
|
-
## Overview
|
16
|
-
|
17
|
-
`reposnap` is a Python script designed to generate a Markdown file that documents the structure and contents of a git project. This tool is particularly useful for creating a quick overview of a project's file hierarchy, including optional syntax-highlighted code snippets.
|
18
|
-
|
19
|
-
## Features
|
20
|
-
|
21
|
-
- **Syntax Highlighting**: Includes syntax highlighting for known file types in the generated Markdown file.
|
22
|
-
- **Structure Only Option**: The `--structure-only` flag can be used to generate the Markdown file with just the directory structure, omitting the contents of the files.
|
23
|
-
|
24
|
-
## Installation
|
25
|
-
```bash
|
26
|
-
pip install reposnap
|
27
|
-
```
|
28
|
-
|
29
|
-
Alternatively, you can clone the repository and install the required dependencies:
|
30
|
-
|
31
|
-
```bash
|
32
|
-
git clone https://github.com/username/reposnap.git
|
33
|
-
cd reposnap
|
34
|
-
pip install -r requirements.lock
|
35
|
-
```
|
36
|
-
|
37
|
-
## Usage
|
38
|
-
|
39
|
-
### Command-Line Interface
|
40
|
-
|
41
|
-
To use `reposnap`, run it with the following options:
|
42
|
-
|
43
|
-
```bash
|
44
|
-
reposnap [-h] [-o OUTPUT] [--structure-only] [--debug] path
|
45
|
-
```
|
46
|
-
|
47
|
-
- `path`: Path to the Git repository or subdirectory
|
48
|
-
- `-h, --help`: show help message and exit
|
49
|
-
- `-o, --output`: The name of the output Markdown file. Defaults to `output.md`.
|
50
|
-
- `--structure-only`: Generate a Markdown file that includes only the project structure, without file contents.
|
51
|
-
- `--debug`: Enable debug-level logging.
|
52
|
-
|
53
|
-
### Examples
|
54
|
-
|
55
|
-
1. **Generate a full project structure with file contents**:
|
56
|
-
|
57
|
-
```bash
|
58
|
-
reposnap .
|
59
|
-
```
|
60
|
-
|
61
|
-
2. **Generate a project structure only**:
|
62
|
-
|
63
|
-
```bash
|
64
|
-
reposnap my_project/ --structure-only
|
65
|
-
```
|
66
|
-
|
67
|
-
3. **Generate a Markdown file excluding certain files and directories**:
|
68
|
-
|
69
|
-
```bash
|
70
|
-
reposnap my_project/ -o output.md
|
71
|
-
```
|
72
|
-
|
73
|
-
## Testing
|
74
|
-
|
75
|
-
To run the tests, use `rye`:
|
76
|
-
|
77
|
-
```bash
|
78
|
-
rye test
|
79
|
-
```
|
80
|
-
|
81
|
-
## License
|
82
|
-
|
83
|
-
This project is licensed under the MIT License.
|
84
|
-
|
85
|
-
## Acknowledgments
|
86
|
-
|
87
|
-
- [GitPython](https://gitpython.readthedocs.io/) - Used for interacting with Git repositories.
|
88
|
-
- [pathspec](https://pathspec.readthedocs.io/) - Used for pattern matching file paths.
|
reposnap-0.3.1.dist-info/RECORD
DELETED
@@ -1,15 +0,0 @@
|
|
1
|
-
reposnap/__init__.py,sha256=FGadYKcWDEh_AL8PbUuUrcCZDlF510JZfdGhHdT6XQk,80
|
2
|
-
reposnap/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
3
|
-
reposnap/core/collector.py,sha256=UQNAaIqgALZmOvtSb7NDYaXmVp4-X4jSWikMMh_B0YY,2401
|
4
|
-
reposnap/core/file_system.py,sha256=yFIaHtJYqw5t8Lx9Nu7yb3G7XcCP1v1aKP_hGfS_KfQ,974
|
5
|
-
reposnap/core/git_repo.py,sha256=A8mdgmT9JGHllkFMx5Z_1gGp3Yw1dr-NFOw2-lH_DfA,1163
|
6
|
-
reposnap/core/markdown_generator.py,sha256=vJl_ac3vDs4CEanjwQazQM9fepGeFtGxo3ozajdkhqA,2889
|
7
|
-
reposnap/interfaces/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
8
|
-
reposnap/interfaces/cli.py,sha256=bU7QAg2wDzQwyAsRyq4zHLnO8nNiJGrWD24n7yZFEZk,1795
|
9
|
-
reposnap/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
10
|
-
reposnap/utils/path_utils.py,sha256=lMuZMMIX2lEE1o6V3QqifmyO5dO5fuA5OUXMxSvYcHI,290
|
11
|
-
reposnap-0.3.1.dist-info/METADATA,sha256=L_Cy9iGwDuqxR5ZU1LmJrvnjoMRr-vhX9WP_OtNw7p0,2333
|
12
|
-
reposnap-0.3.1.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
|
13
|
-
reposnap-0.3.1.dist-info/entry_points.txt,sha256=aaCuB0RZOLW2--ymW8VCEOm0Qz9KvTZCUjwQFZsGaDU,43
|
14
|
-
reposnap-0.3.1.dist-info/licenses/LICENSE,sha256=Aj7WCYBXi98pvi723HPn4GDRyjxToNWb3PC6j1_lnPk,1069
|
15
|
-
reposnap-0.3.1.dist-info/RECORD,,
|
File without changes
|
File without changes
|