├── .envrc
├── test
├── test_helper.exs
├── prompt_module_test.exs
└── prompt_test.exs
├── .tool-versions
├── assets
└── prompt.png
├── .formatter.exs
├── lib
├── prompt
│ ├── io.ex
│ ├── io
│ │ ├── color.ex
│ │ ├── password.ex
│ │ ├── display.ex
│ │ ├── choice.ex
│ │ ├── text.ex
│ │ ├── confirm.ex
│ │ └── select.ex
│ ├── example.ex
│ ├── position.ex
│ ├── table.ex
│ ├── command.ex
│ └── router.ex
└── prompt.ex
├── .woodpecker
├── release.yaml
├── static_analysis.yaml
└── lint.yaml
├── Dockerfile.baseimage
├── .gitignore
├── Makefile
├── flake.nix
├── .builds
└── elixir.yml
├── mix.exs
├── example.livemd
├── CHANGELOG.md
├── mix.lock
├── README.md
├── flake.lock
├── LICENSE
└── COPYING
/.envrc:
--------------------------------------------------------------------------------
1 | use flake;
2 |
--------------------------------------------------------------------------------
/test/test_helper.exs:
--------------------------------------------------------------------------------
1 | ExUnit.start()
2 |
--------------------------------------------------------------------------------
/.tool-versions:
--------------------------------------------------------------------------------
1 | elixir 1.17.2-otp-27
2 | erlang 27.0
3 |
--------------------------------------------------------------------------------
/assets/prompt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/silbermm/prompt/HEAD/assets/prompt.png
--------------------------------------------------------------------------------
/.formatter.exs:
--------------------------------------------------------------------------------
1 | # Used by "mix format"
2 | [
3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
4 | ]
5 |
--------------------------------------------------------------------------------
/lib/prompt/io.ex:
--------------------------------------------------------------------------------
1 | defprotocol Prompt.IO do
2 | @moduledoc false
3 |
4 | @doc "Display the IO"
5 | def display(data)
6 |
7 | @doc "Evaluate the IO"
8 | def evaluate(data)
9 | end
10 |
--------------------------------------------------------------------------------
/.woodpecker/release.yaml:
--------------------------------------------------------------------------------
1 | steps:
2 | - name: build and push image
3 | image: codeberg.org/ahappydeath/prompt-base:latest
4 | commands:
5 | - mix deps.get
6 | - mix hex.publish --yes
7 | environment:
8 | HEX_API_KEY:
9 | from_secret: hex_api_key
10 | when:
11 | - event: release
12 |
--------------------------------------------------------------------------------
/.woodpecker/static_analysis.yaml:
--------------------------------------------------------------------------------
1 | when:
2 | - evaluate: 'not (CI_COMMIT_MESSAGE contains "SKIPCI")'
3 |
4 | steps:
5 | - name: run_dialyzer
6 | image: codeberg.org/ahappydeath/prompt-base:latest
7 | commands:
8 | - mix deps.get
9 | - mix compile --warnings-as-errors
10 | - mix dialyzer
11 | when:
12 | - event: pull_request
13 |
--------------------------------------------------------------------------------
/Dockerfile.baseimage:
--------------------------------------------------------------------------------
1 | ARG ELIXIR_VERSION=1.18.1
2 | ARG OTP_VERSION=27.2
3 | ARG DEBIAN_VERSION=bullseye-20241223-slim
4 |
5 | ARG BUILDER_IMAGE="hexpm/elixir:${ELIXIR_VERSION}-erlang-${OTP_VERSION}-debian-${DEBIAN_VERSION}"
6 |
7 | FROM ${BUILDER_IMAGE}
8 |
9 | # install build dependencies
10 | RUN apt-get update -y && apt-get install -y build-essential git \
11 | && apt-get clean && rm -f /var/lib/apt/lists/*_*
12 |
13 | # prepare build dir
14 | WORKDIR /app
15 |
16 | # install hex + rebar
17 | RUN mix local.hex --force && \
18 | mix local.rebar --force
19 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # The directory Mix will write compiled artifacts to.
2 | /_build/
3 |
4 | # If you run "mix test --cover", coverage assets end up here.
5 | /cover/
6 |
7 | # The directory Mix downloads your dependencies sources to.
8 | /deps/
9 |
10 | # Where third-party dependencies like ExDoc output generated docs.
11 | /doc/
12 |
13 | # Ignore .fetch files in case you like to edit your project deps locally.
14 | /.fetch
15 |
16 | # If the VM crashes, it generates a dump, let's ignore it too.
17 | erl_crash.dump
18 |
19 | # Also ignore archive artifacts (built via "mix archive.build").
20 | *.ez
21 |
22 | # Ignore package tarball (built via "mix hex.build").
23 | prompt-*.tar
24 |
25 | priv/plts
26 | /.direnv/
27 | /.nix-hex/
28 | /.nix-mix/
29 |
--------------------------------------------------------------------------------
/.woodpecker/lint.yaml:
--------------------------------------------------------------------------------
1 | when:
2 | - evaluate: 'not (CI_COMMIT_MESSAGE contains "SKIPCI")'
3 | - event: pull_request
4 |
5 | steps:
6 | - name: compile
7 | image: codeberg.org/ahappydeath/prompt-base:latest
8 | commands:
9 | - mix deps.get
10 | - mix compile --warnings-as-errors
11 | when:
12 | - event: pull_request
13 |
14 | - name: check_formatted
15 | image: codeberg.org/ahappydeath/prompt-base:latest
16 | commands:
17 | - mix format --check-formatted
18 | when:
19 | - event: pull_request
20 |
21 | - name: graph_dependencies
22 | image: codeberg.org/ahappydeath/prompt-base:latest
23 | commands:
24 | - mix graph --fail-above 1
25 | when:
26 | - event: pull_request
27 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | .PHONY: reset check* test*
2 |
3 | APP_NAME ?= `grep 'app:' mix.exs | sed -e 's/\[//g' -e 's/ //g' -e 's/app://' -e 's/[:,]//g'`
4 | APP_VSN ?= `grep 'version:' mix.exs | cut -d '"' -f2`
5 | BUILD ?= `git rev-parse --short HEAD`
6 |
7 | REPO = "codeberg.org"
8 |
9 | help:
10 | @fgrep -h "##" $(MAKEFILE_LIST) | fgrep -v fgrep | sed -e 's/\\$$//' | sed -e 's/##//'
11 |
12 | check: check.all ## Run linters and checks for all apps.
13 | build_image: image.build ## Build a docker image with correct tags
14 | push_image: image.push ## Push the image to docker hub
15 |
16 | check.all:
17 | mix format --check-formatted \
18 | && mix graph --fail-above 1 \
19 | && mix credo --strict \
20 | && mix dialyzer
21 |
22 | image.build:
23 | docker build -t $(REPO)/ahappydeath/prompt-base:latest --file Dockerfile.baseimage .
24 |
25 | image.push:
26 | docker push $(REPO)/ahappydeath/prompt-base:latest
27 |
--------------------------------------------------------------------------------
/lib/prompt/io/color.ex:
--------------------------------------------------------------------------------
1 | defmodule Prompt.IO.Color do
2 | @moduledoc false
3 |
4 | @typedoc "The colors allowed for text and background"
5 | @type t ::
6 | :black
7 | | :blue
8 | | :cyan
9 | | :green
10 | | :light_black
11 | | :light_blue
12 | | :light_cyan
13 | | :light_green
14 | | :light_magneta
15 | | :light_red
16 | | :light_white
17 | | :light_yellow
18 | | :magenta
19 | | :red
20 | | :white
21 | | :yellow
22 |
23 | def all do
24 | [
25 | :black,
26 | :blue,
27 | :cyan,
28 | :green,
29 | :light_black,
30 | :light_blue,
31 | :light_cyan,
32 | :light_green,
33 | :light_magneta,
34 | :light_red,
35 | :light_white,
36 | :light_yellow,
37 | :magenta,
38 | :red,
39 | :white,
40 | :yellow
41 | ]
42 | end
43 | end
44 |
--------------------------------------------------------------------------------
/lib/prompt/example.ex:
--------------------------------------------------------------------------------
1 | defmodule Prompt.Example.Command1 do
2 | @moduledoc false
3 | use Prompt.Command
4 |
5 | defstruct [:limit, :print]
6 |
7 | @impl true
8 | def init(opts) do
9 | %__MODULE__{limit: opts.limit, print: opts.print}
10 | end
11 |
12 | @impl true
13 | def process(%__MODULE__{} = cmd) do
14 | display("cmd1 ran - limit: #{cmd.limit}!", color: :red)
15 | end
16 | end
17 |
18 | defmodule Prompt.Example.Command2 do
19 | @moduledoc false
20 | use Prompt.Command
21 |
22 | @impl true
23 | def process(cmd) do
24 | cmd
25 | end
26 | end
27 |
28 | defmodule Prompt.Example.FallbackCommand do
29 | @moduledoc false
30 | use Prompt.Command
31 |
32 | @impl true
33 | def process(_cmd) do
34 | display("fallback command")
35 | end
36 | end
37 |
38 | defmodule Prompt.Example do
39 | @moduledoc false
40 |
41 | use Prompt.Router, otp_app: :prompt
42 |
43 | command :cmd1, Prompt.Example.Command1 do
44 | arg(:limit, :integer, default: 6)
45 | arg(:print, :boolean)
46 | end
47 |
48 | command :cmd2, Prompt.Example.Command2 do
49 | arg(:whatever, :string, [])
50 | end
51 |
52 | command "", Prompt.Example.FallbackCommand do
53 | arg(:blah, :boolean)
54 | arg(:cmd1, :boolean)
55 | arg(:limit, :integer)
56 | end
57 | end
58 |
--------------------------------------------------------------------------------
/test/prompt_module_test.exs:
--------------------------------------------------------------------------------
1 | defmodule FallbackCommand do
2 | use Prompt.Command
3 |
4 | @impl true
5 | def init(_argv) do
6 | %{}
7 | end
8 |
9 | @impl true
10 | def process(_) do
11 | display("fallback command")
12 | end
13 | end
14 |
15 | defmodule ExampleCommand do
16 | use Prompt.Command
17 |
18 | @impl true
19 | def init(_argv) do
20 | %{}
21 | end
22 |
23 | @impl true
24 | def process(_) do
25 | display("test command")
26 | end
27 | end
28 |
29 | defmodule Example do
30 | use Prompt.Router, otp_app: :prompt
31 |
32 | command :test, ExampleCommand do
33 | arg(:help, :boolean)
34 | end
35 |
36 | command "", FallbackCommand do
37 | arg(:help, :boolean)
38 | end
39 |
40 | @impl true
41 | def help do
42 | display("help")
43 | end
44 | end
45 |
46 | defmodule PromptModuleTest do
47 | use ExUnit.Case
48 | import ExUnit.CaptureIO
49 |
50 | test "show help" do
51 | assert capture_io(fn ->
52 | Example.main(["--help"])
53 | end) =~ "help"
54 | end
55 |
56 | test "subcommand" do
57 | assert capture_io(fn ->
58 | Example.main(["test"])
59 | end) =~ "test command"
60 | end
61 |
62 | test "unknown command forwards to the fallback command" do
63 | assert capture_io(fn ->
64 | Example.main(["whatever"])
65 | end) =~ "[39mfallback command"
66 | end
67 |
68 | test "fallback" do
69 | assert capture_io(fn ->
70 | Example.main([])
71 | end) =~ "fallback command"
72 | end
73 | end
74 |
--------------------------------------------------------------------------------
/flake.nix:
--------------------------------------------------------------------------------
1 | {
2 | description = "Prompt";
3 |
4 | inputs = {
5 | nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
6 | expertpkg.url = "github:elixir-lang/expert";
7 | systems.url = "github:nix-systems/default";
8 | flake-utils = {
9 | url = "github:numtide/flake-utils";
10 | inputs.systems.follows = "systems";
11 | };
12 | };
13 |
14 | outputs =
15 | {
16 | nixpkgs,
17 | flake-utils,
18 | expertpkg,
19 | ...
20 | }:
21 | flake-utils.lib.eachDefaultSystem (
22 | system:
23 | let
24 | pkgs = nixpkgs.legacyPackages.${system};
25 | expert = expertpkg.packages.${system}.expert;
26 | in
27 | {
28 | devShells.default = pkgs.mkShell {
29 | packages = [
30 | pkgs.bashInteractive
31 | pkgs.erlang_28
32 | pkgs.beam.packages.erlang_28.elixir_1_19
33 | pkgs.elixir-ls
34 | pkgs.libnotify
35 | pkgs.inotify-tools
36 | expert
37 | ];
38 | shellHook = ''
39 | # limit mix to current project
40 | mkdir -p .nix-mix
41 | export MIX_HOME=$PWD/.nix-mix
42 | export PATH=$MIX_HOME/bin:$PATH
43 | export PATH=$MIX_HOME/escripts:$PATH
44 |
45 | # limit hex to current project
46 | mkdir -p .nix-hex
47 | export HEX_HOME=$PWD/.nix-hex
48 | export ERL_LIBS=$HEX_HOME/lib/erlang/lib
49 | export PATH=$HEX_HOME/bin:$PATH
50 |
51 | # limit history to current project
52 | export ERL_AFLAGS="-kernel shell_history enabled -kernel shell_history_path '\"$PWD/.erlang-history\"'"
53 | '';
54 | };
55 |
56 | }
57 | );
58 | }
59 |
--------------------------------------------------------------------------------
/lib/prompt/io/password.ex:
--------------------------------------------------------------------------------
1 | defmodule Prompt.IO.Password do
2 | @moduledoc false
3 |
4 | alias __MODULE__
5 | import IO, only: [write: 1, read: 2]
6 |
7 | @type t :: %Password{
8 | text: binary(),
9 | color: Prompt.IO.Color.t(),
10 | background_color: Prompt.IO.Color.t()
11 | }
12 |
13 | defstruct [:text, :color, :background_color]
14 |
15 | def new(text, options) do
16 | %Password{
17 | text: text,
18 | color: Keyword.get(options, :color, IO.ANSI.default_color()),
19 | background_color: Keyword.get(options, :background_color)
20 | }
21 | end
22 |
23 | defimpl Prompt.IO do
24 | def display(password) do
25 | [
26 | :reset,
27 | background_color(password),
28 | password.color,
29 | password.text,
30 | ": ",
31 | IO.ANSI.conceal()
32 | ]
33 | |> IO.ANSI.format()
34 | |> write()
35 |
36 | password
37 | end
38 |
39 | def evaluate(_password) do
40 | case read(:stdio, :line) do
41 | :eof ->
42 | write(IO.ANSI.reset())
43 | :error
44 |
45 | {:error, _reason} ->
46 | write(IO.ANSI.reset())
47 | :error
48 |
49 | answer when is_binary(answer) ->
50 | write(IO.ANSI.reset())
51 | String.trim(answer)
52 |
53 | answer when is_list(answer) ->
54 | write(IO.ANSI.reset())
55 |
56 | answer
57 | |> IO.chardata_to_string()
58 | |> String.trim()
59 | end
60 | end
61 |
62 | defp background_color(password) do
63 | case password.background_color do
64 | nil -> IO.ANSI.default_background()
65 | res -> String.to_atom("#{Atom.to_string(res)}_background")
66 | end
67 | end
68 | end
69 | end
70 |
--------------------------------------------------------------------------------
/.builds/elixir.yml:
--------------------------------------------------------------------------------
1 | arch: amd64
2 | image: ubuntu/24.04
3 | packages:
4 | - build-essential
5 | - zip
6 | - autoconf
7 | - m4
8 | - libncurses5-dev
9 | - libwxgtk3.0-gtk3-dev
10 | - libwxgtk-webview3.0-gtk3-dev
11 | - libgl1-mesa-dev
12 | - libglu1-mesa-dev
13 | - libpng-dev
14 | - libssh-dev
15 | - unixodbc-dev
16 | - xsltproc
17 | - fop
18 | - libxml2-utils
19 | - libncurses-dev
20 | - pkg-config
21 | secrets:
22 | - 79a531a9-22f0-4df5-babd-62d8fc634fd6
23 | tasks:
24 | - install_asdf: |
25 | git clone https://github.com/asdf-vm/asdf.git ~/.asdf --branch v0.13.1
26 | source "$HOME/.asdf/asdf.sh"
27 | sudo update-locale en_US.UTF-8
28 | - install_elixir: |
29 | cd prompt
30 | export KERL_CONFIGURE_OPTIONS="--disable-debug --without-javac"
31 | source "$HOME/.asdf/asdf.sh"
32 | asdf plugin add erlang https://github.com/asdf-vm/asdf-erlang.git
33 | asdf plugin-add elixir https://github.com/asdf-vm/asdf-elixir.git
34 | asdf install
35 | - compile_project: |
36 | cd prompt
37 | source "$HOME/.asdf/asdf.sh"
38 | mix local.hex --force
39 | mix local.rebar --force
40 | mix deps.get
41 | mix compile --warnings-as-errors
42 | - run_analyzer: |
43 | cd prompt
44 | source "$HOME/.asdf/asdf.sh"
45 | mix dialyzer --plt
46 | mix dialyzer --halt-exit-status --format github
47 | - run_tests: |
48 | cd prompt
49 | source "$HOME/.asdf/asdf.sh"
50 | MIX_ENV=test mix test --exclude integration
51 | - release: |
52 | if [[ "$GIT_REF" == refs/tags/* ]]; then
53 | set +x
54 | set -a
55 | source ~/.hextokenenv
56 | set +a
57 | set -x
58 | cd prompt
59 | source "$HOME/.asdf/asdf.sh"
60 | mix deps.get
61 | mix hex.publish --yes
62 | fi
63 |
--------------------------------------------------------------------------------
/lib/prompt/position.ex:
--------------------------------------------------------------------------------
1 | # Prompt - library to help create interative CLI in Elixir
2 | # Copyright (C) 2020 Matt Silbernagel
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | defmodule Prompt.Position do
18 | @moduledoc """
19 | Manipulate the position of the cursor and the display of previous text.
20 | """
21 |
22 | alias IO.ANSI
23 | import IO
24 |
25 | @doc """
26 | Clears the content from the previous `number` of lines
27 | and resets the cursor.
28 | """
29 | @spec clear_lines(pos_integer()) :: :ok
30 | def clear_lines(number) do
31 | 1..number
32 | |> Enum.reduce("", &build_clear_lines_string/2)
33 | |> write
34 | end
35 |
36 | @spec _clear_up :: String.t()
37 | defp _clear_up, do: ANSI.cursor_up() <> ANSI.clear_line()
38 |
39 | defp build_clear_lines_string(_, str), do: str <> _clear_up()
40 |
41 | @doc """
42 | Mask the content on the terminal `relative_line` above.
43 | By default will clear the line and put `#######` in its place
44 | then move the cursor back to the current line.
45 | """
46 | @spec mask_line(pos_integer()) :: :ok
47 | def mask_line(relative_line) do
48 | line_output =
49 | ANSI.cursor_up(relative_line) <>
50 | ANSI.clear_line() <>
51 | ANSI.italic() <>
52 | ANSI.light_green() <>
53 | "#######" <>
54 | ANSI.reset() <> "\n"
55 |
56 | if relative_line - 1 <= 0 do
57 | write(line_output)
58 | else
59 | write(line_output <> ANSI.cursor_down(relative_line - 1))
60 | end
61 | end
62 | end
63 |
--------------------------------------------------------------------------------
/mix.exs:
--------------------------------------------------------------------------------
1 | defmodule Prompt.MixProject do
2 | use Mix.Project
3 |
4 | def project do
5 | [
6 | app: :prompt,
7 | description: "A terminal toolkit and a set of helpers for building console applications.",
8 | version: "0.10.2-rc1",
9 | elixir: "~> 1.12",
10 | package: package(),
11 | aliases: aliases(),
12 | source_url: "https://codeberg.org/ahappydeath/prompt",
13 | dialyzer: [
14 | flags: ["-Wunmatched_returns", :error_handling, :underspecs]
15 | ],
16 | docs: docs(),
17 | start_permanent: Mix.env() == :prod,
18 | deps: deps()
19 | ]
20 | end
21 |
22 | def application do
23 | [
24 | extra_applications: [:logger, :iex]
25 | ]
26 | end
27 |
28 | defp deps do
29 | [
30 | # {:credo, "~> 1.7", only: [:dev, :test], runtime: false},
31 | {:ex_doc, ">= 0.39.1", only: :dev, runtime: false},
32 | {:dialyxir, "~> 1.4", only: [:dev], runtime: false},
33 | {:nimble_options, "~> 1.1.1"}
34 | ]
35 | end
36 |
37 | defp package do
38 | [
39 | licenses: ["GPL-3.0-or-later"],
40 | files: ["lib", "mix.exs", "README.md", "CHANGELOG.md", "COPYING*"],
41 | maintainers: ["Matt Silbernagel"],
42 | links: %{:Codeberg => "https://codeberg.org/ahappydeath/prompt"}
43 | ]
44 | end
45 |
46 | defp docs do
47 | [
48 | main: "Prompt",
49 | api_reference: false,
50 | extras: [
51 | "README.md": [filename: "introduction", title: "Introduction"],
52 | "example.livemd": [filename: "example", title: "Example"],
53 | "CHANGELOG.md": [filename: "changelog", title: "Changelog"],
54 | LICENSE: [filename: "license", title: "License"]
55 | ],
56 | logo: "assets/prompt.png",
57 | authors: ["Matt Silbernagel"],
58 | groups_for_docs: [
59 | "Input Functions": &(&1[:section] == :input),
60 | "Output Functions": &(&1[:section] == :output)
61 | ],
62 | nest_modules_by_prefix: [
63 | Prompt,
64 | Prompt.Command,
65 | Prompt.Position
66 | ]
67 | ]
68 | end
69 |
70 | defp aliases do
71 | [
72 | graph: "xref graph --label compile-connected"
73 | ]
74 | end
75 | end
76 |
--------------------------------------------------------------------------------
/example.livemd:
--------------------------------------------------------------------------------
1 | # Simple Example
2 |
3 | ```elixir
4 | Mix.install([
5 | {:prompt, "~> 0.9.3"}
6 | ])
7 | ```
8 |
9 | ## Starting Out
10 |
11 | Lets go through an example of creating and building a new commandline/terminal app with `Prompt` that will acknowledge a person.
12 | Lets call it `ack`.
13 |
14 |
15 |
16 | Lets define a `CLI` module and create where we can define what arguments we allow and what options are available for our tool.
17 |
18 | ```elixir
19 | defmodule CLI do
20 | @moduledoc """
21 | DOCUMENTATION FOR THE TOOL
22 | """
23 | use Prompt.Router, otp_app: :ack
24 |
25 | command :hello, HelloCommand do
26 | arg(:help, :boolean)
27 | end
28 | end
29 | ```
30 |
31 | ## Now Create the Command Handler
32 |
33 | Now we'll have to create the handler for the `hello` command.
34 |
35 | ```elixir
36 | defmodule HelloCommand do
37 | @moduledoc """
38 | The help message
39 |
40 | ack hello
41 |
42 | --help prints this help message
43 |
44 | """
45 | use Prompt.Command
46 |
47 | @impl true
48 | def init(opts) do
49 | # opts is map of data which includes the
50 | # options for the command and any other data passed in
51 | # Our opts here look like give the following incanatation `ack hello bob`:
52 | # `%{help: false, leftover: ["bob"]}
53 |
54 | # `init/1` can be used to transform any arguments if needed.
55 | Map.put(opts, :name, List.first(opts.leftover, nil))
56 | end
57 |
58 | @impl true
59 | def process(%{help: true}), do: help()
60 |
61 | def process(%{name: name}) do
62 | display("Hello #{name}", color: :green)
63 | end
64 | end
65 | ```
66 |
67 | ## Simulate calling the CLI
68 |
69 | ```elixir
70 | CLI.main(["hello", "bob"])
71 | ```
72 |
73 | ```elixir
74 | CLI.main(["hello", "--help"])
75 | ```
76 |
77 | ## Bundle and Distribute
78 |
79 | To build your app, you'll need to decide if you want an escript or a binary. The former will require
80 | the user of your tool to have Elixir and Erlang installed on their system. A binary built using
81 | Bakeware or Burrito can be distributed and used without having Elixir or Erlang on the system.
82 |
83 | See the [documentation](https://hexdocs.pm/prompt/Prompt.html#module-building-for-distribution) for details on both
84 |
85 |
--------------------------------------------------------------------------------
/lib/prompt/io/display.ex:
--------------------------------------------------------------------------------
1 | defmodule Prompt.IO.Display do
2 | @moduledoc false
3 |
4 | alias __MODULE__
5 | import IO, only: [write: 1, read: 2]
6 |
7 | @type t() :: %Display{
8 | text: binary(),
9 | color: Prompt.IO.Color.t(),
10 | background_color: Prompt.IO.Color.t(),
11 | trim: bool(),
12 | mask_line: bool(),
13 | from: atom(),
14 | position: :left | :right
15 | }
16 |
17 | defstruct [:text, :color, :background_color, :trim, :mask_line, :from, :position]
18 |
19 | def new(txt, options) do
20 | %Display{
21 | text: txt,
22 | color: Keyword.get(options, :color, IO.ANSI.default_color()),
23 | background_color: Keyword.get(options, :background_color),
24 | mask_line: Keyword.get(options, :mask_line),
25 | trim: Keyword.get(options, :trim),
26 | from: Keyword.get(options, :from),
27 | position: Keyword.get(options, :position)
28 | }
29 | end
30 |
31 | defimpl Prompt.IO do
32 | def display(text) do
33 | # Put the cursor in the correct place
34 | _ = position(text.position, text.text)
35 |
36 | if text.mask_line && text.from == :self do
37 | IO.ANSI.format([
38 | :reset,
39 | background_color(text),
40 | text.color,
41 | text.text,
42 | :reset,
43 | " [Press Enter to continue]"
44 | ])
45 | |> write()
46 | else
47 | [
48 | :reset,
49 | background_color(text),
50 | text.color,
51 | text.text,
52 | :reset,
53 | without_newline(text.trim)
54 | ]
55 | |> IO.ANSI.format()
56 | |> write()
57 | end
58 |
59 | text
60 | end
61 |
62 | def evaluate(text) do
63 | if text.mask_line && text.from == :self do
64 | case read(:stdio, :line) do
65 | :eof -> :error
66 | {:error, _reason} -> :error
67 | _ -> Prompt.Position.mask_line(1)
68 | end
69 | end
70 |
71 | :ok
72 | end
73 |
74 | defp without_newline(true), do: ""
75 | defp without_newline(false), do: "\n"
76 |
77 | defp position(:left, _), do: write(IO.ANSI.cursor_left(10_000))
78 |
79 | defp position(:right, content) do
80 | move_left = String.length(content)
81 | write(IO.ANSI.cursor_right(10_000) <> IO.ANSI.cursor_left(move_left))
82 | end
83 |
84 | defp background_color(display) do
85 | case display.background_color do
86 | nil -> IO.ANSI.default_background()
87 | res -> String.to_atom("#{Atom.to_string(res)}_background")
88 | end
89 | end
90 | end
91 | end
92 |
--------------------------------------------------------------------------------
/lib/prompt/io/choice.ex:
--------------------------------------------------------------------------------
1 | defmodule Prompt.IO.Choice do
2 | @moduledoc false
3 |
4 | alias __MODULE__
5 | alias IO.ANSI
6 | import IO, only: [write: 1, read: 2]
7 |
8 | @type t :: %Choice{
9 | default_answer: atom(),
10 | question: binary(),
11 | custom: any(),
12 | color: any(),
13 | background_color: any(),
14 | trim: boolean()
15 | }
16 |
17 | defstruct [
18 | :default_answer,
19 | :question,
20 | :custom,
21 | :color,
22 | :background_color,
23 | :trim
24 | ]
25 |
26 | @doc ""
27 | def new(question, custom, options) do
28 | [{k, _} | _rest] = custom
29 |
30 | %Choice{
31 | color: Keyword.get(options, :color, IO.ANSI.default_color()),
32 | trim: Keyword.get(options, :trim),
33 | default_answer: Keyword.get(options, :default_answer, k),
34 | question: question,
35 | custom: custom
36 | }
37 | end
38 |
39 | defimpl Prompt.IO do
40 | def display(choice) do
41 | [
42 | :reset,
43 | background_color(choice),
44 | choice.color,
45 | "#{choice.question} #{choice_text(choice.custom, choice.default_answer)} ",
46 | :reset,
47 | without_newline(choice.trim)
48 | ]
49 | |> ANSI.format()
50 | |> write()
51 |
52 | choice
53 | end
54 |
55 | def evaluate(choice) do
56 | case read(:stdio, :line) do
57 | :eof -> :error
58 | {:error, _reason} -> :error
59 | answer when is_binary(answer) -> _evaluate_choice(answer, choice)
60 | answer when is_list(answer) -> _evaluate_choice(IO.chardata_to_string(answer), choice)
61 | end
62 | end
63 |
64 | defp choice_text(custom_choices, default) do
65 | lst =
66 | Enum.map(custom_choices, fn {d, c} ->
67 | if d == default do
68 | String.upcase(c)
69 | else
70 | c
71 | end
72 | end)
73 |
74 | "(#{Enum.join(lst, "/")}):"
75 | end
76 |
77 | defp _evaluate_choice("\n", choice),
78 | do: choice.custom |> Keyword.take([choice.default_answer]) |> List.first() |> elem(0)
79 |
80 | defp _evaluate_choice(answer, choice) do
81 | chosen =
82 | choice.custom
83 | |> Enum.find(fn {_k, v} ->
84 | v |> String.downcase() == answer |> String.trim() |> String.downcase()
85 | end)
86 |
87 | case chosen do
88 | nil -> :invalid
89 | {result, _} -> result
90 | end
91 | end
92 |
93 | defp background_color(display) do
94 | case display.background_color do
95 | nil -> ANSI.default_background()
96 | res -> String.to_atom("#{Atom.to_string(res)}_background")
97 | end
98 | end
99 |
100 | defp without_newline(true), do: ""
101 | defp without_newline(false), do: "\n"
102 | end
103 | end
104 |
--------------------------------------------------------------------------------
/lib/prompt/table.ex:
--------------------------------------------------------------------------------
1 | defmodule Prompt.Table do
2 | @moduledoc false
3 |
4 | alias __MODULE__
5 |
6 | @type input :: list(list())
7 |
8 | @type t :: %Table{
9 | data: input(),
10 | column_count: number(),
11 | row_count: number(),
12 | columns_length: map(),
13 | opts: Keyword.t(),
14 | error: nil | :invalid
15 | }
16 |
17 | defstruct data: [[]], column_count: 0, row_count: 0, columns_length: %{}, error: nil, opts: []
18 |
19 | @doc "Create a new Table struct"
20 | @spec new(input(), Keyword.t()) :: t()
21 | def new(data, opts) do
22 | max_column_length_map = columns_length(data)
23 | column_index = max_column_length_map |> Map.keys() |> List.last()
24 |
25 | %Table{
26 | data: data,
27 | row_count: Enum.count(data),
28 | column_count: column_index + 1,
29 | columns_length: max_column_length_map,
30 | opts: opts
31 | }
32 | end
33 |
34 | @doc "Generate the row of data"
35 | @spec row(t(), list()) :: String.t()
36 | def row(%Table{} = table, row) do
37 | row_str =
38 | for {column, idx} <- Enum.with_index(row) do
39 | column_string = column_str(column, Map.get(table.columns_length, idx))
40 |
41 | if Keyword.get(table.opts, :border) == :none,
42 | do: " #{column_string} ",
43 | else: "| #{column_string} "
44 | end
45 |
46 | if Keyword.get(table.opts, :border) == :none do
47 | "#{row_str}\n"
48 | else
49 | "#{row_str}|\n"
50 | end
51 | end
52 |
53 | @doc "Generate the row delimiter"
54 | @spec row_delimiter(t()) :: iolist()
55 | def row_delimiter(%Table{} = table) do
56 | delimiter =
57 | case Keyword.get(table.opts, :border, :normal) do
58 | :markdown -> "|"
59 | :normal -> "+"
60 | :none -> ""
61 | end
62 |
63 | if delimiter == "" do
64 | "\n"
65 | else
66 | row =
67 | for column_number <- 0..(table.column_count - 1) do
68 | # should get us the length of the largest cell in this column
69 | length = Map.get(table.columns_length, column_number)
70 | r = row_str(length)
71 | "#{delimiter}-#{r}-"
72 | end
73 |
74 | [row, delimiter, "\n"]
75 | end
76 | end
77 |
78 | defp row_str(total_length), do: Enum.map(1..total_length, fn _ -> "-" end)
79 |
80 | defp column_str(word, column_length) do
81 | String.pad_trailing(word, column_length)
82 | end
83 |
84 | defp columns_length(matrix),
85 | do: Enum.reduce(matrix, %{}, &largest_column(Enum.with_index(&1), &2))
86 |
87 | defp largest_column(row, per_column_map) do
88 | Enum.reduce(row, per_column_map, fn {column, idx}, acc ->
89 | {_, updated} = Map.get_and_update(acc, idx, &update_map(&1, column))
90 | updated
91 | end)
92 | end
93 |
94 | defp update_map(nil, column), do: {nil, String.length(column)}
95 |
96 | defp update_map(curr, column) do
97 | column_count = String.length(column)
98 |
99 | if column_count > curr do
100 | {curr, column_count}
101 | else
102 | {curr, curr}
103 | end
104 | end
105 | end
106 |
--------------------------------------------------------------------------------
/lib/prompt/io/text.ex:
--------------------------------------------------------------------------------
1 | defmodule Prompt.IO.Text do
2 | @moduledoc false
3 |
4 | alias __MODULE__
5 | alias IO.ANSI
6 | import IO, only: [write: 1, read: 2]
7 |
8 | @type t() :: %Text{
9 | question: String.t(),
10 | color: any(),
11 | background_color: any(),
12 | trim: boolean(),
13 | min: integer(),
14 | max: integer()
15 | }
16 |
17 | defstruct [:question, :color, :background_color, :trim, :min, :max]
18 |
19 | @doc ""
20 | def new(question, options) do
21 | %Text{
22 | question: question,
23 | color: Keyword.get(options, :color, IO.ANSI.default_color()),
24 | background_color: Keyword.get(options, :background_color),
25 | trim: Keyword.get(options, :trim),
26 | min: Keyword.get(options, :min, 0),
27 | max: Keyword.get(options, :max, 0)
28 | }
29 | end
30 |
31 | defimpl Prompt.IO do
32 | @spec display(Prompt.IO.Text.t()) :: Prompt.IO.Text.t()
33 | def display(txt) do
34 | [
35 | :reset,
36 | background_color(txt),
37 | txt.color,
38 | "#{txt.question}: ",
39 | :reset,
40 | without_newline(txt.trim)
41 | ]
42 | |> ANSI.format()
43 | |> write()
44 |
45 | txt
46 | end
47 |
48 | @spec evaluate(Prompt.IO.Text.t()) :: String.t() | :error_min | :error_max
49 | def evaluate(txt) do
50 | case read(:stdio, :line) do
51 | :eof ->
52 | :error
53 |
54 | {:error, _reason} ->
55 | :error
56 |
57 | answer when is_binary(answer) ->
58 | answer
59 | |> String.trim()
60 | |> do_evaluate(txt)
61 |
62 | answer when is_list(answer) ->
63 | answer
64 | |> IO.chardata_to_string()
65 | |> String.trim()
66 | |> do_evaluate(txt)
67 | end
68 | end
69 |
70 | defp do_evaluate(answer, txt) do
71 | case {determine_min(answer, txt), determine_max(answer, txt)} do
72 | {false, _} -> :error_min
73 | {true, false} -> :error_max
74 | {true, true} -> answer
75 | end
76 | end
77 |
78 | defp without_newline(true), do: ""
79 | defp without_newline(false), do: "\n"
80 |
81 | defp background_color(display) do
82 | case display.background_color do
83 | nil -> ANSI.default_background()
84 | res -> String.to_atom("#{Atom.to_string(res)}_background")
85 | end
86 | end
87 |
88 | defp determine_min(answer, %Text{min: min}) when min > 0 do
89 | min_size = min * 8
90 |
91 | case answer do
92 | <<_val::bitstring-size(min_size), _rest::binary>> ->
93 | true
94 |
95 | _ ->
96 | false
97 | end
98 | end
99 |
100 | defp determine_min(_answer, %Text{}), do: true
101 |
102 | defp determine_max(answer, %Text{max: max}) when max > 0 do
103 | max_size = max * 8
104 |
105 | case answer do
106 | <<_val::bitstring-size(max_size), rest::binary>> when rest != "" ->
107 | false
108 |
109 | _ ->
110 | true
111 | end
112 | end
113 |
114 | defp determine_max(_answer, %Text{}), do: true
115 | end
116 | end
117 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 | All notable changes to this project will be documented in this file.
3 |
4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6 |
7 | ## Unreleased
8 | ### Fixed
9 | - Cleaned up all Credo reported issues
10 |
11 | ### Updated
12 | - ex_doc to 0.39.1
13 |
14 | ### Added
15 | - Flake with a dev shell for development
16 |
17 | ## [0.10.1](https://codeberg.org/ahappydeath/prompt/releases/tag/v0.10.1) - 2025-01-31
18 | ### Updated
19 | - Moved Repo to Codeberg from Sourcehut
20 | - Dependencies including
21 | - nimble_options (1.1.1)
22 |
23 | ### Added
24 | - Generated command `--complete` that will build a simple zsh completion script
25 |
26 | ## [0.10.0]
27 | ### Updated
28 | - Forward all params to fallback command instead of failing when unable to match a command.
29 |
30 | ## [0.9.4]
31 | ### Updated
32 | - Documentation for building binary releases
33 | - Livebook Example
34 |
35 | ## [0.9.3]
36 | ### Added
37 | - Allow for border-less tables
38 |
39 | ## [0.9.2] - 2023-07-31
40 | ### Added
41 | - a `short` option for arguments
42 |
43 | ## [0.9.1] - 2023-07-17
44 | ### Fixed
45 | - Properly handle the charlist return from `IO.read/2`
46 |
47 | ## [0.9.0] - 2023-07-17
48 | ### Changed
49 | - when a command is passed in that is not recognized, print help to the screen
50 |
51 | ## [0.8.1] - 2022-12-13
52 | ### Added
53 | - Better support for halting the runtime when a command is finished
54 | - a new callback `handle_exit_value/1` that is overrideable and called after each command is done.
55 |
56 | ## [0.8.0] - 2022-06-27
57 | ### Added
58 | - Prompt.Router to simplify creating commands
59 | - introduces the `command` and `arg` macros
60 |
61 | ## [0.7.4] - 2022-06-06
62 | ### Added
63 | - min and max validations for text entry
64 |
65 | ## [0.6.3] - 2021-11-28
66 | ### Added
67 | - use NimbleOptions to validate options
68 | - background_color as an option for displaying text
69 |
70 | ### Changed
71 | - modified the way to pass in text color
72 | * takes an atom now instead of an `IO.ANSI`color function
73 | - refactored `select/2` into it's own module
74 | - refactored `choice/2` into it's own module
75 | - refactored `confirm/2` into it's own module
76 | - refactored `text/2` into it's own module
77 |
78 |
79 | ## [0.6.2] - 2021-10-25
80 | ### Documentation
81 | - Added Livebook example as extra pages in hexdoc
82 | - Organized `Prompt` functions as Input / Output
83 | - Nested Modules for better readability
84 | - Updated ex_docs
85 | - Added GPL License file
86 |
87 | ## [0.6.1] - 2021-10-21
88 | ### Added
89 | - Many more tests
90 | - Livebook notebook with an example
91 | -
92 |
93 | ## [0.6.0] - 2021-10-17
94 | ### Added
95 | - a `help/0` callback and the ability to override
96 |
97 | ### Changed
98 | - Instead of taking a list of tuples for commands (`[{"command", Module"}]`), now take a Keyword list (`[command: Module]`)
99 |
100 | [0.8.1]: https://github.com/silbermm/prompt/releases/tag/v0.8.1
101 | [0.8.0]: https://github.com/silbermm/prompt/releases/tag/v0.8.0
102 | [0.7.4]: https://github.com/silbermm/prompt/releases/tag/v0.7.4
103 | [0.6.3]: https://github.com/silbermm/prompt/releases/tag/v0.6.3
104 | [0.6.2]: https://github.com/silbermm/prompt/releases/tag/v0.6.2
105 | [0.6.1]: https://github.com/silbermm/prompt/releases/tag/v0.6.1
106 | [0.6.0]: https://github.com/silbermm/prompt/releases/tag/v0.6.0
107 |
--------------------------------------------------------------------------------
/lib/prompt/io/confirm.ex:
--------------------------------------------------------------------------------
1 | defmodule Prompt.IO.Confirm do
2 | @moduledoc false
3 |
4 | alias __MODULE__
5 | alias IO.ANSI
6 | alias Prompt.IO.Color
7 |
8 | import IO, only: [write: 1, read: 2]
9 |
10 | @type t :: %Confirm{
11 | color: Color.t(),
12 | background_color: Color.t(),
13 | default_answer: :yes | :no,
14 | trim: boolean(),
15 | question: binary(),
16 | error: nil | binary(),
17 | answer: nil | binary(),
18 | mask_line: boolean()
19 | }
20 |
21 | defstruct [
22 | :color,
23 | :background_color,
24 | :trim,
25 | :question,
26 | :answer,
27 | :error,
28 | :default_answer,
29 | :mask_line
30 | ]
31 |
32 | @spec new(binary(), keyword()) :: t()
33 | def new(question, options) do
34 | %Confirm{
35 | color: Keyword.get(options, :color, ANSI.default_color()),
36 | trim: Keyword.get(options, :trim),
37 | default_answer: Keyword.get(options, :default_answer),
38 | question: question,
39 | answer: nil,
40 | error: nil,
41 | mask_line: Keyword.get(options, :mask_line, false)
42 | }
43 | end
44 |
45 | defimpl Prompt.IO do
46 | def display(%Confirm{} = confirm) do
47 | if confirm.mask_line do
48 | ANSI.format([
49 | :reset,
50 | background_color(confirm),
51 | confirm.color,
52 | "#{confirm.question} #{confirm_text(confirm.default_answer)} ",
53 | :reset
54 | ])
55 | |> write()
56 | else
57 | [
58 | :reset,
59 | background_color(confirm),
60 | confirm.color,
61 | "#{confirm.question} #{confirm_text(confirm.default_answer)} ",
62 | :reset,
63 | without_newline(confirm.trim)
64 | ]
65 | |> ANSI.format()
66 | |> write()
67 | end
68 |
69 | confirm
70 | end
71 |
72 | @spec evaluate(Prompt.IO.Confirm.t()) :: :yes | :no | :error
73 | def evaluate(%Confirm{} = confirm) do
74 | case read(:stdio, :line) do
75 | :eof ->
76 | :error
77 |
78 | {:error, _reason} ->
79 | :error
80 |
81 | answer when is_binary(answer) ->
82 | if confirm.mask_line do
83 | Prompt.Position.mask_line(1)
84 | end
85 |
86 | evaluate_confirm(%{confirm | answer: answer})
87 |
88 | answer when is_list(answer) ->
89 | if confirm.mask_line do
90 | Prompt.Position.mask_line(1)
91 | end
92 |
93 | evaluate_confirm(%{confirm | answer: IO.chardata_to_string(answer)})
94 | end
95 | end
96 |
97 | defp confirm_text(:yes), do: "(Y/n):"
98 | defp confirm_text(:no), do: "(y/N):"
99 |
100 | defp evaluate_confirm(%Confirm{} = confirm) do
101 | confirm.answer
102 | |> String.trim()
103 | |> String.downcase()
104 | |> _evaluate_confirm(confirm)
105 | end
106 |
107 | defp _evaluate_confirm("y", _), do: :yes
108 | defp _evaluate_confirm("n", _), do: :no
109 | defp _evaluate_confirm("", confirm), do: confirm.default_answer
110 | defp _evaluate_confirm(_, confirm), do: confirm |> display() |> evaluate()
111 |
112 | defp background_color(display) do
113 | case display.background_color do
114 | nil -> ANSI.default_background()
115 | res -> String.to_atom("#{Atom.to_string(res)}_background")
116 | end
117 | end
118 |
119 | defp without_newline(true), do: ""
120 | defp without_newline(false), do: "\n"
121 | end
122 | end
123 |
--------------------------------------------------------------------------------
/mix.lock:
--------------------------------------------------------------------------------
1 | %{
2 | "bunt": {:hex, :bunt, "1.0.0", "081c2c665f086849e6d57900292b3a161727ab40431219529f13c4ddcf3e7a44", [:mix], [], "hexpm", "dc5f86aa08a5f6fa6b8096f0735c4e76d54ae5c9fa2c143e5a1fc7c1cd9bb6b5"},
3 | "credo": {:hex, :credo, "1.7.7", "771445037228f763f9b2afd612b6aa2fd8e28432a95dbbc60d8e03ce71ba4446", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "8bc87496c9aaacdc3f90f01b7b0582467b69b4bd2441fe8aae3109d843cc2f2e"},
4 | "dialyxir": {:hex, :dialyxir, "1.4.3", "edd0124f358f0b9e95bfe53a9fcf806d615d8f838e2202a9f430d59566b6b53b", [:mix], [{:erlex, ">= 0.2.6", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "bf2cfb75cd5c5006bec30141b131663299c661a864ec7fbbc72dfa557487a986"},
5 | "earmark_parser": {:hex, :earmark_parser, "1.4.44", "f20830dd6b5c77afe2b063777ddbbff09f9759396500cdbe7523efd58d7a339c", [:mix], [], "hexpm", "4778ac752b4701a5599215f7030989c989ffdc4f6df457c5f36938cc2d2a2750"},
6 | "erlex": {:hex, :erlex, "0.2.6", "c7987d15e899c7a2f34f5420d2a2ea0d659682c06ac607572df55a43753aa12e", [:mix], [], "hexpm", "2ed2e25711feb44d52b17d2780eabf998452f6efda104877a3881c2f8c0c0c75"},
7 | "ex_doc": {:hex, :ex_doc, "0.39.1", "e19d356a1ba1e8f8cfc79ce1c3f83884b6abfcb79329d435d4bbb3e97ccc286e", [:mix], [{:earmark_parser, "~> 1.4.44", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.0", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14 or ~> 1.0", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1 or ~> 1.0", [hex: :makeup_erlang, repo: "hexpm", optional: false]}, {:makeup_html, ">= 0.1.0", [hex: :makeup_html, repo: "hexpm", optional: true]}], "hexpm", "8abf0ed3e3ca87c0847dfc4168ceab5bedfe881692f1b7c45f4a11b232806865"},
8 | "file_system": {:hex, :file_system, "1.0.0", "b689cc7dcee665f774de94b5a832e578bd7963c8e637ef940cd44327db7de2cd", [:mix], [], "hexpm", "6752092d66aec5a10e662aefeed8ddb9531d79db0bc145bb8c40325ca1d8536d"},
9 | "jason": {:hex, :jason, "1.4.3", "d3f984eeb96fe53b85d20e0b049f03e57d075b5acda3ac8d465c969a2536c17b", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "9a90e868927f7c777689baa16d86f4d0e086d968db5c05d917ccff6d443e58a3"},
10 | "makeup": {:hex, :makeup, "1.2.1", "e90ac1c65589ef354378def3ba19d401e739ee7ee06fb47f94c687016e3713d1", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "d36484867b0bae0fea568d10131197a4c2e47056a6fbe84922bf6ba71c8d17ce"},
11 | "makeup_elixir": {:hex, :makeup_elixir, "1.0.1", "e928a4f984e795e41e3abd27bfc09f51db16ab8ba1aebdba2b3a575437efafc2", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "7284900d412a3e5cfd97fdaed4f5ed389b8f2b4cb49efc0eb3bd10e2febf9507"},
12 | "makeup_erlang": {:hex, :makeup_erlang, "1.0.2", "03e1804074b3aa64d5fad7aa64601ed0fb395337b982d9bcf04029d68d51b6a7", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "af33ff7ef368d5893e4a267933e7744e46ce3cf1f61e2dccf53a111ed3aa3727"},
13 | "nimble_options": {:hex, :nimble_options, "1.1.1", "e3a492d54d85fc3fd7c5baf411d9d2852922f66e69476317787a7b2bb000a61b", [:mix], [], "hexpm", "821b2470ca9442c4b6984882fe9bb0389371b8ddec4d45a9504f00a66f650b44"},
14 | "nimble_parsec": {:hex, :nimble_parsec, "1.4.2", "8efba0122db06df95bfaa78f791344a89352ba04baedd3849593bfce4d0dc1c6", [:mix], [], "hexpm", "4b21398942dda052b403bbe1da991ccd03a053668d147d53fb8c4e0efe09c973"},
15 | }
16 |
--------------------------------------------------------------------------------
/lib/prompt/command.ex:
--------------------------------------------------------------------------------
1 | # Prompt - library to help create interative CLI in Elixir
2 | # Copyright (C) 2020 Matt Silbernagel
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 | defmodule Prompt.Command do
17 | @moduledoc """
18 | Helps users define and build command line commands.
19 |
20 | Defines the behaviour for a Command.
21 |
22 | We expect `init/1` to be called with the command line options and get
23 | back a data structure that is passed to `process/1` which handles all
24 | of the side effects of the command itself.
25 |
26 | ## Example
27 | ```
28 | defmodule MyCommand do
29 | @moduledoc "MyCommand's help message help() is defined in the __using__ macro that prints this message if called"
30 |
31 | use Prompt.Command
32 |
33 | @impl true
34 | def init(_argv) do
35 | # parse list of args to a struct if desired
36 | %SomeStruct{list: true, help: false, directory: "path/to/dir"}
37 | end
38 |
39 | @impl true
40 | def process(%{help: true}), do: help() # this help function is defined by default in the macro that prints the @moduledoc when called
41 | def process(%{list: true, help: false, directory: dir}) do
42 | display(File.ls!(dir))
43 | end
44 |
45 | end
46 | ```
47 |
48 | If this is used in a release, `help()` won't print the @moduledoc correctly because releases strip documentation by default. For this to work correctly, tell the release to keep docs:
49 | ```
50 | releases: [
51 | appname: [
52 | strip_beams: [keep: ["Docs"]]
53 | ]
54 | ]
55 | ```
56 |
57 | """
58 |
59 | @doc """
60 | Takes the options passed in via the command line and
61 | tramforms them into a struct that the process command can handle
62 | """
63 | @callback init(map()) :: term
64 |
65 | @doc """
66 | Prints the help available for this command
67 | """
68 | @callback help() :: :ok
69 |
70 | @doc """
71 | Processes the command and does the things required
72 | """
73 | @callback process(term) :: :ok | {:error, binary()}
74 | @doc false
75 | defmacro __using__(_opts) do
76 | quote do
77 | @behaviour Prompt.Command
78 | import Prompt
79 |
80 | @doc false
81 | @impl Prompt.Command
82 | def help do
83 | help =
84 | case Code.fetch_docs(__MODULE__) do
85 | {:docs_v1, _, :elixir, _, :none, _, _} -> "Help not available"
86 | {:docs_v1, _, :elixir, _, %{"en" => module_doc}, _, _} -> module_doc
87 | {:error, _} -> "Help not available"
88 | _ -> "Help not available"
89 | end
90 |
91 | display(help)
92 | end
93 |
94 | defoverridable help: 0
95 |
96 | @doc false
97 | @impl Prompt.Command
98 | def init(init_arg) do
99 | init_arg
100 | end
101 |
102 | defoverridable init: 1
103 |
104 | @before_compile Prompt.Command
105 | end
106 | end
107 |
108 | defmacro __before_compile__(env) do
109 | unless Module.defines?(env.module, {:process, 1}) do
110 | message = """
111 | function process/1 required by behaviour Prompt.Command is not implemented \
112 | (in module #{inspect(env.module)}).
113 |
114 | You'll need to create the function that takes a list of input and preforms the appropriate actions.
115 | """
116 |
117 | IO.warn(message, Macro.Env.stacktrace(env))
118 | end
119 | end
120 | end
121 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | [](https://hexdocs.pm/prompt/Prompt.html#content)
4 |
5 | > Main development happens in [Codeberg](https://codeberg.org/ahappydeath/prompt)
6 | >
7 | > Mirrored to [Github](https://github.com/silbermm/prompt)
8 |
9 | # Terminal UI Library for Elixir
10 | * [Motivation](#motivation)
11 | * [Installation](#installation)
12 | * [Basic Usage](#basic-usage)
13 | * [Display text on the screen](#display-text-on-the-screen)
14 | * [Ask the user for input](#ask-the-user-for-input)
15 | * [Ask the user for a password](#ask-the-user-for-a-password)
16 | * [Ask the user for confirmation](#ask-the-user-for-confirmation)
17 | * [Custom confirmation choices](#custom-confirmation-choices)
18 | * [List of selections](#list-of-selections)
19 | * [Tables](#tables)
20 | * [Advanced Usage](#advanced-usage-with-subcommands)
21 | * [Example Application](#example)
22 |
23 | [](https://livebook.dev/run?url=https%3A%2F%2Fgithub.com%2Fsilbermm%2Fprompt%2Fblob%2Fmain%2Fexample.livemd)
24 |
25 | ## Motivation
26 |
27 | To create a really great development experience and API for Elixir developers that want to build commandline tools.
28 |
29 | ## Installation
30 |
31 | Add `prompt` to your list of dependencies in `mix.exs`:
32 |
33 | ```elixir
34 | def deps do
35 | [
36 | {:prompt, "~> 0.10.0"}
37 | ]
38 | end
39 | ```
40 |
41 | [Read the official documentation](https://hexdocs.pm/prompt/Prompt.html)
42 |
43 | ## Basic Usage
44 | All of the following commands take a keyword list of options for things like text color and positioning.
45 |
46 | ### Display text on the screen
47 | [Prompt.display/2](https://hexdocs.pm/prompt/Prompt.html#display/2)
48 | ```elixir
49 | Prompt.display("Hello, world!")
50 | ```
51 |
52 | ### Ask the user for input
53 | [Prompt.text/2](https://hexdocs.pm/prompt/Prompt.html#text/2)
54 | Useful for prompting the user to enter freeform text
55 | ```elixir
56 | Prompt.text("Enter info here")
57 | ```
58 | Will display:
59 | ```bash
60 | > Enter info here:
61 | ```
62 | and wait for the user to enter text
63 |
64 | ### Ask the user for a password
65 | [Prompt.password/2](https://hexdocs.pm/prompt/Prompt.html#password/2)
66 | When you need to hide the input that the user types
67 | ```elixir
68 | Prompt.password("Enter password")
69 | ```
70 |
71 | ### Ask the user for confirmation
72 | [Prompt.confirm/2](https://hexdocs.pm/prompt/Prompt.html#confirm/2)
73 | ```elixir
74 | Prompt.confirm("Are you sure?")
75 | ```
76 | Will display:
77 | ```bash
78 | > Are you sure? (Y/n):
79 | ```
80 | and will allow the user to just press [enter] to confirm
81 |
82 | If you'd prefer `n` to be the default pass the `default_answer` option
83 | ```elixir
84 | Prompt.confirm("Are you sure?", default_answer: :no)
85 | ```
86 | Returns `:yes` or `:no` based on the answer
87 |
88 | ### Custom confirmation choices
89 | [Prompt.choice/2](https://hexdocs.pm/prompt/Prompt.html#choice/2)
90 | Sometimes yes/no aren't the only choices a user can make, this method allows you to pass any choices as the confirmation.
91 | ```elixir
92 | Prompt.choice("Accept, Reload or Cancel", accept: "a", reload: "r", cancel: "c")
93 | ```
94 | displays
95 | ```bash
96 | > Accept, Reload or Cancel (A/r/c):
97 | ```
98 | Returns the key of the answer i.e `:accept`, `:reload` or `cancel` in this exammple
99 |
100 | ### List of selections
101 | [Prompt.select/2](https://hexdocs.pm/prompt/Prompt.html#select/2)
102 | To show the user a list of options to select from
103 |
104 | ```elixir
105 | Prompt.select("Choose a protocol", ["file://", "ssh://", "ftp://"])
106 | ```
107 | Displays:
108 | ```bash
109 | [1] file://
110 | [2] ssh://
111 | [3] ftp://
112 | > Choose a protocol [1-3]:
113 | ```
114 | and returns a string of their choice
115 |
116 | ### Tables
117 | [Prompt.table/2](https://hexdocs.pm/prompt/Prompt.html#table/2)
118 | To show a table of data
119 | ```elixir
120 | Prompt.table([["Hello", "from", "the", "terminal!"],["this", "is", "another", "row"]])
121 | ```
122 | Will display
123 | ```bash
124 | > +-------+------+---------+----------+
125 | | Hello | from | the | terminal |
126 | | this | is | another | row |
127 | +-------+------+---------+----------+
128 | ```
129 |
130 | ## Advanced Usage with Subcommands
131 | To use the more advanced features, see the [official documentation](https://hexdocs.pm/prompt/Prompt.html#module-subcommands)
132 |
133 | ## Example
134 | For a complete example, take a look at [Genex - a password manager](https://git.sr.ht/~ahappydeath/genex)
135 |
--------------------------------------------------------------------------------
/flake.lock:
--------------------------------------------------------------------------------
1 | {
2 | "nodes": {
3 | "beam-flakes": {
4 | "inputs": {
5 | "flake-parts": [
6 | "expertpkg",
7 | "flake-parts"
8 | ],
9 | "nixpkgs": [
10 | "expertpkg",
11 | "nixpkgs"
12 | ]
13 | },
14 | "locked": {
15 | "lastModified": 1763144771,
16 | "narHash": "sha256-VWF3RK2lNPX5tz14LnJM7DXkP1YwgrTuu3RqeVEymCk=",
17 | "owner": "elixir-tools",
18 | "repo": "nix-beam-flakes",
19 | "rev": "0927b7964669ff9301e90ec5753ac81885a4b1bf",
20 | "type": "github"
21 | },
22 | "original": {
23 | "owner": "elixir-tools",
24 | "repo": "nix-beam-flakes",
25 | "type": "github"
26 | }
27 | },
28 | "expertpkg": {
29 | "inputs": {
30 | "beam-flakes": "beam-flakes",
31 | "flake-parts": "flake-parts",
32 | "nixpkgs": "nixpkgs"
33 | },
34 | "locked": {
35 | "lastModified": 1764217863,
36 | "narHash": "sha256-86U5X6vrYG81oyY0AAH5G8av/8F/cbhmSGiZcrygjeQ=",
37 | "owner": "elixir-lang",
38 | "repo": "expert",
39 | "rev": "b237fd547a0bc3a34df2574b2d1c1fee47d1f2b6",
40 | "type": "github"
41 | },
42 | "original": {
43 | "owner": "elixir-lang",
44 | "repo": "expert",
45 | "type": "github"
46 | }
47 | },
48 | "flake-parts": {
49 | "inputs": {
50 | "nixpkgs-lib": "nixpkgs-lib"
51 | },
52 | "locked": {
53 | "lastModified": 1762980239,
54 | "narHash": "sha256-8oNVE8TrD19ulHinjaqONf9QWCKK+w4url56cdStMpM=",
55 | "owner": "hercules-ci",
56 | "repo": "flake-parts",
57 | "rev": "52a2caecc898d0b46b2b905f058ccc5081f842da",
58 | "type": "github"
59 | },
60 | "original": {
61 | "owner": "hercules-ci",
62 | "repo": "flake-parts",
63 | "type": "github"
64 | }
65 | },
66 | "flake-utils": {
67 | "inputs": {
68 | "systems": [
69 | "systems"
70 | ]
71 | },
72 | "locked": {
73 | "lastModified": 1731533236,
74 | "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
75 | "owner": "numtide",
76 | "repo": "flake-utils",
77 | "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
78 | "type": "github"
79 | },
80 | "original": {
81 | "owner": "numtide",
82 | "repo": "flake-utils",
83 | "type": "github"
84 | }
85 | },
86 | "nixpkgs": {
87 | "locked": {
88 | "lastModified": 1762977756,
89 | "narHash": "sha256-4PqRErxfe+2toFJFgcRKZ0UI9NSIOJa+7RXVtBhy4KE=",
90 | "owner": "nixos",
91 | "repo": "nixpkgs",
92 | "rev": "c5ae371f1a6a7fd27823bc500d9390b38c05fa55",
93 | "type": "github"
94 | },
95 | "original": {
96 | "owner": "nixos",
97 | "ref": "nixos-unstable",
98 | "repo": "nixpkgs",
99 | "type": "github"
100 | }
101 | },
102 | "nixpkgs-lib": {
103 | "locked": {
104 | "lastModified": 1761765539,
105 | "narHash": "sha256-b0yj6kfvO8ApcSE+QmA6mUfu8IYG6/uU28OFn4PaC8M=",
106 | "owner": "nix-community",
107 | "repo": "nixpkgs.lib",
108 | "rev": "719359f4562934ae99f5443f20aa06c2ffff91fc",
109 | "type": "github"
110 | },
111 | "original": {
112 | "owner": "nix-community",
113 | "repo": "nixpkgs.lib",
114 | "type": "github"
115 | }
116 | },
117 | "nixpkgs_2": {
118 | "locked": {
119 | "lastModified": 1764242076,
120 | "narHash": "sha256-sKoIWfnijJ0+9e4wRvIgm/HgE27bzwQxcEmo2J/gNpI=",
121 | "owner": "nixos",
122 | "repo": "nixpkgs",
123 | "rev": "2fad6eac6077f03fe109c4d4eb171cf96791faa4",
124 | "type": "github"
125 | },
126 | "original": {
127 | "owner": "nixos",
128 | "ref": "nixos-unstable",
129 | "repo": "nixpkgs",
130 | "type": "github"
131 | }
132 | },
133 | "root": {
134 | "inputs": {
135 | "expertpkg": "expertpkg",
136 | "flake-utils": "flake-utils",
137 | "nixpkgs": "nixpkgs_2",
138 | "systems": "systems"
139 | }
140 | },
141 | "systems": {
142 | "locked": {
143 | "lastModified": 1681028828,
144 | "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
145 | "owner": "nix-systems",
146 | "repo": "default",
147 | "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
148 | "type": "github"
149 | },
150 | "original": {
151 | "owner": "nix-systems",
152 | "repo": "default",
153 | "type": "github"
154 | }
155 | }
156 | },
157 | "root": "root",
158 | "version": 7
159 | }
160 |
--------------------------------------------------------------------------------
/lib/prompt/io/select.ex:
--------------------------------------------------------------------------------
1 | # Prompt - library to help create interative CLI in Elixir
2 | # Copyright (C) 2021 Matt Silbernagel
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 | defmodule Prompt.IO.Select do
17 | @moduledoc false
18 |
19 | alias __MODULE__
20 | alias IO.ANSI
21 | import IO, only: [write: 1, read: 2]
22 |
23 | @typep color ::
24 | :black
25 | | :blue
26 | | :cyan
27 | | :green
28 | | :light_black
29 | | :light_blue
30 | | :light_cyan
31 | | :light_green
32 | | :light_magneta
33 | | :light_red
34 | | :light_white
35 | | :light_yellow
36 | | :magenta
37 | | :red
38 | | :white
39 | | :yellow
40 |
41 | @type t :: %Select{
42 | color: color(),
43 | background_color: color(),
44 | multi: boolean(),
45 | trim: boolean(),
46 | display: binary(),
47 | choices: list(binary()),
48 | error: nil | binary(),
49 | answer: nil | binary() | list(binary)
50 | }
51 |
52 | defstruct [:color, :background_color, :multi, :trim, :display, :choices, :answer, :error]
53 |
54 | @spec new(binary(), list(binary()), keyword()) :: t()
55 | def new(display, choices, opts) when is_list(choices) do
56 | %Select{
57 | color: Keyword.get(opts, :color, ANSI.default_color()),
58 | background_color: Keyword.get(opts, :background_color),
59 | multi: Keyword.get(opts, :multi),
60 | trim: Keyword.get(opts, :trim),
61 | display: display,
62 | choices: choices,
63 | answer: nil,
64 | error: nil
65 | }
66 | end
67 |
68 | defimpl Prompt.IO do
69 | @spec display(Prompt.IO.Select.t()) :: Prompt.IO.Select.t()
70 | def display(%Select{} = select) do
71 | for {choice, number} <- Enum.with_index(select.choices) do
72 | [
73 | :reset,
74 | background_color(select),
75 | select.color,
76 | :bright,
77 | "\n",
78 | ANSI.cursor_left(1000),
79 | ANSI.cursor_right(2),
80 | select_text(choice, number)
81 | ]
82 | |> ANSI.format()
83 | |> write()
84 | end
85 |
86 | [
87 | "\n",
88 | "\n",
89 | ANSI.cursor_left(1000),
90 | background_color(select),
91 | select.color,
92 | "#{select.display} [1-#{Enum.count(select.choices)}]:"
93 | ]
94 | |> ANSI.format()
95 | |> write()
96 |
97 | select
98 | end
99 |
100 | @spec evaluate(Prompt.IO.Select.t()) :: binary() | list(binary)
101 | def evaluate(%Select{} = select) do
102 | case read(:stdio, :line) do
103 | :eof ->
104 | %Select{select | error: "reached end of file when reading input"}
105 |
106 | {:error, reason} ->
107 | %Select{select | error: reason}
108 |
109 | answer when is_binary(answer) ->
110 | answer
111 | |> String.trim()
112 | |> do_evaluate(select)
113 |
114 | answer when is_list(answer) ->
115 | answer
116 | |> IO.chardata_to_string()
117 | |> String.trim()
118 | |> do_evaluate(select)
119 | end
120 | end
121 |
122 | defp do_evaluate(answer, select) do
123 | evaluate_choice_answer(answer, select)
124 | |> case do
125 | %Select{error: err} = s when not is_nil(err) ->
126 | s
127 | |> show_select_error()
128 | |> evaluate()
129 |
130 | %Select{answer: answer} ->
131 | answer
132 | end
133 | end
134 |
135 | defp select_text({dis, _}, number), do: "[#{number + 1}] #{dis}"
136 | defp select_text(choice, number), do: "[#{number + 1}] #{choice}"
137 |
138 | defp show_select_error(select) do
139 | text =
140 | if select.multi do
141 | "Enter numbers from 1-#{Enum.count(select.choices)} seperated by spaces: "
142 | else
143 | "Enter a number from 1-#{Enum.count(select.choices)}: "
144 | end
145 |
146 | [
147 | select.color,
148 | background_color(select),
149 | :bright,
150 | text
151 | ]
152 | |> ANSI.format()
153 | |> write
154 |
155 | # reset error
156 | %{select | error: nil}
157 | end
158 |
159 | defp evaluate_choice_answer(answers, %Select{multi: true} = select) do
160 | answer_numbers = String.split(answers, " ")
161 |
162 | answer_data =
163 | for answer_number <- answer_numbers do
164 | idx = String.to_integer(answer_number) - 1
165 |
166 | case Enum.at(select.choices, idx) do
167 | nil -> nil
168 | {_, result} -> result
169 | result -> result
170 | end
171 | end
172 |
173 | if Enum.any?(answer_data, fn a -> a == nil end) do
174 | %Select{select | error: :invalid_answer}
175 | else
176 | %Select{select | answer: answer_data}
177 | end
178 | catch
179 | _kind, error ->
180 | %Select{select | error: error}
181 | end
182 |
183 | defp evaluate_choice_answer(answer, %Select{multi: false} = select) do
184 | answer_number = String.to_integer(answer) - 1
185 |
186 | case Enum.at(select.choices, answer_number) do
187 | nil -> %Select{select | error: :invalid_answer}
188 | {_, result} -> %Select{select | answer: result}
189 | result -> %Select{select | answer: result}
190 | end
191 | catch
192 | _kind, error ->
193 | %Select{select | error: error}
194 | end
195 |
196 | defp background_color(select) do
197 | case select.background_color do
198 | nil -> ANSI.default_background()
199 | res -> String.to_atom("#{Atom.to_string(res)}_background")
200 | end
201 | end
202 | end
203 | end
204 |
--------------------------------------------------------------------------------
/test/prompt_test.exs:
--------------------------------------------------------------------------------
1 | defmodule PromptTest do
2 | use ExUnit.Case
3 | import ExUnit.CaptureIO
4 |
5 | describe "confirm" do
6 | test "handle confirm" do
7 | assert capture_io("y", fn ->
8 | result = Prompt.confirm("Send the email?")
9 | assert result == :yes
10 | end) =~ "Send the email? (Y/n): "
11 | end
12 |
13 | test "handle confirm - default" do
14 | assert capture_io("\n", fn ->
15 | result = Prompt.confirm("Send the email?", [])
16 | assert result == :yes
17 | end) =~ "Send the email? (Y/n): "
18 | end
19 |
20 | test "handle confirm - default to no" do
21 | assert capture_io("\n", fn ->
22 | result = Prompt.confirm("Send the email?", default_answer: :no)
23 | assert result == :no
24 | end) =~ "Send the email? (y/N): "
25 | end
26 |
27 | test "handle confirm - no" do
28 | assert capture_io("n", fn ->
29 | result = Prompt.confirm("Send the email?", [])
30 | assert result == :no
31 | end) =~ "Send the email? (Y/n): "
32 | end
33 |
34 | test "handle confirm - unknown answer" do
35 | assert capture_io("asdf", fn ->
36 | Prompt.confirm("Send the email?", [])
37 | end) =~ "Send the email? (Y/n): "
38 | end
39 |
40 | test "handle confirm - mask output" do
41 | assert capture_io("y", fn ->
42 | result = Prompt.confirm("Send the email?", mask_line: true)
43 | assert result == :yes
44 | end) =~ "#######"
45 | end
46 | end
47 |
48 | describe "choice" do
49 | test "handle custom choices" do
50 | assert capture_io("y", fn ->
51 | result = Prompt.choice("Send the email?", yes: "y", no: "n")
52 | assert result == :yes
53 | end) =~ "Send the email? (Y/n): "
54 | end
55 |
56 | test "handle many custom choices" do
57 | assert capture_io("y", fn ->
58 | result = Prompt.choice("Send the email?", yes: "y", no: "n", cancel: "c")
59 | assert result == :yes
60 | end) =~ "Send the email? (Y/n/c): "
61 | end
62 |
63 | test "handle many custom choices - default" do
64 | assert capture_io("\n", fn ->
65 | result =
66 | Prompt.choice("Send the email?", [yes: "y", no: "n", cancel: "c"],
67 | default_answer: :cancel
68 | )
69 |
70 | assert result == :cancel
71 | end) =~ "Send the email? (y/n/C): "
72 | end
73 | end
74 |
75 | describe "select" do
76 | test "returns selected option" do
77 | assert capture_io("1", fn ->
78 | result = Prompt.select("Which email?", ["t@t.com", "a@a.com"])
79 | assert result == "t@t.com"
80 | end) =~ "Which email? [1-2]:"
81 | end
82 |
83 | test "requires choice from list" do
84 | assert capture_io("3", fn ->
85 | Prompt.select("Which email?", ["t@t.com", "a@a.com"])
86 | end) =~ "Enter a number from 1-2: "
87 | end
88 |
89 | test "requires valid number" do
90 | assert capture_io("one", fn ->
91 | Prompt.select("Which email?", ["t@t.com", "a@a.com"])
92 | end) =~ "Enter a number from 1-2: "
93 | end
94 |
95 | test "allows list of tuples" do
96 | assert capture_io("1", fn ->
97 | result = Prompt.select("Which email?", [{"t@t.com", "t"}, {"a@a.com", "a"}])
98 | assert result == "t"
99 | end) =~ "Which email? [1-2]:"
100 | end
101 |
102 | test "returns selected options(multi)" do
103 | assert capture_io("1 2", fn ->
104 | result = Prompt.select("Which email?", ["t@t.com", "a@a.com"], multi: true)
105 | assert result == ["t@t.com", "a@a.com"]
106 | end) =~ "Which email? [1-2]:"
107 | end
108 |
109 | test "allows list of tuples(multi)" do
110 | assert capture_io("1 2", fn ->
111 | result =
112 | Prompt.select("Which email?", [{"t@t.com", "t"}, {"a@a.com", "a"}], multi: true)
113 |
114 | assert result == ["t", "a"]
115 | end) =~ "Which email? [1-2]:"
116 | end
117 |
118 | test "returns selected options(multi) - requires integers" do
119 | assert capture_io("one", fn ->
120 | Prompt.select("Which email?", ["t@t.com", "a@a.com"], multi: true)
121 | end) =~ "Enter numbers from 1-2 seperated by spaces: "
122 | end
123 |
124 | test "returns selected options(multi) - requires choice" do
125 | assert capture_io("3", fn ->
126 | Prompt.select("Which email?", ["t@t.com", "a@a.com"], multi: true)
127 | end) =~ "Enter numbers from 1-2 seperated by spaces: "
128 | end
129 | end
130 |
131 | describe "text" do
132 | test "returns input" do
133 | assert capture_io("t@t.com", fn ->
134 | result = Prompt.text("email address")
135 | assert result == "t@t.com"
136 | end)
137 | end
138 |
139 | test "validates min length" do
140 | assert capture_io("t@", fn ->
141 | result = Prompt.text("email address", min: 3)
142 | assert result == :error_min
143 | end)
144 | end
145 |
146 | test "validates max length" do
147 | assert capture_io("t@t.com", fn ->
148 | result = Prompt.text("email address", max: 3)
149 | assert result == :error_max
150 | end)
151 | end
152 | end
153 |
154 | describe "password" do
155 | test "ask for hidden input" do
156 | assert capture_io("password", fn ->
157 | result = Prompt.password("Enter Password: ")
158 | assert result == "password"
159 | end)
160 | end
161 | end
162 |
163 | describe "display" do
164 | test "hides text on enter" do
165 | assert capture_io("\n", fn ->
166 | assert Prompt.display("password", mask_line: true) == :ok
167 | end) =~ "#######"
168 | end
169 |
170 | test "shows list of text" do
171 | assert capture_io(fn ->
172 | assert Prompt.display(["hello", "world"]) == :ok
173 | end) =~ "world"
174 | end
175 |
176 | test "shows text on the right" do
177 | assert capture_io(fn ->
178 | assert Prompt.display("hello", position: :right) == :ok
179 | end) =~ "hello"
180 | end
181 | end
182 |
183 | describe "tables" do
184 | test "display simple table" do
185 | assert capture_io(fn ->
186 | Prompt.table([
187 | ["Hello", "from", "the", "terminal!"],
188 | ["this", "is", "another", "row"]
189 | ])
190 | end) =~
191 | "\e[39m+-------+------+---------+-----------+\n| Hello | from | the | terminal! |\n| this | is | another | row |\n+-------+------+---------+-----------+\n"
192 | end
193 |
194 | test "display simple table with headers" do
195 | assert capture_io(fn ->
196 | Prompt.table(
197 | [
198 | ["Hello", "from", "the", "terminal!"],
199 | ["this", "is", "another", "row"]
200 | ],
201 | header: true
202 | )
203 | end) =~
204 | "\e[39m+-------+------+---------+-----------+\n| Hello | from | the | terminal! |\n+-------+------+---------+-----------+\n| this | is | another | row |\n+-------+------+---------+-----------+\n"
205 | end
206 |
207 | test "return table data" do
208 | assert Prompt.table_data([
209 | ["Hello", "from", "the", "terminal!"],
210 | ["this", "is", "another", "row"]
211 | ]) ==
212 | [
213 | [["+-------", "+------", "+---------", "+-----------"], "+", "\n"],
214 | "",
215 | [
216 | "| Hello | from | the | terminal! |\n",
217 | "| this | is | another | row |\n"
218 | ],
219 | [["+-------", "+------", "+---------", "+-----------"], "+", "\n"]
220 | ]
221 | end
222 | end
223 | end
224 |
--------------------------------------------------------------------------------
/lib/prompt/router.ex:
--------------------------------------------------------------------------------
1 | defmodule Prompt.Router do
2 | @moduledoc """
3 | Router for Prompt
4 |
5 | Simplifies defining commands, sub-commands and arguments.
6 |
7 | Choose the module responsible for taking the command line arguments and
8 | `use Prompt.Router, otp_app: :your_app` at the top.
9 |
10 | Then simply define your commands and arguments.
11 |
12 | Exposes a main/1 function that is called with the command line args
13 |
14 | ## Arguments
15 | See `arg/3`
16 |
17 | ## Example
18 |
19 | ```elixir
20 | defmodule My.CLI do
21 | use Prompt.Router, otp_app: :my_app
22 |
23 | command :checkout, My.CheckoutCommand do
24 | arg :help, :boolean
25 | arg :branch, :string, short: :b, default: "main"
26 | end
27 |
28 | command "", My.DefaultCommand do
29 | arg :info, :boolean
30 | end
31 | end
32 |
33 | defmodule My.CheckoutCommand do
34 | use Prompt.Command
35 |
36 | @impl true
37 | def process(arguments) do
38 | # arguments will be a map of the defined arguments and their values
39 | # from the command line input
40 | # If someone used the command and passed `--branch feature/test`, then
41 | # `argmuments would look like `%{help: false, branch: "feature/test"}`
42 | display("checking out " <> arguments.branch)
43 | end
44 | end
45 |
46 | defmodule My.DefaultCommand do
47 | use Prompt.Command
48 |
49 | @impl true
50 | def init(arguments) do
51 | # you can implement the `c:init/1` callback to transform
52 | # the arguments before `c:process/1` is called if you want
53 | arguments
54 | end
55 |
56 | @impl true
57 | def process(arguments) do
58 | # arguments will have a key of `:leftover` for anything
59 | # passed to the command that doesn't have a `arg` defined.
60 | # IF someone called this with `--info --test something`, then then
61 | # arguments will look like `%{info: true, leftover: ["--test", "something"]}`
62 | display("showing info")
63 | end
64 | end
65 | ```
66 |
67 | """
68 |
69 | @doc """
70 | The function responsible for filtering and calling the correct command
71 | module based on command line input
72 | """
73 | @callback main([binary()]) :: no_return()
74 |
75 | @doc """
76 | Prints help to the screen when there is an error, or `--help` is passed as an argument.
77 |
78 | Overridable
79 | """
80 | @callback help() :: non_neg_integer()
81 |
82 | @doc """
83 | Prints help to the screen when there is an error with a string indicating the error
84 |
85 | Overridable
86 | """
87 | @callback help(String.t()) :: non_neg_integer()
88 |
89 | @doc """
90 | Prints the version from the projects mix.exs file
91 |
92 | Overridable
93 | """
94 | @callback version() :: non_neg_integer()
95 |
96 | @doc """
97 | This function is called after the main function is done.
98 |
99 | It does it's best to handle any value returned from a command and turn
100 | it into an integer, 0 being a successful command and any non-zero being
101 | an error.
102 |
103 | Overrideable
104 | """
105 | @callback handle_exit_value(any()) :: no_return()
106 |
107 | @doc """
108 | Called when the flag `--completions string` is passed on the command-line.
109 |
110 | The default behaviour for this is to write the completion script to the
111 | screen.
112 |
113 | zsh is supported out of the box. If other completion scripts are required,
114 | this callback will need to be implemented.
115 |
116 | see https://github.com/zsh-users/zsh-completions/blob/master/zsh-completions-howto.org
117 |
118 | Overrideable
119 | """
120 | @callback generate_completions(binary()) :: non_neg_integer()
121 |
122 | defmacro __using__(opts) do
123 | app = Keyword.get(opts, :otp_app, nil)
124 |
125 | # credo:disable-for-next-line Credo.Check.Refactor.LongQuoteBlocks
126 | quote location: :keep do
127 | require unquote(__MODULE__)
128 | import unquote(__MODULE__)
129 | import Prompt, only: [display: 1, display: 2]
130 |
131 | Module.register_attribute(__MODULE__, :commands, accumulate: true, persist: true)
132 |
133 | @behaviour Prompt.Router
134 |
135 | @app unquote(app)
136 |
137 | @impl true
138 | def main(args) do
139 | commands =
140 | __MODULE__.module_info()
141 | |> Keyword.get(:attributes, [])
142 | |> Keyword.get_values(:commands)
143 | |> List.flatten()
144 |
145 | if commands == [] do
146 | raise "Please define some commands"
147 | end
148 |
149 | case Prompt.Router.process(args, commands) do
150 | :help ->
151 | handle_exit_value(help())
152 |
153 | {:help, reason} ->
154 | handle_exit_value(help(reason))
155 |
156 | :version ->
157 | handle_exit_value(version())
158 |
159 | {:completion, shell} ->
160 | generate_completions(shell)
161 |
162 | {mod, data} ->
163 | transformed = mod.init(data)
164 | result = mod.process(transformed)
165 | handle_exit_value(result)
166 | end
167 | end
168 |
169 | @impl true
170 | def help do
171 | help =
172 | case Code.fetch_docs(__MODULE__) do
173 | {:docs_v1, _, :elixir, _, :none, _, _} -> "Help not available"
174 | {:docs_v1, _, :elixir, _, %{"en" => module_doc}, _, _} -> module_doc
175 | {:error, _} -> "Help not available"
176 | _ -> "Help not available"
177 | end
178 |
179 | display(help)
180 | 0
181 | end
182 |
183 | @impl true
184 | def help(reason) do
185 | help =
186 | case Code.fetch_docs(__MODULE__) do
187 | {:docs_v1, _, :elixir, _, :none, _, _} -> "Help not available"
188 | {:docs_v1, _, :elixir, _, %{"en" => module_doc}, _, _} -> module_doc
189 | {:error, _} -> "Help not available"
190 | _ -> "Help not available"
191 | end
192 |
193 | display(reason, color: :red)
194 | display(help)
195 | 1
196 | end
197 |
198 | @impl true
199 | def version do
200 | {:ok, vsn} = :application.get_key(@app, :vsn)
201 | display(List.to_string(vsn))
202 | 0
203 | end
204 |
205 | @impl true
206 | def handle_exit_value(:ok), do: handle_exit_value(0)
207 |
208 | def handle_exit_value({:error, _reason}) do
209 | handle_exit_value(1)
210 | end
211 |
212 | def handle_exit_value(val) when is_integer(val) and val >= 0 do
213 | # Prevent exiting if running from an iex console.
214 | unless Code.ensure_loaded?(IEx) and IEx.started?() do
215 | System.halt(val)
216 | end
217 | end
218 |
219 | def handle_exit_value(anything_else) do
220 | handle_exit_value(2)
221 | end
222 |
223 | def generate_completions("zsh") do
224 | commands =
225 | __MODULE__.module_info()
226 | |> Keyword.get(:attributes, [])
227 | |> Keyword.get_values(:commands)
228 | |> List.flatten()
229 |
230 | args =
231 | for command <- commands, into: "" do
232 | "#{command.command_name}\u005c:'' "
233 | end
234 |
235 | line = "\"1: :((#{args}))\" \\"
236 |
237 | cases =
238 | for command <- commands, command.command_name != "", into: "" do
239 | ~s"""
240 | \t#{command.command_name})
241 | \t\t_#{@app}_#{command.command_name}
242 | \t;;
243 | """
244 | end
245 |
246 | funcs =
247 | for command <- commands, command.command_name != "", into: "" do
248 | ~s"""
249 | function _#{@app}_#{command.command_name} {
250 | \t_arguments \\
251 | \t\t#{for arg <- command.arguments, into: "" do
252 | "\"--#{arg.name}[]\" "
253 | end}
254 | }
255 |
256 | """
257 | end
258 |
259 | base = """
260 | #compdef #{@app}
261 | local line
262 |
263 | _arguments -C \\
264 | \t"--help[Show help information]" \\
265 | \t"--version[Show version information]" \\
266 | \t"--completion[Generate completion script]:shell_name:->shell_names" \\
267 | \t#{line}
268 | \t"*::arg:->args"
269 |
270 | case "$state" in
271 | \tshell_names)
272 | \t\t_values 'shell_names' zsh bash fish
273 | \t;;
274 | esac
275 |
276 | case $line[1] in
277 | #{cases}
278 | esac
279 |
280 | #{funcs}
281 | """
282 |
283 | display(base)
284 | 0
285 | end
286 |
287 | @impl true
288 | def generate_completions(shell) do
289 | display("Completions for #{shell} are not supported", color: :yellow)
290 | 1
291 | end
292 |
293 | defoverridable help: 0
294 | defoverridable help: 1
295 | defoverridable version: 0
296 | defoverridable handle_exit_value: 1
297 | defoverridable generate_completions: 1
298 | end
299 | end
300 |
301 | @doc false
302 | def process(argv, commands) do
303 | # first figure out which command was passed in
304 | argv
305 | |> OptionParser.parse_head(
306 | switches: [help: :boolean, version: :boolean, completion: :string],
307 | aliases: [h: :help, v: :version]
308 | )
309 | |> parse_opts(commands, argv)
310 | end
311 |
312 | # if help or version were passed, process them and exit
313 | defp parse_opts({[help: true], _, _}, _, _), do: :help
314 | defp parse_opts({[version: true], _, _}, _, _), do: :version
315 | defp parse_opts({[completion: shell], _, _}, _, _), do: {:completion, shell}
316 |
317 | defp parse_opts({_, additional, _}, defined_commands, original) do
318 | case additional do
319 | [head | rest] ->
320 | # if there is an array of data, then a subcommand was passed in
321 | command = find_in_defined_commands(defined_commands, head)
322 |
323 | if command == nil do
324 | # the passed in command or option is not recognized, try the fallback
325 | # passing the data as options
326 | fallback_command(original, defined_commands)
327 | else
328 | # process the options for the module
329 | switches = build_parser_switches(command)
330 | aliases = build_parser_aliases(command)
331 |
332 | {parsed, leftover, _} =
333 | OptionParser.parse_head(rest, switches: switches, aliases: aliases)
334 |
335 | data = build_command_data(command, parsed, leftover)
336 | {command.module, data}
337 | end
338 |
339 | [] ->
340 | # no subcommand was passed in try the fallback module
341 | fallback_command(original, defined_commands)
342 | end
343 | end
344 |
345 | defp fallback_command(original_args, defined_commands) do
346 | # no subcommand was passed in try the fallback module
347 | fallback = find_in_defined_commands(defined_commands, "")
348 |
349 | if fallback == nil do
350 | {:help, "invalid flag or command"}
351 | else
352 | switches = build_parser_switches(fallback)
353 | {parsed, leftover, _} = OptionParser.parse(original_args, switches: switches)
354 | data = build_command_data(fallback, parsed, leftover)
355 | {fallback.module, data}
356 | end
357 | end
358 |
359 | defp find_in_defined_commands(defined_commands, "") do
360 | Enum.find(defined_commands, fn
361 | %{command_name: ""} -> true
362 | _ -> false
363 | end)
364 | end
365 |
366 | defp find_in_defined_commands(defined_commands, command_value) do
367 | Enum.find(defined_commands, fn
368 | %{command_name: command_name_atom} -> command_value == to_string(command_name_atom)
369 | _ -> false
370 | end)
371 | end
372 |
373 | defp build_parser_switches(nil), do: []
374 |
375 | defp build_parser_switches(command) do
376 | Enum.map(command.arguments, &{&1.name, &1.type})
377 | end
378 |
379 | defp build_parser_aliases(nil), do: []
380 |
381 | defp build_parser_aliases(command) do
382 | for args <- command.arguments, reduce: [] do
383 | a ->
384 | if Keyword.has_key?(args.options, :short) do
385 | [{Keyword.get(args.options, :short), args.name} | a]
386 | else
387 | a
388 | end
389 | end
390 | end
391 |
392 | defp build_command_data(command, parsed, leftover) do
393 | command.arguments
394 | |> Enum.reduce(%{}, fn arg, acc ->
395 | Map.put_new(acc, arg.name, Keyword.get(parsed, arg.name, default_value(arg)))
396 | end)
397 | |> Map.put_new(:leftover, leftover)
398 | end
399 |
400 | defp default_value(%{type: type, options: [_ | _] = opts}),
401 | do: Keyword.get(opts, :default, default_value(%{type: type}))
402 |
403 | defp default_value(%{type: :boolean}), do: false
404 | defp default_value(%{type: :string}), do: ""
405 | defp default_value(%{type: :integer}), do: nil
406 | defp default_value(%{type: :float}), do: nil
407 |
408 | @doc """
409 | Name of the subcommand that is expectedaany()
410 |
411 | Takes an atom or string as the command name and a Prompt.Command module.
412 | """
413 | defmacro command(name, module, do: block) do
414 | args =
415 | case block do
416 | {:__block__, _, arguments} -> arguments
417 | {:arg, _, _} = args -> [args]
418 | end
419 |
420 | quote do
421 | new_args = Enum.map(unquote(args), fn o -> o end)
422 |
423 | res = %{
424 | command_name: unquote(name),
425 | module: unquote(module),
426 | arguments: new_args
427 | }
428 |
429 | Module.put_attribute(__MODULE__, :commands, res)
430 | end
431 | end
432 |
433 | defmacro command(name, module) do
434 | quote do
435 | res = %{
436 | command_name: unquote(name),
437 | module: unquote(module),
438 | arguments: []
439 | }
440 |
441 | Module.put_attribute(__MODULE__, :commands, res)
442 | end
443 | end
444 |
445 | @doc """
446 | Defines the arguments of a command.
447 | ## Argument Name
448 | This indicates what the user will type as the option to the sub-command.
449 | For example,
450 | ```elixir
451 | arg :print, :boolean
452 | ```
453 | would allow the user to type `$ your_command --print`
454 |
455 | ## Options
456 | Available options are:
457 | * default - a default value if the user doesn't use this option
458 | * short - an optional short argument option i.e `short: :h` would all the user to type `-h`
459 | """
460 | defmacro arg(arg_name, arg_type, opts \\ []) do
461 | quote do
462 | %{name: unquote(arg_name), type: unquote(arg_type), options: unquote(opts)}
463 | end
464 | end
465 | end
466 |
--------------------------------------------------------------------------------
/lib/prompt.ex:
--------------------------------------------------------------------------------
1 | # Prompt - library to help create interative CLI in Elixir
2 | # Copyright (C) 2021 Matt Silbernagel
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | defmodule Prompt do
18 | @moduledoc """
19 | Prompt provides a complete solution for building interactive command line applications.
20 |
21 | It's very flexible and can be used just to provide helpers for taking input from the user and displaying output.
22 |
23 | ## Basic Usage
24 | `import Prompt` includes utilities for:
25 | * printing to the screen -> `display/1`
26 | * printing tables to the screen -> `table/1`
27 | * asking for confirmation -> `confirm/1`
28 | * picking from a list of choices -> `select/2`
29 | * asking for passwords -> `password/1`
30 | * free form text input -> `text/1`
31 |
32 | ## Advanced usage
33 | See `Prompt.Router`
34 |
35 | ## Building for Distribution
36 |
37 | There are a couple of different options for building a binary ready for distributing. Which ever approach you decide to use, you'll probably want to keep the docs instead of stripping them.
38 | For escripts, you'll add the following to the escript key in mix.exs, if using Bakeware, you'll add it to the releases key.
39 |
40 | ```
41 | :strip_beams: [keep: ["Docs"]]
42 | ```
43 |
44 | ### Escript
45 | An [escript](https://hexdocs.pm/mix/master/Mix.Tasks.Escript.Build.html) is the most straightforward approach, but requires that erlang is already installed on the system.
46 |
47 | ### Bakeware
48 | This has been my preferred approach recently. [Bakeware](https://hexdocs.pm/bakeware/readme.html) uses releases to build a single executable binary that can be run on the system without the dependency on erlang or elixir.
49 |
50 | For Bakeware, I also set `export RELEASE_DISTRIBUTION=none` in `rel/env.sh.eex` and `rel/env.bat.eex` - unless you need erlang distribution in your CLI.
51 |
52 | For a complete example see [Genex](https://git.sr.ht/~ahappydeath/genex)
53 |
54 | Run `MIX_ENV=prod mix release` to build the binary. This will output the usual release messages for a `mix release` command, but in the case of a CLI, it's a bit of a red herring. The binary you want to run as a CLI will be in `_build/prod/rel/bakeware/`.
55 |
56 |
57 | ### Burrito
58 | [Burrito](https://github.com/burrito-elixir/burrito) is another option for building a single binary artifact. It is unique because you can build binaries for windows, mac and linux all from one machine.
59 |
60 | For a complete example see [Genex](https://github.com/silbermm/genex)
61 |
62 | Run `MIX_ENV=prod mix release` to build the binary. This will output the usual release messages for a `mix release` command, but in the case of a CLI, it's a bit of a red herring. The binary you want to run as a CLI will be in `burrito_out/`.
63 | """
64 |
65 | import IO
66 |
67 | @typedoc """
68 | A keyword list of commands and implementations of `Prompt.Command`
69 |
70 | ## Examples
71 |
72 | iex> commands = [help: CLI.Commands.Help, version: CLI.Commands.Version]
73 |
74 | """
75 | alias Prompt.IO.Choice
76 | alias Prompt.IO.Confirm
77 | alias Prompt.IO.Display
78 | alias Prompt.IO.Password
79 | alias Prompt.IO.Select
80 | alias Prompt.IO.Text
81 |
82 | @type command_list() :: keyword(Prompt.Command)
83 |
84 | @typedoc """
85 | The list of strings coming from the commmand-line arguments
86 | """
87 | @type argv() :: list(String.t())
88 |
89 | @colors Prompt.IO.Color.all()
90 |
91 | @confirm_options NimbleOptions.new!(
92 | color: [
93 | type: {:in, @colors},
94 | doc: "The text color. One of `#{Kernel.inspect(@colors)}`."
95 | ],
96 | background_color: [
97 | type: {:in, @colors},
98 | doc: "The background color. One of `#{Kernel.inspect(@colors)}`."
99 | ],
100 | default_answer: [
101 | type: {:in, [:yes, :no]},
102 | default: :yes,
103 | doc: "The default answer to the confirmation."
104 | ],
105 | mask_line: [
106 | type: :boolean,
107 | default: false,
108 | doc:
109 | "If set to true, this will mask the current line by replacing it with `#####`. Useful when showing passwords in the terminal."
110 | ],
111 | trim: [type: :boolean, default: true, doc: false],
112 | from: [type: :atom, default: :confirm, doc: false]
113 | )
114 | @doc section: :input
115 | @doc """
116 | Display a Y/n prompt.
117 |
118 | Sets 'Y' as the the default answer, allowing the user to just press the enter key. To make 'n' the default answer pass the option `default_answer: :no`
119 |
120 | Supported options:
121 | #{NimbleOptions.docs(@confirm_options)}
122 |
123 | ## Examples
124 |
125 | iex> Prompt.confirm("Send the email?")
126 | "Send the email? (Y/n):" Y
127 | iex> :yes
128 |
129 | iex> Prompt.confirm("Send the email?", default_answer: :no)
130 | "Send the email? (y/N):" [enter]
131 | iex> :no
132 |
133 | """
134 | @spec confirm(String.t(), keyword()) :: :yes | :no | :error
135 | def confirm(question, opts \\ []) do
136 | run(opts, @confirm_options, fn options ->
137 | Confirm.new(question, options)
138 | end)
139 | end
140 |
141 | @choice_options NimbleOptions.new!(
142 | color: [
143 | type: {:in, @colors},
144 | doc: "The text color. One of `#{Kernel.inspect(@colors)}`."
145 | ],
146 | background_color: [
147 | type: {:in, @colors},
148 | doc: "The background color. One of `#{Kernel.inspect(@colors)}`."
149 | ],
150 | default_answer: [
151 | type: :atom,
152 | doc: "The default answer for the choices. Defaults to the first choice."
153 | ],
154 | trim: [type: :boolean, default: true, doc: false],
155 | from: [type: :atom, default: :confirm, doc: false]
156 | )
157 |
158 | @doc section: :input
159 | @doc """
160 | Display a choice prompt with custom answers.
161 |
162 | Takes a keyword list of answers in the form of atom to return and string to display.
163 |
164 | `[yes: "y", no: "n"]`
165 |
166 | will show "(y/n)" and return `:yes` or `:no` based on the choice.
167 |
168 | Supported options:
169 | #{NimbleOptions.docs(@choice_options)}
170 |
171 | ## Examples
172 |
173 | iex> Prompt.choice("Save password?",
174 | ...> [yes: "y", no: "n", regenerate: "r"],
175 | ...> default_answer: :regenerate
176 | ...> )
177 | "Save Password? (y/n/R):" [enter]
178 | iex> :regenerate
179 | """
180 | @spec choice(String.t(), keyword(), keyword()) :: :error | atom()
181 | def choice(question, custom, opts \\ []) do
182 | run(opts, @choice_options, fn options ->
183 | Choice.new(question, custom, options)
184 | end)
185 | end
186 |
187 | @text_options NimbleOptions.new!(
188 | color: [
189 | type: {:in, @colors},
190 | doc:
191 | "The text color. One of `#{Kernel.inspect(@colors)}`. Defaults to the terminal default."
192 | ],
193 | background_color: [
194 | type: {:in, @colors},
195 | doc:
196 | "The background color. One of `#{Kernel.inspect(@colors)}`. Defaults to the terminal default."
197 | ],
198 | trim: [type: :boolean, default: false, doc: false],
199 | min: [
200 | type: :integer,
201 | default: 0,
202 | doc: "The minimum charactors required for input"
203 | ],
204 | max: [
205 | type: :integer,
206 | default: 0,
207 | doc: "The maximum charactors required for input"
208 | ]
209 | )
210 |
211 | @doc section: :input
212 | @doc """
213 | Display text on the screen and wait for the users text imput.
214 |
215 | Supported options:
216 | #{NimbleOptions.docs(@text_options)}
217 |
218 | ## Examples
219 |
220 | iex> Prompt.text("Enter your email")
221 | "Enter your email:" t@t.com
222 | iex> t@t.com
223 | """
224 | @spec text(String.t(), keyword()) :: String.t() | :error | :error_min | :error_max
225 | def text(display, opts \\ []) do
226 | run(opts, @text_options, fn options ->
227 | Text.new(display, options)
228 | end)
229 | end
230 |
231 | @select_options NimbleOptions.new!(
232 | color: [
233 | type: {:in, @colors},
234 | doc:
235 | "The text color. One of `#{Kernel.inspect(@colors)}`. Defaults to the terminal default."
236 | ],
237 | background_color: [
238 | type: {:in, @colors},
239 | doc:
240 | "The background color. One of `#{Kernel.inspect(@colors)}`. Defaults to the terminal default."
241 | ],
242 | multi: [
243 | type: :boolean,
244 | default: false,
245 | doc: "Allows multiple selections from the options presented."
246 | ],
247 | trim: [type: :boolean, default: true, doc: false]
248 | )
249 |
250 | @doc section: :input
251 | @doc """
252 | Displays options to the user denoted by numbers.
253 |
254 | Allows for a list of 2 tuples where the first value is what is displayed
255 | and the second value is what is returned to the caller.
256 |
257 | Supported options:
258 | #{NimbleOptions.docs(@select_options)}
259 |
260 | ## Examples
261 |
262 | iex> Prompt.select("Choose One", ["Choice A", "Choice B"])
263 | " [1] Choice A"
264 | " [2] Choice B"
265 | "Choose One [1-2]:" 1
266 | iex> "Choice A"
267 |
268 | iex> Prompt.select("Choose One", [{"Choice A", 1000}, {"Choice B", 1001}])
269 | " [1] Choice A"
270 | " [2] Choice B"
271 | "Choose One [1-2]:" 2
272 | iex> 1001
273 |
274 | iex> Prompt.select("Choose as many as you want", ["Choice A", "Choice B"], multi: true)
275 | " [1] Choice A"
276 | " [2] Choice B"
277 | "Choose as many as you want [1-2]:" 1 2
278 | iex> ["Choice A", "Choice B"]
279 |
280 | """
281 | @spec select(String.t(), list(String.t()) | list({String.t(), any()}), keyword()) ::
282 | any() | :error
283 | def select(display, choices, opts \\ []) do
284 | run(opts, @select_options, fn options ->
285 | Select.new(display, choices, options)
286 | end)
287 | end
288 |
289 | @password_options NimbleOptions.new!(
290 | color: [
291 | type: {:in, @colors},
292 | doc:
293 | "The text color. One of `#{Kernel.inspect(@colors)}`. Defaults to the terminal default."
294 | ],
295 | background_color: [
296 | type: {:in, @colors},
297 | doc:
298 | "The background color. One of `#{Kernel.inspect(@colors)}`. Defaults to the terminal default."
299 | ]
300 | )
301 |
302 | @doc section: :input
303 | @doc """
304 | Prompt the user for input, but conceal the users typing.
305 |
306 | Supported options:
307 | #{NimbleOptions.docs(@password_options)}
308 |
309 | ## Examples
310 |
311 | iex> Prompt.password("Enter your passsword")
312 | "Enter your password:"
313 | iex> "super_secret_passphrase"
314 | """
315 | @spec password(String.t(), keyword()) :: String.t()
316 | def password(display, opts \\ []) do
317 | run(opts, @password_options, fn options ->
318 | Password.new(display, options)
319 | end)
320 | end
321 |
322 | @display_options NimbleOptions.new!(
323 | color: [
324 | type: {:in, @colors},
325 | doc:
326 | "The text color. One of `#{Kernel.inspect(@colors)}`. Defaults to the terminal default."
327 | ],
328 | background_color: [
329 | type: {:in, @colors},
330 | doc:
331 | "The background color. One of `#{Kernel.inspect(@colors)}`. Defaults to the terminal default."
332 | ],
333 | trim: [type: :boolean, default: false, doc: false],
334 | from: [type: :atom, default: :self, doc: false],
335 | position: [
336 | type: {:in, [:left, :right]},
337 | default: :left,
338 | doc:
339 | "Print the content starting from the leftmost position or the rightmost position"
340 | ],
341 | mask_line: [
342 | type: :boolean,
343 | default: false,
344 | doc:
345 | "If set to true, this will mask the current line by replacing it with `#####`. Useful when showing passwords in the terminal."
346 | ]
347 | )
348 |
349 | @doc section: :output
350 | @doc """
351 | Writes text to the screen.
352 |
353 | Takes a single string argument or a list of strings where each item in the list will be diplayed on a new line.
354 |
355 |
356 | Supported options:
357 | #{NimbleOptions.docs(@display_options)}
358 |
359 | ## Examples
360 |
361 | iex> Prompt.display("Hello from the terminal!")
362 | "Hello from the terminal!"
363 |
364 | iex> Prompt.display(["Hello", "from", "the", "terminal"])
365 | "Hello"
366 | "from"
367 | "the"
368 | "terminal"
369 | """
370 | @spec display(String.t() | list(String.t()), keyword()) :: :ok
371 | def display(text, opts \\ []), do: _display(text, opts)
372 |
373 | defp _display(texts, opts) when is_list(texts) do
374 | Enum.each(texts, &display(&1, opts))
375 | end
376 |
377 | defp _display(text, opts) do
378 | run(opts, @display_options, fn options ->
379 | Display.new(text, options)
380 | end)
381 | end
382 |
383 | @table_options NimbleOptions.new!(
384 | header: [
385 | type: :boolean,
386 | default: false,
387 | doc: "Use the first element as the header for the table."
388 | ],
389 | border: [
390 | type: {:in, [:normal, :markdown, :none]},
391 | default: :normal,
392 | doc:
393 | "Determine how the border is displayed, one of :normal (default), :markdown, or :none"
394 | ],
395 | color: [
396 | type: {:in, @colors},
397 | doc:
398 | "The text color. One of `#{Kernel.inspect(@colors)}`. Defaults to the terminal default."
399 | ]
400 | )
401 |
402 | @doc section: :output
403 | @doc """
404 | Print an ASCII table of data. Requires a list of lists as input.
405 |
406 | Supported options:
407 | #{NimbleOptions.docs(@table_options)}
408 |
409 | ## Examples
410 |
411 | iex> Prompt.table([["Hello", "from", "the", "terminal!"],["this", "is", "another", "row"]])
412 | "
413 | +-------+------+---------+----------+
414 | | Hello | from | the | terminal |
415 | | this | is | another | row |
416 | +-------+------+---------+----------+
417 | "
418 |
419 | iex> Prompt.table([["One", "Two", "Three", "Four"], ["Hello", "from", "the", "terminal!"],["this", "is", "another", "row"]], header: true)
420 | "
421 | +-------+------+---------+----------+
422 | | One | Two | Three | Four |
423 | +-------+------+---------+----------+
424 | | Hello | from | the | terminal |
425 | | this | is | another | row |
426 | +-------+------+---------+----------+
427 | "
428 |
429 | iex> Prompt.table([["One", "Two", "Three", "Four"], ["Hello", "from", "the", "terminal!"],["this", "is", "another", "row"]], header: true, border: :markdown)
430 | "
431 | | One | Two | Three | Four |
432 | |-------|------|---------|----------|
433 | | Hello | from | the | terminal |
434 | | this | is | another | row |
435 | "
436 |
437 | iex> Prompt.table([["Hello", "from", "the", "terminal!"],["this", "is", "another", "row"]], border: :none)
438 | "
439 | Hello from the terminal
440 | this is another row
441 | "
442 |
443 | """
444 | @spec table(list(list()), keyword()) :: :ok
445 | def table(matrix, opts \\ []) when is_list(matrix) do
446 | case NimbleOptions.validate(opts, @table_options) do
447 | {:ok, options} ->
448 | table = matrix |> build_table(options)
449 | color = Keyword.get(options, :color, IO.ANSI.default_color())
450 |
451 | [
452 | :reset,
453 | IO.ANSI.default_background(),
454 | color,
455 | table,
456 | :reset
457 | ]
458 | |> IO.ANSI.format()
459 | |> write()
460 |
461 | {:error, err} ->
462 | display(err.message, error: true)
463 | :error
464 | end
465 | end
466 |
467 | @doc """
468 | Use this to get an iolist back of the table. Useful when you want an ascii `table/1` for
469 | other mediums like markdown files.
470 | """
471 | @spec table_data(list(list()), keyword()) :: [<<>> | [any()], ...]
472 | def table_data(matrix, opts \\ [border: :normal]) when is_list(matrix) do
473 | matrix
474 | |> build_table(opts)
475 | end
476 |
477 | defp build_table(matrix, opts) do
478 | tbl = Prompt.Table.new(matrix, opts)
479 | row_delimiter = Prompt.Table.row_delimiter(tbl)
480 |
481 | first =
482 | if Keyword.get(opts, :border) == :normal do
483 | row_delimiter
484 | else
485 | ""
486 | end
487 |
488 | {next, matrix} =
489 | if Keyword.get(opts, :header, false) do
490 | # get the first 'row'
491 | headers = Enum.at(matrix, 0)
492 | {[Prompt.Table.row(tbl, headers), row_delimiter], Enum.drop(matrix, 1)}
493 | else
494 | {"", matrix}
495 | end
496 |
497 | rest =
498 | for row <- matrix do
499 | Prompt.Table.row(tbl, row)
500 | end
501 |
502 | last =
503 | if Keyword.get(opts, :border) == :normal do
504 | row_delimiter
505 | else
506 | ""
507 | end
508 |
509 | if Keyword.get(opts, :color) do
510 | [first, next, rest, last]
511 | else
512 | [first, next, rest, last]
513 | end
514 | end
515 |
516 | defp run(opts, validation, io) do
517 | case NimbleOptions.validate(opts, validation) do
518 | {:ok, options} ->
519 | io.(options)
520 | |> Prompt.IO.display()
521 | |> Prompt.IO.evaluate()
522 |
523 | {:error, err} ->
524 | display(err.message, error: true)
525 | :error
526 | end
527 | end
528 | end
529 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
676 |
--------------------------------------------------------------------------------