manager/magefiles/internal/walk/copy_files.go
Dan Anglin a909803b29
refactor: reorganise magefiles
Reorganise and refactor the magefiles to make it more manageable and
reduce duplication.
2024-09-14 05:58:43 +01:00

64 lines
1.3 KiB
Go

package walk
import (
"fmt"
"io/fs"
"path/filepath"
"slices"
"strings"
"codeflow.dananglin.me.uk/linux-home/manager/magefiles/internal/utilities"
"github.com/magefile/mage/sh"
)
func CopyFiles(
homeConfigDirectory string,
rootDir string,
rootManagedDir string,
validationFunc func(string) bool,
) fs.WalkDirFunc {
return func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if path == rootDir {
return nil
}
relativePath := strings.TrimPrefix(path, rootDir+"/")
if validationFunc != nil {
if !validationFunc(relativePath) {
return nil
}
}
managedPath := filepath.Join(rootManagedDir, relativePath)
configPath := filepath.Join(homeConfigDirectory, relativePath)
if d.IsDir() {
dirs := []string{managedPath, configPath}
for _, dir := range slices.All(dirs) {
if err := utilities.EnsureDirectory(dir); err != nil {
return fmt.Errorf("unable to ensure the existence of the directory %q: %w", dir, err)
}
}
return nil
}
fmt.Println("Processing file:", relativePath)
if err := sh.Copy(managedPath, path); err != nil {
return fmt.Errorf("unable to copy %s to %s: %w", path, managedPath, err)
}
if err := utilities.EnsureSymlink(managedPath, configPath); err != nil {
return err
}
return nil
}
}