Skip to content
This repository has been archived by the owner on Jul 5, 2024. It is now read-only.

Commit

Permalink
Configure CA2007 and add ConfigureAwait(false) to every await in Squi…
Browse files Browse the repository at this point in the history
…rrelLib
  • Loading branch information
caesay committed Dec 31, 2021
1 parent ab6315c commit 0b8bcc1
Show file tree
Hide file tree
Showing 14 changed files with 75 additions and 68 deletions.
5 changes: 5 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_
dotnet_naming_symbols.constant_fields.applicable_kinds = field
dotnet_naming_symbols.constant_fields.applicable_accessibilities = *
dotnet_naming_symbols.constant_fields.required_modifiers = const
dotnet_diagnostic.CA2007.severity=warning
###############################
# C# Coding Conventions #
###############################
Expand Down Expand Up @@ -117,6 +118,10 @@ csharp_space_between_method_call_empty_parameter_list_parentheses = false
csharp_preserve_single_line_statements = true
csharp_preserve_single_line_blocks = true
insert_final_newline=false
dotnet_diagnostic.IL3000.severity=error
dotnet_diagnostic.IL3001.severity=error
dotnet_diagnostic.IL3002.severity=error
dotnet_diagnostic.IL3003.severity=error
###############################
# VB Coding Conventions #
###############################
Expand Down
6 changes: 3 additions & 3 deletions src/Squirrel/FileDownloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,10 @@ public async Task DownloadFile(string url, string targetFile, Action<int> progre

await this.WarnIfThrows(
async () => {
await wc.DownloadFileTaskAsync(failedUrl ?? url, targetFile);
await wc.DownloadFileTaskAsync(failedUrl ?? url, targetFile).ConfigureAwait(false);
progress(100);
},
"Failed downloading URL: " + (failedUrl ?? url));
"Failed downloading URL: " + (failedUrl ?? url)).ConfigureAwait(false);
} catch (Exception) {
// NB: Some super brain-dead services are case-sensitive yet
// corrupt case on upload. I can't even.
Expand All @@ -84,7 +84,7 @@ public async Task<byte[]> DownloadUrl(string url)
this.Log().Info("Downloading url: " + (failedUrl ?? url));

return await this.WarnIfThrows(() => wc.DownloadDataTaskAsync(failedUrl ?? url),
"Failed to download url: " + (failedUrl ?? url));
"Failed to download url: " + (failedUrl ?? url)).ConfigureAwait(false);
} catch (Exception) {
// NB: Some super brain-dead services are case-sensitive yet
// corrupt case on upload. I can't even.
Expand Down
8 changes: 4 additions & 4 deletions src/Squirrel/IUpdateManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -203,19 +203,19 @@ public static async Task<ReleaseEntry> UpdateApp(this IUpdateManager This, Actio

try {
updateInfo = await This.ErrorIfThrows(() => This.CheckForUpdate(ignoreDeltaUpdates, x => progress(x / 3)),
"Failed to check for updates");
"Failed to check for updates").ConfigureAwait(false);

await This.ErrorIfThrows(() =>
This.DownloadReleases(updateInfo.ReleasesToApply, x => progress(x / 3 + 33)),
"Failed to download updates");
"Failed to download updates").ConfigureAwait(false);

await This.ErrorIfThrows(() =>
This.ApplyReleases(updateInfo, x => progress(x / 3 + 66)),
"Failed to apply updates");
"Failed to apply updates").ConfigureAwait(false);

