diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..4596e57 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,76 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Commands + +```bash +# Run all specs +crystal spec + +# Run a single spec file +crystal spec spec/command_spec.cr + +# Type-check without running +crystal build src/cligen.cr --no-codegen + +# Install dependencies +shards install +``` + +## What This Is + +`cligen` is a Crystal **shard (library)** — not a standalone application. It wraps Crystal's built-in `OptionParser` with an annotation- and macro-driven system that auto-generates CLI parsers from class definitions. Users of the shard subclass `CliGen::Command` and annotate methods; the library generates the `OptionParser` wiring at compile time via Crystal macros. + +## Architecture + +### Entry point: `src/cligen.cr` + +Defines the `CliGen` module. The `macro finished` hook calls `define_root_parser`, which scans all `CliGen::Command` subclasses at compile time and registers each as a subcommand on the root `OptionParser`. `CliGen.parse` runs the root parser. + +`ADDITIONAL_DEFAULT_FLAGS` / `add_default_flag` let users inject extra flags into every parser (root and subcommand). + +### Command definition: `src/cligen/command.cr` + +`CliGen::Command` is the base class. When subclassed, `macro inherited` installs a `macro finished` block that triggers four code-generation macros in order: + +1. `define_actions` — collects all `@[SubCommand]`-annotated class methods into `ACTIONS : Array(String)` and `@@action : String`. +2. `define_header` — builds the `HEADER` string (banner + examples) from `@[SubCommand]` and `@[CommandSelection]` annotation metadata. +3. `define_runner` (skipped if `@[CommandInfo(def_runner: false)]`) — generates a `self.run` method that dispatches on `@@action` or a selection variable via a `case` statement. +4. `define_action_setter` — generates `self.action=` with bounds-checking against `ACTIONS`. + +#### Key macros on `Command` + +- **`define_argument`** — declares a class-level variable (`@@`) and an annotated setter method (`@[CommandArgument]`). Handles `String`, `Bool`, `Int32`, `Array(String|Int32)`, and `Time`. Optional `check:` proc, `logger:` method, and `def_getter:` flag. +- **`define_selection`** — like `define_argument` but validates against a fixed list of values; annotated with `@[CommandArgument]` and participates in selection-based dispatch. + +### Parser generation: `src/cligen/command/parser.cr` + +`CliGen::Parser` is `extend`ed by `Command`. It provides `define_parser`, which generates `self.make_parser(parent_parser)`. That method: + +1. Creates a subparser `OptionParser` with the command's `HEADER` as banner. +2. Wires `@[CommandSelection]`-annotated methods as `parser.on(name, description)` that set the selection variable. +3. Wires `@[SubCommand]`-annotated methods as subcommand strings that set `@@action`. +4. Wires `@[CommandArgument]`-annotated methods as `parser.on(short, long, description)` flag handlers. +5. Calls `CliGen.define_default_flags` (adds `-h`/`--help`, error handlers). +6. Registers the whole subparser on `parent_parser` under the command's lowercase class name. + +### Annotations + +| Annotation | Applied to | Purpose | +|---|---|---| +| `@[CommandInfo(description:, def_runner:)]` | Command subclass | Required; provides the description shown in root help; `def_runner: false` skips auto-generating `run` | +| `@[SubCommand(description:, examples:)]` | class method on Command | Marks a method as a dispatachable subcommand | +| `@[CommandArgument(short:, long:, description:, type:)]` | class method on Command | Generated automatically by `define_argument`/`define_selection`; drives parser wiring | +| `@[CommandSelection(selector:, description:, examples:)]` | class method on Command | Alternative to `SubCommand`; dispatches via a named selector variable instead of `@@action` | +| `@[CommandPreRun]` | class method on Command | Methods run unconditionally before dispatch inside `self.run` | +| `@[DefaultFlag]` | (reserved) | Defined but not currently used in generation | + +### Supporting files + +- `src/cligen/format.cr` — date/datetime format strings used by `Time` argument parsing. +- `src/cligen/regex.cr` — regexes for validating date/datetime input strings. + +## Spec structure + +`spec/command_spec.cr` uses Crystal's macro system heavily: most `it` blocks are generated at compile time by inspecting `CommandSubclass` via `@type` introspection. The `macro finished` wrapper around the entire `describe` block is required because `make_parser` and `run` don't exist until all `macro finished` hooks have fired. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..614ef80 --- /dev/null +++ b/Makefile @@ -0,0 +1,22 @@ +DOC_DIR := docs +PROJECT_NAME := CliGenerator +.DEFAULT_GOAL := spec + +.PHONY: spec spec_silent doc doc_show +.SILENT: spec spec_silent doc doc_show + +.DEFAULT: + @echo "BRUV "$@" isn't a valid target" + +spec: + crystal spec -v + +spec_silent: + crystal spec + +doc: + crystal doc --project-name "$(PROJECT_NAME)" --output "$(DOC_DIR)" + echo "Done Generating docs" + +doc_show: + cd "$(DOC_DIR)"; python -m http.server diff --git a/design.adoc b/design.adoc new file mode 100644 index 0000000..f55182b --- /dev/null +++ b/design.adoc @@ -0,0 +1,76 @@ += Crytal Cli Generator + +:author: Tristan Anclelet +:email: tristanancelet@yahoo.com +:toc: + +This document outlines the overall design of the CliGen shard & it's underlying classes/objects & their usecases. + +== Architecture + +The desire for this project is to provide a framework for generating commandline arg-parses & command dispatch built into a class/object. + +The idea is to (much like `JSON::Serializable` & `YAML::Serializable`) is to use macros to help defining a Command object and abstract the command-line away from the codebase needing input from the user at init time. + +=== Command Objects + +The core of this codebase is the `CliGen::Command` object. + +This is the object that is meant to provide you the hook into being able to utilize the codebase. It is where you are able to define all of your expecetd arguments/flags & any selectables (aka, instance variable that you want the user to choose one value for. `ex: -f|--format json|yaml|ecr`). + +To make this all possible we load the base class with macros that help define your variables & inform the framework how it needs to handle arguments being presented to your command object setters. + +[source,crystal] +---- +require "cligen" + +module MyModule + class MyCommand < CliGen::Command + argument(myvar : Int32 = 23, + long: "--myvar VAR", + short: "-m", + description: "This tells the utility how many times to do thing", + validate: ->(v : Int32) : Bool { (1..23).includes?(v) } + ) + + selection(output_format : String = "ecr", + long: "--format FORMAT", + short: "-f", + description: "Inform the utility what output you want the data in", + options: %w[ json yaml ecr ] + ) + + DO_THING_EXAMPLES = [ + "myutil mycommand do_thing --myvar 5" + ] + + subcommand do_thing : Int32, + description: "Do the THING", + examples: MyModule::MyCommand::DO_THING_EXAMPLES \ + do + output = 0 + + @myvar.times do |i| + puts "thing done %i times" % [ i + 1 ] + output += i + end + + output + end + end + + CliGen::App.process(ARGV) +end +---- + +The examples like above provide a "DSL-esk" way of defining: +- Instance Variables, +- Short/Long flags +- Description of the flags (used in the help output as well) +- A verification proc/lambda for doing ad-hoc checks of the value provided by the user (essentially allowing you to implement your own option: key like in selection) +- Selections (currently compile-time and will open it up to runtime collecting of options later on based on defined annotations in the class) +- define subcommands of this current command + +==== How it works + +Using crystal macros, you define the shape (arguments/flags, selections, work functions/subcommands, etc diff --git a/docs/404.html b/docs/404.html new file mode 100644 index 0000000..46e67d4 --- /dev/null +++ b/docs/404.html @@ -0,0 +1,177 @@ + + + + + + + + + + + + + + + + + CliGenerator object_rework-dev + + + + + + + + + + +
+

+ 404 Not Found +

+ +

+ This page is unavailable in this version of the API docs. +

+ +

+ You can use the sidebar to search for your page, or try a different + Crystal version. +

+ +
+ + diff --git a/docs/CliGen.html b/docs/CliGen.html new file mode 100644 index 0000000..812004f --- /dev/null +++ b/docs/CliGen.html @@ -0,0 +1,363 @@ + + + + + + + + + + + + + + + + + CliGen - CliGenerator object_rework-dev + + + + + + + + + + +
+

+ + + module + CliGen + +

+ + + + + + + + + + + + + + + + + + + + +

+ + + + Defined in: +

+ + + cligen.cr + +
+ + + cligen/annotations.cr + +
+ + + cligen/app.cr + +
+ + + cligen/arg.cr + +
+ + + cligen/command.cr + +
+ + + cligen/command/argument.cr + +
+ + + cligen/command/selection.cr + +
+ + + cligen/command/subcommand.cr + +
+ + + cligen/command/trigger.cr + +
+ + + cligen/command_node.cr + +
+ + + cligen/flag.cr + +
+ + + cligen/generate.cr + +
+ + + cligen/match_type.cr + +
+ + + + + +

+ + + + Constant Summary +

+ +
+ +
+ ADDITIONAL_DEFAULT_FLAGS = [] of AdditionalDefaultFlag +
+ + +
+ APPNAME = File.basename(PROGRAM_NAME) +
+ + +
+ VERSION = "0.1.0" +
+ + +
+ + + + + + +

+ + + + Class Method Summary +

+ + + + + + + + +
+ +
+ + + + +

+ + + + Class Method Detail +

+ +
+
+ + def self.add_default_flag(short : String = "", long : String = "", description : String = "", &work : String -> ) + + # +
+ +
+
+ +
+
+ + + + + + + + +
+ + + diff --git a/docs/CliGen/AdditionalDefaultFlag.html b/docs/CliGen/AdditionalDefaultFlag.html new file mode 100644 index 0000000..d8aad54 --- /dev/null +++ b/docs/CliGen/AdditionalDefaultFlag.html @@ -0,0 +1,451 @@ + + + + + + + + + + + + + + + + + CliGen::AdditionalDefaultFlag - CliGenerator object_rework-dev + + + + + + + + + + +
+

+ + + struct + CliGen::AdditionalDefaultFlag + +

+ + + + + + + + + + + + + + + + + + + + + + +

+ + + + Defined in: +

+ + + cligen.cr + +
+ + + + + + + +

+ + + + Constructors +

+ + + + + + + + +

+ + + + Instance Method Summary +

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + +

+ + + + Constructor Detail +

+ +
+
+ + def self.new(short : String, long : String, description : String, work : String -> ) + + # +
+ +
+
+ +
+
+ + + + + + + + +

+ + + + Instance Method Detail +

+ +
+
+ + def clone + + # +
+ +
+
+ +
+
+ +
+
+ + def copy_with(short _short = @short, long _long = @long, description _description = @description, work _work = @work) + + # +
+ +
+
+ +
+
+ +
+
+ + def description : String + + # +
+ +
+
+ +
+
+ +
+
+ + def long : String + + # +
+ +
+
+ +
+
+ +
+
+ + def short : String + + # +
+ +
+
+ +
+
+ +
+
+ + def work : String -> + + # +
+ +
+
+ +
+
+ + + + +
+ + + diff --git a/docs/CliGen/App.html b/docs/CliGen/App.html new file mode 100644 index 0000000..3b7600b --- /dev/null +++ b/docs/CliGen/App.html @@ -0,0 +1,451 @@ + + + + + + + + + + + + + + + + + CliGen::App - CliGenerator object_rework-dev + + + + + + + + + + +
+

+ + + class + CliGen::App + +

+ + + + + + + +

+ + + + Overview +

+ +

This serves as the default App object, that holds a copy of all flags & +handles flag processing until it hands off to the user defined commands

+ + + + + + + + + + + + + + + + +

+ + + + Defined in: +

+ + + cligen/app.cr + +
+ + + + + + + +

+ + + + Constructors +

+ + + + +

+ + + + Class Method Summary +

+ + + + + + +

+ + + + Instance Method Summary +

+ + + + +
+ + + +

Instance methods inherited from class CliGen::CommandNode

+ + + + check! + check!, + + + + check_for_duplicates!(flags : Array(BaseFlag)) + check_for_duplicates!, + + + + find_match(arg : String) + find_match, + + + + process(args : Array(String))
process(args : Array(Arg)) : Nil
+ process
+ + + + + + +

Constructor methods inherited from class CliGen::CommandNode

+ + + + new(name : String, flags : Array(CliGen::BaseFlag), commands : Array(CliGen::CommandNode), pre_run_commands : Array(_), post_run_commands : Array(_)) + new + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + +

+ + + + Constructor Detail +

+ +
+
+ + def self.new(name, flags, commands, pre_run_commands, post_run_commands) + + # +
+ +
+
+ +
+
+ + + + +

+ + + + Class Method Detail +

+ +
+
+ + def self.process(args : Array(String) = ARGV) + + # +
+ +
+ +

Serves as a convinence method for the user to call to begin processing an +argument array provided by the user.

+

This defaults to ARGV for convinence if no arguments are passed through

+
+ +
+
+ +
+
+ + + + + + +

+ + + + Instance Method Detail +

+ +
+
+ + def check! + + # +
+ +
+
+ +
+
+ + + + +
+ + + diff --git a/docs/CliGen/Arg.html b/docs/CliGen/Arg.html new file mode 100644 index 0000000..ce837ff --- /dev/null +++ b/docs/CliGen/Arg.html @@ -0,0 +1,450 @@ + + + + + + + + + + + + + + + + + CliGen::Arg - CliGenerator object_rework-dev + + + + + + + + + + +
+

+ + + class + CliGen::Arg + +

+ + + + + + + +

+ + + + Overview +

+ +

This class serves as a "argument wrapper" to force a fail-fast approach to +arg-parsing.

+

It wraps around the argument + index of the argument to do state tracking +and ensure that each argument is only processed once (plus allows for +easier filtering of processed arguments to avoid having to do index math)

+
args.reject(&.processed?) # returns the args that haven't been processed yet
+

It expects each argument to only be processed once and will force a raise +if the argument has Arg#processed called a second time. This is to force +the developer (me) to fix any processing issues during the development of +this framework.

+ + + + + + + + + + + + + + + + +

+ + + + Defined in: +

+ + + cligen/arg.cr + +
+ + + + + + + +

+ + + + Constructors +

+ + + + + + + + +

+ + + + Instance Method Summary +

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + +

+ + + + Constructor Detail +

+ +
+
+ + def self.new(value : String, index : Int32) + + # +
+ +
+
+ +
+
+ + + + + + + + +

+ + + + Instance Method Detail +

+ +
+
+ + def index : Int32 + + # +
+ +
+ +

The index of the argument in the array it was in

+
+ +
+
+ +
+
+ +
+
+ + def processed + + # +
+ +
+ +

This serves as a trigger that tells the object that it has been processed

+

This will raise an exception if it is re-called after already having been +processed.

+
+ +
+
+ +
+
+ +
+
+ + def processed? : Bool + + # +
+ +
+ +

The "flag"/variable that tracks is the Arg has been processed yet

+
+ +
+
+ +
+
+ +
+
+ + def value : String + + # +
+ +
+ +

The raw string argument provided from the user

+
+ +
+
+ +
+
+ + + + +
+ + + diff --git a/docs/CliGen/Argument.html b/docs/CliGen/Argument.html new file mode 100644 index 0000000..94dea09 --- /dev/null +++ b/docs/CliGen/Argument.html @@ -0,0 +1,233 @@ + + + + + + + + + + + + + + + + + CliGen::Argument - CliGenerator object_rework-dev + + + + + + + + + + +
+

+ + + annotation + CliGen::Argument + +

+ + + + + + + + + + + + + + + + + + + + +

+ + + + Defined in: +

+ + + cligen/annotations.cr + +
+ + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + +
+ + + diff --git a/docs/CliGen/BaseFlag.html b/docs/CliGen/BaseFlag.html new file mode 100644 index 0000000..e9d3ae9 --- /dev/null +++ b/docs/CliGen/BaseFlag.html @@ -0,0 +1,528 @@ + + + + + + + + + + + + + + + + + CliGen::BaseFlag - CliGenerator object_rework-dev + + + + + + + + + + +
+

+ + + abstract class + CliGen::BaseFlag + +

+ + + + + + + + + + + + + + + + + +

+ + + + Direct Known Subclasses +

+ + + + + + + +

+ + + + Defined in: +

+ + + cligen/flag.cr + +
+ + + + + + + +

+ + + + Constructors +

+ + + + + + + + +

+ + + + Instance Method Summary +

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + +

+ + + + Constructor Detail +

+ +
+
+ + def self.new(var : String, short : String | Nil, long : String | Nil, env_var : String | Nil, description : String) + + # +
+ +
+
+ +
+
+ + + + + + + + +

+ + + + Instance Method Detail +

+ +
+
+ + def description : String + + # +
+ +
+
+ +
+
+ +
+
+ + def env_var : String | Nil + + # +
+ +
+
+ +
+
+ +
+
+ + def long : String | Nil + + # +
+ +
+
+ +
+
+ +
+
+ + def long_key : String + + # +
+ +
+
+ +
+
+ +
+
+ + def matches?(token : String) : Bool + + # +
+ +
+
+ +
+
+ +
+
+ abstract + def raw_value : String | Nil + + # +
+ +
+
+ +
+
+ +
+
+ abstract + def satisfied? : Bool + + # +
+ +
+
+ +
+
+ +
+
+ + def short : String | Nil + + # +
+ +
+
+ +
+
+ +
+
+ abstract + def validate! : Nil + + # +
+ +
+
+ +
+
+ +
+
+ + def var : String + + # +
+ +
+
+ +
+
+ + + + +
+ + + diff --git a/docs/CliGen/Command.html b/docs/CliGen/Command.html new file mode 100644 index 0000000..6368b1c --- /dev/null +++ b/docs/CliGen/Command.html @@ -0,0 +1,379 @@ + + + + + + + + + + + + + + + + + CliGen::Command - CliGenerator object_rework-dev + + + + + + + + + + +
+

+ + + class + CliGen::Command + +

+ + + + + + + + + + + + + + + + + + + + + + +

+ + + + Defined in: +

+ + + cligen/command.cr + +
+ + + cligen/command/argument.cr + +
+ + + cligen/command/selection.cr + +
+ + + cligen/command/subcommand.cr + +
+ + + cligen/command/trigger.cr + +
+ + + + + + + + + + + +

+ + + + Macro Summary +

+ + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + +

+ + + + Macro Detail +

+ +
+
+ + macro argument(variable, short, long, description, validation = nil) + + # +
+ +
+
+ +
+
+ +
+
+ + macro selection(variable, short, long, description, options) + + # +
+ +
+
+ +
+
+ +
+
+ + macro subcommand(func, description, examples = nil, &block) + + # +
+ +
+
+ +
+
+ +
+
+ + macro trigger(short, long, argument = nil, &on_match) + + # +
+ +
+
+ +
+
+ + + + + + +
+ + + diff --git a/docs/CliGen/CommandInfo.html b/docs/CliGen/CommandInfo.html new file mode 100644 index 0000000..7d596a8 --- /dev/null +++ b/docs/CliGen/CommandInfo.html @@ -0,0 +1,233 @@ + + + + + + + + + + + + + + + + + CliGen::CommandInfo - CliGenerator object_rework-dev + + + + + + + + + + +
+

+ + + annotation + CliGen::CommandInfo + +

+ + + + + + + + + + + + + + + + + + + + +

+ + + + Defined in: +

+ + + cligen/annotations.cr + +
+ + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + +
+ + + diff --git a/docs/CliGen/CommandNode.html b/docs/CliGen/CommandNode.html new file mode 100644 index 0000000..7e323d5 --- /dev/null +++ b/docs/CliGen/CommandNode.html @@ -0,0 +1,441 @@ + + + + + + + + + + + + + + + + + CliGen::CommandNode - CliGenerator object_rework-dev + + + + + + + + + + +
+

+ + + class + CliGen::CommandNode + +

+ + + + + + + + + + + + + + + + + +

+ + + + Direct Known Subclasses +

+ + + + + + + +

+ + + + Defined in: +

+ + + cligen/command_node.cr + +
+ + + + + + + +

+ + + + Constructors +

+ + + + + + + + +

+ + + + Instance Method Summary +

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + +

+ + + + Constructor Detail +

+ +
+
+ + def self.new(name : String, flags : Array(CliGen::BaseFlag), commands : Array(CliGen::CommandNode), pre_run_commands : Array(_), post_run_commands : Array(_)) + + # +
+ +
+
+ +
+
+ + + + + + + + +

+ + + + Instance Method Detail +

+ +
+
+ + def check! + + # +
+ +
+
+ +
+
+ +
+
+ + def check_for_duplicates!(flags : Array(BaseFlag)) + + # +
+ +
+
+ +
+
+ +
+
+ + def find_match(arg : String) + + # +
+ +
+
+ +
+
+ +
+
+ + def process(args : Array(String)) + + # +
+ +
+ +

This serves to just convert the arguments into a usable Array(Arg) format +and pass it to the ACTUAL CommandNode#process method

+
+ +
+
+ +
+
+ +
+
+ + def process(args : Array(Arg)) : Nil + + # +
+ +
+
+ +
+
+ + + + +
+ + + diff --git a/docs/CliGen/DefaultFlag.html b/docs/CliGen/DefaultFlag.html new file mode 100644 index 0000000..4e47633 --- /dev/null +++ b/docs/CliGen/DefaultFlag.html @@ -0,0 +1,233 @@ + + + + + + + + + + + + + + + + + CliGen::DefaultFlag - CliGenerator object_rework-dev + + + + + + + + + + +
+

+ + + annotation + CliGen::DefaultFlag + +

+ + + + + + + + + + + + + + + + + + + + +

+ + + + Defined in: +

+ + + cligen.cr + +
+ + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + +
+ + + diff --git a/docs/CliGen/Flag.html b/docs/CliGen/Flag.html new file mode 100644 index 0000000..7e7e6e6 --- /dev/null +++ b/docs/CliGen/Flag.html @@ -0,0 +1,514 @@ + + + + + + + + + + + + + + + + + CliGen::Flag(T) - CliGenerator object_rework-dev + + + + + + + + + + +
+

+ + + class + CliGen::Flag(T) + +

+ + + + + + + + + + + + + + + + + + + + + + +

+ + + + Defined in: +

+ + + cligen/flag.cr + +
+ + + + + + + +

+ + + + Constructors +

+ + + + + + + + +

+ + + + Instance Method Summary +

+ + + + +
+ + + +

Instance methods inherited from class CliGen::BaseFlag

+ + + + description : String + description, + + + + env_var : String | Nil + env_var, + + + + long : String | Nil + long, + + + + long_key : String + long_key, + + + + matches?(token : String) : Bool + matches?, + + + + raw_value : String | Nil + raw_value, + + + + satisfied? : Bool + satisfied?, + + + + short : String | Nil + short, + + + + validate! : Nil + validate!, + + + + var : String + var + + + + + + +

Constructor methods inherited from class CliGen::BaseFlag

+ + + + new(var : String, short : String | Nil, long : String | Nil, env_var : String | Nil, description : String) + new + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + +

+ + + + Constructor Detail +

+ +
+
+ + def self.new(var : String, short : String | Nil, long : String | Nil, env_var : String | Nil, description : String, default : T | Nil = nil, options : Array(String) | Nil = nil, validate : T -> Bool | Nil = nil, on_match : Proc(Nil) | Nil = nil) + + # +
+ +
+
+ +
+
+ + + + + + + + +

+ + + + Instance Method Detail +

+ +
+
+ + def process(argv : Array(Arg) = [] of Array(Arg)) : Nil + + # +
+ +
+
+ +
+
+ +
+
+ + def raw_value : String | Nil + + # +
+ +
+
+ +
+
+ +
+
+ + def requires_arg? : Bool + + # +
+ +
+
+ +
+
+ +
+
+ + def satisfied? : Bool + + # +
+ +
+
+ +
+
+ +
+
+ + def validate! : Nil + + # +
+ +
+
+ +
+
+ +
+
+ + def value! : T + + # +
+ +
+
+ +
+
+ + + + +
+ + + diff --git a/docs/CliGen/Format.html b/docs/CliGen/Format.html new file mode 100644 index 0000000..830ecbe --- /dev/null +++ b/docs/CliGen/Format.html @@ -0,0 +1,257 @@ + + + + + + + + + + + + + + + + + CliGen::Format - CliGenerator object_rework-dev + + + + + + + + + + +
+

+ + + module + CliGen::Format + +

+ + + + + + + + + + + + + + + + + + + + +

+ + + + Defined in: +

+ + + cligen/format.cr + +
+ + + + + +

+ + + + Constant Summary +

+ +
+ +
+ INPUT_DATE_FORMAT = "%Y-%m-%d" +
+ + +
+ INPUT_DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" +
+ + +
+ + + + + + + + + + + + +
+ +
+ + + + + + + + + + +
+ + + diff --git a/docs/CliGen/MatchType.html b/docs/CliGen/MatchType.html new file mode 100644 index 0000000..7b6983f --- /dev/null +++ b/docs/CliGen/MatchType.html @@ -0,0 +1,445 @@ + + + + + + + + + + + + + + + + + CliGen::MatchType - CliGenerator object_rework-dev + + + + + + + + + + +
+

+ + + enum + CliGen::MatchType + +

+ + + + + + + + + + + + + + + + + + + + +

+ + + + Defined in: +

+ + + cligen/match_type.cr + +
+ + + + + +

+ + + + Enum Members +

+ +
+ +
+ FlagWithArg = 0 +
+ + +
+ FlagMultipleShort = 1 +
+ + +
+ ShortWithInlineArg = 2 +
+ + +
+ NoMatch = 3 +
+ + +
+ + + + + + + + + + +

+ + + + Instance Method Summary +

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +

+ + + + Instance Method Detail +

+ +
+
+ + def flag_multiple_short? + + # +
+ +
+ +

Returns true if this enum value equals FlagMultipleShort

+
+ +
+
+ +
+
+ +
+
+ + def flag_with_arg? + + # +
+ +
+ +

Returns true if this enum value equals FlagWithArg

+
+ +
+
+ +
+
+ +
+
+ + def no_match? + + # +
+ +
+ +

Returns true if this enum value equals NoMatch

+
+ +
+
+ +
+
+ +
+
+ + def short_with_inline_arg? + + # +
+ +
+ +

Returns true if this enum value equals ShortWithInlineArg

+
+ +
+
+ +
+
+ + + + +
+ + + diff --git a/docs/CliGen/ProxyCommand.html b/docs/CliGen/ProxyCommand.html new file mode 100644 index 0000000..bab043a --- /dev/null +++ b/docs/CliGen/ProxyCommand.html @@ -0,0 +1,233 @@ + + + + + + + + + + + + + + + + + CliGen::ProxyCommand - CliGenerator object_rework-dev + + + + + + + + + + +
+

+ + + annotation + CliGen::ProxyCommand + +

+ + + + + + + + + + + + + + + + + + + + +

+ + + + Defined in: +

+ + + cligen/annotations.cr + +
+ + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + +
+ + + diff --git a/docs/CliGen/Regex.html b/docs/CliGen/Regex.html new file mode 100644 index 0000000..59b2ff4 --- /dev/null +++ b/docs/CliGen/Regex.html @@ -0,0 +1,277 @@ + + + + + + + + + + + + + + + + + CliGen::Regex - CliGenerator object_rework-dev + + + + + + + + + + +
+

+ + + module + CliGen::Regex + +

+ + + + + + + + + + + + + + + + + + + + +

+ + + + Defined in: +

+ + + cligen/regex.cr + +
+ + + + + +

+ + + + Constant Summary +

+ +
+ +
+ FLAG_MULTIPLE_SHORT = /^-[a-zA-Z]+$/ +
+ + +
+ FLAG_REGEX = /^(-[a-zA-Z]|--[a-zA-Z-_]+)$/ +
+ + +
+ FLAG_WITH_ARG = /^(?<flag>(-[a-zA-Z]|--[a-zA-Z-_]+))="?(?<arg>\S+?)"?$/ +
+ + +
+ INPUT_DATE_REGEX = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/ +
+ + +
+ INPUT_DATETIME_REGEX = /^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/ +
+ + +
+ SHORT_WITH_INLINE_ARG = /^-[a-zA-Z][a-zA-Z0-9]+$/ +
+ + +
+ + + + + + + + + + + + +
+ +
+ + + + + + + + + + +
+ + + diff --git a/docs/CliGen/Selection.html b/docs/CliGen/Selection.html new file mode 100644 index 0000000..e10af63 --- /dev/null +++ b/docs/CliGen/Selection.html @@ -0,0 +1,233 @@ + + + + + + + + + + + + + + + + + CliGen::Selection - CliGenerator object_rework-dev + + + + + + + + + + +
+

+ + + annotation + CliGen::Selection + +

+ + + + + + + + + + + + + + + + + + + + +

+ + + + Defined in: +

+ + + cligen/annotations.cr + +
+ + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + +
+ + + diff --git a/docs/CliGen/SubCommand.html b/docs/CliGen/SubCommand.html new file mode 100644 index 0000000..c39fbfb --- /dev/null +++ b/docs/CliGen/SubCommand.html @@ -0,0 +1,233 @@ + + + + + + + + + + + + + + + + + CliGen::SubCommand - CliGenerator object_rework-dev + + + + + + + + + + +
+

