Skip to content

Commit

Permalink
completion: add configlet completion subcommand (#631)
Browse files Browse the repository at this point in the history
With this commit, running e.g.

    configlet completion --shell fish

will output the fish completion script to stdout. This allows us to
distribute completion scripts to the user without adding them to the
release assets, which avoids cluttering every directory in which the
user runs `fetch-configlet`.

For example, the user can enable completions for fish by running:

    configlet completion -s fish > ~/.config/fish/completions/configlet.fish

Closes: #630
  • Loading branch information
ee7 authored Aug 6, 2022
1 parent 1a295da commit d10dcd6
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 12 deletions.
19 changes: 12 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,18 @@ Usage:
configlet [global-options] <command> [command-options]
Commands:
fmt Format the exercise '.meta/config.json' files
generate Generate Concept Exercise 'introduction.md' files from 'introduction.md.tpl' files
info Print some information about the track
lint Check the track configuration for correctness
sync Check or update Practice Exercise docs, metadata, and tests from 'problem-specifications'.
Check or populate missing 'files' values for Concept/Practice Exercises from the track 'config.json'.
uuid Output new (version 4) UUIDs, suitable for the value of a 'uuid' key
completion Output a completion script for a given shell
fmt Format the exercise '.meta/config.json' files
generate Generate Concept Exercise 'introduction.md' files from 'introduction.md.tpl' files
info Print some information about the track
lint Check the track configuration for correctness
sync Check or update Practice Exercise docs, metadata, and tests from 'problem-specifications'.
Check or populate missing 'files' values for Concept/Practice Exercises from the track 'config.json'.
uuid Output new (version 4) UUIDs, suitable for the value of a 'uuid' key
Options for completion:
-s, --shell <shell> Choose the shell type (required)
Allowed values: b[ash], f[ish]
Options for fmt:
-e, --exercise <slug> Only operate on this exercise
Expand Down
32 changes: 29 additions & 3 deletions src/cli.nim
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,19 @@ import pkg/cligen/parseopt3
type
ActionKind* = enum
actNil = "nil"
actCompletion = "completion"
actFmt = "fmt"
actGenerate = "generate"
actInfo = "info"
actLint = "lint"
actSync = "sync"
actUuid = "uuid"

Shell* = enum
sNil = "nil"
sBash = "bash"
sFish = "fish"

SyncKind* = enum
skDocs = "docs"
skFilepaths = "filepaths"
Expand All @@ -26,6 +32,8 @@ type
case kind*: ActionKind
of actNil, actGenerate, actLint:
discard
of actCompletion:
shell*: Shell
of actFmt:
# We can't name these fields `exercise`, `update`, and `yes` because we
# use those names in `actSync`, and Nim doesn't yet support duplicate
Expand Down Expand Up @@ -62,6 +70,9 @@ type
optTrackDir = "trackDir"
optVerbosity = "verbosity"

# Options for `completion`
optCompletionShell = "shell"

# Options for both `fmt` and `sync`
optFmtSyncExercise = "exercise"
optFmtSyncUpdate = "update"
Expand Down Expand Up @@ -133,8 +144,10 @@ func genHelpText: string =
## Returns a string that describes the allowed values for an enum `T`.
result = "Allowed values: "
for val in T:
result.add &"{($val)[0]}"
result.add &"[{($val)[1 .. ^1]}], "
let s = $val
if s != "nil":
result.add s[0]
result.add &"[{s[1 .. ^1]}], "
setLen(result, result.len - 2)

func genSyntaxStrings: tuple[syntax: array[Opt, string], maxLen: int] =
Expand All @@ -147,6 +160,7 @@ func genHelpText: string =
case opt
of optTrackDir: "dir"
of optVerbosity: "verbosity"
of optCompletionShell: "shell"
of optFmtSyncExercise: "slug"
of optSyncTests: "mode"
of optUuidNum: "int"
Expand Down Expand Up @@ -174,6 +188,7 @@ func genHelpText: string =

const actionDescriptions: array[ActionKind, string] = [
actNil: "",
actCompletion: "Output a completion script for a given shell",
actFmt: "Format the exercise '.meta/config.json' files",
actGenerate: "Generate Concept Exercise 'introduction.md' files from 'introduction.md.tpl' files",
actInfo: "Print some information about the track",
Expand All @@ -199,6 +214,8 @@ func genHelpText: string =
optTrackDir: "Specify a track directory to use instead of the current directory",
optVerbosity: &"The verbosity of output.\n" &
&"{paddingOpt}{allowedValues(Verbosity)} (default: normal)",
optCompletionShell: &"Choose the shell type (required)\n" &
&"{paddingOpt}{allowedValues(Shell)}",
optFmtSyncExercise: "Only operate on this exercise",
optFmtSyncUpdate: "Prompt to update the unsynced track data",
optFmtSyncYes: &"Auto-confirm prompts from --{$optFmtSyncUpdate} for updating docs, filepaths, and metadata",
Expand Down Expand Up @@ -330,7 +347,7 @@ func formatOpt(kind: CmdLineKind, key: string, val = ""): string =
func init*(T: typedesc[Action], actionKind: ActionKind,
scope: set[SyncKind] = {}): T =
case actionKind
of actNil, actFmt, actGenerate, actInfo, actLint:
of actNil, actCompletion, actFmt, actGenerate, actInfo, actLint:
T(kind: actionKind)
of actSync:
T(kind: actionKind, scope: scope)
Expand Down Expand Up @@ -463,6 +480,12 @@ proc handleOption(conf: var Conf; kind: CmdLineKind; key, val: string) =
case conf.action.kind
of actNil, actGenerate, actLint:
discard
of actCompletion:
case opt
of optCompletionShell:
setActionOpt(shell, parseVal[Shell](kind, key, val))
else:
discard
of actFmt:
case opt
of optFmtSyncExercise:
Expand Down Expand Up @@ -533,6 +556,9 @@ proc processCmdLine*: Conf =
case result.action.kind
of actNil:
showHelp()
of actCompletion:
if result.action.shell == sNil:
showError("Please choose a shell. For example: `configlet completion -s bash`")
of actFmt, actGenerate, actInfo, actLint, actUuid:
discard
of actSync:
Expand Down
12 changes: 12 additions & 0 deletions src/completion/completion.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import std/[os, strformat]
import ../cli

proc readCompletions: array[Shell, string] =
const repoRootDir = currentSourcePath().parentDir().parentDir().parentDir()
const completionsDir = repoRootDir / "completions"
for shell in sBash .. result.high:
result[shell] = staticRead(completionsDir / &"configlet.{shell}")

proc completion*(shellKind: Shell) =
const completions = readCompletions()
stdout.write completions[shellKind]
6 changes: 4 additions & 2 deletions src/configlet.nim
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import std/posix
import "."/[cli, fmt/fmt, info/info, generate/generate, lint/lint, logger,
sync/sync, uuid/uuid]
import "."/[cli, completion/completion, fmt/fmt, info/info, generate/generate,
lint/lint, logger, sync/sync, uuid/uuid]

proc main =
onSignal(SIGTERM):
Expand All @@ -13,6 +13,8 @@ proc main =
case conf.action.kind
of actNil:
discard
of actCompletion:
completion(conf.action.shell)
of actFmt:
fmt(conf)
of actLint:
Expand Down
28 changes: 28 additions & 0 deletions tests/test_binary.nim
Original file line number Diff line number Diff line change
Expand Up @@ -929,6 +929,32 @@ proc testsForGenerate(binaryPath: string) =
test "and writes the `introduction.md` file as expected":
checkNoDiff(trackDir)

proc testsForCompletion(binaryPath: string) =
suite "completion":
const completionsDir = repoRootDir / "completions"
for shell in ["bash", "fish"]:
test shell:
let c = shell[0]
# Convert platform-specific line endings (e.g. CR+LF on Windows) to LF
# before comparing. The below `replace` makes the tests pass on Windows.
let expected = readFile(completionsDir / &"configlet.{shell}").replace("\p", "\n")
execAndCheck(0, &"{binaryPath} completion --shell {shell}", expected)
execAndCheck(0, &"{binaryPath} completion --shell {c}", expected)
execAndCheck(0, &"{binaryPath} completion -s {shell}", expected)
execAndCheck(0, &"{binaryPath} completion -s {c}", expected)
execAndCheck(0, &"{binaryPath} completion -s{c}", expected)
for shell in ["powershell", "zsh"]:
test &"{shell} (produces an error)":
let (outp, exitCode) = execCmdEx(&"{binaryPath} completion -s {shell}")
check:
outp.contains(&"invalid value for '-s': '{shell}'")
exitCode == 1
test "the -s option is required":
let (outp, exitCode) = execCmdEx(&"{binaryPath} completion")
check:
outp.contains(&"Please choose a shell. For example: `configlet completion -s bash`")
exitCode == 1

proc main =
const
binaryExt =
Expand Down Expand Up @@ -1081,5 +1107,7 @@ proc main =

testsForGenerate(binaryPath)

testsForCompletion(binaryPath)

main()
{.used.}

0 comments on commit d10dcd6

Please sign in to comment.