Exemple #1
0
 protected GitModule(DirectoryPath repositoryPath)
 {
     if (repositoryPath != null && !repositoryPath.IsAbsolute)
     {
         throw new ArgumentException("The repository location must be absolute", nameof(repositoryPath));
     }
     _repositoryPath = repositoryPath;
 }
Exemple #2
0
 /// <summary>
 /// Combines the current path with another <see cref="DirectoryPath"/>.
 /// The provided <see cref="DirectoryPath"/> must be relative.
 /// </summary>
 /// <param name="path">The path.</param>
 /// <returns>A combination of the current path and the provided <see cref="DirectoryPath"/>.</returns>
 public DirectoryPath Combine(DirectoryPath path)
 {
     if (path == null)
     {
         throw new ArgumentNullException(nameof(path));
     }
     return !path.IsRelative ? path : new DirectoryPath(System.IO.Path.Combine(FullPath, path.FullPath));
 }
Exemple #3
0
        public static IDisposable Start(DirectoryPath path, int port, bool forceExtension)
        {
            IDisposable server;
            try
            {
                StartOptions options = new StartOptions("http://localhost:" + port);

                // Disable built-in owin tracing by using a null trace output
                // http://stackoverflow.com/questions/17948363/tracelistener-in-owin-self-hosting
                options.Settings.Add(typeof(ITraceOutputFactory).FullName, typeof(NullTraceOutputFactory).AssemblyQualifiedName);

                server = WebApp.Start(options, app =>
                {
                    Microsoft.Owin.FileSystems.IFileSystem outputFolder = new PhysicalFileSystem(path.FullPath);

                    // Disable caching
                    app.Use((c, t) =>
                    {
                        c.Response.Headers.Append("Cache-Control", "no-cache, no-store, must-revalidate");
                        c.Response.Headers.Append("Pragma", "no-cache");
                        c.Response.Headers.Append("Expires", "0");
                        return t();
                    });

                    // Support for extensionless URLs
                    if (!forceExtension)
                    {
                        app.UseExtensionlessUrls(new ExtensionlessUrlsOptions
                        {
                            FileSystem = outputFolder
                        });
                    }

                    // Serve up all static files
                    app.UseDefaultFiles(new DefaultFilesOptions
                    {
                        RequestPath = PathString.Empty,
                        FileSystem = outputFolder,
                        DefaultFileNames = new List<string> { "index.html", "index.htm", "home.html", "home.htm", "default.html", "default.html" }
                    });
                    app.UseStaticFiles(new StaticFileOptions
                    {
                        RequestPath = PathString.Empty,
                        FileSystem = outputFolder,
                        ServeUnknownFileTypes = true
                    });
                });
            }
            catch (Exception ex)
            {
                Trace.Critical("Error while running preview server: {0}", ex.Message);
                return null;
            }

            Trace.Information("Preview server listening on port {0} and serving from path {1}", port, path);
            return server;
        }
Exemple #4
0
            public void ShouldCollapsePath(string fullPath, string expected)
            {
                // Given
                DirectoryPath directoryPath = new DirectoryPath(fullPath);

                // When
                string path = NormalizedPath.Collapse(directoryPath);

                // Then
                Assert.AreEqual(expected, path);
            }
            public void ShouldThrowIfPathIsNull()
            {
                // Given
                DirectoryPath path = new DirectoryPath("assets");

                // When
                TestDelegate test = () => path.CombineFile(null);

                // Then
                Assert.Throws<ArgumentNullException>(test);
            }
            public void ShouldCombinePaths(string first, string second, string expected)
            {
                // Given
                DirectoryPath path = new DirectoryPath(first);

                // When
                FilePath result = path.GetFilePath(new FilePath(second));

                // Then
                Assert.AreEqual(expected, result.FullPath);
            }
Exemple #7
0
            public void ShouldReturnDirectoryName(string directoryPath, string name)
            {
                // Given
                DirectoryPath path = new DirectoryPath(directoryPath);

                // When
                string result = path.Name;

                // Then
                Assert.AreEqual(name, result);
            }
Exemple #8
0
            public void RootDirectoryReturnsNullParent(string directoryPath)
            {
                // Given
                DirectoryPath path = new DirectoryPath(directoryPath);

                // When
                DirectoryPath parent = path.Parent;

                // Then
                Assert.IsNull(parent);
            }
