Latest commit

History

68 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Package szargs

Overview

package szargs

Package szargs provides a minimal and consistent interface for retrieving settings from command-line arguments ([]string) and environment variables.

It supports three types of arguments:

  • Flagged: Identified by a single dash (e.g., "-v") for short flags, or a double dash (e.g., "--dir") for long-form flags. Flags may be standalone booleans or followed by a value.
  • Positional: Identified by their order in the argument list after all flagged arguments have been processed.
  • Settings: A composite configuration mechanism that combines a default value, an environment variable, and a flagged argument—allowing each to override the previous in precedence: default < env < flag.

The package includes built-in parsers for standard Go data types.

Usage centers around the Args type, created using:

szargs.New(programDesc string, programArgs []string)

The programArgs slice must include the program name as the first element; this is ignored during argument parsing.

After retrieving all relevant arguments, the Args.Done() method must be called to report an error if any unprocessed arguments remain.

This utility reflects a preference for simplicity and clarity in tooling. If it helps your project flow a little more smoothly, it's done its job.

Dedication

This project is dedicated to Reem. Your brilliance, courage, and quiet strength continue to inspire me. Every line is written in gratitude for the light and hope you brought into my life.

NOTE: Documentation reviewed and polished with the assistance of ChatGPT from OpenAI.


Contents

Usage

Generally the flow of argument extraction proceeds as follows:

funcmain() {
// Create the args object with a program description (that will be used in// the Usage message) and the system arguments. These will be copied// leaving the original os.Args untouched.args:=szargs.New(
"A simple demo of values flag.",
os.Args,
)
// Flagged arguments are then extracted using various methods defined on the// args object.verbose:=args.Count("[-v | --verbose ...]","The verbose level.")
lines:=args.Value("[-n | --num numOfLines]","Number of lines to display.")
// Positional arguments are then extracted.file:=args.Next("filename","The file to display the lines.")
// All expected arguments have now been extracted.args.Done()
ifargs.HasErr() {
//Report any errors and optionally providing a Usage message.fmt.Fprintf(os.Stderr, "Error: %v\n\n%s\n", args.Err(), args.Usage())
} else {
// Process with the arguments.
}
}

General functions operating on the state of the szargs object can be divided into three categories as follows:

Relating to errors:

// HasErr returns true if any errors have been encountered or registered.func (args*Args) HasErr() bool// PushErr registers the provided error if not nil to the Args error stack.func (args*Args) PushErr(errerror)
// Err returns any errors encountered or registered while parsing the// arguments.func (args*Args) Err() error

Relating to the raw argument list:

// HasNext returns true if any arguments remain unabsorbed.func (args*Args) HasNext() bool// PushArg places the supplied argument to the end of the internal args list.func (args*Args) PushArg(argstring)
// Args returns a copy of the current argument list.func (args*Args) Args() []string

And general reporting and processing:

// Usage returns a usage messages representing the Args object. It is// formatted to the lineWidth provided. A zero uses the defaultLineWidth// while a negative value caused an effort to determine if writing to a// terminal and if so using its width otherwise defaulting.func (args*Args) Usage(lineWidthint) string// Done registers an error if there are any remaining arguments.func (args*Args) Done()

A working example can be found in the example directory as described here:

Contents

Boolean Flags

Boolean flags are defined by their presence only. If they are present then they are true and/or counted. If not present then they are considered false. There are two methods that operate with boolean flags as follows:

// Is returns true if the flag is present one and only one time.func (args*Args) Is(flag, descstring) bool// Count returns the number of times the flag appears.func (args*Args) Count(flag, descstring) int

Contents

Value Flagged Arguments

A flagged argument has two components: the flag followed by the value. It may only appear once in the argument list. The basic string functions are:

// ValueString scans for a specific flagged argument and captures its// following value as a string. The flag and its value are removed from the// argument list.// // If the flag appears more than once or lacks a following value, an error is// registered.// // Returns the string value and a boolean indicating whether the flag was// found.func (args*Args) ValueString(flag, descstring) (string, bool)
// ValueOption scans for a specific flagged argument (e.g., "--mode value")// and captures its associated value. The flag and its value are removed from// the argument list.// // If the flag appears more than once, or if it lacks a following value, an// error is registered. If the value is not found in the provided list of// validOptions, an error is also registered.// // Returns the value and a boolean indicating whether the flag was found.func (args*Args) ValueOption(flagstring, validOptions []string, descstring) (string, bool)

with numeric versions for basic go data types

func (args*Args) ValueFloat64(flag, descstring) (float64, bool)
func (args*Args) ValueFloat32(flag, descstring) (float32, bool)
func (args*Args) ValueInt64(flag, descstring) (int64, bool)
func (args*Args) ValueInt32(flag, descstring) (int32, bool)
func (args*Args) ValueInt16(flag, descstring) (int16, bool)
func (args*Args) ValueInt8(flag, descstring) (int8, bool)
func (args*Args) ValueInt(flag, descstring) (int, bool)
func (args*Args) ValueUint64(flag, descstring) (uint64, bool)
func (args*Args) ValueUint32(flag, descstring) (uint32, bool)
func (args*Args) ValueUint16(flag, descstring) (uint16, bool)
func (args*Args) ValueUint8(flag, descstring) (uint8, bool)
func (args*Args) ValueUint(flag, descstring) (uint, bool)

Contents

Value Flagged Slices

A flagged argument has two components: the flag followed by the value. Multiple instances may be provided with all the values collected and returned in a slice. The basic string functions are:

// ValuesString scans for repeated instances of the specified flag and// captures the following values as a slice of strings. The flags and values// are removed from the argument list.// // If any instance of the flag lacks a following value, an error is// registered.// // Returns a slice of the captured string values.func (args*Args) ValuesString(flag, descstring) []string// ValuesOption scans for repeated instances of the specified flag and// captures the following values. Each value must appear in the provided list// of validOptions. The flags and values are removed from the argument list.// // If any flag lacks a following value, or if a value is not found in// validOptions, an error is registered.// // Returns a slice of the captured values.func (args*Args) ValuesOption(flagstring, validOptions []string, descstring) []string

with numeric versions for basic go data types

func (args*Args) ValuesFloat64(flag, descstring) []float64func (args*Args) ValuesFloat32(flag, descstring) []float32func (args*Args) ValuesInt64(flag, descstring) []int64func (args*Args) ValuesInt32(flag, descstring) []int32func (args*Args) ValuesInt16(flag, descstring) []int16func (args*Args) ValuesInt8(flag, descstring) []int8func (args*Args) ValuesInt(flag, descstring) []intfunc (args*Args) ValuesUint64(flag, descstring) []uint64func (args*Args) ValuesUint32(flag, descstring) []uint32func (args*Args) ValuesUint16(flag, descstring) []uint16func (args*Args) ValuesUint8(flag, descstring) []uint8func (args*Args) ValuesUint(flag, descstring) []uint

Contents

Positional Arguments

A positional argument depends on its location in the argument list. Since flagged arguments are not automatically distinguished from positional ones, it is recommended to extract all flagged arguments first—before retrieving positional ones. The basic string functions are:

// NextString removes and returns the next argument from the argument list.// // If no arguments remain, an error is registered.// // Returns the next argument value as a string.func (args*Args) NextString(name, descstring) string// NextOption removes and returns the next argument from the argument list.// The value must match one of the entries in validOptions.// // If no arguments remain, or if the value is not found in validOptions,// an error is registered.// // Returns the next argument value.func (args*Args) NextOption(namestring, validOptions []string, descstring) string

with numeric versions for basic go data types

func (args*Args) NextFloat64(name, descstring) float64func (args*Args) NextFloat32(name, descstring) float32func (args*Args) NextInt64(name, descstring) int64func (args*Args) NextInt32(name, descstring) int32func (args*Args) NextInt16(name, descstring) int16func (args*Args) NextInt8(name, descstring) int8func (args*Args) NextInt(name, descstring) intfunc (args*Args) NextUint64(name, descstring) uint64func (args*Args) NextUint32(name, descstring) uint32func (args*Args) NextUint16(name, descstring) uint16func (args*Args) NextUint8(name, descstring) uint8func (args*Args) NextUint(name, descstring) uint

Contents

Settings

A setting implements an argument that has a default that can be overridden by an system environment variable which can be overridden by a flagged value. The basic string functions are:

// SettingString returns a configuration value based on a default,// optionally overridden by an environment variable, and further overridden// by a flagged command-line argument.// // Returns the final selected string value.func (args*Args) SettingString(flag, env, def, descstring) string// SettingOption returns a configuration value based on a default,// optionally overridden by an environment variable, and further overridden// by a flagged command-line argument.// // If the final value is not found in the list of validOptions,// an error is registered.// // Returns the final selected value.func (args*Args) SettingOption(flag, envstring, defstring, validOptions []string, descstring) string// SettingIs returns true if a specified environment variable is set to a// truthy value, or if a corresponding boolean command-line flag is present.// // Unlike other Setting methods, there is no default.// // The environment variable is considered true if it is set to one of: "",// "T", "Y", "TRUE", "YES", "ON" or "1" (case-insensitive). Any other value is// considered false.// // The command-line flag override takes no value—its presence alone indicates// true.// // Returns the resulting boolean value.func (args*Args) SettingIs(flag, envstring, descstring) bool

with numeric versions for basic go data types

func (args*Args) SettingFloat64(flag, envstring, deffloat64, descstring) float64func (args*Args) SettingFloat32(flag, envstring, deffloat32, descstring) float32func (args*Args) SettingInt64(flag, envstring, defint64, descstring) int64func (args*Args) SettingInt32(flag, envstring, defint32, descstring) int32func (args*Args) SettingInt16(flag, envstring, defint16, descstring) int16func (args*Args) SettingInt8(flag, envstring, defint8, descstring) int8func (args*Args) SettingInt(flag, envstring, defint, descstring) intfunc (args*Args) SettingUint64(flag, envstring, defuint64, descstring) uint64func (args*Args) SettingUint32(flag, envstring, defuint32, descstring) uint32func (args*Args) SettingUint16(flag, envstring, defuint16, descstring) uint16func (args*Args) SettingUint8(flag, envstring, defuint8, descstring) uint8func (args*Args) SettingUint(flag, envstring, defuint, descstring) uint

Contents

About

