github.com/afking/bazel-gazelle@v0.0.0-20180301150245-c02bc0f529e8/cmd/gazelle/diff.go (about) 1 /* Copyright 2016 The Bazel Authors. All rights reserved. 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 */ 15 16 package main 17 18 import ( 19 "bytes" 20 "io/ioutil" 21 "os" 22 "os/exec" 23 24 "github.com/bazelbuild/bazel-gazelle/internal/config" 25 bf "github.com/bazelbuild/buildtools/build" 26 ) 27 28 func diffFile(c *config.Config, file *bf.File, path string) error { 29 oldContents, err := ioutil.ReadFile(file.Path) 30 if err != nil { 31 oldContents = nil 32 } 33 newContents := bf.Format(file) 34 if bytes.Equal(oldContents, newContents) { 35 return nil 36 } 37 f, err := ioutil.TempFile("", c.DefaultBuildFileName()) 38 if err != nil { 39 return err 40 } 41 f.Close() 42 defer os.Remove(f.Name()) 43 if err := ioutil.WriteFile(f.Name(), newContents, 0666); err != nil { 44 return err 45 } 46 cmd := exec.Command("diff", "-u", "--new-file", path, f.Name()) 47 cmd.Stdout = os.Stdout 48 cmd.Stderr = os.Stderr 49 err = cmd.Run() 50 if _, ok := err.(*exec.ExitError); ok { 51 // diff returns non-zero when files are different. This is not an error. 52 return nil 53 } 54 return err 55 }