diff.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* Copyright 2016 The Bazel Authors. All rights reserved.
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package main
  13. import (
  14. "fmt"
  15. "io"
  16. "io/ioutil"
  17. "os"
  18. "path/filepath"
  19. "github.com/bazelbuild/bazel-gazelle/config"
  20. "github.com/bazelbuild/bazel-gazelle/rule"
  21. "github.com/pmezard/go-difflib/difflib"
  22. )
  23. var exitError = fmt.Errorf("encountered changes while running diff")
  24. func diffFile(c *config.Config, f *rule.File) error {
  25. rel, err := filepath.Rel(c.RepoRoot, f.Path)
  26. if err != nil {
  27. return fmt.Errorf("error getting old path for file %q: %v", f.Path, err)
  28. }
  29. rel = filepath.ToSlash(rel)
  30. date := "1970-01-01 00:00:00.000000000 +0000"
  31. diff := difflib.UnifiedDiff{
  32. Context: 3,
  33. FromDate: date,
  34. ToDate: date,
  35. }
  36. if oldContent, err := ioutil.ReadFile(f.Path); err != nil && !os.IsNotExist(err) {
  37. return fmt.Errorf("error reading original file: %v", err)
  38. } else if err != nil {
  39. diff.FromFile = "/dev/null"
  40. } else if err == nil {
  41. diff.A = difflib.SplitLines(string(oldContent))
  42. if c.ReadBuildFilesDir == "" {
  43. path, err := filepath.Rel(c.RepoRoot, f.Path)
  44. if err != nil {
  45. return fmt.Errorf("error getting old path for file %q: %v", f.Path, err)
  46. }
  47. diff.FromFile = filepath.ToSlash(path)
  48. } else {
  49. diff.FromFile = f.Path
  50. }
  51. }
  52. newContent := f.Format()
  53. diff.B = difflib.SplitLines(string(newContent))
  54. outPath := findOutputPath(c, f)
  55. if c.WriteBuildFilesDir == "" {
  56. path, err := filepath.Rel(c.RepoRoot, f.Path)
  57. if err != nil {
  58. return fmt.Errorf("error getting new path for file %q: %v", f.Path, err)
  59. }
  60. diff.ToFile = filepath.ToSlash(path)
  61. } else {
  62. diff.ToFile = outPath
  63. }
  64. uc := getUpdateConfig(c)
  65. var out io.Writer = os.Stdout
  66. if uc.patchPath != "" {
  67. out = &uc.patchBuffer
  68. }
  69. if err := difflib.WriteUnifiedDiff(out, diff); err != nil {
  70. return fmt.Errorf("error diffing %s: %v", f.Path, err)
  71. }
  72. if ds, _ := difflib.GetUnifiedDiffString(diff); ds != "" {
  73. return exitError
  74. }
  75. return nil
  76. }