Simple command line argument management.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

68 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Package szargs

Overview

package szargs

Package szargs provides a minimal and consistent interface for retrieving settings from command-line arguments ([]string) and environment variables.

It supports three types of arguments:

  • Flagged: Identified by a single dash (e.g., "-v") for short flags, or a double dash (e.g., "--dir") for long-form flags. Flags may be standalone booleans or followed by a value.
  • Positional: Identified by their order in the argument list after all flagged arguments have been processed.
  • Settings: A composite configuration mechanism that combines a default value, an environment variable, and a flagged argument—allowing each to override the previous in precedence: default < env < flag.

The package includes built-in parsers for standard Go data types.

Usage centers around the Args type, created using:

szargs.New(programDesc string, programArgs []string)

The programArgs slice must include the program name as the first element; this is ignored during argument parsing.

After retrieving all relevant arguments, the Args.Done() method must be called to report an error if any unprocessed arguments remain.

This utility reflects a preference for simplicity and clarity in tooling. If it helps your project flow a little more smoothly, it's done its job.

Dedication

This project is dedicated to Reem. Your brilliance, courage, and quiet strength continue to inspire me. Every line is written in gratitude for the light and hope you brought into my life.

NOTE: Documentation reviewed and polished with the assistance of ChatGPT from OpenAI.


Contents

Usage

Generally the flow of argument extraction proceeds as follows:

funcmain() {
// Create the args object with a program description (that will be used in// the Usage message) and the system arguments. These will be copied// leaving the original os.Args untouched.args:=szargs.New(
"A simple demo of values flag.",
os.Args,
)
// Flagged arguments are then extracted using various methods defined on the// args object.verbose:=args.Count("[-v | --verbose ...]","The verbose level.")
lines:=args.Value("[-n | --num numOfLines]","Number of lines to display.")
// Positional arguments are then extracted.file:=args.Next("filename","The file to display the lines.")
// All expected arguments have now been extracted.args.Done()
ifargs.HasErr() {
//Report any errors and optionally providing a Usage message.fmt.Fprintf(os.Stderr, "Error: %v\n\n%s\n", args.Err(), args.Usage())
} else {
// Process with the arguments.
}
}

General functions operating on the state of the szargs object can be divided into three categories as follows:

Relating to errors:

// HasErr returns true if any errors have been encountered or registered.func (args*Args) HasErr() bool// PushErr registers the provided error if not nil to the Args error stack.func (args*Args) PushErr(errerror)
// Err returns any errors encountered or registered while parsing the// arguments.func (args*Args) Err() error

Relating to the raw argument list:

// HasNext returns true if any arguments remain unabsorbed.func (args*Args) HasNext() bool// PushArg places the supplied argument to the end of the internal args list.func (args*Args) PushArg(argstring)
// Args returns a copy of the current argument list.func (args*Args) Args() []string

And general reporting and processing:

// Usage returns a usage messages representing the Args object. It is// formatted to the lineWidth provided. A zero uses the defaultLineWidth// while a negative value caused an effort to determine if writing to a// terminal and if so using its width otherwise defaulting.func (args*Args) Usage(lineWidthint) string// Done registers an error if there are any remaining arguments.func (args*Args) Done()

A working example can be found in the example directory as described here:

Contents

Boolean Flags

Boolean flags are defined by their presence only. If they are present then they are true and/or counted. If not present then they are considered false. There are two methods that operate with boolean flags as follows:

// Is returns true if the flag is present one and only one time.func (args*Args) Is(flag, descstring) bool// Count returns the number of times the flag appears.func (args*Args) Count(flag, descstring) int

Contents

Value Flagged Arguments

A flagged argument has two components: the flag followed by the value. It may only appear once in the argument list. The basic string functions are:

// ValueString scans for a specific flagged argument and captures its// following value as a string. The flag and its value are removed from the// argument list.// // If the flag appears more than once or lacks a following value, an error is// registered.// // Returns the string value and a boolean indicating whether the flag was// found.func (args*Args) ValueString(flag, descstring) (string, bool)
// ValueOption scans for a specific flagged argument (e.g., "--mode value")// and captures its associated value. The flag and its value are removed from// the argument list.// // If the flag appears more than once, or if it lacks a following value, an// error is registered. If the value is not found in the provided list of// validOptions, an error is also registered.// // Returns the value and a boolean indicating whether the flag was found.func (args*Args) ValueOption(flagstring, validOptions []string, descstring) (string, bool)

with numeric versions for basic go data types

func (args*Args) ValueFloat64(flag, descstring) (float64, bool)
func (args*Args) ValueFloat32(flag, descstring) (float32, bool)
func (args*Args) ValueInt64(flag, descstring) (int64, bool)
func (args*Args) ValueInt32(flag, descstring) (int32, bool)
func (args*Args) ValueInt16(flag, descstring) (int16, bool)
func (args*Args) ValueInt8(flag, descstring) (int8, bool)
func (args*Args) ValueInt(flag, descstring) (int, bool)
func (args*Args) ValueUint64(flag, descstring) (uint64, bool)
func (args*Args) ValueUint32(flag, descstring) (uint32, bool)
func (args*Args) ValueUint16(flag, descstring) (uint16, bool)
func (args*Args) ValueUint8(flag, descstring) (uint8, bool)
func (args*Args) ValueUint(flag, descstring) (uint, bool)

Contents

Value Flagged Slices

A flagged argument has two components: the flag followed by the value. Multiple instances may be provided with all the values collected and returned in a slice. The basic string functions are:

// ValuesString scans for repeated instances of the specified flag and// captures the following values as a slice of strings. The flags and values// are removed from the argument list.// // If any instance of the flag lacks a following value, an error is// registered.// // Returns a slice of the captured string values.func (args*Args) ValuesString(flag, descstring) []string// ValuesOption scans for repeated instances of the specified flag and// captures the following values. Each value must appear in the provided list// of validOptions. The flags and values are removed from the argument list.// // If any flag lacks a following value, or if a value is not found in// validOptions, an error is registered.// // Returns a slice of the captured values.func (args*Args) ValuesOption(flagstring, validOptions []string, descstring) []string

with numeric versions for basic go data types

func (args*Args) ValuesFloat64(flag, descstring) []float64func (args*Args) ValuesFloat32(flag, descstring) []float32func (args*Args) ValuesInt64(flag, descstring) []int64func (args*Args) ValuesInt32(flag, descstring) []int32func (args*Args) ValuesInt16(flag, descstring) []int16func (args*Args) ValuesInt8(flag, descstring) []int8func (args*Args) ValuesInt(flag, descstring) []intfunc (args*Args) ValuesUint64(flag, descstring) []uint64func (args*Args) ValuesUint32(flag, descstring) []uint32func (args*Args) ValuesUint16(flag, descstring) []uint16func (args*Args) ValuesUint8(flag, descstring) []uint8func (args*Args) ValuesUint(flag, descstring) []uint

Contents

Positional Arguments

A positional argument depends on its location in the argument list. Since flagged arguments are not automatically distinguished from positional ones, it is recommended to extract all flagged arguments first—before retrieving positional ones. The basic string functions are:

// NextString removes and returns the next argument from the argument list.// // If no arguments remain, an error is registered.// // Returns the next argument value as a string.func (args*Args) NextString(name, descstring) string// NextOption removes and returns the next argument from the argument list.// The value must match one of the entries in validOptions.// // If no arguments remain, or if the value is not found in validOptions,// an error is registered.// // Returns the next argument value.func (args*Args) NextOption(namestring, validOptions []string, descstring) string

with numeric versions for basic go data types

func (args*Args) NextFloat64(name, descstring) float64func (args*Args) NextFloat32(name, descstring) float32func (args*Args) NextInt64(name, descstring) int64func (args*Args) NextInt32(name, descstring) int32func (args*Args) NextInt16(name, descstring) int16func (args*Args) NextInt8(name, descstring) int8func (args*Args) NextInt(name, descstring) intfunc (args*Args) NextUint64(name, descstring) uint64func (args*Args) NextUint32(name, descstring) uint32func (args*Args) NextUint16(name, descstring) uint16func (args*Args) NextUint8(name, descstring) uint8func (args*Args) NextUint(name, descstring) uint

Contents

Settings

A setting implements an argument that has a default that can be overridden by an system environment variable which can be overridden by a flagged value. The basic string functions are:

// SettingString returns a configuration value based on a default,// optionally overridden by an environment variable, and further overridden// by a flagged command-line argument.// // Returns the final selected string value.func (args*Args) SettingString(flag, env, def, descstring) string// SettingOption returns a configuration value based on a default,// optionally overridden by an environment variable, and further overridden// by a flagged command-line argument.// // If the final value is not found in the list of validOptions,// an error is registered.// // Returns the final selected value.func (args*Args) SettingOption(flag, envstring, defstring, validOptions []string, descstring) string// SettingIs returns true if a specified environment variable is set to a// truthy value, or if a corresponding boolean command-line flag is present.// // Unlike other Setting methods, there is no default.// // The environment variable is considered true if it is set to one of: "",// "T", "Y", "TRUE", "YES", "ON" or "1" (case-insensitive). Any other value is// considered false.// // The command-line flag override takes no value—its presence alone indicates// true.// // Returns the resulting boolean value.func (args*Args) SettingIs(flag, envstring, descstring) bool

with numeric versions for basic go data types

func (args*Args) SettingFloat64(flag, envstring, deffloat64, descstring) float64func (args*Args) SettingFloat32(flag, envstring, deffloat32, descstring) float32func (args*Args) SettingInt64(flag, envstring, defint64, descstring) int64func (args*Args) SettingInt32(flag, envstring, defint32, descstring) int32func (args*Args) SettingInt16(flag, envstring, defint16, descstring) int16func (args*Args) SettingInt8(flag, envstring, defint8, descstring) int8func (args*Args) SettingInt(flag, envstring, defint, descstring) intfunc (args*Args) SettingUint64(flag, envstring, defuint64, descstring) uint64func (args*Args) SettingUint32(flag, envstring, defuint32, descstring) uint32func (args*Args) SettingUint16(flag, envstring, defuint16, descstring) uint16func (args*Args) SettingUint8(flag, envstring, defuint8, descstring) uint8func (args*Args) SettingUint(flag, envstring, defuint, descstring) uint

Contents

About

