Created
January 13, 2021 19:54
-
-
Save lmas/5ccebecaf9dd03ebce27c49b874c257b to your computer and use it in GitHub Desktop.
Check if a file/dir path is a symlink
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"fmt" | |
"os" | |
"path/filepath" | |
) | |
// . or tmp/ = current working dir | |
// ./hello.txt = regular file | |
// ./mod = symlink somewhere else | |
// ./dir = symlink to ../tmp | |
var full = []string{ | |
"hello.txt", | |
"./hello.txt", | |
"mod", | |
"./mod", | |
".", | |
"./", | |
"../tmp", | |
"../tmp/", | |
"dir", | |
"dir/", | |
"./dir", | |
"./dir/", | |
"../tmp/hello.txt", | |
"../tmp/mod", | |
"dir/hello.txt", | |
"dir/mod", | |
"./dir/hello.txt", | |
"./dir/mod", | |
"../tmp/dir/hello.txt", | |
"../tmp/dir/mod", | |
"dir/./hello.txt", | |
"dir/./mod", | |
"dir/../hello.txt", | |
"dir/../../tmp/mod", | |
} | |
func main() { | |
for i, f := range full { | |
err := isSymlink(f) | |
if err == nil { | |
continue | |
} | |
fmt.Printf("%d\t f: %v\t d: %v\t %s\t\t %v\n", i, err == ErrFileIsSymlink, err == ErrDirIsSymlink, f, err) | |
} | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////////////// | |
func checkErr(err error) { | |
if err != nil { | |
panic(err) | |
} | |
} | |
func isSymlink(path string) error { | |
// Fails for the last "dot-dot" test paths | |
dir, _ := filepath.Split(path) | |
err := checkSymlink(filepath.Clean(dir)) | |
switch err { | |
case nil: | |
return checkSymlink(path) | |
case ErrFileIsSymlink: | |
return ErrDirIsSymlink | |
default: | |
return err | |
} | |
// Expensive to run, but catches all kinds of paths I think | |
//var d []string | |
//for _, p := range strings.Split(path, string(filepath.Separator)) { | |
//d = append(d, p) | |
//if err := checkSymlink(filepath.Join(d...)); err != nil { | |
//if err == ErrFileIsSymlink { | |
//return ErrDirIsSymlink | |
//} | |
//return err | |
//} | |
//} | |
//return checkSymlink(path) | |
} | |
var ErrFileIsSymlink = errors.New("file is symlink") | |
var ErrDirIsSymlink = errors.New("dir is symlink") | |
func checkSymlink(path string) error { | |
fi, err := os.Lstat(path) | |
if err != nil { | |
return err | |
} | |
if fi.Mode()&os.ModeSymlink != 0 { | |
return ErrFileIsSymlink | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment