clean dmenu code

This commit is contained in:
yory8 2019-05-10 09:20:43 +02:00
parent 970e8ad514
commit 9819a71777

View file

@ -15,10 +15,6 @@ func selector(history []string, max int, tool string) error {
selected, err := dmenu(history, max, tool) selected, err := dmenu(history, max, tool)
if err != nil { if err != nil {
if err.Error() == "exit status 1" {
// dmenu exits with this error when no selection done
return nil
}
return err return err
} }
@ -52,30 +48,36 @@ func dmenu(list []string, max int, tool string) (string, error) {
} }
// dmenu will break if items contain newlines, so we must pass them as literals. // dmenu will break if items contain newlines, so we must pass them as literals.
// however, when it sends them back, we need a way to restore them to non literals // however, when it sends them back, we need a way to restore them
guide := make(map[string]string) guide := make(map[string]string)
reprList := []string{} escaped := []string{}
for _, original := range list { for _, original := range list {
repr := fmt.Sprintf("%#v", original) repr := fmt.Sprintf("%#v", original)
// dmenu will split lines longer than 1200 something; we cut at 400 to spare memory
max := len(repr) - 1 // drop right quote max := len(repr) - 1 // drop right quote
maxChars := 400 maxChars := 400
// dmenu will split lines longer than 1200 something; we cut at 400 to spare memory
if max > maxChars { if max > maxChars {
max = maxChars max = maxChars
} }
repr = repr[1:max] // drop left quote repr = repr[1:max] // drop left quote
guide[repr] = original guide[repr] = original
reprList = append(reprList, repr) escaped = append(escaped, repr)
} }
input := strings.NewReader(strings.Join(reprList, "\n")) input := strings.NewReader(strings.Join(escaped, "\n"))
cmd := exec.Cmd{Path: bin, Args: args, Stdin: input} cmd := exec.Cmd{Path: bin, Args: args, Stdin: input}
selected, err := cmd.Output() selected, err := cmd.Output()
if err != nil { if err != nil {
if err.Error() == "exit status 1" {
// dmenu exits with this error when no selection done
return "", nil
}
return "", err return "", err
} }
trimmed := selected[:len(selected)-1] // drop newline trimmed := selected[:len(selected)-1] // drop newline added by dmenu
sel, ok := guide[string(trimmed)] sel, ok := guide[string(trimmed)]
if !ok { if !ok {