Skip to content

Commit

Permalink
various improvements and code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Peter-Juhasz committed Jan 1, 2025
1 parent 910515d commit 502c283
Show file tree
Hide file tree
Showing 9 changed files with 39 additions and 49 deletions.
12 changes: 4 additions & 8 deletions src/PhotoArchiver.Console/Logging/FileLoggerProvider.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Threading;

namespace PhotoArchiver.Logging;

Expand Down Expand Up @@ -31,16 +32,11 @@ public ILogger CreateLogger(string categoryName)
public void Dispose() { }


private sealed class FileLogger : ILogger
private sealed class FileLogger(string fileName) : ILogger
{
public FileLogger(string fileName)
{
FileName = fileName;
}

public string FileName { get; }
public string FileName { get; } = fileName;

private static readonly object SyncRoot = new();
private static readonly Lock SyncRoot = new();

private static readonly IDisposable Scope = new NullScope();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,8 @@ public WindowsTaskbarProgressIndicator()

public void Initialize(long allBytes, long allItems)
{
if (allBytes < 0)
{
throw new ArgumentOutOfRangeException(nameof(allBytes));
}

if (allItems < 0)
{
throw new ArgumentOutOfRangeException(nameof(allItems));
}
ArgumentOutOfRangeException.ThrowIfNegative(allBytes);
ArgumentOutOfRangeException.ThrowIfNegative(allItems);

AllBytes = allBytes;
TaskbarProgress.SetState(WindowHandle, TaskbarProgress.TaskbarStates.Normal);
Expand All @@ -46,10 +39,7 @@ public void ToIndeterminateState()

public void SetBytesProgress(long processed)
{
if (processed < 0)
{
throw new ArgumentOutOfRangeException(nameof(processed));
}
ArgumentOutOfRangeException.ThrowIfNegative(processed);

if (processed > AllBytes)
{
Expand Down
6 changes: 3 additions & 3 deletions src/PhotoArchiver/Archiver.Download.cs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ private async Task<DownloadResult> DownloadCoreAsync(IFile file, BlobItem blob,
// compute downloaded file hash
using var verifyStream = await file.OpenReadAsync(cancellationToken);
using var hashAlgorithm = MD5.Create();
var hash = hashAlgorithm.ComputeHash(verifyStream);
var hash = await hashAlgorithm.ComputeHashAsync(verifyStream, cancellationToken);

// compare
if (!blobHash.AsSpan().SequenceEqual(hash))
Expand All @@ -243,7 +243,7 @@ private async Task<DownloadResult> DownloadCoreAsync(IFile file, BlobItem blob,

private static bool Match(BlobItem blob, DownloadOptions options)
{
if (options.Tags?.Any() ?? false)
if (options.Tags?.Count > 0)
{
if (blob.Metadata.TryGetValue("Tags", out var tags))
{
Expand All @@ -255,7 +255,7 @@ private static bool Match(BlobItem blob, DownloadOptions options)
}
}

if (options.People?.Any() ?? false)
if (options.People?.Count > 0)
{
if (blob.Metadata.TryGetValue("People", out var people))
{
Expand Down
22 changes: 14 additions & 8 deletions src/PhotoArchiver/Archiver.Upload.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,24 @@ namespace PhotoArchiver;

using Progress;
using Storage;
using System.Threading;
using Thumbnails;
using Upload;

public partial class Archiver
{
public async Task<ArchiveResult> ArchiveAsync(IDirectory directory, IProgressIndicator progressIndicator, CancellationToken cancellationToken)
{
var files = directory.GetFilesAsync(cancellationToken);
var query = files;

// set up filter
var matcher = new Matcher().AddInclude(Options.SearchPattern);
var files = await directory.GetFilesAsync(cancellationToken);
if (Options.SearchPattern != null)
{
var matcher = new Matcher().AddInclude(Options.SearchPattern);
query = query.Where(f => matcher.Match(directory.Path, f.Path).HasMatches);
}

var query = files.Where(f => matcher.Match(directory.Path, f.Path).HasMatches)
.OrderBy(f => f.Path)
query = query.OrderBy(f => f.Path)
.Where(f => !IgnoredFileNames.Contains(f.Name))
.Where(f => !IgnoredExtensions.Contains(f.GetExtension()));

Expand All @@ -47,7 +51,7 @@ public async Task<ArchiveResult> ArchiveAsync(IDirectory directory, IProgressInd
query = query.Take(Options.Take.Value);
}

return await ArchiveAsync(query.ToList(), progressIndicator, cancellationToken);
return await ArchiveAsync(await query.ToListAsync(cancellationToken), progressIndicator, cancellationToken);
}

[SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "<Pending>")]
Expand All @@ -66,7 +70,9 @@ public async Task<ArchiveResult> ArchiveAsync(IReadOnlyList<IFile> files, IProgr
var processedBytes = 0L;
var allBytes = 0L;
foreach (var f in files)
{
allBytes += await f.GetSizeAsync(cancellationToken);
}

// enumerate files in directory
progressIndicator.Initialize(allBytes, files.Count);
Expand Down Expand Up @@ -349,10 +355,10 @@ public async Task<ArchiveResult> ArchiveAsync(IReadOnlyList<IFile> files, IProgr
// check for exists
Logger.LogTrace($"Checking for {blob} exists...");
CostEstimator.AddOther();
if (await blob.ExistsAsync())
if (await blob.ExistsAsync(cancellationToken))
{
Logger.LogTrace($"Fetching attributes for {blob}...");
var properties = (await blob.GetPropertiesAsync()).Value;
var properties = (await blob.GetPropertiesAsync(cancellationToken: cancellationToken)).Value;
CostEstimator.AddOther();

// compare file size
Expand Down
2 changes: 1 addition & 1 deletion src/PhotoArchiver/Files/IDirectory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ public interface IDirectory

string Path { get; }

Task<IReadOnlyList<IFile>> GetFilesAsync(CancellationToken cancellationToken);
IAsyncEnumerable<IFile> GetFilesAsync(CancellationToken cancellationToken);

Task<IFile> GetFileAsync(string name, CancellationToken cancellationToken);

Expand Down
13 changes: 10 additions & 3 deletions src/PhotoArchiver/Files/SystemIODirectory.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
namespace PhotoArchiver.Files;
using System.Runtime.CompilerServices;

namespace PhotoArchiver.Files;

public class SystemIODirectory : IDirectory
{
Expand Down Expand Up @@ -31,8 +33,13 @@ public Task<IFile> GetFileAsync(string name, CancellationToken cancellationToken
return Task.FromResult(new SystemIOFile(new FileInfo(System.IO.Path.Combine(Directory.FullName, name))) as IFile);
}

public Task<IReadOnlyList<IFile>> GetFilesAsync(CancellationToken cancellationToken)
#pragma warning disable CS1998
public async IAsyncEnumerable<IFile> GetFilesAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
return Task.FromResult(Directory.GetFiles("*", SearchOption.AllDirectories).Select(f => new SystemIOFile(f)).ToList() as IReadOnlyList<IFile>);
foreach (var fileInfo in Directory.GetFiles("*", SearchOption.AllDirectories))
{
yield return new SystemIOFile(fileInfo);
}
}
#pragma warning restore CS1998
}
13 changes: 2 additions & 11 deletions src/PhotoArchiver/Progress/StorageProgressShim.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,9 @@
namespace PhotoArchiver.Progress;

public sealed class StorageProgressShim : IProgress<long>
public sealed record StorageProgressShim(IProgressIndicator ProgressIndicator, long SnapshotBytes) : IProgress<long>
{
public StorageProgressShim(IProgressIndicator progressIndicator, long snaphotBytes)
{
ProgressIndicator = progressIndicator;
SnaphotBytes = snaphotBytes;
}

public IProgressIndicator ProgressIndicator { get; }
public long SnaphotBytes { get; }

public void Report(long value)
{
ProgressIndicator.SetBytesProgress(SnaphotBytes + value);
ProgressIndicator.SetBytesProgress(SnapshotBytes + value);
}
}
2 changes: 1 addition & 1 deletion src/PhotoArchiver/Thumbnails/ThumbnailOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class ThumbnailOptions
public bool Force { get; set; } = false;


public bool IsEnabled() => MaxWidth != null && MaxHeight != null;
public bool IsEnabled() => this is { MaxHeight: > 0, MaxWidth: > 0 };


[SuppressMessage("Usage", "CA2208:Instantiate argument exceptions correctly", Justification = "<Pending>")]
Expand Down
2 changes: 1 addition & 1 deletion src/PhotoArchiver/Upload/UploadResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@ public enum UploadResult

public static partial class UploadResultExtensions
{
public static bool IsSuccessful(this UploadResult result) => result == UploadResult.Uploaded || result == UploadResult.AlreadyExists;
public static bool IsSuccessful(this UploadResult result) => result is UploadResult.Uploaded or UploadResult.AlreadyExists;
}

0 comments on commit 502c283

Please sign in to comment.