-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathentrypoint.py
More file actions
287 lines (239 loc) · 10.5 KB
/
entrypoint.py
File metadata and controls
287 lines (239 loc) · 10.5 KB
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
"""Main entry point for ingesting a source and processing its contents."""
from __future__ import annotations
import asyncio
import shutil
import sys
import warnings
from contextlib import asynccontextmanager
from pathlib import Path
from typing import AsyncGenerator
from gitingest.clone import clone_repo
from gitingest.config import MAX_FILE_SIZE
from gitingest.ingestion import ingest_query
from gitingest.query_parser import IngestionQuery, parse_query
from gitingest.utils.auth import resolve_token
from gitingest.utils.ignore_patterns import load_ignore_patterns
async def ingest_async(
source: str,
*,
max_file_size: int = MAX_FILE_SIZE,
include_patterns: str | set[str] | None = None,
exclude_patterns: str | set[str] | None = None,
branch: str | None = None,
tag: str | None = None,
include_gitignored: bool = False,
include_submodules: bool = False,
token: str | None = None,
output: str | None = None,
) -> tuple[str, str, str]:
"""Ingest a source and process its contents.
This function analyzes a source (URL or local path), clones the corresponding repository (if applicable),
and processes its files according to the specified query parameters. It returns a summary, a tree-like
structure of the files, and the content of the files. The results can optionally be written to an output file.
Parameters
----------
source : str
The source to analyze, which can be a URL (for a Git repository) or a local directory path.
max_file_size : int
Maximum allowed file size for file ingestion. Files larger than this size are ignored (default: 10 MB).
include_patterns : str | set[str] | None
Pattern or set of patterns specifying which files to include. If ``None``, all files are included.
exclude_patterns : str | set[str] | None
Pattern or set of patterns specifying which files to exclude. If ``None``, no files are excluded.
branch : str | None
The branch to clone and ingest (default: the default branch).
tag : str | None
The tag to clone and ingest. If ``None``, no tag is used.
include_gitignored : bool
If ``True``, include files ignored by ``.gitignore`` and ``.gitingestignore`` (default: ``False``).
include_submodules : bool
If ``True``, recursively include all Git submodules within the repository (default: ``False``).
token : str | None
GitHub personal access token (PAT) for accessing private repositories.
Can also be set via the ``GITHUB_TOKEN`` environment variable.
output : str | None
File path where the summary and content should be written.
If ``"-"`` (dash), the results are written to ``stdout``.
If ``None``, the results are not written to a file.
Returns
-------
tuple[str, str, str]
A tuple containing:
- A summary string of the analyzed repository or directory.
- A tree-like string representation of the file structure.
- The content of the files in the repository or directory.
"""
token = resolve_token(token)
query: IngestionQuery = await parse_query(
source=source,
max_file_size=max_file_size,
from_web=False,
include_patterns=include_patterns,
ignore_patterns=exclude_patterns,
token=token,
)
if not include_gitignored:
_apply_gitignores(query)
if query.url:
_override_branch_and_tag(query, branch=branch, tag=tag)
query.include_submodules = include_submodules
async with _clone_repo_if_remote(query, token=token):
summary, tree, content = ingest_query(query)
await _write_output(tree, content=content, target=output)
return summary, tree, content
def ingest(
source: str,
*,
max_file_size: int = MAX_FILE_SIZE,
include_patterns: str | set[str] | None = None,
exclude_patterns: str | set[str] | None = None,
branch: str | None = None,
tag: str | None = None,
include_gitignored: bool = False,
include_submodules: bool = False,
token: str | None = None,
output: str | None = None,
) -> tuple[str, str, str]:
"""Provide a synchronous wrapper around ``ingest_async``.
This function analyzes a source (URL or local path), clones the corresponding repository (if applicable),
and processes its files according to the specified query parameters. It returns a summary, a tree-like
structure of the files, and the content of the files. The results can optionally be written to an output file.
Parameters
----------
source : str
The source to analyze, which can be a URL (for a Git repository) or a local directory path.
max_file_size : int
Maximum allowed file size for file ingestion. Files larger than this size are ignored (default: 10 MB).
include_patterns : str | set[str] | None
Pattern or set of patterns specifying which files to include. If ``None``, all files are included.
exclude_patterns : str | set[str] | None
Pattern or set of patterns specifying which files to exclude. If ``None``, no files are excluded.
branch : str | None
The branch to clone and ingest (default: the default branch).
tag : str | None
The tag to clone and ingest. If ``None``, no tag is used.
include_gitignored : bool
If ``True``, include files ignored by ``.gitignore`` and ``.gitingestignore`` (default: ``False``).
include_submodules : bool
If ``True``, recursively include all Git submodules within the repository (default: ``False``).
token : str | None
GitHub personal access token (PAT) for accessing private repositories.
Can also be set via the ``GITHUB_TOKEN`` environment variable.
output : str | None
File path where the summary and content should be written.
If ``"-"`` (dash), the results are written to ``stdout``.
If ``None``, the results are not written to a file.
Returns
-------
tuple[str, str, str]
A tuple containing:
- A summary string of the analyzed repository or directory.
- A tree-like string representation of the file structure.
- The content of the files in the repository or directory.
See Also
--------
``ingest_async`` : The asynchronous version of this function.
"""
return asyncio.run(
ingest_async(
source=source,
max_file_size=max_file_size,
include_patterns=include_patterns,
exclude_patterns=exclude_patterns,
branch=branch,
tag=tag,
include_gitignored=include_gitignored,
include_submodules=include_submodules,
token=token,
output=output,
),
)
def _override_branch_and_tag(query: IngestionQuery, branch: str | None, tag: str | None) -> None:
"""Compare the caller-supplied ``branch`` and ``tag`` with the ones already in ``query``.
If they differ, update ``query`` to the chosen values and issue a warning.
If both are specified, the tag wins over the branch.
Parameters
----------
query : IngestionQuery
The query to update.
branch : str | None
The branch to use.
tag : str | None
The tag to use.
"""
if tag and query.tag and tag != query.tag:
msg = f"Warning: The specified tag '{tag}' overrides the tag found in the URL '{query.tag}'."
warnings.warn(msg, RuntimeWarning, stacklevel=3)
query.tag = tag or query.tag
if branch and query.branch and branch != query.branch:
msg = f"Warning: The specified branch '{branch}' overrides the branch found in the URL '{query.branch}'."
warnings.warn(msg, RuntimeWarning, stacklevel=3)
query.branch = branch or query.branch
if tag and branch:
msg = "Warning: Both tag and branch are specified. The tag will be used."
warnings.warn(msg, RuntimeWarning, stacklevel=3)
# Tag wins over branch if both supplied
if query.tag:
query.branch = None
def _apply_gitignores(query: IngestionQuery) -> None:
"""Update ``query.ignore_patterns`` in-place.
Parameters
----------
query : IngestionQuery
The query to update.
"""
for fname in (".gitignore", ".gitingestignore"):
query.ignore_patterns.update(load_ignore_patterns(query.local_path, filename=fname))
@asynccontextmanager
async def _clone_repo_if_remote(query: IngestionQuery, *, token: str | None) -> AsyncGenerator[None]:
"""Async context-manager that clones ``query.url`` if present.
If ``query.url`` is set, the repo is cloned, control is yielded, and the temp directory is removed on exit.
If no URL is given, the function simply yields immediately.
Parameters
----------
query : IngestionQuery
Parsed query describing the source to ingest.
token : str | None
GitHub personal access token (PAT) for accessing private repositories.
"""
if query.url:
clone_config = query.extract_clone_config()
await clone_repo(clone_config, token=token)
try:
yield
finally:
shutil.rmtree(query.local_path.parent)
else:
yield
async def _write_output(tree: str, content: str, target: str | None) -> None:
"""Write combined output to ``target`` (``"-"`` ⇒ stdout).
Parameters
----------
tree : str
The tree-like string representation of the file structure.
content : str
The content of the files in the repository or directory.
target : str | None
The path to the output file. If ``None``, the results are not written to a file.
"""
loop = asyncio.get_running_loop()
if target == "-":
# Write to stdout in chunks to avoid large memory allocation
await loop.run_in_executor(None, sys.stdout.write, tree)
await loop.run_in_executor(None, sys.stdout.write, "\n")
await loop.run_in_executor(None, sys.stdout.write, content)
await loop.run_in_executor(None, sys.stdout.flush)
elif target is not None:
# Write to file in chunks to avoid large memory allocation
target_path = Path(target)
# Define synchronous functions for file operations
def write_tree() -> None:
with target_path.open("w", encoding="utf-8") as f:
f.write(tree)
f.write("\n")
def append_content() -> None:
with target_path.open("a", encoding="utf-8") as f:
f.write(content)
# Execute file operations
await loop.run_in_executor(None, write_tree)
await loop.run_in_executor(None, append_content)