private static void DeleteFileSystemInfo(FileSystemInfoBase fileSystemInfo, bool ignoreErrors) { if (!fileSystemInfo.Exists) { return; } try { fileSystemInfo.Attributes = FileAttributes.Normal; } catch { if (!ignoreErrors) { throw; } } var directoryInfo = fileSystemInfo as DirectoryInfoBase; if (directoryInfo != null) { DeleteDirectoryContentsSafe(directoryInfo, ignoreErrors); } DoSafeAction(fileSystemInfo.Delete, ignoreErrors); }
static FileSystemInfoBase GetSourceFileInfo(IFileSystem srcFileSystem, string srcFile) { if (srcFile.EndsWith("\\")) { return(srcFileSystem.DirectoryInfo.FromDirectoryName(srcFile)); } var srcParent = srcFile.Substring(0, srcFile.LastIndexOf('\\') + 1); if (srcParent.Length < "x:\\".Length) { throw new ArgumentException("Invalid destination!"); } else if (srcParent.Equals("x:\\", StringComparison.OrdinalIgnoreCase)) { return(srcFileSystem.DirectoryInfo.FromDirectoryName(srcFile)); } string name = srcFile.Substring(srcFile.LastIndexOf('\\') + 1); DirectoryInfoBase parent = srcFileSystem.DirectoryInfo.FromDirectoryName(srcParent); FileSystemInfoBase match = parent.GetFileSystemInfos().Where(f => f.Name == name).FirstOrDefault(); if (match == null) { throw new FileNotFoundException(srcFile + " does not exists"); } return(match); }
static bool comp(FileSystemInfoBase x, IEntry y) { if (!x.Attributes.Equals((FileAttributes)y.Attributes)) { return(false); } if (!x.CreationTimeUtc.ToFileTimeUtc().Equals((long)y.CreationTime)) { return(false); } if (!x.LastAccessTimeUtc.ToFileTimeUtc().Equals((long)y.LastAccessTime)) { return(false); } if (!x.LastWriteTimeUtc.ToFileTimeUtc().Equals((long)y.LastWriteTime)) { return(false); } return( x.Attributes.Equals((FileAttributes)y.Attributes) && x.CreationTimeUtc.ToFileTimeUtc().Equals((long)y.CreationTime) && x.LastAccessTimeUtc.ToFileTimeUtc().Equals((long)y.LastAccessTime) && x.LastWriteTimeUtc.ToFileTimeUtc().Equals((long)y.LastWriteTime) ); }
public INode Create(FileSystemInfoBase root, FileSystemInfoBase location) { string relativePathFromRoot = root == null ? @".\" : PathExtensions.MakeRelativePath(root, location, this.fileSystem); var directory = location as DirectoryInfoBase; if (directory != null) { return(new FolderNode(directory, relativePathFromRoot)); } var file = location as FileInfoBase; if (this.relevantFileDetector.IsFeatureFile(file)) { Feature feature = this.featureParser.Parse(file.FullName); if (feature != null) { return(new FeatureNode(file, relativePathFromRoot, feature)); } throw new InvalidOperationException("This feature file could not be read and will be excluded"); } else if (this.relevantFileDetector.IsMarkdownFile(file)) { XElement markdownContent = this.htmlMarkdownFormatter.Format(this.fileSystem.File.ReadAllText(file.FullName)); return(new MarkdownNode(file, relativePathFromRoot, markdownContent)); } else if (this.relevantFileDetector.IsImageFile(file)) { return(new ImageNode(file, relativePathFromRoot)); } throw new InvalidOperationException("Cannot create an IItemNode-derived object for " + file.FullName); }
protected override Task <HttpResponseMessage> CreateItemPutResponse(FileSystemInfoBase info, string localFilePath, bool itemExists) { // We don't support putting an individual file using the zip controller HttpResponseMessage notFoundResponse = Request.CreateResponse(HttpStatusCode.NotFound); return(Task.FromResult(notFoundResponse)); }
public FeatureNode(FileSystemInfoBase location, string relativePathFromRoot, Feature feature) { this.OriginalLocation = location; this.OriginalLocationUrl = location.ToUri(); this.RelativePathFromRoot = relativePathFromRoot; this.Feature = feature; }
public MarkdownNode(FileSystemInfoBase location, string relativePathFromRoot, XElement markdownContent) { this.OriginalLocation = location; this.OriginalLocationUrl = location.ToUri(); this.RelativePathFromRoot = relativePathFromRoot; this.MarkdownContent = markdownContent; }
protected override Task <IActionResult> CreateItemGetResponse(FileSystemInfoBase info, string localFilePath) { // CORE TODO Similar to VfsController: File() apparently has built in support for range requests and etags. From a cursory glance // that renders bascially all of this obsolete. Will need checking to ensure proper behavior. Can we use PhysicalFile instead? var stream = new RepositoryItemStream(this, GetFileReadStream(localFilePath)); return(Task.FromResult( (IActionResult)File(stream, MediaTypeMap.GetMediaType(info.Extension).ToString(), info.LastWriteTime, _currentEtag))); //// Check whether we have a conditional If-None-Match request //if (IsIfNoneMatchRequest(_currentEtag)) //{ // var result = StatusCode(StatusCodes.Status304NotModified); // // CORE TODO make sure this works properly // Response.GetTypedHeaders().ETag = _currentEtag; // return Task.FromResult((IActionResult)result); //} //// Check whether we have a conditional range request containing both a Range and If-Range header field //bool isRangeRequest = IsRangeRequest(_currentEtag); //// Generate file response //try //{ // _readStream = new RepositoryItemStream(this, GetFileReadStream(localFilePath)); // MediaTypeHeaderValue mediaType = MediaTypeMap.GetMediaType(info.Extension); // HttpResponseMessage successFileResponse = Request.CreateResponse(isRangeRequest ? HttpStatusCode.PartialContent : HttpStatusCode.OK); // if (isRangeRequest) // { // successFileResponse.Content = new ByteRangeStreamContent(_readStream, Request.Headers.Range, mediaType, BufferSize); // } // else // { // successFileResponse.Content = new StreamContent(_readStream, BufferSize); // successFileResponse.Content.Headers.ContentType = mediaType; // } // // Set etag for the file // successFileResponse.Headers.ETag = _currentEtag; // return Task.FromResult(successFileResponse); //} //catch (InvalidByteRangeException invalidByteRangeException) //{ // // The range request had no overlap with the current extend of the resource so generate a 416 (Requested Range Not Satisfiable) // // including a Content-Range header with the current size. // Tracer.TraceError(invalidByteRangeException); // HttpResponseMessage invalidByteRangeResponse = Request.CreateErrorResponse(invalidByteRangeException); // CloseReadStream(); // return Task.FromResult(invalidByteRangeResponse); //} //catch (Exception ex) //{ // // Could not read the file // Tracer.TraceError(ex); // HttpResponseMessage errorResponse = Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); // CloseReadStream(); // return Task.FromResult(errorResponse); //} }
/// <summary> /// Extracts a snippet. /// </summary> /// <param name="fileSystemInfo">The file system info.</param> /// <param name="pattern">The extraction pattern.</param> /// <returns>The extracted snippet.</returns> public Snippet Extract(FileSystemInfoBase fileSystemInfo, string pattern) { // Get the directory DirectoryInfoBase directoryInfo = this.ConvertToDirectory(fileSystemInfo); // Use * as pattern when none is set if (string.IsNullOrWhiteSpace(pattern)) { pattern = "*"; } try { // Search file system info from pattern FileSystemInfoBase[] fileSystemInfoBase = pattern .Split(new char[] { '|', ';' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Trim()) .Where(x => !string.IsNullOrWhiteSpace(x)) .SelectMany(x => directoryInfo.GetFileSystemInfos(x, SearchOption.AllDirectories)) .OrderByDescending(x => x is DirectoryInfoBase) .ThenBy(x => x.FullName) .ToArray(); // Build snippet return(this.BuildSnippet(directoryInfo, fileSystemInfoBase)); } // Rethrow a snippet extraction exception if the directory is not found catch (DirectoryNotFoundException) { throw new SnippetExtractionException("Cannot find directory", pattern); } }
protected override Task <IActionResult> CreateItemGetResponse(FileSystemInfoBase info, string localFilePath) { var fileStream = GetFileReadStream(localFilePath); return(Task.FromResult( (IActionResult)File(fileStream, MediaTypeMap.GetMediaType(info.Extension).ToString(), info.LastWriteTime, CreateEntityTag(info)))); }
static int Main(string[] args) { try { var arg = new CommandArguments(args); var fileSystem = arg.FileSystem; string cd = fileSystem.Directory.GetCurrentDirectory(); string path = Path.Combine(cd, arg.Path); var info = new FileInfo(path); DirectoryInfoBase parent = fileSystem.DirectoryInfo.FromDirectoryName(info.Directory.FullName); FileSystemInfoBase file = parent.GetFileSystemInfos().Where(f => f.Name == info.Name).FirstOrDefault(); if (file == null) { throw new FileNotFoundException(info.FullName + " does not exists."); } else if (file is DirectoryInfoBase) { throw new NotSupportedException("Delete directory is not supported."); } file.Delete(); return(0); } catch (Exception ex) { Console.WriteLine(ex); return(-1); } }
protected override Task <HttpResponseMessage> CreateItemGetResponse(FileSystemInfoBase info, string localFilePath) { // We don't support getting a file from the zip controller // Conceivably, it could be a zip file containing just the one file, but that's rarely interesting HttpResponseMessage notFoundResponse = Request.CreateResponse(HttpStatusCode.NotFound); return(Task.FromResult(notFoundResponse)); }
public INode Create(FileSystemInfoBase root, FileSystemInfoBase location, ParsingReport report) { string relativePathFromRoot = root == null ? @".\" : PathExtensions.MakeRelativePath(root, location, this.fileSystem); var directory = location as DirectoryInfoBase; if (directory != null) { return(new FolderNode(directory, relativePathFromRoot)); } var file = location as FileInfoBase; if (file != null) { if (this.relevantFileDetector.IsFeatureFile(file)) { try { Feature feature = this.featureParser.Parse(file.FullName); return(feature != null ? new FeatureNode(file, relativePathFromRoot, feature) : null); } catch (FeatureParseException exception) { report.Add(exception.Message); Log.Error(exception.Message); return(null); } } else if (this.relevantFileDetector.IsMarkdownFile(file)) { try { XElement markdownContent = this.htmlMarkdownFormatter.Format(this.fileSystem.File.ReadAllText(file.FullName)); return(new MarkdownNode(file, relativePathFromRoot, markdownContent)); } catch (Exception exception) { string description = "Error parsing the Markdown file located at " + file.FullName + ". Error: " + exception.Message; report.Add(description); Log.Error(description); return(null); } } else if (this.relevantFileDetector.IsImageFile(file)) { return(new ImageNode(file, relativePathFromRoot)); } } var message = "Cannot create an IItemNode-derived object for " + location.FullName; report.Add(message); Log.Error(message); return(null); }
public static Uri ToUri(this FileSystemInfoBase instance) { var di = instance as DirectoryInfoBase; if (di != null) { return(ToUri(di)); } return(ToUri((FileInfoBase)instance)); }
/// <summary> /// Gets the parent directory for the supplied Info. /// </summary> /// <param name="fsinfo">Info whose parent is to be retrieved.</param> /// <returns>The Info's parent directory.</returns> public static DirectoryInfoBase Parent(this FileSystemInfoBase fsinfo) { if (fsinfo is DirectoryInfoBase di) { return(di.Parent); } else if (fsinfo is FileInfoBase fi) { return(fi.Directory); } throw new ArgumentException("Unexpected FileSystemInfo implementation"); }
protected override Task <HttpResponseMessage> CreateItemGetResponse(FileSystemInfoBase info, string localFilePath) { // Check whether we have a conditional If-None-Match request if (IsIfNoneMatchRequest(_currentEtag)) { HttpResponseMessage notModifiedResponse = Request.CreateResponse(HttpStatusCode.NotModified); notModifiedResponse.Headers.ETag = _currentEtag; return(Task.FromResult(notModifiedResponse)); } // Check whether we have a conditional range request containing both a Range and If-Range header field bool isRangeRequest = IsRangeRequest(_currentEtag); // Generate file response try { _readStream = new RepositoryItemStream(this, GetFileReadStream(localFilePath)); MediaTypeHeaderValue mediaType = MediaTypeMap.GetMediaType(info.Extension); HttpResponseMessage successFileResponse = Request.CreateResponse(isRangeRequest ? HttpStatusCode.PartialContent : HttpStatusCode.OK); if (isRangeRequest) { successFileResponse.Content = new ByteRangeStreamContent(_readStream, Request.Headers.Range, mediaType, BufferSize); } else { successFileResponse.Content = new StreamContent(_readStream, BufferSize); successFileResponse.Content.Headers.ContentType = mediaType; } // Set etag for the file successFileResponse.Headers.ETag = _currentEtag; return(Task.FromResult(successFileResponse)); } catch (InvalidByteRangeException invalidByteRangeException) { // The range request had no overlap with the current extend of the resource so generate a 416 (Requested Range Not Satisfiable) // including a Content-Range header with the current size. Tracer.TraceError(invalidByteRangeException); HttpResponseMessage invalidByteRangeResponse = Request.CreateErrorResponse(invalidByteRangeException); CloseReadStream(); return(Task.FromResult(invalidByteRangeResponse)); } catch (Exception ex) { // Could not read the file Tracer.TraceError(ex); HttpResponseMessage errorResponse = Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); CloseReadStream(); return(Task.FromResult(errorResponse)); } }
private void ProcessFoundEntry(FileSystemInfoBase systemInfoBase) { var isDirectory = systemInfoBase.Attributes.HasFlag(FileAttributes.Directory); if (isDirectory) { DirectoryFound?.Invoke(systemInfoBase, EventArgs.Empty); } else { FileFound?.Invoke(systemInfoBase, EventArgs.Empty); } }
public static string MakeRelativePath(FileSystemInfoBase from, FileSystemInfoBase to, IFileSystem fileSystem) { if (from == null) { throw new ArgumentNullException("from"); } if (to == null) { throw new ArgumentNullException("to"); } return(MakeRelativePath(from.FullName, to.FullName, fileSystem)); }
/// <summary> /// Converts a FileSystemInfo to DirectoryInfo. /// </summary> /// <param name="fileSystemInfo">The file system info.</param> /// <returns>The directory info.</returns> protected DirectoryInfoBase ConvertToDirectory(FileSystemInfoBase fileSystemInfo) { // Data validation Ensure.That(() => fileSystemInfo).IsNotNull(); // Cast to DirectoryInfo DirectoryInfoBase directoryInfo = fileSystemInfo as DirectoryInfoBase; Ensure.That(() => directoryInfo).IsNotNull(); // Return as directory return(directoryInfo); }
private static void MoveToPath(FileSystemInfoBase item, string newPath) { if (item is DirectoryInfoBase) { var di = item as DirectoryInfoBase; di.MoveTo(newPath); } else if (item is FileInfoBase) { var fi = item as FileInfoBase; fi.MoveTo(newPath); } }
private void ProcessFilteredEntry(FileSystemInfoBase systemInfoBase, FilteredFileSystemInfoFound args) { var isDirectory = systemInfoBase.Attributes.HasFlag(FileAttributes.Directory); if (isDirectory) { FilteredDirectoryFound?.Invoke(systemInfoBase, args); } else { FilteredFileFound?.Invoke(systemInfoBase, args); } }
public static ItemType GetItemType(FileSystemInfoBase itemInfo) { if (itemInfo is FileInfoBase) { return(ItemType.File); } if (itemInfo is DirectoryInfoBase) { return(ItemType.Directory); } throw new NotImplementedException(); }
/// <summary> /// Extracts a snippet. /// </summary> /// <param name="fileSystemInfo">The file system info.</param> /// <param name="pattern">The extraction pattern, never used for this implementation.</param> /// <returns>The extracted snippet.</returns> public virtual Model.Snippet Extract(FileSystemInfoBase fileSystemInfo, string pattern) { // Data validation if (null == fileSystemInfo) { throw new ArgumentNullException("fileSystemInfo"); } // Extract file content string sourceCode = this.LoadFile(this.ConvertToFile(fileSystemInfo)); // Return the entire code return(new Model.PlainTextSnippet(sourceCode)); }
/// <summary> /// Create unique etag based on the last modified UTC time /// </summary> private static EntityTagHeaderValue CreateEntityTag(FileSystemInfoBase sysInfo) { Contract.Assert(sysInfo != null); byte[] etag = BitConverter.GetBytes(sysInfo.LastWriteTimeUtc.Ticks); var result = new StringBuilder(2 + etag.Length * 2); result.Append("\""); foreach (byte b in etag) { result.AppendFormat("{0:x2}", b); } result.Append("\""); return(new EntityTagHeaderValue(result.ToString())); }
private void FilterItemActions(FileSystemInfoBase item, ref bool breakSearch, ref bool excludeItem) { var filteredDir = item as DirectoryInfoBase; if (filteredDir != null) { FilteredDirectoryFoundEvent?.Invoke(filteredDir, ref breakSearch, ref excludeItem); } var filteredFile = item as FileInfoBase; if (filteredFile != null) { FilteredFileFoundEvent?.Invoke(filteredFile, ref breakSearch, ref excludeItem); } }
private string ShorthandAttributes(FileSystemInfoBase sourceFile) { var sb = new StringBuilder("["); var sfa = sourceFile.Attributes; if ((sfa & FileAttributes.Archive) == FileAttributes.Archive) { sb.Append("A"); } if ((sfa & FileAttributes.Hidden) == FileAttributes.Hidden) { sb.Append("H"); } if ((sfa & FileAttributes.System) == FileAttributes.System) { sb.Append("S"); } if ((sfa & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { sb.Append("R"); } if ((sfa & FileAttributes.Compressed) == FileAttributes.Compressed) { sb.Append("C"); } if ((sfa & FileAttributes.Encrypted) == FileAttributes.Encrypted) { sb.Append("E"); } if (sb.Length == 1) { return(String.Empty); } sb.Append("]"); return(sb.ToString()); }
/// <summary> /// Converts a FileSystemInfo to FileInfo. /// </summary> /// <param name="fileSystemInfo">The file system info.</param> /// <returns>The file info.</returns> protected FileInfoBase ConvertToFile(FileSystemInfoBase fileSystemInfo) { // Data validation if (null == fileSystemInfo) { throw new ArgumentNullException("fileSystemInfo"); } // Cast to FileInfo FileInfoBase fileInfo = fileSystemInfo as FileInfoBase; if (null == fileInfo) { throw new ArgumentException("fileInfo"); } // Return as file return(fileInfo); }
public FileSystemCabinetItemInfo(FileSystemInfoBase itemInfo, string baseDirectory) { if (itemInfo == null) { throw new ArgumentNullException(nameof(itemInfo)); } if (String.IsNullOrWhiteSpace(baseDirectory)) { throw new ArgumentNullException(nameof(baseDirectory)); } this.Type = GetItemType(itemInfo); this.Key = GetItemKey(itemInfo, baseDirectory); this.Exists = itemInfo.Exists; bool isExistingFile = itemInfo.Exists && this.Type == ItemType.File; var fileInfo = itemInfo as FileInfoBase; this.Size = isExistingFile ? fileInfo?.Length : null; this.LastModifiedUtc = isExistingFile ? fileInfo?.LastWriteTimeUtc : null; }
/// <summary> /// Finds the appropriate function to paste an item to a new location. /// </summary> /// <param name="fs">Filesystem to use for pasting.</param> /// <param name="source">The source Info.</param> /// <param name="removeSource">Whether to remove the source item after pasting.</param> /// <returns>An action that may be called with the new destination for <paramref name="source"/>.</returns> public static Action <string> GetPasterFor(this IFileSystem fs, FileSystemInfoBase source, bool removeSource) { if (!source.IsDirectory() && removeSource) { return((string dest) => fs.File.Move(source.FullName, dest)); } if (!source.IsDirectory() && !removeSource) { return((string dest) => fs.File.Copy(source.FullName, dest)); } if (source.IsDirectory() && removeSource) { return((string dest) => fs.Directory.Move(source.FullName, dest)); } if (source.IsDirectory() && !removeSource) { return((string dest) => Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(source.FullName, dest)); } throw new ArgumentException($"Could not paste '{source.Name}"); }
/// <summary> /// Extracts a snippet from a given rule pattern. /// </summary> /// <param name="fileSystemInfo">The file system info.</param> /// <param name="memberPattern">The member pattern to extract.</param> /// <returns>The extracted snippet.</returns> public override Model.Snippet Extract(FileSystemInfoBase fileSystemInfo, string memberPattern) { // Return the entire code if no member is specified if (string.IsNullOrWhiteSpace(memberPattern)) { return(base.Extract(fileSystemInfo, memberPattern)); } // Parse the matching rule from the pattern CSharpMatchingRule rule = CSharpMatchingRule.Parse(memberPattern); // Load the trie for pattern matching if (null == this.syntaxTrie) { // Load file content string sourceCode = base.LoadFile(this.ConvertToFile(fileSystemInfo)); // Build a syntax tree from the source code SyntaxTree tree = CSharpSyntaxTree.ParseText(sourceCode); SyntaxNode root = tree.GetRoot(); // Visit the syntax tree for generating a Trie for pattern matching CSharpSyntaxWalkerMatchingBuilder syntaxMatchingBuilder = new CSharpSyntaxWalkerMatchingBuilder(); syntaxMatchingBuilder.Visit(root); // Retrieve the Trie root this.syntaxTrie = syntaxMatchingBuilder.Root; } // Match the rule from the syntax matching Trie CSharpSyntaxMatchingNode matchingTrie = syntaxTrie.Match(rule.MatchingChunks); if (null == matchingTrie) { throw new SnippetExtractionException("Cannot find member", memberPattern); } // Build a snippet for extracted syntax nodes return(this.BuildSnippet(matchingTrie.MatchingSyntaxNodes, rule.ExtractionMode)); }
/// <summary> /// Allows insertion of a FileSystemInfoBase object into a new file system. Attributes and time stamps /// are copied, and the content will be lazy loaded the first time it is touched. /// </summary> /// <param name="fileSystem">The source file system where the file info originates</param> /// <param name="fileInfo">The source file to be copied</param> public MockFileData(IFileSystem fileSystem, FileSystemInfoBase fileInfo) { if (fileSystem == null) { throw new ArgumentNullException("fileSystem"); } if (fileInfo == null) { throw new ArgumentNullException("fileInfo"); } creationTime = fileInfo.CreationTime; lastAccessTime = fileInfo.LastAccessTime; lastWriteTime = fileInfo.LastWriteTime; attributes = fileInfo.Attributes; lazyLoadContent = () => fileSystem.File.ReadAllBytes(fileInfo.FullName); }