func writeFile()

in cmd/kazel/kazel.go [349:388]


func writeFile(path string, f *build.File, boilerplate []byte, exists, dryRun bool) (bool, error) {
	build.Rewrite(f)
	var out []byte
	out = append(out, boilerplate...)
	// double format the source file as our modification logic sometimes uses
	// LiteralExpr where it should use other types of expressions, and this
	// prevents issues where kazel thus formats structures incorrectly.
	// :this_is_fine:
	outData := build.Format(f)
	var err error
	f, err = build.Parse(path, outData)
	if err != nil {
		return false, fmt.Errorf("internal error occurred formatting file: %v", err)
	}
	// also call Rewrite again to run Buildifier against the results as
	// visibility rules are not ordered correctly for some reason
	build.Rewrite(f)
	out = append(out, build.Format(f)...)
	if exists {
		orig, err := ioutil.ReadFile(path)
		if err != nil {
			return false, err
		}
		if bytes.Compare(orig, out) == 0 {
			return false, nil
		}
		if *printDiff {
			Diff(orig, out)
		}
	}
	if dryRun {
		fmt.Fprintf(os.Stderr, "DRY-RUN: wrote %q\n", path)
		return true, nil
	}
	werr := ioutil.WriteFile(path, out, 0644)
	if werr == nil {
		fmt.Fprintf(os.Stderr, "wrote %q\n", path)
	}
	return werr == nil, werr
}