Skip to content

Commit

Permalink
feat: add work in progress cli package
Browse files Browse the repository at this point in the history
  • Loading branch information
serkonda7 committed Dec 26, 2023
1 parent 5224f99 commit 1857f5d
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 1 deletion.
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ _unreleased_
- Handle skips for lib tests

### Standard Library
- Add quite minimal `time` package
- Add work in progress `time` package
- Add work in progress `cli` package
- Add `bait.util.timers` to aid with performance measurements
- builtin:
- New string method `is_capital() bool`
Expand Down
84 changes: 84 additions & 0 deletions lib/cli/cli.bt
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// SPDX-FileCopyrightText: 2023-present Lukas Neubert <[email protected]>
// SPDX-License-Identifier: MPL-2.0
package cli

import strings

type Callback := fun (Command)

pub struct Command {
name string
exec Callback
required_args []string
mut:
nr_required_args i32
pub mut:
options []Option
args []string
}

pub struct Option {
name string
mut:
found bool
}

pub fun (mut cmd Command) parse(args []string) {
if cmd.nr_required_args < cmd.required_args.length {
cmd.nr_required_args = cmd.required_args.length
}

for i := 0; i < args.length; i += 1 {
arg := args[i]
if arg.starts_with('--') {
// FIXME this should require cmd.options to be mutable as well
for mut opt in cmd.options {
if arg.ends_with(opt.name) {
opt.found = true
break
}
}
} else {
cmd.args.push(arg)
}
}

if cmd.nr_required_args > cmd.args.length {
eprintln('error: missing required arguments')
eprintln(cmd.get_help_text())
exit(1)
}

cmd.exec(cmd)
}

fun (cmd Command) get_help_text() string {
mut help := strings.new_builder(100)
help.write('Usage: ')
help.write(cmd.name)

for i := 0; i < cmd.nr_required_args; i += 1 {
if i < cmd.required_args.length {
help.write(' <')
help.write(cmd.required_args[i])
help.write('>')
} else {
help.write(' <arg>')
}
}

if cmd.options.length > 0 {
help.write(' [options]')
}

return help.str()
}

fun (options []Option) is_set(name string) bool {
for opt in options {
if opt.found and opt.name == name {
return true
}
}
return false
}

0 comments on commit 1857f5d

Please sign in to comment.