complete/args.go

82 lines
1.9 KiB
Go
Raw Normal View History

2017-05-11 10:49:59 -05:00
package complete
2017-05-12 16:17:48 -05:00
import (
"os"
"path/filepath"
)
2017-05-11 12:28:31 -05:00
// Args describes command line arguments
type Args struct {
2017-05-12 07:19:47 -05:00
// All lists of all arguments in command line (not including the command itself)
All []string
2017-05-12 07:19:47 -05:00
// Completed lists of all completed arguments in command line,
// If the last one is still being typed - no space after it,
// it won't appear in this list of arguments.
Completed []string
2017-05-12 07:19:47 -05:00
// Last argument in command line, the one being typed, if the last
// character in the command line is a space, this argument will be empty,
// otherwise this would be the last word.
Last string
2017-05-12 07:19:47 -05:00
// LastCompleted is the last argument that was fully typed.
// If the last character in the command line is space, this would be the
// last word, otherwise, it would be the word before that.
2017-05-11 12:28:31 -05:00
LastCompleted string
2017-05-11 10:49:59 -05:00
}
2017-05-12 16:17:48 -05:00
// Directory gives the directory of the current written
// last argument if it represents a file name being written.
// in case that it is not, we fall back to the current directory.
func (a Args) Directory() string {
if info, err := os.Stat(a.Last); err == nil && info.IsDir() {
2017-05-13 14:44:36 -05:00
if !filepath.IsAbs(a.Last) {
return relativePath(a.Last)
}
2017-05-12 16:17:48 -05:00
return a.Last
}
dir := filepath.Dir(a.Last)
2017-05-13 14:44:36 -05:00
if info, err := os.Stat(dir); err != nil || !info.IsDir() {
2017-05-12 16:17:48 -05:00
return "./"
}
2017-05-13 14:44:36 -05:00
if !filepath.IsAbs(dir) {
dir = relativePath(dir)
}
2017-05-12 16:17:48 -05:00
return dir
}
2017-05-11 12:28:31 -05:00
func newArgs(line []string) Args {
2017-05-13 14:44:36 -05:00
completed := removeLast(line[1:])
2017-05-11 12:28:31 -05:00
return Args{
All: line[1:],
Completed: completed,
Last: last(line),
LastCompleted: last(completed),
2017-05-11 10:49:59 -05:00
}
}
2017-05-11 12:28:31 -05:00
func (a Args) from(i int) Args {
2017-05-13 14:44:36 -05:00
if i > len(a.All) {
i = len(a.All)
}
2017-05-11 12:28:31 -05:00
a.All = a.All[i:]
2017-05-13 14:44:36 -05:00
if i > len(a.Completed) {
i = len(a.Completed)
}
2017-05-11 12:28:31 -05:00
a.Completed = a.Completed[i:]
2017-05-11 10:49:59 -05:00
return a
}
func removeLast(a []string) []string {
if len(a) > 0 {
return a[:len(a)-1]
}
return a
}
func last(args []string) (last string) {
if len(args) > 0 {
last = args[len(args)-1]
}
return
}