-
Notifications
You must be signed in to change notification settings - Fork 989
/
ScriptHandlerHelpers.cs
87 lines (81 loc) · 2.96 KB
/
ScriptHandlerHelpers.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System;
using System.Collections.Generic;
using System.IO;
using GitHub.Runner.Sdk;
using GitHub.Runner.Common;
using GitHub.Runner.Common.Util;
namespace GitHub.Runner.Worker.Handlers
{
internal static class ScriptHandlerHelpers
{
private static readonly Dictionary<string, string> _defaultArguments = new(StringComparer.OrdinalIgnoreCase)
{
["cmd"] = "/D /E:ON /V:OFF /S /C \"CALL \"{0}\"\"",
["pwsh"] = "-command \". '{0}'\"",
["powershell"] = "-command \". '{0}'\"",
["bash"] = "--noprofile --norc -e -o pipefail {0}",
["sh"] = "-e {0}",
["python"] = "{0}"
};
private static readonly Dictionary<string, string> _extensions = new(StringComparer.OrdinalIgnoreCase)
{
["cmd"] = ".cmd",
["pwsh"] = ".ps1",
["powershell"] = ".ps1",
["bash"] = ".sh",
["sh"] = ".sh",
["python"] = ".py"
};
internal static string GetScriptArgumentsFormat(string scriptType)
{
if (_defaultArguments.TryGetValue(scriptType, out var argFormat))
{
return argFormat;
}
return "";
}
internal static string GetScriptFileExtension(string scriptType)
{
if (_extensions.TryGetValue(scriptType, out var extension))
{
return extension;
}
return "";
}
internal static string FixUpScriptContents(string scriptType, string contents)
{
switch (scriptType)
{
case "cmd":
// Note, use @echo off instead of using the /Q command line switch.
// When /Q is used, echo can't be turned on.
contents = $"@echo off{Environment.NewLine}{contents}";
break;
case "powershell":
case "pwsh":
var prepend = "$ErrorActionPreference = 'stop'";
var append = @"if ((Test-Path -LiteralPath variable:\LASTEXITCODE)) { exit $LASTEXITCODE }";
contents = $"{prepend}{Environment.NewLine}{contents}{Environment.NewLine}{append}";
break;
}
return contents;
}
internal static (string shellCommand, string shellArgs) ParseShellOptionString(string shellOption)
{
var shellStringParts = shellOption.Split(" ", 2);
if (shellStringParts.Length == 2)
{
return (shellCommand: shellStringParts[0], shellArgs: shellStringParts[1]);
}
else if (shellStringParts.Length == 1)
{
return (shellCommand: shellStringParts[0], shellArgs: "");
}
else
{
throw new ArgumentException($"Failed to parse COMMAND [..ARGS] from {shellOption}");
}
}
}
}