Simple command line argument management.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

68 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Package szargs

Overview

package szargs

Package szargs provides a minimal and consistent interface for retrieving settings from command-line arguments ([]string) and environment variables.

It supports three types of arguments:

  • Flagged: Identified by a single dash (e.g., "-v") for short flags, or a double dash (e.g., "--dir") for long-form flags. Flags may be standalone booleans or followed by a value.
  • Positional: Identified by their order in the argument list after all flagged arguments have been processed.
  • Settings: A composite configuration mechanism that combines a default value, an environment variable, and a flagged argument—allowing each to override the previous in precedence: default < env < flag.

The package includes built-in parsers for standard Go data types.

Usage centers around the Args type, created using:

szargs.New(programDesc string, programArgs []string)

The programArgs slice must include the program name as the first element; this is ignored during argument parsing.

After retrieving all relevant arguments, the Args.Done() method must be called to report an error if any unprocessed arguments remain.

This utility reflects a preference for simplicity and clarity in tooling. If it helps your project flow a little more smoothly, it's done its job.

Dedication

This project is dedicated to Reem. Your brilliance, courage, and quiet strength continue to inspire me. Every line is written in gratitude for the light and hope you brought into my life.

NOTE: Documentation reviewed and polished with the assistance of ChatGPT from OpenAI.


Contents

Usage

Generally the flow of argument extraction proceeds as follows:

funcmain() {
// Create the args object with a program description (that will be used in// the Usage message) and the system arguments. These will be copied// leaving the original os.Args untouched.args:=szargs.New(
"A simple demo of values flag.",
os.Args,
)
// Flagged arguments are then extracted using various methods defined on the// args object.verbose:=args.Count("[-v | --verbose ...]","The verbose level.")
lines:=args.Value("[-n | --num numOfLines]","Number of lines to display.")
// Positional arguments are then extracted.file:=args.Next("filename","The file to display the lines.")
// All expected arguments have now been extracted.args.Done()
ifargs.HasErr() {
//Report any errors and optionally providing a Usage message.fmt.Fprintf(os.Stderr, "Error: %v\n\n%s\n", args.Err(), args.Usage())
} else {
// Process with the arguments.
}
}

General functions operating on the state of the szargs object can be divided into three categories as follows:

Relating to errors:

// HasErr returns true if any errors have been encountered or registered.func (args*Args) HasErr() bool// PushErr registers the provided error if not nil to the Args error stack.func (args*Args) PushErr(errerror)
// Err returns any errors encountered or registered while parsing the// arguments.func (args*Args) Err() error

Relating to the raw argument list:

// HasNext returns true if any arguments remain unabsorbed.func (args*Args) HasNext() bool// PushArg places the supplied argument to the end of the internal args list.func (args*Args) PushArg(argstring)
// Args returns a copy of the current argument list.func (args*Args) Args() []string

And general reporting and processing:

// Usage returns a usage messages representing the Args object. It is// formatted to the lineWidth provided. A zero uses the defaultLineWidth// while a negative value caused an effort to determine if writing to a// terminal and if so using its width otherwise defaulting.func (args*Args) Usage(lineWidthint) string// Done registers an error if there are any remaining arguments.func (args*Args) Done()

A working example can be found in the example directory as described here:

Contents

Boolean Flags

Boolean flags are defined by their presence only. If they are present then they are true and/or counted. If not present then they are considered false. There are two methods that operate with boolean flags as follows:

// Is returns true if the flag is present one and only one time.func (args*Args) Is(flag, descstring) bool// Count returns the number of times the flag appears.func (args*Args) Count(flag, descstring) int

Contents

Value Flagged Arguments

A flagged argument has two components: the flag followed by the value. It may only appear once in the argument list. The basic string functions are:

// ValueString scans for a specific flagged argument and captures its// following value as a string. The flag and its value are removed from the// argument list.// // If the flag appears more than once or lacks a following value, an error is// registered.// // Returns the string value and a boolean indicating whether the flag was// found.func (args*Args) ValueString(flag, descstring) (string, bool)
// ValueOption scans for a specific flagged argument (e.g., "--mode value")// and captures its associated value. The flag and its value are removed from// the argument list.// // If the flag appears more than once, or if it lacks a following value, an// error is registered. If the value is not found in the provided list of// validOptions, an error is also registered.// // Returns the value and a boolean indicating whether the flag was found.func (args*Args) ValueOption(flagstring, validOptions []string, descstring) (string, bool)

with numeric versions for basic go data types

func (args*Args) ValueFloat64(flag, descstring) (float64, bool)
func (args*Args) ValueFloat32(flag, descstring) (float32, bool)
func (args*Args) ValueInt64(flag, descstring) (int64, bool)
func (args*Args) ValueInt32(flag, descstring) (int32, bool)
func (args*Args) ValueInt16(flag, descstring) (int16, bool)
func (args*Args) ValueInt8(flag, descstring) (int8, bool)
func (args*Args) ValueInt(flag, descstring) (int, bool)
func (args*Args) ValueUint64(flag, descstring) (uint64, bool)
func (args*Args) ValueUint32(flag, descstring) (uint32, bool)
func (args*Args) ValueUint16(flag, descstring) (uint16, bool)
func (args*Args) ValueUint8(flag, descstring) (uint8, bool)
func (args*Args) ValueUint(flag, descstring) (uint, bool)

Contents

Value Flagged Slices

A flagged argument has two components: the flag followed by the value. Multiple instances may be provided with all the values collected and returned in a slice. The basic string functions are:

// ValuesString scans for repeated instances of the specified flag and// captures the following values as a slice of strings. The flags and values// are removed from the argument list.// // If any instance of the flag lacks a following value, an error is// registered.// // Returns a slice of the captured string values.func (args*Args) ValuesString(flag, descstring) []string// ValuesOption scans for repeated instances of the specified flag and// captures the following values. Each value must appear in the provided list// of validOptions. The flags and values are removed from the argument list.// // If any flag lacks a following value, or if a value is not found in// validOptions, an error is registered.// // Returns a slice of the captured values.func (args*Args) ValuesOption(flagstring, validOptions []string, descstring) []string

with numeric versions for basic go data types

func (args*Args) ValuesFloat64(flag, descstring) []float64func (args*Args) ValuesFloat32(flag, descstring) []float32func (args*Args) ValuesInt64(flag, descstring) []int64func (args*Args) ValuesInt32(flag, descstring) []int32func (args*Args) ValuesInt16(flag, descstring) []int16func (args*Args) ValuesInt8(flag, descstring) []int8func (args*Args) ValuesInt(flag, descstring) []intfunc (args*Args) ValuesUint64(flag, descstring) []uint64func (args*Args) ValuesUint32(flag, descstring) []uint32func (args*Args) ValuesUint16(flag, descstring) []uint16func (args*Args) ValuesUint8(flag, descstring) []uint8func (args*Args) ValuesUint(flag, descstring) []uint

Contents

Positional Arguments

A positional argument depends on its location in the argument list. Since flagged arguments are not automatically distinguished from positional ones, it is recommended to extract all flagged arguments first—before retrieving positional ones. The basic string functions are:

// NextString removes and returns the next argument from the argument list.// // If no arguments remain, an error is registered.// // Returns the next argument value as a string.func (args*Args) NextString(name, descstring) string// NextOption removes and returns the next argument from the argument list.// The value must match one of the entries in validOptions.// // If no arguments remain, or if the value is not found in validOptions,// an error is registered.// // Returns the next argument value.func (args*Args) NextOption(namestring, validOptions []string, descstring) string

with numeric versions for basic go data types

func (args*Args) NextFloat64(name, descstring) float64func (args*Args) NextFloat32(name, descstring) float32func (args*Args) NextInt64(name, descstring) int64func (args*Args) NextInt32(name, descstring) int32func (args*Args) NextInt16(name, descstring) int16func (args*Args) NextInt8(name, descstring) int8func (args*Args) NextInt(name, descstring) intfunc (args*Args) NextUint64(name, descstring) uint64func (args*Args) NextUint32(name, descstring) uint32func (args*Args) NextUint16(name, descstring) uint16func (args*Args) NextUint8(name, descstring) uint8func (args*Args) NextUint(name, descstring) uint

Contents

Settings

A setting implements an argument that has a default that can be overridden by an system environment variable which can be overridden by a flagged value. The basic string functions are:

// SettingString returns a configuration value based on a default,// optionally overridden by an environment variable, and further overridden// by a flagged command-line argument.// // Returns the final selected string value.func (args*Args) SettingString(flag, env, def, descstring) string// SettingOption returns a configuration value based on a default,// optionally overridden by an environment variable, and further overridden// by a flagged command-line argument.// // If the final value is not found in the list of validOptions,// an error is registered.// // Returns the final selected value.func (args*Args) SettingOption(flag, envstring, defstring, validOptions []string, descstring) string// SettingIs returns true if a specified environment variable is set to a// truthy value, or if a corresponding boolean command-line flag is present.// // Unlike other Setting methods, there is no default.// // The environment variable is considered true if it is set to one of: "",// "T", "Y", "TRUE", "YES", "ON" or "1" (case-insensitive). Any other value is// considered false.// // The command-line flag override takes no value—its presence alone indicates// true.// // Returns the resulting boolean value.func (args*Args) SettingIs(flag, envstring, descstring) bool

with numeric versions for basic go data types

func (args*Args) SettingFloat64(flag, envstring, deffloat64, descstring) float64func (args*Args) SettingFloat32(flag, envstring, deffloat32, descstring) float32func (args*Args) SettingInt64(flag, envstring, defint64, descstring) int64func (args*Args) SettingInt32(flag, envstring, defint32, descstring) int32func (args*Args) SettingInt16(flag, envstring, defint16, descstring) int16func (args*Args) SettingInt8(flag, envstring, defint8, descstring) int8func (args*Args) SettingInt(flag, envstring, defint, descstring) intfunc (args*Args) SettingUint64(flag, envstring, defuint64, descstring) uint64func (args*Args) SettingUint32(flag, envstring, defuint32, descstring) uint32func (args*Args) SettingUint16(flag, envstring, defuint16, descstring) uint16func (args*Args) SettingUint8(flag, envstring, defuint8, descstring) uint8func (args*Args) SettingUint(flag, envstring, defuint, descstring) uint

Contents

About

Simple command line argument management.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

68 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Package szargs

Overview

package szargs

Package szargs provides a minimal and consistent interface for retrieving settings from command-line arguments ([]string) and environment variables.

It supports three types of arguments:

  • Flagged: Identified by a single dash (e.g., "-v") for short flags, or a double dash (e.g., "--dir") for long-form flags. Flags may be standalone booleans or followed by a value.
  • Positional: Identified by their order in the argument list after all flagged arguments have been processed.
  • Settings: A composite configuration mechanism that combines a default value, an environment variable, and a flagged argument—allowing each to override the previous in precedence: default < env < flag.

The package includes built-in parsers for standard Go data types.

Usage centers around the Args type, created using:

szargs.New(programDesc string, programArgs []string)

The programArgs slice must include the program name as the first element; this is ignored during argument parsing.

After retrieving all relevant arguments, the Args.Done() method must be called to report an error if any unprocessed arguments remain.

This utility reflects a preference for simplicity and clarity in tooling. If it helps your project flow a little more smoothly, it's done its job.

Dedication

This project is dedicated to Reem. Your brilliance, courage, and quiet strength continue to inspire me. Every line is written in gratitude for the light and hope you brought into my life.

NOTE: Documentation reviewed and polished with the assistance of ChatGPT from OpenAI.


Contents

Usage

Generally the flow of argument extraction proceeds as follows:

funcmain() {
// Create the args object with a program description (that will be used in// the Usage message) and the system arguments. These will be copied// leaving the original os.Args untouched.args:=szargs.New(
"A simple demo of values flag.",
os.Args,
)
// Flagged arguments are then extracted using various methods defined on the// args object.verbose:=args.Count("[-v | --verbose ...]","The verbose level.")
lines:=args.Value("[-n | --num numOfLines]","Number of lines to display.")
// Positional arguments are then extracted.file:=args.Next("filename","The file to display the lines.")
// All expected arguments have now been extracted.args.Done()
ifargs.HasErr() {
//Report any errors and optionally providing a Usage message.fmt.Fprintf(os.Stderr, "Error: %v\n\n%s\n", args.Err(), args.Usage())
} else {
// Process with the arguments.
}
}

General functions operating on the state of the szargs object can be divided into three categories as follows:

Relating to errors:

// HasErr returns true if any errors have been encountered or registered.func (args*Args) HasErr() bool// PushErr registers the provided error if not nil to the Args error stack.func (args*Args) PushErr(errerror)
// Err returns any errors encountered or registered while parsing the// arguments.func (args*Args) Err() error

Relating to the raw argument list:

// HasNext returns true if any arguments remain unabsorbed.func (args*Args) HasNext() bool// PushArg places the supplied argument to the end of the internal args list.func (args*Args) PushArg(argstring)
// Args returns a copy of the current argument list.func (args*Args) Args() []string

And general reporting and processing:

// Usage returns a usage messages representing the Args object. It is// formatted to the lineWidth provided. A zero uses the defaultLineWidth// while a negative value caused an effort to determine if writing to a// terminal and if so using its width otherwise defaulting.func (args*Args) Usage(lineWidthint) string// Done registers an error if there are any remaining arguments.func (args*Args) Done()

A working example can be found in the example directory as described here:

Contents

Boolean Flags

Boolean flags are defined by their presence only. If they are present then they are true and/or counted. If not present then they are considered false. There are two methods that operate with boolean flags as follows:

// Is returns true if the flag is present one and only one time.func (args*Args) Is(flag, descstring) bool// Count returns the number of times the flag appears.func (args*Args) Count(flag, descstring) int

Contents

Value Flagged Arguments

A flagged argument has two components: the flag followed by the value. It may only appear once in the argument list. The basic string functions are:

// ValueString scans for a specific flagged argument and captures its// following value as a string. The flag and its value are removed from the// argument list.// // If the flag appears more than once or lacks a following value, an error is// registered.// // Returns the string value and a boolean indicating whether the flag was// found.func (args*Args) ValueString(flag, descstring) (string, bool)
// ValueOption scans for a specific flagged argument (e.g., "--mode value")// and captures its associated value. The flag and its value are removed from// the argument list.// // If the flag appears more than once, or if it lacks a following value, an// error is registered. If the value is not found in the provided list of// validOptions, an error is also registered.// // Returns the value and a boolean indicating whether the flag was found.func (args*Args) ValueOption(flagstring, validOptions []string, descstring) (string, bool)

with numeric versions for basic go data types

func (args*Args) ValueFloat64(flag, descstring) (float64, bool)
func (args*Args) ValueFloat32(flag, descstring) (float32, bool)
func (args*Args) ValueInt64(flag, descstring) (int64, bool)
func (args*Args) ValueInt32(flag, descstring) (int32, bool)
func (args*Args) ValueInt16(flag, descstring) (int16, bool)
func (args*Args) ValueInt8(flag, descstring) (int8, bool)
func (args*Args) ValueInt(flag, descstring) (int, bool)
func (args*Args) ValueUint64(flag, descstring) (uint64, bool)
func (args*Args) ValueUint32(flag, descstring) (uint32, bool)
func (args*Args) ValueUint16(flag, descstring) (uint16, bool)
func (args*Args) ValueUint8(flag, descstring) (uint8, bool)
func (args*Args) ValueUint(flag, descstring) (uint, bool)

Contents

Value Flagged Slices

A flagged argument has two components: the flag followed by the value. Multiple instances may be provided with all the values collected and returned in a slice. The basic string functions are:

// ValuesString scans for repeated instances of the specified flag and// captures the following values as a slice of strings. The flags and values// are removed from the argument list.// // If any instance of the flag lacks a following value, an error is// registered.// // Returns a slice of the captured string values.func (args*Args) ValuesString(flag, descstring) []string// ValuesOption scans for repeated instances of the specified flag and// captures the following values. Each value must appear in the provided list// of validOptions. The flags and values are removed from the argument list.// // If any flag lacks a following value, or if a value is not found in// validOptions, an error is registered.// // Returns a slice of the captured values.func (args*Args) ValuesOption(flagstring, validOptions []string, descstring) []string

with numeric versions for basic go data types

func (args*Args) ValuesFloat64(flag, descstring) []float64func (args*Args) ValuesFloat32(flag, descstring) []float32func (args*Args) ValuesInt64(flag, descstring) []int64func (args*Args) ValuesInt32(flag, descstring) []int32func (args*Args) ValuesInt16(flag, descstring) []int16func (args*Args) ValuesInt8(flag, descstring) []int8func (args*Args) ValuesInt(flag, descstring) []intfunc (args*Args) ValuesUint64(flag, descstring) []uint64func (args*Args) ValuesUint32(flag, descstring) []uint32func (args*Args) ValuesUint16(flag, descstring) []uint16func (args*Args) ValuesUint8(flag, descstring) []uint8func (args*Args) ValuesUint(flag, descstring) []uint

Contents

Positional Arguments

A positional argument depends on its location in the argument list. Since flagged arguments are not automatically distinguished from positional ones, it is recommended to extract all flagged arguments first—before retrieving positional ones. The basic string functions are:

// NextString removes and returns the next argument from the argument list.// // If no arguments remain, an error is registered.// // Returns the next argument value as a string.func (args*Args) NextString(name, descstring) string// NextOption removes and returns the next argument from the argument list.// The value must match one of the entries in validOptions.// // If no arguments remain, or if the value is not found in validOptions,// an error is registered.// // Returns the next argument value.func (args*Args) NextOption(namestring, validOptions []string, descstring) string

with numeric versions for basic go data types

func (args*Args) NextFloat64(name, descstring) float64func (args*Args) NextFloat32(name, descstring) float32func (args*Args) NextInt64(name, descstring) int64func (args*Args) NextInt32(name, descstring) int32func (args*Args) NextInt16(name, descstring) int16func (args*Args) NextInt8(name, descstring) int8func (args*Args) NextInt(name, descstring) intfunc (args*Args) NextUint64(name, descstring) uint64func (args*Args) NextUint32(name, descstring) uint32func (args*Args) NextUint16(name, descstring) uint16func (args*Args) NextUint8(name, descstring) uint8func (args*Args) NextUint(name, descstring) uint

Contents

Settings

A setting implements an argument that has a default that can be overridden by an system environment variable which can be overridden by a flagged value. The basic string functions are:

// SettingString returns a configuration value based on a default,// optionally overridden by an environment variable, and further overridden// by a flagged command-line argument.// // Returns the final selected string value.func (args*Args) SettingString(flag, env, def, descstring) string// SettingOption returns a configuration value based on a default,// optionally overridden by an environment variable, and further overridden// by a flagged command-line argument.// // If the final value is not found in the list of validOptions,// an error is registered.// // Returns the final selected value.func (args*Args) SettingOption(flag, envstring, defstring, validOptions []string, descstring) string// SettingIs returns true if a specified environment variable is set to a// truthy value, or if a corresponding boolean command-line flag is present.// // Unlike other Setting methods, there is no default.// // The environment variable is considered true if it is set to one of: "",// "T", "Y", "TRUE", "YES", "ON" or "1" (case-insensitive). Any other value is// considered false.// // The command-line flag override takes no value—its presence alone indicates// true.// // Returns the resulting boolean value.func (args*Args) SettingIs(flag, envstring, descstring) bool

with numeric versions for basic go data types

func (args*Args) SettingFloat64(flag, envstring, deffloat64, descstring) float64func (args*Args) SettingFloat32(flag, envstring, deffloat32, descstring) float32func (args*Args) SettingInt64(flag, envstring, defint64, descstring) int64func (args*Args) SettingInt32(flag, envstring, defint32, descstring) int32func (args*Args) SettingInt16(flag, envstring, defint16, descstring) int16func (args*Args) SettingInt8(flag, envstring, defint8, descstring) int8func (args*Args) SettingInt(flag, envstring, defint, descstring) intfunc (args*Args) SettingUint64(flag, envstring, defuint64, descstring) uint64func (args*Args) SettingUint32(flag, envstring, defuint32, descstring) uint32func (args*Args) SettingUint16(flag, envstring, defuint16, descstring) uint16func (args*Args) SettingUint8(flag, envstring, defuint8, descstring) uint8func (args*Args) SettingUint(flag, envstring, defuint, descstring) uint

Contents

About

Simple command line argument management.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

68 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Package szargs

Overview

package szargs

Package szargs provides a minimal and consistent interface for retrieving settings from command-line arguments ([]string) and environment variables.

It supports three types of arguments:

  • Flagged: Identified by a single dash (e.g., "-v") for short flags, or a double dash (e.g., "--dir") for long-form flags. Flags may be standalone booleans or followed by a value.
  • Positional: Identified by their order in the argument list after all flagged arguments have been processed.
  • Settings: A composite configuration mechanism that combines a default value, an environment variable, and a flagged argument—allowing each to override the previous in precedence: default < env < flag.

The package includes built-in parsers for standard Go data types.

Usage centers around the Args type, created using:

szargs.New(programDesc string, programArgs []string)

The programArgs slice must include the program name as the first element; this is ignored during argument parsing.

After retrieving all relevant arguments, the Args.Done() method must be called to report an error if any unprocessed arguments remain.

This utility reflects a preference for simplicity and clarity in tooling. If it helps your project flow a little more smoothly, it's done its job.

Dedication

This project is dedicated to Reem. Your brilliance, courage, and quiet strength continue to inspire me. Every line is written in gratitude for the light and hope you brought into my life.

NOTE: Documentation reviewed and polished with the assistance of ChatGPT from OpenAI.


Contents

Usage

Generally the flow of argument extraction proceeds as follows:

funcmain() {
// Create the args object with a program description (that will be used in// the Usage message) and the system arguments. These will be copied// leaving the original os.Args untouched.args:=szargs.New(
"A simple demo of values flag.",
os.Args,
)
// Flagged arguments are then extracted using various methods defined on the// args object.verbose:=args.Count("[-v | --verbose ...]","The verbose level.")
lines:=args.Value("[-n | --num numOfLines]","Number of lines to display.")
// Positional arguments are then extracted.file:=args.Next("filename","The file to display the lines.")
// All expected arguments have now been extracted.args.Done()
ifargs.HasErr() {
//Report any errors and optionally providing a Usage message.fmt.Fprintf(os.Stderr, "Error: %v\n\n%s\n", args.Err(), args.Usage())
} else {
// Process with the arguments.
}
}

General functions operating on the state of the szargs object can be divided into three categories as follows:

Relating to errors:

// HasErr returns true if any errors have been encountered or registered.func (args*Args) HasErr() bool// PushErr registers the provided error if not nil to the Args error stack.func (args*Args) PushErr(errerror)
// Err returns any errors encountered or registered while parsing the// arguments.func (args*Args) Err() error

Relating to the raw argument list:

// HasNext returns true if any arguments remain unabsorbed.func (args*Args) HasNext() bool// PushArg places the supplied argument to the end of the internal args list.func (args*Args) PushArg(argstring)
// Args returns a copy of the current argument list.func (args*Args) Args() []string

And general reporting and processing:

// Usage returns a usage messages representing the Args object. It is// formatted to the lineWidth provided. A zero uses the defaultLineWidth// while a negative value caused an effort to determine if writing to a// terminal and if so using its width otherwise defaulting.func (args*Args) Usage(lineWidthint) string// Done registers an error if there are any remaining arguments.func (args*Args) Done()

A working example can be found in the example directory as described here:

Contents

Boolean Flags

Boolean flags are defined by their presence only. If they are present then they are true and/or counted. If not present then they are considered false. There are two methods that operate with boolean flags as follows:

// Is returns true if the flag is present one and only one time.func (args*Args) Is(flag, descstring) bool// Count returns the number of times the flag appears.func (args*Args) Count(flag, descstring) int

Contents

Value Flagged Arguments

A flagged argument has two components: the flag followed by the value. It may only appear once in the argument list. The basic string functions are:

// ValueString scans for a specific flagged argument and captures its// following value as a string. The flag and its value are removed from the// argument list.// // If the flag appears more than once or lacks a following value, an error is// registered.// // Returns the string value and a boolean indicating whether the flag was// found.func (args*Args) ValueString(flag, descstring) (string, bool)
// ValueOption scans for a specific flagged argument (e.g., "--mode value")// and captures its associated value. The flag and its value are removed from// the argument list.// // If the flag appears more than once, or if it lacks a following value, an// error is registered. If the value is not found in the provided list of// validOptions, an error is also registered.// // Returns the value and a boolean indicating whether the flag was found.func (args*Args) ValueOption(flagstring, validOptions []string, descstring) (string, bool)

with numeric versions for basic go data types

func (args*Args) ValueFloat64(flag, descstring) (float64, bool)
func (args*Args) ValueFloat32(flag, descstring) (float32, bool)
func (args*Args) ValueInt64(flag, descstring) (int64, bool)
func (args*Args) ValueInt32(flag, descstring) (int32, bool)
func (args*Args) ValueInt16(flag, descstring) (int16, bool)
func (args*Args) ValueInt8(flag, descstring) (int8, bool)
func (args*Args) ValueInt(flag, descstring) (int, bool)
func (args*Args) ValueUint64(flag, descstring) (uint64, bool)
func (args*Args) ValueUint32(flag, descstring) (uint32, bool)
func (args*Args) ValueUint16(flag, descstring) (uint16, bool)
func (args*Args) ValueUint8(flag, descstring) (uint8, bool)
func (args*Args) ValueUint(flag, descstring) (uint, bool)

Contents

Value Flagged Slices

A flagged argument has two components: the flag followed by the value. Multiple instances may be provided with all the values collected and returned in a slice. The basic string functions are:

// ValuesString scans for repeated instances of the specified flag and// captures the following values as a slice of strings. The flags and values// are removed from the argument list.// // If any instance of the flag lacks a following value, an error is// registered.// // Returns a slice of the captured string values.func (args*Args) ValuesString(flag, descstring) []string// ValuesOption scans for repeated instances of the specified flag and// captures the following values. Each value must appear in the provided list// of validOptions. The flags and values are removed from the argument list.// // If any flag lacks a following value, or if a value is not found in// validOptions, an error is registered.// // Returns a slice of the captured values.func (args*Args) ValuesOption(flagstring, validOptions []string, descstring) []string

with numeric versions for basic go data types

func (args*Args) ValuesFloat64(flag, descstring) []float64func (args*Args) ValuesFloat32(flag, descstring) []float32func (args*Args) ValuesInt64(flag, descstring) []int64func (args*Args) ValuesInt32(flag, descstring) []int32func (args*Args) ValuesInt16(flag, descstring) []int16func (args*Args) ValuesInt8(flag, descstring) []int8func (args*Args) ValuesInt(flag, descstring) []intfunc (args*Args) ValuesUint64(flag, descstring) []uint64func (args*Args) ValuesUint32(flag, descstring) []uint32func (args*Args) ValuesUint16(flag, descstring) []uint16func (args*Args) ValuesUint8(flag, descstring) []uint8func (args*Args) ValuesUint(flag, descstring) []uint

Contents

Positional Arguments

A positional argument depends on its location in the argument list. Since flagged arguments are not automatically distinguished from positional ones, it is recommended to extract all flagged arguments first—before retrieving positional ones. The basic string functions are:

// NextString removes and returns the next argument from the argument list.// // If no arguments remain, an error is registered.// // Returns the next argument value as a string.func (args*Args) NextString(name, descstring) string// NextOption removes and returns the next argument from the argument list.// The value must match one of the entries in validOptions.// // If no arguments remain, or if the value is not found in validOptions,// an error is registered.// // Returns the next argument value.func (args*Args) NextOption(namestring, validOptions []string, descstring) string

with numeric versions for basic go data types

func (args*Args) NextFloat64(name, descstring) float64func (args*Args) NextFloat32(name, descstring) float32func (args*Args) NextInt64(name, descstring) int64func (args*Args) NextInt32(name, descstring) int32func (args*Args) NextInt16(name, descstring) int16func (args*Args) NextInt8(name, descstring) int8func (args*Args) NextInt(name, descstring) intfunc (args*Args) NextUint64(name, descstring) uint64func (args*Args) NextUint32(name, descstring) uint32func (args*Args) NextUint16(name, descstring) uint16func (args*Args) NextUint8(name, descstring) uint8func (args*Args) NextUint(name, descstring) uint

Contents

Settings

A setting implements an argument that has a default that can be overridden by an system environment variable which can be overridden by a flagged value. The basic string functions are:

// SettingString returns a configuration value based on a default,// optionally overridden by an environment variable, and further overridden// by a flagged command-line argument.// // Returns the final selected string value.func (args*Args) SettingString(flag, env, def, descstring) string// SettingOption returns a configuration value based on a default,// optionally overridden by an environment variable, and further overridden// by a flagged command-line argument.// // If the final value is not found in the list of validOptions,// an error is registered.// // Returns the final selected value.func (args*Args) SettingOption(flag, envstring, defstring, validOptions []string, descstring) string// SettingIs returns true if a specified environment variable is set to a// truthy value, or if a corresponding boolean command-line flag is present.// // Unlike other Setting methods, there is no default.// // The environment variable is considered true if it is set to one of: "",// "T", "Y", "TRUE", "YES", "ON" or "1" (case-insensitive). Any other value is// considered false.// // The command-line flag override takes no value—its presence alone indicates// true.// // Returns the resulting boolean value.func (args*Args) SettingIs(flag, envstring, descstring) bool

with numeric versions for basic go data types

func (args*Args) SettingFloat64(flag, envstring, deffloat64, descstring) float64func (args*Args) SettingFloat32(flag, envstring, deffloat32, descstring) float32func (args*Args) SettingInt64(flag, envstring, defint64, descstring) int64func (args*Args) SettingInt32(flag, envstring, defint32, descstring) int32func (args*Args) SettingInt16(flag, envstring, defint16, descstring) int16func (args*Args) SettingInt8(flag, envstring, defint8, descstring) int8func (args*Args) SettingInt(flag, envstring, defint, descstring) intfunc (args*Args) SettingUint64(flag, envstring, defuint64, descstring) uint64func (args*Args) SettingUint32(flag, envstring, defuint32, descstring) uint32func (args*Args) SettingUint16(flag, envstring, defuint16, descstring) uint16func (args*Args) SettingUint8(flag, envstring, defuint8, descstring) uint8func (args*Args) SettingUint(flag, envstring, defuint, descstring) uint

Contents

About

Simple command line argument management.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

68 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Package szargs

Overview

package szargs

Package szargs provides a minimal and consistent interface for retrieving settings from command-line arguments ([]string) and environment variables.

It supports three types of arguments:

  • Flagged: Identified by a single dash (e.g., "-v") for short flags, or a double dash (e.g., "--dir") for long-form flags. Flags may be standalone booleans or followed by a value.
  • Positional: Identified by their order in the argument list after all flagged arguments have been processed.
  • Settings: A composite configuration mechanism that combines a default value, an environment variable, and a flagged argument—allowing each to override the previous in precedence: default < env < flag.

The package includes built-in parsers for standard Go data types.

Usage centers around the Args type, created using:

szargs.New(programDesc string, programArgs []string)

The programArgs slice must include the program name as the first element; this is ignored during argument parsing.

After retrieving all relevant arguments, the Args.Done() method must be called to report an error if any unprocessed arguments remain.

This utility reflects a preference for simplicity and clarity in tooling. If it helps your project flow a little more smoothly, it's done its job.

Dedication

This project is dedicated to Reem. Your brilliance, courage, and quiet strength continue to inspire me. Every line is written in gratitude for the light and hope you brought into my life.

NOTE: Documentation reviewed and polished with the assistance of ChatGPT from OpenAI.


Contents

Usage

Generally the flow of argument extraction proceeds as follows:

funcmain() {
// Create the args object with a program description (that will be used in// the Usage message) and the system arguments. These will be copied// leaving the original os.Args untouched.args:=szargs.New(
"A simple demo of values flag.",
os.Args,
)
// Flagged arguments are then extracted using various methods defined on the// args object.verbose:=args.Count("[-v | --verbose ...]","The verbose level.")
lines:=args.Value("[-n | --num numOfLines]","Number of lines to display.")
// Positional arguments are then extracted.file:=args.Next("filename","The file to display the lines.")
// All expected arguments have now been extracted.args.Done()
ifargs.HasErr() {
//Report any errors and optionally providing a Usage message.fmt.Fprintf(os.Stderr, "Error: %v\n\n%s\n", args.Err(), args.Usage())
} else {
// Process with the arguments.
}
}

General functions operating on the state of the szargs object can be divided into three categories as follows:

Relating to errors:

// HasErr returns true if any errors have been encountered or registered.func (args*Args) HasErr() bool// PushErr registers the provided error if not nil to the Args error stack.func (args*Args) PushErr(errerror)
// Err returns any errors encountered or registered while parsing the// arguments.func (args*Args) Err() error

Relating to the raw argument list:

// HasNext returns true if any arguments remain unabsorbed.func (args*Args) HasNext() bool// PushArg places the supplied argument to the end of the internal args list.func (args*Args) PushArg(argstring)
// Args returns a copy of the current argument list.func (args*Args) Args() []string

And general reporting and processing:

// Usage returns a usage messages representing the Args object. It is// formatted to the lineWidth provided. A zero uses the defaultLineWidth// while a negative value caused an effort to determine if writing to a// terminal and if so using its width otherwise defaulting.func (args*Args) Usage(lineWidthint) string// Done registers an error if there are any remaining arguments.func (args*Args) Done()

A working example can be found in the example directory as described here:

Contents

Boolean Flags

Boolean flags are defined by their presence only. If they are present then they are true and/or counted. If not present then they are considered false. There are two methods that operate with boolean flags as follows:

// Is returns true if the flag is present one and only one time.func (args*Args) Is(flag, descstring) bool// Count returns the number of times the flag appears.func (args*Args) Count(flag, descstring) int

Contents

Value Flagged Arguments

A flagged argument has two components: the flag followed by the value. It may only appear once in the argument list. The basic string functions are:

// ValueString scans for a specific flagged argument and captures its// following value as a string. The flag and its value are removed from the// argument list.// // If the flag appears more than once or lacks a following value, an error is// registered.// // Returns the string value and a boolean indicating whether the flag was// found.func (args*Args) ValueString(flag, descstring) (string, bool)
// ValueOption scans for a specific flagged argument (e.g., "--mode value")// and captures its associated value. The flag and its value are removed from// the argument list.// // If the flag appears more than once, or if it lacks a following value, an// error is registered. If the value is not found in the provided list of// validOptions, an error is also registered.// // Returns the value and a boolean indicating whether the flag was found.func (args*Args) ValueOption(flagstring, validOptions []string, descstring) (string, bool)

with numeric versions for basic go data types

func (args*Args) ValueFloat64(flag, descstring) (float64, bool)
func (args*Args) ValueFloat32(flag, descstring) (float32, bool)
func (args*Args) ValueInt64(flag, descstring) (int64, bool)
func (args*Args) ValueInt32(flag, descstring) (int32, bool)
func (args*Args) ValueInt16(flag, descstring) (int16, bool)
func (args*Args) ValueInt8(flag, descstring) (int8, bool)
func (args*Args) ValueInt(flag, descstring) (int, bool)
func (args*Args) ValueUint64(flag, descstring) (uint64, bool)
func (args*Args) ValueUint32(flag, descstring) (uint32, bool)
func (args*Args) ValueUint16(flag, descstring) (uint16, bool)
func (args*Args) ValueUint8(flag, descstring) (uint8, bool)
func (args*Args) ValueUint(flag, descstring) (uint, bool)

Contents

Value Flagged Slices

A flagged argument has two components: the flag followed by the value. Multiple instances may be provided with all the values collected and returned in a slice. The basic string functions are:

// ValuesString scans for repeated instances of the specified flag and// captures the following values as a slice of strings. The flags and values// are removed from the argument list.// // If any instance of the flag lacks a following value, an error is// registered.// // Returns a slice of the captured string values.func (args*Args) ValuesString(flag, descstring) []string// ValuesOption scans for repeated instances of the specified flag and// captures the following values. Each value must appear in the provided list// of validOptions. The flags and values are removed from the argument list.// // If any flag lacks a following value, or if a value is not found in// validOptions, an error is registered.// // Returns a slice of the captured values.func (args*Args) ValuesOption(flagstring, validOptions []string, descstring) []string

with numeric versions for basic go data types

func (args*Args) ValuesFloat64(flag, descstring) []float64func (args*Args) ValuesFloat32(flag, descstring) []float32func (args*Args) ValuesInt64(flag, descstring) []int64func (args*Args) ValuesInt32(flag, descstring) []int32func (args*Args) ValuesInt16(flag, descstring) []int16func (args*Args) ValuesInt8(flag, descstring) []int8func (args*Args) ValuesInt(flag, descstring) []intfunc (args*Args) ValuesUint64(flag, descstring) []uint64func (args*Args) ValuesUint32(flag, descstring) []uint32func (args*Args) ValuesUint16(flag, descstring) []uint16func (args*Args) ValuesUint8(flag, descstring) []uint8func (args*Args) ValuesUint(flag, descstring) []uint

Contents

Positional Arguments

A positional argument depends on its location in the argument list. Since flagged arguments are not automatically distinguished from positional ones, it is recommended to extract all flagged arguments first—before retrieving positional ones. The basic string functions are:

// NextString removes and returns the next argument from the argument list.// // If no arguments remain, an error is registered.// // Returns the next argument value as a string.func (args*Args) NextString(name, descstring) string// NextOption removes and returns the next argument from the argument list.// The value must match one of the entries in validOptions.// // If no arguments remain, or if the value is not found in validOptions,// an error is registered.// // Returns the next argument value.func (args*Args) NextOption(namestring, validOptions []string, descstring) string

with numeric versions for basic go data types

func (args*Args) NextFloat64(name, descstring) float64func (args*Args) NextFloat32(name, descstring) float32func (args*Args) NextInt64(name, descstring) int64func (args*Args) NextInt32(name, descstring) int32func (args*Args) NextInt16(name, descstring) int16func (args*Args) NextInt8(name, descstring) int8func (args*Args) NextInt(name, descstring) intfunc (args*Args) NextUint64(name, descstring) uint64func (args*Args) NextUint32(name, descstring) uint32func (args*Args) NextUint16(name, descstring) uint16func (args*Args) NextUint8(name, descstring) uint8func (args*Args) NextUint(name, descstring) uint

Contents

Settings

A setting implements an argument that has a default that can be overridden by an system environment variable which can be overridden by a flagged value. The basic string functions are:

// SettingString returns a configuration value based on a default,// optionally overridden by an environment variable, and further overridden// by a flagged command-line argument.// // Returns the final selected string value.func (args*Args) SettingString(flag, env, def, descstring) string// SettingOption returns a configuration value based on a default,// optionally overridden by an environment variable, and further overridden// by a flagged command-line argument.// // If the final value is not found in the list of validOptions,// an error is registered.// // Returns the final selected value.func (args*Args) SettingOption(flag, envstring, defstring, validOptions []string, descstring) string// SettingIs returns true if a specified environment variable is set to a// truthy value, or if a corresponding boolean command-line flag is present.// // Unlike other Setting methods, there is no default.// // The environment variable is considered true if it is set to one of: "",// "T", "Y", "TRUE", "YES", "ON" or "1" (case-insensitive). Any other value is// considered false.// // The command-line flag override takes no value—its presence alone indicates// true.// // Returns the resulting boolean value.func (args*Args) SettingIs(flag, envstring, descstring) bool

with numeric versions for basic go data types

func (args*Args) SettingFloat64(flag, envstring, deffloat64, descstring) float64func (args*Args) SettingFloat32(flag, envstring, deffloat32, descstring) float32func (args*Args) SettingInt64(flag, envstring, defint64, descstring) int64func (args*Args) SettingInt32(flag, envstring, defint32, descstring) int32func (args*Args) SettingInt16(flag, envstring, defint16, descstring) int16func (args*Args) SettingInt8(flag, envstring, defint8, descstring) int8func (args*Args) SettingInt(flag, envstring, defint, descstring) intfunc (args*Args) SettingUint64(flag, envstring, defuint64, descstring) uint64func (args*Args) SettingUint32(flag, envstring, defuint32, descstring) uint32func (args*Args) SettingUint16(flag, envstring, defuint16, descstring) uint16func (args*Args) SettingUint8(flag, envstring, defuint8, descstring) uint8func (args*Args) SettingUint(flag, envstring, defuint, descstring) uint

Contents

About

Simple command line argument management.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

68 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Package szargs

Overview

package szargs

Package szargs provides a minimal and consistent interface for retrieving settings from command-line arguments ([]string) and environment variables.

It supports three types of arguments:

  • Flagged: Identified by a single dash (e.g., "-v") for short flags, or a double dash (e.g., "--dir") for long-form flags. Flags may be standalone booleans or followed by a value.
  • Positional: Identified by their order in the argument list after all flagged arguments have been processed.
  • Settings: A composite configuration mechanism that combines a default value, an environment variable, and a flagged argument—allowing each to override the previous in precedence: default < env < flag.

The package includes built-in parsers for standard Go data types.

Usage centers around the Args type, created using:

szargs.New(programDesc string, programArgs []string)

The programArgs slice must include the program name as the first element; this is ignored during argument parsing.

After retrieving all relevant arguments, the Args.Done() method must be called to report an error if any unprocessed arguments remain.

This utility reflects a preference for simplicity and clarity in tooling. If it helps your project flow a little more smoothly, it's done its job.

Dedication

This project is dedicated to Reem. Your brilliance, courage, and quiet strength continue to inspire me. Every line is written in gratitude for the light and hope you brought into my life.

NOTE: Documentation reviewed and polished with the assistance of ChatGPT from OpenAI.


Contents

Usage

Generally the flow of argument extraction proceeds as follows:

funcmain() {
// Create the args object with a program description (that will be used in// the Usage message) and the system arguments. These will be copied// leaving the original os.Args untouched.args:=szargs.New(
"A simple demo of values flag.",
os.Args,
)
// Flagged arguments are then extracted using various methods defined on the// args object.verbose:=args.Count("[-v | --verbose ...]","The verbose level.")
lines:=args.Value("[-n | --num numOfLines]","Number of lines to display.")
// Positional arguments are then extracted.file:=args.Next("filename","The file to display the lines.")
// All expected arguments have now been extracted.args.Done()
ifargs.HasErr() {
//Report any errors and optionally providing a Usage message.fmt.Fprintf(os.Stderr, "Error: %v\n\n%s\n", args.Err(), args.Usage())
} else {
// Process with the arguments.
}
}

General functions operating on the state of the szargs object can be divided into three categories as follows:

Relating to errors:

// HasErr returns true if any errors have been encountered or registered.func (args*Args) HasErr() bool// PushErr registers the provided error if not nil to the Args error stack.func (args*Args) PushErr(errerror)
// Err returns any errors encountered or registered while parsing the// arguments.func (args*Args) Err() error

Relating to the raw argument list:

// HasNext returns true if any arguments remain unabsorbed.func (args*Args) HasNext() bool// PushArg places the supplied argument to the end of the internal args list.func (args*Args) PushArg(argstring)
// Args returns a copy of the current argument list.func (args*Args) Args() []string

And general reporting and processing:

// Usage returns a usage messages representing the Args object. It is// formatted to the lineWidth provided. A zero uses the defaultLineWidth// while a negative value caused an effort to determine if writing to a// terminal and if so using its width otherwise defaulting.func (args*Args) Usage(lineWidthint) string// Done registers an error if there are any remaining arguments.func (args*Args) Done()

A working example can be found in the example directory as described here:

Contents

Boolean Flags

Boolean flags are defined by their presence only. If they are present then they are true and/or counted. If not present then they are considered false. There are two methods that operate with boolean flags as follows:

// Is returns true if the flag is present one and only one time.func (args*Args) Is(flag, descstring) bool// Count returns the number of times the flag appears.func (args*Args) Count(flag, descstring) int

Contents

Value Flagged Arguments

A flagged argument has two components: the flag followed by the value. It may only appear once in the argument list. The basic string functions are:

// ValueString scans for a specific flagged argument and captures its// following value as a string. The flag and its value are removed from the// argument list.// // If the flag appears more than once or lacks a following value, an error is// registered.// // Returns the string value and a boolean indicating whether the flag was// found.func (args*Args) ValueString(flag, descstring) (string, bool)
// ValueOption scans for a specific flagged argument (e.g., "--mode value")// and captures its associated value. The flag and its value are removed from// the argument list.// // If the flag appears more than once, or if it lacks a following value, an// error is registered. If the value is not found in the provided list of// validOptions, an error is also registered.// // Returns the value and a boolean indicating whether the flag was found.func (args*Args) ValueOption(flagstring, validOptions []string, descstring) (string, bool)

with numeric versions for basic go data types

func (args*Args) ValueFloat64(flag, descstring) (float64, bool)
func (args*Args) ValueFloat32(flag, descstring) (float32, bool)
func (args*Args) ValueInt64(flag, descstring) (int64, bool)
func (args*Args) ValueInt32(flag, descstring) (int32, bool)
func (args*Args) ValueInt16(flag, descstring) (int16, bool)
func (args*Args) ValueInt8(flag, descstring) (int8, bool)
func (args*Args) ValueInt(flag, descstring) (int, bool)
func (args*Args) ValueUint64(flag, descstring) (uint64, bool)
func (args*Args) ValueUint32(flag, descstring) (uint32, bool)
func (args*Args) ValueUint16(flag, descstring) (uint16, bool)
func (args*Args) ValueUint8(flag, descstring) (uint8, bool)
func (args*Args) ValueUint(flag, descstring) (uint, bool)

Contents

Value Flagged Slices

A flagged argument has two components: the flag followed by the value. Multiple instances may be provided with all the values collected and returned in a slice. The basic string functions are:

// ValuesString scans for repeated instances of the specified flag and// captures the following values as a slice of strings. The flags and values// are removed from the argument list.// // If any instance of the flag lacks a following value, an error is// registered.// // Returns a slice of the captured string values.func (args*Args) ValuesString(flag, descstring) []string// ValuesOption scans for repeated instances of the specified flag and// captures the following values. Each value must appear in the provided list// of validOptions. The flags and values are removed from the argument list.// // If any flag lacks a following value, or if a value is not found in// validOptions, an error is registered.// // Returns a slice of the captured values.func (args*Args) ValuesOption(flagstring, validOptions []string, descstring) []string

with numeric versions for basic go data types

func (args*Args) ValuesFloat64(flag, descstring) []float64func (args*Args) ValuesFloat32(flag, descstring) []float32func (args*Args) ValuesInt64(flag, descstring) []int64func (args*Args) ValuesInt32(flag, descstring) []int32func (args*Args) ValuesInt16(flag, descstring) []int16func (args*Args) ValuesInt8(flag, descstring) []int8func (args*Args) ValuesInt(flag, descstring) []intfunc (args*Args) ValuesUint64(flag, descstring) []uint64func (args*Args) ValuesUint32(flag, descstring) []uint32func (args*Args) ValuesUint16(flag, descstring) []uint16func (args*Args) ValuesUint8(flag, descstring) []uint8func (args*Args) ValuesUint(flag, descstring) []uint

Contents

Positional Arguments

A positional argument depends on its location in the argument list. Since flagged arguments are not automatically distinguished from positional ones, it is recommended to extract all flagged arguments first—before retrieving positional ones. The basic string functions are:

// NextString removes and returns the next argument from the argument list.// // If no arguments remain, an error is registered.// // Returns the next argument value as a string.func (args*Args) NextString(name, descstring) string// NextOption removes and returns the next argument from the argument list.// The value must match one of the entries in validOptions.// // If no arguments remain, or if the value is not found in validOptions,// an error is registered.// // Returns the next argument value.func (args*Args) NextOption(namestring, validOptions []string, descstring) string

with numeric versions for basic go data types

func (args*Args) NextFloat64(name, descstring) float64func (args*Args) NextFloat32(name, descstring) float32func (args*Args) NextInt64(name, descstring) int64func (args*Args) NextInt32(name, descstring) int32func (args*Args) NextInt16(name, descstring) int16func (args*Args) NextInt8(name, descstring) int8func (args*Args) NextInt(name, descstring) intfunc (args*Args) NextUint64(name, descstring) uint64func (args*Args) NextUint32(name, descstring) uint32func (args*Args) NextUint16(name, descstring) uint16func (args*Args) NextUint8(name, descstring) uint8func (args*Args) NextUint(name, descstring) uint

Contents

Settings

A setting implements an argument that has a default that can be overridden by an system environment variable which can be overridden by a flagged value. The basic string functions are:

// SettingString returns a configuration value based on a default,// optionally overridden by an environment variable, and further overridden// by a flagged command-line argument.// // Returns the final selected string value.func (args*Args) SettingString(flag, env, def, descstring) string// SettingOption returns a configuration value based on a default,// optionally overridden by an environment variable, and further overridden// by a flagged command-line argument.// // If the final value is not found in the list of validOptions,// an error is registered.// // Returns the final selected value.func (args*Args) SettingOption(flag, envstring, defstring, validOptions []string, descstring) string// SettingIs returns true if a specified environment variable is set to a// truthy value, or if a corresponding boolean command-line flag is present.// // Unlike other Setting methods, there is no default.// // The environment variable is considered true if it is set to one of: "",// "T", "Y", "TRUE", "YES", "ON" or "1" (case-insensitive). Any other value is// considered false.// // The command-line flag override takes no value—its presence alone indicates// true.// // Returns the resulting boolean value.func (args*Args) SettingIs(flag, envstring, descstring) bool

with numeric versions for basic go data types

func (args*Args) SettingFloat64(flag, envstring, deffloat64, descstring) float64func (args*Args) SettingFloat32(flag, envstring, deffloat32, descstring) float32func (args*Args) SettingInt64(flag, envstring, defint64, descstring) int64func (args*Args) SettingInt32(flag, envstring, defint32, descstring) int32func (args*Args) SettingInt16(flag, envstring, defint16, descstring) int16func (args*Args) SettingInt8(flag, envstring, defint8, descstring) int8func (args*Args) SettingInt(flag, envstring, defint, descstring) intfunc (args*Args) SettingUint64(flag, envstring, defuint64, descstring) uint64func (args*Args) SettingUint32(flag, envstring, defuint32, descstring) uint32func (args*Args) SettingUint16(flag, envstring, defuint16, descstring) uint16func (args*Args) SettingUint8(flag, envstring, defuint8, descstring) uint8func (args*Args) SettingUint(flag, envstring, defuint, descstring) uint

Contents

About

Simple command line argument management.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

