選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 

79 行
2.0 KiB

  1. // Copyright 2016 Google LLC
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package pretty
  15. import (
  16. "fmt"
  17. "io/ioutil"
  18. "os"
  19. "os/exec"
  20. "syscall"
  21. )
  22. // Diff compares the pretty-printed representation of two values. The second
  23. // return value reports whether the two values' representations are identical.
  24. // If it is false, the first return value contains the diffs.
  25. //
  26. // The output labels the first value "want" and the second "got".
  27. //
  28. // Diff works by invoking the "diff" command. It will only succeed in
  29. // environments where "diff" is on the shell path.
  30. func Diff(want, got interface{}) (string, bool, error) {
  31. fname1, err := writeToTemp(want)
  32. if err != nil {
  33. return "", false, err
  34. }
  35. defer os.Remove(fname1)
  36. fname2, err := writeToTemp(got)
  37. if err != nil {
  38. return "", false, err
  39. }
  40. defer os.Remove(fname2)
  41. cmd := exec.Command("diff", "-u", "--label=want", "--label=got", fname1, fname2)
  42. out, err := cmd.Output()
  43. if err == nil {
  44. return string(out), true, nil
  45. }
  46. eerr, ok := err.(*exec.ExitError)
  47. if !ok {
  48. return "", false, err
  49. }
  50. ws, ok := eerr.Sys().(syscall.WaitStatus)
  51. if !ok {
  52. return "", false, err
  53. }
  54. if ws.ExitStatus() != 1 {
  55. return "", false, err
  56. }
  57. // Exit status of 1 means no error, but diffs were found.
  58. return string(out), false, nil
  59. }
  60. func writeToTemp(v interface{}) (string, error) {
  61. f, err := ioutil.TempFile("", "prettyDiff")
  62. if err != nil {
  63. return "", err
  64. }
  65. if _, err := fmt.Fprintf(f, "%+v\n", Value(v)); err != nil {
  66. return "", err
  67. }
  68. if err := f.Close(); err != nil {
  69. return "", err
  70. }
  71. return f.Name(), nil
  72. }