Skip to content

Commit d3265a3

Browse files
authored
fix: fix download dir contain broken symlink fail (#63)
1 parent 510086b commit d3265a3

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

utils/file/file.go

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@ import (
1313
"strconv"
1414
"strings"
1515

16+
"github.com/IceWhaleTech/CasaOS-Common/utils/logger"
1617
"github.com/mholt/archiver/v3"
18+
"go.uber.org/zap"
1719
)
1820

1921
// GetSize get the file size
@@ -400,6 +402,32 @@ func GetCompressionAlgorithm(t string) (string, archiver.Writer, error) {
400402
return "", nil, errors.New("format not implemented")
401403
}
402404
}
405+
func IsBrokenSymlink(path string) (bool, error) {
406+
info, err := os.Lstat(path)
407+
if err != nil {
408+
return false, fmt.Errorf("error getting file info: %w", err)
409+
}
410+
411+
// file is not a symlink
412+
if info.Mode()&os.ModeSymlink == 0 {
413+
return false, nil
414+
}
415+
416+
target, err := os.Readlink(path)
417+
if err != nil {
418+
return false, fmt.Errorf("error reading symlink: %w", err)
419+
}
420+
421+
_, err = os.Stat(target)
422+
if os.IsNotExist(err) {
423+
return true, nil
424+
}
425+
if err != nil {
426+
return false, fmt.Errorf("error checking target: %w", err)
427+
}
428+
429+
return false, nil
430+
}
403431

404432
func AddFile(ar archiver.Writer, path, commonPath string) error {
405433
info, err := os.Stat(path)
@@ -441,7 +469,17 @@ func AddFile(ar archiver.Writer, path, commonPath string) error {
441469
}
442470

443471
for _, name := range names {
444-
err = AddFile(ar, filepath.Join(path, name), commonPath)
472+
filePath := filepath.Join(path, name)
473+
isBroken, err := IsBrokenSymlink(filePath)
474+
if err != nil {
475+
logger.Error("Failed to check symlink", zap.Any("name", filePath), zap.Error(err))
476+
continue
477+
}
478+
if isBroken {
479+
continue
480+
}
481+
482+
err = AddFile(ar, filePath, commonPath)
445483
if err != nil {
446484
return err
447485
}

0 commit comments

Comments
 (0)