Fix default output dir, enable nullables, fix compiler warnings

This commit is contained in:
Konstantin Safonov 2023-10-13 13:36:38 +03:00
parent 08256f0abe
commit 00000db63c
No known key found for this signature in database
GPG Key ID: EBC01B465FCF8665
6 changed files with 75 additions and 46 deletions

View File

@ -11,13 +11,13 @@ internal class BellsAndWhistles
{ {
private static readonly string assemblyEnvironment = string.Format("[{1}, {0}]", RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant(), RuntimeInformation.FrameworkDescription); private static readonly string assemblyEnvironment = string.Format("[{1}, {0}]", RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant(), RuntimeInformation.FrameworkDescription);
private static readonly Assembly entryAssembly = Assembly.GetEntryAssembly(); private static readonly Assembly entryAssembly = Assembly.GetEntryAssembly()!;
private static readonly string assemblyVersion = entryAssembly.GetName().Version.ToString(); private static readonly string assemblyVersion = entryAssembly.GetName().Version!.ToString();
private static readonly string fileVersion = entryAssembly.GetCustomAttribute<AssemblyFileVersionAttribute>().Version; private static readonly string fileVersion = entryAssembly.GetCustomAttribute<AssemblyFileVersionAttribute>()!.Version;
private static readonly string assemblyName = entryAssembly.GetCustomAttribute<AssemblyProductAttribute>().Product; private static readonly string assemblyName = entryAssembly.GetCustomAttribute<AssemblyProductAttribute>()!.Product;
const string assemblyBuildType = const string assemblyBuildType =
#if DEBUG #if DEBUG
"[Debug]" "[Debug]"
@ -31,7 +31,12 @@ internal class BellsAndWhistles
public static void ShowVersionInfo(ILogger logger) public static void ShowVersionInfo(ILogger logger)
{ {
logger.LogInformation($"{assemblyName} {assemblyVersion} {assemblyEnvironment} {assemblyBuildType}"); logger.LogInformation(
"{assemblyName} {assemblyVersion} {assemblyEnvironment} {assemblyBuildType}",
assemblyName,
assemblyVersion,
assemblyEnvironment,
assemblyBuildType);
Console.BackgroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.Black;
WriteColorLine("%╔═╦═══════════════════════════════════════════════════════════════════════════════════════╦═╗"); WriteColorLine("%╔═╦═══════════════════════════════════════════════════════════════════════════════════════╦═╗");
WriteColorLine("%╠═╝ .''. %╚═%╣"); WriteColorLine("%╠═╝ .''. %╚═%╣");

View File

@ -16,12 +16,15 @@ using System.Threading.Tasks;
internal class DownloaderService : IHostedService internal class DownloaderService : IHostedService
{ {
private static readonly JsonSerializerOptions jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly ILogger<DownloaderService> logger; private readonly ILogger<DownloaderService> logger;
private readonly DownloaderOptions options; private readonly DownloaderOptions options;
private readonly HttpClient client; private readonly HttpClient client;
private readonly IHostApplicationLifetime hostApplicationLifetime; private readonly IHostApplicationLifetime hostApplicationLifetime;
public DownloaderService(IHostApplicationLifetime hostApplicationLifetime, ILogger<DownloaderService> logger, HttpClient client, DownloaderOptions options) public DownloaderService(IHostApplicationLifetime hostApplicationLifetime, ILogger<DownloaderService> logger, HttpClient client, DownloaderOptions options)
{ {
this.logger = logger; this.logger = logger;
@ -87,15 +90,12 @@ internal class DownloaderService : IHostedService
this.hostApplicationLifetime.StopApplication(); this.hostApplicationLifetime.StopApplication();
} }
private async Task<(string json, IDictionary<string, ResponseItem[]> versions)> GetJson(string feedUrl, string productVersion = null, CancellationToken cancellationToken = default) private async Task<(string json, IDictionary<string, ResponseItem[]> versions)> GetJson(string feedUrl, string? productVersion = null, CancellationToken cancellationToken = default)
{ {
var atlassianJson = await this.client.GetStringAsync(feedUrl, cancellationToken).ConfigureAwait(false); var atlassianJson = await this.client.GetStringAsync(feedUrl, cancellationToken).ConfigureAwait(false);
var json = atlassianJson.Trim()["downloads(".Length..^1]; var json = atlassianJson.Trim()["downloads(".Length..^1];
this.logger.LogTrace($"Downloaded json: {0}", json); this.logger.LogTrace("Downloaded json: {json}", json);
var parsed = JsonSerializer.Deserialize<ResponseItem[]>(json, new JsonSerializerOptions var parsed = JsonSerializer.Deserialize<ResponseItem[]>(json, jsonOptions)!;
{
PropertyNameCaseInsensitive = true
});
this.logger.LogDebug("Found {releaseCount} releases", parsed.Length); this.logger.LogDebug("Found {releaseCount} releases", parsed.Length);
var versions = parsed var versions = parsed
.GroupBy(a => a.Version) .GroupBy(a => a.Version)
@ -112,7 +112,6 @@ internal class DownloaderService : IHostedService
private async Task DownloadFilesFromFeed(string feedUrl, IDictionary<string, ResponseItem[]> versions, CancellationToken cancellationToken) private async Task DownloadFilesFromFeed(string feedUrl, IDictionary<string, ResponseItem[]> versions, CancellationToken cancellationToken)
{ {
var feedDir = Path.Combine(this.options.OutputDir, feedUrl[(feedUrl.LastIndexOf('/') + 1)..feedUrl.LastIndexOf('.')]); var feedDir = Path.Combine(this.options.OutputDir, feedUrl[(feedUrl.LastIndexOf('/') + 1)..feedUrl.LastIndexOf('.')]);
this.logger.LogInformation("Download from JSON \"{feedUrl}\" started", feedUrl); this.logger.LogInformation("Download from JSON \"{feedUrl}\" started", feedUrl);
foreach (var version in versions) foreach (var version in versions)
@ -137,12 +136,10 @@ internal class DownloaderService : IHostedService
if (file.ZipUrl == null) if (file.ZipUrl == null)
{ {
this.logger.LogWarning($"Empty ZipUrl found for version '{version.Key}' in {feedUrl}"); this.logger.LogWarning("Empty ZipUrl found for version '{version}' in {feedUrl}", version.Key, feedUrl);
continue; continue;
} }
var serverPath = file.ZipUrl.PathAndQuery; var serverPath = file.ZipUrl.PathAndQuery;
var outputFile = Path.Combine(directory, serverPath[(serverPath.LastIndexOf('/') + 1)..]); var outputFile = Path.Combine(directory, serverPath[(serverPath.LastIndexOf('/') + 1)..]);
if (!File.Exists(outputFile)) if (!File.Exists(outputFile))
@ -153,58 +150,64 @@ internal class DownloaderService : IHostedService
{ {
if (this.options.SkipFileCheck == false) if (this.options.SkipFileCheck == false)
{ {
this.logger.LogWarning($"File \"{outputFile}\" already exists. File sizes will be compared."); this.logger.LogWarning("File \"{outputFile}\" already exists. File sizes will be compared.", outputFile);
var localFileSize = new FileInfo(outputFile).Length; var localFileSize = new FileInfo(outputFile).Length;
this.logger.LogInformation($"Size of local file is {localFileSize} bytes."); this.logger.LogInformation("Size of local file is {localFileSize} bytes.", localFileSize);
try try
{ {
var httpClient = new HttpClient(); var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("User-Agent", options.UserAgent); httpClient.DefaultRequestHeaders.Add("User-Agent", options.UserAgent);
var response = await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, file.ZipUrl)); var response = await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, file.ZipUrl), cancellationToken);
if (response.IsSuccessStatusCode) if (response.IsSuccessStatusCode)
{ {
if (response.Content.Headers.ContentLength.HasValue) if (response.Content.Headers.ContentLength.HasValue)
{ {
var remoteFileSize = response.Content.Headers.ContentLength.Value; var remoteFileSize = response.Content.Headers.ContentLength.Value;
this.logger.LogInformation($"Size of remote file is \"{remoteFileSize}\" bytes."); this.logger.LogInformation("Size of remote file is \"{remoteFileSize}\" bytes.", remoteFileSize);
if (remoteFileSize == localFileSize) if (remoteFileSize == localFileSize)
{ {
this.logger.LogInformation($"Size of remote and local files and are same ({remoteFileSize} bytes and {localFileSize} bytes). Nothing to download. Operation skipped."); this.logger.LogInformation(
"Size of remote and local files and are same ({remoteFileSize} bytes and {localFileSize} bytes). Nothing to download. Operation skipped.",
remoteFileSize,
localFileSize);
} }
else else
{ {
this.logger.LogWarning($"Size of remote and local files and are not same ({remoteFileSize} bytes and {localFileSize} bytes). Download started."); this.logger.LogWarning(
"Size of remote and local files and are not same ({remoteFileSize} bytes and {localFileSize} bytes). Download started.",
remoteFileSize,
localFileSize);
File.Delete(outputFile); File.Delete(outputFile);
await this.DownloadFile(file, outputFile, cancellationToken).ConfigureAwait(false); await this.DownloadFile(file, outputFile, cancellationToken).ConfigureAwait(false);
} }
} }
else else
{ {
this.logger.LogWarning($"Cant get size of remote file \"{file.ZipUrl}\". May be server not support it feature. Sorry."); this.logger.LogWarning("Cant get size of remote file \"{uri}\". May be server not support it feature. Sorry.", file.ZipUrl);
continue; continue;
} }
} }
else else
{ {
this.logger.LogCritical($"Request execution error: \"{response.StatusCode}\". Sorry."); this.logger.LogError("Request execution error for {uri}: \"{statusCode}\". Sorry.", file.ZipUrl, response.StatusCode);
} }
} }
catch (HttpRequestException ex) catch (HttpRequestException ex)
{ {
this.logger.LogCritical($"HTTP request error: \"{ex.Message}\", \"{ex.StackTrace}\", \"{ex.StatusCode}\". Sorry."); this.logger.LogError(ex, "HTTP request error for {uri}: \"{message}\", \"{statusCode}\". Sorry.", file.ZipUrl, ex.Message, ex.StatusCode);
}
} }
}
else else
{ {
logger.LogWarning($"File \"{outputFile}\" already exists. Download from \"{file.ZipUrl}\" skipped."); logger.LogWarning("File \"{outputFile}\" already exists. Download from \"{uri}\" skipped.", outputFile, file.ZipUrl);
continue; continue;
} }
} }
} }
} }
this.logger.LogInformation($"All files from \"{feedUrl}\" successfully downloaded."); this.logger.LogInformation("All files from \"{feedUrl}\" successfully downloaded.", feedUrl);
} }
@ -230,14 +233,13 @@ internal class DownloaderService : IHostedService
} }
catch (Exception removeEx) catch (Exception removeEx)
{ {
this.logger.LogError(removeEx, $"Failed to remove incomplete file \"{outputFile}\"."); this.logger.LogError(removeEx, "Failed to remove incomplete file \"{outputFile}\".", outputFile);
} }
} }
this.logger.LogInformation($"File \"{file.ZipUrl}\" successfully downloaded to \"{outputFile}\"."); this.logger.LogInformation("File \"{uri}\" successfully downloaded to \"{outputFile}\".", file.ZipUrl, outputFile);
} }
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
public async Task StopAsync(CancellationToken cancellationToken) { } public async Task StopAsync(CancellationToken cancellationToken) { }
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously

