/// <summary> /// Factory method to create a new <see cref="PurePath"/> instance /// based upon the current operating system. /// </summary> /// <param name="path"></param> /// <param name="options"></param> /// <param name="result"></param> /// <returns></returns> public bool TryCreate(string path, PurePathFactoryOptions options, out IPurePath result) { result = null; switch (PlatformChooser.GetPlatform()) { case Platform.Posix: PurePosixPath purePosixPath; if (PurePosixPath.TryParse(path, out purePosixPath)) { result = purePosixPath; break; } return(false); case Platform.Windows: PureWindowsPath pureWindowsPath; if (PureWindowsPath.TryParse(path, out pureWindowsPath)) { result = pureWindowsPath; break; } return(false); } result = ApplyOptions(result, options); return(true); }
/// <summary> /// Replace the current path components with the given path's. /// </summary> /// <param name="path"></param> private void Assimilate(IPurePath path) { Drive = path.Drive ?? ""; Root = path.Root ?? ""; Dirname = path.Dirname ?? ""; Basename = path.Basename ?? ""; Extension = path.Extension ?? ""; }
internal Repository(string name, string description, IPurePath rootPath, IFileSystem fileSystem, ITemplateLoader templateLoader, ILogger <RepositoryLoader> logger) { this.Name = name; this.Description = description; this.RootPath = rootPath; _templates = new Lazy <ImmutableList <ITemplate> >(() => LoadTemplates(fileSystem, templateLoader, logger)); }
public void MkDir(IPurePath path, bool makeParents = false) { if (!makeParents && !Directory.Exists(path.Parent().ToString())) { throw new IOException("Parent directory does not exist."); } Directory.CreateDirectory(path.ToString()); }
private ITemplateLoader BuildTemplateLoader(IPurePath testTemplatePath) { return(Mock.Of <ITemplateLoader>(loader => loader.LoadFromTemplateDirectory(It.Is <IPurePath>(path => path.Basename == testTemplatePath.Basename)) == Mock.Of <ITemplate>(template => template.Name == this.TemplateName && template.Version == this.TemplateVersion ) )); }
private static IPurePath ApplyOptions(IPurePath path, PurePathFactoryOptions options) { if (options.AutoNormalizeCase) { path = options.Culture != null ? path.NormCase(options.Culture) : path.NormCase(); } return(path); }
bool IPurePath.TrySafeJoin(IPurePath relativePath, out IPurePath joined) { TPath subPath; if (TrySafeJoin(relativePath, out subPath)) { joined = subPath; return(true); } joined = null; return(false); }
internal static IPurePath Combine(IEnumerable <IPurePath> paths, string separator) { if (String.IsNullOrEmpty(separator)) { throw new ArgumentException( "Separator cannot be empty or null.", "separator"); } IPurePath lastAbsolute = null; var dirnameBuilder = new StringBuilder(); var lastPartStr = ""; IPurePath lastPart = null; foreach (var path in paths) { var pStr = path.ToString(); if (pStr == String.Empty || pStr == CurrentDirectoryIdentifier) { continue; } // Does not use IsAbsolute in order to retain compatibility // with Path.Combine: Path.Combine("c:\\windows", "d:dir") // returns "d:dir" despite the fact that it's a relative path. if (lastAbsolute == null || !String.IsNullOrEmpty(path.Anchor)) { dirnameBuilder.Length = 0; lastAbsolute = path; } else if (dirnameBuilder.Length > 0 && !lastPartStr.EndsWith(separator)) { dirnameBuilder.Append(separator); } dirnameBuilder.Append( path.GetComponents(PathComponent.Dirname | PathComponent.Filename)); lastPart = path; lastPartStr = path.ToString(); } if (lastAbsolute == null) { return(null); } var filenameLen = lastPart.Filename.Length; dirnameBuilder.Remove(dirnameBuilder.Length - filenameLen, filenameLen); // TODO optimize this so fewer new objects are created return(lastAbsolute .WithDirname(dirnameBuilder .ToString() .TrimEnd(separator[0])) .WithFilename(lastPart.Filename)); }
/// <inheritdoc/> public bool TrySafeJoin(IPurePath relativePath, out TPath joined) { string combined; if (!PathUtils.TrySafeCombine(this, relativePath, PathSeparator, out combined)) { joined = null; return(false); } joined = PurePathFactory(combined); return(true); }
/// <inheritdoc/> protected TPath PurePathFactoryFromComponents( IPurePath original, string drive = null, string root = null, string dirname = null, string basename = null, string extension = null) { return(PurePathFactoryFromComponents( drive ?? (original != null ? original.Drive : ""), root ?? (original != null ? original.Root : ""), dirname ?? (original != null ? original.Dirname : ""), basename ?? (original != null ? original.Basename : ""), extension ?? (original != null ? original.Extension : ""))); }
/// <summary> /// Factory method to create a new <see cref="PurePath"/> instance /// based upon the current operating system. /// </summary> /// <param name="path"></param> /// <param name="options"></param> /// <returns></returns> public IPurePath Create(string path, PurePathFactoryOptions options) { IPurePath ret = null; switch (PlatformChooser.GetPlatform()) { case Platform.Posix: ret = new PurePosixPath(path); break; case Platform.Windows: ret = new PureWindowsPath(path); break; } return(ApplyOptions(ret, options)); }
/// <inheritdoc/> public TPath WithDirname(IPurePath newDirname) { // Format separators, remove extra separators, and // exclude Drive (if present) var formatted = newDirname.GetComponents( PathComponent.Dirname | PathComponent.Filename); if (IsAbsolute() || !newDirname.IsAbsolute()) { return(PurePathFactoryFromComponents(this, dirname: formatted)); } return(PurePathFactoryFromComponents(this, newDirname.Drive, newDirname.Root, formatted)); }
public ITemplate LoadFromTemplateDirectory(IPurePath templatePath) { const string ManifestFileName = "manifest.yml"; var manifestPath = templatePath.Join(ManifestFileName); using var reader = this.FileSystem.File.OpenText(manifestPath.ToString()); var deserializer = new DeserializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) .WithNodeDeserializer(inner => new ValidatingNodeDeserializer(inner), s => s.InsteadOf <ObjectNodeDeserializer>()) .WithTypeConverter(new TypeCodeTypeConverter()) .WithTagMapping(Builders.ChoiceValidatorBuilder.Tag, typeof(Builders.ChoiceValidatorBuilder)) .Build(); return(deserializer.Deserialize <Builders.TemplateBuilder>(reader).Build()); }
/// <inheritdoc/> protected override WindowsPath PathFactory(IPurePath path) { if (path == null) { throw new NullReferenceException( "Path passed to factory cannot be null."); } var purePath = path as PureWindowsPath; if (purePath != null) { return(new WindowsPath(purePath)); } var parts = new List <string>(); parts.AddRange(path.Parts); return(new WindowsPath(parts.ToArray())); }
/// <inheritdoc/> public TPath RelativeTo(IPurePath parent) { if (!ComponentComparer.Equals(parent.Drive, Drive) || !ComponentComparer.Equals(parent.Root, Root)) { throw new ArgumentException(String.Format( "'{0}' does not share the same root/drive as '{1}', " + "thus cannot be relative.", this, parent)); } var thisDirname = Dirname .Split(PathSeparator[0]).GetEnumerator(); var parentRelative = parent.Relative().ToString(); if (parentRelative == String.Empty) { return(Relative()); } var parentDirname = parentRelative.Split(PathSeparator[0]).GetEnumerator(); while (parentDirname.MoveNext()) { if (!thisDirname.MoveNext() || !ComponentComparer.Equals(parentDirname.Current, thisDirname.Current)) { throw new ArgumentException(String.Format( "'{0}' does not start with '{1}'", this, parent)); } } var builder = new StringBuilder(); while (thisDirname.MoveNext()) { if (builder.Length != 0) { builder.Append(PathSeparator); } builder.Append(thisDirname.Current); } return(PurePathFactoryFromComponents( null, null, null, builder.ToString(), Basename, Extension)); }
/// <summary> /// Removes all parent directory components. Disallows combining /// with absolute paths. /// </summary> /// <param name="base"></param> /// <param name="toJoin"></param> /// <param name="separator"></param> /// <param name="combined"></param> /// <returns></returns> internal static bool TrySafeCombine( IPurePath @base, IPurePath toJoin, string separator, out string combined) { var joinParts = new List <string>(); foreach (var part in toJoin.Parts) { if (part == toJoin.Anchor) { continue; } var normalized = part.Normalize(NormalizationForm.FormKC); if (normalized == ParentDirectoryIdentifier) { if (joinParts.Count > 0) { joinParts.RemoveAt(joinParts.Count - 1); } else // attempted parent dir { combined = null; return(false); } } else { joinParts.Add(part); } } var parts = new List <string>(@base.Parts); parts.AddRange(joinParts); combined = String.Join(separator, parts.ToArray()); return(true); }
public void PutFile(Stream source, IPurePath destinationPath, IFileTransferHandler handler) { var result = Sftp.BeginUploadFile( source, destinationPath.ToString(), r => handler.TransferCanceled(), new object(), handler.IncrementBytesTransferred); Sftp.EndUploadFile(result); }
/// <inheritdoc/> TPurePath IPurePath <TPurePath> .RelativeTo(IPurePath parent) { return(PurePath.RelativeTo(parent)); }
public bool PutFile(IPurePath sourcePath, IPurePath destinationPath, IFileTransferHandler handler, bool ifNewer) { var filename = sourcePath.Filename; var source = Context.LocalEnv.CurrentDirectory.Join(sourcePath); var dest = Context.RemoteEnv.CurrentDirectory.Join(destinationPath); if (handler != null) { handler.Filename = filename; } if (!File.Exists(source.ToString())) { if (handler != null) { handler.FileDoesNotExist(); } return false; } if (String.IsNullOrEmpty(dest.Filename) || Sftp.GetAttributes(dest.ToString()).IsDirectory) { dest = dest.WithFilename(filename); } if (ifNewer) { var modified = File.GetLastWriteTimeUtc(source.ToString()); var remoteModified = DateTime.MinValue; try { remoteModified = Sftp.GetLastWriteTimeUtc(dest.ToString()); } catch (SftpPathNotFoundException) { } if (modified <= remoteModified) { if (handler != null) { handler.FileUpToDate(); } return false; } } using (var file = File.OpenRead(source.ToString())) { PutFile(file, dest, handler); } return true; }
public void PutFile(Stream source, IPurePath destinationPath, IFileTransferHandler handler) { CopyFile(source, destinationPath.ToString(), 1024, handler); }
public void MkDir(IPurePath path, bool makeParents = false) { MkDir(path.ToString(), makeParents); }
/// <inheritdoc/> bool IPurePath.TrySafeJoin(IPurePath relativePath, out IPurePath joined) { return(PurePath.TrySafeJoin(relativePath, out joined)); }
public void PutDir(IPurePath sourceDir, IPurePath destinationDir, Func<IFileTransferHandler> handlerFactory, bool ifNewer, IEnumerable<string> fileFilters) { MkDir(destinationDir, true); foreach (var filter in fileFilters) { var pattern = sourceDir.Join(filter); var matches = Glob.GetMatches(pattern.AsPosix()).ToList(); if (!matches.Any()) { var handler = handlerFactory(); handler.Filename = Path.GetFileName(filter); handler.FileDoesNotExist(); } else { foreach (var file in matches) { var tmpPath = file; if (sourceDir.Drive.StartsWith("//") || sourceDir.Drive.StartsWith(@"\\")) { // TODO fix bug in GlobDir that trims the leading slash off UNC paths // https://github.com/giggio/globdir/issues/2 tmpPath = "/" + file; } var subdir = Context.LocalEnv .CreatePurePath(tmpPath) .RelativeTo(sourceDir); var newDestinationDir = destinationDir.Join(subdir); if (Directory.Exists(tmpPath)) { MkDir(newDestinationDir); } else if (File.Exists(tmpPath)) { PutFile(tmpPath, newDestinationDir.ToString(), handlerFactory(), ifNewer); } else { Context.Logger.Error(String.Format( "File or directory {0} does not exist locally.", tmpPath)); } } } } }
private static IPurePath ApplyOptions(IPurePath path, PurePathFactoryOptions options) { if (options.AutoNormalizeCase) { path = options.Culture != null ? path.NormCase(options.Culture) : path.NormCase(); } return path; }
public void PutDir(IPurePath sourceDir, IPurePath destinationDir, Func<IFileTransferHandler> handlerFactory, bool ifNewer, IEnumerable<string> fileFilters) { PutDir(sourceDir.ToString(), destinationDir.ToString(), handlerFactory, ifNewer, fileFilters); }
/// <inheritdoc/> TPurePath IPurePath <TPurePath> .WithDirname(IPurePath newDirName) { return(PurePath.WithDirname(newDirName)); }
IPurePath IPurePath.RelativeTo(IPurePath parent) { return(RelativeTo(parent)); }
/// <summary> /// Factory method to create a new <see cref="PurePath"/> instance /// based upon the current operating system. /// </summary> /// <param name="path"></param> /// <param name="options"></param> /// <param name="result"></param> /// <returns></returns> public bool TryCreate(string path, PurePathFactoryOptions options, out IPurePath result) { result = null; switch (PlatformChooser.GetPlatform()) { case Platform.Posix: PurePosixPath purePosixPath; if (PurePosixPath.TryParse(path, out purePosixPath)) { result = purePosixPath; break; } return false; case Platform.Windows: PureWindowsPath pureWindowsPath; if (PureWindowsPath.TryParse(path, out pureWindowsPath)) { result = pureWindowsPath; break; } return false; } result = ApplyOptions(result, options); return true; }
/// <inheritdoc/> public TPath RelativeTo(IPurePath parent) { return(PathFactory(PurePath.RelativeTo(parent))); }
/// <inheritdoc/> protected abstract TPath PathFactory(IPurePath path);
public void RmDir(IPurePath path, bool recursive) { var pathStr = path.ToString(); if (!Sftp.GetAttributes(pathStr).IsDirectory) { throw new InvalidOperationException(String.Format( "'{0}' is not a directory.", path)); } if (!recursive && Sftp.ListDirectory(pathStr).Any()) { throw new InvalidOperationException(String.Format( "Directory '{0}' is not empty.", path)); } Sftp.DeleteDirectory(pathStr); }
/// <inheritdoc/> protected override PosixPath PathFactory(IPurePath path) { throw new NotImplementedException(); }
public void RmDir(IPurePath path, bool recursive = false) { RmDir(path.ToString(), recursive); }
/// <inheritdoc/> public TPath WithDirname(IPurePath newDirName) { return(PathFactory(PurePath.WithDirname(newDirName))); }
/// <summary> /// Factory method to create a new <see cref="PurePath"/> instance /// based upon the current operating system. /// </summary> /// <param name="path"></param> /// <param name="result"></param> /// <returns></returns> public bool TryCreate(string path, out IPurePath result) { return(TryCreate(path, new PurePathFactoryOptions(), out result)); }
/// <summary> /// Factory method to create a new <see cref="PurePath"/> instance /// based upon the current operating system. /// </summary> /// <param name="path"></param> /// <param name="result"></param> /// <returns></returns> public bool TryCreate(string path, out IPurePath result) { return TryCreate(path, new PurePathFactoryOptions(), out result); }
public void PutDir(IPurePath sourceDir, IPurePath destinationDir, Func<IFileTransferHandler> handlerFactory, bool ifNewer) { PutDir(sourceDir.ToString(), destinationDir.ToString(), handlerFactory, ifNewer); }
/// <summary> /// Removes all parent directory components. Disallows combining /// with absolute paths. /// </summary> /// <param name="base"></param> /// <param name="toJoin"></param> /// <param name="separator"></param> /// <param name="combined"></param> /// <returns></returns> internal static bool TrySafeCombine( IPurePath @base, IPurePath toJoin, string separator, out string combined) { var joinParts = new List<string>(); foreach (var part in toJoin.Parts) { if (part == toJoin.Anchor) { continue; } var normalized = part.Normalize(NormalizationForm.FormKC); if (normalized == ParentDirectoryIdentifier) { if (joinParts.Count > 0) { joinParts.RemoveAt(joinParts.Count - 1); } else // attempted parent dir { combined = null; return false; } } else { joinParts.Add(part); } } var parts = new List<string>(@base.Parts); parts.AddRange(joinParts); combined = String.Join(separator, parts.ToArray()); return true; }
/// <summary> /// Change to the given directory on the remote machine. /// </summary> /// <param name="context">Deployment context.</param> /// <param name="path">New current directory.</param> public Cd(IDeploymentContext context, IPurePath path) : base(context) { Context.RemoteEnv.Pushd( Context.RemoteEnv.CurrentDirectory.Join(path)); }
private void RecursiveTarDir(TarOutputStream stream, IPurePath subdir, IPurePath source, int depth) { var sourceStr = source.ToString(); if (depth == 0) { return; } if (!Directory.Exists(sourceStr)) { throw new IOException("Could not find path " + source); } foreach (var subfile in Directory.EnumerateFiles(sourceStr)) { TarFile( stream, subdir.WithFilename(source.Filename), Context.LocalEnv.CreatePurePath(subfile)); } foreach (var dirStr in Directory.EnumerateDirectories(sourceStr)) { var dir = Context.LocalEnv.CreatePurePath(dirStr); var dirpath = subdir.Join(Directory.GetParent(dirStr).Name); RecursiveTarDir(stream, dirpath, dir, depth > 0 ? depth - 1 : depth); } }
public bool PutFile(IPurePath sourcePath, IPurePath destinationPath, IFileTransferHandler handler, bool ifNewer) { var filename = sourcePath.Filename; var source = Context.LocalEnv.CurrentDirectory.Join(sourcePath); var dest = Context.LocalEnv.CurrentDirectory.Join(destinationPath); if (handler != null) { handler.Filename = filename; } if (!File.Exists(source.ToString())) { if (handler != null) { handler.FileDoesNotExist(); } return false; } if (String.IsNullOrEmpty(dest.Filename) || Directory.Exists(dest.ToString())) { dest = dest.WithFilename(filename); } var sourceStr = source.ToString(); var destStr = dest.ToString(); if (ifNewer && File.Exists(destStr) && File.GetLastWriteTimeUtc(sourceStr) <= File.GetLastWriteTimeUtc(destStr)) { if (handler != null) { handler.FileUpToDate(); } return false; } using (var file = File.OpenRead(sourceStr)) { PutFile(file, destStr, handler); } return true; }
private void TarFile(TarOutputStream stream, IPurePath baseDir, IPurePath sourcePath) { var tarName = baseDir.WithFilename(sourcePath.Filename); var entry = TarEntry.CreateTarEntry(tarName.ToString()); using (var file = File.OpenRead(sourcePath.ToString())) { entry.Size = file.Length; stream.PutNextEntry(entry); file.CopyTo(stream); } stream.CloseEntry(); }
public void RmDir(IPurePath path, bool recursive) { Directory.Delete(path.ToString(), recursive); }
public void MkDir(IPurePath path, bool makeParents = false) { // Iteratively check whether or not each directory in the path exists // and create them if they do not. if (makeParents) { foreach (var parent in path.Parents().Reverse()) { var pathStr = parent.ToString(); if (!Sftp.Exists(pathStr)) { Sftp.CreateDirectory(pathStr); } } } else { var pathStr = path.ToString(); if (!Sftp.Exists(pathStr)) { Sftp.CreateDirectory(pathStr); } } }
public void PutDir(IPurePath sourceDir, IPurePath destinationDir, Func<IFileTransferHandler> handlerFactory, bool ifNewer) { const string filter = "**"; // All files, recursive PutDir(sourceDir, destinationDir, handlerFactory, ifNewer, new[] { filter }); }
/// <inheritdoc/> public bool TrySafeJoin(IPurePath path, out TPurePath joined) { return(PurePath.TrySafeJoin(path, out joined)); }
IPurePath IPurePath.WithDirname(IPurePath newDirname) { return(WithDirname(newDirname)); }
public bool PutFile(IPurePath sourcePath, IPurePath destinationPath, IFileTransferHandler handler, bool ifNewer) { return PutFile(sourcePath.ToString(), destinationPath.ToString(), handler, ifNewer); }