move shared ExecutionContext properties under .Global (#594)

This commit is contained in:
eric sciple
2020-07-19 19:05:47 -04:00
committed by GitHub
parent 1cc3c08cf2
commit 0921af735a
25 changed files with 149 additions and 148 deletions

View File

@@ -188,7 +188,7 @@ namespace GitHub.Runner.Worker
throw new Exception("Required field 'name' is missing in ##[set-env] command."); throw new Exception("Required field 'name' is missing in ##[set-env] command.");
} }
context.EnvironmentVariables[envName] = command.Data; context.Global.EnvironmentVariables[envName] = command.Data;
context.SetEnvContext(envName, command.Data); context.SetEnvContext(envName, command.Data);
context.Debug($"{envName}='{command.Data}'"); context.Debug($"{envName}='{command.Data}'");
} }
@@ -283,8 +283,8 @@ namespace GitHub.Runner.Worker
public void ProcessCommand(IExecutionContext context, string line, ActionCommand command, ContainerInfo container) public void ProcessCommand(IExecutionContext context, string line, ActionCommand command, ContainerInfo container)
{ {
ArgUtil.NotNullOrEmpty(command.Data, "path"); ArgUtil.NotNullOrEmpty(command.Data, "path");
context.PrependPath.RemoveAll(x => string.Equals(x, command.Data, StringComparison.CurrentCulture)); context.Global.PrependPath.RemoveAll(x => string.Equals(x, command.Data, StringComparison.CurrentCulture));
context.PrependPath.Add(command.Data); context.Global.PrependPath.Add(command.Data);
} }
} }

View File

@@ -66,7 +66,7 @@ namespace GitHub.Runner.Worker
// TODO: Deprecate the PREVIEW_ACTION_TOKEN // TODO: Deprecate the PREVIEW_ACTION_TOKEN
// Log even if we aren't using it to ensure users know. // Log even if we aren't using it to ensure users know.
if (!string.IsNullOrEmpty(executionContext.Variables.Get("PREVIEW_ACTION_TOKEN"))) if (!string.IsNullOrEmpty(executionContext.Global.Variables.Get("PREVIEW_ACTION_TOKEN")))
{ {
executionContext.Warning("The 'PREVIEW_ACTION_TOKEN' secret is deprecated. Please remove it from the repository's secrets"); executionContext.Warning("The 'PREVIEW_ACTION_TOKEN' secret is deprecated. Please remove it from the repository's secrets");
} }
@@ -75,7 +75,7 @@ namespace GitHub.Runner.Worker
IOUtil.DeleteDirectory(HostContext.GetDirectory(WellKnownDirectory.Actions), executionContext.CancellationToken); IOUtil.DeleteDirectory(HostContext.GetDirectory(WellKnownDirectory.Actions), executionContext.CancellationToken);
// todo: Remove when feature flag DistributedTask.NewActionMetadata is removed // todo: Remove when feature flag DistributedTask.NewActionMetadata is removed
var newActionMetadata = executionContext.Variables.GetBoolean("DistributedTask.NewActionMetadata") ?? false; var newActionMetadata = executionContext.Global.Variables.GetBoolean("DistributedTask.NewActionMetadata") ?? false;
var repositoryActions = new List<Pipelines.ActionStep>(); var repositoryActions = new List<Pipelines.ActionStep>();
@@ -589,7 +589,7 @@ namespace GitHub.Runner.Worker
{ {
try try
{ {
actionDownloadInfos = await jobServer.ResolveActionDownloadInfoAsync(executionContext.Plan.ScopeIdentifier, executionContext.Plan.PlanType, executionContext.Plan.PlanId, new WebApi.ActionReferenceList { Actions = actionReferences }, executionContext.CancellationToken); actionDownloadInfos = await jobServer.ResolveActionDownloadInfoAsync(executionContext.Global.Plan.ScopeIdentifier, executionContext.Global.Plan.PlanType, executionContext.Global.Plan.PlanId, new WebApi.ActionReferenceList { Actions = actionReferences }, executionContext.CancellationToken);
break; break;
} }
catch (Exception ex) when (attempt < 3) catch (Exception ex) when (attempt < 3)
@@ -947,7 +947,7 @@ namespace GitHub.Runner.Worker
if (string.IsNullOrEmpty(authToken)) if (string.IsNullOrEmpty(authToken))
{ {
// TODO: Deprecate the PREVIEW_ACTION_TOKEN // TODO: Deprecate the PREVIEW_ACTION_TOKEN
authToken = executionContext.Variables.Get("PREVIEW_ACTION_TOKEN"); authToken = executionContext.Global.Variables.Get("PREVIEW_ACTION_TOKEN");
} }
if (!string.IsNullOrEmpty(authToken)) if (!string.IsNullOrEmpty(authToken))

View File

@@ -77,9 +77,9 @@ namespace GitHub.Runner.Worker
// Add this file to the FileTable in executionContext if it hasn't been added already // Add this file to the FileTable in executionContext if it hasn't been added already
// we use > since fileID is 1 indexed // we use > since fileID is 1 indexed
if (fileId > executionContext.FileTable.Count) if (fileId > executionContext.Global.FileTable.Count)
{ {
executionContext.FileTable.Add(fileRelativePath); executionContext.Global.FileTable.Add(fileRelativePath);
} }
// Read the file // Read the file
@@ -347,9 +347,9 @@ namespace GitHub.Runner.Worker
} }
// Add the file table from the Execution Context // Add the file table from the Execution Context
for (var i = 0; i < executionContext.FileTable.Count; i++) for (var i = 0; i < executionContext.Global.FileTable.Count; i++)
{ {
result.GetFileId(executionContext.FileTable[i]); result.GetFileId(executionContext.Global.FileTable[i]);
} }
return result; return result;

View File

@@ -136,12 +136,12 @@ namespace GitHub.Runner.Worker
} }
// Setup container stephost for running inside the container. // Setup container stephost for running inside the container.
if (ExecutionContext.Container != null) if (ExecutionContext.Global.Container != null)
{ {
// Make sure required container is already created. // Make sure required container is already created.
ArgUtil.NotNullOrEmpty(ExecutionContext.Container.ContainerId, nameof(ExecutionContext.Container.ContainerId)); ArgUtil.NotNullOrEmpty(ExecutionContext.Global.Container.ContainerId, nameof(ExecutionContext.Global.Container.ContainerId));
var containerStepHost = HostContext.CreateService<IContainerStepHost>(); var containerStepHost = HostContext.CreateService<IContainerStepHost>();
containerStepHost.Container = ExecutionContext.Container; containerStepHost.Container = ExecutionContext.Global.Container;
stepHost = containerStepHost; stepHost = containerStepHost;
} }
@@ -231,7 +231,7 @@ namespace GitHub.Runner.Worker
handlerData, handlerData,
inputs, inputs,
environment, environment,
ExecutionContext.Variables, ExecutionContext.Global.Variables,
actionDirectory: definition.Directory); actionDirectory: definition.Directory);
// Print out action details // Print out action details

View File

@@ -86,9 +86,9 @@ namespace GitHub.Runner.Worker
executionContext.Debug("Zipping diagnostic files."); executionContext.Debug("Zipping diagnostic files.");
string buildNumber = executionContext.Variables.Build_Number ?? "UnknownBuildNumber"; string buildNumber = executionContext.Global.Variables.Build_Number ?? "UnknownBuildNumber";
string buildName = $"Build {buildNumber}"; string buildName = $"Build {buildNumber}";
string phaseName = executionContext.Variables.System_PhaseDisplayName ?? "UnknownPhaseName"; string phaseName = executionContext.Global.Variables.System_PhaseDisplayName ?? "UnknownPhaseName";
// zip the files // zip the files
string diagnosticsZipFileName = $"{buildName}-{phaseName}.zip"; string diagnosticsZipFileName = $"{buildName}-{phaseName}.zip";

View File

