diff.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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/internal/config"
  20. "github.com/bazelbuild/bazel-gazelle/internal/rule"
  21. "github.com/pmezard/go-difflib/difflib"
  22. )
  23. func diffFile(c *config.Config, f *rule.File) error {
  24. rel, err := filepath.Rel(c.RepoRoot, f.Path)
  25. if err != nil {
  26. return fmt.Errorf("error getting old path for file %q: %v", f.Path, err)
  27. }
  28. rel = filepath.ToSlash(rel)
  29. date := "1970-01-01 00:00:00.000000000 +0000"
  30. diff := difflib.UnifiedDiff{
  31. Context: 3,
  32. FromDate: date,
  33. ToDate: date,
  34. }
  35. if oldContent, err := ioutil.ReadFile(f.Path); err != nil && !os.IsNotExist(err) {
  36. return fmt.Errorf("error reading original file: %v", err)
  37. } else if err != nil {
  38. diff.FromFile = "/dev/null"
  39. } else if err == nil {
  40. diff.A = difflib.SplitLines(string(oldContent))
  41. if c.ReadBuildFilesDir == "" {
  42. path, err := filepath.Rel(c.RepoRoot, f.Path)
  43. if err != nil {
  44. return fmt.Errorf("error getting old path for file %q: %v", f.Path, err)
  45. }
  46. diff.FromFile = filepath.ToSlash(path)
  47. } else {
  48. diff.FromFile = f.Path
  49. }
  50. }
  51. newContent := f.Format()
  52. diff.B = difflib.SplitLines(string(newContent))
  53. outPath := findOutputPath(c, f)
  54. if c.WriteBuildFilesDir == "" {
  55. path, err := filepath.Rel(c.RepoRoot, f.Path)
  56. if err != nil {
  57. return fmt.Errorf("error getting new path for file %q: %v", f.Path, err)
  58. }
  59. diff.ToFile = filepath.ToSlash(path)
  60. } else {
  61. diff.ToFile = outPath
  62. }
  63. uc := getUpdateConfig(c)
  64. var out io.Writer = os.Stdout
  65. if uc.patchPath != "" {
  66. out = &uc.patchBuffer
  67. }
  68. if err := difflib.WriteUnifiedDiff(out, diff); err != nil {
  69. return fmt.Errorf("error diffing %s: %v", f.Path, err)
  70. }
  71. return nil
  72. }