apply code review results

This commit is contained in:
ohchang-kwon 2020-01-21 12:07:13 +09:00
parent fb4d1f9c8d
commit df767bb195
2 changed files with 26 additions and 25 deletions

View File

@ -201,39 +201,38 @@ func resolveIfSymlink(destPath string) (string, error) {
return "", errors.New("dest path must be abs") return "", errors.New("dest path must be abs")
} }
pathPrefix := "/" var nonexistentPaths []string
pathTokens := strings.Split(destPath, string(os.PathSeparator))
for i, pathToken := range pathTokens { newPath := destPath
currentPath := filepath.Join(pathPrefix, pathToken) for newPath != "/" {
info, err := os.Lstat(currentPath) _, err := os.Lstat(newPath)
if err != nil { if err != nil {
if os.IsNotExist(err) { if os.IsNotExist(err) {
pathPrefix = filepath.Join(append([]string{currentPath}, pathTokens[i+1:]...)...) dir, file := filepath.Split(newPath)
break newPath = filepath.Clean(dir)
nonexistentPaths = append(nonexistentPaths, file)
continue
} else { } else {
return "", errors.Wrap(err, "failed to lstat") return "", errors.Wrap(err, "failed to lstat")
} }
} }
switch mode := info.Mode(); { newPath, err = filepath.EvalSymlinks(newPath)
case mode&os.ModeSymlink != 0: if err != nil {
linkPath, err := os.Readlink(currentPath) return "", errors.Wrap(err, "failed to eval symlinks")
if err != nil {
return "", errors.Wrap(err, "failed to read symlink")
}
if filepath.IsAbs(linkPath) {
pathPrefix = linkPath
} else {
pathPrefix = filepath.Join(pathPrefix, linkPath)
}
default:
pathPrefix = filepath.Join(pathPrefix, pathToken)
} }
break
} }
if destPath != pathPrefix {
logrus.Tracef("Updating destination path from %v to %v due to symlink", destPath, pathPrefix) for i := len(nonexistentPaths) - 1; i >= 0; i-- {
newPath = filepath.Join(newPath, nonexistentPaths[i])
} }
return filepath.Clean(pathPrefix), nil
if destPath != newPath {
logrus.Tracef("Updating destination path from %v to %v due to symlink", destPath, newPath)
}
return filepath.Clean(newPath), nil
} }
func copyCmdFilesUsedFromContext( func copyCmdFilesUsedFromContext(

View File

@ -194,8 +194,10 @@ func Test_resolveIfSymlink(t *testing.T) {
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
cases := []testCase{{destPath: thepath, expectedPath: thepath, err: nil}} cases := []testCase{
{destPath: thepath, expectedPath: thepath, err: nil},
{destPath: "/", expectedPath: "/", err: nil},
}
baseDir = tmpDir baseDir = tmpDir
symLink := filepath.Join(baseDir, "symlink") symLink := filepath.Join(baseDir, "symlink")
if err := os.Symlink(filepath.Base(thepath), symLink); err != nil { if err := os.Symlink(filepath.Base(thepath), symLink); err != nil {