Skip to content
This repository was archived by the owner on Sep 30, 2023. It is now read-only.

Commit 5c55d6c

Browse files
trurl123kunga
authored andcommitted
Add nuget packages to new csproj (#43)
1 parent e5646d1 commit 5c55d6c

File tree

3 files changed

+76
-16
lines changed

3 files changed

+76
-16
lines changed

Commands/RefAdd.cs

+2-5
Original file line numberDiff line numberDiff line change
@@ -132,21 +132,18 @@ private void CheckBranch()
132132
private void AddModuleToCsproj(InstallData installData)
133133
{
134134
var projectPath = Path.GetFullPath(project);
135+
var csproj = new ProjectFile(projectPath);
135136

136137
try
137138
{
138-
var currentModuleDirectory = Helper.GetModuleDirectory(Directory.GetCurrentDirectory());
139-
var packagesDirectory = Path.Combine(currentModuleDirectory, "packages");
140-
new NuGetPackageHepler(Log).InstallPackages(installData.NuGetPackages, packagesDirectory, projectPath);
139+
csproj.InstallNuGetPackages(installData.NuGetPackages);
141140
}
142141
catch (Exception e)
143142
{
144143
ConsoleWriter.WriteWarning($"Installation of NuGet packages failed: {e.InnerException?.Message ?? e.Message}");
145144
Log.Error("Installation of NuGet packages failed:", e);
146145
}
147146

148-
var csproj = new ProjectFile(projectPath);
149-
150147
foreach (var buildItem in installData.BuildFiles)
151148
{
152149
var refName = Path.GetFileNameWithoutExtension(buildItem);

Common/NuGetPackageHepler.cs

+7-7
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System;
1+
using System;
22
using System.Collections.Generic;
33
using System.IO;
44
using System.Linq;
@@ -32,28 +32,28 @@ public NuGetPackageHepler(ILog log)
3232
private class NuGetProject
3333
{
3434
private readonly List<string> packagesList;
35+
private readonly ProjectFile projectFile;
3536
private readonly Console logger;
3637
private readonly MSBuildNuGetProject project;
3738
private readonly ConsoleProjectContext projectContext;
3839
private readonly MSBuildProjectSystem projectSystem;
3940
private readonly List<SourceRepository> repositories;
4041
private readonly HashSet<PackageIdentity> installedPackages;
41-
private readonly string originalLineEndings;
4242
private readonly ILog log;
4343

44-
public NuGetProject(List<string> packagesList, string packagesPath, string projectFilePath, ILog log)
44+
public NuGetProject(List<string> packagesList, string packagesPath, ProjectFile projectFile, ILog log)
4545
{
4646
this.log = log;
4747
this.packagesList = packagesList;
48+
this.projectFile = projectFile;
4849
installedPackages = new HashSet<PackageIdentity>();
4950
var sourceProvider = new PackageSourceProvider(Settings.LoadDefaultSettings(null));
5051
var sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(sourceProvider);
5152
repositories = sourceProvider.LoadPackageSources().Select(sourceRepositoryProvider.CreateRepository)
5253
.ToList();
5354
logger = new Console();
5455

55-
var projectFileContent = File.ReadAllText(projectFilePath);
56-
originalLineEndings = projectFileContent.Contains("\r\n") ? "\r\n" : "\n";
56+
var projectFilePath = projectFile.FilePath;
5757

5858
var msbuildDirectory =
5959
Path.GetDirectoryName(ModuleBuilderHelper.FindMsBuild(null, "Cement NuGet Package Installer"));
@@ -85,7 +85,7 @@ public void Install()
8585
contentLines[0] = contentLines[0].Replace("utf-16", "utf-8");
8686
File.WriteAllText(
8787
projectSystem.ProjectFileFullPath,
88-
string.Join(originalLineEndings, contentLines),
88+
string.Join(projectFile.LineEndings, contentLines),
8989
new UTF8Encoding(true));
9090
}
9191

@@ -154,7 +154,7 @@ private static PackageIdentity ParsePackage(string packageName)
154154
}
155155
}
156156

157-
public void InstallPackages(List<string> packagesList, string packagesPath, string projectFilePath)
157+
public void InstallPackages(List<string> packagesList, string packagesPath, ProjectFile projectFilePath)
158158
{
159159
new NuGetProject(packagesList, packagesPath, projectFilePath, log).Install();
160160
}

Common/ProjectFile.cs

+67-4
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,19 @@ namespace Common
99
{
1010
public class ProjectFile
1111
{
12-
private readonly string lineEndings;
12+
public readonly string LineEndings;
1313

1414
public readonly string FilePath;
1515
public readonly XmlDocument Document;
16-
private bool newFormat;
16+
private readonly bool newFormat;
1717
private ILog log;
1818

1919
public ProjectFile(string csprojFilePath)
2020
{
2121
var fileContent = File.ReadAllText(csprojFilePath);
2222
log = LogManager.GetLogger(typeof(ProjectFile));
2323

24-
lineEndings = fileContent.Contains("\r\n") ? "\r\n" : "\n";
24+
LineEndings = fileContent.Contains("\r\n") ? "\r\n" : "\n";
2525
FilePath = csprojFilePath;
2626
Document = XmlDocumentHelper.Create(fileContent);
2727
newFormat = !string.IsNullOrEmpty(Document.DocumentElement?.GetAttribute("Sdk"));
@@ -100,6 +100,13 @@ public XmlNode CreateReference(string refName, string refPath)
100100

101101
return elementToInsert;
102102
}
103+
public XmlNode CreateNuGetReference(string refName, string version)
104+
{
105+
var elementToInsert = Document.CreateElement("PackageReference", Document.DocumentElement.NamespaceURI);
106+
elementToInsert.SetAttribute("Include", refName);
107+
elementToInsert.SetAttribute("Version", version);
108+
return elementToInsert;
109+
}
103110

104111
public void AddRef(string refName, string refPath)
105112
{
@@ -200,7 +207,7 @@ public XmlDocument CreateCsProjWithNugetReferences(List<Dep> deps, string module
200207

201208
public void Save()
202209
{
203-
XmlDocumentHelper.Save(Document, FilePath, lineEndings);
210+
XmlDocumentHelper.Save(Document, FilePath, LineEndings);
204211
}
205212

206213
private XmlNode CreateAnalyzerGroup()
@@ -221,6 +228,12 @@ private bool IsReferenceGroup(XmlNode xmlNode)
221228
.Cast<XmlNode>()
222229
.Any(childNode => childNode.Name == "Reference");
223230
}
231+
private bool IsPackageReferenceGroup(XmlNode xmlNode)
232+
{
233+
return xmlNode.ChildNodes
234+
.Cast<XmlNode>()
235+
.Any(childNode => childNode.Name == "PackageReference");
236+
}
224237

225238
private XmlNode CreateItemGroup()
226239
{
@@ -239,5 +252,55 @@ private XmlNode CreateItemGroup()
239252

240253
return itemGroup;
241254
}
255+
256+
public void InstallNuGetPackages(List<string> nuGetPackages)
257+
{
258+
if (newFormat)
259+
{
260+
foreach (var package in nuGetPackages)
261+
{
262+
var splitted = package.Split('/');
263+
if (splitted.Length != 2)
264+
{
265+
log.Error("package version is not defined: " + package);
266+
}
267+
else
268+
{
269+
InstallNuGetPackage(splitted[0], splitted[1]);
270+
}
271+
}
272+
}
273+
else
274+
{
275+
var currentModuleDirectory = Helper.GetModuleDirectory(Directory.GetCurrentDirectory());
276+
var packagesDirectory = Path.Combine(currentModuleDirectory, "packages");
277+
new NuGetPackageHepler(log).InstallPackages(nuGetPackages, packagesDirectory, this);
278+
}
279+
}
280+
281+
private void InstallNuGetPackage(string packageName, string packageVersion)
282+
{
283+
try
284+
{
285+
var referenceGroup = Document
286+
.GetElementsByTagName("ItemGroup")
287+
.Cast<XmlNode>()
288+
.FirstOrDefault(IsPackageReferenceGroup) ?? CreateItemGroup();
289+
var packageNode = Document.SelectNodes("*/ItemGroup/PackageReference")?.Cast<XmlElement>()
290+
.FirstOrDefault(el => el.Attributes["Include", Document.DocumentElement.NamespaceURI].Value.Equals(packageName, StringComparison.InvariantCultureIgnoreCase));
291+
if (packageNode == null)
292+
referenceGroup?.AppendChild(CreateNuGetReference(packageName, packageVersion));
293+
else
294+
{
295+
packageNode.ParentNode?.RemoveChild(packageNode);
296+
packageNode.SetAttribute("Version", packageVersion);
297+
referenceGroup?.AppendChild(packageNode);
298+
}
299+
}
300+
catch (Exception e)
301+
{
302+
throw new Exception($"Failed to add ref {packageName} to {FilePath}", e);
303+
}
304+
}
242305
}
243306
}

0 commit comments

Comments
 (0)