checkpoint: managing files

This commit is contained in:
Dan Anglin 2024-09-10 12:44:25 +01:00
parent 201fce8747
commit 125c31e78e
Signed by: dananglin
GPG key ID: 0C1D44CFBEE68638

View file

@ -3,6 +3,7 @@
package main
import (
"errors"
"fmt"
"io/fs"
"os"
@ -69,5 +70,72 @@ func manageFilesFunc(homeConfigDirectory string) fs.WalkDirFunc {
}
func ensureSymlink(source, dest string) error {
absolutePathErrorMessageFormat := "unable to get the absolute path to %s: %w"
absoluteSourcePath, err := filepath.Abs(source)
if err != nil {
return fmt.Errorf(absolutePathErrorMessageFormat, source, err)
}
absoluteDestPath, err := filepath.Abs(dest)
if err != nil {
return fmt.Errorf(absolutePathErrorMessageFormat, dest, err)
}
destInfo, err := os.Lstat(absoluteDestPath)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
fmt.Printf("Linking %s to %s\n", absoluteDestPath, absoluteSourcePath)
if err := os.Symlink(absoluteSourcePath, absoluteDestPath); err != nil {
return fmt.Errorf(
"unable to symlink %s to %s: %w",
absoluteDestPath,
absoluteSourcePath,
err,
)
}
return nil
}
return fmt.Errorf("unable to get the file info for %s: %w", absoluteDestPath, err)
}
if destInfo.Mode().Type() != fs.ModeSymlink {
return fmt.Errorf("the path %s exists but it is not a symlink", absoluteDestPath)
}
destLinksTo, err := filepath.EvalSymlinks(absoluteDestPath)
if err != nil {
return fmt.Errorf("unable to evaluate the symlink %s: %w", absoluteDestPath, err)
}
if destLinksTo == absoluteSourcePath {
return nil
}
fmt.Printf(
"%s should link back to %s but instead links back to %s\n",
absoluteDestPath,
absoluteSourcePath,
destLinksTo,
)
fmt.Println("Recreating:", absoluteDestPath)
if err := os.Remove(absoluteDestPath); err != nil {
return fmt.Errorf("unable to remove %s: %w", absoluteDestPath, err)
}
if err := os.Symlink(absoluteSourcePath, absoluteDestPath); err != nil {
return fmt.Errorf(
"unable to symlink %s to %s: %w",
absoluteDestPath,
absoluteSourcePath,
err,
)
}
return nil
}