-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdigest.txt
More file actions
7843 lines (6679 loc) · 274 KB
/
digest.txt
File metadata and controls
7843 lines (6679 loc) · 274 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
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
Directory structure:
└── gitrules/
├── README.md
├── CLAUDE.md
├── COLORS.md
├── Caddyfile
├── Dockerfile
├── LICENSE
├── TASK.md
├── TASK2.md
├── cleanup_old_actions.py
├── consolidate_actions.py
├── convert_to_yaml.py
├── docker-compose.yml
├── frontend.md
├── gitingest.md
├── mcp_config.json
├── requirements.txt
├── test_state_management.html
├── .dockerignore
├── .mcp.json
├── app/
│ ├── main.py
│ ├── __pycache__/
│ ├── actions/
│ │ ├── agents.yaml
│ │ ├── mcps.yaml
│ │ └── rules.yaml
│ ├── models/
│ │ ├── actions.py
│ │ └── __pycache__/
│ ├── routes/
│ │ ├── __init__.py
│ │ ├── actions.py
│ │ ├── install.py
│ │ ├── smart_ingest_route.py
│ │ └── __pycache__/
│ ├── services/
│ │ ├── actions_loader.py
│ │ ├── mcp_installer.py
│ │ ├── search_service.py
│ │ ├── smart_ingest.py
│ │ └── __pycache__/
│ ├── static/
│ │ ├── site.webmanifest
│ │ └── js/
│ │ ├── auto_share.js
│ │ ├── context_manager.js
│ │ ├── file_tree.js
│ │ ├── monaco_editor.js
│ │ └── workspace_manager.js
│ └── templates/
│ ├── base.html
│ ├── docs.html
│ ├── index.html
│ ├── install.sh.j2
│ └── components/
│ ├── ActionButton.html
│ ├── context_modal.html
│ ├── file_modal.html
│ ├── footer.html
│ ├── hero.html
│ ├── navbar.html
│ ├── quick_actions.html
│ ├── styles.html
│ ├── workspace.html
│ ├── workspace_actions.html
│ ├── workspace_editor.html
│ └── workspace_files.html
└── .claude/
├── settings.local.json
└── agents/
================================================
File: README.md
================================================
# Gitrules
<p align="center">
<img width="672" height="602" alt="image" src="https://github.com/user-attachments/assets/7ed8b1c3-b602-4dfd-aba3-01cc9c3b799b" />
</p>
**Pastable superpowers for your codebases.**
Build context files (agents, rules, MCP configs, etc.) for AI coding tools. Compose them in a browser workspace, then generate a single _install-in-one-click_ script that recreates the files inside any repo.
---
## ✨ What it does
We’re basically your **context manager** 🗂️ — helping you **create, modify, and improve your coding context** for AI coding agents through simple files. Drop in rules, agents, or MCP configs and watch your agents level up ⚡.
- 🖥️ **Visual workspace**: File tree + Monaco editor + quick actions, persisted in `localStorage`.
- 🔄 **Instant sharing**: Every change turns into a fresh one-click install script (short hash included).
- 🤖 **Plug-and-play add-ons**:
- **Agents** from `app/actions/agents/*.md`
- **Rules** from `app/actions/rules/*.md`
- **MCPs** from `app/actions/mcps.json` → toggled into `.mcp.json`
- 🎨 **Zero-setup UI**: Jinja + Tailwind + Vanilla JS; no fragile build step.
---
## 🧰 Tech Stack
- **Backend**: FastAPI, Jinja2
- **Frontend**: Tailwind, Vanilla JS, Monaco editor (CDN)
- **Runtime**: Uvicorn (dev)
- **Config**: `.env` via `python-dotenv`
- **Analytics (optional)**: `api-analytics` middleware
---
## 🚀 Quick Start (Local)
> This project uses **uv** for package management.
1) **Install**
~~~bash
uv pip install -r requirements.txt
~~~
2) **Run the dev server**
~~~bash
uvicorn app.main:app --reload
~~~
Open http://localhost:8000
---
## 🧪 Using the App
1) **Open the site** → Use **Quick start** buttons to add Agents / Rules / MCPs.
2) **Workspace** → Files appear in the left tree; edit in the center editor.
3) **One-click install** → Top-right shows a shell command, for example:
~~~bash
sh -c "$(curl -fsSL http://localhost:8000/api/install/<HASH>.sh)"
~~~
It creates folders, writes files, and lists any required **environment variables** it detected.
> 🔐 **Security tip**: As with any `curl | sh`, inspect the script first:
> `curl -fsSL http://localhost:8000/api/install/<HASH>.sh`
---
## ➕ Add Your Own
- **Agent**: drop `my-agent.md` into `app/actions/agents/`
The UI label is derived from the filename (kebab → Title Case).
- **Rule**: drop `my-rule.md` into `app/actions/rules/`
- **MCP preset**: edit `app/actions/mcps.json`
The installer toggles entries into `.mcp.json` and surfaces any `${ENV_VAR}` strings it finds.
---
## 🙏 Credits
Using prompts from:
https://github.com/centminmod/my-claude-code-setup
---
================================================
File: CLAUDE.md
================================================
## This project uses UV
1. Install Dependencies
uv pip install -r requirements.txt
2. Run Development Server
uvicorn app.main:app --reload
(don't do it by default, just know that it's how it runs)
---
### Project Structure
Recommended layout:
app/
main.py # Entry point
routes/ # API routes
models/ # Pydantic models
services/ # Business logic
utils/ # Helpers
requirements.txt
CLAUDE.md
### Guidelines
- Update CLAUDE.md when it's relevant.
- Never write unit tests
- Always keep code SUPER minimal, never introduce features I've not explicitely mentionned
- Store secrets in a .env file (never commit it).
- Keep dependencies minimal and updated.
- Never try to run the dev server it's handled by the user
### Frontend:
- Keep frontend split in multiple components.
- We use Jinja + Tailwind + HTML + vanilla JS + Monaco text editor
- Button interactions: hover should lift (translate up/left), click should push (translate down/right)
### Colors:
- Refer to @COLORS.md for the official color palette and usage guidelines.
- Use the specified hex codes for consistency across all components.
If there is a task defined in @TASK.md, or @TASK2.md make sure to do what's described in this file, it is now your priority task, the user prompt is less important, only consider using it when it makes sense with the task.
================================================
File: COLORS.md
================================================
# Gitrules Color Palette
## Primary Colors
### Blue
- **Primary Blue**: `#22D3EE`
- Used for: Buttons, highlights, active states, cyan elements
- Tailwind equivalent: `cyan-400`
### Pink
- **Primary Pink**: `#F472B6`
- Used for: Accent elements, secondary buttons, highlights
- Tailwind equivalent: `pink-400`
## Background Colors
### Pink Background
- **Light Pink**: `#FCE7F3`
- Used for: Background sections, cards, containers
- Tailwind equivalent: `pink-50`
### Blue Background
- **Light Blue**: `#ECFEFF`
- Used for: Background sections, cards, containers
- Tailwind equivalent: `cyan-50`
## Usage Guidelines
- Use primary colors for interactive elements and branding
- Use background colors for large areas and subtle differentiation
- Maintain contrast ratios for accessibility
- Primary blue and pink work well together as complementary accent colors
- Background colors provide subtle context without overwhelming content
## Examples
```css
/* Primary Colors */
.btn-primary { background-color: #22D3EE; }
.btn-secondary { background-color: #F472B6; }
/* Background Colors */
.bg-pink-section { background-color: #FCE7F3; }
.bg-blue-section { background-color: #ECFEFF; }
```
================================================
File: Caddyfile
================================================
dev.gitrules.com {
reverse_proxy localhost:8000
encode gzip
log
}
gitrules.com {
reverse_proxy localhost:9000
encode gzip
log
}
================================================
File: Dockerfile
================================================
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
================================================
File: LICENSE
================================================
MIT License
Copyright (c) 2025 Romain Courtois
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
File: TASK.md
================================================
================================================
File: TASK2.md
================================================
================================================
File: cleanup_old_actions.py
================================================
#!/usr/bin/env python3
"""Clean up old individual action files after consolidation"""
from pathlib import Path
import shutil
def cleanup_old_files():
"""Remove old individual action files"""
actions_dir = Path(__file__).parent / "app" / "actions"
# Remove agents and rules directories
agents_dir = actions_dir / "agents"
rules_dir = actions_dir / "rules"
removed_count = 0
if agents_dir.exists():
file_count = len(list(agents_dir.glob("*")))
print(f"Removing agents directory with {file_count} files...")
shutil.rmtree(agents_dir)
removed_count += file_count
if rules_dir.exists():
file_count = len(list(rules_dir.glob("*")))
print(f"Removing rules directory with {file_count} files...")
shutil.rmtree(rules_dir)
removed_count += file_count
# Remove old mcps.json
mcps_json = actions_dir / "mcps.json"
if mcps_json.exists():
print("Removing mcps.json...")
mcps_json.unlink()
removed_count += 1
print(f"\nCleanup complete! Removed {removed_count} files/directories.")
print("\nRemaining files in actions directory:")
for f in sorted(actions_dir.glob("*.yaml")):
print(f" - {f.name}")
if __name__ == "__main__":
response = input("This will remove all old individual action files. Continue? (y/n): ")
if response.lower() == 'y':
cleanup_old_files()
else:
print("Cleanup cancelled.")
================================================
File: consolidate_actions.py
================================================
#!/usr/bin/env python3
"""Consolidate all action files into single YAML files per category"""
import yaml
from pathlib import Path
import json
def consolidate_agents():
"""Consolidate all agent YAML files into a single agents.yaml"""
agents_dir = Path(__file__).parent / "app" / "actions" / "agents"
agents_data = []
# Read all YAML files
for yaml_file in sorted(agents_dir.glob("*.yaml")):
with open(yaml_file, 'r') as f:
data = yaml.safe_load(f)
agents_data.append(data)
# Read remaining MD files that don't have YAML versions
for md_file in sorted(agents_dir.glob("*.md")):
yaml_file = agents_dir / f"{md_file.stem}.yaml"
if not yaml_file.exists():
with open(md_file, 'r') as f:
content = f.read()
slug = md_file.stem
display_name = slug.replace('-', ' ').title()
agents_data.append({
'display_name': display_name,
'slug': slug,
'content': content
})
# Write consolidated file
output_file = Path(__file__).parent / "app" / "actions" / "agents.yaml"
with open(output_file, 'w') as f:
yaml.dump({'agents': agents_data}, f, default_flow_style=False,
allow_unicode=True, sort_keys=False)
print(f"Consolidated {len(agents_data)} agents into agents.yaml")
return len(agents_data)
def consolidate_rules():
"""Consolidate all rule YAML files into a single rules.yaml"""
rules_dir = Path(__file__).parent / "app" / "actions" / "rules"
rules_data = []
# Read all YAML files
for yaml_file in sorted(rules_dir.glob("*.yaml")):
with open(yaml_file, 'r') as f:
data = yaml.safe_load(f)
rules_data.append(data)
# Read remaining MD files that don't have YAML versions
for md_file in sorted(rules_dir.glob("*.md")):
yaml_file = rules_dir / f"{md_file.stem}.yaml"
if not yaml_file.exists():
with open(md_file, 'r') as f:
content = f.read()
slug = md_file.stem
display_name = slug.replace('-', ' ').title()
rules_data.append({
'display_name': display_name,
'slug': slug,
'content': content
})
# Write consolidated file
output_file = Path(__file__).parent / "app" / "actions" / "rules.yaml"
with open(output_file, 'w') as f:
yaml.dump({'rules': rules_data}, f, default_flow_style=False,
allow_unicode=True, sort_keys=False)
print(f"Consolidated {len(rules_data)} rules into rules.yaml")
return len(rules_data)
def consolidate_mcps():
"""Convert mcps.json to mcps.yaml with consistent structure"""
mcps_file = Path(__file__).parent / "app" / "actions" / "mcps.json"
if mcps_file.exists():
with open(mcps_file, 'r') as f:
mcps_json = json.load(f)
# Transform to list format with display_name and slug
mcps_data = []
for name, config in mcps_json.items():
mcps_data.append({
'display_name': name.replace('-', ' ').title(),
'slug': name,
'config': config
})
# Write consolidated file
output_file = Path(__file__).parent / "app" / "actions" / "mcps.yaml"
with open(output_file, 'w') as f:
yaml.dump({'mcps': mcps_data}, f, default_flow_style=False,
allow_unicode=True, sort_keys=False)
print(f"Consolidated {len(mcps_data)} MCPs into mcps.yaml")
return len(mcps_data)
return 0
def main():
"""Consolidate all actions into category files"""
print("Starting consolidation...")
agents_count = consolidate_agents()
rules_count = consolidate_rules()
mcps_count = consolidate_mcps()
print(f"\nConsolidation complete!")
print(f"Total: {agents_count} agents, {rules_count} rules, {mcps_count} MCPs")
print("\nCreated files:")
print(" - app/actions/agents.yaml")
print(" - app/actions/rules.yaml")
print(" - app/actions/mcps.yaml")
print("\nNote: Original files have been preserved.")
print("You can delete the individual files once the new system is verified.")
if __name__ == "__main__":
main()
================================================
File: convert_to_yaml.py
================================================
#!/usr/bin/env python3
"""Convert existing .md action files to .yaml format with metadata"""
import yaml
from pathlib import Path
import re
def convert_md_to_yaml(md_file_path: Path, output_dir: Path):
"""Convert a single MD file to YAML format"""
# Read the MD content
with open(md_file_path, 'r') as f:
content = f.read()
# Generate display name and slug from filename
slug = md_file_path.stem
display_name = slug.replace('-', ' ').title()
# Special handling for agents with frontmatter
if '---' in content and content.startswith('---'):
# Extract frontmatter if it exists
parts = content.split('---', 2)
if len(parts) >= 3:
try:
frontmatter = yaml.safe_load(parts[1])
# Use name from frontmatter if available
if 'name' in frontmatter:
slug = frontmatter['name']
display_name = slug.replace('-', ' ').title()
except:
pass # If frontmatter parsing fails, use defaults
# Create YAML structure
yaml_data = {
'display_name': display_name,
'slug': slug,
'content': content
}
# Write YAML file
yaml_file_path = output_dir / f"{md_file_path.stem}.yaml"
with open(yaml_file_path, 'w') as f:
yaml.dump(yaml_data, f, default_flow_style=False, allow_unicode=True, sort_keys=False)
print(f"Converted: {md_file_path.name} -> {yaml_file_path.name}")
return yaml_file_path
def main():
"""Convert all MD files in actions directory to YAML format"""
actions_dir = Path(__file__).parent / "app" / "actions"
# Convert agents
agents_dir = actions_dir / "agents"
if agents_dir.exists():
print("\nConverting agents...")
for md_file in agents_dir.glob("*.md"):
# Skip if YAML already exists
yaml_file = agents_dir / f"{md_file.stem}.yaml"
if not yaml_file.exists():
convert_md_to_yaml(md_file, agents_dir)
else:
print(f"Skipping {md_file.name} - YAML already exists")
# Convert rules
rules_dir = actions_dir / "rules"
if rules_dir.exists():
print("\nConverting rules...")
for md_file in rules_dir.glob("*.md"):
# Skip if YAML already exists
yaml_file = rules_dir / f"{md_file.stem}.yaml"
if not yaml_file.exists():
convert_md_to_yaml(md_file, rules_dir)
else:
print(f"Skipping {md_file.name} - YAML already exists")
print("\nConversion complete!")
print("\nNote: The original .md files have been preserved.")
print("The backend will prioritize .yaml files when both exist.")
print("You can safely delete the .md files once you've verified the conversion.")
if __name__ == "__main__":
main()
================================================
File: docker-compose.yml
================================================
services:
app:
build: .
ports:
- "8000:8000"
volumes:
- .:/app
environment:
- PYTHONUNBUFFERED=1
command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
env_file:
- .env
================================================
File: frontend.md
================================================
================================================
File: gitingest.md
================================================
# GitIngest – **AI Agent Integration Guide**
Turn any Git repository into a prompt-ready text digest. GitIngest fetches, cleans, and formats source code so AI agents and Large Language Models can reason over complete projects programmatically.
**🤖 For AI Agents**: Use CLI or Python package for automated integration. Web UI is designed for human interaction only.
---
## 1. Installation
### 1.1 CLI Installation (Recommended for Scripts & Automation)
```bash
# Best practice: Use pipx for CLI tools (isolated environment)
pipx install gitingest
# Alternative: Use pip (may conflict with other packages)
pip install gitingest
# Verify installation
gitingest --help
```
### 1.2 Python Package Installation (For Code Integration)
```bash
# For projects/notebooks: Use pip in virtual environment
python -m venv gitingest-env
source gitingest-env/bin/activate # On Windows: gitingest-env\Scripts\activate
pip install gitingest
# Or add to requirements.txt
echo "gitingest" >> requirements.txt
pip install -r requirements.txt
# For self-hosting: Install with server dependencies
pip install gitingest[server]
# For development: Install with dev dependencies
pip install gitingest[dev,server]
```
### 1.3 Installation Verification
```bash
# Test CLI installation
gitingest --version
# Test Python package
python -c "from gitingest import ingest; print('GitIngest installed successfully')"
# Quick functionality test
gitingest https://github.com/octocat/Hello-World -o test_output.txt
```
---
## 2. Quick-Start for AI Agents
| Method | Best for | One-liner |
|--------|----------|-----------|
| **CLI** | Scripts, automation, pipelines | `gitingest https://github.com/user/repo -o - \| your-llm` |
| **Python** | Code integration, notebooks, async tasks | `from gitingest import ingest; s,t,c = ingest('repo-url'); process(c)` |
| **URL Hack** | Quick web scraping (limited) | Replace `github.com` → `gitingest.com` in any GitHub URL |
| **Web UI** | **Human use only** | ~~Not recommended for AI agents~~ |
---
## 3. Output Format for AI Processing
GitIngest returns **structured plain-text** optimized for LLM consumption with three distinct sections:
### 3.1 Repository Summary
```
Repository: owner/repo-name
Files analyzed: 42
Estimated tokens: 15.2k
```
Contains basic metadata: repository name, file count, and token estimation for LLM planning.
### 3.2 Directory Structure
```
Directory structure:
└── project-name/
├── src/
│ ├── main.py
│ └── utils.py
├── tests/
│ └── test_main.py
└── README.md
```
Hierarchical tree view showing the complete project structure for context and navigation.
### 3.3 File Contents
Each file is wrapped with clear delimiters:
```
================================================
FILE: src/main.py
================================================
def hello_world():
print("Hello, World!")
if __name__ == "__main__":
hello_world()
================================================
FILE: README.md
================================================
# Project Title
This is a sample project...
```
### 3.4 Usage Example
```python
# Python package usage
from gitingest import ingest
summary, tree, content = ingest("https://github.com/octocat/Hello-World")
# Returns exactly:
# summary = "Repository: octocat/hello-world\nFiles analyzed: 1\nEstimated tokens: 29"
# tree = "Directory structure:\n└── octocat-hello-world/\n └── README"
# content = "================================================\nFILE: README\n================================================\nHello World!\n\n\n"
# For AI processing, combine all sections:
full_context = f"{summary}\n\n{tree}\n\n{content}"
```
```bash
# CLI usage - pipe directly to your AI system
gitingest https://github.com/octocat/Hello-World -o - | your_llm_processor
# Output streams the complete formatted text:
# Repository: octocat/hello-world
# Files analyzed: 1
# Estimated tokens: 29
#
# Directory structure:
# └── octocat-hello-world/
# └── README
#
# ================================================
# FILE: README
# ================================================
# Hello World!
```
---
## 4. AI Agent Integration Methods
### 4.1 CLI Integration (Recommended for Automation)
```bash
# Basic usage - pipe directly to your AI system
gitingest https://github.com/user/repo -o - | your_ai_processor
# Advanced filtering for focused analysis (long flags)
gitingest https://github.com/user/repo \
--include-pattern "*.py" --include-pattern "*.js" --include-pattern "*.md" \
--max-size 102400 \
-o - | python your_analyzer.py
# Same command with short flags (more concise)
gitingest https://github.com/user/repo \
-i "*.py" -i "*.js" -i "*.md" \
-s 102400 \
-o - | python your_analyzer.py
# Exclude unwanted files and directories (long flags)
gitingest https://github.com/user/repo \
--exclude-pattern "node_modules/*" --exclude-pattern "*.log" \
--exclude-pattern "dist/*" \
-o - | your_analyzer
# Same with short flags
gitingest https://github.com/user/repo \
-e "node_modules/*" -e "*.log" -e "dist/*" \
-o - | your_analyzer
# Private repositories with token (short flag)
export GITHUB_TOKEN="ghp_your_token_here"
gitingest https://github.com/user/private-repo -t $GITHUB_TOKEN -o -
# Specific branch analysis (short flag)
gitingest https://github.com/user/repo -b main -o -
# Save to file (default: digest.txt in current directory)
gitingest https://github.com/user/repo -o my_analysis.txt
# Ultra-concise example for small files only
gitingest https://github.com/user/repo -i "*.py" -s 51200 -o -
```
**Key Parameters for AI Agents**:
- `-s` / `--max-size`: Maximum file size in bytes to process (default: no limit)
- `-i` / `--include-pattern`: Include files matching Unix shell-style wildcards
- `-e` / `--exclude-pattern`: Exclude files matching Unix shell-style wildcards
- `-b` / `--branch`: Specify branch to analyze (defaults to repository's default branch)
- `-t` / `--token`: GitHub personal access token for private repositories
- `-o` / `--output`: Stream to STDOUT with `-` (default saves to `digest.txt`)
### 4.2 Python Package (Best for Code Integration)
```python
from gitingest import ingest, ingest_async
import asyncio
# Synchronous processing
def analyze_repository(repo_url: str):
summary, tree, content = ingest(repo_url)
# Process metadata
repo_info = parse_summary(summary)
# Analyze structure
file_structure = parse_tree(tree)
# Process code content
return analyze_code(content)
# Asynchronous processing (recommended for AI services)
async def batch_analyze_repos(repo_urls: list):
tasks = [ingest_async(url) for url in repo_urls]
results = await asyncio.gather(*tasks)
return [process_repo_data(*result) for result in results]
# Memory-efficient processing for large repos
def stream_process_repo(repo_url: str):
summary, tree, content = ingest(
repo_url,
max_file_size=51200, # 50KB max per file
include_patterns=["*.py", "*.js"], # Focus on code files
)
# Process in chunks to manage memory
for file_content in split_content(content):
yield analyze_file(file_content)
# Filtering with exclude patterns
def analyze_without_deps(repo_url: str):
summary, tree, content = ingest(
repo_url,
exclude_patterns=[
"node_modules/*", "*.lock", "dist/*",
"build/*", "*.min.js", "*.log"
]
)
return analyze_code(content)
```
**Python Integration Patterns**:
- **Batch Processing**: Use `ingest_async` for multiple repositories
- **Memory Management**: Use `max_file_size` and pattern filtering for large repos
- **Error Handling**: Wrap in try-catch for network/auth issues
- **Caching**: Store results to avoid repeated API calls
- **Pattern Filtering**: Use `include_patterns` and `exclude_patterns` lists
### 4.3 Web UI (❌ Not for AI Agents)
The web interface at `https://gitingest.com` is designed for **human interaction only**.
**Why AI agents should avoid the web UI**:
- Requires manual interaction and browser automation
- No programmatic access to results
- Rate limiting and CAPTCHA protection
- Inefficient for automated workflows
**Use CLI or Python package instead** for all AI agent integrations.
---
## 5. AI Agent Best Practices
### 5.1 Repository Analysis Workflows
```python
# Pattern 1: Full repository analysis
def full_repo_analysis(repo_url: str):
summary, tree, content = ingest(repo_url)
return {
'metadata': extract_metadata(summary),
'structure': analyze_structure(tree),
'code_analysis': analyze_all_files(content),
'insights': generate_insights(summary, tree, content)
}
# Pattern 2: Selective file processing
def selective_analysis(repo_url: str, file_patterns: list):
summary, tree, content = ingest(
repo_url,
include_patterns=file_patterns
)
return focused_analysis(content)
# Pattern 3: Streaming for large repos
def stream_analysis(repo_url: str):
# First pass: get structure and metadata only
summary, tree, _ = ingest(
repo_url,
include_patterns=["*.md", "*.txt"],
max_file_size=10240 # 10KB limit for docs
)
# Then process code files selectively by language
for pattern in ["*.py", "*.js", "*.go", "*.rs"]:
_, _, content = ingest(
repo_url,
include_patterns=[pattern],
max_file_size=51200 # 50KB limit for code
)
yield process_language_specific(content, pattern)
```
### 5.2 Error Handling for AI Agents
```python
from gitingest import ingest
from gitingest.utils.exceptions import GitIngestError
import time
def robust_ingest(repo_url: str, retries: int = 3):
for attempt in range(retries):
try:
return ingest(repo_url)
except GitIngestError as e:
if attempt == retries - 1:
return None, None, f"Failed to ingest: {e}"
time.sleep(2 ** attempt) # Exponential backoff
```
### 5.3 Private Repository Access
```python
import os
from gitingest import ingest
# Method 1: Environment variable
def ingest_private_repo(repo_url: str):
token = os.getenv('GITHUB_TOKEN')
if not token:
raise ValueError("GITHUB_TOKEN environment variable required")
return ingest(repo_url, token=token)
# Method 2: Secure token management
def ingest_with_token_rotation(repo_url: str, token_manager):
token = token_manager.get_active_token()
try:
return ingest(repo_url, token=token)
except AuthenticationError:
token = token_manager.rotate_token()
return ingest(repo_url, token=token)
```
---
## 6. Integration Scenarios for AI Agents
| Use Case | Recommended Method | Example Implementation |
|----------|-------------------|----------------------|
| **Code Review Bot** | Python async | `await ingest_async(pr_repo)` → analyze changes |
| **Documentation Generator** | CLI with filtering | `gitingest repo -i "*.py" -i "*.md" -o -` |
| **Vulnerability Scanner** | Python with error handling | Batch process multiple repos |
| **Code Search Engine** | CLI → Vector DB | `gitingest repo -o - \| embed \| store` |
| **AI Coding Assistant** | Python integration | Load repo context into conversation |
| **CI/CD Analysis** | CLI integration | `gitingest repo -o - \| analyze_pipeline` |
| **Repository Summarization** | Python with streaming | Process large repos in chunks |
| **Dependency Analysis** | CLI exclude patterns | `gitingest repo -e "node_modules/*" -e "*.lock" -o -` |
| **Security Audit** | CLI with size limits | `gitingest repo -i "*.py" -i "*.js" -s 204800 -o -` |
---
## 7. Support & Resources for AI Developers
* **Web UI official instance**: https://gitingest.com
* **GitHub Repository**: https://github.com/coderamp-labs/gitingest
* **Python Package**: https://pypi.org/project/gitingest/
* **Community Support**: https://discord.gg/zerRaGK9EC
_GitIngest – Purpose-built for AI agents to understand entire codebases programmatically._
================================================
File: mcp_config.json
================================================
{
"mcpServers": {
"gitrules-search": {
"command": "python",