├── .gitignore ├── testdata └── script │ ├── error.txtar │ ├── stdout.txtar │ ├── no-dump.txtar │ ├── filter-go-base.txtar │ ├── no-tree.txtar │ ├── gitignore.txtar │ ├── subdirectory.txtar │ ├── filter-go-recursive.txtar │ ├── custom-output.txtar │ ├── filter-out-hidden-recursive.txtar │ ├── filter-out-hidden-base.txtar │ ├── filter-all.txtar │ ├── outline-only.txtar │ └── outline.txtar ├── go.mod ├── examples └── formats │ └── README.md ├── .vscode └── launch.json ├── .github └── workflows │ └── release.yaml ├── internal ├── parser │ ├── parser.go │ └── golang.go ├── utils.go ├── traverse.go ├── output.go ├── output_json.go └── traverse_test.go ├── .goreleaser.yaml ├── main_test.go ├── IDEAS.md ├── go.sum ├── main.go ├── pkg └── filter │ ├── filter.go │ └── filter_test.go ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | **/*amalgo.* 2 | !examples/** 3 | dist/ 4 | testdir/ -------------------------------------------------------------------------------- /testdata/script/error.txtar: -------------------------------------------------------------------------------- 1 | exec amalgo testdir --no-tree --no-dump 2 | stdout 'An empty output is not allowed' 3 | 4 | ! exec amalgo nonexistent 5 | stderr 'error: traversing directories' 6 | -------------------------------------------------------------------------------- /testdata/script/stdout.txtar: -------------------------------------------------------------------------------- 1 | exec amalgo testdir --stdout 2 | ! stderr . 3 | ! stdout 'Successfully generated' 4 | stdout '## Generated with Amalgo' 5 | stdout '## File Tree' 6 | stdout '## File Contents' 7 | 8 | exec amalgo testdir --stdout 9 | ! stderr . 10 | ! stdout 'Successfully generated' 11 | stdout '## Generated with Amalgo' 12 | stdout '## File Contents' 13 | 14 | -- testdir/file1.go -- 15 | package main 16 | 17 | func main() {} 18 | 19 | -- testdir/sub/file2.go -- 20 | package sub 21 | 22 | func Helper() {} 23 | 24 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/Broderick-Westrope/amalgo 2 | 3 | go 1.23.3 4 | 5 | require ( 6 | github.com/MakeNowJust/heredoc v1.0.0 7 | github.com/alecthomas/kong v1.6.1 8 | github.com/fatih/color v1.18.0 9 | github.com/sergi/go-diff v1.3.1 10 | github.com/stretchr/testify v1.10.0 11 | ) 12 | 13 | require golang.org/x/tools v0.22.0 // indirect 14 | 15 | require ( 16 | github.com/davecgh/go-spew v1.1.1 // indirect 17 | github.com/mattn/go-colorable v0.1.13 // indirect 18 | github.com/mattn/go-isatty v0.0.20 // indirect 19 | github.com/pmezard/go-difflib v1.0.0 // indirect 20 | github.com/rogpeppe/go-internal v1.13.1 21 | golang.org/x/sys v0.25.0 // indirect 22 | gopkg.in/yaml.v3 v3.0.1 // indirect 23 | ) 24 | -------------------------------------------------------------------------------- /examples/formats/README.md: -------------------------------------------------------------------------------- 1 | # Format Examples 2 | 3 | These files are examples of each available output format. Each file name is a valid value for the `--format` flag and the file extension is the extension used for the default file of that type. Normally, the generated files will be named "amalgo". These were generated with the following command: 4 | 5 | ```sh 6 | amalgo -f '**/*.go' --outline --format 7 | ``` 8 | 9 | Each generated output file includes: 10 | 11 | 1. **Header**: Timestamp and generation information 12 | 2. **Directory Tree**: Visual representation of the project structure (unless `--no-tree` is specified) 13 | 3. **Language-Specific Outlines**: Structural analysis of supported source files (if `--outline` is specified) 14 | 4. **File Contents**: Complete source code of all included files (unless `--no-dump` is specified) 15 | -------------------------------------------------------------------------------- /testdata/script/no-dump.txtar: -------------------------------------------------------------------------------- 1 | exec amalgo testdir --no-dump 2 | ! stderr . 3 | stdout 'Successfully generated output to: amalgo.txt' 4 | exists amalgo.txt 5 | cmpfile amalgo.txt expected.txt 6 | 7 | exec amalgo testdir --no-dump --format json 8 | ! stderr . 9 | stdout 'Successfully generated output to: amalgo.json' 10 | exists amalgo.json 11 | cmpfile amalgo.json expected.json 12 | 13 | -- testdir/file1.go -- 14 | package main 15 | 16 | func main() {} 17 | 18 | -- testdir/sub/file2.go -- 19 | package sub 20 | 21 | func Helper() {} 22 | 23 | -- expected.txt -- 24 | ## Generated with Amalgo at: 2025-01-13 21:56:20 25 | 26 | ## File Tree 27 | 28 | └── testdir/ 29 | ├── file1.go 30 | └── sub/ 31 | └── file2.go 32 | 33 | -- expected.json -- 34 | { 35 | "timestamp": "2025-01-13 10:58:37", 36 | "tree": "└── testdir/\n ├── file1.go\n └── sub/\n └── file2.go\n" 37 | } -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Launch Package", 9 | "type": "go", 10 | "request": "launch", 11 | "mode": "auto", 12 | "program": "${workspaceFolder}", 13 | "args": [ 14 | "-o", 15 | "stdout", 16 | "--no-dump" 17 | ] 18 | }, 19 | { 20 | "name": "Specific Test Case", 21 | "type": "go", 22 | "request": "launch", 23 | "mode": "auto", 24 | "program": "${workspaceFolder}/internal", 25 | "args": [ 26 | "-test.run", 27 | "TestShouldIncludePath/directory_matching_specific_pattern" 28 | ] 29 | }, 30 | ] 31 | } -------------------------------------------------------------------------------- /testdata/script/filter-go-base.txtar: -------------------------------------------------------------------------------- 1 | exec amalgo testdir -f '*.go' 2 | ! stderr . 3 | stdout 'Successfully generated output to: amalgo.txt' 4 | exists amalgo.txt 5 | cmpfile amalgo.txt expected.txt 6 | 7 | exec amalgo testdir --format json -f '*.go' 8 | ! stderr . 9 | stdout 'Successfully generated output to: amalgo.json' 10 | exists amalgo.json 11 | cmpfile amalgo.json expected.json 12 | 13 | -- testdir/file1.go -- 14 | package main 15 | 16 | func main() {} 17 | 18 | -- testdir/sub/file2.go -- 19 | package sub 20 | 21 | func Helper() {} 22 | 23 | -- expected.txt -- 24 | ## Generated with Amalgo at: 2025-01-13 21:56:20 25 | 26 | ## File Tree 27 | 28 | └── testdir/ 29 | └── file1.go 30 | 31 | ## File Contents 32 | 33 | --- Start File: testdir/file1.go 34 | package main 35 | 36 | func main() {} 37 | 38 | 39 | --- End File: testdir/file1.go 40 | -- expected.json -- 41 | { 42 | "timestamp": "2025-01-13 10:58:37", 43 | "tree": "└── testdir/\n └── file1.go\n", 44 | "files": [ 45 | { 46 | "path": "testdir/file1.go", 47 | "content": "package main\n\nfunc main() {}\n\n" 48 | } 49 | ] 50 | } -------------------------------------------------------------------------------- /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - "v*" 7 | 8 | permissions: 9 | contents: write # needed for creating GitHub releases 10 | packages: write # needed for pushing to GitHub Packages 11 | 12 | jobs: 13 | goreleaser: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Checkout 17 | uses: actions/checkout@v4 18 | with: 19 | fetch-depth: 0 # Important for GoReleaser to generate proper changelog 20 | 21 | - name: Set up Go 22 | uses: actions/setup-go@v5 23 | with: 24 | go-version: ">=1.21.0" 25 | cache: true 26 | 27 | - name: Run GoReleaser 28 | uses: goreleaser/goreleaser-action@v6 29 | with: 30 | distribution: goreleaser 31 | version: latest 32 | args: release --clean 33 | env: 34 | GITHUB_TOKEN: ${{ secrets.GH_PAT }} 35 | 36 | # Optional: Upload artifacts to GitHub Actions 37 | - name: Upload artifacts 38 | uses: actions/upload-artifact@v4 39 | with: 40 | name: binaries 41 | path: dist/* 42 | -------------------------------------------------------------------------------- /testdata/script/no-tree.txtar: -------------------------------------------------------------------------------- 1 | exec amalgo testdir --no-tree 2 | ! stderr . 3 | stdout 'Successfully generated output to: amalgo.txt' 4 | exists amalgo.txt 5 | cmpfile amalgo.txt expected.txt 6 | 7 | exec amalgo testdir --no-tree --format json 8 | ! stderr . 9 | stdout 'Successfully generated output to: amalgo.json' 10 | exists amalgo.json 11 | cmpfile amalgo.json expected.json 12 | 13 | -- testdir/file1.go -- 14 | package main 15 | 16 | func main() {} 17 | 18 | -- testdir/sub/file2.go -- 19 | package sub 20 | 21 | func Helper() {} 22 | 23 | -- expected.txt -- 24 | ## Generated with Amalgo at: 2025-01-13 21:56:20 25 | 26 | ## File Contents 27 | 28 | --- Start File: testdir/file1.go 29 | package main 30 | 31 | func main() {} 32 | 33 | 34 | --- End File: testdir/file1.go 35 | 36 | --- Start File: testdir/sub/file2.go 37 | package sub 38 | 39 | func Helper() {} 40 | 41 | 42 | --- End File: testdir/sub/file2.go 43 | -- expected.json -- 44 | { 45 | "timestamp": "2025-01-13 10:58:37", 46 | "files": [ 47 | { 48 | "path": "testdir/file1.go", 49 | "content": "package main\n\nfunc main() {}\n\n" 50 | }, 51 | { 52 | "path": "testdir/sub/file2.go", 53 | "content": "package sub\n\nfunc Helper() {}\n\n" 54 | } 55 | ] 56 | } -------------------------------------------------------------------------------- /testdata/script/gitignore.txtar: -------------------------------------------------------------------------------- 1 | exec amalgo testdir --gitignore='.a-gitignore,b-gitignore' 2 | ! stderr . 3 | stdout 'Successfully generated output to: amalgo.txt' 4 | exists amalgo.txt 5 | cmpfile amalgo.txt expected.txt 6 | 7 | exec amalgo testdir --format json --gitignore='.a-gitignore,b-gitignore' 8 | ! stderr . 9 | stdout 'Successfully generated output to: amalgo.json' 10 | exists amalgo.json 11 | cmpfile amalgo.json expected.json 12 | 13 | -- .a-gitignore -- 14 | **/*.go 15 | 16 | -- b-gitignore -- 17 | b-gitignore 18 | !*.go 19 | 20 | -- testdir/file1.go -- 21 | package main 22 | 23 | func main() {} 24 | 25 | -- testdir/sub/file2.go -- 26 | package sub 27 | 28 | func Helper() {} 29 | 30 | -- testdir/sub/another/file3.go -- 31 | package another 32 | 33 | func Something() {} 34 | 35 | -- expected.txt -- 36 | ## Generated with Amalgo at: 2025-01-13 21:56:20 37 | 38 | ## File Tree 39 | 40 | └── testdir/ 41 | └── file1.go 42 | 43 | ## File Contents 44 | 45 | --- Start File: testdir/file1.go 46 | package main 47 | 48 | func main() {} 49 | 50 | 51 | --- End File: testdir/file1.go 52 | -- expected.json -- 53 | { 54 | "timestamp": "2025-01-13 10:58:37", 55 | "tree": "└── testdir/\n └── file1.go\n", 56 | "files": [ 57 | { 58 | "path": "testdir/file1.go", 59 | "content": "package main\n\nfunc main() {}\n\n" 60 | } 61 | ] 62 | } -------------------------------------------------------------------------------- /testdata/script/subdirectory.txtar: -------------------------------------------------------------------------------- 1 | exec amalgo testdir 2 | ! stderr . 3 | stdout 'Successfully generated output to: amalgo.txt' 4 | exists amalgo.txt 5 | cmpfile amalgo.txt expected.txt 6 | 7 | exec amalgo testdir --format json 8 | ! stderr . 9 | stdout 'Successfully generated output to: amalgo.json' 10 | exists amalgo.json 11 | cmpfile amalgo.json expected.json 12 | 13 | -- testdir/file1.go -- 14 | package main 15 | 16 | func main() {} 17 | 18 | -- testdir/sub/file2.go -- 19 | package sub 20 | 21 | func Helper() {} 22 | 23 | -- expected.txt -- 24 | ## Generated with Amalgo at: 2025-01-13 21:56:20 25 | 26 | ## File Tree 27 | 28 | └── testdir/ 29 | ├── file1.go 30 | └── sub/ 31 | └── file2.go 32 | 33 | ## File Contents 34 | 35 | --- Start File: testdir/file1.go 36 | package main 37 | 38 | func main() {} 39 | 40 | 41 | --- End File: testdir/file1.go 42 | 43 | --- Start File: testdir/sub/file2.go 44 | package sub 45 | 46 | func Helper() {} 47 | 48 | 49 | --- End File: testdir/sub/file2.go 50 | -- expected.json -- 51 | { 52 | "timestamp": "2025-01-13 10:58:37", 53 | "tree": "└── testdir/\n ├── file1.go\n └── sub/\n └── file2.go\n", 54 | "files": [ 55 | { 56 | "path": "testdir/file1.go", 57 | "content": "package main\n\nfunc main() {}\n\n" 58 | }, 59 | { 60 | "path": "testdir/sub/file2.go", 61 | "content": "package sub\n\nfunc Helper() {}\n\n" 62 | } 63 | ] 64 | } -------------------------------------------------------------------------------- /testdata/script/filter-go-recursive.txtar: -------------------------------------------------------------------------------- 1 | exec amalgo testdir -f '**/*.go' 2 | stdout 'Successfully generated output to: amalgo.txt' 3 | exists amalgo.txt 4 | cmpfile amalgo.txt expected.txt 5 | 6 | exec amalgo testdir --format json -f '**/*.go' 7 | stdout 'Successfully generated output to: amalgo.json' 8 | exists amalgo.json 9 | cmpfile amalgo.json expected.json 10 | 11 | -- testdir/file1.go -- 12 | package main 13 | 14 | func main() {} 15 | 16 | -- testdir/sub/file2.go -- 17 | package sub 18 | 19 | func Helper() {} 20 | 21 | -- expected.txt -- 22 | ## Generated with Amalgo at: 2025-01-13 21:56:20 23 | 24 | ## File Tree 25 | 26 | └── testdir/ 27 | ├── file1.go 28 | └── sub/ 29 | └── file2.go 30 | 31 | ## File Contents 32 | 33 | --- Start File: testdir/file1.go 34 | package main 35 | 36 | func main() {} 37 | 38 | 39 | --- End File: testdir/file1.go 40 | 41 | --- Start File: testdir/sub/file2.go 42 | package sub 43 | 44 | func Helper() {} 45 | 46 | 47 | --- End File: testdir/sub/file2.go 48 | -- expected.json -- 49 | { 50 | "timestamp": "2025-01-13 10:58:37", 51 | "tree": "└── testdir/\n ├── file1.go\n └── sub/\n └── file2.go\n", 52 | "files": [ 53 | { 54 | "path": "testdir/file1.go", 55 | "content": "package main\n\nfunc main() {}\n\n" 56 | }, 57 | { 58 | "path": "testdir/sub/file2.go", 59 | "content": "package sub\n\nfunc Helper() {}\n\n" 60 | } 61 | ] 62 | } -------------------------------------------------------------------------------- /testdata/script/custom-output.txtar: -------------------------------------------------------------------------------- 1 | exec amalgo testdir -o custom.some-txt 2 | stdout 'Successfully generated output to: ' 3 | stdout 'custom.some-txt' 4 | exists custom.some-txt 5 | cmpfile custom.some-txt expected.txt 6 | 7 | exec amalgo testdir -o custom.some-json --format json 8 | stdout 'Successfully generated output to: ' 9 | stdout 'custom.some-json' 10 | exists custom.some-json 11 | cmpfile custom.some-json expected.json 12 | 13 | -- testdir/file1.go -- 14 | package main 15 | 16 | func main() {} 17 | 18 | -- testdir/sub/file2.go -- 19 | package sub 20 | 21 | func Helper() {} 22 | 23 | -- expected.txt -- 24 | ## Generated with Amalgo at: 2025-01-13 21:56:20 25 | 26 | ## File Tree 27 | 28 | └── testdir/ 29 | ├── file1.go 30 | └── sub/ 31 | └── file2.go 32 | 33 | ## File Contents 34 | 35 | --- Start File: testdir/file1.go 36 | package main 37 | 38 | func main() {} 39 | 40 | 41 | --- End File: testdir/file1.go 42 | 43 | --- Start File: testdir/sub/file2.go 44 | package sub 45 | 46 | func Helper() {} 47 | 48 | 49 | --- End File: testdir/sub/file2.go 50 | -- expected.json -- 51 | { 52 | "timestamp": "2025-01-13 10:58:37", 53 | "tree": "└── testdir/\n ├── file1.go\n └── sub/\n └── file2.go\n", 54 | "files": [ 55 | { 56 | "path": "testdir/file1.go", 57 | "content": "package main\n\nfunc main() {}\n\n" 58 | }, 59 | { 60 | "path": "testdir/sub/file2.go", 61 | "content": "package sub\n\nfunc Helper() {}\n\n" 62 | } 63 | ] 64 | } -------------------------------------------------------------------------------- /testdata/script/filter-out-hidden-recursive.txtar: -------------------------------------------------------------------------------- 1 | exec amalgo testdir -f '*,!**/.*' 2 | ! stderr . 3 | stdout 'Successfully generated output to: amalgo.txt' 4 | exists amalgo.txt 5 | cmpfile amalgo.txt expected.txt 6 | 7 | exec amalgo testdir -f '*,!**/.*' --format json 8 | ! stderr . 9 | stdout 'Successfully generated output to: amalgo.json' 10 | exists amalgo.json 11 | cmpfile amalgo.json expected.json 12 | 13 | -- testdir/file1.go -- 14 | package main 15 | 16 | func main() {} 17 | 18 | -- testdir/sub/file2.go -- 19 | package sub 20 | 21 | func Helper() {} 22 | 23 | -- testdir/.env -- 24 | SOME_ENV_VAR=value 25 | 26 | -- testdir/sub/.env -- 27 | SOME_ENV_VAR=value 28 | 29 | -- expected.txt -- 30 | ## Generated with Amalgo at: 2025-01-13 21:56:20 31 | 32 | ## File Tree 33 | 34 | └── testdir/ 35 | ├── file1.go 36 | └── sub/ 37 | └── file2.go 38 | 39 | ## File Contents 40 | 41 | --- Start File: testdir/file1.go 42 | package main 43 | 44 | func main() {} 45 | 46 | 47 | --- End File: testdir/file1.go 48 | 49 | --- Start File: testdir/sub/file2.go 50 | package sub 51 | 52 | func Helper() {} 53 | 54 | 55 | --- End File: testdir/sub/file2.go 56 | -- expected.json -- 57 | { 58 | "timestamp": "2025-01-13 10:58:37", 59 | "tree": "└── testdir/\n ├── file1.go\n └── sub/\n └── file2.go\n", 60 | "files": [ 61 | { 62 | "path": "testdir/file1.go", 63 | "content": "package main\n\nfunc main() {}\n\n" 64 | }, 65 | { 66 | "path": "testdir/sub/file2.go", 67 | "content": "package sub\n\nfunc Helper() {}\n\n" 68 | } 69 | ] 70 | } -------------------------------------------------------------------------------- /testdata/script/filter-out-hidden-base.txtar: -------------------------------------------------------------------------------- 1 | exec amalgo testdir -f '*,!.*' 2 | ! stderr . 3 | stdout 'Successfully generated output to: amalgo.txt' 4 | exists amalgo.txt 5 | cmpfile amalgo.txt expected.txt 6 | 7 | exec amalgo testdir --format json -f '*' 8 | ! stderr . 9 | stdout 'Successfully generated output to: amalgo.json' 10 | exists amalgo.json 11 | cmpfile amalgo.json expected.json 12 | 13 | -- testdir/file1.go -- 14 | package main 15 | 16 | func main() {} 17 | 18 | -- testdir/sub/file2.go -- 19 | package sub 20 | 21 | func Helper() {} 22 | 23 | -- testdir/.env -- 24 | SOME_ENV_VAR=value 25 | 26 | -- testdir/sub/.env -- 27 | SOME_ENV_VAR=value 28 | 29 | -- expected.txt -- 30 | ## Generated with Amalgo at: 2025-01-13 21:56:20 31 | 32 | ## File Tree 33 | 34 | └── testdir/ 35 | ├── file1.go 36 | └── sub/ 37 | ├── .env 38 | └── file2.go 39 | 40 | ## File Contents 41 | 42 | --- Start File: testdir/file1.go 43 | package main 44 | 45 | func main() {} 46 | 47 | 48 | --- End File: testdir/file1.go 49 | 50 | --- Start File: testdir/sub/.env 51 | SOME_ENV_VAR=value 52 | 53 | 54 | --- End File: testdir/sub/.env 55 | 56 | --- Start File: testdir/sub/file2.go 57 | package sub 58 | 59 | func Helper() {} 60 | 61 | 62 | --- End File: testdir/sub/file2.go 63 | -- expected.json -- 64 | { 65 | "timestamp": "2025-01-13 10:58:37", 66 | "tree": "└── testdir/\n ├── .env\n ├── file1.go\n └── sub/\n ├── .env\n └── file2.go\n", 67 | "files": [ 68 | { 69 | "path": "testdir/.env", 70 | "content": "SOME_ENV_VAR=value\n\n" 71 | }, 72 | { 73 | "path": "testdir/file1.go", 74 | "content": "package main\n\nfunc main() {}\n\n" 75 | }, 76 | { 77 | "path": "testdir/sub/.env", 78 | "content": "SOME_ENV_VAR=value\n\n" 79 | }, 80 | { 81 | "path": "testdir/sub/file2.go", 82 | "content": "package sub\n\nfunc Helper() {}\n\n" 83 | } 84 | ] 85 | } -------------------------------------------------------------------------------- /testdata/script/filter-all.txtar: -------------------------------------------------------------------------------- 1 | exec amalgo testdir -f '*' 2 | ! stderr . 3 | stdout 'Successfully generated output to: amalgo.txt' 4 | exists amalgo.txt 5 | cmpfile amalgo.txt expected.txt 6 | 7 | exec amalgo testdir --format json -f '*' 8 | ! stderr . 9 | stdout 'Successfully generated output to: amalgo.json' 10 | exists amalgo.json 11 | cmpfile amalgo.json expected.json 12 | 13 | -- testdir/file1.go -- 14 | package main 15 | 16 | func main() {} 17 | 18 | -- testdir/sub/file2.go -- 19 | package sub 20 | 21 | func Helper() {} 22 | 23 | -- testdir/.env -- 24 | SOME_ENV_VAR=value 25 | 26 | -- testdir/sub/.env -- 27 | SOME_ENV_VAR=value 28 | 29 | -- expected.txt -- 30 | ## Generated with Amalgo at: 2025-01-13 21:56:20 31 | 32 | ## File Tree 33 | 34 | └── testdir/ 35 | ├── .env 36 | ├── file1.go 37 | └── sub/ 38 | ├── .env 39 | └── file2.go 40 | 41 | ## File Contents 42 | 43 | --- Start File: testdir/.env 44 | SOME_ENV_VAR=value 45 | 46 | 47 | --- End File: testdir/.env 48 | 49 | --- Start File: testdir/file1.go 50 | package main 51 | 52 | func main() {} 53 | 54 | 55 | --- End File: testdir/file1.go 56 | 57 | --- Start File: testdir/sub/.env 58 | SOME_ENV_VAR=value 59 | 60 | 61 | --- End File: testdir/sub/.env 62 | 63 | --- Start File: testdir/sub/file2.go 64 | package sub 65 | 66 | func Helper() {} 67 | 68 | 69 | --- End File: testdir/sub/file2.go 70 | -- expected.json -- 71 | { 72 | "timestamp": "2025-01-13 10:58:37", 73 | "tree": "└── testdir/\n ├── .env\n ├── file1.go\n └── sub/\n ├── .env\n └── file2.go\n", 74 | "files": [ 75 | { 76 | "path": "testdir/.env", 77 | "content": "SOME_ENV_VAR=value\n\n" 78 | }, 79 | { 80 | "path": "testdir/file1.go", 81 | "content": "package main\n\nfunc main() {}\n\n" 82 | }, 83 | { 84 | "path": "testdir/sub/.env", 85 | "content": "SOME_ENV_VAR=value\n\n" 86 | }, 87 | { 88 | "path": "testdir/sub/file2.go", 89 | "content": "package sub\n\nfunc Helper() {}\n\n" 90 | } 91 | ] 92 | } -------------------------------------------------------------------------------- /internal/parser/parser.go: -------------------------------------------------------------------------------- 1 | // Package parser provides language-specific parsing capabilities 2 | package parser 3 | 4 | import "path/filepath" 5 | 6 | // Parser defines the interface for language-specific parsers 7 | type Parser interface { 8 | // Parse analyzes the content of a file and returns a structured outline 9 | Parse(content []byte, filename string) (*FileOutline, error) 10 | 11 | // Extensions returns the file extensions this parser handles 12 | Extensions() []string 13 | } 14 | 15 | // Symbol represents a parsed symbol (function, type, class, etc.) 16 | type Symbol struct { 17 | Type string // e.g., "function", "class", "interface", etc. 18 | Name string // Name of the symbol 19 | Signature string // Full signature for functions/methods 20 | Docstring string // Associated documentation 21 | Decorators []string // Any decorators/annotations 22 | Children []*Symbol // Nested symbols (e.g., methods in a class) 23 | Metadata map[string]any // Additional language-specific metadata 24 | } 25 | 26 | // FileOutline represents the parsed structure of a source file 27 | type FileOutline struct { 28 | Filename string // Name of the parsed file 29 | Symbols []*Symbol // Top-level symbols in the file 30 | Errors []error // Any errors encountered during parsing 31 | } 32 | 33 | // Registry manages the available parsers 34 | type Registry struct { 35 | parsers map[string]Parser 36 | } 37 | 38 | // NewRegistry creates a new parser registry 39 | func NewRegistry() *Registry { 40 | return &Registry{ 41 | parsers: make(map[string]Parser), 42 | } 43 | } 44 | 45 | // Register adds a parser to the registry 46 | func (r *Registry) Register(parser Parser) { 47 | for _, ext := range parser.Extensions() { 48 | r.parsers[ext] = parser 49 | } 50 | } 51 | 52 | // GetParser returns the appropriate parser for a file extension 53 | func (r *Registry) GetParser(filename string) Parser { 54 | ext := filepath.Ext(filename) 55 | return r.parsers[ext] 56 | } 57 | 58 | // IsSupported checks if there's a parser available for the given file extension 59 | func (r *Registry) IsSupported(filename string) bool { 60 | ext := filepath.Ext(filename) 61 | _, ok := r.parsers[ext] 62 | return ok 63 | } 64 | -------------------------------------------------------------------------------- /.goreleaser.yaml: -------------------------------------------------------------------------------- 1 | version: 2 2 | project_name: amalgo 3 | 4 | before: 5 | hooks: 6 | - go mod tidy 7 | 8 | builds: 9 | - env: 10 | - CGO_ENABLED=0 11 | goos: 12 | - linux 13 | - windows 14 | - darwin 15 | goarch: 16 | - amd64 17 | - arm64 18 | mod_timestamp: "{{ .CommitTimestamp }}" 19 | flags: 20 | - -trimpath 21 | ldflags: 22 | - -s -w 23 | - -X main.version={{.Version}} 24 | - -X main.commit={{.Commit}} 25 | - -X main.date={{.Date}} 26 | 27 | archives: 28 | - format: tar.gz 29 | name_template: >- 30 | {{ .ProjectName }}_ 31 | {{- title .Os }}_ 32 | {{- if eq .Arch "amd64" }}x86_64 33 | {{- else if eq .Arch "386" }}i386 34 | {{- else }}{{ .Arch }}{{ end }} 35 | {{- if .Arm }}v{{ .Arm }}{{ end }} 36 | format_overrides: 37 | - goos: windows 38 | format: zip 39 | 40 | checksum: 41 | name_template: "checksums.txt" 42 | 43 | changelog: 44 | sort: asc 45 | use: github 46 | groups: 47 | - title: Features 48 | regexp: "^.*feat[(\\w)]*:+.*$" 49 | order: 0 50 | - title: "Bug fixes" 51 | regexp: "^.*fix[(\\w)]*:+.*$" 52 | order: 1 53 | - title: Others 54 | order: 999 55 | filters: 56 | exclude: 57 | - "^docs" 58 | - "^test" 59 | - "^ci" 60 | - "^chore" 61 | - "README" 62 | - Merge pull request 63 | - Merge branch 64 | 65 | brews: 66 | - repository: 67 | owner: Broderick-Westrope 68 | name: homebrew-tap 69 | token: "{{ .Env.GITHUB_TOKEN }}" 70 | 71 | url_template: "https://github.com/Broderick-Westrope/amalgo/releases/download/{{ .Tag }}/{{ .ArtifactName }}" 72 | 73 | commit_author: 74 | name: goreleaserbot 75 | email: bot@goreleaser.com 76 | 77 | commit_msg_template: "Brew formula update for {{ .ProjectName }} version {{ .Tag }}" 78 | 79 | homepage: "https://github.com/Broderick-Westrope/amalgo" 80 | description: "Create consolidated snapshots of source code for analysis, documentation, and sharing with LLMs." 81 | license: "GNU GPLv3" 82 | 83 | test: | 84 | system "#{bin}/amalgo --version" 85 | 86 | install: | 87 | bin.install "amalgo" 88 | 89 | release: 90 | github: 91 | owner: Broderick-Westrope 92 | name: amalgo 93 | draft: true 94 | prerelease: auto 95 | mode: replace 96 | header: | 97 | *Generated using GoReleaser and automated using GitHub Actions.* 98 | -------------------------------------------------------------------------------- /testdata/script/outline-only.txtar: -------------------------------------------------------------------------------- 1 | exec amalgo testdir --no-tree --no-dump --outline 2 | ! stderr . 3 | stdout 'Successfully generated output to: amalgo.txt' 4 | exists amalgo.txt 5 | cmpfile amalgo.txt expected.txt 6 | 7 | exec amalgo testdir --no-tree --no-dump --outline --format json 8 | ! stderr . 9 | stdout 'Successfully generated output to: amalgo.json' 10 | exists amalgo.json 11 | cmpfile amalgo.json expected.json 12 | 13 | -- testdir/file1.go -- 14 | package main 15 | 16 | var Global = Doer{} 17 | const someConst string = "a value" 18 | func main() {} 19 | 20 | type Acter interface { 21 | Act(string) int 22 | } 23 | type Doer struct{} 24 | 25 | func(Doer) Act(_ string) int { 26 | return 1 27 | } 28 | 29 | -- testdir/sub/file2.go -- 30 | package sub 31 | 32 | func Helper() {} 33 | 34 | -- expected.txt -- 35 | ## Generated with Amalgo at: 2025-01-14 23:26:02 36 | 37 | ## Language-Specific Outlines 38 | 39 | ### File: testdir/file1.go 40 | 41 | VAR: Global 42 | CONST: someConst (string) 43 | FUNCTION: main (func main()) 44 | INTERFACE: Acter 45 | METHOD: Act ((string) int) 46 | STRUCT: Doer 47 | METHOD: Doer.Act (func (Doer) Act(_ string) int) 48 | 49 | ### File: testdir/sub/file2.go 50 | 51 | FUNCTION: Helper (func Helper()) 52 | 53 | -- expected.json -- 54 | { 55 | "timestamp": "2025-01-13 10:58:37", 56 | "outlines": [ 57 | { 58 | "path": "testdir/file1.go", 59 | "symbols": [ 60 | { 61 | "type": "var", 62 | "name": "Global", 63 | "metadata": null 64 | }, 65 | { 66 | "type": "const", 67 | "name": "someConst", 68 | "signature": "string", 69 | "metadata": null 70 | }, 71 | { 72 | "type": "function", 73 | "name": "main", 74 | "signature": "func main()", 75 | "metadata": null 76 | }, 77 | { 78 | "type": "interface", 79 | "name": "Acter", 80 | "children": [ 81 | { 82 | "type": "method", 83 | "name": "Act", 84 | "signature": "(string) int", 85 | "metadata": null 86 | } 87 | ], 88 | "metadata": null 89 | }, 90 | { 91 | "type": "struct", 92 | "name": "Doer", 93 | "metadata": null 94 | }, 95 | { 96 | "type": "method", 97 | "name": "Doer.Act", 98 | "signature": "func (Doer) Act(_ string) int", 99 | "metadata": null 100 | } 101 | ] 102 | }, 103 | { 104 | "path": "testdir/sub/file2.go", 105 | "symbols": [ 106 | { 107 | "type": "function", 108 | "name": "Helper", 109 | "signature": "func Helper()", 110 | "metadata": null 111 | } 112 | ] 113 | } 114 | ] 115 | } -------------------------------------------------------------------------------- /internal/utils.go: -------------------------------------------------------------------------------- 1 | package internal 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io" 7 | "os" 8 | "path/filepath" 9 | "time" 10 | ) 11 | 12 | // IsBinaryFile determines if a file is binary by checking its contents 13 | func IsBinaryFile(path string) (bool, error) { 14 | file, err := os.Open(path) 15 | if err != nil { 16 | return false, fmt.Errorf("opening file: %w", err) 17 | } 18 | defer file.Close() 19 | 20 | // Read first 512 bytes 21 | buf := make([]byte, 512) 22 | n, err := file.Read(buf) 23 | if err != nil && err != io.EOF { 24 | return false, fmt.Errorf("reading file: %w", err) 25 | } 26 | buf = buf[:n] 27 | 28 | // Check for null bytes 29 | if bytes.IndexByte(buf, 0) != -1 { 30 | return true, nil 31 | } 32 | 33 | // Look for non-text characters 34 | for _, b := range buf { 35 | if b < 32 && b != 9 && b != 10 && b != 13 { // Not tab, LF, or CR 36 | return true, nil 37 | } 38 | } 39 | return false, nil 40 | } 41 | 42 | // GenerateTree creates a textual representation of the directory structure 43 | func GenerateTree(paths []PathInfo) string { 44 | if len(paths) == 0 { 45 | return "< no paths found >\n" 46 | } 47 | 48 | mapPathToChildren := make(map[string][]PathInfo) 49 | for _, path := range paths { 50 | if path.Depth == 0 { 51 | continue 52 | } 53 | parent := filepath.Dir(path.Path) 54 | mapPathToChildren[parent] = append(mapPathToChildren[parent], path) 55 | } 56 | 57 | var output string 58 | var printTree func(path PathInfo, prefix string, isLast bool) 59 | printTree = func(path PathInfo, prefix string, isLast bool) { 60 | // Print current item 61 | connector := "├── " 62 | if isLast { 63 | connector = "└── " 64 | } 65 | 66 | name := filepath.Base(path.Path) 67 | if path.IsDir { 68 | name += "/" 69 | } 70 | output += fmt.Sprintf("%s%s%s\n", prefix, connector, name) 71 | 72 | // Print children 73 | childPrefix := prefix + "│ " 74 | if isLast { 75 | childPrefix = prefix + " " 76 | } 77 | 78 | pathChildren := mapPathToChildren[path.Path] 79 | for i, child := range pathChildren { 80 | printTree(child, childPrefix, i == len(pathChildren)-1) 81 | } 82 | } 83 | 84 | shortestPath := paths[0] 85 | for _, path := range paths { 86 | if len(path.Path) < len(shortestPath.Path) { 87 | shortestPath = path 88 | } 89 | } 90 | 91 | // Find and process root level items. 92 | rootPaths := mapPathToChildren[filepath.Dir(shortestPath.Path)] 93 | for i, path := range rootPaths { 94 | printTree(path, "", i == len(rootPaths)-1) 95 | } 96 | return output 97 | } 98 | 99 | // WriteOutput writes content to a file or stdout 100 | func WriteOutput(path string, content string) error { 101 | if path == "stdout" || path == "-" { 102 | _, err := fmt.Print(content) 103 | if err != nil { 104 | return fmt.Errorf("writing to stdout: %w", err) 105 | } 106 | return nil 107 | } 108 | 109 | dir := filepath.Dir(path) 110 | err := os.MkdirAll(dir, 0755) 111 | if err != nil { 112 | return fmt.Errorf("creating directories along path %q: %w", dir, err) 113 | } 114 | 115 | err = os.WriteFile(path, []byte(content), 0644) 116 | if err != nil { 117 | return fmt.Errorf("writing to file: %w", err) 118 | } 119 | return nil 120 | } 121 | 122 | // FormatTimestamp returns a formatted timestamp string 123 | func FormatTimestamp() string { 124 | return time.Now().Format("2006-01-02 15:04:05") 125 | } 126 | -------------------------------------------------------------------------------- /main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "strings" 7 | "testing" 8 | 9 | "github.com/fatih/color" 10 | "github.com/rogpeppe/go-internal/testscript" 11 | "github.com/sergi/go-diff/diffmatchpatch" 12 | ) 13 | 14 | func TestMain(m *testing.M) { 15 | color.NoColor = false 16 | os.Exit(testscript.RunMain(m, 17 | map[string]func() int{ 18 | appName: run, 19 | }, 20 | )) 21 | } 22 | 23 | func TestScript(t *testing.T) { 24 | testscript.Run(t, testscript.Params{ 25 | Dir: "testdata/script", 26 | Setup: func(env *testscript.Env) error { 27 | return nil 28 | }, 29 | Cmds: map[string]func(ts *testscript.TestScript, neg bool, args []string){ 30 | "cmpfile": compareFiles, 31 | "showfile": func(ts *testscript.TestScript, neg bool, args []string) { 32 | if len(args) != 1 { 33 | ts.Fatalf("usage: showfile filename") 34 | } 35 | content, err := os.ReadFile(ts.MkAbs(args[0])) 36 | if err != nil { 37 | ts.Fatalf("reading %s: %v", args[0], err) 38 | } 39 | fmt.Fprintf(ts.Stdout(), "=== Content of %s ===\n", args[0]) 40 | fmt.Fprintf(ts.Stdout(), "%s\n", content) 41 | fmt.Fprintf(ts.Stdout(), "=== End of %s ===\n", args[0]) 42 | }, 43 | }, 44 | }) 45 | } 46 | 47 | func compareFiles(ts *testscript.TestScript, neg bool, args []string) { 48 | if len(args) != 2 { 49 | ts.Fatalf("usage: cmpfile actual expected") 50 | } 51 | temp := ts.MkAbs(args[0]) 52 | actual, err := os.ReadFile(temp) 53 | if err != nil { 54 | ts.Fatalf("reading %q (actual): %v", temp, err) 55 | } 56 | temp = ts.MkAbs(args[1]) 57 | expected, err := os.ReadFile(temp) 58 | if err != nil { 59 | ts.Fatalf("reading %q (expected): %v", temp, err) 60 | } 61 | 62 | // Split into lines 63 | actualLines := strings.Split(string(actual), "\n") 64 | expectedLines := strings.Split(string(expected), "\n") 65 | 66 | // Create debug versions with visible empty lines 67 | debugActual := make([]string, len(actualLines)) 68 | debugExpected := make([]string, len(expectedLines)) 69 | 70 | for i, line := range actualLines { 71 | if line == "" { 72 | debugActual[i] = "" 73 | } else { 74 | debugActual[i] = line 75 | } 76 | } 77 | 78 | for i, line := range expectedLines { 79 | if line == "" { 80 | debugExpected[i] = "" 81 | } else { 82 | debugExpected[i] = line 83 | } 84 | } 85 | 86 | matchFailed := false 87 | if len(actualLines) != len(expectedLines) { 88 | if !neg { 89 | matchFailed = true 90 | } 91 | } 92 | 93 | for i := 0; i < len(actualLines) && i < len(expectedLines); i++ { 94 | aLine := actualLines[i] 95 | eLine := expectedLines[i] 96 | // Skip timestamp line 97 | if strings.Contains(aLine, "Generated with Amalgo at:") || strings.Contains(aLine, "timestamp") { 98 | continue 99 | } 100 | if aLine != eLine { 101 | matchFailed = true 102 | break 103 | } 104 | } 105 | 106 | if matchFailed { 107 | diffStr := createDiff( 108 | fmt.Sprintf("Expected (%d lines)", len(expectedLines)), 109 | fmt.Sprintf("Actual (%d lines)", len(actualLines)), 110 | strings.Join(debugExpected, "\n"), 111 | strings.Join(debugActual, "\n"), 112 | ) 113 | ts.Fatalf("Failed to match:\n%s", diffStr) 114 | } else if neg { 115 | ts.Fatalf("files match but should not") 116 | } 117 | } 118 | 119 | func createDiff(name1, name2, text1, text2 string) string { 120 | dmp := diffmatchpatch.New() 121 | diffs := dmp.DiffMain(text1, text2, false) 122 | return fmt.Sprintf( 123 | "%s\n%s\n%s", 124 | color.RedString("--- "+name1), 125 | color.GreenString("+++ "+name2), 126 | dmp.DiffPrettyText(diffs), 127 | ) 128 | } 129 | -------------------------------------------------------------------------------- /testdata/script/outline.txtar: -------------------------------------------------------------------------------- 1 | exec amalgo testdir --outline 2 | ! stderr . 3 | stdout 'Successfully generated output to: amalgo.txt' 4 | exists amalgo.txt 5 | cmpfile amalgo.txt expected.txt 6 | 7 | exec amalgo testdir --outline --format json 8 | ! stderr . 9 | stdout 'Successfully generated output to: amalgo.json' 10 | exists amalgo.json 11 | cmpfile amalgo.json expected.json 12 | 13 | -- testdir/file1.go -- 14 | package main 15 | 16 | var Global = Doer{} 17 | const someConst string = "a value" 18 | func main() {} 19 | 20 | type Acter interface { 21 | Act(string) int 22 | } 23 | type Doer struct{} 24 | 25 | func(Doer) Act(_ string) int { 26 | return 1 27 | } 28 | 29 | -- testdir/sub/file2.go -- 30 | package sub 31 | 32 | func Helper() {} 33 | 34 | -- expected.txt -- 35 | ## Generated with Amalgo at: 2025-01-14 23:26:02 36 | 37 | ## File Tree 38 | 39 | └── testdir/ 40 | ├── file1.go 41 | └── sub/ 42 | └── file2.go 43 | 44 | ## Language-Specific Outlines 45 | 46 | ### File: testdir/file1.go 47 | 48 | VAR: Global 49 | CONST: someConst (string) 50 | FUNCTION: main (func main()) 51 | INTERFACE: Acter 52 | METHOD: Act ((string) int) 53 | STRUCT: Doer 54 | METHOD: Doer.Act (func (Doer) Act(_ string) int) 55 | 56 | ### File: testdir/sub/file2.go 57 | 58 | FUNCTION: Helper (func Helper()) 59 | 60 | ## File Contents 61 | 62 | --- Start File: testdir/file1.go 63 | package main 64 | 65 | var Global = Doer{} 66 | const someConst string = "a value" 67 | func main() {} 68 | 69 | type Acter interface { 70 | Act(string) int 71 | } 72 | type Doer struct{} 73 | 74 | func(Doer) Act(_ string) int { 75 | return 1 76 | } 77 | 78 | 79 | --- End File: testdir/file1.go 80 | 81 | --- Start File: testdir/sub/file2.go 82 | package sub 83 | 84 | func Helper() {} 85 | 86 | 87 | --- End File: testdir/sub/file2.go 88 | -- expected.json -- 89 | { 90 | "timestamp": "2025-01-13 10:58:37", 91 | "tree": "└── testdir/\n ├── file1.go\n └── sub/\n └── file2.go\n", 92 | "files": [ 93 | { 94 | "path": "testdir/file1.go", 95 | "content": "package main\n\nvar Global = Doer{}\nconst someConst string = \"a value\"\nfunc main() {}\n\ntype Acter interface {\n Act(string) int\n}\ntype Doer struct{}\n\nfunc(Doer) Act(_ string) int {\n return 1\n}\n\n" 96 | }, 97 | { 98 | "path": "testdir/sub/file2.go", 99 | "content": "package sub\n\nfunc Helper() {}\n\n" 100 | } 101 | ], 102 | "outlines": [ 103 | { 104 | "path": "testdir/file1.go", 105 | "symbols": [ 106 | { 107 | "type": "var", 108 | "name": "Global", 109 | "metadata": null 110 | }, 111 | { 112 | "type": "const", 113 | "name": "someConst", 114 | "signature": "string", 115 | "metadata": null 116 | }, 117 | { 118 | "type": "function", 119 | "name": "main", 120 | "signature": "func main()", 121 | "metadata": null 122 | }, 123 | { 124 | "type": "interface", 125 | "name": "Acter", 126 | "children": [ 127 | { 128 | "type": "method", 129 | "name": "Act", 130 | "signature": "(string) int", 131 | "metadata": null 132 | } 133 | ], 134 | "metadata": null 135 | }, 136 | { 137 | "type": "struct", 138 | "name": "Doer", 139 | "metadata": null 140 | }, 141 | { 142 | "type": "method", 143 | "name": "Doer.Act", 144 | "signature": "func (Doer) Act(_ string) int", 145 | "metadata": null 146 | } 147 | ] 148 | }, 149 | { 150 | "path": "testdir/sub/file2.go", 151 | "symbols": [ 152 | { 153 | "type": "function", 154 | "name": "Helper", 155 | "signature": "func Helper()", 156 | "metadata": null 157 | } 158 | ] 159 | } 160 | ] 161 | } -------------------------------------------------------------------------------- /IDEAS.md: -------------------------------------------------------------------------------- 1 | # Ideas 2 | 3 | This is intended to be a haphazard list of ideas for the project. If anything resonates with you feel free to start a discussion since an idea being here does not imply any plan to implement it. 4 | 5 | 1. Language Support Expansion 6 | - Add parsers for other popular languages like Python, TypeScript, and Rust 7 | - Create a modular parser interface that makes it easy for contributors to add new language support 8 | - Include special handling for configuration files (JSON, YAML, TOML) and documentation files (Markdown, RST) 9 | 10 | 2. Enhanced Analysis Features 11 | - Generate dependency graphs between files and components 12 | - Add cyclomatic complexity analysis for supported languages 13 | - Include basic static analysis to identify potential code smells or anti-patterns 14 | - Add support for analyzing imported packages and external dependencies 15 | - Generate metrics like lines of code, comment ratio, and function complexity 16 | 17 | 3. Output Format Improvements 18 | - Add support for different output formats (JSON, YAML, HTML) 19 | - Create a templating system for customizable output formats 20 | - Generate interactive HTML reports with collapsible sections and syntax highlighting 21 | - Add options for generating UML diagrams from code structure 22 | - Include a mode for generating documentation in standard formats (e.g., OpenAPI for REST APIs) 23 | 24 | 4. Smart Filtering Capabilities 25 | - Add semantic-based filtering (e.g., "only public functions" or "only types that implement X interface") 26 | - Support regex patterns in addition to glob patterns 27 | - Add the ability to focus on specific code aspects (e.g., only interfaces, only exported symbols) 28 | - Include/exclude based on code complexity or other metrics 29 | 30 | 5. Integration Features 31 | - Create GitHub Action for automated documentation generation 32 | - Add integration with popular documentation platforms (ReadTheDocs, Docusaurus) 33 | - Support for CI/CD pipelines with configurable outputs 34 | - Integrate with code review tools to provide structural insights 35 | - Add webhook support for automated processing 36 | 37 | 6. Performance Optimizations 38 | - Implement parallel processing for file analysis 39 | - Add incremental processing mode that only analyzes changed files 40 | - Include caching mechanism for parsed results 41 | - Optimize memory usage for large codebases 42 | - Add streaming output options for very large projects 43 | 44 | 7. Developer Experience 45 | - Add a config file option for persistent settings 46 | - Create an interactive mode with TUI interface 47 | - Add progress bars and better status reporting 48 | - Implement a debug mode with detailed logging 49 | - Add dry-run capability to preview output 50 | 51 | 8. Code Quality & Testing 52 | - Add more comprehensive unit tests 53 | - Implement integration tests with various real-world codebases 54 | - Add benchmarking tests for performance monitoring 55 | - Implement fuzzing tests for the parser 56 | - Add end-to-end tests for common use cases 57 | 58 | 9. LLM-Specific Enhancements 59 | - Add special formatting modes optimized for different LLM models 60 | - Include token counting and automatic chunking for large codebases 61 | - Add support for generating focused context windows 62 | - Implement smart summarization of large files 63 | - Add ability to generate targeted prompts for specific analysis tasks 64 | 65 | 10. Error Handling & Reporting 66 | - Improve error messages with suggested fixes 67 | - Add validation for complex configurations 68 | - Implement graceful degradation when parsing fails 69 | - Add warning system for potential issues 70 | - Include detailed error context in output 71 | 72 | 11. Security Features 73 | - Add support for detecting and handling sensitive information 74 | - Implement exclude patterns for security-sensitive files 75 | - Add options for obfuscating specific patterns (e.g., API keys) 76 | - Include basic security scanning capabilities 77 | - Add support for scanning dependencies for known vulnerabilities 78 | 79 | - Feature idea: flag to honour gitignore. Glob passing is already in, would just need a way to reliably read gitignore files. Should not overwrite other flags. -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= 2 | github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= 3 | github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0= 4 | github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= 5 | github.com/alecthomas/kong v1.6.1 h1:/7bVimARU3uxPD0hbryPE8qWrS3Oz3kPQoxA/H2NKG8= 6 | github.com/alecthomas/kong v1.6.1/go.mod h1:p2vqieVMeTAnaC83txKtXe8FLke2X07aruPWXyMPQrU= 7 | github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc= 8 | github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= 9 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 10 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 11 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 12 | github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= 13 | github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= 14 | github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= 15 | github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= 16 | github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= 17 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 18 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 19 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= 20 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 21 | github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= 22 | github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= 23 | github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= 24 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= 25 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 26 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 27 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 28 | github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= 29 | github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= 30 | github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8= 31 | github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= 32 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 33 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 34 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= 35 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 36 | golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 37 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 38 | golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= 39 | golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 40 | golang.org/x/tools v0.22.0 h1:gqSGLZqv+AI9lIQzniJ0nZDRG5GBPsSi+DRNHWNz6yA= 41 | golang.org/x/tools v0.22.0/go.mod h1:aCwcsjqvq7Yqt6TNyX7QMU2enbQ/Gt0bo6krSeEri+c= 42 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 43 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= 44 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 45 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 46 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 47 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 48 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 49 | -------------------------------------------------------------------------------- /internal/traverse.go: -------------------------------------------------------------------------------- 1 | package internal 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "io/fs" 7 | "os" 8 | "path/filepath" 9 | "strings" 10 | 11 | "github.com/Broderick-Westrope/amalgo/pkg/filter" 12 | ) 13 | 14 | // PathInfo represents information about a file or directory 15 | type PathInfo struct { 16 | Path string 17 | RelativePath string 18 | Depth int 19 | IsDir bool 20 | } 21 | 22 | // TraverseDirectory traverses the directory and collects path information using the filter package 23 | func TraverseDirectory(dir string, filterPatterns, gitignorePaths []string) ([]PathInfo, error) { 24 | // Create the filter from filter patterns. 25 | f := filter.CompileFilterPatterns(filterPatterns...) 26 | // Create the gitignore filter from gitignore file paths. 27 | gi := new(filter.Filter) 28 | for _, giPath := range gitignorePaths { 29 | tempFilter, err := filter.CompileFilterPatternFile(giPath) 30 | if err != nil { 31 | return nil, fmt.Errorf("compiling patterns from gitignore file %q: %w", giPath, err) 32 | } 33 | gi.MergeWithPrecedence(tempFilter) 34 | } 35 | 36 | paths := make([]PathInfo, 0) 37 | basePath, err := filepath.Abs(dir) 38 | if err != nil { 39 | return nil, fmt.Errorf("getting base path for directory %q: %w", dir, err) 40 | } 41 | 42 | baseInfo, err := os.Stat(basePath) 43 | if err != nil { 44 | return nil, fmt.Errorf("describing base path for directory %q: %w", dir, err) 45 | } 46 | 47 | if !baseInfo.IsDir() { 48 | basePath = filepath.Dir(basePath) 49 | baseInfo, err = os.Stat(basePath) 50 | if err != nil { 51 | return nil, err 52 | } 53 | if !baseInfo.IsDir() { 54 | return nil, fmt.Errorf("expected base path %q to be a directory", basePath) 55 | } 56 | } 57 | 58 | // Base parent allows getting the relative path in relation to the parent. 59 | baseParent := filepath.Dir(basePath) 60 | 61 | err = filepath.WalkDir(basePath, func(path string, d fs.DirEntry, err error) error { 62 | if err != nil { 63 | return fmt.Errorf("at path %q: %w", path, err) 64 | } 65 | 66 | // Skip directories as the filter system is built to process file paths. 67 | // Skip the base path as it's already processed. 68 | if d.IsDir() || path == basePath { 69 | return nil 70 | } 71 | 72 | relPath, err := filepath.Rel(basePath, path) 73 | if err != nil { 74 | return fmt.Errorf("getting relative path between %q and %q: %w", basePath, path, err) 75 | } 76 | relPath = filepath.ToSlash(relPath) 77 | 78 | if gi.MatchesPath(relPath) || !f.MatchesPath(relPath) { 79 | return nil 80 | } 81 | 82 | relPath, err = filepath.Rel(baseParent, path) 83 | if err != nil { 84 | return fmt.Errorf("getting relative path between %q and %q: %w", basePath, path, err) 85 | } 86 | relPath = filepath.ToSlash(relPath) 87 | 88 | paths = append(paths, PathInfo{ 89 | Path: path, 90 | RelativePath: relPath, 91 | Depth: strings.Count(relPath, "/") + 1, 92 | IsDir: false, 93 | }) 94 | return nil 95 | }) 96 | if err != nil { 97 | return nil, fmt.Errorf("walking directory %q: %w", basePath, err) 98 | } 99 | 100 | err = processPaths(&paths) 101 | if err != nil { 102 | return nil, err 103 | } 104 | return paths, nil 105 | } 106 | 107 | // ProcessPaths adds all parent directory paths to the given slice of PathInfo. 108 | // The function modifies the input slice in place, adding parent directories in order 109 | // from shallowest to deepest, followed by the original paths. 110 | func processPaths(paths *[]PathInfo) error { 111 | if paths == nil { 112 | return errors.New("paths must be a pointer to a slice") 113 | } else if *paths == nil { 114 | return errors.New("underlying paths slice cannot be nil") 115 | } 116 | 117 | // Create a map to deduplicate paths. 118 | seen := make(map[string]struct{}) 119 | for _, path := range *paths { 120 | seen[path.Path] = struct{}{} 121 | } 122 | 123 | result := make([]PathInfo, len(*paths)) 124 | if copy(result, *paths) != len(*paths) { 125 | return errors.New("failed to copy paths to result slice") 126 | } 127 | 128 | for _, p := range *paths { 129 | // Split the relative path to process each component. 130 | components := strings.Split(p.RelativePath, "/") 131 | basePath := filepath.Dir(p.Path[:len(p.Path)-len(p.RelativePath)]) 132 | 133 | // Process each level of the path. 134 | currentRel := "" 135 | currentAbs := basePath 136 | for i, comp := range components { 137 | if i == len(components)-1 && !p.IsDir { 138 | // Skip the last component if it's a file - we'll add it from the original slice. 139 | continue 140 | } 141 | 142 | if currentRel == "" { 143 | currentRel = comp 144 | } else { 145 | currentRel = filepath.Join(currentRel, comp) 146 | } 147 | currentAbs = filepath.Join(currentAbs, comp) 148 | 149 | // Only add if we haven't seen this path before. 150 | if _, exists := seen[currentAbs]; !exists { 151 | seen[currentAbs] = struct{}{} 152 | result = append(result, PathInfo{ 153 | Path: currentAbs, 154 | RelativePath: currentRel, 155 | Depth: i + 1, 156 | IsDir: true, 157 | }) 158 | } 159 | } 160 | } 161 | 162 | // Update the input slice with the result. 163 | *paths = result 164 | return nil 165 | } 166 | -------------------------------------------------------------------------------- /internal/output.go: -------------------------------------------------------------------------------- 1 | package internal 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "strings" 7 | 8 | "github.com/Broderick-Westrope/amalgo/internal/parser" 9 | ) 10 | 11 | type OutputFormat string 12 | 13 | const ( 14 | OutputFormatDefault = "default" 15 | OutputFormatJSON = "json" 16 | ) 17 | 18 | // Options configures the output generation 19 | type OutputOptions struct { 20 | NoTree bool 21 | NoDump bool 22 | Outline bool 23 | SkipBinary bool 24 | Format OutputFormat 25 | } 26 | 27 | // GenerateOutput creates the complete output string 28 | func GenerateOutput(paths []PathInfo, registry *parser.Registry, opts OutputOptions) (string, error) { 29 | if opts.Format == OutputFormatJSON { 30 | return generateOutputJSON(paths, registry, opts) 31 | } 32 | 33 | output := fmt.Sprintf("## Generated with Amalgo at: %s\n\n", FormatTimestamp()) 34 | 35 | if !opts.NoTree { 36 | output += fmt.Sprintf("## File Tree\n\n%s\n", GenerateTree(paths)) 37 | } 38 | 39 | if opts.Outline { 40 | outlines, err := generateOutlines(paths, registry) 41 | if err != nil { 42 | return "", fmt.Errorf("generating outlines: %w", err) 43 | } 44 | output += outlines 45 | } 46 | 47 | if !opts.NoDump { 48 | filesDump, err := dumpFiles(paths, opts.SkipBinary) 49 | if err != nil { 50 | return "", fmt.Errorf("dumping files: %w", err) 51 | } 52 | output += filesDump 53 | } 54 | return output, nil 55 | } 56 | 57 | func generateOutlines(paths []PathInfo, registry *parser.Registry) (string, error) { 58 | output := "## Language-Specific Outlines\n\n" 59 | 60 | var temp string 61 | var err error 62 | for _, path := range paths { 63 | if path.IsDir { 64 | continue 65 | } 66 | 67 | // Skip if no parser available for this file type 68 | if !registry.IsSupported(path.Path) { 69 | continue 70 | } 71 | 72 | temp, err = processFileOutline(path.Path, registry) 73 | if err != nil { 74 | return "", fmt.Errorf("processing outline for %q: %w", path.Path, err) 75 | } 76 | output += fmt.Sprintf("### File: %s\n\n%s\n", path.RelativePath, temp) 77 | } 78 | return output, nil 79 | } 80 | 81 | func processFileOutline(filePath string, registry *parser.Registry) (string, error) { 82 | content, err := os.ReadFile(filePath) 83 | if err != nil { 84 | return "", fmt.Errorf("reading file: %w", err) 85 | } 86 | 87 | parser := registry.GetParser(filePath) 88 | if parser == nil { 89 | return "", fmt.Errorf("no parser found for %q", filePath) 90 | } 91 | 92 | outline, err := parser.Parse(content, filePath) 93 | if err != nil { 94 | return "", fmt.Errorf("parsing file %q: %w", filePath, err) 95 | } 96 | 97 | if len(outline.Errors) > 0 { 98 | var errMsgs []string 99 | for _, err := range outline.Errors { 100 | errMsgs = append(errMsgs, err.Error()) 101 | } 102 | return fmt.Sprintf("Parsing errors:\n%s\n", strings.Join(errMsgs, "\n")), nil 103 | } 104 | 105 | result, err := writeSymbols(outline.Symbols, 0) 106 | if err != nil { 107 | return "", fmt.Errorf("writing symbols: %w", err) 108 | } 109 | return result, nil 110 | } 111 | 112 | func writeSymbols(symbols []*parser.Symbol, depth int) (string, error) { 113 | indent := strings.Repeat(" ", depth) 114 | var output string 115 | for _, symbol := range symbols { 116 | // Write symbol header 117 | output += fmt.Sprintf("%s%s: %s", indent, strings.ToUpper(symbol.Type), symbol.Name) 118 | if symbol.Signature != "" { 119 | output += fmt.Sprintf(" (%s)", symbol.Signature) 120 | } 121 | output += "\n" 122 | 123 | // Write decorators if present 124 | if len(symbol.Decorators) > 0 { 125 | output += fmt.Sprintf("%s Decorators: %s\n", indent, strings.Join(symbol.Decorators, ", ")) 126 | } 127 | 128 | // Write docstring if present 129 | if symbol.Docstring != "" { 130 | docLines := strings.Split(strings.TrimSpace(symbol.Docstring), "\n") 131 | output += fmt.Sprintf("%s Documentation:\n", indent) 132 | for _, line := range docLines { 133 | output += fmt.Sprintf("%s %s\n", indent, line) 134 | } 135 | } 136 | 137 | // Recursively write children 138 | if len(symbol.Children) > 0 { 139 | temp, err := writeSymbols(symbol.Children, depth+1) 140 | if err != nil { 141 | return "", err 142 | } 143 | output += temp 144 | } 145 | } 146 | return output, nil 147 | } 148 | 149 | func dumpFiles(paths []PathInfo, skipBinary bool) (string, error) { 150 | var sb strings.Builder 151 | sb.WriteString("## File Contents\n") 152 | 153 | for _, path := range paths { 154 | if path.IsDir { 155 | continue 156 | } 157 | 158 | if skipBinary { 159 | // Check if file is binary 160 | isBinary, err := IsBinaryFile(path.Path) 161 | if err != nil { 162 | return "", fmt.Errorf("checking if file %q is binary: %w", path.Path, err) 163 | } 164 | 165 | if isBinary { 166 | sb.WriteString( 167 | fmt.Sprintf("\n\n--- File: %s\n", path.RelativePath), 168 | ) 169 | continue 170 | } 171 | } 172 | 173 | // Read and write file content 174 | fileContent, err := os.ReadFile(path.Path) 175 | if err != nil { 176 | return "", fmt.Errorf("reading file %q: %w", path.Path, err) 177 | } 178 | 179 | sb.WriteString( 180 | fmt.Sprintf("\n--- Start File: %s\n%s\n--- End File: %s\n", 181 | path.RelativePath, string(fileContent), path.RelativePath), 182 | ) 183 | } 184 | return sb.String(), nil 185 | } 186 | -------------------------------------------------------------------------------- /internal/output_json.go: -------------------------------------------------------------------------------- 1 | package internal 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "os" 7 | 8 | "github.com/Broderick-Westrope/amalgo/internal/parser" 9 | ) 10 | 11 | type JSONDocument struct { 12 | Timestamp string `json:"timestamp"` 13 | Tree string `json:"tree,omitempty"` 14 | Files []JSONFile `json:"files,omitempty"` 15 | Outlines []JSONFileOutline `json:"outlines,omitempty"` 16 | } 17 | 18 | type JSONFile struct { 19 | Path string `json:"path"` 20 | Content string `json:"content,omitempty"` 21 | Binary bool `json:"binary,omitempty"` 22 | } 23 | 24 | // JSONFileOutline represents the parsed structure of a source file 25 | type JSONFileOutline struct { 26 | Path string `json:"path"` 27 | Symbols []JSONSymbol `json:"symbols,omitempty"` 28 | Errors []string `json:"errors,omitempty"` 29 | } 30 | 31 | // JSONSymbol represents a parsed symbol (function, type, class, etc.) 32 | type JSONSymbol struct { 33 | Type string `json:"type"` // e.g., "function", "class", "interface" 34 | Name string `json:"name"` // Name of the symbol 35 | Signature string `json:"signature,omitempty"` // Full signature for functions/methods 36 | Documentation string `json:"documentation,omitempty"` // Associated documentation 37 | Decorators []string `json:"decorators,omitempty"` // Any decorators/annotations 38 | Children []JSONSymbol `json:"children,omitempty"` // Nested symbols (e.g., methods in a class) 39 | Metadata any `json:"metadata,omitempty"` // Additional language-specific metadata 40 | } 41 | 42 | func generateOutputJSON(paths []PathInfo, registry *parser.Registry, opts OutputOptions) (string, error) { 43 | doc := JSONDocument{ 44 | Timestamp: FormatTimestamp(), 45 | } 46 | 47 | if !opts.NoTree { 48 | doc.Tree = GenerateTree(paths) 49 | } 50 | 51 | if !opts.NoDump { 52 | files, err := generateFilesJSON(paths, opts.SkipBinary) 53 | if err != nil { 54 | return "", fmt.Errorf("dumping files: %w", err) 55 | } 56 | doc.Files = files 57 | } 58 | 59 | if opts.Outline { 60 | outlines, err := generateOutlinesJSON(paths, registry) 61 | if err != nil { 62 | return "", fmt.Errorf("generating outlines: %w", err) 63 | } 64 | doc.Outlines = outlines 65 | } 66 | 67 | output, err := json.MarshalIndent(doc, "", " ") 68 | if err != nil { 69 | return "", fmt.Errorf("marshaling JSON: %w", err) 70 | } 71 | 72 | return string(output) + "\n", nil 73 | } 74 | 75 | func generateFilesJSON(paths []PathInfo, skipBinary bool) ([]JSONFile, error) { 76 | files := make([]JSONFile, 0, len(paths)) 77 | 78 | for _, path := range paths { 79 | if path.IsDir { 80 | continue 81 | } 82 | 83 | if skipBinary { 84 | isBinary, err := IsBinaryFile(path.Path) 85 | if err != nil { 86 | return nil, fmt.Errorf("checking if binary: %w", err) 87 | } 88 | 89 | if isBinary { 90 | files = append(files, JSONFile{ 91 | Path: path.RelativePath, 92 | Binary: true, 93 | }) 94 | continue 95 | } 96 | } 97 | 98 | content, err := os.ReadFile(path.Path) 99 | if err != nil { 100 | return nil, fmt.Errorf("reading file %s: %w", path.Path, err) 101 | } 102 | 103 | files = append(files, JSONFile{ 104 | Path: path.RelativePath, 105 | Content: string(content), 106 | }) 107 | } 108 | 109 | return files, nil 110 | } 111 | 112 | func generateOutlinesJSON(paths []PathInfo, registry *parser.Registry) ([]JSONFileOutline, error) { 113 | outlines := make([]JSONFileOutline, 0) 114 | 115 | for _, path := range paths { 116 | if path.IsDir || !registry.IsSupported(path.Path) { 117 | continue 118 | } 119 | 120 | content, err := os.ReadFile(path.Path) 121 | if err != nil { 122 | return nil, fmt.Errorf("reading file %s: %w", path.Path, err) 123 | } 124 | 125 | parser := registry.GetParser(path.Path) 126 | parsedOutline, err := parser.Parse(content, path.Path) 127 | if err != nil { 128 | return nil, fmt.Errorf("parsing file %s: %w", path.Path, err) 129 | } 130 | 131 | outline := JSONFileOutline{ 132 | Path: path.RelativePath, 133 | Symbols: make([]JSONSymbol, 0, len(parsedOutline.Symbols)), 134 | } 135 | 136 | // Convert parser.Symbols to our JSON Symbol type 137 | for _, sym := range parsedOutline.Symbols { 138 | symbol, err := convertSymbol(sym) 139 | if err != nil { 140 | return nil, fmt.Errorf("converting symbol in %s: %w", path.Path, err) 141 | } 142 | outline.Symbols = append(outline.Symbols, symbol) 143 | } 144 | 145 | // Add any parsing errors 146 | if len(parsedOutline.Errors) > 0 { 147 | outline.Errors = make([]string, len(parsedOutline.Errors)) 148 | for i, err := range parsedOutline.Errors { 149 | outline.Errors[i] = err.Error() 150 | } 151 | } 152 | 153 | outlines = append(outlines, outline) 154 | } 155 | 156 | return outlines, nil 157 | } 158 | 159 | func convertSymbol(ps *parser.Symbol) (JSONSymbol, error) { 160 | children := make([]JSONSymbol, 0, len(ps.Children)) 161 | for _, child := range ps.Children { 162 | converted, err := convertSymbol(child) 163 | if err != nil { 164 | return JSONSymbol{}, fmt.Errorf("converting child symbol: %w", err) 165 | } 166 | children = append(children, converted) 167 | } 168 | 169 | return JSONSymbol{ 170 | Type: ps.Type, 171 | Name: ps.Name, 172 | Signature: ps.Signature, 173 | Documentation: ps.Docstring, 174 | Decorators: ps.Decorators, 175 | Children: children, 176 | Metadata: ps.Metadata, 177 | }, nil 178 | } 179 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "strings" 7 | 8 | "github.com/Broderick-Westrope/amalgo/internal" 9 | "github.com/Broderick-Westrope/amalgo/internal/parser" 10 | "github.com/alecthomas/kong" 11 | "github.com/fatih/color" 12 | ) 13 | 14 | const ( 15 | appName = "amalgo" 16 | version = "0.5.1" 17 | ) 18 | 19 | func main() { 20 | os.Exit(run()) 21 | } 22 | 23 | func run() int { 24 | cli := RootCmd{ 25 | Version: versionFlag(version), 26 | } 27 | 28 | exitHandler := &exitWriter{code: -1} 29 | ctx := kong.Parse(&cli, 30 | kong.Name(appName), 31 | kong.Description("Create consolidated snapshots of source code for analysis, documentation, and sharing with LLMs."), 32 | kong.UsageOnError(), 33 | kong.Writers(os.Stdout, exitHandler), 34 | kong.Exit(exitHandler.Exit), 35 | kong.DefaultEnvars(appName), 36 | kong.Vars{"version": string(cli.Version)}, 37 | ) 38 | 39 | switch { 40 | case exitHandler.code == 0: 41 | return exitHandler.code 42 | case exitHandler.code != -1: 43 | fmt.Fprintf(os.Stderr, "%s", exitHandler.message) 44 | return exitHandler.code 45 | } 46 | 47 | err := ctx.Run() 48 | if err != nil { 49 | fmt.Fprintf(os.Stderr, "error: %v\n", err) 50 | return 1 51 | } 52 | return 0 53 | } 54 | 55 | type RootCmd struct { 56 | // Default command args and flags 57 | Dir string `arg:"" optional:"" help:"Directory to analyze. If a file is provided it's parent directory will be used." type:"path" default:"."` 58 | Output string `help:"Specifies the destination path for the output file. The file extension will automatically adjust based on the selected format (see '--format')." short:"o" type:"path" placeholder:"amalgo.txt"` 59 | Stdout bool `help:"Redirects all output to standard output (terminal) instead of writing to a file. Useful for piping output to other commands."` 60 | Filter []string `help:"Controls which files are processed using glob patterns. Include patterns are processed first, then exclude patterns (prefixed with '!'). Hidden files and directories are excluded by default." short:"f" default:"*,!.*"` 61 | GitIgnore []string `help:"Specifies .gitignore files to use for filtering. These patterns are processed before the filter patterns, taking precedence. Of the provided gitignore files, the last one will take the highest precedence." name:"gitignore" short:"g"` 62 | NoTree bool `help:"Skips the inclusion of the file tree in the output." default:"false"` 63 | NoDump bool `help:"Skips the inclusion of file contents in the output." default:"false"` 64 | Outline bool `help:"Includes in the output a language-aware outline of code files, showing functions, classes, and other significant elements. Only available for specific file extensions: '.go'." default:"false"` 65 | NoColor bool `help:"Disables ANSI color codes in the output." default:"false"` 66 | IncludeBinary bool `help:"Processes binary files instead of skipping them. Use with caution as this may produce large or unreadable output." default:"false"` 67 | Format internal.OutputFormat `help:"Selects an alternative output format. This affects both the structure and the file extension of the output. Options: 'default', 'json'." enum:"default,json" default:"default"` 68 | 69 | // Subcommands 70 | Version versionFlag `help:"Displays the current version of the tool and exits immediately." short:"v" name:"version"` 71 | } 72 | 73 | func (c *RootCmd) validate() bool { 74 | if c.Output == "" { 75 | if c.Format == internal.OutputFormatJSON { 76 | c.Output += "amalgo.json" 77 | } else { 78 | c.Output = "amalgo.txt" 79 | } 80 | } 81 | 82 | issues := make([]string, 0) 83 | if c.NoDump && c.NoTree && !c.Outline { 84 | issues = append(issues, "An empty output is not allowed (no dump, no tree, and no outline).") 85 | } 86 | 87 | if len(issues) == 0 { 88 | return true 89 | } 90 | out := strings.Join(issues, "\n") 91 | if !c.NoColor { 92 | out = color.RedString(out) 93 | } 94 | fmt.Println(out) 95 | return false 96 | } 97 | 98 | func (c *RootCmd) Run() error { 99 | if !c.validate() { 100 | return nil 101 | } 102 | 103 | outputDest := c.Output 104 | if c.Stdout { 105 | outputDest = "stdout" 106 | } 107 | 108 | registry := parser.NewRegistry() 109 | registry.Register(parser.NewGoParser()) 110 | 111 | paths, err := internal.TraverseDirectory(c.Dir, c.Filter, c.GitIgnore) 112 | if err != nil { 113 | return fmt.Errorf("traversing directories: %w", err) 114 | } 115 | 116 | outputOpts := internal.OutputOptions{ 117 | NoTree: c.NoTree, 118 | NoDump: c.NoDump, 119 | Outline: c.Outline, 120 | SkipBinary: !c.IncludeBinary, 121 | Format: c.Format, 122 | } 123 | 124 | output, err := internal.GenerateOutput(paths, registry, outputOpts) 125 | if err != nil { 126 | return fmt.Errorf("generating output: %w", err) 127 | } 128 | 129 | err = internal.WriteOutput(outputDest, output) 130 | if err != nil { 131 | return fmt.Errorf("writing output: %w", err) 132 | } 133 | 134 | // Print success message unless output is stdout. 135 | if outputDest != "stdout" { 136 | msg := fmt.Sprintf("Successfully generated output to: %s\n", outputDest) 137 | if !c.NoColor { 138 | msg = color.GreenString(msg) 139 | } 140 | fmt.Print(msg) 141 | } 142 | 143 | return nil 144 | } 145 | 146 | // Custom writer that can capture output for testing 147 | type exitWriter struct { 148 | code int 149 | message string 150 | } 151 | 152 | func (w *exitWriter) Write(p []byte) (n int, err error) { 153 | w.message += string(p) 154 | return len(p), nil 155 | } 156 | 157 | func (w *exitWriter) Exit(code int) { 158 | w.code = code 159 | } 160 | 161 | type versionFlag string 162 | 163 | func (v versionFlag) Decode(_ *kong.DecodeContext) error { return nil } 164 | func (v versionFlag) IsBool() bool { return true } 165 | func (v versionFlag) BeforeApply(app *kong.Kong, vars kong.Vars) error { 166 | fmt.Println(vars["version"]) 167 | app.Exit(0) 168 | return nil 169 | } 170 | -------------------------------------------------------------------------------- /pkg/filter/filter.go: -------------------------------------------------------------------------------- 1 | // Package filter provides functionality for matching paths against exclusion patterns 2 | // using a syntax similar to gitignore - patterns indicate what to include (match against) 3 | // unless prefixed with '!'. This can be used for both file inclusion and exclusion. 4 | package filter 5 | 6 | import ( 7 | "os" 8 | "path/filepath" 9 | "regexp" 10 | "strings" 11 | ) 12 | 13 | // Filter wraps a list of filter patterns. 14 | type Filter struct { 15 | patterns []*Pattern 16 | } 17 | 18 | // Pattern encapsulates a regexp pattern and whether it is negated. 19 | type Pattern struct { 20 | Pattern *regexp.Regexp 21 | Negate bool 22 | LineNo int 23 | Line string 24 | } 25 | 26 | // MergeWithoutPrecedence prepends the patterns of the given filter. 27 | // The provided patterns will be used first, meaning they may be 28 | // overruled by the existing patterns (on this Filter). 29 | func (f *Filter) MergeWithoutPrecedence(other *Filter) { 30 | f.patterns = append(other.patterns, f.patterns...) 31 | } 32 | 33 | // MergeWithoutPrecedence appends the patterns of the given filter. 34 | // The provided patterns will be used last, meaning they may 35 | // overrule the existing patterns (on this Filter). 36 | func (f *Filter) MergeWithPrecedence(other *Filter) { 37 | f.patterns = append(f.patterns, other.patterns...) 38 | } 39 | 40 | func (f *Filter) NegateAll() { 41 | for i := range f.patterns { 42 | f.patterns[i].Negate = !f.patterns[i].Negate 43 | 44 | pattern, found := strings.CutPrefix(f.patterns[i].Line, "!") 45 | if !found { 46 | pattern = "!" + f.patterns[i].Line 47 | } 48 | f.patterns[i].Line = pattern 49 | } 50 | } 51 | 52 | // MatchesPath returns true if the path matches the patterns. 53 | func (f *Filter) MatchesPath(path string) bool { 54 | matches, _ := f.MatchesPathHow(path) 55 | return matches 56 | } 57 | 58 | // MatchesPathHow returns whether the path matches and which pattern matched it. 59 | func (f *Filter) MatchesPathHow(path string) (bool, *Pattern) { 60 | // Normalize path separators. 61 | path = filepath.ToSlash(path) 62 | 63 | var matchingPattern *Pattern 64 | matchesPath := false 65 | 66 | for _, pattern := range f.patterns { 67 | if pattern.Pattern.MatchString(path) { 68 | if !pattern.Negate { 69 | matchesPath = true 70 | matchingPattern = pattern 71 | } else if matchesPath { 72 | // Path was previously matched but now negated. 73 | matchesPath = false 74 | matchingPattern = pattern 75 | } 76 | } 77 | } 78 | return matchesPath, matchingPattern 79 | } 80 | 81 | // CompileFilterPatterns accepts a variadic set of strings and returns a Filterer 82 | // instance with the compiled patterns. 83 | func CompileFilterPatterns(patterns ...string) *Filter { 84 | f := new(Filter) 85 | for i, pattern := range patterns { 86 | pattern = strings.TrimRight(pattern, "\r") 87 | pattern = strings.TrimSpace(pattern) 88 | compiledPattern, isNegated := getPatternFromLine(pattern) 89 | if compiledPattern != nil { 90 | fp := &Pattern{compiledPattern, isNegated, i + 1, pattern} 91 | f.patterns = append(f.patterns, fp) 92 | } 93 | } 94 | return f 95 | } 96 | 97 | // CompileFilterPatternFile reads patterns from a file and compiles them. 98 | func CompileFilterPatternFile(path string) (*Filter, error) { 99 | bs, err := os.ReadFile(path) 100 | if err != nil { 101 | return nil, err 102 | } 103 | 104 | patterns := strings.Split(string(bs), "\n") 105 | return CompileFilterPatterns(patterns...), nil 106 | } 107 | 108 | // CompileExcludePatternFileAndLines compiles patterns from both a file and additional lines. 109 | func CompileFilterPatternFileAndLines(path string, lines ...string) (*Filter, error) { 110 | bs, err := os.ReadFile(path) 111 | if err != nil { 112 | return nil, err 113 | } 114 | 115 | patterns := append(strings.Split(string(bs), "\n"), lines...) 116 | return CompileFilterPatterns(patterns...), nil 117 | } 118 | 119 | // getPatternFromLine converts a single pattern line into a regexp and bool indicating 120 | // if it's a negated pattern. The rules follow .gitignore syntax. 121 | func getPatternFromLine(line string) (*regexp.Regexp, bool) { 122 | // Strip comments. 123 | if strings.HasPrefix(line, "#") { 124 | return nil, false 125 | } 126 | 127 | // Skip empty lines. 128 | if line == "" { 129 | return nil, false 130 | } 131 | 132 | // Check for negation prefix. Several will negate the previous negation (ie. toggling). 133 | negatePattern := false 134 | for line[0] == '!' { 135 | negatePattern = !negatePattern 136 | line = line[1:] 137 | } 138 | 139 | // Create a copy of the line to modify. The original is maintained for later checks. 140 | expr := line 141 | 142 | // Ignore a prefix of escaped '#' or '!'. 143 | if regexp.MustCompile(`^(\#|\!)`).MatchString(expr) { 144 | expr = expr[1:] 145 | } 146 | 147 | // Escape dots. 148 | expr = regexp.MustCompile(`\.`).ReplaceAllString(expr, `\.`) 149 | 150 | // This 'magic star" is used temporarily when handling other single-star cases. 151 | magicStar := "#$~" 152 | 153 | // Handle '/**/' patterns. 154 | if strings.HasPrefix(expr, "/**/") { 155 | expr = expr[1:] 156 | } 157 | expr = regexp.MustCompile(`/\*\*/`).ReplaceAllString(expr, `(/|/.+/)`) 158 | expr = regexp.MustCompile(`\*\*/`).ReplaceAllString(expr, `(|.`+magicStar+`/)`) 159 | expr = regexp.MustCompile(`/\*\*`).ReplaceAllString(expr, `(|/.`+magicStar+`)`) 160 | 161 | // Handle wildcards. 162 | expr = regexp.MustCompile(`\\\*`).ReplaceAllString(expr, `\`+magicStar) 163 | expr = regexp.MustCompile(`\*`).ReplaceAllString(expr, `([^/]*)`) // '*' may be any number of characters other than '/' 164 | expr = strings.Replace(expr, "?", `[^/]`, -1) // '?' may be any single character other than '/' 165 | expr = strings.Replace(expr, magicStar, "*", -1) 166 | 167 | // Build final regex. 168 | if strings.HasSuffix(line, "/") { 169 | expr += "(|.*)$" 170 | } else { 171 | expr += "(|/.*)$" 172 | } 173 | 174 | // Only add directory prefix for patterns starting with / 175 | switch { 176 | case strings.HasPrefix(line, "/"): 177 | expr = "^(|/)" + expr[1:] 178 | 179 | case strings.HasPrefix(line, "**/"): 180 | // Pattern contains a slash but doesn't start with one 181 | expr = "^(|.*/)" + expr 182 | 183 | default: 184 | // Simple pattern like *.go - should only match in current directory 185 | expr = "^" + expr 186 | } 187 | 188 | pattern, _ := regexp.Compile(expr) 189 | return pattern, negatePattern 190 | } 191 | -------------------------------------------------------------------------------- /internal/parser/golang.go: -------------------------------------------------------------------------------- 1 | package parser 2 | 3 | import ( 4 | "go/ast" 5 | "go/parser" 6 | "go/token" 7 | "strings" 8 | ) 9 | 10 | // GoParser implements Parser for Go source files 11 | type GoParser struct{} 12 | 13 | // NewGoParser creates a new Go parser 14 | func NewGoParser() *GoParser { 15 | return &GoParser{} 16 | } 17 | 18 | func (p *GoParser) Extensions() []string { 19 | return []string{".go"} 20 | } 21 | 22 | func (p *GoParser) Parse(content []byte, filename string) (*FileOutline, error) { 23 | fset := token.NewFileSet() 24 | file, err := parser.ParseFile(fset, filename, content, parser.ParseComments) 25 | if err != nil { 26 | return &FileOutline{ 27 | Filename: filename, 28 | Errors: []error{err}, 29 | }, nil 30 | } 31 | 32 | outline := &FileOutline{ 33 | Filename: filename, 34 | Symbols: make([]*Symbol, 0), 35 | } 36 | 37 | // Process package-level declarations 38 | for _, decl := range file.Decls { 39 | symbols := p.processDecl(decl, file) 40 | outline.Symbols = append(outline.Symbols, symbols...) 41 | } 42 | 43 | return outline, nil 44 | } 45 | 46 | func (p *GoParser) processDecl(decl ast.Decl, file *ast.File) []*Symbol { 47 | var symbols []*Symbol 48 | 49 | switch d := decl.(type) { 50 | case *ast.FuncDecl: 51 | symbol := &Symbol{ 52 | Type: "function", 53 | Name: d.Name.Name, 54 | Signature: p.getFunctionSignature(d), 55 | Docstring: p.getDocstring(d.Doc), 56 | } 57 | 58 | // Handle methods 59 | if d.Recv != nil { 60 | symbol.Type = "method" 61 | if len(d.Recv.List) > 0 { 62 | recvType := p.typeToString(d.Recv.List[0].Type) 63 | symbol.Name = recvType + "." + d.Name.Name 64 | } 65 | } 66 | 67 | symbols = append(symbols, symbol) 68 | 69 | case *ast.GenDecl: 70 | switch d.Tok { 71 | case token.TYPE: 72 | for _, spec := range d.Specs { 73 | if typeSpec, ok := spec.(*ast.TypeSpec); ok { 74 | symbol := &Symbol{ 75 | Type: p.getTypeSymbolType(typeSpec), 76 | Name: typeSpec.Name.Name, 77 | Docstring: p.getDocstring(d.Doc), 78 | } 79 | 80 | // Handle interface methods and struct fields 81 | if symbol.Type == "interface" { 82 | if iface, ok := typeSpec.Type.(*ast.InterfaceType); ok { 83 | symbol.Children = p.processInterface(iface) 84 | } 85 | } else if symbol.Type == "struct" { 86 | if structType, ok := typeSpec.Type.(*ast.StructType); ok { 87 | symbol.Children = p.processStruct(structType) 88 | } 89 | } 90 | 91 | symbols = append(symbols, symbol) 92 | } 93 | } 94 | 95 | case token.CONST, token.VAR: 96 | for _, spec := range d.Specs { 97 | if valSpec, ok := spec.(*ast.ValueSpec); ok { 98 | for _, name := range valSpec.Names { 99 | symbol := &Symbol{ 100 | Type: strings.ToLower(d.Tok.String()), 101 | Name: name.Name, 102 | Docstring: p.getDocstring(d.Doc), 103 | } 104 | if valSpec.Type != nil { 105 | symbol.Signature = p.typeToString(valSpec.Type) 106 | } 107 | symbols = append(symbols, symbol) 108 | } 109 | } 110 | } 111 | } 112 | } 113 | 114 | return symbols 115 | } 116 | 117 | func (p *GoParser) processInterface(iface *ast.InterfaceType) []*Symbol { 118 | var methods []*Symbol 119 | if iface.Methods == nil { 120 | return methods 121 | } 122 | 123 | for _, method := range iface.Methods.List { 124 | if len(method.Names) == 0 { 125 | continue // Skip embedded interfaces 126 | } 127 | 128 | methodType, ok := method.Type.(*ast.FuncType) 129 | if !ok { 130 | continue 131 | } 132 | 133 | for _, name := range method.Names { 134 | symbol := &Symbol{ 135 | Type: "method", 136 | Name: name.Name, 137 | Signature: p.getFuncTypeSignature(methodType), 138 | Docstring: p.getDocstring(method.Doc), 139 | } 140 | methods = append(methods, symbol) 141 | } 142 | } 143 | 144 | return methods 145 | } 146 | 147 | func (p *GoParser) processStruct(structType *ast.StructType) []*Symbol { 148 | var fields []*Symbol 149 | if structType.Fields == nil { 150 | return fields 151 | } 152 | 153 | for _, field := range structType.Fields.List { 154 | if len(field.Names) == 0 { 155 | // Anonymous/embedded field 156 | symbol := &Symbol{ 157 | Type: "field", 158 | Name: p.typeToString(field.Type), 159 | Signature: p.typeToString(field.Type), 160 | Docstring: p.getDocstring(field.Doc), 161 | } 162 | fields = append(fields, symbol) 163 | continue 164 | } 165 | 166 | for _, name := range field.Names { 167 | symbol := &Symbol{ 168 | Type: "field", 169 | Name: name.Name, 170 | Signature: p.typeToString(field.Type), 171 | Docstring: p.getDocstring(field.Doc), 172 | } 173 | fields = append(fields, symbol) 174 | } 175 | } 176 | 177 | return fields 178 | } 179 | 180 | func (p *GoParser) getFunctionSignature(fn *ast.FuncDecl) string { 181 | var builder strings.Builder 182 | builder.WriteString("func ") 183 | 184 | // Add receiver if it's a method 185 | if fn.Recv != nil && len(fn.Recv.List) > 0 { 186 | builder.WriteString("(") 187 | if len(fn.Recv.List[0].Names) > 0 { 188 | builder.WriteString(fn.Recv.List[0].Names[0].Name) 189 | builder.WriteString(" ") 190 | } 191 | builder.WriteString(p.typeToString(fn.Recv.List[0].Type)) 192 | builder.WriteString(") ") 193 | } 194 | 195 | builder.WriteString(fn.Name.Name) 196 | builder.WriteString(p.getFuncTypeSignature(fn.Type)) 197 | return builder.String() 198 | } 199 | 200 | func (p *GoParser) getFuncTypeSignature(ft *ast.FuncType) string { 201 | var builder strings.Builder 202 | builder.WriteString("(") 203 | 204 | if ft.Params != nil { 205 | for i, param := range ft.Params.List { 206 | if i > 0 { 207 | builder.WriteString(", ") 208 | } 209 | for j, name := range param.Names { 210 | if j > 0 { 211 | builder.WriteString(", ") 212 | } 213 | builder.WriteString(name.Name) 214 | } 215 | if len(param.Names) > 0 { 216 | builder.WriteString(" ") 217 | } 218 | builder.WriteString(p.typeToString(param.Type)) 219 | } 220 | } 221 | 222 | builder.WriteString(")") 223 | 224 | if ft.Results != nil { 225 | if ft.Results.NumFields() == 1 && len(ft.Results.List[0].Names) == 0 { 226 | builder.WriteString(" ") 227 | builder.WriteString(p.typeToString(ft.Results.List[0].Type)) 228 | } else { 229 | builder.WriteString(" (") 230 | for i, result := range ft.Results.List { 231 | if i > 0 { 232 | builder.WriteString(", ") 233 | } 234 | for j, name := range result.Names { 235 | if j > 0 { 236 | builder.WriteString(", ") 237 | } 238 | builder.WriteString(name.Name) 239 | } 240 | if len(result.Names) > 0 { 241 | builder.WriteString(" ") 242 | } 243 | builder.WriteString(p.typeToString(result.Type)) 244 | } 245 | builder.WriteString(")") 246 | } 247 | } 248 | 249 | return builder.String() 250 | } 251 | 252 | func (p *GoParser) typeToString(expr ast.Expr) string { 253 | switch t := expr.(type) { 254 | case *ast.Ident: 255 | return t.Name 256 | case *ast.SelectorExpr: 257 | return p.typeToString(t.X) + "." + t.Sel.Name 258 | case *ast.StarExpr: 259 | return "*" + p.typeToString(t.X) 260 | case *ast.ArrayType: 261 | return "[]" + p.typeToString(t.Elt) 262 | case *ast.MapType: 263 | return "map[" + p.typeToString(t.Key) + "]" + p.typeToString(t.Value) 264 | case *ast.InterfaceType: 265 | return "interface{}" 266 | case *ast.ChanType: 267 | switch t.Dir { 268 | case ast.SEND: 269 | return "chan<- " + p.typeToString(t.Value) 270 | case ast.RECV: 271 | return "<-chan " + p.typeToString(t.Value) 272 | default: 273 | return "chan " + p.typeToString(t.Value) 274 | } 275 | case *ast.FuncType: 276 | return "func" + p.getFuncTypeSignature(t) 277 | case *ast.StructType: 278 | return "struct{...}" 279 | case *ast.Ellipsis: 280 | return "..." + p.typeToString(t.Elt) 281 | default: 282 | return "" 283 | } 284 | } 285 | 286 | func (p *GoParser) getTypeSymbolType(typeSpec *ast.TypeSpec) string { 287 | switch typeSpec.Type.(type) { 288 | case *ast.InterfaceType: 289 | return "interface" 290 | case *ast.StructType: 291 | return "struct" 292 | default: 293 | return "type" 294 | } 295 | } 296 | 297 | func (p *GoParser) getDocstring(doc *ast.CommentGroup) string { 298 | if doc == nil { 299 | return "" 300 | } 301 | return doc.Text() 302 | } 303 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # amalgo 2 | 3 | [![Version](https://img.shields.io/badge/Go-1.23-00ADD8?style=flat&logo=go)](https://go.dev/doc/install) 4 | [![Reference](https://img.shields.io/badge/Go-Reference-00ADD8?style=flat&logo=go)](https://pkg.go.dev/github.com/Broderick-Westrope/amalgo) 5 | [![License](https://img.shields.io/badge/license-GNU%20GPLv3-blue.svg)](https://github.com/Broderick-Westrope/amalgo/blob/main/LICENSE) 6 | 7 | Amalgo is a command-line tool that creates consolidated snapshots (ie. an amalgamation) of source code for analysis, documentation, and sharing with [LLMs](https://en.wikipedia.org/wiki/Large_language_model). It helps developers gather and organize their codebase into a single, well-structured document. 8 | 9 | - [Features](#features) 10 | - [Installation](#installation) 11 | - [Usage](#usage) 12 | - [Output Format](#output-format) 13 | - [Example Use Cases](#example-use-cases) 14 | - [Contributing](#contributing) 15 | - [License](#license) 16 | 17 | ## Features 18 | 19 | - 📁 **Directory Tree Generation**: Creates a visual representation of your project structure. 20 | - 📝 **Code Content Dumping**: Consolidates all source files into a single document. 21 | - 🎯 **Flexible Filtering**: Include/exclude files using the gitignore pattern syntax. 22 | - 🔍 **Language-Specific Outlines**: Generates structural outlines for supported programming languages. 23 | - 🎨 **Syntax Support**: The language outlines feature currently supports Go, with extensibility for other languages. All other features are language agnostic. 24 | - 🚫 **Binary File Handling**: Option to skip or include binary files. 25 | 26 | ## Installation 27 | 28 | ```bash 29 | # Using Homebrew 30 | brew install Broderick-Westrope/tap/amalgo 31 | 32 | # Using Go install 33 | go install github.com/Broderick-Westrope/amalgo@latest 34 | ``` 35 | 36 | You can also find various builds on [the releases page](https://github.com/Broderick-Westrope/amalgo/releases). 37 | 38 | ## Usage 39 | 40 | Use the help flag to get more information on usage: 41 | 42 | ```bash 43 | amalgo --help 44 | ``` 45 | 46 | Example commands: 47 | 48 | ```bash 49 | # Analyze current directory, excluding hidden files and directories by default 50 | amalgo 51 | 52 | # Analyze a specific directory 53 | amalgo internal/ 54 | 55 | # Output to a specific file 56 | amalgo -o output.txt 57 | 58 | # Print output to stdout 59 | amalgo --stdout 60 | 61 | # Include only specific file types (eg. Go files without any Go tests or hidden files/directories) 62 | amalgo -f '**/*.go,!**/*_test.go,!.*' 63 | 64 | # Exclude certain directories (eg. include everything except the .git directory) 65 | amalgo -f '*,!.git/' 66 | 67 | # Include hidden files and directories 68 | amalgo -f '*' 69 | 70 | # Generate only the language-specific outline 71 | amalgo --no-tree --no-dump --outline 72 | ``` 73 | 74 | ### Positional Arguments 75 | 76 | - `dir` 77 | - **Description:** Directory to analyze. If a file is provided it's parent directory will be used. 78 | - **Optional:** `true` 79 | - **Default:** `.` (current directory) 80 | 81 | ### Flags 82 | 83 | Each flag has a corresponding environment variable which can be used to set the value. Flags override environment variables. 84 | 85 | - `-o, --output` 86 | - **Description:** Specifies the destination path for the output file. The file extension will automatically adjust based on the selected format (see `--format`). 87 | - **Default:** `amalgo.txt` 88 | - **Environment Variable:** `$AMALGO_OUTPUT` 89 | 90 | - `stdout` 91 | - **Description:** Redirects all output to standard output (terminal) instead of writing to a file. Useful for piping output to other commands. 92 | - **Default:** `false` 93 | - **Environment Variable:** `$AMALGO_STDOUT` 94 | 95 | - `-f, --filter` 96 | - **Description:** Controls which files are processed using glob patterns similar to gitignore. Include patterns are processed first, then exclude patterns (prefixed with `!`). Hidden files and directories are excluded by default. 97 | - **Default:** `*,!.*` 98 | - **Environment Variable:** `$AMALGO_FILTER` 99 | - **Examples:** 100 | - `*.go,*.{js,ts}` - Include only Go, JavaScript, and TypeScript files. 101 | - `*,!*.md` - Include everything except Markdown files. 102 | 103 | - `-g`,`--gitignore` 104 | - **Description:** Specifies `.gitignore` files to use for filtering. These patterns are merged with the filter patterns, taking the same precedence. 105 | - **Environment Variable:** `$AMALGO_GITIGNORE` 106 | - **Example**: `.gitignore,../some-project/.gitignore,strange.ignore.file` 107 | 108 | - `--no-tree` 109 | - **Description:** Skips the inclusion of the file tree in the output. 110 | - **Default:** `false` 111 | - **Environment Variable:** `$AMALGO_NO_TREE` 112 | 113 | - `--no-dump` 114 | - **Description:** Skips the inclusion of file contents in the output. 115 | - **Default:** `false` 116 | - **Environment Variable:** `$AMALGO_NO_DUMP` 117 | 118 | - `--outline` 119 | - **Description:** Includes in the output a language-aware outline of code files, showing functions, classes, and other significant elements. Only available for specific file extensions: `.go`. 120 | - **Default:** `false` 121 | - **Environment Variable:** `$AMALGO_OUTLINE` 122 | 123 | - `--no-color` 124 | - **Description:** Disables ANSI color codes in the output. 125 | - **Default:** `false` 126 | - **Environment Variable:** `$AMALGO_NO_COLOR` 127 | 128 | - `--include-binary` 129 | - **Description:** Processes binary files instead of skipping them. Use with caution as this may produce large or unreadable output. 130 | - **Default:** `false` 131 | - **Environment Variable:** `$AMALGO_INCLUDE_BINARY` 132 | 133 | - `--format` 134 | - **Description:** Selects an alternative output format. This affects both the structure and the file extension of the output. Options: `default`, `json`. 135 | - **Default:** `"default"` 136 | - **Environment Variable:** `$AMALGO_FORMAT` 137 | 138 | - `-v, --version` 139 | - **Description:** Displays the current version of the tool and exits immediately. 140 | - **Default:** `false` 141 | - **Environment Variable:** `$AMALGO_VERSION` 142 | 143 | ## Output Format 144 | 145 | Examples of each output format can be found in [examples/formats/](https://github.com/Broderick-Westrope/amalgo/tree/main/examples/formats). 146 | 147 | ## Example Use Cases 148 | 149 | ### 1. Project Onboarding & Understanding 150 | Get up to speed quickly with new codebases: 151 | - Generate comprehensive snapshots for LLM-powered project exploration 152 | - Understand architectural patterns and design decisions 153 | - Identify key components and their relationships 154 | - Perfect for new team members and project handovers 155 | 156 | ### 2. Project Documentation Generation 157 | Quickly create and maintain project documentation: 158 | - Generate READMEs that accurately reflect the current codebase 159 | - Create architecture diagrams and explanations backed by actual code 160 | - Build API documentation with real usage examples 161 | - Keep documentation synchronized with code as projects evolve 162 | 163 | ### 3. Smart Code Reviews & Pull Requests 164 | Generate context-rich snapshots of changes that help LLMs provide deeper insights: 165 | - Create comprehensive PR descriptions that understand implementation context 166 | - Generate targeted review checklists based on affected code patterns 167 | - Identify potential impacts on dependent modules and services 168 | - Go beyond simple diffs to understand architectural implications 169 | 170 | ### 2. Security Audit Assistant 171 | Leverage full codebase context for better security analysis: 172 | - Generate complete snapshots including configs, dependencies, and source code 173 | - Enable security-focused LLMs to identify complex vulnerability patterns 174 | - Catch security issues that emerge from component interactions 175 | - Perfect for pre-release audits and open-source project maintenance 176 | 177 | ### 4. Architectural Decision Analysis 178 | Make informed architectural decisions with full context: 179 | - Compare different approaches using comprehensive snapshots 180 | - Generate impact analysis reports for proposed changes 181 | - Document architectural decisions with complete implementation context 182 | - Track the evolution of architectural choices over time 183 | 184 | ### 5. Enhanced Bug Resolution 185 | Provide LLMs with all the context needed for better bug fixing: 186 | - Include related tests, configs, and error contexts in snapshots 187 | - Enable root cause analysis with full system context 188 | - Get fix suggestions that consider potential side effects 189 | - Generate targeted test cases for better coverage 190 | 191 | ## Contributing 192 | 193 | Contributions are welcome! Feel free to open issues and submit pull requests. 194 | 195 | I encourage you to create an issue and spark a discussion there before beginning work on a large change. This way we can be clear on the goals and acceptance criteria before investing time on it. 196 | 197 | ### What could be improved? 198 | 199 | Here are some suggestions: 200 | 201 | - **Language parsers:** If you would like to add first-class support for a new language that would be great! The `parser` package contains a `Parser` interface that defines what your new parser should include. 202 | - **Ideas:** The thing I'm most interested in hearing is ideas for unique use cases. If the use case requires some modifications that's fine. Similarly, if you think something can be done better I'd love to hear it. This is a relatively small CLI utility, so a bit of growth/change is acceptable for a cool enough use case ;) 203 | 204 | ## License 205 | 206 | This project is licensed under the GNU GPL v3 License - see the [LICENSE](./LICENSE) file for details. 207 | -------------------------------------------------------------------------------- /pkg/filter/filter_test.go: -------------------------------------------------------------------------------- 1 | package filter 2 | 3 | import ( 4 | "strings" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func TestMatchesPath(t *testing.T) { 11 | tests := map[string]struct { 12 | patterns []string 13 | path string 14 | want bool 15 | }{ 16 | "double asterisk at start": { 17 | patterns: []string{"**/test.txt"}, 18 | path: "deep/nested/test.txt", 19 | want: true, 20 | }, 21 | "double asterisk in middle": { 22 | patterns: []string{"src/**/test.txt"}, 23 | path: "src/deeply/nested/test.txt", 24 | want: true, 25 | }, 26 | "double asterisk at end": { 27 | patterns: []string{"src/**"}, 28 | path: "src/any/number/of/subdirs", 29 | want: true, 30 | }, 31 | "leading slash": { 32 | patterns: []string{"/root.txt"}, 33 | path: "root.txt", 34 | want: true, 35 | }, 36 | "single character wildcard": { 37 | patterns: []string{"test?.txt"}, 38 | path: "test1.txt", 39 | want: true, 40 | }, 41 | "actual dots in filenames": { 42 | patterns: []string{"*.txt"}, 43 | path: "file.txt", 44 | want: true, 45 | }, 46 | "multiple extensions separate patterns": { 47 | patterns: []string{"*.txt", "*.md", "*.json"}, 48 | path: "file.json", 49 | want: true, 50 | }, 51 | "complex nesting with negation": { 52 | patterns: []string{ 53 | "**/*.go", 54 | "!vendor/**", 55 | "vendor/allowed/*.go", 56 | }, 57 | path: "vendor/forbidden/file.go", 58 | want: false, 59 | }, 60 | "multiple patterns with precedence": { 61 | patterns: []string{ 62 | "*.txt", 63 | "!important/*.txt", 64 | "important/keepthis.txt", 65 | }, 66 | path: "important/keepthis.txt", 67 | want: true, 68 | }, 69 | "spaces in pattern": { 70 | patterns: []string{" *.txt ", " ", " # comment "}, 71 | path: "file.txt", 72 | want: true, 73 | }, 74 | "carriage return handling": { 75 | patterns: []string{"*.txt\r", "*.md\r"}, 76 | path: "file.txt", 77 | want: true, 78 | }, 79 | "simple match": { 80 | patterns: []string{"*.txt"}, 81 | path: "file.txt", 82 | want: true, 83 | }, 84 | "no match": { 85 | patterns: []string{"*.txt"}, 86 | path: "file.go", 87 | want: false, 88 | }, 89 | "negated pattern": { 90 | patterns: []string{"*.txt", "!test.txt"}, 91 | path: "test.txt", 92 | want: false, 93 | }, 94 | "directory match": { 95 | patterns: []string{"src/**/*.go"}, 96 | path: "src/pkg/file.go", 97 | want: true, 98 | }, 99 | "escaped characters": { 100 | patterns: []string{"\\#file.txt"}, 101 | path: "#file.txt", 102 | want: true, 103 | }, 104 | "multiple patterns with override": { 105 | patterns: []string{"*.txt", "!test.txt", "test.txt"}, 106 | path: "test.txt", 107 | want: true, 108 | }, 109 | "directory trailing slash": { 110 | patterns: []string{"logs/"}, 111 | path: "logs/debug.log", 112 | want: true, 113 | }, 114 | "comment and empty lines": { 115 | patterns: []string{"", "# comment", "*.txt"}, 116 | path: "file.txt", 117 | want: true, 118 | }, 119 | } 120 | 121 | for name, tc := range tests { 122 | t.Run(name, func(t *testing.T) { 123 | f := CompileFilterPatterns(tc.patterns...) 124 | got := f.MatchesPath(tc.path) 125 | assert.Equal(t, got, tc.want, "path: %q, patterns: %v", tc.path, tc.patterns) 126 | }) 127 | } 128 | } 129 | 130 | func TestMatchesPathHow(t *testing.T) { 131 | tests := map[string]struct { 132 | patterns []string 133 | path string 134 | wantMatch bool 135 | wantMatchLine string 136 | wantMatchNegate bool 137 | }{ 138 | "matches first pattern": { 139 | patterns: []string{"*.txt", "*.go"}, 140 | path: "file.txt", 141 | wantMatch: true, 142 | wantMatchLine: "*.txt", 143 | wantMatchNegate: false, 144 | }, 145 | "matches negated pattern": { 146 | patterns: []string{"*.txt", "!test.txt"}, 147 | path: "test.txt", 148 | wantMatch: false, 149 | wantMatchLine: "!test.txt", 150 | wantMatchNegate: true, 151 | }, 152 | "no match returns nil pattern": { 153 | patterns: []string{"*.txt"}, 154 | path: "file.go", 155 | wantMatch: false, 156 | wantMatchLine: "", 157 | wantMatchNegate: false, 158 | }, 159 | } 160 | 161 | for name, tc := range tests { 162 | t.Run(name, func(t *testing.T) { 163 | f := CompileFilterPatterns(tc.patterns...) 164 | gotMatch, gotPattern := f.MatchesPathHow(tc.path) 165 | 166 | assert.Equal(t, tc.wantMatch, gotMatch) 167 | 168 | if tc.wantMatchLine == "" { 169 | assert.Nil(t, gotPattern) 170 | return 171 | } 172 | 173 | assert.NotNil(t, gotPattern) 174 | assert.Equal(t, tc.wantMatchLine, gotPattern.Line) 175 | assert.Equal(t, tc.wantMatchNegate, gotPattern.Negate) 176 | }) 177 | } 178 | } 179 | 180 | func TestCompileAndMatchPatterns(t *testing.T) { 181 | tests := map[string]struct { 182 | patterns []string 183 | pathsToWant map[string]bool 184 | }{ 185 | "match all files": { 186 | patterns: []string{"*"}, 187 | pathsToWant: map[string]bool{ 188 | "main.go": true, 189 | "internal/util.go": true, 190 | "src/main.go": true, 191 | "src/internal/util.go": true, 192 | "README.md": true, 193 | "internal/test.txt": true, 194 | }, 195 | }, 196 | "match all files except top-level hidden files and directories": { 197 | patterns: []string{"*", "!.*"}, 198 | pathsToWant: map[string]bool{ 199 | "main.go": true, 200 | "internal/util.go": true, 201 | "src/main.go": true, 202 | "src/internal/util.go": true, 203 | "src/.env": true, 204 | "README.md": true, 205 | "internal/test.txt": true, 206 | 207 | ".git/config.txt": false, 208 | ".env": false, 209 | }, 210 | }, 211 | "match all files except recursive hidden files and directories": { 212 | patterns: []string{"*", "!**/.*"}, 213 | pathsToWant: map[string]bool{ 214 | "main.go": true, 215 | "internal/util.go": true, 216 | "src/main.go": true, 217 | "src/internal/util.go": true, 218 | "README.md": true, 219 | "internal/test.txt": true, 220 | 221 | "src/.env": false, 222 | ".git/config.txt": false, 223 | ".env": false, 224 | }, 225 | }, 226 | "match top-level go files": { 227 | patterns: []string{"*.go"}, 228 | pathsToWant: map[string]bool{ 229 | "main.go": true, 230 | 231 | "internal/util.go": false, 232 | "src/main.go": false, 233 | "src/internal/util.go": false, 234 | "README.md": false, 235 | "internal/test.txt": false, 236 | }, 237 | }, 238 | "match go files recursively": { 239 | patterns: []string{"**/*.go"}, 240 | pathsToWant: map[string]bool{ 241 | "main.go": true, 242 | "internal/util.go": true, 243 | "src/main.go": true, 244 | "src/internal/util.go": true, 245 | 246 | "README.md": false, 247 | "internal/test.txt": false, 248 | }, 249 | }, 250 | "match go files recursively with negation": { 251 | patterns: []string{"**/*.go", "!internal/**"}, 252 | pathsToWant: map[string]bool{ 253 | "main.go": true, 254 | "src/main.go": true, 255 | "src/internal/util.go": true, 256 | 257 | "internal/util.go": false, 258 | "README.md": false, 259 | "internal/test.txt": false, 260 | }, 261 | }, 262 | "match with escaped special characters": { 263 | patterns: []string{`\!important.txt`, `\#comment.txt`}, 264 | pathsToWant: map[string]bool{ 265 | "!important.txt": true, 266 | "#comment.txt": true, 267 | 268 | "important.txt": false, 269 | "comment.txt": false, 270 | "test/!important.txt": false, 271 | }, 272 | }, 273 | "match directories with trailing slash": { 274 | patterns: []string{"docs/", "!docs/internal/"}, 275 | pathsToWant: map[string]bool{ 276 | "docs/readme.md": true, 277 | "docs/api/spec.md": true, 278 | 279 | "docs/internal/dev.md": false, 280 | "docs/internal/arch.md": false, 281 | "other/docs/readme.md": false, 282 | }, 283 | }, 284 | "match with directory depth constraints": { 285 | patterns: []string{ 286 | "/*/*.go", // Matches files exactly one directory deep 287 | "!/**/test/", // Excludes any test directories at any depth 288 | }, 289 | pathsToWant: map[string]bool{ 290 | "cmd/main.go": true, 291 | "internal/config.go": true, 292 | 293 | "main.go": false, 294 | "pkg/sub/util.go": false, 295 | "cmd/test/testutil.go": false, 296 | }, 297 | }, 298 | "recursively match subdirectory and extension": { 299 | patterns: []string{"src/**/*.go"}, 300 | pathsToWant: map[string]bool{ 301 | "src/pkg/file.go": true, 302 | 303 | "cmd/main.go": false, 304 | "internal/config.go": false, 305 | "main.go": false, 306 | "pkg/sub/util.go": false, 307 | "cmd/test/testutil.go": false, 308 | }, 309 | }, 310 | "complex nested directory matching": { 311 | patterns: []string{ 312 | "src/*/test/**/*.go", 313 | "!src/*/test/vendor/**", 314 | "!src/temp/*/", 315 | }, 316 | pathsToWant: map[string]bool{ 317 | "src/project/test/unit/main_test.go": true, 318 | "src/lib/test/integration/helper_test.go": true, 319 | 320 | "src/project/test/vendor/mock/mock.go": false, 321 | "src/temp/cache/data.txt": false, 322 | "src/project/prod/main.go": false, 323 | }, 324 | }, 325 | "match with multiple pattern ordering": { 326 | patterns: []string{ 327 | "*.txt", 328 | "!important.txt", 329 | "!!important.txt", 330 | "!test/important.txt", 331 | }, 332 | pathsToWant: map[string]bool{ 333 | "readme.txt": true, 334 | "important.txt": true, 335 | "docs/notes.txt": false, 336 | "test/important.txt": false, 337 | }, 338 | }, 339 | "match with question mark wildcards": { 340 | patterns: []string{"test?.txt", "lib/????.go"}, 341 | pathsToWant: map[string]bool{ 342 | "test1.txt": true, 343 | "testa.txt": true, 344 | "lib/util.go": true, 345 | "lib/main.go": true, 346 | 347 | "test.txt": false, 348 | "test12.txt": false, 349 | "lib/utils.go": false, 350 | }, 351 | }, 352 | } 353 | 354 | for name, tt := range tests { 355 | t.Run(name, func(t *testing.T) { 356 | f := CompileFilterPatterns(tt.patterns...) 357 | 358 | for path, want := range tt.pathsToWant { 359 | got := f.MatchesPath(path) 360 | assert.Equal(t, want, got, "Patterns: %q; Path: %q", strings.Join(tt.patterns, ", "), path) 361 | } 362 | }) 363 | } 364 | } 365 | -------------------------------------------------------------------------------- /internal/traverse_test.go: -------------------------------------------------------------------------------- 1 | package internal 2 | 3 | import ( 4 | "errors" 5 | "os" 6 | "path/filepath" 7 | "strings" 8 | "testing" 9 | 10 | "github.com/MakeNowJust/heredoc" 11 | "github.com/stretchr/testify/assert" 12 | "github.com/stretchr/testify/require" 13 | ) 14 | 15 | func TestTraverseDirectories(t *testing.T) { 16 | // Create a temporary directory structure for testing. 17 | tmpDir := t.TempDir() 18 | 19 | // Create test directory structure. Bool indicates if it's a directory. 20 | testFiles := map[string]bool{ 21 | "src": true, 22 | "src/main.go": false, 23 | "src/README.md": false, 24 | "src/internal": true, 25 | "src/internal/util.go": false, 26 | "src/internal/another.go": false, 27 | "src/internal/test.txt": false, 28 | "vendor": true, 29 | "vendor/lib.go": false, 30 | } 31 | 32 | // Create the test files and directories. 33 | for path, isDir := range testFiles { 34 | fullPath := filepath.Join(tmpDir, path) 35 | if isDir { 36 | require.NoError(t, os.MkdirAll(fullPath, 0755)) 37 | } else { 38 | require.NoError(t, os.MkdirAll(filepath.Dir(fullPath), 0755)) 39 | require.NoError(t, os.WriteFile(fullPath, []byte("test content"), 0644)) 40 | } 41 | } 42 | 43 | { 44 | fullPath := filepath.Join(tmpDir, ".gitignore") 45 | require.NoError(t, os.MkdirAll(filepath.Dir(fullPath), 0755)) 46 | require.NoError(t, os.WriteFile(fullPath, []byte(heredoc.Doc(` 47 | internal/ 48 | !internal/util* 49 | `)), 0644)) 50 | } 51 | 52 | tests := map[string]struct { 53 | directory string 54 | filterPatterns []string 55 | wantRelPaths []string 56 | gitignorePaths []string 57 | wantErr bool 58 | }{ 59 | "match go files in top directory": { 60 | directory: filepath.Join(tmpDir, "src"), 61 | filterPatterns: []string{"*.go"}, 62 | wantRelPaths: []string{ 63 | "src/main.go", 64 | }, 65 | }, 66 | "match all go files": { 67 | directory: filepath.Join(tmpDir, "src"), 68 | filterPatterns: []string{"**/*.go"}, 69 | wantRelPaths: []string{ 70 | "src/main.go", 71 | "src/internal/util.go", 72 | "src/internal/another.go", 73 | }, 74 | }, 75 | "exclude directory": { 76 | directory: filepath.Join(tmpDir, "src"), 77 | filterPatterns: []string{"*.go", "**/*.go", "!internal/**"}, 78 | wantRelPaths: []string{ 79 | "src/main.go", 80 | }, 81 | }, 82 | "match specific directory": { 83 | directory: filepath.Join(tmpDir, "src", "internal"), 84 | filterPatterns: []string{"*"}, 85 | wantRelPaths: []string{ 86 | "internal/util.go", 87 | "internal/another.go", 88 | "internal/test.txt", 89 | }, 90 | }, 91 | "non-existent directory": { 92 | directory: filepath.Join(tmpDir, "nonexistent"), 93 | filterPatterns: []string{"**/*.go"}, 94 | wantErr: true, 95 | }, 96 | "file as directory": { 97 | directory: filepath.Join(tmpDir, "src", "main.go"), 98 | filterPatterns: []string{"*.go"}, 99 | wantRelPaths: []string{ 100 | "src/main.go", 101 | }, 102 | }, 103 | "match all go files with gitignore": { 104 | directory: filepath.Join(tmpDir, "src"), 105 | filterPatterns: []string{"**/*.go"}, 106 | gitignorePaths: []string{ 107 | filepath.Join(tmpDir, ".gitignore"), 108 | }, 109 | wantRelPaths: []string{ 110 | "src/main.go", 111 | "src/internal/util.go", 112 | }, 113 | }, 114 | "match specific file with conflicting gitignore": { 115 | directory: filepath.Join(tmpDir, "src"), 116 | filterPatterns: []string{"internal/test.txt"}, 117 | gitignorePaths: []string{ 118 | filepath.Join(tmpDir, ".gitignore"), 119 | }, 120 | wantRelPaths: []string{}, 121 | }, 122 | } 123 | 124 | for name, tt := range tests { 125 | t.Run(name, func(t *testing.T) { 126 | if tt.gitignorePaths == nil { 127 | tt.gitignorePaths = make([]string, 0) 128 | } 129 | paths, err := TraverseDirectory(tt.directory, tt.filterPatterns, tt.gitignorePaths) 130 | 131 | if tt.wantErr { 132 | require.Error(t, err) 133 | return 134 | } 135 | 136 | require.NoError(t, err) 137 | 138 | // Convert PathInfo slice to relative paths for easier comparison. 139 | var gotPaths []string 140 | for _, p := range paths { 141 | if !p.IsDir { // Only include files in our comparison 142 | gotPaths = append(gotPaths, p.RelativePath) 143 | } 144 | } 145 | assert.ElementsMatch(t, tt.wantRelPaths, gotPaths) 146 | 147 | // Additional validation of PathInfo fields. 148 | for _, p := range paths { 149 | // Paths should be absolute. 150 | assert.True(t, filepath.IsAbs(p.Path), "Path should be absolute: %s", p.Path) 151 | 152 | // RelativePath should not be absolute. 153 | assert.False(t, filepath.IsAbs(p.RelativePath), "RelativePath should be relative: %s", p.RelativePath) 154 | 155 | // Depth should match the number of path separators plus one. 156 | expectedDepth := 0 157 | if p.RelativePath != "" { 158 | expectedDepth = len(strings.Split(p.RelativePath, "/")) 159 | } 160 | assert.Equal(t, expectedDepth, p.Depth, "Incorrect depth for path: %s", p.RelativePath) 161 | } 162 | }) 163 | } 164 | } 165 | 166 | func TestProcessPaths(t *testing.T) { 167 | var nilPathInfoSlice []PathInfo = nil 168 | tests := map[string]struct { 169 | paths *[]PathInfo 170 | wantPaths []PathInfo 171 | wantErr error 172 | }{ 173 | "single file adds parent dirs": { 174 | paths: &[]PathInfo{ 175 | { 176 | Path: "/Users/someuser/dev/program/internal/file1.go", 177 | RelativePath: "program/internal/file1.go", 178 | Depth: 3, 179 | IsDir: false, 180 | }, 181 | }, 182 | wantPaths: []PathInfo{ 183 | { 184 | Path: "/Users/someuser/dev/program/internal/file1.go", 185 | RelativePath: "program/internal/file1.go", 186 | Depth: 3, 187 | IsDir: false, 188 | }, 189 | { 190 | Path: "/Users/someuser/dev/program", 191 | RelativePath: "program", 192 | Depth: 1, 193 | IsDir: true, 194 | }, 195 | { 196 | Path: "/Users/someuser/dev/program/internal", 197 | RelativePath: "program/internal", 198 | Depth: 2, 199 | IsDir: true, 200 | }, 201 | }, 202 | }, 203 | "multiple files same directory": { 204 | paths: &[]PathInfo{ 205 | { 206 | Path: "/Users/someuser/dev/program/internal/file1.go", 207 | RelativePath: "program/internal/file1.go", 208 | Depth: 3, 209 | IsDir: false, 210 | }, 211 | { 212 | Path: "/Users/someuser/dev/program/internal/file2.go", 213 | RelativePath: "program/internal/file2.go", 214 | Depth: 3, 215 | IsDir: false, 216 | }, 217 | }, 218 | wantPaths: []PathInfo{ 219 | { 220 | Path: "/Users/someuser/dev/program/internal/file1.go", 221 | RelativePath: "program/internal/file1.go", 222 | Depth: 3, 223 | IsDir: false, 224 | }, 225 | { 226 | Path: "/Users/someuser/dev/program/internal/file2.go", 227 | RelativePath: "program/internal/file2.go", 228 | Depth: 3, 229 | IsDir: false, 230 | }, 231 | { 232 | Path: "/Users/someuser/dev/program", 233 | RelativePath: "program", 234 | Depth: 1, 235 | IsDir: true, 236 | }, 237 | { 238 | Path: "/Users/someuser/dev/program/internal", 239 | RelativePath: "program/internal", 240 | Depth: 2, 241 | IsDir: true, 242 | }, 243 | }, 244 | }, 245 | "different directory depths": { 246 | paths: &[]PathInfo{ 247 | { 248 | Path: "/Users/someuser/dev/program/file1.go", 249 | RelativePath: "program/file1.go", 250 | Depth: 2, 251 | IsDir: false, 252 | }, 253 | { 254 | Path: "/Users/someuser/dev/program/internal/deep/file2.go", 255 | RelativePath: "program/internal/deep/file2.go", 256 | Depth: 4, 257 | IsDir: false, 258 | }, 259 | }, 260 | wantPaths: []PathInfo{ 261 | { 262 | Path: "/Users/someuser/dev/program/file1.go", 263 | RelativePath: "program/file1.go", 264 | Depth: 2, 265 | IsDir: false, 266 | }, 267 | { 268 | Path: "/Users/someuser/dev/program/internal/deep/file2.go", 269 | RelativePath: "program/internal/deep/file2.go", 270 | Depth: 4, 271 | IsDir: false, 272 | }, 273 | { 274 | Path: "/Users/someuser/dev/program", 275 | RelativePath: "program", 276 | Depth: 1, 277 | IsDir: true, 278 | }, 279 | { 280 | Path: "/Users/someuser/dev/program/internal", 281 | RelativePath: "program/internal", 282 | Depth: 2, 283 | IsDir: true, 284 | }, 285 | { 286 | Path: "/Users/someuser/dev/program/internal/deep", 287 | RelativePath: "program/internal/deep", 288 | Depth: 3, 289 | IsDir: true, 290 | }, 291 | }, 292 | }, 293 | "directory included": { 294 | paths: &[]PathInfo{ 295 | { 296 | Path: "/Users/someuser/dev/program/internal", 297 | RelativePath: "program/internal", 298 | Depth: 2, 299 | IsDir: true, 300 | }, 301 | { 302 | Path: "/Users/someuser/dev/program/internal/file1.go", 303 | RelativePath: "program/internal/file1.go", 304 | Depth: 3, 305 | IsDir: false, 306 | }, 307 | }, 308 | wantPaths: []PathInfo{ 309 | { 310 | Path: "/Users/someuser/dev/program/internal", 311 | RelativePath: "program/internal", 312 | Depth: 2, 313 | IsDir: true, 314 | }, 315 | { 316 | Path: "/Users/someuser/dev/program/internal/file1.go", 317 | RelativePath: "program/internal/file1.go", 318 | Depth: 3, 319 | IsDir: false, 320 | }, 321 | { 322 | Path: "/Users/someuser/dev/program", 323 | RelativePath: "program", 324 | Depth: 1, 325 | IsDir: true, 326 | }, 327 | }, 328 | }, 329 | "empty slice": { 330 | paths: &[]PathInfo{}, 331 | wantPaths: []PathInfo{}, 332 | }, 333 | "nil slice": { 334 | paths: &nilPathInfoSlice, 335 | wantPaths: []PathInfo{}, 336 | wantErr: errors.New("underlying paths slice cannot be nil"), 337 | }, 338 | "nil pointer": { 339 | paths: nil, 340 | wantPaths: []PathInfo{}, 341 | wantErr: errors.New("paths must be a pointer to a slice"), 342 | }, 343 | } 344 | 345 | for name, tt := range tests { 346 | t.Run(name, func(t *testing.T) { 347 | err := processPaths(tt.paths) 348 | if tt.wantErr != nil { 349 | assert.EqualError(t, err, tt.wantErr.Error()) 350 | return 351 | } 352 | require.NoError(t, err) 353 | 354 | assert.Equal(t, tt.wantPaths, *tt.paths) 355 | }) 356 | } 357 | } 358 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . --------------------------------------------------------------------------------