Adds basic functionality, ignoring needsterminal applications for now

This commit is contained in:
sloumdrone 2019-06-28 22:51:20 -07:00
parent 08cde441c7
commit 834cc175ba
1 changed files with 85 additions and 5 deletions

View File

@ -2,9 +2,12 @@ package mailcap
import (
"os"
"os/exec"
"strings"
"strconv"
"fmt"
"bufio"
"sort"
)
type Entry map[string]string
@ -21,9 +24,8 @@ func NewMailcap() *Mailcap {
}
func (m *Mailcap) ShowAll() {
for k, _ := range m.Caps {
fmt.Println(k)
}
fmt.Print(m.Caps)
fmt.Println()
}
func (m *Mailcap) Show(mime string) {
@ -36,13 +38,91 @@ func (m *Mailcap) Show(mime string) {
}
}
func (m *Mailcap) ShowSourceFiles() {
func (m *Mailcap) ShowFiles() {
for _, s := range getMailcapFileList() {
fmt.Println(s)
fmt.Println("")
}
}
func (m *Mailcap) FindMatch(mime, key, path string) (string, error) {
entries := m.lookup(mime, key)
for _, v := range entries {
exitCode := 0;
if _, ok := v["needsterminal"]; ok {
continue
}
if t, ok := v["test"]; ok {
cmdArgs := strings.Split(t, " ")
if len(cmdArgs) < 2 {
continue
}
com := exec.Command(cmdArgs[0], cmdArgs[1:]...)
if err := com.Run(); err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
exitCode = exitError.ExitCode()
}
}
}
if exitCode != 0 {
continue
}
if val, ok := v[key]; ok {
if strings.Index(val, "%s") >= 0 {
return fmt.Sprintf(val, path), nil
} else {
return val, nil
}
}
}
return "", fmt.Errorf("Unable to find key %q in entries for %s", key, mime)
}
func (m *Mailcap) RunMatch(mime, key, path string) {
match, err := m.FindMatch(mime, key, path)
var command *exec.Cmd
if err == nil {
matchFields := strings.Fields(match)
if len(matchFields) > 1 {
command = exec.Command(matchFields[0], matchFields[1:]...)
} else {
command = exec.Command(match)
}
e := command.Run()
fmt.Println(err)
if e != nil {
fmt.Println("There was an issue...")
}
}
}
func (m *Mailcap) lookup(mime, key string) Fields {
f := make(Fields, 0, 5)
if val, ok := m.Caps[mime]; ok {
f = append(f, val...)
}
splitMime := strings.SplitN(mime,"/",2)
catchAllMime := splitMime[0] + "/*"
if val, ok := m.Caps[catchAllMime]; ok && mime != catchAllMime {
f = append(f, val...)
}
output := make(Fields, 0, len(f))
for _, v := range f {
if _, ok := v[key]; ok {
output = append(output, v)
}
}
sort.SliceStable(
output,
func(i, j int) bool {
return output[i]["lineno"] < output[j]["lineno"]
})
return output
}
func (m *Mailcap) getCaps() {
lnNum := 0
var moreCaps Cap
@ -116,7 +196,7 @@ func readMailcapFile(f *os.File,ln int) (Cap, int) {
continue
}
if ln >= 0 {
fields["lineno"] = string(ln)
fields["lineno"] = strconv.Itoa(ln)
ln += 1
}
types := strings.Split(key, "/")