-
Notifications
You must be signed in to change notification settings - Fork 25
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add: remotefs/DownloadDirectory function to support recursive download
- Loading branch information
1 parent
66ca9bc
commit 54e8e2d
Showing
1 changed file
with
49 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
package remotefs | ||
|
||
import ( | ||
"fmt" | ||
"os" | ||
"path/filepath" | ||
) | ||
|
||
// DownloadDirectory downloads all files and directories recursively from the remote system to local directory. | ||
func DownloadDirectory(fs FS, src, dst string) error { | ||
// Ensure the destination directory is created even if empty | ||
srcInfo, err := fs.Stat(src) | ||
if err != nil { | ||
return fmt.Errorf("stat dir for download: %w", err) | ||
} | ||
mode := srcInfo.Mode() & os.ModePerm | ||
if err := os.MkdirAll(dst, mode); err != nil { | ||
return fmt.Errorf("create empty dir for download: %w", err) | ||
} | ||
|
||
entries, err := fs.ReadDir(src) | ||
if err != nil { | ||
return fmt.Errorf("read dir for download: %w", err) | ||
} | ||
|
||
for _, entry := range entries { | ||
srcPath := filepath.Join(src, entry.Name()) | ||
dstPath := filepath.Join(dst, entry.Name()) | ||
|
||
info, err := entry.Info() | ||
if err != nil { | ||
return fmt.Errorf("dir info for download: %w", err) | ||
} | ||
|
||
if info.IsDir() { | ||
if err := os.MkdirAll(dstPath, info.Mode()); err != nil { | ||
return fmt.Errorf("create dir for download: %w", err) | ||
} | ||
if err := DownloadDirectory(fs, srcPath, dstPath); err != nil { | ||
return fmt.Errorf("download dir: %w", err) | ||
} | ||
} else { | ||
if err := Download(fs, srcPath, dstPath); err != nil { | ||
return fmt.Errorf("download file in dir: %w", err) | ||
} | ||
} | ||
} | ||
return nil | ||
} |