Skip to content

Latest commit

 

History

History
253 lines (201 loc) · 11 KB

api-reference.md

File metadata and controls

253 lines (201 loc) · 11 KB

cli-fp API reference

How do I...? · Commands · Options · Current limitations

Use this page to look up the current public, application-facing API. For a complete program, start with your first CLI. The public units in src/ are the authoritative declarations. Signature blocks below are API declarations; application code is always labelled as a program-setup fragment and names its variables or states the command pattern it depends on.

Units to use

Unit Use it for
CLI.Interfaces ICommand, ICLIApplication, parameter and progress interfaces
CLI.Application Application factory, concrete debugging/completion support
CLI.Command TBaseCommand and parameter registration helpers
CLI.Parameter Low-level ICommandParameter construction
CLI.Console Coloured terminal output and cursor control
CLI.Progress Spinners and progress bars
CLI.Errors Framework exception type
CLI.Validation Supported definition-validation helpers; registration normally calls them for you

Application

Create and run

function CreateCLIApplication(const Name, Version: string): ICLIApplication; overload;
function CreateCLIApplication(const Name, Version: string;
  const RootCommand: ICommand): ICLIApplication; overload;

Use the two-argument overload for a command-first application. Use the three-argument overload when an unnamed root command should run for myapp [options]. The factory constructs the application; it does not parse process arguments. Name is display metadata, not a compiler output filename. Invoke the actual binary produced by FPC; parsing and dispatch happen when you call App.Execute.

The following program-setup fragment needs CLI.Interfaces and CLI.Application. It assumes TRootCommand is a declared TBaseCommand descendant with an overridden Execute; Root is the instance passed to the factory.

var
  App: ICLIApplication;
  Root: TRootCommand;
begin
  Root := TRootCommand.Create('', 'Run the default action');
  App := CreateCLIApplication('myapp', '1.0.0', Root);
  Halt(App.Execute);
end.

ICLIApplication exposes:

procedure RegisterCommand(const Command: ICommand);
function Execute: Integer;

Execute parses and validates arguments, services built-in requests, and returns the selected command's exit code.

Concrete application features

TCLIApplication also exposes DebugMode, Version, RootCommand, and Commands. It has test-oriented helpers and deprecated completion callback methods; those are not needed for ordinary applications. The callback methods are no-op compatibility members in 1.x—see limitations.

Commands

TBaseCommand

{ Public members }
constructor Create(const AName, ADescription: string);
function Execute: Integer; virtual; abstract;
procedure AddSubCommand(const Command: ICommand);

Protected members for descendants:

protected
function GetParameterValue(const Flag: string; out Value: string): Boolean;
procedure ShowHelp;

Subclass TBaseCommand, override Execute, register options during setup, and return 0 on success. Use an empty AName for a root command.

GetParameterValue is a protected member for command descendants, so call it from your descendant's Execute. It finds either registered flag spelling and returns values as strings. Lookup is case-insensitive and uses the last occurrence across both aliases. The Boolean return indicates an available value or non-empty default, not whether the user supplied the option. After parsing:

Case Return Output string
Non-empty supplied value True Supplied value
Omitted option with a non-empty default True Default
Empty non-Boolean value with a non-empty default True Default
Omitted/empty non-Boolean without a default False ''
Bare Boolean or --bool= True 'true'
Omitted Boolean without a default False 'false'
Unknown flag, or lookup before a parsed list is attached False ''

An omitted AddFlag normally returns True with 'false' because its default is non-empty. Requiredness and type validation use this same lookup contract. ShowHelp is also protected, for a command that intentionally acts as a help-only group.

Date/time and array values are retrieved through the same protected string helper: date/time text uses YYYY-MM-DD HH:MM, and arrays are returned as the raw comma-separated text. cli-fp 1.x has no separate typed getter; convert or split these values in the command that owns their application meaning.

Register parameters

Purpose Signature
Generic parameter AddParameter(ShortFlag, LongFlag, Description, Required, ParamType, DefaultValue, AllowedValues)
String AddStringParameter(ShortFlag, LongFlag, Description, Required = False, DefaultValue = '')
Integer AddIntegerParameter(ShortFlag, LongFlag, Description, Required = False, DefaultValue = '')
Float AddFloatParameter(ShortFlag, LongFlag, Description, Required = False, DefaultValue = '')
Presence flag AddFlag(ShortFlag, LongFlag, Description, DefaultValue = 'false')
Explicit Boolean AddBooleanParameter(ShortFlag, LongFlag, Description, Required, DefaultValue)
Path AddPathParameter(ShortFlag, LongFlag, Description, Required = False, DefaultValue = '')
Enum AddEnumParameter(ShortFlag, LongFlag, Description, AllowedValues, Required = False, DefaultValue = '')
Date/time AddDateTimeParameter(ShortFlag, LongFlag, Description, Required = False, DefaultValue = '')
Comma-separated items AddArrayParameter(ShortFlag, LongFlag, Description, Required = False, DefaultValue = '')
Password AddPasswordParameter(ShortFlag, LongFlag, Description, Required = False)
URL AddUrlParameter(ShortFlag, LongFlag, Description, Required = False, DefaultValue = '')