@@ -44,22 +44,12 @@ namespace GitHub.Runner.Worker
string ResultCode { get; set; } string ResultCode { get; set; }
TaskResult? CommandResult { get; set; } TaskResult? CommandResult { get; set; }
CancellationToken CancellationToken { get; } CancellationToken CancellationToken { get; }
List<ServiceEndpoint> Endpoints { get; } GlobalContext Global { get; }
TaskOrchestrationPlanReference Plan { get; }
PlanFeatures Features { get; }
Variables Variables { get; }
Dictionary<string, string> IntraActionState { get; } Dictionary<string, string> IntraActionState { get; }
IDictionary<String, IDictionary<String, String>> JobDefaults { get; }
Dictionary<string, VariableValue> JobOutputs { get; } Dictionary<string, VariableValue> JobOutputs { get; }
IDictionary<String, String> EnvironmentVariables { get; }
IList<String> FileTable { get; }
StepsContext StepsContext { get; }
DictionaryContextData ExpressionValues { get; } DictionaryContextData ExpressionValues { get; }
IList<IFunctionInfo> ExpressionFunctions { get; } IList<IFunctionInfo> ExpressionFunctions { get; }
List<string> PrependPath { get; }
ContainerInfo Container { get; set; }
List<ContainerInfo> ServiceContainers { get; }
JobContext JobContext { get; } JobContext JobContext { get; }
// Only job level ExecutionContext has JobSteps // Only job level ExecutionContext has JobSteps
@@ -76,7 +66,6 @@ namespace GitHub.Runner.Worker
IExecutionContext CreateChild(Guid recordId, string displayName, string refName, string scopeName, string contextName, Dictionary<string, string> intraActionState = null, int? recordOrder = null, IPagingLogger logger = null); IExecutionContext CreateChild(Guid recordId, string displayName, string refName, string scopeName, string contextName, Dictionary<string, string> intraActionState = null, int? recordOrder = null, IPagingLogger logger = null);
// logging // logging
bool WriteDebug { get; }
long Write(string tag, string message); long Write(string tag, string message);
void QueueAttachFile(string type, string name, string filePath); void QueueAttachFile(string type, string name, string filePath);
@@ -142,21 +131,13 @@ namespace GitHub.Runner.Worker
public string ContextName { get; private set; } public string ContextName { get; private set; }
public Task ForceCompleted => _forceCompleted.Task; public Task ForceCompleted => _forceCompleted.Task;
public CancellationToken CancellationToken => _cancellationTokenSource.Token; public CancellationToken CancellationToken => _cancellationTokenSource.Token;
public List<ServiceEndpoint> Endpoints { get; private set; }
public TaskOrchestrationPlanReference Plan { get; private set; }
public Variables Variables { get; private set; }
public Dictionary<string, string> IntraActionState { get; private set; } public Dictionary<string, string> IntraActionState { get; private set; }
public IDictionary<String, IDictionary<String, String>> JobDefaults { get; private set; }
public Dictionary<string, VariableValue> JobOutputs { get; private set; } public Dictionary<string, VariableValue> JobOutputs { get; private set; }
public IDictionary<String, String> EnvironmentVariables { get; private set; }
public IList<String> FileTable { get; private set; }
public StepsContext StepsContext { get; private set; }
public DictionaryContextData ExpressionValues { get; } = new DictionaryContextData(); public DictionaryContextData ExpressionValues { get; } = new DictionaryContextData();
public IList<IFunctionInfo> ExpressionFunctions { get; } = new List<IFunctionInfo>(); public IList<IFunctionInfo> ExpressionFunctions { get; } = new List<IFunctionInfo>();
public bool WriteDebug { get; private set; }
public List<string> PrependPath { get; private set; } // Shared pointer across job-level execution context and step-level execution contexts
public ContainerInfo Container { get; set; } public GlobalContext Global { get; private set; }
public List<ContainerInfo> ServiceContainers { get; private set; }
// Only job level ExecutionContext has JobSteps // Only job level ExecutionContext has JobSteps
public List<IStep> JobSteps { get; private set; } public List<IStep> JobSteps { get; private set; }
@@ -199,8 +180,6 @@ namespace GitHub.Runner.Worker
} }
} }
public PlanFeatures Features { get; private set; }
private ExecutionContext Root private ExecutionContext Root
{ {
get get
@@ -277,7 +256,7 @@ namespace GitHub.Runner.Worker
{ {
step.ExecutionContext = Root.CreateChild(_record.Id, step.DisplayName, _record.Id.ToString("N"), scopeName, step.Action.ContextName, logger: _logger); step.ExecutionContext = Root.CreateChild(_record.Id, step.DisplayName, _record.Id.ToString("N"), scopeName, step.Action.ContextName, logger: _logger);
step.ExecutionContext.ExpressionValues["inputs"] = inputsData; step.ExecutionContext.ExpressionValues["inputs"] = inputsData;
step.ExecutionContext.ExpressionValues["steps"] = StepsContext.GetScope(step.ExecutionContext.GetFullyQualifiedContextName()); step.ExecutionContext.ExpressionValues["steps"] = Global.StepsContext.GetScope(step.ExecutionContext.GetFullyQualifiedContextName());
// Add the composite action environment variables to each step. // Add the composite action environment variables to each step.
#if OS_WINDOWS #if OS_WINDOWS
@@ -300,12 +279,9 @@ namespace GitHub.Runner.Worker
var child = new ExecutionContext(); var child = new ExecutionContext();
child.Initialize(HostContext); child.Initialize(HostContext);
child.Global = Global;
child.ScopeName = scopeName; child.ScopeName = scopeName;
child.ContextName = contextName; child.ContextName = contextName;
child.Features = Features;
child.Variables = Variables;
child.Endpoints = Endpoints;
child.Plan = Plan;
if (intraActionState == null) if (intraActionState == null)
{ {
child.IntraActionState = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); child.IntraActionState = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
@@ -314,10 +290,6 @@ namespace GitHub.Runner.Worker
{ {
child.IntraActionState = intraActionState; child.IntraActionState = intraActionState;
} }
child.EnvironmentVariables = EnvironmentVariables;
child.JobDefaults = JobDefaults;
child.FileTable = FileTable;
child.StepsContext = StepsContext;
foreach (var pair in ExpressionValues) foreach (var pair in ExpressionValues)
{ {
child.ExpressionValues[pair.Key] = pair.Value; child.ExpressionValues[pair.Key] = pair.Value;
@@ -327,11 +299,7 @@ namespace GitHub.Runner.Worker
child.ExpressionFunctions.Add(item); child.ExpressionFunctions.Add(item);
} }
child._cancellationTokenSource = new CancellationTokenSource(); child._cancellationTokenSource = new CancellationTokenSource();
child.WriteDebug = WriteDebug;
child._parentExecutionContext = this; child._parentExecutionContext = this;
child.PrependPath = PrependPath;
child.Container = Container;
child.ServiceContainers = ServiceContainers;
child.EchoOnActionCommand = EchoOnActionCommand; child.EchoOnActionCommand = EchoOnActionCommand;
if (recordOrder != null) if (recordOrder != null)
@@ -411,8 +379,8 @@ namespace GitHub.Runner.Worker
// todo: Skip if generated context name. After M271-ish the server will never send an empty context name. Generated context names will start with "__" // todo: Skip if generated context name. After M271-ish the server will never send an empty context name. Generated context names will start with "__"
if (!string.IsNullOrEmpty(ContextName)) if (!string.IsNullOrEmpty(ContextName))
{ {
StepsContext.SetOutcome(ScopeName, ContextName, (Outcome ?? Result ?? TaskResult.Succeeded).ToActionResult()); Global.StepsContext.SetOutcome(ScopeName, ContextName, (Outcome ?? Result ?? TaskResult.Succeeded).ToActionResult());
StepsContext.SetConclusion(ScopeName, ContextName, (Result ?? TaskResult.Succeeded).ToActionResult()); Global.StepsContext.SetConclusion(ScopeName, ContextName, (Result ?? TaskResult.Succeeded).ToActionResult());
} }
return Result.Value; return Result.Value;
@@ -480,7 +448,7 @@ namespace GitHub.Runner.Worker
// todo: restrict multiline? // todo: restrict multiline?
StepsContext.SetOutput(ScopeName, ContextName, name, value, out reference); Global.StepsContext.SetOutput(ScopeName, ContextName, name, value, out reference);
} }
public void SetTimeout(TimeSpan? timeout) public void SetTimeout(TimeSpan? timeout)
@@ -614,33 +582,35 @@ namespace GitHub.Runner.Worker
_cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token); _cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token);
Global = new GlobalContext();
// Plan // Plan
Plan = message.Plan; Global.Plan = message.Plan;
Features = PlanUtil.GetFeatures(message.Plan); Global.Features = PlanUtil.GetFeatures(message.Plan);
// Endpoints // Endpoints
Endpoints = message.Resources.Endpoints; Global.Endpoints = message.Resources.Endpoints;
// Variables // Variables
Variables = new Variables(HostContext, message.Variables); Global.Variables = new Variables(HostContext, message.Variables);
// Environment variables shared across all actions // Environment variables shared across all actions
EnvironmentVariables = new Dictionary<string, string>(VarUtil.EnvironmentVariableKeyComparer); Global.EnvironmentVariables = new Dictionary<string, string>(VarUtil.EnvironmentVariableKeyComparer);
// Job defaults shared across all actions // Job defaults shared across all actions
JobDefaults = new Dictionary<string, IDictionary<string, string>>(StringComparer.OrdinalIgnoreCase); Global.JobDefaults = new Dictionary<string, IDictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
// Job Outputs // Job Outputs
JobOutputs = new Dictionary<string, VariableValue>(StringComparer.OrdinalIgnoreCase); JobOutputs = new Dictionary<string, VariableValue>(StringComparer.OrdinalIgnoreCase);
// Service container info // Service container info
ServiceContainers = new List<ContainerInfo>(); Global.ServiceContainers = new List<ContainerInfo>();
// Steps context (StepsRunner manages adding the scoped steps context) // Steps context (StepsRunner manages adding the scoped steps context)
StepsContext = new StepsContext(); Global.StepsContext = new StepsContext();
// File table // File table
FileTable = new List<String>(message.FileTable ?? new string[0]); Global.FileTable = new List<String>(message.FileTable ?? new string[0]);
// Expression values // Expression values
if (message.ContextData?.Count > 0) if (message.ContextData?.Count > 0)
@@ -651,15 +621,15 @@ namespace GitHub.Runner.Worker
} }
} }
ExpressionValues["secrets"] = Variables.ToSecretsContext(); ExpressionValues["secrets"] = Global.Variables.ToSecretsContext();
ExpressionValues["runner"] = new RunnerContext(); ExpressionValues["runner"] = new RunnerContext();
ExpressionValues["job"] = new JobContext(); ExpressionValues["job"] = new JobContext();
Trace.Info("Initialize GitHub context"); Trace.Info("Initialize GitHub context");
var githubAccessToken = new StringContextData(Variables.Get("system.github.token")); var githubAccessToken = new StringContextData(Global.Variables.Get("system.github.token"));
var base64EncodedToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"x-access-token:{githubAccessToken}")); var base64EncodedToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"x-access-token:{githubAccessToken}"));
HostContext.SecretMasker.AddValue(base64EncodedToken); HostContext.SecretMasker.AddValue(base64EncodedToken);
var githubJob = Variables.Get("system.github.job"); var githubJob = Global.Variables.Get("system.github.job");
var githubContext = new GitHubContext(); var githubContext = new GitHubContext();
githubContext["token"] = githubAccessToken; githubContext["token"] = githubAccessToken;
if (!string.IsNullOrEmpty(githubJob)) if (!string.IsNullOrEmpty(githubJob))
@@ -682,7 +652,7 @@ namespace GitHub.Runner.Worker
#endif #endif
// Prepend Path // Prepend Path
PrependPath = new List<string>(); Global.PrependPath = new List<string>();
// JobSteps for job ExecutionContext // JobSteps for job ExecutionContext
JobSteps = new List<IStep>(); JobSteps = new List<IStep>();
@@ -708,10 +678,10 @@ namespace GitHub.Runner.Worker
_logger.Setup(_mainTimelineId, _record.Id); _logger.Setup(_mainTimelineId, _record.Id);
// Initialize 'echo on action command success' property, default to false, unless Step_Debug is set // Initialize 'echo on action command success' property, default to false, unless Step_Debug is set
EchoOnActionCommand = Variables.Step_Debug ?? false; EchoOnActionCommand = Global.Variables.Step_Debug ?? false;
// Verbosity (from GitHub.Step_Debug). // Verbosity (from GitHub.Step_Debug).
WriteDebug = Variables.Step_Debug ?? false; Global.WriteDebug = Global.Variables.Step_Debug ?? false;
// Hook up JobServerQueueThrottling event, we will log warning on server tarpit. // Hook up JobServerQueueThrottling event, we will log warning on server tarpit.
_jobServerQueue.JobServerQueueThrottling += JobServerQueueThrottling_EventReceived; _jobServerQueue.JobServerQueueThrottling += JobServerQueueThrottling_EventReceived;
@@ -960,7 +930,7 @@ namespace GitHub.Runner.Worker
// Do not add a format string overload. See comment on ExecutionContext.Write(). // Do not add a format string overload. See comment on ExecutionContext.Write().
public static void Debug(this IExecutionContext context, string message) public static void Debug(this IExecutionContext context, string message)
{ {
if (context.WriteDebug) if (context.Global.WriteDebug)
{ {
var multilines = message?.Replace("\r\n", "\n")?.Split("\n"); var multilines = message?.Replace("\r\n", "\n")?.Split("\n");
if (multilines != null) if (multilines != null)
@@ -985,7 +955,7 @@ namespace GitHub.Runner.Worker
traceWriter = context.ToTemplateTraceWriter(); traceWriter = context.ToTemplateTraceWriter();
} }
var schema = PipelineTemplateSchemaFactory.GetSchema(); var schema = PipelineTemplateSchemaFactory.GetSchema();
return new PipelineTemplateEvaluator(traceWriter, schema, context.FileTable); return new PipelineTemplateEvaluator(traceWriter, schema, context.Global.FileTable);
} }
public static ObjectTemplating.ITraceWriter ToTemplateTraceWriter(this IExecutionContext context) public static ObjectTemplating.ITraceWriter ToTemplateTraceWriter(this IExecutionContext context)

