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

Commit 9e05986

Browse files
trurl123kunga
authored andcommitted
add pack command (#42)
* add pack command * fix after merge * pack for default build config * more logging and remove ssh restriction * return ssh restriction for gitlab * simplify code and fix wordings * skip NugetRestore for dotnet * show nuget errors * more desription * throw exception from GetProjectFilename * rename function * use NuGetHelper for cm pack
1 parent 0b4a4db commit 9e05986

13 files changed

+301
-38
lines changed

Commands/BuildDeps.cs

+4-4
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;
@@ -103,15 +103,15 @@ public static void TryNugetRestore(List<Dep> modulesToUpdate, ModuleBuilder buil
103103
ConsoleWriter.ResetProgress();
104104
try
105105
{
106-
var nuget = NuGetHelper.FindNuGet();
107-
if (nuget == null)
106+
var nugetRunCommand = NuGetHelper.GetNugetRunCommand();
107+
if (nugetRunCommand == null)
108108
return;
109109

110110
var uniqueDeps = modulesToUpdate.GroupBy(d => d.Name).Select(g => g.First()).ToList();
111111
Parallel.ForEach(uniqueDeps, Helper.ParallelOptions, dep =>
112112
{
113113
ConsoleWriter.WriteProgress($"{dep.Name,-30} nuget restoring");
114-
builder.NugetRestore(dep, nuget);
114+
builder.NugetRestore(dep, nugetRunCommand);
115115
ConsoleWriter.SaveToProcessedModules(dep.Name);
116116
});
117117
}

Commands/Commands.csproj

+1
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
<ItemGroup>
6969
<Compile Include="AnalyzerAdd.cs" />
7070
<Compile Include="AnalyzerCommand.cs" />
71+
<Compile Include="PackCommand.cs" />
7172
<Compile Include="ReadmeGenerator.cs" />
7273
<Compile Include="RefAdd.cs" />
7374
<Compile Include="Build.cs" />

Commands/CommandsList.cs

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System.Collections.Generic;
1+
using System.Collections.Generic;
22
using System.Linq;
33
using Common;
44

@@ -30,7 +30,8 @@ public static class CommandsList
3030
{"update", new Update()},
3131
{"convert-spec", new ConvertSpec()},
3232
{"reinstall", new ReInstall()},
33-
{"complete", new CompleteCommand()}
33+
{"complete", new CompleteCommand()},
34+
{"pack", new PackCommand()}
3435
};
3536

3637
public static void Print()

Commands/ModuleCommand.cs

+2-3
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,8 @@ private int ChangeModule()
7070

7171
public static int AddModule(Package package, string moduleName, string pushUrl, string fetchUrl)
7272
{
73-
if (fetchUrl.StartsWith("https://"))
74-
throw new CementException("HTTPS url not allowed. You should use SSH url.");
75-
73+
if (fetchUrl.StartsWith("https://git.skbkontur.ru/"))
74+
throw new CementException("HTTPS url not allowed for gitlab. You should use SSH url.");
7675
using (var tempDir = new TempDirectory())
7776
{
7877
var repo = new GitRepository("modules_git", tempDir.Path, Log);

Commands/PackCommand.cs

+96
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
using System;
2+
using System.IO;
3+
using System.Linq;
4+
using Common;
5+
using Common.YamlParsers;
6+
7+
namespace Commands
8+
{
9+
public class PackCommand : Command
10+
{
11+
private string project;
12+
private string configuration;
13+
private BuildSettings buildSettings;
14+
15+
public PackCommand() : base(new CommandSettings
16+
{
17+
LogPerfix = "PACK",
18+
LogFileName = null,
19+
MeasureElapsedTime = false,
20+
RequireModuleYaml = true,
21+
Location = CommandSettings.CommandLocation.InsideModuleDirectory
22+
})
23+
{
24+
}
25+
26+
protected override int Execute()
27+
{
28+
var modulePath = Helper.GetModuleDirectory(Directory.GetCurrentDirectory());
29+
var moduleName = Path.GetFileName(modulePath);
30+
project = Yaml.GetProjectFileName(project, moduleName);
31+
configuration = configuration ?? "full-build";
32+
33+
var buildData = Yaml.BuildParser(moduleName).Get(configuration).FirstOrDefault(t => !t.Target.IsFakeTarget());
34+
35+
var projectPath = Path.GetFullPath(project);
36+
var csproj = new ProjectFile(projectPath);
37+
var deps = new DepsParser(modulePath).Get(configuration);
38+
ConsoleWriter.WriteInfo("patching csproj");
39+
var patchedDocument = csproj.CreateCsProjWithNugetReferences(deps.Deps, modulePath);
40+
var backupFileName = Path.Combine(Path.GetDirectoryName(projectPath) ?? "", "backup." + Path.GetFileName(projectPath));
41+
if (File.Exists(backupFileName))
42+
File.Delete(backupFileName);
43+
File.Move(projectPath, backupFileName);
44+
try
45+
{
46+
XmlDocumentHelper.Save(patchedDocument, projectPath, "\n");
47+
var moduleBuilder = new ModuleBuilder(Log, buildSettings);
48+
ConsoleWriter.WriteInfo("start pack");
49+
moduleBuilder.DotnetPack(modulePath, projectPath, buildData?.Configuration ?? "Release");
50+
}
51+
finally
52+
{
53+
if (File.Exists(projectPath))
54+
File.Delete(projectPath);
55+
File.Move(backupFileName, projectPath);
56+
}
57+
return 0;
58+
}
59+
60+
protected override void ParseArgs(string[] args)
61+
{
62+
var parsedArgs = ArgumentParser.ParsePack(args);
63+
64+
//dep = new Dep((string)parsedArgs["module"]);
65+
if (parsedArgs["configuration"] != null)
66+
configuration = (string)parsedArgs["configuration"];
67+
buildSettings = new BuildSettings
68+
{
69+
ShowAllWarnings = (bool)parsedArgs["warnings"],
70+
ShowObsoleteWarnings = (bool)parsedArgs["obsolete"],
71+
ShowOutput = (bool)parsedArgs["verbose"],
72+
ShowProgress = (bool)parsedArgs["progress"],
73+
ShowWarningsSummary = true
74+
};
75+
76+
project = (string)parsedArgs["project"];
77+
if (!project.EndsWith(".csproj"))
78+
throw new BadArgumentException(project + " is not csproj file");
79+
}
80+
81+
public override string HelpMessage => @"
82+
Pack project to nuget package. Replace file references to package references in csproj file and run 'dotnet pack' command.
83+
Allows to publish nuget package to use outside of cement.
84+
85+
Usage:
86+
cm pack [-v|--verbose|-w|-W|--warnings] [-p|--progress] [-c configName] <project-file>
87+
-c/--configuration - build package for specific configuration
88+
89+
-v/--verbose - show full msbuild output
90+
-w/--warnings - show warnings
91+
-W - show only obsolete warnings
92+
93+
-p/--progress - show msbuild output in one line
94+
";
95+
}
96+
}

Commands/RefAdd.cs

+2-15
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System;
1+
using System;
22
using System.IO;
33
using System.Linq;
44
using System.Xml;
@@ -46,20 +46,7 @@ protected override int Execute()
4646
var currentModuleDirectory = Helper.GetModuleDirectory(Directory.GetCurrentDirectory());
4747
var currentModule = Path.GetFileName(currentModuleDirectory);
4848

49-
if (!File.Exists(project))
50-
{
51-
var all = Yaml.GetCsprojsList(currentModule);
52-
var maybe = all.FirstOrDefault(f =>
53-
string.Equals(Path.GetFileName(f), project, StringComparison.CurrentCultureIgnoreCase));
54-
if (maybe != null)
55-
project = maybe;
56-
}
57-
58-
if (!File.Exists(project))
59-
{
60-
ConsoleWriter.WriteError($"Project file '{project}' does not exist.");
61-
return -1;
62-
}
49+
project = Yaml.GetProjectFileName(project, currentModule);
6350

6451
var moduleToInsert = Helper.TryFixModuleCase(dep.Name);
6552
dep = new Dep(moduleToInsert, dep.Treeish, dep.Configuration);

Common/ArgumentParser.cs

+29
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,35 @@ public static Dictionary<string, object> ParseRefAdd(string[] args)
8989
return parsedArguments;
9090
}
9191

92+
public static Dictionary<string, object> ParsePack(string[] args)
93+
{
94+
var parsedArguments = new Dictionary<string, object>
95+
{
96+
{"configuration", null},
97+
{"project", null},
98+
{"warnings", false},
99+
{"obsolete", false},
100+
{"verbose", false},
101+
{"progress", false},
102+
};
103+
var parser = new OptionSet
104+
{
105+
{"c|configuration=", conf => parsedArguments["configuration"] = conf},
106+
{"w|warnings", f => parsedArguments["warnings"] = true},
107+
{"W", f => parsedArguments["obsolete"] = true},
108+
{"v|verbose", v => parsedArguments["verbose"] = true},
109+
{"p|progress", p => parsedArguments["progress"] = true},
110+
};
111+
args = parser.Parse(args).ToArray();
112+
113+
if (args.Length != 2 || args[0] != "pack")
114+
throw new BadArgumentException("Wrong usage of command.\nUsage: cm pack [-c|--configuration <config-name>] <project-file>");
115+
116+
parsedArguments["project"] = args[1];
117+
118+
return parsedArguments;
119+
}
120+
92121
public static Dictionary<string, object> ParseAnalyzerAdd(string[] args)
93122
{
94123
var parsedArguments = new Dictionary<string, object>

Common/ModuleBuilder.cs

+20-8
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,18 @@ public ModuleBuilder(ILog log, BuildSettings buildSettings)
2121
VsDevHelper.ReplaceVariablesToVs();
2222
}
2323

24-
public void NugetRestore(Dep dep, string nuGetPath)
24+
public void DotnetPack(string directory, string projectFileName, string buildConfiguration)
25+
{
26+
var runner = PrepareShellRunner();
27+
var exitCode = runner.RunInDirectory(directory, $"dotnet pack \\\"{projectFileName}\\\" -c {buildConfiguration}");
28+
ConsoleWriter.Write(runner.Output);
29+
if (exitCode != 0)
30+
{
31+
log.Warn($"Failed to build nuget package {projectFileName}. \nOutput: \n{runner.Output} \nError: \n{runner.Errors} \nExit code: {exitCode}");
32+
}
33+
}
34+
35+
public void NugetRestore(Dep dep, string nugetRunCommand)
2536
{
2637
if (Yaml.Exists(dep.Name))
2738
{
@@ -30,21 +41,22 @@ public void NugetRestore(Dep dep, string nuGetPath)
3041
{
3142
if (buildSection.Target == null || !buildSection.Target.EndsWith(".sln"))
3243
continue;
33-
var target = Path.Combine(Helper.CurrentWorkspace, dep.Name, buildSection.Target);
34-
RunNugetRestore(target, nuGetPath);
44+
if (buildSection.Tool.Name != "dotnet")
45+
{
46+
var target = Path.Combine(Helper.CurrentWorkspace, dep.Name, buildSection.Target);
47+
RunNugetRestore(target, nugetRunCommand);
48+
}
3549
}
3650
}
3751
else
38-
RunNugetRestore(Path.Combine(Helper.CurrentWorkspace, dep.Name, "build.cmd"), nuGetPath);
52+
RunNugetRestore(Path.Combine(Helper.CurrentWorkspace, dep.Name, "build.cmd"), nugetRunCommand);
3953
}
4054

41-
private void RunNugetRestore(string buildFile, string nuGetPath)
55+
private void RunNugetRestore(string buildFile, string nugetRunCommand)
4256
{
4357
var buildFolder = Directory.GetParent(buildFile).FullName;
4458
var target = buildFile.EndsWith(".sln") ? Path.GetFileName(buildFile) : "";
45-
var command = $"\"{nuGetPath}\" restore {target} -Verbosity {(buildSettings.ShowOutput ? "normal" : "quiet")}";
46-
if (Helper.OsIsUnix())
47-
command = $"mono {command}";
59+
var command = $"{nugetRunCommand} restore {target} -Verbosity {(buildSettings.ShowOutput ? "normal" : "quiet")}";
4860
log.Info(command);
4961

5062
var runner = PrepareShellRunner();

Common/NuGetHelper.cs

+14-3
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,24 @@
1-
using System.IO;
1+
using System.IO;
22
using log4net;
33

44
namespace Common
55
{
66
public static class NuGetHelper
77
{
88
private static readonly ILog Log = LogManager.GetLogger(typeof(NuGetHelper));
9-
10-
public static string FindNuGet()
9+
10+
public static string GetNugetRunCommand()
11+
{
12+
var nuGetPath = GetNuGetPath();
13+
if (nuGetPath == null)
14+
return null;
15+
var nugetCommand = $"\"{nuGetPath}\"";
16+
if (Helper.OsIsUnix())
17+
nugetCommand = $"mono {nugetCommand}";
18+
return nugetCommand;
19+
}
20+
21+
private static string GetNuGetPath()
1122
{
1223
var nuget = Path.Combine(Helper.GetCementInstallDirectory(), "dotnet", "NuGet.exe");
1324
if (!File.Exists(nuget))

0 commit comments

Comments
 (0)