├── .github └── workflows │ ├── publish.yml │ └── test.yml ├── .gitignore ├── .tool-versions ├── LICENSE ├── README.md ├── gleam.toml ├── manifest.toml ├── publish.sh ├── src ├── outil.gleam ├── outil │ ├── arg.gleam │ ├── error.gleam │ ├── help.gleam │ └── opt.gleam └── outil_ffi.mjs └── test └── outil_test.gleam /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish to hex.pm 2 | 3 | on: 4 | push: 5 | tags: 6 | - 'v[0-9]+.[0-9]+.[0-9]+' 7 | 8 | jobs: 9 | push-hex: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v3.2.0 13 | - uses: erlef/setup-beam@v1.16.0 14 | with: 15 | version-type: strict 16 | version-file: ".tool-versions" 17 | - run: ./publish.sh 18 | env: 19 | HEXPM_USER: ${{ secrets.HEXPM_USER }} 20 | HEXPM_PASS: ${{ secrets.HEXPM_PASS }} 21 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | - main 8 | pull_request: 9 | 10 | jobs: 11 | test: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v3.2.0 15 | - uses: erlef/setup-beam@v1.16.0 16 | with: 17 | version-type: strict 18 | version-file: ".tool-versions" 19 | - run: gleam format --check src test 20 | - run: gleam deps download 21 | - run: gleam build --warnings-as-errors 22 | - run: gleam test 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.beam 2 | *.ez 3 | build 4 | erl_crash.dump 5 | -------------------------------------------------------------------------------- /.tool-versions: -------------------------------------------------------------------------------- 1 | erlang 26.1.2 2 | gleam 0.32.4 3 | rebar 3.22.1 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # outil 2 | 3 | [![Package Version](https://img.shields.io/hexpm/v/outil)](https://hex.pm/packages/outil) 4 | [![Hex Docs](https://img.shields.io/badge/hex-docs-ffaff3)](https://hexdocs.pm/outil/) 5 | 6 | A library for writing command line tools. Like so: 7 | 8 | ```gleam 9 | import gleam/erlang 10 | import gleam/io 11 | import gleam/list 12 | import gleam/result 13 | import gleam/string 14 | import outil.{command, print_usage_and_exit} 15 | import outil/arg 16 | import outil/opt 17 | 18 | fn say_hello(args) { 19 | use cmd <- command("hello", "Say hello to someone", args) 20 | use name, cmd <- arg.string(cmd, "name") 21 | use enthusiasm, cmd <- opt.int(cmd, "enthusiasm", "How enthusiastic?", 1) 22 | 23 | use name <- name(cmd) 24 | use enthusiasm <- enthusiasm(cmd) 25 | 26 | let message = "Hello, " <> name <> string.repeat("!", enthusiasm) 27 | 28 | Ok(io.println(message)) 29 | } 30 | 31 | pub fn main() { 32 | // Erlang is not required, this example just uses it for getting ARGV 33 | let args = erlang.start_arguments() 34 | 35 | say_hello(args) 36 | |> result.map_error(print_usage_and_exit) 37 | } 38 | ``` 39 | 40 | If you don't fancy this style of programming, check out [glint] or [Awesome Gleam] for alternatives. 41 | 42 | Outil is not going to have many cool features for building comprehensive command line 43 | interfaces. It is meant to fit simple programs with simple needs. 44 | 45 | [glint]: https://github.com/tanklesxl/glint 46 | [Awesome Gleam]: https://github.com/gleam-lang/awesome-gleam#cli 47 | 48 | ## Quick start 49 | 50 | ```sh 51 | gleam run # Run the project 52 | gleam test # Run the tests 53 | gleam shell # Run an Erlang shell 54 | ``` 55 | 56 | ## Installation 57 | 58 | Outil is available on Hex and can be added to your Gleam project like so: 59 | 60 | ```sh 61 | gleam add outil 62 | ``` 63 | 64 | and its documentation can be found at . 65 | 66 | ## Changelog 67 | 68 | ### 0.5.0 69 | 70 | * Adapted for Gleam 0.32. 71 | 72 | ### 0.4.0 73 | 74 | * Adapted to Gleam 0.27, so no more try syntax. 75 | * BREAKING -- API change to let library users use use without result.then wrapping. 76 | 77 | ### 0.3.3 78 | 79 | * Made `--help` show itself in the output. 80 | * Made the usage text present the command line error that caused it to be shown. 81 | 82 | ### 0.3.2 83 | 84 | * Fixed a bug where the automatic `--help` flag didn't react unless the command had positional arguments. 85 | 86 | ### 0.3.1 87 | 88 | * Added convenience helpers print_usage and print_usage_and_exit for handling command errors. 89 | 90 | ### 0.3.0 91 | 92 | * Expanded the return type of commands to include a way for the command code itself to return errors. 93 | * **BREAKING** Some types were renamed to support the above, and be more clear. 94 | 95 | ### 0.2.1 96 | 97 | * Fixed some docs. 98 | 99 | ### 0.2.0 100 | 101 | * **BREAKING** Simplified command implementation. The function is the command now, it no longer returns a `Command` value. 102 | 103 | ### 0.1.0 104 | 105 | * Hello world! 106 | * Something kind of working. 107 | -------------------------------------------------------------------------------- /gleam.toml: -------------------------------------------------------------------------------- 1 | name = "outil" 2 | version = "0.5.0" 3 | description = "A Gleam library for writing command line tools." 4 | licences = ["Apache-2.0"] 5 | repository = { type = "github", user = "fabjan", repo = "outil" } 6 | gleam = ">= 0.32.0" 7 | 8 | [dependencies] 9 | gleam_stdlib = "~> 0.32" 10 | 11 | [dev-dependencies] 12 | gleeunit = "~> 1.0" 13 | -------------------------------------------------------------------------------- /manifest.toml: -------------------------------------------------------------------------------- 1 | # This file was generated by Gleam 2 | # You typically do not need to edit this file 3 | 4 | packages = [ 5 | { name = "gleam_stdlib", version = "0.32.1", build_tools = ["gleam"], requirements = [], otp_app = "gleam_stdlib", source = "hex", outer_checksum = "ABF00CDCCB66FABBCE351A50060964C4ACE798F95A0D78622C8A7DC838792577" }, 6 | { name = "gleeunit", version = "1.0.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleeunit", source = "hex", outer_checksum = "D3682ED8C5F9CAE1C928F2506DE91625588CC752495988CBE0F5653A42A6F334" }, 7 | ] 8 | 9 | [requirements] 10 | gleam_stdlib = { version = "~> 0.32" } 11 | gleeunit = { version = "~> 1.0" } 12 | -------------------------------------------------------------------------------- /publish.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh 2 | 3 | tag_version=$(git tag --points-at HEAD | cut -c 2-) 4 | 5 | if [ -z "$tag_version" ]; then 6 | echo "No tag found at HEAD. Aborting." 7 | exit 1 8 | fi 9 | 10 | package_version=$(grep version gleam.toml | cut -d '"' -f 2) 11 | 12 | if [ "$tag_version" != "$package_version" ]; then 13 | echo "Tag version ($tag_version) does not match package version ($package_version). Aborting." 14 | exit 1 15 | fi 16 | 17 | gleam publish --yes 18 | -------------------------------------------------------------------------------- /src/outil.gleam: -------------------------------------------------------------------------------- 1 | import gleam/io 2 | import gleam/option.{type Option} 3 | import outil/error.{type Reason} 4 | 5 | /// Create a command with the given name and description, and pass it to the 6 | /// given continuation function for further configuration. 7 | /// 8 | /// The command gets a default implementation that returns an error. 9 | pub fn command( 10 | name: String, 11 | description: String, 12 | argv: List(String), 13 | continue: fn(Command) -> a, 14 | ) -> a { 15 | continue(Command(name, description, [], [], argv)) 16 | } 17 | 18 | /// Convenience function for handling the result of executing a command. 19 | /// 20 | /// Print usage if there was a command line error or if the user asked for it. 21 | /// 22 | /// Does nothing if the command returned an application error, assuming that 23 | /// the application will handle it. 24 | pub fn print_usage(return) { 25 | case return { 26 | CommandLineError(_, usage) -> io.println(usage) 27 | Help(usage) -> io.println(usage) 28 | _ -> Nil 29 | } 30 | } 31 | 32 | /// Convenience function for handling the result of executing a command. 33 | /// 34 | /// Print usage if there was a command line error or if the user asked for it. 35 | /// 36 | /// Exit with 2 if there was a command line error, 1 if there was a command 37 | /// error, or 0 if the command was successful. 38 | pub fn print_usage_and_exit(return) { 39 | print_usage(return) 40 | case return { 41 | CommandLineError(_, _) -> halt_program(2) 42 | CommandError(_) -> halt_program(1) 43 | Help(_) -> halt_program(0) 44 | } 45 | } 46 | 47 | /// A command line interface to a run function. 48 | pub type Command { 49 | Command( 50 | name: String, 51 | description: String, 52 | arguments: List(Argument), 53 | options: List(Opt), 54 | argv: List(String), 55 | ) 56 | } 57 | 58 | /// A positional command line argument. 59 | pub type Argument { 60 | BoolArgument(name: String) 61 | FloatArgument(name: String) 62 | IntArgument(name: String) 63 | StringArgument(name: String) 64 | } 65 | 66 | /// A command line option/flag. 67 | pub type Opt { 68 | Opt(long: String, short: Option(String), description: String, value: OptValue) 69 | } 70 | 71 | /// The type and default value of an option. 72 | pub type OptValue { 73 | BoolOpt 74 | FloatOpt(default: Float) 75 | IntOpt(default: Int) 76 | StringOpt(default: String) 77 | } 78 | 79 | /// Non-normal return values from executing a command. 80 | pub type CommandReturn(a) { 81 | /// An error in parsing the command line. 82 | CommandLineError(reason: Reason, usage: String) 83 | /// An error in executing the command, `a` is your error value. 84 | CommandError(a) 85 | /// The user asked for help. 86 | Help(usage: String) 87 | } 88 | 89 | /// The result of executing a command. 90 | pub type CommandResult(a, b) = 91 | Result(a, CommandReturn(b)) 92 | 93 | /// Parse a Bool from a string. 94 | pub fn parse_bool(arg: String) -> Result(Bool, Nil) { 95 | case arg { 96 | "true" -> Ok(True) 97 | "false" -> Ok(False) 98 | _ -> Error(Nil) 99 | } 100 | } 101 | 102 | @external(erlang, "erlang", "halt") 103 | @external(javascript, "./outil_ffi.mjs", "exit") 104 | fn halt_program(code: Int) -> Nil 105 | -------------------------------------------------------------------------------- /src/outil/arg.gleam: -------------------------------------------------------------------------------- 1 | import gleam/float 2 | import gleam/int 3 | import gleam/list 4 | import gleam/result 5 | import outil.{ 6 | type Argument, type Command, type CommandReturn, BoolArgument, Command, 7 | FloatArgument, IntArgument, StringArgument, parse_bool, 8 | } 9 | import outil/error.{ 10 | type Reason, MalformedArgument, MissingArgument, OutOfPlaceOption, 11 | } 12 | import outil/help 13 | 14 | /// Add a positional bool argument to the command before continuing. 15 | pub fn bool(cmd: Command, name: String, continue) { 16 | with_positional_argument(cmd, BoolArgument(name), parse_bool, continue) 17 | } 18 | 19 | /// Add a positional float argument to the command before continuing. 20 | pub fn float(cmd: Command, name: String, continue) { 21 | with_positional_argument(cmd, FloatArgument(name), float.parse, continue) 22 | } 23 | 24 | /// Add a positional int argument to the command before continuing. 25 | pub fn int(cmd: Command, name: String, continue) { 26 | with_positional_argument(cmd, IntArgument(name), int.parse, continue) 27 | } 28 | 29 | /// Add a positional string argument to the command before continuing. 30 | pub fn string(cmd: Command, name: String, continue) { 31 | with_positional_argument(cmd, StringArgument(name), Ok, continue) 32 | } 33 | 34 | /// Add a positional argument to the command. 35 | /// 36 | /// The continuation function gets a parser for the argument and the command 37 | /// with the argument added, for further configuration. 38 | fn with_positional_argument( 39 | cmd: Command, 40 | argument: Argument, 41 | parse: fn(String) -> Result(a, Nil), 42 | continue, 43 | ) { 44 | let arg_pos = list.length(cmd.arguments) 45 | let arg_parser = positional_arg_parser(arg_pos, argument.name, parse) 46 | let arg_parser = fn( 47 | run_cmd: Command, 48 | and_then: fn(a) -> Result(b, CommandReturn(c)), 49 | ) { 50 | help.wrap_usage(run_cmd, arg_parser) 51 | |> result.then(and_then) 52 | } 53 | 54 | continue(arg_parser, append_argument(cmd, argument)) 55 | } 56 | 57 | fn append_argument(cmd: Command, arg: Argument) -> Command { 58 | Command( 59 | cmd.name, 60 | cmd.description, 61 | list.append(cmd.arguments, [arg]), 62 | cmd.options, 63 | cmd.argv, 64 | ) 65 | } 66 | 67 | fn positional_arg_parser( 68 | at: Int, 69 | name: String, 70 | parser: fn(String) -> Result(a, Nil), 71 | ) -> fn(List(String)) -> Result(a, Reason) { 72 | fn(args: List(String)) { 73 | case list.at(args, at) { 74 | Error(_) -> Error(MissingArgument(name)) 75 | Ok(arg) -> 76 | case arg { 77 | "-" <> _ -> Error(OutOfPlaceOption(arg)) 78 | _ -> 79 | parser(arg) 80 | |> result.map_error(fn(_) { MalformedArgument(name, arg) }) 81 | } 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/outil/error.gleam: -------------------------------------------------------------------------------- 1 | /// Errors that can occur when parsing command line arguments. 2 | pub type Reason { 3 | MalformedArgument(String, String) 4 | MissingArgument(String) 5 | OutOfPlaceOption(String) 6 | } 7 | -------------------------------------------------------------------------------- /src/outil/help.gleam: -------------------------------------------------------------------------------- 1 | import gleam/float 2 | import gleam/int 3 | import gleam/list 4 | import gleam/option.{type Option, None, Some} 5 | import gleam/result 6 | import gleam/string 7 | import outil.{ 8 | type Command, type CommandResult, type Opt, type OptValue, BoolOpt, 9 | CommandLineError, FloatOpt, Help, IntOpt, Opt, StringOpt, 10 | } 11 | import outil/error.{type Reason} 12 | 13 | /// A function using the command line arguments which can return command error reasons. 14 | pub type UseArgs(a) = 15 | fn(List(String)) -> Result(a, Reason) 16 | 17 | /// Given a command, if the command line arguments contain `--help` or `-h` 18 | /// then return a help "error" with the usage string. 19 | /// Otherwise, pass the arguments to the given function and if it returns an 20 | /// error, wrap it in a `CommandLineError` with the usage string. 21 | pub fn wrap_usage(cmd: Command, continue: UseArgs(a)) -> CommandResult(a, _) { 22 | let argv_contains = fn(s) { list.contains(cmd.argv, s) } 23 | 24 | use args <- result.then(case argv_contains("--help") || argv_contains("-h") { 25 | True -> Error(Help(usage(cmd, None))) 26 | False -> Ok(cmd.argv) 27 | }) 28 | 29 | continue(args) 30 | |> result.map_error(fn(reason) { 31 | let err_desc = case reason { 32 | error.MissingArgument(opt) -> "Missing argument for option: " <> opt 33 | error.MalformedArgument(opt, value) -> 34 | "Malformed argument for option: " <> opt <> " (" <> value <> ")" 35 | error.OutOfPlaceOption(opt) -> "Out of place option: " <> opt 36 | } 37 | CommandLineError(reason, usage(cmd, Some(err_desc))) 38 | }) 39 | } 40 | 41 | fn usage(cmd: Command, err_desc: Option(String)) -> String { 42 | let args = 43 | cmd.arguments 44 | |> list.map(fn(arg) { "<" <> arg.name <> ">" }) 45 | |> string.join(" ") 46 | 47 | let args = case args { 48 | "" -> "" 49 | _ -> " " <> args 50 | } 51 | let usage = "\n\nUsage: " <> cmd.name <> args 52 | 53 | let opts = 54 | cmd.options 55 | |> list.map(describe_opt) 56 | |> list.map(fn(opt) { " " <> opt }) 57 | |> string.join("\n") 58 | 59 | let opts = 60 | "\n\nOptions:\n" <> opts <> "\n" <> " -h, --help Show this help text and exit." 61 | 62 | let desc = 63 | err_desc 64 | |> option.map(fn(desc) { "ERROR! " <> desc }) 65 | |> option.unwrap(cmd.description) 66 | 67 | cmd.name <> " -- " <> desc <> usage <> opts 68 | } 69 | 70 | fn describe_opt(opt: Opt) { 71 | let Opt(long, short, desc, value) = opt 72 | let short = option.map(short, fn(s) { "-" <> s <> ", " }) 73 | let short = option.unwrap(short, "") 74 | let long = "--" <> long 75 | let typ = opt_type(value) 76 | let default = show_default(value) 77 | let meta = "(" <> typ <> ", default: " <> default <> ")" 78 | 79 | short <> long <> " " <> desc <> " " <> meta 80 | } 81 | 82 | fn opt_type(value: OptValue) -> String { 83 | case value { 84 | BoolOpt -> "bool" 85 | FloatOpt(_) -> "float" 86 | IntOpt(_) -> "int" 87 | StringOpt(_) -> "string" 88 | } 89 | } 90 | 91 | fn show_default(value: OptValue) { 92 | case value { 93 | BoolOpt -> "false" 94 | FloatOpt(default) -> float.to_string(default) 95 | IntOpt(default) -> int.to_string(default) 96 | StringOpt(default) -> "\"" <> default <> "\"" 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/outil/opt.gleam: -------------------------------------------------------------------------------- 1 | import gleam/float 2 | import gleam/int 3 | import gleam/list 4 | import gleam/option.{type Option, None, Some} 5 | import gleam/result 6 | import gleam/string 7 | import outil.{ 8 | type Command, type Opt, BoolOpt, Command, FloatOpt, IntOpt, Opt, StringOpt, 9 | parse_bool, 10 | } 11 | import outil/error.{type Reason, MalformedArgument, MissingArgument} 12 | import outil/help 13 | 14 | /// Add a named bool option to the command before continuing. 15 | pub fn bool(cmd: Command, long: String, description: String, continue) { 16 | bool_(cmd, long, None, description, continue) 17 | } 18 | 19 | /// Add a bool option with a short name to the command before continuing. 20 | pub fn bool_( 21 | cmd: Command, 22 | long: String, 23 | short: Option(String), 24 | description: String, 25 | continue, 26 | ) { 27 | let opt = Opt(long, short, description, BoolOpt) 28 | let opt_parser = bool_opt_parser(long, short) 29 | let opt_parser = fn(run_cmd: Command, and_then) { 30 | help.wrap_usage(run_cmd, opt_parser) 31 | |> result.then(and_then) 32 | } 33 | 34 | continue(opt_parser, add_option(cmd, opt)) 35 | } 36 | 37 | /// Add a named float option to the command before continuing. 38 | pub fn float( 39 | cmd: Command, 40 | long: String, 41 | description: String, 42 | default: Float, 43 | continue, 44 | ) { 45 | float_(cmd, long, None, description, default, continue) 46 | } 47 | 48 | /// Add a float option with a short name to the command before continuing. 49 | pub fn float_( 50 | cmd: Command, 51 | long: String, 52 | short: Option(String), 53 | description: String, 54 | default: Float, 55 | continue, 56 | ) { 57 | let opt = Opt(long, short, description, FloatOpt(default)) 58 | 59 | with_named_option(cmd, opt, default, float.parse, continue) 60 | } 61 | 62 | /// Add a named int option to the command before continuing. 63 | pub fn int( 64 | cmd: Command, 65 | long: String, 66 | description: String, 67 | default: Int, 68 | continue, 69 | ) { 70 | int_(cmd, long, None, description, default, continue) 71 | } 72 | 73 | /// Add an int option with a short name to the command before continuing. 74 | pub fn int_( 75 | cmd: Command, 76 | long: String, 77 | short: Option(String), 78 | description: String, 79 | default: Int, 80 | continue, 81 | ) { 82 | let opt = Opt(long, short, description, IntOpt(default)) 83 | 84 | with_named_option(cmd, opt, default, int.parse, continue) 85 | } 86 | 87 | /// Add a named string option to the command before continuing. 88 | pub fn string( 89 | cmd: Command, 90 | long: String, 91 | description: String, 92 | default: String, 93 | continue, 94 | ) { 95 | string_(cmd, long, None, description, default, continue) 96 | } 97 | 98 | /// Add a string option with a short name to the command before continuing. 99 | pub fn string_( 100 | cmd: Command, 101 | long: String, 102 | short: Option(String), 103 | description: String, 104 | default: String, 105 | continue, 106 | ) { 107 | let opt = Opt(long, short, description, StringOpt(default)) 108 | 109 | with_named_option(cmd, opt, default, Ok, continue) 110 | } 111 | 112 | /// Add a named option to the command. Bring your own parser. 113 | /// 114 | /// The continuation function gets a parser for the option and the command 115 | /// with the option added, for further configuration. 116 | pub fn with_named_option( 117 | cmd: Command, 118 | opt: Opt, 119 | default: b, 120 | parse: fn(String) -> Result(b, Nil), 121 | continue, 122 | ) { 123 | let opt_parser = named_opt_parser(opt.long, opt.short, parse, default) 124 | let opt_parser = fn(run_cmd: Command, and_then) { 125 | help.wrap_usage(run_cmd, opt_parser) 126 | |> result.then(and_then) 127 | } 128 | 129 | continue(opt_parser, add_option(cmd, opt)) 130 | } 131 | 132 | fn add_option(cmd: Command, opt: Opt) -> Command { 133 | Command( 134 | cmd.name, 135 | cmd.description, 136 | cmd.arguments, 137 | list.append(cmd.options, [opt]), 138 | cmd.argv, 139 | ) 140 | } 141 | 142 | pub fn named_opt_parser( 143 | long: String, 144 | short: Option(String), 145 | parser: fn(String) -> Result(a, Nil), 146 | default: a, 147 | ) -> fn(List(String)) -> Result(a, Reason) { 148 | fn(args: List(String)) { 149 | case find(long, short, args) { 150 | #(None, _) -> Ok(default) 151 | #(Some(_), Some(arg)) -> 152 | parser(arg) 153 | |> result.map_error(fn(_) { MalformedArgument(long, arg) }) 154 | #(Some(_), None) -> Error(MissingArgument(long)) 155 | } 156 | } 157 | } 158 | 159 | // Bool opts are special because they can be specified without an argument. 160 | fn bool_opt_parser( 161 | long: String, 162 | short: Option(String), 163 | ) -> fn(List(String)) -> Result(Bool, Reason) { 164 | fn(args: List(String)) { 165 | let #(opt, arg) = find(long, short, args) 166 | 167 | case opt { 168 | None -> Ok(False) 169 | Some(_) -> 170 | case arg { 171 | None -> Ok(True) 172 | Some(arg) -> 173 | parse_bool(arg) 174 | |> result.map_error(fn(_) { MalformedArgument(long, arg) }) 175 | } 176 | } 177 | } 178 | } 179 | 180 | // Find an option named "--long" or "-short" in the list of arguments. 181 | // If the string contains an equals sign, the option has an argument. 182 | fn find( 183 | long: String, 184 | short: Option(String), 185 | args: List(String), 186 | ) -> #(Option(String), Option(String)) { 187 | let long_opt = "--" <> long 188 | let short_opt = 189 | short 190 | |> option.map(fn(s) { "-" <> s }) 191 | 192 | let opt = 193 | list.find( 194 | args, 195 | fn(arg) { 196 | let is_long = string.starts_with(arg, long_opt) 197 | let is_short = 198 | short_opt 199 | |> option.map(fn(s) { string.starts_with(arg, s) }) 200 | |> option.unwrap(False) 201 | is_long || is_short 202 | }, 203 | ) 204 | 205 | case opt { 206 | Error(_) -> #(None, None) 207 | Ok(opt) -> { 208 | let arg = 209 | string.split(opt, "=") 210 | |> list.at(1) 211 | 212 | #(Some(opt), option.from_result(arg)) 213 | } 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /src/outil_ffi.mjs: -------------------------------------------------------------------------------- 1 | export function exit(code) { 2 | if (globalThis.Deno) { 3 | return Deno.exit(code); 4 | } else { 5 | return process.exit(code); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /test/outil_test.gleam: -------------------------------------------------------------------------------- 1 | import gleam/option.{Some} 2 | import gleam/string 3 | import gleeunit 4 | import gleeunit/should 5 | import outil.{type CommandResult, CommandError, CommandLineError, Help, command} 6 | import outil/error.{MalformedArgument, MissingArgument} 7 | import outil/arg 8 | import outil/opt 9 | 10 | pub fn main() { 11 | gleeunit.main() 12 | } 13 | 14 | fn hello_cmd(args: List(String)) -> CommandResult(String, Nil) { 15 | use cmd <- command("hello", "Say hello to someone.", args) 16 | use name, cmd <- arg.string(cmd, "name") 17 | 18 | use enthusiasm, cmd <- opt.int(cmd, "enthusiasm", "How enthusiastic?", 1) 19 | use loudly, cmd <- opt.bool(cmd, "loudly", "Use all caps.") 20 | use name <- name(cmd) 21 | use enthusiasm <- enthusiasm(cmd) 22 | use loudly <- loudly(cmd) 23 | 24 | let message = "Hello, " <> name <> string.repeat("!", enthusiasm) 25 | 26 | let message = case loudly { 27 | True -> string.uppercase(message) 28 | False -> message 29 | } 30 | 31 | Ok(message) 32 | } 33 | 34 | type FruitBasket { 35 | FruitBasket( 36 | foo: Bool, 37 | bar: Float, 38 | baz: Int, 39 | qux: String, 40 | quux: Bool, 41 | corge: Float, 42 | grault: Int, 43 | garply: String, 44 | ) 45 | } 46 | 47 | fn the_whole_fruit_basket_cmd( 48 | args: List(String), 49 | ) -> CommandResult(FruitBasket, String) { 50 | use cmd <- command("basket", "Use all the things!", args) 51 | 52 | use foo, cmd <- arg.bool(cmd, "foo") 53 | use bar, cmd <- arg.float(cmd, "bar") 54 | use baz, cmd <- arg.int(cmd, "baz") 55 | use qux, cmd <- arg.string(cmd, "qux") 56 | 57 | use quux, cmd <- opt.bool(cmd, "quux", "include quux?") 58 | use corge, cmd <- opt.float(cmd, "corge", "how much corge?", 1.0) 59 | use grault, cmd <- opt.int(cmd, "grault", "how many grault?", 1) 60 | use garply, cmd <- opt.string(cmd, "garply", "which garply?", "default") 61 | use waldo, cmd <- opt.bool_(cmd, "waldo", Some("w"), "invert quux?") 62 | use fred, cmd <- opt.float_(cmd, "fred", Some("f"), "multiply corge", 10.0) 63 | use plugh, cmd <- opt.int_(cmd, "plugh", Some("p"), "add to grault", 1) 64 | use xyzzy, cmd <- opt.string_(cmd, "xyzzy", Some("x"), "garply suffix", "!") 65 | 66 | use foo <- foo(cmd) 67 | use bar <- bar(cmd) 68 | use baz <- baz(cmd) 69 | use qux <- qux(cmd) 70 | 71 | use quux <- quux(cmd) 72 | use corge <- corge(cmd) 73 | use grault <- grault(cmd) 74 | use garply <- garply(cmd) 75 | 76 | use waldo <- waldo(cmd) 77 | use fred <- fred(cmd) 78 | use plugh <- plugh(cmd) 79 | use xyzzy <- xyzzy(cmd) 80 | 81 | Ok(FruitBasket( 82 | foo, 83 | bar, 84 | baz, 85 | qux, 86 | quux && !waldo, 87 | corge *. fred, 88 | grault + plugh, 89 | garply <> xyzzy, 90 | )) 91 | } 92 | 93 | fn twoface_cmd(args: List(String)) -> CommandResult(String, String) { 94 | use cmd <- command("twoface", "Flip a coin.", args) 95 | use heads, cmd <- opt.bool(cmd, "heads", "Heads?") 96 | use tails, cmd <- opt.bool(cmd, "tails", "Tails?") 97 | 98 | use heads <- heads(cmd) 99 | use tails <- tails(cmd) 100 | 101 | case #(heads, tails) { 102 | #(True, False) -> Ok("Heads!") 103 | #(False, True) -> Ok("Tails!") 104 | _ -> Error(CommandError("You must choose heads or tails.")) 105 | } 106 | } 107 | 108 | // verify that the help text works even if there are no positional arguments 109 | fn help_opt_cmd(args: List(String)) -> CommandResult(String, Nil) { 110 | use cmd <- command("help", "Test help text.", args) 111 | use foo, cmd <- opt.string(cmd, "foo", "bar", "baz") 112 | 113 | use x <- foo(cmd) 114 | 115 | Ok(x) 116 | } 117 | 118 | pub fn help_opt_test() { 119 | let expect_help_usage = 120 | "help -- Test help text. 121 | 122 | Usage: help 123 | 124 | Options: 125 | --foo bar (string, default: \"baz\") 126 | -h, --help Show this help text and exit." 127 | 128 | help_opt_cmd([]) 129 | |> should.equal(Ok("baz")) 130 | 131 | help_opt_cmd(["--help"]) 132 | |> should.equal(Error(Help(expect_help_usage))) 133 | } 134 | 135 | pub fn command_error_usage_test() { 136 | let expect_usage = 137 | "hello -- ERROR! Missing argument for option: name 138 | 139 | Usage: hello 140 | 141 | Options: 142 | --enthusiasm How enthusiastic? (int, default: 1) 143 | --loudly Use all caps. (bool, default: false) 144 | -h, --help Show this help text and exit." 145 | 146 | let assert Error(CommandLineError(_, usage)) = hello_cmd([]) 147 | 148 | usage 149 | |> should.equal(expect_usage) 150 | } 151 | 152 | pub fn help_test() { 153 | let expect_usage = 154 | "hello -- Say hello to someone. 155 | 156 | Usage: hello 157 | 158 | Options: 159 | --enthusiasm How enthusiastic? (int, default: 1) 160 | --loudly Use all caps. (bool, default: false) 161 | -h, --help Show this help text and exit." 162 | 163 | hello_cmd(["--help"]) 164 | |> should.equal(Error(Help(expect_usage))) 165 | } 166 | 167 | pub fn execute_command_test() { 168 | let argv = ["world"] 169 | let result = hello_cmd(argv) 170 | 171 | result 172 | |> should.equal(Ok("Hello, world!")) 173 | } 174 | 175 | pub fn bool_opt_test() { 176 | let argv = ["world", "--loudly"] 177 | let result = hello_cmd(argv) 178 | 179 | result 180 | |> should.equal(Ok("HELLO, WORLD!")) 181 | } 182 | 183 | pub fn int_opt_test() { 184 | let argv = ["world", "--enthusiasm=3"] 185 | let result = hello_cmd(argv) 186 | 187 | result 188 | |> should.equal(Ok("Hello, world!!!")) 189 | } 190 | 191 | pub fn missing_argument_test() { 192 | let assert Error(CommandLineError(reason, _)) = hello_cmd([]) 193 | 194 | reason 195 | |> should.equal(MissingArgument("name")) 196 | } 197 | 198 | pub fn malformed_argument_test() { 199 | let argv = ["world", "--enthusiasm=three"] 200 | let result = hello_cmd(argv) 201 | 202 | let assert Error(CommandLineError(reason, _)) = result 203 | 204 | reason 205 | |> should.equal(MalformedArgument("enthusiasm", "three")) 206 | } 207 | 208 | pub fn all_the_things_test() { 209 | let argv = [ 210 | "true", "1.0", "1", "hello", "--quux", "--corge=2.0", "--grault=2", 211 | "--garply=world", "-w", "-f=2.0", "-p=3", "-x=!", 212 | ] 213 | let result = the_whole_fruit_basket_cmd(argv) 214 | 215 | result 216 | |> should.equal(Ok(FruitBasket(True, 1.0, 1, "hello", False, 4.0, 5, "world!"))) 217 | } 218 | 219 | pub fn command_error_test() { 220 | twoface_cmd(["--heads"]) 221 | |> should.equal(Ok("Heads!")) 222 | 223 | twoface_cmd(["--tails"]) 224 | |> should.equal(Ok("Tails!")) 225 | 226 | twoface_cmd([]) 227 | |> should.equal(Error(CommandError("You must choose heads or tails."))) 228 | 229 | twoface_cmd(["--heads", "--tails"]) 230 | |> should.equal(Error(CommandError("You must choose heads or tails."))) 231 | } 232 | --------------------------------------------------------------------------------