github.com/wolfd/bazel-gazelle@v0.14.0/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  	"path/filepath"
    24  )
    25  
    26  func diffFile(path string, newContents []byte) error {
    27  	oldContents, err := ioutil.ReadFile(path)
    28  	if err != nil {
    29  		oldContents = nil
    30  	}
    31  	if bytes.Equal(oldContents, newContents) {
    32  		return nil
    33  	}
    34  	f, err := ioutil.TempFile("", filepath.Base(path))
    35  	if err != nil {
    36  		return err
    37  	}
    38  	f.Close()
    39  	defer os.Remove(f.Name())
    40  	if err := ioutil.WriteFile(f.Name(), newContents, 0666); err != nil {
    41  		return err
    42  	}
    43  	cmd := exec.Command("diff", "-u", "--new-file", path, f.Name())
    44  	cmd.Stdout = os.Stdout
    45  	cmd.Stderr = os.Stderr
    46  	err = cmd.Run()
    47  	if _, ok := err.(*exec.ExitError); ok {
    48  		// diff returns non-zero when files are different. This is not an error.
    49  		return nil
    50  	}
    51  	return err
    52  }