View File

@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using GitHub.DistributedTask.WebApi;
using GitHub.Runner.Common.Util;
using GitHub.Runner.Worker.Container;
namespace GitHub.Runner.Worker
{
public sealed class GlobalContext
{
public ContainerInfo Container { get; set; }
public List<ServiceEndpoint> Endpoints { get; set; }
public IDictionary<String, String> EnvironmentVariables { get; set; }
public PlanFeatures Features { get; set; }
public IList<String> FileTable { get; set; }
public IDictionary<String, IDictionary<String, String>> JobDefaults { get; set; }
public TaskOrchestrationPlanReference Plan { get; set; }
public List<string> PrependPath { get; set; }
public List<ContainerInfo> ServiceContainers { get; set; }
public StepsContext StepsContext { get; set; }
public Variables Variables { get; set; }
public bool WriteDebug { get; set; }
}
}

View File

@@ -73,7 +73,7 @@ namespace GitHub.Runner.Worker.Handlers
// Get the pointer of the correct "steps" object and pass it to the ExecutionContext so that we can process the outputs correctly // Get the pointer of the correct "steps" object and pass it to the ExecutionContext so that we can process the outputs correctly
ExecutionContext.ExpressionValues["inputs"] = inputsData; ExecutionContext.ExpressionValues["inputs"] = inputsData;
ExecutionContext.ExpressionValues["steps"] = ExecutionContext.StepsContext.GetScope(ExecutionContext.GetFullyQualifiedContextName()); ExecutionContext.ExpressionValues["steps"] = ExecutionContext.Global.StepsContext.GetScope(ExecutionContext.GetFullyQualifiedContextName());
ProcessCompositeActionOutputs(); ProcessCompositeActionOutputs();
} }
@@ -141,7 +141,7 @@ namespace GitHub.Runner.Worker.Handlers
{ {
Trace.Info($"Processing composite step: DisplayName='{step.DisplayName}'"); Trace.Info($"Processing composite step: DisplayName='{step.DisplayName}'");
step.ExecutionContext.ExpressionValues["steps"] = step.ExecutionContext.StepsContext.GetScope(step.ExecutionContext.ScopeName); step.ExecutionContext.ExpressionValues["steps"] = ExecutionContext.Global.StepsContext.GetScope(step.ExecutionContext.ScopeName);
// Populate env context for each step // Populate env context for each step
Trace.Info("Initialize Env context for step"); Trace.Info("Initialize Env context for step");
@@ -152,7 +152,7 @@ namespace GitHub.Runner.Worker.Handlers
#endif #endif
// Global env // Global env
foreach (var pair in step.ExecutionContext.EnvironmentVariables) foreach (var pair in ExecutionContext.Global.EnvironmentVariables)
{ {
envContext[pair.Key] = new StringContextData(pair.Value ?? string.Empty); envContext[pair.Key] = new StringContextData(pair.Value ?? string.Empty);
} }

View File

@@ -185,7 +185,7 @@ namespace GitHub.Runner.Worker.Handlers
} }
// Add Actions Runtime server info // Add Actions Runtime server info
var systemConnection = ExecutionContext.Endpoints.Single(x => string.Equals(x.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase)); var systemConnection = ExecutionContext.Global.Endpoints.Single(x => string.Equals(x.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase));
Environment["ACTIONS_RUNTIME_URL"] = systemConnection.Url.AbsoluteUri; Environment["ACTIONS_RUNTIME_URL"] = systemConnection.Url.AbsoluteUri;
Environment["ACTIONS_RUNTIME_TOKEN"] = systemConnection.Authorization.Parameters[EndpointAuthorizationParameters.AccessToken]; Environment["ACTIONS_RUNTIME_TOKEN"] = systemConnection.Authorization.Parameters[EndpointAuthorizationParameters.AccessToken];
if (systemConnection.Data.TryGetValue("CacheServerUrl", out var cacheUrl) && !string.IsNullOrEmpty(cacheUrl)) if (systemConnection.Data.TryGetValue("CacheServerUrl", out var cacheUrl) && !string.IsNullOrEmpty(cacheUrl))

