< Summary

Information
Class: MyNet.Platform.Windows.Registry.FileHistory.RegistryRecentFileRepository
Assembly: MyNet.Platform.Windows
File(s): https://raw.githubusercontent.com/sandre58/MyNet/5aaaab311aa14541478b9e402357d98b657a23e4/src/MyNet.Platform.Windows/Registry/FileHistory/RegistryRecentFileRepository.cs
Tag: 342_31701152804
Line coverage
97%
Covered lines: 80
Uncovered lines: 2
Coverable lines: 82
Total lines: 223
Line coverage: 97.5%
Branch coverage
82%
Covered branches: 23
Total branches: 28
Branch coverage: 82.1%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
GetAllAsync()100%22100%
AddAsync()83.33%6693.33%
UpdateAsync(...)100%22100%
RemoveAsync(...)100%22100%
ClearAsync()100%22100%
MapToRecentFile(...)100%11100%
MapToRegistryRecentFileEntry(...)50%22100%
NormalizeExtension(...)100%11100%
GetExtension(...)50%22100%
CleanupAsync(...)75%4492.3%
GetExtensionRegistryPath(...)100%11100%
FindRegistryEntry(...)50%22100%
FindByPath(...)100%44100%

File(s)

https://raw.githubusercontent.com/sandre58/MyNet/5aaaab311aa14541478b9e402357d98b657a23e4/src/MyNet.Platform.Windows/Registry/FileHistory/RegistryRecentFileRepository.cs

