|
| 1 | +package teautils |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "strconv" |
| 6 | +) |
| 7 | + |
| 8 | +// 命令帮助 |
| 9 | +type CommandHelp struct { |
| 10 | + product string |
| 11 | + version string |
| 12 | + usage string |
| 13 | + options []*CommandHelpOption |
| 14 | + appendStrings []string |
| 15 | +} |
| 16 | + |
| 17 | +func NewCommandHelp() *CommandHelp { |
| 18 | + return &CommandHelp{} |
| 19 | +} |
| 20 | + |
| 21 | +type CommandHelpOption struct { |
| 22 | + Code string |
| 23 | + Description string |
| 24 | +} |
| 25 | + |
| 26 | +// 产品 |
| 27 | +func (this *CommandHelp) Product(product string) *CommandHelp { |
| 28 | + this.product = product |
| 29 | + return this |
| 30 | +} |
| 31 | + |
| 32 | +// 版本 |
| 33 | +func (this *CommandHelp) Version(version string) *CommandHelp { |
| 34 | + this.version = version |
| 35 | + return this |
| 36 | +} |
| 37 | + |
| 38 | +// 使用方法 |
| 39 | +func (this *CommandHelp) Usage(usage string) *CommandHelp { |
| 40 | + this.usage = usage |
| 41 | + return this |
| 42 | +} |
| 43 | + |
| 44 | +// 选项 |
| 45 | +func (this *CommandHelp) Option(code string, description string) *CommandHelp { |
| 46 | + this.options = append(this.options, &CommandHelpOption{ |
| 47 | + Code: code, |
| 48 | + Description: description, |
| 49 | + }) |
| 50 | + return this |
| 51 | +} |
| 52 | + |
| 53 | +// 附加内容 |
| 54 | +func (this *CommandHelp) Append(appendString string) *CommandHelp { |
| 55 | + this.appendStrings = append(this.appendStrings, appendString) |
| 56 | + return this |
| 57 | +} |
| 58 | + |
| 59 | +// 打印 |
| 60 | +func (this *CommandHelp) Print() { |
| 61 | + fmt.Println(this.product + " v" + this.version) |
| 62 | + fmt.Println("Usage:", "\n "+this.usage) |
| 63 | + |
| 64 | + if len(this.options) > 0 { |
| 65 | + fmt.Println("") |
| 66 | + fmt.Println("Options:") |
| 67 | + |
| 68 | + spaces := 20 |
| 69 | + max := 40 |
| 70 | + for _, option := range this.options { |
| 71 | + l := len(option.Code) |
| 72 | + if l < max && l > spaces { |
| 73 | + spaces = l + 4 |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + for _, option := range this.options { |
| 78 | + if len(option.Code) > max { |
| 79 | + fmt.Println("") |
| 80 | + fmt.Println(" " + option.Code) |
| 81 | + option.Code = "" |
| 82 | + } |
| 83 | + |
| 84 | + fmt.Printf(" %-"+strconv.Itoa(spaces)+"s%s\n", option.Code, ": "+option.Description) |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + if len(this.appendStrings) > 0 { |
| 89 | + fmt.Println("") |
| 90 | + for _, s := range this.appendStrings { |
| 91 | + fmt.Println(s) |
| 92 | + } |
| 93 | + } |
| 94 | +} |
0 commit comments