package testutil

import (
	"bytes"
	"io/ioutil"
	"reflect"

	"git.archive.org/martin/cgraph/skate/atomic"
)

// BufferFileEquals returns true, if the contents of a given buffer matches the
// contents of a file given by filename.
func BufferFileEquals(buf *bytes.Buffer, filename string) (bool, error) {
	b, err := ioutil.ReadFile(filename)
	if err != nil {
		return false, err
	}
	bb := buf.Bytes()
	if len(bb) == 0 && len(b) == 0 {
		return true, nil
	}
	return reflect.DeepEqual(b, bb), nil
}

// BufferToTemp writes the content of a buffer to a temporary file and returns
// its path.
func BufferToTemp(buf *bytes.Buffer) (string, error) {
	f, err := ioutil.TempFile("", "skate-test-*")
	if err != nil {
		return "", err
	}
	if err = atomic.WriteFile(f.Name(), buf.Bytes(), 0755); err != nil {
		return "", err
	}
	return f.Name(), nil
}