protected override bool FixDocumentByStrategy(NugetFixStrategy nugetFixStrategy) { var packageReferences = CsProj.GetPackageReferences(Document).Where(x => x.Attribute(CsProj.IncludeAttribute).Value == nugetFixStrategy.NugetName); var nugetInfoReferences = CsProj.GetNugetInfoReferences(Document).Where(x => CsProj.GetNugetInfoFromNugetInfoReference(x).Name == nugetFixStrategy.NugetName); if (!packageReferences.Any() && !nugetInfoReferences.Any()) { return(false); } if (nugetFixStrategy.NugetVersion == NugetVersion.IgnoreFix) { Log = StringSplicer.SpliceWithNewLine(Log, $" - 根据策略,忽略 {nugetFixStrategy.NugetName} 存在的问题"); return(true); } if (packageReferences.Any()) { FixPackageReferences(packageReferences, nugetFixStrategy); DeleteNugetInfoReferences(nugetInfoReferences); } else { FixNugetInfoReferences(nugetInfoReferences, nugetFixStrategy); } return(true); }
public void ReadsFileContentsIntoObject() { CsProj project = GetProject("Simple"); Assert.AreEqual("{4A37C916-5AA3-4C12-B7A8-E5F878A5CDBA}", project.Guid); Assert.AreEqual("MyProject", project.AssemblyName); Assert.AreEqual(file.FullName, project.Path); Assert.AreEqual("v4.0", project.TargetFrameworkVersion); CollectionAssert.AreEqual(new[] { "System", "System.Core", "System.Xml.Linq", "System.Data.DataSetExtensions", "Microsoft.CSharp", "System.Data", "System.Xml" }, project.ReferencedAssemblyNames); CollectionAssert.AreEqual(new[] { "{99036BB6-4F97-4FCC-AF6C-0345A5089099}", "{69036BB3-4F97-4F9C-AF2C-0349A5049060}" }, project.ReferencedProjectGuids); }
private void ConvertToProjectReference(CsProj project, IEnumerable<CsProj> references) { var doc = LoadProject(project); var nav = doc.CreateNavigator(); foreach (var reference in references) { log.InfoFormat("Converting project {0} assembly reference {1} to project reference {2}.", project.AssemblyName, reference.AssemblyName, reference.Path); var xpath = string.Format("//msb:ItemGroup/msb:Reference[substring-before(concat(@Include, ','), ',') = '{0}']", reference.AssemblyName); var element = nav.SelectSingleNode(xpath, nsMgr); if (element == null) { log.ErrorFormat("Failed to locate Reference element in {0} for assembly {1}.", project.Path, reference.AssemblyName); continue; } var projectReference = doc.CreateElement("ProjectReference", MSBuildXmlNamespace); projectReference.SetAttribute("Include", reference.Path); projectReference.AppendChild(CreateElementWithInnerText(doc, "Project", reference.Guid)); projectReference.AppendChild(CreateElementWithInnerText(doc, "Name", reference.ProjectName)); var wrapper = doc.CreateElement("SlimJimReplacedReference", MSBuildXmlNamespace); wrapper.AppendChild(((XmlNode) element.UnderlyingObject).Clone()); projectReference.AppendChild(wrapper); element.ReplaceSelf(new XmlNodeReader(projectReference)); } doc.Save(project.Path); }
/// <summary> /// 获取 Nuget 包信息列表 /// </summary> /// <returns>Nuget 包信息列表</returns> public IEnumerable <NugetInfo> GetNugetInfos() { if (!IsGoodFormat()) { throw new InvalidOperationException("无法在格式异常的配置文件中读取 Nuget 信息。"); } var nugetInfoList = new List <NugetInfo>(); var packageReferences = CsProj.GetPackageReferences(_xDocument); foreach (var packageReference in packageReferences) { var nugetName = GetNugetName(packageReference); var nugetVersion = GetNugetVersion(packageReference); if (string.IsNullOrWhiteSpace(nugetName) || string.IsNullOrWhiteSpace(nugetVersion)) { continue; } nugetInfoList.Add(new NugetInfo(nugetName, nugetVersion)); } foreach (var nugetInfoReference in CsProj.GetNugetInfoReferences(_xDocument)) { var nugetInfo = CsProj.GetNugetInfoFromNugetInfoReference(nugetInfoReference, _csProjPath); nugetInfoList.Add(nugetInfo); } return(nugetInfoList); }
public void IgnoresNestedReferences() { CsProj project = GetProject("ConvertedReference"); CollectionAssert.DoesNotContain(project.ReferencedAssemblyNames, "log4net"); }
public void CanAddProjectReference() { var slnFile = GetActualSlnFile(); var csProj = CsProj.Get(SampleCsProjFile); slnFile.AddProjectReference(csProj); Assert.Equal(true, slnFile.ContainsProjectReference(csProj)); }
public CsProj GetActualCsProjFile() { if (File.Exists(ActualCsProjFile)) { File.Delete(ActualCsProjFile); } File.Copy(SampleCsProjFile, ActualCsProjFile); return(CsProj.Get(ActualCsProjFile)); }
protected XmlDocument LoadProject(CsProj project) { var doc = new XmlDocument(); doc.Load(project.Path); nsMgr = new XmlNamespaceManager(doc.NameTable); nsMgr.AddNamespace("msb", MSBuildXmlNamespace); return(doc); }
/// <summary> /// 构造一条 Nuget 包修复策略 /// </summary> /// <param name="nugetName">名称</param> /// <param name="nugetVersion">版本号</param> /// <param name="nugetDllInfo">Dll 信息</param> public NugetFixStrategy(string nugetName, string nugetVersion, [NotNull] NugetDllInfo nugetDllInfo) : this( nugetName, nugetVersion) { NugetDllInfo = nugetDllInfo ?? throw new ArgumentNullException(nameof(nugetDllInfo)); if (!string.IsNullOrEmpty(nugetDllInfo.DllPath) && File.Exists(nugetDllInfo.DllPath)) { TargetFramework = CsProj.GetTargetFrameworkOfDll(nugetDllInfo.DllPath); } }
public void should_set_project_attributes() { var projectFile = FileSystem.Combine("Templating", "data", "example1", "example1.csproj"); var project = new CsProj(); _projGatherer.VisitProj(projectFile, project); project.ProjectGuid.ShouldEqual("GUID1"); project.Name.ShouldEqual("FUBUPROJECTNAME"); }
public void HandlesTrailingSlashOnRootDirectory() { var sln = new Sln("sample") { ProjectsRootDirectory = "Fake/Example/" }; var proj = new CsProj { Path = "Fake/Example/ModuleA/ProjectA/ProjectA.csproj", Guid = Guid.NewGuid().ToString("B") }; sln.AddProjects(proj); Assert.AreNotEqual(new Folder(), sln.Folders.FirstOrDefault(f => f.FolderName == "ModuleA"), "Folders"); }
private void RestoreAssemblyReferencesInProject(CsProj project) { var doc = LoadProject(project); var nav = doc.CreateNavigator(); XPathNavigator projectReference; while ((projectReference = nav.SelectSingleNode("//msb:ProjectReference[msb:SlimJimReplacedReference and 1]", nsMgr)) != null) { var original = projectReference.SelectSingleNode("./msb:SlimJimReplacedReference/msb:Reference", nsMgr); log.InfoFormat("Restoring project {0} assembly reference to {1}", project.ProjectName, projectReference.GetAttribute("Include", "")); projectReference.ReplaceSelf(original); } doc.Save(project.Path); }
public void CreatesNestedSolutionFolders() { var sln = new Sln("sample") { ProjectsRootDirectory = "Fake/Example" }; var proj = new CsProj { Path = "Fake/Example/Grouping1/ModuleA/ProjectA/ProjectA.csproj", Guid = Guid.NewGuid().ToString("B") }; sln.AddProjects(proj); var child = sln.Folders.First(f => f.FolderName == "ModuleA"); var parent = sln.Folders.First(f => f.FolderName == "Grouping1"); CollectionAssert.AreEqual(new[] { child.Guid }, parent.ContentGuids.ToArray()); CollectionAssert.AreEqual(new[] { proj.Guid }, child.ContentGuids.ToArray()); }
public void should_add_project_references() { // build it up through a stringbuilder to use the environment-specific newline var solutionBuilder = new StringBuilder("Microsoft Visual Studio Solution File, Format Version 11.00") .AppendLine() .AppendLine("# Visual Studio 2010") .AppendLine(@"Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""FubuMVC.StructureMap"", ""FubuMVC.StructureMap\FubuMVC.StructureMap.csproj"", ""{ABFEA520-820C-4B77-9015-6A09E24252FA}""") .AppendLine("EndProject") .AppendLine("Global") .AppendLine(" GlobalSection(SolutionConfigurationPlatforms) = preSolution") .AppendLine(" Debug|Any CPU = Debug|Any CPU") .AppendLine(" Release|Any CPU = Release|Any CPU") .AppendLine(" EndGlobalSection") .AppendLine(" GlobalSection(SolutionProperties) = preSolution") .AppendLine(" HideSolutionNode = FALSE") .AppendLine(" EndGlobalSection") .AppendLine("EndGlobal"); var system = new FileSystem(); var solutionFile = "tmp.sln"; system.AppendStringToFile(solutionFile, solutionBuilder.ToString()); var project = new CsProj { Name = "Test", ProjectGuid = "123", RelativePath = @"example1\example1.csproj" }; var service = new SolutionFileService(system); service.AddProject(solutionFile, project); var solutionContents = system.ReadStringFromFile(solutionFile); var lines = service.SplitSolution(solutionContents); lines[4].ShouldEqual("Project(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Test\", \"example1\\example1.csproj\", \"{123}\""); lines[5].ShouldEqual("EndProject"); system.DeleteFile(solutionFile); }
private void RestoreAssemblyReferencesInProject(CsProj project) { var doc = new XmlDocument(); doc.Load(project.Path); var nav = doc.CreateNavigator(); var nsMgr = new XmlNamespaceManager(doc.NameTable); nsMgr.AddNamespace("msb", MSBuildXmlNamespace); XPathNavigator projectReference; while ((projectReference = nav.SelectSingleNode("//msb:ProjectReference[msb:SlimJimReplacedReference and 1]", nsMgr)) != null) { var original = projectReference.SelectSingleNode("./msb:SlimJimReplacedReference/msb:Reference", nsMgr); Log.InfoFormat("Restoring project {0} assembly reference to {1}", project.ProjectName, projectReference.GetAttribute("Include", "")); projectReference.ReplaceSelf(original); } doc.Save(project.Path); }
public void ReadsFileContentsIntoObject() { CsProj project = GetProject("Simple"); Assert.That(project.Guid, Is.EqualTo("{4A37C916-5AA3-4C12-B7A8-E5F878A5CDBA}")); Assert.That(project.AssemblyName, Is.EqualTo("MyProject")); Assert.That(project.Path, Is.EqualTo(file.FullName)); Assert.That(project.ReferencedAssemblyNames, Is.EqualTo(new[] { "System", "System.Core", "System.Xml.Linq", "System.Data.DataSetExtensions", "Microsoft.CSharp", "System.Data", "System.Xml" })); Assert.That(project.ReferencedProjectGuids, Is.EqualTo(new[] { "{99036BB6-4F97-4FCC-AF6C-0345A5089099}", "{69036BB3-4F97-4F9C-AF2C-0349A5049060}" })); }
/// <summary> /// 是否格式正常 /// </summary> /// <returns>是否格式正常</returns> public bool IsGoodFormat() { if (_isGoodFormat.HasValue) { return(_isGoodFormat.Value); } _isGoodFormat = false; var root = _xDocument.Root; if (root.Name.LocalName != CsProj.RootName) { ExceptionMessage = $".csproj 文件根节点名称不为 ${CsProj.RootName}"; return(false); } foreach (var packageReference in CsProj.GetPackageReferences(_xDocument)) { if (packageReference.Attribute(CsProj.IncludeAttribute) == null && packageReference.Attribute(CsProj.UpdateAttribute) == null) { ExceptionMessage = $"{CsProj.PackageReferenceName} 缺少 {CsProj.IncludeAttribute} 属性。"; return(false); } if (packageReference.Attribute(CsProj.VersionAttribute) == null && packageReference.Elements().FirstOrDefault(x => x.Name.LocalName == CsProj.VersionElementName) == null) { ExceptionMessage = $"{CsProj.PackageReferenceName} 缺少必要的版本信息。"; return(false); } } _isGoodFormat = true; return(true); }
public void RemoveDuplicateReferences() { CsProj.RemoveDuplicateReferences(); }
public override void ExecuteBuild() { // just calling this DesiredTargetVersion because TargetVersion and TargetedVersion get super confusing. string DesiredTargetVersion = this.ParseParamValue("TargetVersion", null); if (string.IsNullOrEmpty(DesiredTargetVersion)) { throw new AutomationException("-TargetVersion was not specified."); } CommandUtils.Log("Scanning for all csproj's..."); // Check for all csproj's in the engine dir DirectoryReference EngineDir = CommandUtils.EngineDirectory; // grab the targeted version., Regex FrameworkRegex = new Regex("<TargetFrameworkVersion>v(\\d\\.\\d\\.?\\d?)<\\/TargetFrameworkVersion>"); Regex PossibleAppConfigRegex = new Regex("<TargetFrameworkProfile>(.+)<\\/TargetFrameworkProfile>"); Regex AppConfigRegex = new Regex("<supportedRuntime version=\"v(\\d\\.\\d\\.?\\d?)\" sku=\"\\.NETFramework,Version=v(\\d\\.\\d\\.?\\d?),Profile=(.+)\"\\/>"); foreach (FileReference CsProj in DirectoryReference.EnumerateFiles(EngineDir, "*.csproj", SearchOption.AllDirectories)) { if (CsProj.ContainsName(new FileSystemName("ThirdParty"), EngineDir) || (CsProj.ContainsName(new FileSystemName("UE4TemplateProject"), EngineDir) && CsProj.GetFileName().Equals("ProjectTemplate.csproj"))) { continue; } // read in the file string Contents = File.ReadAllText(CsProj.FullName); Match m = FrameworkRegex.Match(Contents); if (m.Success) { string TargetedVersion = m.Groups[1].Value; // make sure we match, throw warning otherwise if (!DesiredTargetVersion.Equals(TargetedVersion, StringComparison.InvariantCultureIgnoreCase)) { CommandUtils.LogWarning("Targeted Framework version for project: {0} was not {1}! Targeted Version: {2}", CsProj, DesiredTargetVersion, TargetedVersion); } } // if we don't have a TargetFrameworkVersion, check for the existence of TargetFrameworkProfile. else { m = PossibleAppConfigRegex.Match(Contents); if (!m.Success) { CommandUtils.Log("No TargetFrameworkVersion or TargetFrameworkProfile found for project {0}, is it a mono project? If not, does it compile properly?", CsProj); continue; } // look for the app config FileReference AppConfigFile = FileReference.Combine(CsProj.Directory, "app.config"); string Profile = m.Groups[1].Value; if (!FileReference.Exists(AppConfigFile)) { CommandUtils.Log("Found TargetFrameworkProfile but no associated app.config containing the version for project {0}.", CsProj); continue; } // read in the app config Contents = File.ReadAllText(AppConfigFile.FullName); m = AppConfigRegex.Match(Contents); if (!m.Success) { CommandUtils.Log("Couldn't find a supportedRuntime match for the version in the app.config for project {0}.", CsProj); continue; } // Version1 is the one that appears right after supportedRuntime // Version2 is the one in the sku // ProfileString should match the TargetFrameworkProfile from the csproj string Version1String = m.Groups[1].Value; string Version2String = m.Groups[2].Value; string ProfileString = m.Groups[3].Value; // not sure how this is possible, but check for it anyway if (!ProfileString.Equals(Profile, StringComparison.InvariantCultureIgnoreCase)) { CommandUtils.LogWarning("The TargetFrameworkProfile in csproj {0} ({1}) doesn't match the sku in it's app.config ({2}).", CsProj, Profile, ProfileString); continue; } // if the version numbers don't match the app.config is probably corrupt. if (!Version1String.Equals(Version2String, StringComparison.InvariantCultureIgnoreCase)) { CommandUtils.LogWarning("The supportedRunTimeVersion ({0}) and the sku version ({1}) in the app.config for project {2} don't match.", Version1String, Version2String, CsProj); continue; } // make sure the versions match if (!(DesiredTargetVersion.Equals(Version1String, StringComparison.InvariantCultureIgnoreCase))) { CommandUtils.LogWarning("Targeted Framework version for project: {0} was not {1}! Targeted Version: {2}", CsProj, DesiredTargetVersion, Version1String); } } } }
public void TakesOnlyNameOfFullyQualifiedAssemblyName() { CsProj project = GetProject("FQAssemblyName"); CollectionAssert.Contains(project.ReferencedAssemblyNames, "NHibernate"); }
public void NoProjectReferencesDoesNotCauseNRE() { CsProj project = GetProject("NoProjectReferences"); CollectionAssert.AreEqual(new List <string>(), project.ReferencedProjectGuids); }
private void ConvertProjectHintPaths(CsProj project, string packagesDir, Mode mode = Mode.Convert) { var doc = LoadProject(project); var nav = doc.CreateNavigator(); var nugetHintPaths = nav.Select("//msb:ItemGroup/msb:Reference/msb:HintPath", nsMgr) .Cast <XPathNavigator>() .Where(e => e.Value.Contains(NuGetPackagesDirectoryName)) .ToList(); if (!nugetHintPaths.Any()) { return; } var firstIndex = nugetHintPaths.First().Value.IndexOf(NuGetPackagesDirectoryName, StringComparison.InvariantCultureIgnoreCase); if (nugetHintPaths.Any(e => e.Value.IndexOf(NuGetPackagesDirectoryName, StringComparison.InvariantCultureIgnoreCase) != firstIndex)) { log.WarnFormat("Project {0} does not have consistent HintPath values for nuget packages. Skipping.", project.Path); return; } log.InfoFormat("Converting nuget hint paths in project {0}.", project.Path); var originalPackageDir = nugetHintPaths.First().Value.Substring(0, firstIndex + NuGetPackagesDirectoryName.Length); string relativePackagesDir; if (mode == Mode.Convert) { relativePackagesDir = CalculateRelativePathToSlimjimPackages(packagesDir, project.Path); } else { var e = doc.SelectSingleNode("//msb:PropertyGroup/msb:SlimJimOriginalPackageDir", nsMgr); if (e == null) { log.WarnFormat("Not restoring hint paths to project {0} because it does not have property SlimJimOriginalPackageDir defined.", project.Path); return; } relativePackagesDir = e.InnerText; e.ParentNode.RemoveChild(e); } foreach (var hintPath in nugetHintPaths) { var modifiedHintPath = Path.Combine(relativePackagesDir, hintPath.Value.Substring(firstIndex + NuGetPackagesDirectoryName.Length)); log.DebugFormat("Change hint path from {0} to {1}", hintPath.Value, modifiedHintPath); var element = CreateElementWithInnerText(doc, "HintPath", modifiedHintPath); hintPath.ReplaceSelf(element.CreateNavigator()); } if (mode == Mode.Convert) { var firstPropertyGroup = doc.SelectSingleNode("//msb:PropertyGroup[1]", nsMgr); if (firstPropertyGroup.SelectSingleNode("msb:SlimJimOriginalPackageDir", nsMgr) == null) { firstPropertyGroup.AppendChild(CreateElementWithInnerText(doc, "SlimJimOriginalPackageDir", originalPackageDir)); } } doc.Save(project.Path); }
private void CanFindWeTcReferenceInCsProj() { CsProj csProj = new CsProj(@"C:\source\ItsMagic\ItsMagic.Tests\Approved\AuthorisationReadModel.Tests.csproj"); Assert.Equal(true, csProj.ContainsProjectReference(new CsProj(@"C:\source\Mercury\src\Platform\WorkerEngine.TestCommon\WorkerEngine.TestCommon.csproj"))); }
public void NoAssemblyName_ReturnsNull() { CsProj project = GetProject("BreaksThings"); Assert.IsNull(project); }
private void CanGetProjectGuid() { var csProj = new CsProj(@"C:\source\ItsMagic\ItsMagic.Tests\Approved\Logging.Client.csproj"); Assert.Equal("42A388A2-B797-4335-8A7D-8D748F58E7A3",csProj.Guid); }
public void IgnoresNestedReferences() { CsProj project = GetProject("ConvertedReference"); Assert.That(project.ReferencedAssemblyNames, Is.Not.Contains("log4net")); }
public void NoAssemblyName_ReturnsNull() { CsProj project = GetProject("BreaksThings"); Assert.That(project, Is.Null); }
public void NoProjectReferencesDoesNotCauseNRE() { CsProj project = GetProject("NoProjectReferences"); Assert.That(project.ReferencedProjectGuids, Is.Empty); }
public void TakesOnlyNameOfFullyQualifiedAssemblyName() { CsProj project = GetProject("FQAssemblyName"); Assert.That(project.ReferencedAssemblyNames, Contains.Item("NHibernate")); }