An open API service indexing awesome lists of open source software.

https://github.com/knsh14/astdiff


https://github.com/knsh14/astdiff

Last synced: 11 months ago
JSON representation

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