github.com/divan/complete@v0.0.0-20170515130636-337e95201af7/args.go (about) 1 package complete 2 3 import ( 4 "os" 5 "path/filepath" 6 ) 7 8 // Args describes command line arguments 9 type Args struct { 10 // All lists of all arguments in command line (not including the command itself) 11 All []string 12 // Completed lists of all completed arguments in command line, 13 // If the last one is still being typed - no space after it, 14 // it won't appear in this list of arguments. 15 Completed []string 16 // Last argument in command line, the one being typed, if the last 17 // character in the command line is a space, this argument will be empty, 18 // otherwise this would be the last word. 19 Last string 20 // LastCompleted is the last argument that was fully typed. 21 // If the last character in the command line is space, this would be the 22 // last word, otherwise, it would be the word before that. 23 LastCompleted string 24 } 25 26 // Directory gives the directory of the current written 27 // last argument if it represents a file name being written. 28 // in case that it is not, we fall back to the current directory. 29 func (a Args) Directory() string { 30 if info, err := os.Stat(a.Last); err == nil && info.IsDir() { 31 if !filepath.IsAbs(a.Last) { 32 return relativePath(a.Last) 33 } 34 return a.Last 35 } 36 dir := filepath.Dir(a.Last) 37 if info, err := os.Stat(dir); err != nil || !info.IsDir() { 38 return "./" 39 } 40 if !filepath.IsAbs(dir) { 41 dir = relativePath(dir) 42 } 43 return dir 44 } 45 46 func newArgs(line []string) Args { 47 completed := removeLast(line[1:]) 48 return Args{ 49 All: line[1:], 50 Completed: completed, 51 Last: last(line), 52 LastCompleted: last(completed), 53 } 54 } 55 56 func (a Args) from(i int) Args { 57 if i > len(a.All) { 58 i = len(a.All) 59 } 60 a.All = a.All[i:] 61 62 if i > len(a.Completed) { 63 i = len(a.Completed) 64 } 65 a.Completed = a.Completed[i:] 66 return a 67 } 68 69 func removeLast(a []string) []string { 70 if len(a) > 0 { 71 return a[:len(a)-1] 72 } 73 return a 74 } 75 76 func last(args []string) (last string) { 77 if len(args) > 0 { 78 last = args[len(args)-1] 79 } 80 return 81 }