Exemple #9
0
 protected override ExitCode RunCommand(Preprocessor preprocessor)
 {
     _path = new DirectoryPath(Environment.CurrentDirectory).Combine(_path ?? "output");
     using (PreviewServer.Start(_path, _port, _forceExtension))
     {
         Trace.Information("Hit any key to exit");
         Console.ReadKey();
         Trace.Information("Shutting down");
     }
     return ExitCode.Normal;
 }
Exemple #10
0
            public void ReturnsParent(string directoryPath, string expected)
            {
                // Given
                DirectoryPath path = new DirectoryPath(directoryPath);

                // When
                DirectoryPath parent = path.Parent;

                // Then
                Assert.AreEqual(expected, parent.FullPath);
            }
Exemple #11
0
 public void ProcessAssembliesAndContent()
 {
     Parallel.ForEach(_packageIdentities, packageIdentity =>
     {
         DirectoryPath installedPath = new DirectoryPath(GetInstalledPath(packageIdentity));
         string packageFilePath = GetInstalledPackageFilePath(packageIdentity);
         PackageArchiveReader archiveReader = new PackageArchiveReader(packageFilePath, null, null);
         AddReferencedAssemblies(installedPath, archiveReader);
         IncludeContentDirectories(installedPath, archiveReader);
         Trace.Verbose($"Finished processing NuGet package at {installedPath}");
     });
 }
            public void ShouldReturnRelativePathWithDirectoryPath(string source, string target, string expected)
            {
                // Given
                DirectoryPath sourcePath = new DirectoryPath(source);
                DirectoryPath targetPath = new DirectoryPath(target);

                // When
                DirectoryPath relativePath = RelativePathResolver.Resolve(sourcePath, targetPath);

                // Then
                Assert.AreEqual(expected, relativePath.FullPath);
            }
Exemple #13
0
        public static string GetLink(NormalizedPath path, string host, DirectoryPath root, bool hideIndexPages, bool hideExtensions)
        {
            // Remove index pages and extensions if a file path
            FilePath filePath = path as FilePath;
            if (filePath != null)
            {
                if (hideIndexPages && (filePath.FileName.FullPath == "index.htm" || filePath.FileName.FullPath == "index.html"))
                {
                    path = filePath.Directory;
                }
                else if (hideExtensions)
                {
                    path = filePath.ChangeExtension(null);
                }
            }

            // Collapse the link to a string
            string link = string.Empty;
            if(path != null)
            {
                link = path.FullPath;
                if (string.IsNullOrWhiteSpace(link) || link == ".")
                {
                    link = "/";
                }
                if (!link.StartsWith("/"))
                {
                    link = "/" + link;
                }
            }

            // Collapse the root and combine
            string rootLink = root == null ? string.Empty : root.FullPath;
            if (rootLink.EndsWith("/"))
            {
                rootLink = rootLink.Substring(0, rootLink.Length - 1);
            }

            // Add the host and convert to URI for escaping
            UriBuilder builder = new UriBuilder
            {
                Path = rootLink + link
            };
            bool hasHost = false;
            if (!string.IsNullOrWhiteSpace(host))
            {
                builder.Host = host;
                hasHost = true;
            }
            Uri uri = builder.Uri;
            return hasHost ? uri.AbsoluteUri : uri.AbsolutePath;
        }
Exemple #14
0
        public static FilePath Resolve(DirectoryPath source, FilePath target)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            return Resolve(source, target.Directory).GetFilePath(target.FileName);
        }
Exemple #15
0
        public IDirectory GetDirectory(DirectoryPath path)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (!path.IsRelative)
            {
                throw new ArgumentException("Path must be relative", nameof(path));
            }

            return new LocalDirectory(_path.Combine(path));
        }
Exemple #16
0
        public LocalDirectory(DirectoryPath path)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (path.IsRelative)
            {
                throw new ArgumentException("Path must be absolute", nameof(path));
            }

            _path = path.Collapse();
            _directory = new DirectoryInfo(_path.FullPath);
        }