View File

@@ -148,14 +148,14 @@ namespace GitHub.Runner.Worker.Handlers
{ {
// Validate args. // Validate args.
Trace.Entering(); Trace.Entering();
ArgUtil.NotNull(ExecutionContext.PrependPath, nameof(ExecutionContext.PrependPath)); ArgUtil.NotNull(ExecutionContext.Global.PrependPath, nameof(ExecutionContext.Global.PrependPath));
if (ExecutionContext.PrependPath.Count == 0) if (ExecutionContext.Global.PrependPath.Count == 0)
{ {
return; return;
} }
// Prepend path. // Prepend path.
string prepend = string.Join(Path.PathSeparator.ToString(), ExecutionContext.PrependPath.Reverse<string>()); string prepend = string.Join(Path.PathSeparator.ToString(), ExecutionContext.Global.PrependPath.Reverse<string>());
var containerStepHost = StepHost as ContainerStepHost; var containerStepHost = StepHost as ContainerStepHost;
if (containerStepHost != null) if (containerStepHost != null)
{ {

View File

@@ -46,7 +46,7 @@ namespace GitHub.Runner.Worker.Handlers
} }
// Add Actions Runtime server info // Add Actions Runtime server info
var systemConnection = ExecutionContext.Endpoints.Single(x => string.Equals(x.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase)); var systemConnection = ExecutionContext.Global.Endpoints.Single(x => string.Equals(x.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase));
Environment["ACTIONS_RUNTIME_URL"] = systemConnection.Url.AbsoluteUri; Environment["ACTIONS_RUNTIME_URL"] = systemConnection.Url.AbsoluteUri;
Environment["ACTIONS_RUNTIME_TOKEN"] = systemConnection.Authorization.Parameters[EndpointAuthorizationParameters.AccessToken]; Environment["ACTIONS_RUNTIME_TOKEN"] = systemConnection.Authorization.Parameters[EndpointAuthorizationParameters.AccessToken];
if (systemConnection.Data.TryGetValue("CacheServerUrl", out var cacheUrl) && !string.IsNullOrEmpty(cacheUrl)) if (systemConnection.Data.TryGetValue("CacheServerUrl", out var cacheUrl) && !string.IsNullOrEmpty(cacheUrl))
@@ -113,7 +113,7 @@ namespace GitHub.Runner.Worker.Handlers
requireExitCodeZero: false, requireExitCodeZero: false,
outputEncoding: outputEncoding, outputEncoding: outputEncoding,
killProcessOnCancel: false, killProcessOnCancel: false,
inheritConsoleHandler: !ExecutionContext.Variables.Retain_Default_Encoding, inheritConsoleHandler: !ExecutionContext.Global.Variables.Retain_Default_Encoding,
cancellationToken: ExecutionContext.CancellationToken); cancellationToken: ExecutionContext.CancellationToken);
// Wait for either the node exit or force finish through ##vso command // Wait for either the node exit or force finish through ##vso command

View File

@@ -31,7 +31,7 @@ namespace GitHub.Runner.Worker.Handlers
{ {
_executionContext = executionContext; _executionContext = executionContext;
_commandManager = commandManager; _commandManager = commandManager;
_container = container ?? executionContext.Container; _container = container ?? executionContext.Global.Container;
// Recursion failsafe (test override) // Recursion failsafe (test override)
var failsafeString = Environment.GetEnvironmentVariable("RUNNER_TEST_GET_REPOSITORY_PATH_FAILSAFE"); var failsafeString = Environment.GetEnvironmentVariable("RUNNER_TEST_GET_REPOSITORY_PATH_FAILSAFE");
@@ -41,7 +41,7 @@ namespace GitHub.Runner.Worker.Handlers
} }
// Determine the timeout // Determine the timeout
var timeoutStr = _executionContext.Variables.Get(_timeoutKey); var timeoutStr = _executionContext.Global.Variables.Get(_timeoutKey);
if (string.IsNullOrEmpty(timeoutStr) || if (string.IsNullOrEmpty(timeoutStr) ||
!TimeSpan.TryParse(timeoutStr, CultureInfo.InvariantCulture, out _timeout) || !TimeSpan.TryParse(timeoutStr, CultureInfo.InvariantCulture, out _timeout) ||
_timeout <= TimeSpan.Zero) _timeout <= TimeSpan.Zero)

View File

