diff options
author | Teddy Wing | 2020-12-20 02:49:54 +0100 |
---|---|---|
committer | Teddy Wing | 2020-12-20 02:52:24 +0100 |
commit | 4db1ee53efc7481b689ebee69b5381d63fe59419 (patch) | |
tree | 7e833e04e8f69b71228e4100bd6dd29969545130 | |
parent | 3dca44be5342384334020c8f64752caaf86d334d (diff) | |
download | browserenv-4db1ee53efc7481b689ebee69b5381d63fe59419.tar.bz2 |
Handle `%s` format string for URL in `BROWSER` variable
The `BROWSER` environment variable might contain a `%s` format string
that should be replaced by the URL to open. If it's present perform the
replacement. Otherwise, append the URL to the `BROWSER` command as
before.
-rw-r--r-- | browserenv.go | 20 | ||||
-rw-r--r-- | browserenv_unix.go | 1 | ||||
-rw-r--r-- | browserenv_unix_test.go | 12 |
3 files changed, 32 insertions, 1 deletions
diff --git a/browserenv.go b/browserenv.go index f0a6dd8..3f463a2 100644 --- a/browserenv.go +++ b/browserenv.go @@ -6,6 +6,8 @@ import ( "os" "os/exec" "path/filepath" + "regexp" + "strings" "github.com/pkg/browser" ) @@ -13,6 +15,8 @@ import ( var Stderr io.Writer = os.Stderr var Stdout io.Writer = os.Stdout +var percentS = regexp.MustCompile("%s[[:^alpha:]]?") + func OpenFile(path string) error { envCommand := envBrowserCommand() if envCommand != "" { @@ -73,8 +77,22 @@ func browserCommand(command, url string) *exec.Cmd { shell := shellArgs[0] args := shellArgs[1:] - command = fmtBrowserCommand(command, url) + if browserCommandIncludesURL(command) { + command = fmtWithURL(command, url) + } else { + command = fmtBrowserCommand(command, url) + } + args = append(args, command) return exec.Command(shell, args...) } + +func browserCommandIncludesURL(command string) bool { + return percentS.MatchString(command) +} + +func fmtWithURL(command, url string) string { + // TODO: shellescape URL + return strings.ReplaceAll(command, "%s", url) +} diff --git a/browserenv_unix.go b/browserenv_unix.go index e6416f8..e09bd10 100644 --- a/browserenv_unix.go +++ b/browserenv_unix.go @@ -21,5 +21,6 @@ func shell() (args []string) { // TODO func fmtBrowserCommand(browser, url string) string { // TODO: handle %s in browser command + // TODO: handle single quotes in URL return fmt.Sprintf("%s '%s'", browser, url) } diff --git a/browserenv_unix_test.go b/browserenv_unix_test.go index 35af81c..f49444e 100644 --- a/browserenv_unix_test.go +++ b/browserenv_unix_test.go @@ -21,6 +21,18 @@ func TestBrowserCommand(t *testing.T) { "https://duckduckgo.com", "open -a Firefox 'https://duckduckgo.com'", }, + { + "with URL directive at end", + "open -a Firefox %s", + "https://duckduckgo.com", + "open -a Firefox https://duckduckgo.com", + }, + { + "with URL directive in middle", + "open -a Firefox %s --other-arg", + "https://duckduckgo.com", + "open -a Firefox https://duckduckgo.com --other-arg", + }, } for _, test := range tests { |