Exemple #17
0
 // Add all reference items to the assembly list
 private void AddReferencedAssemblies(DirectoryPath installedPath, PackageArchiveReader archiveReader)
 {
     FrameworkSpecificGroup referenceGroup = GetMostCompatibleGroup(_reducer,
         _currentFramework, archiveReader.GetReferenceItems().ToList());
     if (referenceGroup != null)
     {
         foreach (FilePath itemPath in referenceGroup.Items
             .Select(x => new FilePath(x))
             .Where(x => x.FileName.Extension == ".dll" || x.FileName.Extension == ".exe"))
         {
             FilePath assemblyPath = installedPath.CombineFile(itemPath);
             _assemblyLoader.Add(assemblyPath.FullPath);
             Trace.Verbose($"Added NuGet reference {assemblyPath} for loading");
         }
     }
 }
Exemple #18
0
 // Add content directories to the input paths
 private void IncludeContentDirectories(DirectoryPath installedPath, PackageArchiveReader archiveReader)
 {
     FrameworkSpecificGroup contentGroup = GetMostCompatibleGroup(_reducer,
         _currentFramework, archiveReader.GetContentItems().ToList());
     if (contentGroup != null)
     {
         // We need to use the directory name from an actual file to make sure we get the casing right
         foreach (string contentSegment in contentGroup.Items
             .Select(x => new FilePath(x).Segments[0])
             .Distinct())
         {
             DirectoryPath contentPath = installedPath.Combine(contentSegment);
             _fileSystem.InputPaths.Insert(0, contentPath);
             Trace.Verbose($"Added content path {contentPath} to included paths");
         }
     }
 }
Exemple #19
0
        public VirtualInputDirectory(FileSystem fileSystem, DirectoryPath path)
        {
            if (fileSystem == null)
            {
                throw new ArgumentNullException(nameof(fileSystem));
            }
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (!path.IsRelative)
            {
                throw new ArgumentException("Virtual input paths should always be relative", nameof(path));
            }

            _fileSystem = fileSystem;
            _path = path;
        }
 public ActionFileSystemWatcher(DirectoryPath outputDirectory, IEnumerable<DirectoryPath> inputDirectories, bool includeSubdirectories, string filter, Action<string> callback)
 {
     foreach (string inputDirectory in inputDirectories.Select(x => x.Collapse().FullPath).Where(Directory.Exists))
     {
         FileSystemWatcher watcher = new FileSystemWatcher
         {
             Path = inputDirectory,
             IncludeSubdirectories = includeSubdirectories,
             Filter = filter,
             EnableRaisingEvents = true
         };
         watcher.Changed += OnChanged;
         watcher.Created += OnChanged;
         _watchers.Add(watcher);
     }
     _outputPath = outputDirectory.Collapse().FullPath;
     _callback = callback;
 }
Exemple #21
0
        public void InstallPackages(string absolutePackagesPath, DirectoryPath contentPath, IConfigurableFileSystem fileSystem, bool updatePackages)
        {
            PackageManager packageManager = new PackageManager(_packageRepository, absolutePackagesPath);

            // On package install...
            packageManager.PackageInstalled += (sender, args) =>
            {
                IDirectory packageContentDirectory = fileSystem.GetRootDirectory(contentPath.Combine(args.Package.Id));

                // Copy all content files on install and add to input paths
                bool firstFile = true;
                foreach (IPackageFile packageFile in args.Package.GetContentFiles())
                {
                    if (firstFile)
                    {
                        // This package does have content files, so create the directory and add an input path
                        packageContentDirectory.Create();
                        fileSystem.InputPaths.Insert(0, packageContentDirectory.Path);
                        firstFile = false;
                    }

                    IFile file = packageContentDirectory.GetFile(packageFile.EffectivePath);
                    file.Directory.Create();
                    using (var fileStream = file.Open(FileMode.Create))
                    {
                        packageFile.GetStream().CopyTo(fileStream);
                    }
                }
            };

            // On package uninstall...
            packageManager.PackageUninstalling += (sender, args) =>
            {
                IDirectory packageContentDirectory = fileSystem.GetRootDirectory(contentPath.Combine(args.Package.Id));
                packageContentDirectory.Delete(true);
            };

            // Install the packages
            foreach (Package package in _packages)
            {
                package.InstallPackage(packageManager, updatePackages);
            }
        }
