1package cmd 2 3import ( 4 "bytes" 5 "errors" 6 "fmt" 7 "io/ioutil" 8 "os/exec" 9) 10 11func init() { 12 // Mute commands. 13 addCmd.SetOut(new(bytes.Buffer)) 14 addCmd.SetErr(new(bytes.Buffer)) 15 initCmd.SetOut(new(bytes.Buffer)) 16 initCmd.SetErr(new(bytes.Buffer)) 17} 18 19// ensureLF converts any \r\n to \n 20func ensureLF(content []byte) []byte { 21 return bytes.Replace(content, []byte("\r\n"), []byte("\n"), -1) 22} 23 24// compareFiles compares the content of files with pathA and pathB. 25// If contents are equal, it returns nil. 26// If not, it returns which files are not equal 27// and diff (if system has diff command) between these files. 28func compareFiles(pathA, pathB string) error { 29 contentA, err := ioutil.ReadFile(pathA) 30 if err != nil { 31 return err 32 } 33 contentB, err := ioutil.ReadFile(pathB) 34 if err != nil { 35 return err 36 } 37 if !bytes.Equal(ensureLF(contentA), ensureLF(contentB)) { 38 output := new(bytes.Buffer) 39 output.WriteString(fmt.Sprintf("%q and %q are not equal!\n\n", pathA, pathB)) 40 41 diffPath, err := exec.LookPath("diff") 42 if err != nil { 43 // Don't execute diff if it can't be found. 44 return nil 45 } 46 diffCmd := exec.Command(diffPath, "-u", pathA, pathB) 47 diffCmd.Stdout = output 48 diffCmd.Stderr = output 49 50 output.WriteString("$ diff -u " + pathA + " " + pathB + "\n") 51 if err := diffCmd.Run(); err != nil { 52 output.WriteString("\n" + err.Error()) 53 } 54 return errors.New(output.String()) 55 } 56 return nil 57} 58