Skip to content

Commit

Permalink
os synlink use related path
Browse files Browse the repository at this point in the history
  • Loading branch information
izouxv committed Jun 29, 2024
1 parent e211396 commit 5e4e749
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
6 changes: 5 additions & 1 deletion basepath.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,11 @@ func (b *BasePathFs) ReadlinkIfPossible(name string) (string, error) {
return "", &os.PathError{Op: "readlink", Path: name, Err: err}
}
if reader, ok := b.source.(LinkReader); ok {
return reader.ReadlinkIfPossible(name)
srcPath, err := reader.ReadlinkIfPossible(name)
if err != nil {
return "", err
}
return strings.TrimPrefix(srcPath, filepath.Clean(b.path)), nil
}
return "", &os.PathError{Op: "readlink", Path: name, Err: ErrNoReadlink}
}
14 changes: 12 additions & 2 deletions os.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package afero

import (
"os"
"path/filepath"
"time"
)

Expand Down Expand Up @@ -105,9 +106,18 @@ func (OsFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
}

func (OsFs) SymlinkIfPossible(oldname, newname string) error {
return os.Symlink(oldname, newname)
relpath, err := filepath.Rel(newname, oldname)
if err != nil {
return &os.LinkError{Op: "symlink", Old: oldname, New: newname, Err: err}
}
return os.Symlink(relpath, newname)
}

func (OsFs) ReadlinkIfPossible(name string) (string, error) {
return os.Readlink(name)
path, err := os.Readlink(name)
if err != nil {
return "", err
}
pathAbs := filepath.Clean(filepath.Join(name, path))
return pathAbs, nil
}
3 changes: 2 additions & 1 deletion symlink_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,14 +132,15 @@ func TestReadlinkIfPossible(t *testing.T) {
}

testRead := func(r LinkReader, name string, output *string) {
_, err := r.ReadlinkIfPossible(name)
str, err := r.ReadlinkIfPossible(name)
if (err != nil) && (output == nil) {
t.Fatalf("Error reading link, expected success, got error: %v", err)
} else if (err == nil) && (output != nil) {
t.Fatalf("Error reading link, succeeded when expecting error: %v", *output)
} else if err != nil && err.Error() != *output && !strings.HasSuffix(err.Error(), *output) {
t.Fatalf("Error reading link, expected error '%v', instead received '%v'", *output, err)
}
t.Logf("str: %v", str)
}

notSupported := ErrNoReadlink.Error()
Expand Down

0 comments on commit 5e4e749

Please sign in to comment.