func Save(filename string, data []byte, fileMode os.FileMode) error {
	log.Tracef("Attempting to open %v for creating, but only if it doesn't already exist", filename)
	file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_EXCL, fileMode)
	if err != nil {
		if !os.IsExist(err) {
			return fmt.Errorf("Unexpected error opening %s: %s", filename, err)
		}
		log.Tracef("%s already exists, check to make sure contents is the same", filename)
		if dataMatches(filename, data) {
			log.Tracef("Data in %s matches expected, using existing", filename)
			chmod(filename, fileMode)
			return nil
		}
		log.Tracef("Data in %s doesn't match expected, truncating file", filename)
		file, err = openAndTruncate(filename, fileMode, true)
		if err != nil {
			return fmt.Errorf("Unable to truncate %s: %s", filename, err)
		}
	}
	log.Tracef("Created new file at %s, writing data", filename)
	_, err = file.Write(data)
	if err != nil {
		if err := os.Remove(filename); err != nil {
			log.Debugf("Unable to remove file: %v", err)
		}
		return fmt.Errorf("Unable to write to file at %s: %s", filename, err)
	}
	if err := file.Sync(); err != nil {
		log.Debugf("Unable to sync file: %v", err)
	}
	if err := file.Close(); err != nil {
		log.Debugf("Unable to close file: %v", err)
	}
	log.Trace("File saved")
	return nil
}
Save saves the given data to the file at filename. If an existing file at
that filename already exists, this simply chmods the existing file to match
the given fileMode and otherwise leaves it alone.
package filepersist
import (
	"fmt"
	"io"
	"os"
	"github.com/getlantern/golog"
)
var (
	log = golog.LoggerFor("filepersist")
)