await This.ErrorIfThrows(() =>
This.CreateUninstallerRegistryEntry(),
"Failed to set up uninstaller");
"Failed to set up uninstaller").ConfigureAwait(false);
} catch {
if (ignoreDeltaUpdates == false) {
ignoreDeltaUpdates = true;
Expand Down
16 changes: 8 additions & 8 deletions src/Squirrel/Internal/HelperExe.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public static async Task CompileWixTemplateToMsi(string wxsTarget, string output
try {
// Candle reprocesses and compiles WiX source files into object files (.wixobj).
var candleParams = new string[] { "-nologo", "-ext", "WixNetFxExtension", "-out", objFile, wxsTarget };
var processResult = await Utility.InvokeProcessAsync(WixCandlePath, candleParams, CancellationToken.None, workingDir);
var processResult = await Utility.InvokeProcessAsync(WixCandlePath, candleParams, CancellationToken.None, workingDir).ConfigureAwait(false);

if (processResult.Item1 != 0) {
var msg = String.Format(
Expand All @@ -101,7 +101,7 @@ public static async Task CompileWixTemplateToMsi(string wxsTarget, string output

// Light links and binds one or more .wixobj files and creates a Windows Installer database (.msi or .msm).
var lightParams = new string[] { "-ext", "WixNetFxExtension", "-spdb", "-sval", "-out", outputFile, objFile };
processResult = await Utility.InvokeProcessAsync(WixLightPath, lightParams, CancellationToken.None, workingDir);
processResult = await Utility.InvokeProcessAsync(WixLightPath, lightParams, CancellationToken.None, workingDir).ConfigureAwait(false);

if (processResult.Item1 != 0) {
var msg = String.Format(
Expand All @@ -118,7 +118,7 @@ public static async Task CompileWixTemplateToMsi(string wxsTarget, string output
public static async Task SetExeIcon(string exePath, string iconPath)
{
var args = new[] { Path.GetFullPath(exePath), "--set-icon", iconPath };
var processResult = await Utility.InvokeProcessAsync(RceditPath, args, CancellationToken.None);
var processResult = await Utility.InvokeProcessAsync(RceditPath, args, CancellationToken.None).ConfigureAwait(false);

if (processResult.ExitCode != 0) {
var msg = String.Format(
Expand Down Expand Up @@ -151,7 +151,7 @@ public static async Task SetPEVersionBlockFromPackageInfo(string exePath, Squirr
args.Add(Path.GetFullPath(iconPath));
}

var processResult = await Utility.InvokeProcessAsync(RceditPath, args, CancellationToken.None);
var processResult = await Utility.InvokeProcessAsync(RceditPath, args, CancellationToken.None).ConfigureAwait(false);

if (processResult.ExitCode != 0) {
var msg = String.Format(
Expand Down Expand Up @@ -183,7 +183,7 @@ public static async Task SignPEFile(string exePath, string signingOpts)
Log.Info("About to sign {0}", exePath);

var psi = Utility.CreateProcessStartInfo(SignToolPath, $"sign {signingOpts} \"{exePath}\"");
var processResult = await Utility.InvokeProcessUnsafeAsync(psi, CancellationToken.None);
var processResult = await Utility.InvokeProcessUnsafeAsync(psi, CancellationToken.None).ConfigureAwait(false);

if (processResult.ExitCode != 0) {
var optsWithPasswordHidden = new Regex(@"/p\s+\w+").Replace(signingOpts, "/p ********");
Expand All @@ -200,7 +200,7 @@ public static async Task NugetPack(string nuspecPath, string baseDirectory, stri
var args = new string[] { "pack", nuspecPath, "-BasePath", baseDirectory, "-OutputDirectory", outputDirectory };

Log.Info($"Packing '{baseDirectory}' into nupkg.");
var res = await Utility.InvokeProcessAsync(NugetPath, args, CancellationToken.None);
var res = await Utility.InvokeProcessAsync(NugetPath, args, CancellationToken.None).ConfigureAwait(false);

if (res.ExitCode != 0)
throw new Exception($"Failed nuget pack (exit {res.ExitCode}): \r\n " + res.StdOutput);
Expand All @@ -220,7 +220,7 @@ public static async Task ExtractZipToDirectory(string zipFilePath, string outFol

var psi = Utility.CreateProcessStartInfo(cmd, args);

var result = await Utility.InvokeProcessUnsafeAsync(psi, CancellationToken.None);
var result = await Utility.InvokeProcessUnsafeAsync(psi, CancellationToken.None).ConfigureAwait(false);
if (result.ExitCode != 0) throw new Exception(result.StdOutput);
} catch (Exception ex) {
Log.Error($"Failed to extract file {zipFilePath} to {outFolder}\n{ex.Message}");
Expand All @@ -242,7 +242,7 @@ public static async Task CreateZipFromDirectory(string zipFilePath, string inFol

var psi = Utility.CreateProcessStartInfo(cmd, args, inFolder);

var result = await Utility.InvokeProcessUnsafeAsync(psi, CancellationToken.None);
var result = await Utility.InvokeProcessUnsafeAsync(psi, CancellationToken.None).ConfigureAwait(false);
if (result.ExitCode != 0) throw new Exception(result.StdOutput);
} catch (Exception ex) {
Log.Error($"Failed to extract file {zipFilePath} to {inFolder}\n{ex.Message}");
Expand Down
14 changes: 7 additions & 7 deletions src/Squirrel/Internal/Utility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ public static async Task CopyToAsync(string from, string to)
}

// XXX: SafeCopy
await Task.Run(() => File.Copy(from, to, true));
await Task.Run(() => File.Copy(from, to, true)).ConfigureAwait(false);
}

public static void Retry(this Action block, int retries = 2, int retryDelay = 250)
Expand Down Expand Up @@ -270,11 +270,11 @@ await Task.Run(() => {
pi.Kill();
ct.ThrowIfCancellationRequested();
}
});
}).ConfigureAwait(false);

string textResult = await pi.StandardOutput.ReadToEndAsync();
string textResult = await pi.StandardOutput.ReadToEndAsync().ConfigureAwait(false);
if (String.IsNullOrWhiteSpace(textResult) || pi.ExitCode != 0) {
textResult = (textResult ?? "") + "\n" + await pi.StandardError.ReadToEndAsync();
textResult = (textResult ?? "") + "\n" + await pi.StandardError.ReadToEndAsync().ConfigureAwait(false);

if (String.IsNullOrWhiteSpace(textResult)) {
textResult = String.Empty;
Expand All @@ -296,7 +296,7 @@ from partition in Partitioner.Create(source).GetPartitions(degreeOfParallelism)
select Task.Run(async () => {
using (partition)
while (partition.MoveNext())
await body(partition.Current);
await body(partition.Current).ConfigureAwait(false);
}));
}

Expand Down Expand Up @@ -604,7 +604,7 @@ public static void LogIfThrows(this IFullLogger This, LogLevel level, string mes
public static async Task LogIfThrows(this IFullLogger This, LogLevel level, string message, Func<Task> block)
{
try {
await block();
await block().ConfigureAwait(false);
} catch (Exception ex) {
switch (level) {
case LogLevel.Debug:
Expand All @@ -627,7 +627,7 @@ public static async Task LogIfThrows(this IFullLogger This, LogLevel level, stri
public static async Task<T> LogIfThrows<T>(this IFullLogger This, LogLevel level, string message, Func<Task<T>> block)
{
try {
return await block();
return await block().ConfigureAwait(false);
} catch (Exception ex) {
switch (level) {
case LogLevel.Debug:
Expand Down
14 changes: 7 additions & 7 deletions src/Squirrel/Runtimes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,11 @@ protected RuntimeInfo(string id, string displayName)
/// <summary> Download the latest installer for this runtime to the specified file </summary>
public virtual async Task DownloadToFile(string localPath, Action<DownloadProgressChangedEventArgs> progress = null)
{
var url = await GetDownloadUrl();
var url = await GetDownloadUrl().ConfigureAwait(false);
Log.Info($"Downloading {Id} from {url} to {localPath}");
using var wc = Utility.CreateWebClient();
wc.DownloadProgressChanged += (s, e) => { progress?.Invoke(e); };
await wc.DownloadFileTaskAsync(url, localPath);
await wc.DownloadFileTaskAsync(url, localPath).ConfigureAwait(false);
}

/// <summary> Execute a runtime installer at a local file path. Typically used after <see cref="DownloadToFile"/> </summary>
Expand All @@ -93,7 +93,7 @@ public virtual async Task<RuntimeInstallResult> InvokeInstaller(string pathToIns
var args = new string[] { "/passive", "/norestart", "/showrmui" };
var quietArgs = new string[] { "/q", "/norestart" };
Log.Info($"Running {Id} installer '{pathToInstaller} {string.Join(" ", args)}'");
var p = await Utility.InvokeProcessAsync(pathToInstaller, isQuiet ? quietArgs : args, CancellationToken.None);
var p = await Utility.InvokeProcessAsync(pathToInstaller, isQuiet ? quietArgs : args, CancellationToken.None).ConfigureAwait(false);

// https://johnkoerner.com/install/windows-installer-error-codes/

Expand Down Expand Up @@ -186,7 +186,7 @@ public override async Task<bool> CheckIsInstalled()
{
switch (CpuArchitecture) {

case RuntimeCpu.X64: return await CheckIsInstalledX64();
case RuntimeCpu.X64: return await CheckIsInstalledX64().ConfigureAwait(false);
case RuntimeCpu.X86: return CheckIsInstalledX86();
default: return false;

Expand Down Expand Up @@ -234,7 +234,7 @@ private async Task<bool> CheckIsInstalledX64()
// return x64 results, so we can ask it as a last resort
try {
var token = new CancellationTokenSource(2000).Token;
var output = await Utility.InvokeProcessAsync("dotnet", new[] { "--info" }, token);
var output = await Utility.InvokeProcessAsync("dotnet", new[] { "--info" }, token).ConfigureAwait(false);
if (output.ExitCode != 0) return false;
return output.StdOutput.Contains("Microsoft.WindowsDesktop.App " + RequiredVersion);
} catch (Win32Exception wex) when (wex.HResult == -2147467259) {
Expand All @@ -261,7 +261,7 @@ private bool CheckIsInstalledInBaseDirectory(string baseDirectory)
/// <inheritdoc/>
public override async Task<string> GetDownloadUrl()
{
var latest = await GetLatestDotNetVersion(DotnetRuntimeType.WindowsDesktop, RequiredVersion);
var latest = await GetLatestDotNetVersion(DotnetRuntimeType.WindowsDesktop, RequiredVersion).ConfigureAwait(false);
var architecture = CpuArchitecture switch {
RuntimeCpu.X86 => "x86",
RuntimeCpu.X64 => "x64",
Expand All @@ -288,7 +288,7 @@ public static async Task<string> GetLatestDotNetVersion(DotnetRuntimeType runtim
};

using var wc = Utility.CreateWebClient();
return await wc.DownloadStringTaskAsync(new Uri($"{UncachedDotNetFeed}/{runtime}/{channel}/latest.version"));
return await wc.DownloadStringTaskAsync(new Uri($"{UncachedDotNetFeed}/{runtime}/{channel}/latest.version")).ConfigureAwait(false);
}

/// <summary>
Expand Down
Loading

0 comments on commit 0b8bcc1

Please sign in to comment.