View File

@ -1,4 +1,11 @@
namespace EpicMorg.Atlassian.Downloader; namespace EpicMorg.Atlassian.Downloader;
using System; using System;
public record DownloaderOptions(string OutputDir, Uri[] CustomFeed, DownloadAction Action, bool Version, string ProductVersion, bool SkipFileCheck, string UserAgent) { } public record DownloaderOptions(
string OutputDir,
Uri[]? CustomFeed,
DownloadAction Action,
bool Version,
string? ProductVersion,
bool SkipFileCheck,
string UserAgent) { }

View File

@ -4,16 +4,16 @@ using System;
public partial class ResponseItem public partial class ResponseItem
{ {
public string Description { get; set; } public string? Description { get; set; }
public string Edition { get; set; } public string? Edition { get; set; }
public Uri ZipUrl { get; set; } public Uri? ZipUrl { get; set; }
public object TarUrl { get; set; } public object? TarUrl { get; set; }
public string Md5 { get; set; } public string? Md5 { get; set; }
public string Size { get; set; } public string? Size { get; set; }
public string Released { get; set; } public string? Released { get; set; }
public string Type { get; set; } public string? Type { get; set; }
public string Platform { get; set; } public string? Platform { get; set; }
public string Version { get; set; } public required string Version { get; set; }
public Uri ReleaseNotes { get; set; } public Uri? ReleaseNotes { get; set; }
public Uri UpgradeNotes { get; set; } public Uri? UpgradeNotes { get; set; }
} }

