2017-05-05 08:06:27 +00:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
"os/exec"
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
// Mute commands.
|
2020-04-01 16:25:22 +00:00
|
|
|
addCmd.SetOut(new(bytes.Buffer))
|
|
|
|
addCmd.SetErr(new(bytes.Buffer))
|
|
|
|
initCmd.SetOut(new(bytes.Buffer))
|
|
|
|
initCmd.SetErr(new(bytes.Buffer))
|
2017-05-05 08:06:27 +00:00
|
|
|
}
|
|
|
|
|
2019-03-20 21:21:26 +00:00
|
|
|
// ensureLF converts any \r\n to \n
|
|
|
|
func ensureLF(content []byte) []byte {
|
|
|
|
return bytes.Replace(content, []byte("\r\n"), []byte("\n"), -1)
|
|
|
|
}
|
|
|
|
|
2017-05-05 08:06:27 +00:00
|
|
|
// compareFiles compares the content of files with pathA and pathB.
|
|
|
|
// If contents are equal, it returns nil.
|
|
|
|
// If not, it returns which files are not equal
|
|
|
|
// and diff (if system has diff command) between these files.
|
|
|
|
func compareFiles(pathA, pathB string) error {
|
|
|
|
contentA, err := ioutil.ReadFile(pathA)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
contentB, err := ioutil.ReadFile(pathB)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-03-20 21:21:26 +00:00
|
|
|
if !bytes.Equal(ensureLF(contentA), ensureLF(contentB)) {
|
2017-05-05 08:06:27 +00:00
|
|
|
output := new(bytes.Buffer)
|
|
|
|
output.WriteString(fmt.Sprintf("%q and %q are not equal!\n\n", pathA, pathB))
|
|
|
|
|
|
|
|
diffPath, err := exec.LookPath("diff")
|
|
|
|
if err != nil {
|
|
|
|
// Don't execute diff if it can't be found.
|
|
|
|
return nil
|
|
|
|
}
|
2017-07-30 08:11:56 +00:00
|
|
|
diffCmd := exec.Command(diffPath, "-u", pathA, pathB)
|
2017-05-05 08:06:27 +00:00
|
|
|
diffCmd.Stdout = output
|
|
|
|
diffCmd.Stderr = output
|
|
|
|
|
2017-07-30 08:11:56 +00:00
|
|
|
output.WriteString("$ diff -u " + pathA + " " + pathB + "\n")
|
2017-05-05 08:06:27 +00:00
|
|
|
if err := diffCmd.Run(); err != nil {
|
|
|
|
output.WriteString("\n" + err.Error())
|
|
|
|
}
|
|
|
|
return errors.New(output.String())
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|