Skip to content
This repository has been archived by the owner on Dec 20, 2024. It is now read-only.

pkg/fileutils: add verifications and unit test for SymboliLlink #1223

Merged
merged 2 commits into from
Mar 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion pkg/fileutils/fileutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,18 @@ func Link(src string, linkName string) error {

// SymbolicLink creates target as a symbolic link to src.
func SymbolicLink(src string, target string) error {
// TODO Add verifications.
if !PathExist(src) {
return fmt.Errorf("failed to symlink %s to %s: src no such file or directory", target, src)
}
if PathExist(target) {
if IsDir(target) {
return fmt.Errorf("failed to symlink %s to %s: link name already exists and is a directory", target, src)
}
if err := DeleteFile(target); err != nil {
return fmt.Errorf("failed to symlink %s to %s when deleting target file: %v", target, src, err)
}

}
return os.Symlink(src, target)
}

Expand Down
32 changes: 32 additions & 0 deletions pkg/fileutils/fileutils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,38 @@ func (s *FileUtilTestSuite) TestLink(c *check.C) {
c.Assert(err, check.NotNil)
}

func (s *FileUtilTestSuite) TestSymbolicLink(c *check.C) {
pathStr := filepath.Join(s.tmpDir, "TestSymLinkFileNonExist")
linkStr := filepath.Join(s.tmpDir, "TestSymLinkNameFileNonExist")
err := SymbolicLink(pathStr, linkStr)
c.Assert(err, check.NotNil)
c.Assert(PathExist(linkStr), check.Equals, false)

pathStr = filepath.Join(s.tmpDir, "TestSymLinkDir")
os.Mkdir(pathStr, 0755)
linkStr = filepath.Join(s.tmpDir, "TestSymLinkNameDir")
err = SymbolicLink(pathStr, linkStr)
c.Assert(err, check.IsNil)
c.Assert(PathExist(linkStr), check.Equals, true)

pathStr = filepath.Join(s.tmpDir, "TestSymLinkFile")
os.Create(pathStr)
linkStr = filepath.Join(s.tmpDir, "TestSymLinkNameFile")
err = SymbolicLink(pathStr, linkStr)
c.Assert(err, check.IsNil)
c.Assert(PathExist(linkStr), check.Equals, true)

linkStr = filepath.Join(s.tmpDir, "TestSymLinkNameDirExist")
os.Mkdir(linkStr, 0755)
err = SymbolicLink(pathStr, linkStr)
c.Assert(err, check.NotNil)

linkStr = filepath.Join(s.tmpDir, "TestSymLinkNameFileExist")
os.Create(linkStr)
err = SymbolicLink(pathStr, linkStr)
c.Assert(err, check.IsNil)
}

func (s *FileUtilTestSuite) TestCopyFile(c *check.C) {
srcPath := filepath.Join(s.tmpDir, "TestCopyFileSrc")
dstPath := filepath.Join(s.tmpDir, "TestCopyFileDst")
Expand Down