Exemple #22
0
        // Returns the absolute path of a valid repository
        protected DirectoryPath GetRepositoryPath(IExecutionContext context)
        {
            // If we've already checked, return the valid one
            if (_validRepositoryPath)
            {
                return _repositoryPath;
            }

            // Get candidate paths
            List<DirectoryPath> candidatePaths = new List<DirectoryPath>();
            if (_repositoryPath != null)
            {
                candidatePaths.Add(_repositoryPath);
            }
            else
            {
                candidatePaths.AddRange(context.FileSystem.InputPaths
                    .Reverse()
                    .Select(x => context.FileSystem.RootPath.Combine(x)));
                candidatePaths.Add(context.FileSystem.RootPath);
            }

            // Find the candidate (or one of it's roots) that contains a repo
            foreach (DirectoryPath candidatePath in candidatePaths)
            {
                DirectoryPath testPath = candidatePath;
                while (testPath != null && !Repository.IsValid(testPath.FullPath))
                {
                    testPath = testPath.Parent;
                }
                if (testPath != null)
                {
                    _repositoryPath = testPath;
                    return testPath;
                }
            }

            // If we got here, we didn't get a valid path
            throw new InvalidOperationException("No repository could be found");
        }
Exemple #23
0
            public void GetCommitsForInputDocument()
            {
                // Given
                DirectoryPath inputPath = new DirectoryPath(TestContext.CurrentContext.TestDirectory).Parent.Parent.Parent.Parent;
                IExecutionContext context = Substitute.For<IExecutionContext>();
                context.FileSystem.RootPath.Returns(new DirectoryPath("/"));
                context.FileSystem.InputPaths.Returns(x => new[] { inputPath });
                context.GetDocument(Arg.Any<IEnumerable<KeyValuePair<string, object>>>()).Returns(getNewDocumentCallInfo =>
                {
                    IDocument newDocument = Substitute.For<IDocument>();
                    newDocument.GetEnumerator()
                        .Returns(getNewDocumentCallInfo.ArgAt<IEnumerable<KeyValuePair<string, object>>>(0).GetEnumerator());
                    newDocument.Get<IReadOnlyDictionary<FilePath, string>>(Arg.Any<string>())
                        .Returns(getCallInfo => (IReadOnlyDictionary<FilePath, string>)getNewDocumentCallInfo.ArgAt<IEnumerable<KeyValuePair<string, object>>>(0).First(x => x.Key == getCallInfo.ArgAt<string>(0)).Value);
                    return newDocument;
                });
                IDocument document = Substitute.For<IDocument>();
                document.Source.Returns(inputPath.CombineFile("Wyam.Core/IModule.cs"));  // Use file that no longer exists so commit count is stable
                context.GetDocument(Arg.Any<IDocument>(), Arg.Any<IEnumerable<KeyValuePair<string, object>>>()).Returns(x =>
                {
                    IDocument newDocument = Substitute.For<IDocument>();
                    newDocument.GetEnumerator().Returns(x.ArgAt<IEnumerable<KeyValuePair<string, object>>>(1).GetEnumerator());
                    return newDocument;
                });
                GitCommits gitCommits = new GitCommits().ForEachInputDocument();

                // When
                List<IDocument> results = gitCommits.Execute(new[] { document }, context).ToList();  // Make sure to materialize the result list

                // Then
                Assert.AreEqual(1, results.Count);
                List<IDocument> commits =
                    ((IEnumerable<IDocument>) results[0].First(x => x.Key == GitKeys.Commits).Value).ToList();
                Assert.AreEqual(6, commits.Count);
                Assert.AreEqual("6274fb76a0380760ab2dc83f90748b7d953aceb4", commits.Last().First(x => x.Key == GitKeys.Sha).Value);
            }
        public static DirectoryPath Resolve(DirectoryPath source, DirectoryPath target)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            // Make sure they're both either relative or absolute
            if (source.IsAbsolute != target.IsAbsolute)
            {
                throw new ArgumentException("Paths must both be relative or both be absolute");
            }

            // Collapse the paths
            source = source.Collapse();
            target = target.Collapse();

            // Check if they share the same provider
            if (source.Provider != target.Provider)
            {
                return(target);
            }

            // Check if they're the same path
            if (source.FullPath == target.FullPath)
            {
                return(new DirectoryPath("."));
            }

            // Special case if source is just root
            if (source.IsAbsolute && source.Segments.Length == 0)
            {
                return(new DirectoryPath(string.Join("/", target.Segments)));
            }

            // Check if they share the same root
            if (string.CompareOrdinal(source.Segments[0], target.Segments[0]) != 0)
            {
                return(target);
            }

            int minimumSegmentsLength = Math.Min(source.Segments.Length, target.Segments.Length);

            int lastCommonRoot = -1;

            // Find common root
            for (int x = 0; x < minimumSegmentsLength; x++)
            {
                if (string.CompareOrdinal(source.Segments[x], target.Segments[x]) != 0)
                {
                    break;
                }

                lastCommonRoot = x;
            }

            if (lastCommonRoot == -1)
            {
                return(target);
            }

            // Add relative folders in from path
            List <string> relativeSegments = new List <string>();

            for (int x = lastCommonRoot + 1; x < source.Segments.Length; x++)
            {
                if (source.Segments[x].Length > 0)
                {
                    relativeSegments.Add("..");
                }
            }

            // Add to folders to path
            for (int x = lastCommonRoot + 1; x < target.Segments.Length; x++)
            {
                relativeSegments.Add(target.Segments[x]);
            }

            // Create relative path
            return(new DirectoryPath(string.Join("/", relativeSegments)));
        }
