shibayan / sharprompt Goto Github PK
View Code? Open in Web Editor NEWInteractive command-line based application framework for C#
License: MIT License
Interactive command-line based application framework for C#
License: MIT License
At the moment, it is impossible to cancel an input request. It would be nice if a CancellationToken could be passed to the input functions to cancel the input request. I imagine the input function would simply throw when it is cancelled.
Adopt NRT as a required condition for the value. I need to use NullabilityInfoContext
which will probably be added in NET 6.
https://devblogs.microsoft.com/dotnet/announcing-net-6-preview-7/#getting-top-level-nullability-information
// Value is required
var intValue = Prompt.Input<int>("Integer value");
var strValue = Prompt.Input<string>("String value");
// Value is optional
var optionalIntValue = Prompt.Input<int?>("Optional integer value");
var optionalStrValue = Prompt.Input<string?>("Optional string value");
When value text overflows the line (appends to next line) pressing the 'down' error key will redraw the first line. This is because the 'reset' function does not take into account any overflowing lines. Since it uses an internal counter.
Steps to reproduce the behavior:
Render should only show the change in selected value.
If applicable, add screenshots to help explain your problem.
Ref #84 (comment)
This fork (https://github.com/FRACerqueira/Sharprompt) at master
adds support for cancellable prompts, two new controls and many enhancement
Resume:
Preview prompts :
With #82 the following regression was introduced:
When using Prompt.Select<MyEnum>("My Prompt")
. I.e. with the automatic choice generation from enums.
When the Enum fields are decorated with Display(Name="choice display text")
but the Order
parameter is not specified, the code will fail with:
The Order property has not been set. Use the GetOrder method to get the value
Apparently one is not supposed to use displayAttribute.Order
if the Order field has not been explicitly set.
referencesource
This should be an easy fix in EnumValue.cs
Flickering on Ubuntu (WSL 2) + Windows Terminal
When pasting U+30FB ( only one character ) with InputForm, it works well. But it doesn't work with more than two characters( U+30FB and other characters ).
Thanks.
P.S. I always appreciate Sharpromt.
The current DefaultConsoleDriver implementation is internal and makes it impossible to override any of the behaviors of the DefaultConsoleDriver class to fit my needs. Some suggestions that I have would be:
I believe that these changes builds on such a neat tool and would make the tool more fun and flexible for users to play around with.
DataAnnotations
DataType
attributeIt would be nice if when the select list of items has been filtered down to a single entry, ENTER commits its value even if the user hasn't "selected" it using the arrow key.
For example, given this list:
1. Red
2. Green
3. Blue
It feels natural to type 1
(only Red remains) and Enter
but that doesn't work.
Currently you need to do 1
, Down
, Enter
.
It would improve the UX if the user could see the amount of pages and which page the user is currently on. Perhaps even a count of the total items in a list.
For Select
and MultiSelect
prompt.
Prompt.Select<MyEnum>(options =>
{
options.Message = "Select a item?";
options.PaginationCallback = (total, current, page) => $"({total} items, {current}/{page} pages)";
});
or
Prompt.Select<MyEnum>(options =>
{
options.Message = "Select a item?";
options.PaginationTemplate ="({0} items, {1}/{2} pages)";
});
Prompt.Select
paging support
The tool only provides getters to the symbols and since I'm working on a windows machine, unicode is not readily available thus resulting in the letter 'V' representing done. Would it be possible to add a setter to allow for more customization for how the done symbol is represented.
Make internal Input
/ Password
/ etc
If using for example the MinLength
validator with a decently large minimum length, you might type a long, but not quite long enough, sentence, click Enter, then get an error message saying the Value is too short, then see your message deleted and have no way to recover it.
The user experience here could be improved if, after showing the error message, either the entered value is kept or it is possible to recover it in some way, for example by clicking the up arrow, like in most command line interfaces.
I can't think of a use case where interactive console input would require a timeout. In most cases, if you can handle the behavior after sending Ctrl+C
, you should be fine.
I haven't checked if it is possible to implement it, but it looks like the following code would be good.
try
{
// Needs `throwExceptionOnCancel` set `true`
var name = Prompt.Input<string>("What's your name?", throwExceptionOnCancel: true);
Console.WriteLine($"Hello, {name}!");
}
catch (PromptCancelledException ex)
{
// handling
}
For improvement console rendering.
Please provide for select enum ordering
For examle using [Display(Name = "End",Order =1)]
Perhaps it's an idea to allow to customize the default internal colours. (Allows for branding).
An error is thrown if you use an enumeration type as the generic argument and provide a default value for the Prompt.Select()
method.
Program.cs
using Sharprompt;
using System;
using System.ComponentModel.DataAnnotations;
namespace SharpromptSelectEnumBug
{
class Program
{
static void Main(string[] args)
{
var value = Prompt.Select<MyEnum>("Select enum value", defaultValue: MyEnum.Bar);
Console.WriteLine($"You selected {value}");
}
}
public enum MyEnum
{
Foo,
Bar,
Baz
}
}
Project.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Sharprompt" Version="2.1.1" />
</ItemGroup>
</Project>
When executing the Prompt.Select
method, the following exception is thrown:
System.InvalidCastException Unable to cast object of type 'SharpromptSelectEnumBug.MyEnum' to type 'Sharprompt.Internal.EnumValue`1[SharpromptSelectEnumBug.MyEnum]'. Source=System.Private.CoreLib StackTrace: at System.Runtime.CompilerServices.CastHelpers.ChkCastAny(Void* toTypeHnd, Object obj) at Sharprompt.Internal.Selector`1.InitializeDefaults(Object defaultValue) at Sharprompt.Internal.Selector`1..ctor(IEnumerable`1 items, Nullable`1 pageSize, Object defaultValue, Func`2 valueSelector) at Sharprompt.Forms.Select`1..ctor(String message, IEnumerable`1 items, Nullable`1 pageSize, Object defaultValue, Func`2 valueSelector) at Sharprompt.Prompt.Select[T](String message, Nullable`1 pageSize, Nullable`1 defaultValue) at SharpromptSelectEnumBug.Program.Main(String[] args) in C:\.......\Program.cs:line 14
This does work correctly for simple string-based entries. For example with this code:
var city = Prompt.Select("Select your city", new[] { "Seattle", "London", "Tokyo" }, defaultValue: "London");
"London" will correctly be selected by default when showing the prompt.
I believe that this might be related to #80, but when pasting an extremely large text into the prompt, The words are rendered slowly and the console begins flickering until all of the characters are visible.
Repro steps:
[Prompt] What is your name? :
Behavior:
Prompt.Select
filtering support
The Validators.Required()
can be added to input on a type different than string.
The Required
validators only check string attributes and return Value is required
if the type is different than a string, even if the value is correct.
Solution:
Update the Required
validator by adding a check on a type different than string.
Sharprompt/Sharprompt/Validators.cs
Lines 9 to 19 in 2a8c885
At the moment if Ctrl-C is hit in the middle of an input, the terminal is left in a strange state (e.g. the cursor is no longer visible).
Would it be possible to clean up properly when the application exits?
Hey @shibayan,
I had a idea to build a List form input that would take in values and append them to an existing list. For example:
What would you like to add to your grocery list? : Banana
Pressing ENTER would append Banana to the end of this list and ask again.
What would you like to add to your grocery list? :
If the user presses ENTER without any value, the prompt would end.
Please let me know what you think and if you like it, I would like to try working on this.
The new interface for the prompt seems to broke my terminals, especially the one that doesn't have a unicode support.
It produces this weird character on the beginning of the line after I type the answer, or submitting the answer.
It also occurs on Powershell 7
The code was a simple yes/no input and the usual input
using Sharprompt;
using System;
namespace ConsolePlayground
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var confirmOverwrite = Prompt.Confirm("Existing configuration already exists! Overwrite file?", false);
if (!confirmOverwrite) return;
var Testvar1 = Prompt.Input<string>("Input a string");
var Testvar2 = Prompt.Password("Input another string");
}
}
}
Also, here's the video demo about the issue.
For the MinLength
and MaxLength
validators, it would be useful to have the possibility of seeing an indication of how many of the allowed or required characters you have used up, for example in parentheses after the message: Type new password (3/8): ***
The indicator could be colored based on whether the current input is valid or not.
For the RegularExpression
validator, it may be harder to show a usable indicator, but it could still say ✅
/valid
or ❌
/invalid
.
Look this fork (https://github.com/FRACerqueira/Sharprompt) at master for all changes and improvements.
the commit Changed to Redraw only the parts that have been changed:
https://github.com/FRACerqueira/Sharprompt/commit/9df3ce55a73b16054759a91c11c421d14c0a62ee
If you want, I can generate a pull-request with all the changes
Make it possible to change the mask character when entering passwords.
// Default '*'
// e.g. Type new password: ********
Prompt.Password("Type new password", passwordChar: '*');
// Override
// e.g. Type new password: ●●●●●●●●
Prompt.Password("Type new password", passwordChar: '●');
// Hidden
// e.g. Type new password:
Prompt.Password("Type new password", passwordChar: null);
I currently have a loop that asks a series of prompts. I want to have a way to return to a previous prompt even when answering the current prompt in case a user realizes that one of the past responses was incorrect. How would I go about doing this? Does Sharprompt support historical navigation?
It' is possible to call Prompt.MultiSelect(message, list, min: 0)
, but this does not actually allow zero items to be selected. It will fail with the message "A minimum selection of 0 items is required".
Prompt.Select and Prompt.MultiSelect fail on Windows 10 in Git Bash (the one installed with Git version 2.24.1.2)
Sharprompt Version 1.0.4
Example
Prompt.Select("Select value", new [] { "Value 1", "Value 2" });
Exception
Unhandled exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
---> System.IO.IOException: The handle is invalid.
at System.ConsolePal.GetBufferInfo(Boolean throwOnNoConsole, Boolean& succeeded)
at System.Console.get_CursorLeft()
at Sharprompt.ConsoleRenderer.Close()
at Sharprompt.Select`1.Start()
at Sharprompt.Prompt.Select[T](String message, IEnumerable`1 items, Object defaultValue, Int32 pageSize, Func`2 valueSelector)
at Console.Commands.SystemCommand.DoCommand(String system) in C:\---\SystemCommand.cs:line 27
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at System.Delegate.DynamicInvoke(Object[] args)
at System.CommandLine.Invocation.ModelBindingCommandHandler.InvokeAsync(InvocationContext context)
at System.CommandLine.Invocation.InvocationPipeline.<>c__DisplayClass4_0.<<BuildInvocationChain>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c.<<UseParseErrorReporting>b__19_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass14_0.<<UseHelp>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass22_0.<<UseVersionOption>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass21_0.<<UseTypoCorrections>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c.<<UseSuggestDirective>b__20_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c.<<UseParseDirective>b__18_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c.<<UseDebugDirective>b__10_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c.<<RegisterWithDotnetSuggest>b__9_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass12_0.<<UseExceptionHandler>b__0>d.MoveNext()
If a defaultValue
is specified in a Prompt.Input<string>
call that also specifies validators, pressing Enter on the prompt sends an empty string to the validators, not the default value. For example:
var userName = Sharprompt.Prompt.Input<string>("Please enter a name", "default", validators: new[] { Sharprompt.Validations.Validators.Required()});
will fail unless providing a non-default value, since an empty string is passed to validators, rather than the default value specified by defaultValue
.
I've created an oversimplified repro in this repo
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.