@@ -57,13 +57,13 @@ namespace GitHub.Runner.Worker.Handlers
string shellCommand; string shellCommand;
string shellCommandPath = null; string shellCommandPath = null;
bool validateShellOnHost = !(StepHost is ContainerStepHost); bool validateShellOnHost = !(StepHost is ContainerStepHost);
string prependPath = string.Join(Path.PathSeparator.ToString(), ExecutionContext.PrependPath.Reverse<string>()); string prependPath = string.Join(Path.PathSeparator.ToString(), ExecutionContext.Global.PrependPath.Reverse<string>());
string shell = null; string shell = null;
if (!Inputs.TryGetValue("shell", out shell) || string.IsNullOrEmpty(shell)) if (!Inputs.TryGetValue("shell", out shell) || string.IsNullOrEmpty(shell))
{ {
// TODO: figure out how defaults interact with template later // TODO: figure out how defaults interact with template later
// for now, we won't check job.defaults if we are inside a template. // for now, we won't check job.defaults if we are inside a template.
if (string.IsNullOrEmpty(ExecutionContext.ScopeName) && ExecutionContext.JobDefaults.TryGetValue("run", out var runDefaults)) if (string.IsNullOrEmpty(ExecutionContext.ScopeName) && ExecutionContext.Global.JobDefaults.TryGetValue("run", out var runDefaults))
{ {
runDefaults.TryGetValue("shell", out shell); runDefaults.TryGetValue("shell", out shell);
} }
@@ -153,7 +153,7 @@ namespace GitHub.Runner.Worker.Handlers
{ {
// TODO: figure out how defaults interact with template later // TODO: figure out how defaults interact with template later
// for now, we won't check job.defaults if we are inside a template. // for now, we won't check job.defaults if we are inside a template.
if (string.IsNullOrEmpty(ExecutionContext.ScopeName) && ExecutionContext.JobDefaults.TryGetValue("run", out var runDefaults)) if (string.IsNullOrEmpty(ExecutionContext.ScopeName) && ExecutionContext.Global.JobDefaults.TryGetValue("run", out var runDefaults))
{ {
if (runDefaults.TryGetValue("working-directory", out workingDirectory)) if (runDefaults.TryGetValue("working-directory", out workingDirectory))
{ {
@@ -169,7 +169,7 @@ namespace GitHub.Runner.Worker.Handlers
{ {
// TODO: figure out how defaults interact with template later // TODO: figure out how defaults interact with template later
// for now, we won't check job.defaults if we are inside a template. // for now, we won't check job.defaults if we are inside a template.
if (string.IsNullOrEmpty(ExecutionContext.ScopeName) && ExecutionContext.JobDefaults.TryGetValue("run", out var runDefaults)) if (string.IsNullOrEmpty(ExecutionContext.ScopeName) && ExecutionContext.Global.JobDefaults.TryGetValue("run", out var runDefaults))
{ {
if (runDefaults.TryGetValue("shell", out shell)) if (runDefaults.TryGetValue("shell", out shell))
{ {
@@ -180,7 +180,7 @@ namespace GitHub.Runner.Worker.Handlers
var isContainerStepHost = StepHost is ContainerStepHost; var isContainerStepHost = StepHost is ContainerStepHost;
string prependPath = string.Join(Path.PathSeparator.ToString(), ExecutionContext.PrependPath.Reverse<string>()); string prependPath = string.Join(Path.PathSeparator.ToString(), ExecutionContext.Global.PrependPath.Reverse<string>());
string commandPath, argFormat, shellCommand; string commandPath, argFormat, shellCommand;
// Set up default command and arguments // Set up default command and arguments
if (string.IsNullOrEmpty(shell)) if (string.IsNullOrEmpty(shell))
@@ -232,7 +232,7 @@ namespace GitHub.Runner.Worker.Handlers
#if OS_WINDOWS #if OS_WINDOWS
// Normalize Windows line endings // Normalize Windows line endings
contents = contents.Replace("\r\n", "\n").Replace("\n", "\r\n"); contents = contents.Replace("\r\n", "\n").Replace("\n", "\r\n");
var encoding = ExecutionContext.Variables.Retain_Default_Encoding && Console.InputEncoding.CodePage != 65001 var encoding = ExecutionContext.Global.Variables.Retain_Default_Encoding && Console.InputEncoding.CodePage != 65001
? Console.InputEncoding ? Console.InputEncoding
: new UTF8Encoding(false); : new UTF8Encoding(false);
#else #else
@@ -285,7 +285,7 @@ namespace GitHub.Runner.Worker.Handlers
requireExitCodeZero: false, requireExitCodeZero: false,
outputEncoding: null, outputEncoding: null,
killProcessOnCancel: false, killProcessOnCancel: false,
inheritConsoleHandler: !ExecutionContext.Variables.Retain_Default_Encoding, inheritConsoleHandler: !ExecutionContext.Global.Variables.Retain_Default_Encoding,
cancellationToken: ExecutionContext.CancellationToken); cancellationToken: ExecutionContext.CancellationToken);
// Error // Error

View File

@@ -162,7 +162,7 @@ namespace GitHub.Runner.Worker
var environmentVariables = templateEvaluator.EvaluateStepEnvironment(token, jobContext.ExpressionValues, jobContext.ExpressionFunctions, VarUtil.EnvironmentVariableKeyComparer); var environmentVariables = templateEvaluator.EvaluateStepEnvironment(token, jobContext.ExpressionValues, jobContext.ExpressionFunctions, VarUtil.EnvironmentVariableKeyComparer);
foreach (var pair in environmentVariables) foreach (var pair in environmentVariables)
{ {
context.EnvironmentVariables[pair.Key] = pair.Value ?? string.Empty; context.Global.EnvironmentVariables[pair.Key] = pair.Value ?? string.Empty;
context.SetEnvContext(pair.Key, pair.Value ?? string.Empty); context.SetEnvContext(pair.Key, pair.Value ?? string.Empty);
} }
} }
@@ -172,7 +172,7 @@ namespace GitHub.Runner.Worker
var container = templateEvaluator.EvaluateJobContainer(message.JobContainer, jobContext.ExpressionValues, jobContext.ExpressionFunctions); var container = templateEvaluator.EvaluateJobContainer(message.JobContainer, jobContext.ExpressionValues, jobContext.ExpressionFunctions);
if (container != null) if (container != null)
{ {
jobContext.Container = new Container.ContainerInfo(HostContext, container); jobContext.Global.Container = new Container.ContainerInfo(HostContext, container);
} }
// Evaluate the job service containers // Evaluate the job service containers
@@ -184,7 +184,7 @@ namespace GitHub.Runner.Worker
{ {
var networkAlias = pair.Key; var networkAlias = pair.Key;
var serviceContainer = pair.Value; var serviceContainer = pair.Value;
jobContext.ServiceContainers.Add(new Container.ContainerInfo(HostContext, serviceContainer, false, networkAlias)); jobContext.Global.ServiceContainers.Add(new Container.ContainerInfo(HostContext, serviceContainer, false, networkAlias));
} }
} }
@@ -195,14 +195,14 @@ namespace GitHub.Runner.Worker
var defaults = token.AssertMapping("defaults"); var defaults = token.AssertMapping("defaults");
if (defaults.Any(x => string.Equals(x.Key.AssertString("defaults key").Value, "run", StringComparison.OrdinalIgnoreCase))) if (defaults.Any(x => string.Equals(x.Key.AssertString("defaults key").Value, "run", StringComparison.OrdinalIgnoreCase)))
{ {
context.JobDefaults["run"] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); context.Global.JobDefaults["run"] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var defaultsRun = defaults.First(x => string.Equals(x.Key.AssertString("defaults key").Value, "run", StringComparison.OrdinalIgnoreCase)); var defaultsRun = defaults.First(x => string.Equals(x.Key.AssertString("defaults key").Value, "run", StringComparison.OrdinalIgnoreCase));
var jobDefaults = templateEvaluator.EvaluateJobDefaultsRun(defaultsRun.Value, jobContext.ExpressionValues, jobContext.ExpressionFunctions); var jobDefaults = templateEvaluator.EvaluateJobDefaultsRun(defaultsRun.Value, jobContext.ExpressionValues, jobContext.ExpressionFunctions);
foreach (var pair in jobDefaults) foreach (var pair in jobDefaults)
{ {
if (!string.IsNullOrEmpty(pair.Value)) if (!string.IsNullOrEmpty(pair.Value))
{ {
context.JobDefaults["run"][pair.Key] = pair.Value; context.Global.JobDefaults["run"][pair.Key] = pair.Value;
} }
} }
} }
@@ -216,15 +216,15 @@ namespace GitHub.Runner.Worker
preJobSteps.AddRange(prepareResult.ContainerSetupSteps); preJobSteps.AddRange(prepareResult.ContainerSetupSteps);
// Add start-container steps, record and stop-container steps // Add start-container steps, record and stop-container steps
if (jobContext.Container != null || jobContext.ServiceContainers.Count > 0) if (jobContext.Global.Container != null || jobContext.Global.ServiceContainers.Count > 0)
{ {
var containerProvider = HostContext.GetService<IContainerOperationProvider>(); var containerProvider = HostContext.GetService<IContainerOperationProvider>();
var containers = new List<Container.ContainerInfo>(); var containers = new List<Container.ContainerInfo>();
if (jobContext.Container != null) if (jobContext.Global.Container != null)
{ {
containers.Add(jobContext.Container); containers.Add(jobContext.Global.Container);
} }
containers.AddRange(jobContext.ServiceContainers); containers.AddRange(jobContext.Global.ServiceContainers);
preJobSteps.Add(new JobExtensionRunner(runAsync: containerProvider.StartContainersAsync, preJobSteps.Add(new JobExtensionRunner(runAsync: containerProvider.StartContainersAsync,
condition: $"{PipelineTemplateConstants.Success}()", condition: $"{PipelineTemplateConstants.Success}()",
@@ -305,7 +305,7 @@ namespace GitHub.Runner.Worker
steps.AddRange(jobSteps); steps.AddRange(jobSteps);
// Prepare for orphan process cleanup // Prepare for orphan process cleanup
_processCleanup = jobContext.Variables.GetBoolean("process.clean") ?? true; _processCleanup = jobContext.Global.Variables.GetBoolean("process.clean") ?? true;
if (_processCleanup) if (_processCleanup)
{ {
// Set the RUNNER_TRACKING_ID env variable. // Set the RUNNER_TRACKING_ID env variable.
@@ -376,13 +376,13 @@ namespace GitHub.Runner.Worker
var envContext = new CaseSensitiveDictionaryContextData(); var envContext = new CaseSensitiveDictionaryContextData();
#endif #endif
context.ExpressionValues["env"] = envContext; context.ExpressionValues["env"] = envContext;
foreach (var pair in context.EnvironmentVariables) foreach (var pair in context.Global.EnvironmentVariables)
{ {
envContext[pair.Key] = new StringContextData(pair.Value ?? string.Empty); envContext[pair.Key] = new StringContextData(pair.Value ?? string.Empty);
} }
Trace.Info("Initialize steps context for evaluating job outputs"); Trace.Info("Initialize steps context for evaluating job outputs");
context.ExpressionValues["steps"] = context.StepsContext.GetScope(context.ScopeName); context.ExpressionValues["steps"] = context.Global.StepsContext.GetScope(context.ScopeName);
var templateEvaluator = context.ToPipelineTemplateEvaluator(); var templateEvaluator = context.ToPipelineTemplateEvaluator();
var outputs = templateEvaluator.EvaluateJobOutput(message.JobOutputs, context.ExpressionValues, context.ExpressionFunctions); var outputs = templateEvaluator.EvaluateJobOutput(message.JobOutputs, context.ExpressionValues, context.ExpressionFunctions);
@@ -413,7 +413,7 @@ namespace GitHub.Runner.Worker
} }
} }
if (context.Variables.GetBoolean(Constants.Variables.Actions.RunnerDebug) ?? false) if (context.Global.Variables.GetBoolean(Constants.Variables.Actions.RunnerDebug) ?? false)
{ {
Trace.Info("Support log upload starting."); Trace.Info("Support log upload starting.");
context.Output("Uploading runner diagnostic logs"); context.Output("Uploading runner diagnostic logs");

View File

@@ -99,7 +99,7 @@ namespace GitHub.Runner.Worker
return await CompleteJobAsync(jobServer, jobContext, message, TaskResult.Failed); return await CompleteJobAsync(jobServer, jobContext, message, TaskResult.Failed);
} }
if (jobContext.WriteDebug) if (jobContext.Global.WriteDebug)
{ {
jobContext.SetRunnerContext("debug", "1"); jobContext.SetRunnerContext("debug", "1");
} }
@@ -209,7 +209,7 @@ namespace GitHub.Runner.Worker
// Clean TEMP after finish process jobserverqueue, since there might be a pending fileupload still use the TEMP dir. // Clean TEMP after finish process jobserverqueue, since there might be a pending fileupload still use the TEMP dir.
_tempDirectoryManager?.CleanupTempDirectory(); _tempDirectoryManager?.CleanupTempDirectory();
if (!jobContext.Features.HasFlag(PlanFeatures.JobCompletedPlanEvent)) if (!jobContext.Global.Features.HasFlag(PlanFeatures.JobCompletedPlanEvent))
{ {
Trace.Info($"Skip raise job completed event call from worker because Plan version is {message.Plan.Version}"); Trace.Info($"Skip raise job completed event call from worker because Plan version is {message.Plan.Version}");
return result; return result;

View File

@@ -100,12 +100,12 @@ namespace GitHub.Runner.Worker
RunnerActionPluginExecutionContext pluginContext = new RunnerActionPluginExecutionContext RunnerActionPluginExecutionContext pluginContext = new RunnerActionPluginExecutionContext
{ {
Inputs = inputs, Inputs = inputs,
Endpoints = context.Endpoints, Endpoints = context.Global.Endpoints,
Context = context.ExpressionValues Context = context.ExpressionValues
}; };
// variables // variables
foreach (var variable in context.Variables.AllVariables) foreach (var variable in context.Global.Variables.AllVariables)
{ {
pluginContext.Variables[variable.Name] = new VariableValue(variable.Value, variable.Secret); pluginContext.Variables[variable.Name] = new VariableValue(variable.Value, variable.Secret);
} }

View File

@@ -70,7 +70,8 @@ namespace GitHub.Runner.Worker
Trace.Info($"Processing step: DisplayName='{step.DisplayName}'"); Trace.Info($"Processing step: DisplayName='{step.DisplayName}'");
ArgUtil.NotNull(step.ExecutionContext, nameof(step.ExecutionContext)); ArgUtil.NotNull(step.ExecutionContext, nameof(step.ExecutionContext));
ArgUtil.NotNull(step.ExecutionContext.Variables, nameof(step.ExecutionContext.Variables)); ArgUtil.NotNull(step.ExecutionContext.Global, nameof(step.ExecutionContext.Global));
ArgUtil.NotNull(step.ExecutionContext.Global.Variables, nameof(step.ExecutionContext.Global.Variables));
// Start // Start
step.ExecutionContext.Start(); step.ExecutionContext.Start();
@@ -82,7 +83,7 @@ namespace GitHub.Runner.Worker
step.ExecutionContext.ExpressionFunctions.Add(new FunctionInfo<SuccessFunction>(PipelineTemplateConstants.Success, 0, 0)); step.ExecutionContext.ExpressionFunctions.Add(new FunctionInfo<SuccessFunction>(PipelineTemplateConstants.Success, 0, 0));
step.ExecutionContext.ExpressionFunctions.Add(new FunctionInfo<HashFilesFunction>(PipelineTemplateConstants.HashFiles, 1, byte.MaxValue)); step.ExecutionContext.ExpressionFunctions.Add(new FunctionInfo<HashFilesFunction>(PipelineTemplateConstants.HashFiles, 1, byte.MaxValue));
step.ExecutionContext.ExpressionValues["steps"] = step.ExecutionContext.StepsContext.GetScope(step.ExecutionContext.ScopeName); step.ExecutionContext.ExpressionValues["steps"] = step.ExecutionContext.Global.StepsContext.GetScope(step.ExecutionContext.ScopeName);
// Populate env context for each step // Populate env context for each step
Trace.Info("Initialize Env context for step"); Trace.Info("Initialize Env context for step");
@@ -92,7 +93,8 @@ namespace GitHub.Runner.Worker
var envContext = new CaseSensitiveDictionaryContextData(); var envContext = new CaseSensitiveDictionaryContextData();
#endif #endif
foreach (var pair in step.ExecutionContext.EnvironmentVariables) // Global env
foreach (var pair in step.ExecutionContext.Global.EnvironmentVariables)
{ {
envContext[pair.Key] = new StringContextData(pair.Value ?? string.Empty); envContext[pair.Key] = new StringContextData(pair.Value ?? string.Empty);
} }
@@ -105,7 +107,7 @@ namespace GitHub.Runner.Worker
// Set GITHUB_ACTION // Set GITHUB_ACTION
// Warning: Do not turn on FF DistributedTask.UseContextNameForGITHUBACTION until after M271-ish. After M271-ish // Warning: Do not turn on FF DistributedTask.UseContextNameForGITHUBACTION until after M271-ish. After M271-ish
// the server will never send an empty context name. Generated context names start with "__" // the server will never send an empty context name. Generated context names start with "__"
if (step.ExecutionContext.Variables.GetBoolean("DistributedTask.UseContextNameForGITHUBACTION") ?? false) if (step.ExecutionContext.Global.Variables.GetBoolean("DistributedTask.UseContextNameForGITHUBACTION") ?? false)
{ {
step.ExecutionContext.SetGitHubContext("action", actionStep.Action.Name); step.ExecutionContext.SetGitHubContext("action", actionStep.Action.Name);
} }

View File

@@ -96,7 +96,7 @@ namespace GitHub.Runner.Common.Tests.Worker
hc.GetTrace().Info($"{issue.Type} {issue.Message} {message ?? string.Empty}"); hc.GetTrace().Info($"{issue.Type} {issue.Message} {message ?? string.Empty}");
}); });
_ec.Setup(x => x.EnvironmentVariables).Returns(new Dictionary<string, string>()); _ec.Object.Global.EnvironmentVariables = new Dictionary<string, string>();
Assert.True(_commandManager.TryProcessCommand(_ec.Object, "##[stop-commands]stopToken", null)); Assert.True(_commandManager.TryProcessCommand(_ec.Object, "##[stop-commands]stopToken", null));
Assert.False(_commandManager.TryProcessCommand(_ec.Object, "##[set-env name=foo]bar", null)); Assert.False(_commandManager.TryProcessCommand(_ec.Object, "##[set-env name=foo]bar", null));
@@ -119,8 +119,6 @@ namespace GitHub.Runner.Common.Tests.Worker
return 1; return 1;
}); });
_ec.SetupAllProperties();
Assert.False(_ec.Object.EchoOnActionCommand); Assert.False(_ec.Object.EchoOnActionCommand);
Assert.True(_commandManager.TryProcessCommand(_ec.Object, "::echo::on", null)); Assert.True(_commandManager.TryProcessCommand(_ec.Object, "::echo::on", null));
@@ -204,8 +202,6 @@ namespace GitHub.Runner.Common.Tests.Worker
return 1; return 1;
}); });
_ec.SetupAllProperties();
// Echo commands below are considered "processed", but are invalid // Echo commands below are considered "processed", but are invalid
// 1. Invalid echo value // 1. Invalid echo value
Assert.True(_commandManager.TryProcessCommand(_ec.Object, "::echo::invalid", null)); Assert.True(_commandManager.TryProcessCommand(_ec.Object, "::echo::invalid", null));
@@ -287,6 +283,8 @@ namespace GitHub.Runner.Common.Tests.Worker
// Execution context // Execution context
_ec = new Mock<IExecutionContext>(); _ec = new Mock<IExecutionContext>();
_ec.SetupAllProperties();
_ec.Setup(x => x.Global).Returns(new GlobalContext());
// Command manager // Command manager
_commandManager = new ActionCommandManager(); _commandManager = new ActionCommandManager();

View File

@@ -3575,17 +3575,18 @@ runs:
_workFolder = _hc.GetDirectory(WellKnownDirectory.Work); _workFolder = _hc.GetDirectory(WellKnownDirectory.Work);
_ec = new Mock<IExecutionContext>(); _ec = new Mock<IExecutionContext>();
_ec.Setup(x => x.Global).Returns(new GlobalContext());
_ec.Setup(x => x.CancellationToken).Returns(_ecTokenSource.Token); _ec.Setup(x => x.CancellationToken).Returns(_ecTokenSource.Token);
var variables = new Dictionary<string, VariableValue>(); var variables = new Dictionary<string, VariableValue>();
if (newActionMetadata) if (newActionMetadata)
{ {
variables["DistributedTask.NewActionMetadata"] = "true"; variables["DistributedTask.NewActionMetadata"] = "true";
} }
_ec.Setup(x => x.Variables).Returns(new Variables(_hc, variables)); _ec.Object.Global.Variables = new Variables(_hc, variables);
_ec.Setup(x => x.ExpressionValues).Returns(new DictionaryContextData()); _ec.Setup(x => x.ExpressionValues).Returns(new DictionaryContextData());
_ec.Setup(x => x.ExpressionFunctions).Returns(new List<IFunctionInfo>()); _ec.Setup(x => x.ExpressionFunctions).Returns(new List<IFunctionInfo>());
_ec.Setup(x => x.FileTable).Returns(new List<String>()); _ec.Object.Global.FileTable = new List<String>();
_ec.Setup(x => x.Plan).Returns(new TaskOrchestrationPlanReference()); _ec.Object.Global.Plan = new TaskOrchestrationPlanReference();
_ec.Setup(x => x.Write(It.IsAny<string>(), It.IsAny<string>())).Callback((string tag, string message) => { _hc.GetTrace().Info($"[{tag}]{message}"); }); _ec.Setup(x => x.Write(It.IsAny<string>(), It.IsAny<string>())).Callback((string tag, string message) => { _hc.GetTrace().Info($"[{tag}]{message}"); });
_ec.Setup(x => x.AddIssue(It.IsAny<Issue>(), It.IsAny<string>())).Callback((Issue issue, string message) => { _hc.GetTrace().Info($"[{issue.Type}]{issue.Message ?? message}"); }); _ec.Setup(x => x.AddIssue(It.IsAny<Issue>(), It.IsAny<string>())).Callback((Issue issue, string message) => { _hc.GetTrace().Info($"[{issue.Type}]{issue.Message ?? message}"); });
_ec.Setup(x => x.GetGitHubContext("workspace")).Returns(Path.Combine(_workFolder, "actions", "actions")); _ec.Setup(x => x.GetGitHubContext("workspace")).Returns(Path.Combine(_workFolder, "actions", "actions"));

View File

@@ -754,12 +754,16 @@ namespace GitHub.Runner.Common.Tests.Worker
_hc = new TestHostContext(this, name); _hc = new TestHostContext(this, name);
_ec = new Mock<IExecutionContext>(); _ec = new Mock<IExecutionContext>();
_ec.Setup(x => x.WriteDebug).Returns(true); _ec.Setup(x => x.Global)
.Returns(new GlobalContext
{
FileTable = new List<String>(),
Variables = new Variables(_hc, new Dictionary<string, VariableValue>()),
WriteDebug = true,
});
_ec.Setup(x => x.CancellationToken).Returns(_ecTokenSource.Token); _ec.Setup(x => x.CancellationToken).Returns(_ecTokenSource.Token);
_ec.Setup(x => x.Variables).Returns(new Variables(_hc, new Dictionary<string, VariableValue>()));
_ec.Setup(x => x.ExpressionValues).Returns(new DictionaryContextData()); _ec.Setup(x => x.ExpressionValues).Returns(new DictionaryContextData());
_ec.Setup(x => x.ExpressionFunctions).Returns(new List<IFunctionInfo>()); _ec.Setup(x => x.ExpressionFunctions).Returns(new List<IFunctionInfo>());
_ec.Setup(x => x.FileTable).Returns(new List<String>());
_ec.Setup(x => x.Write(It.IsAny<string>(), It.IsAny<string>())).Callback((string tag, string message) => { _hc.GetTrace().Info($"{tag}{message}"); }); _ec.Setup(x => x.Write(It.IsAny<string>(), It.IsAny<string>())).Callback((string tag, string message) => { _hc.GetTrace().Info($"{tag}{message}"); });
_ec.Setup(x => x.AddIssue(It.IsAny<Issue>(), It.IsAny<string>())).Callback((Issue issue, string message) => { _hc.GetTrace().Info($"[{issue.Type}]{issue.Message ?? message}"); }); _ec.Setup(x => x.AddIssue(It.IsAny<Issue>(), It.IsAny<string>())).Callback((Issue issue, string message) => { _hc.GetTrace().Info($"[{issue.Type}]{issue.Message ?? message}"); });
} }