#LineLine coverage
 1// -----------------------------------------------------------------------
 2// <copyright file="RegistryRecentFileRepository.cs" company="Stéphane ANDRE">
 3// Copyright (c) Stéphane ANDRE. All rights reserved.
 4// </copyright>
 5// -----------------------------------------------------------------------
 6
 7using System;
 8using System.Collections.Generic;
 9using System.IO;
 10using System.Linq;
 11using System.Runtime.Versioning;
 12using System.Threading.Tasks;
 13using MyNet.IO.FileHistory;
 14using MyNet.IO.Registry;
 15
 16namespace MyNet.Platform.Windows.Registry.FileHistory;
 17
 18/// <summary>
 19/// Implementation of <see cref="IRecentFileRepository"/> that uses the Windows Registry to store recent file entries.
 20/// </summary>
 21/// <param name="registryService">The registry service used to interact with the Windows Registry.</param>
 22/// <param name="options">The options for configuring the recent files repository.</param>
 23[SupportedOSPlatform("windows")]
 24public sealed class RegistryRecentFileRepository(IRegistryService registryService, RecentFilesOptions options) : IRecent
 25{
 3026    private readonly HashSet<string> _supportedExtensions =
 3027        [with(options.SupportedExtensions.Select(NormalizeExtension), StringComparer.OrdinalIgnoreCase)];
 28
 29    /// <inheritdoc/>
 30    public Task<IReadOnlyList<RecentFile>> GetAllAsync()
 31    {
 932        var result = new List<RecentFile>();
 33
 5434        foreach (var entries in _supportedExtensions.Select(GetExtensionRegistryPath).Select(registryService.GetAll<Regi
 35        {
 1836            result.AddRange(entries.Select(x => MapToRecentFile(x.Item)));
 37        }
 38
 939        return Task.FromResult<IReadOnlyList<RecentFile>>(result);
 40    }
 41
 42    /// <inheritdoc/>
 43    public async Task<RecentFile?> AddAsync(RecentFile file)
 44    {
 3945        var extension = GetExtension(file.Path);
 46
 3947        if (extension is null)
 048            return null;
 49
 3950        if (!_supportedExtensions.Contains(extension))
 351            return null;
 52
 3653        var existing = FindByPath(file.Path);
 54
 3655        if (existing is not null)
 56        {
 357            existing = existing with { LastAccessedAt = DateTimeOffset.UtcNow };
 58
 359            return await UpdateAsync(existing).ConfigureAwait(false);
 60        }
 61
 3362        var entry = MapToRegistryRecentFileEntry(file);
 63
 3364        var registryEntry = new RegistryEntry<RegistryRecentFileEntry>(GetExtensionRegistryPath(extension), entry);
 65
 3366        registryService.AddOrUpdate(registryEntry);
 67
 3368        await CleanupAsync(extension).ConfigureAwait(false);
 69
 3370        return file;
 3971    }
 72
 73    /// <inheritdoc/>
 74    public Task<RecentFile?> UpdateAsync(RecentFile file)
 75    {
 976        var existing = FindRegistryEntry(file.Path);
 77
 978        if (existing is null)
 379            return Task.FromResult<RecentFile?>(null);
 80
 681        registryService.AddOrUpdate(new RegistryEntry<RegistryRecentFileEntry>(existing.Path, MapToRegistryRecentFileEnt
 82
 683        return Task.FromResult<RecentFile?>(file);
 84    }
 85
 86    /// <inheritdoc/>
 87    public Task<bool> RemoveAsync(string path)
 88    {
 689        var existing = FindRegistryEntry(path);
 90
 691        if (existing is null)
 392            return Task.FromResult(false);
 93
 394        registryService.Remove(existing.Path);
 95
 396        return Task.FromResult(true);
 97    }
 98
 99    /// <inheritdoc/>
 100    public Task ClearAsync()
 101    {
 18102        foreach (var entry in _supportedExtensions.Select(GetExtensionRegistryPath).Select(registryService.GetAll<Regist
 103        {
 6104            registryService.Remove(entry.Path);
 105        }
 106
 3107        return Task.CompletedTask;
 108    }
 109
 110    /// <summary>
 111    /// Maps a <see cref="RegistryRecentFileEntry"/> to a <see cref="RecentFile"/> instance.
 112    /// </summary>
 113    /// <param name="entry">The registry entry to map.</param>
 114    /// <returns>A <see cref="RecentFile"/> instance.</returns>
 115    private static RecentFile MapToRecentFile(RegistryRecentFileEntry entry)
 15116        => new()
 15117        {
 15118            Name = entry.Name,
 15119            Path = entry.Path,
 15120            IsPinned = entry.IsPinned,
 15121            IsRecovered = entry.IsRecovered,
 15122            LastAccessedAt = DateTimeOffset.FromFileTime(
 15123                entry.LastAccessUtc)
 15124        };
 125
 126    /// <summary>
 127    /// Maps a <see cref="RecentFile"/> to a <see cref="RegistryRecentFileEntry"/> instance for storage in the registry.
 128    /// </summary>
 129    /// <param name="file">The recent file to map.</param>
 130    /// <returns>A <see cref="RegistryRecentFileEntry"/> instance.</returns>
 131    private static RegistryRecentFileEntry MapToRegistryRecentFileEntry(RecentFile file)
 39132        => new()
 39133        {
 39134            Name = file.Name,
 39135            Path = file.Path,
 39136            IsPinned = file.IsPinned,
 39137            IsRecovered = file.IsRecovered,
 39138            LastAccessUtc =
 39139                file.LastAccessedAt?.UtcDateTime.ToFileTimeUtc() ?? 0
 39140        };
 141
 142    /// <summary>
 143    /// Normalizes a file extension by trimming whitespace and leading dots, ensuring consistent formatting for registry
 144    /// </summary>
 145    /// <param name="extension">The file extension to normalize.</param>
 146    /// <returns>The normalized file extension.</returns>
 150147    private static string NormalizeExtension(string extension) => extension.Trim().TrimStart('.');
 148
 149    /// <summary>
 150    /// Extracts and normalizes the file extension from a given file path. If the path does not have an extension, retur
 151    /// </summary>
 152    /// <param name="path">The file path to extract the extension from.</param>
 153    /// <returns>The normalized file extension, or null if the path does not have an extension.</returns>
 154    private static string? GetExtension(string path)
 155    {
 90156        var extension = Path.GetExtension(path);
 157
 90158        return string.IsNullOrWhiteSpace(extension)
 90159            ? null
 90160            : NormalizeExtension(extension);
 161    }
 162
 163    /// <summary>
 164    /// Cleans up old entries for a given file extension, ensuring that the number of recent file entries does not excee
 165    /// </summary>
 166    /// <param name="extension">The file extension for which to clean up old entries.</param>
 167    /// <returns>A task representing the asynchronous cleanup operation.</returns>
 168    private Task CleanupAsync(string extension)
 169    {
 33170        if (options.MaxEntries <= 0)
 0171            return Task.CompletedTask;
 172
 33173        var entries = registryService
 33174            .GetAll<RegistryRecentFileEntry>(GetExtensionRegistryPath(extension))
 33175            .ToList();
 176
 33177        var removable = entries
 33178            .Where(x => x.Item is { IsPinned: false, IsRecovered: false })
 33179            .OrderByDescending(x => x.Item.LastAccessUtc)
 33180            .Skip(options.MaxEntries)
 33181            .ToList();
 182
 72183        foreach (var item in removable)
 3184            registryService.Remove(item.Path);
 185
 33186        return Task.CompletedTask;
 187    }
 188
 189    /// <summary>
 190    /// Constructs the registry path for a given file extension by combining the base path from options with the normali
 191    /// </summary>
 192    /// <param name="extension">The file extension for which to construct the registry path.</param>
 193    /// <returns>The constructed registry path for the specified file extension.</returns>
 141194    private RegistryPath GetExtensionRegistryPath(string extension) => RegistryPath.Combine(options.BasePath, extension)
 195
 196    /// <summary>
 197    /// Finds a registry entry for a given file path by searching through the registry entries for the corresponding fil
 198    /// </summary>
 199    /// <param name="path">The file path for which to find the registry entry.</param>
 200    /// <returns>The registry entry for the specified file path, or null if no match is found.</returns>
 201    private RegistryEntry<RegistryRecentFileEntry>? FindRegistryEntry(string path)
 202    {
 51203        var extension = GetExtension(path);
 204
 51205        return extension is null
 51206            ? null
 51207            : registryService
 51208                .GetAll<RegistryRecentFileEntry>(GetExtensionRegistryPath(extension))
 51209                .FirstOrDefault(x =>
 51210                    string.Equals(
 51211                        x.Item.Path,
 51212                        path,
 51213                        StringComparison.OrdinalIgnoreCase));
 214    }
 215
 216    /// <summary>
 217    /// Finds a recent file entry by its file path by first locating the corresponding registry entry and then mapping i
 218    /// </summary>
 219    /// <param name="path">The file path for which to find the recent file entry.</param>
 220    /// <returns>The recent file entry for the specified path, or null if no match is found.</returns>
 36221    private RecentFile? FindByPath(string path) => FindRegistryEntry(path)?.Item is { } item ? MapToRecentFile(item) : n
 222}
 223