|
| 1 | +using NShell.Shell; |
| 2 | +using NShell.Shell.Commands; |
| 3 | +using NShell.Shell.Config; |
| 4 | +using Spectre.Console; |
| 5 | + |
| 6 | +namespace NShell.Commands; |
| 7 | + |
| 8 | +public class AliasCommand : ICustomCommand, IMetadataCommand |
| 9 | +{ |
| 10 | + public string Name => "alias"; |
| 11 | + public string Description => "Create command aliases (e.g., alias ll='ls -la')."; |
| 12 | + |
| 13 | + // Static dictionary to store aliases |
| 14 | + public static Dictionary<string, string> Aliases { get; } = new Dictionary<string, string>(); |
| 15 | + private static readonly ConfigManager _configManager = new ConfigManager(); |
| 16 | + |
| 17 | + static AliasCommand() |
| 18 | + { |
| 19 | + // Load saved aliases on first use |
| 20 | + var savedAliases = _configManager.LoadAliases(); |
| 21 | + foreach (var alias in savedAliases) |
| 22 | + { |
| 23 | + Aliases[alias.Key] = alias.Value; |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + public void Execute(ShellContext context, string[] args) |
| 28 | + { |
| 29 | + if (args.Length == 0) |
| 30 | + { |
| 31 | + // List all aliases |
| 32 | + if (Aliases.Count == 0) |
| 33 | + { |
| 34 | + AnsiConsole.MarkupLine("[[[yellow]*[/]]] - No aliases defined."); |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + AnsiConsole.MarkupLine("[bold cyan]Current Aliases:[/]\n"); |
| 39 | + foreach (var alias in Aliases.OrderBy(a => a.Key)) |
| 40 | + { |
| 41 | + AnsiConsole.MarkupLine($"[yellow]{alias.Key}[/]=[green]'{alias.Value}'[/]"); |
| 42 | + } |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + // Join all args to handle aliases with spaces |
| 47 | + var fullArg = string.Join(' ', args); |
| 48 | + var parts = fullArg.Split('=', 2); |
| 49 | + |
| 50 | + if (parts.Length != 2) |
| 51 | + { |
| 52 | + AnsiConsole.MarkupLine("[[[yellow]*[/]]] - Usage: alias name='command'"); |
| 53 | + return; |
| 54 | + } |
| 55 | + |
| 56 | + string aliasName = parts[0].Trim(); |
| 57 | + string aliasValue = parts[1].Trim(); |
| 58 | + |
| 59 | + // Remove quotes if present |
| 60 | + if ((aliasValue.StartsWith("\"") && aliasValue.EndsWith("\"")) || |
| 61 | + (aliasValue.StartsWith("'") && aliasValue.EndsWith("'"))) |
| 62 | + { |
| 63 | + aliasValue = aliasValue.Substring(1, aliasValue.Length - 2); |
| 64 | + } |
| 65 | + |
| 66 | + Aliases[aliasName] = aliasValue; |
| 67 | + _configManager.SaveAliases(Aliases); |
| 68 | + AnsiConsole.MarkupLine($"[[[green]+[/]]] - Alias created: [yellow]{aliasName}[/]=[green]'{aliasValue}'[/]"); |
| 69 | + } |
| 70 | +} |
0 commit comments