about summary refs log tree commit diff stats
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/open.go63
-rw-r--r--lib/open_darwin.go21
2 files changed, 51 insertions, 33 deletions
diff --git a/lib/open.go b/lib/open.go
index ebcf878..8a016eb 100644
--- a/lib/open.go
+++ b/lib/open.go
@@ -1,23 +1,62 @@
-// +build !darwin
-
 package lib
 
 import (
 	"os/exec"
+	"runtime"
 )
 
-func OpenFile(filename string, onErr func(error)) {
-	cmd := exec.Command("xdg-open", filename)
-	err := cmd.Start()
-	if err != nil && onErr != nil {
-		onErr(err)
-		return
+var openBin string = "xdg-open"
+
+func init() {
+	if runtime.GOOS == "darwin" {
+		openBin = "open"
+	}
+}
+
+type xdgOpen struct {
+	args  []string
+	errCh chan (error)
+	cmd   *exec.Cmd
+}
+
+// NewXDGOpen returns a handler for opening a file via the system handler xdg-open
+// or comparable tools on other OSs than Linux
+func NewXDGOpen(filename string) *xdgOpen {
+	errch := make(chan error, 1)
+	return &xdgOpen{
+		errCh: errch,
+		args:  []string{filename},
 	}
 
+}
+
+// SetArgs sets additional arguments to the open command prior to the filename
+func (xdg *xdgOpen) SetArgs(args []string) {
+	args = append([]string{}, args...) // don't overwrite array of caller
+	filename := xdg.args[len(xdg.args)-1]
+	xdg.args = append(args, filename)
+}
+
+// Start the open handler.
+// Returns an error if the command could not be started.
+// Use Wait to wait for the commands completion and to check the error.
+func (xdg *xdgOpen) Start() error {
+	xdg.cmd = exec.Command(openBin, xdg.args...)
+	err := xdg.cmd.Start()
+	if err != nil {
+		xdg.errCh <- err // for callers that just check the error from Wait()
+		close(xdg.errCh)
+		return err
+	}
 	go func() {
-		err := cmd.Wait()
-		if err != nil && onErr != nil {
-			onErr(err)
-		}
+		xdg.errCh <- xdg.cmd.Wait()
+		close(xdg.errCh)
 	}()
+	return nil
+}
+
+// Wait for the xdg-open command to complete
+// The xdgOpen must have been started
+func (xdg *xdgOpen) Wait() error {
+	return <-xdg.errCh
 }
diff --git a/lib/open_darwin.go b/lib/open_darwin.go
deleted file mode 100644
index d98c898..0000000
--- a/lib/open_darwin.go
+++ /dev/null
@@ -1,21 +0,0 @@
-package lib
-
-import (
-	"os/exec"
-)
-
-func OpenFile(filename string, onErr func(error)) {
-	cmd := exec.Command("open", filename)
-	err := cmd.Start()
-	if err != nil && onErr != nil {
-		onErr(err)
-		return
-	}
-
-	go func() {
-		err := cmd.Wait()
-		if err != nil && onErr != nil {
-			onErr(err)
-		}
-	}()
-}