Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make TermUi internal to the library #344

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -263,8 +263,6 @@ abstract class CliktCommand(
*
* This is similar to [print] or [println], but converts newlines to the system line separator.
*
* This is equivalent to calling [TermUi.echo] with the console from the current context.
*
* @param message The message to print.
* @param trailingNewline If true, behave like [println], otherwise behave like [print]
* @param err If true, print to stderr instead of stdout
Expand All @@ -278,6 +276,46 @@ abstract class CliktCommand(
TermUi.echo(message, trailingNewline, err, currentContext.console, lineSeparator)
}

/**
* Edit [text] in the [editor].
*
* This blocks until the editor is closed.
*
* @param text The text to edit.
* @param editor The path to the editor to use. Defaults to automatic detection.
* @param env Environment variables to forward to the editor.
* @param requireSave If the editor is closed without saving, null will be returned if true, otherwise
* [text] will be returned.
* @param extension The extension of the temporary file that the editor will open. This can affect syntax
* coloring etc.
* @return The edited text, or null if [requireSave] is true and the editor was closed without saving.
* @throws CliktError if the editor cannot be opened.
*/
protected fun editText(
text: String,
editor: String? = null,
env: Map<String, String> = emptyMap(),
requireSave: Boolean = false,
extension: String = ".txt",
): String? {
return TermUi.editText(text, editor, env, requireSave, extension)
}

/**
* Edit the file with [filename] in the [editor].
*
* @see editText for usage and parameter descriptions.
*/
protected fun editFile(
filename: String,
editor: String? = null,
env: Map<String, String> = emptyMap(),
requireSave: Boolean = false,
extension: String = ".txt",
) {
TermUi.editFile(filename, editor, env, requireSave, extension)
}

/**
* Prompt a user for text input.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import com.github.ajalt.clikt.core.CliktError
import com.github.ajalt.clikt.core.UsageError
import com.github.ajalt.clikt.mpp.isWindowsMpp

object TermUi {
internal object TermUi {
/**
* Print the [message] to the screen.
*
Expand Down Expand Up @@ -152,6 +152,7 @@ object TermUi {
* @param confirmationPrompt The text to show the user when [requireConfirmation] is true.
* @param promptSuffix A delimiter printed between the [text] and the user's input.
* @param showDefault If true, the [default] value will be shown as part of the prompt.
* @param console The console to prompt to
* @return the user's input, or null if the stdin is not interactive and EOF was encountered.
*/
fun prompt(
Expand All @@ -162,9 +163,10 @@ object TermUi {
confirmationPrompt: String = "Repeat for confirmation: ",
promptSuffix: String = ": ",
showDefault: Boolean = true,
console: CliktConsole = defaultCliktConsole(),
): String? {
return prompt(text, default, hideInput, requireConfirmation,
confirmationPrompt, promptSuffix, showDefault) { it }
confirmationPrompt, promptSuffix, showDefault, console) { it }
}

/**
Expand Down
3 changes: 0 additions & 3 deletions docs/advanced.md
Original file line number Diff line number Diff line change
Expand Up @@ -287,9 +287,6 @@ class CustomCLI : NoOpCliktCommand() {
}
```

If you are using [`TermUI`][TermUI] directly,
you can also pass your custom console as an argument.

## Command Line Argument Files ("@argfiles")

Similar to `javac`, Clikt supports loading command line parameters from a file using the "@argfile"
Expand Down
18 changes: 9 additions & 9 deletions docs/utilities.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ commonly used in command line programs.
## Launching Editors

If you need to ask users for multi-line input, or need to have the user edit a file, you can do so
through [`TermUi.editText`][editText] and [`TermUi.editFile`][editFile]. These functions open the
through [`editText`][editText] and [`editFile`][editFile]. These functions open the
program defined in the `VISUAL` or `EDITOR` environment variables, or a sensible default if neither
are defined. The functions return the edited text if the user saved their changes.

Expand All @@ -18,25 +18,25 @@ are defined. The functions return the edited text if the user saved their change
# Enter your message.
# Lines starting with # are ignored
""".trimIndent()
return TermUi.editText(message, requireSave = true)
return editText(message, requireSave = true)
?.replace(Regex("#[^\n]*\n"), "")
}
```

## Input Prompts

Options can [prompt for values automatically][prompting-for-input], but you can also do
so manually with [`TermUi.prompt`][prompt]. By
so manually with [`prompt`][prompt]. By
default, it accepts any input string, but you can also pass in a conversion function. If the
conversion raises a [`UsageError`][UsageError],
the prompt will ask the user to enter a different value.

=== "Example"
```kotlin
val input = TermUi.prompt("Enter a number") {
val input = prompt("Enter a number") {
it.toIntOrNull() ?: throw UsageError("$it is not a valid integer")
}
TermUi.echo("Twice your number is ${input * 2}")
echo("Twice your number is ${input * 2}")
```

=== "Interactive Session"
Expand All @@ -50,19 +50,19 @@ the prompt will ask the user to enter a different value.
## Confirmation Prompts

You can also ask the user for a yes or no response with
[`TermUi.confirm`][confirm]:
[`confirm`][confirm]:

```kotlin
if (TermUi.confirm("Continue?") == true) {
TermUi.echo("OK!")
if (confirm("Continue?") == true) {
echo("OK!")
}
```

If you simply want to abort the program in the user gives a negative
response, you can pass `abort=true`:

```kotlin
TermUi.confirm("Continue?", abort=true)
confirm("Continue?", abort=true)
```


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package com.github.ajalt.clikt.samples.aliases
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.NoOpCliktCommand
import com.github.ajalt.clikt.core.subcommands
import com.github.ajalt.clikt.output.TermUi
import com.github.ajalt.clikt.parameters.options.multiple
import com.github.ajalt.clikt.parameters.options.option
import java.io.File
Expand All @@ -23,20 +22,20 @@ class AliasedCli(private val configFile: File) : NoOpCliktCommand(


class Push : CliktCommand(help = "push changes") {
override fun run() = TermUi.echo("push")
override fun run() = echo("push")
}

class Pull : CliktCommand(help = "pull changes") {
override fun run() = TermUi.echo("pull")
override fun run() = echo("pull")
}

class Clone : CliktCommand(help = "clone a repository") {
override fun run() = TermUi.echo("clone")
override fun run() = echo("clone")
}

class Commit : CliktCommand(help = "clone a repository") {
val message by option("-m", "--message").multiple()
override fun run() = TermUi.echo("commit message=${message.joinToString("\n")}")
override fun run() = echo("commit message=${message.joinToString("\n")}")
}

fun main(args: Array<String>) {
Expand Down
2 changes: 1 addition & 1 deletion samples/copy/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# File copy sample

This example works like the `cp` command, copying files or directories.
It shows how to use `TermUi` to prompt the user for input.
It shows how to use `prompt` to get an input from user.

```
$ touch src.txt dest.txt
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.github.ajalt.clikt.samples.copy

import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.output.TermUi
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.arguments.multiple
import com.github.ajalt.clikt.parameters.options.flag
Expand All @@ -21,7 +20,7 @@ class Copy : CliktCommand(help = "Copy SOURCE to DEST, or multiple SOURCE(s) to
else file.copyTo(dest)
} catch (e: FileAlreadyExistsException) {
if (interactive) {
val response = TermUi.confirm("overwrite '$dest'?", default = true)
val response = confirm("overwrite '$dest'?", default = true)
if (response == false) continue
}
if (recursive) file.copyRecursively(dest, overwrite = true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package com.github.ajalt.clikt.samples.plugins

import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.requireObject
import com.github.ajalt.clikt.output.TermUi
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.arguments.multiple
import com.github.ajalt.clikt.parameters.options.multiple
Expand Down Expand Up @@ -43,7 +42,7 @@ class Commit : CliktCommand(
}
}

val message = TermUi.editText(text)
val message = editText(text)
if (message == null) {
echo("Aborted!")
return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package com.github.ajalt.clikt.samples.plugins

import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.requireObject
import com.github.ajalt.clikt.output.TermUi
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.options.prompt
import org.kodein.di.Kodein
Expand All @@ -27,7 +26,7 @@ class SetUser : CliktCommand(
repo.config["username"] = username
repo.config["email"] = email
repo.config["password"] = "*".repeat(password.length)
TermUi.echo("Changed credentials.")
echo("Changed credentials.")
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package com.github.ajalt.clikt.samples.repo
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.requireObject
import com.github.ajalt.clikt.core.subcommands
import com.github.ajalt.clikt.output.TermUi
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.arguments.multiple
import com.github.ajalt.clikt.parameters.arguments.optional
Expand Down Expand Up @@ -130,7 +129,7 @@ class Commit : CliktCommand(
}
}

val message = TermUi.editText(text)
val message = editText(text)
if (message == null) {
echo("Aborted!")
return
Expand Down