mirror of
https://github.com/nsnail/spectre.console.git
synced 2025-09-18 10:25:35 +08:00
Custom mask for secret (#970)
* Masking Character added, not yet used. * Setting the masking character can be chained with other extensions. * Added string extension for masking, and replaced hardcoded asterisks. * Check if mask is null first. * Fixed Typo in previous test and added new test for custom masks. * Added tests for masking with null character * Added docs and example. * Adjusted extensions so that Mask is integrated into Secret extension. Updated Exampls and Tests accordingly
This commit is contained in:
@@ -5,7 +5,7 @@ namespace Spectre.Console;
|
||||
/// </summary>
|
||||
public static partial class AnsiConsoleExtensions
|
||||
{
|
||||
internal static async Task<string> ReadLine(this IAnsiConsole console, Style? style, bool secret, IEnumerable<string>? items = null, CancellationToken cancellationToken = default)
|
||||
internal static async Task<string> ReadLine(this IAnsiConsole console, Style? style, bool secret, char? mask, IEnumerable<string>? items = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (console is null)
|
||||
{
|
||||
@@ -60,8 +60,9 @@ public static partial class AnsiConsoleExtensions
|
||||
|
||||
if (!char.IsControl(key.KeyChar))
|
||||
{
|
||||
text += key.KeyChar.ToString();
|
||||
console.Write(secret ? "*" : key.KeyChar.ToString(), style);
|
||||
text += key.KeyChar.ToString();
|
||||
var output = key.KeyChar.ToString();
|
||||
console.Write(secret ? output.Mask(mask) : output, style);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -185,5 +185,28 @@ public static class StringExtensions
|
||||
#else
|
||||
return text.Contains(value, StringComparison.Ordinal);
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Masks" every character in a string.
|
||||
/// </summary>
|
||||
/// <param name="value">String value to mask.</param>
|
||||
/// <param name="mask">Character to use for masking.</param>
|
||||
/// <returns>Masked string.</returns>
|
||||
public static string Mask(this string value, char? mask)
|
||||
{
|
||||
var output = string.Empty;
|
||||
|
||||
if (mask is null)
|
||||
{
|
||||
return output;
|
||||
}
|
||||
|
||||
foreach (var c in value)
|
||||
{
|
||||
output += mask;
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user