Skip to content

Instantly share code, notes, and snippets.

@dpinela
Last active July 7, 2019 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpinela/48a613ac7140ae3d8ce7348749f3fa06 to your computer and use it in GitHub Desktop.
Save dpinela/48a613ac7140ae3d8ce7348749f3fa06 to your computer and use it in GitHub Desktop.
Conversion of github.com/dpinela/mflg to use try
diff --git a/application.go b/application.go
index 0dd4012..f689a24 100644
--- a/application.go
+++ b/application.go
@@ -118,15 +118,11 @@ func (app *application) navigateTo(where string) error {
if app.filename != "" {
filename = filepath.Join(filepath.Dir(app.filename), filename)
} else {
- if filename, err = filepath.Abs(filename); err != nil {
- return err
- }
+ filename = try(filepath.Abs(filename))
}
}
}
- if err := app.gotoFile(filename); err != nil {
- return err
- }
+ try(app.gotoFile(filename))
switch {
case regex != nil:
app.mainWindow.searchRegexp(regex, 0)
@@ -269,9 +265,7 @@ func (app *application) back() error {
}
s := app.navStack
loc := s[len(s)-1]
- if err := app.gotoFile(loc.filename); err != nil {
- return err
- }
+ try(app.gotoFile(loc.filename))
app.mainWindow.gotoTextPos(loc.pos)
app.navStack = s[:len(s)-1]
return nil
@@ -311,9 +305,7 @@ func (app *application) run(in io.Reader, resizeSignal <-chan os.Signal, out io.
}
}()
for {
- if err := app.redraw(out); err != nil {
- return err
- }
+ try(app.redraw(out))
aw := app.activeWindow()
fsEvents, fsWatchErrors := app.fsWatcherChannels()
select {
@@ -552,39 +544,27 @@ func (app *application) promptYOffset() int {
}
func (app *application) redraw(console io.Writer) error {
- var err error
- if err := app.mainWindow.redraw(console); err != nil {
- return err
- }
+ try(app.mainWindow.redraw(console))
switch {
case app.promptWindow != nil:
- err = app.promptWindow.redrawAtYOffset(console, app.promptYOffset())
+ try(app.promptWindow.redrawAtYOffset(console, app.promptYOffset()))
case app.note != "":
- _, err = console.Write([]byte(termesc.SetCursorPos(app.height, 0) + styleResetToBold + ellipsify(app.note, app.width)))
- }
- if err != nil {
- return err
+ try(console.Write([]byte(termesc.SetCursorPos(app.height, 0) + styleResetToBold + ellipsify(app.note, app.width))))
}
if app.titleNeedsRedraw {
- if _, err := console.Write([]byte(termesc.SetTitle(app.filename))); err != nil {
- return err
- }
+ try(console.Write([]byte(termesc.SetTitle(app.filename))))
app.titleNeedsRedraw = false
}
nowVisible := app.activeWindow().cursorInViewport()
defer func() { app.cursorVisible = nowVisible }()
if nowVisible {
if !app.cursorVisible {
- if _, err := console.Write([]byte(termesc.ShowCursor)); err != nil {
- return err
- }
+ try(console.Write([]byte(termesc.ShowCursor)))
}
p := app.cursorPos()
- _, err = console.Write([]byte(termesc.SetCursorPos(p.Y+1, p.X+app.activeWindow().gutterWidth()+1)))
- return err
+ try(console.Write([]byte(termesc.SetCursorPos(p.Y+1, p.X+app.activeWindow().gutterWidth()+1))))
} else if app.cursorVisible {
- _, err = console.Write([]byte(termesc.HideCursor))
- return err
+ try(console.Write([]byte(termesc.HideCursor)))
}
return nil
}
diff --git a/internal/atomicwrite/write.go b/internal/atomicwrite/write.go
index 420dd6d..88017f0 100644
--- a/internal/atomicwrite/write.go
+++ b/internal/atomicwrite/write.go
@@ -20,21 +20,20 @@ const (
// The file is created with mode 0644 if it doesn't already exist; if it does, its permissions will be
// preserved if possible.
// If some of the directories on the path don't already exist, they are created with mode 0755.
-func Write(filename string, contentWriter func(io.Writer) error) error {
+func Write(filename string, contentWriter func(io.Writer) error) (err error) {
+ defer func() { err = errors.WithMessage(err, errString(filename)) }()
+
dir := filepath.Dir(filename)
- if err := os.MkdirAll(dir, defaultDirPerms); err != nil {
- return errors.WithMessage(err, errString(filename))
- }
- tf, err := ioutil.TempFile(dir, "mflg-atomic-write")
- if err != nil {
- return errors.WithMessage(err, errString(filename))
- }
+ try(os.MkdirAll(dir, defaultDirPerms))
+ tf := try(ioutil.TempFile(dir, "mflg-atomic-write"))
name := tf.Name()
- if err = contentWriter(tf); err != nil {
- os.Remove(name)
- tf.Close()
- return errors.WithMessage(err, errString(filename))
- }
+ defer func() {
+ if err != nil {
+ tf.Close()
+ os.Remove(name)
+ }
+ }()
+ try(contentWriter(tf))
// Keep existing file's permissions, when possible. This may race with a chmod() on the file.
perms := defaultPerms
if info, err := os.Stat(filename); err == nil {
@@ -42,14 +41,8 @@ func Write(filename string, contentWriter func(io.Writer) error) error {
}
// It's better to save a file with the default TempFile permissions than not save at all, so if this fails we just carry on.
tf.Chmod(perms)
- if err = tf.Close(); err != nil {
- os.Remove(name)
- return errors.WithMessage(err, errString(filename))
- }
- if err = os.Rename(name, filename); err != nil {
- os.Remove(name)
- return errors.WithMessage(err, errString(filename))
- }
+ try(tf.Close())
+ try(os.Rename(name, filename))
return nil
}
diff --git a/internal/clipboard/clipboard.go b/internal/clipboard/clipboard.go
index fe0e1ab..7e095ed 100644
--- a/internal/clipboard/clipboard.go
+++ b/internal/clipboard/clipboard.go
@@ -49,27 +49,16 @@ func pasteGeneric() ([]byte, error) {
}
func clipboardFilename() (string, error) {
- mflgDir, err := basedir.Data.EnsureDir("mflg", 0700)
- if err != nil {
- return "", err
- }
+ mflgDir := try(basedir.Data.EnsureDir("mflg", 0700))
return filepath.Join(mflgDir, "clipboard"), nil
}
func copyBuiltin(data []byte) error {
- p, err := clipboardFilename()
- if err != nil {
- return err
- }
- return atomicwrite.Write(p, func(w io.Writer) error { _, err := w.Write(data); return err })
+ return atomicwrite.Write(try(clipboardFilename()), func(w io.Writer) error { _, err := w.Write(data); return err })
}
func pasteBuiltin() ([]byte, error) {
- p, err := clipboardFilename()
- if err != nil {
- return nil, err
- }
- return ioutil.ReadFile(p)
+ return ioutil.ReadFile(try(clipboardFilename()))
}
func copyToPasteboard(b []byte) error {
diff --git a/internal/config/config.go b/internal/config/config.go
index 1798cc0..369aac2 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -36,23 +36,22 @@ func (c *Config) ConfigForExt(ext string) LangConfig { return c.Lang[ext] }
// XDG base directory specification for configuration files. It always returns a usable *Config,
// even if it also returns a non-nil error.
// The file is expected to be at mflg/config.toml in one of the appropriate configuration directories.
-func Load() (*Config, error) {
- c := Config{
+func Load() (c *Config, err error) {
+ defer func() { err = errors.WithMessage(err, "error loading config file") }()
+
+ c = &Config{
TabWidth: 4,
ScrollSpeed: 1,
Lang: make(map[string]LangConfig),
}
- f, err := basedir.Config.Open(filepath.Join("mflg", "config.toml"))
- if err != nil {
- return &c, errors.WithMessage(err, "error loading config file")
- }
+ f := try(basedir.Config.Open(filepath.Join("mflg", "config.toml")))
defer f.Close()
- _, err = toml.DecodeReader(f, &c)
+ _, err = toml.DecodeReader(f, c)
if c.TextStyle.Comment == (Style{}) {
c.TextStyle.Comment = Style{Foreground: &color.Color{R: 0, G: 200, B: 0}}
}
if c.TextStyle.String == (Style{}) {
c.TextStyle.String = Style{Foreground: &color.Color{R: 0, G: 0, B: 200}}
}
- return &c, errors.WithMessage(err, "error loading config file")
+ return c, err
}
diff --git a/internal/termesc/term.go b/internal/termesc/term.go
index a419902..dbd8681 100644
--- a/internal/termesc/term.go
+++ b/internal/termesc/term.go
@@ -86,10 +86,7 @@ const escDelay = 10 * time.Millisecond
// ReadToken reads and returns a complete UTF-8 encoded rune or escape sequence.
func (r *ConsoleReader) ReadToken() (string, error) {
r.waitPendingPeek()
- c, _, err := r.r.ReadRune()
- if err != nil {
- return "", err
- }
+ c, _ := try(r.r.ReadRune())
if c != 0x1B {
return string(c), nil
}
diff --git a/render.go b/render.go
index 9b154c1..a16a121 100644
--- a/render.go
+++ b/render.go
@@ -21,9 +21,7 @@ func (w *window) redrawAtYOffset(console io.Writer, yOffset int) error {
if !w.needsRedraw {
return nil
}
- if _, err := fmt.Fprint(console, termesc.SetCursorPos(yOffset+1, 1), termesc.ClearScreenForward); err != nil {
- return err
- }
+ try(fmt.Fprint(console, termesc.SetCursorPos(yOffset+1, 1), termesc.ClearScreenForward))
lines := w.wrappedBuf.Lines(w.topLine, w.topLine+w.height)
var hr []highlight.StyledRegion
if len(lines) != 0 {
@@ -37,9 +35,7 @@ func (w *window) redrawAtYOffset(console io.Writer, yOffset int) error {
buf = tf.formatLine(buf, wy, wy+1 >= w.height)
}
w.drawBuffer = buf[:0] // allow this buffer to be reused next time
- if _, err := console.Write(buf); err != nil {
- return err
- }
+ try(console.Write(buf))
w.needsRedraw = console == nil
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment