Documentation ¶
Index ¶
- Constants
- Variables
- func CheckFlag(id string) bool
- func CheckPath(path string) uint8
- func CopyFile(src, dst string, overwrite bool) error
- func DelStr(id string)
- func EscStr(str string) string
- func ExStr(str string) string
- func ExStrX(str string, st StrTable, reserveSGRTag bool) string
- func GetCmdDescList(id, format string) ([]string, error)
- func GetCmdHelpText(id string) (string, error)
- func GetCmdLineArgs(skip uint) []string
- func GetCmdOptDescList(id, format string) ([]string, error)
- func GetExitStatusDescList(format string) []string
- func GetLangInfoList(format string) []string
- func GetStr(id string) string
- func ImportDataFromJSONFile(path string, target interface{}) error
- func ImportStrTableFromRsrc(path string, st StrTable) error
- func IsElevated() bool
- func IsError(err error, id ErrId) bool
- func IsNewer(f1, f2 fs.FileInfo) bool
- func MakeCmdLine(path string, args []string) (string, error)
- func RunApp(ai *AppInitializer)
- func SetFlag(id string, status bool)
- func SetLang(id string) error
- func SetStr(id, str string)
- func TraceAndPrintErrorChain(err error)
- func WriteStr(wr io.Writer, str string) error
- func WriteStrX(wr io.Writer, str string, st StrTable, exRefTag, interpretSGRTag bool) error
- type AppInitializer
- type ArgErr
- type Cmd
- type CmdOpt
- type Err
- type ErrCaller
- type ErrId
- type Rsrc
- type Singleton
- type StrTable
Constants ¶
const ( StdOut stdStream = 1 // The standard output stream. StdErr stdStream = 2 // The standard error stream. )
const ( FMT_PRESET_CMD_DESC = "${#CMD.NAME} $[32]#$[] ${#CMD.DESC}" FMT_PRESET_CMD_OPT_DESC = "${#OPT.SYNTAX} $[32]#$[] ${#OPT.DESC}" FMT_PRESET_LANG_INFO = "${#LANG.ID} $[32]#$[] ${#LANG.NAME}" FMT_PRESET_EXIT_STATUS_DESC = "${#ES.CODE} $[32]#$[] ${#ES.DESC}" )
The preset format string of messasge lines.
Variables ¶
var ( // The exit status code to return when exits. Default as 0. ExitStatusCode int )
var (
/*
Automatically passed as a parameter in
time.Now().Format(FmtTimeStamp)
to determine the expanding format of the preset string identifier "#[TIME_STAMP]". For details, please refer to the documentation of the package [time] which is a part of Golang standard library.
*/
FmtTimeStamp = "2006-01-02 15:04:05"
)
Functions ¶
func CheckFlag ¶
CheckFlag checks the status of the specified app flag.
[PARAMETERS]
id string // The identifier of the app flag.
[RETURNS]
bool // The current status value.
func CheckPath ¶
CheckPath checks whether the specified path exists, and if it exists, determines whether it is a regular file or a directory.
[PARAMETERS]
path string // The specified path to be checked.
[RETURNS]
uint8 // 0 means the path does not exist; 1 means a regular file; 2 means a directory.
func CopyFile ¶
CopyFile copies an existing file to the destination path.
[PARAMETERS]
src string // The path of the file to be copied. dst string // The destination path where the file is copied. overwrite bool // Indicates whether to overwrite the existing file.
[RETURNS]
error // If the function succeeds, it is nil, otherwise it is the first error encountered.
[REMARKS]
The function will fail with an error of ERR_INVALID_OP in any case of the followings:
1. [src] is not a regular file;
2. [src] and [dst] are the same file.
func DelStr ¶
func DelStr(id string)
DelStr deletes the specified string in the global string table. If the string is not defined, no op will be done.
[PARAMETERS]
id string // The identifier of the string.
func EscStr ¶
EscStr escapes any substring that matches the format of a tag by adding an extra $ in front of the tag symbol ($). Besides, an even number of consecutive dollar signs are doubled in number (2n → 4n). E.g.,
"${foo}$$$bar"
will be modified to
"$${foo}$$$$$bar"
The final string will be returned.
[PARAMETERS]
str string // The raw string.
[RETURNS]
string // The final string.
[REMARKS]
For details about definitions of tags, please refer to the documentation of the type StrTable.
func ExStr ¶
ExStr is equivalent to the call:
appbase.ExStrX(str, nil, false)
which means using the global string table when expanding a reference tag and all valid SGR tags will be discarded.
func ExStrX ¶
ExStrX expands all valid reference tags in the given string according to the specified string table and returns the final string. The escape rule for tag symbols will be applied.
[PARAMETERS]
str string // The raw string. st StrTable // The string table for expanding any string reference. If it is nil, the global string table is used. reserveSGRTag bool // Indicates whether to reserve any valid SGR tag. If this is false, any valid SGR tag will be discarded.
[RETURNS]
string // The final string.
[REMARKS]
1. A regular reference tag will expand to the corresponding value in the specified string table. A preset or environment variable reference will expand to the corresponding value regardless of any value that has been set in the specified string table.
2. For details about reference tags, please refer to the documentation of the type StrTable.
func GetCmdDescList ¶
GetCmdDescList returns a list of descriptions for all subcommands defined under the specified command. Generally, it is shown as a part of help/instruction text. This function should be called in subcommand mode.
[PARAMETERS]
id string // The command identifier. If this is empty, it means generating a list of command descriptions for all top-level commands defined. format string // The format of each description text line.
[RETURNS]
[]string // The list of command descriptions. It will be nil if the specified command has no subcommands. All strings are ready to be printed. error // If the function succeeds, it is nil, otherwise it indicates that the app is in non-subcommand mode or an invalid command identifier is specified.
[REMARKS]
The key of the description string in the global string table follows this format:
"[TEXT]CMD.ID.DESC"
where ID is the string identifier of the command. A string should be specified to get formatted list. The following placeholders can be used:
"${#CMD.NAME}" // Expands to the command name. "${#CMD.DESC}" // Expands to the command description. Reference tags in the string will not expand.
func GetCmdHelpText ¶
GetCmdHelpText returns help text for the specified command using the preset text templates and format strings.
[PARAMETERS]
id string // The command identifier. If this is empty, it means generating help text for the root command of the app. It will be ignored if the app is in non-subcommand mode.
[RETURNS]
string // The help text which is ready to be printed. error // If the function succeeds, it is nil, otherwise it means that an invalid command identifier is specified.
[REMARKS]
1. Some of values to the following keys must be set in the global string table:
"[TEXT]HELP.USAGE.TITLE" // Translation for title "Usage", e.g., 用法. "[TEXT]HELP.USAGE.SYNTAX.CMD" // Translation for placeholder "[command]" in the syntax string, e.g., [命令]. "[TEXT]HELP.USAGE.SYNTAX.OPTS" // Translation for placeholder "[options...]" in the syntax string, e.g., [選項...]. "[TEXT]HELP.CMDS.TITLE" // Translation for title "Commands", e.g., 命令. Works only in subcommand mode. "[TEXT]HELP.CMD_OPTS.TITLE" // Translation for title "Command Options", e.g., 命令選項. "[TEXT]CMD.ID.ARGS" // Translation for placeholder of unparsed (non-option) arguments, e.g., [files...]. ID is the command identifier. Works only in subcommand mode. "[TEXT]CMD.ARGS" // As above but this works only in non-subcommand mode.
Reference tags in the strings will not expand.
2. A syntax string in the part "Usage" will expand like this:
"myapp subcmd subsubcmd [options...] [files...]"
where "myapp" is the app command name set in initializer.
3. Refer to the documentation of the function GetCmdDescList for details about how command description text is generated.
4. Refer to the documentation of the function GetCmdOptDescList for details about how command option description text is generated.
5. See text template files in rsrc/text/cmd_help for text layout.
func GetCmdLineArgs ¶
GetCmdLineArgs retrieves command line arguments of the calling process.
[PARAMETERS]
skip uint // Indicates the number of arguments to skip before recording in the argument list.
[RETURNS]
[]string // A list of command line arguments. It is nil if the value of [skip] exceeds the total number of the complete arguments.
[REMARKS]
1. Note that the complete arguments returned (when [skip] is 0) do not always start with the current program name or path since this depends on the specific creation of the process. If the path name for the executable that started the current process is needed, use os.Executable instead.
2. On Windows, this function calls [GetRawCmdLine] and [GetArgsFromCmdLine]. For details, please refer to the documentations.
3. On Linux, this function reads [/proc/self/cmdline].
func GetCmdOptDescList ¶
GetCmdOptDescList returns a list of descriptions for all options defined under the specified command. Generally, it is shown as a part of help/instruction text.
[PARAMETERS]
id string // The command identifier. It will be ignored if the app is in non-subcommand mode. format string // The format of each description text line.
[RETURNS]
[]string // The list of command option descriptions. It will be nil if the specified command has no options. All strings are ready to be printed. error // If the function succeeds, it is nil, otherwise it means that an invalid command identifier is specified.
[REMARKS]
1. The key of the description string in the global string table follows this format:
"[TEXT]OPT.ID.DESC"
where ID is the string identifier of the command option. A string should be specified to get formatted list. The following placeholders can be used:
"${#OPT.SYNTAX}" // Expands to the syntax of the option. "${#OPT.DESC}" // Expands to the option description. Reference tags in the string will not expand.
- In the syntax string, all long and short names of the option are separated by vertical bars. Short names go first. A single dash (-) is placed in front of the first short name and a double-dash (--) in front of the first long name. The argument name of the option, if exists, is surrounded by angle brackets, and starts with an equal sign (=). For example, "-x|y|z, --opt1|opt2|opt3=<ARG_NAME>" "-m, --opt" "-n <ARG_NAME>" "--opt" ...
func GetExitStatusDescList ¶
GetExitStatusDescList returns a list of descriptions for all exit status codes defined. Generally, it is shown as a part of help/instruction text.
[PARAMETERS]
format string // The format of each description text line.
[RETURNS]
[]string // The list of exit status descriptions. All strings are ready to be printed.
[REMARKS]
The key of the description string in the global string table follows this format:
"[TEXT]ES.ID.DESC"
where ID is the string identifier of the exit status. The list is sorted in ascending order of exit status codes. A string should be specified to get formatted list. The following placeholders can be used:
"${#ES.CODE}" // Expands to the exit status code. "${#ES.DESC}" // Expands to the exit status description. Reference tags in the string will not expand.
func GetLangInfoList ¶
GetLangInfoList returns a list of multi-language infos. Generally, it is shown as a part of help/instruction text.
[PARAMETERS]
format string // The format of each description text line.
[RETURNS]
[]string // The list of multi-language infos. All strings are ready to be printed.
[REMARKS]
The list is sorted in ascending order of language identifiers. A string should be specified to get formatted list. The following placeholders can be used:
"${#LANG.ID}" // Expands to the language identifier. "${#LANG.NAME}" // Expands to the language name.
func GetStr ¶
GetStr returns the specified string value in the global string table without expanding any reference tags. The function will return an empty value if the specified string is not defined.
[PARAMETERS]
id string // The identifier of the string.
[RETURNS]
string // The raw string.
##
REMARKS ¶
If a preset identifier or environment variable reference is specified, the function will return a value according to the corresponding rules regardless of any value that has been set. Refer to the documentation of the type StrTable for details.
func ImportDataFromJSONFile ¶
ImportDataFromJSONFile parses the specified JSON file and stores the result in a variable.
[PARAMETERS]
path string // The path of the JSON file. target interface{} // Should be a pointer to the variable that receives the data, cannot be nil.
[RETURNS]
error // If the function succeeds, it is nil, otherwise it is the first error encountered.
func ImportStrTableFromRsrc ¶
ImportStrTableFromRsrc parses the specified JSON data of the string table in the embedded resources and stores the result in a target string table.
[PARAMETERS]
path string // The internal path of the JSON file to be parsed in the embedded resources. st StrTable // The target string table. A nil value means the target is the global string table.
[RETURNS]
error // If the function succeeds, it is nil, otherwise it is the first error encountered.
func IsElevated ¶
func IsElevated() bool
IsElevated checks whether the calling process is running with elevated privileges.
[RETURNS]
bool // If the calling process is running with elevated privileges, it is true, otherwise it is false.
[REMARKS]
1. On Windows, the internal syscall is [IsUserAnAdmin], details in Microsoft documentation: [https://docs.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-isuseranadmin].
2. On Linux, the effective user id of the caller is checked.
func IsError ¶
IsError reports whether any error in the error chain matches the specified type. This function differs from errors.Is since it is merely based on the error type identifier.
[PARAMETERS]
err error // The last error from which to start checking along the error chain. id ErrId // The type identifier of the target error.
[RETURNS]
bool // It is true if any matched error is found, otherwise it is false.
func IsNewer ¶
IsNewer reports whether the former file is newer than the latter.
[PARAMETERS]
f1 fs.FileInfo // The former file info. f2 fs.FileInfo // The latter file info.
[RETURNS]
bool // It is true if the former file is newer than the latter, otherwise it is false.
func MakeCmdLine ¶
MakeCmdLine combines the given program path and arguments into a command line string. Any necessary escapes will be done.
[PARAMETERS]
path string // The command (program) path which should not be empty. Particularly, on Windows, it should not include any quote as well. args []string // The list of arguments.
[RETURNS]
string // The command line string, which will be empty if the function fails. error // If the function succeeds, it is nil, otherwise it is the first error encountered.
[REMARKS]
1. On Windows, the returned command line conforms to the rules of Windows command line parsing. There are certain rules to follow if a full command line string is used in a Windows API call to create a process (such as [CreateProcessW]). For details, please refer to Microsoft documentation: [https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw].
2. On Linux, every argument will be quoted by "", and the returned command line is intended only for debugging. In particular, it is not suitable for use as input to a shell.
func RunApp ¶
func RunApp(ai *AppInitializer)
RunApp runs the app with the specified initializer. Generally, it is called in the function [main].
[PARAMETERS]
ai *AppInitializer // Points to the app initializer. If this is nil, the function will panic.
[REMARKS]
1. The initialization will be done before the app runs.
2. After the initialization, any modification to commands, options or exit statuses defined in the initializer is invalid, as the app has got a safe copy of them.
3. If an error occurs in the initialization, the specified finalizer (if it is not nil) will be invoked and then the app will exit.
func SetFlag ¶
SetFlag sets the status for the specified app flag.
[PARAMETERS]
id string // The identifier of the app flag. status bool // The status value to be set for the app flag.
func SetLang ¶
SetLang sets the app to the specified language by importing the associated string values to the global string table.
[PARAMETERS]
id string // The language identifier which is defined in the language info.
[RETURNS]
error // If the function succeeds, it is nil, otherwise it is the first error encountered.
func SetStr ¶
func SetStr(id, str string)
SetStr sets the value for the specified string in the global string table.
[PARAMETERS]
id string // The identifier of the string. str string // The string value to be set.
[REMARKS]
If a preset identifier or environment variable reference is specified, the value will not be returned by calling GetStr. Refer to the documentation of the type StrTable for details.
func TraceAndPrintErrorChain ¶
func TraceAndPrintErrorChain(err error)
TraceAndPrintErrorChain traces the error chain and prints all details of the previous errors sequentially to the standard error stream. This function is for debugging.
[PARAMETERS]
err error // The last error from which to start tracing the error chain.
func WriteStr ¶
WriteStr expands the given string using the global string table and writes it to the target. All valid SGR tags will be interpreted. This function is equivalent to the call:
appbase.WriteStrX(wr, str, nil, true, true)
func WriteStrX ¶
WriteStrX writes the string to the target according to the specified options.
[PARAMETERS]
wr io.Writer // The target to write to. str string // The raw string to be written. st StrTable // The string table for expanding any string reference. If it is nil, the global string table is used. exRefTag bool // Indicates whether to expand all valid reference tags. If this is false, the parameter [st] will be ignored. interpretSGRTag bool // Indicates whether to interpret SGR tags. It is only when the target is associated with a console (terminal) that SGR tags work, otherwise, any valid SGR tag will be discarded no matter what value [interpretSGRTag] is. It means that "SGR sequences" will not be written to a real file to which a standard stream may have been redirected when calling this function with a string including "SGR tags".
[RETURNS]
error // If the function succeeds, it is nil, otherwise it is the first error encountered during writing.
[REMARKS]
1. For details about definitions of tags, please refer to the documentation of the type StrTable.
2. For details about rules of expanding reference tags, please refer to the documentation of the function ExStrX.
3. On Windows higher than Win10 1511 (build 10586, aka TH2), the ANSI/VT100 sequences are supported. While on lower versions, they cannot be interpreted natively by [conhost.exe], thus they will be printed on the screen as they are.
4. When using functions of [WriteStr...] families (including [(stdStream).WriteStr...] families) on Windows, it is not recommended to call others such as fmt.Print with strings including SGR sequences in case of unexpected output.
Types ¶
type AppInitializer ¶
type AppInitializer struct { // The app version value. AppVer string // The app command name used in command line. Generally, it is the program name. AppCmdName string // The info of embedded resources (including multi-language assets). Leave it nil if no embedded resource are needed. Rsrc *Rsrc // Indicates whether the app has subcommands. SubCmdMode bool // All commands to be defined. If [SubCmdMode] is false, this will be ignored and [OptList] will be used. CmdList []*Cmd // All command options to be defined in global. If [SubCmdMode] is true, this will be ignored and [CmdList] will be used. CmdOptList []*CmdOpt // All exit statuses ([code]id) to be defined. An exit status consists of a status code and a string identifier which should be unique for multi-language features. ExitStatusList map[int]string // The entry function to run the app after a seccessful initialization. The error returned by this function will be passed to the finalizer. Entry func() error // A finalizer is a specified function that performs any necessary handling before the app exits. It will be invoked when the app is exiting. If the exit is caused by an error, it will be passed as the parameter. Finalizer func(error) }
A pointer to this initializer should be passed to RunApp that does initialization work by locating embedded resources, defining command options and exit statuses, etc.
type ArgErr ¶
type ArgErr struct { // The superior command name. This is empty unless the error indicates an unrecognized non-top-level command name. SupCmd string // The command name in the error. This will always be empty if the app is in non-subcommand mode. Cmd string // The option name in the error, which has a double-dash (--) or single dash (-) prefix. Opt string // Indicates which type of argument error it is. See definitions of error type identifier constants for details. Type ErrId }
Context of an argument error encountered when parsing command line arguments.
func ParseArgs ¶
ParseArgs parses the given command line arguments. Any unparsed arguments and argument errors will be returned.
[PARAMETERS]
args []string // A list of command line arguments to be parsed. Note that the program name or path, which is usually the first one, is not supposed to be included.
[RETURNS]
unparsed []string // A list of all unparsed arguments in order. procOpts func() // A function for calling procedural (callback) function of each valid option recognized in order. argErrs []*ArgErr // A list of all argument errors encountered in order. An argument error can be an unrecognized command/option or that the required argument for an option is missing. A nil value means that no argument error is encountered. err error // If the function succeeds, it is nil, otherwise it means uninitialized.
type Cmd ¶
type Cmd struct { // The command identifier, the corresponding flag of this will be set to true when the command is specified. Every command is unique as it takes a specific position in the command tree. So every identifier must be unique in all commands. Id string // The command name which is recognized in the command line and must not contain any white-space characters. It must be different from that of subcommands under the same superior command. If the command is top-level, which does not have a superior, the name should be different from that of all other top-level commands. Name string // Indicates whether this is a final command without any subcommand. Final bool // The subcommands available for the command. It will be ignored when [Final] is set to true. SubCmds []*Cmd // The options available for the command. It will be ignored when [Final] is set to false. Opts []*CmdOpt // contains filtered or unexported fields }
Command info. A command can have several subcommands, so do the subcommands.
type CmdOpt ¶
type CmdOpt struct { // The command option identifier, which should be unique if multi-language features is needed. Id string // The long names for the option. A valid long name cannot start with a dash (-), and cannot contain a vertical bar (|), equal sign (=) or white-space character. A long name is optional if at least one short name is set. All long names must be unique in the command to which the option belongs. LongNames []string // The short names for the option. A valid short name is a UTF-8 character excluding a dash (-), a vertical bar (|) or a white-space character. A short name is optional if at least one long name is set. All short names must be unique in the command to which the option belongs. ShortNames []rune // The argument name which generally indicates the meaning of the argument. This should be set to non-empty if the option requires an argument, as empty indicates that no argument is required. ArgName string // The procedural (callback) function associated with the option, which is invoked in [ParseArgs]. This must not be nil. An argument for the option will be passed as the parameter and it is always empty if no argument is required. Proc func(string) }
Command option info. The option forms used in command line are similar to that in GNU style.
type Err ¶
type Err = *errWrapper
Error wrapper. Errors can be wrapped to make an error chain. Of course, it is recommended to make the error chain shorter.
func NewError ¶
NewError wraps and returns a new error.
[PARAMETERS]
id ErrId // The type identifier of the new error. desc string // The error description. prev error // The previous error of the error chain, which is the error wrapped by this one. It is nil when this is the first one.
[RETURNS]
Err // The new error.
type Rsrc ¶
type Rsrc struct { // Points to the embedded resources containing text templates, multi-language assets, etc. FS *embed.FS // The internal path of multi-language info file (JSON) in the embedded resources. Leave it empty if multi-language features are not needed. LangInfo string }
Info of embedded resources.
type Singleton ¶
type Singleton = *singleton
Kernel-level singleton which is useful in interprocess communications (IPC).
func NewSingleton ¶ added in v0.1.2
NewSingleton creates a kernel-level singleton which is ready to be enabled by calling the method [Enable].
[PARAMETERS]
name string // A unique string for the singleton, e.g., a UUID. It will be used to create an identifier of SHA256 hash.
[RETURNS]
*Singleton // Points to the new singleton.
func (Singleton) Disable ¶ added in v0.1.2
Disable disables the singleton.
[RETURNS]
error // If the function succeeds, it is nil, otherwise it is the first error encountered.
func (Singleton) Enable ¶ added in v0.1.2
Enable tries to enable the singleton.
[RETURNS]
error // If the function succeeds, it is nil, otherwise it is the first error encountered.
[REMARKS]
1. On Windows, it is implemented by a kernel-level mutex object. For details, please refer to Microsoft documentation: [https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createmutexw].
2. On Linux, it is implemented by a UNIX domain socket in the abstract namespace. For details, please refer to [https://troydhanson.github.io/network/Unix_domain_sockets.html].
type StrTable ¶
String table. The following definitions apply to any string table:
1. <String Identifier>: The unique identifier of the string in the string table, which is the key of the string element. There are three types:
(1) <Preset>: The preset identifiers have their preset values or preset rules when expanding strings by function [ExStr...]. Please refer to the comments in the variable [exStrPresetRules] for details.
(2) <Environment Variable Reference>: If the identifier starts with an asterisk (*), it will be regarded as an environment variable reference. The variable name does not contain the leading asterisk.
(3) <Regular>: Any other identifiers except for the above.
2. <String Value>: The value of the string element in which the following types of substrings (segments) can be included:
(1) <SGR (Select Graphic Rendition) Tag>: Follows the format:
"$[n1;n2;...]"
It accepts integer parameters (n1, n2, ...) ranging in [0,107] separated by semicolons without any other characters. It is only when strings are printed to the console that SGR tags may work. They adjust the formatting of all future writes to the console output text buffer. For details, please refer to [https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters].
(2) <Reference Tag>: Follows the format:
"${ID}"
where ID is the identifier of the referenced target string in a specified string table. The ID must not contain curly braces ({ or }), otherwise it will not be recognized as a tag. Refer to the documentation of the function ExStrX for rules of expanding reference tags.
(3) <Regular>: Any other substrings except for the above.
3. <Tag Symbol>: A dollar sign ($) will be regarded as a tag symbol when it leads a tag. There is an escape rule for two or more consecutive tag symbols when expanding a string reference, e.g.,
"$$${foo}$${bar}"
suppose that "foo" and "bar" have been defined in a string table and the value of "foo" is "FOO", then the whole string will expand to
"$FOO${bar}"
which means that double dollar signs ($$) will be regarded as a single literal character ($) and it cannot be recognized as the tag symbol of an SGR or reference tag.