-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdigest.txt
2583 lines (2130 loc) · 96.6 KB
/
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
Directory structure:
└── cyclotruc-gitingest/
├── CODE_OF_CONDUCT.md
├── pytest.ini
├── LICENSE
├── requirements.txt
├── Dockerfile
├── docs/
├── README.md
├── setup.py
├── SECURITY.md
└── src/
├── routers/
│ ├── index.py
│ ├── download.py
│ ├── __init__.py
│ └── dynamic.py
├── config.py
├── __init__.py
├── process_query.py
├── server_utils.py
├── static/
│ ├── js/
│ │ ├── snow.js
│ │ └── utils.js
│ └── robots.txt
├── templates/
│ ├── api.jinja
│ ├── base.jinja
│ ├── github.jinja
│ ├── components/
│ │ ├── github_form.jinja
│ │ ├── navbar.jinja
│ │ ├── result.jinja
│ │ └── footer.jinja
│ └── index.jinja
├── main.py
└── gitingest/
├── ingest.py
├── ingest_from_query.py
├── tests/
│ ├── conftest.py
│ ├── __init__.py
│ ├── test_clone.py
│ ├── test_ingest.py
│ └── test_parse_query.py
├── __init__.py
├── cli.py
├── utils.py
├── parse_query.py
└── clone.py
================================================
File: /CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
================================================
File: /pytest.ini
================================================
[pytest]
pythonpath = src
testpaths = src/gitingest/tests
asyncio_mode = auto
# Coverage configuration
addopts = --no-cov
python_files = test_*.py
python_classes = Test*
python_functions = test_*
================================================
File: /LICENSE
================================================
MIT License
Copyright (c) 2024 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: /requirements.txt
================================================
fastapi[standard]
uvicorn
fastapi-analytics
slowapi
tiktoken
pytest
pytest-asyncio
click>=8.0.0
================================================
File: /Dockerfile
================================================
FROM python:3.12
WORKDIR /app
# Create a non-root user
RUN useradd -m -u 1000 appuser
COPY src/ ./
COPY requirements.txt ./
RUN pip install -r requirements.txt
# Change ownership of the application files
RUN chown -R appuser:appuser /app
# Switch to non-root user
USER appuser
EXPOSE 8000
CMD ["uvicorn", "main:app", "--reload", "--host", "0.0.0.0"]
================================================
File: /README.md
================================================
[![Image](./docs/frontpage.png "GitIngest main page")](https://gitingest.com/)
![License](https://img.shields.io/badge/license-MIT-blue.svg)
# GitIngest 🔍
Turn any Git repository into a prompt-friendly text ingest for LLMs.
You can also replace `hub` with `ingest` in any github url to access the coresponding digest
[gitingest.com](https://gitingest.com/)
## 🚀 Features
- **Easy code context**: Get a text digest from a git repository URL or a directory
- **Smart Formatting**: Optimized output format for LLM prompts
- **Statistics about**: :
- File and directory structure
- Size of the extract
- Token count
- **CLI tool**: Run it as a command (Currently on Linux only)
- **Python package**: Import it in your code
## 📦 Installation
```
pip install gitingest
```
## 💡 Command Line usage
The `gitingest` command line tool allows you to analyze codebases and create a text dump of their contents.
```bash
# Basic usage
gitingest /path/to/directory
# From url
gitingest https://github.com/cyclotruc/gitingest
# See more options
gitingest --help
```
This will write the digest in a text file (default `digest.txt`) in your current working directory.
## 🐛 Python package usage
```python
from gitingest import ingest
summary, tree, content = ingest("path/to/directory")
#or from URL
summary, tree, content = ingest("https://github.com/cyclotruc/gitingest")
```
By default, this won't write a file but can be enabled with the `output` argument
## 🛠️ Using
- Tailwind CSS - Frontend
- [FastAPI](https://github.com/fastapi/fastapi) - Backend framework
- [tiktoken](https://github.com/openai/tiktoken) - Token estimation
- [apianalytics.dev](https://www.apianalytics.dev/) - Simple Analytics
## 🌐 Self-host
1. Build the image:
```
docker build -t gitingest .
```
2. Run the container:
```
docker run -d --name gitingest -p 8000:8000 gitingest
```
The application will be available at `http://localhost:8000`
Ensure environment variables are set before running the application or deploying it via Docker.
## ✔️ Contributing
Contributions are welcome!
Gitingest aims to be friendly for first time contributors, with a simple python and html codebase. If you need any help while working with the code, reach out to us on [discord](https://discord.com/invite/zerRaGK9EC)
### Ways to contribute
1. Provide your feedback and ideas on discord
2. Open an Issue on github to report a bug
2. Create a Pull request
- Fork the repository
- Make your changes and test them locally
- Open a pull request for review and feedback
### 🔧 Local dev
#### Environment Configuration
- **`ALLOWED_HOSTS`**: Specify allowed hostnames for the application. Default: `"gitingest.com,*.gitingest.com,gitdigest.dev,localhost"`.
You can configure the application using the following environment variables:
```bash
ALLOWED_HOSTS="gitingest.local,localhost"
```
#### Run locally
1. Clone the repository
```bash
git clone https://github.com/cyclotruc/gitingest.git
cd gitingest
```
2. Install dependencies
```bash
pip install -r requirements.txt
```
3. Run the application:
```bash
cd src
uvicorn main:app --reload
```
The frontend will be available at `localhost:8000`
================================================
File: /setup.py
================================================
from setuptools import setup, find_packages
setup(
name="gitingest",
version="0.1.2",
packages=find_packages(where="src"),
package_dir={"": "src"},
include_package_data=True,
install_requires=[
"click>=8.0.0",
"tiktoken",
],
entry_points={
"console_scripts": [
"gitingest=gitingest.cli:main",
],
},
python_requires=">=3.6",
author="Romain Courtois",
author_email="[email protected]",
description="CLI tool to analyze and create text dumps of codebases for LLMs",
long_description=open("README.md").read(),
long_description_content_type="text/markdown",
url="https://github.com/cyclotruc/gitingest",
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
],
)
================================================
File: /SECURITY.md
================================================
# Security Policy
## Reporting a Vulnerability
If you have discovered a vulnerability inside the project, report it privately at [email protected]. This way the maintainer can work on a proper fix without disclosing the problem to the public before it has been solved.
================================================
File: /src/routers/index.py
================================================
from fastapi import APIRouter, Request, Form
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from server_utils import limiter
from process_query import process_query
from config import EXAMPLE_REPOS
router = APIRouter()
templates = Jinja2Templates(directory="templates")
@router.get("/", response_class=HTMLResponse)
async def home(request: Request):
return templates.TemplateResponse(
"index.jinja",
{
"request": request,
"examples": EXAMPLE_REPOS,
"default_file_size": 243
}
)
@router.post("/", response_class=HTMLResponse)
@limiter.limit("10/minute")
async def index_post(
request: Request,
input_text: str = Form(...),
max_file_size: int = Form(...),
pattern_type: str = Form(...),
pattern: str = Form(...)
):
return await process_query(request, input_text, max_file_size, pattern_type, pattern, is_index=True)
================================================
File: /src/routers/download.py
================================================
from fastapi import HTTPException, APIRouter
from fastapi.responses import Response
from config import TMP_BASE_PATH
import os
router = APIRouter()
@router.get("/download/{digest_id}")
async def download_ingest(digest_id: str):
try:
# Find the first .txt file in the directory
directory = f"{TMP_BASE_PATH}/{digest_id}"
txt_files = [f for f in os.listdir(directory) if f.endswith('.txt')]
if not txt_files:
raise FileNotFoundError("No .txt file found")
with open(f"{directory}/{txt_files[0]}", "r") as f:
content = f.read()
return Response(
content=content,
media_type="text/plain",
headers={
"Content-Disposition": f"attachment; filename={txt_files[0]}"
}
)
except FileNotFoundError:
raise HTTPException(status_code=404, detail="Digest not found")
================================================
File: /src/routers/__init__.py
================================================
from .download import router as download
from .dynamic import router as dynamic
from .index import router as index
__all__ = ["download", "dynamic", "index"]
================================================
File: /src/routers/dynamic.py
================================================
from fastapi import APIRouter, Request, Form
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from process_query import process_query
from server_utils import limiter
router = APIRouter()
templates = Jinja2Templates(directory="templates")
@router.get("/{full_path:path}")
async def catch_all(request: Request, full_path: str):
return templates.TemplateResponse(
"github.jinja",
{
"request": request,
"github_url": f"https://github.com/{full_path}",
"loading": True,
"default_file_size": 243
}
)
@router.post("/{full_path:path}", response_class=HTMLResponse)
@limiter.limit("10/minute")
async def process_catch_all(
request: Request,
input_text: str = Form(...),
max_file_size: int = Form(...),
pattern_type: str = Form(...),
pattern: str = Form(...)
):
return await process_query(request, input_text, max_file_size, pattern_type, pattern, is_index=False)
================================================
File: /src/config.py
================================================
MAX_DISPLAY_SIZE = 300000
TMP_BASE_PATH = "../tmp"
EXAMPLE_REPOS = [
{"name": "Gitingest", "url": "https://github.com/cyclotruc/gitingest"},
{"name": "FastAPI", "url": "https://github.com/tiangolo/fastapi"},
{"name": "Flask", "url": "https://github.com/pallets/flask"},
{"name": "Tldraw", "url": "https://github.com/tldraw/tldraw"},
{"name": "ApiAnalytics", "url": "https://github.com/tom-draper/api-analytics"},
]
================================================
File: /src/process_query.py
================================================
from typing import List
from fastapi.templating import Jinja2Templates
from fastapi import Request
from config import MAX_DISPLAY_SIZE, EXAMPLE_REPOS
from gitingest import ingest_from_query, clone_repo, parse_query
from server_utils import logSliderToSize
templates = Jinja2Templates(directory="templates")
async def process_query(request: Request, input_text: str, slider_position: int, pattern_type: str = "exclude", pattern: str = "", is_index: bool = False) -> str:
template = "index.jinja" if is_index else "github.jinja"
max_file_size = logSliderToSize(slider_position)
if pattern_type == "include":
include_patterns = pattern
exclude_patterns = None
elif pattern_type == "exclude":
exclude_patterns = pattern
include_patterns = None
try:
query = parse_query(input_text, max_file_size, True, include_patterns, exclude_patterns)
await clone_repo(query)
summary, tree, content = ingest_from_query(query)
with open(f"{query['local_path']}.txt", "w") as f:
f.write(tree + "\n" + content)
print(f"{query['slug']:<20}", end="")
if pattern and pattern != "":
print(f"{pattern_type}[{pattern}]", end="")
print(f"\n{query['url']}")
except Exception as e:
return templates.TemplateResponse(
template,
{
"request": request,
"github_url": input_text,
"error_message": f"Error: {e}",
"examples": EXAMPLE_REPOS if is_index else [],
"default_file_size": slider_position,
"pattern_type": pattern_type,
"pattern": pattern,
}
)
if len(content) > MAX_DISPLAY_SIZE:
content = f"(Files content cropped to {int(MAX_DISPLAY_SIZE/1000)}k characters, download full ingest to see more)\n" + content[:MAX_DISPLAY_SIZE]
return templates.TemplateResponse(
template,
{
"request": request,
"github_url": input_text,
"result": True,
"summary": summary,
"tree": tree,
"content": content,
"examples": EXAMPLE_REPOS if is_index else [],
"ingest_id": query['id'],
"default_file_size": slider_position,
"pattern_type": pattern_type,
"pattern": pattern,
}
)
================================================
File: /src/server_utils.py
================================================
## Rate Limiter
from slowapi import Limiter
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
## Logarithmic slider to file size
import math
def logSliderToSize(position):
"""Convert slider position to file size in KB"""
maxp = 500
minv = math.log(1)
maxv = math.log(102400)
return round(math.exp(minv + (maxv - minv) * pow(position / maxp, 1.5))) * 1024
================================================
File: /src/static/js/snow.js
================================================
// Snow effect initialization
function initSnow() {
const snowCanvas = document.getElementById('snow-canvas');
const ctx = snowCanvas.getContext('2d');
// Configure snow
const snowflakes = [];
const maxSnowflakes = 50;
const spawnInterval = 200;
let currentSnowflakes = 0;
let lastSpawnTime = 0;
// Resize canvas to window size
function resizeCanvas() {
snowCanvas.width = window.innerWidth;
snowCanvas.height = window.innerHeight;
}
// Initial setup
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
// Snowflake class definition
class Snowflake {
constructor() {
this.reset();
}
reset() {
this.x = Math.random() * snowCanvas.width;
this.y = 0;
this.size = Math.random() * 3 + 2;
this.speed = Math.random() * 1 + 0.5;
this.wind = Math.random() * 0.5 - 0.25;
}
update() {
this.y += this.speed;
this.x += this.wind;
if (this.y > snowCanvas.height) {
this.reset();
}
}
draw() {
ctx.save();
ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
ctx.shadowBlur = 5;
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(255, 255, 255, 1)';
ctx.fill();
ctx.strokeStyle = 'rgba(200, 200, 200, 0.8)';
ctx.lineWidth = 0.5;
ctx.stroke();
ctx.restore();
}
}
function animate(currentTime) {
ctx.clearRect(0, 0, snowCanvas.width, snowCanvas.height);
if (currentSnowflakes < maxSnowflakes && currentTime - lastSpawnTime > spawnInterval) {
snowflakes.push(new Snowflake());
currentSnowflakes++;
lastSpawnTime = currentTime;
}
snowflakes.forEach(snowflake => {
snowflake.update();
snowflake.draw();
});
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
}
// Initialize snow when DOM content is loaded
document.addEventListener('DOMContentLoaded', initSnow);
// Also initialize when the HTMX content is swapped
document.addEventListener('htmx:afterSettle', initSnow);
================================================
File: /src/static/js/utils.js
================================================
// Copy functionality
function copyText(className) {
const textarea = document.querySelector('.' + className);
const button = document.querySelector(`button[onclick="copyText('${className}')"]`);
if (!textarea || !button) return;
// Copy text
navigator.clipboard.writeText(textarea.value)
.then(() => {
// Store original content
const originalContent = button.innerHTML;
// Change button content
button.innerHTML = 'Copied!';
// Reset after 1 second
setTimeout(() => {
button.innerHTML = originalContent;
}, 1000);
})
.catch(err => {
// Show error in button
const originalContent = button.innerHTML;
button.innerHTML = 'Failed to copy';
setTimeout(() => {
button.innerHTML = originalContent;
}, 1000);
});
}
function handleSubmit(event, showLoading = false) {
event.preventDefault();
const form = event.target || document.getElementById('ingestForm');
if (!form) return;
const submitButton = form.querySelector('button[type="submit"]');
if (!submitButton) return;
const formData = new FormData(form);
// Update file size
const slider = document.getElementById('file_size');
if (slider) {
formData.delete('max_file_size');
formData.append('max_file_size', slider.value);
}
// Update pattern type and pattern
const patternType = document.getElementById('pattern_type');
const pattern = document.getElementById('pattern');
if (patternType && pattern) {
formData.delete('pattern_type');
formData.delete('pattern');
formData.append('pattern_type', patternType.value);
formData.append('pattern', pattern.value);
}
const originalContent = submitButton.innerHTML;
const currentStars = document.getElementById('github-stars')?.textContent;
if (showLoading) {
submitButton.disabled = true;
submitButton.innerHTML = `
<div class="flex items-center justify-center">
<svg class="animate-spin h-5 w-5 text-gray-900" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<span class="ml-2">Processing...</span>
</div>
`;
submitButton.classList.add('bg-[#ffb14d]');
}
// Submit the form
fetch(form.action, {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(html => {
// Store the star count before updating the DOM
const starCount = currentStars;
// TEMPORARY SNOW LOGIC //
const parser = new DOMParser();
const newDoc = parser.parseFromString(html, 'text/html');
const existingCanvas = document.getElementById('snow-canvas');
document.body.innerHTML = newDoc.body.innerHTML;
if (existingCanvas) {
document.body.insertBefore(existingCanvas, document.body.firstChild);
}
// END TEMPORARY SNOW LOGIC //
// Wait for next tick to ensure DOM is updated
setTimeout(() => {
// Reinitialize slider functionality
initializeSlider();
const starsElement = document.getElementById('github-stars');
if (starsElement && starCount) {
starsElement.textContent = starCount;
}
// Scroll to results if they exist
const resultsSection = document.querySelector('[data-results]');
if (resultsSection) {
resultsSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
}, 0);
})
.catch(error => {
submitButton.disabled = false;
submitButton.innerHTML = originalContent;
});
}
function copyFullDigest() {
const directoryStructure = document.querySelector('.directory-structure').value;
const filesContent = document.querySelector('.result-text').value;
const fullDigest = `${directoryStructure}\n\nFiles Content:\n\n${filesContent}`;
const button = document.querySelector('[onclick="copyFullDigest()"]');
const originalText = button.innerHTML;
navigator.clipboard.writeText(fullDigest).then(() => {
button.innerHTML = `
<svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
</svg>
Copied!
`;
setTimeout(() => {
button.innerHTML = originalText;
}, 2000);
}).catch(err => {
console.error('Failed to copy text: ', err);
});
}
// Add the logSliderToSize helper function
function logSliderToSize(position) {
const minp = 0;
const maxp = 500;
const minv = Math.log(1);
const maxv = Math.log(102400);
const value = Math.exp(minv + (maxv - minv) * Math.pow(position / maxp, 1.5));
return Math.round(value);
}
// Move slider initialization to a separate function
function initializeSlider() {
const slider = document.getElementById('file_size');
const sizeValue = document.getElementById('size_value');
if (!slider || !sizeValue) return;
function updateSlider() {
const value = logSliderToSize(slider.value);
sizeValue.textContent = formatSize(value);
slider.style.backgroundSize = `${(slider.value / slider.max) * 100}% 100%`;
}
// Update on slider change
slider.addEventListener('input', updateSlider);
// Initialize slider position
updateSlider();
}
// Add helper function for formatting size
function formatSize(sizeInKB) {
if (sizeInKB >= 1024) {
return Math.round(sizeInKB / 1024) + 'mb';
}
return Math.round(sizeInKB) + 'kb';
}
// Initialize slider on page load
document.addEventListener('DOMContentLoaded', initializeSlider);
// Make sure these are available globally
window.copyText = copyText;
window.handleSubmit = handleSubmit;
window.initializeSlider = initializeSlider;
window.formatSize = formatSize;
// Add this new function
function setupGlobalEnterHandler() {
document.addEventListener('keydown', function (event) {
if (event.key === 'Enter' && !event.target.matches('textarea')) {
const form = document.getElementById('ingestForm');
if (form) {
handleSubmit(new Event('submit'), true);
}
}
});
}
// Add to the DOMContentLoaded event listener
document.addEventListener('DOMContentLoaded', () => {
initializeSlider();
setupGlobalEnterHandler();
});
================================================
File: /src/static/robots.txt
================================================
User-agent: *
Allow: /
Allow: /api/
Allow: /cyclotruc/gitingest/
================================================
File: /src/templates/api.jinja
================================================
{% extends "base.jinja" %}
{% block title %}Git ingest API{% endblock %}
{% block content %}
<div class="relative">
<div class="w-full h-full absolute inset-0 bg-black rounded-xl translate-y-2 translate-x-2"></div>
<div class="bg-[#fff4da] rounded-xl border-[3px] border-gray-900 p-8 relative z-20">