Repository navigation
Description
Background and motivation
Developers need a way to handle events while recursing directories with FileSystemEnumerable. The FileSystemEnumerator API already gives the ability to do this by exposing ContinueOnError(int), OnDirectoryFinished(ROS<char>), ShouldIncludeEntry(FilesystemEntry), and ShouldRecurseIntoEntry(FileSystemEntry). The last two methods can be easily used with the FileSystemEnumerable API as it allows you set delegates for them. This proposal is about completing the scenario by adding two more delegate properties for the remaining two.
Use case description:
In PowerShell Core repo we are trying to migrate to FileSystemEnumerable.
We need to implement error handling so that continue processing on an error and logging the error.
Also for consistency it would be great to get OnDirectoryFinishedDelegate.
Proposed API
public class FileSystemEnumerable<TResult> : IEnumerable<TResult>
{
public FindPredicate? ShouldIncludePredicate { get; set; } // Existing API
public FindPredicate? ShouldRecursePredicate { get; set; } // Existing API
public delegate void OnDirectoryFinishedDelegate(ReadOnlySpan<char> directory); // New API
public OnDirectoryFinishedDelegate? OnDirectoryFinishedAction { get; set; } // New API
public delegate bool ContinueOnErrorPredicate(int error); // New API
public ContinueOnErrorPredicate? ShouldContinueOnErrorPredicate { get; set; } // New API
}API usage
using System.IO.Enumeration;
string directory = "...";
var context = ... // PowerShell context
var files = new FileSystemEnumerable<string>(
directory,
// Yes, it is weird but we should write right error for root directory too.
(ref FileSystemEntry entry) => entry.OriginalRootDirectory.Length > entry.Directory.Length ? entry.FileName.ToString() : Path.Join(entry.Directory.Slice(entry.OriginalRootDirectory.Length), entry.FileName),
options)
{
ShouldContinueOnErrorPredicate = (int error) =>
{
if (error == 5) // ERROR_ACCESS_DENIED
{
// Log the error...
}
if (error == 3) // ERROR_PATH_NOT_FOUND
{
return false;
}
return true;
}
};Alternative Designs: define FileSystemErrorInfo to abstract the OS native error (this differs from FileSystemEnumerator<T>.ContinueOnError(int)).
public class FileSystemEnumerable<TResult> : IEnumerable<TResult>
{
public FindPredicate? ShouldIncludePredicate { get; set; } // Existing API
public FindPredicate? ShouldRecursePredicate { get; set; } // Existing API
public delegate void OnDirectoryFinishedDelegate(ReadOnlySpan<char> directory); // New API
public OnDirectoryFinishedDelegate? OnDirectoryFinishedAction { get; set; } // New API
public delegate bool ContinueOnErrorPredicate(FileSystemErrorInfo errorInfo); // New API
public ContinueOnErrorPredicate? ShouldContinueOnErrorPredicate { get; set; } // New API
}
public readonly ref struct FileSystemErrorInfo
{
// internal FileSystemErrorInfo(int errno, string path);
public int Error { get; }; // 'errno' is converted on Unix with `internal struct ErrorInfo` to platform-agnostic Error
public string Path { get; };
public Exception GetException(); // Gets platform-agnostic exception for the error
public string GetErrorMessage(); // Optional for me but could be useful due to absence of extra allocations with GetException()
}
public unsafe abstract partial class FileSystemEnumerator<TResult> : CriticalFinalizerObject, IEnumerator<TResult>
{
[Obsolete("The method is deprecated. Use ContinueOnError(FileSystemErrorInfo errorInfo) instead.")] // New API
protected virtual bool ContinueOnError(int error); // Deprecate
protected virtual bool ContinueOnError(FileSystemErrorInfo errorInfo); // New API
}Remarkable questions
- Should we use
events? - Should
OnDirectoryFinishedDelegate(ROS<char>)should beOnDirectoryFinishedDelegate(FilesystemEntry)
This would differ from what the Enumerator type exposes; implementation-wise we would need to create an extra FileSystemEntry that represents the root directory (could impact perf?).
Activity
JeremyKuhne commentedon Mar 4, 2020
This is not the first time I've been asked for this and it is pretty straight-forward, I think we should add this for 5.0.
iSazonov commentedon May 18, 2020
For full consistency I'd add a delegate for
ContinueOnError()too.danmoseley commentedon Jul 23, 2020
@iSazonov How would the "depth limit" scenario work with these predicates? In the implementation of ShouldRecursePredicate would it examine the FileSystemEntry and then calculate the depth vs the start of the recursion (perhaps with Path.GetRelativePath and counting the double dots?)
As with any API proposal it might be useful to write out what the user code would look like.
iSazonov commentedon Jul 23, 2020
@danmosemsft You can see draft code in PowerShell repo PowerShell/PowerShell#12834. The PR demonstrates well a real scenario of using the API.
danmoseley commentedon Jul 23, 2020
@iSazonov to make the API review meetings efficient we ask that all the supporting info be in the proposal (ideally in the top post). For API proposals this ideally includes small usage examples to help demo how the API would be used
iSazonov commentedon Jul 23, 2020
@danmosemsft I added a code snipped from the PowerShell PR.
17 remaining items
jozkee commentedon Feb 15, 2022
For
OnDirectoryFinishedDelegate(ref FileSystemEntry entry): do we want to add an equivalent API toFileSystemEnumeratorand obsolete the current one taking just a ReadOnlySpan?For
bool ContinueOnErrorPredicate(FileSystemErrorInfo errorInfo): can we consider not adding another type and instead re-use FileSystemEntry? If so, I think the API can look likebool ContinueOnErrorPredicate(int error, ref FileSystemEntry entry)I don't see very usefulGetException()andGetErrorMessage().@iSazonov if you are blocked by this, you think you can extend the Enumerator and work with that? e.g:
iSazonov commentedon Feb 16, 2022
If we look current implementation there is no FileSystemEntry instance in points where the error is detected. And I don't see needs to create the instance for "parent" path in the error report (user himself can create Directory/FileInfo if needed) - we can easily have parent path but what about error code - it will OS specific but we need OS agnostic.
As for GetException() and GetErrorMessage(), these address previous API review request to have OS agnostic error report since today we get an OS specific Int value. We could remove FileSystemErrorInfo from the API proposal and return Exception which contains the native error code, but we lost parent path since it will be in error message only. So we again come back to previous API review and suggestion to have new (extendable) type for error reporting.
Yes, it makes sense.If we look current implementation again there is not actual FileSystemEntry instance for parentpath so ReadOnlySpan is ok.I can not process ContinueOnError(int error) well and as result the issue was opened :-)
jozkee commentedon Feb 16, 2022
That's interesting because it contradicts the current
FileSystemEnumerator<TResult>.ContinueOnError(Int32)API which was approved by the same board. Did you get that feedback for this specific proposal? If not, I think this can be an exception and can be discussed live.The trade-off with handling
int errorvsFileSystemErrorInfo errorInfois that people providingContinueOnErrorPredicates will have to write OS-specific code for the former, and for the latter the API will diverge from the current API of the enumerator, plus we may need to add an API to the enumerator (to be consistent) and obsolete the current one.@iSazonov I know you originally opened with the purpose of handling Max Depth, which is now supported by
EnumerationOptions. Can you provide samples that will be addressed by adding this new set of APIs?iSazonov commentedon Feb 17, 2022
Sorry, it seems I don't understand your question. If I remember right Jeremy made a proposal for file enumeration with a lot of new APIs, some from them (including ContinueOnError) was under "need feedback from community". First feedback (as Jeremy mentioned) was community want delegates for all virtual methods so I added OnDirectoryFinishedDelegate in the proposal.
Second feedback comes from my experience with PowerShell code. As I already described PowerShell writes warning messages on (access denied) errors and continue enumeration. (And I'd happy to avoid OS Specific error code processing.) So I added new ContinueOnErrorPredicate in the proposal.
In my old PR PowerShell/PowerShell#12834 you can see how weird looks code (notice, I don't OS specific error code processing there for the example simplicity!) with ContinueOnError(int error) - with ContinueOnError(FileSystemErrorInfo errorInfo) we get exactly we need.
jozkee commentedon Feb 17, 2022
I agree this proposal is about adding delegates for all virtual in the Enumerator and set them as properties in the Enumerable. What I am pointing out is that the virtual method
FileSystemEnumerator<TResult>.ContinueOnError(Int32)already sets precedence for receiving the native error code and should consider follow that precedence.So I would suggest having FileSystemErrorInfo as an alternative design.
Could you please write a minimal sample in here? It would be hard to scroll through your PR while reviewing the proposal.
iSazonov commentedon Feb 17, 2022
Yes, of cause.
bartonjs commentedon Sep 20, 2022
Video
Func<int, bool>ReadOnlySpan<char>. And then it becomesAction<string>.Action Required:
Func<string, int, bool>, something complicated with current directory and current candidate as different parameters, etc)iSazonov commentedon Sep 21, 2022
I agree it is important to pass current context to custom error handler.
Previous proposal contains
readonly ref struct FileSystemErrorInfoto pass a context to the custom error handler.But if we would agree errors in enumaration time are rare we could pass exception instance which contains all information we need and more (like resource string message). This is very convenient and eliminates the need to duplicate non-trivial code
Interop.GetExceptionForIoErrno(). Notice, the exception is OS indepentent!So we could rewrite follow
runtime/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.Unix.cs
Lines 69 to 82 in 2f3fcca
with
This is consistent with the way PowerShell works - catch an exception and print a friendly message to the user, i.e. the exception instance is used anyway.
If there are applications where efficiency is critical at this point, they can use the existing
ContinueOnError(int error).Current proposal:
CyberSinh commentedon May 12, 2023
I understand that this thread still needs some work before it can be reviewed again.
What exactly is expected from the .NET team?
No feedback has been given on the API suggestion proposed by @iSazonov above.