{"id":13877905,"url":"https://github.com/bkuhlmann/sod","last_synced_at":"2025-10-08T18:14:45.600Z","repository":{"id":175915089,"uuid":"654343350","full_name":"bkuhlmann/sod","owner":"bkuhlmann","description":"A domain specific language for creating composable command line interfaces.","archived":false,"fork":false,"pushed_at":"2025-03-25T02:12:41.000Z","size":294,"stargazers_count":12,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-11T21:40:58.833Z","etag":null,"topics":["cli","dsl"],"latest_commit_sha":null,"homepage":"https://alchemists.io/projects/sod","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bkuhlmann.png","metadata":{"files":{"readme":"README.adoc","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.adoc","code_of_conduct":null,"threat_model":null,"audit":null,"citation":"CITATION.cff","codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":["bkuhlmann"]}},"created_at":"2023-06-15T23:35:04.000Z","updated_at":"2025-03-25T02:12:44.000Z","dependencies_parsed_at":null,"dependency_job_id":"d6a0dc6a-2979-45ae-954c-67b15766811b","html_url":"https://github.com/bkuhlmann/sod","commit_stats":{"total_commits":73,"total_committers":1,"mean_commits":73.0,"dds":0.0,"last_synced_commit":"c01c3eaeb9fc868ee5602646791e0dae9af9d77a"},"previous_names":["bkuhlmann/sod"],"tags_count":25,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bkuhlmann%2Fsod","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bkuhlmann%2Fsod/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bkuhlmann%2Fsod/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bkuhlmann%2Fsod/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bkuhlmann","download_url":"https://codeload.github.com/bkuhlmann/sod/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248830906,"owners_count":21168369,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cli","dsl"],"created_at":"2024-08-06T08:01:34.545Z","updated_at":"2025-10-08T18:14:40.567Z","avatar_url":"https://github.com/bkuhlmann.png","language":"Ruby","funding_links":["https://github.com/sponsors/bkuhlmann"],"categories":["Ruby"],"sub_categories":[],"readme":":toc: macro\n:toclevels: 5\n:figure-caption!:\n\n:cogger_link: link:https://alchemists.io/projects/cogger[Cogger]\n:etcher_link: link:https://alchemists.io/projects/etcher[Etcher]\n:gemsmith_link: link:https://alchemists.io/projects/gemsmith[Gemsmith]\n:git-lint_link: link:https://alchemists.io/projects/git-lint[Git Lint]\n:hanamismith_link: link:https://alchemists.io/projects/hanamismith[Hanamismith]\n:infusible_link: link:https://alchemists.io/projects/infusible[Infusible]\n:milestoner_link: link:https://alchemists.io/projects/milestoner[Milestoner]\n:option_parser_link: link:https://alchemists.io/articles/ruby_option_parser[Option Parser]\n:pennyworth_link: link:https://alchemists.io/projects/pennyworth[Pennyworth]\n:pragmater_link: link:https://alchemists.io/projects/pragmater[Pragmater]\n:rubysmith_link: link:https://alchemists.io/projects/rubysmith[Rubysmith]\n:runcom_link: link:https://alchemists.io/projects/runcom[Runcom]\n:spek_link: link:https://alchemists.io/projects/spek[Spek]\n:sublime_text_kit_link: link:https://alchemists.io/projects/sublime_text_kit[Sublime Text Kit]\n:tocer_link: link:https://alchemists.io/projects/tocer[Tocer]\n:tone_link: link:https://alchemists.io/projects/tone[Tone]\n:versionaire_link: link:https://alchemists.io/projects/versionaire[Versionaire]\n:xdg_link: link:https://alchemists.io/projects/xdg[XDG]\n\n= Sod\n\nSod -- as in the ground upon which you stand -- provides a Domain Specific Language (DSL) for creating reusable Command Line Interfaces (CLIs). This gem builds upon and enhances native {option_parser_link} behavior by smoothing out the rough edges you wish {option_parser_link} didn't have.\n\ntoc::[]\n\n== Features\n\n- Builds upon and enhances native {option_parser_link} functionality.\n- Provides a simple DSL for composing reusable CLI commands and actions.\n- Provides a blank slate that is fully customizable to your needs.\n- Provides prefabricated commands and actions for quick setup and experimentation.\n- Uses {infusible_link} for function composition.\n- Uses {tone_link} for colorized documentation.\n- Uses {cogger_link} for colorized logging.\n\n== Screenshots\n\n*DSL*\n\nimage::https://alchemists.io/images/projects/sod/screenshots/dsl.png[A screenshot of the DSL syntax,width=667,height=607,role=focal_point]\n\n*Output*\n\nimage::https://alchemists.io/images/projects/sod/screenshots/output.png[A screenshot of the generated help documentation,width=596,height=662,role=focal_point]\n\n== Requirements\n\n. link:https://www.ruby-lang.org[Ruby].\n. Familiarity with {option_parser_link} syntax and behavior.\n\n== Setup\n\nTo install _with_ security, run:\n\n[source,bash]\n----\n# 💡 Skip this line if you already have the public certificate installed.\ngem cert --add \u003c(curl --compressed --location https://alchemists.io/gems.pem)\ngem install sod --trust-policy HighSecurity\n----\n\nTo install _without_ security, run:\n\n[source,bash]\n----\ngem install sod\n----\n\nYou can also add the gem directly to your project:\n\n[source,bash]\n----\nbundle add sod\n----\n\nOnce the gem is installed, you only need to require it:\n\n[source,ruby]\n----\nrequire \"sod\"\n----\n\n== Usage\n\nCreating and calling a CLI is as simple as:\n\n[source,ruby]\n----\nSod.new.call\n# nil\n----\n\nGranted, the above isn't terribly exciting -- in terms of initial behavior -- but illustrates how default behavior provides a _blank slate_ from which to mold custom behavior as you like. To provide minimum functionality, you'll want to give your CLI a name, banner, and throw in the prefabricated help action:\n\n[source,ruby]\n----\ncli = Sod.new :demo, banner: \"Demo 0.0.0: A demonstration.\" do\n  on Sod::Prefabs::Actions::Help, self\nend\n\ncli.call\n\n# Demo 0.0.0: A demonstration.\n#\n# USAGE\n#   demo [OPTIONS]\n#\n# OPTIONS\n#   -h, --help [COMMAND]     Show this message.\n----\n\nNotice, with only a few extra lines of code, you can build upon the initial _blank slate_ provided for you and start to see your custom CLI take form. You can even take this a step further and outline the structure of your CLI with _inline commands_:\n\n[source,ruby]\n----\ncli = Sod.new :demo, banner: \"Demo 0.0.0: A demonstration.\" do\n  on Sod::Prefabs::Actions::Help, self\n\n  on \"generate\", \"Generate project templates.\"\n  on \"db\", \"Manage database.\"\nend\n\ncli.call\n\n# Demo 0.0.0: A demonstration.\n#\n# USAGE\n#   demo [OPTIONS]\n#   demo COMMAND [OPTIONS]\n#\n# OPTIONS\n#   -h, --help [COMMAND]     Show this message.\n#\n# COMMANDS\n#   generate                 Generate project templates.\n#   db                       Manage database.\n----\n\nWe'll dive into the defaults, prefabrications, and custom commands/actions soon but knowing a _help_ action is provided for you is a good first step in learning how to build your own custom CLI.\n\n=== Name\n\nA good CLI needs a name and, by default, this is the name of file, script, or IRB session you are currently creating your CLI instance in. For example, when using this project's `bin/console` script, my CLI name is:\n\n[source,ruby]\n----\nSod.new.name  # \"console\"\n----\n\nThe default name is automatically acquired via the `$PROGRAM_NAME` global variable. Any file extension is immediately trimmed which means creating your CLI instance within a `demo.rb` file will have a name of `\"demo\"`. Should this not be desired, you can customize further by providing your own name:\n\n[source,ruby]\n----\n# With a symbol.\nSod.new(:demo).name   # \"demo\"\n\n# With a string.\nSod.new(\"demo\").name  # \"demo\"\n----\n\nWhen using the prefabricated help action, the name of your CLI will also show up in the usage documentation:\n\n[source,ruby]\n----\nSod.new(:demo) { on Sod::Prefabs::Actions::Help, self }\n   .call\n\n# USAGE\n#   demo [OPTIONS]\n#\n# OPTIONS\n#   -h, --help [COMMAND]     Show this message.\n----\n\n=== Banner\n\nThe banner is optional but strongly encouraged because it allows you to give your CLI a label and short description. Example:\n\n[source,ruby]\n----\ncli = Sod.new :demo, banner: \"Demo 0.0.0: A demonstration.\" do\n  on Sod::Prefabs::Actions::Help, self\nend\n\ncli.call\n\n# Demo 0.0.0: A demonstration.\n#\n# USAGE\n#   demo [OPTIONS]\n#\n# OPTIONS\n#   -h, --help [COMMAND]     Show this message.\n----\n\nAs you can see, when a banner is present, you are able to describe your CLI while providing relevant information such as current version with minimal effort.\n\n=== DSL\n\nYou've already seen some of the DSL syntax, via the earlier examples, but now we can zoom in on the building blocks: commands and actions. Only a single method is required to add them: `on`. For example, here's what nesting looks like:\n\n[source,ruby]\n----\nSod.new :demo, banner: \"Demo 0.0.0: A demonstration.\" do\n  on \"db\", \"Manage database.\" do\n    on Start\n    on Stop\n\n    on \"structure\", \"Manage database structure.\" do\n      on Dump\n    end\n  end\n\n  on Sod::Prefabs::Actions::Version, \"Demo 0.0.0\"\n  on Sod::Prefabs::Actions::Help, self\nend\n----\n\nDespite the `Start`, `Stop`, and `Dump` actions not being implemented yet -- because you'll get a `NameError` if you try -- this does mean you'd eventually have the following functionality available from the command line:\n\n[source,bash]\n----\ndemo db --start\ndemo db --stop\ndemo db structure --dump\ndemo --version\ndemo --help\n----\n\nThe `on` method is the primary method of the DSL. Short and sweet. You'll also see `on` used when implementing custom commands and actions too. The `on` method can take any number of positional and/or keyword arguments. Here's an example where you might want to customize your database action by injecting a new dependencies:\n\n[source,ruby]\n----\nSod.new :demo, banner: \"Demo 0.0.0: A demonstration.\" do\n  on DB, \"MyDatabase\", host: localhost, port: 5432\nend\n----\n\nThe first _positional_ argument (i.e. `DB`) is _always_ your action, the second _positional_ argument is the first positional argument to the `DB.new` method followed by the `host` and `port` _keyword_ arguments. In other words, here's what's happening:\n\n[source,ruby]\n----\n# Pattern\non DB, *, **\n\n# DSL\non DB, \"MyDatabase\", host: localhost, port: 5432\n\n# Actual\nDB.new \"MyDatabase\", host: localhost, port: 5432\n----\n\nThis also means you get the following benefits:\n\n* Lazy initialization of your commands/actions.\n* Quick injection of dependencies or customization of dependencies in general.\n* Automatic forwarding of positional and/or keyword arguments to your command/action. Blocks are excluded since they are used by the `on` method for nesting purposes.\n\nTo further understand the DSL, commands, and actions you'll need to start with actions since they are the building blocks.\n\n==== Actions\n\nActions are the lowest building blocks of the DSL which allow you to quickly implement, test, reuse, and compose more complex architectures. They provide a nice layer atop native `OptionParser#on` functionality.\n\nThere are two kinds of actions: custom and prefabricated. We'll start with custom actions and explore prefabricated actions later. Custom actions allow you to define your own functionality by inheriting from `Sod::Action` and leveraging the DSL that comes with it.\n\n===== Macros\n\nHere's a high level breakdown of the macros you can use:\n\n* `description`: Optional (but strongly encouraged). Allows you to describe your action and appears within help documentation. If the description is not defined, then only your action's handle (i.e. aliases) will be shown.\n* `ancillary`: Optional. Allows you to provide supplemental text in addition to your description that might be helpful to know about when displaying help documentation. This can accept single or multiple arguments. Order matters since each argument will appear on a separate line in the order listed.\n* `on`: Required. Allows you to define the behavior of your action through keyword arguments. Otherwise, if not defined, you'll get a `Sod::Error` telling you that you must, at a minimum, define some aliases. This macro mimics {option_parser_link} `#on` behavior via the following positional and keyword arguments:\n** `aliases`: Required. This is a positional argument and defines the short and long form aliases of your action. Your aliases can be a single string (i.e. `on \"--version\"`) or an array of short and long form aliases. For example, using `on %w[-v --version]` would allow you to use `-v` or `--version` from the command line to call your action. You can also use boolean aliases such as `--build` or `--[no-]build` which the option parser will supply to your `#call` method as a boolean value.\n** `argument`: Optional. Serves as documentation, must be a string value, and allows the {option_parser_link} to determine if the argument is required or optional. As per the {option_parser_link} documentation, you could use the following values for example:\n*** `TEXT`: Required text.\n*** `[TEXT]`: Optional text.\n*** `a,b,c`: Required list.\n*** `[a,b,c]`: Optional list.\n** `type`: Optional. The type is inferred from your argument but, if you need to be explicit or want to use a custom type not supported by default by option parser, you can specify the type by providing a primitive. Example: `String`, `Array`, `Hash`, `Date`, etc. You can also use custom types, provided by this gem and explained later, or implement your own.\n** `allow`: Optional. Allows you to define what values are allowed as defined via the `argument` or `type` keywords. This can be a string, array, hash, etc. as long as it's compatible with what is defined via the `argument` and/or `type` keyword. This information will also show up in the help documentation as well.\n** `default`: Optional. Allows you to supply a default value and is a handy for simple values which don't require lazy evaluation via the corresponding default macro. ⚠️ This is ignored if the corresponding macro is used so ensure you use one or the other but not both.\n** `description`: Optional. Allows you to define a description. Handy for short descriptions that can fit on a single line. Otherwise, for longer descriptions, use the macro. ⚠️ This is ignored if the corresponding macro is used so ensure you use one or the other but not both.\n** `ancillary`: Optional. Allows you to define ancillary text to supplement your description. It can accept a string or an array. Handy for short, supplementary, text that can fit on a single line. Otherwise, for more verbose details, use the macro. ⚠️ This is ignored if the corresponding macro is used so ensure you use one or the other but not both.\n* `default`: Optional. Uses a block which lazy evaluates and resolves your value. This is most helpful when used in combination with an _optional_ `argument` and/or `type` which can fallback to a safe default. This information shows up in the help text where the value is rendered as green text. In the case of booleans, they will be rendered as green for `true` and red for `false`.\n\nWith the above in mind, let's look at a few examples of what you can do when you put all of this together.\n\n===== Booleans\n\nBoolean are long alases only, use `[no-]` syntax after the double dashes, and provide the boolean value for use within your action. Here's a minimal implementation:\n\n[source,ruby]\n----\nclass Action \u003c Sod::Action\n  on \"--[no-]run\"\n\n  def call(boolean) = puts boolean\nend\n\ncli = Sod.new { on Action }\n\ncli.call %w[--run]     # \"true\"\ncli.call %w[--no-run]  # \"false\"\n----\n\nBecause a value is always provided when using a boolean flag, you can make it a required positional parameter via your method definition (i.e. `call(boolean)`). You don't need to worry about type safety because {option_parser_link} will pass in `true` or `false` as you can see from the output above.\n\n===== Flags\n\nFlags are similar to _Booleans_ but take _no arguments_ and allow short or long aliases. When a flag is supplied, the action is _enabled_ which means you can execute custom functionality. Otherwise, when a flag isn't supplied (i.e. default), then the action is _disabled_ and nothing happens.\n\n[source,ruby]\n----\nclass Action \u003c Sod::Action\n  on %w[-m --max]\n\n  def call(*) = puts \"Maximum enabled.\"\nend\n\ncli = Sod.new { on Action }\n\ncli.call %w[--max]  # \"Maximum enabled.\"\ncli.call            # Nothing happens.\n----\n\nSince `#call` expects an argument, you can use `call(+*+)` for the method signature to ignore all arguments since you don't need them.\n\n===== Arguments\n\nArguments inform {option_parser_link} how to parse values as either _optional_ or _required_. Here's a minimal implementation of an optional argument:\n\n[source,ruby]\n----\nclass Action \u003c Sod::Action\n  on %w[-e --echo], argument: \"[TEXT]\"\n\n  def call(text = nil) = puts \"Got: #{text}\"\nend\n\ncli = Sod.new { on Action }\n\ncli.call %w[-e]         # \"Got: \"\ncli.call %w[--echo]     # \"Got: \"\ncli.call %w[-e hi]      # \"Got: hi\"\ncli.call %w[--echo hi]  # \"Got: hi\"\n----\n\nThe method definition of `call(text = nil)` is important because if you call the action directly you'd want to have a safe default that mirrors the `on` macro. You could provide a non-nil default but we'll discuss this more later. You could also use a `call(text)` method definition since {option_parser_link} will always give you a value even if it is `nil`. You can see see how this behavior plays out in the examples above. On the flip side, when you need a _required_ argument, simply drop the brackets (i.e. `[]`). Here's an example:\n\n[source,ruby]\n----\nclass Action \u003c Sod::Action\n  on %w[-e --echo], argument: \"TEXT\"\n\n  def call(text) = puts \"Got: #{text}\"\nend\n\ncli = Sod.new { on Action }\n\ncli.call %w[-e]         # \"🛑 Missing argument: -e\"\ncli.call %w[--echo]     # \"🛑 Missing argument: --echo\"\ncli.call %w[-e hi]      # \"Got: hi\"\ncli.call %w[--echo hi]  # \"Got: hi\"\n----\n\nThere are three major differences between a _required_ and _optional_ argument:\n\n* The argument is required because it's not wrapped in brackets.\n* The method definition requires a parameter (i.e. `text` in the above example).\n* You get an error when not providing an argument.\n\n===== Types\n\nTypes are optional but worth having when you need the safety check. Here's a minimal example:\n\n[source,ruby]\n----\nclass Action \u003c Sod::Action\n  on %w[-e --echo], argument: \"NUMBER\", type: Float\n\n  def call(number) = puts \"Got: #{number}\"\nend\n\ncli = Sod.new { on Action }\n\ncli.call %w[--echo 123]   # \"Got: 123.0\"\ncli.call %w[--echo 1.5]   # \"Got: 1.5\"\ncli.call %w[--echo hi]  # 🛑 Invalid argument: --echo hi\n----\n\nNotice the type is a `Float` where only the first two examples work but the last one ends in an error because {option_parser_link} can't cast the raw input to a float.\n\n===== Allows\n\nAllows give you the ability to define what is acceptable as input and need to match your type (if you supply one). Here's a minimal example:\n\n[source,ruby]\n----\nclass Action \u003c Sod::Action\n  on %w[-e --echo], argument: \"TEXT\", allow: %w[hi hello]\n\n  def call(text) = puts \"Got: #{text}\"\nend\n\ncli = Sod.new { on Action }\n\ncli.call %w[--echo hi]     # \"Got: hi\"\ncli.call %w[--echo hello]  # \"Got: hello\"\ncli.call %w[--echo test]   # \"🛑 Invalid argument: --echo test\"\n----\n\nHere you can see the first two examples pass while the last one fails because `\"test\"` isn't a valid value within the allowed array.\n\n===== Defaults\n\nDefaults are not supported by {option_parser_link} but are handy for documentation purposes and within your implementation as fallback values. Here's a minimal example:\n\n[source,ruby]\n----\nclass Action \u003c Sod::Action\n  on %w[-e --echo], argument: \"[TEXT]\", default: \"fallback\"\n\n  def call(text = default) = puts \"Got: #{text}\"\nend\n\ncli = Sod.new { on Action }\n\ncli.call %w[--echo]     # \"Got: fallback\"\ncli.call %w[--echo hi]  # \"Got: hi\"\n----\n\nNotice how the default is printed when no value is given but is overwritten when an actual value is supplied.\n\n💡 If you need to lazy compute a default value, then use the block syntax instead.\n\n===== Examples\n\nThe following are a few more examples, in case it helps, with the first leveraging all features:\n\n[source,ruby]\n----\nclass Echo \u003c Sod::Action\n  description \"Echo input as output.\"\n\n  ancillary \"Supplementary text.\", \"Additional text.\"\n\n  on %w[-e --echo], argument: \"[TEXT]\", type: String, allow: %w[hello goodbye]\n\n  default { \"hello\" }\n\n  def call(text = default) = puts text\nend\n\ncli = Sod.new :demo, banner: \"Demo 0.0.0: A demonstration\" do\n  on Echo\n  on Sod::Prefabs::Actions::Help, self\nend\n----\n\nThis time, when we run the above implementation, we have additional details:\n\n[source,ruby]\n----\ncli.call\n\n# Demo 0.0.0: A demonstration\n#\n# USAGE\n#   demo [OPTIONS]\n#\n# OPTIONS\n#   -e, --echo [TEXT]        Echo input as output.\n#                            Supplementary text.\n#                            Additional text.\n#                            Use: hello or goodbye.\n#                            Default: hello.\n#   -h, --help [COMMAND]     Show this message.\n\ncli.call [\"--echo\"]\n\n# hello\n\ncli.call %w[--echo goodbye]\n\n# goodbye\n\ncli.call %w[--echo hi]\n\n# 🛑 Invalid argument: --echo hi\n----\n\nNotice how the help text is more verbose. Not only do you see the description for the `--echo` action printed but you also see the two ancillary lines, documentation on what is allowed (i.e. you can only use \"hello\" or \"goodbye\"), and what the default will be (i.e. \"hello\") when `--echo` doesn't get an argument since it's optional. This is why you can see `--echo` can be called with nothing, an allowed value, or an value that isn't allowed which causes an _invalid argument_ error to show up.\n\nLastly, your action's `#call` method _must_ be implemented. Otherwise, you'll get an exception as show here:\n\n[source,ruby]\n----\nclass Echo \u003c Sod::Action\n  description \"Echo input as output.\"\n  on %w[-e --echo]\nend\n\ncli = Sod.new :demo, banner: \"Demo 0.0.0: A demonstration\" do\n  on Echo\n  on Sod::Prefabs::Actions::Help, self\nend\n\ncli.call [\"--echo\"]\n\n# `Echo#call [[:rest, :*]]` must be implemented. (NoMethodError)\n----\n\nAt a minimum, your `#call` method needs to allow the forwarding of positional arguments which means you can use `def call(*)` if you want to ignore arguments or define which arguments you care about and ignore the rest. Up to you. Also, _all_ of the information defined within your action is available to you within the instance. Here's an example action which inspects itself:\n\n[source,ruby]\n----\nclass Echo \u003c Sod::Action\n  description \"Echo input as output.\"\n\n  ancillary \"Supplementary.\"\n\n  on \"--inspect\", argument: \"[TEXT]\", type: String, allow: %w[one two], default: \"A default.\"\n\n  def call(*)\n    puts handle:, aliases:, argument:, type:, allow:, default:, description:, ancillary:\n  end\nend\n\ncli = Sod.new :demo, banner: \"Demo 0.0.0: A demonstration\" do\n  on Echo\n  on Sod::Prefabs::Actions::Help, self\nend\n\ncli.call [\"--inspect\"]\n\n# {\n#   :handle =\u003e \"--inspect [TEXT]\",\n#   :aliases =\u003e [\"--inspect\"],\n#   :argument =\u003e \"[TEXT]\",\n#   :type =\u003e String,\n#   :allow =\u003e [\"one\", \"two\"],\n#   :default =\u003e \"A default.\",\n#   :description =\u003e \"Echo input as output.\",\n#   :ancillary =\u003e [\"Supplementary.\"]\n# }\n----\n\nAlthough, not shown in the above, the `#to_a` and `#to_h` methods are available as well.\n\n==== Commands\n\nCommands are a step up from actions in that they allow you to organize and group your actions while giving you the ability to process the data parsed by your actions. If it helps, a command mimics {option_parser_link} behavior when you initialize and define multiple, actionable, blocks. Here's an example which maps the terminology of this gem with that of {option_parser_link}:\n\n[source,ruby]\n----\n#! /usr/bin/env ruby\n# frozen_string_literal: true\n\n# Save as `snippet`, then `chmod 755 snippet`, and run as `./snippet`.\n\nrequire \"optparse\"\n\ninput = {}\n\n# Command\nparser = OptionParser.new do |instance|\n  # Actions\n  instance.on(\"--[no-]one\", \"One.\") { |value| input[:one] = value }\n  instance.on(\"--[no-]two\", \"Two.\") { |value| input[:two] = value }\nend\n\nparser.parse [\"--one\", \"--no-two\"]\nputs input\n\n# {:one=\u003etrue, :two=\u003efalse}\n----\n\nThe equivalent of the above, as provided by this gem, is:\n\n[source,ruby]\n----\n#! /usr/bin/env ruby\n# frozen_string_literal: true\n\n# Save as `snippet`, then `chmod 755 snippet`, and run as `./snippet`.\n\nrequire \"bundler/inline\"\n\ngemfile true do\n  source \"https://rubygems.org\"\n  gem \"sod\"\nend\n\nclass One \u003c Sod::Action\n  on \"--[no-]one\", description: \"One.\"\n\n  def call(value) = context.input[:one] = value\nend\n\nclass Two \u003c Sod::Action\n  on \"--[no-]two\", description: \"Two.\"\n\n  def call(value) = context.input[:two] = value\nend\n\nclass Demo \u003c Sod::Command\n  handle \"demo\"\n\n  description \"A demonstration command.\"\n\n  on One\n  on Two\n\n  def call = puts context.input\nend\n\ncontext = Sod::Context[input: {}]\n\ncli = Sod.new banner: \"Demo 0.0.0: A demonstration\" do\n  on(Demo, context:)\n  on Sod::Prefabs::Actions::Help, self\nend\n\ncli.call [\"demo\", \"--one\", \"--no-two\"]\n\n# {:one =\u003e true, :two =\u003e false}\n----\n\nYou might be thinking: \"Hey, that's more lines of code!\" True but -- more importantly -- you get the benefit of composable and reusable architectures -- because each command/action is encapsulated -- which you don't get with {option_parser_link}. You'll also notice that the `input` hash is mutated. The fact that you have to mutate input is a bummer and you should strive to avoid mutation whenever you can. In this case, mutation is necessary because the underlining architecture of the {option_parser_link} doesn't provide any other way to share state amongst your commands and actions. So this is one example of how you can do that.\n\nAs mentioned earlier with actions, commands share a similar DSL with a few differences in terms of macros:\n\n* `handle`: Required. The name of your command or the _namespace_ for which you group multiple actions. Must be a string. Otherwise, if not defined, you'll get a `Sod::Error`.\n* `description`: Optional (but strongly recommended). Defines what your command is about and shows up in the help documentation. Otherwise, if not provided, only your command's handle will be shown.\n* `ancillary`: Optional. Allows you to provide supplemental text for your description. Can accept single or multiple arguments. Order matters since each argument will appear on a separate line in the order listed below your description.\n* `on`: Required. The syntax for this is identical to the CLI DSL where you define your action (constant) as the first positional argument followed by any number of positional and/or keyword arguments that you want to feed into your action when the `.new` method is called.\n\nIf we reuse the above example and print the help documentation, you'll see the following output:\n\n[source,ruby]\n----\ncli.call\n\n# Demo 0.0.0: A demonstration\n#\n# USAGE\n#   demo [OPTIONS]\n#   demo COMMAND [OPTIONS]\n#\n# OPTIONS\n#   -h, --help [COMMAND]     Show this message.\n#\n# COMMANDS\n#   demo                     A demonstration command.\n----\n\n...and if we display help on the `demo` command itself, we'll see all of it's capabilities:\n\n[source,ruby]\n----\ncli.call [\"demo\"]\n\n# A demonstration command.\n#\n# USAGE\n#   demo [OPTIONS]\n#\n# OPTIONS\n#   --[no-]one\n#   --[no-]two\n----\n\nCommands come in two forms: inline and reusable. You've already seen how reusable commands work but the next sections will go into more detail.\n\n===== Inline\n\nInline commands provide a lightweight way to namespace your actions when you don't need, or want, to implement a _reusable_ command. If we refactor the earlier example to use inline commands, here's what it would look like:\n\n[source,ruby]\n----\ncli = Sod.new banner: \"Demo 0.0.0: A demonstration\" do\n  on \"demo\", \"A demonstration command.\" do\n    on One\n    on Two\n  end\n\n  on Sod::Prefabs::Actions::Help, self\nend\n----\n\nInline commands can have ancillary text by passing in additional arguments _after_ the description. Example:\n\n[source,ruby]\n----\ncli = Sod.new banner: \"Demo 0.0.0: A demonstration\" do\n  on \"demo\", \"A demonstration command.\", \"Some text.\", \"Some more text.\"\nend\n----\n\nWhile the above is convenient, it can get out of control quickly. If this happens, please consider taking your _inline_ command and turning it into a _reusable_ command so your implementation remains organized and readable.\n\nThere is no limit on how deep you can go with nesting but if you are using anything beyond one or two levels of nesting then you should reconsider your design as your CLI is getting too complicated.\n\n===== Reusable\n\nA _reusable_ command is what you saw earlier where you can subclass from `Sod::Command` to implement your custom command. Here's the code again:\n\n[source,ruby]\n----\nclass Demo \u003c Sod::Command\n  handle \"demo\"\n\n  description \"A demonstration command.\"\n\n  ancillary \"Some text.\", \"Some more text.\"\n\n  on One\n  on Two\n\n  def call = puts \"Your implementation goes here.\"\nend\n----\n\nOne major difference between _reusable_ and _inline_ commands is that _reusable_ commands allow you implement a `#call` method. This method is optional, so if you don't need it, you don't have to implement it. However, if you do, this means you can process the input from your actions. This method is called _after_ the option parser has parsed all command line input for your actions which gives you a handy way to process all collected input via a single command.\n\n💡 This is how the {rubysmith_link}, {gemsmith_link}, and {hanamismith_link} gems all build new Ruby projects for you based on the actions passed to them via the CLI.\n\n==== Initialization\n\nIn all the action and command examples, thus far, we've not used an initializer. You can always customize how your command or action is initialized by defining one and forwarding all keyword arguments to `super`. Here's an example for both an action and a command:\n\n[source,ruby]\n----\nclass MyAction \u003c Sod::Action\n  def initialize(processor: Processor.new, **)\n    super(**)\n    @processor = processor\n  end\nend\n\nclass MyCommand \u003c Sod::Command\n  def initialize(handler: Handler.new, **)\n    super(**)\n    @handler = handler\n  end\nend\n----\n\nThe reason you need to forward keyword arguments to `super` is so that injected dependencies from the super class are always available to you. Especially, contexts, which are explained next.\n\n==== Contexts\n\nContexts are a mechanism for passing common data between your commands and actions with override capability if desired. They are a hybrid between a `Hash` and a `Struct`. They can be constructed two ways depending on your preference:\n\n[source,ruby]\n----\n# Traditional\ncontext = Sod::Context.new defaults_path: \"path/to/defaults.yml\", version_label: \"Demo 0.0.0\"\n\n# Short (like Struct or Data)\ncontext = Sod::Context[defaults_path: \"path/to/defaults.yml\", version_label: \"Demo 0.0.0\"]\n----\n\nOnce you have an instance, you can use as follows:\n\n[source,ruby]\n----\n# Direct\ncontext.defaults_path               # \"path/to/defaults.yml\"\n\n# With override.\ncontext[\"my/path\", :defaults_path]  # \"my/path\"\n----\n\nThe override is handy for situations where you have a value (first argument) that you would prefer to use while still being able to fallback to the `:defaults_path` if the override is `nil`. When you put all of this together, this means you can build a single context and use it within your commands and actions by injecting it:\n\n[source,ruby]\n----\ncontext = Sod::Context[defaults_path: \"path/to/defaults.yml\" version_label: \"Demo 0.0.0\"]\n\nSod.new banner: \"A demonstration.\" do\n  on(Sod::Prefabs::Commands::Config, context:)\n  on(Sod::Prefabs::Actions::Version, context:)\n  on Sod::Prefabs::Actions::Help, self\nend\n----\n\n💡 When passing a context to a command, it'll automatically be passed to all actions defined within that command. Each action can then choose to use the context or not.\n\n==== Types\n\nTypes are a way to extend default {option_parser_link} functionality. Here are a few types -- not provided by {option_parser_link} -- worth knowing about:\n\n===== Pathname\n\nProvided by this gem and must be manually required since it's disabled by default. Example:\n\n[source,ruby]\n----\nrequire \"sod\"\nrequire \"sod/types/pathname\"\n\nclass Demo \u003c Sod::Action\n  on \"--path\", argument: \"PATH\", type: Pathname\nend\n----\n\nWith the above, you'll always get a link:https://rubyapi.org/o/s?q=Pathname[Pathname] instance as input to your action.\n\n===== Version\n\nProvided via the {versionaire_link} gem which gives you a `Version` type when dealing with link:https://semver.org[semantic versions]. Here's how to leverage it:\n\n[source,ruby]\n----\nrequire \"versionaire\"\nrequire \"versionaire/extensions/option_parser\"\n\nclass Demo \u003c Sod::Action\n  on \"--version\", argument: \"VERSION\", type: Versionaire::Version\nend\n----\n\n===== Custom\n\nCreating a custom type requires minimal effort and can be implemented in only a few files:\n\n[source,ruby]\n----\n# lib/my_type.rb\n\nMyType = -\u003e value { # Implementation details go here. }\n----\n\n[source,ruby]\n----\n# lib/extensions/option_parser.rb\nrequire \"optparse\"\n\nOptionParser.accept(MyType) { |value| MyType.call value }\n----\n\nOnce you've implemented a custom type, you are then free to require and reference it within the DSL.\n\n==== Prefabrications\n\nSeveral pre-built commands and actions are provided for you as foundational tooling to get you up and running quickly. You can use and customize them as desired.\n\n===== Configure\n\nThe configure command -- and associated actions -- allows you to interact with CLI configurations such as those managed by the {xdg_link}, {runcom_link}, and/or {etcher_link} gems which adhere to the XDG Directory Specification. Example:\n\n[source,ruby]\n----\nrequire \"runcom\"\n\ncontext = Sod::Context[\n  defaults_path: \"defaults.yml\",\n  xdg_config: Runcom::Config.new(\"demo/configuration.yml\")\n]\n\ncli = Sod.new :rubysmith, banner: \"Demo 0.0.0: A demonstration.\" do\n  on(Sod::Prefabs::Commands::Config, context:)\n  on Sod::Prefabs::Actions::Help, self\nend\n\ncli.call [\"config\"]\n\n# Manage configuration.\n#\n# USAGE\n#   config [OPTIONS]\n#\n# OPTIONS\n#   -c, --create     Create default configuration.\n#                    Prompts for local or global path.\n#   -e, --edit       Edit project configuration.\n#   -v, --view       View project configuration.\n#   -d, --delete     Delete project configuration.\n#                    Prompts for confirmation.\n----\n\nThis action is most useful when building customizable CLIs where you want users of your CLI to have the flexibility of customizing their preferences.\n\n===== Help\n\nBy now you should be familiar with the help action which allows you to print CLI documentation for users of your CLI. This action consumes the entire graph (i.e. `self`) of information in order to render documentation. You'll want to add this by default or customize with your own help action should you not like the default functionality. Anything is possible. Here's some usage:\n\n[source,ruby]\n----\ncli = Sod.new :demo, banner: \"Demo 0.0.0: A demonstration.\" do\n  on Sod::Prefabs::Actions::Help, self\nend\n\ncli.call\ncli.call [\"-h\"]\ncli.call [\"--help\"]\ncli.call [\"--help\", \"some_command\"]\n----\n\n💡 Passing `-h` or `--help` is optional since the CLI will default to printing help if only given a command.\n\n===== Version\n\nThe version action allows users to check which version of your CLI they are using and only requires supplying version information when creating the action:\n\n[source,ruby]\n----\ncli = Sod.new :demo, banner: \"Demo 0.0.0: A demonstration.\" do\n  on Sod::Prefabs::Actions::Version.new(\"Demo 0.0.0\")\nend\n\ncli.call [\"-v\"]         # Demo 0.0.0\ncli.call [\"--version\"]  # Demo 0.0.0\n----\n\n💡 This pairs well with the {spek_link} gem which pulls this information straight from your `gemspec`.\n\n=== Examples\n\nHopefully the above is plenty of information to get you started but here are a few more examples in case it helps:\n\n==== Inline Script\n\nThe following demonstrates an link:https://alchemists.io/articles/ruby_bundler_inline[inline script] using commands and actions.\n\n[source,ruby]\n----\n#! /usr/bin/env ruby\n# frozen_string_literal: true\n\n# Save as `demo`, then `chmod 755 demo`, and run as `./demo`.\n\nrequire \"bundler/inline\"\n\ngemfile true do\n  source \"https://rubygems.org\"\n\n  gem \"amazing_print\"\n  gem \"debug\"\n  gem \"sod\"\nend\n\nclass Start \u003c Sod::Action\n  include Sod::Dependencies[:logger]\n\n  description \"Start database.\"\n\n  on \"--start\"\n\n  def call(*) = logger.info { \"Starting database...\" }\nend\n\nclass Stop \u003c Sod::Action\n  include Sod::Dependencies[:logger]\n\n  description \"Stop database.\"\n\n  on \"--stop\"\n\n  def call(*) = logger.info { \"Stopping database...\" }\nend\n\nclass Echo \u003c Sod::Action\n  include Sod::Dependencies[:io]\n\n  description \"Echo input as output.\"\n\n  on %w[-e --echo], argument: \"TEXT\"\n\n  def call(text) = io.puts text\nend\n\ncli = Sod.new :demo, banner: \"Demo 0.0.0: A demonstration.\" do\n  on \"db\", \"Manage database.\" do\n    on Start\n    on Stop\n  end\n\n  on Sod::Prefabs::Actions::Version, \"Demo 0.0.0\"\n  on Sod::Prefabs::Actions::Help, self\nend\n----\n\nOnce you've saved the above to your local disk, you can experiment with it by passing different command line arguments to it:\n\n[source,bash]\n----\n./demo\n\n# Demo 0.0.0: A demonstration.\n#\n# USAGE\n#   demo [OPTIONS]\n#   demo COMMAND [OPTIONS]\n#\n# OPTIONS\n#   -v, --version            Show version.\n#   -h, --help [COMMAND]     Show this message.\n#\n# COMMANDS\n#   db                       Manage database.\n\n./demo db\n\n# Manage database.\n#\n# USAGE\n#   db [OPTIONS]\n#\n# OPTIONS\n#   --start     Start database.\n#   --stop      Stop database.\n\n./demo db --start\n# 🟢 Starting database...\n\n./demo db --stop\n# 🟢 Stopping database...\n\n./demo --version\n# Demo 0.0.0\n----\n\n==== Gems\n\nThe following gems are built atop Sod and you can study the `CLI` namespace each or use the {gemsmith_link} gem to generate a CLI template project with all of this baked in for you. Here's the list:\n\n* {gemsmith_link}\n* {git-lint_link}\n* {hanamismith_link}\n* {milestoner_link}\n* {pennyworth_link}\n* {pragmater_link}\n* {rubysmith_link}\n* {sublime_text_kit_link}\n* {tocer_link}\n\n== Development\n\nTo contribute, run:\n\n[source,bash]\n----\ngit clone https://github.com/bkuhlmann/sod\ncd sod\nbin/setup\n----\n\nYou can also use the IRB console for direct access to all objects:\n\n[source,bash]\n----\nbin/console\n----\n\n=== Architecture\n\nThe architecture of this gem is built entirely around {option_parser_link} by using a graph of nodes (i.e. commands) which can be walked since each node within the graph may or may not have children (i.e. nesting).\n\nimage::https://alchemists.io/images/projects/sod/doc/architecture.svg[Architecture Diagram]\n\n== Tests\n\nTo test, run:\n\n[source,bash]\n----\nbin/rake\n----\n\n== link:https://alchemists.io/policies/license[License]\n\n== link:https://alchemists.io/policies/security[Security]\n\n== link:https://alchemists.io/policies/code_of_conduct[Code of Conduct]\n\n== link:https://alchemists.io/policies/contributions[Contributions]\n\n== link:https://alchemists.io/policies/developer_certificate_of_origin[Developer Certificate of Origin]\n\n== link:https://alchemists.io/projects/sod/versions[Versions]\n\n== link:https://alchemists.io/community[Community]\n\n== Credits\n\n* Built with link:https://alchemists.io/projects/gemsmith[Gemsmith].\n* Engineered by link:https://alchemists.io/team/brooke_kuhlmann[Brooke Kuhlmann].\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbkuhlmann%2Fsod","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbkuhlmann%2Fsod","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbkuhlmann%2Fsod/lists"}