engine: resources: file: Require paths to be absolute

This is a requirement of our file resource, so we should validate this
and clearly express it in the documentation.
This commit is contained in:
James Shubin
2018-12-16 07:02:52 -05:00
parent 8282f3b59c
commit d5bfb7257e
3 changed files with 25 additions and 2 deletions

View File

@@ -68,7 +68,7 @@ identified by a trailing slash in their path name. File have no such slash.
It has the following properties: It has the following properties:
* `path`: file path (directories have a trailing slash here) * `path`: absolute file path (directories have a trailing slash here)
* `content`: raw file content * `content`: raw file content
* `state`: either `exists` (the default value) or `absent` * `state`: either `exists` (the default value) or `absent`
* `mode`: octal unix file permissions * `mode`: octal unix file permissions

View File

@@ -54,7 +54,10 @@ type FileRes struct {
init *engine.Init init *engine.Init
Path string `yaml:"path"` // path variable (usually defaults to name) // Path variable, which usually defaults to the name, represents the
// destination path for the file or directory being managed. It must be
// an absolute path, and as a result must start with a slash.
Path string `yaml:"path"`
Dirname string `yaml:"dirname"` // override the path dirname Dirname string `yaml:"dirname"` // override the path dirname
Basename string `yaml:"basename"` // override the path basename Basename string `yaml:"basename"` // override the path basename
Content *string `yaml:"content"` // nil to mark as undefined Content *string `yaml:"content"` // nil to mark as undefined
@@ -93,6 +96,10 @@ func (obj *FileRes) Validate() error {
return fmt.Errorf("basename must not start with a slash") return fmt.Errorf("basename must not start with a slash")
} }
if !strings.HasPrefix(obj.GetPath(), "/") {
return fmt.Errorf("resultant path must be absolute")
}
if obj.Content != nil && obj.Source != "" { if obj.Content != nil && obj.Source != "" {
return fmt.Errorf("can't specify both Content and Source") return fmt.Errorf("can't specify both Content and Source")
} }

View File

@@ -146,3 +146,19 @@ func TestMiscEncodeDecode2(t *testing.T) {
t.Errorf("The input and output Res values do not match: %+v", err) t.Errorf("The input and output Res values do not match: %+v", err)
} }
} }
func TestFileAbsolute1(t *testing.T) {
// file resource paths should be absolute
f1 := &FileRes{
Path: "tmp/a/b", // some relative file
}
f2 := &FileRes{
Path: "tmp/a/b/", // some relative dir
}
f3 := &FileRes{
Path: "tmp", // some short relative file
}
if f1.Validate() == nil || f2.Validate() == nil || f3.Validate() == nil {
t.Errorf("file res should have failed validate")
}
}