-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfolder_picker.go
More file actions
91 lines (81 loc) · 2.13 KB
/
folder_picker.go
File metadata and controls
91 lines (81 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"errors"
"fmt"
"os/exec"
"runtime"
"strings"
)
var errFolderPickerCanceled = errors.New("folder picker canceled")
type pickerCommand struct {
name string
args []string
}
func pickFolderPath() (string, error) {
commands := pickerCommandsForCurrentOS()
if len(commands) == 0 {
return "", fmt.Errorf("native folder picker is not supported on %s", runtime.GOOS)
}
var available []pickerCommand
for _, command := range commands {
if _, err := exec.LookPath(command.name); err == nil {
available = append(available, command)
}
}
if len(available) == 0 {
return "", fmt.Errorf("no native folder picker found (install zenity or kdialog)")
}
for _, command := range available {
path, err := runPickerCommand(command)
if err == nil {
return path, nil
}
if errors.Is(err, errFolderPickerCanceled) {
return "", err
}
}
return "", fmt.Errorf("failed to open native folder picker")
}
func pickerCommandsForCurrentOS() []pickerCommand {
switch runtime.GOOS {
case "darwin":
return []pickerCommand{{
name: "osascript",
args: []string{"-e", `POSIX path of (choose folder with prompt "Select a Git repository")`},
}}
case "windows":
return []pickerCommand{{
name: "powershell",
args: []string{
"-NoProfile",
"-Command",
"Add-Type -AssemblyName System.Windows.Forms; $dialog = New-Object System.Windows.Forms.FolderBrowserDialog; if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::Write($dialog.SelectedPath) }",
},
}}
default:
return []pickerCommand{
{
name: "zenity",
args: []string{"--file-selection", "--directory", "--title=Select a Git repository"},
},
{
name: "kdialog",
args: []string{"--getexistingdirectory", ".", "Select a Git repository"},
},
}
}
}
func runPickerCommand(command pickerCommand) (string, error) {
out, err := exec.Command(command.name, command.args...).CombinedOutput()
output := strings.TrimSpace(string(out))
if err != nil {
if output == "" {
return "", errFolderPickerCanceled
}
return "", err
}
if output == "" {
return "", errFolderPickerCanceled
}
return output, nil
}