Fix IDE0090 (#2211)

This commit is contained in:
Cory Miller
2022-10-18 10:54:08 -04:00
committed by GitHub
parent daba735b52
commit b87b4aac5c
99 changed files with 412 additions and 412 deletions

View File

@@ -31,7 +31,7 @@ namespace GitHub.Runner.Common
new EscapeMapping(token: "%", replacement: "%25"),
};
private readonly Dictionary<string, string> _properties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, string> _properties = new(StringComparer.OrdinalIgnoreCase);
public const string Prefix = "##[";
public const string _commandKey = "::";

View File

@@ -74,12 +74,12 @@ namespace GitHub.Runner.Common
{
get
{
Uri accountUri = new Uri(this.ServerUrl);
Uri accountUri = new(this.ServerUrl);
string repoOrOrgName = string.Empty;
if (accountUri.Host.EndsWith(".githubusercontent.com", StringComparison.OrdinalIgnoreCase))
{
Uri gitHubUrl = new Uri(this.GitHubUrl);
Uri gitHubUrl = new(this.GitHubUrl);
// Use the "NWO part" from the GitHub URL path
repoOrOrgName = gitHubUrl.AbsolutePath.Trim('/');

View File

@@ -14,7 +14,7 @@ namespace GitHub.Runner.Common
public sealed class ExtensionManager : RunnerService, IExtensionManager
{
private readonly ConcurrentDictionary<Type, List<IExtension>> _cache = new ConcurrentDictionary<Type, List<IExtension>>();
private readonly ConcurrentDictionary<Type, List<IExtension>> _cache = new();
public List<T> GetExtensions<T>() where T : class, IExtension
{

View File

@@ -51,12 +51,12 @@ namespace GitHub.Runner.Common
private static int _defaultLogRetentionDays = 30;
private static int[] _vssHttpMethodEventIds = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 24 };
private static int[] _vssHttpCredentialEventIds = new int[] { 11, 13, 14, 15, 16, 17, 18, 20, 21, 22, 27, 29 };
private readonly ConcurrentDictionary<Type, object> _serviceInstances = new ConcurrentDictionary<Type, object>();
private readonly ConcurrentDictionary<Type, Type> _serviceTypes = new ConcurrentDictionary<Type, Type>();
private readonly ConcurrentDictionary<Type, object> _serviceInstances = new();
private readonly ConcurrentDictionary<Type, Type> _serviceTypes = new();
private readonly ISecretMasker _secretMasker = new SecretMasker();
private readonly List<ProductInfoHeaderValue> _userAgents = new List<ProductInfoHeaderValue>() { new ProductInfoHeaderValue($"GitHubActionsRunner-{BuildConstants.RunnerPackage.PackageName}", BuildConstants.RunnerPackage.Version) };
private CancellationTokenSource _runnerShutdownTokenSource = new CancellationTokenSource();
private object _perfLock = new object();
private readonly List<ProductInfoHeaderValue> _userAgents = new() { new ProductInfoHeaderValue($"GitHubActionsRunner-{BuildConstants.RunnerPackage.PackageName}", BuildConstants.RunnerPackage.Version) };
private CancellationTokenSource _runnerShutdownTokenSource = new();
private object _perfLock = new();
private Tracing _trace;
private Tracing _actionsHttpTrace;
private Tracing _netcoreHttpTrace;
@@ -66,7 +66,7 @@ namespace GitHub.Runner.Common
private IDisposable _diagListenerSubscription;
private StartupType _startupType;
private string _perfFile;
private RunnerWebProxy _webProxy = new RunnerWebProxy();
private RunnerWebProxy _webProxy = new();
public event EventHandler Unloading;
public CancellationToken RunnerShutdownToken => _runnerShutdownTokenSource.Token;

View File

@@ -164,7 +164,7 @@ namespace GitHub.Runner.Common
{
if (_enableLogRetention)
{
DirectoryInfo diags = new DirectoryInfo(_logFileDirectory);
DirectoryInfo diags = new(_logFileDirectory);
var logs = diags.GetFiles($"{_logFilePrefix}*.log");
foreach (var log in logs)
{

View File

@@ -39,19 +39,19 @@ namespace GitHub.Runner.Common
private Guid _jobTimelineRecordId;
// queue for web console line
private readonly ConcurrentQueue<ConsoleLineInfo> _webConsoleLineQueue = new ConcurrentQueue<ConsoleLineInfo>();
private readonly ConcurrentQueue<ConsoleLineInfo> _webConsoleLineQueue = new();
// queue for file upload (log file or attachment)
private readonly ConcurrentQueue<UploadFileInfo> _fileUploadQueue = new ConcurrentQueue<UploadFileInfo>();
private readonly ConcurrentQueue<UploadFileInfo> _fileUploadQueue = new();
// queue for timeline or timeline record update (one queue per timeline)
private readonly ConcurrentDictionary<Guid, ConcurrentQueue<TimelineRecord>> _timelineUpdateQueue = new ConcurrentDictionary<Guid, ConcurrentQueue<TimelineRecord>>();
private readonly ConcurrentDictionary<Guid, ConcurrentQueue<TimelineRecord>> _timelineUpdateQueue = new();
// indicate how many timelines we have, we will process _timelineUpdateQueue base on the order of timeline in this list
private readonly List<Guid> _allTimelines = new List<Guid>();
private readonly List<Guid> _allTimelines = new();
// bufferd timeline records that fail to update
private readonly Dictionary<Guid, List<TimelineRecord>> _bufferedRetryRecords = new Dictionary<Guid, List<TimelineRecord>>();
private readonly Dictionary<Guid, List<TimelineRecord>> _bufferedRetryRecords = new();
// Task for each queue's dequeue process
private Task _webConsoleLineDequeueTask;
@@ -61,8 +61,8 @@ namespace GitHub.Runner.Common
// common
private IJobServer _jobServer;
private Task[] _allDequeueTasks;
private readonly TaskCompletionSource<int> _jobCompletionSource = new TaskCompletionSource<int>();
private readonly TaskCompletionSource<int> _jobRecordUpdated = new TaskCompletionSource<int>();
private readonly TaskCompletionSource<int> _jobCompletionSource = new();
private readonly TaskCompletionSource<int> _jobRecordUpdated = new();
private bool _queueInProcess = false;
public TaskCompletionSource<int> JobRecordUpdated => _jobRecordUpdated;
@@ -237,8 +237,8 @@ namespace GitHub.Runner.Common
}
// Group consolelines by timeline record of each step
Dictionary<Guid, List<TimelineRecordLogLine>> stepsConsoleLines = new Dictionary<Guid, List<TimelineRecordLogLine>>();
List<Guid> stepRecordIds = new List<Guid>(); // We need to keep lines in order
Dictionary<Guid, List<TimelineRecordLogLine>> stepsConsoleLines = new();
List<Guid> stepRecordIds = new(); // We need to keep lines in order
int linesCounter = 0;
ConsoleLineInfo lineInfo;
while (_webConsoleLineQueue.TryDequeue(out lineInfo))
@@ -264,7 +264,7 @@ namespace GitHub.Runner.Common
{
// Split consolelines into batch, each batch will container at most 100 lines.
int batchCounter = 0;
List<List<TimelineRecordLogLine>> batchedLines = new List<List<TimelineRecordLogLine>>();
List<List<TimelineRecordLogLine>> batchedLines = new();
foreach (var line in stepsConsoleLines[stepRecordId])
{
var currentBatch = batchedLines.ElementAtOrDefault(batchCounter);
@@ -338,7 +338,7 @@ namespace GitHub.Runner.Common
{
while (!_jobCompletionSource.Task.IsCompleted || runOnce)
{
List<UploadFileInfo> filesToUpload = new List<UploadFileInfo>();
List<UploadFileInfo> filesToUpload = new();
UploadFileInfo dequeueFile;
while (_fileUploadQueue.TryDequeue(out dequeueFile))
{
@@ -398,13 +398,13 @@ namespace GitHub.Runner.Common
{
while (!_jobCompletionSource.Task.IsCompleted || runOnce)
{
List<PendingTimelineRecord> pendingUpdates = new List<PendingTimelineRecord>();
List<PendingTimelineRecord> pendingUpdates = new();
foreach (var timeline in _allTimelines)
{
ConcurrentQueue<TimelineRecord> recordQueue;
if (_timelineUpdateQueue.TryGetValue(timeline, out recordQueue))
{
List<TimelineRecord> records = new List<TimelineRecord>();
List<TimelineRecord> records = new();
TimelineRecord record;
while (recordQueue.TryDequeue(out record))
{
@@ -426,7 +426,7 @@ namespace GitHub.Runner.Common
// we need track whether we have new sub-timeline been created on the last run.
// if so, we need continue update timeline record even we on the last run.
bool pendingSubtimelineUpdate = false;
List<Exception> mainTimelineRecordsUpdateErrors = new List<Exception>();
List<Exception> mainTimelineRecordsUpdateErrors = new();
if (pendingUpdates.Count > 0)
{
foreach (var update in pendingUpdates)
@@ -529,7 +529,7 @@ namespace GitHub.Runner.Common
return timelineRecords;
}
Dictionary<Guid, TimelineRecord> dict = new Dictionary<Guid, TimelineRecord>();
Dictionary<Guid, TimelineRecord> dict = new();
foreach (TimelineRecord rec in timelineRecords)
{
if (rec == null)

View File

@@ -76,7 +76,7 @@ namespace GitHub.Runner.Common
public async Task<WorkerMessage> ReceiveAsync(CancellationToken cancellationToken)
{
WorkerMessage result = new WorkerMessage(MessageType.NotInitialized, string.Empty);
WorkerMessage result = new(MessageType.NotInitialized, string.Empty);
result.MessageType = (MessageType)await _readStream.ReadInt32Async(cancellationToken);
result.Body = await _readStream.ReadStringAsync(cancellationToken);
Trace.Info($"Receiving message of length {result.Body.Length}, with hash '{IOUtil.GetSha256Hash(result.Body)}'");

View File

@@ -291,7 +291,7 @@ namespace GitHub.Runner.Common
public static string GetEnvironmentVariable(this Process process, IHostContext hostContext, string variable)
{
var trace = hostContext.GetTrace(nameof(LinuxProcessExtensions));
Dictionary<string, string> env = new Dictionary<string, string>();
Dictionary<string, string> env = new();
if (Directory.Exists("/proc"))
{
@@ -322,8 +322,8 @@ namespace GitHub.Runner.Common
// It doesn't escape '=' or ' ', so we can't parse the output into a dictionary of all envs.
// So we only look for the env you request, in the format of variable=value. (it won't work if you variable contains = or space)
trace.Info($"Read env from output of `ps e -p {process.Id} -o command`");
List<string> psOut = new List<string>();
object outputLock = new object();
List<string> psOut = new();
object outputLock = new();
using (var p = hostContext.CreateService<IProcessInvoker>())
{
p.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs stdout)

View File

@@ -81,7 +81,7 @@ namespace GitHub.Runner.Common
}
// Trace whether a value was entered.
string val = new String(chars.ToArray());
string val = new(chars.ToArray());
if (!string.IsNullOrEmpty(val))
{
HostContext.SecretMasker.AddValue(val);

View File

@@ -14,7 +14,7 @@ namespace GitHub.Runner.Common
public sealed class TraceManager : ITraceManager
{
private readonly ConcurrentDictionary<string, Tracing> _sources = new ConcurrentDictionary<string, Tracing>(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<string, Tracing> _sources = new(StringComparer.OrdinalIgnoreCase);
private readonly HostTraceListener _hostTraceListener;
private TraceSetting _traceSetting;
private ISecretMasker _secretMasker;

View File

@@ -347,8 +347,8 @@ namespace GitHub.Runner.Listener.Check
public sealed class HttpEventSourceListener : EventListener
{
private readonly List<string> _logs;
private readonly object _lock = new object();
private readonly Dictionary<string, HashSet<string>> _ignoredEvent = new Dictionary<string, HashSet<string>>
private readonly object _lock = new();
private readonly Dictionary<string, HashSet<string>> _ignoredEvent = new()
{
{
"Microsoft-System-Net-Http",

View File

@@ -86,7 +86,7 @@ namespace GitHub.Runner.Listener.Check
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
// Request to github.com or ghes server
Uri requestUrl = new Uri(url);
Uri requestUrl = new(url);
var env = new Dictionary<string, string>()
{
{ "HOSTNAME", requestUrl.Host },

View File

@@ -11,7 +11,7 @@ namespace GitHub.Runner.Listener
{
public sealed class CommandSettings
{
private readonly Dictionary<string, string> _envArgs = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, string> _envArgs = new(StringComparer.OrdinalIgnoreCase);
private readonly CommandLineParser _parser;
private readonly IPromptManager _promptManager;
private readonly Tracing _trace;
@@ -26,7 +26,7 @@ namespace GitHub.Runner.Listener
};
// Valid flags and args for specific command - key: command, value: array of valid flags and args
private readonly Dictionary<string, string[]> validOptions = new Dictionary<string, string[]>
private readonly Dictionary<string, string[]> validOptions = new()
{
// Valid configure flags and args
[Constants.Runner.CommandLine.Commands.Configure] =
@@ -137,7 +137,7 @@ namespace GitHub.Runner.Listener
// Validate commandline parser result
public List<string> Validate()
{
List<string> unknowns = new List<string>();
List<string> unknowns = new();
// detect unknown commands
unknowns.AddRange(_parser.Commands.Where(x => !validOptions.Keys.Contains(x, StringComparer.OrdinalIgnoreCase)));

View File

@@ -86,7 +86,7 @@ namespace GitHub.Runner.Listener.Configuration
throw new InvalidOperationException("Cannot configure the runner because it is already configured. To reconfigure the runner, run 'config.cmd remove' or './config.sh remove' first.");
}
RunnerSettings runnerSettings = new RunnerSettings();
RunnerSettings runnerSettings = new();
// Loop getting url and creds until you can connect
ICredentialProvider credProvider = null;
@@ -521,7 +521,7 @@ namespace GitHub.Runner.Listener.Configuration
private TaskAgent CreateNewAgent(string agentName, RSAParameters publicKey, ISet<string> userLabels, bool ephemeral, bool disableUpdate)
{
TaskAgent agent = new TaskAgent(agentName)
TaskAgent agent = new(agentName)
{
Authorization = new TaskAgentAuthorization
{

View File

@@ -18,7 +18,7 @@ namespace GitHub.Runner.Listener.Configuration
public class CredentialManager : RunnerService, ICredentialManager
{
public static readonly Dictionary<string, Type> CredentialTypes = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase)
public static readonly Dictionary<string, Type> CredentialTypes = new(StringComparer.OrdinalIgnoreCase)
{
{ Constants.Configuration.OAuth, typeof(OAuthCredential)},
{ Constants.Configuration.OAuthAccessToken, typeof(OAuthAccessTokenCredential)},

View File

@@ -48,7 +48,7 @@ namespace GitHub.Runner.Listener.Configuration
ArgUtil.NotNullOrEmpty(token, nameof(token));
trace.Info("token retrieved: {0} chars", token.Length);
VssCredentials creds = new VssCredentials(new VssOAuthAccessTokenCredential(token), CredentialPromptType.DoNotPrompt);
VssCredentials creds = new(new VssOAuthAccessTokenCredential(token), CredentialPromptType.DoNotPrompt);
trace.Info("cred created");
return creds;

View File

@@ -44,7 +44,7 @@ namespace GitHub.Runner.Listener.Configuration
}
// For the service name, replace any characters outside of the alpha-numeric set and ".", "_", "-" with "-"
Regex regex = new Regex(@"[^0-9a-zA-Z._\-]");
Regex regex = new(@"[^0-9a-zA-Z._\-]");
string repoOrOrgName = regex.Replace(settings.RepoOrOrgName, "-");
serviceName = StringUtil.Format(serviceNamePattern, repoOrOrgName, settings.AgentName);

View File

@@ -37,8 +37,8 @@ namespace GitHub.Runner.Listener
// and the server will not send another job while this one is still running.
public sealed class JobDispatcher : RunnerService, IJobDispatcher
{
private static Regex _invalidJsonRegex = new Regex(@"invalid\ Json\ at\ position\ '(\d+)':", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private readonly Lazy<Dictionary<long, TaskResult>> _localRunJobResult = new Lazy<Dictionary<long, TaskResult>>();
private static Regex _invalidJsonRegex = new(@"invalid\ Json\ at\ position\ '(\d+)':", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private readonly Lazy<Dictionary<long, TaskResult>> _localRunJobResult = new();
private int _poolId;
IConfigurationStore _configurationStore;
@@ -47,14 +47,14 @@ namespace GitHub.Runner.Listener
private static readonly string _workerProcessName = $"Runner.Worker{IOUtil.ExeExtension}";
// this is not thread-safe
private readonly Queue<Guid> _jobDispatchedQueue = new Queue<Guid>();
private readonly ConcurrentDictionary<Guid, WorkerDispatcher> _jobInfos = new ConcurrentDictionary<Guid, WorkerDispatcher>();
private readonly Queue<Guid> _jobDispatchedQueue = new();
private readonly ConcurrentDictionary<Guid, WorkerDispatcher> _jobInfos = new();
// allow up to 30sec for any data to be transmitted over the process channel
// timeout limit can be overwritten by environment GITHUB_ACTIONS_RUNNER_CHANNEL_TIMEOUT
private TimeSpan _channelTimeout;
private TaskCompletionSource<bool> _runOnceJobCompleted = new TaskCompletionSource<bool>();
private TaskCompletionSource<bool> _runOnceJobCompleted = new();
public event EventHandler<JobStatusEventArgs> JobStatus;
@@ -111,7 +111,7 @@ namespace GitHub.Runner.Listener
}
}
WorkerDispatcher newDispatch = new WorkerDispatcher(jobRequestMessage.JobId, jobRequestMessage.RequestId);
WorkerDispatcher newDispatch = new(jobRequestMessage.JobId, jobRequestMessage.RequestId);
if (runOnce)
{
Trace.Info("Start dispatcher for one time used runner.");
@@ -357,7 +357,7 @@ namespace GitHub.Runner.Listener
term.WriteLine($"{DateTime.UtcNow:u}: Running job: {message.JobDisplayName}");
// first job request renew succeed.
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
TaskCompletionSource<int> firstJobRequestRenewed = new();
var notification = HostContext.GetService<IJobNotification>();
// lock renew cancellation token.
@@ -398,8 +398,8 @@ namespace GitHub.Runner.Listener
HostContext.WritePerfCounter($"JobRequestRenewed_{requestId.ToString()}");
Task<int> workerProcessTask = null;
object _outputLock = new object();
List<string> workerOutput = new List<string>();
object _outputLock = new();
List<string> workerOutput = new();
using (var processChannel = HostContext.CreateService<IProcessChannel>())
using (var processInvoker = HostContext.CreateService<IProcessInvoker>())
{
@@ -936,7 +936,7 @@ namespace GitHub.Runner.Listener
var runnerServer = HostContext.GetService<IRunnerServer>();
int completeJobRequestRetryLimit = 5;
List<Exception> exceptions = new List<Exception>();
List<Exception> exceptions = new();
while (completeJobRequestRetryLimit-- > 0)
{
try
@@ -1039,7 +1039,7 @@ namespace GitHub.Runner.Listener
public Task WorkerDispatch { get; set; }
public CancellationTokenSource WorkerCancellationTokenSource { get; private set; }
public CancellationTokenSource WorkerCancelTimeoutKillTokenSource { get; private set; }
private readonly object _lock = new object();
private readonly object _lock = new();
public WorkerDispatcher(Guid jobId, long requestId)
{

View File

@@ -38,7 +38,7 @@ namespace GitHub.Runner.Listener
private readonly TimeSpan _sessionCreationRetryInterval = TimeSpan.FromSeconds(30);
private readonly TimeSpan _sessionConflictRetryLimit = TimeSpan.FromMinutes(4);
private readonly TimeSpan _clockSkewRetryLimit = TimeSpan.FromMinutes(30);
private readonly Dictionary<string, int> _sessionCreationExceptionTracker = new Dictionary<string, int>();
private readonly Dictionary<string, int> _sessionCreationExceptionTracker = new();
private TaskAgentStatus runnerStatus = TaskAgentStatus.Online;
private CancellationTokenSource _getMessagesTokenSource;
@@ -198,7 +198,7 @@ namespace GitHub.Runner.Listener
bool encounteringError = false;
int continuousError = 0;
string errorMessage = string.Empty;
Stopwatch heartbeat = new Stopwatch();
Stopwatch heartbeat = new();
heartbeat.Restart();
while (true)
{

View File

@@ -16,7 +16,7 @@ namespace GitHub.Runner.Listener
// Add environment variables from .env file
LoadAndSetEnv();
using (HostContext context = new HostContext("Runner"))
using (HostContext context = new("Runner"))
{
return MainAsync(context, args).GetAwaiter().GetResult();
}

View File

@@ -28,7 +28,7 @@ namespace GitHub.Runner.Listener
private IMessageListener _listener;
private ITerminal _term;
private bool _inConfigStage;
private ManualResetEvent _completedCommand = new ManualResetEvent(false);
private ManualResetEvent _completedCommand = new(false);
public override void Initialize(IHostContext hostContext)
{

View File

@@ -32,14 +32,14 @@ namespace GitHub.Runner.Listener
private static string _platform = BuildConstants.RunnerPackage.PackageName;
private static string _dotnetRuntime = "dotnetRuntime";
private static string _externals = "externals";
private readonly Dictionary<string, string> _contentHashes = new Dictionary<string, string>();
private readonly Dictionary<string, string> _contentHashes = new();
private PackageMetadata _targetPackage;
private ITerminal _terminal;
private IRunnerServer _runnerServer;
private int _poolId;
private int _agentId;
private readonly ConcurrentQueue<string> _updateTrace = new ConcurrentQueue<string>();
private readonly ConcurrentQueue<string> _updateTrace = new();
private Task _cloneAndCalculateContentHashTask;
private string _dotnetRuntimeCloneDirectory;
private string _externalsCloneDirectory;
@@ -134,7 +134,7 @@ namespace GitHub.Runner.Listener
string flagFile = "update.finished";
IOUtil.DeleteFile(flagFile);
// kick off update script
Process invokeScript = new Process();
Process invokeScript = new();
#if OS_WINDOWS
invokeScript.StartInfo.FileName = WhichUtil.Which("cmd.exe", trace: Trace);
invokeScript.StartInfo.Arguments = $"/c \"{updateScript}\"";
@@ -191,9 +191,9 @@ namespace GitHub.Runner.Listener
}
Trace.Info($"Version '{_targetPackage.Version}' of '{_targetPackage.Type}' package available in server.");
PackageVersion serverVersion = new PackageVersion(_targetPackage.Version);
PackageVersion serverVersion = new(_targetPackage.Version);
Trace.Info($"Current running runner version is {BuildConstants.RunnerPackage.Version}");
PackageVersion runnerVersion = new PackageVersion(BuildConstants.RunnerPackage.Version);
PackageVersion runnerVersion = new(BuildConstants.RunnerPackage.Version);
return serverVersion.CompareTo(runnerVersion) > 0;
}
@@ -476,7 +476,7 @@ namespace GitHub.Runner.Listener
long downloadSize = 0;
//open zip stream in async mode
using (HttpClient httpClient = new HttpClient(HostContext.CreateHttpClientHandler()))
using (HttpClient httpClient = new(HostContext.CreateHttpClientHandler()))
{
if (!string.IsNullOrEmpty(_targetPackage.Token))
{
@@ -486,7 +486,7 @@ namespace GitHub.Runner.Listener
Trace.Info($"Downloading {packageDownloadUrl}");
using (FileStream fs = new FileStream(archiveFile, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
using (FileStream fs = new(archiveFile, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
using (Stream result = await httpClient.GetStreamAsync(packageDownloadUrl))
{
//81920 is the default used by System.IO.Stream.CopyTo and is under the large object heap threshold (85k).

View File

@@ -12,7 +12,7 @@ namespace GitHub.Runner.PluginHost
{
public static class Program
{
private static CancellationTokenSource tokenSource = new CancellationTokenSource();
private static CancellationTokenSource tokenSource = new();
private static string executingAssemblyLocation = string.Empty;
public static int Main(string[] args)

View File

@@ -63,7 +63,7 @@ namespace GitHub.Runner.Plugins.Artifact
string containerPath = actionsStorageArtifact.Name; // In actions storage artifacts, name equals the path
long containerId = actionsStorageArtifact.ContainerId;
FileContainerServer fileContainerServer = new FileContainerServer(context.VssConnection, projectId: new Guid(), containerId, containerPath);
FileContainerServer fileContainerServer = new(context.VssConnection, projectId: new Guid(), containerId, containerPath);
await fileContainerServer.DownloadFromContainerAsync(context, targetPath, token);
context.Output("Artifact download finished.");

View File

@@ -23,10 +23,10 @@ namespace GitHub.Runner.Plugins.Artifact
//81920 is the default used by System.IO.Stream.CopyTo and is under the large object heap threshold (85k).
private const int _defaultCopyBufferSize = 81920;
private readonly ConcurrentQueue<string> _fileUploadQueue = new ConcurrentQueue<string>();
private readonly ConcurrentQueue<DownloadInfo> _fileDownloadQueue = new ConcurrentQueue<DownloadInfo>();
private readonly ConcurrentDictionary<string, ConcurrentQueue<string>> _fileUploadTraceLog = new ConcurrentDictionary<string, ConcurrentQueue<string>>();
private readonly ConcurrentDictionary<string, ConcurrentQueue<string>> _fileUploadProgressLog = new ConcurrentDictionary<string, ConcurrentQueue<string>>();
private readonly ConcurrentQueue<string> _fileUploadQueue = new();
private readonly ConcurrentQueue<DownloadInfo> _fileDownloadQueue = new();
private readonly ConcurrentDictionary<string, ConcurrentQueue<string>> _fileUploadTraceLog = new();
private readonly ConcurrentDictionary<string, ConcurrentQueue<string>> _fileUploadProgressLog = new();
private readonly FileContainerHttpClient _fileContainerHttpClient;
private CancellationTokenSource _uploadCancellationTokenSource;
@@ -67,7 +67,7 @@ namespace GitHub.Runner.Plugins.Artifact
CancellationToken cancellationToken)
{
// Find out all container items need to be processed
List<FileContainerItem> containerItems = new List<FileContainerItem>();
List<FileContainerItem> containerItems = new();
int retryCount = 0;
while (retryCount < 3)
{
@@ -106,7 +106,7 @@ namespace GitHub.Runner.Plugins.Artifact
// Create all required empty folders and emptry files, gather a list of files that we need to download from server.
int foldersCreated = 0;
int emptryFilesCreated = 0;
List<DownloadInfo> downloadFiles = new List<DownloadInfo>();
List<DownloadInfo> downloadFiles = new();
foreach (var item in containerItems.OrderBy(x => x.Path))
{
if (!item.Path.StartsWith(_containerPath, StringComparison.OrdinalIgnoreCase))
@@ -306,7 +306,7 @@ namespace GitHub.Runner.Plugins.Artifact
Task downloadMonitor = DownloadReportingAsync(context, files.Count(), token);
// Start parallel download tasks.
List<Task<DownloadResult>> parallelDownloadingTasks = new List<Task<DownloadResult>>();
List<Task<DownloadResult>> parallelDownloadingTasks = new();
for (int downloader = 0; downloader < concurrentDownloads; downloader++)
{
parallelDownloadingTasks.Add(DownloadAsync(context, downloader, token));
@@ -358,7 +358,7 @@ namespace GitHub.Runner.Plugins.Artifact
Task uploadMonitor = UploadReportingAsync(context, files.Count(), _uploadCancellationTokenSource.Token);
// Start parallel upload tasks.
List<Task<UploadResult>> parallelUploadingTasks = new List<Task<UploadResult>>();
List<Task<UploadResult>> parallelUploadingTasks = new();
for (int uploader = 0; uploader < concurrentUploads; uploader++)
{
parallelUploadingTasks.Add(UploadAsync(context, uploader, _uploadCancellationTokenSource.Token));
@@ -381,8 +381,8 @@ namespace GitHub.Runner.Plugins.Artifact
private async Task<DownloadResult> DownloadAsync(RunnerActionPluginExecutionContext context, int downloaderId, CancellationToken token)
{
List<DownloadInfo> failedFiles = new List<DownloadInfo>();
Stopwatch downloadTimer = new Stopwatch();
List<DownloadInfo> failedFiles = new();
Stopwatch downloadTimer = new();
while (_fileDownloadQueue.TryDequeue(out DownloadInfo fileToDownload))
{
token.ThrowIfCancellationRequested();
@@ -396,7 +396,7 @@ namespace GitHub.Runner.Plugins.Artifact
{
context.Debug($"Start downloading file: '{fileToDownload.ItemPath}' (Downloader {downloaderId})");
downloadTimer.Restart();
using (FileStream fs = new FileStream(fileToDownload.LocalPath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: _defaultFileStreamBufferSize, useAsync: true))
using (FileStream fs = new(fileToDownload.LocalPath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: _defaultFileStreamBufferSize, useAsync: true))
using (var downloadStream = await _fileContainerHttpClient.DownloadFileAsync(_containerId, fileToDownload.ItemPath, token, _projectId))
{
await downloadStream.CopyToAsync(fs, _defaultCopyBufferSize, token);
@@ -453,10 +453,10 @@ namespace GitHub.Runner.Plugins.Artifact
private async Task<UploadResult> UploadAsync(RunnerActionPluginExecutionContext context, int uploaderId, CancellationToken token)
{
List<string> failedFiles = new List<string>();
List<string> failedFiles = new();
long uploadedSize = 0;
string fileToUpload;
Stopwatch uploadTimer = new Stopwatch();
Stopwatch uploadTimer = new();
while (_fileUploadQueue.TryDequeue(out fileToUpload))
{
token.ThrowIfCancellationRequested();

View File

@@ -68,7 +68,7 @@ namespace GitHub.Runner.Plugins.Artifact
context.Output($"Uploading artifact '{artifactName}' from '{fullPath}' for run #{buildId}");
FileContainerServer fileContainerHelper = new FileContainerServer(context.VssConnection, projectId: Guid.Empty, containerId, artifactName);
FileContainerServer fileContainerHelper = new(context.VssConnection, projectId: Guid.Empty, containerId, artifactName);
var propertiesDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
long size = 0;
@@ -87,7 +87,7 @@ namespace GitHub.Runner.Plugins.Artifact
// Definition ID is a dummy value only used by HTTP client routing purposes
int definitionId = 1;
PipelinesServer pipelinesHelper = new PipelinesServer(context.VssConnection);
PipelinesServer pipelinesHelper = new(context.VssConnection);
var artifact = await pipelinesHelper.AssociateActionsStorageArtifactAsync(
definitionId,

View File

@@ -18,7 +18,7 @@ namespace GitHub.Runner.Plugins.Repository
#else
private static readonly Encoding s_encoding = null;
#endif
private readonly Dictionary<string, string> gitEnv = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
private readonly Dictionary<string, string> gitEnv = new(StringComparer.OrdinalIgnoreCase)
{
{ "GIT_TERMINAL_PROMPT", "0" },
};
@@ -92,11 +92,11 @@ namespace GitHub.Runner.Plugins.Repository
}
// required 2.0, all git operation commandline args need min git version 2.0
Version minRequiredGitVersion = new Version(2, 0);
Version minRequiredGitVersion = new(2, 0);
EnsureGitVersion(minRequiredGitVersion, throwOnNotMatch: true);
// suggest user upgrade to 2.9 for better git experience
Version recommendGitVersion = new Version(2, 9);
Version recommendGitVersion = new(2, 9);
if (!EnsureGitVersion(recommendGitVersion, throwOnNotMatch: false))
{
context.Output($"To get a better Git experience, upgrade your Git to at least version '{recommendGitVersion}'. Your current Git version is '{gitVersion}'.");
@@ -430,7 +430,7 @@ namespace GitHub.Runner.Plugins.Repository
context.Debug($"Inspect remote.origin.url for repository under {repositoryPath}");
Uri fetchUrl = null;
List<string> outputStrings = new List<string>();
List<string> outputStrings = new();
int exitCode = await ExecuteGitCommandAsync(context, repositoryPath, "config", "--get remote.origin.url", outputStrings);
if (exitCode != 0)
@@ -477,7 +477,7 @@ namespace GitHub.Runner.Plugins.Repository
context.Debug($"Checking git config {configKey} exist or not");
// ignore any outputs by redirect them into a string list, since the output might contains secrets.
List<string> outputStrings = new List<string>();
List<string> outputStrings = new();
int exitcode = await ExecuteGitCommandAsync(context, repositoryPath, "config", StringUtil.Format($"--get-all {configKey}"), outputStrings);
return exitcode == 0;
@@ -539,7 +539,7 @@ namespace GitHub.Runner.Plugins.Repository
string runnerWorkspace = context.GetRunnerContext("workspace");
ArgUtil.Directory(runnerWorkspace, "runnerWorkspace");
Version version = null;
List<string> outputStrings = new List<string>();
List<string> outputStrings = new();
int exitCode = await ExecuteGitCommandAsync(context, runnerWorkspace, "version", null, outputStrings);
context.Output($"{string.Join(Environment.NewLine, outputStrings)}");
if (exitCode == 0)
@@ -550,7 +550,7 @@ namespace GitHub.Runner.Plugins.Repository
{
string verString = outputStrings.First();
// we interested about major.minor.patch version
Regex verRegex = new Regex("\\d+\\.\\d+(\\.\\d+)?", RegexOptions.IgnoreCase);
Regex verRegex = new("\\d+\\.\\d+(\\.\\d+)?", RegexOptions.IgnoreCase);
var matchResult = verRegex.Match(verString);
if (matchResult.Success && !string.IsNullOrEmpty(matchResult.Value))
{
@@ -572,7 +572,7 @@ namespace GitHub.Runner.Plugins.Repository
string runnerWorkspace = context.GetRunnerContext("workspace");
ArgUtil.Directory(runnerWorkspace, "runnerWorkspace");
Version version = null;
List<string> outputStrings = new List<string>();
List<string> outputStrings = new();
int exitCode = await ExecuteGitCommandAsync(context, runnerWorkspace, "lfs version", null, outputStrings);
context.Output($"{string.Join(Environment.NewLine, outputStrings)}");
if (exitCode == 0)
@@ -583,7 +583,7 @@ namespace GitHub.Runner.Plugins.Repository
{
string verString = outputStrings.First();
// we interested about major.minor.patch version
Regex verRegex = new Regex("\\d+\\.\\d+(\\.\\d+)?", RegexOptions.IgnoreCase);
Regex verRegex = new("\\d+\\.\\d+(\\.\\d+)?", RegexOptions.IgnoreCase);
var matchResult = verRegex.Match(verString);
if (matchResult.Success && !string.IsNullOrEmpty(matchResult.Value))
{

View File

@@ -21,7 +21,7 @@ namespace GitHub.Runner.Plugins.Repository.v1_0
private const string _remotePullRefsPrefix = "refs/remotes/pull/";
// min git version that support add extra auth header.
private Version _minGitVersionSupportAuthHeader = new Version(2, 9);
private Version _minGitVersionSupportAuthHeader = new(2, 9);
#if OS_WINDOWS
// min git version that support override sslBackend setting.
@@ -29,7 +29,7 @@ namespace GitHub.Runner.Plugins.Repository.v1_0
#endif
// min git-lfs version that support add extra auth header.
private Version _minGitLfsVersionSupportAuthHeader = new Version(2, 1);
private Version _minGitLfsVersionSupportAuthHeader = new(2, 1);
private void RequirementCheck(RunnerActionPluginExecutionContext executionContext, GitCliManager gitCommandManager, bool checkGitLfs)
{
@@ -83,7 +83,7 @@ namespace GitHub.Runner.Plugins.Repository.v1_0
var githubUrl = executionContext.GetGitHubContext("server_url");
var githubUri = new Uri(!string.IsNullOrEmpty(githubUrl) ? githubUrl : "https://github.com");
var portInfo = githubUri.IsDefaultPort ? string.Empty : $":{githubUri.Port}";
Uri repositoryUrl = new Uri($"{githubUri.Scheme}://{githubUri.Host}{portInfo}/{repoFullName}");
Uri repositoryUrl = new($"{githubUri.Scheme}://{githubUri.Host}{portInfo}/{repoFullName}");
if (!repositoryUrl.IsAbsoluteUri)
{
throw new InvalidOperationException("Repository url need to be an absolute uri.");
@@ -121,7 +121,7 @@ namespace GitHub.Runner.Plugins.Repository.v1_0
executionContext.Debug($"gitLfsSupport={gitLfsSupport}");
// Initialize git command manager with additional environment variables.
Dictionary<string, string> gitEnv = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, string> gitEnv = new(StringComparer.OrdinalIgnoreCase);
// Disable prompting for git credential manager
gitEnv["GCM_INTERACTIVE"] = "Never";
@@ -141,7 +141,7 @@ namespace GitHub.Runner.Plugins.Repository.v1_0
gitEnv[formattedKey] = variable.Value?.Value ?? string.Empty;
}
GitCliManager gitCommandManager = new GitCliManager(gitEnv);
GitCliManager gitCommandManager = new(gitEnv);
await gitCommandManager.LoadGitExecutionInfo(executionContext);
// Make sure the build machine met all requirements for the git repository
@@ -293,8 +293,8 @@ namespace GitHub.Runner.Plugins.Repository.v1_0
await RemoveGitConfig(executionContext, gitCommandManager, targetPath, $"http.{repositoryUrl.AbsoluteUri}.extraheader", string.Empty);
}
List<string> additionalFetchArgs = new List<string>();
List<string> additionalLfsFetchArgs = new List<string>();
List<string> additionalFetchArgs = new();
List<string> additionalLfsFetchArgs = new();
// add accessToken as basic auth header to handle auth challenge.
if (!string.IsNullOrEmpty(accessToken))
@@ -320,7 +320,7 @@ namespace GitHub.Runner.Plugins.Repository.v1_0
}
}
List<string> additionalFetchSpecs = new List<string>();
List<string> additionalFetchSpecs = new();
additionalFetchSpecs.Add("+refs/heads/*:refs/remotes/origin/*");
if (IsPullRequest(sourceBranch))
@@ -395,7 +395,7 @@ namespace GitHub.Runner.Plugins.Repository.v1_0
throw new InvalidOperationException($"Git submodule sync failed with exit code: {exitCode_submoduleSync}");
}
List<string> additionalSubmoduleUpdateArgs = new List<string>();
List<string> additionalSubmoduleUpdateArgs = new();
if (!string.IsNullOrEmpty(accessToken))
{

View File

@@ -12,7 +12,7 @@ namespace GitHub.Runner.Plugins.Repository.v1_0
{
public class CheckoutTask : IRunnerActionPlugin
{
private readonly Regex _validSha1 = new Regex(@"\b[0-9a-f]{40}\b", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled, TimeSpan.FromSeconds(2));
private readonly Regex _validSha1 = new(@"\b[0-9a-f]{40}\b", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled, TimeSpan.FromSeconds(2));
public async Task RunAsync(RunnerActionPluginExecutionContext executionContext, CancellationToken token)
{

View File

@@ -22,7 +22,7 @@ namespace GitHub.Runner.Plugins.Repository.v1_1
private const string _tagRefsPrefix = "refs/tags/";
// min git version that support add extra auth header.
private Version _minGitVersionSupportAuthHeader = new Version(2, 9);
private Version _minGitVersionSupportAuthHeader = new(2, 9);
#if OS_WINDOWS
// min git version that support override sslBackend setting.
@@ -30,7 +30,7 @@ namespace GitHub.Runner.Plugins.Repository.v1_1
#endif
// min git-lfs version that support add extra auth header.
private Version _minGitLfsVersionSupportAuthHeader = new Version(2, 1);
private Version _minGitLfsVersionSupportAuthHeader = new(2, 1);
public static string ProblemMatcher => @"
{
@@ -62,9 +62,9 @@ namespace GitHub.Runner.Plugins.Repository.v1_1
{
// Validate args.
ArgUtil.NotNull(executionContext, nameof(executionContext));
Dictionary<string, string> configModifications = new Dictionary<string, string>();
Dictionary<string, string> configModifications = new();
executionContext.Output($"Syncing repository: {repoFullName}");
Uri repositoryUrl = new Uri($"https://github.com/{repoFullName}");
Uri repositoryUrl = new($"https://github.com/{repoFullName}");
if (!repositoryUrl.IsAbsoluteUri)
{
throw new InvalidOperationException("Repository url need to be an absolute uri.");
@@ -102,7 +102,7 @@ namespace GitHub.Runner.Plugins.Repository.v1_1
executionContext.Debug($"gitLfsSupport={gitLfsSupport}");
// Initialize git command manager with additional environment variables.
Dictionary<string, string> gitEnv = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, string> gitEnv = new(StringComparer.OrdinalIgnoreCase);
// Disable git prompt
gitEnv["GIT_TERMINAL_PROMPT"] = "0";
@@ -125,7 +125,7 @@ namespace GitHub.Runner.Plugins.Repository.v1_1
gitEnv[formattedKey] = variable.Value?.Value ?? string.Empty;
}
GitCliManager gitCommandManager = new GitCliManager(gitEnv);
GitCliManager gitCommandManager = new(gitEnv);
await gitCommandManager.LoadGitExecutionInfo(executionContext);
// Make sure the build machine met all requirements for the git repository
@@ -277,8 +277,8 @@ namespace GitHub.Runner.Plugins.Repository.v1_1
await RemoveGitConfig(executionContext, gitCommandManager, targetPath, $"http.{repositoryUrl.AbsoluteUri}.extraheader", string.Empty);
}
List<string> additionalFetchArgs = new List<string>();
List<string> additionalLfsFetchArgs = new List<string>();
List<string> additionalFetchArgs = new();
List<string> additionalLfsFetchArgs = new();
// Add http.https://github.com.extraheader=... to gitconfig
// accessToken as basic auth header to handle any auth challenge from github.com
@@ -303,7 +303,7 @@ namespace GitHub.Runner.Plugins.Repository.v1_1
}
}
List<string> additionalFetchSpecs = new List<string>();
List<string> additionalFetchSpecs = new();
additionalFetchSpecs.Add("+refs/heads/*:refs/remotes/origin/*");
if (IsPullRequest(sourceBranch))
@@ -378,7 +378,7 @@ namespace GitHub.Runner.Plugins.Repository.v1_1
throw new InvalidOperationException($"Git submodule sync failed with exit code: {exitCode_submoduleSync}");
}
List<string> additionalSubmoduleUpdateArgs = new List<string>();
List<string> additionalSubmoduleUpdateArgs = new();
int exitCode_submoduleUpdate = await gitCommandManager.GitSubmoduleUpdate(executionContext, targetPath, fetchDepth, string.Join(" ", additionalSubmoduleUpdateArgs), checkoutNestedSubmodules, cancellationToken);
if (exitCode_submoduleUpdate != 0)
@@ -404,7 +404,7 @@ namespace GitHub.Runner.Plugins.Repository.v1_1
executionContext.Output($"Cleanup cached git credential from {repositoryPath}.");
// Initialize git command manager
GitCliManager gitCommandManager = new GitCliManager();
GitCliManager gitCommandManager = new();
await gitCommandManager.LoadGitExecutionInfo(executionContext);
executionContext.Debug("Remove any extraheader setting from git config.");
@@ -499,7 +499,7 @@ namespace GitHub.Runner.Plugins.Repository.v1_1
string gitConfig = Path.Combine(targetPath, ".git/config");
if (File.Exists(gitConfig))
{
List<string> safeGitConfig = new List<string>();
List<string> safeGitConfig = new();
var gitConfigContents = File.ReadAllLines(gitConfig);
foreach (var line in gitConfigContents)
{

View File

@@ -23,7 +23,7 @@ namespace GitHub.Runner.Sdk
private readonly string DebugEnvironmentalVariable = "ACTIONS_STEP_DEBUG";
private VssConnection _connection;
private RunnerWebProxy _webProxy;
private readonly object _stdoutLock = new object();
private readonly object _stdoutLock = new();
private readonly ITraceWriter _trace; // for unit tests
public RunnerActionPluginExecutionContext()
@@ -220,7 +220,7 @@ namespace GitHub.Runner.Sdk
return input;
}
private Dictionary<string, string> _commandEscapeMappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
private Dictionary<string, string> _commandEscapeMappings = new(StringComparer.OrdinalIgnoreCase)
{
{
";", "%3B"

View File

@@ -24,18 +24,18 @@ namespace GitHub.Runner.Sdk
private Stopwatch _stopWatch;
private int _asyncStreamReaderCount = 0;
private bool _waitingOnStreams = false;
private readonly AsyncManualResetEvent _outputProcessEvent = new AsyncManualResetEvent();
private readonly TaskCompletionSource<bool> _processExitedCompletionSource = new TaskCompletionSource<bool>();
private readonly CancellationTokenSource _processStandardInWriteCancellationTokenSource = new CancellationTokenSource();
private readonly ConcurrentQueue<string> _errorData = new ConcurrentQueue<string>();
private readonly ConcurrentQueue<string> _outputData = new ConcurrentQueue<string>();
private readonly AsyncManualResetEvent _outputProcessEvent = new();
private readonly TaskCompletionSource<bool> _processExitedCompletionSource = new();
private readonly CancellationTokenSource _processStandardInWriteCancellationTokenSource = new();
private readonly ConcurrentQueue<string> _errorData = new();
private readonly ConcurrentQueue<string> _outputData = new();
private readonly TimeSpan _sigintTimeout = TimeSpan.FromMilliseconds(7500);
private readonly TimeSpan _sigtermTimeout = TimeSpan.FromMilliseconds(2500);
private ITraceWriter Trace { get; set; }
private class AsyncManualResetEvent
{
private volatile TaskCompletionSource<bool> m_tcs = new TaskCompletionSource<bool>();
private volatile TaskCompletionSource<bool> m_tcs = new();
public Task WaitAsync() { return m_tcs.Task; }
@@ -387,8 +387,8 @@ namespace GitHub.Runner.Sdk
private void ProcessOutput()
{
List<string> errorData = new List<string>();
List<string> outputData = new List<string>();
List<string> errorData = new();
List<string> outputData = new();
string errorLine;
while (_errorData.TryDequeue(out errorLine))

View File

@@ -23,9 +23,9 @@ namespace GitHub.Runner.Sdk
private string _httpsProxyPassword;
private string _noProxyString;
private readonly List<ByPassInfo> _noProxyList = new List<ByPassInfo>();
private readonly HashSet<string> _noProxyUnique = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private readonly Regex _validIpRegex = new Regex("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", RegexOptions.Compiled);
private readonly List<ByPassInfo> _noProxyList = new();
private readonly HashSet<string> _noProxyUnique = new(StringComparer.OrdinalIgnoreCase);
private readonly Regex _validIpRegex = new("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", RegexOptions.Compiled);
public string HttpProxyAddress => _httpProxyAddress;
public string HttpProxyUsername => _httpProxyUsername;

View File

@@ -52,7 +52,7 @@ namespace GitHub.Runner.Sdk
using (SHA256 sha256hash = SHA256.Create())
{
byte[] data = sha256hash.ComputeHash(Encoding.UTF8.GetBytes(hashString));
StringBuilder sBuilder = new StringBuilder();
StringBuilder sBuilder = new();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
@@ -77,7 +77,7 @@ namespace GitHub.Runner.Sdk
public static void DeleteDirectory(string path, bool contentsOnly, bool continueOnContentDeleteError, CancellationToken cancellationToken)
{
ArgUtil.NotNullOrEmpty(path, nameof(path));
DirectoryInfo directory = new DirectoryInfo(path);
DirectoryInfo directory = new(path);
if (!directory.Exists)
{
return;
@@ -363,12 +363,12 @@ namespace GitHub.Runner.Sdk
Directory.CreateDirectory(target);
// Get the file contents of the directory to copy.
DirectoryInfo sourceDir = new DirectoryInfo(source);
DirectoryInfo sourceDir = new(source);
foreach (FileInfo sourceFile in sourceDir.GetFiles() ?? new FileInfo[0])
{
// Check if the file already exists.
cancellationToken.ThrowIfCancellationRequested();
FileInfo targetFile = new FileInfo(Path.Combine(target, sourceFile.Name));
FileInfo targetFile = new(Path.Combine(target, sourceFile.Name));
if (!targetFile.Exists ||
sourceFile.Length != targetFile.Length ||
sourceFile.LastWriteTime != targetFile.LastWriteTime)

View File

@@ -9,7 +9,7 @@ namespace GitHub.Runner.Sdk
public static class StringUtil
{
private static readonly object[] s_defaultFormatArgs = new object[] { null };
private static Lazy<JsonSerializerSettings> s_serializerSettings = new Lazy<JsonSerializerSettings>(() =>
private static Lazy<JsonSerializerSettings> s_serializerSettings = new(() =>
{
var settings = new VssJsonMediaTypeFormatter().SerializerSettings;
settings.DateParseHandling = DateParseHandling.None;

View File

@@ -21,7 +21,7 @@ namespace GitHub.Runner.Sdk
return baseUrl;
}
UriBuilder credUri = new UriBuilder(baseUrl);
UriBuilder credUri = new(baseUrl);
// ensure we have a username, uribuild will throw if username is empty but password is not.
if (string.IsNullOrEmpty(username))

View File

@@ -76,7 +76,7 @@ namespace GitHub.Runner.Sdk
// settings are applied to an HttpRequestMessage.
settings.AcceptLanguages.Remove(CultureInfo.InvariantCulture);
VssConnection connection = new VssConnection(serverUri, new VssHttpMessageHandler(credentials, settings), additionalDelegatingHandler);
VssConnection connection = new(serverUri, new VssHttpMessageHandler(credentials, settings), additionalDelegatingHandler);
return connection;
}
@@ -116,7 +116,7 @@ namespace GitHub.Runner.Sdk
// settings are applied to an HttpRequestMessage.
settings.AcceptLanguages.Remove(CultureInfo.InvariantCulture);
RawConnection connection = new RawConnection(serverUri, new RawHttpMessageHandler(credentials.ToOAuthCredentials(), settings), additionalDelegatingHandler);
RawConnection connection = new(serverUri, new RawHttpMessageHandler(credentials.ToOAuthCredentials(), settings), additionalDelegatingHandler);
return connection;
}

View File

@@ -21,9 +21,9 @@ namespace GitHub.Runner.Worker
public sealed class ActionCommandManager : RunnerService, IActionCommandManager
{
private const string _stopCommand = "stop-commands";
private readonly Dictionary<string, IActionCommandExtension> _commandExtensions = new Dictionary<string, IActionCommandExtension>(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<string> _registeredCommands = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private readonly object _commandSerializeLock = new object();
private readonly Dictionary<string, IActionCommandExtension> _commandExtensions = new(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<string> _registeredCommands = new(StringComparer.OrdinalIgnoreCase);
private readonly object _commandSerializeLock = new();
private bool _stopProcessCommand = false;
private string _stopToken = null;
@@ -618,7 +618,7 @@ namespace GitHub.Runner.Worker
context.Debug("Enhanced Annotations not enabled on the server. The 'title', 'end_line', and 'end_column' fields are unsupported.");
}
Issue issue = new Issue()
Issue issue = new()
{
Category = "General",
Type = this.Type,

View File

@@ -52,16 +52,16 @@ namespace GitHub.Runner.Worker
private const int _defaultCopyBufferSize = 81920;
private const string _dotcomApiUrl = "https://api.github.com";
private readonly Dictionary<Guid, ContainerInfo> _cachedActionContainers = new Dictionary<Guid, ContainerInfo>();
private readonly Dictionary<Guid, ContainerInfo> _cachedActionContainers = new();
public Dictionary<Guid, ContainerInfo> CachedActionContainers => _cachedActionContainers;
private readonly Dictionary<Guid, List<Pipelines.ActionStep>> _cachedEmbeddedPreSteps = new Dictionary<Guid, List<Pipelines.ActionStep>>();
private readonly Dictionary<Guid, List<Pipelines.ActionStep>> _cachedEmbeddedPreSteps = new();
public Dictionary<Guid, List<Pipelines.ActionStep>> CachedEmbeddedPreSteps => _cachedEmbeddedPreSteps;
private readonly Dictionary<Guid, List<Guid>> _cachedEmbeddedStepIds = new Dictionary<Guid, List<Guid>>();
private readonly Dictionary<Guid, List<Guid>> _cachedEmbeddedStepIds = new();
public Dictionary<Guid, List<Guid>> CachedEmbeddedStepIds => _cachedEmbeddedStepIds;
private readonly Dictionary<Guid, Stack<Pipelines.ActionStep>> _cachedEmbeddedPostSteps = new Dictionary<Guid, Stack<Pipelines.ActionStep>>();
private readonly Dictionary<Guid, Stack<Pipelines.ActionStep>> _cachedEmbeddedPostSteps = new();
public Dictionary<Guid, Stack<Pipelines.ActionStep>> CachedEmbeddedPostSteps => _cachedEmbeddedPostSteps;
public async Task<PrepareResult> PrepareActionsAsync(IExecutionContext executionContext, IEnumerable<Pipelines.JobStep> steps, Guid rootStepId = default(Guid))
@@ -791,7 +791,7 @@ namespace GitHub.Runner.Worker
try
{
//open zip stream in async mode
using (FileStream fs = new FileStream(archiveFile, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: _defaultFileStreamBufferSize, useAsync: true))
using (FileStream fs = new(archiveFile, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: _defaultFileStreamBufferSize, useAsync: true))
using (var httpClientHandler = HostContext.CreateHttpClientHandler())
using (var httpClient = new HttpClient(httpClientHandler))
{

View File

@@ -53,7 +53,7 @@ namespace GitHub.Runner.Worker
public ActionDefinitionData Load(IExecutionContext executionContext, string manifestFile)
{
var templateContext = CreateTemplateContext(executionContext);
ActionDefinitionData actionDefinition = new ActionDefinitionData();
ActionDefinitionData actionDefinition = new();
// Clean up file name real quick
// Instead of using Regex which can be computationally expensive,

View File

@@ -10,7 +10,7 @@ namespace GitHub.Runner.Worker
{
private readonly IExecutionContext _executionContext;
private readonly Tracing _trace;
private readonly StringBuilder _traceBuilder = new StringBuilder();
private readonly StringBuilder _traceBuilder = new();
public string Trace => _traceBuilder.ToString();

View File

@@ -15,7 +15,7 @@ namespace GitHub.Runner.Worker.Container
private IDictionary<string, string> _userPortMappings;
private List<PortMapping> _portMappings;
private IDictionary<string, string> _environmentVariables;
private List<PathMapping> _pathMappings = new List<PathMapping>();
private List<PathMapping> _pathMappings = new();
public ContainerInfo()
{

View File

@@ -60,7 +60,7 @@ namespace GitHub.Runner.Worker.Container
context.Output($"Docker client API version: {clientVersionStr}");
// we interested about major.minor.patch version
Regex verRegex = new Regex("\\d+\\.\\d+(\\.\\d+)?", RegexOptions.IgnoreCase);
Regex verRegex = new("\\d+\\.\\d+(\\.\\d+)?", RegexOptions.IgnoreCase);
Version serverVersion = null;
var serverVersionMatchResult = verRegex.Match(serverVersionStr);
@@ -309,7 +309,7 @@ namespace GitHub.Runner.Worker.Container
string arg = $"exec {options} {containerId} {command}".Trim();
context.Command($"{DockerPath} {arg}");
object outputLock = new object();
object outputLock = new();
var processInvoker = HostContext.CreateService<IProcessInvoker>();
processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
@@ -447,7 +447,7 @@ namespace GitHub.Runner.Worker.Container
string arg = $"{command} {options}".Trim();
context.Command($"{DockerPath} {arg}");
List<string> output = new List<string>();
List<string> output = new();
var processInvoker = HostContext.CreateService<IProcessInvoker>();
processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{

View File

@@ -6,8 +6,8 @@ namespace GitHub.Runner.Worker.Container
{
public class DockerUtil
{
private static readonly Regex QuoteEscape = new Regex(@"(\\*)" + "\"", RegexOptions.Compiled);
private static readonly Regex EndOfStringEscape = new Regex(@"(\\+)$", RegexOptions.Compiled);
private static readonly Regex QuoteEscape = new(@"(\\*)" + "\"", RegexOptions.Compiled);
private static readonly Regex EndOfStringEscape = new(@"(\\+)$", RegexOptions.Compiled);
public static List<PortMapping> ParseDockerPort(IList<string> portMappingLines)
{
@@ -19,7 +19,7 @@ namespace GitHub.Runner.Worker.Container
//"TARGET_PORT/PROTO -> HOST:HOST_PORT"
string pattern = $"^(?<{targetPort}>\\d+)/(?<{proto}>\\w+) -> (?<{host}>.+):(?<{hostPort}>\\d+)$";
List<PortMapping> portMappings = new List<PortMapping>();
List<PortMapping> portMappings = new();
foreach (var line in portMappingLines)
{
Match m = Regex.Match(line, pattern, RegexOptions.None, TimeSpan.FromSeconds(1));

View File

@@ -354,8 +354,8 @@ namespace GitHub.Runner.Worker
{
context.Command($"{command} {arg}");
List<string> outputs = new List<string>();
object outputLock = new object();
List<string> outputs = new();
object outputLock = new();
var processInvoker = HostContext.CreateService<IProcessInvoker>();
processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
@@ -562,7 +562,7 @@ namespace GitHub.Runner.Worker
#if OS_WINDOWS
Version requiredDockerEngineAPIVersion = new Version(1, 30); // Docker-EE version 17.6
#else
Version requiredDockerEngineAPIVersion = new Version(1, 35); // Docker-CE version 17.12
Version requiredDockerEngineAPIVersion = new(1, 35); // Docker-CE version 17.12
#endif
if (dockerVersion.ServerVersion < requiredDockerEngineAPIVersion)

View File

@@ -122,10 +122,10 @@ namespace GitHub.Runner.Worker
private const int _maxIssueCountInTelemetry = 3; // Only send the first 3 issues to telemetry
private const int _maxIssueMessageLengthInTelemetry = 256; // Only send the first 256 characters of issue message to telemetry
private readonly TimelineRecord _record = new TimelineRecord();
private readonly Dictionary<Guid, TimelineRecord> _detailRecords = new Dictionary<Guid, TimelineRecord>();
private readonly object _loggerLock = new object();
private readonly object _matchersLock = new object();
private readonly TimelineRecord _record = new();
private readonly Dictionary<Guid, TimelineRecord> _detailRecords = new();
private readonly object _loggerLock = new();
private readonly object _matchersLock = new();
private event OnMatcherChanged _onMatcherChanged;
@@ -140,7 +140,7 @@ namespace GitHub.Runner.Worker
private bool _expandedForPostJob = false;
private int _childTimelineRecordOrder = 0;
private CancellationTokenSource _cancellationTokenSource;
private TaskCompletionSource<int> _forceCompleted = new TaskCompletionSource<int>();
private TaskCompletionSource<int> _forceCompleted = new();
private bool _throttlingReported = false;
// only job level ExecutionContext will track throttling delay.

View File

@@ -32,7 +32,7 @@ namespace GitHub.Runner.Worker.Expressions
string githubWorkspace = workspaceData.Value;
bool followSymlink = false;
List<string> patterns = new List<string>();
List<string> patterns = new();
var firstParameter = true;
foreach (var parameter in Parameters)
{

View File

@@ -6,7 +6,7 @@ namespace GitHub.Runner.Worker
{
public sealed class GitHubContext : DictionaryContextData, IEnvironmentContextData
{
private readonly HashSet<string> _contextEnvAllowlist = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
private readonly HashSet<string> _contextEnvAllowlist = new(StringComparer.OrdinalIgnoreCase)
{
"action_path",
"action_ref",

View File

@@ -16,16 +16,16 @@ namespace GitHub.Runner.Worker.Handlers
private const string _colorCodePrefix = "\033[";
private const int _maxAttempts = 3;
private const string _timeoutKey = "GITHUB_ACTIONS_RUNNER_ISSUE_MATCHER_TIMEOUT";
private static readonly Regex _colorCodeRegex = new Regex(@"\x0033\[[0-9;]*m?", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly Regex _colorCodeRegex = new(@"\x0033\[[0-9;]*m?", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private readonly IActionCommandManager _commandManager;
private readonly ContainerInfo _container;
private readonly IExecutionContext _executionContext;
private readonly int _failsafe = 50;
private readonly object _matchersLock = new object();
private readonly object _matchersLock = new();
private readonly TimeSpan _timeout;
private IssueMatcher[] _matchers = Array.Empty<IssueMatcher>();
// Mapping that indicates whether a directory belongs to the workflow repository
private readonly Dictionary<string, string> _directoryMap = new Dictionary<string, string>();
private readonly Dictionary<string, string> _directoryMap = new();
public OutputManager(IExecutionContext executionContext, IActionCommandManager commandManager, ContainerInfo container = null)
{

View File

@@ -10,7 +10,7 @@ namespace GitHub.Runner.Worker.Handlers
{
internal static class ScriptHandlerHelpers
{
private static readonly Dictionary<string, string> _defaultArguments = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
private static readonly Dictionary<string, string> _defaultArguments = new(StringComparer.OrdinalIgnoreCase)
{
["cmd"] = "/D /E:ON /V:OFF /S /C \"CALL \"{0}\"\"",
["pwsh"] = "-command \". '{0}'\"",
@@ -20,7 +20,7 @@ namespace GitHub.Runner.Worker.Handlers
["python"] = "{0}"
};
private static readonly Dictionary<string, string> _extensions = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
private static readonly Dictionary<string, string> _extensions = new(StringComparer.OrdinalIgnoreCase)
{
["cmd"] = ".cmd",
["pwsh"] = ".ps1",

View File

@@ -39,10 +39,10 @@ namespace GitHub.Runner.Worker
public sealed class JobExtension : RunnerService, IJobExtension
{
private readonly HashSet<string> _existingProcesses = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<string> _existingProcesses = new(StringComparer.OrdinalIgnoreCase);
private bool _processCleanup;
private string _processLookupId = $"github_{Guid.NewGuid()}";
private CancellationTokenSource _diskSpaceCheckToken = new CancellationTokenSource();
private CancellationTokenSource _diskSpaceCheckToken = new();
private Task _diskSpaceCheckTask = null;
// Download all required actions.
@@ -59,8 +59,8 @@ namespace GitHub.Runner.Worker
context.StepTelemetry.Type = "runner";
context.StepTelemetry.Action = "setup_job";
List<IStep> preJobSteps = new List<IStep>();
List<IStep> jobSteps = new List<IStep>();
List<IStep> preJobSteps = new();
List<IStep> jobSteps = new();
using (var register = jobContext.CancellationToken.Register(() => { context.CancelToken(); }))
{
try
@@ -386,7 +386,7 @@ namespace GitHub.Runner.Worker
data: (object)jobHookData));
}
List<IStep> steps = new List<IStep>();
List<IStep> steps = new();
steps.AddRange(preJobSteps);
steps.AddRange(jobSteps);
@@ -674,7 +674,7 @@ namespace GitHub.Runner.Worker
private Dictionary<int, Process> SnapshotProcesses()
{
Dictionary<int, Process> snapshot = new Dictionary<int, Process>();
Dictionary<int, Process> snapshot = new();
foreach (var proc in Process.GetProcesses())
{
try

View File

@@ -11,7 +11,7 @@ namespace GitHub.Runner.Worker
{
public static int Main(string[] args)
{
using (HostContext context = new HostContext("Worker"))
using (HostContext context = new("Worker"))
{
return MainAsync(context, args).GetAwaiter().GetResult();
}

View File

@@ -26,7 +26,7 @@ namespace GitHub.Runner.Worker
public sealed class RunnerPluginManager : RunnerService, IRunnerPluginManager
{
private readonly Dictionary<string, RunnerPluginActionInfo> _actionPlugins = new Dictionary<string, RunnerPluginActionInfo>(StringComparer.OrdinalIgnoreCase)
private readonly Dictionary<string, RunnerPluginActionInfo> _actionPlugins = new(StringComparer.OrdinalIgnoreCase)
{
{
"checkout",
@@ -97,7 +97,7 @@ namespace GitHub.Runner.Worker
string arguments = $"action \"{plugin}\"";
// construct plugin context
RunnerActionPluginExecutionContext pluginContext = new RunnerActionPluginExecutionContext
RunnerActionPluginExecutionContext pluginContext = new()
{
Inputs = inputs,
Endpoints = context.Global.Endpoints,

View File

@@ -16,8 +16,8 @@ namespace GitHub.Runner.Worker
/// </summary>
public sealed class StepsContext
{
private static readonly Regex _propertyRegex = new Regex("^[a-zA-Z_][a-zA-Z0-9_]*$", RegexOptions.Compiled);
private readonly DictionaryContextData _contextData = new DictionaryContextData();
private static readonly Regex _propertyRegex = new("^[a-zA-Z_][a-zA-Z0-9_]*$", RegexOptions.Compiled);
private readonly DictionaryContextData _contextData = new();
/// <summary>
/// Clears memory for a composite action's isolated "steps" context, after the action

View File

@@ -32,7 +32,7 @@ namespace GitHub.Runner.Worker
Trace.Entering();
// Create the new tracking config.
TrackingConfig config = new TrackingConfig(executionContext);
TrackingConfig config = new(executionContext);
WriteToFile(file, config);
return config;
}

View File

@@ -14,9 +14,9 @@ namespace GitHub.Runner.Worker
public sealed class Variables
{
private readonly IHostContext _hostContext;
private readonly ConcurrentDictionary<string, Variable> _variables = new ConcurrentDictionary<string, Variable>(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<string, Variable> _variables = new(StringComparer.OrdinalIgnoreCase);
private readonly ISecretMasker _secretMasker;
private readonly object _setLock = new object();
private readonly object _setLock = new();
private readonly Tracing _trace;
public IEnumerable<Variable> AllVariables
@@ -43,7 +43,7 @@ namespace GitHub.Runner.Worker
}
// Initialize the variable dictionary.
List<Variable> variables = new List<Variable>();
List<Variable> variables = new();
foreach (var variable in copy)
{
if (!string.IsNullOrWhiteSpace(variable.Key))

View File

@@ -22,10 +22,10 @@ namespace GitHub.Runner.Worker
public sealed class Worker : RunnerService, IWorker
{
private readonly TimeSpan _workerStartTimeout = TimeSpan.FromSeconds(30);
private ManualResetEvent _completedCommand = new ManualResetEvent(false);
private ManualResetEvent _completedCommand = new(false);
// Do not mask the values of these secrets
private static HashSet<String> SecretVariableMaskWhitelist = new HashSet<String>(StringComparer.OrdinalIgnoreCase)
private static HashSet<String> SecretVariableMaskWhitelist = new(StringComparer.OrdinalIgnoreCase)
{
Constants.Variables.Actions.StepDebug,
Constants.Variables.Actions.RunnerDebug

View File

@@ -15,7 +15,7 @@ namespace GitHub.Runner.Common.Tests
{
Tracing trace = hc.GetTrace();
CommandLineParser clp = new CommandLineParser(hc, secretArgNames: new string[0]);
CommandLineParser clp = new(hc, secretArgNames: new string[0]);
trace.Info("Constructed");
Assert.NotNull(clp);
@@ -30,7 +30,7 @@ namespace GitHub.Runner.Common.Tests
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
CommandLineParser clp = new CommandLineParser(
CommandLineParser clp = new(
hc,
secretArgNames: new[] { "SecretArg1", "SecretArg2" });
@@ -61,7 +61,7 @@ namespace GitHub.Runner.Common.Tests
{
Tracing trace = hc.GetTrace();
CommandLineParser clp = new CommandLineParser(hc, secretArgNames: new string[0]);
CommandLineParser clp = new(hc, secretArgNames: new string[0]);
trace.Info("Constructed.");
clp.Parse(new string[] { "cmd1", "cmd2", "--arg1", "arg1val", "badcmd" });
@@ -81,7 +81,7 @@ namespace GitHub.Runner.Common.Tests
{
Tracing trace = hc.GetTrace();
CommandLineParser clp = new CommandLineParser(hc, secretArgNames: new string[0]);
CommandLineParser clp = new(hc, secretArgNames: new string[0]);
trace.Info("Constructed.");
clp.Parse(new string[] { "cmd1", "--arg1", "arg1val", "--arg2", "arg2val" });
@@ -105,7 +105,7 @@ namespace GitHub.Runner.Common.Tests
{
Tracing trace = hc.GetTrace();
CommandLineParser clp = new CommandLineParser(hc, secretArgNames: new string[0]);
CommandLineParser clp = new(hc, secretArgNames: new string[0]);
trace.Info("Constructed.");
clp.Parse(new string[] { "cmd1", "--flag1", "--arg1", "arg1val", "--flag2" });
@@ -120,7 +120,7 @@ namespace GitHub.Runner.Common.Tests
private TestHostContext CreateTestContext([CallerMemberName] string testName = "")
{
TestHostContext hc = new TestHostContext(this, testName);
TestHostContext hc = new(this, testName);
return hc;
}
}

View File

@@ -12,7 +12,7 @@ namespace GitHub.Runner.Common.Tests
[Trait("Category", "Runner")]
public void BuildConstantGenerateSucceed()
{
List<string> validPackageNames = new List<string>()
List<string> validPackageNames = new()
{
"win-x64",
"win-x86",

View File

@@ -12,10 +12,10 @@ namespace GitHub.Runner.Common.Tests.Worker.Container
public void MountVolumeConstructorParsesStringInput()
{
// Arrange
MountVolume target = new MountVolume("/dst/dir"); // Maps anonymous Docker volume into target dir
MountVolume source_target = new MountVolume("/src/dir:/dst/dir"); // Maps source to target dir
MountVolume target_ro = new MountVolume("/dst/dir:ro");
MountVolume source_target_ro = new MountVolume("/src/dir:/dst/dir:ro");
MountVolume target = new("/dst/dir"); // Maps anonymous Docker volume into target dir
MountVolume source_target = new("/src/dir:/dst/dir"); // Maps source to target dir
MountVolume target_ro = new("/dst/dir:ro");
MountVolume source_target_ro = new("/src/dir:/dst/dir:ro");
// Assert
Assert.Null(target.SourceVolumePath);

View File

@@ -21,7 +21,7 @@ namespace GitHub.Runner.Common.Tests
string shDownloadUrl = "https://dot.net/v1/dotnet-install.sh";
using (HttpClient downloadClient = new HttpClient())
using (HttpClient downloadClient = new())
{
var response = await downloadClient.GetAsync("https://www.bing.com");
if (!response.IsSuccessStatusCode)
@@ -51,7 +51,7 @@ namespace GitHub.Runner.Common.Tests
string ps1DownloadUrl = "https://dot.net/v1/dotnet-install.ps1";
using (HttpClient downloadClient = new HttpClient())
using (HttpClient downloadClient = new())
{
var response = await downloadClient.GetAsync("https://www.bing.com");
if (!response.IsSuccessStatusCode)

View File

@@ -13,7 +13,7 @@ namespace GitHub.Runner.Common.Tests
[Trait("Category", "Common")]
public void LoadsTypeFromString()
{
using (TestHostContext tc = new TestHostContext(this))
using (TestHostContext tc = new(this))
{
// Arrange.
var manager = new ExtensionManager();
@@ -34,7 +34,7 @@ namespace GitHub.Runner.Common.Tests
[Trait("Category", "Common")]
public void LoadsTypes()
{
using (TestHostContext tc = new TestHostContext(this))
using (TestHostContext tc = new(this))
{
// Arrange.
var manager = new ExtensionManager();

View File

@@ -9,7 +9,7 @@ namespace GitHub.Runner.Common.Tests
{
public sealed class CommandSettingsL0
{
private readonly Mock<IPromptManager> _promptManager = new Mock<IPromptManager>();
private readonly Mock<IPromptManager> _promptManager = new();
// It is sufficient to test one arg only. All individual args are tested by the PromptsFor___ methods.
// The PromptsFor___ methods suffice to cover the interesting differences between each of the args.
@@ -879,7 +879,7 @@ namespace GitHub.Runner.Common.Tests
private TestHostContext CreateTestContext([CallerMemberName] string testName = "")
{
TestHostContext hc = new TestHostContext(this, testName);
TestHostContext hc = new(this, testName);
hc.SetSingleton<IPromptManager>(_promptManager.Object);
return hc;
}

View File

@@ -10,7 +10,7 @@ namespace GitHub.Runner.Common.Tests.Listener.Configuration
[Trait("Category", "ArgumentValidator")]
public void ServerUrlValidator()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Assert.True(Validators.ServerUrlValidator("http://servername"));
Assert.False(Validators.ServerUrlValidator("Fail"));
@@ -23,7 +23,7 @@ namespace GitHub.Runner.Common.Tests.Listener.Configuration
[Trait("Category", "ArgumentValidator")]
public void AuthSchemeValidator()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Assert.True(Validators.AuthSchemeValidator("OAuth"));
Assert.False(Validators.AuthSchemeValidator("Fail"));
@@ -35,7 +35,7 @@ namespace GitHub.Runner.Common.Tests.Listener.Configuration
[Trait("Category", "ArgumentValidator")]
public void NonEmptyValidator()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Assert.True(Validators.NonEmptyValidator("test"));
Assert.False(Validators.NonEmptyValidator(string.Empty));

View File

@@ -44,7 +44,7 @@ namespace GitHub.Runner.Common.Tests.Listener.Configuration
private int _defaultRunnerGroupId = 1;
private int _secondRunnerGroupId = 2;
private RSACryptoServiceProvider rsa = null;
private RunnerSettings _configMgrAgentSettings = new RunnerSettings();
private RunnerSettings _configMgrAgentSettings = new();
public ConfigurationManagerL0()
{
@@ -113,7 +113,7 @@ namespace GitHub.Runner.Common.Tests.Listener.Configuration
private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
{
TestHostContext tc = new TestHostContext(this, testName);
TestHostContext tc = new(this, testName);
tc.SetSingleton<ICredentialManager>(_credMgr.Object);
tc.SetSingleton<IPromptManager>(_promptManager.Object);
tc.SetSingleton<IConfigurationStore>(_store.Object);

View File

@@ -12,8 +12,8 @@ namespace GitHub.Runner.Common.Tests.Listener.Configuration
{
private readonly string _argName = "SomeArgName";
private readonly string _description = "Some description";
private readonly PromptManager _promptManager = new PromptManager();
private readonly Mock<ITerminal> _terminal = new Mock<ITerminal>();
private readonly PromptManager _promptManager = new();
private readonly Mock<ITerminal> _terminal = new();
private readonly string _unattendedExceptionMessage = "Invalid configuration provided for SomeArgName. Terminating unattended configuration.";
[Fact]
@@ -21,7 +21,7 @@ namespace GitHub.Runner.Common.Tests.Listener.Configuration
[Trait("Category", "PromptManager")]
public void FallsBackToDefault()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
_terminal
@@ -46,7 +46,7 @@ namespace GitHub.Runner.Common.Tests.Listener.Configuration
[Trait("Category", "PromptManager")]
public void FallsBackToDefaultWhenTrimmed()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
_terminal
@@ -71,7 +71,7 @@ namespace GitHub.Runner.Common.Tests.Listener.Configuration
[Trait("Category", "PromptManager")]
public void FallsBackToDefaultWhenUnattended()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
_terminal
@@ -98,7 +98,7 @@ namespace GitHub.Runner.Common.Tests.Listener.Configuration
[Trait("Category", "PromptManager")]
public void Prompts()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
_terminal
@@ -123,7 +123,7 @@ namespace GitHub.Runner.Common.Tests.Listener.Configuration
[Trait("Category", "PromptManager")]
public void PromptsAgainWhenEmpty()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
var readLineValues = new Queue<string>(new[] { string.Empty, "Some prompt value" });
@@ -150,7 +150,7 @@ namespace GitHub.Runner.Common.Tests.Listener.Configuration
[Trait("Category", "PromptManager")]
public void PromptsAgainWhenFailsValidation()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
var readLineValues = new Queue<string>(new[] { "Some invalid prompt value", "Some valid prompt value" });
@@ -177,7 +177,7 @@ namespace GitHub.Runner.Common.Tests.Listener.Configuration
[Trait("Category", "PromptManager")]
public void ThrowsWhenUnattended()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
_terminal

View File

@@ -14,7 +14,7 @@ namespace GitHub.Runner.Common.Tests.Listener.Configuration
trace.Info("GetVssCredentials()");
var loginCred = new VssOAuthAccessTokenCredential("sometoken");
VssCredentials creds = new VssCredentials(loginCred);
VssCredentials creds = new(loginCred);
trace.Verbose("cred created");
return creds;

View File

@@ -30,7 +30,7 @@ namespace GitHub.Runner.Common.Tests.Listener
private Pipelines.AgentJobRequestMessage CreateJobRequestMessage()
{
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TaskOrchestrationPlanReference plan = new();
TimelineReference timeline = null;
Guid jobId = Guid.NewGuid();
var result = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, "someJob", "someJob", null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);
@@ -101,10 +101,10 @@ namespace GitHub.Runner.Common.Tests.Listener
int count = 0;
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequest));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskCompletionSource<int> firstJobRequestRenewed = new();
CancellationTokenSource cancellationTokenSource = new();
TaskAgentJobRequest request = new TaskAgentJobRequest();
TaskAgentJobRequest request = new();
PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
Assert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
@@ -159,10 +159,10 @@ namespace GitHub.Runner.Common.Tests.Listener
int count = 0;
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobNotFoundExceptions));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskCompletionSource<int> firstJobRequestRenewed = new();
CancellationTokenSource cancellationTokenSource = new();
TaskAgentJobRequest request = new TaskAgentJobRequest();
TaskAgentJobRequest request = new();
PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
Assert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
@@ -218,10 +218,10 @@ namespace GitHub.Runner.Common.Tests.Listener
int count = 0;
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskCompletionSource<int> firstJobRequestRenewed = new();
CancellationTokenSource cancellationTokenSource = new();
TaskAgentJobRequest request = new TaskAgentJobRequest();
TaskAgentJobRequest request = new();
PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
Assert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
@@ -279,8 +279,8 @@ namespace GitHub.Runner.Common.Tests.Listener
var reservedAgent = new TaskAgentReference { Name = newName };
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskCompletionSource<int> firstJobRequestRenewed = new();
CancellationTokenSource cancellationTokenSource = new();
var request = new Mock<TaskAgentJobRequest>();
request.Object.ReservedAgent = reservedAgent;
@@ -335,8 +335,8 @@ namespace GitHub.Runner.Common.Tests.Listener
var reservedAgent = new TaskAgentReference { Name = newName };
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskCompletionSource<int> firstJobRequestRenewed = new();
CancellationTokenSource cancellationTokenSource = new();
var request = new Mock<TaskAgentJobRequest>();
request.Object.ReservedAgent = reservedAgent;
@@ -388,8 +388,8 @@ namespace GitHub.Runner.Common.Tests.Listener
var oldSettings = new RunnerSettings { AgentName = oldName };
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskCompletionSource<int> firstJobRequestRenewed = new();
CancellationTokenSource cancellationTokenSource = new();
var request = new Mock<TaskAgentJobRequest>();
PropertyInfo lockUntilProperty = request.Object.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
@@ -441,10 +441,10 @@ namespace GitHub.Runner.Common.Tests.Listener
int count = 0;
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestRecoverFromExceptions));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskCompletionSource<int> firstJobRequestRenewed = new();
CancellationTokenSource cancellationTokenSource = new();
TaskAgentJobRequest request = new TaskAgentJobRequest();
TaskAgentJobRequest request = new();
PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
Assert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
@@ -502,10 +502,10 @@ namespace GitHub.Runner.Common.Tests.Listener
int count = 0;
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestFirstRenewRetrySixTimes));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskCompletionSource<int> firstJobRequestRenewed = new();
CancellationTokenSource cancellationTokenSource = new();
TaskAgentJobRequest request = new TaskAgentJobRequest();
TaskAgentJobRequest request = new();
PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
Assert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
@@ -557,10 +557,10 @@ namespace GitHub.Runner.Common.Tests.Listener
int count = 0;
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnExpiredRequest));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskCompletionSource<int> firstJobRequestRenewed = new();
CancellationTokenSource cancellationTokenSource = new();
TaskAgentJobRequest request = new TaskAgentJobRequest();
TaskAgentJobRequest request = new();
PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
Assert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));

View File

@@ -36,7 +36,7 @@ namespace GitHub.Runner.Common.Tests.Listener
private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
{
TestHostContext tc = new TestHostContext(this, testName);
TestHostContext tc = new(this, testName);
tc.SetSingleton<IConfigurationManager>(_config.Object);
tc.SetSingleton<IRunnerServer>(_runnerServer.Object);
tc.SetSingleton<ICredentialManager>(_credMgr.Object);
@@ -68,7 +68,7 @@ namespace GitHub.Runner.Common.Tests.Listener
_store.Setup(x => x.GetMigratedCredentials()).Returns(default(CredentialData));
// Act.
MessageListener listener = new MessageListener();
MessageListener listener = new();
listener.Initialize(tc);
bool result = await listener.CreateSessionAsync(tokenSource.Token);
@@ -112,7 +112,7 @@ namespace GitHub.Runner.Common.Tests.Listener
_store.Setup(x => x.GetMigratedCredentials()).Returns(default(CredentialData));
// Act.
MessageListener listener = new MessageListener();
MessageListener listener = new();
listener.Initialize(tc);
bool result = await listener.CreateSessionAsync(tokenSource.Token);
@@ -159,7 +159,7 @@ namespace GitHub.Runner.Common.Tests.Listener
_store.Setup(x => x.GetMigratedCredentials()).Returns(default(CredentialData));
// Act.
MessageListener listener = new MessageListener();
MessageListener listener = new();
listener.Initialize(tc);
bool result = await listener.CreateSessionAsync(tokenSource.Token);
@@ -241,7 +241,7 @@ namespace GitHub.Runner.Common.Tests.Listener
_store.Setup(x => x.GetMigratedCredentials()).Returns(default(CredentialData));
// Act.
MessageListener listener = new MessageListener();
MessageListener listener = new();
listener.Initialize(tc);
bool result = await listener.CreateSessionAsync(tokenSource.Token);
@@ -285,7 +285,7 @@ namespace GitHub.Runner.Common.Tests.Listener
_store.Setup(x => x.GetMigratedCredentials()).Returns(default(CredentialData));
// Act.
MessageListener listener = new MessageListener();
MessageListener listener = new();
listener.Initialize(tc);
bool result = await listener.CreateSessionAsync(tokenSource.Token);

View File

@@ -39,7 +39,7 @@ namespace GitHub.Runner.Common.Tests.Listener
private Pipelines.AgentJobRequestMessage CreateJobRequestMessage(string jobName)
{
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TaskOrchestrationPlanReference plan = new();
TimelineReference timeline = null;
Guid jobId = Guid.NewGuid();
return new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, "test", "test", null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);
@@ -155,7 +155,7 @@ namespace GitHub.Runner.Common.Tests.Listener
}
}
public static TheoryData<string[], bool, Times> RunAsServiceTestData = new TheoryData<string[], bool, Times>()
public static TheoryData<string[], bool, Times> RunAsServiceTestData = new()
{
// staring with run command, configured as run as service, should start the runner
{ new [] { "run" }, true, Times.Once() },

View File

@@ -22,8 +22,8 @@ namespace GitHub.Runner.Common.Tests.Listener
private Mock<ITerminal> _term;
private Mock<IConfigurationStore> _configStore;
private Mock<IJobDispatcher> _jobDispatcher;
private AgentRefreshMessage _refreshMessage = new AgentRefreshMessage(1, "2.299.0");
private List<TrimmedPackageMetadata> _trimmedPackages = new List<TrimmedPackageMetadata>();
private AgentRefreshMessage _refreshMessage = new(1, "2.299.0");
private List<TrimmedPackageMetadata> _trimmedPackages = new();
#if !OS_WINDOWS
private string _packageUrl = null;
@@ -52,7 +52,7 @@ namespace GitHub.Runner.Common.Tests.Listener
if (response.StatusCode == System.Net.HttpStatusCode.Redirect)
{
var redirectUrl = response.Headers.Location.ToString();
Regex regex = new Regex(@"/runner/releases/tag/v(?<version>\d+\.\d+\.\d+)");
Regex regex = new(@"/runner/releases/tag/v(?<version>\d+\.\d+\.\d+)");
var match = regex.Match(redirectUrl);
if (match.Success)
{

View File

@@ -20,7 +20,7 @@ namespace GitHub.Runner.Common.Tests
[Trait("Category", "Common")]
public async Task RunnerLayoutParts_NewFilesCrossAll()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
var runnerCoreAssetsFile = Path.Combine(TestUtil.GetSrcPath(), @"Misc/runnercoreassets");
@@ -53,7 +53,7 @@ namespace GitHub.Runner.Common.Tests
[Trait("Category", "Common")]
public async Task RunnerLayoutParts_OverlapFiles()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
var runnerCoreAssetsFile = Path.Combine(TestUtil.GetSrcPath(), @"Misc/runnercoreassets");
@@ -77,7 +77,7 @@ namespace GitHub.Runner.Common.Tests
[Trait("Category", "Common")]
public async Task RunnerLayoutParts_NewRunnerCoreAssets()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
var runnerCoreAssetsFile = Path.Combine(TestUtil.GetSrcPath(), @"Misc/runnercoreassets");
@@ -120,7 +120,7 @@ namespace GitHub.Runner.Common.Tests
[Trait("Category", "Common")]
public async Task RunnerLayoutParts_NewDotnetRuntimeAssets()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
var runnerDotnetRuntimeFile = Path.Combine(TestUtil.GetSrcPath(), @"Misc/runnerdotnetruntimeassets");
@@ -156,7 +156,7 @@ namespace GitHub.Runner.Common.Tests
[Trait("Category", "Common")]
public async Task RunnerLayoutParts_CheckDotnetRuntimeHash()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
var dotnetRuntimeHashFile = Path.Combine(TestUtil.GetSrcPath(), $"Misc/contentHash/dotnetRuntime/{BuildConstants.RunnerPackage.PackageName}");
@@ -217,7 +217,7 @@ namespace GitHub.Runner.Common.Tests
[Trait("Category", "Common")]
public async Task RunnerLayoutParts_CheckExternalsHash()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
var externalsHashFile = Path.Combine(TestUtil.GetSrcPath(), $"Misc/contentHash/externals/{BuildConstants.RunnerPackage.PackageName}");

View File

@@ -19,7 +19,7 @@ namespace GitHub.Runner.Common.Tests.Listener
private void CleanLogFolder()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
//clean test data if any old test forgot
string pagesFolder = Path.Combine(hc.GetDirectory(WellKnownDirectory.Diag), PagingLogger.PagingFolder);

View File

@@ -16,7 +16,7 @@ namespace GitHub.Runner.Common.Tests
[Trait("Category", "Common")]
public async Task SuccessReadProcessEnv()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();

View File

@@ -63,7 +63,7 @@ namespace GitHub.Runner.Common.Tests
[Trait("Category", "Common")]
public async Task SuccessExitsWithCodeZero()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -86,7 +86,7 @@ namespace GitHub.Runner.Common.Tests
[Trait("Category", "Common")]
public async Task SetCIEnv()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
var existingCI = Environment.GetEnvironmentVariable("CI");
try
@@ -134,7 +134,7 @@ namespace GitHub.Runner.Common.Tests
[Trait("Category", "Common")]
public async Task KeepExistingCIEnv()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
var existingCI = Environment.GetEnvironmentVariable("CI");
try
@@ -185,7 +185,7 @@ namespace GitHub.Runner.Common.Tests
public async Task TestCancel()
{
const int SecondsToRun = 20;
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
using (var tokenSource = new CancellationTokenSource())
{
Tracing trace = hc.GetTrace();
@@ -234,13 +234,13 @@ namespace GitHub.Runner.Common.Tests
[Trait("Category", "Common")]
public async Task RedirectSTDINCloseStream()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationTokenSource cancellationTokenSource = new();
Int32 exitCode = -1;
Channel<string> redirectSTDIN = Channel.CreateUnbounded<string>(new UnboundedChannelOptions() { SingleReader = true, SingleWriter = true });
List<string> stdout = new List<string>();
List<string> stdout = new();
redirectSTDIN.Writer.TryWrite("Single line of STDIN");
var processInvoker = new ProcessInvokerWrapper();
@@ -284,13 +284,13 @@ namespace GitHub.Runner.Common.Tests
[Trait("Category", "Common")]
public async Task RedirectSTDINKeepStreamOpen()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationTokenSource cancellationTokenSource = new();
Int32 exitCode = -1;
Channel<string> redirectSTDIN = Channel.CreateUnbounded<string>(new UnboundedChannelOptions() { SingleReader = true, SingleWriter = true });
List<string> stdout = new List<string>();
List<string> stdout = new();
redirectSTDIN.Writer.TryWrite("Single line of STDIN");
var processInvoker = new ProcessInvokerWrapper();
@@ -339,7 +339,7 @@ namespace GitHub.Runner.Common.Tests
string testProcPath = $"/proc/{Process.GetCurrentProcess().Id}/oom_score_adj";
if (File.Exists(testProcPath))
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
using (var tokenSource = new CancellationTokenSource())
{
Tracing trace = hc.GetTrace();
@@ -375,7 +375,7 @@ namespace GitHub.Runner.Common.Tests
string testProcPath = $"/proc/{Process.GetCurrentProcess().Id}/oom_score_adj";
if (File.Exists(testProcPath))
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
using (var tokenSource = new CancellationTokenSource())
{
Tracing trace = hc.GetTrace();
@@ -415,7 +415,7 @@ namespace GitHub.Runner.Common.Tests
{
int testProcOomScoreAdj = 123;
File.WriteAllText(testProcPath, testProcOomScoreAdj.ToString());
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
using (var tokenSource = new CancellationTokenSource())
{
Tracing trace = hc.GetTrace();

View File

@@ -11,9 +11,9 @@ namespace GitHub.Runner.Common.Tests
{
public sealed class RunnerWebProxyL0
{
private static readonly Regex NewHttpClientHandlerRegex = new Regex("New\\s+HttpClientHandler\\s*\\(", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex NewHttpClientRegex = new Regex("New\\s+HttpClient\\s*\\(\\s*\\)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly List<string> SkippedFiles = new List<string>()
private static readonly Regex NewHttpClientHandlerRegex = new("New\\s+HttpClientHandler\\s*\\(", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex NewHttpClientRegex = new("New\\s+HttpClient\\s*\\(\\s*\\)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly List<string> SkippedFiles = new()
{
"Runner.Common\\HostContext.cs",
"Runner.Common/HostContext.cs",
@@ -39,7 +39,7 @@ namespace GitHub.Runner.Common.Tests
"*.cs",
SearchOption.AllDirectories));
List<string> badCode = new List<string>();
List<string> badCode = new();
foreach (string sourceFile in sourceFiles)
{
// Skip skipped files.
@@ -86,7 +86,7 @@ namespace GitHub.Runner.Common.Tests
"*.cs",
SearchOption.AllDirectories));
List<string> badCode = new List<string>();
List<string> badCode = new();
foreach (string sourceFile in sourceFiles)
{
// Skip skipped files.

View File

@@ -11,7 +11,7 @@ namespace GitHub.Runner.Common.Tests
[Trait("Category", "Service")]
public void CalculateServiceName()
{
RunnerSettings settings = new RunnerSettings();
RunnerSettings settings = new();
settings.AgentName = "thisiskindofalongrunnerabcde";
settings.ServerUrl = "https://example.githubusercontent.com/12345678901234567890123456789012345678901234567890";
@@ -22,7 +22,7 @@ namespace GitHub.Runner.Common.Tests
using (TestHostContext hc = CreateTestContext())
{
ServiceControlManager scm = new ServiceControlManager();
ServiceControlManager scm = new();
scm.Initialize(hc);
scm.CalculateServiceName(
@@ -50,7 +50,7 @@ namespace GitHub.Runner.Common.Tests
[Trait("Category", "Service")]
public void CalculateServiceName80Chars()
{
RunnerSettings settings = new RunnerSettings();
RunnerSettings settings = new();
settings.AgentName = "thisiskindofalongrunnernabcde";
settings.ServerUrl = "https://example.githubusercontent.com/12345678901234567890123456789012345678901234567890";
@@ -61,7 +61,7 @@ namespace GitHub.Runner.Common.Tests
using (TestHostContext hc = CreateTestContext())
{
ServiceControlManager scm = new ServiceControlManager();
ServiceControlManager scm = new();
scm.Initialize(hc);
scm.CalculateServiceName(
@@ -169,7 +169,7 @@ namespace GitHub.Runner.Common.Tests
[Trait("Category", "Service")]
public void CalculateServiceNameLimitsServiceNameTo150Chars()
{
RunnerSettings settings = new RunnerSettings();
RunnerSettings settings = new();
settings.AgentName = "thisisareallyreallylongbutstillvalidagentnameiamusingforthisexampletotestverylongnamelimits";
settings.ServerUrl = "https://example.githubusercontent.com/12345678901234567890123456789012345678901234567890";
@@ -180,7 +180,7 @@ namespace GitHub.Runner.Common.Tests
using (TestHostContext hc = CreateTestContext())
{
ServiceControlManager scm = new ServiceControlManager();
ServiceControlManager scm = new();
scm.Initialize(hc);
scm.CalculateServiceName(
@@ -206,7 +206,7 @@ namespace GitHub.Runner.Common.Tests
private TestHostContext CreateTestContext([CallerMemberName] string testName = "")
{
TestHostContext hc = new TestHostContext(this, testName);
TestHostContext hc = new(this, testName);
return hc;
}

View File

@@ -17,12 +17,12 @@ namespace GitHub.Runner.Common.Tests
{
public sealed class TestHostContext : IHostContext, IDisposable
{
private readonly ConcurrentDictionary<Type, ConcurrentQueue<object>> _serviceInstances = new ConcurrentDictionary<Type, ConcurrentQueue<object>>();
private readonly ConcurrentDictionary<Type, object> _serviceSingletons = new ConcurrentDictionary<Type, object>();
private readonly ConcurrentDictionary<Type, ConcurrentQueue<object>> _serviceInstances = new();
private readonly ConcurrentDictionary<Type, object> _serviceSingletons = new();
private readonly ITraceManager _traceManager;
private readonly Terminal _term;
private readonly SecretMasker _secretMasker;
private CancellationTokenSource _runnerShutdownTokenSource = new CancellationTokenSource();
private CancellationTokenSource _runnerShutdownTokenSource = new();
private string _suiteName;
private string _testName;
private Tracing _trace;
@@ -86,9 +86,9 @@ namespace GitHub.Runner.Common.Tests
}
}
public List<ProductInfoHeaderValue> UserAgents => new List<ProductInfoHeaderValue>() { new ProductInfoHeaderValue("L0Test", "0.0") };
public List<ProductInfoHeaderValue> UserAgents => new() { new ProductInfoHeaderValue("L0Test", "0.0") };
public RunnerWebProxy WebProxy => new RunnerWebProxy();
public RunnerWebProxy WebProxy => new();
public async Task Delay(TimeSpan delay, CancellationToken token)
{

View File

@@ -11,7 +11,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void Equal_MatchesObjectEquality()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -29,12 +29,12 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void Equal_MatchesReferenceEquality()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
// Arrange.
object expected = new object();
object expected = new();
object actual = expected;
// Act/Assert.
@@ -47,7 +47,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void Equal_MatchesStructEquality()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -65,12 +65,12 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void Equal_ThrowsWhenActualObjectIsNull()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
// Arrange.
object expected = new object();
object expected = new();
object actual = null;
// Act/Assert.
@@ -86,13 +86,13 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void Equal_ThrowsWhenExpectedObjectIsNull()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
// Arrange.
object expected = null;
object actual = new object();
object actual = new();
// Act/Assert.
Assert.Throws<ArgumentOutOfRangeException>(() =>
@@ -107,13 +107,13 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void Equal_ThrowsWhenObjectsAreNotEqual()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
// Arrange.
object expected = new object();
object actual = new object();
object expected = new();
object actual = new();
// Act/Assert.
Assert.Throws<ArgumentOutOfRangeException>(() =>
@@ -128,7 +128,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void Equal_ThrowsWhenStructsAreNotEqual()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();

View File

@@ -15,7 +15,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void Delete_DeletesDirectory()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -49,7 +49,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void Delete_DeletesFile()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -83,7 +83,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void DeleteDirectory_DeletesDirectoriesRecursively()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -115,7 +115,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public async Task DeleteDirectory_DeletesDirectoryReparsePointChain()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -179,7 +179,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public async Task DeleteDirectory_DeletesDirectoryReparsePointsBeforeDirectories()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -230,7 +230,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void DeleteDirectory_DeletesFilesRecursively()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -264,7 +264,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void DeleteDirectory_DeletesReadOnlyDirectories()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -305,7 +305,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void DeleteDirectory_DeletesReadOnlyRootDirectory()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -341,7 +341,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void DeleteDirectory_DeletesReadOnlyFiles()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -381,7 +381,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public async Task DeleteDirectory_DoesNotFollowDirectoryReparsePoint()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -428,7 +428,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public async Task DeleteDirectory_DoesNotFollowNestLevel1DirectoryReparsePoint()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -477,7 +477,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public async Task DeleteDirectory_DoesNotFollowNestLevel2DirectoryReparsePoint()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -528,7 +528,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void DeleteDirectory_IgnoresFile()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -563,7 +563,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void DeleteFile_DeletesFile()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -597,7 +597,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void DeleteFile_DeletesReadOnlyFile()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -637,7 +637,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void DeleteFile_IgnoresDirectory()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -670,7 +670,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void GetRelativePath()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -768,7 +768,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void ResolvePath()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -867,7 +867,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void ValidateExecutePermission_DoesNotExceedFailsafe()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -896,7 +896,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void ValidateExecutePermission_ExceedsFailsafe()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();

View File

@@ -12,7 +12,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void FormatAlwaysCallsFormat()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -48,7 +48,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void FormatHandlesFormatException()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();
@@ -79,7 +79,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void FormatUsesInvariantCulture()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
CultureInfo originalCulture = CultureInfo.CurrentCulture;
@@ -105,7 +105,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void ConvertNullOrEmptryStringToBool()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
string nullString = null;
@@ -126,7 +126,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void ConvertNullOrEmptryStringToDefaultBool()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
string nullString = null;
@@ -147,7 +147,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void ConvertStringToBool()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
string trueString1 = "1";

View File

@@ -12,7 +12,7 @@ namespace GitHub.Runner.Common.Tests.Util
public void TaskResultReturnCodeTranslate()
{
// Arrange.
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Act.
TaskResult abandon = TaskResultUtil.TranslateFromReturnCode(TaskResultUtil.TranslateToReturnCode(TaskResult.Abandoned));
@@ -57,7 +57,7 @@ namespace GitHub.Runner.Common.Tests.Util
public void TaskResultsMerge()
{
// Arrange.
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
TaskResult merged;

View File

@@ -12,7 +12,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void VerifyOverwriteVssConnectionSetting()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
Tracing trace = hc.GetTrace();

View File

@@ -13,7 +13,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void UseWhichFindGit()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
//Arrange
Tracing trace = hc.GetTrace();
@@ -33,7 +33,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void WhichReturnsNullWhenNotFound()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
//Arrange
Tracing trace = hc.GetTrace();
@@ -53,7 +53,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void WhichThrowsWhenRequireAndNotFound()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
//Arrange
Tracing trace = hc.GetTrace();
@@ -76,7 +76,7 @@ namespace GitHub.Runner.Common.Tests.Util
[Trait("Category", "Common")]
public void WhichHandleFullyQualifiedPath()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
//Arrange
Tracing trace = hc.GetTrace();

View File

@@ -18,7 +18,7 @@ namespace GitHub.Runner.Common.Tests.Worker
string message;
ActionCommand test;
ActionCommand verify;
HashSet<string> commands = new HashSet<string>() { "do-something" };
HashSet<string> commands = new() { "do-something" };
//##[do-something k1=v1;]msg
message = "##[do-something k1=v1;]msg";
test = new ActionCommand("do-something")
@@ -99,7 +99,7 @@ namespace GitHub.Runner.Common.Tests.Worker
string message;
ActionCommand test;
ActionCommand verify;
HashSet<string> commands = new HashSet<string>() { "do-something" };
HashSet<string> commands = new() { "do-something" };
//::do-something k1=v1;]msg
message = "::do-something k1=v1,::msg";
test = new ActionCommand("do-something")

View File

@@ -228,8 +228,8 @@ namespace GitHub.Runner.Common.Tests.Worker
{
// Set up a few things
// 1. Job request message (with ACTIONS_STEP_DEBUG = true)
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TimelineReference timeline = new TimelineReference();
TaskOrchestrationPlanReference plan = new();
TimelineReference timeline = new();
Guid jobId = Guid.NewGuid();
string jobName = "some job name";
var jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, jobName, jobName, null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);

View File

@@ -1028,7 +1028,7 @@ namespace GitHub.Runner.Common.Tests.Worker
//Arrange
Setup();
Pipelines.ActionStep instance = new Pipelines.ActionStep()
Pipelines.ActionStep instance = new()
{
Id = Guid.NewGuid(),
Reference = new Pipelines.ContainerRegistryReference()
@@ -1065,7 +1065,7 @@ namespace GitHub.Runner.Common.Tests.Worker
//Arrange
Setup();
Pipelines.ActionStep instance = new Pipelines.ActionStep()
Pipelines.ActionStep instance = new()
{
Id = Guid.NewGuid(),
Reference = new Pipelines.ScriptReference()
@@ -1137,7 +1137,7 @@ runs:
Assert.NotNull(definition.Data);
Assert.NotNull(definition.Data.Inputs); // inputs
Dictionary<string, string> inputDefaults = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, string> inputDefaults = new(StringComparer.OrdinalIgnoreCase);
foreach (var input in definition.Data.Inputs)
{
var name = input.Key.AssertString("key").Value;
@@ -1236,7 +1236,7 @@ runs:
Assert.Equal(directory, definition.Directory);
Assert.NotNull(definition.Data);
Assert.NotNull(definition.Data.Inputs); // inputs
Dictionary<string, string> inputDefaults = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, string> inputDefaults = new(StringComparer.OrdinalIgnoreCase);
foreach (var input in definition.Data.Inputs)
{
var name = input.Key.AssertString("key").Value;
@@ -1328,7 +1328,7 @@ runs:
Assert.Equal(directory, definition.Directory);
Assert.NotNull(definition.Data);
Assert.NotNull(definition.Data.Inputs); // inputs
Dictionary<string, string> inputDefaults = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, string> inputDefaults = new(StringComparer.OrdinalIgnoreCase);
foreach (var input in definition.Data.Inputs)
{
var name = input.Key.AssertString("key").Value;
@@ -1397,7 +1397,7 @@ runs:
Assert.Equal(directory, definition.Directory);
Assert.NotNull(definition.Data);
Assert.NotNull(definition.Data.Inputs); // inputs
Dictionary<string, string> inputDefaults = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, string> inputDefaults = new(StringComparer.OrdinalIgnoreCase);
foreach (var input in definition.Data.Inputs)
{
var name = input.Key.AssertString("key").Value;
@@ -1479,7 +1479,7 @@ runs:
Assert.Equal(directory, definition.Directory);
Assert.NotNull(definition.Data);
Assert.NotNull(definition.Data.Inputs); // inputs
Dictionary<string, string> inputDefaults = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, string> inputDefaults = new(StringComparer.OrdinalIgnoreCase);
foreach (var input in definition.Data.Inputs)
{
var name = input.Key.AssertString("key").Value;
@@ -1555,7 +1555,7 @@ runs:
Assert.NotNull(definition.Data);
Assert.NotNull(definition.Data.Inputs); // inputs
Dictionary<string, string> inputDefaults = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, string> inputDefaults = new(StringComparer.OrdinalIgnoreCase);
foreach (var input in definition.Data.Inputs)
{
var name = input.Key.AssertString("key").Value;
@@ -1653,7 +1653,7 @@ runs:
Assert.Equal(directory, definition.Directory);
Assert.NotNull(definition.Data);
Assert.NotNull(definition.Data.Inputs); // inputs
Dictionary<string, string> inputDefaults = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, string> inputDefaults = new(StringComparer.OrdinalIgnoreCase);
foreach (var input in definition.Data.Inputs)
{
var name = input.Key.AssertString("key").Value;
@@ -1745,7 +1745,7 @@ runs:
Assert.Equal(directory, definition.Directory);
Assert.NotNull(definition.Data);
Assert.NotNull(definition.Data.Inputs); // inputs
Dictionary<string, string> inputDefaults = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, string> inputDefaults = new(StringComparer.OrdinalIgnoreCase);
foreach (var input in definition.Data.Inputs)
{
var name = input.Key.AssertString("key").Value;
@@ -1814,7 +1814,7 @@ runs:
Assert.Equal(directory, definition.Directory);
Assert.NotNull(definition.Data);
Assert.NotNull(definition.Data.Inputs); // inputs
Dictionary<string, string> inputDefaults = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, string> inputDefaults = new(StringComparer.OrdinalIgnoreCase);
foreach (var input in definition.Data.Inputs)
{
var name = input.Key.AssertString("key").Value;
@@ -1893,7 +1893,7 @@ runs:
Assert.NotNull(definition.Data);
Assert.NotNull(definition.Data.Inputs); // inputs
Dictionary<string, string> inputDefaults = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, string> inputDefaults = new(StringComparer.OrdinalIgnoreCase);
foreach (var input in definition.Data.Inputs)
{
var name = input.Key.AssertString("key").Value;
@@ -1983,7 +1983,7 @@ runs:
Assert.Equal(directory, definition.Directory);
Assert.NotNull(definition.Data);
Assert.NotNull(definition.Data.Inputs); // inputs
Dictionary<string, string> inputDefaults = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, string> inputDefaults = new(StringComparer.OrdinalIgnoreCase);
foreach (var input in definition.Data.Inputs)
{
var name = input.Key.AssertString("key").Value;

View File

@@ -34,7 +34,7 @@ namespace GitHub.Runner.Common.Tests.Worker
private IActionManifestManager _actionManifestManager;
private Mock<IFileCommandManager> _fileCommandManager;
private DictionaryContextData _context = new DictionaryContextData();
private DictionaryContextData _context = new();
[Fact]
[Trait("Level", "L0")]
@@ -60,7 +60,7 @@ namespace GitHub.Runner.Common.Tests.Worker
_actionRunner.Action = action;
Dictionary<string, string> finialInputs = new Dictionary<string, string>();
Dictionary<string, string> finialInputs = new();
_handlerFactory.Setup(x => x.Create(It.IsAny<IExecutionContext>(), It.IsAny<ActionStepDefinitionReference>(), It.IsAny<IStepHost>(), It.IsAny<ActionExecutionData>(), It.IsAny<Dictionary<string, string>>(), It.IsAny<Dictionary<string, string>>(), It.IsAny<Variables>(), It.IsAny<string>(), It.IsAny<List<JobExtensionRunner>>()))
.Callback((IExecutionContext executionContext, Pipelines.ActionStepDefinitionReference actionReference, IStepHost stepHost, ActionExecutionData data, Dictionary<string, string> inputs, Dictionary<string, string> environment, Variables runtimeVariables, string taskDirectory, List<JobExtensionRunner> localActionContainerSetupSteps) =>
{
@@ -106,7 +106,7 @@ namespace GitHub.Runner.Common.Tests.Worker
_actionRunner.Action = action;
Dictionary<string, string> finialInputs = new Dictionary<string, string>();
Dictionary<string, string> finialInputs = new();
_handlerFactory.Setup(x => x.Create(It.IsAny<IExecutionContext>(), It.IsAny<ActionStepDefinitionReference>(), It.IsAny<IStepHost>(), It.IsAny<ActionExecutionData>(), It.IsAny<Dictionary<string, string>>(), It.IsAny<Dictionary<string, string>>(), It.IsAny<Variables>(), It.IsAny<string>(), It.IsAny<List<JobExtensionRunner>>()))
.Callback((IExecutionContext executionContext, Pipelines.ActionStepDefinitionReference actionReference, IStepHost stepHost, ActionExecutionData data, Dictionary<string, string> inputs, Dictionary<string, string> environment, Variables runtimeVariables, string taskDirectory, List<JobExtensionRunner> localActionContainerSetupSteps) =>
{
@@ -307,7 +307,7 @@ namespace GitHub.Runner.Common.Tests.Worker
_actionRunner.Action = action;
Dictionary<string, string> finialInputs = new Dictionary<string, string>();
Dictionary<string, string> finialInputs = new();
_handlerFactory.Setup(x => x.Create(It.IsAny<IExecutionContext>(), It.IsAny<ActionStepDefinitionReference>(), It.IsAny<IStepHost>(), It.IsAny<ActionExecutionData>(), It.IsAny<Dictionary<string, string>>(), It.IsAny<Dictionary<string, string>>(), It.IsAny<Variables>(), It.IsAny<string>(), It.IsAny<List<JobExtensionRunner>>()))
.Callback((IExecutionContext executionContext, Pipelines.ActionStepDefinitionReference actionReference, IStepHost stepHost, ActionExecutionData data, Dictionary<string, string> inputs, Dictionary<string, string> environment, Variables runtimeVariables, string taskDirectory, List<JobExtensionRunner> localActionContainerSetupSteps) =>
{
@@ -358,7 +358,7 @@ namespace GitHub.Runner.Common.Tests.Worker
_actionRunner.Action = action;
Dictionary<string, string> finialInputs = new Dictionary<string, string>();
Dictionary<string, string> finialInputs = new();
_handlerFactory.Setup(x => x.Create(It.IsAny<IExecutionContext>(), It.IsAny<ActionStepDefinitionReference>(), It.IsAny<IStepHost>(), It.IsAny<ActionExecutionData>(), It.IsAny<Dictionary<string, string>>(), It.IsAny<Dictionary<string, string>>(), It.IsAny<Variables>(), It.IsAny<string>(), It.IsAny<List<JobExtensionRunner>>()))
.Callback((IExecutionContext executionContext, Pipelines.ActionStepDefinitionReference actionReference, IStepHost stepHost, ActionExecutionData data, Dictionary<string, string> inputs, Dictionary<string, string> environment, Variables runtimeVariables, string taskDirectory, List<JobExtensionRunner> localActionContainerSetupSteps) =>
{

View File

@@ -22,12 +22,12 @@ namespace GitHub.Runner.Common.Tests.Worker
private ContainerOperationProvider containerOperationProvider;
private Mock<IJobServerQueue> serverQueue;
private Mock<IPagingLogger> pagingLogger;
private List<string> healthyDockerStatus = new List<string> { "healthy" };
private List<string> emptyDockerStatus = new List<string> { string.Empty };
private List<string> unhealthyDockerStatus = new List<string> { "unhealthy" };
private List<string> dockerLogs = new List<string> { "log1", "log2", "log3" };
private List<string> healthyDockerStatus = new() { "healthy" };
private List<string> emptyDockerStatus = new() { string.Empty };
private List<string> unhealthyDockerStatus = new() { "unhealthy" };
private List<string> dockerLogs = new() { "log1", "log2", "log3" };
List<ContainerInfo> containers = new List<ContainerInfo>();
List<ContainerInfo> containers = new();
[Fact]
[Trait("Level", "L0")]

View File

@@ -189,8 +189,8 @@ namespace GitHub.Runner.Common.Tests.Worker
_issues = new List<Tuple<DTWebApi.Issue, string>>();
// Setup a job request
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TimelineReference timeline = new TimelineReference();
TaskOrchestrationPlanReference plan = new();
TimelineReference timeline = new();
Guid jobId = Guid.NewGuid();
string jobName = "Summary Job";
var jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, jobName, jobName, null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);

View File

@@ -25,8 +25,8 @@ namespace GitHub.Runner.Common.Tests.Worker
using (TestHostContext hc = CreateTestContext())
{
// Arrange: Create a job request message.
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TimelineReference timeline = new TimelineReference();
TaskOrchestrationPlanReference plan = new();
TimelineReference timeline = new();
Guid jobId = Guid.NewGuid();
string jobName = "some job name";
var jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, jobName, jobName, null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);
@@ -101,8 +101,8 @@ namespace GitHub.Runner.Common.Tests.Worker
using (TestHostContext hc = CreateTestContext())
{
// Arrange: Create a job request message.
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TimelineReference timeline = new TimelineReference();
TaskOrchestrationPlanReference plan = new();
TimelineReference timeline = new();
Guid jobId = Guid.NewGuid();
string jobName = "some job name";
var jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, jobName, jobName, null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);
@@ -157,8 +157,8 @@ namespace GitHub.Runner.Common.Tests.Worker
using (TestHostContext hc = CreateTestContext())
{
// Arrange: Create a job request message.
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TimelineReference timeline = new TimelineReference();
TaskOrchestrationPlanReference plan = new();
TimelineReference timeline = new();
Guid jobId = Guid.NewGuid();
string jobName = "some job name";
var jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, jobName, jobName, null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);
@@ -211,8 +211,8 @@ namespace GitHub.Runner.Common.Tests.Worker
using (TestHostContext hc = CreateTestContext())
{
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TimelineReference timeline = new TimelineReference();
TaskOrchestrationPlanReference plan = new();
TimelineReference timeline = new();
Guid jobId = Guid.NewGuid();
string jobName = "some job name";
var jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, jobName, jobName, null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);
@@ -260,8 +260,8 @@ namespace GitHub.Runner.Common.Tests.Worker
using (TestHostContext hc = CreateTestContext())
{
// Arrange: Create a job request message.
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TimelineReference timeline = new TimelineReference();
TaskOrchestrationPlanReference plan = new();
TimelineReference timeline = new();
Guid jobId = Guid.NewGuid();
string jobName = "some job name";
var jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, jobName, jobName, null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);
@@ -311,8 +311,8 @@ namespace GitHub.Runner.Common.Tests.Worker
using (TestHostContext hc = CreateTestContext())
{
// Arrange: Create a job request message.
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TimelineReference timeline = new TimelineReference();
TaskOrchestrationPlanReference plan = new();
TimelineReference timeline = new();
Guid jobId = Guid.NewGuid();
string jobName = "some job name";
var jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, jobName, jobName, null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);
@@ -409,8 +409,8 @@ namespace GitHub.Runner.Common.Tests.Worker
using (TestHostContext hc = CreateTestContext())
{
// Arrange: Create a job request message.
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TimelineReference timeline = new TimelineReference();
TaskOrchestrationPlanReference plan = new();
TimelineReference timeline = new();
Guid jobId = Guid.NewGuid();
string jobName = "some job name";
var jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, jobName, jobName, null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);
@@ -493,8 +493,8 @@ namespace GitHub.Runner.Common.Tests.Worker
{
using (TestHostContext hc = CreateTestContext())
{
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TimelineReference timeline = new TimelineReference();
TaskOrchestrationPlanReference plan = new();
TimelineReference timeline = new();
Guid jobId = Guid.NewGuid();
string jobName = "some job name";
var jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, jobName, jobName, null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);
@@ -548,8 +548,8 @@ namespace GitHub.Runner.Common.Tests.Worker
using (TestHostContext hc = CreateTestContext())
{
// Arrange: Create a job request message.
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TimelineReference timeline = new TimelineReference();
TaskOrchestrationPlanReference plan = new();
TimelineReference timeline = new();
Guid jobId = Guid.NewGuid();
string jobName = "some job name";
var jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, jobName, jobName, null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);
@@ -591,8 +591,8 @@ namespace GitHub.Runner.Common.Tests.Worker
using (TestHostContext hc = CreateTestContext())
{
// Arrange: Create a job request message.
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TimelineReference timeline = new TimelineReference();
TaskOrchestrationPlanReference plan = new();
TimelineReference timeline = new();
Guid jobId = Guid.NewGuid();
string jobName = "some job name";
var jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, jobName, jobName, null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);
@@ -655,8 +655,8 @@ namespace GitHub.Runner.Common.Tests.Worker
using (TestHostContext hc = CreateTestContext())
{
// Arrange: Create a job request message.
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TimelineReference timeline = new TimelineReference();
TaskOrchestrationPlanReference plan = new();
TimelineReference timeline = new();
Guid jobId = Guid.NewGuid();
string jobName = "some job name";
var jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, jobName, jobName, null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);
@@ -851,8 +851,8 @@ namespace GitHub.Runner.Common.Tests.Worker
{
using (TestHostContext hc = CreateTestContext())
{
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TimelineReference timeline = new TimelineReference();
TaskOrchestrationPlanReference plan = new();
TimelineReference timeline = new();
Guid jobId = Guid.NewGuid();
string jobName = "some job name";
var jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, jobName, jobName, null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);

View File

@@ -56,7 +56,7 @@ namespace GitHub.Runner.Common.Tests.Worker
{
variables["DistributedTask.ForceGithubJavascriptActionsToNode16"] = serverFeatureFlag;
}
Variables serverVariables = new Variables(hc, variables);
Variables serverVariables = new(hc, variables);
// Workflow opt-out
var workflowVariables = new Dictionary<string, string>();

View File

@@ -67,10 +67,10 @@ namespace GitHub.Runner.Common.Tests.Worker
}
_tokenSource = new CancellationTokenSource();
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TaskOrchestrationPlanReference plan = new();
TimelineReference timeline = new Timeline(Guid.NewGuid());
List<Pipelines.ActionStep> steps = new List<Pipelines.ActionStep>()
List<Pipelines.ActionStep> steps = new()
{
new Pipelines.ActionStep()
{
@@ -101,7 +101,7 @@ namespace GitHub.Runner.Common.Tests.Worker
Guid jobId = Guid.NewGuid();
_message = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, "test", "test", null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), steps, null, null, null, null);
GitHubContext github = new GitHubContext();
GitHubContext github = new();
github["repository"] = new Pipelines.ContextData.StringContextData("actions/runner");
github["secret_source"] = new Pipelines.ContextData.StringContextData("Actions");
_message.ContextData.Add("github", github);

View File

@@ -15,7 +15,7 @@ namespace GitHub.Runner.Common.Tests.Worker
{
private IExecutionContext _jobEc;
private JobRunner _jobRunner;
private List<IStep> _initResult = new List<IStep>();
private List<IStep> _initResult = new();
private Pipelines.AgentJobRequestMessage _message;
private CancellationTokenSource _tokenSource;
private Mock<IJobServer> _jobServer;
@@ -55,7 +55,7 @@ namespace GitHub.Runner.Common.Tests.Worker
_jobRunner = new JobRunner();
_jobRunner.Initialize(hc);
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TaskOrchestrationPlanReference plan = new();
TimelineReference timeline = new Timeline(Guid.NewGuid());
Guid jobId = Guid.NewGuid();
_message = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, testName, testName, null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);

View File

@@ -199,13 +199,13 @@ namespace GitHub.Runner.Common.Tests.Worker
[CallerMemberName] string name = "")
{
// Setup the host context.
TestHostContext hc = new TestHostContext(this, name);
TestHostContext hc = new(this, name);
// Setup the execution context.
_ec = new Mock<IExecutionContext>();
_ec.Setup(x => x.Global).Returns(new GlobalContext());
GitHubContext githubContext = new GitHubContext();
GitHubContext githubContext = new();
_ec.Setup(x => x.GetGitHubContext("repository")).Returns("actions/runner");
// Store the expected tracking file path.

View File

@@ -27,7 +27,7 @@ namespace GitHub.Runner.Common.Tests.Worker
private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
{
var hc = new TestHostContext(this, testName);
Dictionary<string, VariableValue> variablesToCopy = new Dictionary<string, VariableValue>();
Dictionary<string, VariableValue> variablesToCopy = new();
_variables = new Variables(
hostContext: hc,
copy: variablesToCopy);

View File

@@ -16,14 +16,14 @@ namespace GitHub.Runner.Common.Tests.Worker
public TestHostContext Setup([CallerMemberName] string name = "")
{
// Setup the host context.
TestHostContext hc = new TestHostContext(this, name);
TestHostContext hc = new(this, name);
// Create a random work path.
_workFolder = hc.GetDirectory(WellKnownDirectory.Work);
// Setup the execution context.
_ec = new Mock<IExecutionContext>();
GitHubContext githubContext = new GitHubContext();
GitHubContext githubContext = new();
_ec.Setup(x => x.GetGitHubContext("repository")).Returns("actions/runner");
// Setup the tracking manager.
@@ -113,7 +113,7 @@ namespace GitHub.Runner.Common.Tests.Worker
using (TestHostContext hc = Setup())
{
// Arrange.
TrackingConfig config = new TrackingConfig() { RepositoryName = "actions/runner" };
TrackingConfig config = new() { RepositoryName = "actions/runner" };
string trackingFile = Path.Combine(_workFolder, "trackingconfig.json");
// Act.

View File

@@ -14,7 +14,7 @@ namespace GitHub.Runner.Common.Tests.Worker
[Trait("Category", "Worker")]
public void Constructor_AppliesMaskHints()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
var copy = new Dictionary<string, VariableValue>
@@ -36,7 +36,7 @@ namespace GitHub.Runner.Common.Tests.Worker
[Trait("Category", "Worker")]
public void Constructor_HandlesNullValue()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
var copy = new Dictionary<string, VariableValue>
@@ -59,7 +59,7 @@ namespace GitHub.Runner.Common.Tests.Worker
[Trait("Category", "Worker")]
public void Constructor_SetsNullAsEmpty()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
var copy = new Dictionary<string, VariableValue>
@@ -80,7 +80,7 @@ namespace GitHub.Runner.Common.Tests.Worker
[Trait("Category", "Worker")]
public void Constructor_SetsOrdinalIgnoreCaseComparer()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
CultureInfo currentCulture = CultureInfo.CurrentCulture;
@@ -115,7 +115,7 @@ namespace GitHub.Runner.Common.Tests.Worker
[Trait("Category", "Worker")]
public void Constructor_SkipVariableWithEmptyName()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
var copy = new Dictionary<string, VariableValue>
@@ -139,7 +139,7 @@ namespace GitHub.Runner.Common.Tests.Worker
[Trait("Category", "Worker")]
public void Get_ReturnsNullIfNotFound()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
var variables = new Variables(hc, new Dictionary<string, VariableValue>());
@@ -157,7 +157,7 @@ namespace GitHub.Runner.Common.Tests.Worker
[Trait("Category", "Worker")]
public void GetBoolean_DoesNotThrowWhenNull()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
var variables = new Variables(hc, new Dictionary<string, VariableValue>());
@@ -175,7 +175,7 @@ namespace GitHub.Runner.Common.Tests.Worker
[Trait("Category", "Worker")]
public void GetEnum_DoesNotThrowWhenNull()
{
using (TestHostContext hc = new TestHostContext(this))
using (TestHostContext hc = new(this))
{
// Arrange.
var variables = new Variables(hc, new Dictionary<string, VariableValue>());

View File

@@ -25,17 +25,17 @@ namespace GitHub.Runner.Common.Tests.Worker
private Pipelines.AgentJobRequestMessage CreateJobRequestMessage(string jobName)
{
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference() { PlanId = Guid.NewGuid() };
TaskOrchestrationPlanReference plan = new() { PlanId = Guid.NewGuid() };
TimelineReference timeline = null;
Dictionary<string, VariableValue> variables = new Dictionary<string, VariableValue>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, VariableValue> variables = new(StringComparer.OrdinalIgnoreCase);
variables[Constants.Variables.System.Culture] = "en-US";
Pipelines.JobResources resources = new Pipelines.JobResources();
Pipelines.JobResources resources = new();
var serviceEndpoint = new ServiceEndpoint();
serviceEndpoint.Authorization = new EndpointAuthorization();
serviceEndpoint.Authorization.Parameters.Add("nullValue", null);
resources.Endpoints.Add(serviceEndpoint);
List<Pipelines.ActionStep> actions = new List<Pipelines.ActionStep>();
List<Pipelines.ActionStep> actions = new();
actions.Add(new Pipelines.ActionStep()
{
Id = Guid.NewGuid(),