-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHirotoShioi_repo-digest-tool_digest.txt
6653 lines (5749 loc) · 190 KB
/
HirotoShioi_repo-digest-tool_digest.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
The following text represents the contents of the repository.
Each section begins with ----, followed by the file path and name.
A file list is provided at the beginning. End of repository content is marked by --END--.
----
.gptinclude
----
Dockerfile
# Build stage
FROM ghcr.io/astral-sh/uv:python3.12-bookworm AS builder
WORKDIR /app
RUN --mount=type=cache,target=/root/.cache/uv \
--mount=type=bind,source=uv.lock,target=uv.lock \
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
uv sync --frozen --no-install-project --no-dev
# Install Python dependencies
COPY pyproject.toml uv.lock README.md ./
RUN uv sync --frozen
# Copy application code
COPY repo_tool ./repo_tool
# Final stage
FROM python:3.12-slim-bookworm
WORKDIR /app
# Create non-root user for the final stage
RUN groupadd -r appuser && useradd -r -g appuser appuser
# Install git in the final stage
RUN apt-get update && apt-get install -y \
git \
&& rm -rf /var/lib/apt/lists/*
# Copy the virtual environment from builder
COPY --from=builder /app/.venv /app/.venv
# Copy application code
COPY --from=builder /app/repo_tool /app/repo_tool
# Create directories for bind mounts
RUN mkdir -p /app/repositories /app/digests && \
chown -R appuser:appuser /app
# Switch to non-root user
USER appuser
# Set environment variables
ENV PATH="/app/.venv/bin:$PATH"
ENV PYTHONPATH=/app
ENV REPO_PATH=/app/repositories
ENV DIGEST_PATH=/app/digests
----
makefile
.PHONY: run-app docker-build docker-up docker-down docker-logs docker-shell clean
run-app:
fastapi dev repo_tool/api
docker-build:
docker-compose build
docker-up:
docker compose up --watch
docker-down:
docker-compose down
docker-logs:
docker-compose logs -f
docker-shell:
docker-compose exec api bash
clean:
docker-compose down -v
find . -type d -name "__pycache__" -exec rm -r {} +
find . -type f -name "*.pyc" -delete
----
pyproject.toml
# https://packaging.python.org/en/latest/
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "repo-digest-tool"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"aiofiles>=24.1.0",
"fastapi[standard]>=0.115.6",
"gitpython>=3.1.43",
"humanize>=4.11.0",
"jinja2>=3.1.4",
"langchain>=0.3.9",
"langchain-core>=0.3.21",
"langchain-openai>=0.2.11",
"python-dotenv>=1.0.1",
"rich>=13.9.4",
"tiktoken>=0.8.0",
"typer>=0.15.1",
]
[dependency-groups]
dev = [
"black>=24.10.0",
"fastapi-cli>=0.0.6",
"mypy>=1.13.0",
"pytest>=8.3.4",
"ruff>=0.8.2",
"types-aiofiles>=24.1.0.20240626",
]
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]
[tool.hatch.build.targets.wheel]
packages = ["repo_tool"]
[tool.ruff]
line-length = 100
lint.select = ["E", "F", "I"]
lint.ignore = ["E501"]
target-version = "py312"
[tool.mypy]
python_version = "3.12"
strict = true
----
test.py
from dotenv import load_dotenv
from repo_tool import GitHub, generate_digest
load_dotenv(override=True)
def main() -> None:
repo_url = "https://github.com/HirotoShioi/repo-digest-tool"
branch = None
prompt = None
github = GitHub()
prompt = "I want to know how to use the repository."
try:
print("Cloning repository...")
github.clone(repo_url, branch)
github.update(repo_url)
print("Processing repository...")
repo_path = GitHub.get_repo_path(repo_url)
generate_digest(repo_path, prompt)
repos = github.list()
print(repos)
except Exception as e:
print("Error:", e)
if __name__ == "__main__":
main()
----
.cursorrules
# AI Behavior Customization for Repo Digest Tool
## Expertise and Focus
- You are an expert in CLI application development, Git repository management, and Python tooling, with a strong focus on frameworks such as Typer and GitPython.
## Key Principles
1. Provide concise, technical responses with clear Python examples.
2. Emphasize readability and maintainability in code and CLI workflows.
3. Use descriptive variable and function names that convey purpose explicitly.
4. Adhere to PEP 8 for Python coding style.
5. Highlight best practices for repository handling and digest generation.
## CLI Application Design
- **CLI Framework:** Use Typer for clean, user-friendly command definitions.
- **Repository Operations:** Implement robust handling for cloning, updating, and deleting repositories using GitPython.
- **Digest Generation:** Prioritize flexibility by supporting custom prompts and allowing dynamic digest formats.
- **Error Handling:** Ensure clear error messages for invalid inputs or failed operations.
## Performance Optimization
1. Minimize redundant operations, e.g., use `git pull` for updates instead of re-cloning.
2. Cache repository metadata for faster lookups.
3. Utilize batch operations for managing multiple repositories efficiently.
## Directory Structure and Configuration
- **Repo Storage:** Maintain repositories in the `repo/` directory with a clear naming convention (`{author}@{repo}`).
- **Digest Output:** Store digests in the `digests/` directory with intuitive naming (`{repo_name}_digest.txt`).
## Testing and Documentation
1. Write modular unit tests using `pytest` for all commands and utility functions.
2. Provide usage examples and clear descriptions in `README.md`.
3. Maintain inline comments and docstrings for better code understanding.
## Extension Roadmap
- Add support for multiple repository hosting services (e.g., GitLab, Bitbucket).
- Enhance digest generation to allow filtering by file extensions or directory paths.
- Introduce batch operations for adding or removing repositories.
- Optimize CLI commands with additional flags for granular control.
## Error Handling Guidelines
- Use `try-except` blocks for file I/O and Git operations.
- Validate inputs (e.g., URL formats, branch names) before executing operations.
- Provide actionable feedback on errors (e.g., "Invalid repo URL. Ensure it follows the format `https://github.com/{author}/{repo}`").
## Example Code Guidelines
- **Repository Addition Example**
```python
from git import Repo
def add_repository(repo_url: str, branch: str = 'main', force: bool = False):
repo_id = convert_to_repo_id(repo_url)
repo_path = f"./repo/{repo_id}"
if not force and os.path.exists(repo_path):
print(f"Repository {repo_id} already exists. Use --force to overwrite.")
return
Repo.clone_from(repo_url, repo_path, branch=branch)
print(f"Repository {repo_id} added successfully.")
```
- **Digest Generation Example**
```python
def generate_digest(repo_path: str, output_path: str, prompt: str = None):
files = list_files_in_repo(repo_path)
digest_content = create_digest(files, prompt)
with open(output_path, 'w') as f:
f.write(digest_content)
print(f"Digest saved to {output_path}")
```
## Dependencies
- Typer
- GitPython
- pytest
- Rich (optional, for better CLI output formatting)
## Conventions
1. Begin repository operations by validating URLs and paths.
2. Keep CLI commands intuitive and well-documented.
3. Use modular design for extensibility and maintainability.
4. Log key operations and errors for debugging and audits.
----
README.md
# Repo Digest Tool
![スクリーンショット 2024-12-08 10 07 14](https://github.com/user-attachments/assets/e9e5d500-2ba6-40d5-b564-57dd23301e21)
A CLI tool for managing GitHub repositories and generating digest summaries, implemented with Typer.
---
## Features
- **Repository Digest Generation**: Creates digests of repositories and stores them in the `digests/` directory.
- **Repository Management**: Add, remove, update, or list repositories stored locally in the `repositories/` directory.
- **Custom Filtering**: Uses an LLM (Language Learning Model) for advanced filtering of repository contents based on user prompts.
- **HTML Reports**: Generates user-friendly HTML reports summarizing repository statistics and digest contents.
---
## Installation
### Requirements
- Python 3.12 or above
- `git` installed and accessible in your system path
### Setup
1. Clone the repository:
```bash
git clone https://github.com/<your-username>/repo-digest-tool.git
cd repo-digest-tool
```
2. Install dependencies:
```bash
pip install -r requirements.txt
```
3. Optional: Install as a package for easier access:
```bash
pip install -e .
```
---
## Usage
### CLI Commands
Here’s a quick overview of the commands:
#### Add a Repository
```bash
repo add <repo_url> [--branch <branch>] [--force]
```
- Adds a repository to local storage.
- Example:
```bash
repo add https://github.com/honojs/hono
repo add https://github.com/honojs/hono --branch develop --force
```
#### Remove a Repository
```bash
repo remove <repo_url>
```
- Removes a repository from local storage.
- Example:
```bash
repo remove https://github.com/honojs/hono
```
#### List Repositories
```bash
repo list
```
- Lists all repositories stored locally.
- Example:
```bash
repo list
```
#### Generate a Digest
```bash
repo digest <repo_url> [--branch <branch>] [--prompt <prompt>] [--force]
```
- Generates a digest for a repository. Optional: specify a branch or a custom LLM filtering prompt.
- Example:
```bash
repo digest https://github.com/honojs/hono
repo digest https://github.com/honojs/hono --prompt "Focus on APIs"
```
#### Clear Repositories
```bash
repo clear [--all | --author <author>]
```
- Clears repositories from local storage. Either all or selectively by author.
- Example:
```bash
repo clear --all
repo clear --author honojs
```
#### Update a Repository
```bash
repo update <repo_url>
```
- Updates a repository by pulling the latest changes.
- Example:
```bash
repo update https://github.com/honojs/hono
```
---
## Development Roadmap
1. **Basic Functionality**:
- Repository management (`add`, `remove`, `list`).
- Digest generation.
2. **Digest Extensions**:
- LLM filtering with custom prompts.
- HTML report generation.
3. **Testing and Documentation**:
- Unit tests for all commands.
- Comprehensive documentation.
4. **Future Enhancements**:
- Multi-language report support.
- Integration with other platforms (e.g., GitLab).
---
## License
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
---
## Contribution
Contributions are welcome! Please fork the repository and submit a pull request.
----
.dockerignore
.git
.gitignore
.env
__pycache__
*.pyc
*.pyo
*.pyd
.Python
env/
venv/
.venv/
pip-log.txt
pip-delete-this-directory.txt
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.log
.pytest_cache/
.mypy_cache/
.pyre/
.hypothesis/
.vscode/
repositories/
digests/
----
.python-version
3.12
----
docker-compose.yml
services:
api:
build: .
command: fastapi dev --host 0.0.0.0 --port 8000 repo_tool/api
develop:
watch:
- action: sync
path: ./repo_tool
target: /app/repo_tool
- action: rebuild
path: pyproject.toml
ports:
- "8000:8000"
volumes:
- ./repositories:/app/repositories
- ./digests:/app/digests
- ./.gptinclude:/app/.gptinclude
- ./.gptignore:/app/.gptignore
environment:
- PYTHONPATH=/app
- PYTHONUNBUFFERED=1
env_file:
- .env
deploy:
resources:
limits:
memory: 4G
reservations:
memory: 2G
cap_add:
- SYS_PTRACE
security_opt:
- seccomp:unconfined
volumes:
repositories:
digests:
----
frontend/tsconfig.node.json
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
----
frontend/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="icon" type="image/png" href="/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Repo Digest Tool</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
----
frontend/tailwind.config.js
/** @type {import('tailwindcss').Config} */
export default {
darkMode: ['class'],
content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],
theme: {
extend: {
borderRadius: {
lg: 'var(--radius)',
md: 'calc(var(--radius) - 2px)',
sm: 'calc(var(--radius) - 4px)'
},
colors: {
background: 'hsl(var(--background))',
foreground: 'hsl(var(--foreground))',
card: {
DEFAULT: 'hsl(var(--card))',
foreground: 'hsl(var(--card-foreground))'
},
popover: {
DEFAULT: 'hsl(var(--popover))',
foreground: 'hsl(var(--popover-foreground))'
},
primary: {
DEFAULT: 'hsl(var(--primary))',
foreground: 'hsl(var(--primary-foreground))'
},
secondary: {
DEFAULT: 'hsl(var(--secondary))',
foreground: 'hsl(var(--secondary-foreground))'
},
muted: {
DEFAULT: 'hsl(var(--muted))',
foreground: 'hsl(var(--muted-foreground))'
},
accent: {
DEFAULT: 'hsl(var(--accent))',
foreground: 'hsl(var(--accent-foreground))'
},
destructive: {
DEFAULT: 'hsl(var(--destructive))',
foreground: 'hsl(var(--destructive-foreground))'
},
border: 'hsl(var(--border))',
input: 'hsl(var(--input))',
ring: 'hsl(var(--ring))',
chart: {
'1': 'hsl(var(--chart-1))',
'2': 'hsl(var(--chart-2))',
'3': 'hsl(var(--chart-3))',
'4': 'hsl(var(--chart-4))',
'5': 'hsl(var(--chart-5))'
}
}
}
},
plugins: [require("tailwindcss-animate")],
};
----
frontend/tsconfig.app.json
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src"]
}
----
frontend/.gitignore
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
----
frontend/package.json
{
"name": "vite-react-typescript-starter",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"lint": "eslint .",
"preview": "vite preview",
"generate-types": "openapi-typescript http://0.0.0.0:8000/openapi.json -o src/lib/api/schema.d.ts"
},
"dependencies": {
"@radix-ui/react-checkbox": "^1.1.3",
"@radix-ui/react-dialog": "^1.1.2",
"@radix-ui/react-label": "^2.1.0",
"@radix-ui/react-navigation-menu": "^1.2.1",
"@radix-ui/react-scroll-area": "^1.2.1",
"@radix-ui/react-select": "^2.1.2",
"@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-toast": "^1.2.2",
"@radix-ui/react-tooltip": "^1.1.4",
"@tanstack/react-query": "^5.62.7",
"@tanstack/react-query-devtools": "^5.62.7",
"chart.js": "^4.4.7",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.468.0",
"minimatch": "^9.0.0",
"openapi-fetch": "^0.13.3",
"react": "^18.3.1",
"react-chartjs-2": "^5.2.0",
"react-dom": "^18.3.1",
"react-router": "7.0.2",
"tailwind-merge": "^2.5.5",
"tailwindcss-animate": "^1.0.7"
},
"devDependencies": {
"@eslint/js": "^9.16.0",
"@tanstack/eslint-plugin-query": "^5.62.1",
"@types/minimatch": "^5.1.2",
"@types/node": "^22.10.2",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "^10.4.20",
"eslint": "^9.16.0",
"eslint-plugin-react-hooks": "^5.1.0",
"eslint-plugin-react-refresh": "^0.4.16",
"globals": "^15.13.0",
"openapi-typescript": "^7.4.4",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.16",
"typescript": "^5.7.2",
"typescript-eslint": "^8.18.0",
"vite": "^6.0.3"
},
"packageManager": "[email protected]"
}
----
frontend/components.json
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/index.css",
"baseColor": "zinc",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}
----
frontend/tsconfig.json
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
],
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
----
frontend/eslint.config.js
import js from "@eslint/js";
import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
export default tseslint.config(
{ ignores: ["dist"] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
"react-hooks": reactHooks,
"react-refresh": reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
"react-refresh/only-export-components": "off",
},
}
);
----
frontend/vite.config.ts
import { defineConfig } from 'vite';
import react from "@vitejs/plugin-react";
import path from "path";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
optimizeDeps: {
exclude: ['lucide-react'],
},
resolve: {
alias: {
"@": path.resolve(__dirname, "src"),
},
},
});
----
frontend/postcss.config.js
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
----
repo_tool/__init__.py
"""
repo-digest-tool: CLI tool to generate a summary of a repository
"""
__version__ = "0.1.0"
from repo_tool.core.contants import DIGEST_DIR
from repo_tool.core.digest import generate_digest
from repo_tool.core.github import GitHub
__all__ = ["generate_digest", "GitHub", "DIGEST_DIR"]
----
repo_tool/cli.py
from datetime import datetime
from typing import Optional
import humanize
import typer
from git.exc import GitCommandError
from rich import box
from rich.console import Console
from rich.table import Table
from typer import Typer
from repo_tool.core.digest import generate_digest
from repo_tool.core.github import GitHub
app = Typer()
github = GitHub()
@app.command(name="add")
def add(
repo_url: str = typer.Argument(..., help="GitHub repository URL"),
branch: Optional[str] = typer.Option(None, help="Branch to add"),
force: bool = typer.Option(False, help="Force re-download if exists"),
) -> None:
"""
Add a GitHub repository to the tool.
"""
try:
typer.secho(f"Adding repository {repo_url}...")
github.clone(repo_url, branch, force)
typer.secho(f"Repository {repo_url} was successfully added!")
except GitCommandError as e:
typer.secho(f"Git error: {e}", fg=typer.colors.RED)
raise typer.Abort() from e
except Exception as e:
typer.secho(f"An unexpected error occurred: {e}", fg=typer.colors.RED)
raise typer.Abort() from e
@app.command(name="list")
def list() -> None:
"""
List all added repositories in a pretty table format.
"""
repos = github.list()
console = Console()
if not repos:
console.print("No repositories added yet.")
return
# Create a table
table = Table(box=box.SIMPLE)
table.add_column("Repository Name", justify="left")
table.add_column("Author", justify="left")
table.add_column("URL", justify="left")
table.add_column("Branch", justify="left")
table.add_column("Last Updated", justify="left", width=20)
table.add_column("Size", justify="right")
# Populate the table with repository data
for repo in repos:
formatted_time = humanize.naturaltime(datetime.now() - repo.updated_at)
size = humanize.naturalsize(repo.size)
table.add_row(
repo.name,
repo.author,
repo.url,
repo.branch or "N/A",
formatted_time,
size,
)
# Print the table
console.print(table)
@app.command(name="remove")
def remove(repo_name: str = typer.Argument(..., help="Repository name")) -> None:
"""
Remove a repository.
"""
try:
repo_exists = github.repo_exists(repo_name)
if not repo_exists:
typer.secho(f"Repository {repo_name} not found.", fg=typer.colors.RED)
return
github.remove(repo_name)
typer.secho(f"Repository {repo_name} removed successfully!")
except Exception as e:
typer.secho(f"An unexpected error occurred: {e}", fg=typer.colors.RED)
raise typer.Abort() from e
@app.command(name="clean")
def clean() -> None:
"""
Clean up all repositories.
"""
github.clean()
@app.command(name="update")
def update(
repo_url: Optional[str] = typer.Argument(None, help="Repository URL")
) -> None:
"""
Update a repository.
"""
try:
updated_repos = github.update(repo_url)
if len(updated_repos) == 0:
typer.secho("No repositories updated.", fg=typer.colors.YELLOW)
else:
for repo in updated_repos:
typer.secho(f"Updated repository: {repo.name}")
except Exception as e:
typer.secho(f"An unexpected error occurred: {e}", fg=typer.colors.RED)
raise typer.Abort() from e
@app.command(name="digest")
def digest(
repo_url: str = typer.Argument(..., help="Repository URL"),
branch: Optional[str] = typer.Option(None, help="Branch to generate digest for"),
prompt: Optional[str] = typer.Option(None, help="Prompt to generate digest with"),
) -> None:
"""
Generate a digest for a repository.
"""
try:
repo_path = GitHub.get_repo_path(repo_url)
if not github.repo_exists(repo_url):
typer.secho(f"Repository {repo_url} not found. Cloning...")
github.clone(repo_url, branch)
elif branch:
github.checkout(repo_path, branch)
generate_digest(repo_path, prompt)
typer.secho(
f"Digest generated successfully at digests/{repo_path.name}.txt",
)
except Exception as e:
typer.secho(f"An unexpected error occurred: {e}", fg=typer.colors.RED)
raise typer.Abort() from e
if __name__ == "__main__":
app()
----
tests/github_test.py
import shutil
from pathlib import Path
from typing import Generator
import pytest
from git import GitCommandError
from repo_tool.core.github import REPO_DIR, GitHub
# Constants for testing
TEST_REPO_URL = "https://github.com/octocat/hello-world" # Small public repository
TEST_REPO_AUTHOR = "octocat"