diff --git a/src/Runner.Common/ActionCommand.cs b/src/Runner.Common/ActionCommand.cs index 68ded964c..0ed1362ac 100644 --- a/src/Runner.Common/ActionCommand.cs +++ b/src/Runner.Common/ActionCommand.cs @@ -31,7 +31,7 @@ namespace GitHub.Runner.Common new EscapeMapping(token: "%", replacement: "%25"), }; - private readonly Dictionary _properties = new Dictionary(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _properties = new(StringComparer.OrdinalIgnoreCase); public const string Prefix = "##["; public const string _commandKey = "::"; diff --git a/src/Runner.Common/ConfigurationStore.cs b/src/Runner.Common/ConfigurationStore.cs index 7cce70f60..b3cb26a86 100644 --- a/src/Runner.Common/ConfigurationStore.cs +++ b/src/Runner.Common/ConfigurationStore.cs @@ -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('/'); diff --git a/src/Runner.Common/ExtensionManager.cs b/src/Runner.Common/ExtensionManager.cs index 6f1bfc5d7..340b52676 100644 --- a/src/Runner.Common/ExtensionManager.cs +++ b/src/Runner.Common/ExtensionManager.cs @@ -14,7 +14,7 @@ namespace GitHub.Runner.Common public sealed class ExtensionManager : RunnerService, IExtensionManager { - private readonly ConcurrentDictionary> _cache = new ConcurrentDictionary>(); + private readonly ConcurrentDictionary> _cache = new(); public List GetExtensions() where T : class, IExtension { diff --git a/src/Runner.Common/HostContext.cs b/src/Runner.Common/HostContext.cs index e8eab1989..9d5aefdf8 100644 --- a/src/Runner.Common/HostContext.cs +++ b/src/Runner.Common/HostContext.cs @@ -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 _serviceInstances = new ConcurrentDictionary(); - private readonly ConcurrentDictionary _serviceTypes = new ConcurrentDictionary(); + private readonly ConcurrentDictionary _serviceInstances = new(); + private readonly ConcurrentDictionary _serviceTypes = new(); private readonly ISecretMasker _secretMasker = new SecretMasker(); - private readonly List _userAgents = new List() { new ProductInfoHeaderValue($"GitHubActionsRunner-{BuildConstants.RunnerPackage.PackageName}", BuildConstants.RunnerPackage.Version) }; - private CancellationTokenSource _runnerShutdownTokenSource = new CancellationTokenSource(); - private object _perfLock = new object(); + private readonly List _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; diff --git a/src/Runner.Common/HostTraceListener.cs b/src/Runner.Common/HostTraceListener.cs index e022eb0e4..90ef9938a 100644 --- a/src/Runner.Common/HostTraceListener.cs +++ b/src/Runner.Common/HostTraceListener.cs @@ -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) { diff --git a/src/Runner.Common/JobServerQueue.cs b/src/Runner.Common/JobServerQueue.cs index 3da4400a9..d84614c15 100644 --- a/src/Runner.Common/JobServerQueue.cs +++ b/src/Runner.Common/JobServerQueue.cs @@ -39,19 +39,19 @@ namespace GitHub.Runner.Common private Guid _jobTimelineRecordId; // queue for web console line - private readonly ConcurrentQueue _webConsoleLineQueue = new ConcurrentQueue(); + private readonly ConcurrentQueue _webConsoleLineQueue = new(); // queue for file upload (log file or attachment) - private readonly ConcurrentQueue _fileUploadQueue = new ConcurrentQueue(); + private readonly ConcurrentQueue _fileUploadQueue = new(); // queue for timeline or timeline record update (one queue per timeline) - private readonly ConcurrentDictionary> _timelineUpdateQueue = new ConcurrentDictionary>(); + private readonly ConcurrentDictionary> _timelineUpdateQueue = new(); // indicate how many timelines we have, we will process _timelineUpdateQueue base on the order of timeline in this list - private readonly List _allTimelines = new List(); + private readonly List _allTimelines = new(); // bufferd timeline records that fail to update - private readonly Dictionary> _bufferedRetryRecords = new Dictionary>(); + private readonly Dictionary> _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 _jobCompletionSource = new TaskCompletionSource(); - private readonly TaskCompletionSource _jobRecordUpdated = new TaskCompletionSource(); + private readonly TaskCompletionSource _jobCompletionSource = new(); + private readonly TaskCompletionSource _jobRecordUpdated = new(); private bool _queueInProcess = false; public TaskCompletionSource JobRecordUpdated => _jobRecordUpdated; @@ -237,8 +237,8 @@ namespace GitHub.Runner.Common } // Group consolelines by timeline record of each step - Dictionary> stepsConsoleLines = new Dictionary>(); - List stepRecordIds = new List(); // We need to keep lines in order + Dictionary> stepsConsoleLines = new(); + List 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> batchedLines = new List>(); + List> 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 filesToUpload = new List(); + List filesToUpload = new(); UploadFileInfo dequeueFile; while (_fileUploadQueue.TryDequeue(out dequeueFile)) { @@ -398,13 +398,13 @@ namespace GitHub.Runner.Common { while (!_jobCompletionSource.Task.IsCompleted || runOnce) { - List pendingUpdates = new List(); + List pendingUpdates = new(); foreach (var timeline in _allTimelines) { ConcurrentQueue recordQueue; if (_timelineUpdateQueue.TryGetValue(timeline, out recordQueue)) { - List records = new List(); + List 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 mainTimelineRecordsUpdateErrors = new List(); + List mainTimelineRecordsUpdateErrors = new(); if (pendingUpdates.Count > 0) { foreach (var update in pendingUpdates) @@ -529,7 +529,7 @@ namespace GitHub.Runner.Common return timelineRecords; } - Dictionary dict = new Dictionary(); + Dictionary dict = new(); foreach (TimelineRecord rec in timelineRecords) { if (rec == null) diff --git a/src/Runner.Common/ProcessChannel.cs b/src/Runner.Common/ProcessChannel.cs index ca493c962..d0e574681 100644 --- a/src/Runner.Common/ProcessChannel.cs +++ b/src/Runner.Common/ProcessChannel.cs @@ -76,7 +76,7 @@ namespace GitHub.Runner.Common public async Task 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)}'"); diff --git a/src/Runner.Common/ProcessExtensions.cs b/src/Runner.Common/ProcessExtensions.cs index 5e3bbd35b..5ccda3e8a 100644 --- a/src/Runner.Common/ProcessExtensions.cs +++ b/src/Runner.Common/ProcessExtensions.cs @@ -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 env = new Dictionary(); + Dictionary 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 psOut = new List(); - object outputLock = new object(); + List psOut = new(); + object outputLock = new(); using (var p = hostContext.CreateService()) { p.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs stdout) diff --git a/src/Runner.Common/Terminal.cs b/src/Runner.Common/Terminal.cs index cf52d4154..bade576a0 100644 --- a/src/Runner.Common/Terminal.cs +++ b/src/Runner.Common/Terminal.cs @@ -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); diff --git a/src/Runner.Common/TraceManager.cs b/src/Runner.Common/TraceManager.cs index ebbaefa89..f935aaf8b 100644 --- a/src/Runner.Common/TraceManager.cs +++ b/src/Runner.Common/TraceManager.cs @@ -14,7 +14,7 @@ namespace GitHub.Runner.Common public sealed class TraceManager : ITraceManager { - private readonly ConcurrentDictionary _sources = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + private readonly ConcurrentDictionary _sources = new(StringComparer.OrdinalIgnoreCase); private readonly HostTraceListener _hostTraceListener; private TraceSetting _traceSetting; private ISecretMasker _secretMasker; diff --git a/src/Runner.Listener/Checks/CheckUtil.cs b/src/Runner.Listener/Checks/CheckUtil.cs index b2e58b41c..0802e11b0 100644 --- a/src/Runner.Listener/Checks/CheckUtil.cs +++ b/src/Runner.Listener/Checks/CheckUtil.cs @@ -347,8 +347,8 @@ namespace GitHub.Runner.Listener.Check public sealed class HttpEventSourceListener : EventListener { private readonly List _logs; - private readonly object _lock = new object(); - private readonly Dictionary> _ignoredEvent = new Dictionary> + private readonly object _lock = new(); + private readonly Dictionary> _ignoredEvent = new() { { "Microsoft-System-Net-Http", diff --git a/src/Runner.Listener/Checks/NodeJsCheck.cs b/src/Runner.Listener/Checks/NodeJsCheck.cs index 29fb282e0..df750fe8b 100644 --- a/src/Runner.Listener/Checks/NodeJsCheck.cs +++ b/src/Runner.Listener/Checks/NodeJsCheck.cs @@ -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() { { "HOSTNAME", requestUrl.Host }, diff --git a/src/Runner.Listener/CommandSettings.cs b/src/Runner.Listener/CommandSettings.cs index ca0ea1b7d..44039bb5c 100644 --- a/src/Runner.Listener/CommandSettings.cs +++ b/src/Runner.Listener/CommandSettings.cs @@ -11,7 +11,7 @@ namespace GitHub.Runner.Listener { public sealed class CommandSettings { - private readonly Dictionary _envArgs = new Dictionary(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _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 validOptions = new Dictionary + private readonly Dictionary 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 Validate() { - List unknowns = new List(); + List unknowns = new(); // detect unknown commands unknowns.AddRange(_parser.Commands.Where(x => !validOptions.Keys.Contains(x, StringComparer.OrdinalIgnoreCase))); diff --git a/src/Runner.Listener/Configuration/ConfigurationManager.cs b/src/Runner.Listener/Configuration/ConfigurationManager.cs index 410bec8f6..72b574873 100644 --- a/src/Runner.Listener/Configuration/ConfigurationManager.cs +++ b/src/Runner.Listener/Configuration/ConfigurationManager.cs @@ -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 userLabels, bool ephemeral, bool disableUpdate) { - TaskAgent agent = new TaskAgent(agentName) + TaskAgent agent = new(agentName) { Authorization = new TaskAgentAuthorization { diff --git a/src/Runner.Listener/Configuration/CredentialManager.cs b/src/Runner.Listener/Configuration/CredentialManager.cs index e13d29510..327961794 100644 --- a/src/Runner.Listener/Configuration/CredentialManager.cs +++ b/src/Runner.Listener/Configuration/CredentialManager.cs @@ -18,7 +18,7 @@ namespace GitHub.Runner.Listener.Configuration public class CredentialManager : RunnerService, ICredentialManager { - public static readonly Dictionary CredentialTypes = new Dictionary(StringComparer.OrdinalIgnoreCase) + public static readonly Dictionary CredentialTypes = new(StringComparer.OrdinalIgnoreCase) { { Constants.Configuration.OAuth, typeof(OAuthCredential)}, { Constants.Configuration.OAuthAccessToken, typeof(OAuthAccessTokenCredential)}, diff --git a/src/Runner.Listener/Configuration/CredentialProvider.cs b/src/Runner.Listener/Configuration/CredentialProvider.cs index 304c11770..def579a0d 100644 --- a/src/Runner.Listener/Configuration/CredentialProvider.cs +++ b/src/Runner.Listener/Configuration/CredentialProvider.cs @@ -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; diff --git a/src/Runner.Listener/Configuration/ServiceControlManager.cs b/src/Runner.Listener/Configuration/ServiceControlManager.cs index 9349484c5..e8a749484 100644 --- a/src/Runner.Listener/Configuration/ServiceControlManager.cs +++ b/src/Runner.Listener/Configuration/ServiceControlManager.cs @@ -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); diff --git a/src/Runner.Listener/JobDispatcher.cs b/src/Runner.Listener/JobDispatcher.cs index 9b4b2d6f4..1e5306bd0 100644 --- a/src/Runner.Listener/JobDispatcher.cs +++ b/src/Runner.Listener/JobDispatcher.cs @@ -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> _localRunJobResult = new Lazy>(); + private static Regex _invalidJsonRegex = new(@"invalid\ Json\ at\ position\ '(\d+)':", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Lazy> _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 _jobDispatchedQueue = new Queue(); - private readonly ConcurrentDictionary _jobInfos = new ConcurrentDictionary(); + private readonly Queue _jobDispatchedQueue = new(); + private readonly ConcurrentDictionary _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 _runOnceJobCompleted = new TaskCompletionSource(); + private TaskCompletionSource _runOnceJobCompleted = new(); public event EventHandler 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 firstJobRequestRenewed = new TaskCompletionSource(); + TaskCompletionSource firstJobRequestRenewed = new(); var notification = HostContext.GetService(); // lock renew cancellation token. @@ -398,8 +398,8 @@ namespace GitHub.Runner.Listener HostContext.WritePerfCounter($"JobRequestRenewed_{requestId.ToString()}"); Task workerProcessTask = null; - object _outputLock = new object(); - List workerOutput = new List(); + object _outputLock = new(); + List workerOutput = new(); using (var processChannel = HostContext.CreateService()) using (var processInvoker = HostContext.CreateService()) { @@ -936,7 +936,7 @@ namespace GitHub.Runner.Listener var runnerServer = HostContext.GetService(); int completeJobRequestRetryLimit = 5; - List exceptions = new List(); + List 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) { diff --git a/src/Runner.Listener/MessageListener.cs b/src/Runner.Listener/MessageListener.cs index acea728c7..274967ac3 100644 --- a/src/Runner.Listener/MessageListener.cs +++ b/src/Runner.Listener/MessageListener.cs @@ -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 _sessionCreationExceptionTracker = new Dictionary(); + private readonly Dictionary _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) { diff --git a/src/Runner.Listener/Program.cs b/src/Runner.Listener/Program.cs index 1482600ce..d4d5e43eb 100644 --- a/src/Runner.Listener/Program.cs +++ b/src/Runner.Listener/Program.cs @@ -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(); } diff --git a/src/Runner.Listener/Runner.cs b/src/Runner.Listener/Runner.cs index 20235d51d..b6f9946f7 100644 --- a/src/Runner.Listener/Runner.cs +++ b/src/Runner.Listener/Runner.cs @@ -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) { diff --git a/src/Runner.Listener/SelfUpdater.cs b/src/Runner.Listener/SelfUpdater.cs index 07db370f6..23ba0a0cf 100644 --- a/src/Runner.Listener/SelfUpdater.cs +++ b/src/Runner.Listener/SelfUpdater.cs @@ -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 _contentHashes = new Dictionary(); + private readonly Dictionary _contentHashes = new(); private PackageMetadata _targetPackage; private ITerminal _terminal; private IRunnerServer _runnerServer; private int _poolId; private int _agentId; - private readonly ConcurrentQueue _updateTrace = new ConcurrentQueue(); + private readonly ConcurrentQueue _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). diff --git a/src/Runner.PluginHost/Program.cs b/src/Runner.PluginHost/Program.cs index 249613258..1cacb6a28 100644 --- a/src/Runner.PluginHost/Program.cs +++ b/src/Runner.PluginHost/Program.cs @@ -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) diff --git a/src/Runner.Plugins/Artifact/DownloadArtifact.cs b/src/Runner.Plugins/Artifact/DownloadArtifact.cs index 7e5f6e277..81f654cfb 100644 --- a/src/Runner.Plugins/Artifact/DownloadArtifact.cs +++ b/src/Runner.Plugins/Artifact/DownloadArtifact.cs @@ -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."); diff --git a/src/Runner.Plugins/Artifact/FileContainerServer.cs b/src/Runner.Plugins/Artifact/FileContainerServer.cs index c2b8fb3a2..043bc3bec 100644 --- a/src/Runner.Plugins/Artifact/FileContainerServer.cs +++ b/src/Runner.Plugins/Artifact/FileContainerServer.cs @@ -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 _fileUploadQueue = new ConcurrentQueue(); - private readonly ConcurrentQueue _fileDownloadQueue = new ConcurrentQueue(); - private readonly ConcurrentDictionary> _fileUploadTraceLog = new ConcurrentDictionary>(); - private readonly ConcurrentDictionary> _fileUploadProgressLog = new ConcurrentDictionary>(); + private readonly ConcurrentQueue _fileUploadQueue = new(); + private readonly ConcurrentQueue _fileDownloadQueue = new(); + private readonly ConcurrentDictionary> _fileUploadTraceLog = new(); + private readonly ConcurrentDictionary> _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 containerItems = new List(); + List 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 downloadFiles = new List(); + List 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> parallelDownloadingTasks = new List>(); + List> 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> parallelUploadingTasks = new List>(); + List> 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 DownloadAsync(RunnerActionPluginExecutionContext context, int downloaderId, CancellationToken token) { - List failedFiles = new List(); - Stopwatch downloadTimer = new Stopwatch(); + List 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 UploadAsync(RunnerActionPluginExecutionContext context, int uploaderId, CancellationToken token) { - List failedFiles = new List(); + List failedFiles = new(); long uploadedSize = 0; string fileToUpload; - Stopwatch uploadTimer = new Stopwatch(); + Stopwatch uploadTimer = new(); while (_fileUploadQueue.TryDequeue(out fileToUpload)) { token.ThrowIfCancellationRequested(); diff --git a/src/Runner.Plugins/Artifact/PublishArtifact.cs b/src/Runner.Plugins/Artifact/PublishArtifact.cs index 59f9a04a5..19b316fe0 100644 --- a/src/Runner.Plugins/Artifact/PublishArtifact.cs +++ b/src/Runner.Plugins/Artifact/PublishArtifact.cs @@ -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(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, diff --git a/src/Runner.Plugins/Repository/GitCliManager.cs b/src/Runner.Plugins/Repository/GitCliManager.cs index 338e17a6e..cadba0004 100644 --- a/src/Runner.Plugins/Repository/GitCliManager.cs +++ b/src/Runner.Plugins/Repository/GitCliManager.cs @@ -18,7 +18,7 @@ namespace GitHub.Runner.Plugins.Repository #else private static readonly Encoding s_encoding = null; #endif - private readonly Dictionary gitEnv = new Dictionary(StringComparer.OrdinalIgnoreCase) + private readonly Dictionary 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 outputStrings = new List(); + List 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 outputStrings = new List(); + List 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 outputStrings = new List(); + List 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 outputStrings = new List(); + List 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)) { diff --git a/src/Runner.Plugins/Repository/v1.0/GitSourceProvider.cs b/src/Runner.Plugins/Repository/v1.0/GitSourceProvider.cs index f567a1338..a63eaaf3e 100644 --- a/src/Runner.Plugins/Repository/v1.0/GitSourceProvider.cs +++ b/src/Runner.Plugins/Repository/v1.0/GitSourceProvider.cs @@ -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 gitEnv = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary 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 additionalFetchArgs = new List(); - List additionalLfsFetchArgs = new List(); + List additionalFetchArgs = new(); + List 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 additionalFetchSpecs = new List(); + List 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 additionalSubmoduleUpdateArgs = new List(); + List additionalSubmoduleUpdateArgs = new(); if (!string.IsNullOrEmpty(accessToken)) { diff --git a/src/Runner.Plugins/Repository/v1.0/RepositoryPlugin.cs b/src/Runner.Plugins/Repository/v1.0/RepositoryPlugin.cs index df8bd3363..8f7c27df0 100644 --- a/src/Runner.Plugins/Repository/v1.0/RepositoryPlugin.cs +++ b/src/Runner.Plugins/Repository/v1.0/RepositoryPlugin.cs @@ -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) { diff --git a/src/Runner.Plugins/Repository/v1.1/GitSourceProvider.cs b/src/Runner.Plugins/Repository/v1.1/GitSourceProvider.cs index b2f50f458..e138cb1db 100644 --- a/src/Runner.Plugins/Repository/v1.1/GitSourceProvider.cs +++ b/src/Runner.Plugins/Repository/v1.1/GitSourceProvider.cs @@ -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 configModifications = new Dictionary(); + Dictionary 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 gitEnv = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary 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 additionalFetchArgs = new List(); - List additionalLfsFetchArgs = new List(); + List additionalFetchArgs = new(); + List 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 additionalFetchSpecs = new List(); + List 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 additionalSubmoduleUpdateArgs = new List(); + List 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 safeGitConfig = new List(); + List safeGitConfig = new(); var gitConfigContents = File.ReadAllLines(gitConfig); foreach (var line in gitConfigContents) { diff --git a/src/Runner.Sdk/ActionPlugin.cs b/src/Runner.Sdk/ActionPlugin.cs index 0a0f33ab4..35ffa9ab4 100644 --- a/src/Runner.Sdk/ActionPlugin.cs +++ b/src/Runner.Sdk/ActionPlugin.cs @@ -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 _commandEscapeMappings = new Dictionary(StringComparer.OrdinalIgnoreCase) + private Dictionary _commandEscapeMappings = new(StringComparer.OrdinalIgnoreCase) { { ";", "%3B" diff --git a/src/Runner.Sdk/ProcessInvoker.cs b/src/Runner.Sdk/ProcessInvoker.cs index 78a9f2dd2..e303863b5 100644 --- a/src/Runner.Sdk/ProcessInvoker.cs +++ b/src/Runner.Sdk/ProcessInvoker.cs @@ -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 _processExitedCompletionSource = new TaskCompletionSource(); - private readonly CancellationTokenSource _processStandardInWriteCancellationTokenSource = new CancellationTokenSource(); - private readonly ConcurrentQueue _errorData = new ConcurrentQueue(); - private readonly ConcurrentQueue _outputData = new ConcurrentQueue(); + private readonly AsyncManualResetEvent _outputProcessEvent = new(); + private readonly TaskCompletionSource _processExitedCompletionSource = new(); + private readonly CancellationTokenSource _processStandardInWriteCancellationTokenSource = new(); + private readonly ConcurrentQueue _errorData = new(); + private readonly ConcurrentQueue _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 m_tcs = new TaskCompletionSource(); + private volatile TaskCompletionSource m_tcs = new(); public Task WaitAsync() { return m_tcs.Task; } @@ -387,8 +387,8 @@ namespace GitHub.Runner.Sdk private void ProcessOutput() { - List errorData = new List(); - List outputData = new List(); + List errorData = new(); + List outputData = new(); string errorLine; while (_errorData.TryDequeue(out errorLine)) diff --git a/src/Runner.Sdk/RunnerWebProxy.cs b/src/Runner.Sdk/RunnerWebProxy.cs index abe0506b2..516b1dcec 100644 --- a/src/Runner.Sdk/RunnerWebProxy.cs +++ b/src/Runner.Sdk/RunnerWebProxy.cs @@ -23,9 +23,9 @@ namespace GitHub.Runner.Sdk private string _httpsProxyPassword; private string _noProxyString; - private readonly List _noProxyList = new List(); - private readonly HashSet _noProxyUnique = new HashSet(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 _noProxyList = new(); + private readonly HashSet _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; diff --git a/src/Runner.Sdk/Util/IOUtil.cs b/src/Runner.Sdk/Util/IOUtil.cs index 94a674da3..d95698819 100644 --- a/src/Runner.Sdk/Util/IOUtil.cs +++ b/src/Runner.Sdk/Util/IOUtil.cs @@ -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) diff --git a/src/Runner.Sdk/Util/StringUtil.cs b/src/Runner.Sdk/Util/StringUtil.cs index e55fd7f46..3110e7e21 100644 --- a/src/Runner.Sdk/Util/StringUtil.cs +++ b/src/Runner.Sdk/Util/StringUtil.cs @@ -9,7 +9,7 @@ namespace GitHub.Runner.Sdk public static class StringUtil { private static readonly object[] s_defaultFormatArgs = new object[] { null }; - private static Lazy s_serializerSettings = new Lazy(() => + private static Lazy s_serializerSettings = new(() => { var settings = new VssJsonMediaTypeFormatter().SerializerSettings; settings.DateParseHandling = DateParseHandling.None; diff --git a/src/Runner.Sdk/Util/UrlUtil.cs b/src/Runner.Sdk/Util/UrlUtil.cs index 02e35a8f8..4e74c9820 100644 --- a/src/Runner.Sdk/Util/UrlUtil.cs +++ b/src/Runner.Sdk/Util/UrlUtil.cs @@ -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)) diff --git a/src/Runner.Sdk/Util/VssUtil.cs b/src/Runner.Sdk/Util/VssUtil.cs index 2194e28ff..6bfc7f131 100644 --- a/src/Runner.Sdk/Util/VssUtil.cs +++ b/src/Runner.Sdk/Util/VssUtil.cs @@ -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; } diff --git a/src/Runner.Worker/ActionCommandManager.cs b/src/Runner.Worker/ActionCommandManager.cs index e301515da..33fab1f21 100644 --- a/src/Runner.Worker/ActionCommandManager.cs +++ b/src/Runner.Worker/ActionCommandManager.cs @@ -21,9 +21,9 @@ namespace GitHub.Runner.Worker public sealed class ActionCommandManager : RunnerService, IActionCommandManager { private const string _stopCommand = "stop-commands"; - private readonly Dictionary _commandExtensions = new Dictionary(StringComparer.OrdinalIgnoreCase); - private readonly HashSet _registeredCommands = new HashSet(StringComparer.OrdinalIgnoreCase); - private readonly object _commandSerializeLock = new object(); + private readonly Dictionary _commandExtensions = new(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _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, diff --git a/src/Runner.Worker/ActionManager.cs b/src/Runner.Worker/ActionManager.cs index 30e5c3577..49e14e68a 100644 --- a/src/Runner.Worker/ActionManager.cs +++ b/src/Runner.Worker/ActionManager.cs @@ -52,16 +52,16 @@ namespace GitHub.Runner.Worker private const int _defaultCopyBufferSize = 81920; private const string _dotcomApiUrl = "https://api.github.com"; - private readonly Dictionary _cachedActionContainers = new Dictionary(); + private readonly Dictionary _cachedActionContainers = new(); public Dictionary CachedActionContainers => _cachedActionContainers; - private readonly Dictionary> _cachedEmbeddedPreSteps = new Dictionary>(); + private readonly Dictionary> _cachedEmbeddedPreSteps = new(); public Dictionary> CachedEmbeddedPreSteps => _cachedEmbeddedPreSteps; - private readonly Dictionary> _cachedEmbeddedStepIds = new Dictionary>(); + private readonly Dictionary> _cachedEmbeddedStepIds = new(); public Dictionary> CachedEmbeddedStepIds => _cachedEmbeddedStepIds; - private readonly Dictionary> _cachedEmbeddedPostSteps = new Dictionary>(); + private readonly Dictionary> _cachedEmbeddedPostSteps = new(); public Dictionary> CachedEmbeddedPostSteps => _cachedEmbeddedPostSteps; public async Task PrepareActionsAsync(IExecutionContext executionContext, IEnumerable 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)) { diff --git a/src/Runner.Worker/ActionManifestManager.cs b/src/Runner.Worker/ActionManifestManager.cs index a49a8e5eb..1b3f562a7 100644 --- a/src/Runner.Worker/ActionManifestManager.cs +++ b/src/Runner.Worker/ActionManifestManager.cs @@ -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, diff --git a/src/Runner.Worker/ConditionTraceWriter.cs b/src/Runner.Worker/ConditionTraceWriter.cs index 1f98987cc..a298113eb 100644 --- a/src/Runner.Worker/ConditionTraceWriter.cs +++ b/src/Runner.Worker/ConditionTraceWriter.cs @@ -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(); diff --git a/src/Runner.Worker/Container/ContainerInfo.cs b/src/Runner.Worker/Container/ContainerInfo.cs index 32e55eb3c..72cd0ada9 100644 --- a/src/Runner.Worker/Container/ContainerInfo.cs +++ b/src/Runner.Worker/Container/ContainerInfo.cs @@ -15,7 +15,7 @@ namespace GitHub.Runner.Worker.Container private IDictionary _userPortMappings; private List _portMappings; private IDictionary _environmentVariables; - private List _pathMappings = new List(); + private List _pathMappings = new(); public ContainerInfo() { diff --git a/src/Runner.Worker/Container/DockerCommandManager.cs b/src/Runner.Worker/Container/DockerCommandManager.cs index a0c158bdf..64f42f3bb 100644 --- a/src/Runner.Worker/Container/DockerCommandManager.cs +++ b/src/Runner.Worker/Container/DockerCommandManager.cs @@ -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(); 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 output = new List(); + List output = new(); var processInvoker = HostContext.CreateService(); processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { diff --git a/src/Runner.Worker/Container/DockerUtil.cs b/src/Runner.Worker/Container/DockerUtil.cs index 97a53759b..e8b094298 100644 --- a/src/Runner.Worker/Container/DockerUtil.cs +++ b/src/Runner.Worker/Container/DockerUtil.cs @@ -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 ParseDockerPort(IList 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 portMappings = new List(); + List portMappings = new(); foreach (var line in portMappingLines) { Match m = Regex.Match(line, pattern, RegexOptions.None, TimeSpan.FromSeconds(1)); diff --git a/src/Runner.Worker/ContainerOperationProvider.cs b/src/Runner.Worker/ContainerOperationProvider.cs index b0da20471..79cc8cf76 100644 --- a/src/Runner.Worker/ContainerOperationProvider.cs +++ b/src/Runner.Worker/ContainerOperationProvider.cs @@ -354,8 +354,8 @@ namespace GitHub.Runner.Worker { context.Command($"{command} {arg}"); - List outputs = new List(); - object outputLock = new object(); + List outputs = new(); + object outputLock = new(); var processInvoker = HostContext.CreateService(); 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) diff --git a/src/Runner.Worker/ExecutionContext.cs b/src/Runner.Worker/ExecutionContext.cs index 1152f5845..3fe1ee2ac 100644 --- a/src/Runner.Worker/ExecutionContext.cs +++ b/src/Runner.Worker/ExecutionContext.cs @@ -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 _detailRecords = new Dictionary(); - private readonly object _loggerLock = new object(); - private readonly object _matchersLock = new object(); + private readonly TimelineRecord _record = new(); + private readonly Dictionary _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 _forceCompleted = new TaskCompletionSource(); + private TaskCompletionSource _forceCompleted = new(); private bool _throttlingReported = false; // only job level ExecutionContext will track throttling delay. diff --git a/src/Runner.Worker/Expressions/HashFilesFunction.cs b/src/Runner.Worker/Expressions/HashFilesFunction.cs index 572e7b251..290f41239 100644 --- a/src/Runner.Worker/Expressions/HashFilesFunction.cs +++ b/src/Runner.Worker/Expressions/HashFilesFunction.cs @@ -32,7 +32,7 @@ namespace GitHub.Runner.Worker.Expressions string githubWorkspace = workspaceData.Value; bool followSymlink = false; - List patterns = new List(); + List patterns = new(); var firstParameter = true; foreach (var parameter in Parameters) { diff --git a/src/Runner.Worker/GitHubContext.cs b/src/Runner.Worker/GitHubContext.cs index f320705eb..f92850cc6 100644 --- a/src/Runner.Worker/GitHubContext.cs +++ b/src/Runner.Worker/GitHubContext.cs @@ -6,7 +6,7 @@ namespace GitHub.Runner.Worker { public sealed class GitHubContext : DictionaryContextData, IEnvironmentContextData { - private readonly HashSet _contextEnvAllowlist = new HashSet(StringComparer.OrdinalIgnoreCase) + private readonly HashSet _contextEnvAllowlist = new(StringComparer.OrdinalIgnoreCase) { "action_path", "action_ref", diff --git a/src/Runner.Worker/Handlers/OutputManager.cs b/src/Runner.Worker/Handlers/OutputManager.cs index a67e35e21..8b97c867d 100644 --- a/src/Runner.Worker/Handlers/OutputManager.cs +++ b/src/Runner.Worker/Handlers/OutputManager.cs @@ -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(); // Mapping that indicates whether a directory belongs to the workflow repository - private readonly Dictionary _directoryMap = new Dictionary(); + private readonly Dictionary _directoryMap = new(); public OutputManager(IExecutionContext executionContext, IActionCommandManager commandManager, ContainerInfo container = null) { diff --git a/src/Runner.Worker/Handlers/ScriptHandlerHelpers.cs b/src/Runner.Worker/Handlers/ScriptHandlerHelpers.cs index 159a028f9..9a22c7590 100644 --- a/src/Runner.Worker/Handlers/ScriptHandlerHelpers.cs +++ b/src/Runner.Worker/Handlers/ScriptHandlerHelpers.cs @@ -10,7 +10,7 @@ namespace GitHub.Runner.Worker.Handlers { internal static class ScriptHandlerHelpers { - private static readonly Dictionary _defaultArguments = new Dictionary(StringComparer.OrdinalIgnoreCase) + private static readonly Dictionary _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 _extensions = new Dictionary(StringComparer.OrdinalIgnoreCase) + private static readonly Dictionary _extensions = new(StringComparer.OrdinalIgnoreCase) { ["cmd"] = ".cmd", ["pwsh"] = ".ps1", diff --git a/src/Runner.Worker/JobExtension.cs b/src/Runner.Worker/JobExtension.cs index 14004ecaf..58e1b1137 100644 --- a/src/Runner.Worker/JobExtension.cs +++ b/src/Runner.Worker/JobExtension.cs @@ -39,10 +39,10 @@ namespace GitHub.Runner.Worker public sealed class JobExtension : RunnerService, IJobExtension { - private readonly HashSet _existingProcesses = new HashSet(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _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 preJobSteps = new List(); - List jobSteps = new List(); + List preJobSteps = new(); + List jobSteps = new(); using (var register = jobContext.CancellationToken.Register(() => { context.CancelToken(); })) { try @@ -386,7 +386,7 @@ namespace GitHub.Runner.Worker data: (object)jobHookData)); } - List steps = new List(); + List steps = new(); steps.AddRange(preJobSteps); steps.AddRange(jobSteps); @@ -674,7 +674,7 @@ namespace GitHub.Runner.Worker private Dictionary SnapshotProcesses() { - Dictionary snapshot = new Dictionary(); + Dictionary snapshot = new(); foreach (var proc in Process.GetProcesses()) { try diff --git a/src/Runner.Worker/Program.cs b/src/Runner.Worker/Program.cs index 4f5cf68bd..c4f23f943 100644 --- a/src/Runner.Worker/Program.cs +++ b/src/Runner.Worker/Program.cs @@ -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(); } diff --git a/src/Runner.Worker/RunnerPluginManager.cs b/src/Runner.Worker/RunnerPluginManager.cs index 78f7ff38f..f10348285 100644 --- a/src/Runner.Worker/RunnerPluginManager.cs +++ b/src/Runner.Worker/RunnerPluginManager.cs @@ -26,7 +26,7 @@ namespace GitHub.Runner.Worker public sealed class RunnerPluginManager : RunnerService, IRunnerPluginManager { - private readonly Dictionary _actionPlugins = new Dictionary(StringComparer.OrdinalIgnoreCase) + private readonly Dictionary _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, diff --git a/src/Runner.Worker/StepsContext.cs b/src/Runner.Worker/StepsContext.cs index fe9672537..5dcf258b4 100644 --- a/src/Runner.Worker/StepsContext.cs +++ b/src/Runner.Worker/StepsContext.cs @@ -16,8 +16,8 @@ namespace GitHub.Runner.Worker /// 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(); /// /// Clears memory for a composite action's isolated "steps" context, after the action diff --git a/src/Runner.Worker/TrackingManager.cs b/src/Runner.Worker/TrackingManager.cs index b5eb7c875..cb3ead6c9 100644 --- a/src/Runner.Worker/TrackingManager.cs +++ b/src/Runner.Worker/TrackingManager.cs @@ -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; } diff --git a/src/Runner.Worker/Variables.cs b/src/Runner.Worker/Variables.cs index fb8458475..3284bb7e1 100644 --- a/src/Runner.Worker/Variables.cs +++ b/src/Runner.Worker/Variables.cs @@ -14,9 +14,9 @@ namespace GitHub.Runner.Worker public sealed class Variables { private readonly IHostContext _hostContext; - private readonly ConcurrentDictionary _variables = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + private readonly ConcurrentDictionary _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 AllVariables @@ -43,7 +43,7 @@ namespace GitHub.Runner.Worker } // Initialize the variable dictionary. - List variables = new List(); + List variables = new(); foreach (var variable in copy) { if (!string.IsNullOrWhiteSpace(variable.Key)) diff --git a/src/Runner.Worker/Worker.cs b/src/Runner.Worker/Worker.cs index b26ae9451..4784c1693 100644 --- a/src/Runner.Worker/Worker.cs +++ b/src/Runner.Worker/Worker.cs @@ -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 SecretVariableMaskWhitelist = new HashSet(StringComparer.OrdinalIgnoreCase) + private static HashSet SecretVariableMaskWhitelist = new(StringComparer.OrdinalIgnoreCase) { Constants.Variables.Actions.StepDebug, Constants.Variables.Actions.RunnerDebug diff --git a/src/Test/L0/CommandLineParserL0.cs b/src/Test/L0/CommandLineParserL0.cs index 074660fe7..19ab497fa 100644 --- a/src/Test/L0/CommandLineParserL0.cs +++ b/src/Test/L0/CommandLineParserL0.cs @@ -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; } } diff --git a/src/Test/L0/ConstantGenerationL0.cs b/src/Test/L0/ConstantGenerationL0.cs index f2ad6ab23..204248516 100644 --- a/src/Test/L0/ConstantGenerationL0.cs +++ b/src/Test/L0/ConstantGenerationL0.cs @@ -12,7 +12,7 @@ namespace GitHub.Runner.Common.Tests [Trait("Category", "Runner")] public void BuildConstantGenerateSucceed() { - List validPackageNames = new List() + List validPackageNames = new() { "win-x64", "win-x86", diff --git a/src/Test/L0/Container/ContainerInfoL0.cs b/src/Test/L0/Container/ContainerInfoL0.cs index 5873652ad..6dd74d42c 100644 --- a/src/Test/L0/Container/ContainerInfoL0.cs +++ b/src/Test/L0/Container/ContainerInfoL0.cs @@ -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); diff --git a/src/Test/L0/DotnetsdkDownloadScriptL0.cs b/src/Test/L0/DotnetsdkDownloadScriptL0.cs index ea81d6ace..9d3fbd26c 100644 --- a/src/Test/L0/DotnetsdkDownloadScriptL0.cs +++ b/src/Test/L0/DotnetsdkDownloadScriptL0.cs @@ -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) diff --git a/src/Test/L0/ExtensionManagerL0.cs b/src/Test/L0/ExtensionManagerL0.cs index 37eb7e657..98207ab59 100644 --- a/src/Test/L0/ExtensionManagerL0.cs +++ b/src/Test/L0/ExtensionManagerL0.cs @@ -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(); diff --git a/src/Test/L0/Listener/CommandSettingsL0.cs b/src/Test/L0/Listener/CommandSettingsL0.cs index 014ed5a72..249d05089 100644 --- a/src/Test/L0/Listener/CommandSettingsL0.cs +++ b/src/Test/L0/Listener/CommandSettingsL0.cs @@ -9,7 +9,7 @@ namespace GitHub.Runner.Common.Tests { public sealed class CommandSettingsL0 { - private readonly Mock _promptManager = new Mock(); + private readonly Mock _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(_promptManager.Object); return hc; } diff --git a/src/Test/L0/Listener/Configuration/ArgumentValidatorTestsL0.cs b/src/Test/L0/Listener/Configuration/ArgumentValidatorTestsL0.cs index 6f3a62d62..68128a645 100644 --- a/src/Test/L0/Listener/Configuration/ArgumentValidatorTestsL0.cs +++ b/src/Test/L0/Listener/Configuration/ArgumentValidatorTestsL0.cs @@ -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)); diff --git a/src/Test/L0/Listener/Configuration/ConfigurationManagerL0.cs b/src/Test/L0/Listener/Configuration/ConfigurationManagerL0.cs index 20ec96a78..a3fdd5603 100644 --- a/src/Test/L0/Listener/Configuration/ConfigurationManagerL0.cs +++ b/src/Test/L0/Listener/Configuration/ConfigurationManagerL0.cs @@ -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(_credMgr.Object); tc.SetSingleton(_promptManager.Object); tc.SetSingleton(_store.Object); diff --git a/src/Test/L0/Listener/Configuration/PromptManagerTestsL0.cs b/src/Test/L0/Listener/Configuration/PromptManagerTestsL0.cs index cfc8e03a3..286fc0edb 100644 --- a/src/Test/L0/Listener/Configuration/PromptManagerTestsL0.cs +++ b/src/Test/L0/Listener/Configuration/PromptManagerTestsL0.cs @@ -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 _terminal = new Mock(); + private readonly PromptManager _promptManager = new(); + private readonly Mock _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(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(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 diff --git a/src/Test/L0/Listener/Configuration/RunnerCredentialL0.cs b/src/Test/L0/Listener/Configuration/RunnerCredentialL0.cs index 57aa88dce..a838aa537 100644 --- a/src/Test/L0/Listener/Configuration/RunnerCredentialL0.cs +++ b/src/Test/L0/Listener/Configuration/RunnerCredentialL0.cs @@ -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; diff --git a/src/Test/L0/Listener/JobDispatcherL0.cs b/src/Test/L0/Listener/JobDispatcherL0.cs index f06005f13..f1a74d5fe 100644 --- a/src/Test/L0/Listener/JobDispatcherL0.cs +++ b/src/Test/L0/Listener/JobDispatcherL0.cs @@ -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(), new List(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List(), null, null, null, null); @@ -101,10 +101,10 @@ namespace GitHub.Runner.Common.Tests.Listener int count = 0; var trace = hc.GetTrace(nameof(DispatcherRenewJobRequest)); - TaskCompletionSource firstJobRequestRenewed = new TaskCompletionSource(); - CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + TaskCompletionSource 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 firstJobRequestRenewed = new TaskCompletionSource(); - CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + TaskCompletionSource 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 firstJobRequestRenewed = new TaskCompletionSource(); - CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + TaskCompletionSource 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 firstJobRequestRenewed = new TaskCompletionSource(); - CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + TaskCompletionSource firstJobRequestRenewed = new(); + CancellationTokenSource cancellationTokenSource = new(); var request = new Mock(); 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 firstJobRequestRenewed = new TaskCompletionSource(); - CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + TaskCompletionSource firstJobRequestRenewed = new(); + CancellationTokenSource cancellationTokenSource = new(); var request = new Mock(); 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 firstJobRequestRenewed = new TaskCompletionSource(); - CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + TaskCompletionSource firstJobRequestRenewed = new(); + CancellationTokenSource cancellationTokenSource = new(); var request = new Mock(); 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 firstJobRequestRenewed = new TaskCompletionSource(); - CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + TaskCompletionSource 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 firstJobRequestRenewed = new TaskCompletionSource(); - CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + TaskCompletionSource 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 firstJobRequestRenewed = new TaskCompletionSource(); - CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + TaskCompletionSource 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)); diff --git a/src/Test/L0/Listener/MessageListenerL0.cs b/src/Test/L0/Listener/MessageListenerL0.cs index 09725a1a3..8ce1dfe0f 100644 --- a/src/Test/L0/Listener/MessageListenerL0.cs +++ b/src/Test/L0/Listener/MessageListenerL0.cs @@ -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(_config.Object); tc.SetSingleton(_runnerServer.Object); tc.SetSingleton(_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); diff --git a/src/Test/L0/Listener/RunnerL0.cs b/src/Test/L0/Listener/RunnerL0.cs index a1c283a9f..f35f7e766 100644 --- a/src/Test/L0/Listener/RunnerL0.cs +++ b/src/Test/L0/Listener/RunnerL0.cs @@ -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(), new List(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List(), null, null, null, null); @@ -155,7 +155,7 @@ namespace GitHub.Runner.Common.Tests.Listener } } - public static TheoryData RunAsServiceTestData = new TheoryData() + public static TheoryData RunAsServiceTestData = new() { // staring with run command, configured as run as service, should start the runner { new [] { "run" }, true, Times.Once() }, diff --git a/src/Test/L0/Listener/SelfUpdaterL0.cs b/src/Test/L0/Listener/SelfUpdaterL0.cs index 43afdae43..1bf450366 100644 --- a/src/Test/L0/Listener/SelfUpdaterL0.cs +++ b/src/Test/L0/Listener/SelfUpdaterL0.cs @@ -22,8 +22,8 @@ namespace GitHub.Runner.Common.Tests.Listener private Mock _term; private Mock _configStore; private Mock _jobDispatcher; - private AgentRefreshMessage _refreshMessage = new AgentRefreshMessage(1, "2.299.0"); - private List _trimmedPackages = new List(); + private AgentRefreshMessage _refreshMessage = new(1, "2.299.0"); + private List _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(?\d+\.\d+\.\d+)"); + Regex regex = new(@"/runner/releases/tag/v(?\d+\.\d+\.\d+)"); var match = regex.Match(redirectUrl); if (match.Success) { diff --git a/src/Test/L0/PackagesTrimL0.cs b/src/Test/L0/PackagesTrimL0.cs index 391e85745..da3a44a0c 100644 --- a/src/Test/L0/PackagesTrimL0.cs +++ b/src/Test/L0/PackagesTrimL0.cs @@ -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}"); diff --git a/src/Test/L0/PagingLoggerL0.cs b/src/Test/L0/PagingLoggerL0.cs index 799428aa6..5317b4f99 100644 --- a/src/Test/L0/PagingLoggerL0.cs +++ b/src/Test/L0/PagingLoggerL0.cs @@ -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); diff --git a/src/Test/L0/ProcessExtensionL0.cs b/src/Test/L0/ProcessExtensionL0.cs index 1fd01e304..9708c1495 100644 --- a/src/Test/L0/ProcessExtensionL0.cs +++ b/src/Test/L0/ProcessExtensionL0.cs @@ -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(); diff --git a/src/Test/L0/ProcessInvokerL0.cs b/src/Test/L0/ProcessInvokerL0.cs index 11dcf8d2a..d3d1b5486 100644 --- a/src/Test/L0/ProcessInvokerL0.cs +++ b/src/Test/L0/ProcessInvokerL0.cs @@ -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 redirectSTDIN = Channel.CreateUnbounded(new UnboundedChannelOptions() { SingleReader = true, SingleWriter = true }); - List stdout = new List(); + List 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 redirectSTDIN = Channel.CreateUnbounded(new UnboundedChannelOptions() { SingleReader = true, SingleWriter = true }); - List stdout = new List(); + List 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(); diff --git a/src/Test/L0/RunnerWebProxyL0.cs b/src/Test/L0/RunnerWebProxyL0.cs index 621dbd96f..649f06197 100644 --- a/src/Test/L0/RunnerWebProxyL0.cs +++ b/src/Test/L0/RunnerWebProxyL0.cs @@ -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 SkippedFiles = new List() + 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 SkippedFiles = new() { "Runner.Common\\HostContext.cs", "Runner.Common/HostContext.cs", @@ -39,7 +39,7 @@ namespace GitHub.Runner.Common.Tests "*.cs", SearchOption.AllDirectories)); - List badCode = new List(); + List badCode = new(); foreach (string sourceFile in sourceFiles) { // Skip skipped files. @@ -86,7 +86,7 @@ namespace GitHub.Runner.Common.Tests "*.cs", SearchOption.AllDirectories)); - List badCode = new List(); + List badCode = new(); foreach (string sourceFile in sourceFiles) { // Skip skipped files. diff --git a/src/Test/L0/ServiceControlManagerL0.cs b/src/Test/L0/ServiceControlManagerL0.cs index f94ded572..4d5ab5434 100644 --- a/src/Test/L0/ServiceControlManagerL0.cs +++ b/src/Test/L0/ServiceControlManagerL0.cs @@ -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; } diff --git a/src/Test/L0/TestHostContext.cs b/src/Test/L0/TestHostContext.cs index ce1ec01bc..a88b9170e 100644 --- a/src/Test/L0/TestHostContext.cs +++ b/src/Test/L0/TestHostContext.cs @@ -17,12 +17,12 @@ namespace GitHub.Runner.Common.Tests { public sealed class TestHostContext : IHostContext, IDisposable { - private readonly ConcurrentDictionary> _serviceInstances = new ConcurrentDictionary>(); - private readonly ConcurrentDictionary _serviceSingletons = new ConcurrentDictionary(); + private readonly ConcurrentDictionary> _serviceInstances = new(); + private readonly ConcurrentDictionary _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 UserAgents => new List() { new ProductInfoHeaderValue("L0Test", "0.0") }; + public List UserAgents => new() { new ProductInfoHeaderValue("L0Test", "0.0") }; - public RunnerWebProxy WebProxy => new RunnerWebProxy(); + public RunnerWebProxy WebProxy => new(); public async Task Delay(TimeSpan delay, CancellationToken token) { diff --git a/src/Test/L0/Util/ArgUtilL0.cs b/src/Test/L0/Util/ArgUtilL0.cs index e0e0b3454..5dd29de8e 100644 --- a/src/Test/L0/Util/ArgUtilL0.cs +++ b/src/Test/L0/Util/ArgUtilL0.cs @@ -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(() => @@ -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(() => @@ -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(); diff --git a/src/Test/L0/Util/IOUtilL0.cs b/src/Test/L0/Util/IOUtilL0.cs index 6a990c789..6a504d192 100644 --- a/src/Test/L0/Util/IOUtilL0.cs +++ b/src/Test/L0/Util/IOUtilL0.cs @@ -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(); diff --git a/src/Test/L0/Util/StringUtilL0.cs b/src/Test/L0/Util/StringUtilL0.cs index c67b3922d..e66181874 100644 --- a/src/Test/L0/Util/StringUtilL0.cs +++ b/src/Test/L0/Util/StringUtilL0.cs @@ -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"; diff --git a/src/Test/L0/Util/TaskResultUtilL0.cs b/src/Test/L0/Util/TaskResultUtilL0.cs index b12d07c6a..331e71555 100644 --- a/src/Test/L0/Util/TaskResultUtilL0.cs +++ b/src/Test/L0/Util/TaskResultUtilL0.cs @@ -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; diff --git a/src/Test/L0/Util/VssUtilL0.cs b/src/Test/L0/Util/VssUtilL0.cs index 30ed85692..2965dcc06 100644 --- a/src/Test/L0/Util/VssUtilL0.cs +++ b/src/Test/L0/Util/VssUtilL0.cs @@ -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(); diff --git a/src/Test/L0/Util/WhichUtilL0.cs b/src/Test/L0/Util/WhichUtilL0.cs index 7271bc283..c6a057144 100644 --- a/src/Test/L0/Util/WhichUtilL0.cs +++ b/src/Test/L0/Util/WhichUtilL0.cs @@ -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(); diff --git a/src/Test/L0/Worker/ActionCommandL0.cs b/src/Test/L0/Worker/ActionCommandL0.cs index 4429976f2..314c437fa 100644 --- a/src/Test/L0/Worker/ActionCommandL0.cs +++ b/src/Test/L0/Worker/ActionCommandL0.cs @@ -18,7 +18,7 @@ namespace GitHub.Runner.Common.Tests.Worker string message; ActionCommand test; ActionCommand verify; - HashSet commands = new HashSet() { "do-something" }; + HashSet 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 commands = new HashSet() { "do-something" }; + HashSet commands = new() { "do-something" }; //::do-something k1=v1;]msg message = "::do-something k1=v1,::msg"; test = new ActionCommand("do-something") diff --git a/src/Test/L0/Worker/ActionCommandManagerL0.cs b/src/Test/L0/Worker/ActionCommandManagerL0.cs index cc74397e2..cef826fd9 100644 --- a/src/Test/L0/Worker/ActionCommandManagerL0.cs +++ b/src/Test/L0/Worker/ActionCommandManagerL0.cs @@ -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(), new List(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List(), null, null, null, null); diff --git a/src/Test/L0/Worker/ActionManagerL0.cs b/src/Test/L0/Worker/ActionManagerL0.cs index 971d051ca..07cf9b487 100644 --- a/src/Test/L0/Worker/ActionManagerL0.cs +++ b/src/Test/L0/Worker/ActionManagerL0.cs @@ -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 inputDefaults = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary 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 inputDefaults = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary 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 inputDefaults = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary 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 inputDefaults = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary 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 inputDefaults = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary 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 inputDefaults = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary 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 inputDefaults = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary 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 inputDefaults = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary 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 inputDefaults = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary 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 inputDefaults = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary 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 inputDefaults = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary inputDefaults = new(StringComparer.OrdinalIgnoreCase); foreach (var input in definition.Data.Inputs) { var name = input.Key.AssertString("key").Value; diff --git a/src/Test/L0/Worker/ActionRunnerL0.cs b/src/Test/L0/Worker/ActionRunnerL0.cs index 1f77e1114..31d074365 100644 --- a/src/Test/L0/Worker/ActionRunnerL0.cs +++ b/src/Test/L0/Worker/ActionRunnerL0.cs @@ -34,7 +34,7 @@ namespace GitHub.Runner.Common.Tests.Worker private IActionManifestManager _actionManifestManager; private Mock _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 finialInputs = new Dictionary(); + Dictionary finialInputs = new(); _handlerFactory.Setup(x => x.Create(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny>())) .Callback((IExecutionContext executionContext, Pipelines.ActionStepDefinitionReference actionReference, IStepHost stepHost, ActionExecutionData data, Dictionary inputs, Dictionary environment, Variables runtimeVariables, string taskDirectory, List localActionContainerSetupSteps) => { @@ -106,7 +106,7 @@ namespace GitHub.Runner.Common.Tests.Worker _actionRunner.Action = action; - Dictionary finialInputs = new Dictionary(); + Dictionary finialInputs = new(); _handlerFactory.Setup(x => x.Create(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny>())) .Callback((IExecutionContext executionContext, Pipelines.ActionStepDefinitionReference actionReference, IStepHost stepHost, ActionExecutionData data, Dictionary inputs, Dictionary environment, Variables runtimeVariables, string taskDirectory, List localActionContainerSetupSteps) => { @@ -307,7 +307,7 @@ namespace GitHub.Runner.Common.Tests.Worker _actionRunner.Action = action; - Dictionary finialInputs = new Dictionary(); + Dictionary finialInputs = new(); _handlerFactory.Setup(x => x.Create(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny>())) .Callback((IExecutionContext executionContext, Pipelines.ActionStepDefinitionReference actionReference, IStepHost stepHost, ActionExecutionData data, Dictionary inputs, Dictionary environment, Variables runtimeVariables, string taskDirectory, List localActionContainerSetupSteps) => { @@ -358,7 +358,7 @@ namespace GitHub.Runner.Common.Tests.Worker _actionRunner.Action = action; - Dictionary finialInputs = new Dictionary(); + Dictionary finialInputs = new(); _handlerFactory.Setup(x => x.Create(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny>())) .Callback((IExecutionContext executionContext, Pipelines.ActionStepDefinitionReference actionReference, IStepHost stepHost, ActionExecutionData data, Dictionary inputs, Dictionary environment, Variables runtimeVariables, string taskDirectory, List localActionContainerSetupSteps) => { diff --git a/src/Test/L0/Worker/ContainerOperationProviderL0.cs b/src/Test/L0/Worker/ContainerOperationProviderL0.cs index e0819511b..1cec0d4da 100644 --- a/src/Test/L0/Worker/ContainerOperationProviderL0.cs +++ b/src/Test/L0/Worker/ContainerOperationProviderL0.cs @@ -22,12 +22,12 @@ namespace GitHub.Runner.Common.Tests.Worker private ContainerOperationProvider containerOperationProvider; private Mock serverQueue; private Mock pagingLogger; - private List healthyDockerStatus = new List { "healthy" }; - private List emptyDockerStatus = new List { string.Empty }; - private List unhealthyDockerStatus = new List { "unhealthy" }; - private List dockerLogs = new List { "log1", "log2", "log3" }; + private List healthyDockerStatus = new() { "healthy" }; + private List emptyDockerStatus = new() { string.Empty }; + private List unhealthyDockerStatus = new() { "unhealthy" }; + private List dockerLogs = new() { "log1", "log2", "log3" }; - List containers = new List(); + List containers = new(); [Fact] [Trait("Level", "L0")] diff --git a/src/Test/L0/Worker/CreateStepSummaryCommandL0.cs b/src/Test/L0/Worker/CreateStepSummaryCommandL0.cs index 46fe52608..67631ed4b 100644 --- a/src/Test/L0/Worker/CreateStepSummaryCommandL0.cs +++ b/src/Test/L0/Worker/CreateStepSummaryCommandL0.cs @@ -189,8 +189,8 @@ namespace GitHub.Runner.Common.Tests.Worker _issues = new List>(); // 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(), new List(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List(), null, null, null, null); diff --git a/src/Test/L0/Worker/ExecutionContextL0.cs b/src/Test/L0/Worker/ExecutionContextL0.cs index 670fece20..937d964e8 100644 --- a/src/Test/L0/Worker/ExecutionContextL0.cs +++ b/src/Test/L0/Worker/ExecutionContextL0.cs @@ -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(), new List(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List(), 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(), new List(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List(), 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(), new List(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List(), 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(), new List(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List(), 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(), new List(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List(), 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(), new List(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List(), 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(), new List(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List(), 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(), new List(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List(), 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(), new List(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List(), 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(), new List(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List(), 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(), new List(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List(), 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(), new List(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List(), null, null, null, null); diff --git a/src/Test/L0/Worker/HandlerFactoryL0.cs b/src/Test/L0/Worker/HandlerFactoryL0.cs index f046d9803..18cf8e8ff 100644 --- a/src/Test/L0/Worker/HandlerFactoryL0.cs +++ b/src/Test/L0/Worker/HandlerFactoryL0.cs @@ -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(); diff --git a/src/Test/L0/Worker/JobExtensionL0.cs b/src/Test/L0/Worker/JobExtensionL0.cs index e3955c653..ce7dca1a5 100644 --- a/src/Test/L0/Worker/JobExtensionL0.cs +++ b/src/Test/L0/Worker/JobExtensionL0.cs @@ -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 steps = new List() + List 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(), new List(), 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); diff --git a/src/Test/L0/Worker/JobRunnerL0.cs b/src/Test/L0/Worker/JobRunnerL0.cs index 1bb7f1ac0..152c816aa 100644 --- a/src/Test/L0/Worker/JobRunnerL0.cs +++ b/src/Test/L0/Worker/JobRunnerL0.cs @@ -15,7 +15,7 @@ namespace GitHub.Runner.Common.Tests.Worker { private IExecutionContext _jobEc; private JobRunner _jobRunner; - private List _initResult = new List(); + private List _initResult = new(); private Pipelines.AgentJobRequestMessage _message; private CancellationTokenSource _tokenSource; private Mock _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(), new List(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List(), null, null, null, null); diff --git a/src/Test/L0/Worker/PipelineDirectoryManagerL0.cs b/src/Test/L0/Worker/PipelineDirectoryManagerL0.cs index 4cc6d4bca..d2ad4a89e 100644 --- a/src/Test/L0/Worker/PipelineDirectoryManagerL0.cs +++ b/src/Test/L0/Worker/PipelineDirectoryManagerL0.cs @@ -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(); _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. diff --git a/src/Test/L0/Worker/StepsRunnerL0.cs b/src/Test/L0/Worker/StepsRunnerL0.cs index e090dd1c0..3ff1e304a 100644 --- a/src/Test/L0/Worker/StepsRunnerL0.cs +++ b/src/Test/L0/Worker/StepsRunnerL0.cs @@ -27,7 +27,7 @@ namespace GitHub.Runner.Common.Tests.Worker private TestHostContext CreateTestContext([CallerMemberName] String testName = "") { var hc = new TestHostContext(this, testName); - Dictionary variablesToCopy = new Dictionary(); + Dictionary variablesToCopy = new(); _variables = new Variables( hostContext: hc, copy: variablesToCopy); diff --git a/src/Test/L0/Worker/TrackingManagerL0.cs b/src/Test/L0/Worker/TrackingManagerL0.cs index 8b2c1bffc..a01694337 100644 --- a/src/Test/L0/Worker/TrackingManagerL0.cs +++ b/src/Test/L0/Worker/TrackingManagerL0.cs @@ -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(); - 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. diff --git a/src/Test/L0/Worker/VariablesL0.cs b/src/Test/L0/Worker/VariablesL0.cs index 5b7d50b4d..9c9d24538 100644 --- a/src/Test/L0/Worker/VariablesL0.cs +++ b/src/Test/L0/Worker/VariablesL0.cs @@ -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 @@ -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 @@ -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 @@ -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 @@ -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()); @@ -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()); @@ -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()); diff --git a/src/Test/L0/Worker/WorkerL0.cs b/src/Test/L0/Worker/WorkerL0.cs index 80e5eaa0a..fe1f9c02c 100644 --- a/src/Test/L0/Worker/WorkerL0.cs +++ b/src/Test/L0/Worker/WorkerL0.cs @@ -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 variables = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary 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 actions = new List(); + List actions = new(); actions.Add(new Pipelines.ActionStep() { Id = Guid.NewGuid(),