public Enumerator(DirectoryInfoBase root, string pattern, SearchOption option, IList <Exception> errors) { this.root = root; this.pattern = pattern; this.errors = errors; this.searchOption = option; Reset(); }
// Load a project from the project file at path. // If path is a directory, the directory and its parent directories will be searched for a project file. public static Project Load(string path, IFileSystem fileSystem) { Project project = null; DirectoryInfoBase folder = null; // If the path points to a file, load it if (fileSystem.File.Exists(path)) { project = LoadJSON <Project>(path, fileSystem); FileInfoBase file = fileSystem.FileInfo.FromFileName(path); folder = file.Directory; } else if (fileSystem.Directory.Exists(path)) { foreach (DirectoryInfoBase searchFolder in GetSearchLocations(path, fileSystem)) { FileInfoBase[] files = searchFolder.GetFiles(@"staticsql.json"); if (files.Length == 1) { FileInfoBase file = files.Single(); project = LoadJSON <Project>(file.FullName, fileSystem); folder = file.Directory; break; } else if (files.Length > 1) { throw new StaticSQLException("Multiple project files found " + string.Join(", ", files.Select(f => f.FullName))); } } } if (folder is null) { throw new StaticSQLException("No project file found."); } project.EntityFolderPath = fileSystem.Path.Combine(folder.FullName, project.relativeEntityFolderPath); foreach (string entityPath in fileSystem.Directory.GetFiles(project.EntityFolderPath, ".\\*.json", System.IO.SearchOption.AllDirectories)) { Entity entity = LoadJSON <Entity>(entityPath, fileSystem); entity.FilePath = entityPath; entity.Project = project; int index = 0; foreach (Attribute attr in entity.Attributes) { attr.Entity = entity; attr.Index = index; index += 1; } project.Entities.Add(entity); } return(project); }
public static bool IsEmpty(this DirectoryInfoBase info) { if (info == null) { return(true); } FileSystemInfoBase[] fileSystemInfos = OperationManager.Attempt(() => info.GetFileSystemInfos()); return(fileSystemInfos.Length == 0); }
public MockFileInfo( FileSystemOperationRecorder recorder, DirectoryInfoBase parentDirectory, string fullName, string name) { Recorder = recorder; FullName = fullName; Name = name; }
public void MockFileInfo_GetDirectory_ShouldReturnDirectoryInfoWithCorrectPath() { // Arrange MockFileInfo fileInfo = new MockFileInfo(new MockFileSystem(), XFS.Path(@"c:\temp\level1\level2\file.txt")); // Act DirectoryInfoBase result = fileInfo.Directory; Assert.Equal(XFS.Path(@"c:\temp\level1\level2"), result.FullName); }
internal static Dictionary <string, FileInfoBase> GetJobDirectoryFileMap(string sourceDirectory) { DirectoryInfoBase jobBinariesDirectory = FileSystemHelpers.DirectoryInfoFromDirectoryName(sourceDirectory); FileInfoBase[] files = jobBinariesDirectory.GetFiles("*.*", SearchOption.AllDirectories); int sourceDirectoryPathLength = sourceDirectory.Length + 1; return(files.ToDictionary(p => p.FullName.Substring(sourceDirectoryPathLength), q => q, StringComparer.OrdinalIgnoreCase)); }
/// <summary> /// Returns directories and files that are stored in the specified directory /// </summary> /// <param name="dir">Start directory</param> /// <param name="cancelRecursionFlag">Flag to cancel searching</param> /// <returns>Directories and files that are stored in the specified directory</returns> private IEnumerable <FileSystemInfoBase> GetDirectoryItems(DirectoryInfoBase dir, ref bool cancelRecursionFlag) { var result = new List <FileSystemInfoBase>(); if (cancelRecursionFlag) { return(result); } foreach (var directory in dir.EnumerateDirectories()) { var eventParams = new ItemFindedEventArgs { FullName = directory.FullName }; OnDirectoryFinded(eventParams); if (eventParams.CancelSearching) { cancelRecursionFlag = true; result.Add(directory); return(result); } if (!eventParams.ExcludeItemFromResult) { result.Add(directory); } result.AddRange(GetDirectoryItems(directory, ref cancelRecursionFlag)); if (cancelRecursionFlag) { return(result); } } foreach (var fileInfo in dir.EnumerateFiles()) { var eventParams = new ItemFindedEventArgs { FullName = fileInfo.FullName }; OnFileFinded(eventParams); if (eventParams.CancelSearching) { cancelRecursionFlag = true; result.Add(fileInfo); return(result); } if (!eventParams.ExcludeItemFromResult) { result.Add(fileInfo); } } return(result); }
public IEnumerable <FileSystemInfoBase> GetDirectoryInnerEntities(DirectoryInfoBase entryDirectoryInfo) { bool isCancelled = false; foreach (var entryDirectoryEntity in entryDirectoryInfo.GetFileSystemInfos()) { if (isCancelled) { break; } EntityFoundArgs entityFoundArgs = new EntityFoundArgs() { EntityInfo = entryDirectoryEntity }; if (entryDirectoryEntity is DirectoryInfoBase) { entityFoundArgs.Message = "Directory found"; OnDirectoryFound(entityFoundArgs); if ((IsFilterAlgorithmPassed == null || IsFilterAlgorithmPassed(entryDirectoryEntity)) && !entityFoundArgs.IsExcluded) { entityFoundArgs.Message = "Filtered directory found"; OnFilteredDirectoryFound(entityFoundArgs); yield return(entryDirectoryEntity); } } else { entityFoundArgs.Message = "File found"; OnFileFound(entityFoundArgs); if ((IsFilterAlgorithmPassed == null || IsFilterAlgorithmPassed(entryDirectoryEntity)) && !entityFoundArgs.IsExcluded) { entityFoundArgs.Message = "Filtered file found"; OnFilteredFileFound(entityFoundArgs); yield return(entryDirectoryEntity); } } if (entityFoundArgs.IsCancelled) { isCancelled = true; } } if (!isCancelled) { foreach (var entryDirectoryEntity in entryDirectoryInfo.GetDirectories()) { foreach (var entity in GetDirectoryInnerEntities(entryDirectoryEntity)) { yield return(entity); } } } }
public void ExtractSnippetWrongRoot() { // Prepare the extraction FileSystemSnippetExtractor extractor = new FileSystemSnippetExtractor(); DirectoryInfoBase directoryInfoBase = fileSystem.DirectoryInfo.FromDirectoryName("FooBar"); // Run the extraction Assert.Throws( Is.TypeOf <SnippetExtractionException>().And.Message.EqualTo("Cannot find directory"), () => extractor.Extract(directoryInfoBase, null)); }
public void MockDirectory_GetParent_ShouldReturnADirectoryInfoIfPathDoesNotExist() { // Arrange MockFileSystem fileSystem = new MockFileSystem(); // Act DirectoryInfoBase actualResult = fileSystem.Directory.GetParent(XFS.Path(@"c:\directory\does\not\exist")); // Assert Assert.NotNull(actualResult); }
public static Uri ToUri(this DirectoryInfoBase instance) { string fullName = instance.FullName; if (!instance.FullName.EndsWith(@"\")) { fullName = fullName + @"\"; } return(fullName.ToFolderUri()); }
public FileProviderGlobbingFile(IFileInfo fileInfo, DirectoryInfoBase parent) { if (fileInfo == null) { throw new ArgumentNullException(nameof(fileInfo)); } Name = fileInfo.Name; ParentDirectory = parent ?? throw new ArgumentNullException(nameof(parent)); FullName = ParentDirectory.FullName + DirectorySeparatorChar + Name; }
/// <summary> /// Searches the directory specified for all files matching patterns added to this instance of <see cref="Matcher" /> /// </summary> /// <param name="directoryInfo">The root directory for the search</param> /// <returns>Always returns instance of <see cref="PatternMatchingResult" />, even if no files were matched</returns> public virtual PatternMatchingResult Execute(DirectoryInfoBase directoryInfo) { if (directoryInfo is null) { throw new ArgumentNullException(nameof(directoryInfo)); } var context = new MatcherContext(_includePatterns, _excludePatterns, directoryInfo, _comparison); return(context.Execute()); }
public void ExtractSnippetFilterContent2() { // Run the extraction FileSystemSnippetExtractor extractor = new FileSystemSnippetExtractor(); DirectoryInfoBase directoryInfoBase = fileSystem.DirectoryInfo.FromDirectoryName(fileSystem.Path.GetFullPath("Foo")); NodeSnippet snippet = extractor.Extract(directoryInfoBase, "Content2.txt") as NodeSnippet; // Assert Foo Assert.AreEqual("Foo", snippet.Node.Name); Assert.AreEqual(false, snippet.Node.IsLeaf); Assert.AreEqual(2, snippet.Node.Children.Count); // Assert Foo/Content2.txt Node foocontent2 = snippet.Node.Children["Content2.txt"]; Assert.AreEqual("Content2.txt", foocontent2.Name); Assert.AreEqual(true, foocontent2.IsLeaf); Assert.AreEqual(0, foocontent2.Children.Count); // Assert Foo/Bar Node bar = snippet.Node.Children["Bar"]; Assert.AreEqual("Bar", bar.Name); Assert.AreEqual(false, bar.IsLeaf); Assert.AreEqual(2, bar.Children.Count); // Assert Foo/Bar/Content2.txt Node barcontent2 = bar.Children["Content2.txt"]; Assert.AreEqual("Content2.txt", barcontent2.Name); Assert.AreEqual(true, barcontent2.IsLeaf); Assert.AreEqual(0, barcontent2.Children.Count); // Assert Foo/Bar/Foo Node barfoo = bar.Children["Foo"]; Assert.AreEqual("Foo", barfoo.Name); Assert.AreEqual(false, barfoo.IsLeaf); Assert.AreEqual(1, barfoo.Children.Count); // Assert Foo/Bar/Foo/Bar Node barfoobar = barfoo.Children["Bar"]; Assert.AreEqual("Bar", barfoobar.Name); Assert.AreEqual(false, barfoobar.IsLeaf); Assert.AreEqual(1, barfoobar.Children.Count); // Assert Foo/Bar/Foo/Bar/Content2.txt Node barfoobarcontent2 = barfoobar.Children["Content2.txt"]; Assert.AreEqual("Content2.txt", barfoobarcontent2.Name); Assert.AreEqual(true, barfoobarcontent2.IsLeaf); Assert.AreEqual(0, barfoobarcontent2.Children.Count); }
private static FileInfoBase[] FindAllCsprojFiles(DirectoryInfoBase directory) { FileInfoBase[] fileInfos = directory.GetFiles("*.csproj", SearchOption.TopDirectoryOnly); if (fileInfos.Length == 0) { SystemContext.ConsoleErrorWriteLine("No csproj file found for default namespace. Please specify a namespace as a command argument."); throw new FileNotFoundException(); } return(fileInfos); }
public static Uri ToUri(this DirectoryInfoBase instance) { string fullName = instance.FullName; if (!instance.FullName.EndsWith(Path.DirectorySeparatorChar.ToString())) { fullName = fullName + Path.DirectorySeparatorChar.ToString(); } return(fullName.ToFolderUri()); }
public void ExtractSnippetFilterNotFound() { // Run the extraction FileSystemSnippetExtractor extractor = new FileSystemSnippetExtractor(); DirectoryInfoBase directoryInfoBase = fileSystem.DirectoryInfo.FromDirectoryName(fileSystem.Path.GetFullPath("Foo")); NodeSnippet snippet = extractor.Extract(directoryInfoBase, "NotFound.txt") as NodeSnippet; // Assert Foo Assert.AreEqual("Foo", snippet.Node.Name); Assert.AreEqual(false, snippet.Node.IsLeaf); Assert.AreEqual(0, snippet.Node.Children.Count); }
public void DoSomething() { // The directory can be determined at runtime. // It could, for example, be provided by another service. string directory = @"C:\SomeWhere\"; // Create an instance of the DirectoryInfoWrapper concrete type. DirectoryInfoBase directoryInfo = this.fileSystem.DirectoryInfo.FromDirectoryName(directory); // Do something with the directory (it has the exact same interface as // System.IO.DirectoryInfo). var files = directoryInfo.GetFiles(); }
private static string MakeRelative(FileInfoBase file, DirectoryInfoBase referenceDirectory) { var referencePath = NormalizePathSeparators(referenceDirectory.FullName); referencePath = referencePath.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; var filePath = file.FullName; var fileUri = new Uri(filePath); var referenceUri = new Uri(referencePath); var relativePath = referenceUri.MakeRelativeUri(fileUri).ToString(); return(NormalizePathSeparators(relativePath)); }
// Internal for unit testing. internal PollingWildCardChangeToken( DirectoryInfoBase directoryInfo, string pattern, IClock clock) { _directoryInfo = directoryInfo; Clock = clock; _matcher = new Matcher(StringComparison.OrdinalIgnoreCase); _matcher.AddInclude(pattern); CalculateChanges(); }
public void SetsTemporaryFileAsSongPath() { var fileSystem = new MockFileSystem(); var metadata = new NetworkSong(); var song = MobileSong.Create(metadata, Observable.Never <byte[]>(), fileSystem); DirectoryInfoBase tempDir = fileSystem.DirectoryInfo.FromDirectoryName(fileSystem.Path.GetTempPath()); Assert.Equal(song.OriginalPath, tempDir.GetFiles().First().FullName); Assert.Equal(song.PlaybackPath, tempDir.GetFiles().First().FullName); }
private void PushDirectory(DirectoryInfoBase directory) { foreach (IPatternContext context in _includePatternContexts) { context.PushDirectory(directory); } foreach (IPatternContext context in _excludePatternContexts) { context.PushDirectory(directory); } }
private DirectoryInfoBase[] GetJobRunsDirectories(string jobName) { string jobHistoryPath = Path.Combine(JobsDataPath, jobName); DirectoryInfoBase jobHistoryDirectory = FileSystemHelpers.DirectoryInfoFromDirectoryName(jobHistoryPath); if (!jobHistoryDirectory.Exists) { return(null); } return(jobHistoryDirectory.GetDirectories("*", SearchOption.TopDirectoryOnly)); }
public TriggeredJobRun GetLatestJobRun(string jobName) { DirectoryInfoBase[] jobRunsDirectories = GetJobRunsDirectories(jobName); if (jobRunsDirectories == null || jobRunsDirectories.Length == 0) { return(null); } DirectoryInfoBase latestJobRunDirectory = jobRunsDirectories.OrderByDescending(j => j.Name).First(); return(BuildJobRun(latestJobRunDirectory, jobName, isLatest: true)); }
public virtual Task <HttpResponseMessage> DeleteItem(bool recursive = false) { string localFilePath = GetLocalFilePath(); HttpResponseMessage response; if (VfsSpecialFolders.TryHandleRequest(Request, localFilePath, out response)) { return(Task.FromResult(response)); } DirectoryInfoBase dirInfo = FileSystemHelpers.DirectoryInfoFromDirectoryName(localFilePath); if (dirInfo.Attributes < 0) { HttpResponseMessage notFoundResponse = Request.CreateErrorResponse(HttpStatusCode.NotFound, String.Format("'{0}' not found.", dirInfo.FullName)); return(Task.FromResult(notFoundResponse)); } else if ((dirInfo.Attributes & FileAttributes.Directory) != 0) { try { dirInfo.Delete(recursive); } catch (Exception ex) { Tracer.TraceError(ex); HttpResponseMessage conflictDirectoryResponse = Request.CreateErrorResponse( HttpStatusCode.Conflict, Resources.VfsControllerBase_CannotDeleteDirectory); return(Task.FromResult(conflictDirectoryResponse)); } // Delete directory succeeded. HttpResponseMessage successResponse = Request.CreateResponse(HttpStatusCode.OK); return(Task.FromResult(successResponse)); } else { // If request URI ends in a "/" then redirect to one that does not if (localFilePath[localFilePath.Length - 1] == Path.DirectorySeparatorChar) { HttpResponseMessage redirectResponse = Request.CreateResponse(HttpStatusCode.TemporaryRedirect); UriBuilder location = new UriBuilder(Request.RequestUri); location.Path = location.Path.TrimEnd(_uriSegmentSeparator); redirectResponse.Headers.Location = location.Uri; return(Task.FromResult(redirectResponse)); } // We are ready to delete the file var fileInfo = FileSystemHelpers.FileInfoFromFileName(localFilePath); return(CreateFileDeleteResponse(fileInfo)); } }
public MockDirectoryInfo( FileSystemOperationRecorder recorder, DirectoryInfoBase parentDirectory, string fullName, string name, string[] paths) { ParentDirectory = parentDirectory; Recorder = recorder; FullName = fullName; Name = name; Paths = paths; }
private static string TryReadNpmVersion(DirectoryInfoBase nodeDir) { var npmRedirectionFile = nodeDir.GetFiles("npm.txt").FirstOrDefault(); if (npmRedirectionFile == null) { return(null); } using (StreamReader reader = new StreamReader(npmRedirectionFile.OpenRead())) { return(reader.ReadLine()); } }
private static int CalculateHashForJob(string jobBinariesPath) { var updateDatesString = new StringBuilder(); DirectoryInfoBase jobBinariesDirectory = FileSystemHelpers.DirectoryInfoFromDirectoryName(jobBinariesPath); FileInfoBase[] files = jobBinariesDirectory.GetFiles("*.*", SearchOption.AllDirectories); foreach (FileInfoBase file in files) { updateDatesString.Append(file.LastWriteTimeUtc.Ticks); } return(updateDatesString.ToString().GetHashCode()); }
// Internal constructor for recursive itterator private SafeFileEnumerator(DirectoryInfoBase root, string pattern, SearchOption option, IList <Exception> errors) { if (root == null || !root.Exists) { throw new ArgumentException("Root directory is not set or does not exist.", "root"); } this.root = root; this.searchOption = option; this.pattern = String.IsNullOrEmpty(pattern) ? "*" : pattern; this.errors = errors; }
/// <summary> /// Instantiates a file system repository for the given database at the specified directory location. /// </summary> /// <param name="scriptDirectory">The directory where build scripts are located.</param> /// <param name="serverName">The name of the database server.</param> /// <param name="databaseName">The name of the database.</param> /// <param name="fileSystem">An object that provides access to the file system.</param> /// <param name="sqlParser">The sql script parser for reading the SQL file contents.</param> /// <param name="logger">A Logger</param> /// <param name="ignoreUnsupportedSubdirectories">A flag indicating whether to ignore subdirectories that don't conform to the expected naming convention.</param> public FileSystemScriptRepository(DirectoryInfoBase scriptDirectory, string serverName, string databaseName, IFileSystem fileSystem, IParser sqlParser, ILogger logger, bool ignoreUnsupportedSubdirectories) { Logger = logger; ScriptDirectory = scriptDirectory; ServerName = serverName.TrimObjectName(); DatabaseName = databaseName.TrimObjectName(); IgnoreUnsupportedSubdirectories = ignoreUnsupportedSubdirectories; _objectTypes = Enum.GetValues(typeof(DatabaseObjectType)).Cast <DatabaseObjectType>() .ToDictionary(x => x.ToString(), y => y, StringComparer.InvariantCultureIgnoreCase); this.FileSystem = fileSystem; this._sqlParser = sqlParser; this.IsFileInSupportedDirectory = f => _objectTypes.ContainsKey(f.Directory.Name); }