diff.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package main
  14. import (
  15. "io/ioutil"
  16. "os"
  17. "os/exec"
  18. )
  19. // Diff prints the unified diff of the two provided byte slices
  20. // using the unix diff command.
  21. func Diff(left, right []byte) error {
  22. lf, err := ioutil.TempFile("/tmp", "actual-file-")
  23. if err != nil {
  24. return err
  25. }
  26. defer lf.Close()
  27. defer os.Remove(lf.Name())
  28. rf, err := ioutil.TempFile("/tmp", "expected-file-")
  29. if err != nil {
  30. return err
  31. }
  32. defer rf.Close()
  33. defer os.Remove(rf.Name())
  34. _, err = lf.Write(left)
  35. if err != nil {
  36. return err
  37. }
  38. lf.Close()
  39. _, err = rf.Write(right)
  40. if err != nil {
  41. return err
  42. }
  43. rf.Close()
  44. cmd := exec.Command("/usr/bin/diff", "-u", lf.Name(), rf.Name())
  45. cmd.Stdout = os.Stdout
  46. cmd.Stderr = os.Stderr
  47. cmd.Run()
  48. return nil
  49. }