2019-03-15 02:34:34 +00:00
|
|
|
package commands
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2019-03-15 14:47:09 +00:00
|
|
|
"os"
|
2019-07-30 19:10:58 +00:00
|
|
|
"strings"
|
2019-03-15 02:34:34 +00:00
|
|
|
|
2021-11-05 09:19:46 +00:00
|
|
|
"git.sr.ht/~rjarry/aerc/widgets"
|
2019-03-15 14:47:09 +00:00
|
|
|
"github.com/mitchellh/go-homedir"
|
2019-03-15 02:34:34 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2019-03-15 14:47:09 +00:00
|
|
|
previousDir string
|
2019-03-15 02:34:34 +00:00
|
|
|
)
|
|
|
|
|
2019-06-27 17:33:11 +00:00
|
|
|
type ChangeDirectory struct{}
|
|
|
|
|
2019-03-15 02:34:34 +00:00
|
|
|
func init() {
|
2019-06-27 17:33:11 +00:00
|
|
|
register(ChangeDirectory{})
|
|
|
|
}
|
|
|
|
|
2019-09-03 19:34:03 +00:00
|
|
|
func (ChangeDirectory) Aliases() []string {
|
2019-06-27 17:33:11 +00:00
|
|
|
return []string{"cd"}
|
|
|
|
}
|
|
|
|
|
2019-09-03 19:34:03 +00:00
|
|
|
func (ChangeDirectory) Complete(aerc *widgets.Aerc, args []string) []string {
|
2019-09-20 16:16:29 +00:00
|
|
|
path := strings.Join(args, " ")
|
2019-07-30 19:10:58 +00:00
|
|
|
completions := CompletePath(path)
|
|
|
|
|
|
|
|
var dirs []string
|
|
|
|
for _, c := range completions {
|
|
|
|
// filter out non-directories
|
|
|
|
if strings.HasSuffix(c, "/") {
|
|
|
|
dirs = append(dirs, c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return dirs
|
2019-03-15 02:34:34 +00:00
|
|
|
}
|
|
|
|
|
2019-09-03 19:34:03 +00:00
|
|
|
func (ChangeDirectory) Execute(aerc *widgets.Aerc, args []string) error {
|
2019-09-20 16:16:29 +00:00
|
|
|
if len(args) < 1 {
|
2019-06-05 06:58:40 +00:00
|
|
|
return errors.New("Usage: cd [directory]")
|
2019-03-15 02:34:34 +00:00
|
|
|
}
|
2019-03-15 14:47:09 +00:00
|
|
|
cwd, err := os.Getwd()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-09-20 16:16:29 +00:00
|
|
|
target := strings.Join(args[1:], " ")
|
|
|
|
if target == "" {
|
2019-06-05 06:58:40 +00:00
|
|
|
target = "~"
|
2019-09-20 16:16:29 +00:00
|
|
|
} else if target == "-" {
|
2019-03-15 14:47:09 +00:00
|
|
|
if previousDir == "" {
|
|
|
|
return errors.New("No previous folder to return to")
|
2019-03-15 02:34:34 +00:00
|
|
|
} else {
|
2019-03-15 14:47:09 +00:00
|
|
|
target = previousDir
|
2019-03-15 02:34:34 +00:00
|
|
|
}
|
2019-03-15 14:47:09 +00:00
|
|
|
}
|
|
|
|
target, err = homedir.Expand(target)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := os.Chdir(target); err == nil {
|
|
|
|
previousDir = cwd
|
2019-03-15 02:34:34 +00:00
|
|
|
}
|
2019-03-15 14:47:09 +00:00
|
|
|
return err
|
2019-03-15 02:34:34 +00:00
|
|
|
}
|