View File

@@ -375,15 +375,16 @@ namespace GitHub.Runner.Common.Tests.Worker
#endif #endif
_ec = new Mock<IExecutionContext>(); _ec = new Mock<IExecutionContext>();
_ec.Setup(x => x.Global).Returns(new GlobalContext());
_ec.Setup(x => x.ExpressionValues).Returns(_context); _ec.Setup(x => x.ExpressionValues).Returns(_context);
_ec.Setup(x => x.ExpressionFunctions).Returns(new List<IFunctionInfo>()); _ec.Setup(x => x.ExpressionFunctions).Returns(new List<IFunctionInfo>());
_ec.Setup(x => x.IntraActionState).Returns(new Dictionary<string, string>()); _ec.Setup(x => x.IntraActionState).Returns(new Dictionary<string, string>());
_ec.Setup(x => x.EnvironmentVariables).Returns(new Dictionary<string, string>()); _ec.Object.Global.EnvironmentVariables = new Dictionary<string, string>();
_ec.Setup(x => x.FileTable).Returns(new List<String>()); _ec.Object.Global.FileTable = new List<String>();
_ec.Setup(x => x.SetGitHubContext(It.IsAny<string>(), It.IsAny<string>())); _ec.Setup(x => x.SetGitHubContext(It.IsAny<string>(), It.IsAny<string>()));
_ec.Setup(x => x.GetGitHubContext(It.IsAny<string>())).Returns("{\"foo\":\"bar\"}"); _ec.Setup(x => x.GetGitHubContext(It.IsAny<string>())).Returns("{\"foo\":\"bar\"}");
_ec.Setup(x => x.CancellationToken).Returns(_ecTokenSource.Token); _ec.Setup(x => x.CancellationToken).Returns(_ecTokenSource.Token);
_ec.Setup(x => x.Variables).Returns(new Variables(_hc, new Dictionary<string, VariableValue>())); _ec.Object.Global.Variables = new Variables(_hc, new Dictionary<string, VariableValue>());
_ec.Setup(x => x.Write(It.IsAny<string>(), It.IsAny<string>())).Callback((string tag, string message) => { _hc.GetTrace().Info($"[{tag}]{message}"); }); _ec.Setup(x => x.Write(It.IsAny<string>(), It.IsAny<string>())).Callback((string tag, string message) => { _hc.GetTrace().Info($"[{tag}]{message}"); });
_ec.Setup(x => x.AddIssue(It.IsAny<Issue>(), It.IsAny<string>())).Callback((Issue issue, string message) => { _hc.GetTrace().Info($"[{issue.Type}]{issue.Message ?? message}"); }); _ec.Setup(x => x.AddIssue(It.IsAny<Issue>(), It.IsAny<string>())).Callback((Issue issue, string message) => { _hc.GetTrace().Info($"[{issue.Type}]{issue.Message ?? message}"); });

