コード例 #1
0
ファイル: GitModule.cs プロジェクト: ibebbs/Wyam
 protected GitModule(DirectoryPath repositoryPath)
 {
     if (repositoryPath != null && !repositoryPath.IsAbsolute)
     {
         throw new ArgumentException("The repository location must be absolute", nameof(repositoryPath));
     }
     _repositoryPath = repositoryPath;
 }
コード例 #2
0
ファイル: DirectoryPath.cs プロジェクト: ryanrousseau/Wyam
 /// <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));
 }
コード例 #3
0
ファイル: PreviewServer.cs プロジェクト: ibebbs/Wyam
        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;
        }
コード例 #4
0
ファイル: PathTests.cs プロジェクト: ryanrousseau/Wyam
            public void ShouldCollapsePath(string fullPath, string expected)
            {
                // Given
                DirectoryPath directoryPath = new DirectoryPath(fullPath);

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

                // Then
                Assert.AreEqual(expected, path);
            }
コード例 #5
0
            public void ShouldThrowIfPathIsNull()
            {
                // Given
                DirectoryPath path = new DirectoryPath("assets");

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

                // Then
                Assert.Throws<ArgumentNullException>(test);
            }
コード例 #6
0
            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);
            }
コード例 #7
0
ファイル: DirectoryPathTests.cs プロジェクト: ibebbs/Wyam
            public void ShouldReturnDirectoryName(string directoryPath, string name)
            {
                // Given
                DirectoryPath path = new DirectoryPath(directoryPath);

                // When
                string result = path.Name;

                // Then
                Assert.AreEqual(name, result);
            }
コード例 #8
0
ファイル: DirectoryPathTests.cs プロジェクト: ibebbs/Wyam
            public void RootDirectoryReturnsNullParent(string directoryPath)
            {
                // Given
                DirectoryPath path = new DirectoryPath(directoryPath);

                // When
                DirectoryPath parent = path.Parent;

                // Then
                Assert.IsNull(parent);
            }
コード例 #9
0
ファイル: PreviewCommand.cs プロジェクト: ibebbs/Wyam
 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;
 }
コード例 #10
0
ファイル: DirectoryPathTests.cs プロジェクト: ibebbs/Wyam
            public void ReturnsParent(string directoryPath, string expected)
            {
                // Given
                DirectoryPath path = new DirectoryPath(directoryPath);

                // When
                DirectoryPath parent = path.Parent;

                // Then
                Assert.AreEqual(expected, parent.FullPath);
            }
コード例 #11
0
ファイル: WyamFolderNuGetProject.cs プロジェクト: ibebbs/Wyam
 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}");
     });
 }
コード例 #12
0
            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);
            }
コード例 #13
0
ファイル: LinkGenerator.cs プロジェクト: ibebbs/Wyam
        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;
        }
コード例 #14
0
ファイル: RelativePathResolver.cs プロジェクト: ibebbs/Wyam
        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);
        }
コード例 #15
0
ファイル: LocalDirectory.cs プロジェクト: ibebbs/Wyam
        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));
        }
コード例 #16
0
ファイル: LocalDirectory.cs プロジェクト: ibebbs/Wyam
        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);
        }
コード例 #17
0
ファイル: WyamFolderNuGetProject.cs プロジェクト: ibebbs/Wyam
 // 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");
         }
     }
 }
コード例 #18
0
ファイル: WyamFolderNuGetProject.cs プロジェクト: ibebbs/Wyam
 // 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");
         }
     }
 }
コード例 #19
0
ファイル: VirtualInputDirectory.cs プロジェクト: ibebbs/Wyam
        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;
        }
コード例 #20
0
 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;
 }
コード例 #21
0
ファイル: Repository.cs プロジェクト: ryanrousseau/Wyam
        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);
            }
        }
コード例 #22
0
ファイル: GitModule.cs プロジェクト: ibebbs/Wyam
        // 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");
        }
コード例 #23
0
ファイル: GitCommitsTests.cs プロジェクト: ibebbs/Wyam
            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);
            }
コード例 #24
0
        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)));
        }
コード例 #25
0
ファイル: DirectoryPath.cs プロジェクト: mattbrailsford/Wyam
 /// <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));
 }
コード例 #26
0
ファイル: FileSystemTests.cs プロジェクト: ibebbs/Wyam
            public void ThrowsIfProviderNotFoundForDirectoryPath()
            {
                // Given
                FileSystem fileSystem = new FileSystem();
                DirectoryPath path = new DirectoryPath("foo", "/a/b/c");

                // When, Then
                Assert.Throws<KeyNotFoundException>(() => fileSystem.GetFileProvider(path));
            }
コード例 #27
0
ファイル: FileSystemTests.cs プロジェクト: ibebbs/Wyam
            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);
            }
コード例 #28
0
ファイル: FileSystemTests.cs プロジェクト: ibebbs/Wyam
            public void ThrowsForRelativeDirectoryPath()
            {
                // Given
                FileSystem fileSystem = new FileSystem();
                DirectoryPath relativePath = new DirectoryPath("A/B/C");

                // When, Then
                Assert.Throws<ArgumentException>(() => fileSystem.GetFileProvider(relativePath));
            }
コード例 #29
0
ファイル: TestDirectory.cs プロジェクト: ibebbs/Wyam
 public TestDirectory(TestFileProvider fileProvider, DirectoryPath path)
 {
     _fileProvider = fileProvider;
     _path = path.Collapse();
 }
コード例 #30
0
            public void ShouldThrowIfTargetIsNullWithFilePath()
            {
                // Given
                DirectoryPath sourcePath = new DirectoryPath("/A");

                // When, Then
                Assert.Throws<ArgumentNullException>(() => RelativePathResolver.Resolve(sourcePath, (FilePath)null));
            }
コード例 #31
0
            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()
            }
コード例 #32
0
            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));
            }