private void UpdateFormat() { try { if (DetectFileChange(out var overwrittenEncoding)) { if (!_filesystem.FileExists(_fullFilename)) { SetError(_sourceDoesNotExist); } else { using (var stream = TryOpenRead(_fullFilename, out var error)) { if (stream == null) { SetError(error); } else { var autoDetectedEncoding = _encodingDetector.TryFindEncoding(stream); var defaultEncoding = _services.TryRetrieve <Encoding>() ?? Encoding.Default; var format = _formatDetector.TryDetermineFormat(_fullFilename, stream, overwrittenEncoding ?? autoDetectedEncoding ?? defaultEncoding); var encoding = PickEncoding(overwrittenEncoding, format, autoDetectedEncoding, defaultEncoding); var formatChanged = _propertiesBuffer.SetValue(Core.Properties.Format, format); _propertiesBuffer.SetValue(TextProperties.AutoDetectedEncoding, autoDetectedEncoding); _propertiesBuffer.SetValue(TextProperties.ByteOrderMark, autoDetectedEncoding != null); _propertiesBuffer.SetValue(Core.Properties.EmptyReason, error); var encodingChanged = _propertiesBuffer.SetValue(TextProperties.Encoding, encoding); var currentLogSources = _logSources; if (currentLogSources == null || currentLogSources.Count == 0 || formatChanged || encodingChanged) { Dispose(currentLogSources); // Depending on the log file we're actually opening, the plugins we have installed, the final log source // that we expose here could be anything. It could be the raw log source which reads everything line by line, // but it also could be a plugin's ILogSource implementation which does all kinds of magic. var newLogSources = CreateAllLogSources(_services, _fullFilename, format, encoding, _maximumWaitTime); if (!StartListenTo(newLogSources)) { Dispose(newLogSources); } } } } } } } catch (IOException e) { Log.DebugFormat("Caught exception while reading '{0}': {1}", _fullFilename, e); } catch (Exception e) { Log.DebugFormat("Caught unexpected exception while reading '{0}': {1}", _fullFilename, e); } }
private string ConstructReferenceLineWithLinkedDllAssemblyInfo(Link link, string dll) { var linkDllPath = ConstructPathToLinkDll(link, dll); if (_filesystem.FileExists(linkDllPath)) { var linkedAssembly = Assembly.LoadFile(linkDllPath); return($"{Indentation4}<Reference Include=\"{linkedAssembly.FullName}\">"); } throw new FileNotFoundException($"The constructed path to linked dll \"{linkDllPath}\" does not exist"); }
public ConfigSettings GetConfig(string directoryOrFile) { string path = NormalizePath(directoryOrFile); var containingDirectory = path; // Path.GetDirectoryName(Path.GetFullPath(path)); while (IsNotRoot(containingDirectory)) { var configLocation = Path.Combine(containingDirectory, "storevil.config"); if (_filesystem.FileExists(configLocation)) return BuildConfigSettings(path, configLocation); var csproj = FindCsProj(containingDirectory); if (csproj != null) { return GetConfigFromCsProj(containingDirectory, csproj); } var parent = Directory.GetParent(containingDirectory); if (parent == null) return ConfigSettings.Default(); containingDirectory = parent.FullName; } return ConfigSettings.Default(); }
private (string filePath, string directoryPath) EnsureLinkRegistryFileExists() { var toffeeAppDataDirectoryPath = _toffeeAppDataDirectory.EnsureExists(); var linkRegistryFile = Path.Combine(toffeeAppDataDirectoryPath, "LinkRegistry.csv"); if (!_filesystem.FileExists(linkRegistryFile)) { _filesystem.CreateFile(linkRegistryFile); } return(linkRegistryFile, toffeeAppDataDirectoryPath); }
private ProjectFindResult?TryFindByFullPath(string path) { if (!path.EndsWith(".csproj")) { return(null); } return(new ProjectFindResult { ProjectPath = path, IsFound = _filesystem.FileExists(path), Candidates = new[] { path }, }); }
private string ResolveScriptPath(string filePath, PreprocessorContext context) { if (Path.IsPathRooted(filePath)) { return(filePath); } foreach (var includeFolder in context.IncludeFolders) { var path = Path.Combine(includeFolder, filePath + ".cs"); if (_fileSystem.FileExists(path)) { return(path); } } throw new NotImplementedException(); }
private bool CreateFile(string content, string directory, string fileName) { var fullPath = $"{directory}/{fileName}"; if (_filesystem.FileExists(fullPath)) { Console.WriteLine($"Cannot create file \"{fullPath}\" because it already exists."); return(false); } if (!_filesystem.DirectoryExists(directory)) { Console.WriteLine($"Creating directory \"{directory}\""); _filesystem.CreateDirectory(directory); } Console.WriteLine($"Creating file \"{fullPath}\""); _filesystem.WriteFile(fullPath, content); return(true); }
/// <inheritdoc /> protected override TimeSpan RunOnce(CancellationToken token) { bool read = false; try { if (!_filesystem.FileExists(_fileName)) { SetDoesNotExist(); } else { var info = _filesystem.GetFileInfo(_fileName); var fileSize = info.Length; _localProperties.SetValue(Core.Properties.LastModified, info.LastWriteTimeUtc); _localProperties.SetValue(Core.Properties.Created, info.CreationTimeUtc); _localProperties.SetValue(Core.Properties.Size, Size.FromBytes(fileSize)); UpdatePercentageProcessed(_lastStreamPosition, fileSize, allow100Percent: true); SynchronizePropertiesWithUser(); using (var stream = _filesystem.Open(_fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (var reader = new StreamReaderEx(stream, _encoding)) { // We change the error flag explicitly AFTER opening // the stream because that operation might throw if we're // not allowed to access the file (in which case a different // error must be set). _localProperties.SetValue(Core.Properties.EmptyReason, null); if (stream.Length >= _lastStreamPosition) { stream.Position = _lastStreamPosition; } else { OnReset(stream, out _numberOfLinesRead, out _lastStreamPosition); } int numProcessed = 0; string currentLine; while ((currentLine = reader.ReadLine()) != null) { token.ThrowIfCancellationRequested(); bool lastLineHadNewline = _lastLineHadNewline; var trimmedLine = currentLine.TrimNewlineEnd(out _lastLineHadNewline); var entryCount = _entries.Count; if (entryCount > 0 && !lastLineHadNewline) { // We need to remove the last line and create a new line // that consists of the entire content. RemoveLast(); trimmedLine = _untrimmedLastLine + trimmedLine; _untrimmedLastLine = _untrimmedLastLine + currentLine; } else { _untrimmedLastLine = currentLine; ++_numberOfLinesRead; read = true; } Add(trimmedLine, _numberOfLinesRead); if (++numProcessed % 1000 == 0) { // Here's the deal: Since we're processing the file in chunks, we advance the underlying // stream faster than we're actually consuming lines. This means that it's quite likely // that at the end of the file, we have moved the stream to the end, but have not quite // yet processed the underlying buffer from StreamReaderEx. The percentage processed // should be accurate enough so that if it is at 100%, then no more log entries are added. // We can only guarantee that when we have processed all lines and therefore we reserve // setting the percentage to 100% ONLY when we can read no more lines // (See the SetEndOfSourceReached() call below, outside the loop). UpdatePercentageProcessed(stream.Position, fileSize, allow100Percent: false); SynchronizePropertiesWithUser(); } } _lastStreamPosition = stream.Position; _localProperties.SetValue(TextProperties.LineCount, _entries.Count); _localProperties.SetValue(Core.Properties.LogEntryCount, _entries.Count); } } Listeners.OnRead(_numberOfLinesRead); SetEndOfSourceReached(); } } catch (FileNotFoundException e) { SetError(_sourceDoesNotExist); Log.Debug(e); } catch (DirectoryNotFoundException e) { SetError(_sourceDoesNotExist); Log.Debug(e); } catch (OperationCanceledException e) { Log.Debug(e); } catch (UnauthorizedAccessException e) { SetError(_sourceCannotBeAccessed); Log.Debug(e); } catch (IOException e) { SetError(_sourceCannotBeAccessed); Log.Debug(e); } catch (Exception e) { Log.Debug(e); } if (read) { return(TimeSpan.Zero); } return(TimeSpan.FromMilliseconds(100)); }
public (bool isValid, string reason) IsValid(string[] args) { if (args.Length != 4) { return(false, "Invalid args. Syntax for the \"link-to\" command is: \"link-to --dest={path} --link={link-name} --dlls={comma-separated-list-of-dlls-with-no-spaces}\""); } var command = args[0]; if (command != "link-to") { return(false, "First param was not the \"link-to\" command"); } var destinationDirectoryPathArg = args[1]; if (string.IsNullOrEmpty(destinationDirectoryPathArg)) { return(false, "Path to {--dest|-d} directory was not set"); } var destinationDirectoryPathParts = destinationDirectoryPathArg.Split('='); if (destinationDirectoryPathParts.Length != 2) { return(false, "Path to {--dest|-d} directory was not given correctly. It should be --dest={valid-path} or -d={valid-path}. Remember to wrap the path in double quotes if it contains spaces."); } if (destinationDirectoryPathParts[0] != "--dest" && destinationDirectoryPathParts[0] != "-d") { return(false, "Path to {--dest|-d} directory was not given correctly. It should be --dest={valid-path} or -d={valid-path}. Could not find the \"--dest|-d\"-part. Remember to wrap the path in double quotes if it contains spaces."); } var destinationDirectoryPath = destinationDirectoryPathParts[1].Replace('/', '\\');; if (!_filesystem.DirectoryExists(destinationDirectoryPath)) { return(false, "Path to {--dest|-d} directory does not exist. Remember to wrap the path in double quotes if it contains spaces."); } if (!Path.IsPathRooted(destinationDirectoryPath)) { return(false, "The {--dest|-d} directory path must be absolute"); } var linkNameArg = args[2]; if (string.IsNullOrEmpty(linkNameArg)) { return(false, "Link name was not set"); } var linkNameParts = linkNameArg.Split('='); if (linkNameParts.Length != 2) { return(false, "Link name was not given correctly. It should be --link={link-name} or -l={link-name}. Link name should not contain spaces and be lower case"); } if (linkNameParts[0] != "--link" && linkNameParts[0] != "-l") { return(false, "Link name was not given correctly. It should be --link={link-name} or -l={link-name}. Could not find the \"--link|-l\"-part"); } if (linkNameParts[1].Contains(" ")) { return(false, "Link name can not contain spaces"); } var linkName = linkNameParts[1]; (var foundLink, var link) = _linkRegistryFile.TryGetLink(linkName); if (!foundLink) { return(false, $"The link \"{linkName}\" does not exist in the registry. Did you create it using the \"link-from\" command?"); } var dllsArg = args[3]; if (string.IsNullOrEmpty(dllsArg)) { return(false, "List of dlls to link was not set. It should be --dlls={comma-separated-list-of-dll-names-with-no-spaces} or -D={dll-names}"); } var dllsParts = dllsArg.Split('='); if (dllsParts.Length != 2) { return(false, "List of dlls to link was not given correctly. It should be dlls={comma-separated-list-of-dll-names-with-no-spaces} or -D={dll-names}"); } if (dllsParts[0] != "--dlls" && dllsParts[0] != "-D") { return(false, "List of dlls was not given correctly. It should be dlls={comma-separated-list-of-dll-names-with-no-spaces} or -D={dll-names}. Could not find the \"--dlls|-D\"-part"); } if (dllsParts[1].Contains(" ")) { return(false, "List of dlls can not contain spaces"); } var dlls = dllsParts[1].Split(','); foreach (var dll in dlls.Where(d => !d.EndsWith("*"))) { var fullDllPath = Path.Combine(link.SourceDirectoryPath, dll); var normalizedDllPath = fullDllPath.EndsWith(".dll") ? fullDllPath : $"{fullDllPath}.dll"; if (!_filesystem.FileExists($"{normalizedDllPath}")) { return(false, $"The DLL \"{normalizedDllPath}\" does not exist. The path was constructed by combining the link's ({linkName}) Source Directory ({link.SourceDirectoryPath}) and the entered DLL {dll}. One of these values must be adjusted to make a valid path"); } } return(true, null); }
public bool FileExists(string filePath) { var absoluteFilePath = NormalizeAndEvaluate(filePath); return(_filesystem.FileExists(absoluteFilePath)); }