Debian Codegraph @

lib/open.go

raw
1 package lib
2
3 import (
4 "fmt"
5 "os/exec"
6 "runtime"
7 "strings"
8
9 "git.sr.ht/~rjarry/go-opt/v2"
10 "github.com/danwakefield/fnmatch"
11
12 "git.sr.ht/~rjarry/aerc/config"
13 "git.sr.ht/~rjarry/aerc/lib/log"
14 )
15
16 func XDGOpenMime(
17 uri string, mimeType string, args string,
18 ) error {
19 if len(args) == 0 {
20 // no explicit command provided, lookup opener from mime type
21 for _, o := range config.Openers() {
22 if fnmatch.Match(o.Mime, mimeType, 0) {
23 args = o.Args
24 break
25 }
26 }
27 }
28 if len(args) == 0 {
29 // no opener defined in config, fallback to default
30 if runtime.GOOS == "darwin" {
31 args = "open"
32 } else {
33 args = "xdg-open"
34 }
35 }
36
37 // Escape URI special characters
38 uri = opt.QuoteArg(uri)
39 if strings.Contains(args, "{}") {
40 // found {} placeholder in args, replace with uri
41 args = strings.Replace(args, "{}", uri, 1)
42 } else {
43 // no {} placeholder in args, add uri at the end
44 args = args + " " + uri
45 }
46
47 log.Tracef("running command: %v", args)
48 cmd := exec.Command("sh", "-c", args)
49 out, err := cmd.CombinedOutput()
50 log.Debugf("command: %v exited. err=%v out=%s", args, err, out)
51 if err != nil {
52 return fmt.Errorf("%v: %w", args, err)
53 }
54 return nil
55 }