Skip to content
This repository has been archived by the owner on Feb 27, 2023. It is now read-only.

Commit

Permalink
Merge pull request #1223 from littleroad/symboliclink
Browse files Browse the repository at this point in the history
pkg/fileutils: add verifications and unit test for SymboliLlink
  • Loading branch information
allencloud committed Mar 7, 2020
2 parents 0d0a606 + 082e612 commit a47017f
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
13 changes: 12 additions & 1 deletion pkg/fileutils/fileutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,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

0 comments on commit a47017f

Please sign in to comment.