This commit is contained in:
Francesco Renzi
2026-01-22 00:12:27 +00:00
committed by GitHub
parent 1bba60b475
commit d334ab3f0a
8 changed files with 1446 additions and 1183 deletions

View File

@@ -2,20 +2,30 @@ using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using GitHub.Runner.Common;
using Newtonsoft.Json.Linq;
namespace GitHub.Runner.Worker.Dap.StepCommands
{
/// <summary>
/// Interface for parsing step commands from REPL strings or JSON.
/// Output format for step command responses.
/// </summary>
public enum OutputFormat
{
/// <summary>Human-readable text output (default)</summary>
Text,
/// <summary>JSON output for programmatic use</summary>
Json
}
/// <summary>
/// Interface for parsing step commands from REPL strings.
/// </summary>
[ServiceLocator(Default = typeof(StepCommandParser))]
public interface IStepCommandParser : IRunnerService
{
/// <summary>
/// Parses a command string (REPL or JSON) into a structured StepCommand.
/// Parses a command string into a structured StepCommand.
/// </summary>
/// <param name="input">The input string (e.g., "!step list --verbose" or JSON)</param>
/// <param name="input">The input string (e.g., "steps list --verbose")</param>
/// <returns>Parsed StepCommand</returns>
/// <exception cref="StepCommandException">If parsing fails</exception>
StepCommand Parse(string input);
@@ -24,7 +34,7 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
/// Checks if the input is a step command.
/// </summary>
/// <param name="input">The input string to check</param>
/// <returns>True if this is a step command (REPL or JSON format)</returns>
/// <returns>True if this is a step command (starts with "steps")</returns>
bool IsStepCommand(string input);
}
@@ -36,13 +46,13 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
public abstract class StepCommand
{
/// <summary>
/// Whether the original input was JSON (affects response format).
/// Output format for the command response.
/// </summary>
public bool WasJsonInput { get; set; }
public OutputFormat Output { get; set; } = OutputFormat.Text;
}
/// <summary>
/// !step list [--verbose]
/// steps list [--verbose]
/// </summary>
public class ListCommand : StepCommand
{
@@ -50,7 +60,7 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
}
/// <summary>
/// !step add run "script" [options]
/// steps add run "script" [options]
/// </summary>
public class AddRunCommand : StepCommand
{
@@ -66,7 +76,7 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
}
/// <summary>
/// !step add uses "action@ref" [options]
/// steps add uses "action@ref" [options]
/// </summary>
public class AddUsesCommand : StepCommand
{
@@ -81,7 +91,7 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
}
/// <summary>
/// !step edit <index> [modifications]
/// steps edit &lt;index&gt; [modifications]
/// </summary>
public class EditCommand : StepCommand
{
@@ -101,7 +111,7 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
}
/// <summary>
/// !step remove <index>
/// steps remove &lt;index&gt;
/// </summary>
public class RemoveCommand : StepCommand
{
@@ -109,7 +119,7 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
}
/// <summary>
/// !step move <from> [position options]
/// steps move &lt;from&gt; [position options]
/// </summary>
public class MoveCommand : StepCommand
{
@@ -118,7 +128,7 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
}
/// <summary>
/// !step export [--changes-only] [--with-comments]
/// steps export [--changes-only] [--with-comments]
/// </summary>
public class ExportCommand : StepCommand
{
@@ -178,7 +188,7 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
#endregion
/// <summary>
/// Parser implementation for step commands (REPL and JSON formats).
/// Parser implementation for step commands.
/// </summary>
public sealed class StepCommandParser : RunnerService, IStepCommandParser
{
@@ -194,12 +204,9 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
var trimmed = input.Trim();
// REPL command format: !step ...
if (trimmed.StartsWith("!step", StringComparison.OrdinalIgnoreCase))
return true;
// JSON format: {"cmd": "step.*", ...}
if (trimmed.StartsWith("{") && trimmed.Contains("\"cmd\"") && trimmed.Contains("\"step."))
// Command format: steps ...
if (trimmed.StartsWith("steps ", StringComparison.OrdinalIgnoreCase) ||
trimmed.Equals("steps", StringComparison.OrdinalIgnoreCase))
return true;
return false;
@@ -208,239 +215,9 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
public StepCommand Parse(string input)
{
var trimmed = input?.Trim() ?? "";
if (trimmed.StartsWith("{"))
{
return ParseJsonCommand(trimmed);
}
else
{
return ParseReplCommand(trimmed);
}
return ParseReplCommand(trimmed);
}
#region JSON Parsing
private StepCommand ParseJsonCommand(string json)
{
JObject obj;
try
{
obj = JObject.Parse(json);
}
catch (Exception ex)
{
throw new StepCommandException(StepCommandErrors.ParseError, $"Invalid JSON: {ex.Message}");
}
var cmd = obj["cmd"]?.ToString();
if (string.IsNullOrEmpty(cmd))
{
throw new StepCommandException(StepCommandErrors.ParseError, "Missing 'cmd' field in JSON");
}
StepCommand result = cmd switch
{
"step.list" => ParseJsonListCommand(obj),
"step.add" => ParseJsonAddCommand(obj),
"step.edit" => ParseJsonEditCommand(obj),
"step.remove" => ParseJsonRemoveCommand(obj),
"step.move" => ParseJsonMoveCommand(obj),
"step.export" => ParseJsonExportCommand(obj),
_ => throw new StepCommandException(StepCommandErrors.InvalidCommand, $"Unknown command: {cmd}")
};
result.WasJsonInput = true;
return result;
}
private ListCommand ParseJsonListCommand(JObject obj)
{
return new ListCommand
{
Verbose = obj["verbose"]?.Value<bool>() ?? false
};
}
private StepCommand ParseJsonAddCommand(JObject obj)
{
var type = obj["type"]?.ToString()?.ToLower();
if (type == "run")
{
var script = obj["script"]?.ToString();
if (string.IsNullOrEmpty(script))
{
throw new StepCommandException(StepCommandErrors.ParseError, "Missing 'script' field for run step");
}
return new AddRunCommand
{
Script = script,
Name = obj["name"]?.ToString(),
Shell = obj["shell"]?.ToString(),
WorkingDirectory = obj["workingDirectory"]?.ToString(),
Env = ParseJsonDictionary(obj["env"]),
Condition = obj["if"]?.ToString(),
ContinueOnError = obj["continueOnError"]?.Value<bool>() ?? false,
Timeout = obj["timeout"]?.Value<int>(),
Position = ParseJsonPosition(obj["position"])
};
}
else if (type == "uses")
{
var action = obj["action"]?.ToString();
if (string.IsNullOrEmpty(action))
{
throw new StepCommandException(StepCommandErrors.ParseError, "Missing 'action' field for uses step");
}
return new AddUsesCommand
{
Action = action,
Name = obj["name"]?.ToString(),
With = ParseJsonDictionary(obj["with"]),
Env = ParseJsonDictionary(obj["env"]),
Condition = obj["if"]?.ToString(),
ContinueOnError = obj["continueOnError"]?.Value<bool>() ?? false,
Timeout = obj["timeout"]?.Value<int>(),
Position = ParseJsonPosition(obj["position"])
};
}
else
{
throw new StepCommandException(StepCommandErrors.InvalidType,
$"Invalid step type: '{type}'. Must be 'run' or 'uses'.");
}
}
private EditCommand ParseJsonEditCommand(JObject obj)
{
var index = obj["index"]?.Value<int>();
if (!index.HasValue)
{
throw new StepCommandException(StepCommandErrors.ParseError, "Missing 'index' field for edit command");
}
return new EditCommand
{
Index = index.Value,
Name = obj["name"]?.ToString(),
Script = obj["script"]?.ToString(),
Action = obj["action"]?.ToString(),
Shell = obj["shell"]?.ToString(),
WorkingDirectory = obj["workingDirectory"]?.ToString(),
Condition = obj["if"]?.ToString(),
With = ParseJsonDictionary(obj["with"]),
Env = ParseJsonDictionary(obj["env"]),
RemoveWith = ParseJsonStringList(obj["removeWith"]),
RemoveEnv = ParseJsonStringList(obj["removeEnv"]),
ContinueOnError = obj["continueOnError"]?.Value<bool>(),
Timeout = obj["timeout"]?.Value<int>()
};
}
private RemoveCommand ParseJsonRemoveCommand(JObject obj)
{
var index = obj["index"]?.Value<int>();
if (!index.HasValue)
{
throw new StepCommandException(StepCommandErrors.ParseError, "Missing 'index' field for remove command");
}
return new RemoveCommand { Index = index.Value };
}
private MoveCommand ParseJsonMoveCommand(JObject obj)
{
var from = obj["from"]?.Value<int>();
if (!from.HasValue)
{
throw new StepCommandException(StepCommandErrors.ParseError, "Missing 'from' field for move command");
}
var position = ParseJsonPosition(obj["position"]);
if (position.Type == PositionType.Last)
{
// Default 'last' is fine for add, but move needs explicit position
// unless explicitly set
var posObj = obj["position"];
if (posObj == null)
{
throw new StepCommandException(StepCommandErrors.ParseError, "Missing 'position' field for move command");
}
}
return new MoveCommand
{
FromIndex = from.Value,
Position = position
};
}
private ExportCommand ParseJsonExportCommand(JObject obj)
{
return new ExportCommand
{
ChangesOnly = obj["changesOnly"]?.Value<bool>() ?? false,
WithComments = obj["withComments"]?.Value<bool>() ?? false
};
}
private StepPosition ParseJsonPosition(JToken token)
{
if (token == null || token.Type == JTokenType.Null)
return StepPosition.Last();
if (token.Type == JTokenType.Object)
{
var obj = (JObject)token;
if (obj["at"] != null)
return StepPosition.At(obj["at"].Value<int>());
if (obj["after"] != null)
return StepPosition.After(obj["after"].Value<int>());
if (obj["before"] != null)
return StepPosition.Before(obj["before"].Value<int>());
if (obj["first"]?.Value<bool>() == true)
return StepPosition.First();
if (obj["last"]?.Value<bool>() == true)
return StepPosition.Last();
}
return StepPosition.Last();
}
private Dictionary<string, string> ParseJsonDictionary(JToken token)
{
if (token == null || token.Type != JTokenType.Object)
return null;
var result = new Dictionary<string, string>();
foreach (var prop in ((JObject)token).Properties())
{
result[prop.Name] = prop.Value?.ToString() ?? "";
}
return result.Count > 0 ? result : null;
}
private List<string> ParseJsonStringList(JToken token)
{
if (token == null || token.Type != JTokenType.Array)
return null;
var result = new List<string>();
foreach (var item in (JArray)token)
{
var str = item?.ToString();
if (!string.IsNullOrEmpty(str))
result.Add(str);
}
return result.Count > 0 ? result : null;
}
#endregion
#region REPL Parsing
private StepCommand ParseReplCommand(string input)
@@ -448,10 +225,10 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
// Tokenize the input, respecting quoted strings
var tokens = Tokenize(input);
if (tokens.Count < 2 || !tokens[0].Equals("!step", StringComparison.OrdinalIgnoreCase))
if (tokens.Count < 2 || !tokens[0].Equals("steps", StringComparison.OrdinalIgnoreCase))
{
throw new StepCommandException(StepCommandErrors.ParseError,
"Invalid command format. Expected: !step <command> [args...]");
"Invalid command format. Expected: steps <command> [args...]");
}
var subCommand = tokens[1].ToLower();
@@ -510,7 +287,10 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
private ListCommand ParseReplListCommand(List<string> tokens)
{
var cmd = new ListCommand();
// Extract --output flag before processing other options
var outputFormat = ExtractOutputFlag(tokens);
var cmd = new ListCommand { Output = outputFormat };
for (int i = 2; i < tokens.Count; i++)
{
@@ -531,36 +311,43 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
private StepCommand ParseReplAddCommand(List<string> tokens)
{
// Extract --output flag before processing other options
var outputFormat = ExtractOutputFlag(tokens);
if (tokens.Count < 3)
{
throw new StepCommandException(StepCommandErrors.ParseError,
"Usage: !step add <run|uses> <script|action> [options]");
"Usage: steps add <run|uses> <script|action> [options]");
}
var type = tokens[2].ToLower();
StepCommand cmd;
if (type == "run")
{
return ParseReplAddRunCommand(tokens);
cmd = ParseReplAddRunCommand(tokens);
}
else if (type == "uses")
{
return ParseReplAddUsesCommand(tokens);
cmd = ParseReplAddUsesCommand(tokens);
}
else
{
throw new StepCommandException(StepCommandErrors.InvalidType,
$"Invalid step type: '{type}'. Must be 'run' or 'uses'.");
}
cmd.Output = outputFormat;
return cmd;
}
private AddRunCommand ParseReplAddRunCommand(List<string> tokens)
{
// !step add run "script" [options]
// steps add run "script" [options]
if (tokens.Count < 4)
{
throw new StepCommandException(StepCommandErrors.ParseError,
"Usage: !step add run \"<script>\" [--name \"...\"] [--shell <shell>] [--at|--after|--before <n>]");
"Usage: steps add run \"<script>\" [--name \"...\"] [--shell <shell>] [--at|--after|--before <n>]");
}
var cmd = new AddRunCommand
@@ -626,11 +413,11 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
private AddUsesCommand ParseReplAddUsesCommand(List<string> tokens)
{
// !step add uses "action@ref" [options]
// steps add uses "action@ref" [options]
if (tokens.Count < 4)
{
throw new StepCommandException(StepCommandErrors.ParseError,
"Usage: !step add uses <action@ref> [--name \"...\"] [--with key=value] [--at|--after|--before <n>]");
"Usage: steps add uses <action@ref> [--name \"...\"] [--with key=value] [--at|--after|--before <n>]");
}
var cmd = new AddUsesCommand
@@ -696,11 +483,14 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
private EditCommand ParseReplEditCommand(List<string> tokens)
{
// !step edit <index> [modifications]
// Extract --output flag before processing other options
var outputFormat = ExtractOutputFlag(tokens);
// steps edit <index> [modifications]
if (tokens.Count < 3)
{
throw new StepCommandException(StepCommandErrors.ParseError,
"Usage: !step edit <index> [--name \"...\"] [--script \"...\"] [--if \"...\"]");
"Usage: steps edit <index> [--name \"...\"] [--script \"...\"] [--if \"...\"]");
}
if (!int.TryParse(tokens[2], out var index))
@@ -712,6 +502,7 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
var cmd = new EditCommand
{
Index = index,
Output = outputFormat,
With = new Dictionary<string, string>(),
Env = new Dictionary<string, string>(),
RemoveWith = new List<string>(),
@@ -785,11 +576,14 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
private RemoveCommand ParseReplRemoveCommand(List<string> tokens)
{
// !step remove <index>
// Extract --output flag before processing other options
var outputFormat = ExtractOutputFlag(tokens);
// steps remove <index>
if (tokens.Count < 3)
{
throw new StepCommandException(StepCommandErrors.ParseError,
"Usage: !step remove <index>");
"Usage: steps remove <index>");
}
if (!int.TryParse(tokens[2], out var index))
@@ -798,16 +592,19 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
$"Invalid index: {tokens[2]}. Must be a number.");
}
return new RemoveCommand { Index = index };
return new RemoveCommand { Index = index, Output = outputFormat };
}
private MoveCommand ParseReplMoveCommand(List<string> tokens)
{
// !step move <from> --to|--after|--before <index>|--first|--last
// Extract --output flag before processing other options
var outputFormat = ExtractOutputFlag(tokens);
// steps move <from> --to|--after|--before <index>|--first|--last
if (tokens.Count < 3)
{
throw new StepCommandException(StepCommandErrors.ParseError,
"Usage: !step move <from> --to|--after|--before <index>|--first|--last");
"Usage: steps move <from> --to|--after|--before <index>|--first|--last");
}
if (!int.TryParse(tokens[2], out var fromIndex))
@@ -816,7 +613,7 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
$"Invalid from index: {tokens[2]}. Must be a number.");
}
var cmd = new MoveCommand { FromIndex = fromIndex };
var cmd = new MoveCommand { FromIndex = fromIndex, Output = outputFormat };
// Parse position
for (int i = 3; i < tokens.Count; i++)
@@ -858,7 +655,10 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
private ExportCommand ParseReplExportCommand(List<string> tokens)
{
var cmd = new ExportCommand();
// Extract --output flag before processing other options
var outputFormat = ExtractOutputFlag(tokens);
var cmd = new ExportCommand { Output = outputFormat };
for (int i = 2; i < tokens.Count; i++)
{
@@ -883,6 +683,36 @@ namespace GitHub.Runner.Worker.Dap.StepCommands
#region Argument Helpers
/// <summary>
/// Extracts and removes the --output flag from tokens, returning the output format.
/// Supports: --output json, --output text, -o json, -o text, --output=json, --output=text
/// </summary>
private OutputFormat ExtractOutputFlag(List<string> tokens)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i].ToLower();
if (token == "--output" || token == "-o")
{
if (i + 1 < tokens.Count)
{
var format = tokens[i + 1].ToLower();
tokens.RemoveAt(i); // Remove flag
tokens.RemoveAt(i); // Remove value (now at same index)
return format == "json" ? OutputFormat.Json : OutputFormat.Text;
}
}
else if (token.StartsWith("--output="))
{
var format = token.Substring("--output=".Length);
tokens.RemoveAt(i);
return format == "json" ? OutputFormat.Json : OutputFormat.Text;
}
}
return OutputFormat.Text;
}
private string GetNextArg(List<string> tokens, ref int index, string optName)
{
if (index + 1 >= tokens.Count)