public EpisodeProcessor(EpisodeProcessorSettings settings, ITvService tvService, IFileSystem fileSystem, IAnalyticsService analyticsService) { _settings = settings; _tvService = tvService; _fileSystem = fileSystem; _analyticsService = analyticsService; _sourceFolder = _fileSystem.GetDirectory(_settings.DownloadFolder); _destinationFolder = _fileSystem.GetDirectory(_settings.TvLibraryFolder); }
public AvatarService(IPathResolver pathResolver, IFileSystem fileSystemProvider) { _pathResolver = pathResolver; _fileSystemProvider = fileSystemProvider; _avatarDirectoryInfo = _fileSystemProvider.GetDirectory("avatars"); if (!_avatarDirectoryInfo.Exists) _avatarDirectoryInfo.Create(); }
public ReSharperLoaderPlugin(IFileSystem fileSystem) { _fileSystem = fileSystem; _rootAssemblyCacheDir = _fileSystem.GetDirectory(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)) .GetDirectory("openwrap") .GetDirectory("VisualStudio") .GetDirectory("AssemblyCache") .MustExist(); var vsAppDomain = AppDomain.CurrentDomain.GetData("openwrap.vs.appdomain") as AppDomain; _output = new OpenWrapOutput(); if (vsAppDomain == null) return; DetectResharperLoading(vsAppDomain); }
protected override IReadOnlyCollection <IFile> GetAddinAssemblies(DirectoryPath path) { if (!_fileSystem.Exist(path)) { return(new List <IFile>()); } // Get current framework. var provider = DefaultFrameworkNameProvider.Instance; var current = NuGetFramework.Parse(_environment.Runtime.TargetFramework.FullName, provider); // Get all candidate files. var assemblies = _fileSystem.GetDirectory(path).GetFiles("*.dll", SearchScope.Recursive); // Iterate all found files. var comparer = new NuGetFrameworkFullComparer(); var mapping = new Dictionary <NuGetFramework, List <FilePath> >(comparer); foreach (var assembly in assemblies) { // Get relative path. var relative = path.GetRelativePath(assembly.Path); var framework = ParseFromDirectoryPath(current, relative.GetDirectory()); if (!mapping.ContainsKey(framework)) { mapping.Add(framework, new List <FilePath>()); } mapping[framework].Add(assembly.Path); } // Reduce found frameworks to the closest one. var reducer = new FrameworkReducer(); var nearest = reducer.GetNearest(current, mapping.Keys); if (nearest == null || !mapping.ContainsKey(nearest)) { return(new List <IFile>()); } // Return the result. return(mapping[nearest].Select(p => _fileSystem.GetFile(p)).ToList()); }
private IReadOnlyCollection <IFile> GetToolFiles(DirectoryPath installationLocation, PackageReference package) { var result = new List <IFile>(); var toolFolder = installationLocation.Combine(".store/" + package.Package.ToLowerInvariant()); _log.Debug("Tool Folder: {0}", toolFolder); var toolDirectory = _fileSystem.GetDirectory(toolFolder); if (toolDirectory.Exists) { result.AddRange(GetFiles(toolFolder, package)); } else { _log.Debug("Tool folder does not exist: {0}.", toolFolder); } _log.Debug("Found {0} files in tool folder", result.Count); return(result); }
public int BuildPage(CompilerConfiguration configuration, Content root, Content parent, Content current) { var count = 1; // Create the view model. var model = new LayoutViewModel(parent, current.Title); model.CurrentId = current.Id; model.Current = current; model.Root = root; // Render the master page with the model. var html = _engine.Render(configuration, "templates/layout.cshtml", model); // Save the result to disc. var outputFilePath = current.Id == "index" && current.Parent == root ? new FilePath("index.html") : new FilePath(string.Concat(current.GetLink(), "/index.html").TrimStart('/')); outputFilePath = outputFilePath.MakeAbsolute(configuration.OutputPath); var outputPath = outputFilePath.GetDirectory(); if (!_fileSystem.Exist(outputPath)) { _fileSystem.GetDirectory(outputPath).Create(); } using (var stream = _fileSystem.GetFile(outputFilePath).OpenWrite()) using (var writer = new StreamWriter(stream)) { writer.Write(html); } // Process child pages recursivly. foreach (var child in current.Children) { count += BuildPage(configuration, root, current, child); } return(count); }
private void ReplaceFilesInAdapter(IArchiveAdapter parentAdapter, IFileSystem physicalFS, string root) { // Loop through all directories foreach (var dir in physicalFS.EnumerateDirectories(true)) { ReplaceFilesInAdapter(parentAdapter, physicalFS.GetDirectory(dir), root); } // Update files of this directory foreach (var file in physicalFS.EnumerateFiles()) { var openedFile = physicalFS.OpenFile(file.Remove(0, root.Length + 1)); var afi = parentAdapter.Files.FirstOrDefault(x => UnifyPathDelimiters(x.FileName) == UnifyPathDelimiters(file.Remove(0, root.Length + 1))); if (afi != null) { afi.FileData.Dispose(); afi.FileData = openedFile; afi.State = ArchiveFileState.Replaced; } } }
public FilePath Resolve(MavenPackage package) { var groupId = package.GroupId; var artifactId = package.ArtifactId; var version = package.Version ?? GetLatestVersion(groupId, artifactId); var path = $"{groupId.Replace('.', '/')}/{artifactId}/{version}/{artifactId}-{version}.jar"; var localJarFile = fileSystem.GetFile(localRepository.CombineWithFilePath(path)); if (!localJarFile.Exists) { fileSystem.GetDirectory(localJarFile.Path.GetDirectory()).Create(); using (var source = remoteRepository.OpenRead(path)) using (var target = localJarFile.Open(FileMode.CreateNew)) { source.CopyTo(target); } } return(localJarFile.Path); }
public void Scan(Folder folder) { if (folder == null) { throw new ArgumentNullException("folder"); } var dir = _fileSystem.GetDirectory(folder.Path); if (!dir.Exists) { return; } var filter = _keyValueStore.Get <string>("autoadd.filter"); var files = dir.GetFiles(filter, folder.RecursiveSearch ? SearchScope.Recursive : SearchScope.Current); foreach (var file in files) { var fileName = file.Path.GetFilename().FullPath; if (!string.IsNullOrEmpty(folder.Pattern) && !Regex.IsMatch(fileName, folder.Pattern)) { continue; } if (_autoAddRepository.GetHistoryByPath(file.Path.FullPath) != null) { continue; } AddFile(file); if (folder.RemoveSourceFile) { file.Delete(); } } }
public void Execute(NewCommandInput input, TemplatePlan plan, Action <TemplatePlanContext> continuation) { var context = new TemplatePlanContext { Input = input, TempDir = createTempDir() }; _fileSystem.CreateDirectory(context.TempDir); var targetPath = input.ProjectName; if (input.OutputFlag.IsNotEmpty()) { targetPath = input.OutputFlag; } else if (input.SolutionFlag.IsNotEmpty()) { targetPath = _fileSystem.GetDirectory(input.SolutionFlag); } context.TargetPath = Path.Combine(Environment.CurrentDirectory, targetPath); plan.Preview(context); try { plan .Steps .Each(step => step.Execute(context)); } catch (Exception exc) { context.RegisterError(exc.Message); context.RegisterError(exc.StackTrace); } continuation(context); _fileSystem.DeleteDirectory(context.TempDir); }
private VirtualDirectory GetBuildSystemDirectory(Entity owner, bool validateExist = true) { TargetEntity targetEntity = TargetEntity.Decorate(owner); if (!targetEntity.HasFullName) { return(validateExist ? (VirtualDirectory)null : throw new InvalidOperationException("Need to use a target entity as base.")); } string binaryDirectory = Path.Combine(owner.Root.Path, Constants.IntermediateFolderName, Constants.CmakeFolderName, targetEntity.FullName, GetBuildType(owner)); if (!fileSystem.DirectoryExists(binaryDirectory) && validateExist) { return(null); } return(fileSystem.GetDirectory(binaryDirectory)); }
private static DirectoryPath GetMonoPathWindows() { DirectoryPath programFiles; if (_environment.Is64BitOperativeSystem()) { programFiles = new DirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)); } else { programFiles = new DirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)); } var monoPath = programFiles.Combine("Mono").Combine("bin"); if (_fileSystem.GetDirectory(monoPath).Exists) { return(monoPath); } return(null); }
public void Compile(ProtoCompileSettings settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } if (settings.ProtoInputFile == null || !_fileSystem.Exist(settings.ProtoInputFile)) { throw new CakeException("ProtoInputFile not found"); } if (settings.CSharpOutputPath != null) { var dir = _fileSystem.GetDirectory(settings.CSharpOutputPath); if (!dir.Exists) { dir.Create(); } } Run(settings, GetArguments(settings)); }
public void CreatePackagesForAllNuSpecOutputToArtifactsFolder(string fullVersion) { var files = _globber.GetFiles("./**/*.nuspec").ToList(); if (files.Count == 0) { throw new Exception("No .nuspec files found to create packages from"); } var nuGetToolResolver = new NuGetToolResolver(_fileSystem, _environment, _tools); var packer = new NuGetPacker(_fileSystem, _environment, _processRunner, _log, _tools, nuGetToolResolver); var output = new DirectoryPath("./Artifacts"); var directory = _fileSystem.GetDirectory(output); if (!directory.Exists) { directory.Create(); } var nuGetPackSettings = new NuGetPackSettings { Version = fullVersion, OutputDirectory = output.FullPath, IncludeReferencedProjects = true, Properties = new Dictionary <string, string> { { "Configuration", Configuration } }, }; foreach (var nuspec in files) { _log.Information(nuspec.FullPath); var csproj = nuspec.ChangeExtension(".csproj"); _log.Information(csproj.FullPath); packer.Pack(csproj.FullPath, nuGetPackSettings); } }
private IFileInfo FindProjectFile(string initialProjectPath) { if (initialProjectPath == null) { return(_fileSystem.CurrentDirectory.SingleOrDefault(f => Path.GetExtension(f.Name).EndsWith("proj"))); } var projectDir = _fileSystem.GetDirectory(initialProjectPath); if (projectDir.Exists) { return(projectDir.SingleOrDefault(f => Path.GetExtension(f.Name).EndsWith("proj"))); } var projectFile = _fileSystem.GetFile(initialProjectPath); if (projectFile.Exists) { return(projectFile); } return(null); }
/// <summary> /// Returns the path of the latest SmartAssembly.com version. /// </summary> /// <param name="fileSystem"></param> /// <param name="environment"></param> /// <returns>The path of the latest SmartAssembly.com version</returns> /// <remarks>Throws if SmartAssembly isn't found.</remarks> public static FilePath GetSmartAssemblyPath(IFileSystem fileSystem, ICakeEnvironment environment) { if (fileSystem == null) { throw new ArgumentNullException("fileSystem"); } if (environment == null) { throw new ArgumentNullException("environment"); } var programFiles = new DirectoryPath(Environment.GetEnvironmentVariable("ProgramFiles")).Combine("Red Gate"); Console.WriteLine($"program files: {programFiles}"); var query = from p in fileSystem.GetDirectory(programFiles).GetDirectories("SmartAssembly*", SearchScope.Current) where fileSystem.Exist(p.Path.CombineWithFilePath("SmartAssembly.com")) let name = p.Path.GetDirectoryName() let vt = name.Split(' ')[1] let version = int.Parse(vt) orderby version descending select p; return(query.FirstOrDefault()?.Path.CombineWithFilePath("SmartAssembly.com")); }
public void Generate(CompilerConfiguration configuration, Content parent) { var pagesPath = configuration.Root.Combine("pages").MakeAbsolute(_environment); var pagesDirectory = _fileSystem.GetDirectory(pagesPath); if (!pagesDirectory.Exists) { _log.Warning("No pages directory found."); return; } // Get all files. var pages = new List <StaticPage>(); var files = pagesDirectory.GetFiles("*.md", SearchScope.Current) .Concat(pagesDirectory.GetFiles("*.html", SearchScope.Current)); foreach (var file in files) { var page = StaticPageParser.Parse(file); pages.Add(page); } // Create content from all files. foreach (var page in pages.OrderBy(x => x.SortOrder)) { var pageContent = page.Content; if (page.ContentType == "markdown") { // Process markdown. var md = new MarkdownDeep.Markdown(); pageContent = md.Transform(pageContent); } var content = new Content(page.Id, page.Id, page.Title, null, pageContent); parent.AddChild(content); } }
public SdkInformation Get(string sdkRootPath) { sdkRootPath = sdkRootPath.CleanPath(); return(ParseSdk()); SdkInformation ParseSdk() { SdkSchema definition = SdkProperties.SDK?.FirstOrDefault(s => s.path == sdkRootPath); if (definition == null) { throw new InvalidOperationException($"This should not happen. Expected properties for SDK {sdkRootPath}, but found none."); } IEnumerable <Target> targets = definition.Target?.Select(t => new Target(t.name, t.version)) ?? Enumerable.Empty <Target>(); if (!fileSystem.DirectoryExists(definition.path)) { throw new SdkPathNotExistingException(definition.path); } return(new SdkInformation(targets, definition.IncludePath ?? Enumerable.Empty <string>(), fileSystem.GetDirectory(definition.path), string.IsNullOrEmpty(definition.makepath) ? null : fileSystem.GetFile(definition.makepath), new CompilerInformation(definition.CompilerSpec.compilerPath, definition.CompilerSpec.compilerSysroot, definition.CompilerSpec.compilerFlags, definition.CompilerSpec.IncludePath ?? Enumerable.Empty <string>(), definition.CompilerSpec.CompilerMacro? .Select(m => new CompilerMakro(m.name, m.value)) ?? Enumerable.Empty <CompilerMakro>()))); } }
public void Export_PlaylistRead_AllFilesProcessed() { const int PlaylistTracks = 5; _fileSystem.FileExists(Arg.Any <string>()).Returns(true); _fileSystem.DirectoryExists(Arg.Is <string>("someOutputDir")).Returns(true); _fileSystem.GetRelativePath(Arg.Is <string>($"{OSDirSep}someParent{OSDirSep}someFile"), Arg.Is <string>($"{OSDirSep}someParent")).Returns("someFile"); _fileSystem.GetRelativePath(Arg.Is <string>($"{OSDirSep}someParent"), Arg.Is <string>($"{OSDirSep}someParent")).Returns(""); _fileSystem.GetDirectory(Arg.Is <string>($"{OSDirSep}someParent{OSDirSep}someFile")).Returns($"{OSDirSep}someParent"); _fileSystem.GetShortName(Arg.Is <string>($"{OSDirSep}someParent{OSDirSep}someFile")).Returns("someFile"); _playlistReader.ReadAll(Arg.Any <Stream>(), Arg.Any <string>(), Arg.Any <string>()) .Returns(GetTestPlaylist(PlaylistTracks)); IPlaylistExporter sut = new PlaylistExporter(_fileSystem, _playlistReader, _playlistWriter); sut.Export($"{OSDirSep}someParent{OSDirSep}someFile", "someOutputDir", $"{OSDirSep}someParent", ExportMode.PlaylistContents); _fileSystem.Received(PlaylistTracks).FileCopy(Arg.Is <string>($"{OSDirSep}someParent{OSDirSep}someFile"), Arg.Is <string>($"someOutputDir{OSDirSep}someFile"), Arg.Any <bool>()); }
public ICollection <Type> FindModuleTypes(DirectoryPath root, ICakeConfiguration configuration) { var modulePath = _fileSystem.GetDirectory(configuration.GetModulePath(root, _environment)); if (!modulePath.Exists) { _log.Debug("Module directory does not exist."); return(Array.Empty <Type>()); } var result = new List <Type>(); var files = modulePath.GetFiles("Cake.*.Module.dll", SearchScope.Recursive); foreach (var file in files) { var module = LoadModule(file.Path, configuration); if (module != null) { result.Add(module); } } return(result); }
private void Install(DirectoryPath root) { if (root == null) { throw new ArgumentNullException("root"); } var installRoot = root.Combine(Guid.NewGuid().ToString().Replace("-", string.Empty)); // Install package. var nugetSource = _configuration.GetValue(Constants.Roslyn.NuGetSource) ?? "https://packages.nuget.org/api/v2"; var repository = PackageRepositoryFactory.Default.CreateRepository(nugetSource); var packageManager = new PackageManager(repository, installRoot.FullPath); _log.Verbose("Installing packages (using {0})...", nugetSource); packageManager.InstallPackage("Roslyn.Compilers.CSharp", new SemanticVersion(new Version(1, 2, 20906, 2)), false, true); // Copy files _log.Verbose("Copying files..."); foreach (var path in _paths) { var source = _fileSystem.GetFile(installRoot.CombineWithFilePath(path)); var destination = _fileSystem.GetFile(root.CombineWithFilePath(path.GetFilename())); _log.Information("Copying {0}...", source.Path.GetFilename()); if (!destination.Exists) { source.Copy(destination.Path, true); } } // Delete the install directory. _log.Verbose("Deleting installation directory..."); _fileSystem.GetDirectory(installRoot).Delete(true); }
/// <summary> /// Resolves the path to nuget.exe. /// </summary> /// <returns>The path to nuget.exe.</returns> public FilePath ResolvePath() { // Check if path allready resolved if (_cachedPath != null && _cachedPath.Exists) { return(_cachedPath.Path); } // Check if tool exists in tool folder const string expression = "./tools/**/NuGet.exe"; var toolsExe = _globber.GetFiles(expression).FirstOrDefault(); if (toolsExe != null) { var toolsFile = _fileSystem.GetFile(toolsExe); if (toolsFile.Exists) { _cachedPath = toolsFile; return(_cachedPath.Path); } } // Check if path set to environment variable var environmentExe = _environment.GetEnvironmentVariable("NUGET_EXE"); if (!string.IsNullOrWhiteSpace(environmentExe)) { var envFile = _fileSystem.GetFile(environmentExe); if (envFile.Exists) { _cachedPath = envFile; return(_cachedPath.Path); } } // On Unix /usr/bin/nuget is a viable option if (_environment.IsUnix()) { var nugetUnixPath = new FilePath("/usr/bin/nuget"); if (_fileSystem.Exist(nugetUnixPath)) { _cachedPath = _fileSystem.GetFile(nugetUnixPath); return(_cachedPath.Path); } } // Last resort try path var envPath = _environment.GetEnvironmentVariable("path"); if (!string.IsNullOrWhiteSpace(envPath)) { var pathFile = envPath .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) .Select(path => _fileSystem.GetDirectory(path)) .Where(path => path.Exists) .Select(path => path.Path.CombineWithFilePath("nuget.exe")) .Select(_fileSystem.GetFile) .FirstOrDefault(file => file.Exists); if (pathFile != null) { _cachedPath = pathFile; return(_cachedPath.Path); } } throw new CakeException("Could not locate nuget.exe."); }
public (bool, VirtualDirectory) EnsureConfigured(BuildInformation buildInformation, bool showWarningsToUser, ChangeObservable observable = null, bool throwOnError = false, bool showMessagesToUser = true) { if (!CmakeFileExists()) { GenerateCmakeFile(); } VirtualDirectory cmakeFolder = CreateCmakeFolder(); bool success = ConfigureCMake(); return(success, cmakeFolder); void GenerateCmakeFile() { VirtualFile cMakeFile = buildInformation.RootFileEntity.Directory.File(Constants.CMakeFileName); //TODO Generate cmakefile with template system //TODO Set src folders in cmake file (consider foreign project structure) CMakeFileGenerator.WriteCMakeFile(cMakeFile, buildInformation.RootEntity.Name); observable?.OnNext(new Change(() => { /*Do not delete, because user need to make changes perhaps*/ }, $"Generated cmake file {cMakeFile.FullName}")); } bool CmakeFileExists() { return(buildInformation.RootFileEntity.Directory.FileExists(Constants.CMakeFileName)); } VirtualDirectory CreateCmakeFolder() { VirtualDirectory result = buildInformation.BuildEntity.BuildSystemDirectory; if (buildInformation.Configure && !buildInformation.NoConfigure) { result.Clear(); observable?.OnNext(new Change(() => result.UnClear(), $"Cleared cmake directory.")); } return(result); } string GetRealBuildType() { string buildType = !string.IsNullOrEmpty(buildInformation.BuildType) ? buildInformation.BuildType : Constants.ReleaseFolderName; return(buildType); } bool ConfigureCMake() { executionContext.WriteInformation("Checking if CMake needs to be reconfigured...", showMessagesToUser); if ((!cmakeFolder.FileExists("CMakeCache.txt") || buildInformation.Configure || !IsCorrectlyConfigured() || OutputOptionDiffersFromStagingPrefix()) && !buildInformation.NoConfigure) { string cmakeCommand = GenerateCmakeCommand(buildInformation.Target.Name, buildInformation.Target.LongVersion); if (showMessagesToUser) { executionContext.WriteInformation("Configuring CMake..."); } return(CallCmake(cmakeFolder, cmakeCommand, showMessagesToUser, throwOnError, showWarningsToUser)); } if (!string.IsNullOrEmpty(buildInformation.BuildProperties)) { executionContext.WriteWarning($"The specified build options will not be used, " + $"because no reconfiguration is necessary. " + $"To force a reconfiguration please use the '--configure' command option.", showMessagesToUser); } return(true); string GenerateCmakeCommand(string target, string version) { List <string> commandParts = new List <string>(); string sdkRoot = buildInformation.SdkInformation.Root.FullName.Replace("\\", "/"); if (!buildInformation.BuildProperties.Contains("-DCMAKE_TOOLCHAIN_FILE ")) { commandParts.Add(ToolchainFileOption.Replace("%SDK_ROOT%", sdkRoot)); } if (!buildInformation.BuildProperties.Contains("-DARP_TOOLCHAIN_ROOT ")) { commandParts.Add(ToolchainRootOption.Replace("%SDK_ROOT%", sdkRoot)); } if (!buildInformation.BuildProperties.Contains("-DCMAKE_BUILD_TYPE ")) { commandParts.Add(BuildTypeOption.Replace("%BUILD_TYPE%", GetRealBuildType())); } if (!buildInformation.BuildProperties.Contains("-DARP_DEVICE ")) { commandParts.Add(DeviceOption.Replace("%TARGET%", $"\"{target}\"")); } if (!buildInformation.BuildProperties.Contains("-DARP_DEVICE_VERSION ")) { commandParts.Add(DeviceVersionOption.Replace("%VERSION%", $"\"{version}\"")); } if (!buildInformation.BuildProperties.Contains("-DCMAKE_STAGING_PREFIX ")) { commandParts.Add(StagingPrefixOption.Replace("%STAGING_PREFIX%", GenerateStagingPrefixForTarget())); } if (!buildInformation.BuildProperties.Contains("-DCMAKE_PREFIX_PATH ") && IsIncludePathAvailable(out string includePath)) { commandParts.Add(PrefixPathOption.Replace("%PREFIX_PATH%", includePath)); } if (!buildInformation.BuildProperties.Contains("-G ")) { commandParts.Add(GeneratorOption); if (buildInformation.SdkInformation.MakeFile != null && !buildInformation.BuildProperties.Contains("-DCMAKE_MAKE_PROGRAM ")) { commandParts.Add(MakeFileOption.Replace("%MAKE_EXE%", $"\"{buildInformation.SdkInformation.MakeFile.FullName.Replace("\\", "/")}\"")); } } if (!string.IsNullOrEmpty(buildInformation.BuildProperties)) { commandParts.Add(buildInformation.BuildProperties); } commandParts.Add($"\"{buildInformation.RootFileEntity.Directory.FullName.Replace("\\", "/")}\""); return(string.Join(" ", commandParts)); string GenerateStagingPrefixForTarget() { string basePath = buildInformation.RootFileEntity.Directory.FullName; return(buildInformation.Output != null ? OutputOptionFullPath() : Path.Combine(basePath, Constants.LibraryFolderName) .Replace(Path.DirectorySeparatorChar, '/')); } bool IsIncludePathAvailable(out string path) { path = null; if (!buildInformation.RootFileEntity.Directory.DirectoryExists("external")) { return(false); } Dictionary <Version, VirtualDirectory> versions = new Dictionary <Version, VirtualDirectory>(); VirtualDirectory externalDirectory = buildInformation.RootFileEntity.Directory.Directory("external"); foreach (VirtualDirectory directory in externalDirectory.Directories) { Match patternMatch = IncludeDirectoryPattern.Match(directory.Name); if (!patternMatch.Success || !Version.TryParse(patternMatch.Groups["version"].Value, out Version includeVersion) || target != patternMatch.Groups["name"].Value) { continue; } versions.Add(includeVersion, directory); } Version actualVersion = Version.Parse(buildInformation.Target.Version); Version bestMatch = versions.Keys.Where(v => v <= actualVersion) .OrderByDescending(v => v) .FirstOrDefault(); if (bestMatch != null) { VirtualDirectory directory = versions[bestMatch]; if (directory.DirectoryExists(buildInformation.BuildType)) { path = directory.Directory(buildInformation.BuildType).FullName; } else if (directory.DirectoryExists(Constants.ReleaseFolderName)) { path = directory.Directory(Constants.ReleaseFolderName).FullName; } else { path = directory.FullName; } } else { path = externalDirectory.FullName; } return(true); } } string OutputOptionFullPath() { return(fileSystem.GetDirectory(buildInformation.Output, buildInformation.RootFileEntity.Directory.FullName) .FullName.Replace(Path.DirectorySeparatorChar, '/')); } bool OutputOptionDiffersFromStagingPrefix() { return(buildInformation.Output != null && !buildInformation.BuildEntity.BuildSystem.InstallationPaths.Any(p => p.StartsWith(OutputOptionFullPath(), StringComparison.Ordinal))); } bool IsCorrectlyConfigured() { try { return(buildInformation.BuildEntity.HasBuildSystem && buildInformation.BuildEntity.BuildSystem != null); } catch (Exception e) { if (!IsTimeout(e)) { executionContext.WriteVerbose($"The project is not correctly configured:{Environment.NewLine}{e}"); return(false); } } return(true); //this is a timeout so we dont know if it is correctly configured bool IsTimeout(Exception exception) { return(exception is TimeoutException || exception is AggregateException aggregate && aggregate.InnerExceptions.Any(e => e is TimeoutException)); } } } }
private List <Path> Walk(DirectoryPath rootPath, Stack <Node> segments) { var results = new List <Path>(); var segment = segments.Pop(); var expression = new Regex("^" + segment.Render() + "$", _options); var isDirectoryWildcard = false; if (segment is WildcardSegmentNode) { segments.Push(segment); isDirectoryWildcard = true; } // Get all files and folders. var root = _fileSystem.GetDirectory(rootPath); if (!root.Exists) { return(results); } foreach (var directory in root.GetDirectories("*", SearchScope.Current)) { var part = directory.Path.FullPath.Substring(root.Path.FullPath.Length + 1); var pathTest = expression.IsMatch(part); var subWalkCount = 0; if (isDirectoryWildcard) { // Walk recursivly down the segment. var nextSegments = new Stack <Node>(segments.Reverse()); var subwalkResult = Walk(directory.Path, nextSegments); if (subwalkResult.Count > 0) { results.AddRange(subwalkResult); } subWalkCount++; } // Check without directory wildcard. if (segments.Count > subWalkCount && (subWalkCount == 1 || pathTest)) { // Walk the next segment in the list. var nextSegments = new Stack <Node>(segments.Skip(subWalkCount).Reverse()); var subwalkResult = Walk(directory.Path, nextSegments); if (subwalkResult.Count > 0) { results.AddRange(subwalkResult); } } // Got a match? if (pathTest && segments.Count == 0) { results.Add(directory.Path); } } foreach (var file in root.GetFiles("*", SearchScope.Current)) { var part = file.Path.FullPath.Substring(root.Path.FullPath.Length + 1); var pathTest = expression.IsMatch(part); // Got a match? if (pathTest && segments.Count == 0) { results.Add(file.Path); } else if (pathTest) { /////////////////////////////////////////////////////////////B // We got a match, but we still have segments left. // Is the next part a directory wild card? ///////////////////////////////////////////////////////////// var nextNode = segments.Peek(); if (nextNode is WildcardSegmentNode) { var nextSegments = new Stack <Node>(segments.Skip(1).Reverse()); var subwalkResult = Walk(root.Path, nextSegments); if (subwalkResult.Count > 0) { results.AddRange(subwalkResult); } } } } return(results); }
private async IAsyncEnumerable <IContentSource> BuildSources( [EnumeratorCancellation] CancellationToken cancellationToken) { using var _ = _logger.BeginScope(nameof(BuildSources)); var branches = _site.Branches; foreach (var(branch, definition) in branches) { using (_logger.BeginScope($"Source({branch}):")) { _logger.LogInformation($"Definition: {JsonSerializer.Serialize(definition)}"); var commonInputPaths = definition.InputPath; foreach (var commonInputPath in commonInputPaths) { using var __ = _logger.BeginScope("InputPath({inputPath})", commonInputPath); if (branch == "HEAD") { var status = _git.Repo.RetrieveStatus(); // If we have changes then we actually use the current folder // as the source of the truth //if (status.IsDirty) //{ _logger.LogInformation( "Special branch HEAD is dirty and will fallback to using working copy"); var inputDirectory = await _workFileSystem.GetDirectory(commonInputPath); if (inputDirectory != null) { yield return(new FileSystemContentSource( _workFileSystem, "HEAD", inputDirectory.Path)); // we're mounting the input path } /*} * else * { * _logger.LogInformation("Using HEAD"); * var head = _git.Head(); * if (await head.GetDirectory(commonInputPath) != null) * yield return new GitBranchContentSource(head, commonInputPath); * }*/ } else { // use globbing to find matching branches _logger.LogInformation("Finding matching branches: {glob}", branch); var glob = Glob.Parse(branch); foreach (var repoBranch in _git.Repo.Branches) { if (glob.IsMatch(repoBranch.FriendlyName) || glob.IsMatch(repoBranch.CanonicalName)) { var matchingBranch = _git.Branch(repoBranch.CanonicalName); _logger.LogInformation("Using branch: {branch}", matchingBranch.FriendlyName); if (await matchingBranch.GetDirectory(commonInputPath) != null) { yield return(new GitBranchContentSource( matchingBranch, commonInputPath)); } } } } } } } var tags = _site.Tags; foreach (var(tag, definition) in tags) { using (_logger.BeginScope($"Source({tag}):")) { _logger.LogInformation($"Definition: {JsonSerializer.Serialize(definition)}"); var inputPaths = definition.InputPath; foreach (var inputPath in inputPaths) { // use globbing to find matching branches _logger.LogInformation("Finding matching tags: {glob}", tag); var glob = Glob.Parse(tag); foreach (var repoTag in _git.Repo.Tags) { if (glob.IsMatch(repoTag.FriendlyName) || glob.IsMatch(repoTag.CanonicalName)) { var matchingCommit = _git.Tag(repoTag); _logger.LogInformation("Using tag: {branch}", repoTag.FriendlyName); if (await matchingCommit.GetDirectory(inputPath) != null) { yield return(new GitCommitContentSource( matchingCommit, repoTag.FriendlyName, inputPath)); } } } } } } }
protected override void OnInit(EventArgs e) { FS = Engine.Resolve<IFileSystem>(); Config = Engine.Resolve<ConfigurationManagerWrapper>().Sections.Management; Register.JQueryUi(Page); var selected = Selection.SelectedItem; if (IsPostBack && !string.IsNullOrEmpty(inputFile.PostedFile.FileName)) { string uploadFolder = Request["inputLocation"]; if(!IsAvailable(uploadFolder)) throw new N2Exception("Cannot upload to " + Server.HtmlEncode(uploadFolder)); string fileName = System.IO.Path.GetFileName(inputFile.PostedFile.FileName); string filePath = Url.Combine(uploadFolder, fileName); FS.WriteFile(filePath, inputFile.PostedFile.InputStream); ClientScript.RegisterStartupScript(typeof(Tree), "select", "updateOpenerWithUrlAndClose('" + ResolveUrl(filePath) + "');", true); } else if (Request["location"] == "files" || Request["location"] == "filesselection") { IHost host = Engine.Resolve<IHost>(); HierarchyNode<ContentItem> root = new HierarchyNode<ContentItem>(Engine.Persister.Get(host.DefaultSite.RootItemID)); var selectionTrail = new List<ContentItem>(); if (selected is AbstractNode) { selectionTrail = new List<ContentItem>(Find.EnumerateParents(selected, null, true)); } else { TrySelectingPrevious(ref selected, ref selectionTrail); } foreach (string uploadFolder in Engine.EditManager.UploadFolders) { var dd = FS.GetDirectory(uploadFolder); var dir = Directory.New(dd, root.Current, FS, Engine.Resolve<ImageSizeCache>()); var node = CreateDirectoryNode(FS, dir, root, selectionTrail); root.Children.Add(node); } AddSiteFilesNodes(root, host.DefaultSite, selectionTrail); foreach (var site in host.Sites) { if (site.StartPageID == host.DefaultSite.StartPageID) continue; AddSiteFilesNodes(root, site, selectionTrail); } siteTreeView.Nodes = root; siteTreeView.SelectedItem = selected; } else { var filter = Engine.EditManager.GetEditorFilter(Page.User); siteTreeView.Filter = filter; siteTreeView.RootNode = Engine.Resolve<Navigator>().Navigate(Request["root"] ?? "/"); siteTreeView.SelectedItem = selected; } siteTreeView.SelectableTypes = Request["selectableTypes"]; siteTreeView.SelectableExtensions = Request["selectableExtensions"]; siteTreeView.DataBind(); base.OnInit(e); }
/// <inheritdoc /> public string GetDirectory(string path) { return(_fileSystem.GetDirectory(path)); }
public void Zip(DirectoryPath rootPath, FilePath outputPath, IEnumerable <Path> paths) { if (rootPath == null) { throw new ArgumentNullException(nameof(rootPath)); } if (outputPath == null) { throw new ArgumentNullException(nameof(outputPath)); } if (paths == null) { throw new ArgumentNullException(nameof(paths)); } // Make root path and output file path absolute. rootPath = rootPath.MakeAbsolute(_environment); outputPath = outputPath.MakeAbsolute(_environment); // Get the output file. var outputFile = _fileSystem.GetFile(outputPath); // Open up a stream to the output file. _log.Verbose("Creating zip file: {0}", outputPath.FullPath); using (var outputStream = outputFile.Open(FileMode.Create, FileAccess.Write, FileShare.None)) using (var archive = new ZipArchive(outputStream, ZipArchiveMode.Create)) { var directories = new HashSet <DirectoryPath>((paths as PathCollection)?.Comparer ?? PathComparer.Default); foreach (var path in paths) { var absoluteFilePath = (path as FilePath)?.MakeAbsolute(_environment); var relativeFilePath = GetRelativePath(rootPath, absoluteFilePath); var absoluteDirectoryPath = (path as DirectoryPath)?.MakeAbsolute(_environment) ?? absoluteFilePath?.GetDirectory(); var relativeDirectoryPath = GetRelativePath(rootPath, absoluteDirectoryPath); if (absoluteDirectoryPath != null && !string.IsNullOrEmpty(relativeDirectoryPath) && !directories.Contains(relativeDirectoryPath)) { // Create directory entry. _log.Verbose("Storing directory {0}", absoluteDirectoryPath); var directory = _fileSystem.GetDirectory(absoluteDirectoryPath); var entry = archive.CreateEntry(relativeDirectoryPath + "/"); entry.LastWriteTime = (directory as Directory)?.LastWriteTime ?? DateTimeOffset.Now; directories.Add(relativeDirectoryPath); } if (absoluteFilePath != null && !string.IsNullOrEmpty(relativeFilePath)) { // Create file entry. _log.Verbose("Compressing file {0}", absoluteFilePath); var file = _fileSystem.GetFile(absoluteFilePath); using (var fileStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read)) { var entry = archive.CreateEntry(relativeFilePath); entry.LastWriteTime = (file as File)?.LastWriteTime ?? DateTimeOffset.Now; using (var entryStream = entry.Open()) { fileStream.CopyTo(entryStream); } } } } } _log.Verbose("Zip successfully created: {0}", outputPath.FullPath); }
private void WriteSearch(HttpContext context) { var query = context.Request["query"]; if (string.IsNullOrWhiteSpace(query)) { context.Response.WriteJson(new { Status = "Error", Total = 0, Message = "Please provide a search term." }); return; } query = query.TrimStart().TrimEnd(); var host = Engine.Resolve <IHost>(); var rootItem = Engine.Persister.Get(host.DefaultSite.RootItemID); var root = new HierarchyNode <ContentItem>(rootItem); FS = Engine.Resolve <IFileSystem>(); var selectionTrail = Find.EnumerateParents(Selection.SelectedItem, null, true).ToList().Where(a => a is AbstractNode).Reverse().ToList(); var uploadDirectories = MediaBrowserUtils.GetAvailableUploadFoldersForAllSites(context, root, selectionTrail, Engine, FS); if (uploadDirectories.Count == 0) { context.Response.WriteJson(new { Status = "Error", Total = 0, Message = "No available directories in this site." }); return; } //Do the search using the IFileSystem var resultsFileData = FS.SearchFiles(query, uploadDirectories); if (!resultsFileData.Any()) { context.Response.WriteJson(new { Status = "Error", Total = 0, Message = "0 files found." }); return; } var files = new List <File>(); var fileMap = new Dictionary <string, File>(StringComparer.OrdinalIgnoreCase); var lastParent = string.Empty; AbstractDirectory parent = null; foreach (var fd in resultsFileData.OrderBy(s => s.VirtualPath)) { var parentDirectory = fd.VirtualPath.Substring(0, fd.VirtualPath.LastIndexOf('/')); if (lastParent != parentDirectory) { parent = new Directory(DirectoryData.Virtual(parentDirectory), null); lastParent = parentDirectory; } var file = new File(fd, parent); file.Set(FS); file.Set(ImageSizes); var unresizedFileName = ImageSizes.RemoveImageSize(file.Name); if (unresizedFileName != null && fileMap.ContainsKey(unresizedFileName)) { fileMap[unresizedFileName].Add(file); if (ImageSizes.GetSizeName(file.Name) == "icon") { file.IsIcon = true; } } else { if (unresizedFileName == null) { files.Add(file); fileMap[file.Name] = file; } } } files.Sort(new TitleComparer <File>()); var directory = FS.GetDirectory("/"); var fsRootPath = directory != null && !string.IsNullOrWhiteSpace(directory.RootPath) ? directory.RootPath : ""; var selectableExtensions = context.Request["exts"]; context.Response.WriteJson(new { Path = "", Total = files.Count, Files = GetFileReducedList(files, ImageSizes, selectableExtensions, fsRootPath) }); }
public void Execute(Script script) { var scriptName = _settings.Script.GetFilename(); var cacheDLLFileName = $"{scriptName}.dll"; var cacheHashFileName = $"{scriptName}.hash"; var cachedAssembly = _scriptCachePath.CombineWithFilePath(cacheDLLFileName); var hashFile = _scriptCachePath.CombineWithFilePath(cacheHashFileName); string scriptHash = default; if (_scriptCacheEnabled && _fileSystem.Exist(cachedAssembly) && !_regenerateCache) { _log.Verbose($"Cache enabled: Checking cache build script ({cacheDLLFileName})"); scriptHash = FastHash.GenerateHash(Encoding.UTF8.GetBytes(string.Concat(script.Lines))); var cachedHash = _fileSystem.Exist(hashFile) ? _fileSystem.GetFile(hashFile).ReadLines(Encoding.UTF8).FirstOrDefault() : string.Empty; if (scriptHash.Equals(cachedHash, StringComparison.Ordinal)) { _log.Verbose("Running cached build script..."); RunScriptAssembly(cachedAssembly.FullPath); return; } else { _log.Verbose("Cache check failed."); } } // Generate the script code. var generator = new RoslynCodeGenerator(); var code = generator.Generate(script); // Warn about any code generation excluded namespaces foreach (var @namespace in script.ExcludedNamespaces) { _log.Warning("Namespace {0} excluded by code generation, affected methods:\r\n\t{1}", @namespace.Key, string.Join("\r\n\t", @namespace.Value)); } // Create the script options dynamically. var options = Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default .AddImports(Namespaces.Except(script.ExcludedNamespaces.Keys)) .AddReferences(References) .AddReferences(ReferencePaths.Select(r => r.FullPath)) .WithEmitDebugInformation(_settings.Debug) .WithMetadataResolver(Microsoft.CodeAnalysis.Scripting.ScriptMetadataResolver.Default); var roslynScript = CSharpScript.Create(code, options, _host.GetType()); _log.Verbose("Compiling build script..."); var compilation = roslynScript.GetCompilation(); var diagnostics = compilation.GetDiagnostics(); var errors = new List <Diagnostic>(); foreach (var diagnostic in diagnostics) { // Suppress some diagnostic information. See https://github.com/cake-build/cake/issues/3337 switch (diagnostic.Id) { // CS1701 Compiler Warning (level 2) // Assuming assembly reference "Assembly Name #1" matches "Assembly Name #2", you may need to supply runtime policy // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs1701 case "CS1701": continue; // CS1702 Compiler Warning (level 3) // Assuming assembly reference "Assembly Name #1" matches "Assembly Name #2", you may need to supply runtime policy // https://docs.microsoft.com/en-us/dotnet/csharp/misc/cs1702 case "CS1702": continue; // CS1705 Compiler Error // Assembly 'AssemblyName1' uses 'TypeName' which has a higher version than referenced assembly 'AssemblyName2' case "CS1705": continue; default: break; } switch (diagnostic.Severity) { case DiagnosticSeverity.Info: _log.Information(diagnostic.ToString()); break; case DiagnosticSeverity.Warning: _log.Warning(diagnostic.ToString()); break; case DiagnosticSeverity.Error: _log.Error(diagnostic.ToString()); errors.Add(diagnostic); break; default: break; } } if (errors.Any()) { var errorMessages = string.Join(Environment.NewLine, errors.Select(x => x.ToString())); var message = string.Format(CultureInfo.InvariantCulture, "Error(s) occurred when compiling build script:{0}{1}", Environment.NewLine, errorMessages); throw new CakeException(message); } if (_scriptCacheEnabled) { // Verify cache directory exists if (!_fileSystem.GetDirectory(_scriptCachePath).Exists) { _fileSystem.GetDirectory(_scriptCachePath).Create(); } if (string.IsNullOrWhiteSpace(scriptHash)) { scriptHash = FastHash.GenerateHash(Encoding.UTF8.GetBytes(string.Concat(script.Lines))); } var emitResult = compilation.Emit(cachedAssembly.FullPath); if (emitResult.Success) { using (var stream = _fileSystem.GetFile(hashFile).OpenWrite()) using (var writer = new StreamWriter(stream, Encoding.UTF8)) { writer.Write(scriptHash); } RunScriptAssembly(cachedAssembly.FullPath); } } else { roslynScript.RunAsync(_host).GetAwaiter().GetResult(); } }
public override Entity Resolve(Entity owner, string key, bool fallback = false) { switch (key) { case EntityKeys.ProjectConfigurationsKey: return(GetProjectConfiguration()); case EntityKeys.EngineerVersionKey: return(GetEngineerVersion()); case EntityKeys.SolutionVersionKey: return(GetSolutionVersion()); case EntityKeys.LibraryDescriptionKey: return(GetLibraryDescription()); case EntityKeys.LibraryVersionKey: return(GetLibraryVersion()); default: throw new ContentProviderException(key, owner); } Entity GetProjectConfiguration() { if (!owner.HasPath) { executionContext.WriteVerbose("The executed command lacks the path argument, no project configuration can be loaded."); return(owner.Create(key, new ProjectConfigurations())); } string rootFilePath = fileSystem.GetDirectory(owner.Path, createNew: false) .FullName; string projectDirectory = fileSystem.FileExists(rootFilePath) ? Path.GetDirectoryName(rootFilePath) : rootFilePath; VirtualFile file = fileSystem.DirectoryExists(projectDirectory) && fileSystem.FileExists(Path.Combine(projectDirectory, Constants.ConfigFileName)) ? fileSystem.GetFile(Path.Combine(projectDirectory, Constants.ConfigFileName)) : null; if (file == null) { executionContext.WriteVerbose($"No config file found in {projectDirectory}."); return(owner.Create(key, new ProjectConfigurations())); } try { using (Stream fileStream = file.OpenRead()) using (XmlReader reader = XmlReader.Create(fileStream)) { XmlSerializer serializer = new XmlSerializer(typeof(ProjectConfiguration)); ProjectConfiguration configuration = (ProjectConfiguration)serializer.Deserialize(reader); if (configuration != null) { return(owner.Create(key, new ProjectConfigurations(configuration, file))); } } } catch (DeployArgumentsException) { throw; } catch (Exception e) { executionContext.WriteVerbose($"Error while trying to parse project configuration {file.FullName}." + $"{Environment.NewLine}{e}"); } return(owner.Create(key, new ProjectConfigurations())); } Entity GetEngineerVersion() { CommandEntity command = CommandEntity.Decorate(owner.Origin); ProjectEntity project = ProjectEntity.Decorate(owner); if (command.CommandName.Equals("deploy", StringComparison.OrdinalIgnoreCase) && command.IsCommandArgumentSpecified(Constants.EngineerVersionArgumentKey)) { if (command.IsCommandArgumentSpecified(Constants.SolutionVersionArgumentKey)) { throw new DeployArgumentsException(); } string value = command.GetSingleValueArgument(Constants.EngineerVersionArgumentKey); project.Configuration.EngineerVersion = value; return(owner.Create(key, value)); } return(owner.Create(key, project.Configuration.EngineerVersion)); } Entity GetSolutionVersion() { CommandEntity command = CommandEntity.Decorate(owner.Origin); ProjectEntity project = ProjectEntity.Decorate(owner); if (command.CommandName.Equals("deploy", StringComparison.OrdinalIgnoreCase) && command.IsCommandArgumentSpecified(Constants.SolutionVersionArgumentKey)) { if (command.IsCommandArgumentSpecified(Constants.EngineerVersionArgumentKey)) { throw new DeployArgumentsException(); } string value = command.GetSingleValueArgument(Constants.SolutionVersionArgumentKey); project.Configuration.SolutionVersion = value; return(owner.Create(key, value)); } return(owner.Create(key, project.Configuration.SolutionVersion)); } Entity GetLibraryDescription() { CommandEntity command = CommandEntity.Decorate(owner.Origin); ProjectEntity project = ProjectEntity.Decorate(owner); if (command.CommandName.Equals("deploy", StringComparison.OrdinalIgnoreCase) && command.IsCommandArgumentSpecified(Constants.DescriptionArgumentKey)) { string value = command.GetSingleValueArgument(Constants.DescriptionArgumentKey); project.Configuration.LibraryDescription = value; return(owner.Create(key, value)); } return(owner.Create(key, project.Configuration.LibraryDescription)); } Entity GetLibraryVersion() { CommandEntity command = CommandEntity.Decorate(owner.Origin); ProjectEntity project = ProjectEntity.Decorate(owner); if (command.CommandName.Equals("deploy", StringComparison.OrdinalIgnoreCase) && command.IsCommandArgumentSpecified(Constants.VersionArgumentKey)) { string value = command.GetSingleValueArgument(Constants.VersionArgumentKey); project.Configuration.LibraryVersion = value; return(owner.Create(key, value)); } return(owner.Create(key, project.Configuration.LibraryVersion)); } }
protected override void OnInit(EventArgs e) { FS = Engine.Resolve <IFileSystem>(); Config = Engine.Resolve <ConfigurationManagerWrapper>().Sections.Management; var selected = Selection.SelectedItem; var host = Engine.Resolve <IHost>(); var rootItem = Engine.Persister.Get(host.DefaultSite.RootItemID); var root = new HierarchyNode <ContentItem>(rootItem); var selectionTrail = new List <ContentItem>(); var ckEditor = Request["ckEditor"]; var ckEditorFuncNum = Request["ckEditorFuncNum"]; var mediaCtrl = Request["mediaControl"]; var preferredSize = Request["preferredSize"]; var selectableExtensions = Request["selectableExtensions"]; var selectedUrl = Request["selectedUrl"]; var defaultDirectoryPath = Request["defaultDirectoryPath"]; var mediaBrowserHandler = new MediaBrowserHandler(); mediaBrowserModel = new MediaBrowserModel { CkEditor = ckEditor, CkEditorFuncNum = ckEditorFuncNum, MediaControl = mediaCtrl, HandlerUrl = AjaxMediaBrowserRetriever, PreferredSize = preferredSize, Breadcrumb = new string[] { }, Path = "", RootIsSelectable = false, DefaultDirectoryPath = defaultDirectoryPath }; if (selected is AbstractNode) { selectionTrail = new List <ContentItem>(Find.EnumerateParents(selected, null, true)); } else { mediaBrowserHandler.TrySelectingPrevious(ref selected, ref selectionTrail); } var uploadDirectories = MediaBrowserUtils.GetAvailableUploadFoldersForAllSites(Context, root, selectionTrail, Engine, FS); if (uploadDirectories.Count > 0) { var imageSizes = Engine.Resolve <Management.Files.FileSystem.Pages.ImageSizeCache>(); if (uploadDirectories.Count == 1 || selectionTrail.Count > 1) { var directory = FS.GetDirectory(mediaBrowserModel.Path); var fsRootPath = directory != null && !string.IsNullOrWhiteSpace(directory.RootPath) ? directory.RootPath : ""; var dir = (selectionTrail.Count > 0 ? selectionTrail.ElementAt(0) : uploadDirectories[0].Current) as Directory; //Find and/or create default upload directory for templated content. if (!string.IsNullOrWhiteSpace(mediaBrowserModel.DefaultDirectoryPath)) { var segments = (mediaBrowserModel.DefaultDirectoryPath.Split(new[] { '/' }, 3, StringSplitOptions.RemoveEmptyEntries)); if (segments.Length == 3) { var siteName = segments[0]; var uploadSiteFolder = dir.GetDirectories().FirstOrDefault(d => d.Name == siteName.ToLower()); if (uploadSiteFolder == null) { var newDir = VirtualPathUtility.AppendTrailingSlash(Request.ApplicationPath + dir.LocalUrl) + siteName.ToLower(); FS.CreateDirectory(newDir); uploadSiteFolder = dir.GetDirectories().FirstOrDefault(d => d.Name == siteName.ToLower()); } var contentName = segments[1]; var uploadSiteContentFolder = uploadSiteFolder.GetDirectories().FirstOrDefault(d => d.Name == contentName.ToLower()); if (uploadSiteContentFolder == null) { var newDir = VirtualPathUtility.AppendTrailingSlash(Request.ApplicationPath + uploadSiteFolder.LocalUrl) + contentName.ToLower(); FS.CreateDirectory(newDir); uploadSiteContentFolder = uploadSiteFolder.GetDirectories().FirstOrDefault(d => d.Name == contentName.ToLower()); } var templateName = segments[2]; var uploadSiteContentTemplateFolder = uploadSiteContentFolder.GetDirectories().FirstOrDefault(d => d.Name == templateName.ToLower()); if (uploadSiteContentTemplateFolder == null) { var newDir = VirtualPathUtility.AppendTrailingSlash(Request.ApplicationPath + uploadSiteContentFolder.LocalUrl) + templateName.ToLower(); FS.CreateDirectory(newDir); uploadSiteContentTemplateFolder = uploadSiteContentFolder.GetDirectories().FirstOrDefault(d => d.Name == templateName.ToLower()); dir = uploadSiteContentTemplateFolder; } else { dir = uploadSiteContentTemplateFolder; } } } var files = dir.GetFiles().ToList(); mediaBrowserModel.Dirs = dir.GetDirectories(); mediaBrowserModel.Files = MediaBrowserHandler.GetFileReducedList(files, imageSizes, selectableExtensions, fsRootPath); mediaBrowserModel.Path = System.Web.VirtualPathUtility.ToAppRelative(dir.LocalUrl).Trim('~'); } else { mediaBrowserModel.Path = System.Web.VirtualPathUtility.ToAppRelative("/").Trim('~'); mediaBrowserModel.RootIsSelectable = true; mediaBrowserModel.Dirs = new List <Directory>(); foreach (var updDir in uploadDirectories) { mediaBrowserModel.Dirs.Add(updDir.Current as Directory); } } var breadcrumb = mediaBrowserModel.Path.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries).ToList(); breadcrumb.Insert(0, "[root]"); mediaBrowserModel.Breadcrumb = breadcrumb.ToArray(); } }
public static DirectoryData GetDirectoryOrVirtual(this IFileSystem fs, string virtualDir) { return(fs.GetDirectory(virtualDir) ?? DirectoryData.Virtual(virtualDir)); }
/// <summary> /// Installs the specified resource. /// </summary> /// <param name="package">The package resource.</param> /// <param name="type">The package type.</param> /// <param name="path">The location where to install the resource.</param> /// <returns>The installed files.</returns> public IReadOnlyCollection <IFile> Install(PackageReference package, PackageType type, DirectoryPath path) { if (package == null) { throw new ArgumentNullException(nameof(package)); } // find npm _log.Debug("looking for npm.cmd"); var npmTool = _toolLocator.Resolve("npm.cmd"); if (npmTool == null) { _log.Debug("looking for npm"); npmTool = _toolLocator.Resolve("npm"); } if (npmTool == null) { throw new FileNotFoundException("npm could not be found."); } _log.Debug("Found npm at {0}", npmTool); // Install the package. _log.Debug("Installing package {0} with npm...", package.Package); var workingDir = _environment.WorkingDirectory; if (GetModuleInstallationLocation(package) == ModulesInstallationLocation.Tools) { var toolsFolder = _fileSystem.GetDirectory( _config.GetToolPath(_environment.WorkingDirectory, _environment)); if (!toolsFolder.Exists) { toolsFolder.Create(); } _log.Debug("Installing into cake-tools location: {0}", package.Package); workingDir = toolsFolder.Path; } var process = _processRunner.Start( npmTool.FullPath, new ProcessSettings { Arguments = GetArguments(package, _config), WorkingDirectory = workingDir, RedirectStandardOutput = true, Silent = _log.Verbosity < Verbosity.Diagnostic, }); process.WaitForExit(); var exitCode = process.GetExitCode(); if (exitCode != 0) { _log.Warning("npm exited with {0}", exitCode); var output = string.Join(Environment.NewLine, process.GetStandardOutput()); _log.Verbose(Verbosity.Diagnostic, "Output:\r\n{0}", output); } var result = _contentResolver.GetFiles(package, type, GetModuleInstallationLocation(package)); if (result.Count != 0) { return(result); } _log.Warning("Could not determine installed package files! Installation may not be complete."); // TODO: maybe some warnings here return(result); }
public PostThumbnailService(IFileSystem fileSystem) { _thumbnailDirectory = fileSystem.GetDirectory("post-thumbs"); if (!_thumbnailDirectory.Exists) _thumbnailDirectory.Create(); }