digdep 0.0.3__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.
digdep/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ """
2
+ Copyright (c) 2026 Shine Jayakumar
3
+ SPDX-License-Identifier: MIT
4
+
5
+ Licensed under the MIT License.
6
+ See the LICENSE file in the project root for the full license text.
7
+ """
8
+
9
+ from .analyzer import DepAnalyzer, DepType
10
+ from ._version import __version__
11
+
12
+
digdep/_version.py ADDED
@@ -0,0 +1,13 @@
1
+ """
2
+ Copyright (c) 2026 Shine Jayakumar
3
+ SPDX-License-Identifier: MIT
4
+
5
+ Licensed under the MIT License.
6
+ See the LICENSE file in the project root for the full license text.
7
+
8
+ DigDep version
9
+ """
10
+
11
+ __version__ = "0.0.3"
12
+
13
+
digdep/analyzer.py ADDED
@@ -0,0 +1,228 @@
1
+ """
2
+ Copyright (c) 2026 Shine Jayakumar
3
+ SPDX-License-Identifier: MIT
4
+
5
+ Licensed under the MIT License.
6
+ See the LICENSE file in the project root for the full license text.
7
+
8
+ Core dependency analyzer
9
+ """
10
+
11
+ import ast
12
+ from pathlib import Path
13
+ from rich.console import Console
14
+ from enum import Flag, auto
15
+ import sys
16
+ from .visitors import DependencyVisitor
17
+ from .utils import walkpath
18
+
19
+
20
+ class DepType(Flag):
21
+ NONE = 0
22
+ STDLIB = auto()
23
+ THIRD_PARTY = auto()
24
+ LOCAL = auto()
25
+ UNKNOWN = auto()
26
+ ALL = STDLIB | THIRD_PARTY | LOCAL
27
+
28
+
29
+ class DepAnalyzer:
30
+
31
+ def __init__(self, is_ascii: bool = False) -> None:
32
+ self._root: Path = None
33
+ self._filedep_tree = {}
34
+ self._depfile_tree = {}
35
+ self._dep_type_map: dict[str, DepType] = {}
36
+ self._ignorelist: set[str] = set()
37
+ self._path_dep_map: dict[Path, set[str]] = {}
38
+ self._is_ascii: bool = is_ascii
39
+ self._tree_prefix_char = (
40
+ "├──" if not self._is_ascii else "|__"
41
+ )
42
+ self._console = Console()
43
+
44
+ def ignore(self, ignorelist: list[str]) -> None:
45
+ """Adds files/directories to ignorelist"""
46
+ self._ignorelist = set(ignorelist)
47
+
48
+ def _get_file_deps(self, fpath: str) -> list[str]:
49
+ """Get dependencies in a file"""
50
+ try:
51
+ with open(fpath, "r", encoding="utf-8") as fh:
52
+ source = fh.read()
53
+ tree = ast.parse(source)
54
+ visitor = DependencyVisitor()
55
+ visitor.visit(tree)
56
+ return visitor.packages
57
+ except Exception as ex:
58
+ print(
59
+ (
60
+ f"Failed to read: {fpath}\n"
61
+ f"{ex.__class__.__name__} - {str(ex)}"
62
+ )
63
+ )
64
+ return []
65
+
66
+ def _get_deptype(self, dep: str) -> DepType:
67
+ """Get the dependency type"""
68
+ if dep in sys.stdlib_module_names:
69
+ return DepType.STDLIB
70
+ return DepType.THIRD_PARTY
71
+
72
+ def _update_deptype_map(self, deps: set[str]) -> None:
73
+ """Update dependency in dependency-type mapping"""
74
+ new_deps = deps.difference(self._dep_type_map.keys())
75
+ self._dep_type_map.update({
76
+ dep: self._get_deptype(dep) for dep in new_deps
77
+ })
78
+
79
+ def _reset_vars(self) -> None:
80
+ """Resets variables"""
81
+ self._filedep_tree = {}
82
+ self._depfile_tree = {}
83
+ self._dep_type_map = {}
84
+ self._path_dep_map = {}
85
+
86
+ def scan(self, root: str = ".") -> None:
87
+ """Scans a python file(s) in a directory/sub-directory"""
88
+ self._reset_vars()
89
+ self._root = Path(root)
90
+ for path in walkpath(root, self._ignorelist):
91
+ deps = self._get_file_deps(str(path.resolve()))
92
+ deps = set(deps) if deps else set()
93
+ relpath = path.relative_to(self._root)
94
+ self._path_dep_map[relpath] = deps
95
+ self._update_deptype_map(deps)
96
+
97
+ def get_packages(self, filters: DepType = DepType.ALL) -> tuple[str]:
98
+ deps = self._get_filtered_deps(filters)
99
+ return tuple(deps)
100
+
101
+ def show_packages(self, filters: DepType = DepType.ALL) -> None:
102
+ print("\n".join(dep for dep in self.get_packages(filters)))
103
+
104
+ def _tree_prefix(self, indent: int = 0) -> str:
105
+ """Generates tree prefix with indentation"""
106
+ spaces = " " * indent
107
+ return f"{spaces}{self._tree_prefix_char}"
108
+
109
+ def _vertical_spacer(self, indent: int = 0) -> str:
110
+ """Generates a vertical spacer"""
111
+ spaces = " " * indent
112
+ return f"{spaces}|"
113
+
114
+ def _print(self, text: str) -> None:
115
+ """Coloured print"""
116
+ self._console.print(text)
117
+
118
+ def _gen_filedeps_tree(self) -> None:
119
+ """Generate file dependency tree"""
120
+ if self._filedep_tree:
121
+ return self._filedep_tree
122
+ self._filedep_tree = {"files": []}
123
+ for path, deps in self._path_dep_map.items():
124
+ dirparts = path.parent.parts
125
+ branch = self._filedep_tree
126
+ for part in dirparts:
127
+ branch = branch.setdefault(part, {"files": []})
128
+ branch["files"].append((path.name, deps))
129
+
130
+ def _gen_depfiles_tree(self) -> None:
131
+ """Generate dependency file tree"""
132
+ if self._depfile_tree:
133
+ return self._depfile_tree
134
+ self._depfile_tree = {}
135
+ for path, deps in self._path_dep_map.items():
136
+ dirparts = path.parent.parts
137
+ for dep in deps:
138
+ branch = self._depfile_tree.setdefault(dep, {"files": []})
139
+ for part in dirparts:
140
+ branch = branch.setdefault(part, {"files": []})
141
+ branch["files"].append(path.name)
142
+
143
+ def _get_filtered_deps(self, filters: DepType) -> set[str]:
144
+ """Filter dependencies by type"""
145
+ return {
146
+ dep
147
+ for dep, deptype in self._dep_type_map.items()
148
+ if filters & deptype
149
+ }
150
+
151
+ def get_filedep_tree(self, filters: DepType = DepType.ALL) -> dict:
152
+ """Get the file-dependency tree"""
153
+ self._gen_filedeps_tree()
154
+ return self._filedep_tree
155
+
156
+ def file_dependency_tree(self, filters: DepType = DepType.ALL) -> None:
157
+ """Show file and dependencies"""
158
+ self._gen_filedeps_tree()
159
+ relevant_deps = (
160
+ self._get_filtered_deps(filters) if filters else set()
161
+ )
162
+ def showdep(branch: dict, indent=0):
163
+ files = branch.get("files", [])
164
+ tree_prefix = self._tree_prefix(indent)
165
+ maxwidth = (
166
+ max(len(file) for file, _ in files) if files else 0
167
+ )
168
+ for file, deps in files:
169
+ deps = deps.intersection(relevant_deps)
170
+ deps = ", ".join(sorted(deps))
171
+ deps = f" → [bold cyan]{deps}[/bold cyan]" if deps else ""
172
+ self._print(f"{tree_prefix} {file:<{maxwidth}}{deps}")
173
+
174
+ dirs = {k:v for k,v in branch.items() if isinstance(v, dict)}
175
+ for _dir, val in dirs.items():
176
+ print(self._vertical_spacer(indent))
177
+ self._print(f"{tree_prefix} [blue]{_dir}[/blue]/")
178
+ showdep(val, indent + 4)
179
+
180
+ self._print(f"[bold magenta]Root ({self._root})[/bold magenta]")
181
+ showdep(self._filedep_tree)
182
+
183
+ def get_depfile_tree(self, filters: DepType = DepType.ALL) -> dict:
184
+ """Get the dependency-file tree"""
185
+ self._gen_depfiles_tree()
186
+ return self._depfile_tree
187
+
188
+ def dependency_file_tree(self, filters: DepType = DepType.ALL) -> None:
189
+ """Show dependency and files"""
190
+ self._gen_depfiles_tree()
191
+ relevant_deps = (
192
+ self._get_filtered_deps(filters) if filters else set()
193
+ )
194
+ def showfiles(branch: dict, indent=0):
195
+ files = branch.get("files", [])
196
+ tree_prefix = self._tree_prefix(indent)
197
+ for file in files:
198
+ print(f"{tree_prefix} {file}")
199
+
200
+ dirs = {k:v for k,v in branch.items() if isinstance(v, dict)}
201
+ for _dir, val in dirs.items():
202
+ print(self._vertical_spacer(indent))
203
+ self._print(f"{tree_prefix} [blue]{_dir}[/blue]/")
204
+ showfiles(val, indent + 4)
205
+
206
+ filtered_deps = (
207
+ set(self._depfile_tree.keys()).intersection(relevant_deps)
208
+ )
209
+ for dep in filtered_deps:
210
+ deptree = self._depfile_tree.get(dep)
211
+ self._print(f"[bold cyan]{dep}[/bold cyan]")
212
+ showfiles(deptree)
213
+ print("\n")
214
+
215
+
216
+ if __name__ == "__main__":
217
+ pass
218
+
219
+
220
+
221
+
222
+
223
+
224
+
225
+
226
+
227
+
228
+
digdep/analyzer_bak.py ADDED
@@ -0,0 +1,231 @@
1
+ """
2
+ Copyright (c) 2026 Shine Jayakumar
3
+ SPDX-License-Identifier: MIT
4
+
5
+ Licensed under the MIT License.
6
+ See the LICENSE file in the project root for the full license text.
7
+
8
+ Core dependency analyzer
9
+ """
10
+
11
+ import ast
12
+ from visitors import DependencyVisitor
13
+ from utils import walkpath
14
+ from pathlib import Path
15
+ import os
16
+ from rich.console import Console
17
+
18
+
19
+ class DepAnalyzer:
20
+
21
+ def __init__(self) -> None:
22
+ self._path: Path = None
23
+ self._packages: set[str] = set()
24
+ self._ignorelist: set[str] = set()
25
+ self._path_dep_map: dict[str, set[str]] = {}
26
+ self._dep_path_map: dict[str, list[str]] = {}
27
+ self._root: str = ""
28
+ self.filedep_tree = {"files": []}
29
+ self._console = Console()
30
+
31
+ def ignore(self, ignorelist: list[str]) -> None:
32
+ """Adds files/directories to ignorelist"""
33
+ self._ignorelist.set(ignorelist)
34
+ self._ignorelist = set(ignorelist)
35
+
36
+ def _get_file_deps(self, fpath: str) -> list[str]:
37
+ """Get dependencies in a file"""
38
+ with open(fpath, "r", encoding="utf-8") as fh:
39
+ source = fh.read()
40
+ tree = ast.parse(source)
41
+ visitor = DependencyVisitor()
42
+ visitor.visit(tree)
43
+ return visitor.packages
44
+
45
+ def _get_relative_path(self, path: str):
46
+ path = Path(path)
47
+ return path.relative_to(self._root)
48
+
49
+ def scan(self, root: str = ".") -> None:
50
+ """Scans a python file(s) in a directory/sub-directory"""
51
+ self._root = Path(root)
52
+ for path in walkpath(root, self._ignorelist):
53
+ packages = self._get_file_deps(path)
54
+ packages = set(packages)
55
+ self._path_dep_map[path] = packages
56
+ for pkg in packages:
57
+ self._dep_path_map.setdefault(pkg, []).append(path)
58
+ self._packages.update(packages)
59
+ self._gen_filedeps_tree()
60
+ self._gen_depfiles_tree()
61
+
62
+ @property
63
+ def packages(self):
64
+ return self._packages
65
+
66
+ def show_packages(self):
67
+ print("\n".join(self._packages))
68
+
69
+ def _tree_prefix(self, indent: int = 0) -> str:
70
+ """Generates tree prefix with indentation"""
71
+ spaces = " " * indent
72
+ #return f"{spaces}|__"
73
+ return f"{spaces}├──"
74
+
75
+ def _vertical_spacer(self, indent: int = 0) -> str:
76
+ """Generates a vertical spacer"""
77
+ spaces = " " * indent
78
+ return f"{spaces}|"
79
+
80
+ #def show_filedeps(self) -> str:
81
+ # """Shows file and dependencies"""
82
+ # grouped_dirs_and_deps = {}
83
+ # for path, deps in self._path_dep_map.items():
84
+ # dirname = os.path.dirname(path)
85
+ # basename = os.path.basename(path)
86
+ # grouped_dirs_and_deps.setdefault(
87
+ # dirname, []
88
+ # ).append((basename, deps))
89
+
90
+ # print(f"Root ({self._root})")
91
+ # for dirname, deplist in grouped_dirs_and_deps.items():
92
+ # indent = 0
93
+ # print(self._vertical_spacer())
94
+ # relpath = Path(dirname).relative_to(self._root)
95
+ # parts = relpath.parts
96
+ # if parts:
97
+ # for part in parts:
98
+ # tree_prefix = self._tree_prefix(indent)
99
+ # print(f"{tree_prefix} {part}/")
100
+ # indent += 4
101
+
102
+ # max_filewitdh = max(len(file) for file, _ in deplist)
103
+ # for file, deps in deplist:
104
+ # deps = sorted(deps) if deps else ""
105
+ # deps = str(deps)[1:-1].replace("'", "")
106
+ # deps = f" -> {deps}" if deps else ""
107
+ # tree_prefix = self._tree_prefix(indent)
108
+ # print(f"{tree_prefix} {file:<{max_filewitdh}} {deps}")
109
+
110
+ def _print(self, text: str) -> None:
111
+ """Coloured print"""
112
+ self._console.print(text)
113
+
114
+ def _gen_filedeps_tree(self) -> None:
115
+ """Generate file dependency tree"""
116
+ self.filedep_tree = {"files": []}
117
+ for path, deps in self._path_dep_map.items():
118
+ dirname = os.path.dirname(path)
119
+ basename = os.path.basename(path)
120
+ relpath = Path(dirname).relative_to(self._root)
121
+ dirparts = relpath.parts
122
+ branch = self.filedep_tree
123
+ for part in dirparts:
124
+ branch = branch.setdefault(part, {"files": []})
125
+ branch["files"].append((basename, deps))
126
+
127
+ def _gen_depfiles_tree(self) -> None:
128
+ """Generate dependency file tree"""
129
+ self._depfile_tree = {}
130
+ for path, deps in self._path_dep_map.items():
131
+ dirname = os.path.dirname(path)
132
+ basename = os.path.basename(path)
133
+ relpath = Path(dirname).relative_to(self._root)
134
+ dirparts = relpath.parts
135
+ for dep in deps:
136
+ branch = self._depfile_tree.setdefault(dep, {"files": []})
137
+ for part in dirparts:
138
+ branch = branch.setdefault(part, {"files": []})
139
+ branch["files"].append(basename)
140
+
141
+ def show_filedeps(self):
142
+ """Show file and dependencies"""
143
+ def showdep(branch: dict, indent=0):
144
+ files = branch.get("files", [])
145
+ tree_prefix = self._tree_prefix(indent)
146
+ max_filewitdh = (
147
+ max(len(file) for file, _ in files) if files else 0
148
+ )
149
+ for file, deps in files:
150
+ deps = sorted(deps) if deps else ""
151
+ deps = str(deps)[1:-1].replace("'", "")
152
+ deps = f" → [bold cyan]{deps}[/bold cyan]" if deps else ""
153
+ self._print(f"{tree_prefix} {file:<{max_filewitdh}}{deps}")
154
+
155
+ dirs = {k:v for k,v in branch.items() if isinstance(v, dict)}
156
+ for _dir, val in dirs.items():
157
+ print(self._vertical_spacer(indent))
158
+ self._print(f"{tree_prefix} [blue]{_dir}[/blue]/")
159
+ showdep(val, indent + 4)
160
+
161
+ self._print(f"[bold magenta]Root ({self._root})[/bold magenta]")
162
+ showdep(self.filedep_tree)
163
+
164
+ def show_depfiles(self):
165
+ """Show dependency and files"""
166
+ def showfiles(branch: dict, indent=0):
167
+ files = branch.get("files", [])
168
+ tree_prefix = self._tree_prefix(indent)
169
+ for file in files:
170
+ print(f"{tree_prefix} {file}")
171
+
172
+ dirs = {k:v for k,v in branch.items() if isinstance(v, dict)}
173
+ for _dir, val in dirs.items():
174
+ print(self._vertical_spacer(indent))
175
+ self._print(f"{tree_prefix} [blue]{_dir}[/blue]/")
176
+ showfiles(val, indent + 4)
177
+
178
+ for dep, tree in self._depfile_tree.items():
179
+ self._print(f"[bold cyan]{dep}[/bold cyan]")
180
+ showfiles(tree)
181
+ print("\n")
182
+
183
+ #def show_depfiles(self) -> str:
184
+ # def dirparts(path):
185
+ # dirname = os.path.dirname(path)
186
+
187
+
188
+ # for package, paths in self._dep_path_map.items():
189
+ # print(f"{package} ({len(paths)} files)")
190
+ # #fmtstr = (" " * 5) + "|" + ("_" * 5)
191
+ # tree_prefix = self._tree_prefix()
192
+ # sorted_paths = [
193
+ # Path(path).relative_to(self._root)
194
+ # for path in paths
195
+ # ]
196
+ # #sorted_paths.sort(key=lamdba p: len(p.parts))
197
+ # for path in sorted_paths:
198
+ # dirparts(path)
199
+
200
+ # #path = Path(path).relative_to(self._root)
201
+ # print(f"{tree_prefix} {path}")
202
+ # print("\n")
203
+
204
+
205
+
206
+
207
+
208
+ if __name__ == "__main__":
209
+ dp = DepAnalyzer()
210
+ dp.scan(r"C:\users\shine\pyprojs\insta-likecom-bot\modules")
211
+ from pprint import pprint
212
+ #pprint(dp.packages, width=120)
213
+ #dp.show_depmap()
214
+ #dp.show_filedeps()
215
+ #dp.create_filedeps()
216
+ #dp.show_filedeps1()
217
+ #dp.show_depfiles()
218
+ #dp.show_depfiles()
219
+ dp.show_filedeps()
220
+ #dp.show_packages()
221
+
222
+
223
+
224
+
225
+
226
+
227
+
228
+
229
+
230
+
231
+
digdep/argparsing.py ADDED
@@ -0,0 +1,99 @@
1
+ """
2
+ Copyright (c) 2026 Shine Jayakumar
3
+ SPDX-License-Identifier: MIT
4
+
5
+ Licensed under the MIT License.
6
+ See the LICENSE file in the project root for the full license text.
7
+
8
+ Argument Parsing for DigDep CLI
9
+ """
10
+
11
+ import argparse
12
+ from ._version import __version__
13
+
14
+
15
+ DESCRIPTION = "Scan Python projects and inspect import dependencies."
16
+ EXAMPLES = """
17
+ Examples:
18
+ digdep packages ./myproject
19
+ digdep file-tree ./myproject
20
+ digdep dep-tree ./myproject
21
+
22
+ Ignore directories:
23
+ digdep file-tree ./myproject --ignore venv __pycache__ tests
24
+
25
+ Redirect output:
26
+ digdep dep-tree ./myproject > dependencies.txt
27
+ """
28
+
29
+ def add_common_args(parser: argparse.ArgumentParser) -> None:
30
+ """Add arguments to subparser"""
31
+ parser.add_argument(
32
+ "path",
33
+ help="Path to the Python project.",
34
+ )
35
+ parser.add_argument(
36
+ "-i",
37
+ "--ignore",
38
+ nargs="*",
39
+ default=[],
40
+ metavar="NAME",
41
+ help="Directories or files to ignore.",
42
+ )
43
+ parser.add_argument(
44
+ "--type",
45
+ "-t",
46
+ default="all",
47
+ metavar="TYPES",
48
+ help=(
49
+ "Comma-separated dependency types (stdlib, third-party, "
50
+ "local, all). Defaults to 'all'."
51
+ )
52
+ )
53
+
54
+
55
+ parser = argparse.ArgumentParser(
56
+ prog="digdep",
57
+ description=DESCRIPTION,
58
+ formatter_class=argparse.RawDescriptionHelpFormatter,
59
+ epilog=EXAMPLES
60
+ )
61
+
62
+ parser.add_argument(
63
+ "-v",
64
+ "--version",
65
+ action="version",
66
+ version=f"%(prog)s {__version__}",
67
+ )
68
+
69
+ subparsers = parser.add_subparsers(
70
+ title="Commands",
71
+ dest="command",
72
+ required=True,
73
+ )
74
+ packages = subparsers.add_parser(
75
+ "packages",
76
+ help = "List imported packages."
77
+ )
78
+ add_common_args(packages)
79
+
80
+ file_tree = subparsers.add_parser(
81
+ "file-tree",
82
+ help="Show the file -> dependency tree."
83
+ )
84
+ add_common_args(file_tree)
85
+
86
+ dep_tree = subparsers.add_parser(
87
+ "dep-tree",
88
+ help="Show the dependency -> file tree."
89
+ )
90
+ add_common_args(dep_tree)
91
+
92
+
93
+ def parse_args() -> argparse.Namespace:
94
+ """Parse arguments"""
95
+ return parser.parse_args()
96
+
97
+
98
+ if __name__ == "__main__":
99
+ pass
digdep/cli.py ADDED
@@ -0,0 +1,56 @@
1
+ """
2
+ Copyright (c) 2026 Shine Jayakumar
3
+ SPDX-License-Identifier: MIT
4
+
5
+ Licensed under the MIT License.
6
+ See the LICENSE file in the project root for the full license text.
7
+
8
+ DigDep CLI
9
+ """
10
+
11
+ import sys
12
+ from .argparsing import parse_args
13
+ from .analyzer import DepAnalyzer, DepType
14
+
15
+
16
+ ARG_DEPTYPE_MAP = {
17
+ "stdlib": DepType.STDLIB,
18
+ "third-party": DepType.THIRD_PARTY,
19
+ "local": DepType.LOCAL,
20
+ "all": DepType.ALL,
21
+ }
22
+
23
+
24
+ def main(is_ascii: bool = False):
25
+
26
+ args = parse_args()
27
+
28
+ depanalyzer = DepAnalyzer(is_ascii=is_ascii)
29
+ depanalyzer.ignore(args.ignore)
30
+ depanalyzer.scan(args.path)
31
+
32
+ arg_deptypes = args.type.split(",")
33
+ invalid_types = set(arg_deptypes).difference(ARG_DEPTYPE_MAP.keys())
34
+ if invalid_types:
35
+ invalid_types = ", ".join(invalid_types)
36
+ print(f"Error: Invalid dependency type - {invalid_types}")
37
+ sys.exit(1)
38
+
39
+ filters = DepType.NONE
40
+ for deptype in invalid_types:
41
+ filters |= ARG_DEPTYPE_MAP.get(deptype.strip(), DepType.NONE)
42
+ filters = DepType.ALL if filters == DepType.NONE else filters
43
+
44
+ if args.command == "packages":
45
+ depanalyzer.show_packages(filters=filters)
46
+ elif args.command == "file-tree":
47
+ depanalyzer.file_dependency_tree(filters=filters)
48
+ elif args.command == "dep-tree":
49
+ depanalyzer.dependency_file_tree(filters=filters)
50
+
51
+
52
+ if __name__ == "__main__":
53
+ sys.stdout.reconfigure(encoding="utf-8")
54
+ is_ascii = False if sys.stdout.isatty() else True
55
+ main(is_ascii)
56
+
digdep/utils.py ADDED
@@ -0,0 +1,37 @@
1
+ """
2
+ Copyright (c) 2026 Shine Jayakumar
3
+ SPDX-License-Identifier: MIT
4
+
5
+ Licensed under the MIT License.
6
+ See the LICENSE file in the project root for the full license text.
7
+
8
+ Utility methods
9
+ """
10
+
11
+ from pathlib import Path
12
+ from collections.abc import Iterator
13
+
14
+
15
+ def walkpath(root: str | Path, ignorelist: set[str]) -> Iterator[Path]:
16
+ """Get .py files from directories and sub-directories"""
17
+ if not isinstance(root, Path):
18
+ root = Path(root)
19
+ if not root.exists():
20
+ raise Exception("File/Directory doesn't exist")
21
+
22
+ if root.is_file():
23
+ return root
24
+
25
+ for path in root.iterdir():
26
+ if path.name in ignorelist:
27
+ continue
28
+ if path.is_dir():
29
+ yield from walkpath(path, ignorelist)
30
+
31
+ elif path.suffix == ".py":
32
+ yield path
33
+
34
+
35
+ if __name__ == "__main__":
36
+ pass
37
+
digdep/visitors.py ADDED
@@ -0,0 +1,36 @@
1
+ """
2
+ Copyright (c) 2026 Shine Jayakumar
3
+ SPDX-License-Identifier: MIT
4
+
5
+ Licensed under the MIT License.
6
+ See the LICENSE file in the project root for the full license text.
7
+
8
+ AST Visitors for dependency analysis
9
+ """
10
+
11
+ import ast
12
+
13
+
14
+ class DependencyVisitor(ast.NodeVisitor):
15
+
16
+ def __init__(self):
17
+ self._packages = []
18
+
19
+ @property
20
+ def packages(self):
21
+ return self._packages
22
+
23
+ def visit_Import(self, node):
24
+ self._packages.extend([
25
+ alias.name.split(".", 1)[0] for alias in node.names
26
+ ])
27
+
28
+ def visit_ImportFrom(self, node):
29
+ if node.level == 0:
30
+ self._packages.append(node.module.split(".")[0])
31
+
32
+
33
+ if __name__ == "__main__":
34
+ pass
35
+
36
+
@@ -0,0 +1,228 @@
1
+ Metadata-Version: 2.4
2
+ Name: digdep
3
+ Version: 0.0.3
4
+ Summary: Analyze Python import dependencies.
5
+ Author: Shine Jayakumar
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/shine-jayakumar/digdep
8
+ Project-URL: Repository, https://github.com/shine-jayakumar/digdep
9
+ Project-URL: Issues, https://github.com/shine-jayakumar/digdep/issues
10
+ Keywords: python,dependency,dependencies,import,imports,dependency-analyzer,static-analysis,code-analysis,ast,cli
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Classifier: Topic :: Software Development :: Quality Assurance
20
+ Classifier: Topic :: Utilities
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: rich>=14.0.0
25
+ Dynamic: license-file
26
+
27
+ # DigDep
28
+
29
+ ![Version](https://img.shields.io/static/v1?label=version&message=v.0.0.3&color=blue)
30
+ ![License](https://img.shields.io/static/v1?label=license&message=MIT&color=green)
31
+ ![Status](https://img.shields.io/badge/status-alpha-yellow.svg)
32
+ ![Open Source](https://img.shields.io/static/v1?label=OpenSource&message=Yes&color=brightgreen)
33
+ ![GitHub issues](https://img.shields.io/github/issues/shine-jayakumar/docdsl)
34
+ ![Last Commit](https://img.shields.io/github/last-commit/shine-jayakumar/docdsl)
35
+
36
+ A lightweight Python dependency analyzer that scans Python projects and visualizes import relationships.
37
+
38
+ ---
39
+
40
+ ## Installation
41
+
42
+ ```bash
43
+ pip install digdep
44
+ ```
45
+ ---
46
+
47
+ ## Quick Start (CLI)
48
+
49
+ List all imported packages:
50
+
51
+ ```bash
52
+ digdep packages ./myproject
53
+ ```
54
+
55
+ Show the File → Dependency tree:
56
+
57
+ ```bash
58
+ digdep file-tree ./myproject
59
+ ```
60
+
61
+ Show the Dependency → File tree:
62
+
63
+ ```bash
64
+ digdep dep-tree ./myproject
65
+ ```
66
+
67
+ ---
68
+
69
+ ## Sample Output
70
+
71
+ ### File → Dependency Tree
72
+
73
+ ```text
74
+ Root (/projects/example)
75
+
76
+ ├── main.py → requests, pathlib
77
+ ├── config.py → json
78
+
79
+ ├── modules/
80
+ │ ├── logger.py → logging
81
+ │ ├── parser.py → re, typing
82
+
83
+ └── utils/
84
+ └── helpers.py → functools
85
+ ```
86
+
87
+ ### Dependency → File Tree
88
+
89
+ ```text
90
+ requests
91
+ ├── main.py
92
+
93
+ re
94
+ ├── modules/
95
+ │ └── parser.py
96
+
97
+ logging
98
+ ├── modules/
99
+ │ └── logger.py
100
+ ```
101
+
102
+ ---
103
+
104
+ ## Filtering
105
+
106
+ Filter dependencies by type.
107
+
108
+ Show only standard library imports:
109
+
110
+ ```bash
111
+ digdep file-tree ./myproject --type stdlib
112
+ ```
113
+
114
+ Show both standard library and third-party imports:
115
+
116
+ ```bash
117
+ digdep file-tree ./myproject --type stdlib,third-party
118
+ ```
119
+
120
+ Show only local imports:
121
+
122
+ ```bash
123
+ digdep file-tree ./myproject --type local
124
+ ```
125
+
126
+ ---
127
+
128
+ ## Ignoring Files and Directories
129
+
130
+ Skip directories or files while scanning:
131
+
132
+ ```bash
133
+ digdep file-tree ./myproject --ignore venv __pycache__ tests
134
+ ```
135
+
136
+ ---
137
+
138
+ ## Redirecting Output
139
+
140
+ Save the generated tree to a file:
141
+
142
+ ```bash
143
+ digdep dep-tree ./myproject > dependencies.txt
144
+ ```
145
+
146
+ ---
147
+
148
+ ## Commands
149
+
150
+ | Command | Description |
151
+ |---------|-------------|
152
+ | `packages` | List all imported packages |
153
+ | `file-tree` | Show the File → Dependency tree |
154
+ | `dep-tree` | Show the Dependency → File tree |
155
+
156
+ Run `digdep <command> --help` for command-specific options.
157
+
158
+ ---
159
+
160
+ ## Using as a Python Library
161
+
162
+ ```python
163
+ from digdep import DepAnalyzer, DepType
164
+
165
+ analyzer = DepAnalyzer()
166
+
167
+ # Ignoring directories
168
+ analyzer.ignore([
169
+ "__pycache__",
170
+ "venv",
171
+ "build",
172
+ "tests"
173
+ ])
174
+
175
+ analyzer.scan("./myproject")
176
+
177
+ # List imported packages
178
+ packages = analyzer.get_packages()
179
+
180
+ # Get the File -> Dependency tree
181
+ filedep_tree = analyzer.get_filedep_tree()
182
+
183
+ # Get the Dependency -> File tree
184
+ depfile_tree = analyzer.get_depfile_tree()
185
+
186
+ ```
187
+
188
+ Filter dependencies by type:
189
+
190
+ ```python
191
+ from digdep import DepAnalyzer, DepType
192
+
193
+ analyzer = DepAnalyzer()
194
+ analyzer.scan("./myproject")
195
+
196
+ # Show only standard library imports
197
+ filedep_tree = analyzer.get_filedep_tree(
198
+ filters=DepType.STDLIB
199
+ )
200
+
201
+ # Show standard library and third-party imports
202
+ depfile_tree = analyzer.get_depfile_tree(
203
+ filters=DepType.STDLIB | DepType.THIRD_PARTY
204
+ )
205
+ ```
206
+
207
+ ---
208
+ ## Roadmap
209
+
210
+ - Local module detection
211
+ - Dependency statistics
212
+ - JSON export
213
+ - Circular dependency detection
214
+ - Unused dependency detection
215
+
216
+ ---
217
+
218
+ ## Requirements
219
+
220
+ - Python 3.11+
221
+
222
+ ---
223
+
224
+ ## License
225
+
226
+ Released under the MIT License.
227
+
228
+ ---
@@ -0,0 +1,14 @@
1
+ digdep/__init__.py,sha256=IrfTBnv2zH46vb4QyvU5fS3SDt0fIc1Ga0ISp-LEqqs,265
2
+ digdep/_version.py,sha256=79MJWhXNnaJw5cNtr92jjRu70eZ4XQg5EaOpzH_LZIw,227
3
+ digdep/analyzer.py,sha256=y2mb_4JEu483Rc6tMXIZN6PBbmZEfHvGCVBhwFTHzeA,7841
4
+ digdep/analyzer_bak.py,sha256=FhEOrY88-aTRr7DIMAIx2TuFg-OSV0TVkuXYW5Med1w,8045
5
+ digdep/argparsing.py,sha256=6Rp9N2HV2kdP2GEDSIceVXOOENBk4hC7tsos5wu1SMY,2197
6
+ digdep/cli.py,sha256=npqPAmq3XZ0Td7PlrXDDWKuK7kwFHyvnH7vqdGBAryU,1553
7
+ digdep/utils.py,sha256=87At93jcWathtkyHpoY40Ikz4QQ67SZEG6k8jLU_Buk,876
8
+ digdep/visitors.py,sha256=38p-WAy_gJSMwmHQbkEXde2neCOk36oYifr-1i2R51I,743
9
+ digdep-0.0.3.dist-info/licenses/LICENSE,sha256=1Yd7r-jQ0rtrPD3-VSKbnz4g_0W-BqAk61f4pyyE3mk,1093
10
+ digdep-0.0.3.dist-info/METADATA,sha256=LRlvYcf0Uj7g51TedYH0yrRFv6Di8fMbhwqLztskM5M,4776
11
+ digdep-0.0.3.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
12
+ digdep-0.0.3.dist-info/entry_points.txt,sha256=eVui0hJOlqguQoi33AWWgEV_oJHu3x9K9PnYtz8YnT4,43
13
+ digdep-0.0.3.dist-info/top_level.txt,sha256=peD93GMI23bK_4WyaaxRCynAfGaJnWBj6pWhQfVa9tw,7
14
+ digdep-0.0.3.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ digdep = digdep.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shine Jayakumar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ digdep