Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CoreUtil* structs to facilitate common behavior #127

Merged
merged 3 commits into from
Jan 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions common/common.v
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,19 @@ import flag

pub const version = '0.0.1'

pub struct CoreutilInfo {
pub:
name string
description string
}

pub struct CoreutilExitDetail {
message string
mut:
return_code int = 1
show_help_advice bool // defaults to false
}

// coreutils_version returns formatted coreutils tool version
pub fn coreutils_version() string {
return '(V coreutils) ${common.version}'
Expand Down Expand Up @@ -46,3 +59,28 @@ pub fn exit_with_error_message(tool_name string, error string) {
eprintln("Try '${tool_name} --help' for more information.")
exit(1)
}

// A common way to exit with a custom error code (default: 1)
// and the ability to direct the user to help (default: false)
// to make it easier to match the output of the GNU coreutils
@[noreturn]
pub fn (app CoreutilInfo) quit(detail CoreutilExitDetail) {
eprintln('${app.name}: ${detail.message}')
if detail.show_help_advice {
eprintln("Try '${app.name} --help' for more information.")
}
exit(detail.return_code)
}

// flag_parser returns a flag.FlagParser, with the common
// options already set, reducing the boilerplate code in
// each individual utility.
pub fn (app CoreutilInfo) make_flag_parser(args []string) &flag.FlagParser {
mut fp := flag.new_flag_parser(args)
fp.version(coreutils_version())
fp.footer(coreutils_footer())
fp.skip_executable()
fp.application(app.name)
fp.description(app.description)
return fp
}
Loading