From 17742e7b6cb39406bb875f41d3ae79212ec8859c Mon Sep 17 00:00:00 2001 From: Alex Goodman Date: Tue, 19 Nov 2019 10:13:26 -0800 Subject: [PATCH] add test for formatting/rejecting relative path in filetree --- dive/filetree/file_tree.go | 11 ++++++++--- dive/filetree/file_tree_test.go | 34 +++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/dive/filetree/file_tree.go b/dive/filetree/file_tree.go index f8185594..4333e258 100644 --- a/dive/filetree/file_tree.go +++ b/dive/filetree/file_tree.go @@ -2,6 +2,7 @@ package filetree import ( "fmt" + "path" "sort" "strings" @@ -240,8 +241,12 @@ func (tree *FileTree) GetNode(path string) (*FileNode, error) { } // AddPath adds a new node to the tree with the given payload -func (tree *FileTree) AddPath(path string, data FileInfo) (*FileNode, []*FileNode, error) { - nodeNames := strings.Split(strings.Trim(path, "/"), "/") +func (tree *FileTree) AddPath(filepath string, data FileInfo) (*FileNode, []*FileNode, error) { + filepath = path.Clean(filepath) + if filepath == "." { + return nil, nil, fmt.Errorf("cannot add relative path '%s'", filepath) + } + nodeNames := strings.Split(strings.Trim(filepath, "/"), "/") node := tree.Root addedNodes := make([]*FileNode, 0) for idx, name := range nodeNames { @@ -264,7 +269,7 @@ func (tree *FileTree) AddPath(path string, data FileInfo) (*FileNode, []*FileNod if node == nil { // the child could not be added - return node, addedNodes, fmt.Errorf(fmt.Sprintf("could not add child node: '%s' (path:'%s')", name, path)) + return node, addedNodes, fmt.Errorf(fmt.Sprintf("could not add child node: '%s' (path:'%s')", name, filepath)) } } diff --git a/dive/filetree/file_tree_test.go b/dive/filetree/file_tree_test.go index 15b95e52..c1bc37cb 100644 --- a/dive/filetree/file_tree_test.go +++ b/dive/filetree/file_tree_test.go @@ -125,6 +125,40 @@ func TestStringBetween(t *testing.T) { } +func TestRejectPurelyRelativePath(t *testing.T) { + tree := NewFileTree() + _, _, err := tree.AddPath("./etc/nginx/nginx.conf", FileInfo{}) + if err != nil { + t.Errorf("could not setup test: %v", err) + } + _, _, err = tree.AddPath("./", FileInfo{}) + + if err == nil { + t.Errorf("expected to reject relative path, but did not") + } + +} + +func TestAddRelativePath(t *testing.T) { + tree := NewFileTree() + _, _, err := tree.AddPath("./etc/nginx/nginx.conf", FileInfo{}) + if err != nil { + t.Errorf("could not setup test: %v", err) + } + + expected := + `└── etc + └── nginx + └── nginx.conf +` + actual := tree.String(false) + + if expected != actual { + t.Errorf("Expected tree string:\n--->%s<---\nGot:\n--->%s<---", expected, actual) + } + +} + func TestAddPath(t *testing.T) { tree := NewFileTree() _, _, err := tree.AddPath("/etc/nginx/nginx.conf", FileInfo{})