Exemple #25
0
 /// <summary>
 /// Get the relative path to another directory. If this path and the target path
 /// do not share the same provider, the target path is returned.
 /// </summary>
 /// <param name="target">The target directory path.</param>
 /// <returns>A <see cref="DirectoryPath"/>.</returns>
 public DirectoryPath GetRelativePath(DirectoryPath target)
 {
     return(RelativePathResolver.Resolve(this, target));
 }
Exemple #26
0
            public void ThrowsIfProviderNotFoundForDirectoryPath()
            {
                // Given
                FileSystem fileSystem = new FileSystem();
                DirectoryPath path = new DirectoryPath("foo", "/a/b/c");

                // When, Then
                Assert.Throws<KeyNotFoundException>(() => fileSystem.GetFileProvider(path));
            }
Exemple #27
0
            public void ReturnsOtherProviderForDirectoryPath()
            {
                // Given
                FileSystem fileSystem = new FileSystem();
                IFileProvider defaultProvider = Substitute.For<IFileProvider>();
                IFileProvider fooProvider = Substitute.For<IFileProvider>();
                fileSystem.FileProviders.Add(NormalizedPath.DefaultFileProvider.Scheme, defaultProvider);
                fileSystem.FileProviders.Add("foo", fooProvider);
                DirectoryPath path = new DirectoryPath("foo", "/a/b/c");

                // When
                IFileProvider result = fileSystem.GetFileProvider(path);

                // Then
                Assert.AreEqual(fooProvider, result);
            }
Exemple #28
0
            public void ThrowsForRelativeDirectoryPath()
            {
                // Given
                FileSystem fileSystem = new FileSystem();
                DirectoryPath relativePath = new DirectoryPath("A/B/C");

                // When, Then
                Assert.Throws<ArgumentException>(() => fileSystem.GetFileProvider(relativePath));
            }
Exemple #29
0
 public TestDirectory(TestFileProvider fileProvider, DirectoryPath path)
 {
     _fileProvider = fileProvider;
     _path = path.Collapse();
 }
            public void ShouldThrowIfTargetIsNullWithFilePath()
            {
                // Given
                DirectoryPath sourcePath = new DirectoryPath("/A");

                // When, Then
                Assert.Throws<ArgumentNullException>(() => RelativePathResolver.Resolve(sourcePath, (FilePath)null));
            }
            public void ShouldReturnTargetPathIfProvidersDontMatch()
            {
                // Given
                DirectoryPath sourcePath = new DirectoryPath("foo:///A/B");
                FilePath targetPath = new FilePath("bar", "/A/B/C/test.txt");

                // When
                FilePath resultPath = RelativePathResolver.Resolve(sourcePath, targetPath);

                // Then
                // Assert.AreEqual(targetPath, resultPath); // Uncomment and use this when NUnit is fixed
                Assert.IsTrue(targetPath.Equals(resultPath)); // Workaround for bug in NUnit with explicitly implemented interface method IEquality.Equals()
            }
            public void ShouldThrowIfNotBothSameAbsoluteWithFilePath(string source, string target)
            {
                // Given
                DirectoryPath sourcePath = new DirectoryPath(source);
                FilePath targetPath = new FilePath(target);

                // When, Then
                Assert.Throws<ArgumentException>(() => RelativePathResolver.Resolve(sourcePath, targetPath));
            }