View File

@@ -357,20 +357,20 @@ namespace GitHub.Runner.Common.Tests.Worker
// Act. // Act.
jobContext.InitializeJob(jobRequest, CancellationToken.None); jobContext.InitializeJob(jobRequest, CancellationToken.None);
jobContext.StepsContext.SetConclusion(null, "step1", ActionResult.Success); jobContext.Global.StepsContext.SetConclusion(null, "step1", ActionResult.Success);
var conclusion1 = (jobContext.StepsContext.GetScope(null)["step1"] as DictionaryContextData)["conclusion"].ToString(); var conclusion1 = (jobContext.Global.StepsContext.GetScope(null)["step1"] as DictionaryContextData)["conclusion"].ToString();
Assert.Equal(conclusion1, conclusion1.ToLowerInvariant()); Assert.Equal(conclusion1, conclusion1.ToLowerInvariant());
jobContext.StepsContext.SetOutcome(null, "step2", ActionResult.Cancelled); jobContext.Global.StepsContext.SetOutcome(null, "step2", ActionResult.Cancelled);
var outcome1 = (jobContext.StepsContext.GetScope(null)["step2"] as DictionaryContextData)["outcome"].ToString(); var outcome1 = (jobContext.Global.StepsContext.GetScope(null)["step2"] as DictionaryContextData)["outcome"].ToString();
Assert.Equal(outcome1, outcome1.ToLowerInvariant()); Assert.Equal(outcome1, outcome1.ToLowerInvariant());
jobContext.StepsContext.SetConclusion(null, "step3", ActionResult.Failure); jobContext.Global.StepsContext.SetConclusion(null, "step3", ActionResult.Failure);
var conclusion2 = (jobContext.StepsContext.GetScope(null)["step3"] as DictionaryContextData)["conclusion"].ToString(); var conclusion2 = (jobContext.Global.StepsContext.GetScope(null)["step3"] as DictionaryContextData)["conclusion"].ToString();
Assert.Equal(conclusion2, conclusion2.ToLowerInvariant()); Assert.Equal(conclusion2, conclusion2.ToLowerInvariant());
jobContext.StepsContext.SetOutcome(null, "step4", ActionResult.Skipped); jobContext.Global.StepsContext.SetOutcome(null, "step4", ActionResult.Skipped);
var outcome2 = (jobContext.StepsContext.GetScope(null)["step4"] as DictionaryContextData)["outcome"].ToString(); var outcome2 = (jobContext.Global.StepsContext.GetScope(null)["step4"] as DictionaryContextData)["outcome"].ToString();
Assert.Equal(outcome2, outcome2.ToLowerInvariant()); Assert.Equal(outcome2, outcome2.ToLowerInvariant());
jobContext.JobContext.Status = ActionResult.Success; jobContext.JobContext.Status = ActionResult.Success;

