コード例 #1
0
        /// <summary>
        /// Gets the absolute input path that contains the specified file or directory. If the provided
        /// file or directory path is absolute, this returns the input path that contains the specified
        /// path (note that the specified file or directory does not need to exist and this just returns
        /// the input path that would contain the file or directory based only on path information). If
        /// the provided path is relative, this checks all input paths for the existence of the file
        /// or directory and returns the first one where it exists.
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="path">The file path.</param>
        /// <returns>The input path that contains the specified file,
        /// or <c>null</c> if no input path does.</returns>
        public static NormalizedPath GetContainingInputPath(this IReadOnlyFileSystem fileSystem, NormalizedPath path)
        {
            _ = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem));
            path.ThrowIfNull(nameof(path));

            if (path.IsAbsolute)
            {
                return(fileSystem.GetContainingInputPathForAbsolutePath(path));
            }

            // Try to find a file first
            IFile file = fileSystem.GetInputFile(path);

            if (file.Exists)
            {
                return(fileSystem.GetContainingInputPath(file.Path));
            }

            // Then try to find a directory
            IEnumerable <(NormalizedPath x, IDirectory)> rootDirectories =
                fileSystem.InputPaths
                .Reverse()
                .Select(x => (x, fileSystem.GetRootDirectory(x.Combine(path))));
            IEnumerable <(NormalizedPath x, IDirectory)> existingRootDirectories = rootDirectories.Where(x => x.Item2.Exists);

            return(existingRootDirectories.Select(x => fileSystem.RootPath.Combine(x.Item1)).FirstOrDefault());
        }