68 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Package szargs

Overview

package szargs

Package szargs provides a minimal and consistent interface for retrieving settings from command-line arguments ([]string) and environment variables.

It supports three types of arguments:

  • Flagged: Identified by a single dash (e.g., "-v") for short flags, or a double dash (e.g., "--dir") for long-form flags. Flags may be standalone booleans or followed by a value.
  • Positional: Identified by their order in the argument list after all flagged arguments have been processed.
  • Settings: A composite configuration mechanism that combines a default value, an environment variable, and a flagged argument—allowing each to override the previous in precedence: default < env < flag.

The package includes built-in parsers for standard Go data types.

Usage centers around the Args type, created using:

szargs.New(programDesc string, programArgs []string)

The programArgs slice must include the program name as the first element; this is ignored during argument parsing.

After retrieving all relevant arguments, the Args.Done() method must be called to report an error if any unprocessed arguments remain.

This utility reflects a preference for simplicity and clarity in tooling. If it helps your project flow a little more smoothly, it's done its job.

Dedication

This project is dedicated to Reem. Your brilliance, courage, and quiet strength continue to inspire me. Every line is written in gratitude for the light and hope you brought into my life.

NOTE: Documentation reviewed and polished with the assistance of ChatGPT from OpenAI.


Contents

Usage

Generally the flow of argument extraction proceeds as follows:

funcmain() {
// Create the args object with a program description (that will be used in// the Usage message) and the system arguments. These will be copied// leaving the original os.Args untouched.args:=szargs.New(
"A simple demo of values flag.",
os.Args,
)
// Flagged arguments are then extracted using various methods defined on the// args object.verbose:=args.Count("[-v | --verbose ...]","The verbose level.")
lines:=args.Value("[-n | --num numOfLines]","Number of lines to display.")
// Positional arguments are then extracted.file:=args.Next("filename","The file to display the lines.")
// All expected arguments have now been extracted.args.Done()
ifargs.HasErr() {
//Report any errors and optionally providing a Usage message.fmt.Fprintf(os.Stderr, "Error: %v\n\n%s\n", args.Err(), args.Usage())
} else {
// Process with the arguments.
}
}

General functions operating on the state of the szargs object can be divided into three categories as follows:

Relating to errors:

// HasErr returns true if any errors have been encountered or registered.func (args*Args) HasErr() bool// PushErr registers the provided error if not nil to the Args error stack.func (args*Args) PushErr(errerror)
// Err returns any errors encountered or registered while parsing the// arguments.func (args*Args) Err() error

Relating to the raw argument list:

// HasNext returns true if any arguments remain unabsorbed.func (args*Args) HasNext() bool// PushArg places the supplied argument to the end of the internal args list.func (args*Args) PushArg(argstring)
// Args returns a copy of the current argument list.func (args*Args) Args() []string

And general reporting and processing:

// Usage returns a usage messages representing the Args object. It is// formatted to the lineWidth provided. A zero uses the defaultLineWidth// while a negative value caused an effort to determine if writing to a// terminal and if so using its width otherwise defaulting.func (args*Args) Usage(lineWidthint) string// Done registers an error if there are any remaining arguments.func (args*Args) Done()

A working example can be found in the example directory as described here:

Contents

Boolean Flags

Boolean flags are defined by their presence only. If they are present then they are true and/or counted. If not present then they are considered false. There are two methods that operate with boolean flags as follows:

// Is returns true if the flag is present one and only one time.func (args*Args) Is(flag, descstring) bool// Count returns the number of times the flag appears.func (args*Args) Count(flag, descstring) int

Contents

Value Flagged Arguments

A flagged argument has two components: the flag followed by the value. It may only appear once in the argument list. The basic string functions are:

// ValueString scans for a specific flagged argument and captures its// following value as a string. The flag and its value are removed from the// argument list.// // If the flag appears more than once or lacks a following value, an error is// registered.// // Returns the string value and a boolean indicating whether the flag was// found.func (args*Args) ValueString(flag, descstring) (string, bool)
// ValueOption scans for a specific flagged argument (e.g., "--mode value")// and captures its associated value. The flag and its value are removed from// the argument list.// // If the flag appears more than once, or if it lacks a following value, an// error is registered. If the value is not found in the provided list of// validOptions, an error is also registered.// // Returns the value and a boolean indicating whether the flag was found.func (args*Args) ValueOption(flagstring, validOptions []string, descstring) (string, bool)

with numeric versions for basic go data types

func (args*Args) ValueFloat64(flag, descstring) (float64, bool)
func (args*Args) ValueFloat32(flag, descstring) (float32, bool)
func (args*Args) ValueInt64(flag, descstring) (int64, bool)
func (args*Args) ValueInt32(flag, descstring) (int32, bool)
func (args*Args) ValueInt16(flag, descstring) (int16, bool)
func (args*Args) ValueInt8(flag, descstring) (int8, bool)
func (args*Args) ValueInt(flag, descstring) (int, bool)
func (args*Args) ValueUint64(flag, descstring) (uint64, bool)
func (args*Args) ValueUint32(flag, descstring) (uint32, bool)
func (args*Args) ValueUint16(flag, descstring) (uint16, bool)
func (args*Args) ValueUint8(flag, descstring) (uint8, bool)
func (args*Args) ValueUint(flag, descstring) (uint, bool)

Contents

Value Flagged Slices

A flagged argument has two components: the flag followed by the value. Multiple instances may be provided with all the values collected and returned in a slice. The basic string functions are:

// ValuesString scans for repeated instances of the specified flag and// captures the following values as a slice of strings. The flags and values// are removed from the argument list.// // If any instance of the flag lacks a following value, an error is// registered.// // Returns a slice of the captured string values.func (args*Args) ValuesString(flag, descstring) []string// ValuesOption scans for repeated instances of the specified flag and// captures the following values. Each value must appear in the provided list// of validOptions. The flags and values are removed from the argument list.// // If any flag lacks a following value, or if a value is not found in// validOptions, an error is registered.// // Returns a slice of the captured values.func (args*Args) ValuesOption(flagstring, validOptions []string, descstring) []string

with numeric versions for basic go data types

func (args*Args) ValuesFloat64(flag, descstring) []float64func (args*Args) ValuesFloat32(flag, descstring) []float32func (args*Args) ValuesInt64(flag, descstring) []int64func (args*Args) ValuesInt32(flag, descstring) []int32func (args*Args) ValuesInt16(flag, descstring) []int16func (args*Args) ValuesInt8(flag, descstring) []int8func (args*Args) ValuesInt(flag, descstring) []intfunc (args*Args) ValuesUint64(flag, descstring) []uint64func (args*Args) ValuesUint32(flag, descstring) []uint32func (args*Args) ValuesUint16(flag, descstring) []uint16func (args*Args) ValuesUint8(flag, descstring) []uint8func (args*Args) ValuesUint(flag, descstring) []uint

Contents

Positional Arguments

A positional argument depends on its location in the argument list. Since flagged arguments are not automatically distinguished from positional ones, it is recommended to extract all flagged arguments first—before retrieving positional ones. The basic string functions are:

// NextString removes and returns the next argument from the argument list.// // If no arguments remain, an error is registered.// // Returns the next argument value as a string.func (args*Args) NextString(name, descstring) string// NextOption removes and returns the next argument from the argument list.// The value must match one of the entries in validOptions.// // If no arguments remain, or if the value is not found in validOptions,// an error is registered.// // Returns the next argument value.func (args*Args) NextOption(namestring, validOptions []string, descstring) string

with numeric versions for basic go data types

func (args*Args) NextFloat64(name, descstring) float64func (args*Args) NextFloat32(name, descstring) float32func (args*Args) NextInt64(name, descstring) int64func (args*Args) NextInt32(name, descstring) int32func (args*Args) NextInt16(name, descstring) int16func (args*Args) NextInt8(name, descstring) int8func (args*Args) NextInt(name, descstring) intfunc (args*Args) NextUint64(name, descstring) uint64func (args*Args) NextUint32(name, descstring) uint32func (args*Args) NextUint16(name, descstring) uint16func (args*Args) NextUint8(name, descstring) uint8func (args*Args) NextUint(name, descstring) uint

Contents

Settings

A setting implements an argument that has a default that can be overridden by an system environment variable which can be overridden by a flagged value. The basic string functions are:

// SettingString returns a configuration value based on a default,// optionally overridden by an environment variable, and further overridden// by a flagged command-line argument.// // Returns the final selected string value.func (args*Args) SettingString(flag, env, def, descstring) string// SettingOption returns a configuration value based on a default,// optionally overridden by an environment variable, and further overridden// by a flagged command-line argument.// // If the final value is not found in the list of validOptions,// an error is registered.// // Returns the final selected value.func (args*Args) SettingOption(flag, envstring, defstring, validOptions []string, descstring) string// SettingIs returns true if a specified environment variable is set to a// truthy value, or if a corresponding boolean command-line flag is present.// // Unlike other Setting methods, there is no default.// // The environment variable is considered true if it is set to one of: "",// "T", "Y", "TRUE", "YES", "ON" or "1" (case-insensitive). Any other value is// considered false.// // The command-line flag override takes no value—its presence alone indicates// true.// // Returns the resulting boolean value.func (args*Args) SettingIs(flag, envstring, descstring) bool

with numeric versions for basic go data types

func (args*Args) SettingFloat64(flag, envstring, deffloat64, descstring) float64func (args*Args) SettingFloat32(flag, envstring, deffloat32, descstring) float32func (args*Args) SettingInt64(flag, envstring, defint64, descstring) int64func (args*Args) SettingInt32(flag, envstring, defint32, descstring) int32func (args*Args) SettingInt16(flag, envstring, defint16, descstring) int16func (args*Args) SettingInt8(flag, envstring, defint8, descstring) int8func (args*Args) SettingInt(flag, envstring, defint, descstring) intfunc (args*Args) SettingUint64(flag, envstring, defuint64, descstring) uint64func (args*Args) SettingUint32(flag, envstring, defuint32, descstring) uint32func (args*Args) SettingUint16(flag, envstring, defuint16, descstring) uint16func (args*Args) SettingUint8(flag, envstring, defuint8, descstring) uint8func (args*Args) SettingUint(flag, envstring, defuint, descstring) uint

Contents

About

Simple command line argument management.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages