From 1e7ed8217a2fdd11085be10c4f238526d6ca7dd1 Mon Sep 17 00:00:00 2001 From: niten94 <127052329+niten94@users.noreply.github.com> Date: Tue, 17 Dec 2024 12:33:55 +0800 Subject: [PATCH] Run with internal flag when saving with sudo on Windows --- cmd/micro/micro.go | 28 ++++++++++++++++++++++++++++ internal/buffer/save.go | 15 +++++++++++---- 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/cmd/micro/micro.go b/cmd/micro/micro.go index 4445a34812..94da6394fa 100644 --- a/cmd/micro/micro.go +++ b/cmd/micro/micro.go @@ -38,6 +38,7 @@ var ( flagProfile = flag.Bool("profile", false, "Enable CPU profiling (writes profile info to ./micro.prof)") flagPlugin = flag.String("plugin", "", "Plugin command") flagClean = flag.Bool("clean", false, "Clean configuration directory") + flagWrite = flag.String("write", "", "Write file (internal)") optionFlags map[string]*string sighup chan os.Signal @@ -223,6 +224,25 @@ func LoadInput(args []string) []*buffer.Buffer { return buffers } +func write(name string) (err error) { + var f *os.File + + if f, err = os.OpenFile(*flagWrite, os.O_WRONLY|os.O_CREATE, 0666); err != nil { + return + } + if err = f.Truncate(0); err != nil { + return + } + if _, err = io.Copy(f, os.Stdin); err != nil { + return + } + if err = f.Close(); err != nil { + return + } + + return +} + func main() { defer func() { if util.Stdout.Len() > 0 { @@ -246,6 +266,14 @@ func main() { defer pprof.StopCPUProfile() } + if *flagWrite != "" { + if err := write(*flagWrite); err != nil { + fmt.Println(err) + os.Exit(1) + } + return + } + InitLog() err = config.InitConfigDir(*flagConfigDir) diff --git a/internal/buffer/save.go b/internal/buffer/save.go index af1d9deb26..abb7dc699f 100644 --- a/internal/buffer/save.go +++ b/internal/buffer/save.go @@ -34,7 +34,17 @@ func overwriteFile(name string, enc encoding.Encoding, fn func(io.Writer) error, var c chan os.Signal if withSudo { - cmd = exec.Command(config.GlobalSettings["sucmd"].(string), "dd", "bs=4k", "of="+name) + sucmd := config.GlobalSettings["sucmd"].(string) + if runtime.GOOS == "windows" { + exe, err := os.Executable() + if err == nil { + cmd = exec.Command(sucmd, exe, "-write", name) + } else { + return err + } + } else { + cmd = exec.Command(sucmd, "dd", "bs=4k", "of="+name) + } if writeCloser, err = cmd.StdinPipe(); err != nil { return @@ -130,9 +140,6 @@ func (b *Buffer) saveToFile(filename string, withSudo bool, autoSave bool) error if b.Type.Scratch { return errors.New("Cannot save scratch buffer") } - if withSudo && runtime.GOOS == "windows" { - return errors.New("Save with sudo not supported on Windows") - } if !autoSave && b.Settings["rmtrailingws"].(bool) { for i, l := range b.lines {