https://github.com/knsh14/astdiff
https://github.com/knsh14/astdiff
Last synced: 11 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/knsh14/astdiff
- Owner: knsh14
- Created: 2025-07-04T08:34:46.000Z (11 months ago)
- Default Branch: main
- Last Pushed: 2025-07-04T08:35:01.000Z (11 months ago)
- Last Synced: 2025-07-27T21:18:11.681Z (11 months ago)
- Language: Go
- Size: 8.79 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# astdiff
A Go library and CLI tool for comparing Go source files based on their Abstract Syntax Trees (AST).
## Features
- Compare Go source files at the AST level
- Detect additions, deletions, and modifications
- Use as a library or command-line tool
- Support for text and JSON output formats
## Installation
### As a CLI tool
```bash
go install github.com/knsh14/astdiff/cmd/astdiff@latest
```
### As a library
```bash
go get github.com/knsh14/astdiff
```
## Usage
### CLI
```bash
# Compare two Go files (like standard diff command)
astdiff file1.go file2.go
# Show more context lines
astdiff -u 5 old.go new.go
# Show help
astdiff -h
```
### Library
```go
package main
import (
"fmt"
"log"
"github.com/knsh14/astdiff"
)
func main() {
// Compare files
diff, err := astdiff.DiffFiles("old.go", "new.go")
if err != nil {
log.Fatal(err)
}
// Print human-readable output
fmt.Println(diff.String())
// Or get JSON output
json, err := diff.JSON()
if err != nil {
log.Fatal(err)
}
fmt.Println(json)
}
```
You can also compare from readers or byte slices:
```go
// From readers
diff, err := astdiff.DiffReaders("old.go", oldReader, "new.go", newReader)
// From source code
oldSrc := []byte(`package main
func main() {
println("hello")
}`)
newSrc := []byte(`package main
func main() {
println("world")
}`)
diff, err := astdiff.DiffSource("old.go", oldSrc, "new.go", newSrc)
```
## Example
Given these two files:
**old.go:**
```go
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
x := 10
y := 20
result := add(x, y)
fmt.Printf("Result: %d\n", result)
}
func add(a, b int) int {
return a + b
}
```
**new.go:**
```go
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println("Hello, Go!")
x := 10
y := 30
result := multiply(x, y)
fmt.Printf("Result: %d\n", result)
name := strings.ToUpper("gopher")
fmt.Println(name)
}
func multiply(a, b int) int {
return a * b
}
```
Running `astdiff -old=old.go -new=new.go` will show:
- Import of "strings" was added
- Function body of main() was modified
- Function add() was deleted
- Function multiply() was added
- Variable assignments changed
## How it works
astdiff parses both Go source files into Abstract Syntax Trees using Go's `go/ast` package, then recursively compares the tree nodes to identify structural differences. This provides more meaningful comparisons than text-based diff tools for understanding code changes.
## License
MIT