2017-09-16 16:44:13 +02:00
|
|
|
package status
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/md5"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2017-09-30 19:40:11 +02:00
|
|
|
"regexp"
|
2017-09-16 16:44:13 +02:00
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Checksum validades if a task is up to date by calculating its source
|
|
|
|
// files checksum
|
|
|
|
type Checksum struct {
|
|
|
|
Dir string
|
|
|
|
Task string
|
|
|
|
Sources []string
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsUpToDate implements the Checker interface
|
|
|
|
func (c *Checksum) IsUpToDate() (bool, error) {
|
2017-10-01 20:05:09 +02:00
|
|
|
checksumFile := c.checksumFilePath()
|
2017-09-16 16:44:13 +02:00
|
|
|
|
|
|
|
data, _ := ioutil.ReadFile(checksumFile)
|
|
|
|
oldMd5 := strings.TrimSpace(string(data))
|
|
|
|
|
|
|
|
sources, err := glob(c.Dir, c.Sources)
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
|
|
|
|
newMd5, err := c.checksum(sources...)
|
|
|
|
if err != nil {
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
_ = os.MkdirAll(filepath.Join(c.Dir, ".task"), 0755)
|
2017-09-30 19:40:11 +02:00
|
|
|
if err = ioutil.WriteFile(checksumFile, []byte(newMd5+"\n"), 0644); err != nil {
|
2017-09-16 16:44:13 +02:00
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
return oldMd5 == newMd5, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Checksum) checksum(files ...string) (string, error) {
|
|
|
|
h := md5.New()
|
|
|
|
|
|
|
|
for _, f := range files {
|
|
|
|
f, err := os.Open(f)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2017-09-19 19:03:24 +02:00
|
|
|
info, err := f.Stat()
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
if info.IsDir() {
|
|
|
|
continue
|
|
|
|
}
|
2017-09-16 16:44:13 +02:00
|
|
|
if _, err := io.Copy(h, f); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return fmt.Sprintf("%x", h.Sum(nil)), nil
|
|
|
|
}
|
|
|
|
|
2017-10-01 20:05:09 +02:00
|
|
|
// OnError implements the Checker interface
|
|
|
|
func (c *Checksum) OnError() error {
|
|
|
|
return os.Remove(c.checksumFilePath())
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Checksum) checksumFilePath() string {
|
|
|
|
return filepath.Join(c.Dir, ".task", c.normalizeFilename(c.Task))
|
|
|
|
}
|
|
|
|
|
2017-09-30 19:40:11 +02:00
|
|
|
var checksumFilenameRegexp = regexp.MustCompile("[^A-z0-9]")
|
|
|
|
|
|
|
|
// replaces invalid caracters on filenames with "-"
|
|
|
|
func (*Checksum) normalizeFilename(f string) string {
|
|
|
|
return checksumFilenameRegexp.ReplaceAllString(f, "-")
|
|
|
|
}
|