All parameters use string flag and description arguments. AllowedValues is a pipe-separated string, such as debug|info|warn. See options for validation behavior and How do I...? for minimal examples.

AddFlag and AddBooleanParameter both register ptBoolean, accept explicit false, and interpret bare presence as true. AddFlag always sets Required=False and its default argument is 'false'; AddBooleanParameter requires explicit Required and DefaultValue arguments. Float validation and conversion use the process locale through TryStrToFloat.

Parameter kinds

TParameterType contains ptString, ptInteger, ptFloat, ptBoolean, ptPath, ptEnum, ptDateTime, ptArray, ptPassword, and ptUrl.

The canonical date/time text is YYYY-MM-DD HH:MM; existing v1.x values with seconds remain accepted for compatibility.

ICommandParameter exposes ShortFlag, LongFlag, Description, Required, ParamType, DefaultValue, and AllowedValues. For lower-level registration, use:

function CreateParameter(const ShortFlag, LongFlag, Description: string;
  Required: Boolean; ParamType: TParameterType;
  const DefaultValue: string = ''; const AllowedValues: string = ''): ICommandParameter;

Then pass the result to AddParameter(const Parameter: ICommandParameter).

Command contracts

ICommand is the minimal command contract:

function GetName: string;
function GetDescription: string;
function GetParameters: specialize TArray<ICommandParameter>;
function GetSubCommands: specialize TArray<ICommand>;
function Execute: Integer;

TBaseCommand implements it and is the normal choice when your command needs framework-managed parameter lookup. A custom ICommand may also implement ICommandParameterReceiver.SetParsedParams to receive parsed values.

Terminal output

TConsole

class procedure Write(const Text: string); overload;
class procedure Write(const Text: string; const FgColor: TConsoleColor); overload;
class procedure WriteLn(const Text: string); overload;
class procedure WriteLn(const Text: string; const FgColor: TConsoleColor); overload;

For cursor-oriented terminal work, TConsole also provides foreground and background colour setters, ResetColors, ClearLine, cursor movement, and save/restore cursor methods. TConsoleColor offers standard and bright colour values, including ccGreen, ccYellow, and ccRed. Coloured writes reset to default colours, not arbitrary previous colour state. They disable colour when stdout is redirected or NO_COLOR is non-empty; an empty NO_COLOR value alone does not disable colour.

Progress

function CreateSpinner(const Style: TSpinnerStyle = ssLine): IProgressIndicator;
function CreateProgressBar(const Total: Integer;
  const Width: Integer = 10): IProgressIndicator;

IProgressIndicator has Start, Stop, and Update(const Progress: Integer; const ACaption: string = ''). Spinner styles are ssDots, ssLine, ssCircle, ssSquare, ssArrow, ssBounce, and ssBar. Use Update repeatedly during work, then call Stop in finally.

Errors and built-in requests

CLI.Errors provides public 1.x compatibility types (ECLIException and related classes) for applications that choose to use them. It is not the general runtime-error contract: definition checks can raise standard SysUtils argument exceptions and command-line validation normally reports an error and returns a non-zero exit code. Catch the concrete exception types your own application introduces, or broader Exception only where useful recovery or context is possible.

Applications receive -h/--help, --help-complete, and -v/--version. From v1.6.1, -v/--version are reserved case-insensitively throughout command trees. Used as options, they print the application version, return 0, and skip validation/dispatch at root, named and nested scopes. An equals-form value such as --name=--version remains a value. Conflicting definitions now raise a developer-facing exception; migrate verbose aliases to -d or long-only --verbose. -V is also reserved because matching is case-insensitive. When it is the first argument, --completion-file prints a Bash script and --completion-file-pwsh prints a PowerShell script. See shell completion for usage.

Definitions are validated when commands are registered or parameters are added. Invalid names, flags, duplicate siblings/options, nil commands, and command-tree cycles raise developer-facing exceptions. The parser rejects unexpected positional arguments with exit code 1; it does not implement the -- terminator in v1.x.

Supporting validation

CLI.Validation exposes ValidateCommandName, ValidateParameterDefinition, ValidateCommandTree, and CommandTreeContainsName. They are supported library helpers for advanced integration and tests; normal application setup should use TBaseCommand and RegisterCommand, which enforce these definition checks automatically.