public static string Process(Stream stream, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, bool throwIfNotFound = true) { string text; using (StreamReader streamReader = new StreamReader(stream)) { text = streamReader.ReadToEnd(); } var tokenizer = new Tokenizer(text); StringBuilder result = new StringBuilder(); for (; ;) { Token token = tokenizer.Read(); if (token == null) { break; } if (token.Category == TokenCategory.Variable) { var replaced = ReplaceToken(token.Value, msBuildNuGetProjectSystem, throwIfNotFound); result.Append(replaced); } else { result.Append(token.Value); } } return(result.ToString()); }
public MSBuildNuGetProject(IMSBuildNuGetProjectSystem msbuildNuGetProjectSystem, string folderNuGetProjectPath, string packagesConfigFolderPath) { if (msbuildNuGetProjectSystem == null) { throw new ArgumentNullException(nameof(msbuildNuGetProjectSystem)); } if (folderNuGetProjectPath == null) { throw new ArgumentNullException(nameof(folderNuGetProjectPath)); } if (packagesConfigFolderPath == null) { throw new ArgumentNullException(nameof(packagesConfigFolderPath)); } MSBuildNuGetProjectSystem = msbuildNuGetProjectSystem; FolderNuGetProject = new FolderNuGetProject(folderNuGetProjectPath); InternalMetadata.Add(NuGetProjectMetadataKeys.Name, MSBuildNuGetProjectSystem.ProjectName); InternalMetadata.Add(NuGetProjectMetadataKeys.TargetFramework, MSBuildNuGetProjectSystem.TargetFramework); InternalMetadata.Add(NuGetProjectMetadataKeys.FullPath, msbuildNuGetProjectSystem.ProjectFullPath); InternalMetadata.Add(NuGetProjectMetadataKeys.UniqueName, msbuildNuGetProjectSystem.ProjectUniqueName); PackagesConfigNuGetProject = new PackagesConfigNuGetProject(packagesConfigFolderPath, InternalMetadata); }
// TODO: can this be removed? public ProjectJsonBuildIntegratedNuGetProject( string jsonConfig, string msBuildProjectPath, IMSBuildNuGetProjectSystem projectSystem) : this(jsonConfig, msBuildProjectPath) { }
internal static string Process(ZipArchiveEntry packageFile, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { using (var stream = packageFile.Open()) { return(Process(stream, msBuildNuGetProjectSystem, throwIfNotFound: false)); } }
internal static void TryAddFile(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, string path, Func<Stream> content) { if (msBuildNuGetProjectSystem.FileExistsInProject(path)) { // file exists in project, ask user if he wants to overwrite or ignore string conflictMessage = String.Format(CultureInfo.CurrentCulture, Strings.FileConflictMessage, path, msBuildNuGetProjectSystem.ProjectName); FileConflictAction fileConflictAction = msBuildNuGetProjectSystem.NuGetProjectContext.ResolveFileConflict(conflictMessage); if (fileConflictAction == FileConflictAction.Overwrite || fileConflictAction == FileConflictAction.OverwriteAll) { // overwrite msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Info, Strings.Info_OverwritingExistingFile, path); using (Stream stream = content()) { msBuildNuGetProjectSystem.AddFile(path, stream); } } else { // ignore msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Warning, Strings.Warning_FileAlreadyExists, path); } } else { msBuildNuGetProjectSystem.AddFile(path, content()); } }
public static string Process(Stream stream, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, bool throwIfNotFound = true) { string text; using(StreamReader streamReader = new StreamReader(stream)) { text = streamReader.ReadToEnd(); } var tokenizer = new Tokenizer(text); StringBuilder result = new StringBuilder(); for (; ; ) { Token token = tokenizer.Read(); if (token == null) { break; } if (token.Category == TokenCategory.Variable) { var replaced = ReplaceToken(token.Value, msBuildNuGetProjectSystem, throwIfNotFound); result.Append(replaced); } else { result.Append(token.Value); } } return result.ToString(); }
public static XDocument CreateDocument(XName rootName, string path, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { XDocument document = new XDocument(new XElement(rootName)); // Add it to the project system MSBuildNuGetProjectSystemUtility.AddFile(msBuildNuGetProjectSystem, path, document.Save); return document; }
internal static void TryAddFile(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, string path, Func <Stream> content) { if (msBuildNuGetProjectSystem.FileExistsInProject(path)) { // file exists in project, ask user if he wants to overwrite or ignore var conflictMessage = string.Format(CultureInfo.CurrentCulture, Strings.FileConflictMessage, path, msBuildNuGetProjectSystem.ProjectName); var fileConflictAction = msBuildNuGetProjectSystem.NuGetProjectContext.ResolveFileConflict(conflictMessage); if (fileConflictAction == FileConflictAction.Overwrite || fileConflictAction == FileConflictAction.OverwriteAll) { // overwrite msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Info, Strings.Info_OverwritingExistingFile, path); using (var stream = content()) { msBuildNuGetProjectSystem.AddFile(path, stream); } } else { // ignore msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Warning, Strings.Warning_FileAlreadyExists, path); } } else { msBuildNuGetProjectSystem.AddFile(path, content()); } }
internal static string Process(ZipArchiveEntry packageFile, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { using (var stream = packageFile.Open()) { return Process(stream, msBuildNuGetProjectSystem, throwIfNotFound: false); } }
public void RevertFile(Func <Stream> fileStreamFactory, string targetPath, IEnumerable <InternalZipFileInfo> matchingFiles, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { // Get the xml snippet var xmlFragment = GetXml(fileStreamFactory, msBuildNuGetProjectSystem); var document = XmlUtility.GetOrCreateDocument(xmlFragment.Name, msBuildNuGetProjectSystem.ProjectFullPath, targetPath, msBuildNuGetProjectSystem.NuGetProjectContext); // Merge the other xml elements into one element within this xml hierarchy (matching the config file path) var mergedFragments = matchingFiles.Select(f => GetXml(f, msBuildNuGetProjectSystem)) .Aggregate(new XElement(xmlFragment.Name), (left, right) => left.MergeWith(right, _nodeActions)); // Take the difference of the xml and remove it from the main xml file document.Root.Except(xmlFragment.Except(mergedFragments)); // Save the new content to the file system using (var fileStream = FileSystemUtility.CreateFile(msBuildNuGetProjectSystem.ProjectFullPath, targetPath, msBuildNuGetProjectSystem.NuGetProjectContext)) { document.Save(fileStream); } }
public static XDocument CreateDocument(XName rootName, string path, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { XDocument document = new XDocument(new XElement(rootName)); // Add it to the project system MSBuildNuGetProjectSystemUtility.AddFile(msBuildNuGetProjectSystem, path, document.Save); return(document); }
private static string ReplaceToken(string propertyName, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, bool throwIfNotFound) { var value = msBuildNuGetProjectSystem.GetPropertyValue(propertyName); if (value == null && throwIfNotFound) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Strings.TokenHasNoValue, propertyName)); } return value; }
internal static void AddFile(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, string path, Action <Stream> writeToStream) { using (var memoryStream = new MemoryStream()) { writeToStream(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); msBuildNuGetProjectSystem.AddFile(path, memoryStream); } }
public TestMSBuildNuGetProject( IMSBuildNuGetProjectSystem msbuildProjectSystem, string folderNuGetProjectPath, string packagesConfigFolderPath) : base( msbuildProjectSystem, folderNuGetProjectPath, packagesConfigFolderPath) { ProjectClosure = new List <ExternalProjectReference>(); }
private static string ReplaceToken(string propertyName, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, bool throwIfNotFound) { var value = msBuildNuGetProjectSystem.GetPropertyValue(propertyName); if (value == null && throwIfNotFound) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Strings.TokenHasNoValue, propertyName)); } return(value); }
public TestBuildIntegratedNuGetProject( string jsonConfig, IMSBuildNuGetProjectSystem msbuildProjectSystem) : base( jsonConfig, Path.Combine( msbuildProjectSystem.ProjectFullPath, $"{msbuildProjectSystem.ProjectName}.csproj"), msbuildProjectSystem) { InternalMetadata.Add(NuGetProjectMetadataKeys.UniqueName, msbuildProjectSystem.ProjectName); ProjectClosure = new List <ExternalProjectReference>(); }
public void TransformFile(ZipArchiveEntry packageFile, string targetPath, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { // Get the xml fragment XElement xmlFragment = GetXml(packageFile, msBuildNuGetProjectSystem); XDocument transformDocument = XmlUtility.GetOrCreateDocument(xmlFragment.Name, targetPath, msBuildNuGetProjectSystem); // Do a merge transformDocument.Root.MergeWith(xmlFragment, _nodeActions); MSBuildNuGetProjectSystemUtility.AddFile(msBuildNuGetProjectSystem, targetPath, transformDocument.Save); }
public BuildIntegratedProjectSystem( string jsonConfigPath, string msbuildProjectFilePath, EnvDTEProject envDTEProject, IMSBuildNuGetProjectSystem msbuildProjectSystem, string uniqueName) : base(jsonConfigPath, msbuildProjectFilePath, msbuildProjectSystem) { InternalMetadata.Add(NuGetProjectMetadataKeys.UniqueName, uniqueName); EnvDTEProject = envDTEProject; }
internal static IEnumerable <string> GetFilesSafe(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, string path, string filter) { try { return(GetFiles(msBuildNuGetProjectSystem, path, filter, recursive: false)); } catch (Exception e) { msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Warning, e.Message); } return(Enumerable.Empty <string>()); }
internal static IEnumerable <string> GetDirectoriesSafe(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, string path) { try { return(GetDirectories(msBuildNuGetProjectSystem, path)); } catch (Exception e) { msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Warning, e.Message); } return(Enumerable.Empty <string>()); }
public BindingRedirectManager(string configurationFile, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { if (String.IsNullOrEmpty(configurationFile)) { throw new ArgumentException(NuGet.ProjectManagement.Strings.Argument_Cannot_Be_Null_Or_Empty, "configurationFile"); } if (msBuildNuGetProjectSystem == null) { throw new ArgumentNullException("msBuildNuGetProjectSystem"); } ConfigurationFile = configurationFile; MSBuildNuGetProjectSystem = msBuildNuGetProjectSystem; }
public static XDocument GetOrCreateDocument(XName rootName, string path, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { if (File.Exists(Path.Combine(msBuildNuGetProjectSystem.ProjectFullPath, path))) { try { return(GetDocument(msBuildNuGetProjectSystem.ProjectFullPath, path)); } catch (FileNotFoundException) { return(CreateDocument(rootName, path, msBuildNuGetProjectSystem)); } } return(CreateDocument(rootName, path, msBuildNuGetProjectSystem)); }
public static XDocument GetOrCreateDocument(XName rootName, string path, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { if (File.Exists(Path.Combine(msBuildNuGetProjectSystem.ProjectFullPath, path))) { try { return GetDocument(msBuildNuGetProjectSystem.ProjectFullPath, path); } catch (FileNotFoundException) { return CreateDocument(rootName, path, msBuildNuGetProjectSystem); } } return CreateDocument(rootName, path, msBuildNuGetProjectSystem); }
private static XElement GetXml(InternalZipFileInfo packageFileInfo, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { string content; using (var packageStream = File.OpenRead(packageFileInfo.ZipArchivePath)) { var zipArchive = new ZipArchive(packageStream); var zipArchivePackageEntry = zipArchive.GetEntry(packageFileInfo.ZipArchiveEntryFullName); if(zipArchivePackageEntry == null) { throw new ArgumentException("internalZipFileInfo"); } content = Preprocessor.Process(zipArchivePackageEntry, msBuildNuGetProjectSystem); } return XElement.Parse(content, LoadOptions.PreserveWhitespace); }
public BuildIntegratedProjectSystem( string jsonConfigPath, string msbuildProjectFilePath, DotNetProject dotNetProject, IMSBuildNuGetProjectSystem msbuildProjectSystem, string uniqueName, ISettings settings) : base(jsonConfigPath, msbuildProjectFilePath, msbuildProjectSystem) { this.dotNetProject = new DotNetProjectProxy(dotNetProject); packageManagementEvents = (PackageManagementEvents)PackageManagementServices.PackageManagementEvents; string path = SettingsUtility.GetGlobalPackagesFolder(settings); packagePathResolver = new VersionFolderPathResolver(path); }
public VSMSBuildNuGetProject( EnvDTEProject project, IMSBuildNuGetProjectSystem msbuildNuGetProjectSystem, string folderNuGetProjectPath, string packagesConfigFolderPath) : base( msbuildNuGetProjectSystem, folderNuGetProjectPath, packagesConfigFolderPath) { _project = project; // set project id var projectId = VsHierarchyUtility.GetProjectId(project); InternalMetadata.Add(NuGetProjectMetadataKeys.ProjectId, projectId); }
// Deletes an empty folder from disk and the project private static void DeleteDirectory(IMSBuildNuGetProjectSystem projectSystem, string path) { var fullPath = Path.Combine(projectSystem.ProjectFullPath, path); if (!Directory.Exists(fullPath)) { return; } // Only delete this folder if it is empty and we didn't specify that we want to recurse if (GetFiles(projectSystem, path, "*.*", recursive: false).Any() || GetDirectories(projectSystem, path).Any()) { projectSystem.NuGetProjectContext.Log(MessageLevel.Warning, Strings.Warning_DirectoryNotEmpty, path); return; } projectSystem.RegisterProcessedFiles(new[] { path }); projectSystem.DeleteDirectory(path, recursive: false); // Workaround for update-package TFS issue. If we're bound to TFS, do not try and delete directories. var sourceControlManager = SourceControlUtility.GetSourceControlManager(projectSystem.NuGetProjectContext); if (sourceControlManager != null) { // Source control bound, do not delete return; } // For potential project systems that do not remove items from disk, we delete the folder directly // There is no actual scenario where we know this is broken without the code below, but since the // code was always there, we are leaving it behind for now. if (!Directory.Exists(fullPath)) { Directory.Delete(fullPath, recursive: false); // The directory is not guaranteed to be gone since there could be // other open handles. Wait, up to half a second, until the directory is gone. for (var i = 0; Directory.Exists(fullPath) && i < 5; ++i) { Thread.Sleep(100); } projectSystem.RegisterProcessedFiles(new[] { path }); projectSystem.NuGetProjectContext.Log(MessageLevel.Debug, Strings.Debug_RemovedFolder, fullPath); } }
public static void DeleteFileSafe(string path, Func <Stream> streamFactory, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { // Only delete the file if it exists and the checksum is the same if (msBuildNuGetProjectSystem.FileExistsInProject(path)) { var fullPath = Path.Combine(msBuildNuGetProjectSystem.ProjectFullPath, path); if (FileSystemUtility.ContentEquals(fullPath, streamFactory)) { PerformSafeAction(() => msBuildNuGetProjectSystem.RemoveFile(path), msBuildNuGetProjectSystem.NuGetProjectContext); } else { // This package installed a file that was modified so warn the user msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Warning, Strings.Warning_FileModified, fullPath); } } }
private static string ResolveTargetPath(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, IDictionary <FileTransformExtensions, IPackageFileTransformer> fileTransformers, Func <FileTransformExtensions, string> extensionSelector, string effectivePath, out IPackageFileTransformer transformer) { string truncatedPath; // Remove the transformer extension (e.g. .pp, .transform) transformer = FindFileTransformer(fileTransformers, extensionSelector, effectivePath, out truncatedPath); if (transformer != null) { effectivePath = truncatedPath; } return(msBuildNuGetProjectSystem.ResolvePath(effectivePath)); }
private static XElement GetXml(InternalZipFileInfo packageFileInfo, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { string content; using (var packageStream = File.OpenRead(packageFileInfo.ZipArchivePath)) { var zipArchive = new ZipArchive(packageStream); var zipArchivePackageEntry = PathUtility.GetEntry(zipArchive, packageFileInfo.ZipArchiveEntryFullName); if (zipArchivePackageEntry == null) { throw new ArgumentException("internalZipFileInfo"); } content = Preprocessor.Process(zipArchivePackageEntry.Open, msBuildNuGetProjectSystem); } return(XElement.Parse(content, LoadOptions.PreserveWhitespace)); }
public static void DeleteDirectory(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, string path, bool recursive) { var fullPath = Path.Combine(msBuildNuGetProjectSystem.ProjectFullPath, path); if (!Directory.Exists(fullPath)) { return; } // Only delete this folder if it is empty and we didn't specify that we want to recurse if (!recursive && (GetFiles(msBuildNuGetProjectSystem, path, "*.*", recursive).Any() || GetDirectories(msBuildNuGetProjectSystem, path).Any())) { msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Warning, Strings.Warning_DirectoryNotEmpty, path); return; } msBuildNuGetProjectSystem.DeleteDirectory(path, recursive); // Workaround for update-package TFS issue. If we're bound to TFS, do not try and delete directories. var sourceControlManager = SourceControlUtility.GetSourceControlManager(msBuildNuGetProjectSystem.NuGetProjectContext); if (sourceControlManager != null) { // Source control bound, do not delete return; } try { Directory.Delete(fullPath, recursive); // The directory is not guaranteed to be gone since there could be // other open handles. Wait, up to half a second, until the directory is gone. for (int i = 0; Directory.Exists(fullPath) && i < 5; ++i) { System.Threading.Thread.Sleep(100); } msBuildNuGetProjectSystem.RemoveFile(path); msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Debug, Strings.Debug_RemovedFolder, fullPath); } catch (DirectoryNotFoundException) { } }
private static void PerformXdtTransform(ZipArchiveEntry packageFile, string targetPath, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { if(FileSystemUtility.FileExists(msBuildNuGetProjectSystem.ProjectFullPath, targetPath)) { string content = Preprocessor.Process(packageFile, msBuildNuGetProjectSystem); try { using (var transformation = new XmlTransformation(content, isTransformAFile: false, logger: null)) { using (var document = new XmlTransformableDocument()) { document.PreserveWhitespace = true; // make sure we close the input stream immediately so that we can override // the file below when we save to it. using (var inputStream = File.OpenRead(FileSystemUtility.GetFullPath(msBuildNuGetProjectSystem.ProjectFullPath, targetPath))) { document.Load(inputStream); } bool succeeded = transformation.Apply(document); if (succeeded) { // save the result into a memoryStream first so that if there is any // exception during document.Save(), the original file won't be truncated. MSBuildNuGetProjectSystemUtility.AddFile(msBuildNuGetProjectSystem, targetPath, document.Save); } } } } catch (Exception exception) { throw new InvalidDataException( String.Format( CultureInfo.CurrentCulture, Strings.XdtError + " " + exception.Message, targetPath, msBuildNuGetProjectSystem.ProjectName), exception); } } }
/// <summary> /// Creates a .refresh file in bin directory of the IFileSystem that points to the assembly being installed. /// This works around issues in DTE's AddReference method when dealing with GACed binaries. /// </summary> /// <remarks>Adds the file to disk ONLY!</remarks> /// <param name="root">the root path is dte full path</param> /// <param name="assemblyPath">The relative path to the assembly being added</param> public static void CreateRefreshFile(string root, string assemblyPath, IMSBuildNuGetProjectSystem msbuildNuGetProjectSystem) { string refreshFilePath = CreateRefreshFilePath(root, assemblyPath); if (!FileSystemUtility.FileExists(root, refreshFilePath)) { try { using (var stream = CreateRefreshFileStream(root, assemblyPath)) { msbuildNuGetProjectSystem.AddFile(refreshFilePath, stream); } } catch (UnauthorizedAccessException exception) { // log IO permission error ExceptionHelper.WriteToActivityLog(exception); } } }
public void RevertFile(ZipArchiveEntry packageFile, string targetPath, IEnumerable<InternalZipFileInfo> matchingFiles, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { // Get the xml snippet XElement xmlFragment = GetXml(packageFile, msBuildNuGetProjectSystem); XDocument document = XmlUtility.GetOrCreateDocument(xmlFragment.Name, msBuildNuGetProjectSystem.ProjectFullPath, targetPath, msBuildNuGetProjectSystem.NuGetProjectContext); // Merge the other xml elements into one element within this xml hierarchy (matching the config file path) var mergedFragments = matchingFiles.Select(f => GetXml(f, msBuildNuGetProjectSystem)) .Aggregate(new XElement(xmlFragment.Name), (left, right) => left.MergeWith(right, _nodeActions)); // Take the difference of the xml and remove it from the main xml file document.Root.Except(xmlFragment.Except(mergedFragments)); // Save the new content to the file system using (var fileStream = FileSystemUtility.CreateFile(msBuildNuGetProjectSystem.ProjectFullPath, targetPath, msBuildNuGetProjectSystem.NuGetProjectContext)) { document.Save(fileStream); } }
private static XElement GetXml(ZipArchiveEntry packageFile, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { var content = Preprocessor.Process(packageFile, msBuildNuGetProjectSystem); return XElement.Parse(content, LoadOptions.PreserveWhitespace); }
public void TransformFile(ZipArchiveEntry packageFile, string targetPath, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { MSBuildNuGetProjectSystemUtility.TryAddFile(msBuildNuGetProjectSystem, targetPath, () => StreamUtility.StreamFromString(Process(packageFile, msBuildNuGetProjectSystem))); }
public void RevertFile(ZipArchiveEntry packageFile, string targetPath, IEnumerable<InternalZipFileInfo> matchingFiles, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { MSBuildNuGetProjectSystemUtility.DeleteFileSafe(targetPath, () => StreamUtility.StreamFromString(Process(packageFile, msBuildNuGetProjectSystem)), msBuildNuGetProjectSystem); }
public void TransformFile(ZipArchiveEntry packageFile, string targetPath, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { PerformXdtTransform(packageFile, targetPath, msBuildNuGetProjectSystem); }
public static void DeleteFileSafe(string path, Func<Stream> streamFactory, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { // Only delete the file if it exists and the checksum is the same if (msBuildNuGetProjectSystem.FileExistsInProject(path)) { var fullPath = Path.Combine(msBuildNuGetProjectSystem.ProjectFullPath, path); if (FileSystemUtility.ContentEquals(fullPath, streamFactory)) { PerformSafeAction(() => msBuildNuGetProjectSystem.RemoveFile(path), msBuildNuGetProjectSystem.NuGetProjectContext); } else { // This package installed a file that was modified so warn the user msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Warning, Strings.Warning_FileModified, fullPath); } } }
public static void DeleteDirectory(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, string path, bool recursive) { var fullPath = Path.Combine(msBuildNuGetProjectSystem.ProjectFullPath, path); if (!Directory.Exists(fullPath)) { return; } // Only delete this folder if it is empty and we didn't specify that we want to recurse if (!recursive && (GetFiles(msBuildNuGetProjectSystem, path, "*.*", recursive).Any() || GetDirectories(msBuildNuGetProjectSystem, path).Any())) { msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Warning, Strings.Warning_DirectoryNotEmpty, path); return; } msBuildNuGetProjectSystem.DeleteDirectory(path, recursive); // Workaround for update-package TFS issue. If we're bound to TFS, do not try and delete directories. var sourceControlManager = SourceControlUtility.GetSourceControlManager(msBuildNuGetProjectSystem.NuGetProjectContext); if(sourceControlManager != null) { // Source control bound, do not delete return; } try { Directory.Delete(fullPath, recursive); // The directory is not guaranteed to be gone since there could be // other open handles. Wait, up to half a second, until the directory is gone. for (int i = 0; Directory.Exists(fullPath) && i < 5; ++i) { System.Threading.Thread.Sleep(100); } msBuildNuGetProjectSystem.RemoveFile(path); msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Debug, Strings.Debug_RemovedFolder, fullPath); } catch (DirectoryNotFoundException) { } }
public static IEnumerable<string> GetFilesSafe(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, string path, string filter) { try { return GetFiles(msBuildNuGetProjectSystem, path, filter, recursive: false); } catch (Exception e) { msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Warning, e.Message); } return Enumerable.Empty<string>(); }
internal static void AddFiles(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, ZipArchive zipArchive, FrameworkSpecificGroup frameworkSpecificGroup, IDictionary<FileTransformExtensions, IPackageFileTransformer> fileTransformers) { var packageTargetFramework = frameworkSpecificGroup.TargetFramework; // Content files are maintained with AltDirectorySeparatorChar List<string> packageItemListAsArchiveEntryNames = frameworkSpecificGroup.Items.Select(i => PathUtility.ReplaceDirSeparatorWithAltDirSeparator(i)).ToList(); packageItemListAsArchiveEntryNames.Sort(new PackageItemComparer()); try { var zipArchiveEntryList = packageItemListAsArchiveEntryNames.Select(i => zipArchive.GetEntry(i)).Where(i => i != null).ToList(); try { var paths = zipArchiveEntryList.Select(file => ResolvePath(fileTransformers, fte => fte.InstallExtension, GetEffectivePathForContentFile(packageTargetFramework, file.FullName))); paths = paths.Where(p => !String.IsNullOrEmpty(p)); msBuildNuGetProjectSystem.BeginProcessing(paths); } catch (Exception) { // Ignore all exceptions for now } foreach (ZipArchiveEntry zipArchiveEntry in zipArchiveEntryList) { if (zipArchiveEntry == null) { throw new ArgumentNullException("zipArchiveEntry"); } if (IsEmptyFolder(zipArchiveEntry.FullName)) { continue; } var effectivePathForContentFile = GetEffectivePathForContentFile(packageTargetFramework, zipArchiveEntry.FullName); // Resolve the target path IPackageFileTransformer installTransformer; string path = ResolveTargetPath(msBuildNuGetProjectSystem, fileTransformers, fte => fte.InstallExtension, effectivePathForContentFile, out installTransformer); if (msBuildNuGetProjectSystem.IsSupportedFile(path)) { if (installTransformer != null) { installTransformer.TransformFile(zipArchiveEntry, path, msBuildNuGetProjectSystem); } else { // Ignore uninstall transform file during installation string truncatedPath; IPackageFileTransformer uninstallTransformer = FindFileTransformer(fileTransformers, fte => fte.UninstallExtension, effectivePathForContentFile, out truncatedPath); if (uninstallTransformer != null) { continue; } TryAddFile(msBuildNuGetProjectSystem, path, zipArchiveEntry.Open); } } } } finally { msBuildNuGetProjectSystem.EndProcessing(); } }
/// <summary> /// Project.json based project system. /// </summary> /// <param name="jsonConfig">Path to project.json.</param> /// <param name="msBuildProjectPath">Path to the msbuild project file.</param> /// <param name="msbuildProjectSystem">Underlying msbuild project system.</param> public BuildIntegratedNuGetProject( string jsonConfig, string msBuildProjectPath, IMSBuildNuGetProjectSystem msbuildProjectSystem) { if (jsonConfig == null) { throw new ArgumentNullException(nameof(jsonConfig)); } if (msBuildProjectPath == null) { throw new ArgumentNullException(nameof(msBuildProjectPath)); } _jsonConfig = new FileInfo(jsonConfig); MSBuildNuGetProjectSystem = msbuildProjectSystem; MSBuildProjectPath = msBuildProjectPath; _projectName = Path.GetFileNameWithoutExtension(msBuildProjectPath); if (string.IsNullOrEmpty(_projectName)) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, Strings.InvalidProjectName, MSBuildProjectPath)); } JObject projectJson; IEnumerable <NuGetFramework> targetFrameworks = Enumerable.Empty <NuGetFramework>(); try { projectJson = GetJson(); targetFrameworks = JsonConfigUtility.GetFrameworks(projectJson); } catch (InvalidOperationException) { // Ignore a bad project.json when constructing the project, and treat it as unsupported. } // Default to unsupported if anything unexpected is returned var targetFramework = NuGetFramework.UnsupportedFramework; // Having more than one framework is not supported, but we pick the first as fallback // We will eventually support more than one framework ala projectK. if (targetFrameworks.Count() == 1) { targetFramework = targetFrameworks.First(); } InternalMetadata.Add(NuGetProjectMetadataKeys.TargetFramework, targetFramework); InternalMetadata.Add(NuGetProjectMetadataKeys.Name, msbuildProjectSystem.ProjectName); InternalMetadata.Add(NuGetProjectMetadataKeys.FullPath, msbuildProjectSystem.ProjectFullPath); var supported = new List <FrameworkName> { new FrameworkName(targetFramework.DotNetFrameworkName) }; InternalMetadata.Add(NuGetProjectMetadataKeys.SupportedFrameworks, supported); }
public static void AddFile(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, string path, Action<Stream> writeToStream) { using (var memoryStream = new MemoryStream()) { writeToStream(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); msBuildNuGetProjectSystem.AddFile(path, memoryStream); } }
private static string ResolveTargetPath(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, IDictionary<FileTransformExtensions, IPackageFileTransformer> fileTransformers, Func<FileTransformExtensions, string> extensionSelector, string effectivePath, out IPackageFileTransformer transformer) { string truncatedPath; // Remove the transformer extension (e.g. .pp, .transform) transformer = FindFileTransformer(fileTransformers, extensionSelector, effectivePath, out truncatedPath); if (transformer != null) { effectivePath = truncatedPath; } return msBuildNuGetProjectSystem.ResolvePath(effectivePath); }
public static IEnumerable<string> GetDirectories(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, string path) { return msBuildNuGetProjectSystem.GetDirectories(path); }
public static IEnumerable<string> GetFiles(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, string path, string filter, bool recursive) { return msBuildNuGetProjectSystem.GetFiles(path, filter, recursive); }
public static IEnumerable<string> GetDirectoriesSafe(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, string path) { try { return GetDirectories(msBuildNuGetProjectSystem, path); } catch (Exception e) { msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Warning, e.Message); } return Enumerable.Empty<string>(); }
private static XElement GetXml(Func <Stream> fileStreamFactory, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { var content = Preprocessor.Process(fileStreamFactory, msBuildNuGetProjectSystem); return(XElement.Parse(content, LoadOptions.PreserveWhitespace)); }
public void RevertFile(ZipArchiveEntry packageFile, string targetPath, System.Collections.Generic.IEnumerable<InternalZipFileInfo> matchingFiles, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { PerformXdtTransform(packageFile, targetPath, msBuildNuGetProjectSystem); }
public void RevertFile(Func <Stream> fileStreamFactory, string targetPath, IEnumerable <InternalZipFileInfo> matchingFiles, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { PerformXdtTransform(fileStreamFactory, targetPath, msBuildNuGetProjectSystem); }
public static void DeleteDirectorySafe(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, string path, bool recursive) { PerformSafeAction(() => DeleteDirectory(msBuildNuGetProjectSystem, path, recursive), msBuildNuGetProjectSystem.NuGetProjectContext); }
public void TransformFile(Func <Stream> fileStreamFactory, string targetPath, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { PerformXdtTransform(fileStreamFactory, targetPath, msBuildNuGetProjectSystem); }
public static IEnumerable<string> GetFilesSafe(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, string path) { return GetFilesSafe(msBuildNuGetProjectSystem, path, "*.*"); }
private static void PerformXdtTransform(Func <Stream> fileStreamFactory, string targetPath, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { if (FileSystemUtility.FileExists(msBuildNuGetProjectSystem.ProjectFullPath, targetPath)) { var content = Preprocessor.Process(fileStreamFactory, msBuildNuGetProjectSystem); try { using (var transformation = new XmlTransformation(content, isTransformAFile: false, logger: null)) { using (var document = new XmlTransformableDocument()) { document.PreserveWhitespace = true; // make sure we close the input stream immediately so that we can override // the file below when we save to it. using (var inputStream = File.OpenRead(FileSystemUtility.GetFullPath(msBuildNuGetProjectSystem.ProjectFullPath, targetPath))) { document.Load(inputStream); } var succeeded = transformation.Apply(document); if (succeeded) { // save the result into a memoryStream first so that if there is any // exception during document.Save(), the original file won't be truncated. MSBuildNuGetProjectSystemUtility.AddFile(msBuildNuGetProjectSystem, targetPath, document.Save); } } } } catch (Exception exception) { throw new InvalidDataException( string.Format( CultureInfo.CurrentCulture, Strings.XdtError + " " + exception.Message, targetPath, msBuildNuGetProjectSystem.ProjectName), exception); } } }
internal static void DeleteFiles(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem, ZipArchive zipArchive, IEnumerable<string> otherPackagesPath, FrameworkSpecificGroup frameworkSpecificGroup, IDictionary<FileTransformExtensions, IPackageFileTransformer> fileTransformers) { var packageTargetFramework = frameworkSpecificGroup.TargetFramework; IPackageFileTransformer transformer; var directoryLookup = frameworkSpecificGroup.Items.ToLookup( p => Path.GetDirectoryName(ResolveTargetPath(msBuildNuGetProjectSystem, fileTransformers, fte => fte.UninstallExtension, GetEffectivePathForContentFile(packageTargetFramework, p), out transformer))); // Get all directories that this package may have added var directories = from grouping in directoryLookup from directory in FileSystemUtility.GetDirectories(grouping.Key, altDirectorySeparator: false) orderby directory.Length descending select directory; // Remove files from every directory foreach (var directory in directories) { var directoryFiles = directoryLookup.Contains(directory) ? directoryLookup[directory] : Enumerable.Empty<string>(); if (!Directory.Exists(Path.Combine(msBuildNuGetProjectSystem.ProjectFullPath, directory))) { continue; } try { foreach (var file in directoryFiles) { if (IsEmptyFolder(file)) { continue; } // Resolve the path string path = ResolveTargetPath(msBuildNuGetProjectSystem, fileTransformers, fte => fte.UninstallExtension, GetEffectivePathForContentFile(packageTargetFramework, file), out transformer); if (msBuildNuGetProjectSystem.IsSupportedFile(path)) { if (transformer != null) { // TODO: use the framework from packages.config instead of the current framework // which may have changed during re-targeting NuGetFramework projectFramework = msBuildNuGetProjectSystem.TargetFramework; List<InternalZipFileInfo> matchingFiles = new List<InternalZipFileInfo>(); foreach(var otherPackagePath in otherPackagesPath) { using(var otherPackageStream = File.OpenRead(otherPackagePath)) { var otherPackageZipArchive = new ZipArchive(otherPackageStream); var otherPackageZipReader = new PackageReader(otherPackageZipArchive); // use the project framework to find the group that would have been installed var mostCompatibleContentFilesGroup = GetMostCompatibleGroup(projectFramework, otherPackageZipReader.GetContentItems(), altDirSeparator: true); if(mostCompatibleContentFilesGroup != null && IsValid(mostCompatibleContentFilesGroup)) { foreach(var otherPackageItem in mostCompatibleContentFilesGroup.Items) { if(GetEffectivePathForContentFile(packageTargetFramework, otherPackageItem) .Equals(GetEffectivePathForContentFile(packageTargetFramework, file), StringComparison.OrdinalIgnoreCase)) { matchingFiles.Add(new InternalZipFileInfo(otherPackagePath, otherPackageItem)); } } } } } try { var zipArchiveFileEntry = zipArchive.GetEntry(PathUtility.ReplaceDirSeparatorWithAltDirSeparator(file)); if (zipArchiveFileEntry != null) { transformer.RevertFile(zipArchiveFileEntry, path, matchingFiles, msBuildNuGetProjectSystem); } } catch (Exception e) { msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Warning, e.Message); } } else { var zipArchiveFileEntry = zipArchive.GetEntry(PathUtility.ReplaceDirSeparatorWithAltDirSeparator(file)); if (zipArchiveFileEntry != null) { DeleteFileSafe(path, zipArchiveFileEntry.Open, msBuildNuGetProjectSystem); } } } } // If the directory is empty then delete it if (!GetFilesSafe(msBuildNuGetProjectSystem, directory).Any() && !GetDirectoriesSafe(msBuildNuGetProjectSystem, directory).Any()) { DeleteDirectorySafe(msBuildNuGetProjectSystem, directory, recursive: false); } } finally { } } }