Skip to content

Commit

Permalink
extract both
Browse files Browse the repository at this point in the history
  • Loading branch information
itayd committed May 26, 2022
1 parent cd2d8cc commit 162193e
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 49 deletions.
55 changes: 55 additions & 0 deletions both.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package main

import (
"fmt"
"io"
"os"
"os/exec"
)

func both(werr io.Writer, args []string) error {
editor := os.Getenv("EDITOR")
if editor == "" {
return fmt.Errorf("$EDITOR must be set")
}

f, err := os.CreateTemp("", "pounce-")
if err != nil {
return fmt.Errorf("create temp file: %w", err)
}

fname := f.Name()

defer os.Remove(fname)

if err := collect(f, werr, args); err != nil {
return fmt.Errorf("collect: %w", err)
}

if err := f.Close(); err != nil {
return fmt.Errorf("close temp file: %w", err)
}

cmd := exec.Command(editor, fname)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr

if err := cmd.Run(); err != nil {
if err, ok := err.(*exec.ExitError); ok && err != nil {
return fmt.Errorf("editor exited with code %d", err.ExitCode())
}

return fmt.Errorf("run editor %q: %w", editor, err)
}

if f, err = os.Open(fname); err != nil {
return fmt.Errorf("open temp file: %w", err)
}

if err := apply(f); err != nil {
return fmt.Errorf("apply: %w", err)
}

return nil
}
49 changes: 0 additions & 49 deletions pounce.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ package main

import (
"fmt"
"io"
"os"
"os/exec"

"github.com/urfave/cli/v2"
)
Expand Down Expand Up @@ -45,53 +43,6 @@ var app = cli.App{
},
}

func both(werr io.Writer, args []string) error {
editor := os.Getenv("EDITOR")
if editor == "" {
return fmt.Errorf("$EDITOR must be set")
}

f, err := os.CreateTemp("", "pounce-")
if err != nil {
return fmt.Errorf("create temp file: %w", err)
}

fname := f.Name()

defer os.Remove(fname)

if err := collect(f, werr, args); err != nil {
return fmt.Errorf("collect: %w", err)
}

if err := f.Close(); err != nil {
return fmt.Errorf("close temp file: %w", err)
}

cmd := exec.Command(editor, fname)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr

if err := cmd.Run(); err != nil {
if err, ok := err.(*exec.ExitError); ok && err != nil {
return fmt.Errorf("editor exited with code %d", err.ExitCode())
}

return fmt.Errorf("run editor %q: %w", editor, err)
}

if f, err = os.Open(fname); err != nil {
return fmt.Errorf("open temp file: %w", err)
}

if err := apply(f); err != nil {
return fmt.Errorf("apply: %w", err)
}

return nil
}

func main() {
if err := app.Run(os.Args); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
Expand Down

0 comments on commit 162193e

Please sign in to comment.