Files
Cleanuparr/code/backend/Cleanuparr.Shared/Helpers/PathHelper.cs
2026-05-27 19:26:39 +03:00

53 lines
2.2 KiB
C#

namespace Cleanuparr.Shared.Helpers;
/// <summary>
/// Helpers for working with file system paths.
/// </summary>
public static class PathHelper
{
/// <summary>
/// Remaps a file path by replacing a source directory prefix with a target directory prefix.
/// Checks path-segment boundaries to avoid false matches
/// (e.g. source "/downloads" does not match "/downloads-other/file.mkv").
/// </summary>
/// <param name="filePath">The file path to remap.</param>
/// <param name="source">The directory prefix to replace (e.g. "/downloads").</param>
/// <param name="target">The replacement directory prefix (e.g. "/mnt/media").</param>
/// <returns>The remapped path, or <paramref name="filePath"/> unchanged if no match.</returns>
public static string RemapPath(string filePath, string? source, string? target)
{
if (string.IsNullOrEmpty(source) || string.IsNullOrEmpty(target))
{
return filePath;
}
// Normalize separators so Windows source paths (backslashes) match Linux-normalized filePaths
var normSource = source.Replace('\\', Path.DirectorySeparatorChar).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
var normTarget = target.TrimEnd('/', '\\');
// Exact match: filePath is exactly the source directory (no trailing separator)
if (filePath.Equals(normSource.TrimEnd(Path.DirectorySeparatorChar), StringComparison.OrdinalIgnoreCase))
{
return normTarget;
}
// Prefix match with path-segment boundary: filePath starts with "source/"
if (filePath.StartsWith(normSource, StringComparison.OrdinalIgnoreCase))
{
return normTarget + Path.DirectorySeparatorChar + filePath[normSource.Length..];
}
return filePath;
}
/// <summary>
/// Normalizes path separators to the host's <see cref="Path.DirectorySeparatorChar"/> and then
/// applies <see cref="RemapPath"/>.
/// </summary>
public static string NormalizeAndRemap(string path, string? source, string? target)
{
string normalized = string.Join(Path.DirectorySeparatorChar, path.Split(['\\', '/']));
return RemapPath(normalized, source, target);
}
}