View File

@@ -955,12 +955,13 @@ namespace GitHub.Runner.Common.Tests.Worker
_variables = new Variables(hostContext, new Dictionary<string, DTWebApi.VariableValue>()); _variables = new Variables(hostContext, new Dictionary<string, DTWebApi.VariableValue>());
_executionContext = new Mock<IExecutionContext>(); _executionContext = new Mock<IExecutionContext>();
_executionContext.Setup(x => x.WriteDebug) _executionContext.Setup(x => x.Global)
.Returns(true); .Returns(new GlobalContext
_executionContext.Setup(x => x.Variables) {
.Returns(_variables); Container = jobContainer,
_executionContext.Setup(x => x.Container) Variables = _variables,
.Returns(jobContainer); WriteDebug = true,
});
_executionContext.Setup(x => x.GetMatchers()) _executionContext.Setup(x => x.GetMatchers())
.Returns(matchers?.Matchers ?? new List<IssueMatcherConfig>()); .Returns(matchers?.Matchers ?? new List<IssueMatcherConfig>());
_executionContext.Setup(x => x.Add(It.IsAny<OnMatcherChanged>())) _executionContext.Setup(x => x.Add(It.IsAny<OnMatcherChanged>()))

View File

@@ -203,6 +203,7 @@ namespace GitHub.Runner.Common.Tests.Worker
// Setup the execution context. // Setup the execution context.
_ec = new Mock<IExecutionContext>(); _ec = new Mock<IExecutionContext>();
_ec.Setup(x => x.Global).Returns(new GlobalContext());
GitHubContext githubContext = new GitHubContext(); GitHubContext githubContext = new GitHubContext();
_ec.Setup(x => x.GetGitHubContext("repository")).Returns("actions/runner"); _ec.Setup(x => x.GetGitHubContext("repository")).Returns("actions/runner");

View File

@@ -38,7 +38,9 @@ namespace GitHub.Runner.Common.Tests.Worker
}; };
_ec = new Mock<IExecutionContext>(); _ec = new Mock<IExecutionContext>();
_ec.SetupAllProperties(); _ec.SetupAllProperties();
_ec.Setup(x => x.Variables).Returns(_variables); _ec.Setup(x => x.Global).Returns(new GlobalContext { WriteDebug = true });
_ec.Object.Global.Variables = _variables;
_ec.Object.Global.EnvironmentVariables = _env;
_contexts = new DictionaryContextData(); _contexts = new DictionaryContextData();
_jobContext = new JobContext(); _jobContext = new JobContext();
@@ -50,7 +52,7 @@ namespace GitHub.Runner.Common.Tests.Worker
_ec.Setup(x => x.JobContext).Returns(_jobContext); _ec.Setup(x => x.JobContext).Returns(_jobContext);
_stepContext = new StepsContext(); _stepContext = new StepsContext();
_ec.Setup(x => x.StepsContext).Returns(_stepContext); _ec.Object.Global.StepsContext = _stepContext;
_ec.Setup(x => x.PostJobSteps).Returns(new Stack<IStep>()); _ec.Setup(x => x.PostJobSteps).Returns(new Stack<IStep>());
@@ -599,13 +601,10 @@ namespace GitHub.Runner.Common.Tests.Worker
// Setup the step execution context. // Setup the step execution context.
var stepContext = new Mock<IExecutionContext>(); var stepContext = new Mock<IExecutionContext>();
stepContext.SetupAllProperties(); stepContext.SetupAllProperties();
stepContext.Setup(x => x.WriteDebug).Returns(true); stepContext.Setup(x => x.Global).Returns(() => _ec.Object.Global);
stepContext.Setup(x => x.Variables).Returns(_variables);
stepContext.Setup(x => x.EnvironmentVariables).Returns(_env);
stepContext.Setup(x => x.ExpressionValues).Returns(new DictionaryContextData()); stepContext.Setup(x => x.ExpressionValues).Returns(new DictionaryContextData());
stepContext.Setup(x => x.ExpressionFunctions).Returns(new List<IFunctionInfo>()); stepContext.Setup(x => x.ExpressionFunctions).Returns(new List<IFunctionInfo>());
stepContext.Setup(x => x.JobContext).Returns(_jobContext); stepContext.Setup(x => x.JobContext).Returns(_jobContext);
stepContext.Setup(x => x.StepsContext).Returns(_stepContext);
stepContext.Setup(x => x.ContextName).Returns(step.Object.Action.ContextName); stepContext.Setup(x => x.ContextName).Returns(step.Object.Action.ContextName);
stepContext.Setup(x => x.Complete(It.IsAny<TaskResult?>(), It.IsAny<string>(), It.IsAny<string>())) stepContext.Setup(x => x.Complete(It.IsAny<TaskResult?>(), It.IsAny<string>(), It.IsAny<string>()))
.Callback((TaskResult? r, string currentOperation, string resultCode) => .Callback((TaskResult? r, string currentOperation, string resultCode) =>