on main help sign in
remove node dependency and implement diff format
commit0130bde1edabb81d82dbce9d2d562966d2dee133 authorKujtim Hoxha <kujtimii.h@gmail.com> dateMon 14 Apr 2025, 14:09 (2 years ago) parent0b3e5f5
7 files changed+1028−372
go.mod+6−18 go.sum+1−56 internal/diff/diff.go+995 internal/git/diff.go−264 internal/llm/tools/edit.go+16−23 internal/llm/tools/write.go+7−8 internal/tui/components/dialog/permission.go+3−3
go.mod+6−18
@@ -7,6 +7,7 @@ toolchain go1.24.2
77require (
88 github.com/JohannesKaufmann/html-to-markdown v1.6.0
99 github.com/PuerkitoBio/goquery v1.9.2
10+ github.com/alecthomas/chroma/v2 v2.15.0
1011 github.com/anthropics/anthropic-sdk-go v0.2.0-beta.2
1112 github.com/bmatcuk/doublestar/v4 v4.8.1
1213 github.com/catppuccin/go v0.3.0
@@ -17,7 +18,6 @@ require (
1718 github.com/charmbracelet/lipgloss v1.1.0
1819 github.com/charmbracelet/x/ansi v0.8.0
1920 github.com/fsnotify/fsnotify v1.8.0
20− github.com/go-git/go-git/v5 v5.15.0
2121 github.com/go-logfmt/logfmt v0.6.0
2222 github.com/golang-migrate/migrate/v4 v4.18.2
2323 github.com/google/generative-ai-go v0.19.0
@@ -31,6 +31,7 @@ require (
3131 github.com/muesli/reflow v0.3.0
3232 github.com/muesli/termenv v0.16.0
3333 github.com/openai/openai-go v0.1.0-beta.2
34+ github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3
3435 github.com/spf13/cobra v1.9.1
3536 github.com/spf13/viper v1.20.0
3637 github.com/stretchr/testify v1.10.0
@@ -45,10 +46,6 @@ require (
4546 cloud.google.com/go/auth/oauth2adapt v0.2.6 // indirect
4647 cloud.google.com/go/compute/metadata v0.6.0 // indirect
4748 cloud.google.com/go/longrunning v0.5.7 // indirect
48− dario.cat/mergo v1.0.0 // indirect
49− github.com/Microsoft/go-winio v0.6.2 // indirect
50− github.com/ProtonMail/go-crypto v1.1.6 // indirect
51− github.com/alecthomas/chroma/v2 v2.15.0 // indirect
5249 github.com/andybalholm/cascadia v1.3.2 // indirect
5350 github.com/atotto/clipboard v0.1.4 // indirect
5451 github.com/aws/aws-sdk-go-v2 v1.30.3 // indirect
@@ -71,20 +68,15 @@ require (
7168 github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect
7269 github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect
7370 github.com/charmbracelet/x/term v0.2.1 // indirect
74− github.com/cloudflare/circl v1.6.1 // indirect
75− github.com/cyphar/filepath-securejoin v0.4.1 // indirect
7671 github.com/davecgh/go-spew v1.1.1 // indirect
7772 github.com/dlclark/regexp2 v1.11.4 // indirect
7873 github.com/dustin/go-humanize v1.0.1 // indirect
79− github.com/emirpasic/gods v1.18.1 // indirect
8074 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
8175 github.com/felixge/httpsnoop v1.0.4 // indirect
82− github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
83− github.com/go-git/go-billy/v5 v5.6.2 // indirect
8476 github.com/go-logr/logr v1.4.2 // indirect
8577 github.com/go-logr/stdr v1.2.2 // indirect
8678 github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
87− github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect
79+ github.com/google/go-cmp v0.7.0 // indirect
8880 github.com/google/s2a-go v0.1.8 // indirect
8981 github.com/googleapis/enterprise-certificate-proxy v0.3.4 // indirect
9082 github.com/googleapis/gax-go/v2 v2.14.1 // indirect
@@ -92,8 +84,6 @@ require (
9284 github.com/hashicorp/errwrap v1.1.0 // indirect
9385 github.com/hashicorp/go-multierror v1.1.1 // indirect
9486 github.com/inconshreveable/mousetrap v1.1.0 // indirect
95− github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
96− github.com/kevinburke/ssh_config v1.2.0 // indirect
9787 github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
9888 github.com/mattn/go-isatty v0.0.20 // indirect
9989 github.com/mattn/go-localereader v0.0.1 // indirect
@@ -101,13 +91,11 @@ require (
10191 github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect
10292 github.com/muesli/cancelreader v0.2.2 // indirect
10393 github.com/pelletier/go-toml/v2 v2.2.3 // indirect
104− github.com/pjbgf/sha1cd v0.3.2 // indirect
10594 github.com/pmezard/go-difflib v1.0.0 // indirect
10695 github.com/rivo/uniseg v0.4.7 // indirect
96+ github.com/rogpeppe/go-internal v1.14.1 // indirect
10797 github.com/sagikazarmark/locafero v0.7.0 // indirect
10898 github.com/sahilm/fuzzy v0.1.1 // indirect
109− github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect
110− github.com/skeema/knownhosts v1.3.1 // indirect
11199 github.com/sourcegraph/conc v0.3.0 // indirect
112100 github.com/spf13/afero v1.12.0 // indirect
113101 github.com/spf13/cast v1.7.1 // indirect
@@ -117,7 +105,6 @@ require (
117105 github.com/tidwall/match v1.1.1 // indirect
118106 github.com/tidwall/pretty v1.2.1 // indirect
119107 github.com/tidwall/sjson v1.2.5 // indirect
120− github.com/xanzy/ssh-agent v0.3.3 // indirect
121108 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
122109 github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
123110 github.com/yuin/goldmark v1.7.8 // indirect
@@ -131,6 +118,7 @@ require (
131118 go.uber.org/multierr v1.9.0 // indirect
132119 golang.design/x/clipboard v0.7.0 // indirect
133120 golang.org/x/crypto v0.37.0 // indirect
121+ golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 // indirect
134122 golang.org/x/exp/shiny v0.0.0-20250305212735-054e65f0b394 // indirect
135123 golang.org/x/image v0.14.0 // indirect
136124 golang.org/x/mobile v0.0.0-20231127183840-76ac6878050a // indirect
@@ -144,6 +132,6 @@ require (
144132 google.golang.org/genproto/googleapis/rpc v0.0.0-20241223144023-3abc09e42ca8 // indirect
145133 google.golang.org/grpc v1.67.3 // indirect
146134 google.golang.org/protobuf v1.36.1 // indirect
147− gopkg.in/warnings.v0 v0.1.2 // indirect
135+ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
148136 gopkg.in/yaml.v3 v3.0.1 // indirect
149137)
go.sum+1−56
@@ -10,17 +10,10 @@ cloud.google.com/go/compute/metadata v0.6.0 h1:A6hENjEsCDtC1k8byVsgwvVcioamEHvZ4
1010cloud.google.com/go/compute/metadata v0.6.0/go.mod h1:FjyFAW1MW0C203CEOMDTu3Dk1FlqW3Rga40jzHL4hfg=
1111cloud.google.com/go/longrunning v0.5.7 h1:WLbHekDbjK1fVFD3ibpFFVoyizlLRl73I7YKuAKilhU=
1212cloud.google.com/go/longrunning v0.5.7/go.mod h1:8GClkudohy1Fxm3owmBGid8W0pSgodEMwEAztp38Xng=
13−dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk=
14−dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=
1513github.com/JohannesKaufmann/html-to-markdown v1.6.0 h1:04VXMiE50YYfCfLboJCLcgqF5x+rHJnb1ssNmqpLH/k=
1614github.com/JohannesKaufmann/html-to-markdown v1.6.0/go.mod h1:NUI78lGg/a7vpEJTz/0uOcYMaibytE4BUOQS8k78yPQ=
1715github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
1816github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
19−github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY=
20−github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
21−github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
22−github.com/ProtonMail/go-crypto v1.1.6 h1:ZcV+Ropw6Qn0AX9brlQLAUXfqLBc7Bl+f/DmNxpLfdw=
23−github.com/ProtonMail/go-crypto v1.1.6/go.mod h1:rA3QumHc/FZ8pAHreoekgiAbzpNsfQAosU5td4SnOrE=
2417github.com/PuerkitoBio/goquery v1.9.2 h1:4/wZksC3KgkQw7SQgkKotmKljk0M6V8TUvA8Wb4yPeE=
2518github.com/PuerkitoBio/goquery v1.9.2/go.mod h1:GHPCaP0ODyyxqcNoFGYlAprUFH81NuRPd0GX3Zu2Mvk=
2619github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0=
@@ -31,12 +24,8 @@ github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc
3124github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
3225github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss=
3326github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU=
34−github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
35−github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
3627github.com/anthropics/anthropic-sdk-go v0.2.0-beta.2 h1:h7qxtumNjKPWFv1QM/HJy60MteeW23iKeEtBoY7bYZk=
3728github.com/anthropics/anthropic-sdk-go v0.2.0-beta.2/go.mod h1:AapDW22irxK2PSumZiQXYUFvsdQgkwIWlpESweWZI/c=
38−github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
39−github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
4029github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
4130github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
4231github.com/aws/aws-sdk-go-v2 v1.30.3 h1:jUeBtG0Ih+ZIFH0F4UkmL9w3cSpaMv9tYYDbzILP8dY=
@@ -99,11 +88,7 @@ github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 h1:qko
9988github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0/go.mod h1:pBhA0ybfXv6hDjQUZ7hk1lVxBiUbupdw5R31yPUViVQ=
10089github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
10190github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
102−github.com/cloudflare/circl v1.6.1 h1:zqIqSPIndyBh1bjLVVDHMPpVKqp8Su/V+6MeDzzQBQ0=
103−github.com/cloudflare/circl v1.6.1/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs=
10491github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
105−github.com/cyphar/filepath-securejoin v0.4.1 h1:JyxxyPEaktOD+GAnqIqTf9A8tHyAG22rowi7HkoSU1s=
106−github.com/cyphar/filepath-securejoin v0.4.1/go.mod h1:Sdj7gXlvMcPZsbhwhQ33GguGLDGQL7h7bg04C/+u9jI=
10792github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
10893github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
10994github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -111,10 +96,6 @@ github.com/dlclark/regexp2 v1.11.4 h1:rPYF9/LECdNymJufQKmri9gV604RvvABwgOA8un7yA
11196github.com/dlclark/regexp2 v1.11.4/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
11297github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
11398github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
114−github.com/elazarl/goproxy v1.7.2 h1:Y2o6urb7Eule09PjlhQRGNsqRfPmYI3KKQLFpCAV3+o=
115−github.com/elazarl/goproxy v1.7.2/go.mod h1:82vkLNir0ALaW14Rc399OTTjyNREgmdL2cVoIbS6XaE=
116−github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
117−github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
11899github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
119100github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
120101github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
@@ -123,16 +104,6 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk
123104github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
124105github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
125106github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
126−github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c=
127−github.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU=
128−github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI=
129−github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376/go.mod h1:an3vInlBmSxCcxctByoQdvwPiA7DTK7jaaFDBTtu0ic=
130−github.com/go-git/go-billy/v5 v5.6.2 h1:6Q86EsPXMa7c3YZ3aLAQsMA0VlWmy43r6FHqa/UNbRM=
131−github.com/go-git/go-billy/v5 v5.6.2/go.mod h1:rcFC2rAsp/erv7CMz9GczHcuD0D32fWzH+MJAU+jaUU=
132−github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399 h1:eMje31YglSBqCdIqdhKBW8lokaMrL3uTkpGYlE2OOT4=
133−github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399/go.mod h1:1OCfN199q1Jm3HZlxleg+Dw/mwps2Wbk9frAWm+4FII=
134−github.com/go-git/go-git/v5 v5.15.0 h1:f5Qn0W0F7ry1iN0ZwIU5m/n7/BKB4hiZfc+zlZx7ly0=
135−github.com/go-git/go-git/v5 v5.15.0/go.mod h1:4Ge4alE/5gPs30F2H1esi2gPd69R0C39lolkucHBOp8=
136107github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4=
137108github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
138109github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
@@ -144,8 +115,6 @@ github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIx
144115github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
145116github.com/golang-migrate/migrate/v4 v4.18.2 h1:2VSCMz7x7mjyTXx3m2zPokOY82LTRgxK1yQYKo6wWQ8=
146117github.com/golang-migrate/migrate/v4 v4.18.2/go.mod h1:2CM6tJvn2kqPXwnXO/d3rAQYiyoIm180VsO8PRX6Rpk=
147−github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=
148−github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=
149118github.com/google/generative-ai-go v0.19.0 h1:R71szggh8wHMCUlEMsW2A/3T+5LdEIkiaHSYgSpUgdg=
150119github.com/google/generative-ai-go v0.19.0/go.mod h1:JYolL13VG7j79kM5BtHz4qwONHkeJQzOCkKXnpqtS/E=
151120github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
@@ -169,11 +138,8 @@ github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUq
169138github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
170139github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
171140github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
172−github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A=
173−github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo=
174−github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4gf13a4=
175−github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
176141github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
142+github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
177143github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
178144github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
179145github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
@@ -213,17 +179,11 @@ github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=
213179github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=
214180github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
215181github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
216−github.com/onsi/gomega v1.34.1 h1:EUMJIKUjM8sKjYbtxQI9A4z2o+rruxnzNvpknOXie6k=
217−github.com/onsi/gomega v1.34.1/go.mod h1:kU1QgUvBDLXBJq618Xvm2LUX6rSAfRaFRTcdOeDLwwY=
218182github.com/openai/openai-go v0.1.0-beta.2 h1:Ra5nCFkbEl9w+UJwAciC4kqnIBUCcJazhmMA0/YN894=
219183github.com/openai/openai-go v0.1.0-beta.2/go.mod h1:g461MYGXEXBVdV5SaR/5tNzNbSfwTBBefwc+LlDCK0Y=
220184github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
221185github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
222−github.com/pjbgf/sha1cd v0.3.2 h1:a9wb0bp1oC2TGwStyn0Umc/IGKQnEgF0vVaZ8QF8eo4=
223−github.com/pjbgf/sha1cd v0.3.2/go.mod h1:zQWigSxVmsHEZow5qaLtPYxpcKMMQpa09ixqBxuCS6A=
224186github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
225−github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
226−github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
227187github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
228188github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
229189github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
@@ -243,9 +203,6 @@ github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAm
243203github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
244204github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 h1:n661drycOFuPLCN3Uc8sB6B/s6Z4t2xvBgU1htSHuq8=
245205github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
246−github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
247−github.com/skeema/knownhosts v1.3.1 h1:X2osQ+RAjK76shCbvhHHHVl3ZlgDm8apHEHFqRjnBY8=
248−github.com/skeema/knownhosts v1.3.1/go.mod h1:r7KTdC8l4uxWRyK2TpQZ/1o5HaSzh06ePQNxPwTcfiY=
249206github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
250207github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
251208github.com/spf13/afero v1.12.0 h1:UcOPyRBYczmFn6yvphxkn9ZEOY65cpwGKb5mL36mrqs=
@@ -259,7 +216,6 @@ github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An
259216github.com/spf13/viper v1.20.0 h1:zrxIyR3RQIOsarIrgL8+sAvALXul9jeEPa06Y0Ph6vY=
260217github.com/spf13/viper v1.20.0/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4=
261218github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
262−github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
263219github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
264220github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
265221github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
@@ -276,8 +232,6 @@ github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
276232github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
277233github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
278234github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
279−github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM=
280−github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw=
281235github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
282236github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
283237github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
@@ -306,7 +260,6 @@ golang.design/x/clipboard v0.7.0 h1:4Je8M/ys9AJumVnl8m+rZnIvstSnYj1fvzqYrU3TXvo=
306260golang.design/x/clipboard v0.7.0/go.mod h1:PQIvqYO9GP29yINEfsEn5zSQKAz3UgXmZKzDA6dnq2E=
307261golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
308262golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
309−golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
310263golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
311264golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
312265golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
@@ -324,7 +277,6 @@ golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91
324277golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
325278golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
326279golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
327−golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
328280golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
329281golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
330282golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
@@ -342,14 +294,10 @@ golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
342294golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610=
343295golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
344296golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
345−golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
346297golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
347−golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
348−golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
349298golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
350299golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
351300golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
352−golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
353301golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
354302golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
355303golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -372,7 +320,6 @@ golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o=
372320golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw=
373321golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
374322golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
375−golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
376323golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
377324golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
378325golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
@@ -401,8 +348,6 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8
401348gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
402349gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
403350gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
404−gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME=
405−gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI=
406351gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
407352gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
408353gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
internal/diff/diff.gonew file+995
@@ -0,0 +1,995 @@
1+package diff
2+
3+import (
4+ "bytes"
5+ "fmt"
6+ "io"
7+ "regexp"
8+ "strconv"
9+ "strings"
10+ "time"
11+
12+ "github.com/alecthomas/chroma/v2"
13+ "github.com/alecthomas/chroma/v2/formatters"
14+ "github.com/alecthomas/chroma/v2/lexers"
15+ "github.com/alecthomas/chroma/v2/styles"
16+ "github.com/charmbracelet/lipgloss"
17+ "github.com/charmbracelet/x/ansi"
18+ "github.com/sergi/go-diff/diffmatchpatch"
19+)
20+
21+// LineType represents the kind of line in a diff.
22+type LineType int
23+
24+const (
25+ // LineContext represents a line that exists in both the old and new file.
26+ LineContext LineType = iota
27+ // LineAdded represents a line added in the new file.
28+ LineAdded
29+ // LineRemoved represents a line removed from the old file.
30+ LineRemoved
31+)
32+
33+// DiffLine represents a single line in a diff, either from the old file,
34+// the new file, or a context line.
35+type DiffLine struct {
36+ OldLineNo int // Line number in the old file (0 for added lines)
37+ NewLineNo int // Line number in the new file (0 for removed lines)
38+ Kind LineType // Type of line (added, removed, context)
39+ Content string // Content of the line
40+}
41+
42+// Hunk represents a section of changes in a diff.
43+type Hunk struct {
44+ Header string
45+ Lines []DiffLine
46+}
47+
48+// DiffResult contains the parsed result of a diff.
49+type DiffResult struct {
50+ OldFile string
51+ NewFile string
52+ Hunks []Hunk
53+}
54+
55+// HunkDelta represents the change statistics for a hunk.
56+type HunkDelta struct {
57+ StartLine1 int
58+ LineCount1 int
59+ StartLine2 int
60+ LineCount2 int
61+}
62+
63+// linePair represents a pair of lines to be displayed side by side.
64+type linePair struct {
65+ left *DiffLine
66+ right *DiffLine
67+}
68+
69+// -------------------------------------------------------------------------
70+// Style Configuration with Option Pattern
71+// -------------------------------------------------------------------------
72+
73+// StyleConfig defines styling for diff rendering.
74+type StyleConfig struct {
75+ RemovedLineBg lipgloss.Color
76+ AddedLineBg lipgloss.Color
77+ ContextLineBg lipgloss.Color
78+ HunkLineBg lipgloss.Color
79+ HunkLineFg lipgloss.Color
80+ RemovedFg lipgloss.Color
81+ AddedFg lipgloss.Color
82+ LineNumberFg lipgloss.Color
83+ HighlightStyle string
84+ RemovedHighlightBg lipgloss.Color
85+ AddedHighlightBg lipgloss.Color
86+ RemovedLineNumberBg lipgloss.Color
87+ AddedLineNamerBg lipgloss.Color
88+ RemovedHighlightFg lipgloss.Color
89+ AddedHighlightFg lipgloss.Color
90+}
91+
92+// StyleOption defines a function that modifies a StyleConfig.
93+type StyleOption func(*StyleConfig)
94+
95+// NewStyleConfig creates a StyleConfig with default values and applies any provided options.
96+func NewStyleConfig(opts ...StyleOption) StyleConfig {
97+ // Set default values
98+ config := StyleConfig{
99+ RemovedLineBg: lipgloss.Color("#3A3030"),
100+ AddedLineBg: lipgloss.Color("#303A30"),
101+ ContextLineBg: lipgloss.Color("#212121"),
102+ HunkLineBg: lipgloss.Color("#2A2822"),
103+ HunkLineFg: lipgloss.Color("#D4AF37"),
104+ RemovedFg: lipgloss.Color("#7C4444"),
105+ AddedFg: lipgloss.Color("#478247"),
106+ LineNumberFg: lipgloss.Color("#888888"),
107+ HighlightStyle: "dracula",
108+ RemovedHighlightBg: lipgloss.Color("#612726"),
109+ AddedHighlightBg: lipgloss.Color("#256125"),
110+ RemovedLineNumberBg: lipgloss.Color("#332929"),
111+ AddedLineNamerBg: lipgloss.Color("#293229"),
112+ RemovedHighlightFg: lipgloss.Color("#FADADD"),
113+ AddedHighlightFg: lipgloss.Color("#DAFADA"),
114+ }
115+
116+ // Apply all provided options
117+ for _, opt := range opts {
118+ opt(&config)
119+ }
120+
121+ return config
122+}
123+
124+// WithRemovedLineBg sets the background color for removed lines.
125+func WithRemovedLineBg(color lipgloss.Color) StyleOption {
126+ return func(s *StyleConfig) {
127+ s.RemovedLineBg = color
128+ }
129+}
130+
131+// WithAddedLineBg sets the background color for added lines.
132+func WithAddedLineBg(color lipgloss.Color) StyleOption {
133+ return func(s *StyleConfig) {
134+ s.AddedLineBg = color
135+ }
136+}
137+
138+// WithContextLineBg sets the background color for context lines.
139+func WithContextLineBg(color lipgloss.Color) StyleOption {
140+ return func(s *StyleConfig) {
141+ s.ContextLineBg = color
142+ }
143+}
144+
145+// WithRemovedFg sets the foreground color for removed line markers.
146+func WithRemovedFg(color lipgloss.Color) StyleOption {
147+ return func(s *StyleConfig) {
148+ s.RemovedFg = color
149+ }
150+}
151+
152+// WithAddedFg sets the foreground color for added line markers.
153+func WithAddedFg(color lipgloss.Color) StyleOption {
154+ return func(s *StyleConfig) {
155+ s.AddedFg = color
156+ }
157+}
158+
159+// WithLineNumberFg sets the foreground color for line numbers.
160+func WithLineNumberFg(color lipgloss.Color) StyleOption {
161+ return func(s *StyleConfig) {
162+ s.LineNumberFg = color
163+ }
164+}
165+
166+// WithHighlightStyle sets the syntax highlighting style.
167+func WithHighlightStyle(style string) StyleOption {
168+ return func(s *StyleConfig) {
169+ s.HighlightStyle = style
170+ }
171+}
172+
173+// WithRemovedHighlightColors sets the colors for highlighted parts in removed text.
174+func WithRemovedHighlightColors(bg, fg lipgloss.Color) StyleOption {
175+ return func(s *StyleConfig) {
176+ s.RemovedHighlightBg = bg
177+ s.RemovedHighlightFg = fg
178+ }
179+}
180+
181+// WithAddedHighlightColors sets the colors for highlighted parts in added text.
182+func WithAddedHighlightColors(bg, fg lipgloss.Color) StyleOption {
183+ return func(s *StyleConfig) {
184+ s.AddedHighlightBg = bg
185+ s.AddedHighlightFg = fg
186+ }
187+}
188+
189+// WithRemovedLineNumberBg sets the background color for removed line numbers.
190+func WithRemovedLineNumberBg(color lipgloss.Color) StyleOption {
191+ return func(s *StyleConfig) {
192+ s.RemovedLineNumberBg = color
193+ }
194+}
195+
196+// WithAddedLineNumberBg sets the background color for added line numbers.
197+func WithAddedLineNumberBg(color lipgloss.Color) StyleOption {
198+ return func(s *StyleConfig) {
199+ s.AddedLineNamerBg = color
200+ }
201+}
202+
203+func WithHunkLineBg(color lipgloss.Color) StyleOption {
204+ return func(s *StyleConfig) {
205+ s.HunkLineBg = color
206+ }
207+}
208+
209+func WithHunkLineFg(color lipgloss.Color) StyleOption {
210+ return func(s *StyleConfig) {
211+ s.HunkLineFg = color
212+ }
213+}
214+
215+// -------------------------------------------------------------------------
216+// Parse Options with Option Pattern
217+// -------------------------------------------------------------------------
218+
219+// ParseConfig configures the behavior of diff parsing.
220+type ParseConfig struct {
221+ ContextSize int // Number of context lines to include
222+}
223+
224+// ParseOption defines a function that modifies a ParseConfig.
225+type ParseOption func(*ParseConfig)
226+
227+// NewParseConfig creates a ParseConfig with default values and applies any provided options.
228+func NewParseConfig(opts ...ParseOption) ParseConfig {
229+ // Set default values
230+ config := ParseConfig{
231+ ContextSize: 3,
232+ }
233+
234+ // Apply all provided options
235+ for _, opt := range opts {
236+ opt(&config)
237+ }
238+
239+ return config
240+}
241+
242+// WithContextSize sets the number of context lines to include.
243+func WithContextSize(size int) ParseOption {
244+ return func(p *ParseConfig) {
245+ if size >= 0 {
246+ p.ContextSize = size
247+ }
248+ }
249+}
250+
251+// -------------------------------------------------------------------------
252+// Side-by-Side Options with Option Pattern
253+// -------------------------------------------------------------------------
254+
255+// SideBySideConfig configures the rendering of side-by-side diffs.
256+type SideBySideConfig struct {
257+ TotalWidth int
258+ Style StyleConfig
259+}
260+
261+// SideBySideOption defines a function that modifies a SideBySideConfig.
262+type SideBySideOption func(*SideBySideConfig)
263+
264+// NewSideBySideConfig creates a SideBySideConfig with default values and applies any provided options.
265+func NewSideBySideConfig(opts ...SideBySideOption) SideBySideConfig {
266+ // Set default values
267+ config := SideBySideConfig{
268+ TotalWidth: 160, // Default width for side-by-side view
269+ Style: NewStyleConfig(),
270+ }
271+
272+ // Apply all provided options
273+ for _, opt := range opts {
274+ opt(&config)
275+ }
276+
277+ return config
278+}
279+
280+// WithTotalWidth sets the total width for side-by-side view.
281+func WithTotalWidth(width int) SideBySideOption {
282+ return func(s *SideBySideConfig) {
283+ if width > 0 {
284+ s.TotalWidth = width
285+ }
286+ }
287+}
288+
289+// WithStyle sets the styling configuration.
290+func WithStyle(style StyleConfig) SideBySideOption {
291+ return func(s *SideBySideConfig) {
292+ s.Style = style
293+ }
294+}
295+
296+// WithStyleOptions applies the specified style options.
297+func WithStyleOptions(opts ...StyleOption) SideBySideOption {
298+ return func(s *SideBySideConfig) {
299+ s.Style = NewStyleConfig(opts...)
300+ }
301+}
302+
303+// -------------------------------------------------------------------------
304+// Diff Parsing and Generation
305+// -------------------------------------------------------------------------
306+
307+// ParseUnifiedDiff parses a unified diff format string into structured data.
308+func ParseUnifiedDiff(diff string) (DiffResult, error) {
309+ var result DiffResult
310+ var currentHunk *Hunk
311+
312+ hunkHeaderRe := regexp.MustCompile(`^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@`)
313+ lines := strings.Split(diff, "\n")
314+
315+ var oldLine, newLine int
316+ inFileHeader := true
317+
318+ for _, line := range lines {
319+ // Parse the file headers
320+ if inFileHeader {
321+ if strings.HasPrefix(line, "--- a/") {
322+ result.OldFile = strings.TrimPrefix(line, "--- a/")
323+ continue
324+ }
325+ if strings.HasPrefix(line, "+++ b/") {
326+ result.NewFile = strings.TrimPrefix(line, "+++ b/")
327+ inFileHeader = false
328+ continue
329+ }
330+ }
331+
332+ // Parse hunk headers
333+ if matches := hunkHeaderRe.FindStringSubmatch(line); matches != nil {
334+ if currentHunk != nil {
335+ result.Hunks = append(result.Hunks, *currentHunk)
336+ }
337+ currentHunk = &Hunk{
338+ Header: line,
339+ Lines: []DiffLine{},
340+ }
341+
342+ oldStart, _ := strconv.Atoi(matches[1])
343+ newStart, _ := strconv.Atoi(matches[3])
344+ oldLine = oldStart
345+ newLine = newStart
346+
347+ continue
348+ }
349+
350+ if currentHunk == nil {
351+ continue
352+ }
353+
354+ if len(line) > 0 {
355+ // Process the line based on its prefix
356+ switch line[0] {
357+ case '+':
358+ currentHunk.Lines = append(currentHunk.Lines, DiffLine{
359+ OldLineNo: 0,
360+ NewLineNo: newLine,
361+ Kind: LineAdded,
362+ Content: line[1:], // skip '+'
363+ })
364+ newLine++
365+ case '-':
366+ currentHunk.Lines = append(currentHunk.Lines, DiffLine{
367+ OldLineNo: oldLine,
368+ NewLineNo: 0,
369+ Kind: LineRemoved,
370+ Content: line[1:], // skip '-'
371+ })
372+ oldLine++
373+ default:
374+ currentHunk.Lines = append(currentHunk.Lines, DiffLine{
375+ OldLineNo: oldLine,
376+ NewLineNo: newLine,
377+ Kind: LineContext,
378+ Content: line,
379+ })
380+ oldLine++
381+ newLine++
382+ }
383+ } else {
384+ // Handle empty lines
385+ currentHunk.Lines = append(currentHunk.Lines, DiffLine{
386+ OldLineNo: oldLine,
387+ NewLineNo: newLine,
388+ Kind: LineContext,
389+ Content: "",
390+ })
391+ oldLine++
392+ newLine++
393+ }
394+ }
395+
396+ // Add the last hunk if there is one
397+ if currentHunk != nil {
398+ result.Hunks = append(result.Hunks, *currentHunk)
399+ }
400+
401+ return result, nil
402+}
403+
404+// HighlightIntralineChanges updates the content of lines in a hunk to show
405+// character-level differences within lines.
406+func HighlightIntralineChanges(h *Hunk, style StyleConfig) {
407+ var updated []DiffLine
408+ dmp := diffmatchpatch.New()
409+
410+ for i := 0; i < len(h.Lines); i++ {
411+ // Look for removed line followed by added line, which might have similar content
412+ if i+1 < len(h.Lines) &&
413+ h.Lines[i].Kind == LineRemoved &&
414+ h.Lines[i+1].Kind == LineAdded {
415+
416+ oldLine := h.Lines[i]
417+ newLine := h.Lines[i+1]
418+
419+ // Find character-level differences
420+ patches := dmp.DiffMain(oldLine.Content, newLine.Content, false)
421+ patches = dmp.DiffCleanupEfficiency(patches)
422+ patches = dmp.DiffCleanupSemantic(patches)
423+
424+ // Apply highlighting to the differences
425+ oldLine.Content = colorizeSegments(patches, true, style)
426+ newLine.Content = colorizeSegments(patches, false, style)
427+
428+ updated = append(updated, oldLine, newLine)
429+ i++ // Skip the next line as we've already processed it
430+ } else {
431+ updated = append(updated, h.Lines[i])
432+ }
433+ }
434+
435+ h.Lines = updated
436+}
437+
438+// colorizeSegments applies styles to the character-level diff segments.
439+func colorizeSegments(diffs []diffmatchpatch.Diff, isOld bool, style StyleConfig) string {
440+ var buf strings.Builder
441+
442+ removeBg := lipgloss.NewStyle().
443+ Background(style.RemovedHighlightBg).
444+ Foreground(style.RemovedHighlightFg)
445+
446+ addBg := lipgloss.NewStyle().
447+ Background(style.AddedHighlightBg).
448+ Foreground(style.AddedHighlightFg)
449+
450+ removedLineStyle := lipgloss.NewStyle().Background(style.RemovedLineBg)
451+ addedLineStyle := lipgloss.NewStyle().Background(style.AddedLineBg)
452+
453+ afterBg := false
454+
455+ for _, d := range diffs {
456+ switch d.Type {
457+ case diffmatchpatch.DiffEqual:
458+ // Handle text that's the same in both versions
459+ if afterBg {
460+ if isOld {
461+ buf.WriteString(removedLineStyle.Render(d.Text))
462+ } else {
463+ buf.WriteString(addedLineStyle.Render(d.Text))
464+ }
465+ } else {
466+ buf.WriteString(d.Text)
467+ }
468+ case diffmatchpatch.DiffDelete:
469+ // Handle deleted text (only show in old version)
470+ if isOld {
471+ buf.WriteString(removeBg.Render(d.Text))
472+ afterBg = true
473+ }
474+ case diffmatchpatch.DiffInsert:
475+ // Handle inserted text (only show in new version)
476+ if !isOld {
477+ buf.WriteString(addBg.Render(d.Text))
478+ afterBg = true
479+ }
480+ }
481+ }
482+
483+ return buf.String()
484+}
485+
486+// pairLines converts a flat list of diff lines to pairs for side-by-side display.
487+func pairLines(lines []DiffLine) []linePair {
488+ var pairs []linePair
489+ i := 0
490+
491+ for i < len(lines) {
492+ switch lines[i].Kind {
493+ case LineRemoved:
494+ // Check if the next line is an addition, if so pair them
495+ if i+1 < len(lines) && lines[i+1].Kind == LineAdded {
496+ pairs = append(pairs, linePair{left: &lines[i], right: &lines[i+1]})
497+ i += 2
498+ } else {
499+ pairs = append(pairs, linePair{left: &lines[i], right: nil})
500+ i++
501+ }
502+ case LineAdded:
503+ pairs = append(pairs, linePair{left: nil, right: &lines[i]})
504+ i++
505+ case LineContext:
506+ pairs = append(pairs, linePair{left: &lines[i], right: &lines[i]})
507+ i++
508+ }
509+ }
510+
511+ return pairs
512+}
513+
514+// -------------------------------------------------------------------------
515+// Syntax Highlighting
516+// -------------------------------------------------------------------------
517+
518+// SyntaxHighlight applies syntax highlighting to a string based on the file extension.
519+func SyntaxHighlight(w io.Writer, source, fileName, formatter string, bg lipgloss.TerminalColor) error {
520+ // Determine the language lexer to use
521+ l := lexers.Match(fileName)
522+ if l == nil {
523+ l = lexers.Analyse(source)
524+ }
525+ if l == nil {
526+ l = lexers.Fallback
527+ }
528+ l = chroma.Coalesce(l)
529+
530+ // Get the formatter
531+ f := formatters.Get(formatter)
532+ if f == nil {
533+ f = formatters.Fallback
534+ }
535+
536+ // Get the style
537+ s := styles.Get("dracula")
538+ if s == nil {
539+ s = styles.Fallback
540+ }
541+
542+ // Modify the style to use the provided background
543+ s, err := s.Builder().Transform(
544+ func(t chroma.StyleEntry) chroma.StyleEntry {
545+ r, g, b, _ := bg.RGBA()
546+ ru8 := uint8(r >> 8)
547+ gu8 := uint8(g >> 8)
548+ bu8 := uint8(b >> 8)
549+ t.Background = chroma.NewColour(ru8, gu8, bu8)
550+ return t
551+ },
552+ ).Build()
553+ if err != nil {
554+ s = styles.Fallback
555+ }
556+
557+ // Tokenize and format
558+ it, err := l.Tokenise(nil, source)
559+ if err != nil {
560+ return err
561+ }
562+
563+ return f.Format(w, s, it)
564+}
565+
566+// highlightLine applies syntax highlighting to a single line.
567+func highlightLine(fileName string, line string, bg lipgloss.TerminalColor) string {
568+ var buf bytes.Buffer
569+ err := SyntaxHighlight(&buf, line, fileName, "terminal16m", bg)
570+ if err != nil {
571+ return line
572+ }
573+ return buf.String()
574+}
575+
576+// createStyles generates the lipgloss styles needed for rendering diffs.
577+func createStyles(config StyleConfig) (removedLineStyle, addedLineStyle, contextLineStyle, lineNumberStyle lipgloss.Style) {
578+ removedLineStyle = lipgloss.NewStyle().Background(config.RemovedLineBg)
579+ addedLineStyle = lipgloss.NewStyle().Background(config.AddedLineBg)
580+ contextLineStyle = lipgloss.NewStyle().Background(config.ContextLineBg)
581+ lineNumberStyle = lipgloss.NewStyle().Foreground(config.LineNumberFg)
582+
583+ return
584+}
585+
586+// renderLeftColumn formats the left side of a side-by-side diff.
587+func renderLeftColumn(fileName string, dl *DiffLine, colWidth int, styles StyleConfig) string {
588+ if dl == nil {
589+ contextLineStyle := lipgloss.NewStyle().Background(styles.ContextLineBg)
590+ return contextLineStyle.Width(colWidth).Render("")
591+ }
592+
593+ removedLineStyle, _, contextLineStyle, lineNumberStyle := createStyles(styles)
594+
595+ var marker string
596+ var bgStyle lipgloss.Style
597+
598+ switch dl.Kind {
599+ case LineRemoved:
600+ marker = removedLineStyle.Foreground(styles.RemovedFg).Render("-")
601+ bgStyle = removedLineStyle
602+ lineNumberStyle = lineNumberStyle.Foreground(styles.RemovedFg).Background(styles.RemovedLineNumberBg)
603+ case LineAdded:
604+ marker = "?"
605+ bgStyle = contextLineStyle
606+ case LineContext:
607+ marker = contextLineStyle.Render(" ")
608+ bgStyle = contextLineStyle
609+ }
610+
611+ lineNum := ""
612+ if dl.OldLineNo > 0 {
613+ lineNum = fmt.Sprintf("%6d", dl.OldLineNo)
614+ }
615+
616+ prefix := lineNumberStyle.Render(lineNum + " " + marker)
617+ content := highlightLine(fileName, dl.Content, bgStyle.GetBackground())
618+
619+ if dl.Kind == LineRemoved {
620+ content = bgStyle.Render(" ") + content
621+ }
622+
623+ lineText := prefix + content
624+ return bgStyle.MaxHeight(1).Width(colWidth).Render(ansi.Truncate(lineText, colWidth, "..."))
625+}
626+
627+// renderRightColumn formats the right side of a side-by-side diff.
628+func renderRightColumn(fileName string, dl *DiffLine, colWidth int, styles StyleConfig) string {
629+ if dl == nil {
630+ contextLineStyle := lipgloss.NewStyle().Background(styles.ContextLineBg)
631+ return contextLineStyle.Width(colWidth).Render("")
632+ }
633+
634+ _, addedLineStyle, contextLineStyle, lineNumberStyle := createStyles(styles)
635+
636+ var marker string
637+ var bgStyle lipgloss.Style
638+
639+ switch dl.Kind {
640+ case LineAdded:
641+ marker = addedLineStyle.Foreground(styles.AddedFg).Render("+")
642+ bgStyle = addedLineStyle
643+ lineNumberStyle = lineNumberStyle.Foreground(styles.AddedFg).Background(styles.AddedLineNamerBg)
644+ case LineRemoved:
645+ marker = "?"
646+ bgStyle = contextLineStyle
647+ case LineContext:
648+ marker = contextLineStyle.Render(" ")
649+ bgStyle = contextLineStyle
650+ }
651+
652+ lineNum := ""
653+ if dl.NewLineNo > 0 {
654+ lineNum = fmt.Sprintf("%6d", dl.NewLineNo)
655+ }
656+
657+ prefix := lineNumberStyle.Render(lineNum + " " + marker)
658+ content := highlightLine(fileName, dl.Content, bgStyle.GetBackground())
659+
660+ if dl.Kind == LineAdded {
661+ content = bgStyle.Render(" ") + content
662+ }
663+
664+ lineText := prefix + content
665+ return bgStyle.MaxHeight(1).Width(colWidth).Render(ansi.Truncate(lineText, colWidth, "..."))
666+}
667+
668+// -------------------------------------------------------------------------
669+// Public API Methods
670+// -------------------------------------------------------------------------
671+
672+// RenderSideBySideHunk formats a hunk for side-by-side display.
673+func RenderSideBySideHunk(fileName string, h Hunk, opts ...SideBySideOption) string {
674+ // Apply options to create the configuration
675+ config := NewSideBySideConfig(opts...)
676+
677+ // Make a copy of the hunk so we don't modify the original
678+ hunkCopy := Hunk{Lines: make([]DiffLine, len(h.Lines))}
679+ copy(hunkCopy.Lines, h.Lines)
680+
681+ // Highlight changes within lines
682+ HighlightIntralineChanges(&hunkCopy, config.Style)
683+
684+ // Pair lines for side-by-side display
685+ pairs := pairLines(hunkCopy.Lines)
686+
687+ // Calculate column width
688+ colWidth := config.TotalWidth / 2
689+
690+ var sb strings.Builder
691+ for _, p := range pairs {
692+ leftStr := renderLeftColumn(fileName, p.left, colWidth, config.Style)
693+ rightStr := renderRightColumn(fileName, p.right, colWidth, config.Style)
694+ sb.WriteString(leftStr + rightStr + "\n")
695+ }
696+
697+ return sb.String()
698+}
699+
700+// FormatDiff creates a side-by-side formatted view of a diff.
701+func FormatDiff(diffText string, opts ...SideBySideOption) (string, error) {
702+ diffResult, err := ParseUnifiedDiff(diffText)
703+ if err != nil {
704+ return "", err
705+ }
706+
707+ var sb strings.Builder
708+
709+ config := NewSideBySideConfig(opts...)
710+ for i, h := range diffResult.Hunks {
711+ if i > 0 {
712+ sb.WriteString(lipgloss.NewStyle().Background(config.Style.HunkLineBg).Foreground(config.Style.HunkLineFg).Width(config.TotalWidth).Render(h.Header) + "\n")
713+ }
714+ sb.WriteString(RenderSideBySideHunk(diffResult.OldFile, h, opts...))
715+ }
716+
717+ return sb.String(), nil
718+}
719+
720+// GenerateDiff creates a unified diff from two file contents.
721+func GenerateDiff(beforeContent, afterContent, beforeFilename, afterFilename string, opts ...ParseOption) (string, int, int) {
722+ config := NewParseConfig(opts...)
723+
724+ var output strings.Builder
725+
726+ // Ensure we handle newlines correctly
727+ beforeHasNewline := len(beforeContent) > 0 && beforeContent[len(beforeContent)-1] == '\n'
728+ afterHasNewline := len(afterContent) > 0 && afterContent[len(afterContent)-1] == '\n'
729+
730+ // Split into lines
731+ beforeLines := strings.Split(beforeContent, "\n")
732+ afterLines := strings.Split(afterContent, "\n")
733+
734+ // Remove empty trailing element from the split if the content ended with a newline
735+ if beforeHasNewline && len(beforeLines) > 0 {
736+ beforeLines = beforeLines[:len(beforeLines)-1]
737+ }
738+ if afterHasNewline && len(afterLines) > 0 {
739+ afterLines = afterLines[:len(afterLines)-1]
740+ }
741+
742+ dmp := diffmatchpatch.New()
743+ dmp.DiffTimeout = 5 * time.Second
744+
745+ // Convert lines to characters for efficient diffing
746+ lineArray1, lineArray2, lineArrays := dmp.DiffLinesToChars(beforeContent, afterContent)
747+ diffs := dmp.DiffMain(lineArray1, lineArray2, false)
748+ diffs = dmp.DiffCharsToLines(diffs, lineArrays)
749+
750+ // Default filenames if not provided
751+ if beforeFilename == "" {
752+ beforeFilename = "a"
753+ }
754+ if afterFilename == "" {
755+ afterFilename = "b"
756+ }
757+
758+ // Write diff header
759+ output.WriteString(fmt.Sprintf("diff --git a/%s b/%s\n", beforeFilename, afterFilename))
760+ output.WriteString(fmt.Sprintf("--- a/%s\n", beforeFilename))
761+ output.WriteString(fmt.Sprintf("+++ b/%s\n", afterFilename))
762+
763+ line1 := 0 // Line numbers start from 0 internally
764+ line2 := 0
765+ additions := 0
766+ deletions := 0
767+
768+ var hunks []string
769+ var currentHunk strings.Builder
770+ var hunkStartLine1, hunkStartLine2 int
771+ var hunkLines1, hunkLines2 int
772+ inHunk := false
773+
774+ contextSize := config.ContextSize
775+
776+ // startHunk begins recording a new hunk
777+ startHunk := func(startLine1, startLine2 int) {
778+ inHunk = true
779+ hunkStartLine1 = startLine1
780+ hunkStartLine2 = startLine2
781+ hunkLines1 = 0
782+ hunkLines2 = 0
783+ currentHunk.Reset()
784+ }
785+
786+ // writeHunk adds the current hunk to the hunks slice
787+ writeHunk := func() {
788+ if inHunk {
789+ hunkHeader := fmt.Sprintf("@@ -%d,%d +%d,%d @@\n",
790+ hunkStartLine1+1, hunkLines1,
791+ hunkStartLine2+1, hunkLines2)
792+ hunks = append(hunks, hunkHeader+currentHunk.String())
793+ inHunk = false
794+ }
795+ }
796+
797+ // Process diffs to create hunks
798+ pendingContext := make([]string, 0, contextSize*2)
799+ var contextLines1, contextLines2 int
800+
801+ // Helper function to add context lines to the hunk
802+ addContextToHunk := func(lines []string, count int) {
803+ for i := 0; i < count; i++ {
804+ if i < len(lines) {
805+ currentHunk.WriteString(" " + lines[i] + "\n")
806+ hunkLines1++
807+ hunkLines2++
808+ }
809+ }
810+ }
811+
812+ // Process diffs
813+ for _, diff := range diffs {
814+ lines := strings.Split(diff.Text, "\n")
815+
816+ // Remove empty trailing line that comes from splitting a string that ends with \n
817+ if len(lines) > 0 && lines[len(lines)-1] == "" && diff.Text[len(diff.Text)-1] == '\n' {
818+ lines = lines[:len(lines)-1]
819+ }
820+
821+ switch diff.Type {
822+ case diffmatchpatch.DiffEqual:
823+ // If we have enough equal lines to serve as context, add them to pending
824+ pendingContext = append(pendingContext, lines...)
825+
826+ // If pending context grows too large, trim it
827+ if len(pendingContext) > contextSize*2 {
828+ pendingContext = pendingContext[len(pendingContext)-contextSize*2:]
829+ }
830+
831+ // If we're in a hunk, add the necessary context
832+ if inHunk {
833+ // Only add the first contextSize lines as trailing context
834+ numContextLines := min(contextSize, len(lines))
835+ addContextToHunk(lines[:numContextLines], numContextLines)
836+
837+ // If we've added enough trailing context, close the hunk
838+ if numContextLines >= contextSize {
839+ writeHunk()
840+ }
841+ }
842+
843+ line1 += len(lines)
844+ line2 += len(lines)
845+ contextLines1 += len(lines)
846+ contextLines2 += len(lines)
847+
848+ case diffmatchpatch.DiffDelete, diffmatchpatch.DiffInsert:
849+ // Start a new hunk if needed
850+ if !inHunk {
851+ // Determine how many context lines we can add before
852+ contextBefore := min(contextSize, len(pendingContext))
853+ ctxStartIdx := len(pendingContext) - contextBefore
854+
855+ // Calculate the correct start lines
856+ startLine1 := line1 - contextLines1 + ctxStartIdx
857+ startLine2 := line2 - contextLines2 + ctxStartIdx
858+
859+ startHunk(startLine1, startLine2)
860+
861+ // Add the context lines before
862+ addContextToHunk(pendingContext[ctxStartIdx:], contextBefore)
863+ }
864+
865+ // Reset context tracking when we see a diff
866+ pendingContext = pendingContext[:0]
867+ contextLines1 = 0
868+ contextLines2 = 0
869+
870+ // Add the changes
871+ if diff.Type == diffmatchpatch.DiffDelete {
872+ for _, line := range lines {
873+ currentHunk.WriteString("-" + line + "\n")
874+ hunkLines1++
875+ deletions++
876+ }
877+ line1 += len(lines)
878+ } else { // DiffInsert
879+ for _, line := range lines {
880+ currentHunk.WriteString("+" + line + "\n")
881+ hunkLines2++
882+ additions++
883+ }
884+ line2 += len(lines)
885+ }
886+ }
887+ }
888+
889+ // Write the final hunk if there's one pending
890+ if inHunk {
891+ writeHunk()
892+ }
893+
894+ // Merge hunks that are close to each other (within 2*contextSize lines)
895+ var mergedHunks []string
896+ if len(hunks) > 0 {
897+ mergedHunks = append(mergedHunks, hunks[0])
898+
899+ for i := 1; i < len(hunks); i++ {
900+ prevHunk := mergedHunks[len(mergedHunks)-1]
901+ currHunk := hunks[i]
902+
903+ // Extract line numbers to check proximity
904+ var prevStart, prevLen, currStart, currLen int
905+ fmt.Sscanf(prevHunk, "@@ -%d,%d", &prevStart, &prevLen)
906+ fmt.Sscanf(currHunk, "@@ -%d,%d", &currStart, &currLen)
907+
908+ prevEnd := prevStart + prevLen - 1
909+
910+ // If hunks are close, merge them
911+ if currStart-prevEnd <= contextSize*2 {
912+ // Create a merged hunk - this is a simplification, real git has more complex merging logic
913+ merged := mergeHunks(prevHunk, currHunk)
914+ mergedHunks[len(mergedHunks)-1] = merged
915+ } else {
916+ mergedHunks = append(mergedHunks, currHunk)
917+ }
918+ }
919+ }
920+
921+ // Write all hunks to output
922+ for _, hunk := range mergedHunks {
923+ output.WriteString(hunk)
924+ }
925+
926+ // Handle "No newline at end of file" notifications
927+ if !beforeHasNewline && len(beforeLines) > 0 {
928+ // Find the last deletion in the diff and add the notification after it
929+ lastPos := strings.LastIndex(output.String(), "\n-")
930+ if lastPos != -1 {
931+ // Insert the notification after the line
932+ str := output.String()
933+ output.Reset()
934+ output.WriteString(str[:lastPos+1])
935+ output.WriteString("\\ No newline at end of file\n")
936+ output.WriteString(str[lastPos+1:])
937+ }
938+ }
939+
940+ if !afterHasNewline && len(afterLines) > 0 {
941+ // Find the last insertion in the diff and add the notification after it
942+ lastPos := strings.LastIndex(output.String(), "\n+")
943+ if lastPos != -1 {
944+ // Insert the notification after the line
945+ str := output.String()
946+ output.Reset()
947+ output.WriteString(str[:lastPos+1])
948+ output.WriteString("\\ No newline at end of file\n")
949+ output.WriteString(str[lastPos+1:])
950+ }
951+ }
952+
953+ // Return the diff without the summary line
954+ return output.String(), additions, deletions
955+}
956+
957+// Helper function to merge two hunks
958+func mergeHunks(hunk1, hunk2 string) string {
959+ // This is a simplified implementation
960+ // A full implementation would need to properly recalculate the hunk header
961+ // and remove redundant context lines
962+
963+ // Extract header info from both hunks
964+ var start1, len1, start2, len2 int
965+ var startB1, lenB1, startB2, lenB2 int
966+
967+ fmt.Sscanf(hunk1, "@@ -%d,%d +%d,%d @@", &start1, &len1, &startB1, &lenB1)
968+ fmt.Sscanf(hunk2, "@@ -%d,%d +%d,%d @@", &start2, &len2, &startB2, &lenB2)
969+
970+ // Split the hunks to get content
971+ parts1 := strings.SplitN(hunk1, "\n", 2)
972+ parts2 := strings.SplitN(hunk2, "\n", 2)
973+
974+ content1 := ""
975+ content2 := ""
976+
977+ if len(parts1) > 1 {
978+ content1 = parts1[1]
979+ }
980+ if len(parts2) > 1 {
981+ content2 = parts2[1]
982+ }
983+
984+ // Calculate the new header
985+ newEnd := max(start1+len1-1, start2+len2-1)
986+ newEndB := max(startB1+lenB1-1, startB2+lenB2-1)
987+
988+ newLen := newEnd - start1 + 1
989+ newLenB := newEndB - startB1 + 1
990+
991+ newHeader := fmt.Sprintf("@@ -%d,%d +%d,%d @@", start1, newLen, startB1, newLenB)
992+
993+ // Combine the content, potentially with some overlap handling
994+ return newHeader + "\n" + content1 + content2
995+}
internal/git/diff.godeleted−264
@@ -1,264 +0,0 @@
1−package git
2−
3−import (
4− "bytes"
5− "fmt"
6− "os"
7− "os/exec"
8− "path/filepath"
9− "strings"
10− "time"
11−
12− "github.com/go-git/go-git/v5"
13− "github.com/go-git/go-git/v5/plumbing/object"
14−)
15−
16−type DiffStats struct {
17− Additions int
18− Removals int
19−}
20−
21−func GenerateGitDiff(filePath string, contentBefore string, contentAfter string) (string, error) {
22− tempDir, err := os.MkdirTemp("", "git-diff-temp")
23− if err != nil {
24− return "", fmt.Errorf("failed to create temp dir: %w", err)
25− }
26− defer os.RemoveAll(tempDir)
27−
28− repo, err := git.PlainInit(tempDir, false)
29− if err != nil {
30− return "", fmt.Errorf("failed to initialize git repo: %w", err)
31− }
32−
33− wt, err := repo.Worktree()
34− if err != nil {
35− return "", fmt.Errorf("failed to get worktree: %w", err)
36− }
37−
38− fullPath := filepath.Join(tempDir, filePath)
39− if err = os.MkdirAll(filepath.Dir(fullPath), 0o755); err != nil {
40− return "", fmt.Errorf("failed to create directories: %w", err)
41− }
42− if err = os.WriteFile(fullPath, []byte(contentBefore), 0o644); err != nil {
43− return "", fmt.Errorf("failed to write 'before' content: %w", err)
44− }
45−
46− _, err = wt.Add(filePath)
47− if err != nil {
48− return "", fmt.Errorf("failed to add file to git: %w", err)
49− }
50−
51− beforeCommit, err := wt.Commit("Before", &git.CommitOptions{
52− Author: &object.Signature{
53− Name: "OpenCode",
54− Email: "coder@opencode.ai",
55− When: time.Now(),
56− },
57− })
58− if err != nil {
59− return "", fmt.Errorf("failed to commit 'before' version: %w", err)
60− }
61−
62− if err = os.WriteFile(fullPath, []byte(contentAfter), 0o644); err != nil {
63− return "", fmt.Errorf("failed to write 'after' content: %w", err)
64− }
65−
66− _, err = wt.Add(filePath)
67− if err != nil {
68− return "", fmt.Errorf("failed to add updated file to git: %w", err)
69− }
70−
71− afterCommit, err := wt.Commit("After", &git.CommitOptions{
72− Author: &object.Signature{
73− Name: "OpenCode",
74− Email: "coder@opencode.ai",
75− When: time.Now(),
76− },
77− })
78− if err != nil {
79− return "", fmt.Errorf("failed to commit 'after' version: %w", err)
80− }
81−
82− beforeCommitObj, err := repo.CommitObject(beforeCommit)
83− if err != nil {
84− return "", fmt.Errorf("failed to get 'before' commit: %w", err)
85− }
86−
87− afterCommitObj, err := repo.CommitObject(afterCommit)
88− if err != nil {
89− return "", fmt.Errorf("failed to get 'after' commit: %w", err)
90− }
91−
92− patch, err := beforeCommitObj.Patch(afterCommitObj)
93− if err != nil {
94− return "", fmt.Errorf("failed to generate patch: %w", err)
95− }
96−
97− return patch.String(), nil
98−}
99−
100−func GenerateGitDiffWithStats(filePath string, contentBefore string, contentAfter string) (string, DiffStats, error) {
101− tempDir, err := os.MkdirTemp("", "git-diff-temp")
102− if err != nil {
103− return "", DiffStats{}, fmt.Errorf("failed to create temp dir: %w", err)
104− }
105− defer os.RemoveAll(tempDir)
106−
107− repo, err := git.PlainInit(tempDir, false)
108− if err != nil {
109− return "", DiffStats{}, fmt.Errorf("failed to initialize git repo: %w", err)
110− }
111−
112− wt, err := repo.Worktree()
113− if err != nil {
114− return "", DiffStats{}, fmt.Errorf("failed to get worktree: %w", err)
115− }
116−
117− fullPath := filepath.Join(tempDir, filePath)
118− if err = os.MkdirAll(filepath.Dir(fullPath), 0o755); err != nil {
119− return "", DiffStats{}, fmt.Errorf("failed to create directories: %w", err)
120− }
121− if err = os.WriteFile(fullPath, []byte(contentBefore), 0o644); err != nil {
122− return "", DiffStats{}, fmt.Errorf("failed to write 'before' content: %w", err)
123− }
124−
125− _, err = wt.Add(filePath)
126− if err != nil {
127− return "", DiffStats{}, fmt.Errorf("failed to add file to git: %w", err)
128− }
129−
130− beforeCommit, err := wt.Commit("Before", &git.CommitOptions{
131− Author: &object.Signature{
132− Name: "OpenCode",
133− Email: "coder@opencode.ai",
134− When: time.Now(),
135− },
136− })
137− if err != nil {
138− return "", DiffStats{}, fmt.Errorf("failed to commit 'before' version: %w", err)
139− }
140−
141− if err = os.WriteFile(fullPath, []byte(contentAfter), 0o644); err != nil {
142− return "", DiffStats{}, fmt.Errorf("failed to write 'after' content: %w", err)
143− }
144−
145− _, err = wt.Add(filePath)
146− if err != nil {
147− return "", DiffStats{}, fmt.Errorf("failed to add updated file to git: %w", err)
148− }
149−
150− afterCommit, err := wt.Commit("After", &git.CommitOptions{
151− Author: &object.Signature{
152− Name: "OpenCode",
153− Email: "coder@opencode.ai",
154− When: time.Now(),
155− },
156− })
157− if err != nil {
158− return "", DiffStats{}, fmt.Errorf("failed to commit 'after' version: %w", err)
159− }
160−
161− beforeCommitObj, err := repo.CommitObject(beforeCommit)
162− if err != nil {
163− return "", DiffStats{}, fmt.Errorf("failed to get 'before' commit: %w", err)
164− }
165−
166− afterCommitObj, err := repo.CommitObject(afterCommit)
167− if err != nil {
168− return "", DiffStats{}, fmt.Errorf("failed to get 'after' commit: %w", err)
169− }
170−
171− patch, err := beforeCommitObj.Patch(afterCommitObj)
172− if err != nil {
173− return "", DiffStats{}, fmt.Errorf("failed to generate patch: %w", err)
174− }
175−
176− stats := DiffStats{}
177− for _, fileStat := range patch.Stats() {
178− stats.Additions += fileStat.Addition
179− stats.Removals += fileStat.Deletion
180− }
181−
182− return patch.String(), stats, nil
183−}
184−
185−func FormatDiff(diffText string, width int) (string, error) {
186− if isSplitDiffsAvailable() {
187− return formatWithSplitDiffs(diffText, width)
188− }
189−
190− return formatSimple(diffText), nil
191−}
192−
193−func isSplitDiffsAvailable() bool {
194− _, err := exec.LookPath("node")
195− return err == nil
196−}
197−
198−func formatWithSplitDiffs(diffText string, width int) (string, error) {
199− args := []string{
200− "--color",
201− }
202−
203− var diffCmd *exec.Cmd
204−
205− if _, err := exec.LookPath("git-split-diffs-opencode"); err == nil {
206− fullArgs := append([]string{"git-split-diffs-opencode"}, args...)
207− diffCmd = exec.Command(fullArgs[0], fullArgs[1:]...)
208− } else {
209− npxArgs := append([]string{"git-split-diffs-opencode"}, args...)
210− diffCmd = exec.Command("npx", npxArgs...)
211− }
212−
213− diffCmd.Env = append(os.Environ(), fmt.Sprintf("DIFF_COLUMNS=%d", width))
214−
215− diffCmd.Stdin = strings.NewReader(diffText)
216−
217− var out bytes.Buffer
218− diffCmd.Stdout = &out
219−
220− var stderr bytes.Buffer
221− diffCmd.Stderr = &stderr
222−
223− if err := diffCmd.Run(); err != nil {
224− return "", fmt.Errorf("git-split-diffs-opencode error: %w, stderr: %s", err, stderr.String())
225− }
226−
227− return out.String(), nil
228−}
229−
230−func formatSimple(diffText string) string {
231− lines := strings.Split(diffText, "\n")
232− var result strings.Builder
233−
234− for _, line := range lines {
235− if len(line) == 0 {
236− result.WriteString("\n")
237− continue
238− }
239−
240− switch line[0] {
241− case '+':
242− result.WriteString("\033[32m" + line + "\033[0m\n")
243− case '-':
244− result.WriteString("\033[31m" + line + "\033[0m\n")
245− case '@':
246− result.WriteString("\033[36m" + line + "\033[0m\n")
247− case 'd':
248− if strings.HasPrefix(line, "diff --git") {
249− result.WriteString("\033[1m" + line + "\033[0m\n")
250− } else {
251− result.WriteString(line + "\n")
252− }
253− default:
254− result.WriteString(line + "\n")
255− }
256− }
257−
258− if !strings.HasSuffix(diffText, "\n") {
259− output := result.String()
260− return output[:len(output)-1]
261− }
262−
263− return result.String()
264−}
internal/llm/tools/edit.go+16−23
@@ -10,7 +10,7 @@ import (
1010 "time"
1111
1212 "github.com/kujtimiihoxha/termai/internal/config"
13− "github.com/kujtimiihoxha/termai/internal/git"
13+ "github.com/kujtimiihoxha/termai/internal/diff"
1414 "github.com/kujtimiihoxha/termai/internal/lsp"
1515 "github.com/kujtimiihoxha/termai/internal/permission"
1616)
@@ -182,14 +182,12 @@ func (e *editTool) createNewFile(ctx context.Context, filePath, content string)
182182 return ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a new file")
183183 }
184184
185− diff, stats, err := git.GenerateGitDiffWithStats(
186− removeWorkingDirectoryPrefix(filePath),
185+ diff, additions, removals := diff.GenerateDiff(
187186 "",
188187 content,
188+ filePath,
189+ filePath,
189190 )
190− if err != nil {
191− return ToolResponse{}, fmt.Errorf("failed to get file diff: %w", err)
192− }
193191 p := e.permissions.Request(
194192 permission.CreatePermissionRequest{
195193 Path: filepath.Dir(filePath),
@@ -218,8 +216,8 @@ func (e *editTool) createNewFile(ctx context.Context, filePath, content string)
218216 NewTextResponse("File created: "+filePath),
219217 EditResponseMetadata{
220218 Diff: diff,
221− Additions: stats.Additions,
222− Removals: stats.Removals,
219+ Additions: additions,
220+ Removals: removals,
223221 },
224222 ), nil
225223}
@@ -275,14 +273,12 @@ func (e *editTool) deleteContent(ctx context.Context, filePath, oldString string
275273 return ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a new file")
276274 }
277275
278− diff, stats, err := git.GenerateGitDiffWithStats(
279− removeWorkingDirectoryPrefix(filePath),
276+ diff, additions, removals := diff.GenerateDiff(
280277 oldContent,
281278 newContent,
279+ filePath,
280+ filePath,
282281 )
283− if err != nil {
284− return ToolResponse{}, fmt.Errorf("failed to get file diff: %w", err)
285− }
286282
287283 p := e.permissions.Request(
288284 permission.CreatePermissionRequest{
@@ -311,8 +307,8 @@ func (e *editTool) deleteContent(ctx context.Context, filePath, oldString string
311307 NewTextResponse("Content deleted from file: "+filePath),
312308 EditResponseMetadata{
313309 Diff: diff,
314− Additions: stats.Additions,
315− Removals: stats.Removals,
310+ Additions: additions,
311+ Removals: removals,
316312 },
317313 ), nil
318314}
@@ -367,15 +363,12 @@ func (e *editTool) replaceContent(ctx context.Context, filePath, oldString, newS
367363 if sessionID == "" || messageID == "" {
368364 return ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a new file")
369365 }
370− diff, stats, err := git.GenerateGitDiffWithStats(
371− removeWorkingDirectoryPrefix(filePath),
366+ diff, additions, removals := diff.GenerateDiff(
372367 oldContent,
373368 newContent,
369+ filePath,
370+ filePath,
374371 )
375− if err != nil {
376− return ToolResponse{}, fmt.Errorf("failed to get file diff: %w", err)
377− }
378−
379372 p := e.permissions.Request(
380373 permission.CreatePermissionRequest{
381374 Path: filepath.Dir(filePath),
@@ -405,7 +398,7 @@ func (e *editTool) replaceContent(ctx context.Context, filePath, oldString, newS
405398 NewTextResponse("Content replaced in file: "+filePath),
406399 EditResponseMetadata{
407400 Diff: diff,
408− Additions: stats.Additions,
409− Removals: stats.Removals,
401+ Additions: additions,
402+ Removals: removals,
410403 }), nil
411404}
internal/llm/tools/write.go+7−8
@@ -9,7 +9,7 @@ import (
99 "time"
1010
1111 "github.com/kujtimiihoxha/termai/internal/config"
12− "github.com/kujtimiihoxha/termai/internal/git"
12+ "github.com/kujtimiihoxha/termai/internal/diff"
1313 "github.com/kujtimiihoxha/termai/internal/lsp"
1414 "github.com/kujtimiihoxha/termai/internal/permission"
1515)
@@ -149,14 +149,13 @@ func (w *writeTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error
149149 if sessionID == "" || messageID == "" {
150150 return ToolResponse{}, fmt.Errorf("session_id and message_id are required")
151151 }
152− diff, stats, err := git.GenerateGitDiffWithStats(
153− removeWorkingDirectoryPrefix(filePath),
152+
153+ diff, additions, removals := diff.GenerateDiff(
154154 oldContent,
155155 params.Content,
156+ filePath,
157+ filePath,
156158 )
157− if err != nil {
158− return ToolResponse{}, fmt.Errorf("error generating diff: %w", err)
159− }
160159 p := w.permissions.Request(
161160 permission.CreatePermissionRequest{
162161 Path: filePath,
@@ -188,8 +187,8 @@ func (w *writeTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error
188187 return WithResponseMetadata(NewTextResponse(result),
189188 WriteResponseMetadata{
190189 Diff: diff,
191− Additions: stats.Additions,
192− Removals: stats.Removals,
190+ Additions: additions,
191+ Removals: removals,
193192 },
194193 ), nil
195194}
internal/tui/components/dialog/permission.go+3−3
@@ -9,7 +9,7 @@ import (
99 tea "github.com/charmbracelet/bubbletea"
1010 "github.com/charmbracelet/glamour"
1111 "github.com/charmbracelet/lipgloss"
12− "github.com/kujtimiihoxha/termai/internal/git"
12+ "github.com/kujtimiihoxha/termai/internal/diff"
1313 "github.com/kujtimiihoxha/termai/internal/llm/tools"
1414 "github.com/kujtimiihoxha/termai/internal/permission"
1515 "github.com/kujtimiihoxha/termai/internal/tui/components/core"
@@ -242,7 +242,7 @@ func (p *permissionDialogCmp) render() string {
242242 // Calculate content height dynamically based on window size
243243 maxContentHeight := p.height - lipgloss.Height(headerContent) - lipgloss.Height(form) - 2 - 2 - 1
244244 p.contentViewPort.Height = maxContentHeight
245− diff, err := git.FormatDiff(pr.Diff, p.contentViewPort.Width)
245+ diff, err := diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))
246246 if err != nil {
247247 diff = fmt.Sprintf("Error formatting diff: %v", err)
248248 }
@@ -291,7 +291,7 @@ func (p *permissionDialogCmp) render() string {
291291 // Calculate content height dynamically based on window size
292292 maxContentHeight := p.height - lipgloss.Height(headerContent) - lipgloss.Height(form) - 2 - 2 - 1
293293 p.contentViewPort.Height = maxContentHeight
294− diff, err := git.FormatDiff(pr.Diff, p.contentViewPort.Width)
294+ diff, err := diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))
295295 if err != nil {
296296 diff = fmt.Sprintf("Error formatting diff: %v", err)
297297 }