2016-03-16 19:59:34 +00:00
|
|
|
package mtree
|
|
|
|
|
2016-03-18 20:31:12 +00:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"sort"
|
|
|
|
)
|
|
|
|
|
2016-04-05 20:20:04 +00:00
|
|
|
// Result of a Check
|
2016-03-16 19:59:34 +00:00
|
|
|
type Result struct {
|
2016-04-05 20:20:04 +00:00
|
|
|
Failures []Failure // list of any failures in the Check
|
2016-03-16 19:59:34 +00:00
|
|
|
}
|
|
|
|
|
2016-04-05 20:20:04 +00:00
|
|
|
// Failure of a particular keyword for a path
|
2016-04-05 15:44:55 +00:00
|
|
|
type Failure struct {
|
|
|
|
Path string
|
|
|
|
Keyword string
|
|
|
|
Expected string
|
|
|
|
Got string
|
|
|
|
}
|
|
|
|
|
2016-04-05 20:20:04 +00:00
|
|
|
// String returns a "pretty" formatting for a Failure
|
2016-04-05 15:44:55 +00:00
|
|
|
func (f Failure) String() string {
|
|
|
|
return fmt.Sprintf("%q: keyword %q: expected %s; got %s", f.Path, f.Keyword, f.Expected, f.Got)
|
|
|
|
}
|
2016-03-18 20:31:12 +00:00
|
|
|
|
2016-04-05 20:20:04 +00:00
|
|
|
// Check a root directory path for a DirectoryHierarchy
|
2016-03-16 19:59:34 +00:00
|
|
|
func Check(root string, dh *DirectoryHierarchy) (*Result, error) {
|
2016-03-18 20:31:12 +00:00
|
|
|
creator := dhCreator{DH: dh}
|
|
|
|
curDir, err := os.Getwd()
|
|
|
|
if err == nil {
|
|
|
|
defer os.Chdir(curDir)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := os.Chdir(root); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
sort.Sort(byPos(creator.DH.Entries))
|
|
|
|
|
2016-04-05 15:44:55 +00:00
|
|
|
var result Result
|
2016-03-18 20:31:12 +00:00
|
|
|
for _, e := range creator.DH.Entries {
|
|
|
|
switch e.Type {
|
|
|
|
case SpecialType:
|
|
|
|
if e.Name == "/set" {
|
|
|
|
creator.curSet = &e
|
|
|
|
} else if e.Name == "/unset" {
|
|
|
|
creator.curSet = nil
|
|
|
|
}
|
2016-03-23 20:58:16 +00:00
|
|
|
case RelativeType, FullType:
|
|
|
|
info, err := os.Lstat(filepath.Join(root, e.Path()))
|
2016-03-18 20:31:12 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-03-23 20:58:16 +00:00
|
|
|
|
|
|
|
var kvs KeyVals
|
|
|
|
if creator.curSet != nil {
|
|
|
|
kvs = MergeSet(creator.curSet.Keywords, e.Keywords)
|
|
|
|
} else {
|
|
|
|
kvs = NewKeyVals(e.Keywords)
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, kv := range kvs {
|
|
|
|
keywordFunc, ok := KeywordFuncs[kv.Keyword()]
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("Unknown keyword %q for file %q", kv.Keyword(), e.Path())
|
|
|
|
}
|
|
|
|
curKeyVal, err := keywordFunc(filepath.Join(root, e.Path()), info)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if string(kv) != curKeyVal {
|
2016-04-05 15:44:55 +00:00
|
|
|
failure := Failure{Path: e.Path(), Keyword: kv.Keyword(), Expected: kv.Value(), Got: KeyVal(curKeyVal).Value()}
|
|
|
|
result.Failures = append(result.Failures, failure)
|
2016-03-23 20:58:16 +00:00
|
|
|
}
|
|
|
|
}
|
2016-03-18 20:31:12 +00:00
|
|
|
}
|
|
|
|
}
|
2016-04-05 15:44:55 +00:00
|
|
|
return &result, nil
|
2016-03-16 19:59:34 +00:00
|
|
|
}
|