View File

@ -24,7 +24,14 @@ public class Program
/// <param name="productVersion">Override target version to download some product. Advice: Use it with "customFeed".</param> /// <param name="productVersion">Override target version to download some product. Advice: Use it with "customFeed".</param>
/// <param name="skipFileCheck">Skip compare of file sizes if a local file already exists. Existing file will be skipped to check and redownload.</param> /// <param name="skipFileCheck">Skip compare of file sizes if a local file already exists. Existing file will be skipped to check and redownload.</param>
/// <param name="userAgent">Set custom user agent via this feature flag.</param> /// <param name="userAgent">Set custom user agent via this feature flag.</param>
static async Task Main(string outputDir, Uri[] customFeed = null, DownloadAction action = DownloadAction.Download, bool about = false, string productVersion = null, bool skipFileCheck = false, string userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:101.0) Gecko/20100101 Firefox/101.0") => await static async Task Main(
string? outputDir = default,
Uri[]? customFeed = null,
DownloadAction action = DownloadAction.Download,
bool about = false,
string? productVersion = null,
bool skipFileCheck = false,
string userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:101.0) Gecko/20100101 Firefox/101.0") => await
Host Host
.CreateDefaultBuilder() .CreateDefaultBuilder()
.ConfigureHostConfiguration(configHost => configHost.AddEnvironmentVariables()) .ConfigureHostConfiguration(configHost => configHost.AddEnvironmentVariables())
@ -46,7 +53,14 @@ public class Program
.AddSerilog(dispose: true); .AddSerilog(dispose: true);
}) })
.AddHostedService<DownloaderService>() .AddHostedService<DownloaderService>()
.AddSingleton(new DownloaderOptions(outputDir, customFeed, action, about, productVersion, skipFileCheck, userAgent)) .AddSingleton(new DownloaderOptions(
outputDir ?? Environment.CurrentDirectory,
customFeed,
action,
about,
productVersion,
skipFileCheck,
userAgent))
.AddHttpClient()) .AddHttpClient())
.RunConsoleAsync() .RunConsoleAsync()
.ConfigureAwait(false); .ConfigureAwait(false);

View File

@ -10,6 +10,7 @@
<RuntimeIdentifier>win-x64</RuntimeIdentifier> <RuntimeIdentifier>win-x64</RuntimeIdentifier>
<!--build props--> <!--build props-->
<Nullable>enable</Nullable>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<IsPackable>false</IsPackable> <IsPackable>false</IsPackable>