~juju-qa/ubuntu/xenial/juju/xenial-2.0-beta3

« back to all changes in this revision

Viewing changes to src/github.com/juju/webbrowser/webbrowser.go

  • Committer: Martin Packman
  • Date: 2016-03-30 19:31:08 UTC
  • mfrom: (1.1.41)
  • Revision ID: martin.packman@canonical.com-20160330193108-h9iz3ak334uk0z5r
Merge new upstream source 2.0~beta3

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// Copyright 2016 Canonical Ltd.
 
2
// Licensed under the LGPLv3, see LICENCE file for details.
 
3
 
 
4
package webbrowser
 
5
 
 
6
import (
 
7
        "errors"
 
8
        "net/url"
 
9
        "os"
 
10
        "os/exec"
 
11
        "runtime"
 
12
        "strings"
 
13
)
 
14
 
 
15
// Open opens a web browser at the given URL.
 
16
// If the OS is not recognized, an ErrNoBrowser is returned.
 
17
func Open(url *url.URL) error {
 
18
        var args []string
 
19
        if runtime.GOOS == "windows" {
 
20
                // Windows is special because the start command is built into cmd.exe
 
21
                // and hence requires the argument to be quoted.
 
22
                args = []string{"cmd", "/c", "start", winCmdQuote.Replace(url.String())}
 
23
        } else if b := browser[runtime.GOOS]; b != "" {
 
24
                args = []string{b, url.String()}
 
25
        } else {
 
26
                return ErrNoBrowser
 
27
        }
 
28
        cmd := exec.Command(args[0], args[1:]...)
 
29
        cmd.Stdout = os.Stdout
 
30
        cmd.Stderr = os.Stderr
 
31
        cmd.Start()
 
32
        go cmd.Wait()
 
33
        return nil
 
34
}
 
35
 
 
36
// ErrNoBrowser is returned when a browser cannot be found for the current OS.
 
37
var ErrNoBrowser = errors.New("cannot find a browser to open the web page")
 
38
 
 
39
var browser = map[string]string{
 
40
        "linux":   "sensible-browser",
 
41
        "darwin":  "open",
 
42
        "freebsd": "xdg-open",
 
43
        "netbsd":  "xdg-open",
 
44
        "openbsd": "xdg-open",
 
45
}
 
46
 
 
47
// winCmdQuote can quote metacharacters special to the Windows
 
48
// cmd.exe command interpreter. It does that by inserting
 
49
// a '^' character before each metacharacter. Note that
 
50
// most of these cannot actually be produced by URL.String,
 
51
// but we include them for completeness.
 
52
var winCmdQuote = strings.NewReplacer(
 
53
        "&", "^&",
 
54
        "%", "^%",
 
55
        "(", "^(",
 
56
        ")", "^)",
 
57
        "^", "^^",
 
58
        "<", "^<",
 
59
        ">", "^>",
 
60
        "|", "^|",
 
61
)