| 45 | } |
| 46 | |
| 47 | func parseUsageSubCommand(args []string, text *preparedText) (res []string) { |
| 48 | var words []string |
| 49 | foundUsage := false |
| 50 | |
| 51 | // First of all we split the first paragraph of help into words |
| 52 | // and make sure that first word is `usage` |
| 53 | for _, line := range text.lines { |
| 54 | curWords := wordRegexp.FindAllString(line, -1) |
| 55 | if curWords == nil { |
| 56 | break |
| 57 | } |
| 58 | if !foundUsage { |
| 59 | if strings.ToLower(curWords[0]) != "usage:" && |
| 60 | strings.ToLower(curWords[0]) != "usage" { |
| 61 | return |
| 62 | } |
| 63 | foundUsage = true |
| 64 | // Don't need `usage word` |
| 65 | words = append(words, curWords[1:]...) |
| 66 | continue |
| 67 | } |
| 68 | words = append(words, curWords...) |
| 69 | } |
| 70 | |
| 71 | // Then we make sure that the first word after usage is name of application (we check only basename). |
| 72 | executableBase := path.Base(args[0]) |
| 73 | if words == nil || len(words) < 1 { |
| 74 | return |
| 75 | } |
| 76 | |
| 77 | if path.Base(words[0]) != executableBase { |
| 78 | return |
| 79 | } |
| 80 | |
| 81 | argsIdx := 1 |
| 82 | wordIdx := 1 |
| 83 | |
| 84 | // We iterate over words of usage paragraph until we find the word that can't be sub-command. |
| 85 | // We check each word in actual command line to double check that it's actual sub-command used. |
| 86 | outerLoop: |
| 87 | for ; wordIdx < len(words); wordIdx += 1 { |
| 88 | w := words[wordIdx] |
| 89 | if !subCommandRegexp.MatchString(w) { |
| 90 | wordIdx += 1 |
| 91 | break |
| 92 | } |
| 93 | for ; argsIdx < len(args); argsIdx += 1 { |
| 94 | if w == args[wordIdx] { |
| 95 | res = append(res, w) |
| 96 | continue outerLoop |
| 97 | } |
| 98 | } |
| 99 | res = nil |
| 100 | break |
| 101 | } |
| 102 | |
| 103 | if res == nil { |
| 104 | return |