aerc/commands/cd.go

67 lines
1.2 KiB
Go
Raw Permalink Normal View History

2019-03-15 03:34:34 +01:00
package commands
import (
"errors"
2019-03-15 15:47:09 +01:00
"os"
"strings"
2019-03-15 03:34:34 +01:00
"git.sr.ht/~rjarry/aerc/widgets"
2019-03-15 15:47:09 +01:00
"github.com/mitchellh/go-homedir"
2019-03-15 03:34:34 +01:00
)
var previousDir string
2019-03-15 03:34:34 +01:00
type ChangeDirectory struct{}
2019-03-15 03:34:34 +01:00
func init() {
register(ChangeDirectory{})
}
func (ChangeDirectory) Aliases() []string {
return []string{"cd"}
}
func (ChangeDirectory) Complete(aerc *widgets.Aerc, args []string) []string {
path := strings.Join(args, " ")
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 03:34:34 +01:00
}
func (ChangeDirectory) Execute(aerc *widgets.Aerc, args []string) error {
if len(args) < 1 {
return errors.New("Usage: cd [directory]")
2019-03-15 03:34:34 +01:00
}
2019-03-15 15:47:09 +01:00
cwd, err := os.Getwd()
if err != nil {
return err
}
target := strings.Join(args[1:], " ")
if target == "" {
target = "~"
} else if target == "-" {
2019-03-15 15:47:09 +01:00
if previousDir == "" {
return errors.New("No previous folder to return to")
2019-03-15 03:34:34 +01:00
} else {
2019-03-15 15:47:09 +01:00
target = previousDir
2019-03-15 03:34:34 +01:00
}
2019-03-15 15:47:09 +01:00
}
target, err = homedir.Expand(target)
if err != nil {
return err
}
if err := os.Chdir(target); err == nil {
previousDir = cwd
aerc.UpdateStatus()
2019-03-15 03:34:34 +01:00
}
2019-03-15 15:47:09 +01:00
return err
2019-03-15 03:34:34 +01:00
}