+ + + annotation + CliGen::SubCommand + +

+ + + + + + + + + + + + + + + + + + + + +

+ + + + Defined in: +

+ + + cligen/annotations.cr + +
+ + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + +
+ + + diff --git a/docs/CliGen/Trigger.html b/docs/CliGen/Trigger.html new file mode 100644 index 0000000..9ff7dd2 --- /dev/null +++ b/docs/CliGen/Trigger.html @@ -0,0 +1,233 @@ + + + + + + + + + + + + + + + + + CliGen::Trigger - CliGenerator object_rework-dev + + + + + + + + + + +
+

+ + + annotation + CliGen::Trigger + +

+ + + + + + + + + + + + + + + + + + + + +

+ + + + Defined in: +

+ + + cligen/annotations.cr + +
+ + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + +
+ + + diff --git a/docs/css/style.css b/docs/css/style.css new file mode 100644 index 0000000..774a0e1 --- /dev/null +++ b/docs/css/style.css @@ -0,0 +1,988 @@ +:root { + color-scheme: light dark; +} + +html, body { + background: #FFFFFF; + position: relative; + margin: 0; + padding: 0; + width: 100%; + height: 100%; + overflow: hidden; +} + +body { + font-family: "Avenir", "Tahoma", "Lucida Sans", "Lucida Grande", Verdana, Arial, sans-serif; + color: #333; + line-height: 1.5; +} + +a { + color: #263F6C; +} + +a:visited { + color: #112750; +} + +h1, h2, h3, h4, h5, h6 { + margin: 35px 0 25px; + color: #444444; +} + +h1.type-name { + color: #47266E; + margin: 20px 0 30px; + background-color: #F8F8F8; + padding: 10px 12px; + border: 1px solid #EBEBEB; + border-radius: 2px; +} + +h2 { + border-bottom: 1px solid #E6E6E6; + padding-bottom: 5px; +} + +body { + display: flex; +} + +.sidebar, .main-content { + overflow: auto; +} + +p, li { + max-width: 42em; +} + +.methods-inherited { + max-width: 60em; +} + +.sidebar { + width: 30em; + color: #F8F4FD; + background-color: #2E1052; + padding: 0 0 30px; + box-shadow: inset -3px 0 4px rgba(0,0,0,.35); + line-height: 1.2; + z-index: 0; +} + +.sidebar .search-box { + padding: 13px 9px; +} + +.sidebar input { + display: block; + box-sizing: border-box; + margin: 0; + padding: 5px; + font: inherit; + font-family: inherit; + line-height: 1.2; + width: 100%; + border: 0; + outline: 0; + border-radius: 2px; + box-shadow: 0px 3px 5px rgba(0,0,0,.25); + transition: box-shadow .12s; +} + +.sidebar input:focus { + box-shadow: 0px 5px 6px rgba(0,0,0,.5); +} + +.sidebar input::-webkit-input-placeholder { /* Chrome/Opera/Safari */ + color: #757575; + font-size: 14px; + text-indent: 2px; +} + +.sidebar input::-moz-placeholder { /* Firefox 19+ */ + color: #757575; + font-size: 14px; + text-indent: 2px; +} + +.sidebar input:-ms-input-placeholder { /* IE 10+ */ + color: #757575; + font-size: 14px; + text-indent: 2px; +} + +.sidebar input:-moz-placeholder { /* Firefox 18- */ + color: #757575; + font-size: 14px; + text-indent: 2px; +} + +.project-summary { + padding: 9px 15px 30px 30px; +} + +.project-name { + font-size: 1.4rem; + margin: 0; + color: #f4f4f4; + font-weight: 600; +} + +.project-version { + margin-top: 5px; + display: inline-block; + position: relative; +} + +.project-version > form::after { + position: absolute; + right: 0; + top: 0; + content: "\25BC"; + font-size: .6em; + line-height: 1.2rem; + z-index: -1; +} + +.project-versions-nav { + cursor: pointer; + margin: 0; + padding: 0 .9em 0 0; + border: none; + -moz-appearance: none; + -webkit-appearance: none; + appearance: none; + background-color: transparent; + color: inherit; + font-family: inherit; + font-size: inherit; + line-height: inherit; +} +.project-versions-nav:focus { + outline: none; +} + +.project-versions-nav > option { + color: initial; +} + +.sidebar ul { + margin: 0; + padding: 0; + list-style: none outside; +} + +.sidebar li { + display: block; + position: relative; +} + +.types-list li.hide { + display: none; +} + +.sidebar a { + text-decoration: none; + color: inherit; + transition: color .14s; +} +.types-list a { + display: block; + padding: 5px 15px 5px 30px; +} + +.types-list { + display: block; +} + +.sidebar a:focus { + outline: 1px solid #D1B7F1; +} + +.types-list a { + padding: 5px 15px 5px 30px; +} + +.sidebar .current > a, +.sidebar a:hover { + color: #866BA6; +} + +.types-list li ul { + overflow: hidden; + height: 0; + max-height: 0; + transition: 1s ease-in-out; +} + +.types-list li.parent { + padding-left: 30px; +} + +.types-list li.parent::before { + box-sizing: border-box; + content: "▼"; + display: block; + width: 30px; + height: 30px; + position: absolute; + top: 0; + left: 0; + text-align: center; + color: white; + font-size: 8px; + line-height: 30px; + transform: rotateZ(-90deg); + cursor: pointer; + transition: .2s linear; +} + + +.types-list li.parent > a { + padding-left: 0; +} + +.types-list li.parent.open::before { + transform: rotateZ(0); +} + +.types-list li.open > ul { + height: auto; + max-height: 1000em; +} + +.main-content { + padding: 0 30px 30px 30px; + width: 100%; +} + +.kind { + font-size: 60%; + color: #866BA6; +} + +.superclass-hierarchy { + margin: -15px 0 30px 0; + padding: 0; + list-style: none outside; + font-size: 80%; +} + +.superclass-hierarchy .superclass { + display: inline-block; + margin: 0 7px 0 0; + padding: 0; +} + +.superclass-hierarchy .superclass + .superclass::before { + content: "<"; + margin-right: 7px; +} + +.other-types-list li { + display: inline-block; +} + +.other-types-list, +.list-summary { + margin: 0 0 30px 0; + padding: 0; + list-style: none outside; +} + +.entry-const { + font-family: Menlo, Monaco, Consolas, 'Courier New', Courier, monospace; +} + +.entry-const code { + white-space: pre-wrap; +} + +.entry-summary { + padding-bottom: 4px; +} + +.superclass-hierarchy .superclass a, +.other-type a, +.entry-summary .signature { + padding: 4px 8px; + margin-bottom: 4px; + display: inline-block; + background-color: #f8f8f8; + color: #47266E; + border: 1px solid #f0f0f0; + text-decoration: none; + border-radius: 3px; + font-family: Menlo, Monaco, Consolas, 'Courier New', Courier, monospace; + transition: background .15s, border-color .15s; +} + +.superclass-hierarchy .superclass a:hover, +.other-type a:hover, +.entry-summary .signature:hover { + background: #D5CAE3; + border-color: #624288; +} + +.entry-summary .summary { + padding-left: 32px; +} + +.entry-summary .summary p { + margin: 12px 0 16px; +} + +.entry-summary a { + text-decoration: none; +} + +.entry-detail { + padding: 30px 0; +} + +.entry-detail .signature { + position: relative; + padding: 5px 15px; + margin-bottom: 10px; + display: block; + border-radius: 5px; + background-color: #f8f8f8; + color: #47266E; + border: 1px solid #f0f0f0; + font-family: Menlo, Monaco, Consolas, 'Courier New', Courier, monospace; + transition: .2s ease-in-out; +} + +.entry-detail:target .signature { + background-color: #D5CAE3; + border: 1px solid #624288; +} + +.entry-detail .signature .method-permalink { + position: absolute; + top: 0; + left: -35px; + padding: 5px 15px; + text-decoration: none; + font-weight: bold; + color: #624288; + opacity: .4; + transition: opacity .2s; +} + +.entry-detail .signature .method-permalink:hover { + opacity: 1; +} + +.entry-detail:target .signature .method-permalink { + opacity: 1; +} + +.methods-inherited { + padding-right: 10%; + line-height: 1.5em; +} + +.methods-inherited h3 { + margin-bottom: 4px; +} + +.methods-inherited a { + display: inline-block; + text-decoration: none; + color: #47266E; +} + +.methods-inherited a:hover { + text-decoration: underline; + color: #6C518B; +} + +.methods-inherited .tooltip>span { + background: #D5CAE3; + padding: 4px 8px; + border-radius: 3px; + margin: -4px -8px; +} + +.methods-inherited .tooltip * { + color: #47266E; +} + +pre { + padding: 10px 20px; + margin-top: 4px; + border-radius: 3px; + line-height: 1.45; + overflow: auto; + color: #333; + background: #fdfdfd; + font-size: 14px; + border: 1px solid #eee; +} + +code { + font-family: Menlo, Monaco, Consolas, 'Courier New', Courier, monospace; +} + +:not(pre) > code { + background-color: rgba(40,35,30,0.05); + padding: 0.2em 0.4em; + font-size: 85%; + border-radius: 3px; +} + +span.flag { + padding: 2px 4px 1px; + border-radius: 3px; + margin-right: 3px; + font-size: 11px; + border: 1px solid transparent; +} + +span.flag.orange { + background-color: #EE8737; + color: #FCEBDD; + border-color: #EB7317; +} + +span.flag.yellow { + background-color: #E4B91C; + color: #FCF8E8; + border-color: #B69115; +} + +span.flag.green { + background-color: #469C14; + color: #E2F9D3; + border-color: #34700E; +} + +span.flag.red { + background-color: #BF1919; + color: #F9ECEC; + border-color: #822C2C; +} + +span.flag.purple { + background-color: #2E1052; + color: #ECE1F9; + border-color: #1F0B37; +} + +span.flag.lime { + background-color: #a3ff00; + color: #222222; + border-color: #00ff1e; +} + +.tooltip>span { + position: absolute; + opacity: 0; + display: none; + pointer-events: none; +} + +.tooltip:hover>span { + display: inline-block; + opacity: 1; +} + +.c { + color: #969896; +} + +.n { + color: #0086b3; +} + +.t { + color: #0086b3; +} + +.s { + color: #183691; +} + +.i { + color: #7f5030; +} + +.k { + color: #a71d5d; +} + +.o { + color: #a71d5d; +} + +.m { + color: #795da3; +} + +.hidden { + display: none; +} +.search-results { + font-size: 90%; + line-height: 1.3; +} + +.search-results mark { + color: inherit; + background: transparent; + font-weight: bold; +} +.search-result { + padding: 5px 8px 5px 5px; + cursor: pointer; + border-left: 5px solid transparent; + transform: translateX(-3px); + transition: all .2s, background-color 0s, border .02s; + min-height: 3.2em; +} +.search-result.current { + border-left-color: #ddd; + background-color: rgba(200,200,200,0.4); + transform: translateX(0); + transition: all .2s, background-color .5s, border 0s; +} +.search-result.current:hover, +.search-result.current:focus { + border-left-color: #866BA6; +} +.search-result:not(.current):nth-child(2n) { + background-color: rgba(255,255,255,.06); +} +.search-result__title { + font-size: 105%; + word-break: break-all; + line-height: 1.1; + padding: 3px 0; +} +.search-result__title strong { + font-weight: normal; +} +.search-results .search-result__title > a { + padding: 0; + display: block; +} +.search-result__title > a > .args { + color: #dddddd; + font-weight: 300; + transition: inherit; + font-size: 88%; + line-height: 1.2; + letter-spacing: -.02em; +} +.search-result__title > a > .args * { + color: inherit; +} + +.search-result a, +.search-result a:hover { + color: inherit; +} +.search-result:not(.current):hover .search-result__title > a, +.search-result:not(.current):focus .search-result__title > a, +.search-result__title > a:focus { + color: #866BA6; +} +.search-result:not(.current):hover .args, +.search-result:not(.current):focus .args { + color: #6a5a7d; +} + +.search-result__type { + color: #e8e8e8; + font-weight: 300; +} +.search-result__doc { + color: #bbbbbb; + font-size: 90%; +} +.search-result__doc p { + margin: 0; + text-overflow: ellipsis; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + overflow: hidden; + line-height: 1.2em; + max-height: 2.4em; +} + +.js-modal-visible .modal-background { + display: flex; +} +.main-content { + position: relative; +} +.modal-background { + position: absolute; + display: none; + height: 100%; + width: 100%; + background: rgba(120,120,120,.4); + z-index: 100; + align-items: center; + justify-content: center; +} +.usage-modal { + max-width: 90%; + background: #fff; + border: 2px solid #ccc; + border-radius: 9px; + padding: 5px 15px 20px; + min-width: 50%; + color: #555; + position: relative; + transform: scale(.5); + transition: transform 200ms; +} +.js-modal-visible .usage-modal { + transform: scale(1); +} +.usage-modal > .close-button { + position: absolute; + right: 15px; + top: 8px; + color: #aaa; + font-size: 27px; + cursor: pointer; +} +.usage-modal > .close-button:hover { + text-shadow: 2px 2px 2px #ccc; + color: #999; +} +.modal-title { + margin: 0; + text-align: center; + font-weight: normal; + color: #666; + border-bottom: 2px solid #ddd; + padding: 10px; +} +.usage-list { + padding: 0; + margin: 13px; +} +.usage-list > li { + padding: 5px 2px; + overflow: auto; + padding-left: 100px; + min-width: 12em; +} +.usage-modal kbd { + background: #eee; + border: 1px solid #ccc; + border-bottom-width: 2px; + border-radius: 3px; + padding: 3px 8px; + font-family: monospace; + margin-right: 2px; + display: inline-block; +} +.usage-key { + float: left; + clear: left; + margin-left: -100px; + margin-right: 12px; +} +.doc-inherited { + font-weight: bold; +} + +.anchor { + float: left; + padding-right: 4px; + margin-left: -20px; +} + +.main-content .anchor .octicon-link { + width: 16px; + height: 16px; +} + +.main-content .anchor:focus { + outline: none +} + +.main-content h1:hover .anchor, +.main-content h2:hover .anchor, +.main-content h3:hover .anchor, +.main-content h4:hover .anchor, +.main-content h5:hover .anchor, +.main-content h6:hover .anchor { + text-decoration: none +} + +.main-content h1 .octicon-link, +.main-content h2 .octicon-link, +.main-content h3 .octicon-link, +.main-content h4 .octicon-link, +.main-content h5 .octicon-link, +.main-content h6 .octicon-link { + visibility: hidden +} + +.main-content h1:hover .anchor .octicon-link, +.main-content h2:hover .anchor .octicon-link, +.main-content h3:hover .anchor .octicon-link, +.main-content h4:hover .anchor .octicon-link, +.main-content h5:hover .anchor .octicon-link, +.main-content h6:hover .anchor .octicon-link { + visibility: visible +} + +img { + max-width: 100%; +} + +table { + font-size: 14px; + display: block; + max-width: -moz-fit-content; + max-width: fit-content; + overflow-x: auto; + white-space: nowrap; + background: #fdfdfd; + text-align: center; + border: 1px solid #eee; + border-collapse: collapse; + padding: 0px 5px 0px 5px; +} + +table th { + padding: 10px; + letter-spacing: 1px; + border-bottom: 1px solid #eee; +} + +table td { + padding: 10px; +} + +#sidebar-btn { + height: 32px; + width: 32px; +} + +#sidebar-btn-label { + height: 2em; + width: 2em; +} + +#sidebar-btn, #sidebar-btn-label { + display: none; + margin: .7rem; + appearance: none; + color: black; + cursor: pointer; +} + +@media only screen and (max-width: 635px) { + .sidebar, .main-content { + /* svg size + vertical margin - .search-box padding-top */ + padding-top: calc(2em + 2 * 0.7rem - 13px); + } + + #sidebar-btn, #sidebar-btn-label { + display: block; + position: absolute; + z-index: 50; + transition-duration: 200ms; + left: 0; + } + + #sidebar-btn:not(:checked) ~ #sidebar-btn-label > .close, + #sidebar-btn:checked ~ #sidebar-btn-label > .open, + #sidebar-btn:checked ~ .main-content { + display: none; + } + + #sidebar-btn:checked { + left: calc(100% - 32px - (2 * 0.7rem)); + } + + #sidebar-btn:checked ~ #sidebar-btn-label { + color: white; + /* 100% - svg size - horizontal margin */ + left: calc(100% - 2em - (2 * 0.7rem)); + } + + #sidebar-btn~.sidebar { + width: 0%; + } + + #sidebar-btn:checked~.sidebar { + visibility: visible; + width: 100%; + } + + .sidebar { + transition-duration: 200ms; + max-width: 100vw; + visibility: hidden; + } +} + +@media (prefers-color-scheme: dark) { + html, body { + background: #1b1b1b; + } + + body { + color: white; + } + + a { + color: #8cb4ff; + } + + .main-content a:visited { + color: #5f8de3; + } + + h1, h2, h3, h4, h5, h6 { + color: white; + } + + h1.type-name { + color: white; + background-color: #202020; + border: 1px solid #353535; + } + + .project-versions-nav > option { + background-color: #222; + } + + .superclass-hierarchy .superclass a, + .superclass-hierarchy .superclass a:visited, + .other-type a, + .other-type a:visited, + .entry-summary .signature, + .entry-summary a:visited { + background-color: #202020; + color: white; + border: 1px solid #353535; + } + + .superclass-hierarchy .superclass a:hover, + .other-type a:hover, + .entry-summary .signature:hover { + background: #443d4d; + border-color: #b092d4; + } + + .kind { + color: #b092d4; + } + + .n { + color: #00ade6; + } + + .t { + color: #00ade6; + } + + .k { + color: #ff66ae; + } + + .o { + color: #ff66ae; + } + + .s { + color: #7799ff; + } + + .i { + color: #b38668; + } + + .m { + color: #b9a5d6; + } + + .c { + color: #a1a1a1; + } + + .methods-inherited a, .methods-inherited a:visited { + color: #B290D9; + } + + .methods-inherited a:hover { + color: #D4B7F4; + } + + .methods-inherited .tooltip>span { + background: #443d4d; + } + + .methods-inherited .tooltip * { + color: white; + } + + .entry-detail:target .signature { + background-color: #443d4d; + border: 1px solid #b092d4; + } + + .entry-detail .signature { + background-color: #202020; + color: white; + border: 1px solid #353535; + } + + .entry-detail .signature .method-permalink { + color: #b092d4; + } + + :not(pre)>code { + background-color: #202020; + } + + span.flag.purple { + background-color: #443d4d; + color: #ECE1F9; + border-color: #b092d4; + } + + .sidebar input::-webkit-input-placeholder { /* Chrome/Opera/Safari */ + color: white; + } + + .sidebar input::-moz-placeholder { /* Firefox 19+ */ + color: white; + } + + .sidebar input:-ms-input-placeholder { /* IE 10+ */ + color: white; + } + + .sidebar input:-moz-placeholder { /* Firefox 18- */ + color: white; + } + + pre, + table { + color: white; + background: #202020; + border: 1px solid #353535; + } + + table th { + border-bottom: 1px solid #353535; + } + + #sidebar-btn, #sidebar-btn-label { + color: white; + } +} diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000..1293fb3 --- /dev/null +++ b/docs/index.html @@ -0,0 +1,199 @@ + + + + + + + + + + + + + + + + + CliGenerator object_rework-dev + + + + + + + + + + +
+

+CliGenerator

+

This is a crystal project to manage setting up OptionParser objects based around "Command" objects and arguments you define inside them.

+

+ +Installation

+
    +
  1. +

    Add the dependency to your shard.yml:

    +
    dependencies:
    +  cligen:
    +    git: https://git.arcanium.tech/tristan/cligen
    +
  2. +
  3. +

    Run shards install

    +
  4. +
+

+ +Usage

+
require "cligen"
+

+ +Contributors

+ +
+ + diff --git a/docs/index.json b/docs/index.json new file mode 100644 index 0000000..fd62139 --- /dev/null +++ b/docs/index.json @@ -0,0 +1 @@ +{"repository_name":"CliGenerator","body":"# CliGenerator\n \nThis is a crystal project to manage setting up OptionParser objects based around \"Command\" objects and arguments you define inside them.\n\n## Installation\n\n1. Add the dependency to your `shard.yml`:\n\n ```yaml\n dependencies:\n cligen:\n git: https://git.arcanium.tech/tristan/cligen\n ```\n\n2. Run `shards install`\n\n\n## Usage\n```crystal\nrequire \"cligen\"\n```\n\n## Contributors\n\n- [Tristan Ancelet](https://git.arcanium.tech/tristan) - creator and maintainer\n","program":{"html_id":"CliGenerator/toplevel","path":"toplevel.html","kind":"module","full_name":"Top Level Namespace","name":"Top Level Namespace","abstract":false,"locations":[],"repository_name":"CliGenerator","program":true,"enum":false,"alias":false,"const":false,"types":[{"html_id":"CliGenerator/CliGen","path":"CliGen.html","kind":"module","full_name":"CliGen","name":"CliGen","abstract":false,"locations":[{"filename":"src/cligen.cr","line_number":10,"url":null},{"filename":"src/cligen/annotations.cr","line_number":1,"url":null},{"filename":"src/cligen/app.cr","line_number":5,"url":null},{"filename":"src/cligen/arg.cr","line_number":1,"url":null},{"filename":"src/cligen/command.cr","line_number":10,"url":null},{"filename":"src/cligen/command/argument.cr","line_number":1,"url":null},{"filename":"src/cligen/command/selection.cr","line_number":1,"url":null},{"filename":"src/cligen/command/subcommand.cr","line_number":1,"url":null},{"filename":"src/cligen/command/trigger.cr","line_number":1,"url":null},{"filename":"src/cligen/command_node.cr","line_number":4,"url":null},{"filename":"src/cligen/flag.cr","line_number":3,"url":null},{"filename":"src/cligen/generate.cr","line_number":2,"url":null},{"filename":"src/cligen/match_type.cr","line_number":1,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"constants":[{"id":"ADDITIONAL_DEFAULT_FLAGS","name":"ADDITIONAL_DEFAULT_FLAGS","value":"[] of AdditionalDefaultFlag"},{"id":"APPNAME","name":"APPNAME","value":"File.basename(PROGRAM_NAME)"},{"id":"VERSION","name":"VERSION","value":"\"0.1.0\""}],"class_methods":[{"html_id":"add_default_flag(short:String=\"\",long:String=\"\",description:String=\"\",&work:String->)-class-method","name":"add_default_flag","abstract":false,"args":[{"name":"short","default_value":"\"\"","external_name":"short","restriction":"String"},{"name":"long","default_value":"\"\"","external_name":"long","restriction":"String"},{"name":"description","default_value":"\"\"","external_name":"description","restriction":"String"}],"args_string":"(short : String = \"\", long : String = \"\", description : String = \"\", &work : String -> )","args_html":"(short : String = "", long : String = "", description : String = "", &work : String -> )","location":{"filename":"src/cligen.cr","line_number":23,"url":null},"def":{"name":"add_default_flag","args":[{"name":"short","default_value":"\"\"","external_name":"short","restriction":"String"},{"name":"long","default_value":"\"\"","external_name":"long","restriction":"String"},{"name":"description","default_value":"\"\"","external_name":"description","restriction":"String"}],"yields":1,"block_arity":1,"block_arg":{"name":"work","external_name":"work","restriction":"(String ->)"},"visibility":"Public","body":"if description.empty?\n raise(\"ERROR : add_default_flag : You must provide a description\")\nend\nADDITIONAL_DEFAULT_FLAGS << AdditionalDefaultFlag.new(short: short, long: long, description: description, work: work)\n"},"external_var":false}],"types":[{"html_id":"CliGenerator/CliGen/AdditionalDefaultFlag","path":"CliGen/AdditionalDefaultFlag.html","kind":"struct","full_name":"CliGen::AdditionalDefaultFlag","name":"AdditionalDefaultFlag","abstract":false,"superclass":{"html_id":"CliGenerator/Struct","kind":"struct","full_name":"Struct","name":"Struct"},"ancestors":[{"html_id":"CliGenerator/Struct","kind":"struct","full_name":"Struct","name":"Struct"},{"html_id":"CliGenerator/Value","kind":"struct","full_name":"Value","name":"Value"},{"html_id":"CliGenerator/Object","kind":"class","full_name":"Object","name":"Object"}],"locations":[{"filename":"src/cligen.cr","line_number":15,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"},"constructors":[{"html_id":"new(short:String,long:String,description:String,work:String->)-class-method","name":"new","abstract":false,"args":[{"name":"short","external_name":"short","restriction":"String"},{"name":"long","external_name":"long","restriction":"String"},{"name":"description","external_name":"description","restriction":"String"},{"name":"work","external_name":"work","restriction":"(String ->)"}],"args_string":"(short : String, long : String, description : String, work : String -> )","args_html":"(short : String, long : String, description : String, work : String -> )","location":{"filename":"src/cligen.cr","line_number":15,"url":null},"def":{"name":"new","args":[{"name":"short","external_name":"short","restriction":"String"},{"name":"long","external_name":"long","restriction":"String"},{"name":"description","external_name":"description","restriction":"String"},{"name":"work","external_name":"work","restriction":"(String ->)"}],"visibility":"Public","body":"_ = allocate\n_.initialize(short, long, description, work)\nif _.responds_to?(:finalize)\n ::GC.add_finalizer(_)\nend\n_\n"},"external_var":false}],"instance_methods":[{"html_id":"clone-instance-method","name":"clone","abstract":false,"location":{"filename":"src/cligen.cr","line_number":15,"url":null},"def":{"name":"clone","visibility":"Public","body":"self.class.new(@short.clone, @long.clone, @description.clone, @work.clone)"},"external_var":false},{"html_id":"copy_with(short_short=@short,long_long=@long,description_description=@description,work_work=@work)-instance-method","name":"copy_with","abstract":false,"args":[{"name":"_short","default_value":"@short","external_name":"short","restriction":""},{"name":"_long","default_value":"@long","external_name":"long","restriction":""},{"name":"_description","default_value":"@description","external_name":"description","restriction":""},{"name":"_work","default_value":"@work","external_name":"work","restriction":""}],"args_string":"(short _short = @short, long _long = @long, description _description = @description, work _work = @work)","args_html":"(short _short = @short, long _long = @long, description _description = @description, work _work = @work)","location":{"filename":"src/cligen.cr","line_number":15,"url":null},"def":{"name":"copy_with","args":[{"name":"_short","default_value":"@short","external_name":"short","restriction":""},{"name":"_long","default_value":"@long","external_name":"long","restriction":""},{"name":"_description","default_value":"@description","external_name":"description","restriction":""},{"name":"_work","default_value":"@work","external_name":"work","restriction":""}],"visibility":"Public","body":"self.class.new(_short, _long, _description, _work)"},"external_var":false},{"html_id":"description:String-instance-method","name":"description","abstract":false,"def":{"name":"description","return_type":"String","visibility":"Public","body":"@description"},"external_var":false},{"html_id":"long:String-instance-method","name":"long","abstract":false,"def":{"name":"long","return_type":"String","visibility":"Public","body":"@long"},"external_var":false},{"html_id":"short:String-instance-method","name":"short","abstract":false,"def":{"name":"short","return_type":"String","visibility":"Public","body":"@short"},"external_var":false},{"html_id":"work:String->-instance-method","name":"work","abstract":false,"def":{"name":"work","return_type":"(String ->)","visibility":"Public","body":"@work"},"external_var":false}]},{"html_id":"CliGenerator/CliGen/App","path":"CliGen/App.html","kind":"class","full_name":"CliGen::App","name":"App","abstract":false,"superclass":{"html_id":"CliGenerator/CliGen/CommandNode","kind":"class","full_name":"CliGen::CommandNode","name":"CommandNode"},"ancestors":[{"html_id":"CliGenerator/CliGen/CommandNode","kind":"class","full_name":"CliGen::CommandNode","name":"CommandNode"},{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},{"html_id":"CliGenerator/Object","kind":"class","full_name":"Object","name":"Object"}],"locations":[{"filename":"src/cligen/app.cr","line_number":8,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"},"doc":"This serves as the default App object, that holds a copy of all flags & \nhandles flag processing until it hands off to the user defined commands","summary":"

This serves as the default App object, that holds a copy of all flags & handles flag processing until it hands off to the user defined commands

","class_methods":[{"html_id":"process(args:Array(String)=ARGV)-class-method","name":"process","doc":"Serves as a convinence method for the user to call to begin processing an\nargument array provided by the user.\n\nThis defaults to ARGV for convinence if no arguments are passed through","summary":"

Serves as a convinence method for the user to call to begin processing an argument array provided by the user.

","abstract":false,"args":[{"name":"args","default_value":"ARGV","external_name":"args","restriction":"Array(String)"}],"args_string":"(args : Array(String) = ARGV)","args_html":"(args : Array(String) = ARGV)","location":{"filename":"src/cligen/app.cr","line_number":28,"url":null},"def":{"name":"process","args":[{"name":"args","default_value":"ARGV","external_name":"args","restriction":"Array(String)"}],"visibility":"Public","body":"if @@instance.nil?\n raise(\"ERROR : CliGen::App.process was called before an instance of App was defined\")\nend\n@@instance.process(args)\n"},"external_var":false}],"constructors":[{"html_id":"new(name,flags,commands,pre_run_commands,post_run_commands)-class-method","name":"new","abstract":false,"args":[{"name":"name","external_name":"name","restriction":""},{"name":"flags","external_name":"flags","restriction":""},{"name":"commands","external_name":"commands","restriction":""},{"name":"pre_run_commands","external_name":"pre_run_commands","restriction":""},{"name":"post_run_commands","external_name":"post_run_commands","restriction":""}],"args_string":"(name, flags, commands, pre_run_commands, post_run_commands)","args_html":"(name, flags, commands, pre_run_commands, post_run_commands)","location":{"filename":"src/cligen/app.cr","line_number":12,"url":null},"def":{"name":"new","args":[{"name":"name","external_name":"name","restriction":""},{"name":"flags","external_name":"flags","restriction":""},{"name":"commands","external_name":"commands","restriction":""},{"name":"pre_run_commands","external_name":"pre_run_commands","restriction":""},{"name":"post_run_commands","external_name":"post_run_commands","restriction":""}],"visibility":"Public","body":"_ = allocate\n_.initialize(name, flags, commands, pre_run_commands, post_run_commands)\nif _.responds_to?(:finalize)\n ::GC.add_finalizer(_)\nend\n_\n"},"external_var":false}],"instance_methods":[{"html_id":"check!-instance-method","name":"check!","abstract":false,"location":{"filename":"src/cligen/app.cr","line_number":16,"url":null},"def":{"name":"check!","visibility":"Public","body":"CliGen::GLOBAL_FLAGS.each(&.check!)\n\n\ncheck_for_duplicates!([CliGen::GLOBAL_FLAGS, @flags].flatten)\n@commands.each(&.check!)\n"},"external_var":false}]},{"html_id":"CliGenerator/CliGen/Arg","path":"CliGen/Arg.html","kind":"class","full_name":"CliGen::Arg","name":"Arg","abstract":false,"superclass":{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},"ancestors":[{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},{"html_id":"CliGenerator/Object","kind":"class","full_name":"Object","name":"Object"}],"locations":[{"filename":"src/cligen/arg.cr","line_number":15,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"},"doc":"This class serves as a \"argument wrapper\" to force a fail-fast approach to\narg-parsing. \n\nIt wraps around the argument + index of the argument to do state tracking\nand ensure that each argument is only processed once (plus allows for\neasier filtering of processed arguments to avoid having to do index math)\n\n args.reject(&.processed?) # returns the args that haven't been processed yet\n\nIt expects each argument to only be processed once and will force a raise\nif the argument has Arg#processed called a second time. This is to force \nthe developer (me) to fix any processing issues during the development of\nthis framework.","summary":"

This class serves as a "argument wrapper" to force a fail-fast approach to arg-parsing.

","constructors":[{"html_id":"new(value:String,index:Int32)-class-method","name":"new","abstract":false,"args":[{"name":"value","external_name":"value","restriction":"::String"},{"name":"index","external_name":"index","restriction":"::Int32"}],"args_string":"(value : String, index : Int32)","args_html":"(value : String, index : Int32)","location":{"filename":"src/cligen/arg.cr","line_number":24,"url":null},"def":{"name":"new","args":[{"name":"value","external_name":"value","restriction":"::String"},{"name":"index","external_name":"index","restriction":"::Int32"}],"visibility":"Public","body":"_ = allocate\n_.initialize(value, index)\nif _.responds_to?(:finalize)\n ::GC.add_finalizer(_)\nend\n_\n"},"external_var":false}],"instance_methods":[{"html_id":"index:Int32-instance-method","name":"index","doc":"The index of the argument in the array it was in","summary":"

The index of the argument in the array it was in

","abstract":false,"location":{"filename":"src/cligen/arg.cr","line_number":20,"url":null},"def":{"name":"index","return_type":"Int32","visibility":"Public","body":"@index"},"external_var":false},{"html_id":"processed-instance-method","name":"processed","doc":"This serves as a trigger that tells the object that it has been processed\n\nThis will raise an exception if it is re-called after already having been\nprocessed.","summary":"

This serves as a trigger that tells the object that it has been processed

","abstract":false,"location":{"filename":"src/cligen/arg.cr","line_number":31,"url":null},"def":{"name":"processed","visibility":"Public","body":"if @processed\n raise(\"ERROR : CliGen::Arg(index: #{@index}, value: #{@value})#processed : This arg was re-processed\")\nend\n@processed = true\n"},"external_var":false},{"html_id":"processed?:Bool-instance-method","name":"processed?","doc":"The \"flag\"/variable that tracks is the Arg has been processed yet","summary":"

The "flag"/variable that tracks is the Arg has been processed yet

","abstract":false,"location":{"filename":"src/cligen/arg.cr","line_number":22,"url":null},"def":{"name":"processed?","return_type":"Bool","visibility":"Public","body":"@processed"},"external_var":false},{"html_id":"value:String-instance-method","name":"value","doc":"The raw string argument provided from the user","summary":"

The raw string argument provided from the user

","abstract":false,"location":{"filename":"src/cligen/arg.cr","line_number":18,"url":null},"def":{"name":"value","return_type":"String","visibility":"Public","body":"@value"},"external_var":false}]},{"html_id":"CliGenerator/CliGen/Argument","path":"CliGen/Argument.html","kind":"annotation","full_name":"CliGen::Argument","name":"Argument","abstract":false,"locations":[{"filename":"src/cligen/annotations.cr","line_number":8,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"}},{"html_id":"CliGenerator/CliGen/BaseFlag","path":"CliGen/BaseFlag.html","kind":"class","full_name":"CliGen::BaseFlag","name":"BaseFlag","abstract":true,"superclass":{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},"ancestors":[{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},{"html_id":"CliGenerator/Object","kind":"class","full_name":"Object","name":"Object"}],"locations":[{"filename":"src/cligen/flag.cr","line_number":4,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"subclasses":[{"html_id":"CliGenerator/CliGen/Flag","kind":"class","full_name":"CliGen::Flag(T)","name":"Flag"}],"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"},"constructors":[{"html_id":"new(var:String,short:String|Nil,long:String|Nil,env_var:String|Nil,description:String)-class-method","name":"new","abstract":false,"args":[{"name":"var","external_name":"var","restriction":"String"},{"name":"short","external_name":"short","restriction":"String | ::Nil"},{"name":"long","external_name":"long","restriction":"String | ::Nil"},{"name":"env_var","external_name":"env_var","restriction":"String | ::Nil"},{"name":"description","external_name":"description","restriction":"String"}],"args_string":"(var : String, short : String | Nil, long : String | Nil, env_var : String | Nil, description : String)","args_html":"(var : String, short : String | Nil, long : String | Nil, env_var : String | Nil, description : String)","location":{"filename":"src/cligen/flag.cr","line_number":12,"url":null},"def":{"name":"new","args":[{"name":"var","external_name":"var","restriction":"String"},{"name":"short","external_name":"short","restriction":"String | ::Nil"},{"name":"long","external_name":"long","restriction":"String | ::Nil"},{"name":"env_var","external_name":"env_var","restriction":"String | ::Nil"},{"name":"description","external_name":"description","restriction":"String"}],"visibility":"Public","body":"_ = allocate\n_.initialize(var, short, long, env_var, description)\nif _.responds_to?(:finalize)\n ::GC.add_finalizer(_)\nend\n_\n"},"external_var":false}],"instance_methods":[{"html_id":"description:String-instance-method","name":"description","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":10,"url":null},"def":{"name":"description","return_type":"String","visibility":"Public","body":"@description"},"external_var":false},{"html_id":"env_var:String|Nil-instance-method","name":"env_var","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":9,"url":null},"def":{"name":"env_var","return_type":"String | ::Nil","visibility":"Public","body":"@env_var"},"external_var":false},{"html_id":"long:String|Nil-instance-method","name":"long","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":7,"url":null},"def":{"name":"long","return_type":"String | ::Nil","visibility":"Public","body":"@long"},"external_var":false},{"html_id":"long_key:String-instance-method","name":"long_key","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":8,"url":null},"def":{"name":"long_key","return_type":"String","visibility":"Public","body":"@long_key"},"external_var":false},{"html_id":"matches?(token:String):Bool-instance-method","name":"matches?","abstract":false,"args":[{"name":"token","external_name":"token","restriction":"String"}],"args_string":"(token : String) : Bool","args_html":"(token : String) : Bool","location":{"filename":"src/cligen/flag.cr","line_number":22,"url":null},"def":{"name":"matches?","args":[{"name":"token","external_name":"token","restriction":"String"}],"return_type":"Bool","visibility":"Public","body":"(token == @short) || (!@long_key.empty? && (token == @long_key))"},"external_var":false},{"html_id":"raw_value:String|Nil-instance-method","name":"raw_value","abstract":true,"location":{"filename":"src/cligen/flag.cr","line_number":28,"url":null},"def":{"name":"raw_value","return_type":"String | ::Nil","visibility":"Public","body":""},"external_var":false},{"html_id":"satisfied?:Bool-instance-method","name":"satisfied?","abstract":true,"location":{"filename":"src/cligen/flag.cr","line_number":26,"url":null},"def":{"name":"satisfied?","return_type":"Bool","visibility":"Public","body":""},"external_var":false},{"html_id":"short:String|Nil-instance-method","name":"short","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":6,"url":null},"def":{"name":"short","return_type":"String | ::Nil","visibility":"Public","body":"@short"},"external_var":false},{"html_id":"validate!:Nil-instance-method","name":"validate!","abstract":true,"location":{"filename":"src/cligen/flag.cr","line_number":27,"url":null},"def":{"name":"validate!","return_type":"Nil","visibility":"Public","body":""},"external_var":false},{"html_id":"var:String-instance-method","name":"var","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":5,"url":null},"def":{"name":"var","return_type":"String","visibility":"Public","body":"@var"},"external_var":false}]},{"html_id":"CliGenerator/CliGen/Command","path":"CliGen/Command.html","kind":"class","full_name":"CliGen::Command","name":"Command","abstract":false,"superclass":{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},"ancestors":[{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},{"html_id":"CliGenerator/Object","kind":"class","full_name":"Object","name":"Object"}],"locations":[{"filename":"src/cligen/command.cr","line_number":11,"url":null},{"filename":"src/cligen/command/argument.cr","line_number":2,"url":null},{"filename":"src/cligen/command/selection.cr","line_number":2,"url":null},{"filename":"src/cligen/command/subcommand.cr","line_number":2,"url":null},{"filename":"src/cligen/command/trigger.cr","line_number":2,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"},"macros":[{"html_id":"argument(variable,short,long,description,validation=nil)-macro","name":"argument","abstract":false,"args":[{"name":"variable","external_name":"variable","restriction":""},{"name":"short","external_name":"short","restriction":""},{"name":"long","external_name":"long","restriction":""},{"name":"description","external_name":"description","restriction":""},{"name":"validation","default_value":"nil","external_name":"validation","restriction":""}],"args_string":"(variable, short, long, description, validation = nil)","args_html":"(variable, short, long, description, validation = nil)","location":{"filename":"src/cligen/command/argument.cr","line_number":3,"url":null},"def":{"name":"argument","args":[{"name":"variable","external_name":"variable","restriction":""},{"name":"short","external_name":"short","restriction":""},{"name":"long","external_name":"long","restriction":""},{"name":"description","external_name":"description","restriction":""},{"name":"validation","default_value":"nil","external_name":"validation","restriction":""}],"visibility":"Public","body":" \n{% unless variable.is_a?(TypeDeclaration)\n raise(\"ERROR : CliGen::Command.argument : First argument (#{variable}) must be a TypeDeclaration (ex: ' : [= val]')\")\nend %}\n\n \n{% name = variable.name %}\n\n \n{% type = variable.type %}\n\n \n{% unless short.is_a?(StringLiteral) || (string == nil)\n raise(\"ERROR : CliGen::Command.argument(#{name}) : Provided short must be a string\")\nend %}\n\n \n{% unless long.is_a?(StringLiteral) || (long == nil)\n raise(\"ERROR : CliGen::Command.argument(#{name}) : Provided long must be a string\")\nend %}\n\n \n{% unless long || short\n raise(\"ERROR : CliGen::Command.argument(#{name}) : You must provide a short or long\")\nend %}\n\n \n{% unless description\n raise(\"ERROR : CliGen::Command.argument(#{name}) : You must provide a description\")\nend %}\n\n \n{% unless description.is_a?(StringLiteral)\n raise(\"ERROR : CliGen::Command.argument(#{name}) : Provided description must be a String\")\nend %}\n\n \n{% unless validation.nil? %}\n {% unless validation.is_a?(ProcLiteral)\n raise(\"ERROR : CliGen::Command.argument(#{name}) : Provided validation must be a Proc\")\nend %}\n {% unless validation.return_type == Bool\n raise(\"ERROR : CliGen::Command.argument(#{name}) : Provided validation return type must be a Bool\")\nend %}\n {% if validation.args.empty?\n raise(\"ERROR : CliGen::Command.argument(#{name}) : Provided validation provided validation must have an input variable\")\nend %}\n {% arg = validation.args.first %}\n {% unless arg.restriction == type %}\n {% example = \"->(#{arg.name} : #{type}) : #{type} { #{validation.body} }\" %}\n {% raise(\"ERROR : CliGen::Command.argument(#{name}) : Provided validation input value must be #{type}. EX: #{example}\") %}\n {% end %}\n {% end %}\n\n\n @[CliGen::Argument(short: \n{{ short }}\n, long: \n{{ long }}\n, description: \n{{ description }}\n, validation: \n{{ validation }}\n, on_match: \n{{ on_match }}\n)]\n @\n{{ variable }}\n\n\n def \n{{ variable.name }}\n= (value : \n{{ type }}\n)\n \n{% unless validation.nil? %}\n raise \"ERROR : #{@type.name}##{@def.name} : Provided value #{value} is not passing validation\" unless {{ validation }}.call(value)\n {% end %}\n\n @\n{{ name }}\n = value\n \nend\n \n"}},{"html_id":"selection(variable,short,long,description,options)-macro","name":"selection","abstract":false,"args":[{"name":"variable","external_name":"variable","restriction":""},{"name":"short","external_name":"short","restriction":""},{"name":"long","external_name":"long","restriction":""},{"name":"description","external_name":"description","restriction":""},{"name":"options","external_name":"options","restriction":""}],"args_string":"(variable, short, long, description, options)","args_html":"(variable, short, long, description, options)","location":{"filename":"src/cligen/command/selection.cr","line_number":3,"url":null},"def":{"name":"selection","args":[{"name":"variable","external_name":"variable","restriction":""},{"name":"short","external_name":"short","restriction":""},{"name":"long","external_name":"long","restriction":""},{"name":"description","external_name":"description","restriction":""},{"name":"options","external_name":"options","restriction":""}],"visibility":"Public","body":" \n{% unless variable.is_a?(TypeDeclaration)\n raise(\"ERROR : CliGen::Command.selection : First selection must be a TypeDeclaration (ex: ' : [= val]')\")\nend %}\n\n \n{% unless short.is_a?(StringLiteral) || (string == nil)\n raise(\"ERROR : CliGen::Command.selection : Provided short must be a string\")\nend %}\n\n \n{% unless long.is_a?(StringLiteral) || (long == nil)\n raise(\"ERROR : CliGen::Command.selection : Provided long must be a string\")\nend %}\n\n \n{% unless long || short\n raise(\"ERROR : CliGen::Command.selection : You must provide a short or long\")\nend %}\n\n \n{% unless description\n raise(\"ERROR : CliGen::Command.selection : You must provide a description\")\nend %}\n\n \n{% unless description.is_a?(StringLiteral)\n raise(\"ERROR : CliGen::Command.selection : Provided description must be a String\")\nend %}\n\n \n{% unless options\n raise(\"ERROR : CliGen::Command.selection : You must provide options\")\nend %}\n\n \n{% unless options\n raise(\"ERROR : CliGen::Command.selection : Provided options must be \")\nend %}\n\n \n"}},{"html_id":"subcommand(func,description,examples=nil,&block)-macro","name":"subcommand","abstract":false,"args":[{"name":"func","external_name":"func","restriction":""},{"name":"description","external_name":"description","restriction":""},{"name":"examples","default_value":"nil","external_name":"examples","restriction":""}],"args_string":"(func, description, examples = nil, &block)","args_html":"(func, description, examples = nil, &block)","location":{"filename":"src/cligen/command/subcommand.cr","line_number":3,"url":null},"def":{"name":"subcommand","args":[{"name":"func","external_name":"func","restriction":""},{"name":"description","external_name":"description","restriction":""},{"name":"examples","default_value":"nil","external_name":"examples","restriction":""}],"block_arg":{"name":"block","external_name":"block","restriction":""},"visibility":"Public","body":" \n{% unless variable.is_a?(TypeDeclaration)\n raise(\"ERROR : CliGen::Command.subcommand : First argument must be a TypeDeclaration (ex: ' : ')\")\nend %}\n\n \n{% unless description\n raise(\"ERROR : CliGen::Command.subcommand : You must provide a description\")\nend %}\n\n \n{% unless description.is_a?(StringLiteral)\n raise(\"ERROR : CliGen::Command.subcommand : Provided description must be a String\")\nend %}\n\n \n{% unless examples.nil? %}\n {% if examples.is_a?(Path)\n examples = examples.resolve\nend %}\n {% unless examples.is_a?(ArrayLiteral)\n raise(\"ERROR : CliGen::Command.subcommand : Provided example must be an Array\")\nend %}\n {% end %}\n\n \n{% unless block\n raise(\"ERROR : CliGen::Command.subcommand : You MUST provide a function body\")\nend %}\n\n\n @[CliGen::SubCommand(description: \n{{ description }}\n, \nexamples: \n{{ examples }}\n)]\n def \n{{ func }}\n\n \n{{ block.body }}\n\n \nend\n \n"}},{"html_id":"trigger(short,long,argument=nil,&on_match)-macro","name":"trigger","abstract":false,"args":[{"name":"short","external_name":"short","restriction":""},{"name":"long","external_name":"long","restriction":""},{"name":"argument","default_value":"nil","external_name":"argument","restriction":""}],"args_string":"(short, long, argument = nil, &on_match)","args_html":"(short, long, argument = nil, &on_match)","location":{"filename":"src/cligen/command/trigger.cr","line_number":3,"url":null},"def":{"name":"trigger","args":[{"name":"short","external_name":"short","restriction":""},{"name":"long","external_name":"long","restriction":""},{"name":"argument","default_value":"nil","external_name":"argument","restriction":""}],"block_arg":{"name":"on_match","external_name":"on_match","restriction":""},"visibility":"Public","body":" \n{% unless short.is_a?(StringLiteral)\n raise(\"ERROR : CliGen::Command.trigger : Provided short must be a string\")\nend %}\n\n \n{% unless long.is_a?(StringLiteral)\n raise(\"ERROR : CliGen::Command.trigger : Provided long must be a string\")\nend %}\n\n \n{% unless on_match\n raise(\"ERROR : CliGen::Command.trigger : Must provide a block for on_match trigger\")\nend %}\n\n \n{% name = long.gsub(/--/, \"\") %}\n\n\n @[CliGen::Trigger(short: \n{{ short }}\n, long: \n{{ long }}\n, argument: \n{{ argument }}\n)]\n \n{% if argument %}\n def self.__cligen_trigger__{{ name }}__({{ name }} : {{ argument }}) : Nil\n {{ on_match.body }}\n end\n {% else %}\n def self.__cligen_trigger__{{ name }}__ : Nil\n {{ on_match.body }}\n end\n {% end %}\n\n \n"}}]},{"html_id":"CliGenerator/CliGen/CommandInfo","path":"CliGen/CommandInfo.html","kind":"annotation","full_name":"CliGen::CommandInfo","name":"CommandInfo","abstract":false,"locations":[{"filename":"src/cligen/annotations.cr","line_number":5,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"}},{"html_id":"CliGenerator/CliGen/CommandNode","path":"CliGen/CommandNode.html","kind":"class","full_name":"CliGen::CommandNode","name":"CommandNode","abstract":false,"superclass":{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},"ancestors":[{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},{"html_id":"CliGenerator/Object","kind":"class","full_name":"Object","name":"Object"}],"locations":[{"filename":"src/cligen/command_node.cr","line_number":5,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"subclasses":[{"html_id":"CliGenerator/CliGen/App","kind":"class","full_name":"CliGen::App","name":"App"}],"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"},"constructors":[{"html_id":"new(name:String,flags:Array(CliGen::BaseFlag),commands:Array(CliGen::CommandNode),pre_run_commands:Array(_),post_run_commands:Array(_))-class-method","name":"new","abstract":false,"args":[{"name":"name","external_name":"name","restriction":"::String"},{"name":"flags","external_name":"flags","restriction":"::Array(::CliGen::BaseFlag)"},{"name":"commands","external_name":"commands","restriction":"::Array(::CliGen::CommandNode)"},{"name":"pre_run_commands","external_name":"pre_run_commands","restriction":"::Array(_)"},{"name":"post_run_commands","external_name":"post_run_commands","restriction":"::Array(_)"}],"args_string":"(name : String, flags : Array(CliGen::BaseFlag), commands : Array(CliGen::CommandNode), pre_run_commands : Array(_), post_run_commands : Array(_))","args_html":"(name : String, flags : Array(CliGen::BaseFlag), commands : Array(CliGen::CommandNode), pre_run_commands : Array(_), post_run_commands : Array(_))","location":{"filename":"src/cligen/command_node.cr","line_number":12,"url":null},"def":{"name":"new","args":[{"name":"name","external_name":"name","restriction":"::String"},{"name":"flags","external_name":"flags","restriction":"::Array(::CliGen::BaseFlag)"},{"name":"commands","external_name":"commands","restriction":"::Array(::CliGen::CommandNode)"},{"name":"pre_run_commands","external_name":"pre_run_commands","restriction":"::Array(_)"},{"name":"post_run_commands","external_name":"post_run_commands","restriction":"::Array(_)"}],"visibility":"Public","body":"_ = allocate\n_.initialize(name, flags, commands, pre_run_commands, post_run_commands)\nif _.responds_to?(:finalize)\n ::GC.add_finalizer(_)\nend\n_\n"},"external_var":false}],"instance_methods":[{"html_id":"check!-instance-method","name":"check!","abstract":false,"location":{"filename":"src/cligen/command_node.cr","line_number":49,"url":null},"def":{"name":"check!","visibility":"Public","body":"@flags.each(&.check!)\ncheck_for_duplicates!(@flags)\n@commands.each(&.check!)\n"},"external_var":false},{"html_id":"check_for_duplicates!(flags:Array(BaseFlag))-instance-method","name":"check_for_duplicates!","abstract":false,"args":[{"name":"flags","external_name":"flags","restriction":"Array(BaseFlag)"}],"args_string":"(flags : Array(BaseFlag))","args_html":"(flags : Array(BaseFlag))","location":{"filename":"src/cligen/command_node.cr","line_number":15,"url":null},"def":{"name":"check_for_duplicates!","args":[{"name":"flags","external_name":"flags","restriction":"Array(BaseFlag)"}],"visibility":"Public","body":"shorts = flags.compact_map(&.short)\nshort_duplicates = [] of String\nlongs = flags.compact_map do |f| if f.long_key.empty?\nelse\n f.long_key\nend end\nlong_duplicates = [] of String\n\nlast_short : String = \"\"\nshorts.sort.each do |short|\n if last_short == short\n short_duplicates << short\n end\n last_short = short\nend\n\nlast_long : String = \"\"\nlongs.sort.each do |long|\n if last_long == long\n long_duplicates << long\n end\n last_long = long\nend\n\nif long_duplicates.empty? && short_duplicates.empty?\nelse\n error_buffer = \"ERROR : CommandNode(%s)#check! : Found Duplicates : %s\"\n\n message = \"\"\n if long_duplicates.empty?\n else\n message = message + (\"\\nLong:\\n%s\\n\" % (long_duplicates.map do |f| \"- #{f}\" end.join(\"\\n\")))\n end\n\n if short_duplicates.empty?\n else\n message = message + (\"\\nShort:\\n%s\" % (short_duplicates.map do |f| \"- #{f}\" end.join(\"\\n\")))\n end\n\n raise(error_buffer % [@name, message])\nend\n"},"external_var":false},{"html_id":"find_match(arg:String)-instance-method","name":"find_match","abstract":false,"args":[{"name":"arg","external_name":"arg","restriction":"String"}],"args_string":"(arg : String)","args_html":"(arg : String)","location":{"filename":"src/cligen/command_node.cr","line_number":55,"url":null},"def":{"name":"find_match","args":[{"name":"arg","external_name":"arg","restriction":"String"}],"visibility":"Public","body":"case arg\nwhen CliGen::Regex::FLAG_REGEX\n if flg = @flags.find(&.matches?(arg))\n flg\n else\n CliGen::MatchType::NoMatch\n end\nwhen CliGen::Regex::FLAG_WITH_ARG\n CliGen::MatchType::FlagWithArg\nwhen CliGen::Regex::SHORT_WITH_INLINE_ARG\n CliGen::MatchType::ShortWithInlineArg\nwhen CliGen::Regex::FLAG_MULTIPLE_SHORT\n CliGen::MatchType::FlagMultipleShort\nelse\n if cmd = @commands.find do |c| c.name == arg end\n cmd\n else\n CliGen::MatchType::NoMatch\n end\nend"},"external_var":false},{"html_id":"process(args:Array(String))-instance-method","name":"process","doc":"This serves to just convert the arguments into a usable Array(Arg) format\nand pass it to the ACTUAL CommandNode#process method","summary":"

This serves to just convert the arguments into a usable Array(Arg) format and pass it to the ACTUAL CommandNode#process method

","abstract":false,"args":[{"name":"args","external_name":"args","restriction":"Array(String)"}],"args_string":"(args : Array(String))","args_html":"(args : Array(String))","location":{"filename":"src/cligen/command_node.cr","line_number":80,"url":null},"def":{"name":"process","args":[{"name":"args","external_name":"args","restriction":"Array(String)"}],"visibility":"Public","body":"new_args = [] of Arg\nargs.each_with_index do |arg, index|\n new_args << Arg.new(value: arg, index: index)\nend\n\n\nprocess(new_args)\n"},"external_var":false},{"html_id":"process(args:Array(Arg)):Nil-instance-method","name":"process","abstract":false,"args":[{"name":"args","external_name":"args","restriction":"Array(Arg)"}],"args_string":"(args : Array(Arg)) : Nil","args_html":"(args : Array(Arg)) : Nil","location":{"filename":"src/cligen/command_node.cr","line_number":90,"url":null},"def":{"name":"process","args":[{"name":"args","external_name":"args","restriction":"Array(Arg)"}],"return_type":"Nil","visibility":"Public","body":"check!\n\n@pre_run_commands.each(&.call)\n\nargs.each do |arg|\n if arg.processed?\n next\n end\n arg.processed\n\n case match = find_match(arg.value)\n when CommandNode\n match.process(args.reject(&.processed?))\n when BaseFlag\n if match.requires_arg?\n match.process(args.reject(&.processed?))\n else\n match.process\n end\n when MatchType::FlagWithArg\n if regex_match = CliGen::Regex::FLAG_WITH_ARG.match(arg.value)\n case flag_match = find_match(regex_match[\"flag\"])\n when BaseFlag\n flag_match.process([Arg.new(value: regex_match[\"arg\"], index: arg.index)])\n else\n raise(\"ERROR : CommandNode(#{@name}).run : There was no match for #{regex_match[\"flag\"]}\")\n end\n else\n raise(\"Oh good, you broke regex. How the hell did it match in find_match but not above? What the hell is going on\")\n end\n when MatchType::ShortWithInlineArg\n abort(\"#{CliGen::APPNAME}: invalid flag '#{arg.value}' — inline values are not supported. Did you mean '#{arg.value[0..1]} #{arg.value[2..]}' ?\")\n when MatchType::FlagMultipleShort\n (arg.value.gsub(/^-/, \"\")).chars.map do |c| \"-#{c}\" end.each do |flag|\n case match = find_match(flag)\n when BaseFlag\n if match.requires_arg?\n abort(\"#{CliGen::APPNAME}: cannot bundle flag that requires an argument: #{flag}\")\n end\n match.process\n when MatchType::NoMatch\n raise(\"ERROR : CommandNode(#{@name}).run : There was no match for #{flag}\")\n end\n end\n when MatchType::NoMatch\n raise(\"ERROR : CommandNode(#{@name}).run : There was no match for #{arg.value}\")\n end\nend\n\n@post_run_commands.each(&.call)\n"},"external_var":false}]},{"html_id":"CliGenerator/CliGen/DefaultFlag","path":"CliGen/DefaultFlag.html","kind":"annotation","full_name":"CliGen::DefaultFlag","name":"DefaultFlag","abstract":false,"locations":[{"filename":"src/cligen.cr","line_number":33,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"}},{"html_id":"CliGenerator/CliGen/Flag","path":"CliGen/Flag.html","kind":"class","full_name":"CliGen::Flag(T)","name":"Flag","abstract":false,"superclass":{"html_id":"CliGenerator/CliGen/BaseFlag","kind":"class","full_name":"CliGen::BaseFlag","name":"BaseFlag"},"ancestors":[{"html_id":"CliGenerator/CliGen/BaseFlag","kind":"class","full_name":"CliGen::BaseFlag","name":"BaseFlag"},{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},{"html_id":"CliGenerator/Object","kind":"class","full_name":"Object","name":"Object"}],"locations":[{"filename":"src/cligen/flag.cr","line_number":31,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"},"constructors":[{"html_id":"new(var:String,short:String|Nil,long:String|Nil,env_var:String|Nil,description:String,default:T|Nil=nil,options:Array(String)|Nil=nil,validate:T->Bool|Nil=nil,on_match:Proc(Nil)|Nil=nil)-class-method","name":"new","abstract":false,"args":[{"name":"var","external_name":"var","restriction":"String"},{"name":"short","external_name":"short","restriction":"String | ::Nil"},{"name":"long","external_name":"long","restriction":"String | ::Nil"},{"name":"env_var","external_name":"env_var","restriction":"String | ::Nil"},{"name":"description","external_name":"description","restriction":"String"},{"name":"default","default_value":"nil","external_name":"default","restriction":"T | ::Nil"},{"name":"options","default_value":"nil","external_name":"options","restriction":"Array(String) | ::Nil"},{"name":"validate","default_value":"nil","external_name":"validate","restriction":"(T -> Bool) | ::Nil"},{"name":"on_match","default_value":"nil","external_name":"on_match","restriction":"Proc(Nil) | ::Nil"}],"args_string":"(var : String, short : String | Nil, long : String | Nil, env_var : String | Nil, description : String, default : T | Nil = nil, options : Array(String) | Nil = nil, validate : T -> Bool | Nil = nil, on_match : Proc(Nil) | Nil = nil)","args_html":"(var : String, short : String | Nil, long : String | Nil, env_var : String | Nil, description : String, default : T | Nil = nil, options : Array(String) | Nil = nil, validate : T -> Bool | Nil = nil, on_match : Proc(Nil) | Nil = nil)","location":{"filename":"src/cligen/flag.cr","line_number":38,"url":null},"def":{"name":"new","args":[{"name":"var","external_name":"var","restriction":"String"},{"name":"short","external_name":"short","restriction":"String | ::Nil"},{"name":"long","external_name":"long","restriction":"String | ::Nil"},{"name":"env_var","external_name":"env_var","restriction":"String | ::Nil"},{"name":"description","external_name":"description","restriction":"String"},{"name":"default","default_value":"nil","external_name":"default","restriction":"T | ::Nil"},{"name":"options","default_value":"nil","external_name":"options","restriction":"Array(String) | ::Nil"},{"name":"validate","default_value":"nil","external_name":"validate","restriction":"(T -> Bool) | ::Nil"},{"name":"on_match","default_value":"nil","external_name":"on_match","restriction":"Proc(Nil) | ::Nil"}],"visibility":"Public","body":"_ = Flag(T).allocate\n_.initialize(var, short, long, env_var, description, default, options, validate, on_match)\nif _.responds_to?(:finalize)\n ::GC.add_finalizer(_)\nend\n_\n"},"external_var":false}],"instance_methods":[{"html_id":"process(argv:Array(Arg)=[]ofArray(Arg)):Nil-instance-method","name":"process","abstract":false,"args":[{"name":"argv","default_value":"[] of Array(Arg)","external_name":"argv","restriction":"Array(Arg)"}],"args_string":"(argv : Array(Arg) = [] of Array(Arg)) : Nil","args_html":"(argv : Array(Arg) = [] of Array(Arg)) : Nil","location":{"filename":"src/cligen/flag.cr","line_number":56,"url":null},"def":{"name":"process","args":[{"name":"argv","default_value":"[] of Array(Arg)","external_name":"argv","restriction":"Array(Arg)"}],"return_type":"Nil","visibility":"Public","body":"if requires_arg?\n if argv.empty?\n raise(\"ERROR : Flag({{T}}) : Array requires an argument but provided array is empty\")\n end\nend\n\n{% if T == Bool %}\n @value = true\n {% elsif T <= Array %}\n {% if T.type_vars.size > 1\n raise(\"ERROR : Flag(#{T}) : You cannot define multiple types of array entries\")\nend %}\n {% elem = T.type_vars.first %}\n argv.each do |arg|\n break if arg.value.starts_with('-')\n {% if elem == Int32 %}\n (@value ||= [] of Int32) << arg.value.to_i\n {% else %}\n (@value ||= [] of String) << arg.value\n {% end %}\n arg.processed\n end\n {% elsif T == Int32 %}\n @value = argv.first.value.to_i\n argv.first.processed\n {% elsif T == Time %}\n @value = parse_time(argv.first.value)\n argv.first.processed\n {% else %} # String\n @value = argv.first.value\n argv.first.processed\n {% end %}\n@on_match.try(&.call)\n"},"external_var":false},{"html_id":"raw_value:String|Nil-instance-method","name":"raw_value","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":104,"url":null},"def":{"name":"raw_value","return_type":"String | ::Nil","visibility":"Public","body":"{% if T == Bool %}\n @value.try(&.to_s)\n {% elsif T <= Array %}\n @value.try(&.join(\",\"))\n {% else %}\n @value.try(&.to_s)\n {% end %}"},"external_var":false},{"html_id":"requires_arg?:Bool-instance-method","name":"requires_arg?","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":52,"url":null},"def":{"name":"requires_arg?","return_type":"Bool","visibility":"Public","body":"({{ T }}) != Bool"},"external_var":false},{"html_id":"satisfied?:Bool-instance-method","name":"satisfied?","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":114,"url":null},"def":{"name":"satisfied?","return_type":"Bool","visibility":"Public","body":"if !@value.nil?\n return true\nend\nif @env_var && ENV[@env_var.not_nil!]?\n return true\nend\nif !@default.nil?\n return true\nend\nfalse\n"},"external_var":false},{"html_id":"validate!:Nil-instance-method","name":"validate!","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":121,"url":null},"def":{"name":"validate!","return_type":"Nil","visibility":"Public","body":"v = value!\n\nif opts = @options\n str_v = v.to_s\n if opts.includes?(str_v)\n else\n abort(\"#{CliGen::APPNAME}: '#{str_v}' is not a valid value for #{@long_key.empty? ? @short : @long_key} (valid: #{opts.join(\", \")})\")\n end\nend\n\nif check = @validate\n if check.call(v)\n else\n abort(\"#{CliGen::APPNAME}: validation failed for #{@long_key.empty? ? @short : @long_key}\")\n end\nend\n"},"external_var":false},{"html_id":"value!:T-instance-method","name":"value!","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":88,"url":null},"def":{"name":"value!","return_type":"T","visibility":"Public","body":"v = @value\n\n\nif v.nil? && @env_var\n if raw = ENV[@env_var.not_nil!]?\n v = coerce(raw)\n end\nend\n\nv || (v = @default)\n\nif v.nil?\n abort(\"#{CliGen::APPNAME}: required flag #{@long_key.empty? ? @short : @long_key} was not provided\")\nend\nv.not_nil!\n"},"external_var":false}]},{"html_id":"CliGenerator/CliGen/Format","path":"CliGen/Format.html","kind":"module","full_name":"CliGen::Format","name":"Format","abstract":false,"locations":[{"filename":"src/cligen/format.cr","line_number":1,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"constants":[{"id":"INPUT_DATE_FORMAT","name":"INPUT_DATE_FORMAT","value":"\"%Y-%m-%d\""},{"id":"INPUT_DATETIME_FORMAT","name":"INPUT_DATETIME_FORMAT","value":"\"%Y-%m-%d %H:%M:%S\""}],"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"}},{"html_id":"CliGenerator/CliGen/MatchType","path":"CliGen/MatchType.html","kind":"enum","full_name":"CliGen::MatchType","name":"MatchType","abstract":false,"ancestors":[{"html_id":"CliGenerator/Enum","kind":"struct","full_name":"Enum","name":"Enum"},{"html_id":"CliGenerator/Comparable","kind":"module","full_name":"Comparable","name":"Comparable"},{"html_id":"CliGenerator/Value","kind":"struct","full_name":"Value","name":"Value"},{"html_id":"CliGenerator/Object","kind":"class","full_name":"Object","name":"Object"}],"locations":[{"filename":"src/cligen/match_type.cr","line_number":2,"url":null}],"repository_name":"CliGenerator","program":false,"enum":true,"alias":false,"const":false,"constants":[{"id":"FlagWithArg","name":"FlagWithArg","value":"0"},{"id":"FlagMultipleShort","name":"FlagMultipleShort","value":"1"},{"id":"ShortWithInlineArg","name":"ShortWithInlineArg","value":"2"},{"id":"NoMatch","name":"NoMatch","value":"3"}],"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"},"instance_methods":[{"html_id":"flag_multiple_short?-instance-method","name":"flag_multiple_short?","doc":"Returns `true` if this enum value equals `FlagMultipleShort`","summary":"

Returns true if this enum value equals FlagMultipleShort

","abstract":false,"location":{"filename":"src/cligen/match_type.cr","line_number":4,"url":null},"def":{"name":"flag_multiple_short?","visibility":"Public","body":"self == FlagMultipleShort"},"external_var":false},{"html_id":"flag_with_arg?-instance-method","name":"flag_with_arg?","doc":"Returns `true` if this enum value equals `FlagWithArg`","summary":"

Returns true if this enum value equals FlagWithArg

","abstract":false,"location":{"filename":"src/cligen/match_type.cr","line_number":3,"url":null},"def":{"name":"flag_with_arg?","visibility":"Public","body":"self == FlagWithArg"},"external_var":false},{"html_id":"no_match?-instance-method","name":"no_match?","doc":"Returns `true` if this enum value equals `NoMatch`","summary":"

Returns true if this enum value equals NoMatch

","abstract":false,"location":{"filename":"src/cligen/match_type.cr","line_number":6,"url":null},"def":{"name":"no_match?","visibility":"Public","body":"self == NoMatch"},"external_var":false},{"html_id":"short_with_inline_arg?-instance-method","name":"short_with_inline_arg?","doc":"Returns `true` if this enum value equals `ShortWithInlineArg`","summary":"

Returns true if this enum value equals ShortWithInlineArg

","abstract":false,"location":{"filename":"src/cligen/match_type.cr","line_number":5,"url":null},"def":{"name":"short_with_inline_arg?","visibility":"Public","body":"self == ShortWithInlineArg"},"external_var":false}]},{"html_id":"CliGenerator/CliGen/ProxyCommand","path":"CliGen/ProxyCommand.html","kind":"annotation","full_name":"CliGen::ProxyCommand","name":"ProxyCommand","abstract":false,"locations":[{"filename":"src/cligen/annotations.cr","line_number":2,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"}},{"html_id":"CliGenerator/CliGen/Regex","path":"CliGen/Regex.html","kind":"module","full_name":"CliGen::Regex","name":"Regex","abstract":false,"locations":[{"filename":"src/cligen/regex.cr","line_number":1,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"constants":[{"id":"FLAG_MULTIPLE_SHORT","name":"FLAG_MULTIPLE_SHORT","value":"/^-[a-zA-Z]+$/"},{"id":"FLAG_REGEX","name":"FLAG_REGEX","value":"/^(-[a-zA-Z]|--[a-zA-Z-_]+)$/"},{"id":"FLAG_WITH_ARG","name":"FLAG_WITH_ARG","value":"/^(?(-[a-zA-Z]|--[a-zA-Z-_]+))=\"?(?\\S+?)\"?$/"},{"id":"INPUT_DATE_REGEX","name":"INPUT_DATE_REGEX","value":"/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/"},{"id":"INPUT_DATETIME_REGEX","name":"INPUT_DATETIME_REGEX","value":"/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/"},{"id":"SHORT_WITH_INLINE_ARG","name":"SHORT_WITH_INLINE_ARG","value":"/^-[a-zA-Z][a-zA-Z0-9]+$/"}],"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"}},{"html_id":"CliGenerator/CliGen/Selection","path":"CliGen/Selection.html","kind":"annotation","full_name":"CliGen::Selection","name":"Selection","abstract":false,"locations":[{"filename":"src/cligen/annotations.cr","line_number":14,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"}},{"html_id":"CliGenerator/CliGen/SubCommand","path":"CliGen/SubCommand.html","kind":"annotation","full_name":"CliGen::SubCommand","name":"SubCommand","abstract":false,"locations":[{"filename":"src/cligen/annotations.cr","line_number":17,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"}},{"html_id":"CliGenerator/CliGen/Trigger","path":"CliGen/Trigger.html","kind":"annotation","full_name":"CliGen::Trigger","name":"Trigger","abstract":false,"locations":[{"filename":"src/cligen/annotations.cr","line_number":11,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"}}]}]}} \ No newline at end of file diff --git a/docs/js/doc.js b/docs/js/doc.js new file mode 100644 index 0000000..eaedd5c --- /dev/null +++ b/docs/js/doc.js @@ -0,0 +1,1099 @@ +window.CrystalDocs = (window.CrystalDocs || {}); + +CrystalDocs.base_path = (CrystalDocs.base_path || ""); + +CrystalDocs.searchIndex = (CrystalDocs.searchIndex || false); +CrystalDocs.MAX_RESULTS_DISPLAY = 140; + +CrystalDocs.runQuery = function(query) { + function searchType(type, query, results) { + var matches = []; + var matchedFields = []; + var name = type.full_name; + var i = name.lastIndexOf("::"); + if (i > 0) { + name = name.substring(i + 2); + } + var nameMatches = query.matches(name); + if (nameMatches){ + matches = matches.concat(nameMatches); + matchedFields.push("name"); + } + + var namespaceMatches = query.matchesNamespace(type.full_name); + if(namespaceMatches){ + matches = matches.concat(namespaceMatches); + matchedFields.push("name"); + } + + var docMatches = query.matches(type.doc); + if(docMatches){ + matches = matches.concat(docMatches); + matchedFields.push("doc"); + } + if (matches.length > 0) { + results.push({ + id: type.html_id, + result_type: "type", + kind: type.kind, + name: name, + full_name: type.full_name, + href: type.path, + summary: type.summary, + matched_fields: matchedFields, + matched_terms: matches + }); + } + + if (type.instance_methods) { + type.instance_methods.forEach(function(method) { + searchMethod(method, type, "instance_method", query, results); + }) + } + if (type.class_methods) { + type.class_methods.forEach(function(method) { + searchMethod(method, type, "class_method", query, results); + }) + } + if (type.constructors) { + type.constructors.forEach(function(constructor) { + searchMethod(constructor, type, "constructor", query, results); + }) + } + if (type.macros) { + type.macros.forEach(function(macro) { + searchMethod(macro, type, "macro", query, results); + }) + } + if (type.constants) { + type.constants.forEach(function(constant){ + searchConstant(constant, type, query, results); + }); + } + if (type.types) { + type.types.forEach(function(subtype){ + searchType(subtype, query, results); + }); + } + }; + + function searchMethod(method, type, kind, query, results) { + var matches = []; + var matchedFields = []; + var nameMatches = query.matchesMethod(method.name, kind, type); + if (nameMatches){ + matches = matches.concat(nameMatches); + matchedFields.push("name"); + } + + if (method.args) { + method.args.forEach(function(arg){ + var argMatches = query.matches(arg.external_name); + if (argMatches) { + matches = matches.concat(argMatches); + matchedFields.push("args"); + } + }); + } + + var docMatches = query.matches(type.doc); + if(docMatches){ + matches = matches.concat(docMatches); + matchedFields.push("doc"); + } + + if (matches.length > 0) { + var typeMatches = query.matches(type.full_name); + if (typeMatches) { + matchedFields.push("type"); + matches = matches.concat(typeMatches); + } + results.push({ + id: method.html_id, + type: type.full_name, + result_type: kind, + name: method.name, + full_name: type.full_name + "#" + method.name, + args_string: method.args_string, + summary: method.summary, + href: type.path + "#" + method.html_id, + matched_fields: matchedFields, + matched_terms: matches + }); + } + } + + function searchConstant(constant, type, query, results) { + var matches = []; + var matchedFields = []; + var nameMatches = query.matches(constant.name); + if (nameMatches){ + matches = matches.concat(nameMatches); + matchedFields.push("name"); + } + var docMatches = query.matches(constant.doc); + if(docMatches){ + matches = matches.concat(docMatches); + matchedFields.push("doc"); + } + if (matches.length > 0) { + var typeMatches = query.matches(type.full_name); + if (typeMatches) { + matchedFields.push("type"); + matches = matches.concat(typeMatches); + } + results.push({ + id: constant.id, + type: type.full_name, + result_type: "constant", + name: constant.name, + full_name: type.full_name + "#" + constant.name, + value: constant.value, + summary: constant.summary, + href: type.path + "#" + constant.id, + matched_fields: matchedFields, + matched_terms: matches + }); + } + } + + var results = []; + searchType(CrystalDocs.searchIndex.program, query, results); + return results; +}; + +CrystalDocs.rankResults = function(results, query) { + function uniqueArray(ar) { + var j = {}; + + ar.forEach(function(v) { + j[v + "::" + typeof v] = v; + }); + + return Object.keys(j).map(function(v) { + return j[v]; + }); + } + + results = results.sort(function(a, b) { + var matchedTermsDiff = uniqueArray(b.matched_terms).length - uniqueArray(a.matched_terms).length; + var aHasDocs = b.matched_fields.includes("doc"); + var bHasDocs = b.matched_fields.includes("doc"); + + var aOnlyDocs = aHasDocs && a.matched_fields.length == 1; + var bOnlyDocs = bHasDocs && b.matched_fields.length == 1; + + if (a.result_type == "type" && b.result_type != "type" && !aOnlyDocs) { + if(CrystalDocs.DEBUG) { console.log("a is type b not"); } + return -1; + } else if (b.result_type == "type" && a.result_type != "type" && !bOnlyDocs) { + if(CrystalDocs.DEBUG) { console.log("b is type, a not"); } + return 1; + } + if (a.matched_fields.includes("name")) { + if (b.matched_fields.includes("name")) { + var a_name = (CrystalDocs.prefixForType(a.result_type) || "") + ((a.result_type == "type") ? a.full_name : a.name); + var b_name = (CrystalDocs.prefixForType(b.result_type) || "") + ((b.result_type == "type") ? b.full_name : b.name); + a_name = a_name.toLowerCase(); + b_name = b_name.toLowerCase(); + for(var i = 0; i < query.normalizedTerms.length; i++) { + var term = query.terms[i].replace(/^::?|::?$/, ""); + var a_orig_index = a_name.indexOf(term); + var b_orig_index = b_name.indexOf(term); + if(CrystalDocs.DEBUG) { console.log("term: " + term + " a: " + a_name + " b: " + b_name); } + if(CrystalDocs.DEBUG) { console.log(a_orig_index, b_orig_index, a_orig_index - b_orig_index); } + if (a_orig_index >= 0) { + if (b_orig_index >= 0) { + if(CrystalDocs.DEBUG) { console.log("both have exact match", a_orig_index > b_orig_index ? -1 : 1); } + if(a_orig_index != b_orig_index) { + if(CrystalDocs.DEBUG) { console.log("both have exact match at different positions", a_orig_index > b_orig_index ? 1 : -1); } + return a_orig_index > b_orig_index ? 1 : -1; + } + } else { + if(CrystalDocs.DEBUG) { console.log("a has exact match, b not"); } + return -1; + } + } else if (b_orig_index >= 0) { + if(CrystalDocs.DEBUG) { console.log("b has exact match, a not"); } + return 1; + } + } + } else { + if(CrystalDocs.DEBUG) { console.log("a has match in name, b not"); } + return -1; + } + } else if ( + !a.matched_fields.includes("name") && + b.matched_fields.includes("name") + ) { + return 1; + } + + if (matchedTermsDiff != 0 || (aHasDocs != bHasDocs)) { + if(CrystalDocs.DEBUG) { console.log("matchedTermsDiff: " + matchedTermsDiff, aHasDocs, bHasDocs); } + return matchedTermsDiff; + } + + var matchedFieldsDiff = b.matched_fields.length - a.matched_fields.length; + if (matchedFieldsDiff != 0) { + if(CrystalDocs.DEBUG) { console.log("matched to different number of fields: " + matchedFieldsDiff); } + return matchedFieldsDiff > 0 ? 1 : -1; + } + + var nameCompare = a.name.localeCompare(b.name); + if(nameCompare != 0){ + if(CrystalDocs.DEBUG) { console.log("nameCompare resulted in: " + a.name + "<=>" + b.name + ": " + nameCompare); } + return nameCompare > 0 ? 1 : -1; + } + + if(a.matched_fields.includes("args") && b.matched_fields.includes("args")) { + for(var i = 0; i < query.terms.length; i++) { + var term = query.terms[i]; + var aIndex = a.args_string.indexOf(term); + var bIndex = b.args_string.indexOf(term); + if(CrystalDocs.DEBUG) { console.log("index of " + term + " in args_string: " + aIndex + " - " + bIndex); } + if(aIndex >= 0){ + if(bIndex >= 0){ + if(aIndex != bIndex){ + return aIndex > bIndex ? 1 : -1; + } + }else{ + return -1; + } + }else if(bIndex >= 0) { + return 1; + } + } + } + + return 0; + }); + + if (results.length > 1) { + // if we have more than two search terms, only include results with the most matches + var bestMatchedTerms = uniqueArray(results[0].matched_terms).length; + + results = results.filter(function(result) { + return uniqueArray(result.matched_terms).length + 1 >= bestMatchedTerms; + }); + } + return results; +}; + +CrystalDocs.prefixForType = function(type) { + switch (type) { + case "instance_method": + return "#"; + + case "class_method": + case "macro": + case "constructor": + return "."; + + default: + return false; + } +}; + +CrystalDocs.displaySearchResults = function(results, query) { + function sanitize(html){ + return html.replace(/<(?!\/?code)[^>]+>/g, ""); + } + + // limit results + if (results.length > CrystalDocs.MAX_RESULTS_DISPLAY) { + results = results.slice(0, CrystalDocs.MAX_RESULTS_DISPLAY); + } + + var $frag = document.createDocumentFragment(); + var $resultsElem = document.querySelector(".search-list"); + $resultsElem.innerHTML = ""; + + results.forEach(function(result, i) { + var url = CrystalDocs.base_path + result.href; + var type = false; + + var title = query.highlight(result.result_type == "type" ? result.full_name : result.name); + + var prefix = CrystalDocs.prefixForType(result.result_type); + if (prefix) { + title = "" + prefix + "" + title; + } + + title = "" + title + ""; + + if (result.args_string) { + title += + "" + query.highlight(result.args_string) + ""; + } + + $elem = document.createElement("li"); + $elem.className = "search-result search-result--" + result.result_type; + $elem.dataset.href = url; + $elem.setAttribute("title", result.full_name + " docs page"); + + var $title = document.createElement("div"); + $title.setAttribute("class", "search-result__title"); + var $titleLink = document.createElement("a"); + $titleLink.setAttribute("href", url); + + $titleLink.innerHTML = title; + $title.appendChild($titleLink); + $elem.appendChild($title); + $elem.addEventListener("click", function() { + $titleLink.click(); + }); + + if (result.result_type !== "type") { + var $type = document.createElement("div"); + $type.setAttribute("class", "search-result__type"); + $type.innerHTML = query.highlight(result.type); + $elem.appendChild($type); + } + + if(result.summary){ + var $doc = document.createElement("div"); + $doc.setAttribute("class", "search-result__doc"); + $doc.innerHTML = query.highlight(sanitize(result.summary)); + $elem.appendChild($doc); + } + + $elem.appendChild(document.createComment(JSON.stringify(result))); + $frag.appendChild($elem); + }); + + $resultsElem.appendChild($frag); + + CrystalDocs.toggleResultsList(true); +}; + +CrystalDocs.toggleResultsList = function(visible) { + if (visible) { + document.querySelector(".types-list").classList.add("hidden"); + document.querySelector(".search-results").classList.remove("hidden"); + } else { + document.querySelector(".types-list").classList.remove("hidden"); + document.querySelector(".search-results").classList.add("hidden"); + } +}; + +CrystalDocs.Query = function(string) { + this.original = string; + this.terms = string.split(/\s+/).filter(function(word) { + return CrystalDocs.Query.stripModifiers(word).length > 0; + }); + + var normalized = this.terms.map(CrystalDocs.Query.normalizeTerm); + this.normalizedTerms = normalized; + + function runMatcher(field, matcher) { + if (!field) { + return false; + } + var normalizedValue = CrystalDocs.Query.normalizeTerm(field); + + var matches = []; + normalized.forEach(function(term) { + if (matcher(normalizedValue, term)) { + matches.push(term); + } + }); + return matches.length > 0 ? matches : false; + } + + this.matches = function(field) { + return runMatcher(field, function(normalized, term) { + if (term[0] == "#" || term[0] == ".") { + return false; + } + return normalized.indexOf(term) >= 0; + }); + }; + + function namespaceMatcher(normalized, term){ + var i = term.indexOf(":"); + if(i >= 0){ + term = term.replace(/^::?|::?$/, ""); + var index = normalized.indexOf(term); + if((index == 0) || (index > 0 && normalized[index-1] == ":")){ + return true; + } + } + return false; + } + this.matchesMethod = function(name, kind, type) { + return runMatcher(name, function(normalized, term) { + var i = term.indexOf("#"); + if(i >= 0){ + if (kind != "instance_method") { + return false; + } + }else{ + i = term.indexOf("."); + if(i >= 0){ + if (kind != "class_method" && kind != "macro" && kind != "constructor") { + return false; + } + }else{ + //neither # nor . + if(term.indexOf(":") && namespaceMatcher(normalized, term)){ + return true; + } + } + } + + var methodName = term; + if(i >= 0){ + var termType = term.substring(0, i); + methodName = term.substring(i+1); + + if(termType != "") { + if(CrystalDocs.Query.normalizeTerm(type.full_name).indexOf(termType) < 0){ + return false; + } + } + } + return normalized.indexOf(methodName) >= 0; + }); + }; + + this.matchesNamespace = function(namespace){ + return runMatcher(namespace, namespaceMatcher); + }; + + this.highlight = function(string) { + if (typeof string == "undefined") { + return ""; + } + function escapeRegExp(s) { + return s.replace(/[.*+?\^${}()|\[\]\\]/g, "\\$&").replace(/^[#\.:]+/, ""); + } + return string.replace( + new RegExp("(" + this.normalizedTerms.map(escapeRegExp).join("|") + ")", "gi"), + "$1" + ); + }; +}; +CrystalDocs.Query.normalizeTerm = function(term) { + return term.toLowerCase(); +}; +CrystalDocs.Query.stripModifiers = function(term) { + switch (term[0]) { + case "#": + case ".": + case ":": + return term.substr(1); + + default: + return term; + } +} + +CrystalDocs.search = function(string) { + if(!CrystalDocs.searchIndex) { + console.log("CrystalDocs search index not initialized, delaying search"); + + document.addEventListener("CrystalDocs:loaded", function listener(){ + document.removeEventListener("CrystalDocs:loaded", listener); + CrystalDocs.search(string); + }); + return; + } + + document.dispatchEvent(new Event("CrystalDocs:searchStarted")); + + var query = new CrystalDocs.Query(string); + var results = CrystalDocs.runQuery(query); + results = CrystalDocs.rankResults(results, query); + CrystalDocs.displaySearchResults(results, query); + + document.dispatchEvent(new Event("CrystalDocs:searchPerformed")); +}; + +CrystalDocs.initializeIndex = function(data) { + CrystalDocs.searchIndex = data; + + document.dispatchEvent(new Event("CrystalDocs:loaded")); +}; + +CrystalDocs.loadIndex = function() { + function loadJSON(file, callback) { + var xobj = new XMLHttpRequest(); + xobj.overrideMimeType("application/json"); + xobj.open("GET", file, true); + xobj.onreadystatechange = function() { + if (xobj.readyState == 4 && xobj.status == "200") { + callback(xobj.responseText); + } + }; + xobj.send(null); + } + + function loadScript(file) { + script = document.createElement("script"); + script.src = file; + document.body.appendChild(script); + } + + function parseJSON(json) { + CrystalDocs.initializeIndex(JSON.parse(json)); + } + + for(var i = 0; i < document.scripts.length; i++){ + var script = document.scripts[i]; + if (script.src && script.src.indexOf("js/doc.js") >= 0) { + if (script.src.indexOf("file://") == 0) { + // We need to support JSONP files for the search to work on local file system. + var jsonPath = script.src.replace("js/doc.js", "search-index.js"); + loadScript(jsonPath); + return; + } else { + var jsonPath = script.src.replace("js/doc.js", "index.json"); + loadJSON(jsonPath, parseJSON); + return; + } + } + } + console.error("Could not find location of js/doc.js"); +}; + +// Callback for jsonp +function crystal_doc_search_index_callback(data) { + CrystalDocs.initializeIndex(data); +} + +Navigator = function(sidebar, searchInput, list, leaveSearchScope){ + this.list = list; + var self = this; + + var performingSearch = false; + + document.addEventListener('CrystalDocs:searchStarted', function(){ + performingSearch = true; + }); + document.addEventListener('CrystalDocs:searchDebounceStarted', function(){ + performingSearch = true; + }); + document.addEventListener('CrystalDocs:searchPerformed', function(){ + performingSearch = false; + }); + document.addEventListener('CrystalDocs:searchDebounceStopped', function(event){ + performingSearch = false; + }); + + function delayWhileSearching(callback) { + if(performingSearch){ + document.addEventListener('CrystalDocs:searchPerformed', function listener(){ + document.removeEventListener('CrystalDocs:searchPerformed', listener); + + // add some delay to let search results display kick in + setTimeout(callback, 100); + }); + }else{ + callback(); + } + } + + function clearMoveTimeout() { + clearTimeout(self.moveTimeout); + self.moveTimeout = null; + } + + function startMoveTimeout(upwards){ + /*if(self.moveTimeout) { + clearMoveTimeout(); + } + + var go = function() { + if (!self.moveTimeout) return; + self.move(upwards); + self.moveTimeout = setTimeout(go, 600); + }; + self.moveTimeout = setTimeout(go, 800);*/ + } + + function scrollCenter(element) { + var rect = element.getBoundingClientRect(); + var middle = sidebar.clientHeight / 2; + sidebar.scrollTop += rect.top + rect.height / 2 - middle; + } + + var move = this.move = function(upwards){ + if(!this.current){ + this.highlightFirst(); + return true; + } + var next = upwards ? this.current.previousElementSibling : this.current.nextElementSibling; + if(next && next.classList) { + this.highlight(next); + scrollCenter(next); + return true; + } + return false; + }; + + this.moveRight = function(){ + }; + this.moveLeft = function(){ + }; + + this.highlight = function(elem) { + if(!elem){ + return; + } + this.removeHighlight(); + + this.current = elem; + this.current.classList.add("current"); + }; + + this.highlightFirst = function(){ + this.highlight(this.list.querySelector('li:first-child')); + }; + + this.removeHighlight = function() { + if(this.current){ + this.current.classList.remove("current"); + } + this.current = null; + } + + this.openSelectedResult = function() { + if(this.current) { + this.current.click(); + } + } + + this.focus = function() { + searchInput.focus(); + searchInput.select(); + this.highlightFirst(); + } + + function handleKeyUp(event) { + switch(event.key) { + case "ArrowUp": + case "ArrowDown": + case "i": + case "j": + case "k": + case "l": + case "c": + case "h": + case "t": + case "n": + event.stopPropagation(); + clearMoveTimeout(); + } + } + + function handleKeyDown(event) { + switch(event.key) { + case "Enter": + event.stopPropagation(); + event.preventDefault(); + leaveSearchScope(); + self.openSelectedResult(); + break; + case "Escape": + event.stopPropagation(); + event.preventDefault(); + leaveSearchScope(); + break; + case "j": + case "c": + case "ArrowUp": + if(event.ctrlKey || event.key == "ArrowUp") { + event.stopPropagation(); + self.move(true); + startMoveTimeout(true); + } + break; + case "k": + case "h": + case "ArrowDown": + if(event.ctrlKey || event.key == "ArrowDown") { + event.stopPropagation(); + self.move(false); + startMoveTimeout(false); + } + break; + case "k": + case "t": + case "ArrowLeft": + if(event.ctrlKey || event.key == "ArrowLeft") { + event.stopPropagation(); + self.moveLeft(); + } + break; + case "l": + case "n": + case "ArrowRight": + if(event.ctrlKey || event.key == "ArrowRight") { + event.stopPropagation(); + self.moveRight(); + } + break; + } + } + + function handleInputKeyUp(event) { + switch(event.key) { + case "ArrowUp": + case "ArrowDown": + event.stopPropagation(); + event.preventDefault(); + clearMoveTimeout(); + } + } + + function handleInputKeyDown(event) { + switch(event.key) { + case "Enter": + event.stopPropagation(); + event.preventDefault(); + delayWhileSearching(function(){ + self.openSelectedResult(); + leaveSearchScope(); + }); + break; + case "Escape": + event.stopPropagation(); + event.preventDefault(); + // remove focus from search input + leaveSearchScope(); + sidebar.focus(); + break; + case "ArrowUp": + event.stopPropagation(); + event.preventDefault(); + self.move(true); + startMoveTimeout(true); + break; + + case "ArrowDown": + event.stopPropagation(); + event.preventDefault(); + self.move(false); + startMoveTimeout(false); + break; + } + } + + sidebar.tabIndex = 100; // set tabIndex to enable keylistener + sidebar.addEventListener('keyup', function(event) { + handleKeyUp(event); + }); + sidebar.addEventListener('keydown', function(event) { + handleKeyDown(event); + }); + searchInput.addEventListener('keydown', function(event) { + handleInputKeyDown(event); + }); + searchInput.addEventListener('keyup', function(event) { + handleInputKeyUp(event); + }); + this.move(); +}; + +CrystalDocs.initializeVersions = function () { + function loadJSON(file, callback) { + var xobj = new XMLHttpRequest(); + xobj.overrideMimeType("application/json"); + xobj.open("GET", file, true); + xobj.onreadystatechange = function() { + if (xobj.readyState == 4 && xobj.status == "200") { + callback(xobj.responseText); + } + }; + xobj.send(null); + } + + function parseJSON(json) { + CrystalDocs.loadConfig(JSON.parse(json)); + } + + $elem = document.querySelector("html > head > meta[name=\"crystal_docs.json_config_url\"]") + if ($elem == undefined) { + return + } + jsonURL = $elem.getAttribute("content") + if (jsonURL && jsonURL != "") { + loadJSON(jsonURL, parseJSON); + } +} + +CrystalDocs.loadConfig = function (config) { + var projectVersions = config["versions"] + var currentVersion = document.querySelector("html > head > meta[name=\"crystal_docs.project_version\"]").getAttribute("content") + + var currentVersionInList = projectVersions.find(function (element) { + return element.name == currentVersion + }) + + if (!currentVersionInList) { + projectVersions.unshift({ name: currentVersion, url: '#' }) + } + + $version = document.querySelector(".project-summary > .project-version") + $version.innerHTML = "" + + $select = document.createElement("select") + $select.classList.add("project-versions-nav") + $select.addEventListener("change", function () { + window.location.href = this.value + }) + projectVersions.forEach(function (version) { + $item = document.createElement("option") + $item.setAttribute("value", version.url) + $item.append(document.createTextNode(version.name)) + + if (version.name == currentVersion) { + $item.setAttribute("selected", true) + $item.setAttribute("disabled", true) + } + $select.append($item) + }); + $form = document.createElement("form") + $form.setAttribute("autocomplete", "off") + $form.append($select) + $version.append($form) +} + +document.addEventListener("DOMContentLoaded", function () { + CrystalDocs.initializeVersions() +}) + +var UsageModal = function(title, content) { + var $body = document.body; + var self = this; + var $modalBackground = document.createElement("div"); + $modalBackground.classList.add("modal-background"); + var $usageModal = document.createElement("div"); + $usageModal.classList.add("usage-modal"); + $modalBackground.appendChild($usageModal); + var $title = document.createElement("h3"); + $title.classList.add("modal-title"); + $title.innerHTML = title + $usageModal.appendChild($title); + var $closeButton = document.createElement("span"); + $closeButton.classList.add("close-button"); + $closeButton.setAttribute("title", "Close modal"); + $closeButton.innerText = '×'; + $usageModal.appendChild($closeButton); + $usageModal.insertAdjacentHTML("beforeend", content); + + $modalBackground.addEventListener('click', function(event) { + var element = event.target || event.srcElement; + + if(element == $modalBackground) { + self.hide(); + } + }); + $closeButton.addEventListener('click', function(event) { + self.hide(); + }); + + $body.insertAdjacentElement('beforeend', $modalBackground); + + this.show = function(){ + $body.classList.add("js-modal-visible"); + }; + this.hide = function(){ + $body.classList.remove("js-modal-visible"); + }; + this.isVisible = function(){ + return $body.classList.contains("js-modal-visible"); + } +} + + +document.addEventListener('DOMContentLoaded', function() { + var sessionStorage; + try { + sessionStorage = window.sessionStorage; + } catch (e) { } + if(!sessionStorage) { + sessionStorage = { + setItem: function() {}, + getItem: function() {}, + removeItem: function() {} + }; + } + + var repositoryName = document.querySelector('[name=repository-name]').getAttribute('content'); + var typesList = document.querySelector('.types-list'); + var searchInput = document.querySelector('.search-input'); + var parents = document.querySelectorAll('.types-list li.parent'); + + var scrollSidebarToOpenType = function(){ + var openTypes = typesList.querySelectorAll('.current'); + if (openTypes.length > 0) { + var lastOpenType = openTypes[openTypes.length - 1]; + lastOpenType.scrollIntoView(!(window.matchMedia('only screen and (max-width: 635px)')).matches); + } + } + + scrollSidebarToOpenType(); + + var setPersistentSearchQuery = function(value){ + sessionStorage.setItem(repositoryName + '::search-input:value', value); + } + + for(var i = 0; i < parents.length; i++) { + var _parent = parents[i]; + _parent.addEventListener('click', function(e) { + e.stopPropagation(); + + if(e.target.tagName.toLowerCase() == 'li') { + if(e.target.className.match(/open/)) { + sessionStorage.removeItem(e.target.getAttribute('data-id')); + e.target.className = e.target.className.replace(/ +open/g, ''); + } else { + sessionStorage.setItem(e.target.getAttribute('data-id'), '1'); + if(e.target.className.indexOf('open') == -1) { + e.target.className += ' open'; + } + } + } + }); + + if(sessionStorage.getItem(_parent.getAttribute('data-id')) == '1') { + _parent.className += ' open'; + } + } + + var leaveSearchScope = function(){ + CrystalDocs.toggleResultsList(false); + window.focus(); + } + + var navigator = new Navigator(document.querySelector('.types-list'), searchInput, document.querySelector(".search-results"), leaveSearchScope); + + CrystalDocs.loadIndex(); + var searchTimeout; + var lastSearchText = false; + var performSearch = function() { + document.dispatchEvent(new Event("CrystalDocs:searchDebounceStarted")); + + clearTimeout(searchTimeout); + searchTimeout = setTimeout(function() { + var text = searchInput.value; + + if(text == "") { + CrystalDocs.toggleResultsList(false); + }else if(text == lastSearchText){ + document.dispatchEvent(new Event("CrystalDocs:searchDebounceStopped")); + }else{ + CrystalDocs.search(text); + navigator.highlightFirst(); + searchInput.focus(); + } + lastSearchText = text; + setPersistentSearchQuery(text); + }, 200); + }; + + if(location.hash.length > 3 && location.hash.substring(0,3) == "#q="){ + // allows directly linking a search query which is then executed on the client + // this comes handy for establishing a custom browser search engine with https://crystal-lang.org/api/#q=%s as a search URL + // TODO: Add OpenSearch description + var searchQuery = location.hash.substring(3); + history.pushState({searchQuery: searchQuery}, "Search for " + searchQuery, location.href.replace(/#q=.*/, "")); + searchInput.value = decodeURIComponent(searchQuery); + document.addEventListener('CrystalDocs:loaded', performSearch); + } + + if (searchInput.value.length == 0) { + var searchText = sessionStorage.getItem(repositoryName + '::search-input:value'); + if(searchText){ + searchInput.value = searchText; + } + } + searchInput.addEventListener('keyup', performSearch); + searchInput.addEventListener('input', performSearch); + + var usageModal = new UsageModal('Keyboard Shortcuts', '' + + '
    ' + + '
  • ' + + ' ' + + ' s,' + + ' /' + + ' ' + + ' Search' + + '
  • ' + + '
  • ' + + ' Esc' + + ' Abort search / Close modal' + + '
  • ' + + '
  • ' + + ' ' + + ' ,' + + ' Enter' + + ' ' + + ' Open highlighted result' + + '
  • ' + + '
  • ' + + ' ' + + ' ,' + + ' Ctrl+j' + + ' ' + + ' Select previous result' + + '
  • ' + + '
  • ' + + ' ' + + ' ,' + + ' Ctrl+k' + + ' ' + + ' Select next result' + + '
  • ' + + '
  • ' + + ' ?' + + ' Show usage info' + + '
  • ' + + '
' + ); + + function handleShortkeys(event) { + var element = event.target || event.srcElement; + + if(element.tagName == "INPUT" || element.tagName == "TEXTAREA" || element.parentElement.tagName == "TEXTAREA"){ + return; + } + + switch(event.key) { + case "?": + usageModal.show(); + break; + + case "Escape": + usageModal.hide(); + break; + + case "s": + case "/": + if(usageModal.isVisible()) { + return; + } + event.stopPropagation(); + navigator.focus(); + performSearch(); + break; + } + } + + document.addEventListener('keyup', handleShortkeys); + + var scrollToEntryFromLocationHash = function() { + var hash = window.location.hash; + if (hash) { + var targetAnchor = decodeURI(hash.substr(1)); + var targetEl = document.getElementById(targetAnchor) + if (targetEl) { + targetEl.offsetParent.scrollTop = targetEl.offsetTop; + } + } + }; + window.addEventListener("hashchange", scrollToEntryFromLocationHash, false); + scrollToEntryFromLocationHash(); +}); diff --git a/docs/search-index.js b/docs/search-index.js new file mode 100644 index 0000000..100b096 --- /dev/null +++ b/docs/search-index.js @@ -0,0 +1 @@ +crystal_doc_search_index_callback({"repository_name":"CliGenerator","body":"# CliGenerator\n \nThis is a crystal project to manage setting up OptionParser objects based around \"Command\" objects and arguments you define inside them.\n\n## Installation\n\n1. Add the dependency to your `shard.yml`:\n\n ```yaml\n dependencies:\n cligen:\n git: https://git.arcanium.tech/tristan/cligen\n ```\n\n2. Run `shards install`\n\n\n## Usage\n```crystal\nrequire \"cligen\"\n```\n\n## Contributors\n\n- [Tristan Ancelet](https://git.arcanium.tech/tristan) - creator and maintainer\n","program":{"html_id":"CliGenerator/toplevel","path":"toplevel.html","kind":"module","full_name":"Top Level Namespace","name":"Top Level Namespace","abstract":false,"locations":[],"repository_name":"CliGenerator","program":true,"enum":false,"alias":false,"const":false,"types":[{"html_id":"CliGenerator/CliGen","path":"CliGen.html","kind":"module","full_name":"CliGen","name":"CliGen","abstract":false,"locations":[{"filename":"src/cligen.cr","line_number":10,"url":null},{"filename":"src/cligen/annotations.cr","line_number":1,"url":null},{"filename":"src/cligen/app.cr","line_number":5,"url":null},{"filename":"src/cligen/arg.cr","line_number":1,"url":null},{"filename":"src/cligen/command.cr","line_number":10,"url":null},{"filename":"src/cligen/command/argument.cr","line_number":1,"url":null},{"filename":"src/cligen/command/selection.cr","line_number":1,"url":null},{"filename":"src/cligen/command/subcommand.cr","line_number":1,"url":null},{"filename":"src/cligen/command/trigger.cr","line_number":1,"url":null},{"filename":"src/cligen/command_node.cr","line_number":4,"url":null},{"filename":"src/cligen/flag.cr","line_number":3,"url":null},{"filename":"src/cligen/generate.cr","line_number":2,"url":null},{"filename":"src/cligen/match_type.cr","line_number":1,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"constants":[{"id":"ADDITIONAL_DEFAULT_FLAGS","name":"ADDITIONAL_DEFAULT_FLAGS","value":"[] of AdditionalDefaultFlag"},{"id":"APPNAME","name":"APPNAME","value":"File.basename(PROGRAM_NAME)"},{"id":"VERSION","name":"VERSION","value":"\"0.1.0\""}],"class_methods":[{"html_id":"add_default_flag(short:String=\"\",long:String=\"\",description:String=\"\",&work:String->)-class-method","name":"add_default_flag","abstract":false,"args":[{"name":"short","default_value":"\"\"","external_name":"short","restriction":"String"},{"name":"long","default_value":"\"\"","external_name":"long","restriction":"String"},{"name":"description","default_value":"\"\"","external_name":"description","restriction":"String"}],"args_string":"(short : String = \"\", long : String = \"\", description : String = \"\", &work : String -> )","args_html":"(short : String = "", long : String = "", description : String = "", &work : String -> )","location":{"filename":"src/cligen.cr","line_number":23,"url":null},"def":{"name":"add_default_flag","args":[{"name":"short","default_value":"\"\"","external_name":"short","restriction":"String"},{"name":"long","default_value":"\"\"","external_name":"long","restriction":"String"},{"name":"description","default_value":"\"\"","external_name":"description","restriction":"String"}],"yields":1,"block_arity":1,"block_arg":{"name":"work","external_name":"work","restriction":"(String ->)"},"visibility":"Public","body":"if description.empty?\n raise(\"ERROR : add_default_flag : You must provide a description\")\nend\nADDITIONAL_DEFAULT_FLAGS << AdditionalDefaultFlag.new(short: short, long: long, description: description, work: work)\n"},"external_var":false}],"types":[{"html_id":"CliGenerator/CliGen/AdditionalDefaultFlag","path":"CliGen/AdditionalDefaultFlag.html","kind":"struct","full_name":"CliGen::AdditionalDefaultFlag","name":"AdditionalDefaultFlag","abstract":false,"superclass":{"html_id":"CliGenerator/Struct","kind":"struct","full_name":"Struct","name":"Struct"},"ancestors":[{"html_id":"CliGenerator/Struct","kind":"struct","full_name":"Struct","name":"Struct"},{"html_id":"CliGenerator/Value","kind":"struct","full_name":"Value","name":"Value"},{"html_id":"CliGenerator/Object","kind":"class","full_name":"Object","name":"Object"}],"locations":[{"filename":"src/cligen.cr","line_number":15,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"},"constructors":[{"html_id":"new(short:String,long:String,description:String,work:String->)-class-method","name":"new","abstract":false,"args":[{"name":"short","external_name":"short","restriction":"String"},{"name":"long","external_name":"long","restriction":"String"},{"name":"description","external_name":"description","restriction":"String"},{"name":"work","external_name":"work","restriction":"(String ->)"}],"args_string":"(short : String, long : String, description : String, work : String -> )","args_html":"(short : String, long : String, description : String, work : String -> )","location":{"filename":"src/cligen.cr","line_number":15,"url":null},"def":{"name":"new","args":[{"name":"short","external_name":"short","restriction":"String"},{"name":"long","external_name":"long","restriction":"String"},{"name":"description","external_name":"description","restriction":"String"},{"name":"work","external_name":"work","restriction":"(String ->)"}],"visibility":"Public","body":"_ = allocate\n_.initialize(short, long, description, work)\nif _.responds_to?(:finalize)\n ::GC.add_finalizer(_)\nend\n_\n"},"external_var":false}],"instance_methods":[{"html_id":"clone-instance-method","name":"clone","abstract":false,"location":{"filename":"src/cligen.cr","line_number":15,"url":null},"def":{"name":"clone","visibility":"Public","body":"self.class.new(@short.clone, @long.clone, @description.clone, @work.clone)"},"external_var":false},{"html_id":"copy_with(short_short=@short,long_long=@long,description_description=@description,work_work=@work)-instance-method","name":"copy_with","abstract":false,"args":[{"name":"_short","default_value":"@short","external_name":"short","restriction":""},{"name":"_long","default_value":"@long","external_name":"long","restriction":""},{"name":"_description","default_value":"@description","external_name":"description","restriction":""},{"name":"_work","default_value":"@work","external_name":"work","restriction":""}],"args_string":"(short _short = @short, long _long = @long, description _description = @description, work _work = @work)","args_html":"(short _short = @short, long _long = @long, description _description = @description, work _work = @work)","location":{"filename":"src/cligen.cr","line_number":15,"url":null},"def":{"name":"copy_with","args":[{"name":"_short","default_value":"@short","external_name":"short","restriction":""},{"name":"_long","default_value":"@long","external_name":"long","restriction":""},{"name":"_description","default_value":"@description","external_name":"description","restriction":""},{"name":"_work","default_value":"@work","external_name":"work","restriction":""}],"visibility":"Public","body":"self.class.new(_short, _long, _description, _work)"},"external_var":false},{"html_id":"description:String-instance-method","name":"description","abstract":false,"def":{"name":"description","return_type":"String","visibility":"Public","body":"@description"},"external_var":false},{"html_id":"long:String-instance-method","name":"long","abstract":false,"def":{"name":"long","return_type":"String","visibility":"Public","body":"@long"},"external_var":false},{"html_id":"short:String-instance-method","name":"short","abstract":false,"def":{"name":"short","return_type":"String","visibility":"Public","body":"@short"},"external_var":false},{"html_id":"work:String->-instance-method","name":"work","abstract":false,"def":{"name":"work","return_type":"(String ->)","visibility":"Public","body":"@work"},"external_var":false}]},{"html_id":"CliGenerator/CliGen/App","path":"CliGen/App.html","kind":"class","full_name":"CliGen::App","name":"App","abstract":false,"superclass":{"html_id":"CliGenerator/CliGen/CommandNode","kind":"class","full_name":"CliGen::CommandNode","name":"CommandNode"},"ancestors":[{"html_id":"CliGenerator/CliGen/CommandNode","kind":"class","full_name":"CliGen::CommandNode","name":"CommandNode"},{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},{"html_id":"CliGenerator/Object","kind":"class","full_name":"Object","name":"Object"}],"locations":[{"filename":"src/cligen/app.cr","line_number":8,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"},"doc":"This serves as the default App object, that holds a copy of all flags & \nhandles flag processing until it hands off to the user defined commands","summary":"

This serves as the default App object, that holds a copy of all flags & handles flag processing until it hands off to the user defined commands

","class_methods":[{"html_id":"process(args:Array(String)=ARGV)-class-method","name":"process","doc":"Serves as a convinence method for the user to call to begin processing an\nargument array provided by the user.\n\nThis defaults to ARGV for convinence if no arguments are passed through","summary":"

Serves as a convinence method for the user to call to begin processing an argument array provided by the user.

","abstract":false,"args":[{"name":"args","default_value":"ARGV","external_name":"args","restriction":"Array(String)"}],"args_string":"(args : Array(String) = ARGV)","args_html":"(args : Array(String) = ARGV)","location":{"filename":"src/cligen/app.cr","line_number":28,"url":null},"def":{"name":"process","args":[{"name":"args","default_value":"ARGV","external_name":"args","restriction":"Array(String)"}],"visibility":"Public","body":"if @@instance.nil?\n raise(\"ERROR : CliGen::App.process was called before an instance of App was defined\")\nend\n@@instance.process(args)\n"},"external_var":false}],"constructors":[{"html_id":"new(name,flags,commands,pre_run_commands,post_run_commands)-class-method","name":"new","abstract":false,"args":[{"name":"name","external_name":"name","restriction":""},{"name":"flags","external_name":"flags","restriction":""},{"name":"commands","external_name":"commands","restriction":""},{"name":"pre_run_commands","external_name":"pre_run_commands","restriction":""},{"name":"post_run_commands","external_name":"post_run_commands","restriction":""}],"args_string":"(name, flags, commands, pre_run_commands, post_run_commands)","args_html":"(name, flags, commands, pre_run_commands, post_run_commands)","location":{"filename":"src/cligen/app.cr","line_number":12,"url":null},"def":{"name":"new","args":[{"name":"name","external_name":"name","restriction":""},{"name":"flags","external_name":"flags","restriction":""},{"name":"commands","external_name":"commands","restriction":""},{"name":"pre_run_commands","external_name":"pre_run_commands","restriction":""},{"name":"post_run_commands","external_name":"post_run_commands","restriction":""}],"visibility":"Public","body":"_ = allocate\n_.initialize(name, flags, commands, pre_run_commands, post_run_commands)\nif _.responds_to?(:finalize)\n ::GC.add_finalizer(_)\nend\n_\n"},"external_var":false}],"instance_methods":[{"html_id":"check!-instance-method","name":"check!","abstract":false,"location":{"filename":"src/cligen/app.cr","line_number":16,"url":null},"def":{"name":"check!","visibility":"Public","body":"CliGen::GLOBAL_FLAGS.each(&.check!)\n\n\ncheck_for_duplicates!([CliGen::GLOBAL_FLAGS, @flags].flatten)\n@commands.each(&.check!)\n"},"external_var":false}]},{"html_id":"CliGenerator/CliGen/Arg","path":"CliGen/Arg.html","kind":"class","full_name":"CliGen::Arg","name":"Arg","abstract":false,"superclass":{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},"ancestors":[{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},{"html_id":"CliGenerator/Object","kind":"class","full_name":"Object","name":"Object"}],"locations":[{"filename":"src/cligen/arg.cr","line_number":15,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"},"doc":"This class serves as a \"argument wrapper\" to force a fail-fast approach to\narg-parsing. \n\nIt wraps around the argument + index of the argument to do state tracking\nand ensure that each argument is only processed once (plus allows for\neasier filtering of processed arguments to avoid having to do index math)\n\n args.reject(&.processed?) # returns the args that haven't been processed yet\n\nIt expects each argument to only be processed once and will force a raise\nif the argument has Arg#processed called a second time. This is to force \nthe developer (me) to fix any processing issues during the development of\nthis framework.","summary":"

This class serves as a "argument wrapper" to force a fail-fast approach to arg-parsing.

","constructors":[{"html_id":"new(value:String,index:Int32)-class-method","name":"new","abstract":false,"args":[{"name":"value","external_name":"value","restriction":"::String"},{"name":"index","external_name":"index","restriction":"::Int32"}],"args_string":"(value : String, index : Int32)","args_html":"(value : String, index : Int32)","location":{"filename":"src/cligen/arg.cr","line_number":24,"url":null},"def":{"name":"new","args":[{"name":"value","external_name":"value","restriction":"::String"},{"name":"index","external_name":"index","restriction":"::Int32"}],"visibility":"Public","body":"_ = allocate\n_.initialize(value, index)\nif _.responds_to?(:finalize)\n ::GC.add_finalizer(_)\nend\n_\n"},"external_var":false}],"instance_methods":[{"html_id":"index:Int32-instance-method","name":"index","doc":"The index of the argument in the array it was in","summary":"

The index of the argument in the array it was in

","abstract":false,"location":{"filename":"src/cligen/arg.cr","line_number":20,"url":null},"def":{"name":"index","return_type":"Int32","visibility":"Public","body":"@index"},"external_var":false},{"html_id":"processed-instance-method","name":"processed","doc":"This serves as a trigger that tells the object that it has been processed\n\nThis will raise an exception if it is re-called after already having been\nprocessed.","summary":"

This serves as a trigger that tells the object that it has been processed

","abstract":false,"location":{"filename":"src/cligen/arg.cr","line_number":31,"url":null},"def":{"name":"processed","visibility":"Public","body":"if @processed\n raise(\"ERROR : CliGen::Arg(index: #{@index}, value: #{@value})#processed : This arg was re-processed\")\nend\n@processed = true\n"},"external_var":false},{"html_id":"processed?:Bool-instance-method","name":"processed?","doc":"The \"flag\"/variable that tracks is the Arg has been processed yet","summary":"

The "flag"/variable that tracks is the Arg has been processed yet

","abstract":false,"location":{"filename":"src/cligen/arg.cr","line_number":22,"url":null},"def":{"name":"processed?","return_type":"Bool","visibility":"Public","body":"@processed"},"external_var":false},{"html_id":"value:String-instance-method","name":"value","doc":"The raw string argument provided from the user","summary":"

The raw string argument provided from the user

","abstract":false,"location":{"filename":"src/cligen/arg.cr","line_number":18,"url":null},"def":{"name":"value","return_type":"String","visibility":"Public","body":"@value"},"external_var":false}]},{"html_id":"CliGenerator/CliGen/Argument","path":"CliGen/Argument.html","kind":"annotation","full_name":"CliGen::Argument","name":"Argument","abstract":false,"locations":[{"filename":"src/cligen/annotations.cr","line_number":8,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"}},{"html_id":"CliGenerator/CliGen/BaseFlag","path":"CliGen/BaseFlag.html","kind":"class","full_name":"CliGen::BaseFlag","name":"BaseFlag","abstract":true,"superclass":{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},"ancestors":[{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},{"html_id":"CliGenerator/Object","kind":"class","full_name":"Object","name":"Object"}],"locations":[{"filename":"src/cligen/flag.cr","line_number":4,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"subclasses":[{"html_id":"CliGenerator/CliGen/Flag","kind":"class","full_name":"CliGen::Flag(T)","name":"Flag"}],"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"},"constructors":[{"html_id":"new(var:String,short:String|Nil,long:String|Nil,env_var:String|Nil,description:String)-class-method","name":"new","abstract":false,"args":[{"name":"var","external_name":"var","restriction":"String"},{"name":"short","external_name":"short","restriction":"String | ::Nil"},{"name":"long","external_name":"long","restriction":"String | ::Nil"},{"name":"env_var","external_name":"env_var","restriction":"String | ::Nil"},{"name":"description","external_name":"description","restriction":"String"}],"args_string":"(var : String, short : String | Nil, long : String | Nil, env_var : String | Nil, description : String)","args_html":"(var : String, short : String | Nil, long : String | Nil, env_var : String | Nil, description : String)","location":{"filename":"src/cligen/flag.cr","line_number":12,"url":null},"def":{"name":"new","args":[{"name":"var","external_name":"var","restriction":"String"},{"name":"short","external_name":"short","restriction":"String | ::Nil"},{"name":"long","external_name":"long","restriction":"String | ::Nil"},{"name":"env_var","external_name":"env_var","restriction":"String | ::Nil"},{"name":"description","external_name":"description","restriction":"String"}],"visibility":"Public","body":"_ = allocate\n_.initialize(var, short, long, env_var, description)\nif _.responds_to?(:finalize)\n ::GC.add_finalizer(_)\nend\n_\n"},"external_var":false}],"instance_methods":[{"html_id":"description:String-instance-method","name":"description","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":10,"url":null},"def":{"name":"description","return_type":"String","visibility":"Public","body":"@description"},"external_var":false},{"html_id":"env_var:String|Nil-instance-method","name":"env_var","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":9,"url":null},"def":{"name":"env_var","return_type":"String | ::Nil","visibility":"Public","body":"@env_var"},"external_var":false},{"html_id":"long:String|Nil-instance-method","name":"long","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":7,"url":null},"def":{"name":"long","return_type":"String | ::Nil","visibility":"Public","body":"@long"},"external_var":false},{"html_id":"long_key:String-instance-method","name":"long_key","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":8,"url":null},"def":{"name":"long_key","return_type":"String","visibility":"Public","body":"@long_key"},"external_var":false},{"html_id":"matches?(token:String):Bool-instance-method","name":"matches?","abstract":false,"args":[{"name":"token","external_name":"token","restriction":"String"}],"args_string":"(token : String) : Bool","args_html":"(token : String) : Bool","location":{"filename":"src/cligen/flag.cr","line_number":22,"url":null},"def":{"name":"matches?","args":[{"name":"token","external_name":"token","restriction":"String"}],"return_type":"Bool","visibility":"Public","body":"(token == @short) || (!@long_key.empty? && (token == @long_key))"},"external_var":false},{"html_id":"raw_value:String|Nil-instance-method","name":"raw_value","abstract":true,"location":{"filename":"src/cligen/flag.cr","line_number":28,"url":null},"def":{"name":"raw_value","return_type":"String | ::Nil","visibility":"Public","body":""},"external_var":false},{"html_id":"satisfied?:Bool-instance-method","name":"satisfied?","abstract":true,"location":{"filename":"src/cligen/flag.cr","line_number":26,"url":null},"def":{"name":"satisfied?","return_type":"Bool","visibility":"Public","body":""},"external_var":false},{"html_id":"short:String|Nil-instance-method","name":"short","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":6,"url":null},"def":{"name":"short","return_type":"String | ::Nil","visibility":"Public","body":"@short"},"external_var":false},{"html_id":"validate!:Nil-instance-method","name":"validate!","abstract":true,"location":{"filename":"src/cligen/flag.cr","line_number":27,"url":null},"def":{"name":"validate!","return_type":"Nil","visibility":"Public","body":""},"external_var":false},{"html_id":"var:String-instance-method","name":"var","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":5,"url":null},"def":{"name":"var","return_type":"String","visibility":"Public","body":"@var"},"external_var":false}]},{"html_id":"CliGenerator/CliGen/Command","path":"CliGen/Command.html","kind":"class","full_name":"CliGen::Command","name":"Command","abstract":false,"superclass":{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},"ancestors":[{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},{"html_id":"CliGenerator/Object","kind":"class","full_name":"Object","name":"Object"}],"locations":[{"filename":"src/cligen/command.cr","line_number":11,"url":null},{"filename":"src/cligen/command/argument.cr","line_number":2,"url":null},{"filename":"src/cligen/command/selection.cr","line_number":2,"url":null},{"filename":"src/cligen/command/subcommand.cr","line_number":2,"url":null},{"filename":"src/cligen/command/trigger.cr","line_number":2,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"},"macros":[{"html_id":"argument(variable,short,long,description,validation=nil)-macro","name":"argument","abstract":false,"args":[{"name":"variable","external_name":"variable","restriction":""},{"name":"short","external_name":"short","restriction":""},{"name":"long","external_name":"long","restriction":""},{"name":"description","external_name":"description","restriction":""},{"name":"validation","default_value":"nil","external_name":"validation","restriction":""}],"args_string":"(variable, short, long, description, validation = nil)","args_html":"(variable, short, long, description, validation = nil)","location":{"filename":"src/cligen/command/argument.cr","line_number":3,"url":null},"def":{"name":"argument","args":[{"name":"variable","external_name":"variable","restriction":""},{"name":"short","external_name":"short","restriction":""},{"name":"long","external_name":"long","restriction":""},{"name":"description","external_name":"description","restriction":""},{"name":"validation","default_value":"nil","external_name":"validation","restriction":""}],"visibility":"Public","body":" \n{% unless variable.is_a?(TypeDeclaration)\n raise(\"ERROR : CliGen::Command.argument : First argument (#{variable}) must be a TypeDeclaration (ex: ' : [= val]')\")\nend %}\n\n \n{% name = variable.name %}\n\n \n{% type = variable.type %}\n\n \n{% unless short.is_a?(StringLiteral) || (string == nil)\n raise(\"ERROR : CliGen::Command.argument(#{name}) : Provided short must be a string\")\nend %}\n\n \n{% unless long.is_a?(StringLiteral) || (long == nil)\n raise(\"ERROR : CliGen::Command.argument(#{name}) : Provided long must be a string\")\nend %}\n\n \n{% unless long || short\n raise(\"ERROR : CliGen::Command.argument(#{name}) : You must provide a short or long\")\nend %}\n\n \n{% unless description\n raise(\"ERROR : CliGen::Command.argument(#{name}) : You must provide a description\")\nend %}\n\n \n{% unless description.is_a?(StringLiteral)\n raise(\"ERROR : CliGen::Command.argument(#{name}) : Provided description must be a String\")\nend %}\n\n \n{% unless validation.nil? %}\n {% unless validation.is_a?(ProcLiteral)\n raise(\"ERROR : CliGen::Command.argument(#{name}) : Provided validation must be a Proc\")\nend %}\n {% unless validation.return_type == Bool\n raise(\"ERROR : CliGen::Command.argument(#{name}) : Provided validation return type must be a Bool\")\nend %}\n {% if validation.args.empty?\n raise(\"ERROR : CliGen::Command.argument(#{name}) : Provided validation provided validation must have an input variable\")\nend %}\n {% arg = validation.args.first %}\n {% unless arg.restriction == type %}\n {% example = \"->(#{arg.name} : #{type}) : #{type} { #{validation.body} }\" %}\n {% raise(\"ERROR : CliGen::Command.argument(#{name}) : Provided validation input value must be #{type}. EX: #{example}\") %}\n {% end %}\n {% end %}\n\n\n @[CliGen::Argument(short: \n{{ short }}\n, long: \n{{ long }}\n, description: \n{{ description }}\n, validation: \n{{ validation }}\n, on_match: \n{{ on_match }}\n)]\n @\n{{ variable }}\n\n\n def \n{{ variable.name }}\n= (value : \n{{ type }}\n)\n \n{% unless validation.nil? %}\n raise \"ERROR : #{@type.name}##{@def.name} : Provided value #{value} is not passing validation\" unless {{ validation }}.call(value)\n {% end %}\n\n @\n{{ name }}\n = value\n \nend\n \n"}},{"html_id":"selection(variable,short,long,description,options)-macro","name":"selection","abstract":false,"args":[{"name":"variable","external_name":"variable","restriction":""},{"name":"short","external_name":"short","restriction":""},{"name":"long","external_name":"long","restriction":""},{"name":"description","external_name":"description","restriction":""},{"name":"options","external_name":"options","restriction":""}],"args_string":"(variable, short, long, description, options)","args_html":"(variable, short, long, description, options)","location":{"filename":"src/cligen/command/selection.cr","line_number":3,"url":null},"def":{"name":"selection","args":[{"name":"variable","external_name":"variable","restriction":""},{"name":"short","external_name":"short","restriction":""},{"name":"long","external_name":"long","restriction":""},{"name":"description","external_name":"description","restriction":""},{"name":"options","external_name":"options","restriction":""}],"visibility":"Public","body":" \n{% unless variable.is_a?(TypeDeclaration)\n raise(\"ERROR : CliGen::Command.selection : First selection must be a TypeDeclaration (ex: ' : [= val]')\")\nend %}\n\n \n{% unless short.is_a?(StringLiteral) || (string == nil)\n raise(\"ERROR : CliGen::Command.selection : Provided short must be a string\")\nend %}\n\n \n{% unless long.is_a?(StringLiteral) || (long == nil)\n raise(\"ERROR : CliGen::Command.selection : Provided long must be a string\")\nend %}\n\n \n{% unless long || short\n raise(\"ERROR : CliGen::Command.selection : You must provide a short or long\")\nend %}\n\n \n{% unless description\n raise(\"ERROR : CliGen::Command.selection : You must provide a description\")\nend %}\n\n \n{% unless description.is_a?(StringLiteral)\n raise(\"ERROR : CliGen::Command.selection : Provided description must be a String\")\nend %}\n\n \n{% unless options\n raise(\"ERROR : CliGen::Command.selection : You must provide options\")\nend %}\n\n \n{% unless options\n raise(\"ERROR : CliGen::Command.selection : Provided options must be \")\nend %}\n\n \n"}},{"html_id":"subcommand(func,description,examples=nil,&block)-macro","name":"subcommand","abstract":false,"args":[{"name":"func","external_name":"func","restriction":""},{"name":"description","external_name":"description","restriction":""},{"name":"examples","default_value":"nil","external_name":"examples","restriction":""}],"args_string":"(func, description, examples = nil, &block)","args_html":"(func, description, examples = nil, &block)","location":{"filename":"src/cligen/command/subcommand.cr","line_number":3,"url":null},"def":{"name":"subcommand","args":[{"name":"func","external_name":"func","restriction":""},{"name":"description","external_name":"description","restriction":""},{"name":"examples","default_value":"nil","external_name":"examples","restriction":""}],"block_arg":{"name":"block","external_name":"block","restriction":""},"visibility":"Public","body":" \n{% unless variable.is_a?(TypeDeclaration)\n raise(\"ERROR : CliGen::Command.subcommand : First argument must be a TypeDeclaration (ex: ' : ')\")\nend %}\n\n \n{% unless description\n raise(\"ERROR : CliGen::Command.subcommand : You must provide a description\")\nend %}\n\n \n{% unless description.is_a?(StringLiteral)\n raise(\"ERROR : CliGen::Command.subcommand : Provided description must be a String\")\nend %}\n\n \n{% unless examples.nil? %}\n {% if examples.is_a?(Path)\n examples = examples.resolve\nend %}\n {% unless examples.is_a?(ArrayLiteral)\n raise(\"ERROR : CliGen::Command.subcommand : Provided example must be an Array\")\nend %}\n {% end %}\n\n \n{% unless block\n raise(\"ERROR : CliGen::Command.subcommand : You MUST provide a function body\")\nend %}\n\n\n @[CliGen::SubCommand(description: \n{{ description }}\n, \nexamples: \n{{ examples }}\n)]\n def \n{{ func }}\n\n \n{{ block.body }}\n\n \nend\n \n"}},{"html_id":"trigger(short,long,argument=nil,&on_match)-macro","name":"trigger","abstract":false,"args":[{"name":"short","external_name":"short","restriction":""},{"name":"long","external_name":"long","restriction":""},{"name":"argument","default_value":"nil","external_name":"argument","restriction":""}],"args_string":"(short, long, argument = nil, &on_match)","args_html":"(short, long, argument = nil, &on_match)","location":{"filename":"src/cligen/command/trigger.cr","line_number":3,"url":null},"def":{"name":"trigger","args":[{"name":"short","external_name":"short","restriction":""},{"name":"long","external_name":"long","restriction":""},{"name":"argument","default_value":"nil","external_name":"argument","restriction":""}],"block_arg":{"name":"on_match","external_name":"on_match","restriction":""},"visibility":"Public","body":" \n{% unless short.is_a?(StringLiteral)\n raise(\"ERROR : CliGen::Command.trigger : Provided short must be a string\")\nend %}\n\n \n{% unless long.is_a?(StringLiteral)\n raise(\"ERROR : CliGen::Command.trigger : Provided long must be a string\")\nend %}\n\n \n{% unless on_match\n raise(\"ERROR : CliGen::Command.trigger : Must provide a block for on_match trigger\")\nend %}\n\n \n{% name = long.gsub(/--/, \"\") %}\n\n\n @[CliGen::Trigger(short: \n{{ short }}\n, long: \n{{ long }}\n, argument: \n{{ argument }}\n)]\n \n{% if argument %}\n def self.__cligen_trigger__{{ name }}__({{ name }} : {{ argument }}) : Nil\n {{ on_match.body }}\n end\n {% else %}\n def self.__cligen_trigger__{{ name }}__ : Nil\n {{ on_match.body }}\n end\n {% end %}\n\n \n"}}]},{"html_id":"CliGenerator/CliGen/CommandInfo","path":"CliGen/CommandInfo.html","kind":"annotation","full_name":"CliGen::CommandInfo","name":"CommandInfo","abstract":false,"locations":[{"filename":"src/cligen/annotations.cr","line_number":5,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"}},{"html_id":"CliGenerator/CliGen/CommandNode","path":"CliGen/CommandNode.html","kind":"class","full_name":"CliGen::CommandNode","name":"CommandNode","abstract":false,"superclass":{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},"ancestors":[{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},{"html_id":"CliGenerator/Object","kind":"class","full_name":"Object","name":"Object"}],"locations":[{"filename":"src/cligen/command_node.cr","line_number":5,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"subclasses":[{"html_id":"CliGenerator/CliGen/App","kind":"class","full_name":"CliGen::App","name":"App"}],"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"},"constructors":[{"html_id":"new(name:String,flags:Array(CliGen::BaseFlag),commands:Array(CliGen::CommandNode),pre_run_commands:Array(_),post_run_commands:Array(_))-class-method","name":"new","abstract":false,"args":[{"name":"name","external_name":"name","restriction":"::String"},{"name":"flags","external_name":"flags","restriction":"::Array(::CliGen::BaseFlag)"},{"name":"commands","external_name":"commands","restriction":"::Array(::CliGen::CommandNode)"},{"name":"pre_run_commands","external_name":"pre_run_commands","restriction":"::Array(_)"},{"name":"post_run_commands","external_name":"post_run_commands","restriction":"::Array(_)"}],"args_string":"(name : String, flags : Array(CliGen::BaseFlag), commands : Array(CliGen::CommandNode), pre_run_commands : Array(_), post_run_commands : Array(_))","args_html":"(name : String, flags : Array(CliGen::BaseFlag), commands : Array(CliGen::CommandNode), pre_run_commands : Array(_), post_run_commands : Array(_))","location":{"filename":"src/cligen/command_node.cr","line_number":12,"url":null},"def":{"name":"new","args":[{"name":"name","external_name":"name","restriction":"::String"},{"name":"flags","external_name":"flags","restriction":"::Array(::CliGen::BaseFlag)"},{"name":"commands","external_name":"commands","restriction":"::Array(::CliGen::CommandNode)"},{"name":"pre_run_commands","external_name":"pre_run_commands","restriction":"::Array(_)"},{"name":"post_run_commands","external_name":"post_run_commands","restriction":"::Array(_)"}],"visibility":"Public","body":"_ = allocate\n_.initialize(name, flags, commands, pre_run_commands, post_run_commands)\nif _.responds_to?(:finalize)\n ::GC.add_finalizer(_)\nend\n_\n"},"external_var":false}],"instance_methods":[{"html_id":"check!-instance-method","name":"check!","abstract":false,"location":{"filename":"src/cligen/command_node.cr","line_number":49,"url":null},"def":{"name":"check!","visibility":"Public","body":"@flags.each(&.check!)\ncheck_for_duplicates!(@flags)\n@commands.each(&.check!)\n"},"external_var":false},{"html_id":"check_for_duplicates!(flags:Array(BaseFlag))-instance-method","name":"check_for_duplicates!","abstract":false,"args":[{"name":"flags","external_name":"flags","restriction":"Array(BaseFlag)"}],"args_string":"(flags : Array(BaseFlag))","args_html":"(flags : Array(BaseFlag))","location":{"filename":"src/cligen/command_node.cr","line_number":15,"url":null},"def":{"name":"check_for_duplicates!","args":[{"name":"flags","external_name":"flags","restriction":"Array(BaseFlag)"}],"visibility":"Public","body":"shorts = flags.compact_map(&.short)\nshort_duplicates = [] of String\nlongs = flags.compact_map do |f| if f.long_key.empty?\nelse\n f.long_key\nend end\nlong_duplicates = [] of String\n\nlast_short : String = \"\"\nshorts.sort.each do |short|\n if last_short == short\n short_duplicates << short\n end\n last_short = short\nend\n\nlast_long : String = \"\"\nlongs.sort.each do |long|\n if last_long == long\n long_duplicates << long\n end\n last_long = long\nend\n\nif long_duplicates.empty? && short_duplicates.empty?\nelse\n error_buffer = \"ERROR : CommandNode(%s)#check! : Found Duplicates : %s\"\n\n message = \"\"\n if long_duplicates.empty?\n else\n message = message + (\"\\nLong:\\n%s\\n\" % (long_duplicates.map do |f| \"- #{f}\" end.join(\"\\n\")))\n end\n\n if short_duplicates.empty?\n else\n message = message + (\"\\nShort:\\n%s\" % (short_duplicates.map do |f| \"- #{f}\" end.join(\"\\n\")))\n end\n\n raise(error_buffer % [@name, message])\nend\n"},"external_var":false},{"html_id":"find_match(arg:String)-instance-method","name":"find_match","abstract":false,"args":[{"name":"arg","external_name":"arg","restriction":"String"}],"args_string":"(arg : String)","args_html":"(arg : String)","location":{"filename":"src/cligen/command_node.cr","line_number":55,"url":null},"def":{"name":"find_match","args":[{"name":"arg","external_name":"arg","restriction":"String"}],"visibility":"Public","body":"case arg\nwhen CliGen::Regex::FLAG_REGEX\n if flg = @flags.find(&.matches?(arg))\n flg\n else\n CliGen::MatchType::NoMatch\n end\nwhen CliGen::Regex::FLAG_WITH_ARG\n CliGen::MatchType::FlagWithArg\nwhen CliGen::Regex::SHORT_WITH_INLINE_ARG\n CliGen::MatchType::ShortWithInlineArg\nwhen CliGen::Regex::FLAG_MULTIPLE_SHORT\n CliGen::MatchType::FlagMultipleShort\nelse\n if cmd = @commands.find do |c| c.name == arg end\n cmd\n else\n CliGen::MatchType::NoMatch\n end\nend"},"external_var":false},{"html_id":"process(args:Array(String))-instance-method","name":"process","doc":"This serves to just convert the arguments into a usable Array(Arg) format\nand pass it to the ACTUAL CommandNode#process method","summary":"

This serves to just convert the arguments into a usable Array(Arg) format and pass it to the ACTUAL CommandNode#process method

","abstract":false,"args":[{"name":"args","external_name":"args","restriction":"Array(String)"}],"args_string":"(args : Array(String))","args_html":"(args : Array(String))","location":{"filename":"src/cligen/command_node.cr","line_number":80,"url":null},"def":{"name":"process","args":[{"name":"args","external_name":"args","restriction":"Array(String)"}],"visibility":"Public","body":"new_args = [] of Arg\nargs.each_with_index do |arg, index|\n new_args << Arg.new(value: arg, index: index)\nend\n\n\nprocess(new_args)\n"},"external_var":false},{"html_id":"process(args:Array(Arg)):Nil-instance-method","name":"process","abstract":false,"args":[{"name":"args","external_name":"args","restriction":"Array(Arg)"}],"args_string":"(args : Array(Arg)) : Nil","args_html":"(args : Array(Arg)) : Nil","location":{"filename":"src/cligen/command_node.cr","line_number":90,"url":null},"def":{"name":"process","args":[{"name":"args","external_name":"args","restriction":"Array(Arg)"}],"return_type":"Nil","visibility":"Public","body":"check!\n\n@pre_run_commands.each(&.call)\n\nargs.each do |arg|\n if arg.processed?\n next\n end\n arg.processed\n\n case match = find_match(arg.value)\n when CommandNode\n match.process(args.reject(&.processed?))\n when BaseFlag\n if match.requires_arg?\n match.process(args.reject(&.processed?))\n else\n match.process\n end\n when MatchType::FlagWithArg\n if regex_match = CliGen::Regex::FLAG_WITH_ARG.match(arg.value)\n case flag_match = find_match(regex_match[\"flag\"])\n when BaseFlag\n flag_match.process([Arg.new(value: regex_match[\"arg\"], index: arg.index)])\n else\n raise(\"ERROR : CommandNode(#{@name}).run : There was no match for #{regex_match[\"flag\"]}\")\n end\n else\n raise(\"Oh good, you broke regex. How the hell did it match in find_match but not above? What the hell is going on\")\n end\n when MatchType::ShortWithInlineArg\n abort(\"#{CliGen::APPNAME}: invalid flag '#{arg.value}' — inline values are not supported. Did you mean '#{arg.value[0..1]} #{arg.value[2..]}' ?\")\n when MatchType::FlagMultipleShort\n (arg.value.gsub(/^-/, \"\")).chars.map do |c| \"-#{c}\" end.each do |flag|\n case match = find_match(flag)\n when BaseFlag\n if match.requires_arg?\n abort(\"#{CliGen::APPNAME}: cannot bundle flag that requires an argument: #{flag}\")\n end\n match.process\n when MatchType::NoMatch\n raise(\"ERROR : CommandNode(#{@name}).run : There was no match for #{flag}\")\n end\n end\n when MatchType::NoMatch\n raise(\"ERROR : CommandNode(#{@name}).run : There was no match for #{arg.value}\")\n end\nend\n\n@post_run_commands.each(&.call)\n"},"external_var":false}]},{"html_id":"CliGenerator/CliGen/DefaultFlag","path":"CliGen/DefaultFlag.html","kind":"annotation","full_name":"CliGen::DefaultFlag","name":"DefaultFlag","abstract":false,"locations":[{"filename":"src/cligen.cr","line_number":33,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"}},{"html_id":"CliGenerator/CliGen/Flag","path":"CliGen/Flag.html","kind":"class","full_name":"CliGen::Flag(T)","name":"Flag","abstract":false,"superclass":{"html_id":"CliGenerator/CliGen/BaseFlag","kind":"class","full_name":"CliGen::BaseFlag","name":"BaseFlag"},"ancestors":[{"html_id":"CliGenerator/CliGen/BaseFlag","kind":"class","full_name":"CliGen::BaseFlag","name":"BaseFlag"},{"html_id":"CliGenerator/Reference","kind":"class","full_name":"Reference","name":"Reference"},{"html_id":"CliGenerator/Object","kind":"class","full_name":"Object","name":"Object"}],"locations":[{"filename":"src/cligen/flag.cr","line_number":31,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"},"constructors":[{"html_id":"new(var:String,short:String|Nil,long:String|Nil,env_var:String|Nil,description:String,default:T|Nil=nil,options:Array(String)|Nil=nil,validate:T->Bool|Nil=nil,on_match:Proc(Nil)|Nil=nil)-class-method","name":"new","abstract":false,"args":[{"name":"var","external_name":"var","restriction":"String"},{"name":"short","external_name":"short","restriction":"String | ::Nil"},{"name":"long","external_name":"long","restriction":"String | ::Nil"},{"name":"env_var","external_name":"env_var","restriction":"String | ::Nil"},{"name":"description","external_name":"description","restriction":"String"},{"name":"default","default_value":"nil","external_name":"default","restriction":"T | ::Nil"},{"name":"options","default_value":"nil","external_name":"options","restriction":"Array(String) | ::Nil"},{"name":"validate","default_value":"nil","external_name":"validate","restriction":"(T -> Bool) | ::Nil"},{"name":"on_match","default_value":"nil","external_name":"on_match","restriction":"Proc(Nil) | ::Nil"}],"args_string":"(var : String, short : String | Nil, long : String | Nil, env_var : String | Nil, description : String, default : T | Nil = nil, options : Array(String) | Nil = nil, validate : T -> Bool | Nil = nil, on_match : Proc(Nil) | Nil = nil)","args_html":"(var : String, short : String | Nil, long : String | Nil, env_var : String | Nil, description : String, default : T | Nil = nil, options : Array(String) | Nil = nil, validate : T -> Bool | Nil = nil, on_match : Proc(Nil) | Nil = nil)","location":{"filename":"src/cligen/flag.cr","line_number":38,"url":null},"def":{"name":"new","args":[{"name":"var","external_name":"var","restriction":"String"},{"name":"short","external_name":"short","restriction":"String | ::Nil"},{"name":"long","external_name":"long","restriction":"String | ::Nil"},{"name":"env_var","external_name":"env_var","restriction":"String | ::Nil"},{"name":"description","external_name":"description","restriction":"String"},{"name":"default","default_value":"nil","external_name":"default","restriction":"T | ::Nil"},{"name":"options","default_value":"nil","external_name":"options","restriction":"Array(String) | ::Nil"},{"name":"validate","default_value":"nil","external_name":"validate","restriction":"(T -> Bool) | ::Nil"},{"name":"on_match","default_value":"nil","external_name":"on_match","restriction":"Proc(Nil) | ::Nil"}],"visibility":"Public","body":"_ = Flag(T).allocate\n_.initialize(var, short, long, env_var, description, default, options, validate, on_match)\nif _.responds_to?(:finalize)\n ::GC.add_finalizer(_)\nend\n_\n"},"external_var":false}],"instance_methods":[{"html_id":"process(argv:Array(Arg)=[]ofArray(Arg)):Nil-instance-method","name":"process","abstract":false,"args":[{"name":"argv","default_value":"[] of Array(Arg)","external_name":"argv","restriction":"Array(Arg)"}],"args_string":"(argv : Array(Arg) = [] of Array(Arg)) : Nil","args_html":"(argv : Array(Arg) = [] of Array(Arg)) : Nil","location":{"filename":"src/cligen/flag.cr","line_number":56,"url":null},"def":{"name":"process","args":[{"name":"argv","default_value":"[] of Array(Arg)","external_name":"argv","restriction":"Array(Arg)"}],"return_type":"Nil","visibility":"Public","body":"if requires_arg?\n if argv.empty?\n raise(\"ERROR : Flag({{T}}) : Array requires an argument but provided array is empty\")\n end\nend\n\n{% if T == Bool %}\n @value = true\n {% elsif T <= Array %}\n {% if T.type_vars.size > 1\n raise(\"ERROR : Flag(#{T}) : You cannot define multiple types of array entries\")\nend %}\n {% elem = T.type_vars.first %}\n argv.each do |arg|\n break if arg.value.starts_with('-')\n {% if elem == Int32 %}\n (@value ||= [] of Int32) << arg.value.to_i\n {% else %}\n (@value ||= [] of String) << arg.value\n {% end %}\n arg.processed\n end\n {% elsif T == Int32 %}\n @value = argv.first.value.to_i\n argv.first.processed\n {% elsif T == Time %}\n @value = parse_time(argv.first.value)\n argv.first.processed\n {% else %} # String\n @value = argv.first.value\n argv.first.processed\n {% end %}\n@on_match.try(&.call)\n"},"external_var":false},{"html_id":"raw_value:String|Nil-instance-method","name":"raw_value","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":104,"url":null},"def":{"name":"raw_value","return_type":"String | ::Nil","visibility":"Public","body":"{% if T == Bool %}\n @value.try(&.to_s)\n {% elsif T <= Array %}\n @value.try(&.join(\",\"))\n {% else %}\n @value.try(&.to_s)\n {% end %}"},"external_var":false},{"html_id":"requires_arg?:Bool-instance-method","name":"requires_arg?","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":52,"url":null},"def":{"name":"requires_arg?","return_type":"Bool","visibility":"Public","body":"({{ T }}) != Bool"},"external_var":false},{"html_id":"satisfied?:Bool-instance-method","name":"satisfied?","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":114,"url":null},"def":{"name":"satisfied?","return_type":"Bool","visibility":"Public","body":"if !@value.nil?\n return true\nend\nif @env_var && ENV[@env_var.not_nil!]?\n return true\nend\nif !@default.nil?\n return true\nend\nfalse\n"},"external_var":false},{"html_id":"validate!:Nil-instance-method","name":"validate!","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":121,"url":null},"def":{"name":"validate!","return_type":"Nil","visibility":"Public","body":"v = value!\n\nif opts = @options\n str_v = v.to_s\n if opts.includes?(str_v)\n else\n abort(\"#{CliGen::APPNAME}: '#{str_v}' is not a valid value for #{@long_key.empty? ? @short : @long_key} (valid: #{opts.join(\", \")})\")\n end\nend\n\nif check = @validate\n if check.call(v)\n else\n abort(\"#{CliGen::APPNAME}: validation failed for #{@long_key.empty? ? @short : @long_key}\")\n end\nend\n"},"external_var":false},{"html_id":"value!:T-instance-method","name":"value!","abstract":false,"location":{"filename":"src/cligen/flag.cr","line_number":88,"url":null},"def":{"name":"value!","return_type":"T","visibility":"Public","body":"v = @value\n\n\nif v.nil? && @env_var\n if raw = ENV[@env_var.not_nil!]?\n v = coerce(raw)\n end\nend\n\nv || (v = @default)\n\nif v.nil?\n abort(\"#{CliGen::APPNAME}: required flag #{@long_key.empty? ? @short : @long_key} was not provided\")\nend\nv.not_nil!\n"},"external_var":false}]},{"html_id":"CliGenerator/CliGen/Format","path":"CliGen/Format.html","kind":"module","full_name":"CliGen::Format","name":"Format","abstract":false,"locations":[{"filename":"src/cligen/format.cr","line_number":1,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"constants":[{"id":"INPUT_DATE_FORMAT","name":"INPUT_DATE_FORMAT","value":"\"%Y-%m-%d\""},{"id":"INPUT_DATETIME_FORMAT","name":"INPUT_DATETIME_FORMAT","value":"\"%Y-%m-%d %H:%M:%S\""}],"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"}},{"html_id":"CliGenerator/CliGen/MatchType","path":"CliGen/MatchType.html","kind":"enum","full_name":"CliGen::MatchType","name":"MatchType","abstract":false,"ancestors":[{"html_id":"CliGenerator/Enum","kind":"struct","full_name":"Enum","name":"Enum"},{"html_id":"CliGenerator/Comparable","kind":"module","full_name":"Comparable","name":"Comparable"},{"html_id":"CliGenerator/Value","kind":"struct","full_name":"Value","name":"Value"},{"html_id":"CliGenerator/Object","kind":"class","full_name":"Object","name":"Object"}],"locations":[{"filename":"src/cligen/match_type.cr","line_number":2,"url":null}],"repository_name":"CliGenerator","program":false,"enum":true,"alias":false,"const":false,"constants":[{"id":"FlagWithArg","name":"FlagWithArg","value":"0"},{"id":"FlagMultipleShort","name":"FlagMultipleShort","value":"1"},{"id":"ShortWithInlineArg","name":"ShortWithInlineArg","value":"2"},{"id":"NoMatch","name":"NoMatch","value":"3"}],"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"},"instance_methods":[{"html_id":"flag_multiple_short?-instance-method","name":"flag_multiple_short?","doc":"Returns `true` if this enum value equals `FlagMultipleShort`","summary":"

Returns true if this enum value equals FlagMultipleShort

","abstract":false,"location":{"filename":"src/cligen/match_type.cr","line_number":4,"url":null},"def":{"name":"flag_multiple_short?","visibility":"Public","body":"self == FlagMultipleShort"},"external_var":false},{"html_id":"flag_with_arg?-instance-method","name":"flag_with_arg?","doc":"Returns `true` if this enum value equals `FlagWithArg`","summary":"

Returns true if this enum value equals FlagWithArg

","abstract":false,"location":{"filename":"src/cligen/match_type.cr","line_number":3,"url":null},"def":{"name":"flag_with_arg?","visibility":"Public","body":"self == FlagWithArg"},"external_var":false},{"html_id":"no_match?-instance-method","name":"no_match?","doc":"Returns `true` if this enum value equals `NoMatch`","summary":"

Returns true if this enum value equals NoMatch

","abstract":false,"location":{"filename":"src/cligen/match_type.cr","line_number":6,"url":null},"def":{"name":"no_match?","visibility":"Public","body":"self == NoMatch"},"external_var":false},{"html_id":"short_with_inline_arg?-instance-method","name":"short_with_inline_arg?","doc":"Returns `true` if this enum value equals `ShortWithInlineArg`","summary":"

Returns true if this enum value equals ShortWithInlineArg

","abstract":false,"location":{"filename":"src/cligen/match_type.cr","line_number":5,"url":null},"def":{"name":"short_with_inline_arg?","visibility":"Public","body":"self == ShortWithInlineArg"},"external_var":false}]},{"html_id":"CliGenerator/CliGen/ProxyCommand","path":"CliGen/ProxyCommand.html","kind":"annotation","full_name":"CliGen::ProxyCommand","name":"ProxyCommand","abstract":false,"locations":[{"filename":"src/cligen/annotations.cr","line_number":2,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"}},{"html_id":"CliGenerator/CliGen/Regex","path":"CliGen/Regex.html","kind":"module","full_name":"CliGen::Regex","name":"Regex","abstract":false,"locations":[{"filename":"src/cligen/regex.cr","line_number":1,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"constants":[{"id":"FLAG_MULTIPLE_SHORT","name":"FLAG_MULTIPLE_SHORT","value":"/^-[a-zA-Z]+$/"},{"id":"FLAG_REGEX","name":"FLAG_REGEX","value":"/^(-[a-zA-Z]|--[a-zA-Z-_]+)$/"},{"id":"FLAG_WITH_ARG","name":"FLAG_WITH_ARG","value":"/^(?(-[a-zA-Z]|--[a-zA-Z-_]+))=\"?(?\\S+?)\"?$/"},{"id":"INPUT_DATE_REGEX","name":"INPUT_DATE_REGEX","value":"/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/"},{"id":"INPUT_DATETIME_REGEX","name":"INPUT_DATETIME_REGEX","value":"/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/"},{"id":"SHORT_WITH_INLINE_ARG","name":"SHORT_WITH_INLINE_ARG","value":"/^-[a-zA-Z][a-zA-Z0-9]+$/"}],"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"}},{"html_id":"CliGenerator/CliGen/Selection","path":"CliGen/Selection.html","kind":"annotation","full_name":"CliGen::Selection","name":"Selection","abstract":false,"locations":[{"filename":"src/cligen/annotations.cr","line_number":14,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"}},{"html_id":"CliGenerator/CliGen/SubCommand","path":"CliGen/SubCommand.html","kind":"annotation","full_name":"CliGen::SubCommand","name":"SubCommand","abstract":false,"locations":[{"filename":"src/cligen/annotations.cr","line_number":17,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"}},{"html_id":"CliGenerator/CliGen/Trigger","path":"CliGen/Trigger.html","kind":"annotation","full_name":"CliGen::Trigger","name":"Trigger","abstract":false,"locations":[{"filename":"src/cligen/annotations.cr","line_number":11,"url":null}],"repository_name":"CliGenerator","program":false,"enum":false,"alias":false,"const":false,"namespace":{"html_id":"CliGenerator/CliGen","kind":"module","full_name":"CliGen","name":"CliGen"}}]}]}}) \ No newline at end of file diff --git a/spec/command_spec.cr b/spec/command_spec.cr deleted file mode 100644 index 7e6bf30..0000000 --- a/spec/command_spec.cr +++ /dev/null @@ -1,131 +0,0 @@ -require "spec" -require "../src/command" - -@[CliGen::CommandInfo(description: "Test")] -class CommandSubclass < CliGen::Command - - define_argument(testvar, - type: Int32, - long: "--testvar TESTVAR", - description: "Does things" - ) - - define_argument(testvar_the_return, - type: Int32, - def_getter: true, - long: "--testvar_the_return TESTVAR", - description: "Does things" - ) -end - -EXAMPLES = [ - "Have test" -] - -@[CliGen::SubCommand(description: "test", examples: ::EXAMPLES)] -def CommandSubclass.do_thing - puts "HI" -end - -@[CliGen::CommandPreRun] -def CommandSubclass.check_things - puts "I was run" -end - -## Need to make sure EVERYTHING is generated before testing -macro finished -describe CliGen::Command do - - describe "subclassing" do - - describe "Creates the arguments" do - it "has testvar" do - {{CommandSubclass.class.has_method?(:testvar)}}.should be_true - end - - it "has testvar2 getter" do - {{CommandSubclass.class.has_method?(:get_testvar_the_return)}}.should be_true - end - - end - - it "has Header" do - CommandSubclass::HEADER.empty?.should be_false - end - - it "has examples" do - CommandSubclass::HEADER.includes?("Examples").should be_true - end - - {% pre_runs = CommandSubclass.class.methods.select(&.annotation(::CliGen::CommandPreRun)) %} - {% run = CommandSubclass.class.methods.find{|m| m.name.stringify == "run"}.stringify %} - {% if pre_runs.size > 0 %} - describe "when defining pre-run methods" do - {% for pre_run in pre_runs %} - it "generates {{pre_run.name}}" do - {{run}}.includes?({{pre_run.name.stringify}}).should be_true - end - {% end %} - end - {% end %} - - {% subcommands = CommandSubclass.class.methods.select(&.annotation(::CliGen::SubCommand)) %} - {% unless subcommands.empty? %} - describe "should have subcommands" do - {% for subcommand in subcommands %} - it "has {{subcommand.name}}" do - {{CommandSubclass.class.has_method?(subcommand.name.symbolize)}}.should be_true - end - {% end %} - end - {% end %} - {% arguments = CommandSubclass.class.methods.select(&.annotation(::CliGen::CommandArgument)) %} - {% unless arguments.empty? %} - describe "should have arguments" do - {% for argument in arguments %} - it "has {{argument.name}}" do - {{CommandSubclass.class.has_method?(argument.name.symbolize)}}.should be_true - end - {% end %} - end - {% end %} - - {% if [arguments, subcommands].any?{|i| i.size >= 0 } %} - describe "should have generated OptionParser parser.on" do - {{ make_parser = CommandSubclass.class.methods.find{|m| m.name.stringify == "make_parser"}.stringify}} - {% unless subcommands.empty? %} - describe "for subcommands" do - {% for command in subcommands %} - it "has {{command.name}}" do - {{make_parser}}.includes?("on(" + {{command.name.stringify.stringify}}).should be_true - end - {% end %} - end - {% end %} - {% unless arguments.empty? %} - describe "for arguments" do - {% for argument in arguments %} - {% anno = argument.annotation(::CliGen::CommandArgument) %} - it "has " + {{anno[:long].stringify}} do - {{make_parser}}.includes?({{anno[:long]}}).should be_true - end - {% end %} - end - {% end %} - end - {% end %} - - describe "Should have generated macro class methods" do - it "has generated run" do - {{CommandSubclass.class.has_method?(:run)}}.should be_true - end - - it "has generated make_parser" do - {{CommandSubclass.class.has_method?(:make_parser)}}.should be_true - end - end - - end - -end -end diff --git a/src/cligen.cr b/src/cligen.cr index 3de370b..7e7e477 100644 --- a/src/cligen.cr +++ b/src/cligen.cr @@ -1,11 +1,17 @@ -require "option_parser" -require "./cligen/regex" +require "./cligen/parsable" +require "./cligen/annotations" require "./cligen/format" +require "./cligen/regex" +require "./cligen/flag" +require "./cligen/command" +require "./cligen/command_node" +require "./cligen/app" module CliGen VERSION = "0.1.0" APPNAME = File.basename(PROGRAM_NAME) + record AdditionalDefaultFlag, short : String, long : String, @@ -26,78 +32,5 @@ module CliGen annotation DefaultFlag end - - macro define_section(section_name, parser) - {{parser}}.separator "" - {{parser}}.separator "{{section_name.id}}".colorize(:green) - {{parser}}.separator "-------------------------------------------------------------------------------".colorize(:blue) - end - - - alias OnType = Tuple(String, String) | Tuple(String, String, String) - macro define_default_flags(parser) - CliGen.define_section("Misc Flags", {{parser}}) - {{parser}}.on("-h", "--help", "Print out this help output"){ abort {{parser}} } - {{parser}}.invalid_option{|opt| - abort "#{CliGen::APPNAME} : invalid_option : Inavlid option provided #{opt}" - } - {{parser}}.invalid_option{|opt| - case opt - when /^-+[a-z-]+/ - STDERR.puts "#{CliGen::APPNAME} : ERROR : {{@type.name}} : {{parser}} : invalid_option : Inavlid option provided #{opt}" - else - abort "#{CliGen::APPNAME} : ERROR : {{@type.name}} : {{parser}} : invalid_option : Inavlid option provided #{opt}" - end - } - {{parser}}.missing_option{|opt| - abort "ERROR : {{@type.name}} : {{parser}} : missing_option : Argument was not provided to #{opt}" - } - {{parser}}.unknown_args{|opt| - unless opt.empty? - case opt.first - when /^-+[a-z-]+$/ - STDERR.puts "ERROR : {{@type.name}} : {{parser}} : unknown_args : #{opt} not a configured argument" - else - abort "ERROR : {{@type.name}} : {{parser}} : unknown_args : #{opt} not a configured argument" - end - end - } - - CliGen::ADDITIONAL_DEFAULT_FLAGS.each do |flag| - if [ flag.short, flag.long ].all?(&.!= "") - {{parser}}.on(flag.short, flag.long, flag.description){|var| flag.work.call(var) } - elsif flag.short != "" - {{parser}}.on(flag.short, flag.description){|var| flag.work.call(var) } - elsif flag.long != "" - {{parser}}.on(flag.long, flag.description){|var| flag.work.call(var) } - end - end - end - - macro define_root_parser - ROOT_COMMAND = OptionParser.new do |parser| - parser.banner = "#{CliGen::APPNAME} [command] [flags]" - - {% commands = ::CliGen::Command.subclasses %} - {% raise "ERROR : No commands defined (no subclasses of ::CliGen::Command were found)" if commands.empty? %} - CliGen.define_section("Commands", parser) - {% for command in commands %} - {{command.name}}.make_parser(parser) - {% end %} - - CliGen.define_default_flags(parser) - - abort parser if ARGV.empty? - end - end - - macro finished - define_root_parser - end - - def self.parse - ROOT_COMMAND.parse - end end -require "./cligen/command" diff --git a/src/cligen/annotations.cr b/src/cligen/annotations.cr new file mode 100644 index 0000000..bf331ec --- /dev/null +++ b/src/cligen/annotations.cr @@ -0,0 +1,19 @@ +module CliGen + annotation ProxyCommand + end + + annotation CommandInfo + end + + annotation Argument + end + + annotation Trigger + end + + annotation Selection + end + + annotation SubCommand + end +end diff --git a/src/cligen/app.cr b/src/cligen/app.cr new file mode 100644 index 0000000..fe3d24a --- /dev/null +++ b/src/cligen/app.cr @@ -0,0 +1,30 @@ +require "./arg" +require "./command_node" +require "./flag" +require "./app/generate" + +module CliGen + # Root entry point. Holds a flattened copy of all flags from every command + # for global-flag matching, then hands off to the matched child CommandNode. + class App < CliGen::BaseCommandNode + @@instance : self? + + def initialize(@name, flags : Array(BaseFlag), commands : Array(BaseCommandNode), pre_run_commands : Array(RunCommand), post_run_commands : Array(RunCommand)) + super(name: @name, flags: flags, commands: commands, pre_run_commands: pre_run_commands, post_run_commands: post_run_commands) + @@instance = self + end + + def check! : Nil + CliGen::GLOBAL_FLAGS.each(&.check!) + # @flags is the amalgamation of all child flags — checked by the commands themselves + check_for_duplicates!([CliGen::GLOBAL_FLAGS, @flags].flatten) + @commands.each(&.check!) + end + + # Convenience entry point; defaults to ARGV + def self.process(args : Array(String) = ARGV.to_a) : Nil + generate if @@instance.nil? + @@instance.not_nil!.process(args) + end + end +end diff --git a/src/cligen/app/generate.cr b/src/cligen/app/generate.cr new file mode 100644 index 0000000..e9de1d1 --- /dev/null +++ b/src/cligen/app/generate.cr @@ -0,0 +1,57 @@ +module CliGen + macro finished + class App + private def self.generate + app_flags = [] of BaseFlag + app_commands = [] of BaseCommandNode + + {% for cmd in CliGen::Command.subclasses %} + {% cmd_info = cmd.annotation(CliGen::CommandInfo) %} + {% raise "ERROR : CliGen::App.generate : No CliGen::CommandInfo annotation made for #{cmd.name}" unless cmd_info %} + {% raise "ERROR : CliGen::App.generate : Description must be provided for #{cmd.name}" unless cmd_info[:description].is_a? StringLiteral %} + {% cmd_name = cmd.name.split("::").last.downcase %} + {% cmd_flags = cmd.instance_vars.select{|v| v.annotation(CliGen::Argument) || v.annotation(CliGen::Selection) } %} + + cmd_flags = [] of BaseFlag + cmd_sub_commands = [] of BaseCommandNode + cmd_pre_run_cmds = [] of Proc(Nil) + cmd_post_run_cmds = [] of Proc(Nil) + + {% for var in cmd_flags %} + {% anno = var.annotation(CliGen::Argument) || var.annotation(CliGen::Selection) %} + cmd_flags << Flag({{var.type}}).new( + var: {{ var.name.stringify }}, + short: {% if anno[:short] %} {{anno[:short]}} {% else %} nil {% end %}, + long: {{ anno[:long] }}, + env_var: {% if anno[:env_var] %} {{anno[:env_var]}} {% else %} {{"#{cmd.name.upcase}_#{var.name.upcase}"}} {% end %}, + description: {{ anno[:description] }}, + default: {% if anno[:default] %} {{anno[:default]}} {% else %} nil {% end %}, + validate: {% if anno[:validate] %} {{anno[:validate]}} {% else %} nil {% end %}, + on_match: {% if anno[:on_match] %} {{anno[:on_match]}} {% else %} nil {% end %} + ) + {% end %} + + # Keep a copy of every flag on the root for global matching + app_flags += cmd_flags + + app_commands << CommandNode({{cmd}}).new( + name: {{cmd_name}}, + flags: cmd_flags, + commands: cmd_sub_commands, + pre_run_commands: cmd_pre_run_cmds, + post_run_commands: cmd_post_run_cmds, + description: {{cmd_info[:description]}} + ) + {% end %} + + new( + name: ::PROGRAM_NAME, + flags: app_flags, + commands: app_commands, + pre_run_commands: [] of Proc(Nil), + post_run_commands: [] of Proc(Nil) + ) + end + end + end +end diff --git a/src/cligen/arg.cr b/src/cligen/arg.cr new file mode 100644 index 0000000..43b35fe --- /dev/null +++ b/src/cligen/arg.cr @@ -0,0 +1,36 @@ +module CliGen + # This class serves as a "argument wrapper" to force a fail-fast approach to + # arg-parsing. + # + # It wraps around the argument + index of the argument to do state tracking + # and ensure that each argument is only processed once (plus allows for + # easier filtering of processed arguments to avoid having to do index math) + # + # args.reject(&.processed?) # returns the args that haven't been processed yet + # + # It expects each argument to only be processed once and will force a raise + # if the argument has Arg#processed called a second time. This is to force + # the developer (me) to fix any processing issues during the development of + # this framework. + class Arg + + # The raw string argument provided from the user + getter value : String + # The index of the argument in the array it was in + getter index : Int32 + # The "flag"/variable that tracks is the Arg has been processed yet + getter? processed : Bool = false + + def initialize(@value, @index) + end + + # This serves as a trigger that tells the object that it has been processed + # + # This will raise an exception if it is re-called after already having been + # processed. + def processed + raise "ERROR : CliGen::Arg(index: #{@index}, value: #{@value})#processed : This arg was re-processed" if @processed + @processed = true + end + end +end diff --git a/src/cligen/coercable.cr b/src/cligen/coercable.cr new file mode 100644 index 0000000..d87e0f2 --- /dev/null +++ b/src/cligen/coercable.cr @@ -0,0 +1,3 @@ +module CliGen::Coercable + abstract def coerce(arg : String) : self +end diff --git a/src/cligen/command.cr b/src/cligen/command.cr index 70d0c0d..89f3ca6 100644 --- a/src/cligen/command.cr +++ b/src/cligen/command.cr @@ -1,193 +1,35 @@ require "colorize" require "time" -require "./command/parser" +require "./annotations" +require "./command/argument" +require "./command/selection" +require "./command/trigger" +require "./command/subcommand" module CliGen - - annotation CommandPreRun - end - - annotation CommandInfo - end - - annotation CommandArgument - end - - annotation CommandSelection - end - - annotation SubCommand - end - - class Command - extend CliGen::Parser - - macro inherited - {% verbatim do %} macro finished - define_actions - define_header - {% anno = @type.annotation(::CliGen::CommandInfo) %} - {% unless anno[:def_runner] == false %} - define_runner - {% end %} - define_parser - define_action_setter - end - {% end %} - end - - macro define_actions - @@action : String = "" - ACTIONS = {{@type.class.methods.select(&.annotation(::CliGen::SubCommand)).map(&.name.stringify)}} of String - end - - macro define_header - {% name = @type.name.split("::").last.downcase.id %} - {% info_annos = @type.class.methods.select(&.annotation(::CliGen::SubCommand)).map(&.annotation(::CliGen::SubCommand)) %} - {% info_annos += @type.class.methods.select(&.annotation(::CliGen::CommandSelection)).map(&.annotation(::CliGen::CommandSelection)) %} - {% examples = [] of StringLiteral %} - {% info_annos.select(&.[](:examples)).map(&.[](:examples).resolve).each(&.each{|example| examples << example}) %} - HEADER = [ - "#{CliGen::APPNAME} {{name}} [[flags]]", - "", - {% unless examples.empty? %} - "Examples:".colorize(:green), - "-------------------------------------------------------------------------------".colorize(:blue), - {% for example in examples %} - {{example}}, - {% end %} - {% end %} - ].join("\n") - end - - macro define_selection(selection_name, short = "", long = "", description = nil, default = "", values = [] of StringLiteral) - {% if values.is_a? Path %} - {% values = values.resolve %} - {% end %} - {% raise "ERROR : define_selection : You MUST provide a description" unless description %} - {% raise "ERROR : define_selection : You must provide a valid set of values in Array(String) format" if values.empty? %} - {% description = "#{description.id} (valid: #{values.join(", ").id})" %} - {% unless default.empty? %} - {% description = "#{description.id} (default: #{default.id})" %} - {% end %} - @@{{selection_name}} : String = {{default}} - - @[::CliGen::CommandArgument(short: {{short}}, long: {{long}}, description: {{description}} )] - def self.{{selection_name}}= (selection : String) - raise "ERROR : {{selection_name}} : Invalid Selection(#{selection}) (valid: {{values.map(&.id).join(", ").id}})" unless {{values}}.includes?(selection) - @@{{selection_name}} = selection - end - end - - macro define_argument(arg_name, variable = nil, type = String, short = "", long = "", description = nil, subtype = Nil, format = nil, check = nil, def_getter = false, default = nil, logger = nil, &block?) - {% raise "ERROR : define_argument : You must provide a format or set it to \"auto\" to use builtin formats when defining a Time argument" if type.id.stringify == "Time" && format == nil %} - {% raise "ERROR : define_argument : You MUST provide a description" unless description %} - {% variable = arg_name unless variable %} - {% _type = type.id.stringify %} - {% _subtype = subtype.id.stringify %} - {% if _type == "String" %} - @@{{variable}} : {{type}} = "" - {% elsif _type == "Bool" %} - @@{{variable}} : {{type}} = false - {% elsif _type == "Int32" %} - @@{{variable}} : {{type}} = 0 - {% elsif _type == "Array" %} - {% raise "define_argument : subtype can only be Int32 or String" unless %w[ Int32 String ].includes?(_subtype) %} - @@{{variable}} : {{type}}({{subtype}}) = [] of {{subtype}} - {% elsif _type == "Time" %} - @@{{variable}} : {{type}} = Time.unix(seconds: 0) - {% end %} - {% if def_getter %} - def self.get_{{arg_name}} : {{type}} - @@{{variable}} - end - {% end %} - - @[::CliGen::CommandArgument(type: {{type}}, short: {{short}}, long: {{long}}, description: {{description}})] - def self.{{arg_name}}(var : String) : Nil - {% if check %} - ## If the check exists go ahead and call it - {{check}}(var) - {% end %} - - ## If a logger method has been provided by the user - {% if logger %} - {{logger.id}} "Command : subclass : argument_setter : {{arg_name}} : Entered with #{var}" - {% end %} - {% if _type == "Time" %} - formats = [ - CliGen::Regex::INPUT_DATETIME_REGEX, - CliGen::Regex::INPUT_DATE_REGEX - ] - abort "ERROR : Command : {{arg_name}} : Incorrect format for provided data #{var}" unless formats.any?{|f| var.match(f)} - if var =~ formats[0] - @@{{variable}} = Time.parse_local(var, CliGen::Format::INPUT_DATETIME_FORMAT) - elsif var =~ formats[1] - @@{{variable}} = Time.parse_local(var, CliGen::Format::INPUT_DATE_FORMAT) - end - {% elsif _type == "Array" %} - {% if _subtype == "Int32" %} - var : Int32 = var.to_i - {% elsif _subtype == "String" %} - {% else %} - var = {{subtype}}.new(var) + def initialize(*, handler : CliGen::BaseCommandNode) + {% verbatim do %} + {% for var in @type.instance_vars %} + {% anno = (var.annotation(CliGen::Argument) || var.annotation(CliGen::Selection)) %} + {% if anno %} + {% raise "ERROR : #{@type.name}#initialize : Argument '#{var.name}' cannot be a nilable type (#{var.type}) — flags always resolve to a concrete value" if var.type.union? %} + if flg = handler.flags.find{|f| f.var == {{var.name.stringify}} && f.long == {{anno[:long]}}} + @{{var.id}} = flg.as(CliGen::Flag({{var.type}})).value! + else + raise "ERROR : {{@type.name}}#{{@def.name}} : No flag found for \"{{var.name}}\"?" + end + {% else %} + {% raise "ERROR : #{@type.name}#{@def.name} : Instance Variable(#{var.name}) is not handled by CliGen and does not have a default value" unless var.default %} + @{{var.id}} = {{var.default}} + {% end %} + {% end %} {% end %} - @@{{variable}} << var - {% elsif _type == "Bool" %} - @@{{variable}} = true - {% elsif _type == "Int32" %} - @@{{variable}} = var.to_i - {% elsif _type == "String" %} - @@{{variable}} = var - {% end %} - end - end - - macro define_runner - def self.run - {% pre_run_commands = @type.class.methods.select(&.annotation(::CliGen::CommandPreRun)) %} - {% unless pre_run_commands.empty? %} - ## Ensuring that all runs that are tagged with the the CommandPreRun annotation are run - {% for method in pre_run_commands %} - {{method.name}} - {% end %} - {% end %} - - {% selections = @type.class.methods.select(&.annotation(::CliGen::CommandSelection)) %} - {% methods = @type.class.methods.select(&.annotation(::CliGen::SubCommand)) %} - {% raise "ERROR : No commands or selections defined for #{@type.name}" if methods.empty? && selections.empty? %} - {% raise "ERROR : Can't define both selections and commands for work in #{@type.name}" if ! methods.empty? && ! selections.empty? %} - {% var = methods.empty? ? nil : "action" %} - {% targets = methods.empty? ? selections : methods %} - {% if targets == selections %} - {% selectors = selections.map(&.annotation(::CliGen::CommandSelection)).map(&.[:selector]).uniq %} - {% raise "ERROR : Can't provide more than a single selector for runner" if selectors.size > 1 %} - {% var = selectors.first %} - {% end %} - {% begin %} - case @@{{var.id}} - {% for target in targets %} - when {{target.name.stringify}} - {{target.name}} - {% end %} - else - abort "ERROR : No action provided to command {{@type.name}}" end - {% end %} end end - - macro define_action_setter - def self.action=(action : String) - abort "ERROR : Action(#{action}) is not valid. Only #{ACTIONS.join(", ")} are acceptable" unless ACTIONS.includes?(action) - @@action = action - end - end - end - end diff --git a/src/cligen/command/argument.cr b/src/cligen/command/argument.cr new file mode 100644 index 0000000..b27c668 --- /dev/null +++ b/src/cligen/command/argument.cr @@ -0,0 +1,34 @@ +module CliGen + class Command + macro argument(variable, short, long, description, validation = nil) + {% raise "ERROR : CliGen::Command.argument : First argument (#{variable}) must be a TypeDeclaration (ex: ' : [= val]')" unless variable.is_a? TypeDeclaration %} + {% name = variable.name %} + {% type = variable.type %} + {% raise "ERROR : CliGen::Command.argument(#{name}) : Provided short must be a string" unless short.is_a? StringLiteral || string == nil %} + {% raise "ERROR : CliGen::Command.argument(#{name}) : Provided long must be a string" unless long.is_a? StringLiteral || long == nil %} + {% raise "ERROR : CliGen::Command.argument(#{name}) : You must provide a short or long" unless long || short %} + {% raise "ERROR : CliGen::Command.argument(#{name}) : You must provide a description" unless description %} + {% raise "ERROR : CliGen::Command.argument(#{name}) : Provided description must be a String" unless description.is_a? StringLiteral %} + {% unless validation.nil? %} + {% raise "ERROR : CliGen::Command.argument(#{name}) : Provided validation must be a Proc" unless validation.is_a? ProcLiteral %} + {% raise "ERROR : CliGen::Command.argument(#{name}) : Provided validation return type must be a Bool" unless validation.return_type == Bool %} + {% raise "ERROR : CliGen::Command.argument(#{name}) : Provided validation provided validation must have an input variable" if validation.args.empty? %} + {% arg = validation.args.first %} + {% unless arg.restriction == type %} + {% example = "->(#{arg.name} : #{type}) : #{type} { #{validation.body} }" %} + {% raise "ERROR : CliGen::Command.argument(#{name}) : Provided validation input value must be #{type}. EX: #{example}" %} + {% end %} + {% end %} + + @[CliGen::Argument(short: {{short}}, long: {{long}}, description: {{description}}, validation: {{validation}}, on_match: {{on_match}})] + @{{variable}} + + def {{variable.name}}= (value : {{type}}) + {% unless validation.nil? %} + raise "ERROR : #{@type.name}##{@def.name} : Provided value #{value} is not passing validation" unless {{validation}}.call(value) + {% end %} + @{{name}} = value + end + end + end +end diff --git a/src/cligen/command/parser.cr b/src/cligen/command/parser.cr deleted file mode 100644 index 11774f0..0000000 --- a/src/cligen/command/parser.cr +++ /dev/null @@ -1,70 +0,0 @@ -module CliGen::Parser - - macro extended - {% verbatim do %} - macro define_parser - def self.make_parser(parent_parser : OptionParser) : Nil - {% puts "#{@type.name} OptionParser is being generated" %} - {% name = @type.name.split("::").last %} - {% var = name.downcase %} - {% methods = @type.class.methods %} - {% info = @type.annotation(::CliGen::CommandInfo) %} - {% raise "ERROR : No CommandInfo annotation provided to {{@type.name}}" unless info %} - subparser = OptionParser.new do |parser| - parser.banner = {{@type.name}}::HEADER - - {% selections = methods.select(&.annotation(::CliGen::CommandSelection)) %} - {% if selections.size > 0 %} - CliGen.define_section("Selections", parser) - {% for selection in selections %} - {% selection_anno = selection.annotation(::CliGen::CommandSelection) %} - parser.on({{selection.name.stringify}}, {{selection_anno[:description]}}){ - {{@type.name}}.{{selection_anno[:selector]}}= {{selection.name.stringify}} - } - {% end %} - {% end %} - - {% subcommands = methods.select(&.annotation(::CliGen::SubCommand)) %} - {% if subcommands.size > 0 %} - CliGen.define_section("Subcommands", parser) - {% for subcommand in subcommands %} - {% subcommand_anno = subcommand.annotation(::CliGen::SubCommand) %} - parser.on({{subcommand.name.stringify}}, {{subcommand_anno[:description]}}){ - {{@type.name}}.action= {{subcommand.name.stringify}} - } - {% end %} - {% end %} - - {% arguments = methods.select(&.annotation(::CliGen::CommandArgument)) %} - {% if arguments.size > 0 %} - CliGen.define_section("Provide Arguments", parser) - {% for argument in arguments %} - {% argument_anno = argument.annotation(::CliGen::CommandArgument) %} - {% if argument_anno[:short] == "" && argument_anno[:long] != "" %} - parser.on({{argument_anno[:long]}}, {{argument_anno[:description]}}){|val| - {% elsif argument_anno[:short] != "" && argument_anno[:long] == "" %} - parser.on({{argument_anno[:short]}}, {{argument_anno[:description]}}){|val| - {% else %} - parser.on({{argument_anno[:short]}}, {{argument_anno[:long]}}, {{argument_anno[:description]}}){|val| - {% end %} - {{@type.name}}.{{argument.name}}(val) - } - {% end %} - {% end %} - CliGen.define_default_flags(parser) - end - parent_parser.on({{var}}, {{info[:description]}}){ - raise "ERROR : {{var.id}} not found in ARGV" unless i = ARGV.index({{var}}) - ## Removing all preceeding arguments so that only the actual required - ## args for the next command are present - ARGV.shift(i+1) - abort subparser if ARGV.empty? - subparser.parse - {{@type.name}}.run - } - end - end - {% end %} - end - -end diff --git a/src/cligen/command/selection.cr b/src/cligen/command/selection.cr new file mode 100644 index 0000000..14cb4d2 --- /dev/null +++ b/src/cligen/command/selection.cr @@ -0,0 +1,14 @@ +module CliGen + class Command + macro selection(variable, short, long, description, options) + {% raise "ERROR : CliGen::Command.selection : First selection must be a TypeDeclaration (ex: ' : [= val]')" unless variable.is_a? TypeDeclaration %} + {% raise "ERROR : CliGen::Command.selection : Provided short must be a string" unless short.is_a? StringLiteral || string == nil %} + {% raise "ERROR : CliGen::Command.selection : Provided long must be a string" unless long.is_a? StringLiteral || long == nil %} + {% raise "ERROR : CliGen::Command.selection : You must provide a short or long" unless long || short %} + {% raise "ERROR : CliGen::Command.selection : You must provide a description" unless description %} + {% raise "ERROR : CliGen::Command.selection : Provided description must be a String" unless description.is_a? StringLiteral %} + {% raise "ERROR : CliGen::Command.selection : You must provide options" unless options %} + {% raise "ERROR : CliGen::Command.selection : Provided options must be " unless options %} + end + end +end diff --git a/src/cligen/command/subcommand.cr b/src/cligen/command/subcommand.cr new file mode 100644 index 0000000..44d61d5 --- /dev/null +++ b/src/cligen/command/subcommand.cr @@ -0,0 +1,19 @@ +module CliGen + class Command + macro subcommand(func, description, examples = nil, &block) + {% raise "ERROR : CliGen::Command.subcommand : First argument must be a TypeDeclaration (ex: ' : ')" unless variable.is_a? TypeDeclaration %} + {% raise "ERROR : CliGen::Command.subcommand : You must provide a description" unless description %} + {% raise "ERROR : CliGen::Command.subcommand : Provided description must be a String" unless description.is_a? StringLiteral %} + {% unless examples.nil? %} + {% examples = examples.resolve if examples.is_a? Path %} + {% raise "ERROR : CliGen::Command.subcommand : Provided example must be an Array" unless examples.is_a? ArrayLiteral %} + {% end %} + {% raise "ERROR : CliGen::Command.subcommand : You MUST provide a function body" unless block %} + + @[CliGen::SubCommand(description: {{description}}, examples: {{examples}})] + def {{func}} + {{block.body}} + end + end + end +end diff --git a/src/cligen/command/trigger.cr b/src/cligen/command/trigger.cr new file mode 100644 index 0000000..da04f1a --- /dev/null +++ b/src/cligen/command/trigger.cr @@ -0,0 +1,21 @@ +module CliGen + class Command + macro trigger(short, long, argument = nil, &on_match) + {% raise "ERROR : CliGen::Command.trigger : Provided short must be a string" unless short.is_a? StringLiteral %} + {% raise "ERROR : CliGen::Command.trigger : Provided long must be a string" unless long.is_a? StringLiteral %} + {% raise "ERROR : CliGen::Command.trigger : Must provide a block for on_match trigger" unless on_match %} + {% name = long.gsub(/--/, "") %} + + @[CliGen::Trigger(short: {{short}}, long: {{long}}, argument: {{argument}})] + {% if argument %} + def self.__cligen_trigger__{{name}}__({{name}} : {{argument}}) : Nil + {{on_match.body}} + end + {% else %} + def self.__cligen_trigger__{{name}}__ : Nil + {{on_match.body}} + end + {% end %} + end + end +end diff --git a/src/cligen/command_node.cr b/src/cligen/command_node.cr new file mode 100644 index 0000000..2371f36 --- /dev/null +++ b/src/cligen/command_node.cr @@ -0,0 +1,235 @@ +require "./global_flag" +require "./flag" +require "./arg" +require "ecr" + +module CliGen + record SubCommandInfo, + name : String, + description : String, + examples : Array(String)? + + alias RunCommand = Proc(Nil) + + # Non-generic base that lets the tree hold heterogeneous CommandNode(T) children. + # Everything that doesn't depend on T lives here. + abstract class BaseCommandNode + getter name : String + getter flags : Array(BaseFlag) + getter commands : Array(BaseCommandNode) + getter description : String? + @pre_run_commands : Array(RunCommand) + @post_run_commands : Array(RunCommand) + + def initialize( + @name : String, + flags : Array(BaseFlag), + @commands : Array(BaseCommandNode), + @pre_run_commands : Array(RunCommand), + @post_run_commands : Array(RunCommand), + @description : String? = nil + ) + @flags = flags + CliGen::GLOBAL_FLAGS + @commands.flat_map(&.flags) + end + + def help : String + ECR.render("src/cligen/template/cmd_help.ecr") + end + + def check_for_duplicates!(flags : Array(BaseFlag)) : Nil + shorts = flags.compact_map(&.short) + short_duplicates = [] of String + longs = flags.compact_map { |f| f.long_key unless f.long_key.empty? } + long_duplicates = [] of String + + last_short : String = "" + shorts.sort.each do |short| + short_duplicates << short if last_short == short + last_short = short + end + + last_long : String = "" + longs.sort.each do |long| + long_duplicates << long if last_long == long + last_long = long + end + + unless long_duplicates.empty? && short_duplicates.empty? + error_buffer = "ERROR : CommandNode(%s)#check! : Found Duplicates : %s" + + message = "" + unless long_duplicates.empty? + message += "\nLong:\n%s\n" % long_duplicates.map { |f| "- #{f}" }.join("\n") + end + + unless short_duplicates.empty? + message += "\nShort:\n%s" % short_duplicates.map { |f| "- #{f}" }.join("\n") + end + + raise error_buffer % [@name, message] + end + end + + def get(flag_long : String) : BaseFlag? + @flags.find{|f| f.long_key == flag_long} + end + + def find_match(arg : String) + if subcommand?(arg) + return CliGen::MatchType::SubCommand + end + case arg + when "-h", "--help" + CliGen::MatchType::Help + when CliGen::Regex::FLAG_REGEX + if flg = @flags.find(&.matches?(arg)) + flg + else + CliGen::MatchType::NoMatch + end + when CliGen::Regex::FLAG_WITH_ARG + CliGen::MatchType::FlagWithArg + when CliGen::Regex::SHORT_WITH_INLINE_ARG + CliGen::MatchType::ShortWithInlineArg + when CliGen::Regex::FLAG_MULTIPLE_SHORT + CliGen::MatchType::FlagMultipleShort + else + if cmd = @commands.find { |c| c.name == arg } + cmd + else + CliGen::MatchType::NoMatch + end + end + end + + def subcommands? : Bool + subcommands.size > 0 + end + + def subcommand?(arg : String) : Bool + subcommands.any?{|f| f.name == arg} + end + + # Converts String array to Arg array and hands off to the typed process method + def process(args : Array(String)) : Nil + new_args = args.each_with_index.map { |arg, i| Arg.new(value: arg, index: i) }.to_a + process(new_args) + end + + abstract def subcommands : Array(SubCommandInfo) + abstract def check! : Nil + abstract def process(args : Array(Arg)) : Nil + end + + class CommandNode(T) < BaseCommandNode + def subcommands : Array(SubCommandInfo) + {% subcmds = T.methods.select(&.annotation(CliGen::SubCommand)) %} + {% if subcmds.empty? %} + [] of SubCommandInfo + {% else %} + [ + {% for cmd in subcmds %} + {% anno = cmd.annotation(CliGen::SubCommand) %} + SubCommandInfo.new( + name: {{cmd.name.stringify}}, + description: {{anno[:description]}}, + examples: {% if anno[:examples] %} {{anno[:examples]}} {% else %} nil {% end %} + ), + {% end %} + ] + {% end %} + end + + def check! : Nil + @flags.each(&.check!) + check_for_duplicates!(@flags) + @commands.each(&.check!) + raise "ERROR : CommandNode({{T}})#check! : {{T}} has no subcommands and no #main defined" \ + if subcommands.empty? && !{{T.has_method?(:main)}} + end + + def process(args : Array(Arg)) : Nil + check! + passed_execution = false + matched_subcommand : String? = nil + + @pre_run_commands.each(&.call) + + args.each do |arg| + next if arg.processed? + arg.processed + + case match = find_match(arg.value) + when BaseCommandNode + # Hand off remainder to the child; we're done at this level + match.process(args.reject(&.processed?)) + passed_execution = true + + when BaseFlag + if match.requires_arg? + match.process(args.reject(&.processed?)) + else + match.process + end + + when MatchType::SubCommand + raise "ERROR : CommandNode({{T}})#process : Subcommand(#{matched_subcommand}) was already matched" if matched_subcommand + matched_subcommand = arg.value + + when MatchType::Help + abort help + + when MatchType::FlagWithArg + if regex_match = CliGen::Regex::FLAG_WITH_ARG.match(arg.value) + case flag_match = find_match(regex_match["flag"]) + when BaseFlag + flag_match.process([Arg.new(value: regex_match["arg"], index: arg.index)]) + else + raise "ERROR : CommandNode(#{@name}).run : No flag matched '#{regex_match["flag"]}'" + end + else + raise "Oh good, you broke regex. How the hell did it match in find_match but not above? What the hell is going on" + end + + when MatchType::ShortWithInlineArg + abort "#{CliGen::APPNAME}: invalid flag '#{arg.value}' — inline values are not supported. Did you mean '#{arg.value[0..1]} #{arg.value[2..]}' ?" + + when MatchType::FlagMultipleShort + arg.value.gsub(/^-/, "").chars.map { |c| "-#{c}" }.each do |flag| + case match = find_match(flag) + when BaseFlag + abort "#{CliGen::APPNAME}: cannot bundle flag that requires an argument: #{flag}" if match.requires_arg? + match.process + when MatchType::NoMatch + raise "ERROR : CommandNode(#{@name}).run : No match for '#{flag}'" + end + end + + when MatchType::NoMatch + raise "ERROR : CommandNode(#{@name}).run : No match for '#{arg.value}'" + end + end + + @post_run_commands.each(&.call) + + unless passed_execution + cls = T.new(self) + {% subcmds = T.methods.select(&.annotation(CliGen::SubCommand)) %} + {% begin %} + case matched_subcommand + {% for cmd in subcmds %} + when {{cmd.name.stringify}} + cls.{{cmd.name}} + {% end %} + else + {% if T.has_method?(:main) %} + cls.main + {% else %} + raise "ERROR : CommandNode({{T}})#{{@def.name}} : No subcommand matched and no #main defined" + {% end %} + end + {% end %} + end + end + end +end diff --git a/src/cligen/flag.cr b/src/cligen/flag.cr new file mode 100644 index 0000000..825120a --- /dev/null +++ b/src/cligen/flag.cr @@ -0,0 +1,203 @@ +require "./arg" + +module CliGen + abstract class BaseFlag + getter var : String + getter short : String? + getter long : String + getter long_key : String + getter env_var : String + getter description : String + + def initialize( + @var : String, + @short : String?, + @long : String, + @env_var : String, + @description : String + ) + # if the user provides just a "--long" I want the @long_key to match it + if @long.includes(" ") + @long_key = @long.split(" ").first + else + @long_key = @long + end + end + + def matches?(token : String) : Bool + token == @short || (!@long_key.empty? && token == @long_key) + end + + abstract def satisfied? : Bool + abstract def validate! : Nil + abstract def raw_value : String? + abstract def check! : Nil + end + + class Flag(T) < BaseFlag + @value : T? + @default : T? + @options : Array(T)? + @validate : (T -> Bool)? + @on_match : Proc(Nil)? + + def initialize( + var : String, + short : String?, + long : String, + env_var : String, + description : String, + @default : T? = nil, + @options : Array(T)? = nil, + @validate : (T -> Bool)? = nil, + @on_match : Proc(Nil)? = nil + ) + super(var, short, long, env_var, description) + end + + def requires_arg? : Bool + {{T}} != Bool + end + + def process(argv : Array(Arg) = [] of Arg) : Nil + if requires_arg? + raise "ERROR : Flag({{T}}) : Array requires an argument but provided array is empty" if argv.empty? + end + + {% if T == Bool %} + @value = true + {% elsif T <= Array %} + {% raise "ERROR : Flag(#{T}) : You cannot define multiple types of array entries" if T.type_vars.size > 1 %} + {% elem = T.type_vars.first %} + argv.each do |arg| + break if arg.value.starts_with('-') + {% if elem == Int32 %} + (@value ||= [] of Int32) << arg.value.to_i + {% elsif elem == String %} + (@value ||= [] of String) << arg.value + {% elsif elem < CliGen::Coercable %} + if arg.value.includes?(",") + (@value ||= [] of {{elem}}) += arg.value.split(",").map{|i| {{elem}}.coerce(i)} + else + (@value ||= [] of {{elem}}) << {{elem}}.coerce(arg.value) + end + {% else %} + {% raise "ERROR : Flag(#{T}) : #{elem} is not a coercable type. If you wish to coerce it from a bare string include CliGen::Coercable & implement the class method" %} + {% end %} + arg.processed + end + {% elsif T == Int32 %} + @value = argv.first.value.to_i + argv.first.processed + {% elsif T == Time %} + @value = parse_time(argv.first.value) + argv.first.processed + {% elsif T == String %} # String + @value = argv.first.value + argv.first.processed + {% elsif T < CliGen::Parsable %} + processed = argv.select(&.processed?) + @value = T.parse_args(argv) + post_processed = argv.select(&.processed?) + if processed == post_processed + raise "ERROR : Flag({{T}}, long: #{@long_key})#process : Your {{T}}#process_args did not mark processed args as processed. Please check your code" + end + {% else %} + {% raise "ERROR : Flag({{T}}, long: #{@long_key})#process : Generic Type #{T} is not supported. To add support you must include CliGen::Parsable & implement the class method" %} + {% end %} + + validate! + @on_match.try(&.call) + end + + def value! : T + v = @value + + # Priority: provided arg → env var → default → abort + if v.nil? + if raw = ENV[@env_var]? + v = coerce(raw) + end + end + + v ||= @default + + raise "#{CliGen::APPNAME}: required flag #{@long_key} was not provided" if v.nil? + v.not_nil! + end + + def raw_value : String? + {% if T == Bool %} + @value.try(&.to_s) + {% elsif T <= Array %} + @value.try(&.join(",")) + {% else %} + @value.try(&.to_s) + {% end %} + end + + def satisfied? : Bool + return true if !@value.nil? + return true if @env_var && ENV[@env_var]? + return true if !@default.nil? + false + end + + def validate! : Nil + v = value! + + if opts = @options + abort "#{CliGen::APPNAME}: '#{v}' is not a valid value for #{@long_key} (valid: #{opts.join(", ")})" unless opts.includes?(v) + end + + if check = @validate + abort "#{CliGen::APPNAME}: validation failed for #{@long_key}" unless check.call(v) + end + end + + def check! + raise "ERROR : Flag({{T}}, long: #{@long})#check! : -h is reserved for internal help usage" if @short == "-h" + raise "ERROR : Flag({{T}}, long: #{@long})#check! : --help is reserved for internal help usage" if @long_key == "--help" + end + + private def coerce(raw : String) : T + {% if T == Bool %} + raw == "true" || raw == "1" + {% elsif T == Int32 %} + raw.to_i + {% elsif T == Time %} + parse_time(raw) + {% elsif T <= Array %} + {% elem = T.type_vars.first %} + {% if elem == Int32 %} + raw.split(',').map(&.to_i) + {% elsif elem == String %} + raw.split(',') + {% elsif elem < CliGen::Coercable %} + raw.split(',').map{|i| {{elem}}.coerce(i)} + {% else %} + {% raise "ERROR : Flag(#{T}) : #{elem} is not a coercable type. If you wish to coerce it from a bare string include CliGen::Coercable & implement the class method" %} + {% end %} + {% elsif T == String %} # String + raw + {% elsif T < CliGen::Coercable %} + T.coerce(raw) + {% else %} + {% raise "ERROR : Flag(#{T}) : #{T} is not a coercable type. If you wish to coerce it from a bare string include CliGen::Coercable & implement the class method" %} + {% end %} + end + + private def parse_time(raw : String) : Time + formats = [ + CliGen::Regex::INPUT_DATETIME_REGEX, + CliGen::Regex::INPUT_DATE_REGEX + ] + abort "#{CliGen::APPNAME}: invalid date/time format '#{raw}' (expected YYYY-MM-DD or YYYY-MM-DD HH:MM:SS)" unless formats.any? { |f| raw.match(f) } + if raw.match(formats[0]) + Time.parse_local(raw, CliGen::Format::INPUT_DATETIME_FORMAT) + else + Time.parse_local(raw, CliGen::Format::INPUT_DATE_FORMAT) + end + end + end +end diff --git a/src/cligen/global_flag.cr b/src/cligen/global_flag.cr new file mode 100644 index 0000000..4b2ecc3 --- /dev/null +++ b/src/cligen/global_flag.cr @@ -0,0 +1,37 @@ +require "./flag" + +module CliGen + GLOBAL_FLAGS = [] of BaseFlag + + macro add_global_flag(type, long, description, env_var = nil, short = nil, validation = nil, &on_match) + {% raise "ERROR : CliGen.add_global_flag : type must be a TypeNode" unless type.is_a? TypeNode %} + {% raise "ERROR : CliGen.add_global_flag : long must begin a StringLiteral" unless long.is_a? StringLiteral %} + {% raise "ERROR : CliGen.add_global_flag : long must begin with --" unless long =~ /^--/ %} + {% if short %} + {% raise "ERROR : CliGen.add_global_flag : Short must be a StringLiteral" unless short.is_a? StringLiteral %} + {% raise "ERROR : CliGen.add_global_flag : Short must be a - with single char (ex: -a)" unless short =~ /^-[a-zA-Z]/ %} + {% end %} + {% if validation %} + {% raise "ERROR : CliGen.add_global_flag : validation must be a Proc" unless validation.is_a? ProcLiteral %} + {% raise "ERROR : CliGen.add_global_flag : validation proc return type must be nil \"->(...) : Nil {...}\"" unless validation.is_a? ProcLiteral %} + {% raise "ERROR : CliGen.add_global_flag : validation proc must have a single input variable" unless validation.args.size == 1%} + {% arg = validation.args.first %} + {% raise "ERROR : CliGen.add_global_flag : validation proc input variable MUST be typed to match the flag type \"->(#{arg.name} : #{type}) : Nil { ... }\"" unless arg.restriction == type %} + {% end %} + {% raise "ERROR : CliGen.add_global_flag : decription must be a StringLiteral" unless description.is_a? StringLiteral %} + {% if env_var %} + {% raise "ERROR : CliGen.add_global_flag : env_var must be a StringLiteral" unless env_var.is_a? StringLiteral %} + {% else %} + {% env_var = long.gsub(/--/, "").upcase %} + {% end %} + CliGen::GLOBAL_FLAGS << CliGen::Flag({{type}}).new( + var: "", + short: {{short}}, + long: {{long}}, + description: {{description}}, + env_var: {{env_var}}, + on_match: {% if on_match %} ->() : Nil { {{on_match.body}} } {% else %} nil {% end %}, + validation: {% if validation %} {{validation}} {% else %} nil {% end %} + ) + end +end diff --git a/src/cligen/match_type.cr b/src/cligen/match_type.cr new file mode 100644 index 0000000..aba76d7 --- /dev/null +++ b/src/cligen/match_type.cr @@ -0,0 +1,10 @@ +module CliGen + enum MatchType + FlagWithArg + FlagMultipleShort + ShortWithInlineArg + SubCommand + Help + NoMatch + end +end diff --git a/src/cligen/parsable.cr b/src/cligen/parsable.cr new file mode 100644 index 0000000..ebe5c6a --- /dev/null +++ b/src/cligen/parsable.cr @@ -0,0 +1,3 @@ +module CliGen::Parseable + abstract def parse_args(args : Array(CliGen::Arg)) : self +end diff --git a/src/cligen/regex.cr b/src/cligen/regex.cr index d585de6..9d63c85 100644 --- a/src/cligen/regex.cr +++ b/src/cligen/regex.cr @@ -1,4 +1,9 @@ module CliGen::Regex + FLAG_REGEX=/^(-[a-zA-Z]|--[a-zA-Z-_]+)$/ + FLAG_WITH_ARG=/^(?(-[a-zA-Z]|--[a-zA-Z-_]+))="?(?\S+?)"?$/ + FLAG_MULTIPLE_SHORT=/^-[a-zA-Z]+$/ + SHORT_WITH_INLINE_ARG=/^-[a-zA-Z][a-zA-Z0-9]+$/ + INPUT_DATETIME_REGEX = /^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/ INPUT_DATE_REGEX = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/ end diff --git a/src/cligen/template/cmd_help.ecr b/src/cligen/template/cmd_help.ecr new file mode 100644 index 0000000..c019ea0 --- /dev/null +++ b/src/cligen/template/cmd_help.ecr @@ -0,0 +1,42 @@ +Command: <% @name %> +<%- unless @description.nil? -%> +Description: <%= @description %> +<%- end -%> + +Flags: +--------------------------------------------------------------- +<%- @flags.each do |flag| -%> + <%- unless flag.short.nil? -%> + <%= "%-10s %s" % ["#{flag.short},#{flag.long}", flag.description] %> + <%- else -%> + <%= "%-10s %s" % [flag.long, flag.description] %> + <%- end -%> + +<%- end -%> +<%- unless @commands.empty? -%> +Other Commands +--------------------------------------------------------------- + <%- @commands.each do |command| -%> + <%= "%-10s %s" % [ command.name, command.description ] %> + <%- end -%> + +<%- end -%> +<%- if subcommands? -%> +SubCommands of <%= @name %>: +--------------------------------------------------------------- + <%- subcommands.each do |cmd| -%> + <%= "%-10 %s" % [cmd.name, cmd.description] %> + <%- end -%> + + <%- cmds = subcommands.select{|c| ! c.examples.nil? } -%> + <%- unless cmds.empty? -%> +Examples: +--------------------------------------------------------------- + <%- cmds.map(&.examples).flatten.each do |example| -%> +<%= example %> + <%- end -%> + + <%- end -%> +<%- end -%> + +Note: When wanting help output of any command you can provide the -h/--help flags or help command diff --git a/tags b/tags new file mode 100644 index 0000000..77a95a4 --- /dev/null +++ b/tags @@ -0,0 +1,22 @@ +!_TAG_EXTRA_DESCRIPTION anonymous /Include tags for non-named objects like lambda/ +!_TAG_EXTRA_DESCRIPTION fileScope /Include tags of file scope/ +!_TAG_EXTRA_DESCRIPTION pseudo /Include pseudo tags/ +!_TAG_EXTRA_DESCRIPTION subparser /Include tags generated by subparsers/ +!_TAG_FIELD_DESCRIPTION epoch /the last modified time of the input file (only for F\/file kind tag)/ +!_TAG_FIELD_DESCRIPTION file /File-restricted scoping/ +!_TAG_FIELD_DESCRIPTION input /input file/ +!_TAG_FIELD_DESCRIPTION name /tag name/ +!_TAG_FIELD_DESCRIPTION pattern /pattern/ +!_TAG_FIELD_DESCRIPTION typeref /Type and name of a variable or typedef/ +!_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;" to lines/ +!_TAG_FILE_SORTED 1 /0=unsorted, 1=sorted, 2=foldcase/ +!_TAG_OUTPUT_EXCMD mixed /number, pattern, mixed, or combineV2/ +!_TAG_OUTPUT_FILESEP slash /slash or backslash/ +!_TAG_OUTPUT_MODE u-ctags /u-ctags or e-ctags/ +!_TAG_OUTPUT_VERSION 1.1 /current.age/ +!_TAG_PATTERN_LENGTH_LIMIT 96 /0 for no limit/ +!_TAG_PROC_CWD /home/tristan/Projects/Crystal/cligen/ // +!_TAG_PROGRAM_AUTHOR Universal Ctags Team // +!_TAG_PROGRAM_NAME Universal Ctags /Derived from Exuberant Ctags/ +!_TAG_PROGRAM_URL https://ctags.io/ /official site/ +!_TAG_PROGRAM_VERSION 6.2.1 /v6.2.1/ diff --git a/test.cr b/test.cr new file mode 100644 index 0000000..1171edf --- /dev/null +++ b/test.cr @@ -0,0 +1,14 @@ +require "./src/cligen" + +module MyModule + @[CliGen::CommandInfo(description: "HI")] + class MyTest < CliGen::Command + argument(myvar : Int32, long: "--myvar VAR", description: "To do thing") + + def main + puts @myvar + end + end + + CliGen::App.process +end