Skip to content

Commit

Permalink
Run with internal flag when saving with sudo on Windows
Browse files Browse the repository at this point in the history
  • Loading branch information
niten94 committed Dec 17, 2024
1 parent 8cdf68b commit 1e7ed82
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
28 changes: 28 additions & 0 deletions cmd/micro/micro.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand All @@ -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)
Expand Down
15 changes: 11 additions & 4 deletions internal/buffer/save.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit 1e7ed82

Please sign in to comment.