From df73f63078a69b4f1914c6753c37b8c965c8f176 Mon Sep 17 00:00:00 2001 From: Konstantin Tyukalov <52399739+KonstantinTyukalov@users.noreply.github.com> Date: Mon, 26 Dec 2022 17:43:33 +0400 Subject: [PATCH] Format agent source code (#4101) * Run dotnet format * Remove extra semicolons --- src/Agent.Listener/CommandSettings.cs | 10 +- .../AutoLogonRegistryManager.cs | 26 ++-- .../WindowsRegistryManager.cs | 18 +-- .../WindowsServiceControlManager.cs | 4 +- .../Configuration/ConfigurationManager.cs | 30 ++-- .../Configuration/ConfigurationProvider.cs | 8 +- .../Configuration/CredentialManager.cs | 10 +- .../Configuration/ServiceControlManager.cs | 2 +- .../Configuration/Validators.cs | 2 +- src/Agent.Listener/Diagnostics/DiskInfo.cs | 6 +- .../Diagnostics/FolderPermissionInfo.cs | 4 +- .../Yaml/Contracts/DeploymentTarget.cs | 2 +- .../Yaml/Contracts/QueueTarget.cs | 2 +- .../Yaml/Contracts/ServerTarget.cs | 2 +- .../Yaml/PipelineParser.cs | 8 +- .../TypeConverters/ConverterUtil.processes.cs | 2 +- src/Agent.Listener/SelfUpdater.cs | 3 +- .../Artifact/ArtifactItemFilters.cs | 2 +- .../Artifact/FileContainerProvider.cs | 12 +- .../Artifact/FileShareProvider.cs | 18 +-- .../Artifact/PipelineArtifactProvider.cs | 6 +- .../Artifact/PipelineArtifactServer.cs | 30 ++-- src/Agent.Plugins/ArtifactsTracer.cs | 2 +- .../BuildArtifact/BuildArtifactPluginV1.cs | 22 +-- src/Agent.Plugins/GitCliManager.cs | 5 +- src/Agent.Plugins/GitSourceProvider.cs | 2 +- .../PipelineArtifact/FilePathServer.cs | 8 +- .../PipelineArtifactPlugin.cs | 5 +- .../PipelineArtifactPluginUtil.cs | 3 +- .../PipelineArtifactPluginV2.cs | 25 ++-- .../Telemetry/FileShareActionRecord.cs | 2 +- .../PipelineCache/FingerprintCreator.cs | 72 +++++----- .../PipelineCache/PipelineCacheServer.cs | 12 +- .../PipelineCacheTaskPluginBase.cs | 32 +++-- .../PipelineCache/RestorePipelineCacheV0.cs | 6 +- .../PipelineCache/SavePipelineCacheV0.cs | 12 +- src/Agent.Plugins/PipelineCache/TarUtils.cs | 19 +-- src/Agent.Plugins/RepositoryPlugin.cs | 3 +- .../Gateway/LogParserGateway.cs | 4 +- .../PipelineTestRunPublisher.cs | 6 +- .../Plugin/TestResultLogPlugin.cs | 2 +- src/Agent.Plugins/TfsVCCliManager.cs | 10 +- src/Agent.Sdk/CommandStringConvertor.cs | 2 +- src/Agent.Sdk/ContainerInfo.cs | 13 +- src/Agent.Sdk/Knob/Knob.cs | 8 +- src/Agent.Sdk/Knob/KnobValue.cs | 2 +- src/Agent.Sdk/MountVolume.cs | 4 +- src/Agent.Sdk/ProcessInvoker.cs | 6 +- src/Agent.Sdk/ScopedEnvironment.cs | 8 +- src/Agent.Sdk/Util/ExceptionsUtil.cs | 6 +- src/Agent.Sdk/Util/IOUtil.cs | 2 +- src/Agent.Sdk/Util/PlatformUtil.cs | 11 +- src/Agent.Sdk/Util/RepositoryUtil.cs | 4 +- src/Agent.Sdk/Util/TeeUtil.cs | 9 +- src/Agent.Sdk/Util/VssUtil.cs | 4 +- src/Agent.Service/Windows/Program.cs | 2 +- src/Agent.Worker/AgentPluginManager.cs | 2 +- .../Build/ArtifactCommandExtension.cs | 6 +- src/Agent.Worker/Build/BuildJobExtension.cs | 4 +- src/Agent.Worker/Build/FileContainerServer.cs | 4 +- src/Agent.Worker/Build/GitCommandManager.cs | 5 +- src/Agent.Worker/Build/GitSourceProvider.cs | 3 +- src/Agent.Worker/Build/TrackingConfig.cs | 2 +- .../Build/WorkspaceMaintenanceProvider.cs | 2 +- .../CodeCoverage/CodeCoverageCommands.cs | 8 +- .../Container/DockerCommandManager.cs | 3 +- src/Agent.Worker/Container/DockerUtil.cs | 2 +- .../ContainerOperationProvider.cs | 15 +- src/Agent.Worker/DiagnosticLogManager.cs | 18 ++- src/Agent.Worker/Handlers/Handler.cs | 2 +- src/Agent.Worker/Handlers/NodeHandler.cs | 2 +- src/Agent.Worker/Handlers/StepHost.cs | 3 +- src/Agent.Worker/JobRunner.cs | 2 +- .../PluginInternalCommandExtension.cs | 6 +- .../Release/Artifacts/BuildArtifact.cs | 14 +- .../Definition/JenkinsArtifactDetails.cs | 2 +- .../Release/Artifacts/GenericHttpClient.cs | 2 +- .../Release/Artifacts/JenkinsArtifact.cs | 19 ++- .../ContainerFetchEngine/FetchEngine.cs | 4 +- .../HttpRetryOnTimeoutHandler.cs | 2 +- .../FileContainerProvider.cs | 2 +- .../ContainerProvider/Helpers/AsyncLazy.cs | 6 +- .../Helpers/VssConnectionFactory.cs | 6 +- .../Release/ReleaseCommandExtension.cs | 4 +- .../Release/ReleaseFileSystemManager.cs | 2 +- .../Release/ReleaseJobExtension.cs | 24 ++-- .../Release/ZipStreamDownloader.cs | 3 +- src/Agent.Worker/StepsRunner.cs | 5 +- src/Agent.Worker/TaskCommandExtension.cs | 48 +++---- src/Agent.Worker/TaskManager.cs | 2 +- src/Agent.Worker/TaskRestrictionsExtension.cs | 6 +- src/Agent.Worker/TaskRunner.cs | 2 +- .../Telemetry/TelemetryCommandExtension.cs | 6 +- src/Agent.Worker/TempDirectoryManager.cs | 2 +- .../ContainerStructureTestResultReader.cs | 28 ++-- .../TestResults/Legacy/CtestResultReader.cs | 6 +- .../TestResults/Legacy/IResultReader.cs | 2 +- .../TestResults/Legacy/JunitResultReader.cs | 34 ++--- .../Legacy/LegacyTestRunDataPublisher.cs | 16 +-- .../TestResults/Legacy/NunitResultReader.cs | 24 ++-- .../TestResults/Legacy/TestCaseResultData.cs | 4 +- .../TestResults/Legacy/TestResultsServer.cs | 14 +- .../TestResults/Legacy/TestRunData.cs | 2 +- .../TestResults/Legacy/TestRunPublisher.cs | 11 +- .../TestResults/Legacy/TrxResultReader.cs | 28 ++-- .../TestResults/Legacy/XunitResultReader.cs | 8 +- src/Agent.Worker/TestResults/Parser.cs | 2 +- .../PublishToEvidenceStoreCommand.cs | 2 +- .../TestResults/ResultsCommandExtension.cs | 70 +++++----- .../TestResults/TestDataPublisher.cs | 13 +- .../TestResults/TestRunDataPublisherHelper.cs | 4 +- .../TestResults/Utils/FeatureFlagService.cs | 2 +- .../TestResults/Utils/TestResultUtils.cs | 18 +-- src/Agent.Worker/Variables.cs | 5 +- src/Agent.Worker/Worker.cs | 2 +- src/Agent.Worker/WorkerCommandManager.cs | 6 +- .../LinuxAgentCredentialStore.cs | 2 +- .../MacOSAgentCredentialStore.cs | 2 +- .../WindowsAgentCredentialStore.cs | 26 ++-- .../AsyncManualResetEvent.cs | 2 +- .../Blob/BlobFileInfo.cs | 6 +- .../Blob/BlobStoreClientTelemetryTfs.cs | 4 +- .../Blob/BlobStoreUtils.cs | 10 +- .../Blob/BuildArtifactActionRecord.cs | 10 +- .../CustomerIntelligenceTelemetrySender.cs | 2 +- .../DedupManifestArtifactClientFactory.cs | 12 +- .../Blob/PipelineTelemetryRecord.cs | 18 +-- ...TimelineRecordAttachmentTelemetryRecord.cs | 6 +- .../Capabilities/AgentCapabilitiesProvider.cs | 16 +-- .../Capabilities/UserCapabilitiesProvider.cs | 9 +- .../Command.cs | 2 +- .../DeploymentGroupServer.cs | 4 +- .../HostContext.cs | 7 +- .../HostTraceListener.cs | 2 +- .../JobNotification.cs | 4 +- .../JobServer.cs | 5 +- .../JobServerQueue.cs | 8 +- .../ProcessExtensions.cs | 2 +- .../ProcessInvoker.cs | 2 +- .../Util/EnumUtil.cs | 2 +- .../Util/ServerUtil.cs | 12 +- .../Util/VarUtil.cs | 2 +- .../VstsAgentWebProxy.cs | 2 +- .../WindowsEnvVarHelper.cs | 2 +- src/Test/L0/Container/ContainerInfoL0.cs | 36 ++--- src/Test/L0/ExtensionManagerL0.cs | 2 +- src/Test/L0/KnobL0.cs | 10 +- src/Test/L0/Listener/AgentL0.cs | 10 +- src/Test/L0/Listener/CommandSettingsL0.cs | 10 +- .../AgentCapabilitiesProviderTestL0.cs | 2 +- .../Configuration/ConfigurationManagerL0.cs | 14 +- .../NativeWindowsServiceHelperL0.cs | 2 +- .../UserCapabilitiesProviderTestL0.cs | 11 +- src/Test/L0/PagingLoggerL0.cs | 4 +- src/Test/L0/Plugin/FingerprintCreatorTests.cs | 26 ++-- src/Test/L0/Plugin/FingerprintTests.cs | 2 +- src/Test/L0/Plugin/IsPathyTests.cs | 4 +- src/Test/L0/Plugin/LogPluginHostL0.cs | 2 +- src/Test/L0/Plugin/MatchingTests.cs | 46 +++--- src/Test/L0/Plugin/RepositoryPluginL0.cs | 2 +- src/Test/L0/Plugin/TarUtilsL0.cs | 10 +- .../TestFilePublisher/TestFileFinderL0.cs | 2 +- .../TestFilePublisher/TestFilePublisherL0.cs | 2 +- .../TestFilePublisherLogPluginL0.cs | 2 +- .../TestFileShareProviderL0.cs | 42 +++--- .../TestGitCliManager/TestGitCliManagerL0.cs | 4 +- .../TestResultParser/EnumerableExtensionL0.cs | 4 +- .../TestResultParser/LogPreProcessorL0.cs | 2 +- .../PipelineTestRunPublisherL0.cs | 4 +- .../TestResultParser/TestResultLogPluginL0.cs | 4 +- .../TestResultParser/TestRunManagerL0.cs | 2 +- src/Test/L0/ProcessExtensionL0.cs | 2 +- src/Test/L0/ProcessInvokerL0.cs | 10 +- src/Test/L0/ServiceInterfacesL0.cs | 3 +- src/Test/L0/TestUtil.cs | 2 +- src/Test/L0/Util/IOUtilL0.cs | 20 +-- src/Test/L0/Util/TaskResultUtilL0.cs | 2 +- src/Test/L0/Util/TelemetryPropsUtil.cs | 2 +- src/Test/L0/Util/VssUtilL0.cs | 2 +- src/Test/L0/Worker/AgentPluginManagerL0.cs | 34 ++--- .../L0/Worker/Build/BuildJobExtensionL0.cs | 10 +- .../Build/TrackingConfigHashAlgorithmL0.cs | 4 +- .../CodeCoverageCommandExtensionTests.cs | 2 +- src/Test/L0/Worker/ExecutionContextL0.cs | 18 ++- ...inInternalUpdateRepositoryPathCommandL0.cs | 4 +- src/Test/L0/Worker/Release/FetchEngineL0.cs | 132 +++++++++--------- .../Release/ReleaseDirectoryManagerL0.cs | 2 +- .../Worker/Release/ReleaseJobExtensionL0.cs | 4 +- .../L0/Worker/SetVariableRestrictionsL0.cs | 10 +- src/Test/L0/Worker/StepsRunnerL0.cs | 3 +- src/Test/L0/Worker/TaskDecoratorManagerL0.cs | 2 +- src/Test/L0/Worker/TaskRunnerL0.cs | 14 +- .../Legacy/JunitResultReaderTests.cs | 30 ++-- .../Legacy/NUnitResultReaderTests.cs | 6 +- .../Legacy/TestRunPublisherTests.cs | 9 +- .../Legacy/TrxResultReaderTests.cs | 18 +-- .../ResultsCommandExtensionTests.cs | 2 +- src/Test/L0/Worker/VariablesL0.cs | 14 +- src/Test/L0/Worker/WorkerCommandManagerL0.cs | 6 +- src/Test/L1/Mock/FakeJobServer.cs | 5 +- src/Test/L1/Plugins/FakeCheckoutTask.cs | 4 +- src/Test/L1/Worker/L1TestBase.cs | 16 +-- 202 files changed, 1003 insertions(+), 922 deletions(-) diff --git a/src/Agent.Listener/CommandSettings.cs b/src/Agent.Listener/CommandSettings.cs index 4c055b95a5..5757291e86 100644 --- a/src/Agent.Listener/CommandSettings.cs +++ b/src/Agent.Listener/CommandSettings.cs @@ -83,7 +83,7 @@ public CommandSettings(IHostContext context, string[] args, IScopedEnvironment e // Store and remove any args passed via environment variables. var environment = environmentScope.GetEnvironmentVariables(); - + string envPrefix = "VSTS_AGENT_INPUT_"; foreach (DictionaryEntry entry in environment) { @@ -449,7 +449,7 @@ public string GetStartupType() { return GetArg(Run?.StartupType, Constants.Agent.CommandLine.Args.StartupType); } - + public string GetProxyUrl() { return GetArg(Configure?.ProxyUrl, Constants.Agent.CommandLine.Args.ProxyUrl); @@ -467,7 +467,7 @@ public string GetProxyPassword() public bool GetSkipCertificateValidation() { - return TestFlag(Configure?.SslSkipCertValidation , Constants.Agent.CommandLine.Flags.SslSkipCertValidation); + return TestFlag(Configure?.SslSkipCertValidation, Constants.Agent.CommandLine.Flags.SslSkipCertValidation); } public string GetCACertificate() @@ -518,7 +518,7 @@ public bool GetDeploymentPool() public bool GetDeploymentOrMachineGroup() { - if (TestFlag(Configure?.DeploymentGroup, Constants.Agent.CommandLine.Flags.DeploymentGroup) || + if (TestFlag(Configure?.DeploymentGroup, Constants.Agent.CommandLine.Flags.DeploymentGroup) || (Configure?.MachineGroup == true)) { return true; @@ -802,7 +802,7 @@ private void PrintArguments() { if (Configure != null) { - _trace.Info(string.Concat(nameof(Configure)," ",ObjectAsJson(Configure))); + _trace.Info(string.Concat(nameof(Configure), " ", ObjectAsJson(Configure))); } if (Remove != null) diff --git a/src/Agent.Listener/Configuration.Windows/AutoLogonRegistryManager.cs b/src/Agent.Listener/Configuration.Windows/AutoLogonRegistryManager.cs index cba342d88f..f996d77681 100644 --- a/src/Agent.Listener/Configuration.Windows/AutoLogonRegistryManager.cs +++ b/src/Agent.Listener/Configuration.Windows/AutoLogonRegistryManager.cs @@ -62,14 +62,14 @@ public void UpdateRegistrySettings(CommandSettings command, string domainName, s try { string securityId = _windowsServiceHelper.GetSecurityId(domainName, userName); - if(string.IsNullOrEmpty(securityId)) + if (string.IsNullOrEmpty(securityId)) { Trace.Error($"Could not find the Security ID for the user '{domainName}\\{userName}'. AutoLogon will not be configured."); throw new ArgumentException(StringUtil.Loc("InvalidSIDForUser", domainName, userName)); } //check if the registry exists for the user, if not load the user profile - if(!_registryManager.SubKeyExists(RegistryHive.Users, securityId)) + if (!_registryManager.SubKeyExists(RegistryHive.Users, securityId)) { userProfile.dwSize = Marshal.SizeOf(typeof(PROFILEINFO)); userProfile.lpUserName = userName; @@ -77,7 +77,7 @@ public void UpdateRegistrySettings(CommandSettings command, string domainName, s _windowsServiceHelper.LoadUserProfile(domainName, userName, logonPassword, out userHandler, out userProfile); } - if(!_registryManager.SubKeyExists(RegistryHive.Users, securityId)) + if (!_registryManager.SubKeyExists(RegistryHive.Users, securityId)) { throw new InvalidOperationException(StringUtil.Loc("ProfileLoadFailure", domainName, userName)); } @@ -90,7 +90,7 @@ public void UpdateRegistrySettings(CommandSettings command, string domainName, s } finally { - if(userHandler != IntPtr.Zero) + if (userHandler != IntPtr.Zero) { _windowsServiceHelper.UnloadUserProfile(userHandler, userProfile); } @@ -100,7 +100,7 @@ public void UpdateRegistrySettings(CommandSettings command, string domainName, s public void ResetRegistrySettings(string domainName, string userName) { string securityId = _windowsServiceHelper.GetSecurityId(domainName, userName); - if(string.IsNullOrEmpty(securityId)) + if (string.IsNullOrEmpty(securityId)) { Trace.Error($"Could not find the Security ID for the user '{domainName}\\{userName}'. Unconfiguration of AutoLogon is not possible."); throw new ArgumentException(StringUtil.Loc("InvalidSIDForUser", domainName, userName)); @@ -140,7 +140,7 @@ public void DumpAutoLogonRegistrySettings() Trace.Info($"Legal notice caption - Subkey - {legalNoticeSubKey} ValueName - {captionValueName}. Is defined - {isLegalNoticeCaptionDefined}"); var textValueName = RegistryConstants.MachineSettings.ValueNames.LegalNoticeText; - var legalNoticeText = _registryManager.GetValue(RegistryHive.LocalMachine, legalNoticeSubKey, textValueName); + var legalNoticeText = _registryManager.GetValue(RegistryHive.LocalMachine, legalNoticeSubKey, textValueName); var isLegalNoticeTextDefined = !string.IsNullOrEmpty(legalNoticeCaption); Trace.Info($"Legal notice text - Subkey - {legalNoticeSubKey} ValueName - {textValueName}. Is defined - {isLegalNoticeTextDefined}"); } @@ -164,7 +164,7 @@ public void DumpAutoLogonRegistrySettings() Trace.Info("****User specific policies/settings****"); var screenSaverPolicySubKeyName = RegistryConstants.UserSettings.SubKeys.ScreenSaverDomainPolicy; var screenSaverValueName = RegistryConstants.UserSettings.ValueNames.ScreenSaver; - if(_registryManager.SubKeyExists(RegistryHive.CurrentUser, screenSaverPolicySubKeyName)) + if (_registryManager.SubKeyExists(RegistryHive.CurrentUser, screenSaverPolicySubKeyName)) { var screenSaverSettingValue = _registryManager.GetValue(RegistryHive.CurrentUser, screenSaverPolicySubKeyName, screenSaverValueName); Trace.Info($"Screensaver policy. SubKey - {screenSaverPolicySubKeyName} ValueName - {screenSaverValueName} : {screenSaverSettingValue} (1- enabled)"); @@ -176,7 +176,7 @@ public void DumpAutoLogonRegistrySettings() Trace.Info("****User specific settings****"); - var screenSaverSettingSubKeyName = RegistryConstants.UserSettings.SubKeys.ScreenSaver; + var screenSaverSettingSubKeyName = RegistryConstants.UserSettings.SubKeys.ScreenSaver; var screenSaverSettingValueName = RegistryConstants.UserSettings.ValueNames.ScreenSaver; var screenSaverValue = _registryManager.GetValue(RegistryHive.CurrentUser, screenSaverSettingSubKeyName, screenSaverSettingValueName); Trace.Info($"Screensaver - SubKey - {screenSaverSettingSubKeyName}, ValueName - {screenSaverSettingValueName} : {screenSaverValue} (0-disabled, 1-enabled)"); @@ -256,7 +256,7 @@ private void InspectAutoLogonRelatedPolicies() var legalNoticeCaption = _registryManager.GetValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.LegalNotice, RegistryConstants.MachineSettings.ValueNames.LegalNoticeCaption); - var legalNoticeText = _registryManager.GetValue(RegistryHive.LocalMachine, + var legalNoticeText = _registryManager.GetValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.LegalNotice, RegistryConstants.MachineSettings.ValueNames.LegalNoticeText); if (!string.IsNullOrEmpty(legalNoticeCaption) || !string.IsNullOrEmpty(legalNoticeText)) @@ -269,7 +269,7 @@ private void InspectAutoLogonRelatedPolicies() { Trace.Warning("Following policies may affect the autologon:"); _terminal.WriteError(StringUtil.Loc("AutoLogonPoliciesWarningsHeader")); - for (int i=0; i < warningReasons.Count; i++) + for (int i = 0; i < warningReasons.Count; i++) { var msg = String.Format("{0} - {1}", i + 1, warningReasons[i]); Trace.Warning(msg); @@ -295,7 +295,7 @@ private void UpdateScreenSaverSettings(CommandSettings command, string securityI _terminal.WriteLine(StringUtil.Loc("ScreenSaverPoliciesInspection")); string subKeyName = $"{securityId}\\{RegistryConstants.UserSettings.SubKeys.ScreenSaverDomainPolicy}"; - if(_registryManager.SubKeyExists(RegistryHive.Users, subKeyName)) + if (_registryManager.SubKeyExists(RegistryHive.Users, subKeyName)) { var screenSaverValue = _registryManager.GetValue(RegistryHive.Users, subKeyName, RegistryConstants.UserSettings.ValueNames.ScreenSaver); if (int.TryParse(screenSaverValue, out int isScreenSaverDomainPolicySet) @@ -351,7 +351,7 @@ private void ResetUserSpecificSettings(string securityId) var screenSaverSubKey = $"{securityId}\\{RegistryConstants.UserSettings.SubKeys.ScreenSaver}"; var currentValue = _registryManager.GetValue(targetHive, screenSaverSubKey, RegistryConstants.UserSettings.ValueNames.ScreenSaver); - if(string.Equals(currentValue, "0", StringComparison.CurrentCultureIgnoreCase)) + if (string.Equals(currentValue, "0", StringComparison.CurrentCultureIgnoreCase)) { //we only take the backup of screensaver setting at present, reverting it back if it exists RevertOriginalValue(targetHive, screenSaverSubKey, RegistryConstants.UserSettings.ValueNames.ScreenSaver); @@ -369,7 +369,7 @@ private void DeleteStartupCommand(RegistryHive targetHive, string securityId) var actualStartupCmd = _registryManager.GetValue(targetHive, startupProcessSubKeyName, RegistryConstants.UserSettings.ValueNames.StartupProcess); // Use StartWith() instead of Equals() because we don't know if the startupCmd should include the runOnce parameter - if(actualStartupCmd != null && + if (actualStartupCmd != null && actualStartupCmd.StartsWith(expectedStartupCmd, StringComparison.CurrentCultureIgnoreCase)) { _registryManager.DeleteValue(RegistryHive.Users, startupProcessSubKeyName, RegistryConstants.UserSettings.ValueNames.StartupProcess); diff --git a/src/Agent.Listener/Configuration.Windows/WindowsRegistryManager.cs b/src/Agent.Listener/Configuration.Windows/WindowsRegistryManager.cs index ebbd5a6dd5..95cd1ff112 100644 --- a/src/Agent.Listener/Configuration.Windows/WindowsRegistryManager.cs +++ b/src/Agent.Listener/Configuration.Windows/WindowsRegistryManager.cs @@ -19,7 +19,7 @@ public class WindowsRegistryManager : AgentService, IWindowsRegistryManager { public void DeleteValue(RegistryHive hive, string subKeyName, string name) { - using(RegistryKey key = OpenRegistryKey(hive, subKeyName, true)) + using (RegistryKey key = OpenRegistryKey(hive, subKeyName, true)) { if (key != null) { @@ -30,9 +30,9 @@ public void DeleteValue(RegistryHive hive, string subKeyName, string name) public string GetValue(RegistryHive hive, string subKeyName, string name) { - using(RegistryKey key = OpenRegistryKey(hive, subKeyName, false)) + using (RegistryKey key = OpenRegistryKey(hive, subKeyName, false)) { - if(key == null) + if (key == null) { return null; } @@ -44,7 +44,7 @@ public string GetValue(RegistryHive hive, string subKeyName, string name) public void SetValue(RegistryHive hive, string subKeyName, string name, string value) { - using(RegistryKey key = OpenRegistryKey(hive, subKeyName, true)) + using (RegistryKey key = OpenRegistryKey(hive, subKeyName, true)) { if (key == null) { @@ -64,7 +64,7 @@ public void SetValue(RegistryHive hive, string subKeyName, string name, string v public bool SubKeyExists(RegistryHive hive, string subKeyName) { - using(RegistryKey key = OpenRegistryKey(hive, subKeyName, false)) + using (RegistryKey key = OpenRegistryKey(hive, subKeyName, false)) { return key != null; } @@ -75,10 +75,10 @@ private RegistryKey OpenRegistryKey(RegistryHive hive, string subKeyName, bool w RegistryKey key = null; switch (hive) { - case RegistryHive.CurrentUser : + case RegistryHive.CurrentUser: key = Registry.CurrentUser.OpenSubKey(subKeyName, writable); break; - case RegistryHive.Users : + case RegistryHive.Users: key = Registry.Users.OpenSubKey(subKeyName, writable); break; case RegistryHive.LocalMachine: @@ -93,10 +93,10 @@ private RegistryKey CreateRegistryKey(RegistryHive hive, string subKeyName, bool RegistryKey key = null; switch (hive) { - case RegistryHive.CurrentUser : + case RegistryHive.CurrentUser: key = Registry.CurrentUser.CreateSubKey(subKeyName, writable); break; - case RegistryHive.Users : + case RegistryHive.Users: key = Registry.Users.CreateSubKey(subKeyName, writable); break; case RegistryHive.LocalMachine: diff --git a/src/Agent.Listener/Configuration.Windows/WindowsServiceControlManager.cs b/src/Agent.Listener/Configuration.Windows/WindowsServiceControlManager.cs index ebbb4509e7..b90039e5c1 100644 --- a/src/Agent.Listener/Configuration.Windows/WindowsServiceControlManager.cs +++ b/src/Agent.Listener/Configuration.Windows/WindowsServiceControlManager.cs @@ -144,11 +144,11 @@ public void ConfigureService(AgentSettings settings, CommandSettings command) _windowsServiceHelper.CreateVstsAgentRegistryKey(); Trace.Info("Configuration was successful, trying to start the service"); - if(!command.GetPreventServiceStart()) + if (!command.GetPreventServiceStart()) { _windowsServiceHelper.StartService(serviceName); } - + } public void UnconfigureService() diff --git a/src/Agent.Listener/Configuration/ConfigurationManager.cs b/src/Agent.Listener/Configuration/ConfigurationManager.cs index 0fc4be42be..25aaf3ba66 100644 --- a/src/Agent.Listener/Configuration/ConfigurationManager.cs +++ b/src/Agent.Listener/Configuration/ConfigurationManager.cs @@ -77,7 +77,7 @@ public async Task ConfigureAsync(CommandSettings command) ArgUtil.NotNull(command, nameof(command)); if (PlatformUtil.RunningOnWindows) - { + { CheckAgentRootDirectorySecure(); } @@ -374,7 +374,7 @@ public async Task ConfigureAsync(CommandSettings command) agentSettings.DisableLogUploads = command.GetDisableLogUploads(); agentSettings.AlwaysExtractTask = command.GetAlwaysExtractTask(); - + _store.SaveSettings(agentSettings); if (saveProxySetting) @@ -503,7 +503,7 @@ public async Task UnconfigureAsync(CommandSettings command) bool isEnvironmentVMResource = false; bool isDeploymentGroup = (settings.MachineGroupId > 0) || (settings.DeploymentGroupId > 0); - if(!isDeploymentGroup) + if (!isDeploymentGroup) { isEnvironmentVMResource = settings.EnvironmentId > 0; } @@ -520,7 +520,7 @@ public async Task UnconfigureAsync(CommandSettings command) IConfigurationProvider agentProvider = (extensionManager.GetExtensions()).FirstOrDefault(x => x.ConfigurationProviderType == agentType); ArgUtil.NotNull(agentProvider, agentType); - bool isHostedServer = await checkIsHostedServer(agentProvider, settings, credProvider);; + bool isHostedServer = await checkIsHostedServer(agentProvider, settings, credProvider); VssCredentials creds = credProvider.GetVssCredentials(HostContext); await agentProvider.TestConnectionAsync(settings, creds, isHostedServer); @@ -708,21 +708,23 @@ private void CheckAgentRootDirectorySecure() _term.Write(StringUtil.Loc("agentRootFolderInsecure", bulitInUsersGroup.ToString())); } } - else + else { Trace.Warning("Can't get path to the agent root folder, check was skipped."); } } - catch (Exception ex) { + catch (Exception ex) + { Trace.Warning("Can't check permissions for agent root folder:"); Trace.Warning(ex.Message); _term.Write(StringUtil.Loc("agentRootFolderCheckError")); } } - private bool SetupVstsProxySetting(IVstsAgentWebProxy vstsProxy, CommandSettings command) { + private bool SetupVstsProxySetting(IVstsAgentWebProxy vstsProxy, CommandSettings command) + { ArgUtil.NotNull(command, nameof(command)); - + bool saveProxySetting = false; string proxyUrl = command.GetProxyUrl(); if (!string.IsNullOrEmpty(proxyUrl)) @@ -742,7 +744,8 @@ private bool SetupVstsProxySetting(IVstsAgentWebProxy vstsProxy, CommandSettings return saveProxySetting; } - private bool SetupCertSettings(IAgentCertificateManager agentCertManager, CommandSettings command) { + private bool SetupCertSettings(IAgentCertificateManager agentCertManager, CommandSettings command) + { bool saveCertSetting = false; bool skipCertValidation = command.GetSkipCertificateValidation(); string caCert = command.GetCACertificate(); @@ -792,7 +795,8 @@ private bool SetupCertSettings(IAgentCertificateManager agentCertManager, Comman return saveCertSetting; } - private string GetAgentTypeFromCommand(CommandSettings command) { + private string GetAgentTypeFromCommand(CommandSettings command) + { string agentType = Constants.Agent.AgentConfigurationProvider.BuildReleasesAgentConfiguration; if (command.GetDeploymentOrMachineGroup()) @@ -811,7 +815,8 @@ private string GetAgentTypeFromCommand(CommandSettings command) { return agentType; } - private async Task checkIsHostedServer(IConfigurationProvider agentProvider, AgentSettings agentSettings, ICredentialProvider credProvider) { + private async Task checkIsHostedServer(IConfigurationProvider agentProvider, AgentSettings agentSettings, ICredentialProvider credProvider) + { bool isHostedServer = false; VssCredentials creds = credProvider.GetVssCredentials(HostContext); @@ -820,7 +825,8 @@ private async Task checkIsHostedServer(IConfigurationProvider agentProvide // Determine the service deployment type based on connection data. (Hosted/OnPremises) await _serverUtil.DetermineDeploymentType(agentSettings.ServerUrl, creds, _locationServer); } - catch (VssUnauthorizedException) { + catch (VssUnauthorizedException) + { // In case if GetConnectionData returned some auth problem need to check // maybe connect will be successfull with CollectionName // (as example PAT was generated for url/CollectionName) diff --git a/src/Agent.Listener/Configuration/ConfigurationProvider.cs b/src/Agent.Listener/Configuration/ConfigurationProvider.cs index 7fcf466610..1a674a3850 100644 --- a/src/Agent.Listener/Configuration/ConfigurationProvider.cs +++ b/src/Agent.Listener/Configuration/ConfigurationProvider.cs @@ -51,7 +51,7 @@ public class BuildReleasesAgentConfigProvider : AgentService, IConfigurationProv public string ConfigurationProviderType => Constants.Agent.AgentConfigurationProvider.BuildReleasesAgentConfiguration; - public bool IsCollectionPossible + public bool IsCollectionPossible => false; public override void Initialize(IHostContext hostContext) @@ -140,7 +140,7 @@ public class DeploymentGroupAgentConfigProvider : AgentService, IConfigurationPr public Type ExtensionType => typeof(IConfigurationProvider); public string ConfigurationProviderType => Constants.Agent.AgentConfigurationProvider.DeploymentAgentConfiguration; - public bool IsCollectionPossible + public bool IsCollectionPossible => true; protected ITerminal _term; protected string _projectName = string.Empty; @@ -482,7 +482,7 @@ public override async Task AddAgentAsync(AgentSettings agentSettings, virtualMachine = await _environmentsServer.AddEnvironmentVMAsync(new Guid(agentSettings.ProjectId), agentSettings.EnvironmentId, virtualMachine); Trace.Info("Environment virtual machine resource with name: '{0}', id: '{1}' has been added successfully.", virtualMachine.Name, virtualMachine.Id); - var pool = await _environmentsServer.GetEnvironmentPoolAsync(new Guid(agentSettings.ProjectId), agentSettings.EnvironmentId); + var pool = await _environmentsServer.GetEnvironmentPoolAsync(new Guid(agentSettings.ProjectId), agentSettings.EnvironmentId); Trace.Info("environment pool id: '{0}'", pool.Id); agentSettings.PoolId = pool.Id; agentSettings.AgentName = virtualMachine.Name; @@ -556,7 +556,7 @@ public override async Task UpdateAgentAsync(AgentSettings agentSettin Trace.Info("Replacing environment virtual machine resource with id: '{0}'", vmResource.Id); vmResource = await _environmentsServer.ReplaceEnvironmentVMAsync(new Guid(agentSettings.ProjectId), agentSettings.EnvironmentId, vmResource); Trace.Info("environment virtual machine resource with id: '{0}' has been replaced successfully", vmResource.Id); - var pool = await _environmentsServer.GetEnvironmentPoolAsync(new Guid(agentSettings.ProjectId), agentSettings.EnvironmentId); + var pool = await _environmentsServer.GetEnvironmentPoolAsync(new Guid(agentSettings.ProjectId), agentSettings.EnvironmentId); agentSettings.AgentName = vmResource.Name; agentSettings.EnvironmentVMResourceId = vmResource.Id; diff --git a/src/Agent.Listener/Configuration/CredentialManager.cs b/src/Agent.Listener/Configuration/CredentialManager.cs index 3f82133798..bc8d9f57e1 100644 --- a/src/Agent.Listener/Configuration/CredentialManager.cs +++ b/src/Agent.Listener/Configuration/CredentialManager.cs @@ -16,7 +16,7 @@ public interface ICredentialManager : IAgentService } public class CredentialManager : AgentService, ICredentialManager - { + { public static readonly Dictionary CredentialTypes = new Dictionary(StringComparer.OrdinalIgnoreCase) { { Constants.Configuration.AAD, typeof(AadDeviceCodeAccessToken)}, @@ -43,20 +43,20 @@ public ICredentialProvider GetCredentialProvider(string credType) Trace.Verbose("Created credential type"); return creds; } - + public VssCredentials LoadCredentials() { - IConfigurationStore store = HostContext.GetService(); + IConfigurationStore store = HostContext.GetService(); if (!store.HasCredentials()) { throw new InvalidOperationException("Credentials not stored. Must reconfigure."); } - + CredentialData credData = store.GetCredentials(); ICredentialProvider credProv = GetCredentialProvider(credData.Scheme); credProv.CredentialData = credData; - + VssCredentials creds = credProv.GetVssCredentials(HostContext); return creds; diff --git a/src/Agent.Listener/Configuration/ServiceControlManager.cs b/src/Agent.Listener/Configuration/ServiceControlManager.cs index 94cacf2ba7..46955455b7 100644 --- a/src/Agent.Listener/Configuration/ServiceControlManager.cs +++ b/src/Agent.Listener/Configuration/ServiceControlManager.cs @@ -73,7 +73,7 @@ public void CalculateServiceName(AgentSettings settings, string serviceNamePatte } serviceDisplayName = StringUtil.Format(serviceDisplayNamePattern, accountName, resourceCollection, settings.AgentName); - + Trace.Info($"Service name '{serviceName}' display name '{serviceDisplayName}' will be used for service configuration."); } } diff --git a/src/Agent.Listener/Configuration/Validators.cs b/src/Agent.Listener/Configuration/Validators.cs index d97abf48d2..85f751d687 100644 --- a/src/Agent.Listener/Configuration/Validators.cs +++ b/src/Agent.Listener/Configuration/Validators.cs @@ -90,7 +90,7 @@ public static bool NTAccountValidator(string arg) { try { - if(!logonAccount.EndsWith('$')) + if (!logonAccount.EndsWith('$')) { NTAccount ntaccount = new NTAccount(logonAccount + '$'); SecurityIdentifier sid = (SecurityIdentifier)ntaccount.Translate(typeof(SecurityIdentifier)); diff --git a/src/Agent.Listener/Diagnostics/DiskInfo.cs b/src/Agent.Listener/Diagnostics/DiskInfo.cs index a1d7b6fc21..38f8c25e6c 100644 --- a/src/Agent.Listener/Diagnostics/DiskInfo.cs +++ b/src/Agent.Listener/Diagnostics/DiskInfo.cs @@ -22,7 +22,7 @@ public void Execute(ITerminal terminal) terminal.WriteLine($" File system: {d.DriveFormat}"); terminal.WriteLine(string.Format(" Available space to current user:{0, 15:N0} KB", d.AvailableFreeSpace / c_kb)); terminal.WriteLine(string.Format(" Total available space: {0, 15:N0} KB", d.TotalFreeSpace / c_kb)); - terminal.WriteLine(string.Format(" Total size of drive: {0, 15:N0} KB", d.TotalSize/ c_kb)); + terminal.WriteLine(string.Format(" Total size of drive: {0, 15:N0} KB", d.TotalSize / c_kb)); } else { @@ -30,11 +30,11 @@ public void Execute(ITerminal terminal) } } } - catch(IOException ex) + catch (IOException ex) { terminal.WriteError(ex); } - catch(System.UnauthorizedAccessException ex) + catch (System.UnauthorizedAccessException ex) { terminal.WriteError(ex); } diff --git a/src/Agent.Listener/Diagnostics/FolderPermissionInfo.cs b/src/Agent.Listener/Diagnostics/FolderPermissionInfo.cs index 205f90389d..57898011e3 100644 --- a/src/Agent.Listener/Diagnostics/FolderPermissionInfo.cs +++ b/src/Agent.Listener/Diagnostics/FolderPermissionInfo.cs @@ -15,12 +15,12 @@ public void Execute(ITerminal terminal) string currentDirName = Directory.GetCurrentDirectory(); DirectoryInfo directoryInfo = new DirectoryInfo(currentDirName); - terminal.WriteLine($"{ directoryInfo.FullName.PadRight(c_padding)} {HasFolderWritePermission(terminal, currentDirName)}"); + terminal.WriteLine($"{directoryInfo.FullName.PadRight(c_padding)} {HasFolderWritePermission(terminal, currentDirName)}"); DirectoryInfo[] folders = directoryInfo.GetDirectories(); foreach (DirectoryInfo folder in folders) { - terminal.WriteLine($"{ folder.FullName.PadRight(c_padding)} {HasFolderWritePermission(terminal, folder.FullName)}"); + terminal.WriteLine($"{folder.FullName.PadRight(c_padding)} {HasFolderWritePermission(terminal, folder.FullName)}"); } string[] files = Directory.GetFiles(currentDirName); diff --git a/src/Agent.Listener/DistributedTask.Pipelines/Yaml/Contracts/DeploymentTarget.cs b/src/Agent.Listener/DistributedTask.Pipelines/Yaml/Contracts/DeploymentTarget.cs index 5783c45f2f..63a72abed1 100644 --- a/src/Agent.Listener/DistributedTask.Pipelines/Yaml/Contracts/DeploymentTarget.cs +++ b/src/Agent.Listener/DistributedTask.Pipelines/Yaml/Contracts/DeploymentTarget.cs @@ -6,7 +6,7 @@ namespace Microsoft.TeamFoundation.DistributedTask.Orchestration.Server.Pipelines.Yaml.Contracts { - internal sealed class DeploymentTarget: IPhaseTarget + internal sealed class DeploymentTarget : IPhaseTarget { internal String ContinueOnError { get; set; } diff --git a/src/Agent.Listener/DistributedTask.Pipelines/Yaml/Contracts/QueueTarget.cs b/src/Agent.Listener/DistributedTask.Pipelines/Yaml/Contracts/QueueTarget.cs index 605edf18bd..cc9cb865cd 100644 --- a/src/Agent.Listener/DistributedTask.Pipelines/Yaml/Contracts/QueueTarget.cs +++ b/src/Agent.Listener/DistributedTask.Pipelines/Yaml/Contracts/QueueTarget.cs @@ -6,7 +6,7 @@ namespace Microsoft.TeamFoundation.DistributedTask.Orchestration.Server.Pipelines.Yaml.Contracts { - internal sealed class QueueTarget: IPhaseTarget + internal sealed class QueueTarget : IPhaseTarget { internal String ContinueOnError { get; set; } diff --git a/src/Agent.Listener/DistributedTask.Pipelines/Yaml/Contracts/ServerTarget.cs b/src/Agent.Listener/DistributedTask.Pipelines/Yaml/Contracts/ServerTarget.cs index c19d84d8e1..3669b72995 100644 --- a/src/Agent.Listener/DistributedTask.Pipelines/Yaml/Contracts/ServerTarget.cs +++ b/src/Agent.Listener/DistributedTask.Pipelines/Yaml/Contracts/ServerTarget.cs @@ -6,7 +6,7 @@ namespace Microsoft.TeamFoundation.DistributedTask.Orchestration.Server.Pipelines.Yaml.Contracts { - internal sealed class ServerTarget: IPhaseTarget + internal sealed class ServerTarget : IPhaseTarget { internal String ContinueOnError { get; set; } diff --git a/src/Agent.Listener/DistributedTask.Pipelines/Yaml/PipelineParser.cs b/src/Agent.Listener/DistributedTask.Pipelines/Yaml/PipelineParser.cs index ccaaacd8f1..dccd4b88c0 100644 --- a/src/Agent.Listener/DistributedTask.Pipelines/Yaml/PipelineParser.cs +++ b/src/Agent.Listener/DistributedTask.Pipelines/Yaml/PipelineParser.cs @@ -336,7 +336,7 @@ private void ResolveTemplates(Process process, String defaultRoot, CancellationT private void ResolveTemplates(IList phases, String defaultRoot, CancellationToken cancellationToken, ref Int32 fileCount) { - for (int i = 0 ; i < (phases?.Count ?? 0) ; ) + for (int i = 0; i < (phases?.Count ?? 0);) { if (phases[i] is PhasesTemplateReference) { @@ -392,7 +392,7 @@ private void ResolveTemplates(IList phases, String defaultRoot, Cancella private void ResolveTemplates(IList variables, String defaultRoot, CancellationToken cancellationToken, ref Int32 fileCount) { - for (int i = 0 ; i < (variables?.Count ?? 0) ; ) + for (int i = 0; i < (variables?.Count ?? 0);) { if (variables[i] is VariablesTemplateReference) { @@ -423,7 +423,7 @@ private void ResolveTemplates(IList variables, String defaultRoot, Ca private void ResolveTemplates(IList steps, String defaultRoot, CancellationToken cancellationToken, ref Int32 fileCount) { - for (int i = 0 ; i < (steps?.Count ?? 0); ) + for (int i = 0; i < (steps?.Count ?? 0);) { if (steps[i] is StepsTemplateReference) { @@ -487,7 +487,7 @@ private static void ApplyStepOverrides(IDictionary> s { stepOverrides = stepOverrides ?? new Dictionary>(0); steps = steps ?? new List(0); - for (int i = 0 ; i < steps.Count ; ) + for (int i = 0; i < steps.Count;) { if (steps[i] is StepGroup) { diff --git a/src/Agent.Listener/DistributedTask.Pipelines/Yaml/TypeConverters/ConverterUtil.processes.cs b/src/Agent.Listener/DistributedTask.Pipelines/Yaml/TypeConverters/ConverterUtil.processes.cs index cee64be685..cda9f7da18 100644 --- a/src/Agent.Listener/DistributedTask.Pipelines/Yaml/TypeConverters/ConverterUtil.processes.cs +++ b/src/Agent.Listener/DistributedTask.Pipelines/Yaml/TypeConverters/ConverterUtil.processes.cs @@ -34,7 +34,7 @@ internal static IList ReadProcessResources(IParser parser) } var resource = new ProcessResource { Type = scalar.Value }; - resource.Name = ReadNonEmptyString(parser);; + resource.Name = ReadNonEmptyString(parser); while (parser.Allow() == null) { string dataKey = ReadNonEmptyString(parser); diff --git a/src/Agent.Listener/SelfUpdater.cs b/src/Agent.Listener/SelfUpdater.cs index 64632dbf94..31f5c231ee 100644 --- a/src/Agent.Listener/SelfUpdater.cs +++ b/src/Agent.Listener/SelfUpdater.cs @@ -168,7 +168,8 @@ private async Task UpdateNeeded(string targetVersion, CancellationToken to Trace.Warning($"The operating system the agent is running on is \"{systemId}\" ({systemVersion}), which will not be supported by the .NET 6 based v3 agent. Please upgrade the operating system of this host to ensure compatibility with the v3 agent. See https://aka.ms/azdo-pipeline-agent-version"); return false; } - } else + } + else { Trace.Warning($"The operating system the agent is running on is \"{systemId}\" ({systemVersion}), which has not been tested with the .NET 6 based v3 agent. The v2 agent wil not automatically upgrade to the v3 agent. You can manually download the .NET 6 based v3 agent from https://github.com/microsoft/azure-pipelines-agent/releases. See https://aka.ms/azdo-pipeline-agent-version"); return false; diff --git a/src/Agent.Plugins/Artifact/ArtifactItemFilters.cs b/src/Agent.Plugins/Artifact/ArtifactItemFilters.cs index c184e3b94d..eacac7aaa2 100644 --- a/src/Agent.Plugins/Artifact/ArtifactItemFilters.cs +++ b/src/Agent.Plugins/Artifact/ArtifactItemFilters.cs @@ -167,7 +167,7 @@ private string[] ExpandBraces(string pattern, Options matchOptions) private void UpdatePatternsMap(bool isIncludePattern, List paths, IEnumerable> minimatcherFuncs, ref Hashtable map) { string patternType = isIncludePattern ? "include" : "exclude"; - tracer.Info($"Applying { patternType } pattern against original list."); + tracer.Info($"Applying {patternType} pattern against original list."); List matchResults = this.FilterItemsByPatterns(paths, minimatcherFuncs); int matchCount = 0; diff --git a/src/Agent.Plugins/Artifact/FileContainerProvider.cs b/src/Agent.Plugins/Artifact/FileContainerProvider.cs index 4e5fcbd434..c31baa640e 100644 --- a/src/Agent.Plugins/Artifact/FileContainerProvider.cs +++ b/src/Agent.Plugins/Artifact/FileContainerProvider.cs @@ -349,7 +349,7 @@ await clientTelemetry.MeasureActionAsync( using (var targetFileStream = new FileStream(destinationPath, FileMode.Create)) using (var uncompressStream = new GZipStream(targetFileStream, CompressionMode.Decompress)) { - await dedupClient.DownloadToStreamAsync(dedupIdentifier, uncompressStream, null, EdgeCache.Allowed, (size) => {}, (size) => {}, cancellationToken); + await dedupClient.DownloadToStreamAsync(dedupIdentifier, uncompressStream, null, EdgeCache.Allowed, (size) => { }, (size) => { }, cancellationToken); } } else @@ -418,9 +418,12 @@ private void ExtractTarsIfPresent(AgentTaskPluginExecutionContext context, IEnum } } - if (tarsFoundCount == 0) { + if (tarsFoundCount == 0) + { context.Warning(StringUtil.Loc("TarsNotFound")); - } else { + } + else + { tracer.Info(StringUtil.Loc("TarsFound", tarsFoundCount)); string targetDirectory = Path.Combine(rootPath, "extracted_tars"); @@ -454,7 +457,8 @@ private void ExtractTar(string tarArchivePath, string extractedFilesDir) } // Recursively moves sourcePath directory to targetPath - private void MoveDirectory(string sourcePath, string targetPath) { + private void MoveDirectory(string sourcePath, string targetPath) + { var sourceDirectoryInfo = new DirectoryInfo(sourcePath); foreach (FileInfo file in sourceDirectoryInfo.GetFiles("*", SearchOption.TopDirectoryOnly)) { diff --git a/src/Agent.Plugins/Artifact/FileShareProvider.cs b/src/Agent.Plugins/Artifact/FileShareProvider.cs index 26e739806e..8599095112 100644 --- a/src/Agent.Plugins/Artifact/FileShareProvider.cs +++ b/src/Agent.Plugins/Artifact/FileShareProvider.cs @@ -25,7 +25,7 @@ namespace Agent.Plugins { - internal class FileShareProvider: IArtifactProvider + internal class FileShareProvider : IArtifactProvider { private readonly AgentTaskPluginExecutionContext context; private readonly IAppTraceSource tracer; @@ -48,12 +48,12 @@ internal FileShareProvider(AgentTaskPluginExecutionContext context, VssConnectio this.connection = connection; } - public async Task DownloadSingleArtifactAsync(ArtifactDownloadParameters downloadParameters, BuildArtifact buildArtifact, CancellationToken cancellationToken, AgentTaskPluginExecutionContext context) + public async Task DownloadSingleArtifactAsync(ArtifactDownloadParameters downloadParameters, BuildArtifact buildArtifact, CancellationToken cancellationToken, AgentTaskPluginExecutionContext context) { await DownloadMultipleArtifactsAsync(downloadParameters, new List { buildArtifact }, cancellationToken, context); } - public async Task DownloadMultipleArtifactsAsync(ArtifactDownloadParameters downloadParameters, IEnumerable buildArtifacts, CancellationToken cancellationToken, AgentTaskPluginExecutionContext context) + public async Task DownloadMultipleArtifactsAsync(ArtifactDownloadParameters downloadParameters, IEnumerable buildArtifacts, CancellationToken cancellationToken, AgentTaskPluginExecutionContext context) { context.Warning(StringUtil.Loc("DownloadArtifactWarning", "UNC")); var (dedupManifestClient, clientTelemetry) = await this.factory.CreateDedupManifestClientAsync( @@ -97,7 +97,7 @@ private async Task DownloadArtifactsAsync(ArtifactDownl totalFileCount += record.FileCount; records.Add(record); } - + return new FileShareDownloadResult(records, totalFileCount, totalContentSize); } @@ -105,7 +105,7 @@ public async Task PublishArtifactAsync( string sourcePath, string destPath, int parallelCount, - CancellationToken cancellationToken) + CancellationToken cancellationToken) { var (dedupManifestClient, clientTelemetry) = await this.factory.CreateDedupManifestClientAsync( context.IsSystemDebugTrue(), @@ -187,7 +187,7 @@ private async Task PublishArtifactUsingRobocopyAsync( throw new Exception(StringUtil.Loc("RobocopyBasedPublishArtifactTaskFailed", exitCode)); } - return new FileSharePublishResult (exitCode); + return new FileSharePublishResult(exitCode); } } @@ -264,7 +264,7 @@ private async Task DownloadFileShareArtifactAsync( var actionBlock = NonSwallowingActionBlock.Create( action: async file => { - if (minimatchFuncs == null || minimatchFuncs.Any(match => match(file.FullName))) + if (minimatchFuncs == null || minimatchFuncs.Any(match => match(file.FullName))) { string tempPath = Path.Combine(destPath, Path.GetRelativePath(sourcePath, file.FullName)); context.Output(StringUtil.Loc("CopyFileToDestination", file, tempPath)); @@ -282,8 +282,8 @@ await WriteStreamToFile( } }, dataflowBlockOptions: parallelism); - - await actionBlock.SendAllAndCompleteAsync(filteredFiles, actionBlock, cancellationToken); + + await actionBlock.SendAllAndCompleteAsync(filteredFiles, actionBlock, cancellationToken); watch.Stop(); diff --git a/src/Agent.Plugins/Artifact/PipelineArtifactProvider.cs b/src/Agent.Plugins/Artifact/PipelineArtifactProvider.cs index bfc773b916..6090909f5f 100644 --- a/src/Agent.Plugins/Artifact/PipelineArtifactProvider.cs +++ b/src/Agent.Plugins/Artifact/PipelineArtifactProvider.cs @@ -41,7 +41,8 @@ public async Task DownloadSingleArtifactAsync(ArtifactDownloadParameters downloa WellKnownDomainIds.DefaultDomainId, cancellationToken); - using(clientTelemetry) { + using (clientTelemetry) + { var manifestId = DedupIdentifier.Create(buildArtifact.Resource.Data); var options = DownloadDedupManifestArtifactOptions.CreateWithManifestId( manifestId, @@ -82,7 +83,8 @@ public async Task DownloadMultipleArtifactsAsync(ArtifactDownloadParameters down WellKnownDomainIds.DefaultDomainId, cancellationToken); - using(clientTelemetry) { + using (clientTelemetry) + { var artifactNameAndManifestIds = buildArtifacts.ToDictionary( keySelector: (a) => a.Name, // keys should be unique, if not something is really wrong elementSelector: (a) => DedupIdentifier.Create(a.Resource.Data)); diff --git a/src/Agent.Plugins/Artifact/PipelineArtifactServer.cs b/src/Agent.Plugins/Artifact/PipelineArtifactServer.cs index 9e3d61d673..eeba92396f 100644 --- a/src/Agent.Plugins/Artifact/PipelineArtifactServer.cs +++ b/src/Agent.Plugins/Artifact/PipelineArtifactServer.cs @@ -61,7 +61,7 @@ internal async Task UploadAsync( PublishResult result = await clientTelemetry.MeasureActionAsync( record: uploadRecord, actionAsync: async () => await AsyncHttpRetryHelper.InvokeAsync( - async () => + async () => { return await dedupManifestClient.PublishAsync(source, cancellationToken); }, @@ -70,7 +70,7 @@ internal async Task UploadAsync( canRetryDelegate: e => true, // this isn't great, but failing on upload stinks, so just try a couple of times cancellationToken: cancellationToken, continueOnCapturedContext: false) - + ); // Send results to CustomerIntelligence context.PublishTelemetry(area: PipelineArtifactConstants.AzurePipelinesAgent, feature: PipelineArtifactConstants.PipelineArtifact, record: uploadRecord); @@ -86,15 +86,15 @@ internal async Task UploadAsync( }; BuildArtifact buildArtifact = await AsyncHttpRetryHelper.InvokeAsync( - async () => + async () => { - return await buildServer.AssociateArtifactAsync(projectId, - pipelineId, - name, - context.Variables.GetValueOrDefault(WellKnownDistributedTaskVariables.JobId)?.Value?? string.Empty, - ArtifactResourceTypes.PipelineArtifact, - result.ManifestId.ValueString, - propertiesDictionary, + return await buildServer.AssociateArtifactAsync(projectId, + pipelineId, + name, + context.Variables.GetValueOrDefault(WellKnownDistributedTaskVariables.JobId)?.Value ?? string.Empty, + ArtifactResourceTypes.PipelineArtifact, + result.ManifestId.ValueString, + propertiesDictionary, cancellationToken); }, @@ -103,7 +103,7 @@ internal async Task UploadAsync( canRetryDelegate: e => e is TimeoutException || e.InnerException is TimeoutException, cancellationToken: cancellationToken, continueOnCapturedContext: false); - + context.Output(StringUtil.Loc("AssociateArtifactWithBuild", buildArtifact.Id, pipelineId)); } } @@ -134,7 +134,7 @@ internal Task DownloadAsync( internal async Task DownloadAsync( AgentTaskPluginExecutionContext context, ArtifactDownloadParameters downloadParameters, - DownloadOptions downloadOptions, + DownloadOptions downloadOptions, CancellationToken cancellationToken) { VssConnection connection = context.VssConnection; @@ -217,7 +217,7 @@ await AsyncHttpRetryHelper.InvokeVoidAsync( // Send results to CustomerIntelligence context.PublishTelemetry(area: PipelineArtifactConstants.AzurePipelinesAgent, feature: PipelineArtifactConstants.PipelineArtifact, record: downloadRecord); - } + } } else if (downloadOptions == DownloadOptions.SingleDownload) { @@ -330,7 +330,7 @@ internal async Task DownloadAsyncV2( await provider.DownloadMultipleArtifactsAsync(downloadParameters, pipelineArtifacts, cancellationToken, context); } - if (fileShareArtifacts.Any()) + if (fileShareArtifacts.Any()) { FileShareProvider provider = new FileShareProvider(context, connection, this.tracer); await provider.DownloadMultipleArtifactsAsync(downloadParameters, fileShareArtifacts, cancellationToken, context); @@ -362,7 +362,7 @@ internal async Task DownloadAsyncV2( ArtifactProviderFactory factory = new ArtifactProviderFactory(context, connection, this.tracer); IArtifactProvider provider = factory.GetProvider(buildArtifact); - + await provider.DownloadSingleArtifactAsync(downloadParameters, buildArtifact, cancellationToken, context); } else diff --git a/src/Agent.Plugins/ArtifactsTracer.cs b/src/Agent.Plugins/ArtifactsTracer.cs index 5ff8a3e305..61a8e85952 100644 --- a/src/Agent.Plugins/ArtifactsTracer.cs +++ b/src/Agent.Plugins/ArtifactsTracer.cs @@ -22,7 +22,7 @@ public static IAppTraceSource CreateArtifactsTracer(this AgentTaskPluginExecutio ArgUtil.NotNull(context, nameof(context)); bool verbose = context.IsSystemDebugTrue(); return new CallbackAppTraceSource( - (str, level) => + (str, level) => { if (level == System.Diagnostics.SourceLevels.Warning) { diff --git a/src/Agent.Plugins/BuildArtifact/BuildArtifactPluginV1.cs b/src/Agent.Plugins/BuildArtifact/BuildArtifactPluginV1.cs index c80eeffc10..6b15ac9529 100644 --- a/src/Agent.Plugins/BuildArtifact/BuildArtifactPluginV1.cs +++ b/src/Agent.Plugins/BuildArtifact/BuildArtifactPluginV1.cs @@ -75,10 +75,11 @@ public class DownloadBuildArtifactTaskV1_0_0 : BuildArtifactTaskPluginBaseV1 static readonly string buildVersionToDownloadSpecific = "specific"; static readonly string buildVersionToDownloadLatestFromBranch = "latestFromBranch"; static readonly string extractedTarsTempDir = "extracted_tars"; - static readonly Options minimatchOptions = new Options() { - Dot = true, - NoBrace = true, - AllowWindowsPaths = PlatformUtil.RunningOnWindows + static readonly Options minimatchOptions = new Options() + { + Dot = true, + NoBrace = true, + AllowWindowsPaths = PlatformUtil.RunningOnWindows }; protected override async Task ProcessCommandInternalAsync( @@ -219,9 +220,9 @@ protected override async Task ProcessCommandInternalAsync( { throw new ArgumentNullException(StringUtil.Loc("CannotBeNullOrEmpty"), "Project Name"); } - Guid projectId; + Guid projectId; bool isProjGuid = Guid.TryParse(projectName, out projectId); - if (!isProjGuid) + if (!isProjGuid) { projectId = await GetProjectIdAsync(context, projectName); } @@ -352,7 +353,7 @@ private void CleanDirectory(AgentTaskPluginExecutionContext context, string dire { FileAttributes dirAttributes; context.Output(StringUtil.Loc("CleaningDestinationFolder", directoryPath)); - + try { dirAttributes = File.GetAttributes(directoryPath); @@ -393,7 +394,7 @@ private void CleanDirectory(AgentTaskPluginExecutionContext context, string dire private async Task GetPipelineIdAsync(AgentTaskPluginExecutionContext context, string pipelineDefinition, string buildVersionToDownload, string project, string[] tagFilters, BuildResult resultFilter = BuildResult.Succeeded, string branchName = null, CancellationToken cancellationToken = default(CancellationToken)) { - if(String.IsNullOrWhiteSpace(pipelineDefinition)) + if (String.IsNullOrWhiteSpace(pipelineDefinition)) { throw new InvalidOperationException(StringUtil.Loc("CannotBeNullOrEmpty", "Pipeline Definition")); } @@ -461,7 +462,7 @@ private BuildResult GetResultFilter(bool allowPartiallySucceededBuilds, bool all return result; } - + private async Task GetProjectIdAsync(AgentTaskPluginExecutionContext context, string projectName) { VssConnection connection = context.VssConnection; @@ -481,7 +482,8 @@ private async Task GetProjectIdAsync(AgentTaskPluginExecutionContext conte return proj.Id; } - private void OutputBuildInfo(AgentTaskPluginExecutionContext context, int? pipelineId){ + private void OutputBuildInfo(AgentTaskPluginExecutionContext context, int? pipelineId) + { context.Output(StringUtil.Loc("DownloadingFromBuild", pipelineId)); // populate output variable 'BuildNumber' with buildId context.SetVariable("BuildNumber", pipelineId.ToString()); diff --git a/src/Agent.Plugins/GitCliManager.cs b/src/Agent.Plugins/GitCliManager.cs index 00aad05d5c..ca36a5c69d 100644 --- a/src/Agent.Plugins/GitCliManager.cs +++ b/src/Agent.Plugins/GitCliManager.cs @@ -190,7 +190,7 @@ public async Task GitFetch(AgentTaskPluginExecutionContext context, string // If shallow fetch add --depth arg // If the local repository is shallowed but there is no fetch depth provide for this build, // add --unshallow to convert the shallow repository to a complete repository - string depth = fetchDepth > 0 ? $"--depth={fetchDepth}" : (File.Exists(Path.Combine(repositoryPath, ".git", "shallow")) ? "--unshallow" : string.Empty ); + string depth = fetchDepth > 0 ? $"--depth={fetchDepth}" : (File.Exists(Path.Combine(repositoryPath, ".git", "shallow")) ? "--unshallow" : string.Empty); //define options for fetch string options = $"{forceTag} {tags} --prune {pruneTags} {progress} --no-recurse-submodules {remoteName} {depth} {string.Join(" ", refSpec)}"; @@ -244,7 +244,8 @@ public async Task GitLFSFetch(AgentTaskPluginExecutionContext context, stri // default options for git checkout .lfsconfig string options = StringUtil.Format($"{refSpec} -- {lfsconfig}"); int exitCodeLfsConfigCheckout = await ExecuteGitCommandAsync(context, repositoryPath, "checkout", options, additionalCommandLine, cancellationToken); - if (exitCodeLfsConfigCheckout != 0) { + if (exitCodeLfsConfigCheckout != 0) + { context.Debug("There were some issues while checkout of .lfsconfig - probably because this file does not exist (see message above for more details). Continue fetching."); } diff --git a/src/Agent.Plugins/GitSourceProvider.cs b/src/Agent.Plugins/GitSourceProvider.cs index 4a47f5776d..6af5fd4804 100644 --- a/src/Agent.Plugins/GitSourceProvider.cs +++ b/src/Agent.Plugins/GitSourceProvider.cs @@ -695,7 +695,7 @@ public async Task GetSourceAsync( if (await gitCommandManager.GitConfigExist(executionContext, targetPath, $"http.extraheader", existingExtraheaders)) { executionContext.Debug("Remove http.extraheader setting from git config."); - foreach(var configValue in existingExtraheaders) + foreach (var configValue in existingExtraheaders) { await RemoveGitConfig(executionContext, gitCommandManager, targetPath, $"http.extraheader", configValue); } diff --git a/src/Agent.Plugins/PipelineArtifact/FilePathServer.cs b/src/Agent.Plugins/PipelineArtifact/FilePathServer.cs index 9ff2759b74..3e470e6c52 100644 --- a/src/Agent.Plugins/PipelineArtifact/FilePathServer.cs +++ b/src/Agent.Plugins/PipelineArtifact/FilePathServer.cs @@ -74,20 +74,20 @@ internal static class FileShareArtifactUploadEventProperties private int GetParallelCount(AgentTaskPluginExecutionContext context, string parallelCount) { var result = 8; - if(int.TryParse(parallelCount, out result)) + if (int.TryParse(parallelCount, out result)) { - if(result < 1) + if (result < 1) { context.Output(StringUtil.Loc("UnexpectedParallelCount")); result = 1; } - else if(result > 128) + else if (result > 128) { context.Output(StringUtil.Loc("UnexpectedParallelCount")); result = 128; } } - else + else { throw new ArgumentException(StringUtil.Loc("ParallelCountNotANumber")); } diff --git a/src/Agent.Plugins/PipelineArtifact/PipelineArtifactPlugin.cs b/src/Agent.Plugins/PipelineArtifact/PipelineArtifactPlugin.cs index 6781325275..dff8e2eebd 100644 --- a/src/Agent.Plugins/PipelineArtifact/PipelineArtifactPlugin.cs +++ b/src/Agent.Plugins/PipelineArtifact/PipelineArtifactPlugin.cs @@ -29,7 +29,7 @@ public async Task RunAsync(AgentTaskPluginExecutionContext context, Cancellation // Path // TODO: Translate targetPath from container to host (Ting) string targetPath = context.GetInput(ArtifactEventProperties.TargetPath, required: true); - + this.tracer = context.CreateArtifactsTracer(); await ProcessCommandInternalAsync(context, targetPath, token); @@ -83,7 +83,8 @@ protected override async Task ProcessCommandInternalAsync( } string hostType = context.Variables.GetValueOrDefault("system.hosttype")?.Value; - if (!string.Equals(hostType, "Build", StringComparison.OrdinalIgnoreCase)) { + if (!string.Equals(hostType, "Build", StringComparison.OrdinalIgnoreCase)) + { throw new InvalidOperationException( StringUtil.Loc("CannotUploadFromCurrentEnvironment", hostType ?? string.Empty)); } diff --git a/src/Agent.Plugins/PipelineArtifact/PipelineArtifactPluginUtil.cs b/src/Agent.Plugins/PipelineArtifact/PipelineArtifactPluginUtil.cs index 3d955ea8cf..fce6b44206 100644 --- a/src/Agent.Plugins/PipelineArtifact/PipelineArtifactPluginUtil.cs +++ b/src/Agent.Plugins/PipelineArtifact/PipelineArtifactPluginUtil.cs @@ -21,7 +21,8 @@ public static class PipelineArtifactPathHelper '"', ':', '<', '>', '|', '*', '?', '/', '\\' }; private static readonly HashSet ForbiddenArtifactNameCharsSet = new HashSet(ForbiddenArtifactNameChars); - public static bool IsValidArtifactName(string artifactName){ + public static bool IsValidArtifactName(string artifactName) + { return !artifactName.Any(c => ForbiddenArtifactNameCharsSet.Contains(c)); } } diff --git a/src/Agent.Plugins/PipelineArtifact/PipelineArtifactPluginV2.cs b/src/Agent.Plugins/PipelineArtifact/PipelineArtifactPluginV2.cs index b7de85a5d5..5e297ac23a 100644 --- a/src/Agent.Plugins/PipelineArtifact/PipelineArtifactPluginV2.cs +++ b/src/Agent.Plugins/PipelineArtifact/PipelineArtifactPluginV2.cs @@ -68,7 +68,7 @@ public class DownloadPipelineArtifactTaskV2_0_0 : PipelineArtifactTaskPluginBase static readonly string pipelineVersionToDownloadLatest = "latest"; static readonly string pipelineVersionToDownloadSpecific = "specific"; static readonly string pipelineVersionToDownloadLatestFromBranch = "latestFromBranch"; - private const int MaxRetries = 3; + private const int MaxRetries = 3; protected override async Task ProcessCommandInternalAsync( AgentTaskPluginExecutionContext context, @@ -96,7 +96,7 @@ protected override async Task ProcessCommandInternalAsync( context.Debug($"TargetPath: {targetPath}"); bool onPrem = !String.Equals(context.Variables.GetValueOrDefault(WellKnownDistributedTaskVariables.ServerType)?.Value, "Hosted", StringComparison.OrdinalIgnoreCase); - + if (onPrem) { throw new InvalidOperationException(StringUtil.Loc("OnPremIsNotSupported")); @@ -148,7 +148,7 @@ protected override async Task ProcessCommandInternalAsync( { throw new ArgumentNullException(StringUtil.Loc("CannotBeNullOrEmpty"), "Project ID"); } - + Guid projectId = Guid.Parse(projectIdStr); ArgUtil.NotEmpty(projectId, nameof(projectId)); context.Debug($"ProjectId: {projectId.ToString()}"); @@ -195,9 +195,9 @@ protected override async Task ProcessCommandInternalAsync( { throw new ArgumentNullException(StringUtil.Loc("CannotBeNullOrEmpty"), "Project Name"); } - Guid projectId; + Guid projectId; bool isProjGuid = Guid.TryParse(projectName, out projectId); - if (!isProjGuid) + if (!isProjGuid) { projectId = await GetProjectIdAsync(context, projectName, token); } @@ -250,7 +250,7 @@ protected override async Task ProcessCommandInternalAsync( else if (pipelineVersionToDownload == pipelineVersionToDownloadSpecific) { bool isPipelineIdNum = Int32.TryParse(userSpecifiedRunId, out pipelineId); - if(!isPipelineIdNum) + if (!isPipelineIdNum) { throw new ArgumentException(StringUtil.Loc("RunIDNotValid", userSpecifiedRunId)); } @@ -328,7 +328,7 @@ private async Task GetPipelineIdAsync( string branchName = null, CancellationToken cancellationToken = default(CancellationToken)) { - if(String.IsNullOrWhiteSpace(pipelineDefinition)) + if (String.IsNullOrWhiteSpace(pipelineDefinition)) { throw new InvalidOperationException(StringUtil.Loc("CannotBeNullOrEmpty", "Pipeline Definition")); } @@ -346,9 +346,9 @@ private async Task GetPipelineIdAsync( context: "GetBuildDefinitionReferencesByName", cancellationToken: cancellationToken, continueOnCapturedContext: false); - + var definitionRef = definitionReferencesWithName.FirstOrDefault(); - + if (definitionRef == null) { throw new ArgumentException(StringUtil.Loc("PipelineDoesNotExist", pipelineDefinition)); @@ -430,12 +430,12 @@ private BuildResult GetResultFilter(bool allowPartiallySucceededBuilds, bool all return result; } - + private async Task GetProjectIdAsync(AgentTaskPluginExecutionContext context, string projectName, CancellationToken cancellationToken) { VssConnection connection = context.VssConnection; var projectClient = connection.GetClient(); - + try { TeamProject project = await AsyncHttpRetryHelper.InvokeAsync( @@ -453,7 +453,8 @@ private async Task GetProjectIdAsync(AgentTaskPluginExecutionContext conte } } - private void OutputBuildInfo(AgentTaskPluginExecutionContext context, int? pipelineId){ + private void OutputBuildInfo(AgentTaskPluginExecutionContext context, int? pipelineId) + { context.Output(StringUtil.Loc("DownloadingFromBuild", pipelineId)); // populate output variable 'BuildNumber' with buildId context.SetVariable("BuildNumber", pipelineId.ToString()); diff --git a/src/Agent.Plugins/PipelineArtifact/Telemetry/FileShareActionRecord.cs b/src/Agent.Plugins/PipelineArtifact/Telemetry/FileShareActionRecord.cs index faa7ec3876..47efc265e3 100644 --- a/src/Agent.Plugins/PipelineArtifact/Telemetry/FileShareActionRecord.cs +++ b/src/Agent.Plugins/PipelineArtifact/Telemetry/FileShareActionRecord.cs @@ -42,7 +42,7 @@ protected override void SetMeasuredActionResult(T value) } } } - + public sealed class FileSharePublishResult { public int ExitCode { get; private set; } diff --git a/src/Agent.Plugins/PipelineCache/FingerprintCreator.cs b/src/Agent.Plugins/PipelineCache/FingerprintCreator.cs index 71827ed2f4..51d7f65cde 100644 --- a/src/Agent.Plugins/PipelineCache/FingerprintCreator.cs +++ b/src/Agent.Plugins/PipelineCache/FingerprintCreator.cs @@ -32,7 +32,7 @@ public static class FingerprintCreator AllowWindowsPaths = isWindows, }; - private static readonly char[] GlobChars = new [] { '*', '?', '[', ']' }; + private static readonly char[] GlobChars = new[] { '*', '?', '[', ']' }; private const char ForceStringLiteral = '"'; @@ -49,7 +49,7 @@ internal static bool IsPathyKeySegment(string keySegment) { if (keySegment.First() == ForceStringLiteral && keySegment.Last() == ForceStringLiteral) return false; if (keySegment.Any(c => !IsPathyChar(c))) return false; - if (!keySegment.Contains(".") && + if (!keySegment.Contains(".") && !keySegment.Contains(Path.DirectorySeparatorChar) && !keySegment.Contains(Path.AltDirectorySeparatorChar)) return false; if (keySegment.Last() == '.') return false; @@ -58,8 +58,9 @@ internal static bool IsPathyKeySegment(string keySegment) internal static Func CreateMinimatchFilter(AgentTaskPluginExecutionContext context, string rule, bool invert) { - Func filter = Minimatcher.CreateFilter(rule, minimatchOptions); - Func tracedFilter = (path) => { + Func filter = Minimatcher.CreateFilter(rule, minimatchOptions); + Func tracedFilter = (path) => + { bool filterResult = filter(path); context.Verbose($"Path `{path}` is {(filterResult ? "" : "not ")}{(invert ? "excluded" : "included")} because of pattern `{(invert ? "!" : "")}{rule}`."); return invert ^ filterResult; @@ -81,16 +82,16 @@ internal static string MakePathCanonical(string defaultWorkingDirectory, string } } - internal static Func CreateFilter( + internal static Func CreateFilter( AgentTaskPluginExecutionContext context, IEnumerable includeRules, IEnumerable excludeRules) { - Func[] includeFilters = includeRules.Select(includeRule => + Func[] includeFilters = includeRules.Select(includeRule => CreateMinimatchFilter(context, includeRule, invert: false)).ToArray(); - Func[] excludeFilters = excludeRules.Select(excludeRule => + Func[] excludeFilters = excludeRules.Select(excludeRule => CreateMinimatchFilter(context, excludeRule, invert: true)).ToArray(); - Func filter = (path) => includeFilters.Any(f => f(path)) && excludeFilters.All(f => f(path)); + Func filter = (path) => includeFilters.Any(f => f(path)) && excludeFilters.All(f => f(path)); return filter; } @@ -109,10 +110,10 @@ public MatchedFile(string displayPath, long fileLength, string hash) { this.DisplayPath = displayPath; this.FileLength = fileLength; - this.Hash = hash; + this.Hash = hash; } - public MatchedFile(string displayPath, FileStream fs): + public MatchedFile(string displayPath, FileStream fs) : this(displayPath, fs.Length, s_sha256.ComputeHash(fs).ToHex()) { } @@ -121,11 +122,13 @@ public MatchedFile(string displayPath, FileStream fs): public long FileLength; public string Hash; - public string GetHash() { - return MatchedFile.GenerateHash(new [] { this }); + public string GetHash() + { + return MatchedFile.GenerateHash(new[] { this }); } - public static string GenerateHash(IEnumerable matches) { + public static string GenerateHash(IEnumerable matches) + { string s = matches.Aggregate(new StringBuilder(), (sb, file) => sb.Append($"\nSHA256({file.DisplayPath})=[{file.FileLength}]{file.Hash}"), sb => sb.ToString()); @@ -159,7 +162,8 @@ internal static Enumeration DetermineFileEnumerationFromGlob(string includeGlobP // no globbing if (firstGlob < 0) { - return new Enumeration() { + return new Enumeration() + { RootPath = Path.GetDirectoryName(includeGlobPathAbsolute), Pattern = Path.GetFileName(includeGlobPathAbsolute), Depth = SearchOption.TopDirectoryOnly @@ -167,9 +171,10 @@ internal static Enumeration DetermineFileEnumerationFromGlob(string includeGlobP } else { - int rootDirLength = includeGlobPathAbsolute.Substring(0,firstGlob).LastIndexOfAny( new [] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}); - return new Enumeration() { - RootPath = includeGlobPathAbsolute.Substring(0,rootDirLength), + int rootDirLength = includeGlobPathAbsolute.Substring(0, firstGlob).LastIndexOfAny(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }); + return new Enumeration() + { + RootPath = includeGlobPathAbsolute.Substring(0, rootDirLength), Pattern = "*", Depth = hasRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly }; @@ -216,7 +221,7 @@ public static Fingerprint EvaluateKeyToFingerprint( Action LogKeySegment = (segment, type, details) => { - Func FormatForDisplay = (value, displayLength) => + Func FormatForDisplay = (value, displayLength) => { if (value.Length > displayLength) { @@ -235,7 +240,7 @@ public static Fingerprint EvaluateKeyToFingerprint( else { var matches = (details as MatchedFile[]) ?? new MatchedFile[0]; - + if (type == KeySegmentType.FilePath) { string fileHash = matches.Length > 0 ? matches[0].Hash : null; @@ -252,9 +257,9 @@ public static Fingerprint EvaluateKeyToFingerprint( context.Output($" - {FormatForDisplay(match.DisplayPath, filePathDisplayLength)} --> {match.Hash}"); } } - } + } } - }; + }; foreach (string keySegment in keySegments) { @@ -265,7 +270,7 @@ public static Fingerprint EvaluateKeyToFingerprint( } else { - string[] pathRules = keySegment.Split(new []{','}, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray(); + string[] pathRules = keySegment.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray(); string[] includeRules = pathRules.Where(p => !p.StartsWith('!')).ToArray(); if (!includeRules.Any()) @@ -273,38 +278,39 @@ public static Fingerprint EvaluateKeyToFingerprint( throw new ArgumentException("No include rules specified."); } - var enumerations = new Dictionary>(); - foreach(string includeRule in includeRules) + var enumerations = new Dictionary>(); + foreach (string includeRule in includeRules) { string absoluteRootRule = MakePathCanonical(defaultWorkingDirectory, includeRule); context.Verbose($"Expanded include rule is `{absoluteRootRule}`."); Enumeration enumeration = DetermineFileEnumerationFromGlob(absoluteRootRule); List globs; - if(!enumerations.TryGetValue(enumeration, out globs)) + if (!enumerations.TryGetValue(enumeration, out globs)) { - enumerations[enumeration] = globs = new List(); + enumerations[enumeration] = globs = new List(); } globs.Add(absoluteRootRule); } string[] excludeRules = pathRules.Where(p => p.StartsWith('!')).ToArray(); - string[] absoluteExcludeRules = excludeRules.Select(excludeRule => { + string[] absoluteExcludeRules = excludeRules.Select(excludeRule => + { excludeRule = excludeRule.Substring(1); return MakePathCanonical(defaultWorkingDirectory, excludeRule); }).ToArray(); var matchedFiles = new SortedDictionary(StringComparer.Ordinal); - foreach(var kvp in enumerations) + foreach (var kvp in enumerations) { Enumeration enumerate = kvp.Key; List absoluteIncludeGlobs = kvp.Value; context.Verbose($"Enumerating starting at root `{enumerate.RootPath}` with pattern `{enumerate.Pattern}` and depth `{enumerate.Depth}`."); IEnumerable files = Directory.EnumerateFiles(enumerate.RootPath, enumerate.Pattern, enumerate.Depth); - Func filter = CreateFilter(context, absoluteIncludeGlobs, absoluteExcludeRules); + Func filter = CreateFilter(context, absoluteIncludeGlobs, absoluteExcludeRules); files = files.Where(f => filter(f)).Distinct(); - foreach(string path in files) + foreach (string path in files) { using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { @@ -324,7 +330,7 @@ public static Fingerprint EvaluateKeyToFingerprint( displayKeySegment = context.Container.TranslateToContainerPath(displayKeySegment); } - LogKeySegment(displayKeySegment, + LogKeySegment(displayKeySegment, patternSegment ? KeySegmentType.FilePattern : KeySegmentType.FilePath, matchedFiles.Values.ToArray()); @@ -339,9 +345,9 @@ public static Fingerprint EvaluateKeyToFingerprint( exceptions.Add(new FileNotFoundException($"File not found: {displayKeySegment}")); } } - + resolvedSegments.Add(MatchedFile.GenerateHash(matchedFiles.Values)); - } + } } if (exceptions.Any()) diff --git a/src/Agent.Plugins/PipelineCache/PipelineCacheServer.cs b/src/Agent.Plugins/PipelineCache/PipelineCacheServer.cs index dd83002c82..df2f3ec496 100644 --- a/src/Agent.Plugins/PipelineCache/PipelineCacheServer.cs +++ b/src/Agent.Plugins/PipelineCache/PipelineCacheServer.cs @@ -56,7 +56,7 @@ internal async Task UploadAsync( // Check if the key exists. PipelineCacheActionRecord cacheRecordGet = clientTelemetry.CreateRecord((level, uri, type) => new PipelineCacheActionRecord(level, uri, type, PipelineArtifactConstants.RestoreCache, context)); - PipelineCacheArtifact getResult = await pipelineCacheClient.GetPipelineCacheArtifactAsync(new [] {fingerprint}, cancellationToken, cacheRecordGet); + PipelineCacheArtifact getResult = await pipelineCacheClient.GetPipelineCacheArtifactAsync(new[] { fingerprint }, cancellationToken, cacheRecordGet); // Send results to CustomerIntelligence context.PublishTelemetry(area: PipelineArtifactConstants.AzurePipelinesAgent, feature: PipelineArtifactConstants.PipelineCache, record: cacheRecordGet); //If cache exists, return. @@ -217,7 +217,7 @@ await clientTelemetry.MeasureActionAsync( context.Verbose($"Exact fingerprint: `{result.Fingerprint.ToString()}`"); bool foundExact = false; - foreach(var fingerprint in fingerprints) + foreach (var fingerprint in fingerprints) { context.Verbose($"This fingerprint: `{fingerprint.ToString()}`"); @@ -269,7 +269,7 @@ private async Task CreateClientAsync( private async Task GetUploadPathAsync(ContentFormat contentFormat, AgentTaskPluginExecutionContext context, string path, CancellationToken cancellationToken) { string uploadPath = path; - if(contentFormat == ContentFormat.SingleTar) + if (contentFormat == ContentFormat.SingleTar) { uploadPath = await TarUtils.ArchiveFilesToTarAsync(context, path, cancellationToken); } @@ -301,15 +301,15 @@ await AsyncHttpRetryHelper.InvokeVoidAsync( continueOnCapturedContext: false); Manifest manifest = JsonSerializer.Deserialize(File.ReadAllText(manifestPath)); - await TarUtils.DownloadAndExtractTarAsync (context, manifest, dedupManifestClient, targetDirectory, cancellationToken); + await TarUtils.DownloadAndExtractTarAsync(context, manifest, dedupManifestClient, targetDirectory, cancellationToken); try { - if(File.Exists(manifestPath)) + if (File.Exists(manifestPath)) { File.Delete(manifestPath); } } - catch {} + catch { } } else { diff --git a/src/Agent.Plugins/PipelineCache/PipelineCacheTaskPluginBase.cs b/src/Agent.Plugins/PipelineCache/PipelineCacheTaskPluginBase.cs index f7c805c26a..d7b682f8ca 100644 --- a/src/Agent.Plugins/PipelineCache/PipelineCacheTaskPluginBase.cs +++ b/src/Agent.Plugins/PipelineCache/PipelineCacheTaskPluginBase.cs @@ -31,26 +31,27 @@ public abstract class PipelineCacheTaskPluginBase : IAgentTaskPlugin public abstract String Stage { get; } public const string ResolvedFingerPrintVariableName = "RESTORE_STEP_RESOLVED_FINGERPRINT"; - internal static (bool isOldFormat, string[] keySegments,IEnumerable restoreKeys) ParseIntoSegments(string salt, string key, string restoreKeysBlock) + internal static (bool isOldFormat, string[] keySegments, IEnumerable restoreKeys) ParseIntoSegments(string salt, string key, string restoreKeysBlock) { - Func splitAcrossPipes = (s) => { - var segments = s.Split(new [] {'|'},StringSplitOptions.RemoveEmptyEntries).Select(segment => segment.Trim()); - if(!string.IsNullOrWhiteSpace(salt)) + Func splitAcrossPipes = (s) => + { + var segments = s.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(segment => segment.Trim()); + if (!string.IsNullOrWhiteSpace(salt)) { - segments = (new [] { $"{SaltVariableName}={salt}"}).Concat(segments); + segments = (new[] { $"{SaltVariableName}={salt}" }).Concat(segments); } return segments.ToArray(); }; - Func splitAcrossNewlines = (s) => + Func splitAcrossNewlines = (s) => s.Replace("\r\n", "\n") //normalize newlines - .Split(new [] {'\n'}, StringSplitOptions.RemoveEmptyEntries) + .Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries) .Select(line => line.Trim()) .ToArray(); - + string[] keySegments; bool isOldFormat = key.Contains('\n'); - + IEnumerable restoreKeys; bool hasRestoreKeys = !string.IsNullOrWhiteSpace(restoreKeysBlock); @@ -58,7 +59,7 @@ internal static (bool isOldFormat, string[] keySegments,IEnumerable re { throw new ArgumentException(OldKeyFormatMessage); } - + if (isOldFormat) { keySegments = splitAcrossNewlines(key); @@ -67,7 +68,7 @@ internal static (bool isOldFormat, string[] keySegments,IEnumerable re { keySegments = splitAcrossPipes(key); } - + if (hasRestoreKeys) { @@ -80,7 +81,7 @@ internal static (bool isOldFormat, string[] keySegments,IEnumerable re return (isOldFormat, keySegments, restoreKeys); } - + public async virtual Task RunAsync(AgentTaskPluginExecutionContext context, CancellationToken token) { ArgUtil.NotNull(context, nameof(context)); @@ -105,11 +106,12 @@ public async virtual Task RunAsync(AgentTaskPluginExecutionContext context, Canc Fingerprint keyFp = FingerprintCreator.EvaluateKeyToFingerprint(context, workspaceRoot, keySegments); context.Output($"Resolved to: {keyFp}"); - Func restoreKeysGenerator = () => - restoreKeys.Select(restoreKey => { + Func restoreKeysGenerator = () => + restoreKeys.Select(restoreKey => + { context.Output("Resolving restore key:"); Fingerprint f = FingerprintCreator.EvaluateKeyToFingerprint(context, workspaceRoot, restoreKey); - f.Segments = f.Segments.Concat(new [] { Fingerprint.Wildcard} ).ToArray(); + f.Segments = f.Segments.Concat(new[] { Fingerprint.Wildcard }).ToArray(); context.Output($"Resolved to: {f}"); return f; }).ToArray(); diff --git a/src/Agent.Plugins/PipelineCache/RestorePipelineCacheV0.cs b/src/Agent.Plugins/PipelineCache/RestorePipelineCacheV0.cs index de0805ef51..8ed95439c3 100644 --- a/src/Agent.Plugins/PipelineCache/RestorePipelineCacheV0.cs +++ b/src/Agent.Plugins/PipelineCache/RestorePipelineCacheV0.cs @@ -9,7 +9,7 @@ using Microsoft.VisualStudio.Services.PipelineCache.WebApi; namespace Agent.Plugins.PipelineCache -{ +{ public class RestorePipelineCacheV0 : PipelineCacheTaskPluginBase { public override string Stage => "main"; @@ -27,8 +27,8 @@ protected override async Task ProcessCommandInternalAsync( var server = new PipelineCacheServer(context); Fingerprint[] restoreFingerprints = restoreKeysGenerator(); await server.DownloadAsync( - context, - (new [] { fingerprint}).Concat(restoreFingerprints).ToArray(), + context, + (new[] { fingerprint }).Concat(restoreFingerprints).ToArray(), path, context.GetInput(PipelineCacheTaskPluginConstants.CacheHitVariable, required: false), token); diff --git a/src/Agent.Plugins/PipelineCache/SavePipelineCacheV0.cs b/src/Agent.Plugins/PipelineCache/SavePipelineCacheV0.cs index 4967e03fd6..4b7805fddb 100644 --- a/src/Agent.Plugins/PipelineCache/SavePipelineCacheV0.cs +++ b/src/Agent.Plugins/PipelineCache/SavePipelineCacheV0.cs @@ -62,15 +62,15 @@ protected override async Task ProcessCommandInternalAsync( string path, CancellationToken token) { - string contentFormatValue = context.Variables.GetValueOrDefault(ContentFormatVariableName)?.Value ?? string.Empty; + string contentFormatValue = context.Variables.GetValueOrDefault(ContentFormatVariableName)?.Value ?? string.Empty; string calculatedFingerPrint = context.TaskVariables.GetValueOrDefault(ResolvedFingerPrintVariableName)?.Value ?? string.Empty; - if(!string.IsNullOrWhiteSpace(calculatedFingerPrint) && !fingerprint.ToString().Equals(calculatedFingerPrint, StringComparison.Ordinal)) + if (!string.IsNullOrWhiteSpace(calculatedFingerPrint) && !fingerprint.ToString().Equals(calculatedFingerPrint, StringComparison.Ordinal)) { - context.Warning($"The given cache key has changed in its resolved value between restore and save steps;\n"+ - $"original key: {calculatedFingerPrint}\n"+ + context.Warning($"The given cache key has changed in its resolved value between restore and save steps;\n" + + $"original key: {calculatedFingerPrint}\n" + $"modified key: {fingerprint}\n"); - } + } ContentFormat contentFormat; if (string.IsNullOrWhiteSpace(contentFormatValue)) @@ -85,7 +85,7 @@ protected override async Task ProcessCommandInternalAsync( PipelineCacheServer server = new PipelineCacheServer(context); await server.UploadAsync( context, - fingerprint, + fingerprint, path, token, contentFormat); diff --git a/src/Agent.Plugins/PipelineCache/TarUtils.cs b/src/Agent.Plugins/PipelineCache/TarUtils.cs index 82902fd803..9ea9afea1b 100644 --- a/src/Agent.Plugins/PipelineCache/TarUtils.cs +++ b/src/Agent.Plugins/PipelineCache/TarUtils.cs @@ -31,7 +31,7 @@ public static async Task ArchiveFilesToTarAsync( string inputPath, CancellationToken cancellationToken) { - if(File.Exists(inputPath)) + if (File.Exists(inputPath)) { throw new DirectoryNotFoundException($"Please specify path to a directory, File path is not allowed. {inputPath} is a file."); } @@ -75,14 +75,15 @@ public static Task DownloadAndExtractTarAsync( ValidateTarManifest(manifest); Directory.CreateDirectory(targetDirectory); - - DedupIdentifier dedupId = DedupIdentifier.Create(manifest.Items.Single(i => i.Path.EndsWith(archive, StringComparison.OrdinalIgnoreCase)).Blob.Id); + + DedupIdentifier dedupId = DedupIdentifier.Create(manifest.Items.Single(i => i.Path.EndsWith(archive, StringComparison.OrdinalIgnoreCase)).Blob.Id); ProcessStartInfo processStartInfo = GetExtractStartProcessInfo(context, targetDirectory); Func downloadTaskFunc = (process, ct) => - Task.Run(async () => { + Task.Run(async () => + { try { await dedupManifestClient.DownloadToStreamAsync(dedupId, process.StandardInput.BaseStream, proxyUri: null, cancellationToken: ct); @@ -94,7 +95,7 @@ public static Task DownloadAndExtractTarAsync( { process.Kill(); } - catch {} + catch { } ExceptionDispatchInfo.Capture(e).Throw(); } }); @@ -178,17 +179,17 @@ private static ProcessStartInfo GetCreateTarProcessInfo(AgentTaskPluginExecution { processArguments = "-h " + processArguments; } - + ProcessStartInfo processStartInfo = new ProcessStartInfo(); CreateProcessStartInfo(processStartInfo, processFileName, processArguments, processWorkingDirectory: Path.GetTempPath()); // We want to create the archiveFile in temp folder, and hence starting the tar process from TEMP to avoid absolute paths in tar cmd line. return processStartInfo; } private static string GetTar(AgentTaskPluginExecutionContext context) - { + { // check if the user specified the tar executable to use: string location = Environment.GetEnvironmentVariable(TarLocationEnvironmentVariableName); - return String.IsNullOrWhiteSpace(location) ? "tar" : location; + return String.IsNullOrWhiteSpace(location) ? "tar" : location; } private static ProcessStartInfo GetExtractStartProcessInfo(AgentTaskPluginExecutionContext context, string targetDirectory) @@ -235,7 +236,7 @@ private static void TryDeleteFile(string fileName) File.Delete(fileName); } } - catch {} + catch { } } private static string CreateArchiveFileName() diff --git a/src/Agent.Plugins/RepositoryPlugin.cs b/src/Agent.Plugins/RepositoryPlugin.cs index f2760b461d..5bcd417aa6 100644 --- a/src/Agent.Plugins/RepositoryPlugin.cs +++ b/src/Agent.Plugins/RepositoryPlugin.cs @@ -93,7 +93,8 @@ protected bool HasMultipleCheckouts(AgentTaskPluginExecutionContext executionCon } protected TeeUtil teeUtil; - protected void initializeTeeUtil(AgentTaskPluginExecutionContext executionContext, CancellationToken cancellationToken) { + protected void initializeTeeUtil(AgentTaskPluginExecutionContext executionContext, CancellationToken cancellationToken) + { teeUtil = new TeeUtil( executionContext.Variables.GetValueOrDefault("Agent.HomeDirectory")?.Value, executionContext.Variables.GetValueOrDefault("Agent.TempDirectory")?.Value, diff --git a/src/Agent.Plugins/TestResultParser/Gateway/LogParserGateway.cs b/src/Agent.Plugins/TestResultParser/Gateway/LogParserGateway.cs index 7d1fb8e7d7..c5655e9425 100644 --- a/src/Agent.Plugins/TestResultParser/Gateway/LogParserGateway.cs +++ b/src/Agent.Plugins/TestResultParser/Gateway/LogParserGateway.cs @@ -63,8 +63,8 @@ public async Task CompleteAsync() _broadcast.Complete(); Task.WaitAll(_subscribers.Values.Select(x => x.Completion).ToArray()); - using (var timer = new SimpleTimer("TestRunManagerFinalize", _logger, - new TelemetryDataWrapper(_telemetry, TelemetryConstants.TestRunManagerEventArea, TelemetryConstants.FinalizeAsync), + using (var timer = new SimpleTimer("TestRunManagerFinalize", _logger, + new TelemetryDataWrapper(_telemetry, TelemetryConstants.TestRunManagerEventArea, TelemetryConstants.FinalizeAsync), TimeSpan.FromMilliseconds(Int32.MaxValue))) { await _testRunManager.FinalizeAsync(); diff --git a/src/Agent.Plugins/TestResultParser/PipelineTestRunPublisher.cs b/src/Agent.Plugins/TestResultParser/PipelineTestRunPublisher.cs index 2402aa6c0f..30151af209 100644 --- a/src/Agent.Plugins/TestResultParser/PipelineTestRunPublisher.cs +++ b/src/Agent.Plugins/TestResultParser/PipelineTestRunPublisher.cs @@ -36,9 +36,9 @@ public async Task PublishAsync(TestRun testRun) runCreateModel.PipelineReference = new PipelineReference() { PipelineId = _pipelineConfig.BuildId, - StageReference = new StageReference() { StageName = _pipelineConfig.StageName, Attempt = _pipelineConfig.StageAttempt}, - PhaseReference = new PhaseReference() { PhaseName = _pipelineConfig.PhaseName, Attempt = _pipelineConfig.PhaseAttempt}, - JobReference = new JobReference() { JobName = _pipelineConfig.JobName, Attempt = _pipelineConfig.JobAttempt} + StageReference = new StageReference() { StageName = _pipelineConfig.StageName, Attempt = _pipelineConfig.StageAttempt }, + PhaseReference = new PhaseReference() { PhaseName = _pipelineConfig.PhaseName, Attempt = _pipelineConfig.PhaseAttempt }, + JobReference = new JobReference() { JobName = _pipelineConfig.JobName, Attempt = _pipelineConfig.JobAttempt } }; // Create the test run on the server diff --git a/src/Agent.Plugins/TestResultParser/Plugin/TestResultLogPlugin.cs b/src/Agent.Plugins/TestResultParser/Plugin/TestResultLogPlugin.cs index d09d69e36a..3cfbb2a03d 100644 --- a/src/Agent.Plugins/TestResultParser/Plugin/TestResultLogPlugin.cs +++ b/src/Agent.Plugins/TestResultParser/Plugin/TestResultLogPlugin.cs @@ -51,7 +51,7 @@ public async Task InitializeAsync(IAgentLogPluginContext context) await _telemetry.PublishCumulativeTelemetryAsync(); return false; // disable the plugin } - + await _inputDataParser.InitializeAsync(_clientFactory, _pipelineConfig, _logger, _telemetry); _telemetry.AddOrUpdate(TelemetryConstants.PluginInitialized, true); } diff --git a/src/Agent.Plugins/TfsVCCliManager.cs b/src/Agent.Plugins/TfsVCCliManager.cs index 5cb8d63607..f6a8646d2f 100644 --- a/src/Agent.Plugins/TfsVCCliManager.cs +++ b/src/Agent.Plugins/TfsVCCliManager.cs @@ -103,7 +103,7 @@ protected async Task RunCommandAsync(FormatFlags formatFlags, bool quiet, int re await Task.Delay(sleep); // Use attempt+2 since we're using 0 based indexing and we're displaying this for the next attempt. - ExecutionContext.Output($@"Retrying. Attempt {attempt+2}/{retriesOnFailure}"); + ExecutionContext.Output($@"Retrying. Attempt {attempt + 2}/{retriesOnFailure}"); } // Perform one last try and fail on non-zero exit code @@ -161,7 +161,7 @@ protected async Task RunCommandAsync(FormatFlags formatFlags, bool quiet, b } ExecutionContext.Command($@"tf {arguments}"); - var result = await processInvoker.ExecuteAsync( + var result = await processInvoker.ExecuteAsync( workingDirectory: SourcesDirectory, fileName: "tf", arguments: arguments, @@ -170,7 +170,7 @@ protected async Task RunCommandAsync(FormatFlags formatFlags, bool quiet, b outputEncoding: OutputEncoding, cancellationToken: CancellationToken); - if(useSecureParameterPassing) + if (useSecureParameterPassing) { File.Delete(Path.Combine(this.SourcesDirectory, temporaryFileWithCommand)); } @@ -265,7 +265,7 @@ protected async Task TryRunPorcelainCommandAsync(Fo { arguments = formattedArguments; } - + ExecutionContext.Debug($@"tf {arguments}"); // TODO: Test whether the output encoding needs to be specified on a non-Latin OS. try @@ -284,7 +284,7 @@ await processInvoker.ExecuteAsync( result.Exception = ex; } - if(useSecretParameterPassing) + if (useSecretParameterPassing) { CleanupTfsVCOutput(ref result, formattedArguments); File.Delete(Path.Combine(this.SourcesDirectory, cmdFileName)); diff --git a/src/Agent.Sdk/CommandStringConvertor.cs b/src/Agent.Sdk/CommandStringConvertor.cs index 82d4142811..e165c55f57 100644 --- a/src/Agent.Sdk/CommandStringConvertor.cs +++ b/src/Agent.Sdk/CommandStringConvertor.cs @@ -37,7 +37,7 @@ public static string Unescape(string escaped, bool unescapePercents) } string unescaped = escaped; - + foreach (EscapeMapping mapping in _specialSymbolsMapping) { unescaped = unescaped.Replace(mapping.Replacement, mapping.Token); diff --git a/src/Agent.Sdk/ContainerInfo.cs b/src/Agent.Sdk/ContainerInfo.cs index 9e26459108..4f96740f4b 100644 --- a/src/Agent.Sdk/ContainerInfo.cs +++ b/src/Agent.Sdk/ContainerInfo.cs @@ -56,8 +56,8 @@ public ContainerInfo(Pipelines.ContainerResource container, Boolean isJobContain // Windows has never automatically enabled Docker.Sock, but Linux does. So we need to set the default here based on OS. this.MapDockerSocket = container.Properties.Get("mapDockerSocket", !PlatformUtil.RunningOnWindows); this._imageOS = PlatformUtil.HostOS; - _pathMappings = new Dictionary( PlatformUtil.RunningOnWindows ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); - this._readOnlyVolumes = container.ReadOnlyMounts != null ? new List(container.ReadOnlyMounts) : new List(); + _pathMappings = new Dictionary(PlatformUtil.RunningOnWindows ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + this._readOnlyVolumes = container.ReadOnlyMounts != null ? new List(container.ReadOnlyMounts) : new List(); if (container.Ports?.Count > 0) { @@ -93,7 +93,8 @@ public ContainerInfo(Pipelines.ContainerResource container, Boolean isJobContain public bool IsJobContainer { get; set; } public bool MapDockerSocket { get; set; } - public PlatformUtil.OS ImageOS { + public PlatformUtil.OS ImageOS + { get { return _imageOS; @@ -104,7 +105,7 @@ public PlatformUtil.OS ImageOS { _imageOS = value; if (_pathMappings != null) { - var newMappings = new Dictionary( _pathMappings.Comparer); + var newMappings = new Dictionary(_pathMappings.Comparer); foreach (var mapping in _pathMappings) { newMappings[mapping.Key] = TranslateContainerPathForImageOS(previousImageOS, mapping.Value); @@ -260,7 +261,7 @@ public string TranslateToHostPath(string path) } else { - retval = retval.Replace("\\","/"); + retval = retval.Replace("\\", "/"); } return retval; } @@ -279,7 +280,7 @@ public string TranslateContainerPathForImageOS(PlatformUtil.OS runningOs, string { if (runningOs == PlatformUtil.OS.Windows && ImageOS == PlatformUtil.OS.Linux) { - return translateWindowsDriveRegex.Replace(path,"/").Replace("\\", "/"); + return translateWindowsDriveRegex.Replace(path, "/").Replace("\\", "/"); } } return path; diff --git a/src/Agent.Sdk/Knob/Knob.cs b/src/Agent.Sdk/Knob/Knob.cs index 4edec2f8b0..96b76487a1 100644 --- a/src/Agent.Sdk/Knob/Knob.cs +++ b/src/Agent.Sdk/Knob/Knob.cs @@ -40,7 +40,7 @@ public SecretKnob(string name, string description, params IKnobSource[] sources) public class Knob { public string Name { get; private set; } - public ICompositeKnobSource Source { get; private set;} + public ICompositeKnobSource Source { get; private set; } public string Description { get; private set; } public virtual bool IsDeprecated => false; // is going away at a future date public virtual bool IsExperimental => false; // may go away at a future date @@ -66,10 +66,10 @@ public KnobValue GetValue(IKnobValueContext context) public KnobValue GetValue(IKnobValueContext context) { - ArgUtil.NotNull(context, nameof(context)); - ArgUtil.NotNull(Source, nameof(Source)); + ArgUtil.NotNull(context, nameof(context)); + ArgUtil.NotNull(Source, nameof(Source)); - return Source.GetValue(context); + return Source.GetValue(context); } public static List GetAllKnobsFor() diff --git a/src/Agent.Sdk/Knob/KnobValue.cs b/src/Agent.Sdk/Knob/KnobValue.cs index 608bacafb8..64f6752a94 100644 --- a/src/Agent.Sdk/Knob/KnobValue.cs +++ b/src/Agent.Sdk/Knob/KnobValue.cs @@ -7,7 +7,7 @@ namespace Agent.Sdk.Knob { public class KnobValue { - public IKnobSource Source { get; private set;} + public IKnobSource Source { get; private set; } private string _value; public KnobValue(string value, IKnobSource source) diff --git a/src/Agent.Sdk/MountVolume.cs b/src/Agent.Sdk/MountVolume.cs index 0e0c687fc4..e004e3c583 100644 --- a/src/Agent.Sdk/MountVolume.cs +++ b/src/Agent.Sdk/MountVolume.cs @@ -42,14 +42,14 @@ private void ParseVolumeString(string volume) if (volume.EndsWith(readonlyToken, System.StringComparison.OrdinalIgnoreCase)) { ReadOnly = true; - volume = volume.Remove(volume.Length-readonlyToken.Length); + volume = volume.Remove(volume.Length - readonlyToken.Length); } // for completeness, in case someone explicitly added :rw in the volume mapping, we should strip it as well string readWriteToken = ":rw"; if (volume.EndsWith(readWriteToken, System.StringComparison.OrdinalIgnoreCase)) { ReadOnly = false; - volume = volume.Remove(volume.Length-readWriteToken.Length); + volume = volume.Remove(volume.Length - readWriteToken.Length); } // if volume starts with a ":", this is the same as having only a single path diff --git a/src/Agent.Sdk/ProcessInvoker.cs b/src/Agent.Sdk/ProcessInvoker.cs index 3c6971ddf7..35014614d7 100644 --- a/src/Agent.Sdk/ProcessInvoker.cs +++ b/src/Agent.Sdk/ProcessInvoker.cs @@ -62,7 +62,7 @@ public void Reset() } } - public bool DisableWorkerCommands {get; set; } + public bool DisableWorkerCommands { get; set; } public event EventHandler OutputDataReceived; public event EventHandler ErrorDataReceived; @@ -363,8 +363,8 @@ public async Task ExecuteAsync( // data buffers one last time before returning ProcessOutput(); - if(_proc.HasExited) - { + if (_proc.HasExited) + { Trace.Info($"Finished process {_proc.Id} with exit code {_proc.ExitCode}, and elapsed time {_stopWatch.Elapsed}."); } else diff --git a/src/Agent.Sdk/ScopedEnvironment.cs b/src/Agent.Sdk/ScopedEnvironment.cs index e8457243f0..96bc32011c 100644 --- a/src/Agent.Sdk/ScopedEnvironment.cs +++ b/src/Agent.Sdk/ScopedEnvironment.cs @@ -34,14 +34,14 @@ public string GetEnvironmentVariable(string key) public class LocalEnvironment : IScopedEnvironment { - private Dictionary _delegate = null; + private Dictionary _delegate = null; public LocalEnvironment() : this(null) { } - - public LocalEnvironment(Dictionary data) + + public LocalEnvironment(Dictionary data) { _delegate = data; if (_delegate == null) @@ -56,7 +56,7 @@ public IDictionary GetEnvironmentVariables() // is used in foreach statements that modify the environment. This // is allowed from Environment class since the methods are not typed to a // a single object. - return new Dictionary(_delegate); + return new Dictionary(_delegate); } public void SetEnvironmentVariable(string key, string value) diff --git a/src/Agent.Sdk/Util/ExceptionsUtil.cs b/src/Agent.Sdk/Util/ExceptionsUtil.cs index de7640afbd..29da4be311 100644 --- a/src/Agent.Sdk/Util/ExceptionsUtil.cs +++ b/src/Agent.Sdk/Util/ExceptionsUtil.cs @@ -21,13 +21,13 @@ public static void HandleAggregateException(AggregateException e, Action traceErrorAction(ex.ToString()); } } - + public static void HandleSocketException(SocketException e, string url, Action traceErrorAction) { traceErrorAction("SocketException occurred."); traceErrorAction(e.Message); - traceErrorAction($"Verify whether you have (network) access to { url }"); - traceErrorAction($"URLs the agent need communicate with - { BlobStoreWarningInfoProvider.GetAllowListLinkForCurrentPlatform() }"); + traceErrorAction($"Verify whether you have (network) access to {url}"); + traceErrorAction($"URLs the agent need communicate with - {BlobStoreWarningInfoProvider.GetAllowListLinkForCurrentPlatform()}"); } } } diff --git a/src/Agent.Sdk/Util/IOUtil.cs b/src/Agent.Sdk/Util/IOUtil.cs index 27fdb71a67..efa0f72832 100644 --- a/src/Agent.Sdk/Util/IOUtil.cs +++ b/src/Agent.Sdk/Util/IOUtil.cs @@ -521,7 +521,7 @@ public static string GetDirectoryName(string path, PlatformUtil.OS platform) if (platform == PlatformUtil.OS.Windows) { var paths = path.TrimEnd('\\', '/') - .Split(new char[] {'\\','/'}, StringSplitOptions.RemoveEmptyEntries); + .Split(new char[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries); Array.Resize(ref paths, paths.Length - 1); return string.Join('\\', paths); } diff --git a/src/Agent.Sdk/Util/PlatformUtil.cs b/src/Agent.Sdk/Util/PlatformUtil.cs index 0b72300a5e..53d5bfd108 100644 --- a/src/Agent.Sdk/Util/PlatformUtil.cs +++ b/src/Agent.Sdk/Util/PlatformUtil.cs @@ -322,7 +322,8 @@ private async static Task GetNet6SupportedSystems() string supportOSfilePath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "net6.json"); string supportOSfileContent; - if (!File.Exists(supportOSfilePath) || File.GetLastWriteTimeUtc(supportOSfilePath) < DateTime.UtcNow.AddHours(-1)) { + if (!File.Exists(supportOSfilePath) || File.GetLastWriteTimeUtc(supportOSfilePath) < DateTime.UtcNow.AddHours(-1)) + { HttpResponseMessage response = await httpClient.GetAsync(serverFileUrl); if (!response.IsSuccessStatusCode) { @@ -330,7 +331,7 @@ private async static Task GetNet6SupportedSystems() } supportOSfileContent = await response.Content.ReadAsStringAsync(); await File.WriteAllTextAsync(supportOSfilePath, supportOSfileContent); - } + } else { if (net6SupportedSystems != null) @@ -490,11 +491,11 @@ public class OperatingSystem public OperatingSystem() { } - public bool Equals(string systemId) => + public bool Equals(string systemId) => this.Id.Equals(systemId, StringComparison.OrdinalIgnoreCase); - public bool Equals(string systemId, SystemVersion systemVersion) => - this.Equals(systemId) && this.Versions.Length > 0 + public bool Equals(string systemId, SystemVersion systemVersion) => + this.Equals(systemId) && this.Versions.Length > 0 ? this.Versions.Any(version => version.Equals(systemVersion)) : false; } diff --git a/src/Agent.Sdk/Util/RepositoryUtil.cs b/src/Agent.Sdk/Util/RepositoryUtil.cs index 7283f870e0..ca8aeae48b 100644 --- a/src/Agent.Sdk/Util/RepositoryUtil.cs +++ b/src/Agent.Sdk/Util/RepositoryUtil.cs @@ -116,7 +116,7 @@ public static RepositoryResource GetRepositoryForLocalPath(IList(RepositoryPropertyNames.Path)?.TrimEnd(Path.DirectorySeparatorChar); - if (!string.IsNullOrEmpty(repoPath) && + if (!string.IsNullOrEmpty(repoPath) && (localPath.Equals(repoPath, IOUtil.FilePathStringComparison)) || localPath.StartsWith(repoPath + Path.DirectorySeparatorChar, IOUtil.FilePathStringComparison)) { @@ -157,7 +157,7 @@ public static string GuessRepositoryType(string repositoryUrl) { return RepositoryTypes.GitHub; } - else if (repositoryUrl.IndexOf(".visualstudio.com", StringComparison.OrdinalIgnoreCase) >= 0 + else if (repositoryUrl.IndexOf(".visualstudio.com", StringComparison.OrdinalIgnoreCase) >= 0 || repositoryUrl.IndexOf("dev.azure.com", StringComparison.OrdinalIgnoreCase) >= 0) { if (repositoryUrl.IndexOf("/_git/", StringComparison.OrdinalIgnoreCase) >= 0) diff --git a/src/Agent.Sdk/Util/TeeUtil.cs b/src/Agent.Sdk/Util/TeeUtil.cs index c7ef6b2552..14c52196f8 100644 --- a/src/Agent.Sdk/Util/TeeUtil.cs +++ b/src/Agent.Sdk/Util/TeeUtil.cs @@ -31,7 +31,8 @@ public TeeUtil( int providedDownloadRetryCount, Action debug, CancellationToken cancellationToken - ) { + ) + { this.agentHomeDirectory = agentHomeDirectory; this.agentTempDirectory = agentTempDirectory; this.downloadRetryCount = Math.Min(Math.Max(providedDownloadRetryCount, 3), 10); @@ -40,7 +41,8 @@ CancellationToken cancellationToken } // If TEE is not found in the working directory (externals/tee), tries to download and extract it with retries. - public async Task DownloadTeeIfAbsent() { + public async Task DownloadTeeIfAbsent() + { if (Directory.Exists(GetTeePath())) { return; @@ -70,7 +72,8 @@ public async Task DownloadTeeIfAbsent() { // Downloads TEE archive to the TEE temp directory. // Once downloaded, archive is extracted to the working TEE directory (externals/tee) // Sets required permissions for extracted files. - private async Task DownloadAndExtractTee() { + private async Task DownloadAndExtractTee() + { string tempDirectory = Path.Combine(agentTempDirectory, TeeTempDir); IOUtil.DeleteDirectory(tempDirectory, CancellationToken.None); Directory.CreateDirectory(tempDirectory); diff --git a/src/Agent.Sdk/Util/VssUtil.cs b/src/Agent.Sdk/Util/VssUtil.cs index c33a1d2295..bc4814fa1f 100644 --- a/src/Agent.Sdk/Util/VssUtil.cs +++ b/src/Agent.Sdk/Util/VssUtil.cs @@ -24,7 +24,7 @@ public static class VssUtil private const string _testUri = "https://microsoft.com/"; private static bool? _isCustomServerCertificateValidationSupported; - + public static void InitializeVssClientSettings(ProductInfoHeaderValue additionalUserAgent, IWebProxy proxy, IVssClientCertificateManager clientCert) { @@ -54,7 +54,7 @@ public static void InitializeVssClientSettings(ProductInfoHeaderValue additional [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "connection")] public static VssConnection CreateConnection( - Uri serverUri, + Uri serverUri, VssCredentials credentials, ITraceWriter trace, IEnumerable additionalDelegatingHandler = null, diff --git a/src/Agent.Service/Windows/Program.cs b/src/Agent.Service/Windows/Program.cs index 0110411a19..530086ab18 100644 --- a/src/Agent.Service/Windows/Program.cs +++ b/src/Agent.Service/Windows/Program.cs @@ -39,7 +39,7 @@ static int Main(String[] args) catch (Win32Exception ex) { Console.WriteLine("[ERROR] Unable to create '{0}' event source under 'Application' event log.", AgentService.EventSourceName); - Console.WriteLine("[ERROR] {0}",ex.Message); + Console.WriteLine("[ERROR] {0}", ex.Message); Console.WriteLine("[ERROR] Error Code: {0}", ex.ErrorCode); return 1; } diff --git a/src/Agent.Worker/AgentPluginManager.cs b/src/Agent.Worker/AgentPluginManager.cs index 587a9bfc50..68c91b9c2e 100644 --- a/src/Agent.Worker/AgentPluginManager.cs +++ b/src/Agent.Worker/AgentPluginManager.cs @@ -105,7 +105,7 @@ public AgentTaskPluginExecutionContext GeneratePluginExecutionContext(IExecution // TODO: look to see if there is a better way to not have translate these back if (containerInfo != null) { - var newInputs = new Dictionary(); + var newInputs = new Dictionary(); foreach (var entry in inputs) { newInputs[entry.Key] = containerInfo.TranslateToHostPath(entry.Value); diff --git a/src/Agent.Worker/Build/ArtifactCommandExtension.cs b/src/Agent.Worker/Build/ArtifactCommandExtension.cs index 343bec15e6..22265cf1bd 100644 --- a/src/Agent.Worker/Build/ArtifactCommandExtension.cs +++ b/src/Agent.Worker/Build/ArtifactCommandExtension.cs @@ -15,7 +15,7 @@ namespace Microsoft.VisualStudio.Services.Agent.Worker.Build { - public sealed class ArtifactCommandExtension: BaseWorkerCommandExtension + public sealed class ArtifactCommandExtension : BaseWorkerCommandExtension { public ArtifactCommandExtension() { @@ -26,7 +26,7 @@ public ArtifactCommandExtension() } } - public sealed class ArtifactAssociateCommand: IWorkerCommand + public sealed class ArtifactAssociateCommand : IWorkerCommand { public string Name => "associate"; public List Aliases => null; @@ -122,7 +122,7 @@ public void Execute(IExecutionContext context, Command command) } } - public sealed class ArtifactUploadCommand: IWorkerCommand + public sealed class ArtifactUploadCommand : IWorkerCommand { public string Name => "upload"; public List Aliases => null; diff --git a/src/Agent.Worker/Build/BuildJobExtension.cs b/src/Agent.Worker/Build/BuildJobExtension.cs index 9d18569222..de5ac9d9f6 100644 --- a/src/Agent.Worker/Build/BuildJobExtension.cs +++ b/src/Agent.Worker/Build/BuildJobExtension.cs @@ -166,7 +166,7 @@ public override void InitializeJobExtension(IExecutionContext executionContext, string pipelineWorkspaceDirectory = Path.Combine(_workDirectory, trackingConfig.BuildDirectory); UpdateCheckoutTasksAndVariables(executionContext, steps, pipelineWorkspaceDirectory); - + // Get default value for RepoLocalPath variable string selfRepoPath = GetDefaultRepoLocalPathValue(executionContext, steps, trackingConfig, repoInfo); @@ -361,7 +361,7 @@ private string GetDefaultRepoLocalPathValue(IExecutionContext executionContext, { selfRepoPath = trackingConfig.RepositoryTrackingInfo .Where(repo => RepositoryUtil.IsPrimaryRepositoryName(repo.Identifier)) - .Select(props => props.SourcesDirectory).FirstOrDefault(); + .Select(props => props.SourcesDirectory).FirstOrDefault(); } } // For single checkout jobs and multicheckout jobs with default paths set selfRepoPath to the default sources directory diff --git a/src/Agent.Worker/Build/FileContainerServer.cs b/src/Agent.Worker/Build/FileContainerServer.cs index b4d32a4da4..e6c849ce19 100644 --- a/src/Agent.Worker/Build/FileContainerServer.cs +++ b/src/Agent.Worker/Build/FileContainerServer.cs @@ -423,10 +423,10 @@ private async Task AssociateAsync(IAsyncCommandContext context, Co { if (file.Success) { - var length = (long) file.Node.TransitiveContentBytes; + var length = (long)file.Node.TransitiveContentBytes; response = await retryHelper.Retry(async () => await _fileContainerHttpClient.CreateItemForArtifactUpload(_containerId, itemPath, _projectId, file.DedupId.ValueString, length, token), - (retryCounter) => (int) Math.Pow(retryCounter, 2) * 5, + (retryCounter) => (int)Math.Pow(retryCounter, 2) * 5, (exception) => true); uploadResult.TotalFileSizeUploaded += length; } diff --git a/src/Agent.Worker/Build/GitCommandManager.cs b/src/Agent.Worker/Build/GitCommandManager.cs index ffc8419681..5ca3478323 100644 --- a/src/Agent.Worker/Build/GitCommandManager.cs +++ b/src/Agent.Worker/Build/GitCommandManager.cs @@ -267,7 +267,7 @@ public async Task GitFetch(IExecutionContext context, string repositoryPath // If shallow fetch add --depth arg // If the local repository is shallowed but there is no fetch depth provide for this build, // add --unshallow to convert the shallow repository to a complete repository - string depth = fetchDepth > 0 ? $"--depth={fetchDepth}" : (File.Exists(Path.Combine(repositoryPath, ".git", "shallow")) ? "--unshallow" : string.Empty ); + string depth = fetchDepth > 0 ? $"--depth={fetchDepth}" : (File.Exists(Path.Combine(repositoryPath, ".git", "shallow")) ? "--unshallow" : string.Empty); //define options for fetch string options = $"{tags} --prune {pruneTags} --progress --no-recurse-submodules {remoteName} {depth} {string.Join(" ", refSpec)}"; @@ -286,7 +286,8 @@ public async Task GitLFSFetch(IExecutionContext context, string repositoryP // default options for git checkout .lfsconfig string options = StringUtil.Format($"{refSpec} -- {lfsconfig}"); int exitCodeLfsConfigCheckout = await ExecuteGitCommandAsync(context, repositoryPath, "checkout", options, additionalCommandLine, cancellationToken); - if (exitCodeLfsConfigCheckout != 0) { + if (exitCodeLfsConfigCheckout != 0) + { context.Debug("There were some issues while checkout of .lfsconfig - probably because this file does not exist (see message above for more details). Continue fetching."); } diff --git a/src/Agent.Worker/Build/GitSourceProvider.cs b/src/Agent.Worker/Build/GitSourceProvider.cs index 366c60a3e1..670a74db5b 100644 --- a/src/Agent.Worker/Build/GitSourceProvider.cs +++ b/src/Agent.Worker/Build/GitSourceProvider.cs @@ -1204,7 +1204,8 @@ public override async Task RunMaintenanceOperations(IExecutionContext executionC if (lfsVersion is null) { executionContext.Debug("Machine does not have git-lfs installed. Skipping git lfs prune"); - } else + } + else { int exitCode_lFSPrune = await _gitCommandManager.GitLFSPrune(executionContext, repositoryPath); if (exitCode_lFSPrune != 0) diff --git a/src/Agent.Worker/Build/TrackingConfig.cs b/src/Agent.Worker/Build/TrackingConfig.cs index 5b2c1c9427..c9922277e0 100644 --- a/src/Agent.Worker/Build/TrackingConfig.cs +++ b/src/Agent.Worker/Build/TrackingConfig.cs @@ -55,7 +55,7 @@ public TrackingConfig( RepositoryUrl = copy.RepositoryUrl; System = copy.System; // Let's make sure this file gets cleaned up by the garbage collector - LastRunOn = new DateTime(1,1,1,0,0,0,DateTimeKind.Utc); + LastRunOn = new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc); } public TrackingConfig Clone() diff --git a/src/Agent.Worker/Build/WorkspaceMaintenanceProvider.cs b/src/Agent.Worker/Build/WorkspaceMaintenanceProvider.cs index 59ba2ae804..c8df5e4918 100644 --- a/src/Agent.Worker/Build/WorkspaceMaintenanceProvider.cs +++ b/src/Agent.Worker/Build/WorkspaceMaintenanceProvider.cs @@ -110,7 +110,7 @@ private bool TryHandleGarbageCollection(IExecutionContext executionContext, ITra return true; } - private static bool ShouldRunMaintenance(IExecutionContext executionContext, TrackingConfig trackingConfig, int totalAvailableTimeInMinutes, Stopwatch totalTimeSpent) + private static bool ShouldRunMaintenance(IExecutionContext executionContext, TrackingConfig trackingConfig, int totalAvailableTimeInMinutes, Stopwatch totalTimeSpent) { bool runMainenance = false; diff --git a/src/Agent.Worker/CodeCoverage/CodeCoverageCommands.cs b/src/Agent.Worker/CodeCoverage/CodeCoverageCommands.cs index bf938b800a..b88a5a511c 100644 --- a/src/Agent.Worker/CodeCoverage/CodeCoverageCommands.cs +++ b/src/Agent.Worker/CodeCoverage/CodeCoverageCommands.cs @@ -15,7 +15,7 @@ namespace Microsoft.VisualStudio.Services.Agent.Worker.CodeCoverage { - public sealed class CodeCoverageCommandExtension: BaseWorkerCommandExtension + public sealed class CodeCoverageCommandExtension : BaseWorkerCommandExtension { public CodeCoverageCommandExtension() @@ -27,7 +27,7 @@ public CodeCoverageCommandExtension() } #region publish code coverage helper methods - public sealed class PublishCodeCoverageCommand: IWorkerCommand + public sealed class PublishCodeCoverageCommand : IWorkerCommand { public string Name => "publish"; public List Aliases => null; @@ -149,9 +149,9 @@ private async Task PublishCodeCoverageAsync( } catch (SocketException ex) { - #pragma warning disable CA2000 // Dispose objects before losing scope +#pragma warning disable CA2000 // Dispose objects before losing scope ExceptionsUtil.HandleSocketException(ex, WorkerUtilities.GetVssConnection(executionContext).Uri.ToString(), executionContext.Warning); - #pragma warning restore CA2000 // Dispose objects before losing scope +#pragma warning restore CA2000 // Dispose objects before losing scope } catch (Exception ex) { diff --git a/src/Agent.Worker/Container/DockerCommandManager.cs b/src/Agent.Worker/Container/DockerCommandManager.cs index a4cbd37c79..fdeee39d51 100644 --- a/src/Agent.Worker/Container/DockerCommandManager.cs +++ b/src/Agent.Worker/Container/DockerCommandManager.cs @@ -349,7 +349,8 @@ public async Task> DockerPort(IExecutionContext context, strin /// true, if specified container is running, false otherwise. /// - public async Task IsContainerRunning(IExecutionContext context, string containerId) { + public async Task IsContainerRunning(IExecutionContext context, string containerId) + { List filteredItems = await DockerPS(context, $"--filter id={containerId}"); // docker ps function is returning table with containers in Running state. diff --git a/src/Agent.Worker/Container/DockerUtil.cs b/src/Agent.Worker/Container/DockerUtil.cs index 758e1e741f..477ed82f3a 100644 --- a/src/Agent.Worker/Container/DockerUtil.cs +++ b/src/Agent.Worker/Container/DockerUtil.cs @@ -24,7 +24,7 @@ public static List ParseDockerPort(IList portMappingLines) string pattern = $"^(?<{targetPort}>\\d+)/(?<{proto}>\\w+) -> (?<{host}>.+):(?<{hostPort}>\\d+)$"; List portMappings = new List(); - foreach(var line in portMappingLines) + foreach (var line in portMappingLines) { Match m = Regex.Match(line, pattern, RegexOptions.None, TimeSpan.FromSeconds(1)); if (m.Success) diff --git a/src/Agent.Worker/ContainerOperationProvider.cs b/src/Agent.Worker/ContainerOperationProvider.cs index 584e5cc328..a24ceddcd1 100644 --- a/src/Agent.Worker/ContainerOperationProvider.cs +++ b/src/Agent.Worker/ContainerOperationProvider.cs @@ -127,7 +127,8 @@ public async Task StartContainersAsync(IExecutionContext executionContext, objec // Build JSON to expose docker container name mapping to env var containerMapping = new JObject(); - foreach (var container in containers) { + foreach (var container in containers) + { var containerInfo = new JObject(); containerInfo["id"] = container.ContainerId; containerMapping[container.ContainerName] = containerInfo; @@ -455,7 +456,7 @@ private async Task StartContainerAsync(IExecutionContext executionContext, Conta readOnly: container.isReadOnlyVolume(Constants.DefaultContainerMounts.Tools))); bool externalReadOnly = container.ImageOS != PlatformUtil.OS.Windows || container.isReadOnlyVolume(Constants.DefaultContainerMounts.Externals); // This code was refactored to use PlatformUtils. The previous implementation did not have the externals directory mounted read-only for Windows. - // That seems wrong, but to prevent any potential backwards compatibility issues, we are keeping the same logic + // That seems wrong, but to prevent any potential backwards compatibility issues, we are keeping the same logic container.MountVolumes.Add(new MountVolume(HostContext.GetDirectory(WellKnownDirectory.Externals), container.TranslateToContainerPath(HostContext.GetDirectory(WellKnownDirectory.Externals)), externalReadOnly)); if (container.ImageOS != PlatformUtil.OS.Windows) @@ -677,10 +678,10 @@ private async Task StartContainerAsync(IExecutionContext executionContext, Conta // check all potential groups that might match the GID. foreach (string groupOutput in groupsOutput) { - if(!string.IsNullOrEmpty(groupOutput)) + if (!string.IsNullOrEmpty(groupOutput)) { var groupSegments = groupOutput.Split(':'); - if( groupSegments.Length != 4 ) + if (groupSegments.Length != 4) { Trace.Warning($"Unexpected output from /etc/group: '{groupOutput}'"); } @@ -690,7 +691,7 @@ private async Task StartContainerAsync(IExecutionContext executionContext, Conta var groupName = groupSegments[0]; var groupId = groupSegments[2]; - if(string.Equals(dockerSockGroupId, groupId)) + if (string.Equals(dockerSockGroupId, groupId)) { existingGroupName = groupName; break; @@ -700,7 +701,7 @@ private async Task StartContainerAsync(IExecutionContext executionContext, Conta } } - if(string.IsNullOrEmpty(existingGroupName)) + if (string.IsNullOrEmpty(existingGroupName)) { // create a new group with same gid existingGroupName = "azure_pipelines_docker"; @@ -801,7 +802,7 @@ private async Task CreateContainerNetworkAsync(IExecutionContext executionContex { Trace.Entering(); ArgUtil.NotNull(executionContext, nameof(executionContext)); - + if (network != "host") { int networkExitCode = await _dockerManger.DockerNetworkCreate(executionContext, network); diff --git a/src/Agent.Worker/DiagnosticLogManager.cs b/src/Agent.Worker/DiagnosticLogManager.cs index f631e0831a..64dc877491 100644 --- a/src/Agent.Worker/DiagnosticLogManager.cs +++ b/src/Agent.Worker/DiagnosticLogManager.cs @@ -169,7 +169,7 @@ public async Task UploadDiagnosticLogsAsync(IExecutionContext executionContext, try { - string eventLogsFile = $"{HostContext.GetDiagDirectory()}/EventViewer-{ jobStartTimeUtc.ToString("yyyyMMdd-HHmmss") }.csv"; + string eventLogsFile = $"{HostContext.GetDiagDirectory()}/EventViewer-{jobStartTimeUtc.ToString("yyyyMMdd-HHmmss")}.csv"; await DumpCurrentJobEventLogs(executionContext, eventLogsFile, jobStartTimeUtc); string destination = Path.Combine(supportFilesFolder, Path.GetFileName(eventLogsFile)); @@ -183,13 +183,17 @@ public async Task UploadDiagnosticLogsAsync(IExecutionContext executionContext, } bool dumpPackagesVerificationResult = AgentKnobs.DumpPackagesVerificationResult.GetValue(executionContext).AsBoolean(); - if (dumpPackagesVerificationResult && PlatformUtil.RunningOnLinux && !PlatformUtil.RunningOnRHEL6) { + if (dumpPackagesVerificationResult && PlatformUtil.RunningOnLinux && !PlatformUtil.RunningOnRHEL6) + { executionContext.Debug("Dumping info about invalid MD5 sums of installed packages."); var debsums = WhichUtil.Which("debsums"); - if (debsums == null) { + if (debsums == null) + { executionContext.Debug("Debsums is not installed on the system. Skipping broken packages check."); - } else { + } + else + { try { string packageVerificationResults = await GetPackageVerificationResult(debsums); @@ -197,7 +201,7 @@ public async Task UploadDiagnosticLogsAsync(IExecutionContext executionContext, .Split("\n") .Where((line) => !String.IsNullOrEmpty(line) && !line.EndsWith("OK")); - string brokenPackagesLogsPath = $"{HostContext.GetDiagDirectory()}/BrokenPackages-{ jobStartTimeUtc.ToString("yyyyMMdd-HHmmss") }.log"; + string brokenPackagesLogsPath = $"{HostContext.GetDiagDirectory()}/BrokenPackages-{jobStartTimeUtc.ToString("yyyyMMdd-HHmmss")}.log"; File.AppendAllLines(brokenPackagesLogsPath, brokenPackagesInfo); string destination = Path.Combine(supportFilesFolder, Path.GetFileName(brokenPackagesLogsPath)); @@ -209,7 +213,9 @@ public async Task UploadDiagnosticLogsAsync(IExecutionContext executionContext, executionContext.Debug($"Error message: {ex}"); } } - } else { + } + else + { executionContext.Debug("The platform is not based on Debian - skipping debsums check."); } diff --git a/src/Agent.Worker/Handlers/Handler.cs b/src/Agent.Worker/Handlers/Handler.cs index a096e457e7..45e8873e47 100644 --- a/src/Agent.Worker/Handlers/Handler.cs +++ b/src/Agent.Worker/Handlers/Handler.cs @@ -36,7 +36,7 @@ public abstract class Handler : AgentService // On Windows, the maximum supported size of a environment variable value is 32k. // You can set environment variables greater then 32K, but Node won't be able to read them. private const int _windowsEnvironmentVariableMaximumSize = 32766; - + protected bool _continueAfterCancelProcessTreeKillAttempt; protected IWorkerCommandManager CommandManager { get; private set; } diff --git a/src/Agent.Worker/Handlers/NodeHandler.cs b/src/Agent.Worker/Handlers/NodeHandler.cs index d536b37b7f..421281c9ba 100644 --- a/src/Agent.Worker/Handlers/NodeHandler.cs +++ b/src/Agent.Worker/Handlers/NodeHandler.cs @@ -249,7 +249,7 @@ public string GetNodeLocation() if (!String.IsNullOrWhiteSpace(useNodeKnob) && filteredPossibleNodeFolders.Length > 0) { Trace.Info($"Found UseNode knob with value \"{useNodeKnob}\", will try to find appropriate Node Runner"); - + switch (useNodeKnob.ToUpper()) { case NodeHandler.useNodeKnobLtsKey: diff --git a/src/Agent.Worker/Handlers/StepHost.cs b/src/Agent.Worker/Handlers/StepHost.cs index d016d61a54..e21006d4c0 100644 --- a/src/Agent.Worker/Handlers/StepHost.cs +++ b/src/Agent.Worker/Handlers/StepHost.cs @@ -109,7 +109,8 @@ public string ResolvePathForStepHost(string path) StringComparison sc = (PlatformUtil.RunningOnWindows) ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; - if (Container.MountVolumes.Exists(x => { + if (Container.MountVolumes.Exists(x => + { if (!string.IsNullOrEmpty(x.SourceVolumePath)) { return path.StartsWith(x.SourceVolumePath, sc); diff --git a/src/Agent.Worker/JobRunner.cs b/src/Agent.Worker/JobRunner.cs index e6e7d21c51..e2f54e6fe7 100644 --- a/src/Agent.Worker/JobRunner.cs +++ b/src/Agent.Worker/JobRunner.cs @@ -257,7 +257,7 @@ public async Task RunAsync(Pipelines.AgentJobRequestMessage message, { checkoutOptions = jobContext.Variables.ExpandValues(target: checkoutOptions); checkoutOptions = VarUtil.ExpandEnvironmentVariables(HostContext, target: checkoutOptions); - repository.Properties.Set(Pipelines.RepositoryPropertyNames.CheckoutOptions, checkoutOptions); ; + repository.Properties.Set(Pipelines.RepositoryPropertyNames.CheckoutOptions, checkoutOptions); } // expand workspace mapping diff --git a/src/Agent.Worker/PluginInternalCommandExtension.cs b/src/Agent.Worker/PluginInternalCommandExtension.cs index ab4635306e..b81084f6ee 100644 --- a/src/Agent.Worker/PluginInternalCommandExtension.cs +++ b/src/Agent.Worker/PluginInternalCommandExtension.cs @@ -12,7 +12,7 @@ namespace Microsoft.VisualStudio.Services.Agent.Worker { - public sealed class PluginInternalCommandExtension: BaseWorkerCommandExtension + public sealed class PluginInternalCommandExtension : BaseWorkerCommandExtension { public PluginInternalCommandExtension() { @@ -22,7 +22,7 @@ public PluginInternalCommandExtension() } } - public sealed class PluginInternalUpdateRepositoryPathCommand: IWorkerCommand + public sealed class PluginInternalUpdateRepositoryPathCommand : IWorkerCommand { public string Name => "updaterepositorypath"; public List Aliases => null; @@ -72,7 +72,7 @@ public void Execute(IExecutionContext context, Command command) // So, we will just reset the repo local path string buildDirectory = context.Variables.Get(Constants.Variables.Pipeline.Workspace); string repoRelativePath = directoryManager.GetRelativeRepositoryPath(buildDirectory, repositoryPath); - + string sourcesDirectory = context.Variables.Get(Constants.Variables.Build.SourcesDirectory); string repoLocalPath = context.Variables.Get(Constants.Variables.Build.RepoLocalPath); string newRepoLocation = Path.Combine(_workDirectory, repoRelativePath); diff --git a/src/Agent.Worker/Release/Artifacts/BuildArtifact.cs b/src/Agent.Worker/Release/Artifacts/BuildArtifact.cs index 1c4e3e90f5..7e59a69968 100644 --- a/src/Agent.Worker/Release/Artifacts/BuildArtifact.cs +++ b/src/Agent.Worker/Release/Artifacts/BuildArtifact.cs @@ -128,13 +128,13 @@ public IArtifactDetails GetArtifactDetails(IExecutionContext context, AgentArtif if (artifactDetails.TryGetValue("RelativePath", out relativePath)) { var buildArtifactDetails = new BuildArtifactDetails - { - Credentials = vssCredentials, - RelativePath = artifactDetails["RelativePath"], - AccessToken = accessToken, - Project = projectId.ToString(), - TfsUrl = new Uri(tfsUrl) - }; + { + Credentials = vssCredentials, + RelativePath = artifactDetails["RelativePath"], + AccessToken = accessToken, + Project = projectId.ToString(), + TfsUrl = new Uri(tfsUrl) + }; if (artifactDetails.ContainsKey("DefinitionName")) { diff --git a/src/Agent.Worker/Release/Artifacts/Definition/JenkinsArtifactDetails.cs b/src/Agent.Worker/Release/Artifacts/Definition/JenkinsArtifactDetails.cs index a750d8df54..bfe54baa83 100644 --- a/src/Agent.Worker/Release/Artifacts/Definition/JenkinsArtifactDetails.cs +++ b/src/Agent.Worker/Release/Artifacts/Definition/JenkinsArtifactDetails.cs @@ -29,7 +29,7 @@ public class JenkinsArtifactDetails : IArtifactDetails public string StartCommitArtifactVersion { get; set; } - public string EndCommitArtifactVersion { get; set; } + public string EndCommitArtifactVersion { get; set; } public string Alias { get; set; } } diff --git a/src/Agent.Worker/Release/Artifacts/GenericHttpClient.cs b/src/Agent.Worker/Release/Artifacts/GenericHttpClient.cs index 811484f84e..e9a9a6e1f6 100644 --- a/src/Agent.Worker/Release/Artifacts/GenericHttpClient.cs +++ b/src/Agent.Worker/Release/Artifacts/GenericHttpClient.cs @@ -48,7 +48,7 @@ public async Task GetStringAsync(string url, string userName, string pas { return await response.Content.ReadAsStringAsync(); } - else + else { throw new InvalidOperationException(StringUtil.Loc("RMApiFailure", url, response.StatusCode)); } diff --git a/src/Agent.Worker/Release/Artifacts/JenkinsArtifact.cs b/src/Agent.Worker/Release/Artifacts/JenkinsArtifact.cs index 6aaf963c9c..6a325d20fb 100644 --- a/src/Agent.Worker/Release/Artifacts/JenkinsArtifact.cs +++ b/src/Agent.Worker/Release/Artifacts/JenkinsArtifact.cs @@ -159,19 +159,23 @@ public async Task DownloadCommitsAsync(IExecutionContext context, ArtifactDefini } catch (SocketException ex) { - context.AddIssue(new Issue { Type = IssueType.Error, Message = $"SocketException occurred. { ex.Message }." + - $"Verify whether you have (network) access to { jenkinsDetails.Url }. URLs the agent need communicate with - { BlobStoreWarningInfoProvider.GetAllowListLinkForCurrentPlatform() }."}); + context.AddIssue(new Issue + { + Type = IssueType.Error, + Message = $"SocketException occurred. {ex.Message}." + + $"Verify whether you have (network) access to {jenkinsDetails.Url}. URLs the agent need communicate with - {BlobStoreWarningInfoProvider.GetAllowListLinkForCurrentPlatform()}." + }); return; } catch (Exception ex) { - context.AddIssue(new Issue { Type=IssueType.Warning, Message = StringUtil.Loc("DownloadingJenkinsCommitsFailedWithException", jenkinsDetails.Alias, ex.ToString()) }); + context.AddIssue(new Issue { Type = IssueType.Warning, Message = StringUtil.Loc("DownloadingJenkinsCommitsFailedWithException", jenkinsDetails.Alias, ex.ToString()) }); return; } } else { - context.AddIssue(new Issue { Type=IssueType.Warning, Message = StringUtil.Loc("JenkinsCommitsInvalidEndJobId", jenkinsDetails.EndCommitArtifactVersion, jenkinsDetails.Alias) }); + context.AddIssue(new Issue { Type = IssueType.Warning, Message = StringUtil.Loc("JenkinsCommitsInvalidEndJobId", jenkinsDetails.EndCommitArtifactVersion, jenkinsDetails.Alias) }); return; } } @@ -191,8 +195,8 @@ private void WriteCommitsToFile(IExecutionContext context, IEnumerable c IOUtil.DeleteFile(commitsFilePath); if (commits.Any()) { - using(StreamWriter sw = File.CreateText(commitsFilePath)) - using(JsonTextWriter jw = new JsonTextWriter(sw)) + using (StreamWriter sw = File.CreateText(commitsFilePath)) + using (JsonTextWriter jw = new JsonTextWriter(sw)) { jw.Formatting = Formatting.Indented; jw.WriteStartArray(); @@ -366,7 +370,8 @@ private bool IsGitRepo(IExecutionContext executionContext, JenkinsArtifactDetail executionContext.Debug($"repo query result from Jenkins api {repoResult.ToString()}"); var repoKindResult = ParseToken(repoResult.ToString(), "$.changeSet.kind"); - if (repoKindResult != null && repoKindResult.Any()) { + if (repoKindResult != null && repoKindResult.Any()) + { string repoKind = repoKindResult.First().ToString(); executionContext.Debug($"Parsed repo result {repoKind}"); diff --git a/src/Agent.Worker/Release/ContainerFetchEngine/FetchEngine.cs b/src/Agent.Worker/Release/ContainerFetchEngine/FetchEngine.cs index f9228af7ea..0abf6216c4 100644 --- a/src/Agent.Worker/Release/ContainerFetchEngine/FetchEngine.cs +++ b/src/Agent.Worker/Release/ContainerFetchEngine/FetchEngine.cs @@ -149,7 +149,7 @@ private void LogStatistics() if (_downloadedFiles > 0) { - string message = StringUtil.Loc("RMDownloadProgressDetails", Math.Ceiling(_bytesDownloaded/(1024.0*1024.0)), Math.Floor(_bytesDownloaded/(1024.0*_elapsedDownloadTime.TotalSeconds)), _elapsedDownloadTime); + string message = StringUtil.Loc("RMDownloadProgressDetails", Math.Ceiling(_bytesDownloaded / (1024.0 * 1024.0)), Math.Floor(_bytesDownloaded / (1024.0 * _elapsedDownloadTime.TotalSeconds)), _elapsedDownloadTime); ExecutionLogger.Output(message); } } @@ -223,7 +223,7 @@ private async Task LogProgressAsync(LinkedList remainingTasks) lock (_lock) { - ExecutionLogger.Warning(StringUtil.Loc("RMDownloadTaskCompletedStatus", (int) timeSinceLastTaskCompletion.TotalMinutes)); + ExecutionLogger.Warning(StringUtil.Loc("RMDownloadTaskCompletedStatus", (int)timeSinceLastTaskCompletion.TotalMinutes)); foreach (IGrouping group in taskStates) { ExecutionLogger.Warning(StringUtil.Loc("RMDownloadTaskStates", group.Key, group.Count())); diff --git a/src/Agent.Worker/Release/ContainerFetchEngine/HttpRetryOnTimeoutHandler.cs b/src/Agent.Worker/Release/ContainerFetchEngine/HttpRetryOnTimeoutHandler.cs index d3b7baa35e..df2b2fb715 100644 --- a/src/Agent.Worker/Release/ContainerFetchEngine/HttpRetryOnTimeoutHandler.cs +++ b/src/Agent.Worker/Release/ContainerFetchEngine/HttpRetryOnTimeoutHandler.cs @@ -85,7 +85,7 @@ protected override async Task SendAsync( break; } - string message = StringUtil.Loc("RMContainerItemRequestTimedOut", (int) watch.Elapsed.TotalSeconds, backoff.TotalSeconds, request.Method, request.RequestUri); + string message = StringUtil.Loc("RMContainerItemRequestTimedOut", (int)watch.Elapsed.TotalSeconds, backoff.TotalSeconds, request.Method, request.RequestUri); _logger.Warning(message); attempt++; diff --git a/src/Agent.Worker/Release/ContainerProvider/FileContainerProvider.cs b/src/Agent.Worker/Release/ContainerProvider/FileContainerProvider.cs index e73d95c4f6..5cf0219b24 100644 --- a/src/Agent.Worker/Release/ContainerProvider/FileContainerProvider.cs +++ b/src/Agent.Worker/Release/ContainerProvider/FileContainerProvider.cs @@ -128,7 +128,7 @@ private static ContainerItem ConvertToContainerItem(FileContainerItem x) { return new ContainerItem { - ItemType = (ItemType) (int) x.ItemType, + ItemType = (ItemType)(int)x.ItemType, Path = x.Path, FileLength = x.FileLength, ContainerId = x.ContainerId, diff --git a/src/Agent.Worker/Release/ContainerProvider/Helpers/AsyncLazy.cs b/src/Agent.Worker/Release/ContainerProvider/Helpers/AsyncLazy.cs index d02efd7964..a8aa367ffb 100644 --- a/src/Agent.Worker/Release/ContainerProvider/Helpers/AsyncLazy.cs +++ b/src/Agent.Worker/Release/ContainerProvider/Helpers/AsyncLazy.cs @@ -11,10 +11,12 @@ namespace Microsoft.VisualStudio.Services.Agent.Worker.Release.ContainerProvider public class AsyncLazy : Lazy> { public AsyncLazy(Func valueFactory) : - base(() => Task.Factory.StartNew(valueFactory)) { } + base(() => Task.Factory.StartNew(valueFactory)) + { } public AsyncLazy(Func> taskFactory) : - base(() => Task.Factory.StartNew(() => taskFactory()).Unwrap()) { } + base(() => Task.Factory.StartNew(() => taskFactory()).Unwrap()) + { } public TaskAwaiter GetAwaiter() { return Value.GetAwaiter(); } } diff --git a/src/Agent.Worker/Release/ContainerProvider/Helpers/VssConnectionFactory.cs b/src/Agent.Worker/Release/ContainerProvider/Helpers/VssConnectionFactory.cs index d2e354dc79..a8ec2456d8 100644 --- a/src/Agent.Worker/Release/ContainerProvider/Helpers/VssConnectionFactory.cs +++ b/src/Agent.Worker/Release/ContainerProvider/Helpers/VssConnectionFactory.cs @@ -26,9 +26,9 @@ public static class VssConnectionFactory private static readonly TimeSpan _minTimeout = TimeSpan.FromMinutes(5); public static async Task GetVssConnectionAsync( - Uri uri, - string accessToken, - DelegatingHandler retryOnTimeoutMessageHandler = null, + Uri uri, + string accessToken, + DelegatingHandler retryOnTimeoutMessageHandler = null, ITraceWriter trace = null) { VssConnection connection; diff --git a/src/Agent.Worker/Release/ReleaseCommandExtension.cs b/src/Agent.Worker/Release/ReleaseCommandExtension.cs index 7380098b6d..34a5876a41 100644 --- a/src/Agent.Worker/Release/ReleaseCommandExtension.cs +++ b/src/Agent.Worker/Release/ReleaseCommandExtension.cs @@ -10,7 +10,7 @@ namespace Microsoft.VisualStudio.Services.Agent.Worker.Release { - public sealed class ReleaseCommandExtension: BaseWorkerCommandExtension + public sealed class ReleaseCommandExtension : BaseWorkerCommandExtension { public ReleaseCommandExtension() { @@ -19,7 +19,7 @@ public ReleaseCommandExtension() InstallWorkerCommand(new ReleaseUpdateReleaseNameCommand()); } - private class ReleaseUpdateReleaseNameCommand: IWorkerCommand + private class ReleaseUpdateReleaseNameCommand : IWorkerCommand { public string Name => "updatereleasename"; public List Aliases => null; diff --git a/src/Agent.Worker/Release/ReleaseFileSystemManager.cs b/src/Agent.Worker/Release/ReleaseFileSystemManager.cs index 3d0766fed4..b90bb59bd5 100644 --- a/src/Agent.Worker/Release/ReleaseFileSystemManager.cs +++ b/src/Agent.Worker/Release/ReleaseFileSystemManager.cs @@ -52,7 +52,7 @@ public void EnsureEmptyDirectory(string directoryPath, CancellationToken cancell catch (Exception ex) { var exception = ex; - + if (ex is AggregateException) { exception = ((AggregateException)ex).Flatten().InnerException; diff --git a/src/Agent.Worker/Release/ReleaseJobExtension.cs b/src/Agent.Worker/Release/ReleaseJobExtension.cs index 64cd396f65..9bc98baef7 100644 --- a/src/Agent.Worker/Release/ReleaseJobExtension.cs +++ b/src/Agent.Worker/Release/ReleaseJobExtension.cs @@ -483,20 +483,20 @@ private ArtifactDefinition ConvertToArtifactDefinition(AgentArtifactDefinition a }; RetryExecutor retryExecutor = new RetryExecutor(); - retryExecutor.ShouldRetryAction = (ex) => + retryExecutor.ShouldRetryAction = (ex) => + { + bool retry = true; + if (ex is InvalidOperationException) { - bool retry = true; - if (ex is InvalidOperationException) - { - retry = false; - } - else - { - Trace.Warning(ex.ToString()); - } + retry = false; + } + else + { + Trace.Warning(ex.ToString()); + } - return retry; - }; + return retry; + }; retryExecutor.Execute( () => diff --git a/src/Agent.Worker/Release/ZipStreamDownloader.cs b/src/Agent.Worker/Release/ZipStreamDownloader.cs index 45743eb8e7..b0a444ad32 100644 --- a/src/Agent.Worker/Release/ZipStreamDownloader.cs +++ b/src/Agent.Worker/Release/ZipStreamDownloader.cs @@ -92,7 +92,8 @@ private async Task DownloadStreams(IExecutionContext executionContext, Stre string destFileName = Path.GetFullPath(Path.Combine(localFolderPath, path)); string destDirPath = Path.GetFullPath(localFolderPath + Path.DirectorySeparatorChar); - if (!destFileName.StartsWith(destDirPath)) { + if (!destFileName.StartsWith(destDirPath)) + { throw new InvalidOperationException(StringUtil.Loc("ZipSlipFailure", destFileName)); } diff --git a/src/Agent.Worker/StepsRunner.cs b/src/Agent.Worker/StepsRunner.cs index 5ea30f99d8..ad70b11bb7 100644 --- a/src/Agent.Worker/StepsRunner.cs +++ b/src/Agent.Worker/StepsRunner.cs @@ -314,7 +314,8 @@ private async Task RunStepAsync(IStep step, CancellationToken jobCancellationTok // We need to drain the queues after a task just in case if // there are a lot of items since it can cause some UI hangs. await JobServerQueue.DrainQueues(); - } catch (Exception ex) + } + catch (Exception ex) { Trace.Error($"Error has occurred while draining queues, it can cause some UI glitches but it doesn't affect a pipeline execution itself: {ex}"); step.ExecutionContext.Error(ex); @@ -344,7 +345,7 @@ private async Task SwitchToUtf8Codepage(IStep step) killProcessOnCancel: false, redirectStandardIn: null, inheritConsoleHandler: true, - continueAfterCancelProcessTreeKillAttempt: ProcessInvoker.ContinueAfterCancelProcessTreeKillAttemptDefault, + continueAfterCancelProcessTreeKillAttempt: ProcessInvoker.ContinueAfterCancelProcessTreeKillAttemptDefault, cancellationToken: step.ExecutionContext.CancellationToken); if (exitCode == 0) { diff --git a/src/Agent.Worker/TaskCommandExtension.cs b/src/Agent.Worker/TaskCommandExtension.cs index bf14026dda..f165f8e2b1 100644 --- a/src/Agent.Worker/TaskCommandExtension.cs +++ b/src/Agent.Worker/TaskCommandExtension.cs @@ -14,7 +14,7 @@ namespace Microsoft.VisualStudio.Services.Agent.Worker { - public sealed class TaskCommandExtension: BaseWorkerCommandExtension + public sealed class TaskCommandExtension : BaseWorkerCommandExtension { public TaskCommandExtension() { @@ -36,8 +36,8 @@ public TaskCommandExtension() } } - [CommandRestriction(AllowedInRestrictedMode=true)] - public sealed class TaskDetailCommand: IWorkerCommand + [CommandRestriction(AllowedInRestrictedMode = true)] + public sealed class TaskDetailCommand : IWorkerCommand { public string Name => "logdetail"; public List Aliases => null; @@ -228,7 +228,7 @@ private TimelineRecordState ParseTimelineRecordState(String timelineRecordStateT } } - public sealed class TaskUploadSummaryCommand: IWorkerCommand + public sealed class TaskUploadSummaryCommand : IWorkerCommand { public string Name => "uploadsummary"; public List Aliases => null; @@ -255,7 +255,7 @@ public void Execute(IExecutionContext context, Command command) } } - public sealed class TaskUploadFileCommand: IWorkerCommand + public sealed class TaskUploadFileCommand : IWorkerCommand { public string Name => "uploadfile"; public List Aliases => null; @@ -283,7 +283,7 @@ public void Execute(IExecutionContext context, Command command) } } - public sealed class TaskAddAttachmentCommand: IWorkerCommand + public sealed class TaskAddAttachmentCommand : IWorkerCommand { public string Name => "addattachment"; public List Aliases => null; @@ -339,11 +339,11 @@ public static void AddAttachment(IExecutionContext context, Dictionary "logissue"; - public List Aliases => new List(){"issue"}; + public List Aliases => new List() { "issue" }; public void Execute(IExecutionContext context, Command command) { @@ -461,8 +461,8 @@ private Issue CreateIssue(IExecutionContext context, string issueType, String me } } - [CommandRestriction(AllowedInRestrictedMode=true)] - public sealed class TaskCompleteCommand: IWorkerCommand + [CommandRestriction(AllowedInRestrictedMode = true)] + public sealed class TaskCompleteCommand : IWorkerCommand { public string Name => "complete"; public List Aliases => null; @@ -496,8 +496,8 @@ public void Execute(IExecutionContext context, Command command) } } - [CommandRestriction(AllowedInRestrictedMode=true)] - public sealed class TaskProgressCommand: IWorkerCommand + [CommandRestriction(AllowedInRestrictedMode = true)] + public sealed class TaskProgressCommand : IWorkerCommand { public string Name => "setprogress"; public List Aliases => null; @@ -525,8 +525,8 @@ public void Execute(IExecutionContext context, Command command) } } - [CommandRestriction(AllowedInRestrictedMode=true)] - public sealed class TaskSetSecretCommand: IWorkerCommand + [CommandRestriction(AllowedInRestrictedMode = true)] + public sealed class TaskSetSecretCommand : IWorkerCommand { public string Name => "setsecret"; public List Aliases => null; @@ -544,8 +544,8 @@ public void Execute(IExecutionContext context, Command command) } } - [CommandRestriction(AllowedInRestrictedMode=true)] - public sealed class TaskSetVariableCommand: IWorkerCommand + [CommandRestriction(AllowedInRestrictedMode = true)] + public sealed class TaskSetVariableCommand : IWorkerCommand { public string Name => "setvariable"; public List Aliases => null; @@ -622,8 +622,8 @@ public void Execute(IExecutionContext context, Command command) } } - [CommandRestriction(AllowedInRestrictedMode=true)] - public sealed class TaskDebugCommand: IWorkerCommand + [CommandRestriction(AllowedInRestrictedMode = true)] + public sealed class TaskDebugCommand : IWorkerCommand { public string Name => "debug"; public List Aliases => null; @@ -638,8 +638,8 @@ public void Execute(IExecutionContext context, Command command) } } - [CommandRestriction(AllowedInRestrictedMode=true)] - public sealed class TaskSetTaskVariableCommand: IWorkerCommand + [CommandRestriction(AllowedInRestrictedMode = true)] + public sealed class TaskSetTaskVariableCommand : IWorkerCommand { public string Name => "settaskvariable"; public List Aliases => null; @@ -700,7 +700,7 @@ public void Execute(IExecutionContext context, Command command) } } - public sealed class TaskSetEndpointCommand: IWorkerCommand + public sealed class TaskSetEndpointCommand : IWorkerCommand { public string Name => "setendpoint"; public List Aliases => null; @@ -781,8 +781,8 @@ public void Execute(IExecutionContext context, Command command) } } - [CommandRestriction(AllowedInRestrictedMode=true)] - public sealed class TaskPrepandPathCommand: IWorkerCommand + [CommandRestriction(AllowedInRestrictedMode = true)] + public sealed class TaskPrepandPathCommand : IWorkerCommand { public string Name => "prependpath"; public List Aliases => null; diff --git a/src/Agent.Worker/TaskManager.cs b/src/Agent.Worker/TaskManager.cs index 34a090fdce..5d289cce66 100644 --- a/src/Agent.Worker/TaskManager.cs +++ b/src/Agent.Worker/TaskManager.cs @@ -341,7 +341,7 @@ public sealed class Definition { public DefinitionData Data { get; set; } public string Directory { get; set; } - public string ZipPath {get;set;} + public string ZipPath { get; set; } } public sealed class DefinitionData diff --git a/src/Agent.Worker/TaskRestrictionsExtension.cs b/src/Agent.Worker/TaskRestrictionsExtension.cs index c65c8f5d07..55326dff3c 100644 --- a/src/Agent.Worker/TaskRestrictionsExtension.cs +++ b/src/Agent.Worker/TaskRestrictionsExtension.cs @@ -8,7 +8,7 @@ namespace Microsoft.VisualStudio.Services.Agent.Worker { - [ AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] + [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] public sealed class CommandRestrictionAttribute : Attribute { public bool AllowedInRestrictedMode { get; set; } @@ -30,13 +30,13 @@ public static Boolean IsCommandAllowed(this TaskRestrictions restrictions, IWork return true; } } - + return false; } else { return true; - } + } } public static Boolean IsSetVariableAllowed(this TaskRestrictions restrictions, String variable) diff --git a/src/Agent.Worker/TaskRunner.cs b/src/Agent.Worker/TaskRunner.cs index b267c3fd4a..d6a63919e0 100644 --- a/src/Agent.Worker/TaskRunner.cs +++ b/src/Agent.Worker/TaskRunner.cs @@ -577,7 +577,7 @@ private void PublishTelemetry(Definition taskDefinition, HandlerData handlerData var useNode10 = AgentKnobs.UseNode10.GetValue(ExecutionContext).AsString(); var expectedExecutionHandler = (taskDefinition.Data.Execution?.All != null) ? string.Join(", ", taskDefinition.Data.Execution.All) : ""; - + Dictionary telemetryData = new Dictionary { { "TaskName", Task.Reference.Name }, diff --git a/src/Agent.Worker/Telemetry/TelemetryCommandExtension.cs b/src/Agent.Worker/Telemetry/TelemetryCommandExtension.cs index 5815c31d5b..c89a3a602b 100644 --- a/src/Agent.Worker/Telemetry/TelemetryCommandExtension.cs +++ b/src/Agent.Worker/Telemetry/TelemetryCommandExtension.cs @@ -13,7 +13,7 @@ namespace Microsoft.VisualStudio.Services.Agent.Worker.Telemetry { - public class TelemetryCommandExtension: BaseWorkerCommandExtension + public class TelemetryCommandExtension : BaseWorkerCommandExtension { public TelemetryCommandExtension() { @@ -23,8 +23,8 @@ public TelemetryCommandExtension() } } - [CommandRestriction(AllowedInRestrictedMode=true)] - public sealed class PublishTelemetryCommand: IWorkerCommand + [CommandRestriction(AllowedInRestrictedMode = true)] + public sealed class PublishTelemetryCommand : IWorkerCommand { public string Name => "publish"; public List Aliases => null; diff --git a/src/Agent.Worker/TempDirectoryManager.cs b/src/Agent.Worker/TempDirectoryManager.cs index 2a12a39b79..0bcd9d8e45 100644 --- a/src/Agent.Worker/TempDirectoryManager.cs +++ b/src/Agent.Worker/TempDirectoryManager.cs @@ -65,7 +65,7 @@ public void InitializeTempDirectory(IExecutionContext jobContext) else { jobContext.Debug($"SET TMPDIR={_tempDirectory}"); - jobContext.SetVariable("TMPDIR", _tempDirectory, isFilePath:true); + jobContext.SetVariable("TMPDIR", _tempDirectory, isFilePath: true); } } } diff --git a/src/Agent.Worker/TestResults/Legacy/ContainerStructureTestResultReader.cs b/src/Agent.Worker/TestResults/Legacy/ContainerStructureTestResultReader.cs index 08e5129ee8..17afa277b6 100644 --- a/src/Agent.Worker/TestResults/Legacy/ContainerStructureTestResultReader.cs +++ b/src/Agent.Worker/TestResults/Legacy/ContainerStructureTestResultReader.cs @@ -17,7 +17,7 @@ namespace Microsoft.VisualStudio.Services.Agent.Worker.LegacyTestResults /// public class ContainerStructureTestResultReader : AgentService, IResultReader { - public bool AddResultsFileToRunLevelAttachments {get;set;} + public bool AddResultsFileToRunLevelAttachments { get; set; } public string Name => "ContainerStructure"; @@ -33,7 +33,7 @@ public TestRunData ReadResults(IExecutionContext executionContext, string filePa try { string jsonTestSummary = File.ReadAllText(filePath); - if (string.IsNullOrWhiteSpace(jsonTestSummary)) + if (string.IsNullOrWhiteSpace(jsonTestSummary)) { return null; } @@ -41,7 +41,7 @@ public TestRunData ReadResults(IExecutionContext executionContext, string filePa JsonTestSummary testSummary = StringUtil.ConvertFromJson(jsonTestSummary); // Adding the minimum details from the JSON. - TestRunData testRunData = new TestRunData( name: "Container Structure Test", + TestRunData testRunData = new TestRunData(name: "Container Structure Test", isAutomated: true, buildId: runContext != null ? runContext.BuildId : 0, buildFlavor: runContext != null ? runContext.Configuration : string.Empty, @@ -51,18 +51,18 @@ public TestRunData ReadResults(IExecutionContext executionContext, string filePa List results = new List(); - foreach(JsonTestResult result in testSummary.Results) + foreach (JsonTestResult result in testSummary.Results) { TestCaseResultData resultCreateModel = new TestCaseResultData(); resultCreateModel.TestCaseTitle = result.Name; resultCreateModel.AutomatedTestName = result.Name; bool outcome = result.Pass.Equals("true", StringComparison.OrdinalIgnoreCase); - if(!outcome) + if (!outcome) { resultCreateModel.ErrorMessage = string.Join("|", result.Errors); } - + resultCreateModel.State = "Completed"; resultCreateModel.AutomatedTestType = Name; resultCreateModel.Outcome = outcome ? TestOutcome.Passed.ToString() : TestOutcome.Failed.ToString(); @@ -73,7 +73,7 @@ public TestRunData ReadResults(IExecutionContext executionContext, string filePa return testRunData; } - catch(Exception ex) + catch (Exception ex) { executionContext.Output("Error occured in reading results : " + ex); } @@ -83,10 +83,10 @@ public TestRunData ReadResults(IExecutionContext executionContext, string filePa public class JsonTestSummary { - public string Name {get;set;} - public int Pass {get;set;} - public int Fail {get;set;} - public JsonTestResult[] Results {get;set;} + public string Name { get; set; } + public int Pass { get; set; } + public int Fail { get; set; } + public JsonTestResult[] Results { get; set; } public JsonTestSummary() { } @@ -95,9 +95,9 @@ public JsonTestSummary() public class JsonTestResult { - public string Name {get;set;} - public string Pass {get;set;} - public string[] Errors {get;set;} + public string Name { get; set; } + public string Pass { get; set; } + public string[] Errors { get; set; } public JsonTestResult() { } diff --git a/src/Agent.Worker/TestResults/Legacy/CtestResultReader.cs b/src/Agent.Worker/TestResults/Legacy/CtestResultReader.cs index 8ed8e62a33..f216887ded 100644 --- a/src/Agent.Worker/TestResults/Legacy/CtestResultReader.cs +++ b/src/Agent.Worker/TestResults/Legacy/CtestResultReader.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using Microsoft.TeamFoundation.TestManagement.WebApi; +using Microsoft.TeamFoundation.TestManagement.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.WebApi; using System; @@ -85,7 +85,7 @@ public TestRunData ReadResults(IExecutionContext executionContext, string filePa ) { Attachments = AddResultsFileToRunLevelAttachments ? new string[] { filePath } : new string[0] - }; + }; // Read results XmlNodeList resultsNodes = doc.SelectNodes("/Site/Testing/Test"); results.AddRange(ReadActualResults(resultsNodes)); @@ -105,7 +105,7 @@ private void ParseRunStartAndFinishDates(XmlNode node) { int startTime, endTime; if (int.TryParse(node.SelectSingleNode("./StartTestTime")?.InnerText, out startTime) && int.TryParse(node.SelectSingleNode("./EndTestTime")?.InnerText, out endTime) - && startTime>0 && endTime>0) + && startTime > 0 && endTime > 0) { _ec.Debug("Setting run start and finish times."); diff --git a/src/Agent.Worker/TestResults/Legacy/IResultReader.cs b/src/Agent.Worker/TestResults/Legacy/IResultReader.cs index 15c87e0b83..c029cae0db 100644 --- a/src/Agent.Worker/TestResults/Legacy/IResultReader.cs +++ b/src/Agent.Worker/TestResults/Legacy/IResultReader.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using TestRunContext = Microsoft.TeamFoundation.TestClient.PublishTestResults.TestRunContext; +using TestRunContext = Microsoft.TeamFoundation.TestClient.PublishTestResults.TestRunContext; namespace Microsoft.VisualStudio.Services.Agent.Worker.LegacyTestResults { diff --git a/src/Agent.Worker/TestResults/Legacy/JunitResultReader.cs b/src/Agent.Worker/TestResults/Legacy/JunitResultReader.cs index 80819614e6..762447db69 100644 --- a/src/Agent.Worker/TestResults/Legacy/JunitResultReader.cs +++ b/src/Agent.Worker/TestResults/Legacy/JunitResultReader.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using Microsoft.TeamFoundation.TestManagement.WebApi; +using Microsoft.TeamFoundation.TestManagement.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.WebApi; using System; @@ -32,7 +32,7 @@ public JUnitResultReader() public TestRunData ReadResults(IExecutionContext executionContext, string filePath, TestRunContext runContext = null) { // http://windyroad.com.au/dl/Open%20Source/JUnit.xsd - + XmlDocument doc = new XmlDocument(); try { @@ -130,20 +130,20 @@ public TestRunData ReadResults(IExecutionContext executionContext, string filePa if (!runSummary.SuiteTimeStampAvailable) { executionContext.Output("Timestamp is not available for one or more testsuites. Total run duration is being calculated as the sum of time durations of detected testsuites"); - + if (!runSummary.SuiteTimeDataAvailable) { executionContext.Output("Time is not available for one or more testsuites. Total run duration is being calculated as the sum of time durations of detected testcases"); } } //if start time is not calculated then it should be initialized as present time - runSummary.TimeStamp = runSummary.TimeStamp == DateTime.MaxValue - ? presentTime + runSummary.TimeStamp = runSummary.TimeStamp == DateTime.MaxValue + ? presentTime : runSummary.TimeStamp; //if suite timestamp data is not available even for single testsuite, then fallback to testsuite run time //if testsuite run time is not available even for single testsuite, then fallback to total test case duration - maxCompletedTime = !runSummary.SuiteTimeStampAvailable || maxCompletedTime == DateTime.MinValue - ? runSummary.TimeStamp.Add(runSummary.SuiteTimeDataAvailable ? runSummary.TestSuiteDuration + maxCompletedTime = !runSummary.SuiteTimeStampAvailable || maxCompletedTime == DateTime.MinValue + ? runSummary.TimeStamp.Add(runSummary.SuiteTimeDataAvailable ? runSummary.TestSuiteDuration : runSummary.TotalTestCaseDuration) : maxCompletedTime; //create test run data var testRunData = new TestRunData( @@ -180,17 +180,17 @@ public bool AddResultsFileToRunLevelAttachments private TestSuiteSummary ReadTestSuite(XmlNode rootNode, IdentityRef runUserIdRef) { TestSuiteSummary testSuiteSummary = new TestSuiteSummary(Name); - + XmlNodeList innerTestSuiteNodeList = rootNode.SelectNodes("./testsuite"); - if(innerTestSuiteNodeList != null) + if (innerTestSuiteNodeList != null) { - foreach(XmlNode innerTestSuiteNode in innerTestSuiteNodeList) + foreach (XmlNode innerTestSuiteNode in innerTestSuiteNodeList) { - TestSuiteSummary innerTestSuiteSummary = ReadTestSuite(innerTestSuiteNode , runUserIdRef); + TestSuiteSummary innerTestSuiteSummary = ReadTestSuite(innerTestSuiteNode, runUserIdRef); testSuiteSummary.Results.AddRange(innerTestSuiteSummary.Results); } } - + TimeSpan totalTestSuiteDuration = TimeSpan.Zero; TimeSpan totalTestCaseDuration = TimeSpan.Zero; @@ -326,8 +326,8 @@ private static TimeSpan GetTimeSpan(XmlNode rootNode, out bool TimeDataAvailable if (timeValue != null) { // Ensure that the time data is a positive value within range - if (Double.TryParse(timeValue, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out double timeInSeconds) - && !Double.IsNaN(timeInSeconds) + if (Double.TryParse(timeValue, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out double timeInSeconds) + && !Double.IsNaN(timeInSeconds) && !Double.IsInfinity(timeInSeconds) && timeInSeconds >= 0) { @@ -362,7 +362,7 @@ private void AddSystemLogsToResult(XmlNode testCaseNode, TestCaseResultData resu stdout = testCaseNode.SelectSingleNode("./system-out"); resultCreateModel.AttachmentData = new AttachmentData(); - + if (stdout != null && !string.IsNullOrWhiteSpace(stdout.InnerText)) { resultCreateModel.AttachmentData.ConsoleLog = stdout.InnerText; @@ -389,9 +389,9 @@ class TestSuiteSummary public List Results { get; set; } public TimeSpan TotalTestCaseDuration { get; set; } - + public bool SuiteTimeDataAvailable { get; set; } - + public bool SuiteTimeStampAvailable { get; set; } public TestSuiteSummary(string name) diff --git a/src/Agent.Worker/TestResults/Legacy/LegacyTestRunDataPublisher.cs b/src/Agent.Worker/TestResults/Legacy/LegacyTestRunDataPublisher.cs index 038277f911..6ed9b9f017 100644 --- a/src/Agent.Worker/TestResults/Legacy/LegacyTestRunDataPublisher.cs +++ b/src/Agent.Worker/TestResults/Legacy/LegacyTestRunDataPublisher.cs @@ -219,7 +219,7 @@ private async Task PublishAllTestResultsToSingleTestRunAsync(List isTestRunOutcomeFailed = runOutcome.Value; } } - + StoreTestRunSummaryInEnvVar(testRunSummary); } } @@ -235,7 +235,7 @@ private async Task PublishAllTestResultsToSingleTestRunAsync(List private void StoreTestRunSummaryInEnvVar(TestRunSummary testRunSummary) { // Storing testrun summary in environment variable, which will be read by PublishPipelineMetadataTask and publish to evidence store. - if(_calculateTestRunSummary) + if (_calculateTestRunSummary) { TestResultUtils.StoreTestRunSummaryInEnvVar(_executionContext, testRunSummary, _testRunner, "PublishTestResults"); } @@ -291,10 +291,10 @@ private async Task PublishToNewTestRunPerTestResultFileAsync(List { testRunData.AddCustomField(_testRunSystemCustomFieldName, runContext.TestRunSystem); AddTargetBranchInfoToRunCreateModel(testRunData, runContext.TargetBranchName); - TestRun testRun = await publisher.StartTestRunAsync(testRunData, _executionContext.CancellationToken); + TestRun testRun = await publisher.StartTestRunAsync(testRunData, _executionContext.CancellationToken); await publisher.AddResultsAsync(testRun, testRunData.Results, _executionContext.CancellationToken); TestRun updatedRun = await publisher.EndTestRunAsync(testRunData, testRun.Id, cancellationToken: _executionContext.CancellationToken); - + publishedRuns.Add(updatedRun); } else @@ -336,7 +336,7 @@ private async Task PublishToNewTestRunPerTestResultFileAsync(List private string GetRunName(string runTitle) { - lock (_sync) + lock (_sync) { return StringUtil.Format("{0}_{1}", runTitle, ++_runCounter); } @@ -380,11 +380,11 @@ private void AddTargetBranchInfoToRunCreateModel(RunCreateModel runCreateModel, private bool GetTestRunOutcome(TestRunData testRunData, TestRunSummary testRunSummary) { bool anyFailedTests = false; - foreach(var testCaseResultData in testRunData.Results) + foreach (var testCaseResultData in testRunData.Results) { testRunSummary.Total += 1; Enum.TryParse(testCaseResultData.Outcome, out TestOutcome outcome); - switch(outcome) + switch (outcome) { case TestOutcome.Failed: case TestOutcome.Aborted: @@ -400,7 +400,7 @@ private bool GetTestRunOutcome(TestRunData testRunData, TestRunSummary testRunSu default: break; } - if(!_calculateTestRunSummary && anyFailedTests) + if (!_calculateTestRunSummary && anyFailedTests) { return anyFailedTests; } diff --git a/src/Agent.Worker/TestResults/Legacy/NunitResultReader.cs b/src/Agent.Worker/TestResults/Legacy/NunitResultReader.cs index 5cc39b121d..f543fc6e74 100644 --- a/src/Agent.Worker/TestResults/Legacy/NunitResultReader.cs +++ b/src/Agent.Worker/TestResults/Legacy/NunitResultReader.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using Microsoft.TeamFoundation.TestManagement.WebApi; +using Microsoft.TeamFoundation.TestManagement.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.WebApi; using System; @@ -14,7 +14,7 @@ namespace Microsoft.VisualStudio.Services.Agent.Worker.LegacyTestResults { internal class NUnitResultsXmlReader { - public NUnitResultsXmlReader() + public NUnitResultsXmlReader() { } @@ -162,7 +162,7 @@ private List FindTestCaseNodes(XmlNode startNode, string hos resultCreateModel.TestCaseTitle = testCaseNode.Attributes["name"].Value; resultCreateModel.AutomatedTestName = testCaseNode.Attributes["name"].Value; } - + if (!string.IsNullOrEmpty(testStorage)) { resultCreateModel.AutomatedTestStorage = testStorage; @@ -175,7 +175,7 @@ private List FindTestCaseNodes(XmlNode startNode, string hos double duration = 0; double.TryParse(testCaseNode.Attributes["time"].Value, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out duration); // Duration of a test case cannot be less than zero - testCaseDuration = ( duration < 0 ) ? testCaseDuration : TimeSpan.FromSeconds(duration); + testCaseDuration = (duration < 0) ? testCaseDuration : TimeSpan.FromSeconds(duration); } resultCreateModel.DurationInMs = testCaseDuration.TotalMilliseconds; @@ -268,7 +268,7 @@ public interface INUnitResultsXmlReader TestRunData GetTestRunData(string filePath, XmlDocument doc, XmlNode testResultsNode, TestRunContext runContext, bool addResultsAsAttachments); } - internal class NUnit2ResultsXmlReader: NUnitResultsXmlReader, INUnitResultsXmlReader + internal class NUnit2ResultsXmlReader : NUnitResultsXmlReader, INUnitResultsXmlReader { public new TestRunData GetTestRunData(string filePath, XmlDocument doc, XmlNode testResultsNode, TestRunContext runContext, bool addResultsAsAttachments) { @@ -280,7 +280,7 @@ internal class NUnit2ResultsXmlReader: NUnitResultsXmlReader, INUnitResultsXmlRe } } - internal class NUnit3ResultsXmlReader: INUnitResultsXmlReader + internal class NUnit3ResultsXmlReader : INUnitResultsXmlReader { private IdentityRef _runUserIdRef; private string _platform; @@ -299,14 +299,14 @@ private TestCaseResultData getTestCaseResultData(XmlNode testCaseResultNode, str double duration = 0; double.TryParse(testCaseResultNode.Attributes["duration"]?.Value, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out duration); // Ensure Duration cannot be negative - duration = (duration <0) ? 0 : duration; + duration = (duration < 0) ? 0 : duration; testCaseResultData.DurationInMs = TimeSpan.FromSeconds(duration).TotalMilliseconds; var testExecutionStartedOn = DateTime.MinValue; DateTime.TryParse(testCaseResultNode.Attributes["start-time"]?.Value, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out testExecutionStartedOn); testCaseResultData.StartedDate = testExecutionStartedOn; var testExecutionEndedOn = DateTime.MinValue; - DateTime.TryParse(testCaseResultNode.Attributes["end-time"]?.Value, DateTimeFormatInfo.InvariantInfo,DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out testExecutionEndedOn); - testCaseResultData.CompletedDate = testExecutionEndedOn; + DateTime.TryParse(testCaseResultNode.Attributes["end-time"]?.Value, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out testExecutionEndedOn); + testCaseResultData.CompletedDate = testExecutionEndedOn; testCaseResultData.AttachmentData = new AttachmentData(); if (testCaseResultNode.Attributes["result"] != null) { @@ -321,7 +321,7 @@ private TestCaseResultData getTestCaseResultData(XmlNode testCaseResultNode, str else if (string.Equals(testCaseResultNode.Attributes["result"].Value, "Skipped", StringComparison.OrdinalIgnoreCase)) { testCaseResultData.Outcome = TestOutcome.NotExecuted.ToString(); - } + } else { testCaseResultData.Outcome = TestOutcome.Inconclusive.ToString(); @@ -376,7 +376,7 @@ public TestRunData GetTestRunData(string filePath, XmlDocument doc, XmlNode test { var environmentNode = testAssemblyNode.SelectSingleNode("environment"); var hostname = String.Empty; - var assemblyName = (testAssemblyNode.Attributes["name"] != null ? testAssemblyNode.Attributes["name"].Value : null); + var assemblyName = (testAssemblyNode.Attributes["name"] != null ? testAssemblyNode.Attributes["name"].Value : null); if (environmentNode != null) { if (environmentNode.Attributes["machine-name"] != null) @@ -499,7 +499,7 @@ public TestRunData ReadResults(IExecutionContext executionContext, string filePa } return nunitResultsReader.GetTestRunData(filePath, doc, testResultsNode, runContext, AddResultsFileToRunLevelAttachments); - + } diff --git a/src/Agent.Worker/TestResults/Legacy/TestCaseResultData.cs b/src/Agent.Worker/TestResults/Legacy/TestCaseResultData.cs index aaff8cf188..05877dd67d 100644 --- a/src/Agent.Worker/TestResults/Legacy/TestCaseResultData.cs +++ b/src/Agent.Worker/TestResults/Legacy/TestCaseResultData.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; +using System; using System.Collections.Generic; using Microsoft.VisualStudio.Services.WebApi; using Microsoft.TeamFoundation.TestManagement.WebApi; @@ -45,7 +45,7 @@ public class TestCaseResultData public int Priority; public string ComputerName; - + public int ResetCount; public ShallowReference Build; diff --git a/src/Agent.Worker/TestResults/Legacy/TestResultsServer.cs b/src/Agent.Worker/TestResults/Legacy/TestResultsServer.cs index f8f46ea8de..b1e0cd6008 100644 --- a/src/Agent.Worker/TestResults/Legacy/TestResultsServer.cs +++ b/src/Agent.Worker/TestResults/Legacy/TestResultsServer.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using Microsoft.TeamFoundation.TestManagement.WebApi; +using Microsoft.TeamFoundation.TestManagement.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.FeatureAvailability.WebApi; using Microsoft.VisualStudio.Services.TestResults.WebApi; @@ -24,9 +24,9 @@ public interface ITestResultsServer : IAgentService Task CreateTestResultAttachmentAsync(TestAttachmentRequestModel reqModel, string projectName, int testRunId, int testCaseResultId, CancellationToken cancellationToken = default(CancellationToken)); Task CreateTestSubResultAttachmentAsync(TestAttachmentRequestModel reqModel, string projectName, int testRunId, int testCaseResultId, int testSubResultId, CancellationToken cancellationToken = default(CancellationToken)); Task GetTestResultsSettingsAsync(string project, TestResultsSettingsType? settingsType = null, object userState = null, CancellationToken cancellationToken = default(CancellationToken)); - Task GetTestRunStatisticsAsync(string project,int runId,object userState = null, + Task GetTestRunStatisticsAsync(string project, int runId, object userState = null, CancellationToken cancellationToken = default(CancellationToken)); - Task GetTestRunSummaryByOutcomeAsync(string project,int runId,object userState = null, + Task GetTestRunSummaryByOutcomeAsync(string project, int runId, object userState = null, CancellationToken cancellationToken = default); Task UpdateCodeCoverageSummaryAsync(VssConnection connection, string project, int buildId); } @@ -51,11 +51,11 @@ public void InitializeServer(VssConnection connection, IExecutionContext executi TestHttpClient = connection.GetClient(); } } - - public async Task UpdateCodeCoverageSummaryAsync(VssConnection connection ,string project, int buildId) + + public async Task UpdateCodeCoverageSummaryAsync(VssConnection connection, string project, int buildId) { TestResultsHttpClient tcmClient = connection.GetClient(); - return await tcmClient.UpdateCodeCoverageSummaryAsync(project, buildId); + return await tcmClient.UpdateCodeCoverageSummaryAsync(project, buildId); } public async Task> AddTestResultsToTestRunAsync( @@ -145,7 +145,7 @@ private static bool GetFeatureFlagState(IExecutionContext executionContext, VssC return true; } } - catch(Exception ex) + catch (Exception ex) { executionContext.Output("Unable to get the FF: " + EnablePublishToTcmServiceDirectlyFromTaskFF + ". Reason: " + ex.Message); } diff --git a/src/Agent.Worker/TestResults/Legacy/TestRunData.cs b/src/Agent.Worker/TestResults/Legacy/TestRunData.cs index bae8203026..1102a44ab0 100644 --- a/src/Agent.Worker/TestResults/Legacy/TestRunData.cs +++ b/src/Agent.Worker/TestResults/Legacy/TestRunData.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using Microsoft.TeamFoundation.TestManagement.WebApi; +using Microsoft.TeamFoundation.TestManagement.WebApi; using System.Collections.Generic; namespace Microsoft.VisualStudio.Services.Agent.Worker.LegacyTestResults diff --git a/src/Agent.Worker/TestResults/Legacy/TestRunPublisher.cs b/src/Agent.Worker/TestResults/Legacy/TestRunPublisher.cs index a79e88ed5b..5b4e8743cb 100644 --- a/src/Agent.Worker/TestResults/Legacy/TestRunPublisher.cs +++ b/src/Agent.Worker/TestResults/Legacy/TestRunPublisher.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using Microsoft.TeamFoundation.TestManagement.WebApi; +using Microsoft.TeamFoundation.TestManagement.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.Agent.Worker.TestResults.Utils; using Microsoft.VisualStudio.Services.WebApi; @@ -121,7 +121,8 @@ public async Task AddResultsAsync(TestRun testRun, TestCaseResultData[] testResu var testResultsBatch = new TestCaseResult[noOfResultsToBePublished]; Array.Copy(testResults, i, currentBatch, 0, noOfResultsToBePublished); - for (int testResultsIndex = 0; testResultsIndex < noOfResultsToBePublished; testResultsIndex++){ + for (int testResultsIndex = 0; testResultsIndex < noOfResultsToBePublished; testResultsIndex++) + { if (IsMaxLimitReachedForSubresultPreProcessing(currentBatch[testResultsIndex].AutomatedTestName, currentBatch[testResultsIndex].TestCaseSubResultData) == false) { @@ -395,9 +396,9 @@ private async Task UploadTestResultsAttachmentAsync(int testRunId, } } - if(testCaseResult.SubResults != null && testCaseResult.SubResults.Any() && testCaseResultData.TestCaseSubResultData != null) + if (testCaseResult.SubResults != null && testCaseResult.SubResults.Any() && testCaseResultData.TestCaseSubResultData != null) { - for(int i = 0; i < testCaseResultData.TestCaseSubResultData.Count; i++) + for (int i = 0; i < testCaseResultData.TestCaseSubResultData.Count; i++) { await UploadTestSubResultsAttachmentAsync(testRunId, testCaseResult.Id, testCaseResultData.TestCaseSubResultData[i], testCaseResult.SubResults[i], 1, cancellationToken); } @@ -425,7 +426,7 @@ private async Task UploadTestSubResultsAttachmentAsync(int testRunId, .Select(async attachment => { TestAttachmentRequestModel reqModel = GetAttachmentRequestModel(attachment); - if(reqModel != null) + if (reqModel != null) { await _testResultsServer.CreateTestSubResultAttachmentAsync(reqModel, _projectName, testRunId, testResultId, subresult.Id, cancellationToken); } diff --git a/src/Agent.Worker/TestResults/Legacy/TrxResultReader.cs b/src/Agent.Worker/TestResults/Legacy/TrxResultReader.cs index ee65eb40b4..790aa5e89a 100644 --- a/src/Agent.Worker/TestResults/Legacy/TrxResultReader.cs +++ b/src/Agent.Worker/TestResults/Legacy/TrxResultReader.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using Microsoft.TeamFoundation.TestManagement.WebApi; +using Microsoft.TeamFoundation.TestManagement.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.WebApi; using System; @@ -80,11 +80,11 @@ public TestRunData ReadResults(IExecutionContext executionContext, string filePa DateTime runFinishDate = DateTime.MinValue; if (node != null && node.Attributes["start"] != null && node.Attributes["finish"] != null) { - if (DateTime.TryParse(node.Attributes["start"].Value, DateTimeFormatInfo.InvariantInfo,DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out runStartDate)) + if (DateTime.TryParse(node.Attributes["start"].Value, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out runStartDate)) { _executionContext.Debug(string.Format(CultureInfo.InvariantCulture, "Setting run start and finish times.")); //Only if there is a valid start date. - DateTime.TryParse(node.Attributes["finish"].Value, DateTimeFormatInfo.InvariantInfo,DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out runFinishDate); + DateTime.TryParse(node.Attributes["finish"].Value, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out runFinishDate); if (runFinishDate < runStartDate) { runFinishDate = runStartDate = DateTime.MinValue; @@ -111,7 +111,7 @@ public TestRunData ReadResults(IExecutionContext executionContext, string filePa //Parse the Deployment node for the runDeploymentRoot - this is the attachment root. Required for .NET Core XmlNode deploymentNode = doc.SelectSingleNode("/TestRun/TestSettings/Deployment"); var _attachmentRoot = string.Empty; - if (deploymentNode != null && deploymentNode.Attributes["runDeploymentRoot"] != null ) + if (deploymentNode != null && deploymentNode.Attributes["runDeploymentRoot"] != null) { _attachmentRoot = deploymentNode.Attributes["runDeploymentRoot"].Value; } @@ -309,17 +309,18 @@ private List ReadActualResults(XmlNodeList resultsNodes, Tes DateTime completedDate = startedDate.AddTicks(duration.Ticks); resultCreateModel.CompletedDate = completedDate; - if ((DateTime.Compare(default(DateTime), startedDate) < 0 && DateTime.Compare(startedDate, (DateTime) SqlDateTime.MinValue) <= 0) - || (DateTime.Compare(default(DateTime), completedDate) < 0 && DateTime.Compare(completedDate, (DateTime) SqlDateTime.MinValue) <= 0)) { + if ((DateTime.Compare(default(DateTime), startedDate) < 0 && DateTime.Compare(startedDate, (DateTime)SqlDateTime.MinValue) <= 0) + || (DateTime.Compare(default(DateTime), completedDate) < 0 && DateTime.Compare(completedDate, (DateTime)SqlDateTime.MinValue) <= 0)) + { - DateTime utcNow = DateTime.UtcNow; - resultCreateModel.StartedDate = utcNow; - resultCreateModel.CompletedDate = utcNow.AddTicks(duration.Ticks); + DateTime utcNow = DateTime.UtcNow; + resultCreateModel.StartedDate = utcNow; + resultCreateModel.CompletedDate = utcNow.AddTicks(duration.Ticks); } if (resultNode.Attributes["outcome"] == null || resultNode.Attributes["outcome"].Value == null || string.Equals(resultNode.Attributes["outcome"].Value, "failed", StringComparison.OrdinalIgnoreCase)) { - resultCreateModel.Outcome = TestOutcome.Failed.ToString(); ; + resultCreateModel.Outcome = TestOutcome.Failed.ToString(); } else if (string.Equals(resultNode.Attributes["outcome"].Value, "passed", StringComparison.OrdinalIgnoreCase)) { @@ -509,7 +510,7 @@ private List ReadActualSubResults(XmlNodeList resultsNode if (resultNode.Attributes["outcome"] == null || resultNode.Attributes["outcome"].Value == null || string.Equals(resultNode.Attributes["outcome"].Value, "failed", StringComparison.OrdinalIgnoreCase)) { - resultCreateModel.Outcome = TestOutcome.Failed.ToString(); ; + resultCreateModel.Outcome = TestOutcome.Failed.ToString(); } else if (string.Equals(resultNode.Attributes["outcome"].Value, "passed", StringComparison.OrdinalIgnoreCase)) { @@ -582,7 +583,7 @@ private List ReadActualSubResults(XmlNodeList resultsNode resultCreateModel.SubResultData = new List(); - resultCreateModel.SubResultData.AddRange(ReadActualSubResults(resNodes, TestType.UnitTest, level+1)); + resultCreateModel.SubResultData.AddRange(ReadActualSubResults(resNodes, TestType.UnitTest, level + 1)); resultCreateModel.SubResultData.AddRange(ReadActualSubResults(webTestResultNodes, TestType.WebTest, level + 1)); resultCreateModel.SubResultData.AddRange(ReadActualSubResults(orderedTestResultNodes, TestType.OrderedTest, level + 1)); } @@ -664,7 +665,8 @@ private ResultGroupType GetResultGroupType(XmlNode resultNode, TestType testType if (testType == TestType.OrderedTest) { return ResultGroupType.OrderedTest; - } else + } + else { if (resultNode.Attributes["resultType"]?.Value != null && resultNode.Attributes["resultType"]?.Value == "DataDrivenTest") { diff --git a/src/Agent.Worker/TestResults/Legacy/XunitResultReader.cs b/src/Agent.Worker/TestResults/Legacy/XunitResultReader.cs index 538b63e60c..10807179d5 100644 --- a/src/Agent.Worker/TestResults/Legacy/XunitResultReader.cs +++ b/src/Agent.Worker/TestResults/Legacy/XunitResultReader.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using Microsoft.TeamFoundation.TestManagement.WebApi; +using Microsoft.TeamFoundation.TestManagement.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.WebApi; using System; @@ -87,7 +87,7 @@ public TestRunData ReadResults(IExecutionContext executionContext, string filePa var startDate = DateTime.Now; var startTime = TimeSpan.Zero; - if (DateTime.TryParse(runDate, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out startDate) && + if (DateTime.TryParse(runDate, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out startDate) && TimeSpan.TryParse(runTime, CultureInfo.InvariantCulture, out startTime)) { dateTimeParseError = false; @@ -98,7 +98,7 @@ public TestRunData ReadResults(IExecutionContext executionContext, string filePa minStartTime = assemblyRunStartTimeStamp; } } - else + else { assemblyRunDateTimeAttributesNotPresent = true; } @@ -253,7 +253,7 @@ public TestRunData ReadResults(IExecutionContext executionContext, string filePa } //if minimum start time is not available then set it to present time - minStartTime = minStartTime == DateTime.MaxValue ? DateTime.UtcNow : minStartTime ; + minStartTime = minStartTime == DateTime.MaxValue ? DateTime.UtcNow : minStartTime; //if start time cannot be obtained even for one assembly then fallback duration to sum of assembly run time //if assembly run time cannot be obtained even for one assembly then fallback duration to total test run diff --git a/src/Agent.Worker/TestResults/Parser.cs b/src/Agent.Worker/TestResults/Parser.cs index 31b80174e2..378c7822b8 100644 --- a/src/Agent.Worker/TestResults/Parser.cs +++ b/src/Agent.Worker/TestResults/Parser.cs @@ -130,7 +130,7 @@ protected override ITestResultParser GetTestResultParser(IExecutionContext execu } - public class ContainerStructureTestParser: Parser, IParser + public class ContainerStructureTestParser : Parser, IParser { public override string Name => "ContainerStructure"; diff --git a/src/Agent.Worker/TestResults/PublishToEvidenceStoreCommand.cs b/src/Agent.Worker/TestResults/PublishToEvidenceStoreCommand.cs index 32b3a0cbb4..4540f02feb 100644 --- a/src/Agent.Worker/TestResults/PublishToEvidenceStoreCommand.cs +++ b/src/Agent.Worker/TestResults/PublishToEvidenceStoreCommand.cs @@ -53,7 +53,7 @@ private void ParseInputParameters(IExecutionContext context, Dictionary "publish"; public List Aliases => null; @@ -271,13 +271,15 @@ private async Task PublishTestRunDataAsync(String teamProject, TestRunContext te _telemetryProperties.Add("UsePublishTestResultsLib", publishTestResultsLibFeatureState); //This check is to determine to use "Microsoft.TeamFoundation.PublishTestResults" Library or the agent code to parse and publish the test results. - if (publishTestResultsLibFeatureState){ + if (publishTestResultsLibFeatureState) + { var publisher = _executionContext.GetHostContext().GetService(); publisher.InitializePublisher(_executionContext, teamProject, connection, _testRunner); isTestRunOutcomeFailed = await publisher.PublishAsync(testRunContext, _testResultFiles, GetPublishOptions(), _executionContext.CancellationToken); } - else { + else + { var publisher = _executionContext.GetHostContext().GetService(); publisher.InitializePublisher(_executionContext, teamProject, connection, _testRunner, _publishRunLevelAttachments); @@ -290,60 +292,60 @@ private async Task PublishTestRunDataAsync(String teamProject, TestRunContext te _executionContext.Error(StringUtil.Loc("FailedTestsInResults")); } - await PublishEventsAsync(connection); + await PublishEventsAsync(connection); var triggerCoverageMergeJobFeatureState = featureFlagService.GetFeatureFlagState(CodeCoverageConstants.TriggerCoverageMergeJobFF, TestResultsConstants.TFSServiceInstanceGuid); if (triggerCoverageMergeJobFeatureState) { TriggerCoverageMergeJob(_testResultFiles, _executionContext); } } - + // Queue code coverage merge job if code coverage attachments are published to avoid BQC timeout. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "connection")] - private void TriggerCoverageMergeJob(List resultFilesInput , IExecutionContext context) - { - try + private void TriggerCoverageMergeJob(List resultFilesInput, IExecutionContext context) { - ITestResultsServer _testResultsServer = context.GetHostContext().GetService(); - foreach (var resultFile in resultFilesInput) + try { - string text = File.ReadAllText(resultFile); - XmlDocument xdoc = new XmlDocument(); - xdoc.LoadXml(text); - XmlNodeList nodes = xdoc.GetElementsByTagName("A"); - - var connection = WorkerUtilities.GetVssConnection(_executionContext); - foreach (XmlNode attachmentNode in nodes) + ITestResultsServer _testResultsServer = context.GetHostContext().GetService(); + foreach (var resultFile in resultFilesInput) { - var file = attachmentNode.Attributes?["href"]?.Value; - if (!string.IsNullOrEmpty(file)) + string text = File.ReadAllText(resultFile); + XmlDocument xdoc = new XmlDocument(); + xdoc.LoadXml(text); + XmlNodeList nodes = xdoc.GetElementsByTagName("A"); + + var connection = WorkerUtilities.GetVssConnection(_executionContext); + foreach (XmlNode attachmentNode in nodes) { - if ( - Path.GetExtension(file).Equals(".covx", StringComparison.OrdinalIgnoreCase) || - Path.GetExtension(file).Equals(".covb", StringComparison.OrdinalIgnoreCase) || - Path.GetExtension(file).Equals(".coverage", StringComparison.OrdinalIgnoreCase) - ) - { - _testResultsServer.InitializeServer(connection, _executionContext); + var file = attachmentNode.Attributes?["href"]?.Value; + if (!string.IsNullOrEmpty(file)) + { + if ( + Path.GetExtension(file).Equals(".covx", StringComparison.OrdinalIgnoreCase) || + Path.GetExtension(file).Equals(".covb", StringComparison.OrdinalIgnoreCase) || + Path.GetExtension(file).Equals(".coverage", StringComparison.OrdinalIgnoreCase) + ) + { + _testResultsServer.InitializeServer(connection, _executionContext); try { - var codeCoverageResults = _testResultsServer.UpdateCodeCoverageSummaryAsync(connection,_executionContext.Variables.System_TeamProjectId.ToString(), _executionContext.Variables.Build_BuildId.GetValueOrDefault()); + var codeCoverageResults = _testResultsServer.UpdateCodeCoverageSummaryAsync(connection, _executionContext.Variables.System_TeamProjectId.ToString(), _executionContext.Variables.Build_BuildId.GetValueOrDefault()); } catch (Exception e) - { - _executionContext.Section($"Could not queue code coverage merge:{e}"); + { + _executionContext.Section($"Could not queue code coverage merge:{e}"); } } - } + } + } } } - } catch (Exception e) { _executionContext.Debug($"Exception in Method:{e.Message}"); } } - + private async Task PublishEventsAsync(VssConnection connection) { try @@ -359,7 +361,7 @@ private async Task PublishEventsAsync(VssConnection connection) ciService.Initialize(connection); await ciService.PublishEventsAsync(new CustomerIntelligenceEvent[] { ciEvent }); } - catch(Exception ex) + catch (Exception ex) { _executionContext.Debug(StringUtil.Loc("TelemetryCommandFailed", ex.Message)); } diff --git a/src/Agent.Worker/TestResults/TestDataPublisher.cs b/src/Agent.Worker/TestResults/TestDataPublisher.cs index bc8ce25c0d..fd4c417e2e 100644 --- a/src/Agent.Worker/TestResults/TestDataPublisher.cs +++ b/src/Agent.Worker/TestResults/TestDataPublisher.cs @@ -66,7 +66,8 @@ public void InitializePublisher(IExecutionContext context, string projectName, V TestDataProvider testDataProvider = ParseTestResultsFile(runContext, testResultFiles); var publishTasks = new List(); - if (testDataProvider != null){ + if (testDataProvider != null) + { var testRunData = testDataProvider.GetTestRunData(); //publishing run level attachment Task> publishtestRunDataTask = Task.Run(() => _testRunPublisher.PublishTestRunDataAsync(runContext, _projectName, testRunData, publishOptions, cancellationToken)); @@ -84,9 +85,9 @@ public void InitializePublisher(IExecutionContext context, string projectName, V _calculateTestRunSummary = _featureFlagService.GetFeatureFlagState(TestResultsConstants.CalculateTestRunSummaryFeatureFlag, TestResultsConstants.TFSServiceInstanceGuid); var isTestRunOutcomeFailed = GetTestRunOutcome(_executionContext, testRunData, out TestRunSummary testRunSummary); - + // Storing testrun summary in environment variable, which will be read by PublishPipelineMetadataTask and publish to evidence store. - if(_calculateTestRunSummary) + if (_calculateTestRunSummary) { TestResultUtils.StoreTestRunSummaryInEnvVar(_executionContext, testRunSummary, _testRunner, "PublishTestResults"); } @@ -111,7 +112,7 @@ public void InitializePublisher(IExecutionContext context, string projectName, V } catch (Exception ex) { - _executionContext.Warning("Failed to publish test run data: "+ ex.ToString()); + _executionContext.Warning("Failed to publish test run data: " + ex.ToString()); } return false; } @@ -135,7 +136,7 @@ private bool GetTestRunOutcome(IExecutionContext executionContext, IList 0 && testRunSummary.Total - testRunSummary.Skipped > 0 ? ((double)testRunSummary.Passed/(testRunSummary.Total-testRunSummary.Skipped)) * 100 : 0).ToString(); + this.TestPassPercentage = (testRunSummary.Total > 0 && testRunSummary.Total - testRunSummary.Skipped > 0 ? ((double)testRunSummary.Passed / (testRunSummary.Total - testRunSummary.Skipped)) * 100 : 0).ToString(); // Will populate this in separate PR. As it required change in logic at client side. this.TestDurationSeconds = 0.0; } diff --git a/src/Agent.Worker/Variables.cs b/src/Agent.Worker/Variables.cs index 6e851b72aa..661248f3b2 100644 --- a/src/Agent.Worker/Variables.cs +++ b/src/Agent.Worker/Variables.cs @@ -398,7 +398,7 @@ public void Unset(string name) lock (_setLock) { Variable dummy; - _expanded.Remove(name, out dummy); + _expanded.Remove(name, out dummy); _nonexpanded.Remove(name, out dummy); _trace.Verbose($"Unset '{name}'"); } @@ -447,7 +447,8 @@ public void Set(string name, string val, bool secret = false, bool readOnly = fa public bool IsReadOnly(string name) { Variable existingVariable = null; - if (!_expanded.TryGetValue(name, out existingVariable)) { + if (!_expanded.TryGetValue(name, out existingVariable)) + { _nonexpanded.TryGetValue(name, out existingVariable); } diff --git a/src/Agent.Worker/Worker.cs b/src/Agent.Worker/Worker.cs index eb93e1c8e4..d6882fe964 100644 --- a/src/Agent.Worker/Worker.cs +++ b/src/Agent.Worker/Worker.cs @@ -22,7 +22,7 @@ public interface IWorker : IAgentService public sealed class Worker : AgentService, IWorker { private readonly TimeSpan _workerStartTimeout = TimeSpan.FromSeconds(30); - private static readonly char[] _quoteLikeChars = new char[] {'\'', '"'}; + private static readonly char[] _quoteLikeChars = new char[] { '\'', '"' }; public async Task RunAsync(string pipeIn, string pipeOut) diff --git a/src/Agent.Worker/WorkerCommandManager.cs b/src/Agent.Worker/WorkerCommandManager.cs index 153862bcbc..30c79a8e18 100644 --- a/src/Agent.Worker/WorkerCommandManager.cs +++ b/src/Agent.Worker/WorkerCommandManager.cs @@ -111,9 +111,9 @@ public bool TryProcessCommand(IExecutionContext context, string input) } catch (SocketException ex) { - #pragma warning disable CA2000 // Dispose objects before losing scope +#pragma warning disable CA2000 // Dispose objects before losing scope ExceptionsUtil.HandleSocketException(ex, WorkerUtilities.GetVssConnection(context).Uri.ToString(), context.Error); - #pragma warning restore CA2000 // Dispose objects before losing scope +#pragma warning restore CA2000 // Dispose objects before losing scope context.CommandResult = TaskResult.Failed; } catch (Exception ex) @@ -166,7 +166,7 @@ public interface IWorkerCommand void Execute(IExecutionContext context, Command command); } - public abstract class BaseWorkerCommandExtension: AgentService, IWorkerCommandExtension + public abstract class BaseWorkerCommandExtension : AgentService, IWorkerCommandExtension { public string CommandArea { get; protected set; } diff --git a/src/Microsoft.VisualStudio.Services.Agent/AgentCredentialStore/LinuxAgentCredentialStore.cs b/src/Microsoft.VisualStudio.Services.Agent/AgentCredentialStore/LinuxAgentCredentialStore.cs index 02e1b5221a..370c1eace3 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/AgentCredentialStore/LinuxAgentCredentialStore.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/AgentCredentialStore/LinuxAgentCredentialStore.cs @@ -13,7 +13,7 @@ namespace Microsoft.VisualStudio.Services.Agent { - public sealed class LinuxAgentCredentialStore : AgentService, IAgentCredentialStore + public sealed class LinuxAgentCredentialStore : AgentService, IAgentCredentialStore { // 'msftvsts' 128 bits iv private readonly byte[] iv = new byte[] { 0x36, 0x64, 0x37, 0x33, 0x36, 0x36, 0x37, 0x34, 0x37, 0x36, 0x37, 0x33, 0x37, 0x34, 0x37, 0x33 }; diff --git a/src/Microsoft.VisualStudio.Services.Agent/AgentCredentialStore/MacOSAgentCredentialStore.cs b/src/Microsoft.VisualStudio.Services.Agent/AgentCredentialStore/MacOSAgentCredentialStore.cs index 9b5b1e466f..349a77b290 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/AgentCredentialStore/MacOSAgentCredentialStore.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/AgentCredentialStore/MacOSAgentCredentialStore.cs @@ -12,7 +12,7 @@ namespace Microsoft.VisualStudio.Services.Agent { - public sealed class MacOSAgentCredentialStore : AgentService, IAgentCredentialStore + public sealed class MacOSAgentCredentialStore : AgentService, IAgentCredentialStore { // Keychain requires a password, but this is not intended to add security private const string _osxAgentCredStoreKeyChainPassword = "A1DC2A63B3D14817A64619FDDBC92264"; diff --git a/src/Microsoft.VisualStudio.Services.Agent/AgentCredentialStore/WindowsAgentCredentialStore.cs b/src/Microsoft.VisualStudio.Services.Agent/AgentCredentialStore/WindowsAgentCredentialStore.cs index e9f7d5cbb3..d1608aa1fa 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/AgentCredentialStore/WindowsAgentCredentialStore.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/AgentCredentialStore/WindowsAgentCredentialStore.cs @@ -13,19 +13,19 @@ namespace Microsoft.VisualStudio.Services.Agent { - // Windows credential store is per user. - // This is a limitation for user configure the agent run as windows service, when user's current login account is different with the service run as account. - // Ex: I login the box as domain\admin, configure the agent as windows service and run as domian\buildserver - // domain\buildserver won't read the stored credential from domain\admin's windows credential store. - // To workaround this limitation. - // Anytime we try to save a credential: - // 1. store it into current user's windows credential store - // 2. use DP-API do a machine level encrypt and store the encrypted content on disk. - // At the first time we try to read the credential: - // 1. read from current user's windows credential store, delete the DP-API encrypted backup content on disk if the windows credential store read succeed. - // 2. if credential not found in current user's windows credential store, read from the DP-API encrypted backup content on disk, - // write the credential back the current user's windows credential store and delete the backup on disk. - public sealed class WindowsAgentCredentialStore : AgentService, IAgentCredentialStore + // Windows credential store is per user. + // This is a limitation for user configure the agent run as windows service, when user's current login account is different with the service run as account. + // Ex: I login the box as domain\admin, configure the agent as windows service and run as domian\buildserver + // domain\buildserver won't read the stored credential from domain\admin's windows credential store. + // To workaround this limitation. + // Anytime we try to save a credential: + // 1. store it into current user's windows credential store + // 2. use DP-API do a machine level encrypt and store the encrypted content on disk. + // At the first time we try to read the credential: + // 1. read from current user's windows credential store, delete the DP-API encrypted backup content on disk if the windows credential store read succeed. + // 2. if credential not found in current user's windows credential store, read from the DP-API encrypted backup content on disk, + // write the credential back the current user's windows credential store and delete the backup on disk. + public sealed class WindowsAgentCredentialStore : AgentService, IAgentCredentialStore { private string _credStoreFile; private Dictionary _credStore; diff --git a/src/Microsoft.VisualStudio.Services.Agent/AsyncManualResetEvent.cs b/src/Microsoft.VisualStudio.Services.Agent/AsyncManualResetEvent.cs index bbfcd71a46..e90f0b3793 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/AsyncManualResetEvent.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/AsyncManualResetEvent.cs @@ -7,7 +7,7 @@ namespace Microsoft.VisualStudio.Services.Agent { //Stephen Toub: http://blogs.msdn.com/b/pfxteam/archive/2012/02/11/10266920.aspx - + public class AsyncManualResetEvent { private volatile TaskCompletionSource m_tcs = new TaskCompletionSource(); diff --git a/src/Microsoft.VisualStudio.Services.Agent/Blob/BlobFileInfo.cs b/src/Microsoft.VisualStudio.Services.Agent/Blob/BlobFileInfo.cs index ef9bb936ce..9e1906547e 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/Blob/BlobFileInfo.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/Blob/BlobFileInfo.cs @@ -9,12 +9,12 @@ public class BlobFileInfo { public DedupNode Node { get; set; } public string Path { get; set; } - public DedupIdentifier DedupId + public DedupIdentifier DedupId { - get + get { return Node.GetDedupIdentifier(HashType.Dedup64K); - } + } } public bool Success { get; set; } } diff --git a/src/Microsoft.VisualStudio.Services.Agent/Blob/BlobStoreClientTelemetryTfs.cs b/src/Microsoft.VisualStudio.Services.Agent/Blob/BlobStoreClientTelemetryTfs.cs index f007084701..4d86dd996d 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/Blob/BlobStoreClientTelemetryTfs.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/Blob/BlobStoreClientTelemetryTfs.cs @@ -16,7 +16,7 @@ public class BlobStoreClientTelemetryTfs : BlobStoreClientTelemetry { private CustomerIntelligenceTelemetrySender sender; - public BlobStoreClientTelemetryTfs(IAppTraceSource tracer, Uri baseAddress, VssConnection connection) + public BlobStoreClientTelemetryTfs(IAppTraceSource tracer, Uri baseAddress, VssConnection connection) : this(tracer, baseAddress, new CustomerIntelligenceTelemetrySender(connection)) { } @@ -28,7 +28,7 @@ public BlobStoreClientTelemetryTfs(IAppTraceSource tracer, Uri baseAddress, VssC this.sender = sender as CustomerIntelligenceTelemetrySender; } - private BlobStoreClientTelemetryTfs(IAppTraceSource tracer, Uri baseAddress, CustomerIntelligenceTelemetrySender sender) + private BlobStoreClientTelemetryTfs(IAppTraceSource tracer, Uri baseAddress, CustomerIntelligenceTelemetrySender sender) : base(tracer, baseAddress, sender) { this.sender = sender; diff --git a/src/Microsoft.VisualStudio.Services.Agent/Blob/BlobStoreUtils.cs b/src/Microsoft.VisualStudio.Services.Agent/Blob/BlobStoreUtils.cs index 844244232b..662ed20a92 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/Blob/BlobStoreUtils.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/Blob/BlobStoreUtils.cs @@ -36,13 +36,13 @@ public static class BlobStoreUtils traceOutput(StringUtil.Loc("BuildingFileTree")); var fileNodes = await GenerateHashes(itemPaths, cancellationToken); var rootNode = CreateNodeToUpload(fileNodes.Where(x => x.Success).Select(y => y.Node)); - + // If there are multiple paths to one DedupId (duplicate files) // take the last one var fileDedupIds = new Dictionary(); foreach (var file in fileNodes.Where(x => x.Success)) { - // ChunkHelper uses 64k block default size + // ChunkHelper uses 64k block default size var dedupId = file.Node.GetDedupIdentifier(HashType.Dedup64K); fileDedupIds[dedupId] = file.Path; } @@ -127,7 +127,7 @@ private static async Task> GenerateHashes(IReadOnlyList nodes) { // Create chunks and identifier var chunk = await ChunkerHelper.CreateFromFileAsync(FileSystem.Instance, itemPath, cancellationToken, false); - var rootNode = new DedupNode(new []{ chunk }); + var rootNode = new DedupNode(new[] { chunk }); // ChunkHelper uses 64k block default size var dedupId = rootNode.GetDedupIdentifier(HashType.Dedup64K); @@ -196,7 +196,7 @@ await clientTelemetry.MeasureActionAsync( actionAsync: async () => await AsyncHttpRetryHelper.InvokeAsync( async () => { - await uploadSession.UploadAsync(rootNode, new Dictionary(){ [dedupId] = itemPath }, cancellationToken); + await uploadSession.UploadAsync(rootNode, new Dictionary() { [dedupId] = itemPath }, cancellationToken); return uploadSession.UploadStatistics; }, maxRetries: 3, diff --git a/src/Microsoft.VisualStudio.Services.Agent/Blob/BuildArtifactActionRecord.cs b/src/Microsoft.VisualStudio.Services.Agent/Blob/BuildArtifactActionRecord.cs index 020694c947..453e189b70 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/Blob/BuildArtifactActionRecord.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/Blob/BuildArtifactActionRecord.cs @@ -13,11 +13,11 @@ namespace Microsoft.VisualStudio.Services.Agent.Blob public class BuildArtifactActionRecord : PipelineTelemetryRecord { public BuildArtifactActionRecord( - TelemetryInformationLevel level, - Uri baseAddress, - string eventNamePrefix, - string eventNameSuffix, - IKnobValueContext context, + TelemetryInformationLevel level, + Uri baseAddress, + string eventNamePrefix, + string eventNameSuffix, + IKnobValueContext context, uint attemptNumber = 1) : base(level, baseAddress, eventNamePrefix, eventNameSuffix, context, attemptNumber) { diff --git a/src/Microsoft.VisualStudio.Services.Agent/Blob/CustomerIntelligenceTelemetrySender.cs b/src/Microsoft.VisualStudio.Services.Agent/Blob/CustomerIntelligenceTelemetrySender.cs index 8091841608..9097372e08 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/Blob/CustomerIntelligenceTelemetrySender.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/Blob/CustomerIntelligenceTelemetrySender.cs @@ -104,7 +104,7 @@ public async Task CommitTelemetryUpload(Guid planId, Guid jobId) Feature = "BuildArtifacts", Properties = ciData }; - await _ciClient.PublishEventsAsync(new [] { ciEvent }); + await _ciClient.PublishEventsAsync(new[] { ciEvent }); } public Dictionary GetArtifactDownloadTelemetry(Guid planId, Guid jobId) diff --git a/src/Microsoft.VisualStudio.Services.Agent/Blob/DedupManifestArtifactClientFactory.cs b/src/Microsoft.VisualStudio.Services.Agent/Blob/DedupManifestArtifactClientFactory.cs index 9f2adf92b3..2f37bf9be7 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/Blob/DedupManifestArtifactClientFactory.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/Blob/DedupManifestArtifactClientFactory.cs @@ -122,7 +122,7 @@ private DedupManifestArtifactClientFactory() continueOnCapturedContext: false); var telemetry = new BlobStoreClientTelemetry(tracer, dedupStoreHttpClient.BaseAddress); - var client = new DedupStoreClientWithDataport(dedupStoreHttpClient, maxParallelism); + var client = new DedupStoreClientWithDataport(dedupStoreHttpClient, maxParallelism); return (new DedupManifestArtifactClient(telemetry, client, tracer), telemetry); } @@ -150,7 +150,7 @@ private DedupManifestArtifactClientFactory() cancellationToken); // this is actually a hidden network call to the location service: - return Task.FromResult(factory.CreateVssHttpClient(connection.GetClient().BaseAddress)); + return Task.FromResult(factory.CreateVssHttpClient(connection.GetClient().BaseAddress)); }, maxRetries: maxRetries, tracer: tracer, @@ -160,14 +160,14 @@ private DedupManifestArtifactClientFactory() continueOnCapturedContext: false); var telemetry = new BlobStoreClientTelemetryTfs(tracer, dedupStoreHttpClient.BaseAddress, connection); - var client = new DedupStoreClient(dedupStoreHttpClient, maxParallelism); + var client = new DedupStoreClient(dedupStoreHttpClient, maxParallelism); return (client, telemetry); } public int GetDedupStoreClientMaxParallelism(AgentTaskPluginExecutionContext context) { ConfigureEnvironmentVariables(context); - + int parallelism = DefaultDedupStoreClientMaxParallelism; if (context.Variables.TryGetValue("AZURE_PIPELINES_DEDUP_PARALLELISM", out VariableValue v)) @@ -190,11 +190,11 @@ public int GetDedupStoreClientMaxParallelism(AgentTaskPluginExecutionContext con return parallelism; } - private static readonly string[] EnvironmentVariables = new [] { "VSO_DEDUP_REDIRECT_TIMEOUT_IN_SEC" }; + private static readonly string[] EnvironmentVariables = new[] { "VSO_DEDUP_REDIRECT_TIMEOUT_IN_SEC" }; private static void ConfigureEnvironmentVariables(AgentTaskPluginExecutionContext context) { - foreach(string varName in EnvironmentVariables) + foreach (string varName in EnvironmentVariables) { if (context.Variables.TryGetValue(varName, out VariableValue v)) { diff --git a/src/Microsoft.VisualStudio.Services.Agent/Blob/PipelineTelemetryRecord.cs b/src/Microsoft.VisualStudio.Services.Agent/Blob/PipelineTelemetryRecord.cs index 92048dbcfd..e97e2dbbac 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/Blob/PipelineTelemetryRecord.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/Blob/PipelineTelemetryRecord.cs @@ -21,11 +21,11 @@ public abstract class PipelineTelemetryRecord : BlobStoreTelemetryRecord, IDedup public DedupDownloadStatistics DownloadStatistics { get; private set; } public PipelineTelemetryRecord( - TelemetryInformationLevel level, - Uri baseAddress, - string eventNamePrefix, - string eventNameSuffix, - IKnobValueContext context, + TelemetryInformationLevel level, + Uri baseAddress, + string eventNamePrefix, + string eventNameSuffix, + IKnobValueContext context, uint attemptNumber = 1) : base(level, baseAddress, eventNamePrefix, eventNameSuffix, attemptNumber) { @@ -35,10 +35,10 @@ public PipelineTelemetryRecord( } public PipelineTelemetryRecord( - TelemetryInformationLevel level, - Uri baseAddress, - string eventNamePrefix, - string eventNameSuffix, + TelemetryInformationLevel level, + Uri baseAddress, + string eventNamePrefix, + string eventNameSuffix, Guid planId, Guid jobId, Guid taskInstanceId, diff --git a/src/Microsoft.VisualStudio.Services.Agent/Blob/TimelineRecordAttachmentTelemetryRecord.cs b/src/Microsoft.VisualStudio.Services.Agent/Blob/TimelineRecordAttachmentTelemetryRecord.cs index 71a11bd395..758ee80052 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/Blob/TimelineRecordAttachmentTelemetryRecord.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/Blob/TimelineRecordAttachmentTelemetryRecord.cs @@ -15,9 +15,9 @@ namespace Microsoft.VisualStudio.Services.Agent.Blob public class TimelineRecordAttachmentTelemetryRecord : PipelineTelemetryRecord { public TimelineRecordAttachmentTelemetryRecord( - TelemetryInformationLevel level, - Uri baseAddress, - string eventNamePrefix, + TelemetryInformationLevel level, + Uri baseAddress, + string eventNamePrefix, string eventNameSuffix, Guid planId, Guid jobId, diff --git a/src/Microsoft.VisualStudio.Services.Agent/Capabilities/AgentCapabilitiesProvider.cs b/src/Microsoft.VisualStudio.Services.Agent/Capabilities/AgentCapabilitiesProvider.cs index 4acf5c794f..c4dfc61368 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/Capabilities/AgentCapabilitiesProvider.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/Capabilities/AgentCapabilitiesProvider.cs @@ -28,7 +28,7 @@ public Task> GetCapabilitiesAsync(AgentSettings settings, Cance { Add(capabilities, "Agent.OSVersion", GetOSVersionString()); Add(capabilities, "Cmd", Environment.GetEnvironmentVariable("comspec")); - } + } else if (PlatformUtil.RunningOnMacOS) { Add(capabilities, "Agent.OSVersion", GetDarwinVersionString()); @@ -91,13 +91,13 @@ private string GetOSVersionString() string build = GetHklmValue(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentBuildNumber") as string; return StringUtil.Format("{0}.{1}", majorMinorString, build); } - - // 10.0 covers all versions prior to Darwin 5 - // Mac OS X 10.1 mapped to Darwin 5.x, and the mapping continues that way - // So just subtract 4 from the Darwin version. - // https://en.wikipedia.org/wiki/Darwin_%28operating_system%29 - // with Big Sur Apple made the jump from 10.* to 11.* that means that - // the version reported from that point is 20.1.0.0 for 11.0.1 + + // 10.0 covers all versions prior to Darwin 5 + // Mac OS X 10.1 mapped to Darwin 5.x, and the mapping continues that way + // So just subtract 4 from the Darwin version. + // https://en.wikipedia.org/wiki/Darwin_%28operating_system%29 + // with Big Sur Apple made the jump from 10.* to 11.* that means that + // the version reported from that point is 20.1.0.0 for 11.0.1 private static string GetDarwinVersionString() { // from .net 5 onwards the runtime returns the product version instead of the darwin kernel version diff --git a/src/Microsoft.VisualStudio.Services.Agent/Capabilities/UserCapabilitiesProvider.cs b/src/Microsoft.VisualStudio.Services.Agent/Capabilities/UserCapabilitiesProvider.cs index d81035241c..388ced5c80 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/Capabilities/UserCapabilitiesProvider.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/Capabilities/UserCapabilitiesProvider.cs @@ -7,7 +7,7 @@ namespace Microsoft.VisualStudio.Services.Agent.Capabilities { - + public sealed class UserCapabilitiesProvider : AgentService, ICapabilitiesProvider { public Type ExtensionType => typeof(ICapabilitiesProvider); @@ -21,7 +21,8 @@ public Task> GetCapabilitiesAsync(AgentSettings settings, Cance // Location of the .capabilities file var capbabilitiesFile = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), ".capabilities"); - if (File.Exists(capbabilitiesFile)) { + if (File.Exists(capbabilitiesFile)) + { // Load the file content, and parse it like the .env file. Trace.Info($"Reading capabilities from '{capbabilitiesFile}'"); var fileContents = File.ReadAllLines(capbabilitiesFile); @@ -31,11 +32,11 @@ public Task> GetCapabilitiesAsync(AgentSettings settings, Cance { string name = line.Substring(0, line.IndexOf('=')); string value = line.Substring(line.IndexOf('=') + 1); - + Trace.Info($"Adding '{name}': '{value}'"); capabilities.Add(new Capability(name, value)); } - } + } } return Task.FromResult(capabilities); diff --git a/src/Microsoft.VisualStudio.Services.Agent/Command.cs b/src/Microsoft.VisualStudio.Services.Agent/Command.cs index fe67125562..1b5de7dd48 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/Command.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/Command.cs @@ -59,7 +59,7 @@ public static bool TryParse(string message, bool unescapePercents, out Command c // Get the command name (area.event). int spaceIndex = cmdInfo.IndexOf(' '); - string commandName = + string commandName = spaceIndex < 0 ? cmdInfo : cmdInfo.Substring(0, spaceIndex); diff --git a/src/Microsoft.VisualStudio.Services.Agent/DeploymentGroupServer.cs b/src/Microsoft.VisualStudio.Services.Agent/DeploymentGroupServer.cs index 7921a0756c..95f42fb276 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/DeploymentGroupServer.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/DeploymentGroupServer.cs @@ -102,13 +102,13 @@ public Task DeleteDeploymentTargetAsync(Guid projectId, int deploymentGroupId, i public Task> GetDeploymentTargetsAsync(string projectName, int deploymentGroupId, string machineName) { CheckConnection(); - return _taskAgentClient.GetDeploymentTargetsAsync(projectName, deploymentGroupId, tags : null, name : machineName); + return _taskAgentClient.GetDeploymentTargetsAsync(projectName, deploymentGroupId, tags: null, name: machineName); } public Task> GetDeploymentTargetsAsync(Guid projectGuid, int deploymentGroupId, string machineName) { CheckConnection(); - return _taskAgentClient.GetDeploymentTargetsAsync(projectGuid, deploymentGroupId, tags : null, name :machineName); + return _taskAgentClient.GetDeploymentTargetsAsync(projectGuid, deploymentGroupId, tags: null, name: machineName); } //----------------------------------------------------------------- diff --git a/src/Microsoft.VisualStudio.Services.Agent/HostContext.cs b/src/Microsoft.VisualStudio.Services.Agent/HostContext.cs index d1c74dbb87..fe34ab2b56 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/HostContext.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/HostContext.cs @@ -91,7 +91,8 @@ public HostContext(HostType hostType, string logFile = null) { _secretMasker = new LoggedSecretMasker(new SecretMasker()); // Validate args. - if (hostType == HostType.Undefined) { + if (hostType == HostType.Undefined) + { throw new ArgumentException(message: $"HostType cannot be {HostType.Undefined}"); } _hostType = hostType; @@ -285,10 +286,10 @@ private string GetDiagOrDefault(string diagFolder) { return diagFolder; } - + return Path.Combine( new DirectoryInfo(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)).Parent.FullName, - Constants.Path.DiagDirectory); + Constants.Path.DiagDirectory); } public string GetConfigFile(WellKnownConfigFile configFile) diff --git a/src/Microsoft.VisualStudio.Services.Agent/HostTraceListener.cs b/src/Microsoft.VisualStudio.Services.Agent/HostTraceListener.cs index 55fccd7790..3e2a9b58b3 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/HostTraceListener.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/HostTraceListener.cs @@ -12,7 +12,7 @@ namespace Microsoft.VisualStudio.Services.Agent { public sealed class HostTraceListener : TextWriterTraceListener { - public bool DisableConsoleReporting { get; set; } + public bool DisableConsoleReporting { get; set; } private const string _logFileNamingPattern = "{0}_{1:yyyyMMdd-HHmmss}-utc.log"; private string _logFileDirectory; private string _logFilePrefix; diff --git a/src/Microsoft.VisualStudio.Services.Agent/JobNotification.cs b/src/Microsoft.VisualStudio.Services.Agent/JobNotification.cs index 0856e477a2..361a122d5a 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/JobNotification.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/JobNotification.cs @@ -140,7 +140,7 @@ public void StartClient(string socketAddress, string monitorSocketAddress) } catch (FormatException e) { - Trace.Error("Invalid socket ip address {0}. Job Notification will be disabled",splitAddress[0]); + Trace.Error("Invalid socket ip address {0}. Job Notification will be disabled", splitAddress[0]); Trace.Error(e); return; } @@ -169,7 +169,7 @@ public void StartClient(string socketAddress, string monitorSocketAddress) private void StartMonitor(Guid jobId, string accessToken, Uri serverUri, Guid planId, string identifier, string definitionId, string planType) { - if(String.IsNullOrEmpty(accessToken)) + if (String.IsNullOrEmpty(accessToken)) { Trace.Info("No access token could be retrieved to start the monitor."); return; diff --git a/src/Microsoft.VisualStudio.Services.Agent/JobServer.cs b/src/Microsoft.VisualStudio.Services.Agent/JobServer.cs index 6cfa865564..dddb220ae6 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/JobServer.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/JobServer.cs @@ -99,7 +99,7 @@ public Task AppendLogContentAsync(Guid scopeIdentifier, string hubName, return _taskClient.AppendLogContentAsync(scopeIdentifier, hubName, planId, logId, uploadStream, cancellationToken: cancellationToken); } - public Task AppendTimelineRecordFeedAsync(Guid scopeIdentifier, string hubName, Guid planId, Guid timelineId, Guid timelineRecordId, Guid stepId, IList lines, long startLine, CancellationToken cancellationToken) + public Task AppendTimelineRecordFeedAsync(Guid scopeIdentifier, string hubName, Guid planId, Guid timelineId, Guid timelineRecordId, Guid stepId, IList lines, long startLine, CancellationToken cancellationToken) { CheckConnection(); return _taskClient.AppendTimelineRecordFeedAsync(scopeIdentifier, hubName, planId, timelineId, timelineRecordId, stepId, lines, startLine, cancellationToken: cancellationToken); @@ -183,7 +183,8 @@ public async Task UploadLogToBlobStore(Stream blob, st return results; } - private IBlobStoreHttpClient CreateArtifactsClient(VssConnection connection, CancellationToken cancellationToken){ + private IBlobStoreHttpClient CreateArtifactsClient(VssConnection connection, CancellationToken cancellationToken) + { var tracer = new CallbackAppTraceSource(str => Trace.Info(str), System.Diagnostics.SourceLevels.Information); ArtifactHttpClientFactory factory = new ArtifactHttpClientFactory( diff --git a/src/Microsoft.VisualStudio.Services.Agent/JobServerQueue.cs b/src/Microsoft.VisualStudio.Services.Agent/JobServerQueue.cs index 9750c97902..1571f152b1 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/JobServerQueue.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/JobServerQueue.cs @@ -77,7 +77,7 @@ public sealed class JobServerQueue : AgentService, IJobServerQueue // In this way, customer still can get instance live console output on job start, // at the same time we can cut the load to server after the build run for more than 60s private int _webConsoleLineAggressiveDequeueCount = 0; - private int _webConsoleLineUpdateRate = (int) _delayForWebConsoleLineDequeueDefault.TotalMilliseconds; + private int _webConsoleLineUpdateRate = (int)_delayForWebConsoleLineDequeueDefault.TotalMilliseconds; private const int _webConsoleLineAggressiveDequeueLimit = 2 * 15; private bool _webConsoleLineAggressiveDequeue = true; private TaskCompletionSource _webConsoleLinesDequeueNow = new TaskCompletionSource(); @@ -148,7 +148,7 @@ public void Start(Pipelines.AgentJobRequestMessage jobRequest) { if (!Int32.TryParse(postLinesSpeed.Value, out _webConsoleLineUpdateRate)) { - _webConsoleLineUpdateRate = (int) _delayForWebConsoleLineDequeueDefault.TotalMilliseconds; + _webConsoleLineUpdateRate = (int)_delayForWebConsoleLineDequeueDefault.TotalMilliseconds; } } @@ -682,9 +682,9 @@ private async Task UploadFile(UploadFileInfo file) { try { - var (dedupId, length) = await _jobServer.UploadAttachmentToBlobStore(_debugMode, file.Path, _planId, _jobTimelineRecordId, default(CancellationToken)); + var (dedupId, length) = await _jobServer.UploadAttachmentToBlobStore(_debugMode, file.Path, _planId, _jobTimelineRecordId, default(CancellationToken)); // Notify TFS - await _jobServer.AssosciateAttachmentAsync(_scopeIdentifier, _hubName, _planId, file.TimelineId, file.TimelineRecordId, file.Type, file.Name, dedupId, (long) length, default(CancellationToken)); + await _jobServer.AssosciateAttachmentAsync(_scopeIdentifier, _hubName, _planId, file.TimelineId, file.TimelineRecordId, file.Type, file.Name, dedupId, (long)length, default(CancellationToken)); } catch { diff --git a/src/Microsoft.VisualStudio.Services.Agent/ProcessExtensions.cs b/src/Microsoft.VisualStudio.Services.Agent/ProcessExtensions.cs index 892a2f8bef..a9fc9cfab6 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/ProcessExtensions.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/ProcessExtensions.cs @@ -11,7 +11,7 @@ namespace Microsoft.VisualStudio.Services.Agent { - public static class ProcessExtensions + public static class ProcessExtensions { public static string GetEnvironmentVariable(this Process process, IHostContext hostContext, string variable) { diff --git a/src/Microsoft.VisualStudio.Services.Agent/ProcessInvoker.cs b/src/Microsoft.VisualStudio.Services.Agent/ProcessInvoker.cs index 55c2d45235..0b2da006d4 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/ProcessInvoker.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/ProcessInvoker.cs @@ -115,7 +115,7 @@ Task ExecuteAsync( public sealed class ProcessInvokerWrapper : AgentService, IProcessInvoker { private ProcessInvoker _invoker; - public bool DisableWorkerCommands {get; set; } + public bool DisableWorkerCommands { get; set; } public override void Initialize(IHostContext hostContext) { diff --git a/src/Microsoft.VisualStudio.Services.Agent/Util/EnumUtil.cs b/src/Microsoft.VisualStudio.Services.Agent/Util/EnumUtil.cs index 52011f2218..f5ef9f7b6a 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/Util/EnumUtil.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/Util/EnumUtil.cs @@ -7,7 +7,7 @@ namespace Microsoft.VisualStudio.Services.Agent.Util public static class EnumUtil { - public static T? TryParse(string value) where T: struct + public static T? TryParse(string value) where T : struct { T val; if (Enum.TryParse(value ?? string.Empty, ignoreCase: true, result: out val)) diff --git a/src/Microsoft.VisualStudio.Services.Agent/Util/ServerUtil.cs b/src/Microsoft.VisualStudio.Services.Agent/Util/ServerUtil.cs index 78c63175ff..f1510b0f78 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/Util/ServerUtil.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/Util/ServerUtil.cs @@ -10,20 +10,20 @@ namespace Microsoft.VisualStudio.Services.Agent.Util { public class DeploymentTypeNotDeterminedException : Exception { - public DeploymentTypeNotDeterminedException() {} + public DeploymentTypeNotDeterminedException() { } - public DeploymentTypeNotDeterminedException(string message) : base(message) {} + public DeploymentTypeNotDeterminedException(string message) : base(message) { } - public DeploymentTypeNotDeterminedException(string message, Exception inner) : base(message, inner) {} + public DeploymentTypeNotDeterminedException(string message, Exception inner) : base(message, inner) { } } public class DeploymentTypeNotRecognizedException : Exception { - public DeploymentTypeNotRecognizedException() {} + public DeploymentTypeNotRecognizedException() { } - public DeploymentTypeNotRecognizedException(string message) : base(message) {} + public DeploymentTypeNotRecognizedException(string message) : base(message) { } - public DeploymentTypeNotRecognizedException(string message, Exception inner) : base(message, inner) {} + public DeploymentTypeNotRecognizedException(string message, Exception inner) : base(message, inner) { } } public class ServerUtil diff --git a/src/Microsoft.VisualStudio.Services.Agent/Util/VarUtil.cs b/src/Microsoft.VisualStudio.Services.Agent/Util/VarUtil.cs index 0192a32b5c..2206a681aa 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/Util/VarUtil.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/Util/VarUtil.cs @@ -12,7 +12,7 @@ namespace Microsoft.VisualStudio.Services.Agent.Util { - public static class VarUtil + public static class VarUtil { public static StringComparer EnvironmentVariableKeyComparer { diff --git a/src/Microsoft.VisualStudio.Services.Agent/VstsAgentWebProxy.cs b/src/Microsoft.VisualStudio.Services.Agent/VstsAgentWebProxy.cs index 83b777a6b4..a012f483c1 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/VstsAgentWebProxy.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/VstsAgentWebProxy.cs @@ -144,7 +144,7 @@ public void LoadProxyBypassList() var proxyBypassEnv = AgentKnobs.NoProxy.GetValue(HostContext).AsString(); - foreach (string bypass in proxyBypassEnv.Split(new [] {',', ';'}).Where(value => !string.IsNullOrWhiteSpace(value)).Select(value => value.Trim())) + foreach (string bypass in proxyBypassEnv.Split(new[] { ',', ';' }).Where(value => !string.IsNullOrWhiteSpace(value)).Select(value => value.Trim())) { var saveRegexString = ProcessProxyByPassFromEnv(bypass); diff --git a/src/Microsoft.VisualStudio.Services.Agent/WindowsEnvVarHelper.cs b/src/Microsoft.VisualStudio.Services.Agent/WindowsEnvVarHelper.cs index 545f6c47da..4d1eecaafd 100644 --- a/src/Microsoft.VisualStudio.Services.Agent/WindowsEnvVarHelper.cs +++ b/src/Microsoft.VisualStudio.Services.Agent/WindowsEnvVarHelper.cs @@ -101,7 +101,7 @@ public static string GetEnvironmentVariable(Process process, IHostContext hostCo } // Reference: https://github.com/gapotchenko/Gapotchenko.FX/blob/master/Source/Gapotchenko.FX.Diagnostics.Process/ProcessEnvironment.cs - static Dictionary _EnvToDictionary(byte[] env) + static Dictionary _EnvToDictionary(byte[] env) { var result = new Dictionary(StringComparer.OrdinalIgnoreCase); diff --git a/src/Test/L0/Container/ContainerInfoL0.cs b/src/Test/L0/Container/ContainerInfoL0.cs index f4cdd25cb2..5fcff50a80 100644 --- a/src/Test/L0/Container/ContainerInfoL0.cs +++ b/src/Test/L0/Container/ContainerInfoL0.cs @@ -18,7 +18,7 @@ private class MountVolumeTest private MountVolume Expected; private string Title; - public MountVolumeTest(string input, MountVolume expected, string title="") + public MountVolumeTest(string input, MountVolume expected, string title = "") { this.Input = input; this.Expected = expected; @@ -81,10 +81,10 @@ public void MountVolumeConstructorParsesStringInput() public void DefaultContainerInfoMappings() { var dockerContainer = new Pipelines.ContainerResource() - { - Alias = "vsts_container_preview", - Image = "foo" - }; + { + Alias = "vsts_container_preview", + Image = "foo" + }; using (TestHostContext hc = CreateTestContext()) { ContainerInfo info = hc.CreateContainerInfo(dockerContainer, isJobContainer: false); @@ -101,15 +101,15 @@ public void DefaultContainerInfoMappings() public void TranslateContainerPathForImageOSTestsWindowsToLinux() { var dockerContainer = new Pipelines.ContainerResource() - { - Alias = "vsts_container_preview", - Image = "foo" - }; + { + Alias = "vsts_container_preview", + Image = "foo" + }; using (TestHostContext hc = CreateTestContext()) { ContainerInfo info = hc.CreateContainerInfo(dockerContainer, isJobContainer: false); info.ImageOS = PlatformUtil.OS.Linux; - + foreach (var test in new string[][] { new string [] { "C:\\path\\for\\linux", "/path/for/linux" }, new string [] { "c:\\path\\for\\linux", "/path/for/linux" }, @@ -118,7 +118,7 @@ public void TranslateContainerPathForImageOSTestsWindowsToLinux() new string [] { "/path/for/linux", "/path/for/linux" }, new string [] { "", "" }, new string [] { null, null }, - }) + }) { var winPath = test[0]; var linPath = test[1]; @@ -134,23 +134,23 @@ public void TranslateContainerPathForImageOSTestsWindowsToLinux() public void TranslateContainerPathForImageOSTestsUnixLikeToLinux() { var dockerContainer = new Pipelines.ContainerResource() - { - Alias = "vsts_container_preview", - Image = "foo" - }; + { + Alias = "vsts_container_preview", + Image = "foo" + }; using (TestHostContext hc = CreateTestContext()) { ContainerInfo info = hc.CreateContainerInfo(dockerContainer, isJobContainer: false); info.ImageOS = PlatformUtil.OS.Linux; - - foreach (var os in new PlatformUtil.OS[] { PlatformUtil.OS.Linux, PlatformUtil.OS.OSX}) + + foreach (var os in new PlatformUtil.OS[] { PlatformUtil.OS.Linux, PlatformUtil.OS.OSX }) { foreach (var test in new string[][] { new string [] { "/path/for/linux", "/path/for/linux" }, new string [] { "/", "/" }, new string [] { "", "" }, new string [] { null, null }, - }) + }) { var origPath = test[0]; var linPath = test[1]; diff --git a/src/Test/L0/ExtensionManagerL0.cs b/src/Test/L0/ExtensionManagerL0.cs index cceb07801e..c3cf575e07 100644 --- a/src/Test/L0/ExtensionManagerL0.cs +++ b/src/Test/L0/ExtensionManagerL0.cs @@ -63,7 +63,7 @@ public void LoadsTypes() AssertContains( manager, concreteType: typeof(Microsoft.VisualStudio.Services.Agent.Worker.LegacyTestResults.JUnitResultReader)); - AssertContains ( + AssertContains( manager, concreteType: typeof(Microsoft.VisualStudio.Services.Agent.Worker.Build.WorkspaceMaintenanceProvider)); AssertContains( diff --git a/src/Test/L0/KnobL0.cs b/src/Test/L0/KnobL0.cs index f6e080b2a1..06d1520a67 100644 --- a/src/Test/L0/KnobL0.cs +++ b/src/Test/L0/KnobL0.cs @@ -41,16 +41,16 @@ public void BasicKnobTests() var environment = new LocalEnvironment(); var executionContext = new Mock(); - executionContext - .Setup(x => x.GetScopedEnvironment()) - .Returns(environment); + executionContext + .Setup(x => x.GetScopedEnvironment()) + .Returns(environment); { var knobValue = TestKnobs.A.GetValue(executionContext.Object); Assert.True(knobValue.Source.GetType() == typeof(BuiltInDefaultKnobSource)); } - environment.SetEnvironmentVariable("A","true"); + environment.SetEnvironmentVariable("A", "true"); { var knobValue = TestKnobs.A.GetValue(executionContext.Object); @@ -59,7 +59,7 @@ public void BasicKnobTests() Assert.True(string.Equals(knobValue.AsString(), "true", StringComparison.OrdinalIgnoreCase)); } - environment.SetEnvironmentVariable("A","false"); + environment.SetEnvironmentVariable("A", "false"); { var knobValue = TestKnobs.A.GetValue(executionContext.Object); diff --git a/src/Test/L0/Listener/AgentL0.cs b/src/Test/L0/Listener/AgentL0.cs index 5d00b42e98..f63edb52e9 100644 --- a/src/Test/L0/Listener/AgentL0.cs +++ b/src/Test/L0/Listener/AgentL0.cs @@ -581,7 +581,7 @@ public async void TestRunOnceHandleUpdateMessage() [InlineData("--version")] [InlineData("--commit")] [InlineData("--bad-argument", Constants.Agent.ReturnCode.TerminatedError)] - public async void TestInfoArgumentsCLI(string arg, int expected=Constants.Agent.ReturnCode.Success) + public async void TestInfoArgumentsCLI(string arg, int expected = Constants.Agent.ReturnCode.Success) { using (var hc = new TestHostContext(this)) { @@ -651,7 +651,7 @@ public async void TestExitsIfUnconfigured() [InlineData("configure", true)] //TODO: this passes. If already configured, probably should error out asked to configure again [InlineData("remove", false)] //TODO: this passes. If already not configured, probably should error out [InlineData("remove", true)] - public async void TestConfigureCLI(string arg, bool IsConfigured, int expected=Constants.Agent.ReturnCode.Success) + public async void TestConfigureCLI(string arg, bool IsConfigured, int expected = Constants.Agent.ReturnCode.Success) { using (var hc = new TestHostContext(this)) { @@ -733,9 +733,9 @@ public async void TestMetadataUpdate() var metadataMessage = new TaskAgentMessage() { Body = JsonUtility.ToString(new JobMetadataMessage() - { - PostLinesFrequencyMillis = 500 - }), + { + PostLinesFrequencyMillis = 500 + }), MessageId = 4235, MessageType = JobEventTypes.JobMetadataUpdate }; diff --git a/src/Test/L0/Listener/CommandSettingsL0.cs b/src/Test/L0/Listener/CommandSettingsL0.cs index b7c43463ce..70219c9814 100644 --- a/src/Test/L0/Listener/CommandSettingsL0.cs +++ b/src/Test/L0/Listener/CommandSettingsL0.cs @@ -349,7 +349,7 @@ public void GetsFlagUnattended() using (TestHostContext hc = CreateTestContext()) { // Arrange. - var command = new CommandSettings(hc, args: new string[] { "configure","--unattended" }); + var command = new CommandSettings(hc, args: new string[] { "configure", "--unattended" }); // Act. bool actual = command.Unattended(); @@ -511,7 +511,7 @@ public void PromptsForAuth() using (TestHostContext hc = CreateTestContext()) { // Arrange. - var command = new CommandSettings(hc, args: new string[] { "configure"}); + var command = new CommandSettings(hc, args: new string[] { "configure" }); _promptManager .Setup(x => x.ReadValue( Constants.Agent.CommandLine.Args.Auth, // argName @@ -1069,7 +1069,7 @@ public void DeploymentGroupNameBackCompat() // Validate if --machinegroupname parameter is working Assert.Equal("Test-MachineGroupName", actual); - + // Validate Read Value should not get invoked. _promptManager.Verify(x => x.ReadValue(It.IsAny(), It.IsAny(), @@ -1134,11 +1134,11 @@ public void DeploymentGroupTagsBackCompat() // Validate if --machinegrouptags parameter is working fine Assert.Equal("Test-MachineGrouptag1,Test-MachineGrouptag2", actual); - + // Validate Read Value should not get invoked. _promptManager.Verify(x => x.ReadValue(It.IsAny(), It.IsAny(), - It.IsAny(),It.IsAny(), It.IsAny>(),It.IsAny()), Times.Never); + It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny()), Times.Never); } } diff --git a/src/Test/L0/Listener/Configuration/AgentCapabilitiesProviderTestL0.cs b/src/Test/L0/Listener/Configuration/AgentCapabilitiesProviderTestL0.cs index 39839833ca..fb8929b8cd 100644 --- a/src/Test/L0/Listener/Configuration/AgentCapabilitiesProviderTestL0.cs +++ b/src/Test/L0/Listener/Configuration/AgentCapabilitiesProviderTestL0.cs @@ -25,7 +25,7 @@ public async void TestGetCapabilities() { Mock configurationManager = new Mock(); hc.SetSingleton(configurationManager.Object); - + // Arrange var provider = new AgentCapabilitiesProvider(); provider.Initialize(hc); diff --git a/src/Test/L0/Listener/Configuration/ConfigurationManagerL0.cs b/src/Test/L0/Listener/Configuration/ConfigurationManagerL0.cs index e85ffe579c..372214d12d 100644 --- a/src/Test/L0/Listener/Configuration/ConfigurationManagerL0.cs +++ b/src/Test/L0/Listener/Configuration/ConfigurationManagerL0.cs @@ -560,11 +560,11 @@ public async Task CanEnsureEnvironmentVMResourceConfigureVSTSScenario() Assert.True(s.EnvironmentVMResourceId.Equals(_expectedEnvironmentVMResourceId)); // Validate mock calls - _environmentsServer.Verify( x => x.ConnectAsync(It.IsAny()), Times.Once); - _environmentsServer.Verify(x => x.AddEnvironmentVMAsync(It.IsAny(), It.Is(e => e == 54 ), It.Is( v => v.Agent.Name == "environmentVMResourceName")), Times.Once); - _environmentsServer.Verify(x => x.GetEnvironmentVMsAsync(It.IsAny(), It.Is(e => e == 54), It.Is( v => v == "environmentVMResourceName")), Times.Once); - _environmentsServer.Verify(x => x.GetEnvironmentsAsync(It.IsAny(), It.Is( e => e == "env1")), Times.Once); - _environmentsServer.Verify(x => x.GetEnvironmentPoolAsync(It.Is( p => p == projectId ), It.Is( e => e == 54)), Times.Once); + _environmentsServer.Verify(x => x.ConnectAsync(It.IsAny()), Times.Once); + _environmentsServer.Verify(x => x.AddEnvironmentVMAsync(It.IsAny(), It.Is(e => e == 54), It.Is(v => v.Agent.Name == "environmentVMResourceName")), Times.Once); + _environmentsServer.Verify(x => x.GetEnvironmentVMsAsync(It.IsAny(), It.Is(e => e == 54), It.Is(v => v == "environmentVMResourceName")), Times.Once); + _environmentsServer.Verify(x => x.GetEnvironmentsAsync(It.IsAny(), It.Is(e => e == "env1")), Times.Once); + _environmentsServer.Verify(x => x.GetEnvironmentPoolAsync(It.Is(p => p == projectId), It.Is(e => e == 54)), Times.Once); } } @@ -602,10 +602,10 @@ private List GetDeploymentGroups(int dgId, int poolId) private List GetEnvironments(string projectName, Guid projectId) { - var environmentJson = "{'id':54, 'project':{'id':'" + projectId + "','name':'" + projectName +"'},'name':'env1'}"; + var environmentJson = "{'id':54, 'project':{'id':'" + projectId + "','name':'" + projectName + "'},'name':'env1'}"; var env = JsonConvert.DeserializeObject(environmentJson); - return new List{ env }; + return new List { env }; } // Init the Agent Config Provider diff --git a/src/Test/L0/Listener/Configuration/NativeWindowsServiceHelperL0.cs b/src/Test/L0/Listener/Configuration/NativeWindowsServiceHelperL0.cs index faf492dfb4..2691ff2e27 100644 --- a/src/Test/L0/Listener/Configuration/NativeWindowsServiceHelperL0.cs +++ b/src/Test/L0/Listener/Configuration/NativeWindowsServiceHelperL0.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; diff --git a/src/Test/L0/Listener/Configuration/UserCapabilitiesProviderTestL0.cs b/src/Test/L0/Listener/Configuration/UserCapabilitiesProviderTestL0.cs index 01b7bf1249..4971d451db 100644 --- a/src/Test/L0/Listener/Configuration/UserCapabilitiesProviderTestL0.cs +++ b/src/Test/L0/Listener/Configuration/UserCapabilitiesProviderTestL0.cs @@ -22,11 +22,12 @@ public async void TestGetCapabilitiesWithDotCapabilities() using (var tokenSource = new CancellationTokenSource()) { var capFile = Path.Combine(hc.GetDirectory(WellKnownDirectory.Root), ".capabilities"); - try { + try + { File.WriteAllText(capFile, "User.Capability=My Value"); Mock configurationManager = new Mock(); hc.SetSingleton(configurationManager.Object); - + // Arrange var provider = new UserCapabilitiesProvider(); provider.Initialize(hc); @@ -41,7 +42,9 @@ public async void TestGetCapabilitiesWithDotCapabilities() Assert.NotNull(myCapability); Assert.Equal("My Value", myCapability.Value); Assert.Equal(1, capabilities.Count); - } finally { + } + finally + { File.Delete(capFile); } } @@ -56,7 +59,7 @@ public async void TestGetCapabilitiesWithoutDotCapabilities() { Mock configurationManager = new Mock(); hc.SetSingleton(configurationManager.Object); - + // Arrange var provider = new UserCapabilitiesProvider(); provider.Initialize(hc); diff --git a/src/Test/L0/PagingLoggerL0.cs b/src/Test/L0/PagingLoggerL0.cs index d7865a22ea..477ff2f385 100644 --- a/src/Test/L0/PagingLoggerL0.cs +++ b/src/Test/L0/PagingLoggerL0.cs @@ -46,7 +46,7 @@ public void WriteAndShipLog() { //Arrange using (var hc = new TestHostContext(this)) - using ( var pagingLogger = new PagingLogger()) + using (var pagingLogger = new PagingLogger()) { hc.SetSingleton(_jobServerQueue.Object); pagingLogger.Initialize(hc); @@ -107,7 +107,7 @@ public void ShipEmptyLog() { //Arrange using (var hc = new TestHostContext(this)) - using ( var pagingLogger = new PagingLogger()) + using (var pagingLogger = new PagingLogger()) { hc.SetSingleton(_jobServerQueue.Object); pagingLogger.Initialize(hc); diff --git a/src/Test/L0/Plugin/FingerprintCreatorTests.cs b/src/Test/L0/Plugin/FingerprintCreatorTests.cs index 808b05d436..b2a091ded7 100644 --- a/src/Test/L0/Plugin/FingerprintCreatorTests.cs +++ b/src/Test/L0/Plugin/FingerprintCreatorTests.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -53,14 +53,14 @@ static FingerprintCreatorTests() [Trait("Category", "Plugin")] public void Fingerprint_ReservedFails() { - using(var hostContext = new TestHostContext(this)) + using (var hostContext = new TestHostContext(this)) { var context = new AgentTaskPluginExecutionContext(hostContext.GetTrace()); Assert.Throws( - () => FingerprintCreator.EvaluateKeyToFingerprint(context, directory, new [] {"*"}) + () => FingerprintCreator.EvaluateKeyToFingerprint(context, directory, new[] { "*" }) ); Assert.Throws( - () => FingerprintCreator.EvaluateKeyToFingerprint(context, directory, new [] {"**"}) + () => FingerprintCreator.EvaluateKeyToFingerprint(context, directory, new[] { "**" }) ); } } @@ -70,7 +70,7 @@ public void Fingerprint_ReservedFails() [Trait("Category", "Plugin")] public void Fingerprint_ExcludeExactMatches() { - using(var hostContext = new TestHostContext(this)) + using (var hostContext = new TestHostContext(this)) { var context = new AgentTaskPluginExecutionContext(hostContext.GetTrace()); var segments = new[] @@ -88,7 +88,7 @@ public void Fingerprint_ExcludeExactMatches() [Trait("Category", "Plugin")] public void Fingerprint_ExcludeExactMisses() { - using(var hostContext = new TestHostContext(this)) + using (var hostContext = new TestHostContext(this)) { var context = new AgentTaskPluginExecutionContext(hostContext.GetTrace()); var segments = new[] @@ -109,7 +109,7 @@ public void Fingerprint_ExcludeExactMisses() [Trait("Category", "Plugin")] public void Fingerprint_FileAbsolute() { - using(var hostContext = new TestHostContext(this)) + using (var hostContext = new TestHostContext(this)) { var context = new AgentTaskPluginExecutionContext(hostContext.GetTrace()); var segments = new[] @@ -137,7 +137,7 @@ public void Fingerprint_FileRelative() string relPath1 = Path.GetFileName(path1); string relPath2 = Path.GetFileName(path2); - using(var hostContext = new TestHostContext(this)) + using (var hostContext = new TestHostContext(this)) { var context = new AgentTaskPluginExecutionContext(hostContext.GetTrace()); context.SetVariable( @@ -167,7 +167,7 @@ public void Fingerprint_FileRelative() [Trait("Category", "Plugin")] public void Fingerprint_Str() { - using(var hostContext = new TestHostContext(this)) + using (var hostContext = new TestHostContext(this)) { var context = new AgentTaskPluginExecutionContext(hostContext.GetTrace()); var segments = new[] @@ -192,7 +192,7 @@ public void ParseMultilineKeyAsOld() "gems\n$(Agent.OS)\n$(Build.SourcesDirectory)/my.gemspec", string.Empty); Assert.True(isOldFormat); - Assert.Equal(new [] {"gems", "$(Agent.OS)", "$(Build.SourcesDirectory)/my.gemspec"}, keySegments); + Assert.Equal(new[] { "gems", "$(Agent.OS)", "$(Build.SourcesDirectory)/my.gemspec" }, keySegments); Assert.Equal(0, restoreKeys.Count()); } @@ -206,7 +206,7 @@ public void ParseSingleLineAsNew() "$(Agent.OS)", string.Empty); Assert.False(isOldFormat); - Assert.Equal(new [] {"$(Agent.OS)"}, keySegments); + Assert.Equal(new[] { "$(Agent.OS)" }, keySegments); Assert.Equal(0, restoreKeys.Count()); } @@ -220,8 +220,8 @@ public void ParseMultilineWithRestoreKeys() "$(Agent.OS) | Gemfile.lock | **/*.gemspec,!./junk/**", "$(Agent.OS) | Gemfile.lock\n$(Agent.OS)"); Assert.False(isOldFormat); - Assert.Equal(new [] {"$(Agent.OS)","Gemfile.lock","**/*.gemspec,!./junk/**"}, keySegments); - Assert.Equal(new [] {new []{ "$(Agent.OS)","Gemfile.lock"}, new[] {"$(Agent.OS)"}}, restoreKeys); + Assert.Equal(new[] { "$(Agent.OS)", "Gemfile.lock", "**/*.gemspec,!./junk/**" }, keySegments); + Assert.Equal(new[] { new[] { "$(Agent.OS)", "Gemfile.lock" }, new[] { "$(Agent.OS)" } }, restoreKeys); } } } \ No newline at end of file diff --git a/src/Test/L0/Plugin/FingerprintTests.cs b/src/Test/L0/Plugin/FingerprintTests.cs index 38a0a47ccf..27de416863 100644 --- a/src/Test/L0/Plugin/FingerprintTests.cs +++ b/src/Test/L0/Plugin/FingerprintTests.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; +using System; using Microsoft.VisualStudio.Services.PipelineCache.WebApi; using Xunit; diff --git a/src/Test/L0/Plugin/IsPathyTests.cs b/src/Test/L0/Plugin/IsPathyTests.cs index 5c60006afd..09d9fe6190 100644 --- a/src/Test/L0/Plugin/IsPathyTests.cs +++ b/src/Test/L0/Plugin/IsPathyTests.cs @@ -14,7 +14,7 @@ public class IsPathyTests [Trait("Category", "Plugin")] public void Fingerprint_IsPath() { - Action assertPath = (path, isPath) => + Action assertPath = (path, isPath) => Assert.True(isPath == FingerprintCreator.IsPathyKeySegment(path), $"IsPathy({path}) should have returned {isPath}."); assertPath(@"''", false); assertPath(@"Windows_NT", false); @@ -29,7 +29,7 @@ public void Fingerprint_IsPath() assertPath(@"./**,!./.git/**", true); assertPath(@"/src/foo", true); assertPath(@"src/foo", true); - + // ones we don't feel great about assertPath(@"We should go to the store/mall", true); assertPath(@"KEY_SALT=5-macos-10.13-stable-x86_64-apple-darwin", true); diff --git a/src/Test/L0/Plugin/LogPluginHostL0.cs b/src/Test/L0/Plugin/LogPluginHostL0.cs index 5010ea675f..d8e330b3d7 100644 --- a/src/Test/L0/Plugin/LogPluginHostL0.cs +++ b/src/Test/L0/Plugin/LogPluginHostL0.cs @@ -298,7 +298,7 @@ public async Task LogPluginHost_RunMultiplePlugins() logPluginHost.Finish(); await task; - foreach (var fragment in new string[] { "Test1: 0", "Test1: 999", "Test1: Done", "Test2: 0", "Test2: 999", "Test2: Done"}) + foreach (var fragment in new string[] { "Test1: 0", "Test1: 999", "Test1: Done", "Test2: 0", "Test2: 999", "Test2: Done" }) { Assert.True(trace.Outputs.Contains(fragment), $"Found '{fragment}' in: {trace.Outputs}"); } diff --git a/src/Test/L0/Plugin/MatchingTests.cs b/src/Test/L0/Plugin/MatchingTests.cs index c267d1eab8..2709c10ac9 100644 --- a/src/Test/L0/Plugin/MatchingTests.cs +++ b/src/Test/L0/Plugin/MatchingTests.cs @@ -15,7 +15,7 @@ namespace Microsoft.VisualStudio.Services.Agent.Tests.PipelineCache public class MatchingTests { private static readonly bool IsWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); - private static readonly string DefaultWorkingDirectory = + private static readonly string DefaultWorkingDirectory = IsWindows ? "C:\\working" : "/working"; @@ -27,13 +27,13 @@ private static string MakeOSPath(string path) return path; } - path = path.Replace('\\','/'); - + path = path.Replace('\\', '/'); + if (path.Length >= 2 && path[1] == ':') { return path.Substring(2); } - + return path; } @@ -43,7 +43,7 @@ private void RunTests( (string path, bool match)[] testCases, [CallerMemberName] string testName = null) { - using(var hostContext = new TestHostContext(this, testName)) + using (var hostContext = new TestHostContext(this, testName)) { var context = new AgentTaskPluginExecutionContext(hostContext.GetTrace()); @@ -59,16 +59,16 @@ private void RunTests( DefaultWorkingDirectory, p)) .ToArray(); - Func filter = FingerprintCreator.CreateFilter( + Func filter = FingerprintCreator.CreateFilter( context, includePatterns, excludePatterns ); - Action assertPath = (path, isMatch) => + Action assertPath = (path, isMatch) => Assert.True(isMatch == filter(path), $"filter({path}) should have returned {isMatch}."); - foreach((string path, bool match) in testCases) + foreach ((string path, bool match) in testCases) { assertPath(MakeOSPath(path), match); } @@ -81,9 +81,9 @@ private void RunTests( public void MultipleIncludes() { RunTests( - includePatterns: new [] {"good1.tmp","good2.tmp"}, - excludePatterns: new string[] {}, - testCases:new []{ + includePatterns: new[] { "good1.tmp", "good2.tmp" }, + excludePatterns: new string[] { }, + testCases: new[]{ ("C:\\working\\good1.tmp",true), ("C:\\working\\good2.tmp",true), ("C:\\working\\something.else",false), @@ -97,9 +97,9 @@ public void MultipleIncludes() public void AbsoluteAndRelative() { RunTests( - includePatterns: new [] {"C:\\working\\good1.tmp","good2.tmp"}, - excludePatterns: new string[] {}, - testCases:new []{ + includePatterns: new[] { "C:\\working\\good1.tmp", "good2.tmp" }, + excludePatterns: new string[] { }, + testCases: new[]{ ("C:\\working\\good1.tmp",true), ("C:\\working\\good2.tmp",true), ("C:\\working\\something.else",false), @@ -114,9 +114,9 @@ public void AbsoluteAndRelative() public void ExcludeSingleFile() { RunTests( - includePatterns: new [] {"*.tmp"}, - excludePatterns: new [] {"bad.tmp"}, - testCases:new []{ + includePatterns: new[] { "*.tmp" }, + excludePatterns: new[] { "bad.tmp" }, + testCases: new[]{ ("C:\\working\\good.tmp",true), ("C:\\working\\bad.tmp",false), ("C:\\working\\something.else",false), @@ -130,9 +130,9 @@ public void ExcludeSingleFile() public void ExcludeSingleFileWithDot() { RunTests( - includePatterns: new [] {"./*.tmp"}, - excludePatterns: new [] {"./bad.tmp"}, - testCases:new []{ + includePatterns: new[] { "./*.tmp" }, + excludePatterns: new[] { "./bad.tmp" }, + testCases: new[]{ ("C:\\working\\good.tmp",true), ("C:\\working\\bad.tmp",false), ("C:\\working\\something.else",false), @@ -146,9 +146,9 @@ public void ExcludeSingleFileWithDot() public void DoubleAsteriskAsPartOfPathSegment() { RunTests( - includePatterns: new [] {"./**blah/.tmp"}, - excludePatterns: new [] {"./bad.tmp"}, - testCases:new []{ + includePatterns: new[] { "./**blah/.tmp" }, + excludePatterns: new[] { "./bad.tmp" }, + testCases: new[]{ ("C:\\working\\good.tmp",false), ("C:\\working\\bad.tmp",false), ("C:\\working\\something.else",false), diff --git a/src/Test/L0/Plugin/RepositoryPluginL0.cs b/src/Test/L0/Plugin/RepositoryPluginL0.cs index aa4b903297..1933e1850a 100644 --- a/src/Test/L0/Plugin/RepositoryPluginL0.cs +++ b/src/Test/L0/Plugin/RepositoryPluginL0.cs @@ -425,7 +425,7 @@ private void Setup(TestHostContext hostContext, List() + JobSettings = new Dictionary() { // Set HasMultipleCheckouts to true if the number of repos is greater than 1 { WellKnownJobSettings.HasMultipleCheckouts, (repos.Count > 1).ToString() } diff --git a/src/Test/L0/Plugin/TarUtilsL0.cs b/src/Test/L0/Plugin/TarUtilsL0.cs index 52213ee369..b4752827e3 100644 --- a/src/Test/L0/Plugin/TarUtilsL0.cs +++ b/src/Test/L0/Plugin/TarUtilsL0.cs @@ -8,14 +8,16 @@ namespace Microsoft.VisualStudio.Services.Agent.Tests.PipelineCaching { - public class TarUtilsL0 { + public class TarUtilsL0 + { [Fact] [Trait("Level", "L0")] [Trait("Category", "Plugin")] - public async Task UnavailableProcessDependency_ThrowsNiceError() { + public async Task UnavailableProcessDependency_ThrowsNiceError() + { var startInfo = new ProcessStartInfo(); - startInfo.FileName = "ThisProcessObviouslyWillFail"; - await Assert.ThrowsAsync(async () => await TarUtils.RunProcessAsync(new AgentTaskPluginExecutionContext(), startInfo, (p,ct) => null,() => {}, new CancellationToken())); + startInfo.FileName = "ThisProcessObviouslyWillFail"; + await Assert.ThrowsAsync(async () => await TarUtils.RunProcessAsync(new AgentTaskPluginExecutionContext(), startInfo, (p, ct) => null, () => { }, new CancellationToken())); } } } \ No newline at end of file diff --git a/src/Test/L0/Plugin/TestFilePublisher/TestFileFinderL0.cs b/src/Test/L0/Plugin/TestFilePublisher/TestFileFinderL0.cs index 0e6a2489b8..b723e03821 100644 --- a/src/Test/L0/Plugin/TestFilePublisher/TestFileFinderL0.cs +++ b/src/Test/L0/Plugin/TestFilePublisher/TestFileFinderL0.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; diff --git a/src/Test/L0/Plugin/TestFilePublisher/TestFilePublisherL0.cs b/src/Test/L0/Plugin/TestFilePublisher/TestFilePublisherL0.cs index a54d184c6b..b6ae737522 100644 --- a/src/Test/L0/Plugin/TestFilePublisher/TestFilePublisherL0.cs +++ b/src/Test/L0/Plugin/TestFilePublisher/TestFilePublisherL0.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; diff --git a/src/Test/L0/Plugin/TestFilePublisher/TestFilePublisherLogPluginL0.cs b/src/Test/L0/Plugin/TestFilePublisher/TestFilePublisherLogPluginL0.cs index 5dde86b11b..993c1e2ca1 100644 --- a/src/Test/L0/Plugin/TestFilePublisher/TestFilePublisherLogPluginL0.cs +++ b/src/Test/L0/Plugin/TestFilePublisher/TestFilePublisherLogPluginL0.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; +using System; using System.Collections.Generic; using System.Threading.Tasks; using Agent.Plugins.Log.TestFilePublisher; diff --git a/src/Test/L0/Plugin/TestFileShareProvider/TestFileShareProviderL0.cs b/src/Test/L0/Plugin/TestFileShareProvider/TestFileShareProviderL0.cs index 79d6e27b11..a2d834b6d6 100644 --- a/src/Test/L0/Plugin/TestFileShareProvider/TestFileShareProviderL0.cs +++ b/src/Test/L0/Plugin/TestFileShareProvider/TestFileShareProviderL0.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; +using System; using System.Collections; using System.Collections.Generic; using System.IO; @@ -32,7 +32,7 @@ public class TestFileShareProviderL0 [Trait("Category", "Plugin")] public async Task TestPublishArtifactAsync() { - if(!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Robocopy only works in Windows and since agent is using Xunit, Assert.Inconclusive doesn't exist. return; @@ -41,9 +41,9 @@ public async Task TestPublishArtifactAsync() byte[] sourceContent = GenerateRandomData(); TestFile sourceFile = new TestFile(sourceContent); - sourceFile.PlaceItem( Path.Combine(Directory.GetCurrentDirectory(), Path.Combine(TestSourceFolder, "test1.txt"))); + sourceFile.PlaceItem(Path.Combine(Directory.GetCurrentDirectory(), Path.Combine(TestSourceFolder, "test1.txt"))); - using(var hostContext = new TestHostContext(this)) + using (var hostContext = new TestHostContext(this)) { var context = new AgentTaskPluginExecutionContext(hostContext.GetTrace()); context.Variables.Add("system.hosttype", "build"); @@ -56,7 +56,7 @@ public async Task TestPublishArtifactAsync() var sourceFiles = Directory.GetFiles(sourcePath); var destFiles = Directory.GetFiles(destPath); Assert.Equal(sourceFiles.Length, destFiles.Length); - foreach(var file in sourceFiles) + foreach (var file in sourceFiles) { string destFile = destFiles.FirstOrDefault(f => Path.GetFileName(f).Equals(Path.GetFileName(file))); Assert.True(StructuralComparisons.StructuralEqualityComparer.Equals(ComputeHash(file), ComputeHash(destFile))); @@ -75,30 +75,30 @@ public async Task TestDownloadArtifactAsync() TestFile sourceFile1 = new TestFile(sourceContent1); TestFile sourceFile2 = new TestFile(sourceContent2); - sourceFile1.PlaceItem( Path.Combine(Directory.GetCurrentDirectory(), Path.Combine(TestDownloadSourceFolder, "drop/test2.txt"))); - sourceFile2.PlaceItem( Path.Combine(Directory.GetCurrentDirectory(), Path.Combine(TestDownloadSourceFolder, "drop/test3.txt"))); + sourceFile1.PlaceItem(Path.Combine(Directory.GetCurrentDirectory(), Path.Combine(TestDownloadSourceFolder, "drop/test2.txt"))); + sourceFile2.PlaceItem(Path.Combine(Directory.GetCurrentDirectory(), Path.Combine(TestDownloadSourceFolder, "drop/test3.txt"))); - using(var hostContext = new TestHostContext(this)) + using (var hostContext = new TestHostContext(this)) { var context = new AgentTaskPluginExecutionContext(hostContext.GetTrace()); var provider = new FileShareProvider(context, null, context.CreateArtifactsTracer(), new MockDedupManifestArtifactClientFactory()); - + string sourcePath = Path.Combine(Directory.GetCurrentDirectory(), TestDownloadSourceFolder); string destPath = Path.Combine(Directory.GetCurrentDirectory(), TestDestFolder); ArtifactDownloadParameters downloadParameters = new ArtifactDownloadParameters(); downloadParameters.TargetDirectory = destPath; - downloadParameters.MinimatchFilters = new string[] {"**"}; + downloadParameters.MinimatchFilters = new string[] { "**" }; BuildArtifact buildArtifact = new BuildArtifact(); buildArtifact.Name = "drop"; buildArtifact.Resource = new ArtifactResource(); buildArtifact.Resource.Data = sourcePath; - + await provider.DownloadMultipleArtifactsAsync(downloadParameters, new List { buildArtifact }, CancellationToken.None, context); var sourceFiles = Directory.GetFiles(sourcePath); var destFiles = Directory.GetFiles(destPath); Assert.Equal(sourceFiles.Length, destFiles.Length); - foreach(var file in sourceFiles) + foreach (var file in sourceFiles) { string destFile = destFiles.FirstOrDefault(f => Path.GetFileName(f).Equals(Path.GetFileName(file))); Assert.True(StructuralComparisons.StructuralEqualityComparer.Equals(ComputeHash(file), ComputeHash(destFile))); @@ -117,29 +117,29 @@ public async Task TestDownloadArtifactAsyncWithMinimatchPattern() TestFile sourceFile1 = new TestFile(sourceContent1); TestFile sourceFile2 = new TestFile(sourceContent2); - sourceFile1.PlaceItem( Path.Combine(Directory.GetCurrentDirectory(), Path.Combine(TestDownloadSourceFolder, "drop/test2.txt"))); - sourceFile2.PlaceItem( Path.Combine(Directory.GetCurrentDirectory(), Path.Combine(TestDownloadSourceFolder, "drop/test3.txt"))); + sourceFile1.PlaceItem(Path.Combine(Directory.GetCurrentDirectory(), Path.Combine(TestDownloadSourceFolder, "drop/test2.txt"))); + sourceFile2.PlaceItem(Path.Combine(Directory.GetCurrentDirectory(), Path.Combine(TestDownloadSourceFolder, "drop/test3.txt"))); - using(var hostContext = new TestHostContext(this)) + using (var hostContext = new TestHostContext(this)) { var context = new AgentTaskPluginExecutionContext(hostContext.GetTrace()); var provider = new FileShareProvider(context, null, context.CreateArtifactsTracer(), new MockDedupManifestArtifactClientFactory()); - + string sourcePath = Path.Combine(Directory.GetCurrentDirectory(), TestDownloadSourceFolder); string destPath = Path.Combine(Directory.GetCurrentDirectory(), TestDestFolder); ArtifactDownloadParameters downloadParameters = new ArtifactDownloadParameters(); downloadParameters.TargetDirectory = destPath; - downloadParameters.MinimatchFilters = new string[] {"drop/test2.txt"}; + downloadParameters.MinimatchFilters = new string[] { "drop/test2.txt" }; BuildArtifact buildArtifact = new BuildArtifact(); buildArtifact.Name = "drop"; buildArtifact.Resource = new ArtifactResource(); buildArtifact.Resource.Data = sourcePath; - - await provider.DownloadMultipleArtifactsAsync(downloadParameters, new List {buildArtifact}, CancellationToken.None, context); + + await provider.DownloadMultipleArtifactsAsync(downloadParameters, new List { buildArtifact }, CancellationToken.None, context); var sourceFiles = Directory.GetFiles(sourcePath); var destFiles = Directory.GetFiles(Path.Combine(destPath, buildArtifact.Name)); Assert.Equal(1, destFiles.Length); - foreach(var file in sourceFiles) + foreach (var file in sourceFiles) { string destFile = destFiles.FirstOrDefault(f => Path.GetFileName(f).Equals(Path.GetFileName(file))); Assert.True(StructuralComparisons.StructuralEqualityComparer.Equals(ComputeHash(file), ComputeHash(destFile))); @@ -184,7 +184,7 @@ public class TestFile { public byte[] Content { get; protected set; } protected internal TestFile(byte[] content) - { + { this.Content = content; } diff --git a/src/Test/L0/Plugin/TestGitCliManager/TestGitCliManagerL0.cs b/src/Test/L0/Plugin/TestGitCliManager/TestGitCliManagerL0.cs index 276387b2a7..dcc5252b24 100644 --- a/src/Test/L0/Plugin/TestGitCliManager/TestGitCliManagerL0.cs +++ b/src/Test/L0/Plugin/TestGitCliManager/TestGitCliManagerL0.cs @@ -57,10 +57,10 @@ public async Task TestGitLfsFetchLfsConfigExistsAsync() // Assert Assert.Equal(2, gitCliManagerMock.GitCommandCallsOptions.Count); - + Assert.True(gitCliManagerMock.GitCommandCallsOptions.Contains("repositoryPath,checkout,refSpec -- .lfsconfig,additionalCmdLine"), "ExecuteGitCommandAsync should pass arguments properly to 'git checkout .lfsconfig' command"); Assert.True(gitCliManagerMock.GitCommandCallsOptions.Contains("repositoryPath,lfs,fetch origin refSpec,additionalCmdLine"), "ExecuteGitCommandAsync should pass arguments properly to 'git lfs fetch' command"); - + } finally { diff --git a/src/Test/L0/Plugin/TestResultParser/EnumerableExtensionL0.cs b/src/Test/L0/Plugin/TestResultParser/EnumerableExtensionL0.cs index b60acd3f6d..de6b045943 100644 --- a/src/Test/L0/Plugin/TestResultParser/EnumerableExtensionL0.cs +++ b/src/Test/L0/Plugin/TestResultParser/EnumerableExtensionL0.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; +using System; using System.Linq; using Agent.Plugins.Log.TestResultParser.Plugin; using Xunit; @@ -36,7 +36,7 @@ public void ListShouldBeBatchedIfSizeIsLessThanBatch() var randomList = Enumerable.Range(1, listSize).OrderBy(e => rnd.Next()).ToList(); var batchedList = randomList.Batch(100).ToArray(); - + Assert.True(batchedList.Length == 1); Assert.True(batchedList[0].Count() == 50); } diff --git a/src/Test/L0/Plugin/TestResultParser/LogPreProcessorL0.cs b/src/Test/L0/Plugin/TestResultParser/LogPreProcessorL0.cs index 52bb754ecf..2ffae747aa 100644 --- a/src/Test/L0/Plugin/TestResultParser/LogPreProcessorL0.cs +++ b/src/Test/L0/Plugin/TestResultParser/LogPreProcessorL0.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using Agent.Plugins.Log.TestResultParser.Plugin; +using Agent.Plugins.Log.TestResultParser.Plugin; using Xunit; namespace Test.L0.Plugin.TestResultParser diff --git a/src/Test/L0/Plugin/TestResultParser/PipelineTestRunPublisherL0.cs b/src/Test/L0/Plugin/TestResultParser/PipelineTestRunPublisherL0.cs index fa7ee05d7d..1b15cc2659 100644 --- a/src/Test/L0/Plugin/TestResultParser/PipelineTestRunPublisherL0.cs +++ b/src/Test/L0/Plugin/TestResultParser/PipelineTestRunPublisherL0.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; +using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -20,7 +20,7 @@ namespace Test.L0.Plugin.TestResultParser public class PipelineTestRunPublisherL0 { private PipelineConfig _pipelineConfig; - public PipelineTestRunPublisherL0 () + public PipelineTestRunPublisherL0() { this._pipelineConfig = new PipelineConfig() { diff --git a/src/Test/L0/Plugin/TestResultParser/TestResultLogPluginL0.cs b/src/Test/L0/Plugin/TestResultParser/TestResultLogPluginL0.cs index 8d3deb6af0..5cd0050fb3 100644 --- a/src/Test/L0/Plugin/TestResultParser/TestResultLogPluginL0.cs +++ b/src/Test/L0/Plugin/TestResultParser/TestResultLogPluginL0.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; +using System; using System.Collections.Generic; using System.Threading.Tasks; using Agent.Plugins.Log.TestResultParser.Contracts; @@ -126,7 +126,7 @@ public async Task TestResultLogPlugin_DisableIfPublishTaskPresent() {"system.hosttype", new VariableValue("build") }, {"system.servertype", new VariableValue("Hosted") } }); - + agentContext.Setup(x => x.Steps).Returns(new List() { new TaskStepDefinitionReference() diff --git a/src/Test/L0/Plugin/TestResultParser/TestRunManagerL0.cs b/src/Test/L0/Plugin/TestResultParser/TestRunManagerL0.cs index f4af605c16..3e98749e08 100644 --- a/src/Test/L0/Plugin/TestResultParser/TestRunManagerL0.cs +++ b/src/Test/L0/Plugin/TestResultParser/TestRunManagerL0.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; +using System; using System.Collections.Generic; using System.Threading.Tasks; using Agent.Plugins.Log.TestResultParser.Contracts; diff --git a/src/Test/L0/ProcessExtensionL0.cs b/src/Test/L0/ProcessExtensionL0.cs index 315f9f1148..94ca411685 100644 --- a/src/Test/L0/ProcessExtensionL0.cs +++ b/src/Test/L0/ProcessExtensionL0.cs @@ -87,7 +87,7 @@ public async Task SuccessReadProcessEnv() { sleep?.Kill(); } - catch { } + catch { } } } } diff --git a/src/Test/L0/ProcessInvokerL0.cs b/src/Test/L0/ProcessInvokerL0.cs index 6155b7d4e1..a8398fd881 100644 --- a/src/Test/L0/ProcessInvokerL0.cs +++ b/src/Test/L0/ProcessInvokerL0.cs @@ -170,7 +170,7 @@ public async Task RedirectSTDINCloseStream() List stdout = new List(); redirectSTDIN.Enqueue("Single line of STDIN"); - using (var cancellationTokenSource = new CancellationTokenSource() ) + using (var cancellationTokenSource = new CancellationTokenSource()) using (var processInvoker = new ProcessInvokerWrapper()) { processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) => @@ -220,7 +220,7 @@ public async Task RedirectSTDINKeepStreamOpen() Int32 exitCode = -1; List stdout = new List(); redirectSTDIN.Enqueue("Single line of STDIN"); - using (var cancellationTokenSource = new CancellationTokenSource() ) + using (var cancellationTokenSource = new CancellationTokenSource()) using (var processInvoker = new ProcessInvokerWrapper()) { processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) => @@ -326,7 +326,7 @@ public async Task OomScoreAdjIsWriten_FromEnv() try { var proc = await processInvoker.ExecuteAsync("", "bash", "-c \"cat /proc/$$/oom_score_adj\"", - new Dictionary { {"PIPELINE_JOB_OOMSCOREADJ", "1234"} }, + new Dictionary { { "PIPELINE_JOB_OOMSCOREADJ", "1234" } }, false, null, false, null, false, false, highPriorityProcess: false, continueAfterCancelProcessTreeKillAttempt: ProcessInvoker.ContinueAfterCancelProcessTreeKillAttemptDefault, @@ -406,7 +406,7 @@ public async Task DisableWorkerCommands() processInvoker.DisableWorkerCommands = true; processInvoker.Initialize(hc); exitCode = (TestUtil.IsWindows()) - ? await processInvoker.ExecuteAsync("", "powershell.exe", $@"-NoLogo -Sta -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ""Write-Host '##vso somecommand'""", null, CancellationToken.None) + ? await processInvoker.ExecuteAsync("", "powershell.exe", $@"-NoLogo -Sta -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ""Write-Host '##vso somecommand'""", null, CancellationToken.None) : await processInvoker.ExecuteAsync("", "bash", "-c \"echo '##vso somecommand'\"", null, CancellationToken.None); trace.Info("Exit Code: {0}", exitCode); @@ -437,7 +437,7 @@ public async Task EnableWorkerCommandsByDefault() }; processInvoker.Initialize(hc); exitCode = (TestUtil.IsWindows()) - ? await processInvoker.ExecuteAsync("", "powershell.exe", $@"-NoLogo -Sta -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ""Write-Host '##vso somecommand'""", null, CancellationToken.None) + ? await processInvoker.ExecuteAsync("", "powershell.exe", $@"-NoLogo -Sta -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ""Write-Host '##vso somecommand'""", null, CancellationToken.None) : await processInvoker.ExecuteAsync("", "bash", "-c \"echo '##vso somecommand'\"", null, CancellationToken.None); trace.Info("Exit Code: {0}", exitCode); diff --git a/src/Test/L0/ServiceInterfacesL0.cs b/src/Test/L0/ServiceInterfacesL0.cs index d0ce1c9ee1..f7c8162132 100644 --- a/src/Test/L0/ServiceInterfacesL0.cs +++ b/src/Test/L0/ServiceInterfacesL0.cs @@ -118,7 +118,8 @@ private static void Validate(Assembly assembly, params Type[] whitelist) continue; } - if (interfaceTypeInfo.FullName.Contains("IConverter")){ + if (interfaceTypeInfo.FullName.Contains("IConverter")) + { continue; } diff --git a/src/Test/L0/TestUtil.cs b/src/Test/L0/TestUtil.cs index a90338da62..15ed156348 100644 --- a/src/Test/L0/TestUtil.cs +++ b/src/Test/L0/TestUtil.cs @@ -46,7 +46,7 @@ public static string GetTestDataPath() return testDataDir; } - public static string WriteAllTextToTempFile(string content, string extension=null) + public static string WriteAllTextToTempFile(string content, string extension = null) { string file = Path.GetTempFileName(); if (!string.IsNullOrEmpty(extension)) diff --git a/src/Test/L0/Util/IOUtilL0.cs b/src/Test/L0/Util/IOUtilL0.cs index b55f976698..536eb2a64f 100644 --- a/src/Test/L0/Util/IOUtilL0.cs +++ b/src/Test/L0/Util/IOUtilL0.cs @@ -778,7 +778,7 @@ public void GetRelativePathNonWindows() Assert.True(string.Equals(relativePath, string.Empty, StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}"); } } - + [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] @@ -890,7 +890,7 @@ public void ResolvePathNonWindows() Assert.True(string.Equals(resolvePath, @"/", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {resolvePath}"); } } - + [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] @@ -991,16 +991,16 @@ public void GetDirectoryName_LinuxStyle() using (TestHostContext hc = new TestHostContext(this)) { Tracing trace = hc.GetTrace(); - string[,] testcases = new string [,] { + string[,] testcases = new string[,] { {"/foo/bar", "/foo"}, {"/foo", "/"}, {"/foo\\ bar/blah", "/foo\\ bar"} }; - for (int i=0; i(){ + var inputs = new Dictionary(){ { "input1", "foo" }, { "input2", tc.GetDirectory(WellKnownDirectory.Work)}, }; - var variables = new Dictionary(){ + var variables = new Dictionary(){ { "variable1", "foo" }, { "variable2", tc.GetDirectory(WellKnownDirectory.Work)}, }; - var taskVariables = new Dictionary(){ + var taskVariables = new Dictionary(){ { "taskVariable1", "foo" }, { "taskVariable2", tc.GetDirectory(WellKnownDirectory.Work)}, }; @@ -177,10 +177,10 @@ public void GeneratePluginExecutionContextHostInfoTest() public void GeneratePluginExecutionContextContainerInfoTest() { var dockerContainer = new Pipelines.ContainerResource() - { - Alias = "vsts_container_preview", - Image = "foo" - }; + { + Alias = "vsts_container_preview", + Image = "foo" + }; using (TestHostContext tc = CreateTestContext()) { @@ -193,37 +193,37 @@ public void GeneratePluginExecutionContextContainerInfoTest() { containerWorkPath = "C:\\__w"; } - var inputs = new Dictionary(){ + var inputs = new Dictionary(){ { "input1", "foo" }, { "input2", containerWorkPath}, { "input3", tc.GetDirectory(WellKnownDirectory.Work)}, }; - var expectedInputs = new Dictionary(){ + var expectedInputs = new Dictionary(){ { "input1", "foo" }, { "input2", tc.GetDirectory(WellKnownDirectory.Work)}, { "input3", tc.GetDirectory(WellKnownDirectory.Work)}, }; - var variables = new Dictionary(){ + var variables = new Dictionary(){ { "variable1", "foo" }, { "variable2", containerWorkPath}, { "variable3", tc.GetDirectory(WellKnownDirectory.Work)}, }; - var expectedVariables = new Dictionary(){ + var expectedVariables = new Dictionary(){ { "variable1", "foo" }, { "variable2", tc.GetDirectory(WellKnownDirectory.Work)}, { "variable3", tc.GetDirectory(WellKnownDirectory.Work)}, }; - var taskVariables = new Dictionary(){ + var taskVariables = new Dictionary(){ { "taskVariable1", "foo" }, { "taskVariable2", containerWorkPath}, { "taskVariable3", tc.GetDirectory(WellKnownDirectory.Work)}, }; - var expectedTaskVariables = new Dictionary(){ + var expectedTaskVariables = new Dictionary(){ { "taskVariable1", "foo" }, { "taskVariable2", tc.GetDirectory(WellKnownDirectory.Work)}, { "taskVariable3", tc.GetDirectory(WellKnownDirectory.Work)}, @@ -265,17 +265,17 @@ private IExecutionContext CreateTestExecutionContext(TestHostContext tc, if (stepTarget == null) { executionContext - .Setup( x => x.StepTarget()) + .Setup(x => x.StepTarget()) .Returns(new HostInfo()); } else { executionContext - .Setup( x => x.StepTarget()) + .Setup(x => x.StepTarget()) .Returns(stepTarget); } - return executionContext.Object; + return executionContext.Object; } } } diff --git a/src/Test/L0/Worker/Build/BuildJobExtensionL0.cs b/src/Test/L0/Worker/Build/BuildJobExtensionL0.cs index 8d3258a977..cd07f539da 100644 --- a/src/Test/L0/Worker/Build/BuildJobExtensionL0.cs +++ b/src/Test/L0/Worker/Build/BuildJobExtensionL0.cs @@ -129,7 +129,7 @@ private TestHostContext Setup([CallerMemberName] string name = "", _workspaceOptions = new Pipelines.WorkspaceOptions(); _configurationStore = new Mock(); _configurationStore.Setup(store => store.GetSettings()).Returns(new AgentSettings { WorkFolder = this.stubWorkFolder }); - + steps = new List(); var selfCheckoutTask = new Pipelines.TaskStep() { @@ -180,17 +180,17 @@ private TestHostContext Setup([CallerMemberName] string name = "", jobSettings = new Dictionary(); jobSettings.Add(WellKnownJobSettings.HasMultipleCheckouts, isMulticheckoutScenario.ToString()); _ec.Setup(x => x.JobSettings).Returns(jobSettings); - + _ec.Setup(x => x.SetVariable(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string varName, string varValue, bool isSecret, bool isOutput, bool isFilePath, bool isReadOnly) => { _variables.Set(varName, varValue, false); }); - + _extensionManager.Setup(x => x.GetExtensions()) .Returns(new List { _sourceProvider.Object }); - + _sourceProvider.Setup(x => x.RepositoryType) .Returns(Pipelines.RepositoryTypes.ExternalGit); - + _buildDirectoryManager.Setup(x => x.PrepareDirectory(_ec.Object, repositories, _workspaceOptions)) .Returns(new TrackingConfig(_ec.Object, repositories, 1)); diff --git a/src/Test/L0/Worker/Build/TrackingConfigHashAlgorithmL0.cs b/src/Test/L0/Worker/Build/TrackingConfigHashAlgorithmL0.cs index 52e6414ef7..41b83213e3 100644 --- a/src/Test/L0/Worker/Build/TrackingConfigHashAlgorithmL0.cs +++ b/src/Test/L0/Worker/Build/TrackingConfigHashAlgorithmL0.cs @@ -38,7 +38,7 @@ public void ComputeHash_returns_correct_hash() }; // Act. - string hashKey = TrackingConfigHashAlgorithm.ComputeHash(collectionId, definitionId, new [] { repoInfo }); + string hashKey = TrackingConfigHashAlgorithm.ComputeHash(collectionId, definitionId, new[] { repoInfo }); // Assert. Assert.Equal("5c5c3d7ac33cca6604736eb3af977f23f1cf1146", hashKey); @@ -164,7 +164,7 @@ public void ComputeHash_with_multi_repos_should_return_correct_hash() // Make sure that only the coll, def, identifier, and url are used in the hash Assert.Equal( - TrackingConfigHashAlgorithm.ComputeHash(collectionId, definitionId, new[] { repo1, repo2 }), + TrackingConfigHashAlgorithm.ComputeHash(collectionId, definitionId, new[] { repo1, repo2 }), TrackingConfigHashAlgorithm.ComputeHash(collectionId, definitionId, new[] { repo1, repo2_newPath })); // Make sure that different coll creates different hash diff --git a/src/Test/L0/Worker/CodeCoverage/CodeCoverageCommandExtensionTests.cs b/src/Test/L0/Worker/CodeCoverage/CodeCoverageCommandExtensionTests.cs index 2913e95214..66321f2860 100644 --- a/src/Test/L0/Worker/CodeCoverage/CodeCoverageCommandExtensionTests.cs +++ b/src/Test/L0/Worker/CodeCoverage/CodeCoverageCommandExtensionTests.cs @@ -369,7 +369,7 @@ private TestHostContext SetupMocks([CallerMemberName] string name = "") _ec.Setup(x => x.Restrictions).Returns(new List()); _ec.Setup(x => x.Endpoints).Returns(new List { new ServiceEndpoint { Url = new Uri("http://dummyurl"), Name = WellKnownServiceEndpointNames.SystemVssConnection, Authorization = endpointAuthorization } }); _ec.Setup(x => x.Variables).Returns(_variables); - _ec.Setup(x => x.TranslateToHostPath(It.IsAny())).Returns( (string x) => x ); + _ec.Setup(x => x.TranslateToHostPath(It.IsAny())).Returns((string x) => x); var asyncCommands = new List(); _ec.Setup(x => x.AsyncCommands).Returns(asyncCommands); _ec.Setup(x => x.GetHostContext()).Returns(_hc); diff --git a/src/Test/L0/Worker/ExecutionContextL0.cs b/src/Test/L0/Worker/ExecutionContextL0.cs index 6fd646404a..d534c07931 100644 --- a/src/Test/L0/Worker/ExecutionContextL0.cs +++ b/src/Test/L0/Worker/ExecutionContextL0.cs @@ -134,7 +134,8 @@ public void StepTarget_VerifySet() { ec.Initialize(hc); - var pipeContainer = new Pipelines.ContainerResource { + var pipeContainer = new Pipelines.ContainerResource + { Alias = "container" }; pipeContainer.Properties.Set("image", "someimage"); @@ -182,7 +183,8 @@ public void StepTarget_RestrictedCommands_Host() { ec.Initialize(hc); - var pipeContainer = new Pipelines.ContainerResource { + var pipeContainer = new Pipelines.ContainerResource + { Alias = "container" }; pipeContainer.Properties.Set("image", "someimage"); @@ -231,7 +233,8 @@ public void StepTarget_LoadStepContainersWithoutJobContainer() { ec.Initialize(hc); - var pipeContainer = new Pipelines.ContainerResource { + var pipeContainer = new Pipelines.ContainerResource + { Alias = "container" }; pipeContainer.Properties.Set("image", "someimage"); @@ -278,13 +281,16 @@ public void SidecarContainers_VerifyNotJobContainers() { ec.Initialize(hc); - var pipeContainer = new Pipelines.ContainerResource { + var pipeContainer = new Pipelines.ContainerResource + { Alias = "container" }; - var pipeContainerSidecar = new Pipelines.ContainerResource { + var pipeContainerSidecar = new Pipelines.ContainerResource + { Alias = "sidecar" }; - var pipeContainerExtra = new Pipelines.ContainerResource { + var pipeContainerExtra = new Pipelines.ContainerResource + { Alias = "extra" }; pipeContainer.Properties.Set("image", "someimage"); diff --git a/src/Test/L0/Worker/PluginInternalUpdateRepositoryPathCommandL0.cs b/src/Test/L0/Worker/PluginInternalUpdateRepositoryPathCommandL0.cs index 8c53da09dc..3a88922b4b 100644 --- a/src/Test/L0/Worker/PluginInternalUpdateRepositoryPathCommandL0.cs +++ b/src/Test/L0/Worker/PluginInternalUpdateRepositoryPathCommandL0.cs @@ -184,13 +184,13 @@ private void InitializeExecutionContext(TestHostContext hc, bool isMultiCheckout var directoryManager = new Mock(); directoryManager.Setup(x => x.GetRelativeRepositoryPath(It.IsAny(), It.IsAny())) .Returns((bd, path) => GetLastPathPart(path)); - + hc.SetSingleton(directoryManager.Object); } private string GetLastPathPart(string path) { - return path?.Substring(path.LastIndexOfAny(new char[] { '/', '\\' } ) + 1); + return path?.Substring(path.LastIndexOfAny(new char[] { '/', '\\' }) + 1); } private RepositoryResource _selfRepo; diff --git a/src/Test/L0/Worker/Release/FetchEngineL0.cs b/src/Test/L0/Worker/Release/FetchEngineL0.cs index 0cf0f08074..5fd25c8984 100644 --- a/src/Test/L0/Worker/Release/FetchEngineL0.cs +++ b/src/Test/L0/Worker/Release/FetchEngineL0.cs @@ -91,79 +91,79 @@ public async void ShouldNotDoParallelDownloadIfSpecified() } } -/* - [Fact] - [Trait("Level", "L0")] - [Trait("Category", "Worker")] - public async Task ShouldHonorRetryLimit() - { - int fetchCount = 0; - var stubContainerProvider = new StubContainerProvider( - new List - { - DummyConatinerItem1 - }, - (item1, c) => - { - fetchCount++; - if (fetchCount == 1) - { - throw new FileNotFoundException(); - } - return mockItemContent; - }); - containerFetchEngineTestOptions.RetryLimit = 2; - var fetchEngine = GetFetchEngine(stubContainerProvider, CancellationToken.None); - - Task fetchAsync = fetchEngine.FetchAsync(CancellationToken.None); - await fetchAsync; - - Assert.Equal(containerFetchEngineTestOptions.RetryLimit, fetchCount); - } - - [Fact] - [Trait("Level", "L0")] - [Trait("Category", "Worker")] - public async Task ShouldCancelAllDownloadsOnException() - { - bool isTaskCancelled = false; - var stubContainerProvider = new StubContainerProvider( - new List + /* + [Fact] + [Trait("Level", "L0")] + [Trait("Category", "Worker")] + public async Task ShouldHonorRetryLimit() { - DummyConatinerItem1, - DummyConatinerItem2 - }, - (item1, c) => + int fetchCount = 0; + var stubContainerProvider = new StubContainerProvider( + new List + { + DummyConatinerItem1 + }, + (item1, c) => + { + fetchCount++; + if (fetchCount == 1) + { + throw new FileNotFoundException(); + } + return mockItemContent; + }); + containerFetchEngineTestOptions.RetryLimit = 2; + var fetchEngine = GetFetchEngine(stubContainerProvider, CancellationToken.None); + + Task fetchAsync = fetchEngine.FetchAsync(CancellationToken.None); + await fetchAsync; + + Assert.Equal(containerFetchEngineTestOptions.RetryLimit, fetchCount); + } + + [Fact] + [Trait("Level", "L0")] + [Trait("Category", "Worker")] + public async Task ShouldCancelAllDownloadsOnException() { - Thread.Sleep(300); - if (((ContainerItem)item1).ContainerId == 1) + bool isTaskCancelled = false; + var stubContainerProvider = new StubContainerProvider( + new List + { + DummyConatinerItem1, + DummyConatinerItem2 + }, + (item1, c) => + { + Thread.Sleep(300); + if (((ContainerItem)item1).ContainerId == 1) + { + throw new FileNotFoundException(); + } + while (!c.IsCancellationRequested) + { + } + + isTaskCancelled = c.IsCancellationRequested; + return mockItemContent; + }); + containerFetchEngineTestOptions.RetryLimit = 0; + containerFetchEngineTestOptions.ParallelDownloadLimit = 2; + var fetchEngine = GetFetchEngine(stubContainerProvider, CancellationToken.None); + + Task fetchAsync = fetchEngine.FetchAsync(CancellationToken.None); + try { - throw new FileNotFoundException(); + await fetchAsync; } - while (!c.IsCancellationRequested) + catch { + // ignored } - isTaskCancelled = c.IsCancellationRequested; - return mockItemContent; - }); - containerFetchEngineTestOptions.RetryLimit = 0; - containerFetchEngineTestOptions.ParallelDownloadLimit = 2; - var fetchEngine = GetFetchEngine(stubContainerProvider, CancellationToken.None); - - Task fetchAsync = fetchEngine.FetchAsync(CancellationToken.None); - try - { - await fetchAsync; - } - catch - { - // ignored - } - - Assert.Equal(isTaskCancelled, true); - } -*/ + Assert.Equal(isTaskCancelled, true); + } + */ [Fact] [Trait("Level", "L0")] diff --git a/src/Test/L0/Worker/Release/ReleaseDirectoryManagerL0.cs b/src/Test/L0/Worker/Release/ReleaseDirectoryManagerL0.cs index 511962ea9d..4c74074c3a 100644 --- a/src/Test/L0/Worker/Release/ReleaseDirectoryManagerL0.cs +++ b/src/Test/L0/Worker/Release/ReleaseDirectoryManagerL0.cs @@ -114,7 +114,7 @@ public void PrepareArtifactsDirectoryShouldReturnMapIfWorkDirectoryDoesNotExist( private TestHostContext Initialize([CallerMemberName] string name = "", bool createWorkDirectory = true) { - var hostContext = new TestHostContext(this, name); + var hostContext = new TestHostContext(this, name); this.stubWorkFolder = hostContext.GetDirectory(WellKnownDirectory.Work); if (createWorkDirectory) { diff --git a/src/Test/L0/Worker/Release/ReleaseJobExtensionL0.cs b/src/Test/L0/Worker/Release/ReleaseJobExtensionL0.cs index 8c4bd9e96f..5a61cb2fd6 100644 --- a/src/Test/L0/Worker/Release/ReleaseJobExtensionL0.cs +++ b/src/Test/L0/Worker/Release/ReleaseJobExtensionL0.cs @@ -116,7 +116,7 @@ public void PreapreAsyncShouldInitializeAgentIfSkipArtifactDownloadIsTrueAndRele private TestHostContext Setup([CallerMemberName] string name = "", bool createWorkDirectory = true, bool useReleaseDefinitionId = true, bool setupArtifactsDirectory = false) { TestHostContext hc = new TestHostContext(this, name); - this.stubWorkFolder =hc.GetDirectory(WellKnownDirectory.Work); + this.stubWorkFolder = hc.GetDirectory(WellKnownDirectory.Work); if (createWorkDirectory) { Directory.CreateDirectory(this.stubWorkFolder); @@ -135,7 +135,7 @@ private TestHostContext Setup([CallerMemberName] string name = "", bool createWo ? GetReleaseVariables(id.ToString(), bool.TrueString) : GetReleaseVariables(null, bool.TrueString); - if(setupArtifactsDirectory) + if (setupArtifactsDirectory) { releaseVariables.Add(Constants.Variables.Release.ArtifactsDirectory, this.stubWorkFolder); } diff --git a/src/Test/L0/Worker/SetVariableRestrictionsL0.cs b/src/Test/L0/Worker/SetVariableRestrictionsL0.cs index 3609afdbfc..5a54cccf62 100644 --- a/src/Test/L0/Worker/SetVariableRestrictionsL0.cs +++ b/src/Test/L0/Worker/SetVariableRestrictionsL0.cs @@ -83,7 +83,7 @@ public void ExactMatchAllowed() Command command; var value = "myValue"; - foreach(String variable in new String[] { "myVar", "myvar", "MYVAR", "otherVAR" }) + foreach (String variable in new String[] { "myVar", "myvar", "MYVAR", "otherVAR" }) { command = SetVariableCommand(variable, value); setVariable = new TaskSetVariableCommand(); @@ -117,7 +117,7 @@ public void MiniMatchAllowed() Command command; var value = "myValue"; - foreach(String variable in new String[] { "myVar", "mything", "MY" }) + foreach (String variable in new String[] { "myVar", "mything", "MY" }) { command = SetVariableCommand(variable, value); setVariable = new TaskSetVariableCommand(); @@ -159,7 +159,7 @@ public void MultipleRestrictionsMostRestrictive() var value = "myValue"; // settable is both allowed lists - foreach(String variable in new String[] { "myVar", "myThing" }) + foreach (String variable in new String[] { "myVar", "myThing" }) { command = SetVariableCommand(variable, value); setVariable = new TaskSetVariableCommand(); @@ -176,7 +176,7 @@ public void MultipleRestrictionsMostRestrictive() setVariable = new TaskSetVariableCommand(); setVariable.Execute(_ec.Object, command); Assert.Equal(null, _variables.Get(variable)); - Assert.Equal(lastCount+1, _warnings.Count); + Assert.Equal(lastCount + 1, _warnings.Count); Assert.Contains("SetVariableNotAllowed", _warnings.Last()); lastCount = _warnings.Count; } @@ -209,7 +209,7 @@ public void MultipleRestrictionsNothingAllowed() setVariable = new TaskSetVariableCommand(); setVariable.Execute(_ec.Object, command); Assert.Equal(null, _variables.Get(variable)); - Assert.Equal(lastCount+1, _warnings.Count); + Assert.Equal(lastCount + 1, _warnings.Count); Assert.Contains("SetVariableNotAllowed", _warnings.Last()); lastCount = _warnings.Count; } diff --git a/src/Test/L0/Worker/StepsRunnerL0.cs b/src/Test/L0/Worker/StepsRunnerL0.cs index c3d35d760b..d39b97c98b 100644 --- a/src/Test/L0/Worker/StepsRunnerL0.cs +++ b/src/Test/L0/Worker/StepsRunnerL0.cs @@ -407,7 +407,8 @@ public async Task SetStepTarget() { using (TestHostContext hc = CreateTestContext()) { - var stepTarget = new Pipelines.StepTarget { + var stepTarget = new Pipelines.StepTarget + { Target = "container" }; var step = CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded); diff --git a/src/Test/L0/Worker/TaskDecoratorManagerL0.cs b/src/Test/L0/Worker/TaskDecoratorManagerL0.cs index 1028c56976..53c62906f9 100644 --- a/src/Test/L0/Worker/TaskDecoratorManagerL0.cs +++ b/src/Test/L0/Worker/TaskDecoratorManagerL0.cs @@ -21,7 +21,7 @@ public void IsInjectedTaskForTarget_TaskWithTargetPrefix() const String PreTargetTask = "__system_pretargettask_"; var taskWithPreTarget = $"{PreTargetTask}TestTask"; var taskWithPostTarget = $"{PostTargetTask}TestTask"; - + TaskDecoratorManager decoratorManager = new TaskDecoratorManager(); Assert.True(decoratorManager.IsInjectedTaskForTarget(taskWithPostTarget, executionContext.Object)); diff --git a/src/Test/L0/Worker/TaskRunnerL0.cs b/src/Test/L0/Worker/TaskRunnerL0.cs index 4c3b0d841d..a2c0b26035 100644 --- a/src/Test/L0/Worker/TaskRunnerL0.cs +++ b/src/Test/L0/Worker/TaskRunnerL0.cs @@ -33,7 +33,7 @@ private class GetHandlerTest public HandlerData Expected; public ExecutionTargetInfo StepTarget = null; - public void RunTest(TestHostContext hc, Dictionary variables=null) + public void RunTest(TestHostContext hc, Dictionary variables = null) { var _ec = new Mock(); _ec.Setup(x => x.StepTarget()).Returns(StepTarget); @@ -69,10 +69,10 @@ public void RunTest(TestHostContext hc, Dictionary variab [Trait("Category", "Worker")] public void GetHandlerHostOnlyTests() { - var nodeData = new NodeHandlerData() { Platforms=new string[]{"linux", "osx" }}; + var nodeData = new NodeHandlerData() { Platforms = new string[] { "linux", "osx" } }; var nodeOnlyExecutionData = new ExecutionData(); nodeOnlyExecutionData.Node = nodeData; - var powerShell3Data = new PowerShell3HandlerData() { Platforms=new string[]{"windows"}}; + var powerShell3Data = new PowerShell3HandlerData() { Platforms = new string[] { "windows" } }; var ps3OnlyExecutionData = new ExecutionData(); ps3OnlyExecutionData.PowerShell3 = powerShell3Data; var mixedExecutionData = new ExecutionData(); @@ -108,14 +108,14 @@ public void GetHandlerContainerTargetTests() var nodeData = new NodeHandlerData(); var nodeOnlyExecutionData = new ExecutionData(); nodeOnlyExecutionData.Node = nodeData; - var powerShell3Data = new PowerShell3HandlerData() { Platforms=new string[]{"windows"}}; + var powerShell3Data = new PowerShell3HandlerData() { Platforms = new string[] { "windows" } }; var ps3OnlyExecutionData = new ExecutionData(); ps3OnlyExecutionData.PowerShell3 = powerShell3Data; var mixedExecutionData = new ExecutionData(); mixedExecutionData.Node = nodeData; mixedExecutionData.PowerShell3 = powerShell3Data; - ContainerInfo containerInfo = new ContainerInfo() {}; + ContainerInfo containerInfo = new ContainerInfo() { }; foreach (var test in new GetHandlerTest[] { new GetHandlerTest() { Name="Empty Test", Input=null, Expected=null, HostOS=PlatformUtil.OS.Windows, StepTarget=containerInfo }, @@ -145,14 +145,14 @@ public void GetHandlerContainerTargetPreferNodeDisabledTests() var nodeData = new NodeHandlerData(); var nodeOnlyExecutionData = new ExecutionData(); nodeOnlyExecutionData.Node = nodeData; - var powerShell3Data = new PowerShell3HandlerData() { Platforms=new string[]{"windows"}}; + var powerShell3Data = new PowerShell3HandlerData() { Platforms = new string[] { "windows" } }; var ps3OnlyExecutionData = new ExecutionData(); ps3OnlyExecutionData.PowerShell3 = powerShell3Data; var mixedExecutionData = new ExecutionData(); mixedExecutionData.Node = nodeData; mixedExecutionData.PowerShell3 = powerShell3Data; - ContainerInfo containerInfo = new ContainerInfo() {}; + ContainerInfo containerInfo = new ContainerInfo() { }; foreach (var test in new GetHandlerTest[] { new GetHandlerTest() { Name="Empty Test", Input=null, Expected=null, HostOS=PlatformUtil.OS.Windows, StepTarget=containerInfo }, diff --git a/src/Test/L0/Worker/TestResults/Legacy/JunitResultReaderTests.cs b/src/Test/L0/Worker/TestResults/Legacy/JunitResultReaderTests.cs index 2da06bfbf1..acc1f18255 100644 --- a/src/Test/L0/Worker/TestResults/Legacy/JunitResultReaderTests.cs +++ b/src/Test/L0/Worker/TestResults/Legacy/JunitResultReaderTests.cs @@ -59,21 +59,21 @@ public class JunitResultReaderTests : IDisposable + "" + ""; - private const string _jUnitNestedResultsXmlWithEmptyNameAttribute = "" - + "" - + "" - + "" - + "" - + "" - + "junit.framework.AssertionFailedError at com.contoso.billingservice.ConsoleMessageRendererTest.testRenderMessage(ConsoleMessageRendererTest.java:11)" - + "" - + "" - + "" - + "" - + "" - + "" - + "" - + ""; + private const string _jUnitNestedResultsXmlWithEmptyNameAttribute = "" + + "" + + "" + + "" + + "" + + "" + + "junit.framework.AssertionFailedError at com.contoso.billingservice.ConsoleMessageRendererTest.testRenderMessage(ConsoleMessageRendererTest.java:11)" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + ""; private const string _sampleJunitResultXmlInvalidTime = "" + "" diff --git a/src/Test/L0/Worker/TestResults/Legacy/NUnitResultReaderTests.cs b/src/Test/L0/Worker/TestResults/Legacy/NUnitResultReaderTests.cs index bc2af8724a..1f09f0e112 100644 --- a/src/Test/L0/Worker/TestResults/Legacy/NUnitResultReaderTests.cs +++ b/src/Test/L0/Worker/TestResults/Legacy/NUnitResultReaderTests.cs @@ -533,7 +533,7 @@ public void PublishNUnit3ResultsShouldConsiderTestCaseAttachments() var failedTestWithAttachment = _testRunData.Results.Where(x => x.Outcome.Equals("Failed")).FirstOrDefault(); Assert.Equal(failedTestWithAttachment.AttachmentData.AttachmentsFilePathList.Count(), 1); - Assert.Collection(failedTestWithAttachment.AttachmentData.AttachmentsFilePathList.ToList(), x=>{x.Equals(@"C:\Users\navb\Pictures\dummy1.png");}); + Assert.Collection(failedTestWithAttachment.AttachmentData.AttachmentsFilePathList.ToList(), x => { x.Equals(@"C:\Users\navb\Pictures\dummy1.png"); }); } [Fact] @@ -548,7 +548,7 @@ public void PublishNUnit3ResultsShouldConsiderTestCaseAttachmentsMultiple() var failedTestWithAttachment = _testRunData.Results.Where(x => x.Outcome.Equals("Failed")).FirstOrDefault(); Assert.Equal(failedTestWithAttachment.AttachmentData.AttachmentsFilePathList.Count(), 2); - Assert.Collection(failedTestWithAttachment.AttachmentData.AttachmentsFilePathList.ToList(), x=>{x.Equals(@"C:\Users\navb\Pictures\dummy1.png");}, y=>{y.Equals( @"C:\Users\navb\Pictures\dummy4.png");}); + Assert.Collection(failedTestWithAttachment.AttachmentData.AttachmentsFilePathList.ToList(), x => { x.Equals(@"C:\Users\navb\Pictures\dummy1.png"); }, y => { y.Equals(@"C:\Users\navb\Pictures\dummy4.png"); }); // checking other test cases should not have attachments. var passedTest = _testRunData.Results.Where(x => x.Outcome.Equals("Passed")).FirstOrDefault(); @@ -567,7 +567,7 @@ public void PublishNUnit3ResultsShouldConsiderTestSuiteLevelAttachments() // 2 files are test suites level attachments and one is the result file itself. Assert.Equal(_testRunData.Attachments.Count(), 3); - Assert.Collection(_testRunData.Attachments.ToList(), x=>{x.Equals(@"C:\Users\navb\Pictures\dummy2.png");}, y=>{y.Equals( @"C:\Users\navb\Pictures\dummy3.png");}, z=>{z.Equals(_fileName);}); + Assert.Collection(_testRunData.Attachments.ToList(), x => { x.Equals(@"C:\Users\navb\Pictures\dummy2.png"); }, y => { y.Equals(@"C:\Users\navb\Pictures\dummy3.png"); }, z => { z.Equals(_fileName); }); } public void Dispose() diff --git a/src/Test/L0/Worker/TestResults/Legacy/TestRunPublisherTests.cs b/src/Test/L0/Worker/TestResults/Legacy/TestRunPublisherTests.cs index 0f6a9ac163..d40fa73b92 100644 --- a/src/Test/L0/Worker/TestResults/Legacy/TestRunPublisherTests.cs +++ b/src/Test/L0/Worker/TestResults/Legacy/TestRunPublisherTests.cs @@ -89,7 +89,7 @@ public TestRunPublisherTests() int j = 1; foreach (TestCaseResult resultCreateModel in _resultCreateModels) { - List SubResults = null; + List SubResults = null; if (resultCreateModel.SubResults != null) { SubResults = new List(); @@ -156,7 +156,7 @@ public TestRunPublisherTests() { if (_subResultsLevelAttachments.ContainsKey(testCaseResultId)) { - if(_subResultsLevelAttachments[testCaseResultId].ContainsKey(testSubResultId)) + if (_subResultsLevelAttachments[testCaseResultId].ContainsKey(testSubResultId)) { _subResultsLevelAttachments[testCaseResultId][testSubResultId].Add(reqModel); } @@ -248,7 +248,7 @@ public void AddResultsWithSubResultsAttachmentsCallsRightApi() _testRunData = _publisher.ReadResultsFromFile(_testRunContext, "filepath"); _publisher.StartTestRunAsync(_testRunData); var result = new TestCaseResultData(); - result.TestCaseSubResultData = new List { new TestCaseSubResultData()}; + result.TestCaseSubResultData = new List { new TestCaseSubResultData() }; var testRun = new TestRun { Id = 1 }; result.TestCaseSubResultData[0].AttachmentData = new AttachmentData(); result.TestCaseSubResultData[0].AttachmentData.AttachmentsFilePathList = new string[] { "attachment.txt" }; @@ -460,7 +460,8 @@ public void BatchSizeIsCorrect() ResetValues(); _publisher.StartTestRunAsync(new TestRunData()).Wait(); List testCaseResultData = new List(); - for (int i = 0; i < batchSize + 1; i++) { + for (int i = 0; i < batchSize + 1; i++) + { testCaseResultData.Add(new TestCaseResultData()); testCaseResultData[i].AttachmentData = new AttachmentData(); } diff --git a/src/Test/L0/Worker/TestResults/Legacy/TrxResultReaderTests.cs b/src/Test/L0/Worker/TestResults/Legacy/TrxResultReaderTests.cs index 58ea13be3c..0eaf9ccb0b 100644 --- a/src/Test/L0/Worker/TestResults/Legacy/TrxResultReaderTests.cs +++ b/src/Test/L0/Worker/TestResults/Legacy/TrxResultReaderTests.cs @@ -154,8 +154,8 @@ public void ResultsWithInvalidStartDate() Assert.NotNull(runData); Assert.Equal(1, runData.Results.Length); - Assert.Equal(true, DateTime.Compare((DateTime) SqlDateTime.MinValue, runData.Results[0].StartedDate) < 0); - Assert.Equal(true, DateTime.Compare((DateTime) SqlDateTime.MinValue, runData.Results[0].CompletedDate) < 0); + Assert.Equal(true, DateTime.Compare((DateTime)SqlDateTime.MinValue, runData.Results[0].StartedDate) < 0); + Assert.Equal(true, DateTime.Compare((DateTime)SqlDateTime.MinValue, runData.Results[0].CompletedDate) < 0); } [Fact] @@ -862,13 +862,13 @@ protected virtual void Dispose(bool disposing) { if (disposing) { - try - { - File.Delete(_trxResultFile); - } - catch - { - } + try + { + File.Delete(_trxResultFile); + } + catch + { + } } } diff --git a/src/Test/L0/Worker/TestResults/ResultsCommandExtensionTests.cs b/src/Test/L0/Worker/TestResults/ResultsCommandExtensionTests.cs index 674e782b12..dc2e01f222 100644 --- a/src/Test/L0/Worker/TestResults/ResultsCommandExtensionTests.cs +++ b/src/Test/L0/Worker/TestResults/ResultsCommandExtensionTests.cs @@ -164,7 +164,7 @@ private TestHostContext SetupMocks([CallerMemberName] string name = "", bool inc List warnings; _variables = new Variables(_hc, new Dictionary(), out warnings); _variables.Set("build.buildId", "1"); - if(includePipelineVariables) + if (includePipelineVariables) { _variables.Set("system.jobName", "job1"); _variables.Set("system.phaseName", "phase1"); diff --git a/src/Test/L0/Worker/VariablesL0.cs b/src/Test/L0/Worker/VariablesL0.cs index f702dc7605..0faff3d9f5 100644 --- a/src/Test/L0/Worker/VariablesL0.cs +++ b/src/Test/L0/Worker/VariablesL0.cs @@ -646,12 +646,14 @@ public void RecalculateExpanded_PathTranslator() List warnings; var variables = new Variables(hc, copy, out warnings); - variables.StringTranslator = (str) => { - if (str.StartsWith("/path/to")) { + variables.StringTranslator = (str) => + { + if (str.StartsWith("/path/to")) + { return str.Replace("/path/to", "/another/path"); } return str; - };; + }; Assert.Equal(0, warnings.Count); @@ -874,7 +876,7 @@ public void IsReadOnly_ListContainsAllReadOnlyVariables() foreach (System.Type systemVariableClass in wellKnownSystemVariableClasses) { var wellKnownDistributedTaskFields = systemVariableClass.GetFields(); - foreach(var field in wellKnownDistributedTaskFields) + foreach (var field in wellKnownDistributedTaskFields) { var fieldValue = field.GetValue(systemVariableClass); if (fieldValue != null) @@ -886,7 +888,7 @@ public void IsReadOnly_ListContainsAllReadOnlyVariables() } // Assert. - foreach(string systemVariable in wellKnownSystemVariables) + foreach (string systemVariable in wellKnownSystemVariables) { Assert.True(Constants.Variables.ReadOnlyVariables.Contains(systemVariable), "Constants.Variables.ReadOnlyVariables should contain " + systemVariable); } @@ -938,7 +940,7 @@ public void CopyInto_Basic() var variables = new Variables(hc, new Dictionary(), out warnings); - Dictionary dict1 = new Dictionary(); + Dictionary dict1 = new Dictionary(); variables.CopyInto(dict1, Variables.DefaultStringTranslator); Assert.Equal(0, dict1.Count); diff --git a/src/Test/L0/Worker/WorkerCommandManagerL0.cs b/src/Test/L0/Worker/WorkerCommandManagerL0.cs index 7a3a0b4432..cc1deeafec 100644 --- a/src/Test/L0/Worker/WorkerCommandManagerL0.cs +++ b/src/Test/L0/Worker/WorkerCommandManagerL0.cs @@ -24,7 +24,7 @@ public void InstallFoo2Command() } } - public class FooCommand: IWorkerCommand + public class FooCommand : IWorkerCommand { public string Name => "foo"; public List Aliases => null; @@ -34,7 +34,7 @@ public void Execute(IExecutionContext context, Command command) } } - public class Foo2Command: IWorkerCommand + public class Foo2Command : IWorkerCommand { public string Name => "foo"; public List Aliases => null; @@ -44,7 +44,7 @@ public void Execute(IExecutionContext context, Command command) } } - public class BarCommand: IWorkerCommand + public class BarCommand : IWorkerCommand { public string Name => "bar"; public List Aliases => new List() { "cat" }; diff --git a/src/Test/L1/Mock/FakeJobServer.cs b/src/Test/L1/Mock/FakeJobServer.cs index 2f4723b09a..c19de4341b 100644 --- a/src/Test/L1/Mock/FakeJobServer.cs +++ b/src/Test/L1/Mock/FakeJobServer.cs @@ -88,7 +88,8 @@ public Task CreateLogAsync(Guid scopeIdentifier, string hubName, Guid p public Task CreateTimelineAsync(Guid scopeIdentifier, string hubName, Guid planId, Guid timelineId, CancellationToken cancellationToken) { - var timeline = new Timeline { + var timeline = new Timeline + { Id = timelineId }; Timelines.Add(timelineId, timeline); @@ -140,7 +141,7 @@ public Task UploadLogToBlobStore(Stream blob, string h { UploadedAttachmentBlobFiles.Add(itemPath); var chunk = await ChunkerHelper.CreateFromFileAsync(FileSystem.Instance, itemPath, cancellationToken, false); - var rootNode = new DedupNode(new []{ chunk}); + var rootNode = new DedupNode(new[] { chunk }); var dedupId = rootNode.GetDedupIdentifier(HashType.Dedup64K); return (dedupId, rootNode.TransitiveContentBytes); diff --git a/src/Test/L1/Plugins/FakeCheckoutTask.cs b/src/Test/L1/Plugins/FakeCheckoutTask.cs index 8c944f92c1..888019ac9d 100644 --- a/src/Test/L1/Plugins/FakeCheckoutTask.cs +++ b/src/Test/L1/Plugins/FakeCheckoutTask.cs @@ -10,10 +10,10 @@ namespace Microsoft.VisualStudio.Services.Agent.Tests.L1.Worker public class FakeCheckoutTask : CheckoutTask { public FakeCheckoutTask() : base(new FakeSourceProviderFactory()) - {} + { } public FakeCheckoutTask(ISourceProviderFactory SourceProviderFactory) : base(new FakeSourceProviderFactory()) - {} + { } } public sealed class FakeSourceProviderFactory : SourceProviderFactory diff --git a/src/Test/L1/Worker/L1TestBase.cs b/src/Test/L1/Worker/L1TestBase.cs index 51929d71ce..13deb6fabe 100644 --- a/src/Test/L1/Worker/L1TestBase.cs +++ b/src/Test/L1/Worker/L1TestBase.cs @@ -60,12 +60,12 @@ protected IList GetTimelineLogLines(TimelineRecord record) var lines = jobService.LogLines.GetValueOrDefault(record.Log.Id).ToList(); if (lines.Count <= 0) { - lines = new List(); - // Fall back to blobstore - foreach (var blobId in jobService.IdToBlobMapping.GetValueOrDefault(record.Log.Id)) - { - lines.AddRange(jobService.UploadedLogBlobs.GetValueOrDefault(blobId)); - } + lines = new List(); + // Fall back to blobstore + foreach (var blobId in jobService.IdToBlobMapping.GetValueOrDefault(record.Log.Id)) + { + lines.AddRange(jobService.UploadedLogBlobs.GetValueOrDefault(blobId)); + } } return lines; } @@ -249,8 +249,8 @@ protected async Task RunWorker(Pipelines.AgentJobRequestMessage mes using (var cts = new CancellationTokenSource()) { - cts.CancelAfter((int)JobTimeout.TotalMilliseconds); - return await RunWorker(_l1HostContext, message, cts.Token); + cts.CancelAfter((int)JobTimeout.TotalMilliseconds); + return await RunWorker(_l1HostContext, message, cts.Token); } }