Skip to content

Instantly share code, notes, and snippets.

@dmitshur
Created November 25, 2013 00:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmitshur/7634341 to your computer and use it in GitHub Desktop.
Save dmitshur/7634341 to your computer and use it in GitHub Desktop.
package main
import "github.com/sergi/go-diff/diffmatchpatch"
import "bytes"
import "os"
import "os/exec"
import "io/ioutil"
func diff_native(s1, s2 string) string {
dmp := diffmatchpatch.New()
return dmp.PatchToText(dmp.PatchMake(s1, s2))
}
func diff_not_native(s1, s2 string) string {
if data, err := diff_gofmt([]byte(s1), []byte(s2)); err == nil {
data = data[bytes.IndexByte(data, '\n')+1:] // Skip first line
data = data[bytes.IndexByte(data, '\n')+1:] // Skip second line
return string(data)
} else {
panic(err)
}
}
func diff_gofmt(b1, b2 []byte) (data []byte, err error) {
f1, err := ioutil.TempFile("", "gofmt")
if err != nil {
return
}
defer os.Remove(f1.Name())
defer f1.Close()
f2, err := ioutil.TempFile("", "gofmt")
if err != nil {
return
}
defer os.Remove(f2.Name())
defer f2.Close()
f1.Write(b1)
f2.Write(b2)
data, err = exec.Command("diff", "-u", f1.Name(), f2.Name()).CombinedOutput()
if len(data) > 0 {
// diff exits with a non-zero status when the files don't match.
// Ignore that failure as long as we get output.
err = nil
}
return
}
var s1, s2 = `package main
import (
"fmt"
"io/ioutil"
"net/http"
"time"
)
const Const = 1 + 1
type Bar struct {
key string
value int
}
func foo() (int, string) { return 5, "hi" }
func handler(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
_ = b
_ = err
}
func main() {
foo()
fmt.Println("Booyah!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
for i := 1; i <= 10; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(i)
}
i := Bar{"i", 1236}
i.value++
}
`, `package main
import (
"fmt"
"io/ioutil"
"net/http"
"time"
)
const Const = 1 + 1
type Bar struct {
key string
value int
}
func foo() (int, string) { return 5, "hi" }
func handler(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
_ = b
_ = err
}
func main() {
foo()
fmt.Println("Booyah!!!!!!!!!!!!!!!!!!!!!!!!!!")
for i := 1; i <= 10; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(i)
}
i := Bar{"i", 1236}
i.value++
}
`
func main() {
output := diff_native(s1, s2)
desiredOutput := diff_not_native(s1, s2)
if output == desiredOutput {
print("Victory! Thank you for playing.")
} else {
print("got:\n", output)
print("\ndesired:\n", desiredOutput)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment