Beispiel #1
0
        /// <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);
        }
Beispiel #2
0
 /// <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 ?? "";
 }
Beispiel #3
0
 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());
 }
Beispiel #5
0
 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
                                                                                                                                                                     )
                                      ));
 }
Beispiel #6
0
 private static IPurePath ApplyOptions(IPurePath path, PurePathFactoryOptions options)
 {
     if (options.AutoNormalizeCase)
     {
         path = options.Culture != null
             ? path.NormCase(options.Culture)
             : path.NormCase();
     }
     return(path);
 }
Beispiel #7
0
        bool IPurePath.TrySafeJoin(IPurePath relativePath, out IPurePath joined)
        {
            TPath subPath;

            if (TrySafeJoin(relativePath, out subPath))
            {
                joined = subPath;
                return(true);
            }
            joined = null;
            return(false);
        }
Beispiel #8
0
        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));
        }
Beispiel #9
0
        /// <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);
        }
Beispiel #10
0
 /// <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 : "")));
 }
Beispiel #11
0
        /// <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));
        }
Beispiel #12
0
        /// <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));
        }
Beispiel #13
0
        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());
        }
Beispiel #14
0
        /// <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()));
        }
Beispiel #15
0
        /// <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));
        }
Beispiel #16
0
        /// <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);
        }
Beispiel #17
0
 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);
 }
Beispiel #18
0
 /// <inheritdoc/>
 TPurePath IPurePath <TPurePath> .RelativeTo(IPurePath parent)
 {
     return(PurePath.RelativeTo(parent));
 }
Beispiel #19
0
        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);
 }
Beispiel #21
0
 public void MkDir(IPurePath path, bool makeParents = false)
 {
     MkDir(path.ToString(), makeParents);
 }
Beispiel #22
0
 /// <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));
                        }
                    }
                }
            }
        }
Beispiel #24
0
 private static IPurePath ApplyOptions(IPurePath path, PurePathFactoryOptions options)
 {
     if (options.AutoNormalizeCase)
     {
         path = options.Culture != null
             ? path.NormCase(options.Culture)
             : path.NormCase();
     }
     return path;
 }
Beispiel #25
0
 public void PutDir(IPurePath sourceDir, IPurePath destinationDir, Func<IFileTransferHandler> handlerFactory,
     bool ifNewer, IEnumerable<string> fileFilters)
 {
     PutDir(sourceDir.ToString(), destinationDir.ToString(), handlerFactory, ifNewer, fileFilters);
 }
Beispiel #26
0
 /// <inheritdoc/>
 TPurePath IPurePath <TPurePath> .WithDirname(IPurePath newDirName)
 {
     return(PurePath.WithDirname(newDirName));
 }
Beispiel #27
0
 IPurePath IPurePath.RelativeTo(IPurePath parent)
 {
     return(RelativeTo(parent));
 }
Beispiel #28
0
 /// <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;
 }
Beispiel #29
0
 /// <inheritdoc/>
 public TPath RelativeTo(IPurePath parent)
 {
     return(PathFactory(PurePath.RelativeTo(parent)));
 }
Beispiel #30
0
 /// <inheritdoc/>
 protected abstract TPath PathFactory(IPurePath path);
Beispiel #31
0
 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);
 }
Beispiel #32
0
 /// <inheritdoc/>
 protected override PosixPath PathFactory(IPurePath path)
 {
     throw new NotImplementedException();
 }
Beispiel #33
0
 public void RmDir(IPurePath path, bool recursive = false)
 {
     RmDir(path.ToString(), recursive);
 }
Beispiel #34
0
 /// <inheritdoc/>
 public TPath WithDirname(IPurePath newDirName)
 {
     return(PathFactory(PurePath.WithDirname(newDirName)));
 }
Beispiel #35
0
 /// <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));
 }
Beispiel #36
0
 /// <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);
 }
Beispiel #37
0
 public void PutDir(IPurePath sourceDir, IPurePath destinationDir, Func<IFileTransferHandler> handlerFactory,
     bool ifNewer)
 {
     PutDir(sourceDir.ToString(), destinationDir.ToString(), handlerFactory, ifNewer);
 }
Beispiel #38
0
        /// <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;
        }
Beispiel #39
0
 /// <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));
 }
Beispiel #40
0
        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;
        }
Beispiel #42
0
 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);
 }
Beispiel #44
0
 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 });
 }
Beispiel #46
0
 /// <inheritdoc/>
 public bool TrySafeJoin(IPurePath path, out TPurePath joined)
 {
     return(PurePath.TrySafeJoin(path, out joined));
 }
Beispiel #47
0
 IPurePath IPurePath.WithDirname(IPurePath newDirname)
 {
     return(WithDirname(newDirname));
 }
Beispiel #48
0
 public bool PutFile(IPurePath sourcePath, IPurePath destinationPath, IFileTransferHandler handler, bool ifNewer)
 {
     return PutFile(sourcePath.ToString(), destinationPath.ToString(), handler, ifNewer);
 }