mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 12:11:10 +00:00
Standardizes the remaining boolean names across the stack
This commit is contained in:
1 parent
3e0c3b624f
commit
39f4a04459
40 files changed
+1062
-448
No files matched your search
+46
-46
@@ -37,15 +37,15 @@ internal class DirectoryProviderService : IDirectoryProviderService
|
||||
/// Retrieves a list of subdirectory paths from the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path from which to retrieve the subdirectory paths.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of directory paths or an error.</returns>
|
||||
public Result<IEnumerable<FileSystemPathId>> GetSubdirectoryPaths(FileSystemPathId path, bool includeHiddenElements)
|
||||
public Result<IEnumerable<FileSystemPathId>> GetSubdirectoryPaths(FileSystemPathId path, bool shouldIncludeHiddenElements)
|
||||
{
|
||||
// check if the user has access permissions to the provided path
|
||||
// Check if the user has access permissions to the provided path.
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
return Result.From(_fileSystem.Directory.GetDirectories(path.Path)
|
||||
.Where(path => includeHiddenElements || (GetAttributes(path) & FileAttributes.Hidden) != FileAttributes.Hidden)
|
||||
.Where(path => shouldIncludeHiddenElements || (GetAttributes(path) & FileAttributes.Hidden) != FileAttributes.Hidden)
|
||||
.OrderBy(path => path)
|
||||
.Select(path => path.EndsWith(_fileSystem.Path.DirectorySeparatorChar) ? path : path + _fileSystem.Path.DirectorySeparatorChar)
|
||||
.Select(path => FileSystemPathId.Create(path))
|
||||
@@ -63,7 +63,7 @@ internal class DirectoryProviderService : IDirectoryProviderService
|
||||
{
|
||||
try
|
||||
{
|
||||
// File.GetAttributes is used for both directories and files
|
||||
// File.GetAttributes is used for both directories and files.
|
||||
return _fileSystem.File.GetAttributes(path);
|
||||
}
|
||||
catch
|
||||
@@ -101,7 +101,7 @@ internal class DirectoryProviderService : IDirectoryProviderService
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the optional last write time of <paramref name="path"/> if available, or an error.</returns>
|
||||
public Result<Optional<DateTime>> GetLastWriteTime(FileSystemPathId path)
|
||||
{
|
||||
// check if the user has access permissions to the provided path
|
||||
// Check if the user has access permissions to the provided path.
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
return Optional<DateTime>.FromNullable(_fileSystem.Directory.GetLastWriteTime(path.Path));
|
||||
@@ -114,7 +114,7 @@ internal class DirectoryProviderService : IDirectoryProviderService
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing the optional creation time of <paramref name="path"/> if available, or an error.</returns>
|
||||
public Result<Optional<DateTime>> GetCreationTime(FileSystemPathId path)
|
||||
{
|
||||
// check if the user has access permissions to the provided path
|
||||
// Check if the user has access permissions to the provided path.
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
return Optional<DateTime>.FromNullable(_fileSystem.Directory.GetCreationTime(path.Path));
|
||||
@@ -128,10 +128,10 @@ internal class DirectoryProviderService : IDirectoryProviderService
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the path of a created directory, or an error.</returns>
|
||||
public Result<FileSystemPathId> CreateDirectory(FileSystemPathId path, string name)
|
||||
{
|
||||
// to create a directory, its parent directory must be writable
|
||||
// To create a directory, its parent directory must be writable.
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Write, false))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
// create the directory and return its absolute path
|
||||
// Create the directory and return its absolute path.
|
||||
string directoryPath = _fileSystem.Directory.CreateDirectory(_fileSystem.Path.Combine(path.Path, name)).FullName;
|
||||
return FileSystemPathId.Create(directoryPath);
|
||||
}
|
||||
@@ -141,28 +141,28 @@ internal class DirectoryProviderService : IDirectoryProviderService
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">Identifier for the path where the directory to be copied is located.</param>
|
||||
/// <param name="destinationPath">Identifier for the path where the directory will be copied.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <param name="shouldOverrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the copied directory, or an error.</returns>
|
||||
public Result<FileSystemPathId> CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting)
|
||||
public Result<FileSystemPathId> CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool shouldOverrideExisting)
|
||||
{
|
||||
// check if the source directory exists
|
||||
// Check if the source directory exists.
|
||||
if (!_fileSystem.Directory.Exists(sourcePath.Path))
|
||||
return Errors.FileSystemManagement.DirectoryNotFound;
|
||||
string destPath = CreateUniqueDirectoryPath(destinationPath.Path);
|
||||
try
|
||||
{
|
||||
// create the new directory
|
||||
// Create the new directory.
|
||||
IDirectoryInfo destDirInfo = _fileSystem.DirectoryInfo.New(_fileSystem.Directory.CreateDirectory(destPath).FullName);
|
||||
// get the information of the source directory
|
||||
// Get the information of the source directory.
|
||||
IDirectoryInfo sourceDirInfo = _fileSystem.DirectoryInfo.New(sourcePath.Path);
|
||||
// copy all files
|
||||
// Copy all files.
|
||||
foreach (IFileInfo fileInfo in sourceDirInfo.GetFiles())
|
||||
{
|
||||
string targetFilePath = _fileSystem.Path.Combine(destPath, fileInfo.Name);
|
||||
fileInfo.CopyTo(targetFilePath, overrideExisting);
|
||||
_fileSystem.File.SetAttributes(targetFilePath, fileInfo.Attributes); // preserve file attributes
|
||||
fileInfo.CopyTo(targetFilePath, shouldOverrideExisting);
|
||||
_fileSystem.File.SetAttributes(targetFilePath, fileInfo.Attributes); // Preserve file attributes.
|
||||
}
|
||||
// copy all subdirectories
|
||||
// Copy all subdirectories.
|
||||
foreach (IDirectoryInfo subDirInfo in sourceDirInfo.GetDirectories())
|
||||
{
|
||||
Result<FileSystemPathId> newSourcePathResult = FileSystemPathId.Create(subDirInfo.FullName);
|
||||
@@ -171,8 +171,8 @@ internal class DirectoryProviderService : IDirectoryProviderService
|
||||
Result<FileSystemPathId> newDestinationPathResult = FileSystemPathId.Create(_fileSystem.Path.Combine(destPath, subDirInfo.Name));
|
||||
if (newDestinationPathResult.IsFailure)
|
||||
return newDestinationPathResult.Errors;
|
||||
// recursive call
|
||||
Result<FileSystemPathId> copySubDirResult = CopyDirectory(newSourcePathResult.Value, newDestinationPathResult.Value, overrideExisting);
|
||||
// Recursive call.
|
||||
Result<FileSystemPathId> copySubDirResult = CopyDirectory(newSourcePathResult.Value, newDestinationPathResult.Value, shouldOverrideExisting);
|
||||
if (copySubDirResult.IsFailure)
|
||||
return copySubDirResult.Errors;
|
||||
}
|
||||
@@ -193,7 +193,7 @@ internal class DirectoryProviderService : IDirectoryProviderService
|
||||
{
|
||||
string destPath = destinationPath;
|
||||
int copyNumber = 1;
|
||||
// check if the destination directory exists and create a unique directory name
|
||||
// Check if the destination directory exists and create a unique directory name.
|
||||
while (_fileSystem.Directory.Exists(destPath) || _fileSystem.File.Exists(destPath))
|
||||
destPath = $"{destinationPath} - Copy ({copyNumber++})";
|
||||
return destPath;
|
||||
@@ -204,20 +204,20 @@ internal class DirectoryProviderService : IDirectoryProviderService
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">Identifier for the path where the directory to be moved is located.</param>
|
||||
/// <param name="destinationPath">Identifier for the path where the directory will be moved.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <param name="shouldOverrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a moved directory, or an error.</returns>
|
||||
public Result<FileSystemPathId> MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting)
|
||||
public Result<FileSystemPathId> MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool shouldOverrideExisting)
|
||||
{
|
||||
// check if the source directory exists
|
||||
// Check if the source directory exists.
|
||||
if (!_fileSystem.Directory.Exists(sourcePath.Path))
|
||||
return Errors.FileSystemManagement.DirectoryNotFound;
|
||||
try
|
||||
{
|
||||
// if the destination directory does not exist, perform a simple move
|
||||
// If the destination directory does not exist, perform a simple move.
|
||||
if (!_fileSystem.Directory.Exists(destinationPath.Path))
|
||||
_fileSystem.Directory.Move(sourcePath.Path, destinationPath.Path);
|
||||
else
|
||||
MergeDirectories(sourcePath.Path, destinationPath.Path, overrideExisting); // if the destination directory exists, perform a merge based on the overwrite policy
|
||||
MergeDirectories(sourcePath.Path, destinationPath.Path, shouldOverrideExisting); // If the destination directory exists, perform a merge based on the overwrite policy.
|
||||
return FileSystemPathId.Create(destinationPath.Path);
|
||||
}
|
||||
catch
|
||||
@@ -231,39 +231,39 @@ internal class DirectoryProviderService : IDirectoryProviderService
|
||||
/// </summary>
|
||||
/// <param name="sourceDir">The source directory to be merged.</param>
|
||||
/// <param name="destDir">The destination directory to be merged.</param>
|
||||
/// <param name="overwrite">Whether to override existing files.</param>
|
||||
private void MergeDirectories(string sourceDir, string destDir, bool overwrite)
|
||||
/// <param name="shouldOverwrite">Whether to override existing files.</param>
|
||||
private void MergeDirectories(string sourceDir, string destDir, bool shouldOverwrite)
|
||||
{
|
||||
// merge files from source directory to destination directory
|
||||
// Merge files from source directory to destination directory.
|
||||
foreach (string sourceFilePath in _fileSystem.Directory.GetFiles(sourceDir))
|
||||
{
|
||||
string fileName = _fileSystem.Path.GetFileName(sourceFilePath);
|
||||
string destFilePath = _fileSystem.Path.Combine(destDir, fileName);
|
||||
// if a file with the same name exists in the destination
|
||||
// If a file with the same name exists in the destination.
|
||||
if (_fileSystem.File.Exists(destFilePath))
|
||||
{
|
||||
if (overwrite)
|
||||
if (shouldOverwrite)
|
||||
{
|
||||
// overwrite the file in the destination directory
|
||||
// Overwrite the file in the destination directory.
|
||||
_fileSystem.File.Delete(destFilePath);
|
||||
_fileSystem.File.Move(sourceFilePath, destFilePath);
|
||||
}
|
||||
}
|
||||
else
|
||||
_fileSystem.File.Move(sourceFilePath, destFilePath); // move the file if it does not exist in the destination directory
|
||||
_fileSystem.File.Move(sourceFilePath, destFilePath); // Move the file if it does not exist in the destination directory.
|
||||
}
|
||||
// recursively merge subdirectories
|
||||
// Recursively merge subdirectories.
|
||||
foreach (string sourceSubDirPath in _fileSystem.Directory.GetDirectories(sourceDir))
|
||||
{
|
||||
string subDirName = _fileSystem.Path.GetFileName(sourceSubDirPath);
|
||||
string destSubDirPath = _fileSystem.Path.Combine(destDir, subDirName);
|
||||
// if the subdirectory does not exist in the destination, move it
|
||||
// If the subdirectory does not exist in the destination, move it.
|
||||
if (!_fileSystem.Directory.Exists(destSubDirPath))
|
||||
_fileSystem.Directory.Move(sourceSubDirPath, destSubDirPath);
|
||||
else
|
||||
MergeDirectories(sourceSubDirPath, destSubDirPath, overwrite); // if the subdirectory exists, recursively merge its contents
|
||||
MergeDirectories(sourceSubDirPath, destSubDirPath, shouldOverwrite); // If the subdirectory exists, recursively merge its contents.
|
||||
}
|
||||
// after merging the contents, delete the source directory if it's now empty
|
||||
// After merging the contents, delete the source directory if it's now empty.
|
||||
if (!_fileSystem.Directory.EnumerateFileSystemEntries(sourceDir).Any())
|
||||
_fileSystem.Directory.Delete(sourceDir);
|
||||
}
|
||||
@@ -276,22 +276,22 @@ internal class DirectoryProviderService : IDirectoryProviderService
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the absolute path of the renamed directory, or an error.</returns>
|
||||
public Result<FileSystemPathId> RenameDirectory(FileSystemPathId path, string name)
|
||||
{
|
||||
// to rename a directory, its parent directory must be writable
|
||||
string? parentDirectory = _fileSystem.Directory.GetParent(path.Path)?.FullName;
|
||||
if (!string.IsNullOrEmpty(parentDirectory))
|
||||
// To rename a directory, its parent directory must be writable.
|
||||
Optional<string> parentDirectory = Optional<string>.FromNullable(_fileSystem.Directory.GetParent(path.Path)?.FullName);
|
||||
if (parentDirectory.HasValue && !string.IsNullOrEmpty(parentDirectory.Value))
|
||||
{
|
||||
Result<FileSystemPathId> parendDirectoryResult = FileSystemPathId.Create(parentDirectory);
|
||||
Result<FileSystemPathId> parendDirectoryResult = FileSystemPathId.Create(parentDirectory.Value);
|
||||
if (parendDirectoryResult.IsFailure)
|
||||
return parendDirectoryResult.Errors;
|
||||
string? newDirectory = _fileSystem.Path.Combine(parentDirectory, name);
|
||||
if (!string.IsNullOrEmpty(newDirectory))
|
||||
Optional<string> newDirectory = Optional<string>.FromNullable(_fileSystem.Path.Combine(parentDirectory.Value, name));
|
||||
if (newDirectory.HasValue && !string.IsNullOrEmpty(newDirectory.Value))
|
||||
{
|
||||
Result<FileSystemPathId> newDirectoryPathResult = FileSystemPathId.Create(newDirectory);
|
||||
Result<FileSystemPathId> newDirectoryPathResult = FileSystemPathId.Create(newDirectory.Value);
|
||||
if (newDirectoryPathResult.IsFailure)
|
||||
return newDirectoryPathResult.Errors;
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(parendDirectoryResult.Value, FileAccessMode.Write, false))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
// to rename a directory, it must be executable
|
||||
// To rename a directory, it must be executable.
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute, false))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
_fileSystem.Directory.Move(path.Path, newDirectoryPathResult.Value.Path);
|
||||
@@ -311,7 +311,7 @@ internal class DirectoryProviderService : IDirectoryProviderService
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the result of deleting a directory, or an error.</returns>
|
||||
public Result<Deleted> DeleteDirectory(FileSystemPathId path)
|
||||
{
|
||||
// check if the user has access permissions to the provided path
|
||||
// Check if the user has access permissions to the provided path.
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete, false))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
_fileSystem.DirectoryInfo.New(path.Path).Delete(true);
|
||||
|
||||
+34
-34
@@ -36,48 +36,48 @@ public class DirectoryService : IDirectoryService
|
||||
/// Retrieves subdirectories for the specified string path.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the file path.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of subdirectories or an error.</returns>
|
||||
public Result<IEnumerable<Directory>> GetSubdirectories(string path, bool includeHiddenElements)
|
||||
public Result<IEnumerable<Directory>> GetSubdirectories(string path, bool shouldIncludeHiddenElements)
|
||||
{
|
||||
Result<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
if (fileSystemPathIdResult.IsFailure)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
return GetSubdirectories(fileSystemPathIdResult.Value, includeHiddenElements);
|
||||
return GetSubdirectories(fileSystemPathIdResult.Value, shouldIncludeHiddenElements);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves subdirectories for the given directory.
|
||||
/// </summary>
|
||||
/// <param name="directory">Directory object to retrieve subdirectories for.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of subdirectories or an error.</returns>
|
||||
public Result<IEnumerable<Directory>> GetSubdirectories(Directory directory, bool includeHiddenElements)
|
||||
public Result<IEnumerable<Directory>> GetSubdirectories(Directory directory, bool shouldIncludeHiddenElements)
|
||||
{
|
||||
return GetSubdirectories(directory.Id, includeHiddenElements);
|
||||
return GetSubdirectories(directory.Id, shouldIncludeHiddenElements);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves subdirectories for the specified file system path.
|
||||
/// </summary>
|
||||
/// <param name="path">Identifier for the file path.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of subdirectories or an error.</returns>
|
||||
public Result<IEnumerable<Directory>> GetSubdirectories(FileSystemPathId path, bool includeHiddenElements)
|
||||
public Result<IEnumerable<Directory>> GetSubdirectories(FileSystemPathId path, bool shouldIncludeHiddenElements)
|
||||
{
|
||||
// retrieve the list of subdirectories
|
||||
Result<IEnumerable<FileSystemPathId>> subdirectoryPathsResult = _environmentContext.DirectoryProviderService.GetSubdirectoryPaths(path, includeHiddenElements);
|
||||
// Retrieve the list of subdirectories.
|
||||
Result<IEnumerable<FileSystemPathId>> subdirectoryPathsResult = _environmentContext.DirectoryProviderService.GetSubdirectoryPaths(path, shouldIncludeHiddenElements);
|
||||
if (subdirectoryPathsResult.IsFailure)
|
||||
return subdirectoryPathsResult.Errors;
|
||||
List<Directory> result = [];
|
||||
foreach (FileSystemPathId subPath in subdirectoryPathsResult.Value)
|
||||
{
|
||||
// extract directory details
|
||||
// Extract directory details.
|
||||
Result<string> dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(subPath);
|
||||
Result<Optional<DateTime>> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(subPath);
|
||||
Result<Optional<DateTime>> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(subPath);
|
||||
|
||||
// if any error occurred, mark directory as Inaccessible
|
||||
// If any error occurred, mark the directory as inaccessible.
|
||||
if (dirNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure)
|
||||
{
|
||||
Result<Directory> errorDirResult = Directory.Create(subPath, !dirNameResult.IsFailure ? dirNameResult.Value : null!,
|
||||
@@ -123,7 +123,7 @@ public class DirectoryService : IDirectoryService
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the result of creating a directory, or an error.</returns>
|
||||
public Result<Directory> CreateDirectory(FileSystemPathId path, string name)
|
||||
{
|
||||
// first, check if the directory about to be created does not already exist
|
||||
// First, check that the target directory does not already exist.
|
||||
Result<FileSystemPathId> combinedPath = _platformContext.PathStrategy.CombinePath(path, name);
|
||||
if (combinedPath.IsFailure)
|
||||
return combinedPath.Errors;
|
||||
@@ -134,14 +134,14 @@ public class DirectoryService : IDirectoryService
|
||||
return Errors.FileSystemManagement.DirectoryAlreadyExists;
|
||||
else
|
||||
{
|
||||
// create the new directory
|
||||
// Create the new directory.
|
||||
Result<FileSystemPathId> newDirectoryPathResult = _environmentContext.DirectoryProviderService.CreateDirectory(path, name);
|
||||
if (newDirectoryPathResult.IsFailure)
|
||||
return newDirectoryPathResult.Errors;
|
||||
Result<string> dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(newDirectoryPathResult.Value);
|
||||
Result<Optional<DateTime>> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(newDirectoryPathResult.Value);
|
||||
Result<Optional<DateTime>> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(newDirectoryPathResult.Value);
|
||||
// if any error occurred, mark directory as Inaccessible
|
||||
// If any error occurred, mark the directory as inaccessible.
|
||||
if (dirNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure)
|
||||
{
|
||||
Result<Directory> errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsFailure ? dirNameResult.Value : null!,
|
||||
@@ -164,11 +164,11 @@ public class DirectoryService : IDirectoryService
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">String representation of the path where the directory to be copied is located.</param>
|
||||
/// <param name="destinationPath">String representation of the path where the directory will be copied.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <param name="shouldOverrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a copied directory, or an error.</returns>
|
||||
public Result<Directory> CopyDirectory(string sourcePath, string destinationPath, bool? overrideExisting)
|
||||
public Result<Directory> CopyDirectory(string sourcePath, string destinationPath, Optional<bool> shouldOverrideExisting)
|
||||
{
|
||||
// make sure the paths are in the expected format
|
||||
// Make sure the paths are in the expected format.
|
||||
if (!sourcePath.EndsWith(_platformContext.PathStrategy.PathSeparator))
|
||||
sourcePath += _platformContext.PathStrategy.PathSeparator;
|
||||
if (!destinationPath.EndsWith(_platformContext.PathStrategy.PathSeparator))
|
||||
@@ -179,7 +179,7 @@ public class DirectoryService : IDirectoryService
|
||||
Result<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath);
|
||||
if (fileSystemDestinationPathIdResult.IsFailure)
|
||||
return fileSystemDestinationPathIdResult.Errors;
|
||||
return CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
|
||||
return CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, shouldOverrideExisting.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -187,9 +187,9 @@ public class DirectoryService : IDirectoryService
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">Identifier for the path where the directory to be copied is located.</param>
|
||||
/// <param name="destinationPath">Identifier for the path where the directory will be copied.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <param name="shouldOverrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the copied directory, or an error.</returns>
|
||||
public Result<Directory> CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting)
|
||||
public Result<Directory> CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool shouldOverrideExisting)
|
||||
{
|
||||
Result<bool> directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(sourcePath);
|
||||
if (directoryExists.IsFailure)
|
||||
@@ -198,8 +198,8 @@ public class DirectoryService : IDirectoryService
|
||||
return Errors.FileSystemManagement.DirectoryNotFound;
|
||||
else
|
||||
{
|
||||
// copy the directory
|
||||
Result<FileSystemPathId> newDirectory = _environmentContext.DirectoryProviderService.CopyDirectory(sourcePath, destinationPath, overrideExisting);
|
||||
// Copy the directory.
|
||||
Result<FileSystemPathId> newDirectory = _environmentContext.DirectoryProviderService.CopyDirectory(sourcePath, destinationPath, shouldOverrideExisting);
|
||||
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
@@ -210,11 +210,11 @@ public class DirectoryService : IDirectoryService
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">String representation of the path where the directory to be moved is located.</param>
|
||||
/// <param name="destinationPath">String representation of the path where the directory will be moved.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <param name="shouldOverrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a moved directory, or an error.</returns>
|
||||
public Result<Directory> MoveDirectory(string sourcePath, string destinationPath, bool? overrideExisting)
|
||||
public Result<Directory> MoveDirectory(string sourcePath, string destinationPath, Optional<bool> shouldOverrideExisting)
|
||||
{
|
||||
// make sure the paths are in the expected format
|
||||
// Make sure the paths are in the expected format.
|
||||
if (!sourcePath.EndsWith(_platformContext.PathStrategy.PathSeparator))
|
||||
sourcePath += _platformContext.PathStrategy.PathSeparator;
|
||||
if (!destinationPath.EndsWith(_platformContext.PathStrategy.PathSeparator))
|
||||
@@ -225,7 +225,7 @@ public class DirectoryService : IDirectoryService
|
||||
Result<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath);
|
||||
if (fileSystemDestinationPathIdResult.IsFailure)
|
||||
return fileSystemDestinationPathIdResult.Errors;
|
||||
return MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
|
||||
return MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, shouldOverrideExisting.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -233,9 +233,9 @@ public class DirectoryService : IDirectoryService
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">Identifier for the path where the directory to be moved is located.</param>
|
||||
/// <param name="destinationPath">Identifier for the path where the directory will be moved.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <param name="shouldOverrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the moved directory, or an error.</returns>
|
||||
public Result<Directory> MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting)
|
||||
public Result<Directory> MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool shouldOverrideExisting)
|
||||
{
|
||||
Result<bool> directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(sourcePath);
|
||||
if (directoryExists.IsFailure)
|
||||
@@ -244,8 +244,8 @@ public class DirectoryService : IDirectoryService
|
||||
return Errors.FileSystemManagement.DirectoryNotFound;
|
||||
else
|
||||
{
|
||||
// move the directory
|
||||
Result<FileSystemPathId> newDirectory = _environmentContext.DirectoryProviderService.MoveDirectory(sourcePath, destinationPath, overrideExisting);
|
||||
// Move the directory.
|
||||
Result<FileSystemPathId> newDirectory = _environmentContext.DirectoryProviderService.MoveDirectory(sourcePath, destinationPath, shouldOverrideExisting);
|
||||
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
@@ -273,7 +273,7 @@ public class DirectoryService : IDirectoryService
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the renamed directory, or an error.</returns>
|
||||
public Result<Directory> RenameDirectory(FileSystemPathId path, string name)
|
||||
{
|
||||
// first, check if the directory about to be created does not already exist
|
||||
// First, check that the target directory does not already exist.
|
||||
Result<FileSystemPathId> combinedPath = _platformContext.PathStrategy.CombinePath(path, name);
|
||||
if (combinedPath.IsFailure)
|
||||
return combinedPath.Errors;
|
||||
@@ -284,14 +284,14 @@ public class DirectoryService : IDirectoryService
|
||||
return Errors.FileSystemManagement.DirectoryAlreadyExists;
|
||||
else
|
||||
{
|
||||
// rename the directory
|
||||
// Rename the directory.
|
||||
Result<FileSystemPathId> newDirectoryPathResult = _environmentContext.DirectoryProviderService.RenameDirectory(path, name);
|
||||
if (newDirectoryPathResult.IsFailure)
|
||||
return newDirectoryPathResult.Errors;
|
||||
Result<string> dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(newDirectoryPathResult.Value);
|
||||
Result<Optional<DateTime>> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(newDirectoryPathResult.Value);
|
||||
Result<Optional<DateTime>> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(newDirectoryPathResult.Value);
|
||||
// if any error occurred, mark directory as Inaccessible
|
||||
// If any error occurred, mark the directory as inaccessible.
|
||||
if (dirNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure)
|
||||
{
|
||||
Result<Directory> errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsFailure ? dirNameResult.Value : null!,
|
||||
|
||||
+40
-38
@@ -36,15 +36,15 @@ internal class FileProviderService : IFileProviderService
|
||||
/// Retrieves a list of file paths at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path for which to retrieve the list of files.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of file paths or an error.</returns>
|
||||
public Result<IEnumerable<FileSystemPathId>> GetFilePaths(FileSystemPathId path, bool includeHiddenElements)
|
||||
public Result<IEnumerable<FileSystemPathId>> GetFilePaths(FileSystemPathId path, bool shouldIncludeHiddenElements)
|
||||
{
|
||||
// check if the user has access permissions to the provided path
|
||||
// Check if the user has access permissions to the provided path.
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
return Result.From(_fileSystem.Directory.GetFiles(path.Path)
|
||||
.Where(path => includeHiddenElements || (GetAttributes(path) & FileAttributes.Hidden) != FileAttributes.Hidden)
|
||||
.Where(path => shouldIncludeHiddenElements || (GetAttributes(path) & FileAttributes.Hidden) != FileAttributes.Hidden)
|
||||
.OrderBy(path => path)
|
||||
.Select(path => FileSystemPathId.Create(path))
|
||||
.Where(pathIdResult => !pathIdResult.IsFailure)
|
||||
@@ -61,7 +61,7 @@ internal class FileProviderService : IFileProviderService
|
||||
{
|
||||
try
|
||||
{
|
||||
// File.GetAttributes is used for both directories and files
|
||||
// File.GetAttributes is used for both directories and files.
|
||||
return _fileSystem.File.GetAttributes(path);
|
||||
}
|
||||
catch
|
||||
@@ -97,7 +97,7 @@ internal class FileProviderService : IFileProviderService
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the contents of a file at the specified path, or an error.</returns>
|
||||
public Result<byte[]> GetFileAsync(FileSystemPathId path)
|
||||
{
|
||||
// check if the user has access permissions to the provided path
|
||||
// Check if the user has access permissions to the provided path.
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
return _fileSystem.File.ReadAllBytes(path.Path);
|
||||
@@ -110,7 +110,7 @@ internal class FileProviderService : IFileProviderService
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the optional last write time of <paramref name="path"/> if available, or an error.</returns>
|
||||
public Result<Optional<DateTime>> GetLastWriteTime(FileSystemPathId path)
|
||||
{
|
||||
// check if the user has access permissions to the provided path
|
||||
// Check if the user has access permissions to the provided path.
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
return Optional<DateTime>.FromNullable(_fileSystem.File.GetLastWriteTime(path.Path));
|
||||
@@ -123,7 +123,7 @@ internal class FileProviderService : IFileProviderService
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the optional creation time of <paramref name="path"/> if available, or an error.</returns>
|
||||
public Result<Optional<DateTime>> GetCreationTime(FileSystemPathId path)
|
||||
{
|
||||
// check if the user has access permissions to the provided path
|
||||
// Check if the user has access permissions to the provided path.
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
return Optional<DateTime>.FromNullable(_fileSystem.File.GetCreationTime(path.Path));
|
||||
@@ -136,7 +136,7 @@ internal class FileProviderService : IFileProviderService
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the size of <paramref name="path"/> or an error.</returns>
|
||||
public Result<long?> GetSize(FileSystemPathId path)
|
||||
{
|
||||
// check if the user has access permissions to the provided path
|
||||
// Check if the user has access permissions to the provided path.
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
return _fileSystem.FileInfo.New(path.Path)?.Length ?? 0;
|
||||
@@ -147,27 +147,27 @@ internal class FileProviderService : IFileProviderService
|
||||
/// </summary>
|
||||
/// <param name="sourceFilePath">Identifier for the path where the file to be copied is located.</param>
|
||||
/// <param name="destinationDirectoryPath">Identifier for the path of the directory where the file will be copied.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <param name="shouldOverrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the copied file, or an error.</returns>
|
||||
public Result<FileSystemPathId> CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting)
|
||||
public Result<FileSystemPathId> CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool shouldOverrideExisting)
|
||||
{
|
||||
// check if the source file exists
|
||||
// Check if the source file exists.
|
||||
if (!_fileSystem.File.Exists(sourceFilePath.Path))
|
||||
return Errors.FileSystemManagement.FileNotFound;
|
||||
string fileName = _fileSystem.Path.GetFileName(sourceFilePath.Path);
|
||||
string destinationFilePath = _fileSystem.Path.Combine(destinationDirectoryPath.Path, fileName);
|
||||
// when copying a file to the same location, just copy it with a new name
|
||||
// When copying a file to the same location, just copy it with a new name.
|
||||
if (_fileSystem.Path.GetDirectoryName(sourceFilePath.Path) == destinationDirectoryPath.Path)
|
||||
destinationFilePath = CreateUniqueFilePath(destinationFilePath);
|
||||
else
|
||||
// check if there is already a file with the same name as the copied file, in the destination directory
|
||||
// Check if there is already a file with the same name as the copied file, in the destination directory.
|
||||
if (_fileSystem.File.Exists(destinationFilePath))
|
||||
if (!overrideExisting)
|
||||
if (!shouldOverrideExisting)
|
||||
return Errors.FileSystemManagement.FileAlreadyExists;
|
||||
try
|
||||
{
|
||||
_fileSystem.File.Copy(sourceFilePath.Path, destinationFilePath, overrideExisting); // copy the file
|
||||
_fileSystem.File.SetAttributes(destinationFilePath, _fileSystem.File.GetAttributes(sourceFilePath.Path)); // preserve file attributes
|
||||
_fileSystem.File.Copy(sourceFilePath.Path, destinationFilePath, shouldOverrideExisting); // Copy the file.
|
||||
_fileSystem.File.SetAttributes(destinationFilePath, _fileSystem.File.GetAttributes(sourceFilePath.Path)); // Preserve file attributes.
|
||||
return FileSystemPathId.Create(destinationFilePath);
|
||||
}
|
||||
catch
|
||||
@@ -177,21 +177,23 @@ internal class FileProviderService : IFileProviderService
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a file path that is unique
|
||||
/// Creates a file path that is unique.
|
||||
/// </summary>
|
||||
/// <param name="destinationFilePath">The path from which to generate the unique file path.</param>
|
||||
/// <returns>A unique directory path.</returns>
|
||||
private string CreateUniqueFilePath(string destinationFilePath)
|
||||
{
|
||||
string? directory = _fileSystem.Path.GetDirectoryName(destinationFilePath);
|
||||
string? filename = _fileSystem.Path.GetFileNameWithoutExtension(destinationFilePath);
|
||||
string? extension = _fileSystem.Path.GetExtension(destinationFilePath);
|
||||
Optional<string> directory = Optional<string>.FromNullable(_fileSystem.Path.GetDirectoryName(destinationFilePath));
|
||||
Optional<string> filename = Optional<string>.FromNullable(_fileSystem.Path.GetFileNameWithoutExtension(destinationFilePath));
|
||||
Optional<string> extension = Optional<string>.FromNullable(_fileSystem.Path.GetExtension(destinationFilePath));
|
||||
string destFilePath = destinationFilePath;
|
||||
int copyNumber = 1;
|
||||
// check if the destination file exists and create a unique file name
|
||||
if (!string.IsNullOrEmpty(directory) && !string.IsNullOrEmpty(filename) && !string.IsNullOrEmpty(extension))
|
||||
// Check if the destination file exists and create a unique file name.
|
||||
if (directory.HasValue && !string.IsNullOrEmpty(directory.Value)
|
||||
&& filename.HasValue && !string.IsNullOrEmpty(filename.Value)
|
||||
&& extension.HasValue && !string.IsNullOrEmpty(extension.Value))
|
||||
while (_fileSystem.File.Exists(destFilePath))
|
||||
destFilePath = _fileSystem.Path.Combine(directory, $"{filename} - Copy ({copyNumber++}){extension}");
|
||||
destFilePath = _fileSystem.Path.Combine(directory.Value, $"{filename.Value} - Copy ({copyNumber++}){extension.Value}");
|
||||
return destFilePath;
|
||||
}
|
||||
|
||||
@@ -200,23 +202,23 @@ internal class FileProviderService : IFileProviderService
|
||||
/// </summary>
|
||||
/// <param name="sourceFilePath">Identifier for the path where the file to be moved is located.</param>
|
||||
/// <param name="destinationDirectoryPath">Identifier for the path of the directory where the file will be moved.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <param name="shouldOverrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a moved file, or an error.</returns>
|
||||
public Result<FileSystemPathId> MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting)
|
||||
public Result<FileSystemPathId> MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool shouldOverrideExisting)
|
||||
{
|
||||
// check if the source file exists
|
||||
// Check if the source file exists.
|
||||
if (!_fileSystem.File.Exists(sourceFilePath.Path))
|
||||
return Errors.FileSystemManagement.FileNotFound;
|
||||
try
|
||||
{
|
||||
string fileName = _fileSystem.Path.GetFileName(sourceFilePath.Path);
|
||||
string destinationFilePath = _fileSystem.Path.Combine(destinationDirectoryPath.Path, fileName);
|
||||
// if the destination file does not exist, perform a simple move
|
||||
// If the destination file does not exist, perform a simple move.
|
||||
if (!_fileSystem.File.Exists(destinationFilePath))
|
||||
_fileSystem.File.Move(sourceFilePath.Path, destinationFilePath);
|
||||
else
|
||||
if (overrideExisting)
|
||||
_fileSystem.File.Move(sourceFilePath.Path, destinationFilePath, overrideExisting);
|
||||
if (shouldOverrideExisting)
|
||||
_fileSystem.File.Move(sourceFilePath.Path, destinationFilePath, shouldOverrideExisting);
|
||||
else
|
||||
return Errors.FileSystemManagement.FileAlreadyExists;
|
||||
return FileSystemPathId.Create(destinationFilePath);
|
||||
@@ -235,19 +237,19 @@ internal class FileProviderService : IFileProviderService
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the absolute path of the renamed file, or an error.</returns>
|
||||
public Result<FileSystemPathId> RenameFile(FileSystemPathId path, string name)
|
||||
{
|
||||
string? parentDirectory = _fileSystem.FileInfo.New(path.Path)?.DirectoryName;
|
||||
if (!string.IsNullOrEmpty(parentDirectory))
|
||||
Optional<string> parentDirectory = Optional<string>.FromNullable(_fileSystem.FileInfo.New(path.Path)?.DirectoryName);
|
||||
if (parentDirectory.HasValue && !string.IsNullOrEmpty(parentDirectory.Value))
|
||||
{
|
||||
Result<FileSystemPathId> parendDirectoryResult = FileSystemPathId.Create(parentDirectory);
|
||||
Result<FileSystemPathId> parendDirectoryResult = FileSystemPathId.Create(parentDirectory.Value);
|
||||
if (parendDirectoryResult.IsFailure)
|
||||
return parendDirectoryResult.Errors;
|
||||
string? newFile = _fileSystem.Path.Combine(parendDirectoryResult.Value.Path, name);
|
||||
if (!string.IsNullOrEmpty(newFile))
|
||||
Optional<string> newFile = Optional<string>.FromNullable(_fileSystem.Path.Combine(parendDirectoryResult.Value.Path, name));
|
||||
if (newFile.HasValue && !string.IsNullOrEmpty(newFile.Value))
|
||||
{
|
||||
Result<FileSystemPathId> newFilePathResult = FileSystemPathId.Create(newFile);
|
||||
Result<FileSystemPathId> newFilePathResult = FileSystemPathId.Create(newFile.Value);
|
||||
if (newFilePathResult.IsFailure)
|
||||
return newFilePathResult.Errors;
|
||||
// renaming a file only requires write access to its parent directory, never execute access to the file itself
|
||||
// Renaming a file only requires write access to its parent directory, never execute access to the file itself.
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(parendDirectoryResult.Value, FileAccessMode.Write))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
_fileSystem.File.Move(path.Path, newFilePathResult.Value.Path);
|
||||
@@ -267,7 +269,7 @@ internal class FileProviderService : IFileProviderService
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the result of deleting a file, or an error.</returns>
|
||||
public Result<Deleted> DeleteFile(FileSystemPathId path)
|
||||
{
|
||||
// check if the user has access permissions to the provided path
|
||||
// Check if the user has access permissions to the provided path.
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
_fileSystem.File.Delete(path.Path);
|
||||
|
||||
+33
-33
@@ -35,50 +35,50 @@ public class FileService : IFileService
|
||||
/// Retrieves files for the specified string path.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the file path.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of files or an error.</returns>
|
||||
public Result<IEnumerable<File>> GetFiles(string path, bool includeHiddenElements)
|
||||
public Result<IEnumerable<File>> GetFiles(string path, bool shouldIncludeHiddenElements)
|
||||
{
|
||||
Result<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
if (fileSystemPathIdResult.IsFailure)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
return GetFiles(fileSystemPathIdResult.Value, includeHiddenElements);
|
||||
return GetFiles(fileSystemPathIdResult.Value, shouldIncludeHiddenElements);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves files associated with a given file.
|
||||
/// </summary>
|
||||
/// <param name="file">The file object.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of files or an error.</returns>
|
||||
public Result<IEnumerable<File>> GetFiles(File file, bool includeHiddenElements)
|
||||
public Result<IEnumerable<File>> GetFiles(File file, bool shouldIncludeHiddenElements)
|
||||
{
|
||||
return GetFiles(file.Id, includeHiddenElements);
|
||||
return GetFiles(file.Id, shouldIncludeHiddenElements);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves files for a specified file path Id.
|
||||
/// </summary>
|
||||
/// <param name="path">Identifier for the file path.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of files or an error.</returns>
|
||||
public Result<IEnumerable<File>> GetFiles(FileSystemPathId path, bool includeHiddenElements)
|
||||
public Result<IEnumerable<File>> GetFiles(FileSystemPathId path, bool shouldIncludeHiddenElements)
|
||||
{
|
||||
// retrieve the list of files
|
||||
Result<IEnumerable<FileSystemPathId>> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path, includeHiddenElements);
|
||||
// Retrieve the list of files.
|
||||
Result<IEnumerable<FileSystemPathId>> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path, shouldIncludeHiddenElements);
|
||||
if (filePathsResult.IsFailure)
|
||||
return filePathsResult.Errors;
|
||||
List<File> result = [];
|
||||
IEnumerable<FileSystemPathId> filePaths = filePathsResult.Value;
|
||||
foreach (FileSystemPathId filePath in filePaths)
|
||||
{
|
||||
// extract file details and add to the result list
|
||||
// Extract file details and add them to the result list.
|
||||
Result<string> fileNameResult = _environmentContext.FileProviderService.GetFileName(filePath);
|
||||
Result<Optional<DateTime>> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(filePath);
|
||||
Result<Optional<DateTime>> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(filePath);
|
||||
Result<long?> sizeResult = _environmentContext.FileProviderService.GetSize(filePath);
|
||||
long size = !sizeResult.IsFailure ? sizeResult.Value ?? 0 : 0;
|
||||
// if any of the details returned an error, set inaccessible status
|
||||
// If any of the details returned an error, set the inaccessible status.
|
||||
if (fileNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure || sizeResult.IsFailure)
|
||||
{
|
||||
Result<File> errorFileResult = File.Create(filePath, !fileNameResult.IsFailure ? fileNameResult.Value : null!,
|
||||
@@ -107,13 +107,13 @@ public class FileService : IFileService
|
||||
/// </summary>
|
||||
/// <param name="sourceFilePath">String representation of the path where the file to be copied is located.</param>
|
||||
/// <param name="destinationDirectoryPath">String representation of the path of the directory where the file will be copied.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <param name="shouldOverrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a copied file, or an error.</returns>
|
||||
public Result<File> CopyFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting)
|
||||
public Result<File> CopyFile(string sourceFilePath, string destinationDirectoryPath, Optional<bool> shouldOverrideExisting)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(destinationDirectoryPath))
|
||||
return Errors.FileSystemManagement.InvalidPath;
|
||||
// make sure the paths are in the expected format
|
||||
// Make sure the paths are in the expected format.
|
||||
if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator))
|
||||
destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator;
|
||||
Result<FileSystemPathId> fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath);
|
||||
@@ -122,7 +122,7 @@ public class FileService : IFileService
|
||||
Result<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath);
|
||||
if (fileSystemDestinationPathIdResult.IsFailure)
|
||||
return fileSystemDestinationPathIdResult.Errors;
|
||||
return CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
|
||||
return CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, shouldOverrideExisting.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -130,9 +130,9 @@ public class FileService : IFileService
|
||||
/// </summary>
|
||||
/// <param name="sourceFilePath">Identifier for the path where the file to be copied is located.</param>
|
||||
/// <param name="destinationDirectoryPath">Identifier for the path of the directory where the file will be copied.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <param name="shouldOverrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the copied file, or an error.</returns>
|
||||
public Result<File> CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting)
|
||||
public Result<File> CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool shouldOverrideExisting)
|
||||
{
|
||||
Result<bool> fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath);
|
||||
if (fileExists.IsFailure)
|
||||
@@ -141,8 +141,8 @@ public class FileService : IFileService
|
||||
return Errors.FileSystemManagement.FileNotFound;
|
||||
else
|
||||
{
|
||||
// copy the file
|
||||
Result<FileSystemPathId> copyFileResult = _environmentContext.FileProviderService.CopyFile(sourceFilePath, destinationDirectoryPath, overrideExisting);
|
||||
// Copy the file.
|
||||
Result<FileSystemPathId> copyFileResult = _environmentContext.FileProviderService.CopyFile(sourceFilePath, destinationDirectoryPath, shouldOverrideExisting);
|
||||
if (copyFileResult.IsFailure)
|
||||
return copyFileResult.Errors;
|
||||
Result<string> fileNameResult = _environmentContext.FileProviderService.GetFileName(copyFileResult.Value);
|
||||
@@ -150,7 +150,7 @@ public class FileService : IFileService
|
||||
Result<Optional<DateTime>> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(copyFileResult.Value);
|
||||
Result<long?> sizeResult = _environmentContext.FileProviderService.GetSize(copyFileResult.Value);
|
||||
long size = !sizeResult.IsFailure ? sizeResult.Value ?? 0 : 0;
|
||||
// if any of the details returned an error, set inaccessible status
|
||||
// If any of the details returned an error, set the inaccessible status.
|
||||
if (fileNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure || sizeResult.IsFailure)
|
||||
{
|
||||
Result<File> errorFileResult = File.Create(copyFileResult.Value, !fileNameResult.IsFailure ? fileNameResult.Value : null!,
|
||||
@@ -173,13 +173,13 @@ public class FileService : IFileService
|
||||
/// </summary>
|
||||
/// <param name="sourceFilePath">String representation of the path where the file to be moved is located.</param>
|
||||
/// <param name="destinationDirectoryPath">String representation of the path of the directory where the file will be moved.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <param name="shouldOverrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a moved file, or an error.</returns>
|
||||
public Result<File> MoveFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting)
|
||||
public Result<File> MoveFile(string sourceFilePath, string destinationDirectoryPath, Optional<bool> shouldOverrideExisting)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(destinationDirectoryPath))
|
||||
return Errors.FileSystemManagement.InvalidPath;
|
||||
// make sure the paths are in the expected format
|
||||
// Make sure the paths are in the expected format.
|
||||
if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator))
|
||||
destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator;
|
||||
Result<FileSystemPathId> fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath);
|
||||
@@ -188,7 +188,7 @@ public class FileService : IFileService
|
||||
Result<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath);
|
||||
if (fileSystemDestinationPathIdResult.IsFailure)
|
||||
return fileSystemDestinationPathIdResult.Errors;
|
||||
return MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
|
||||
return MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, shouldOverrideExisting.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -196,9 +196,9 @@ public class FileService : IFileService
|
||||
/// </summary>
|
||||
/// <param name="sourceFilePath">Identifier for the path where the file to be moved is located.</param>
|
||||
/// <param name="destinationDirectoryPath">Identifier for the path of the directory where the file will be moved.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <param name="shouldOverrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the moved file, or an error.</returns>
|
||||
public Result<File> MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting)
|
||||
public Result<File> MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool shouldOverrideExisting)
|
||||
{
|
||||
Result<bool> fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath);
|
||||
if (fileExists.IsFailure)
|
||||
@@ -207,8 +207,8 @@ public class FileService : IFileService
|
||||
return Errors.FileSystemManagement.FileNotFound;
|
||||
else
|
||||
{
|
||||
// move the file
|
||||
Result<FileSystemPathId> moveFileResult = _environmentContext.FileProviderService.MoveFile(sourceFilePath, destinationDirectoryPath, overrideExisting);
|
||||
// Move the file.
|
||||
Result<FileSystemPathId> moveFileResult = _environmentContext.FileProviderService.MoveFile(sourceFilePath, destinationDirectoryPath, shouldOverrideExisting);
|
||||
if (moveFileResult.IsFailure)
|
||||
return moveFileResult.Errors;
|
||||
Result<string> fileNameResult = _environmentContext.FileProviderService.GetFileName(moveFileResult.Value);
|
||||
@@ -216,7 +216,7 @@ public class FileService : IFileService
|
||||
Result<Optional<DateTime>> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(moveFileResult.Value);
|
||||
Result<long?> sizeResult = _environmentContext.FileProviderService.GetSize(moveFileResult.Value);
|
||||
long size = !sizeResult.IsFailure ? sizeResult.Value ?? 0 : 0;
|
||||
// if any of the details returned an error, set inaccessible status
|
||||
// If any of the details returned an error, set the inaccessible status.
|
||||
if (fileNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure || sizeResult.IsFailure)
|
||||
{
|
||||
Result<File> errorFileResult = File.Create(moveFileResult.Value, !fileNameResult.IsFailure ? fileNameResult.Value : null!,
|
||||
@@ -256,7 +256,7 @@ public class FileService : IFileService
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the renamed file, or an error.</returns>
|
||||
public Result<File> RenameFile(FileSystemPathId path, string name)
|
||||
{
|
||||
// first, check if the directory about to be created does not already exist
|
||||
// First, check that the target file does not already exist.
|
||||
Result<FileSystemPathId> combinedPath = _platformContext.PathStrategy.CombinePath(path, name);
|
||||
if (combinedPath.IsFailure)
|
||||
return combinedPath.Errors;
|
||||
@@ -267,7 +267,7 @@ public class FileService : IFileService
|
||||
return Errors.FileSystemManagement.FileAlreadyExists;
|
||||
else
|
||||
{
|
||||
// rename the file
|
||||
// Rename the file.
|
||||
Result<FileSystemPathId> newFilePathResult = _environmentContext.FileProviderService.RenameFile(path, name);
|
||||
if (newFilePathResult.IsFailure)
|
||||
return newFilePathResult.Errors;
|
||||
@@ -276,7 +276,7 @@ public class FileService : IFileService
|
||||
Result<Optional<DateTime>> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(newFilePathResult.Value);
|
||||
Result<long?> sizeResult = _environmentContext.FileProviderService.GetSize(newFilePathResult.Value);
|
||||
long size = !sizeResult.IsFailure ? sizeResult.Value ?? 0 : 0;
|
||||
// if any of the details returned an error, set inaccessible status
|
||||
// If any of the details returned an error, set the inaccessible status.
|
||||
if (fileNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure || sizeResult.IsFailure)
|
||||
{
|
||||
Result<File> errorFileResult = File.Create(newFilePathResult.Value, !fileNameResult.IsFailure ? fileNameResult.Value : null!,
|
||||
|
||||
+10
-10
@@ -16,25 +16,25 @@ public interface IDirectoryService
|
||||
/// Retrieves subdirectories for the specified string path.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the file path.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of subdirectories or an error.</returns>
|
||||
Result<IEnumerable<Directory>> GetSubdirectories(string path, bool includeHiddenElements);
|
||||
Result<IEnumerable<Directory>> GetSubdirectories(string path, bool shouldIncludeHiddenElements);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves subdirectories for the given directory.
|
||||
/// </summary>
|
||||
/// <param name="directory">Directory object to retrieve subdirectories for.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of subdirectories or an error.</returns>
|
||||
Result<IEnumerable<Directory>> GetSubdirectories(Directory directory, bool includeHiddenElements);
|
||||
Result<IEnumerable<Directory>> GetSubdirectories(Directory directory, bool shouldIncludeHiddenElements);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves subdirectories for the specified file system path.
|
||||
/// </summary>
|
||||
/// <param name="path">Identifier for the file path.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of subdirectories or an error.</returns>
|
||||
Result<IEnumerable<Directory>> GetSubdirectories(FileSystemPathId path, bool includeHiddenElements);
|
||||
Result<IEnumerable<Directory>> GetSubdirectories(FileSystemPathId path, bool shouldIncludeHiddenElements);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a directory with the specified <paramref name="name"/>, at the specified <paramref name="path"/>.
|
||||
@@ -49,18 +49,18 @@ public interface IDirectoryService
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">String representation of the path where the directory to be copied is located.</param>
|
||||
/// <param name="destinationPath">String representation of the path where the directory will be copied.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <param name="shouldOverrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a copied directory, or an error.</returns>
|
||||
Result<Directory> CopyDirectory(string sourcePath, string destinationPath, bool? overrideExisting);
|
||||
Result<Directory> CopyDirectory(string sourcePath, string destinationPath, Optional<bool> shouldOverrideExisting);
|
||||
|
||||
/// <summary>
|
||||
/// Moves a directory located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">String representation of the path where the directory to be moved is located.</param>
|
||||
/// <param name="destinationPath">String representation of the path where the directory will be moved.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <param name="shouldOverrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a moved directory, or an error.</returns>
|
||||
Result<Directory> MoveDirectory(string sourcePath, string destinationPath, bool? overrideExisting);
|
||||
Result<Directory> MoveDirectory(string sourcePath, string destinationPath, Optional<bool> shouldOverrideExisting);
|
||||
|
||||
/// <summary>
|
||||
/// Renames a directory with the specified <paramref name="name"/>, at the specified <paramref name="path"/>.
|
||||
|
||||
+10
-10
@@ -16,43 +16,43 @@ public interface IFileService
|
||||
/// Retrieves files for the specified string path.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the file path.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of files or an error.</returns>
|
||||
Result<IEnumerable<File>> GetFiles(string path, bool includeHiddenElements);
|
||||
Result<IEnumerable<File>> GetFiles(string path, bool shouldIncludeHiddenElements);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves files associated with a given file.
|
||||
/// </summary>
|
||||
/// <param name="file">The file object.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of files or an error.</returns>
|
||||
Result<IEnumerable<File>> GetFiles(File file, bool includeHiddenElements);
|
||||
Result<IEnumerable<File>> GetFiles(File file, bool shouldIncludeHiddenElements);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves files for a specified file path ID.
|
||||
/// </summary>
|
||||
/// <param name="path">Identifier for the file path.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of files or an error.</returns>
|
||||
Result<IEnumerable<File>> GetFiles(FileSystemPathId path, bool includeHiddenElements);
|
||||
Result<IEnumerable<File>> GetFiles(FileSystemPathId path, bool shouldIncludeHiddenElements);
|
||||
|
||||
/// <summary>
|
||||
/// Copies a file located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">String representation of the path where the file to be copied is located.</param>
|
||||
/// <param name="destinationPath">String representation of the path where the file will be copied.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <param name="shouldOverrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a copied file, or an error.</returns>
|
||||
Result<File> CopyFile(string sourcePath, string destinationPath, bool? overrideExisting);
|
||||
Result<File> CopyFile(string sourcePath, string destinationPath, Optional<bool> shouldOverrideExisting);
|
||||
|
||||
/// <summary>
|
||||
/// Moves a file located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">String representation of the path where the file to be moved is located.</param>
|
||||
/// <param name="destinationPath">String representation of the path where the file will be moved.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <param name="shouldOverrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a moved file, or an error.</returns>
|
||||
Result<File> MoveFile(string sourcePath, string destinationPath, bool? overrideExisting);
|
||||
Result<File> MoveFile(string sourcePath, string destinationPath, Optional<bool> shouldOverrideExisting);
|
||||
|
||||
/// <summary>
|
||||
/// Renames a file with the specified <paramref name="name"/>, at the specified <paramref name="path"/>.
|
||||
|
||||
+10
-2
@@ -27,9 +27,9 @@ public interface IPathService
|
||||
/// Checks if <paramref name="path"/> exists.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be checked.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <returns><see langword="true"/> if <paramref name="path"/> exists, <see langword="false"/> otherwise.</returns>
|
||||
bool Exists(string path, bool includeHiddenElements = true);
|
||||
bool Exists(string path, bool shouldIncludeHiddenElements = true);
|
||||
|
||||
/// <summary>
|
||||
/// Tries to combine <paramref name="path"/> with <paramref name="name"/>.
|
||||
@@ -72,4 +72,12 @@ public interface IPathService
|
||||
/// <param name="path">The path for which to get the root.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing the root of <paramref name="path"/>, or an error.</returns>
|
||||
Result<PathSegment> GetPathRoot(string path);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether <paramref name="path"/> is located inside <paramref name="parentPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be checked.</param>
|
||||
/// <param name="parentPath">The path that must contain the checked path.</param>
|
||||
/// <returns><see langword="true"/> if the path is inside the parent path, <see langword="false"/> otherwise.</returns>
|
||||
bool IsPathWithin(string path, string parentPath);
|
||||
}
|
||||
+27
-10
@@ -50,21 +50,21 @@ public class PathService : IPathService
|
||||
/// Checks if <paramref name="path"/> exists.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be checked.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <returns><see langword="true"/> if <paramref name="path"/> exists, <see langword="false"/> otherwise.</returns>
|
||||
public bool Exists(string path, bool includeHiddenElements = true)
|
||||
public bool Exists(string path, bool shouldIncludeHiddenElements = true)
|
||||
{
|
||||
Result<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
|
||||
if (newPathResult.IsFailure)
|
||||
return false;
|
||||
return _platformContext.PathStrategy.Exists(newPathResult.Value, includeHiddenElements);
|
||||
return _platformContext.PathStrategy.Exists(newPathResult.Value, shouldIncludeHiddenElements);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to combine <paramref name="path"/> with <paramref name="name"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be combined.</param>
|
||||
/// <param name="path">The name to be combined with the path.</param>
|
||||
/// <param name="name">The name to be combined with the path.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing the combined path, or an error.</returns>
|
||||
public Result<string> CombinePath(string path, string name)
|
||||
{
|
||||
@@ -127,28 +127,28 @@ public class PathService : IPathService
|
||||
char[] invalidChars = _platformContext.PathStrategy.GetInvalidPathSegmentCharsForPlatform();
|
||||
char[] sanitizedChars = [.. name.Trim().Select(character => Array.IndexOf(invalidChars, character) >= 0 ? ' ' : character)];
|
||||
|
||||
// collapse the consecutive whitespace into a single space, so that the segment does not contain ragged spacing
|
||||
// Collapse the consecutive whitespace into a single space, so that the segment does not contain ragged spacing.
|
||||
List<char> collapsedChars = [];
|
||||
bool previousWasWhitespace = false;
|
||||
bool wasPreviousWhitespace = false;
|
||||
foreach (char character in sanitizedChars)
|
||||
{
|
||||
if (char.IsWhiteSpace(character))
|
||||
{
|
||||
if (!previousWasWhitespace)
|
||||
if (!wasPreviousWhitespace)
|
||||
collapsedChars.Add(' ');
|
||||
previousWasWhitespace = true;
|
||||
wasPreviousWhitespace = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
collapsedChars.Add(character);
|
||||
previousWasWhitespace = false;
|
||||
wasPreviousWhitespace = false;
|
||||
}
|
||||
}
|
||||
|
||||
string sanitized = new string([.. collapsedChars]).Trim();
|
||||
if (string.Equals(sanitized, ".", StringComparison.Ordinal) || string.Equals(sanitized, "..", StringComparison.Ordinal))
|
||||
return Errors.FileSystemManagement.InvalidPath;
|
||||
// a segment must never contain a path separator, otherwise the segment could escape its directory or nest additional directories
|
||||
// A segment must never contain a path separator, otherwise the segment could escape its directory or nest additional directories.
|
||||
if (sanitized.Contains('/') || sanitized.Contains('\\'))
|
||||
return Errors.FileSystemManagement.InvalidPath;
|
||||
if (sanitized.Length > MAX_DIRECTORY_SEGMENT_LENGTH)
|
||||
@@ -171,4 +171,21 @@ public class PathService : IPathService
|
||||
return newPathResult.Errors;
|
||||
return _platformContext.PathStrategy.GetPathRoot(newPathResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether <paramref name="path"/> is located inside <paramref name="parentPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be checked.</param>
|
||||
/// <param name="parentPath">The path that must contain the checked path.</param>
|
||||
/// <returns><see langword="true"/> if the path is inside the parent path, <see langword="false"/> otherwise.</returns>
|
||||
public bool IsPathWithin(string path, string parentPath)
|
||||
{
|
||||
Result<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
|
||||
if (newPathResult.IsFailure)
|
||||
return false;
|
||||
Result<FileSystemPathId> parentPathResult = FileSystemPathId.Create(parentPath);
|
||||
if (parentPathResult.IsFailure)
|
||||
return false;
|
||||
return _platformContext.PathStrategy.IsPathWithin(newPathResult.Value, parentPathResult.Value);
|
||||
}
|
||||
}
|
||||
+10
-2
@@ -24,9 +24,9 @@ public interface IPathStrategy
|
||||
/// Checks if <paramref name="path"/> exists.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be checked.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <returns><see langword="true"/> if <paramref name="path"/> exists, <see langword="false"/> otherwise.</returns>
|
||||
bool Exists(FileSystemPathId path, bool includeHiddenElements = true);
|
||||
bool Exists(FileSystemPathId path, bool shouldIncludeHiddenElements = true);
|
||||
|
||||
/// <summary>
|
||||
/// Tries to combine <paramref name="path"/> with <paramref name="name"/>.
|
||||
@@ -68,4 +68,12 @@ public interface IPathStrategy
|
||||
/// <param name="path">The path for which to get the root.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing the root of <paramref name="path"/>, or an error.</returns>
|
||||
Result<PathSegment> GetPathRoot(FileSystemPathId path);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether <paramref name="path"/> is located inside <paramref name="parentPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be checked.</param>
|
||||
/// <param name="parentPath">The path that must contain the checked path.</param>
|
||||
/// <returns><see langword="true"/> if the path is inside the parent path, <see langword="false"/> otherwise.</returns>
|
||||
bool IsPathWithin(FileSystemPathId path, FileSystemPathId parentPath);
|
||||
}
|
||||
+63
-20
@@ -37,11 +37,11 @@ public class UnixPathStrategy : IUnixPathStrategy
|
||||
/// <returns><see langword="true"/> if <paramref name="path"/> is a valid path, <see langword="false"/> otherwise.</returns>
|
||||
public bool IsValidPath(FileSystemPathId path)
|
||||
{
|
||||
// check for invalid path characters
|
||||
// Check for invalid path characters.
|
||||
char[] invalidChars = GetInvalidPathCharsForPlatform();
|
||||
if (path.Path.IndexOfAny(invalidChars) >= 0)
|
||||
return false;
|
||||
// check for relative paths
|
||||
// Check for relative paths.
|
||||
if (path.Path.StartsWith("./") || path.Path.StartsWith("../"))
|
||||
return false;
|
||||
const string PATH_PATTERN = @"^\/([\w\-\.\~!$&'()*+,;=:@\[\] ]+(\/[\w\-\.\~!$&'()*+,;=:@\[\] ]+)*)?\/?$";
|
||||
@@ -52,9 +52,9 @@ public class UnixPathStrategy : IUnixPathStrategy
|
||||
/// Checks if <paramref name="path"/> exists.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be checked.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <returns><see langword="true"/> if <paramref name="path"/> exists, <see langword="false"/> otherwise.</returns>
|
||||
public bool Exists(FileSystemPathId path, bool includeHiddenElements = true)
|
||||
public bool Exists(FileSystemPathId path, bool shouldIncludeHiddenElements = true)
|
||||
{
|
||||
if (!_fileSystem.Path.Exists(path.Path))
|
||||
return false;
|
||||
@@ -69,9 +69,9 @@ public class UnixPathStrategy : IUnixPathStrategy
|
||||
IFileInfo fileInfo = _fileSystem.FileInfo.New(path.Path);
|
||||
isHidden = (fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
|
||||
}
|
||||
else // path exists but is neither a file nor a directory (drive, etc)
|
||||
else // The path exists but is neither a file nor a directory (drive, etc.).
|
||||
return true;
|
||||
return includeHiddenElements || !isHidden;
|
||||
return shouldIncludeHiddenElements || !isHidden;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -84,11 +84,11 @@ public class UnixPathStrategy : IUnixPathStrategy
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
return Errors.FileSystemManagement.NameCannotBeEmpty;
|
||||
// trim any directory separator characters from the end of the path
|
||||
// Trim any directory separator characters from the end of the path.
|
||||
string subpath = path.Path.TrimEnd(PathSeparator);
|
||||
// if the name begins with a directory separator, remove it
|
||||
// If the name begins with a directory separator, remove it.
|
||||
name = name.TrimStart(PathSeparator);
|
||||
// combine the two parts with the Unix directory separator character
|
||||
// Combine the two parts with the Unix directory separator character.
|
||||
return FileSystemPathId.Create(subpath + PathSeparator + name + PathSeparator);
|
||||
}
|
||||
|
||||
@@ -99,20 +99,20 @@ public class UnixPathStrategy : IUnixPathStrategy
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing the path segments, or an error.</returns>
|
||||
public Result<IEnumerable<PathSegment>> ParsePath(FileSystemPathId path)
|
||||
{
|
||||
// if path starts with anything other than '/', it's considered relative and invalid for this parser
|
||||
// If the path starts with anything other than '/', it is considered relative and invalid for this parser.
|
||||
if (!path.Path.StartsWith(PathSeparator))
|
||||
return Errors.FileSystemManagement.InvalidPath;
|
||||
// get the path segments
|
||||
// Get the path segments.
|
||||
List<string> splitSegments = [.. path.Path.Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries)];
|
||||
IEnumerable<Result<PathSegment>> segmentsResults = splitSegments.Select((segment, index) =>
|
||||
{
|
||||
bool isDirectory;
|
||||
if (segment.Contains('.'))
|
||||
isDirectory = index != splitSegments.Count - 1 || path.Path.EndsWith(PathSeparator); // check if it's the last segment or if the path ends with a '/'
|
||||
isDirectory = index != splitSegments.Count - 1 || path.Path.EndsWith(PathSeparator); // Check if it is the last segment or if the path ends with a '/'.
|
||||
else
|
||||
isDirectory = true;
|
||||
return PathSegment.Create(segment, isDirectory, isDrive: false);
|
||||
}).Prepend(PathSegment.Create(PathSeparator.ToString(), isDirectory: false, isDrive: true)); // UNIX paths have '/' as "root drive"
|
||||
}).Prepend(PathSegment.Create(PathSeparator.ToString(), isDirectory: false, isDrive: true)); // UNIX paths have '/' as their "root drive".
|
||||
foreach (Result<PathSegment> segment in segmentsResults)
|
||||
if (segment.IsFailure)
|
||||
return segment.Errors;
|
||||
@@ -126,19 +126,19 @@ public class UnixPathStrategy : IUnixPathStrategy
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing the path segments of the path up one level from <paramref name="path"/>, or an error.</returns>
|
||||
public Result<IEnumerable<PathSegment>> GoUpOneLevel(FileSystemPathId path)
|
||||
{
|
||||
// validation: ensure the path is not null or empty
|
||||
// Validation: ensure the path is not null or empty.
|
||||
if (!IsValidPath(path))
|
||||
return Errors.FileSystemManagement.InvalidPath;
|
||||
// trim trailing slash for consistent processing
|
||||
// Trim the trailing slash for consistent processing.
|
||||
string tempPath = path.Path;
|
||||
if (tempPath.EndsWith('/'))
|
||||
tempPath = tempPath.TrimEnd(PathSeparator);
|
||||
// find the last occurrence of a slash
|
||||
// Find the last occurrence of a slash.
|
||||
int lastIndex = tempPath.LastIndexOf(PathSeparator);
|
||||
// if there's no slash found (shouldn't happen due to previous steps), or if we are at the root level after trimming, return error
|
||||
// If no slash is found (which should not happen after the previous steps), or if we are at the root level after trimming, return an error.
|
||||
if (lastIndex < 0)
|
||||
return Errors.FileSystemManagement.CannotNavigateUp;
|
||||
// return the path up to the last slash, or, if there's only the root slash, return that one instead
|
||||
// Return the path up to the last slash, or, if there is only the root slash, return that one instead.
|
||||
Result<FileSystemPathId> newPathResult = FileSystemPathId.Create(lastIndex > 0 ? tempPath[..lastIndex] : tempPath[..1]);
|
||||
if (newPathResult.IsFailure)
|
||||
return newPathResult.Errors;
|
||||
@@ -148,7 +148,7 @@ public class UnixPathStrategy : IUnixPathStrategy
|
||||
/// <summary>
|
||||
/// Returns a collection of characters that are invalid for paths.
|
||||
/// </summary>
|
||||
/// <returns>A collection of characters that are invalid in the context of paths</returns>
|
||||
/// <returns>A collection of characters that are invalid in the context of paths.</returns>
|
||||
public char[] GetInvalidPathCharsForPlatform()
|
||||
{
|
||||
return ['\0'];
|
||||
@@ -173,9 +173,52 @@ public class UnixPathStrategy : IUnixPathStrategy
|
||||
if (!IsValidPath(path))
|
||||
return Errors.FileSystemManagement.InvalidPath;
|
||||
|
||||
// On Unix-like systems, the root is always "/"
|
||||
// On Unix-like systems, the root is always "/".
|
||||
if (path.Path.StartsWith(PathSeparator))
|
||||
return PathSegment.Create(PathSeparator.ToString(), isDirectory: false, isDrive: true);
|
||||
return Errors.FileSystemManagement.InvalidPath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether <paramref name="path"/> is located inside <paramref name="parentPath"/>. The comparison resolves the "." and ".."
|
||||
/// segments first, so that a path can never escape its parent through relative segments, and it is case-sensitive, because
|
||||
/// Unix paths are case-sensitive.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be checked.</param>
|
||||
/// <param name="parentPath">The path that must contain the checked path.</param>
|
||||
/// <returns><see langword="true"/> if the path is inside the parent path, <see langword="false"/> otherwise.</returns>
|
||||
public bool IsPathWithin(FileSystemPathId path, FileSystemPathId parentPath)
|
||||
{
|
||||
string[] pathSegments = NormalizePathSegments(path.Path);
|
||||
string[] parentPathSegments = NormalizePathSegments(parentPath.Path);
|
||||
if (parentPathSegments.Length == 0 || pathSegments.Length <= parentPathSegments.Length)
|
||||
return false;
|
||||
for (int index = 0; index < parentPathSegments.Length; index++)
|
||||
if (!string.Equals(pathSegments[index], parentPathSegments[index], StringComparison.Ordinal))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Splits <paramref name="path"/> into its segments, resolving the "." (current directory) and ".." (parent directory) segments.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be normalized.</param>
|
||||
/// <returns>The normalized path segments of the path.</returns>
|
||||
private string[] NormalizePathSegments(string path)
|
||||
{
|
||||
List<string> segments = [];
|
||||
foreach (string segment in path.Split([PathSeparator], StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (segment == ".")
|
||||
continue;
|
||||
if (segment == "..")
|
||||
{
|
||||
if (segments.Count > 0)
|
||||
segments.RemoveAt(segments.Count - 1);
|
||||
continue;
|
||||
}
|
||||
segments.Add(segment);
|
||||
}
|
||||
return [.. segments];
|
||||
}
|
||||
}
|
||||
+82
-39
@@ -37,12 +37,12 @@ public class WindowsPathStrategy : IWindowsPathStrategy
|
||||
/// <returns><see langword="true"/> if <paramref name="path"/> is a valid path, <see langword="false"/> otherwise.</returns>
|
||||
public bool IsValidPath(FileSystemPathId path)
|
||||
{
|
||||
// check for invalid path characters
|
||||
// Check for invalid path characters.
|
||||
char[] invalidChars = GetInvalidPathCharsForPlatform();
|
||||
if (path.Path.IndexOfAny(invalidChars) >= 0)
|
||||
return false;
|
||||
// regular expression to match valid absolute paths
|
||||
// this allows drive letters (e.g., C:\) and UNC paths (e.g., \\server\share)
|
||||
// Regular expression to match valid absolute paths.
|
||||
// This allows drive letters (e.g., C:\) and UNC paths (e.g., \\server\share).
|
||||
const string PATH_PATTERN = @"^(?:[a-zA-Z]:\\|\\\\[a-zA-Z0-9\s()._&+,\[\]-]+\\[a-zA-Z0-9\s()._&+,\[\]-]+)(?:[a-zA-Z0-9\s()._&+,\[\]-]+\\)*[a-zA-Z0-9\s()._&+,\[\]-]*\\?$";
|
||||
return Regex.IsMatch(path.Path, PATH_PATTERN);
|
||||
}
|
||||
@@ -51,9 +51,9 @@ public class WindowsPathStrategy : IWindowsPathStrategy
|
||||
/// Checks if <paramref name="path"/> exists.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be checked.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <returns><see langword="true"/> if <paramref name="path"/> exists, <see langword="false"/> otherwise.</returns>
|
||||
public bool Exists(FileSystemPathId path, bool includeHiddenElements = true)
|
||||
public bool Exists(FileSystemPathId path, bool shouldIncludeHiddenElements = true)
|
||||
{
|
||||
if (!_fileSystem.Path.Exists(path.Path))
|
||||
return false;
|
||||
@@ -68,9 +68,9 @@ public class WindowsPathStrategy : IWindowsPathStrategy
|
||||
IFileInfo fileInfo = _fileSystem.FileInfo.New(path.Path);
|
||||
isHidden = (fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
|
||||
}
|
||||
else // path exists but is neither a file nor a directory (drive, etc)
|
||||
else // The path exists but is neither a file nor a directory (drive, etc.).
|
||||
return true;
|
||||
return includeHiddenElements || !isHidden;
|
||||
return shouldIncludeHiddenElements || !isHidden;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -81,13 +81,13 @@ public class WindowsPathStrategy : IWindowsPathStrategy
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing the combined path, or an error.</returns>
|
||||
public Result<FileSystemPathId> CombinePath(FileSystemPathId path, string name)
|
||||
{
|
||||
if (name == null)
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
return Errors.FileSystemManagement.NameCannotBeEmpty;
|
||||
// trim any directory separator characters from the end of the path
|
||||
// Trim any directory separator characters from the end of the path.
|
||||
string subpath = path.Path.TrimEnd(PathSeparator);
|
||||
// if the name begins with a directory separator, remove it
|
||||
// If the name begins with a directory separator, remove it.
|
||||
name = name.TrimStart(PathSeparator);
|
||||
// combine the two parts with the Windows directory separator character
|
||||
// Combine the two parts with the Windows directory separator character.
|
||||
return FileSystemPathId.Create(subpath + PathSeparator + name + PathSeparator);
|
||||
}
|
||||
|
||||
@@ -98,7 +98,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing the path segments, or an error.</returns>
|
||||
public Result<IEnumerable<PathSegment>> ParsePath(FileSystemPathId path)
|
||||
{
|
||||
// Windows paths usually start with a drive letter and colon, e.g., "C:", or "\\" (UNC paths)
|
||||
// Windows paths usually start with a drive letter and colon (e.g., "C:") or with "\\" (UNC paths).
|
||||
if (!(path.Path.StartsWith(@"\\") || (path.Path.Length >= 3 && char.IsLetter(path.Path[0]) && path.Path[1] == ':' && path.Path[2] == PathSeparator)))
|
||||
return Errors.FileSystemManagement.InvalidPath;
|
||||
IEnumerable<Result<PathSegment>> getPathSegmentsResults = GetPathSegments();
|
||||
@@ -110,25 +110,25 @@ public class WindowsPathStrategy : IWindowsPathStrategy
|
||||
{
|
||||
if (path.Path.StartsWith(@"\\"))
|
||||
{
|
||||
// handle UNC path
|
||||
// Handle a UNC path.
|
||||
yield return PathSegment.Create(@"\\", isDirectory: false, isDrive: true);
|
||||
|
||||
string[] segments = path.Path[2..].Split([PathSeparator], StringSplitOptions.RemoveEmptyEntries);
|
||||
for (int i = 0; i < segments.Length; i++)
|
||||
yield return CreatePathSegment(segments[i], i, segments.Length);
|
||||
}
|
||||
else // handle regular Windows path
|
||||
else // Handle a regular Windows path.
|
||||
{
|
||||
// the drive segment
|
||||
// The drive segment.
|
||||
yield return PathSegment.Create(path.Path[..2], isDirectory: false, isDrive: true);
|
||||
// extract the other segments
|
||||
// Extract the other segments.
|
||||
string[] segments = path.Path[3..].Split([PathSeparator], StringSplitOptions.RemoveEmptyEntries);
|
||||
for (int i = 0; i < segments.Length; i++)
|
||||
{
|
||||
string segment = segments[i];
|
||||
bool isDirectory;
|
||||
if (segment.Contains('.'))
|
||||
isDirectory = i != segments.Length - 1 || path.Path.EndsWith(PathSeparator); // check if it's the last segment or if the next segment also contains a path delimiter
|
||||
isDirectory = i != segments.Length - 1 || path.Path.EndsWith(PathSeparator); // Check if it is the last segment, or if the next segment also contains a path delimiter.
|
||||
else
|
||||
isDirectory = true;
|
||||
yield return PathSegment.Create(segment, isDirectory, isDrive: false);
|
||||
@@ -151,29 +151,29 @@ public class WindowsPathStrategy : IWindowsPathStrategy
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing the path segments of the path up one level from <paramref name="path"/>, or an error.</returns>
|
||||
public Result<IEnumerable<PathSegment>> GoUpOneLevel(FileSystemPathId path)
|
||||
{
|
||||
// validation: ensure the path is not null or empty
|
||||
// Validation: ensure the path is not null or empty.
|
||||
if (!IsValidPath(path))
|
||||
return Errors.FileSystemManagement.InvalidPath;
|
||||
// trim trailing backslash for consistent processing
|
||||
// Trim the trailing backslash for consistent processing.
|
||||
string tempPath = path.Path.TrimEnd(PathSeparator);
|
||||
// check for UNC path
|
||||
// Check for a UNC path.
|
||||
if (tempPath.StartsWith(@"\\"))
|
||||
{
|
||||
string[] parts = tempPath.Split(PathSeparator, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length <= 2)
|
||||
return Errors.FileSystemManagement.CannotNavigateUp;
|
||||
// if it's a single-level UNC path, return the UNC root
|
||||
// If it is a single-level UNC path, return the UNC root.
|
||||
if (parts.Length == 3)
|
||||
return ParsePath(FileSystemPathId.Create($@"\\{parts[0]}\{parts[1]}").Value);
|
||||
} // check for drive root (both with and without trailing backslash)
|
||||
} // Check for the drive root, both with and without a trailing backslash.
|
||||
else if ((tempPath.Length == 2 && tempPath[1] == ':') || (tempPath.Length == 3 && tempPath[1] == ':' && tempPath[2] == PathSeparator))
|
||||
return Errors.FileSystemManagement.CannotNavigateUp;
|
||||
// find the last occurrence of a backslash
|
||||
// Find the last occurrence of a backslash.
|
||||
int lastIndex = tempPath.LastIndexOf(PathSeparator);
|
||||
// if there's no backslash found or it's at the root level, return the root
|
||||
// If no backslash is found or it is at the root level, return the root.
|
||||
if (lastIndex <= 2)
|
||||
return ParsePath(FileSystemPathId.Create(tempPath[..3]).Value);
|
||||
// return the path up to the last backslash
|
||||
// Return the path up to the last backslash.
|
||||
Result<FileSystemPathId> newPathResult = FileSystemPathId.Create(tempPath[..lastIndex]);
|
||||
if (newPathResult.IsFailure)
|
||||
return newPathResult.Errors;
|
||||
@@ -184,7 +184,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy
|
||||
/// <summary>
|
||||
/// Returns a collection of characters that are invalid for paths.
|
||||
/// </summary>
|
||||
/// <returns>A collection of characters that are invalid in the context of paths</returns>
|
||||
/// <returns>A collection of characters that are invalid in the context of paths.</returns>
|
||||
public char[] GetInvalidPathCharsForPlatform()
|
||||
{
|
||||
return ['<', '>', '"', '/', '|', '?', '*'];
|
||||
@@ -208,28 +208,71 @@ public class WindowsPathStrategy : IWindowsPathStrategy
|
||||
{
|
||||
if (!IsValidPath(path))
|
||||
return Errors.FileSystemManagement.InvalidPath;
|
||||
// handle UNC paths (e.g., \\server\share\folder)
|
||||
// Handle UNC paths (e.g., \\server\share\folder).
|
||||
if (path.Path.StartsWith(@"\\"))
|
||||
{
|
||||
// find the position of the second backslash (after \\server)
|
||||
// Find the position of the second backslash (after \\server).
|
||||
int secondBackslash = path.Path.IndexOf('\\', 2);
|
||||
if (secondBackslash == -1)
|
||||
return Errors.FileSystemManagement.InvalidPath; // invalid UNC path, missing server name
|
||||
// find the position of the third backslash (after \\server\share)
|
||||
return Errors.FileSystemManagement.InvalidPath; // Invalid UNC path, missing server name.
|
||||
// Find the position of the third backslash (after \\server\share).
|
||||
int thirdBackslash = path.Path.IndexOf('\\', secondBackslash + 1);
|
||||
if (thirdBackslash == -1)
|
||||
thirdBackslash = path.Path.Length; // no third backslash, use entire path
|
||||
// return the UNC root (\\server\share\)
|
||||
thirdBackslash = path.Path.Length; // No third backslash, use the entire path.
|
||||
// Return the UNC root (\\server\share\).
|
||||
return PathSegment.Create(path.Path[..thirdBackslash] + "\\", isDirectory: true, isDrive: false);
|
||||
}
|
||||
else // handle drive letter paths (e.g., C:\folder)
|
||||
// check if the path starts with a drive letter followed by a colon (e.g., C:)
|
||||
// path.Path.Length >= 2: Ensure the path is at least 2 characters long
|
||||
// char.IsLetter(path.Path[0]): First character should be a letter
|
||||
// path.Path[1] == ':': Second character should be a colon
|
||||
else // Handle drive letter paths (e.g., C:\folder).
|
||||
// Check if the path starts with a drive letter followed by a colon (e.g., C:).
|
||||
// The path must be at least 2 characters long.
|
||||
// The first character must be a letter.
|
||||
// The second character must be a colon.
|
||||
if (path.Path.Length >= 2 && char.IsLetter(path.Path[0]) && path.Path[1] == ':')
|
||||
return PathSegment.Create(path.Path[..2] + "\\", isDirectory: true, isDrive: true); // return the drive root (e.g., C:\)
|
||||
// if we reach here, the path is neither a valid UNC path nor a valid drive path
|
||||
return PathSegment.Create(path.Path[..2] + "\\", isDirectory: true, isDrive: true); // Return the drive root (e.g., C:\).
|
||||
// If we reach here, the path is neither a valid UNC path nor a valid drive path.
|
||||
return Errors.FileSystemManagement.InvalidPath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether <paramref name="path"/> is located inside <paramref name="parentPath"/>. The comparison resolves the "." and ".."
|
||||
/// segments first, so that a path can never escape its parent through relative segments, and it is case-insensitive, because
|
||||
/// Windows paths are case-insensitive.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be checked.</param>
|
||||
/// <param name="parentPath">The path that must contain the checked path.</param>
|
||||
/// <returns><see langword="true"/> if the path is inside the parent path, <see langword="false"/> otherwise.</returns>
|
||||
public bool IsPathWithin(FileSystemPathId path, FileSystemPathId parentPath)
|
||||
{
|
||||
string[] pathSegments = NormalizePathSegments(path.Path);
|
||||
string[] parentPathSegments = NormalizePathSegments(parentPath.Path);
|
||||
if (parentPathSegments.Length == 0 || pathSegments.Length <= parentPathSegments.Length)
|
||||
return false;
|
||||
for (int index = 0; index < parentPathSegments.Length; index++)
|
||||
if (!string.Equals(pathSegments[index], parentPathSegments[index], StringComparison.OrdinalIgnoreCase))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Splits <paramref name="path"/> into its segments, resolving the "." (current directory) and ".." (parent directory) segments.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be normalized.</param>
|
||||
/// <returns>The normalized path segments of the path.</returns>
|
||||
private string[] NormalizePathSegments(string path)
|
||||
{
|
||||
List<string> segments = [];
|
||||
foreach (string segment in path.Split([PathSeparator], StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (segment == ".")
|
||||
continue;
|
||||
if (segment == "..")
|
||||
{
|
||||
if (segments.Count > 0)
|
||||
segments.RemoveAt(segments.Count - 1);
|
||||
continue;
|
||||
}
|
||||
segments.Add(segment);
|
||||
}
|
||||
return [.. segments];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user