Implement undoing

This commit is contained in:
2025-03-10 18:52:55 +01:00
parent 8c5d783d2c
commit ae1986cb81
2 changed files with 35 additions and 3 deletions

View File

@@ -49,12 +49,36 @@ func (instruction *LinkInstruction) String() string {
flagsStr = " [" + strings.Join(flags, ", ") + "]" flagsStr = " [" + strings.Join(flags, ", ") + "]"
} }
return fmt.Sprintf("%s%s%s → %s%s%s%s", return fmt.Sprintf("%s%s%s",
SourceColor, instruction.Source, DefaultColor, FormatSourcePath(instruction.Source),
TargetColor, instruction.Target, DefaultColor, FormatTargetPath(instruction.Target),
flagsStr) flagsStr)
} }
func (instruction *LinkInstruction) Undo() {
if !FileExists(instruction.Target) {
return
}
isSymlink, err := IsSymlink(instruction.Target)
if err != nil {
LogError("could not determine whether %s is a sym link or not, stopping; err: %v",
FormatTargetPath(instruction.Target), err)
return
}
if isSymlink {
LogInfo("Removing symlink at %s", FormatTargetPath(instruction.Target))
err = os.Remove(instruction.Target)
if err != nil {
LogError("could not remove symlink at %s; err: %v",
FormatTargetPath(instruction.Target), err)
}
} else {
LogInfo("%s is not a symlink, skipping", FormatTargetPath(instruction.Target))
}
}
func ParseInstruction(line, workdir string) (LinkInstruction, error) { func ParseInstruction(line, workdir string) (LinkInstruction, error) {
line = strings.TrimSpace(line) line = strings.TrimSpace(line)
if strings.HasPrefix(line, "#") { if strings.HasPrefix(line, "#") {
@@ -131,6 +155,11 @@ func isTrue(value string) bool {
func (instruction *LinkInstruction) RunAsync(status chan (error)) { func (instruction *LinkInstruction) RunAsync(status chan (error)) {
defer close(status) defer close(status)
if undo {
instruction.Undo()
return
}
if !FileExists(instruction.Source) { if !FileExists(instruction.Source) {
status <- fmt.Errorf("instruction source %s does not exist", FormatSourcePath(instruction.Source)) status <- fmt.Errorf("instruction source %s does not exist", FormatSourcePath(instruction.Source))
return return

View File

@@ -22,12 +22,15 @@ const PathColor = Green
var FileRegex, _ = regexp.Compile(`sync\.ya?ml$`) var FileRegex, _ = regexp.Compile(`sync\.ya?ml$`)
var programName = os.Args[0] var programName = os.Args[0]
var undo = false
func main() { func main() {
recurse := flag.String("r", "", "recurse into directories") recurse := flag.String("r", "", "recurse into directories")
file := flag.String("f", "", "file to read instructions from") file := flag.String("f", "", "file to read instructions from")
debug := flag.Bool("d", false, "debug") debug := flag.Bool("d", false, "debug")
undoF := flag.Bool("u", false, "undo")
flag.Parse() flag.Parse()
undo = *undoF
if *debug { if *debug {
log.SetFlags(log.Lmicroseconds | log.Lshortfile) log.SetFlags(log.Lmicroseconds | log.Lshortfile)