Skip to content

Commit

Permalink
Add some functions for the fs package
Browse files Browse the repository at this point in the history
  • Loading branch information
mstmdev committed Aug 7, 2023
1 parent a27d763 commit a92e16c
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
31 changes: 30 additions & 1 deletion fs/fs.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package fs

import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -119,5 +121,32 @@ func IsSymlink(path string) (bool, error) {
if err != nil {
return false, err
}
return fi.Mode()&os.ModeSymlink != 0, nil
return IsSymlinkMode(fi.Mode()), nil
}

// IsSymlinkMode check the mode is a symbolic link or not
func IsSymlinkMode(mode fs.FileMode) bool {
return mode&fs.ModeSymlink != 0
}

// IsSymlinkSupported checks if the system supports symbolic links
func IsSymlinkSupported() bool {
symlink := filepath.Join(os.TempDir(), "symlink_detect.symlink")
defer os.RemoveAll(symlink)
return Symlink(os.Args[0], symlink) == nil
}

// Symlink create a symbolic link
func Symlink(oldname, newname string) error {
return os.Symlink(oldname, newname)
}

// Readlink returns the destination of the named symbolic link
func Readlink(name string) (string, error) {
return os.Readlink(name)
}

// SymlinkText build custom symlink text content
func SymlinkText(realPath string) string {
return fmt.Sprintf("# symlink\n%s", realPath)
}
19 changes: 19 additions & 0 deletions fs/fs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,25 @@ func TestIsSymlink(t *testing.T) {
}
}

func TestIsSymlinkSupported(t *testing.T) {
IsSymlinkSupported()
}

func TestReadlink_IsNotExistError(t *testing.T) {
_, err := Readlink(testNotFoundFilePath)
if !os.IsNotExist(err) {
t.Errorf("expect to get is not exist error, but actual get %v", err)
}
}

func TestSymlinkText(t *testing.T) {
expect := "# symlink\n/etc/profile"
actual := SymlinkText("/etc/profile")
if expect != actual {
t.Errorf("TestSymlinkText error, expect get %s, but actual get %s", expect, actual)
}
}

func isNotExistAlwaysFalseMock(err error) bool {
return false
}
Expand Down

0 comments on commit a92e16c

Please sign in to comment.