private IReadOnlyList <RestoredCommand> GetCommands() { try { // The mock restorer wrote the path to the executable into project.assets.json (not a real assets file) // Currently only "dotnet" commands are supported var executablePath = _fileSystem.File.ReadAllText(Path.Combine(PackageDirectory.Value, "project.assets.json")); var fakeSettingFile = _fileSystem.File.ReadAllText(Path.Combine(PackageDirectory.Value, ProjectRestorerMock.FakeCommandSettingsFileName)); string name; using (JsonDocument doc = JsonDocument.Parse(fakeSettingFile)) { JsonElement root = doc.RootElement; name = root.GetProperty("Name").GetString(); } return(new RestoredCommand[] { new RestoredCommand( new ToolCommandName(name), "dotnet", PackageDirectory.WithFile(executablePath)) }); } catch (IOException ex) { throw new ToolPackageException( string.Format( CommonLocalizableStrings.FailedToRetrieveToolConfiguration, Id, ex.Message), ex); } }
private ObservableCollection <PackageItem> buildPackageTree(XElement phntCurrentDirectory) { var items = new ObservableCollection <PackageItem>(); // For each directory node foreach (var directory in phntCurrentDirectory.Elements("directory")) { // Create a new PackageDirectory object and assign properties var item = new PackageDirectory { ItemName = directory.Element("name").Value, // Pass the current directory for recursion PackageItems = buildPackageTree(directory) }; // Add PackageItems to collection items.Add(item); } foreach (var file in phntCurrentDirectory.Elements("file")) { var item = new PackageFile { ItemName = file.Element("name").Value, WindowsPath = file.Element("path").Value, }; // Pass the settings node for this file to the setPackageFileSettings function setPackageFileSettings(item, file.Element("settings")); items.Add(item); } return(items); }
public override int GetHashCode() { unchecked { return(((PackageDirectory != null ? PackageDirectory.GetHashCode() : 0) * 397) ^ (DestinationDirectory != null ? DestinationDirectory.GetHashCode() : 0)); } }
public static string Combine(this PackageDirectory packageDirectory, string targetFramework, string targetSubdirectory, string fileName) { switch (packageDirectory) { case PackageDirectory.Root: return(Path.Combine(targetSubdirectory, fileName)); case PackageDirectory.Content: return(Path.Combine(PackagingConstants.Folders.Content, targetSubdirectory, fileName)); case PackageDirectory.ContentFiles: return(Path.Combine(PackagingConstants.Folders.ContentFiles, targetSubdirectory, fileName)); case PackageDirectory.Build: return(Path.Combine(PackagingConstants.Folders.Build, targetSubdirectory, fileName)); case PackageDirectory.Lib: return(Path.Combine(PackagingConstants.Folders.Lib, targetFramework, targetSubdirectory, fileName)); case PackageDirectory.Tools: return(Path.Combine(PackagingConstants.Folders.Tools, targetSubdirectory, fileName)); case PackageDirectory.Analyzers: return(Path.Combine(PackagingConstants.Folders.Analyzers, targetFramework, targetSubdirectory, fileName)); default: return(fileName); } }
private IReadOnlyList <RestoredCommand> GetCommands() { try { // The mock restorer wrote the path to the executable into project.assets.json (not a real assets file) // Currently only "dotnet" commands are supported var executablePath = _fileSystem.File.ReadAllText(Path.Combine(PackageDirectory.Value, "project.assets.json")); return(new RestoredCommand[] { new RestoredCommand( ProjectRestorerMock.FakeCommandName, "dotnet", PackageDirectory.WithFile(executablePath)) }); } catch (IOException ex) { throw new ToolPackageException( string.Format( CommonLocalizableStrings.FailedToRetrieveToolConfiguration, Id, ex.Message), ex); } }
internal void Remove() { try { Logger.Message("Attempting to undo package composition"); UndoPackageComposition(); } catch { // if something goes wrong in removing package composition, keep uninstalling. } try { Logger.Message("Attempting to remove MSI"); PackageHandler.Remove(this); // clean up the package directory if it hangs around. PackageDirectory.TryHardToDelete(); IsInstalled = false; PackageManagerSettings.PerPackageSettings.DeleteSubkey(CanonicalName); } catch (Exception e) { Logger.Error(e); Event <GetResponseInterface> .RaiseFirst().FailedPackageRemoval(CanonicalName, "GS01: During package removal, things went horribly wrong.... "); throw new OperationCompletedBeforeResultException(); } }
private void MoveFile(string commit, FileInfo buildLogFile) { var outputDirectory = new DirectoryInfo(OutputDirectory.FullName); var moveDirectory = Path.Combine(TargetDirectory.FullName, commit); Log($"将{outputDirectory.FullName}移动到{moveDirectory}"); PackageDirectory.Move(outputDirectory, new DirectoryInfo(moveDirectory)); if (File.Exists(buildLogFile.FullName)) { try { // 等待日志写完 Thread.Sleep(3000); Directory.CreateDirectory(moveDirectory); var logFile = Path.Combine(moveDirectory, "BuildLog.txt"); buildLogFile.CopyTo(logFile); File.Delete(buildLogFile.FullName); } catch (Exception) { } } }
private FilePath LockFileRelativePathToFullFilePath(string lockFileRelativePath, LockFileTargetLibrary library) { return(PackageDirectory .WithSubDirectories( Id.ToString(), library.Version.ToNormalizedString()) .WithFile(lockFileRelativePath)); }
private IReadOnlyList <CommandSettings> GetCommands() { const string AssetsFileName = "project.assets.json"; const string ToolSettingsFileName = "DotnetToolSettings.xml"; try { var commands = new List <CommandSettings>(); var lockFile = new LockFileFormat().Read(PackageDirectory.WithFile(AssetsFileName).Value); var library = FindLibraryInLockFile(lockFile); var dotnetToolSettings = FindItemInTargetLibrary(library, ToolSettingsFileName); if (dotnetToolSettings == null) { throw new ToolConfigurationException( CommonLocalizableStrings.MissingToolSettingsFile); } var toolConfigurationPath = PackageDirectory .WithSubDirectories( Id.ToString(), library.Version.ToNormalizedString()) .WithFile(dotnetToolSettings.Path); var configuration = ToolConfigurationDeserializer.Deserialize(toolConfigurationPath.Value); var entryPointFromLockFile = FindItemInTargetLibrary(library, configuration.ToolAssemblyEntryPoint); if (entryPointFromLockFile == null) { throw new ToolConfigurationException( string.Format( CommonLocalizableStrings.MissingToolEntryPointFile, configuration.ToolAssemblyEntryPoint, configuration.CommandName)); } // Currently only "dotnet" commands are supported commands.Add(new CommandSettings( configuration.CommandName, "dotnet", PackageDirectory .WithSubDirectories( Id.ToString(), library.Version.ToNormalizedString()) .WithFile(entryPointFromLockFile.Path))); return(commands); } catch (Exception ex) when(ex is UnauthorizedAccessException || ex is IOException) { throw new ToolConfigurationException( string.Format( CommonLocalizableStrings.FailedToRetrieveToolConfiguration, ex.Message), ex); } }
public MooDir Initialize() { Path.AsDir().Create(); PackageDirectory.AsDir().Create(); CacheDirectory.AsDir().Create(); BinDirectory.AsDir().Create(); SourcesFilePath.AsFile().Initialize(DefaultSourcesListText); return(this); }
public void Uninstall() { var rootDirectory = PackageDirectory.GetParentPath(); string tempPackageDirectory = null; TransactionalAction.Run( action: () => { try { if (Directory.Exists(PackageDirectory.Value)) { // Use the same staging directory for uninstall instead of temp // This prevents cross-device moves when temp is mounted to a different device var tempPath = _store .Root .WithSubDirectories(ToolPackageInstaller.StagingDirectory) .WithFile(Path.GetRandomFileName()) .Value; Directory.Move(PackageDirectory.Value, tempPath); tempPackageDirectory = tempPath; } if (Directory.Exists(rootDirectory.Value) && !Directory.EnumerateFileSystemEntries(rootDirectory.Value).Any()) { Directory.Delete(rootDirectory.Value, false); } } catch (Exception ex) when(ex is UnauthorizedAccessException || ex is IOException) { throw new ToolPackageException( string.Format( CommonLocalizableStrings.FailedToUninstallToolPackage, PackageId, ex.Message), ex); } }, commit: () => { if (tempPackageDirectory != null) { Directory.Delete(tempPackageDirectory, true); } }, rollback: () => { if (tempPackageDirectory != null) { Directory.CreateDirectory(rootDirectory.Value); Directory.Move(tempPackageDirectory, PackageDirectory.Value); } }); }
public void Uninstall() { var rootDirectory = PackageDirectory.GetParentPath(); string tempPackageDirectory = null; TransactionalAction.Run( action: () => { try { if (_fileSystem.Directory.Exists(PackageDirectory.Value)) { var tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); _fileSystem.Directory.Move(PackageDirectory.Value, tempPath); tempPackageDirectory = tempPath; } if (_fileSystem.Directory.Exists(rootDirectory.Value) && !_fileSystem.Directory.EnumerateFileSystemEntries(rootDirectory.Value).Any()) { _fileSystem.Directory.Delete(rootDirectory.Value, false); } if (_uninstallCallback != null) { _uninstallCallback(); } } catch (Exception ex) when(ex is UnauthorizedAccessException || ex is IOException) { throw new ToolPackageException( string.Format( CommonLocalizableStrings.FailedToUninstallToolPackage, Id, ex.Message), ex); } }, commit: () => { if (tempPackageDirectory != null) { _fileSystem.Directory.Delete(tempPackageDirectory, true); } }, rollback: () => { if (tempPackageDirectory != null) { _fileSystem.Directory.CreateDirectory(rootDirectory.Value); _fileSystem.Directory.Move(tempPackageDirectory, PackageDirectory.Value); } }); }
public static PackageDirectory GetPackageDirectory(this ITaskItem taskItem, PackageDirectory defaultValue = PackageDirectory.Root) { var packageDirectoryName = taskItem.GetMetadata(Metadata.PackageDirectory); if (string.IsNullOrEmpty(packageDirectoryName)) { return(defaultValue); } PackageDirectory result; Enum.TryParse(packageDirectoryName, true, out result); return(result); }
private IReadOnlyList <FilePath> GetPackagedShims() { LockFileTargetLibrary library; try { LockFile lockFile = new LockFileFormat().Read(PackageDirectory.WithFile(AssetsFileName).Value); library = FindLibraryInLockFile(lockFile); } catch (Exception ex) when(ex is UnauthorizedAccessException || ex is IOException) { throw new ToolPackageException( string.Format( CommonLocalizableStrings.FailedToReadNuGetLockFile, Id, ex.Message), ex); } IEnumerable <LockFileItem> filesUnderShimsDirectory = library ?.ToolsAssemblies ?.Where(t => LockFileMatcher.MatchesDirectoryPath(t, PackagedShimsDirectoryConvention)); if (filesUnderShimsDirectory == null) { return(Array.Empty <FilePath>()); } IEnumerable <string> allAvailableShimRuntimeIdentifiers = filesUnderShimsDirectory .Select(f => f.Path.Split('\\', '/')?[4]) // ex: "tools/netcoreapp2.1/any/shims/osx-x64/demo" osx-x64 is at [4] .Where(f => !string.IsNullOrEmpty(f)); if (new FrameworkDependencyFile().TryGetMostFitRuntimeIdentifier( DotnetFiles.VersionFileObject.BuildRid, allAvailableShimRuntimeIdentifiers.ToArray(), out var mostFitRuntimeIdentifier)) { return(library ?.ToolsAssemblies ?.Where(l => LockFileMatcher.MatchesDirectoryPath(l, $"{PackagedShimsDirectoryConvention}/{mostFitRuntimeIdentifier}")) .Select(l => LockFileRelativePathToFullFilePath(l.Path, library)).ToArray() ?? Array.Empty <FilePath>()); } else { return(Array.Empty <FilePath>()); } }
private ToolConfiguration GetToolConfiguration() { try { var lockFile = new LockFileFormat().Read(PackageDirectory.WithFile(AssetsFileName).Value); var library = FindLibraryInLockFile(lockFile); return(DeserializeToolConfiguration(ToolSettingsFileName, library)); } catch (Exception ex) when(ex is UnauthorizedAccessException || ex is IOException) { throw new ToolConfigurationException( string.Format( CommonLocalizableStrings.FailedToRetrieveToolConfiguration, ex.Message), ex); } }
private ToolConfiguration DeserializeToolConfiguration(string ToolSettingsFileName, LockFileTargetLibrary library) { var dotnetToolSettings = FindItemInTargetLibrary(library, ToolSettingsFileName); if (dotnetToolSettings == null) { throw new ToolConfigurationException( CommonLocalizableStrings.MissingToolSettingsFile); } var toolConfigurationPath = PackageDirectory .WithSubDirectories( Id.ToString(), library.Version.ToNormalizedString()) .WithFile(dotnetToolSettings.Path); var configuration = ToolConfigurationDeserializer.Deserialize(toolConfigurationPath.Value); return(configuration); }
internal void Compile(ArgumentsFile argumentsFile) { PackageDirectory.Delete(_targetDirectory); PackageDirectory.Create(_targetDirectory); foreach (var file in argumentsFile.Compile) { var fileName = Path.GetFileNameWithoutExtension(file); var text = File.ReadAllText(file); if (text.Contains("GenerateGenericFromThis", StringComparison.Ordinal)) { var generatedCodes = Compile(text, argumentsFile.DefineConstants); foreach (var pair in generatedCodes) { var filePath = Path.Combine( _targetDirectory.FullName, $"{fileName}.{pair.Key}.cs"); File.WriteAllText(filePath, pair.Value); } } } }
internal void Run(Options options) { // 准备编译环境。 var context = new ProjectCompilingContext(options); // 进行重新编译测试。 var shouldRebuild = CheckRebuild(context); if (!shouldRebuild) { new MSBuildMessage($"dotnetCampus.TelescopeTask:项目已最新,无需导出编译信息。").Message(); return; } // 清除前一次生成的文件。 new MSBuildMessage($"dotnetCampus.TelescopeTask:删除前一次的导出结果…").Message(); PackageDirectory.Delete(context.GeneratedCodeFolder); // 收集并生成类。 new MSBuildMessage($"dotnetCampus.TelescopeTask:正在生成新的编译信息…").Message(); var code = GenerateAttributedTypesExportCode(context.Assembly); if (string.IsNullOrWhiteSpace(code)) { return; } // 将生成的类(编译单元)写入到文件中。 new MSBuildMessage($"dotnetCampus.TelescopeTask:正在写入编译导出文件…").Message(); PackageDirectory.Create(context.GeneratedCodeFolder); var targetFile = Path.Combine(context.GeneratedCodeFolder, "AttributedTypesExport.g.cs"); File.WriteAllText(targetFile, code); // 生成本次运行的摘要。 var resultFile = new FileInfo(Path.Combine(context.WorkingFolder, context.ToolsFolder, "Result.txt")); File.WriteAllText(resultFile.FullName, ""); resultFile.LastAccessTimeUtc = DateTime.UtcNow; }
public static void GetTargetPackageDirectory(this ITaskItem taskItem, out PackageDirectory packageDirectory, out string directoryPath) { var fileTarget = taskItem.GetMetadata(Metadata.FileTarget) ?? string.Empty; var fileTargetParts = fileTarget.Split(new[] { '\\', '/' }, 2, StringSplitOptions.RemoveEmptyEntries); if (fileTargetParts.Length <= 1) { packageDirectory = PackageDirectory.Root; directoryPath = fileTarget; return; } Enum.TryParse(fileTargetParts[0], true, out packageDirectory); if (packageDirectory == PackageDirectory.Root) { directoryPath = fileTarget; } else { directoryPath = fileTargetParts[1]; } }
public static string Combine(this PackageDirectory packageDirectory, string targetFramework, string fileName) { switch (packageDirectory) { case PackageDirectory.Root: return(fileName); case PackageDirectory.Content: return(Path.Combine(Constants.ContentDirectory, fileName)); case PackageDirectory.Build: return(Path.Combine(Constants.BuildDirectory, fileName)); case PackageDirectory.Lib: return(Path.Combine(Constants.LibDirectory, targetFramework, fileName)); case PackageDirectory.Tools: return(Path.Combine(Constants.ToolsDirectory, fileName)); default: return(fileName); } }
private IReadOnlyList <CommandSettings> GetCommands() { try { var commands = new List <CommandSettings>(); LockFile lockFile = new LockFileFormat().Read(PackageDirectory.WithFile(AssetsFileName).Value); LockFileTargetLibrary library = FindLibraryInLockFile(lockFile); ToolConfiguration configuration = _toolConfiguration.Value; LockFileItem entryPointFromLockFile = FindItemInTargetLibrary(library, configuration.ToolAssemblyEntryPoint); if (entryPointFromLockFile == null) { throw new ToolConfigurationException( string.Format( CommonLocalizableStrings.MissingToolEntryPointFile, configuration.ToolAssemblyEntryPoint, configuration.CommandName)); } // Currently only "dotnet" commands are supported commands.Add(new CommandSettings( configuration.CommandName, "dotnet", LockFileRelativePathToFullFilePath(entryPointFromLockFile.Path, library))); return(commands); } catch (Exception ex) when(ex is UnauthorizedAccessException || ex is IOException) { throw new ToolConfigurationException( string.Format( CommonLocalizableStrings.FailedToRetrieveToolConfiguration, ex.Message), ex); } }
public Package(string name, PackageDirectory rootDirectory) { Name = name; RootDirectory = rootDirectory; }
private void ResolveDirectory(ref Dictionary <string, IPackageData> dict, Stream stream, string path, PackageDirectory parentDir = null) { var rootName = GetRootName(path); var downPath = path.Substring(Math.Min(path.Length, rootName.Length + 1)); var pathDictKey = parentDir?.Path + (parentDir?.Path == null ? rootName : $@"\{rootName}"); if (downPath.Length > 0) { // 하위 경로 검색 var findDict = dict.Find(pathDictKey) as PackageDirectory; var currentDir = findDict ?? new PackageDirectory(rootName, null); if (findDict == null) { if (parentDir != null) { parentDir.Children.Add(currentDir); } dict.Add(pathDictKey, currentDir); } ResolveDirectory(ref dict, stream, downPath, currentDir); } else if (parentDir != null) { // 최하위 파일 if (IsDirectory(path)) { parentDir.Children.Add(new PackageDirectory(CleanName(path), null)); } else { parentDir.Children.Add(new PackageFile(path, stream)); } } else { // 단일 파일 if (IsDirectory(path)) { dict.Add(pathDictKey, new PackageDirectory(CleanName(path), null)); } else { dict.Add(pathDictKey, new PackageFile(path, stream)); } } }
protected override void ProcessRecord() { #if USING_RESTABLE_CMDLET if (Remote) { ProcessRecordViaRest(); return; } #endif ProviderInfo packagePathProviderInfo; var pkgPath = SessionState.Path.GetResolvedProviderPathFromPSPath(Package, out packagePathProviderInfo); using (var local = LocalEventSource) { local.Events += new SourceError((code, location, message, objects) => { location = location ?? SourceLocation.Unknowns; Host.UI.WriteErrorLine("{0}:Error {1}:{2}".format(location.FirstOrDefault(), code, message.format(objects))); return(true); }); if (!NoWarnings) { local.Events += new SourceWarning((code, location, message, objects) => { WriteWarning("{0}:Warning {1}:{2}".format((location ?? SourceLocation.Unknowns).FirstOrDefault(), message.format(objects))); return(false); }); } local.Events += new SourceDebug((code, location, message, objects) => { WriteVerbose("{0}:DebugMessage {1}:{2}".format((location ?? SourceLocation.Unknowns).FirstOrDefault(), code, message.format(objects))); return(false); }); using (var script = new PackageScript(pkgPath.FirstOrDefault())) { script.SplitThreshold = SplitThreshold * 1024 * 1024; if (PackageDirectory.Is()) { script.AddNuGetPackageDirectory(PackageDirectory.GetFullPath()); } if (Defines != null) { foreach (var i in Defines) { var p = i.IndexOf("="); var k = p > -1 ? i.Substring(0, p) : i; var v = p > -1 ? i.Substring(p + 1) : ""; script.AddMacro(k, v); } } if (Define != null) { foreach (var i in Define) { var p = i.IndexOf("="); var k = p > -1 ? i.Substring(0, p) : i; var v = p > -1 ? i.Substring(p + 1) : ""; script.AddMacro(k, v); } } IEnumerable <string> overlayPackages; var pkgFile = script.Save(PackageTypes.NuGet, !NoClean, GenerateOnly, out overlayPackages); } } }