-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathProgram.cs
368 lines (319 loc) · 12.4 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
using System;
using System.IO;
using System.Linq;
using System.Xml;
using System.Reflection;
using System.Diagnostics;
using ConsoleColors;
class Program
{
static Assembly Dll = Assembly.GetExecutingAssembly();
static string ToolName = Dll.GetName().Name;
static string ToolVersion = FileVersionInfo.GetVersionInfo(Dll.Location).ProductVersion;
static string Home = Environment.GetEnvironmentVariable("HOME");
static string ConfigDir = $"{Home}/.netpkg-tool";
static int Width = 64;
static Shell.NET.Bash Bash = new Shell.NET.Bash();
static string Csproj;
static string ProjectDir;
static string Destination;
static string DllName;
static string AppName;
static string DotNetVersion;
static string Here = AppDomain.CurrentDomain.BaseDirectory;
static string[] Args;
static bool Verbose = false;
static bool SkipRestore = false;
static bool CustomAppName = false;
static bool SelfContainedDeployment = false;
static bool KeepTempFiles = false;
static string Extension = ".AppImage";
static void Main(string[] args)
{
SayHello();
ParseArgs(args);
CheckPaths(args);
FindCsproj(args[0]);
SayTask(ProjectDir, $"{Destination}/{AppName}");
if (!SkipRestore) RestoreProject();
ComileProject();
TransferFiles();
RunAppImageTool();
if (!KeepTempFiles) DeleteTempFiles();
SayFinished($"New AppImage created at {Destination}/{AppName}");
SayBye();
}
static void CheckPaths(string[] args)
{
if (args.Length < 2 || !Directory.Exists(args[0]) && !Directory.Exists(args[1]))
{
ExitWithError("You must specify a valid .NET project AND Destination folder.", 6);
}
if (Directory.Exists(args[0]) && !Directory.Exists(args[1]))
{
if (Bash.Command($"mkdir -p {args[1]}").ExitCode != 0)
ExitWithError($"{args[1]} is not a valid folder", 7);
}
if (!Directory.Exists(args[0]) && Directory.Exists(args[1]))
{
if (Bash.Command($"mkdir -p {args[0]}").ExitCode != 0)
ExitWithError($"{args[0]} is not a valid folder", 8);
}
ProjectDir = GetRelativePath(args[0]);
Destination = GetRelativePath(args[1]);
}
static void ParseArgs(string[] args)
{
Args = args;
if (args == null || args.Length == 0)
HelpMenu();
if (args[0] == "--clear-log")
ClearLogs();
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "-v" || args[i] == "--verbose")
{
Verbose = true;
}
else if (args[i] == "-c" || args[i] == "--compile")
{
SkipRestore = true;
}
else if (args[i] == "-n" || args[i] == "--name")
{
CustomAppName = true;
AppName = args[i + 1];
}
else if (args[i] == "-s" || args[i] == "--scd")
{
SelfContainedDeployment = true;
}
else if (args[i] == "-k" || args[i] == "--keep")
{
KeepTempFiles = true;
}
else if (args[i] == "-h" || args[i] == "--help")
{
HelpMenu();
}
else if (args[i] == "--noext")
{
Extension = "";
}
}
}
static void FindCsproj(string project)
{
var location = Bash.Command($"find {project} -maxdepth 1 -name '*.csproj'", redirect: true).Lines;
if (location == null || location[0] == "")
ExitWithError($"No .csproj found in {GetRelativePath(project)}", 10);
if (location.Length > 1)
ExitWithError($"More than one .csproj found in {GetRelativePath(project)}", 11);
var folderSplit = location[0].Split('/');
Csproj = folderSplit[folderSplit.Length - 1];
ProjectDir = GetRelativePath(project);
DotNetVersion = GetCoreVersion();
var nameSplit = Csproj.Split('.');
DllName = string.Join('.', nameSplit.Take(nameSplit.Length - 1));
if (!CustomAppName)
AppName = $"{DllName}{Extension}";
if (SingleRuntimeIdentifier() && !SelfContainedDeployment)
{
SelfContainedDeployment = true;
Printer.WriteLine(
$"{Clr.Yellow}Caution: Single runtime identifier detected. Using --scd{Clr.Default}");
}
}
static string GetCoreVersion()
{
var path = GetAbsolutePath($"{ProjectDir}/{Csproj}");
var node = "/Project/PropertyGroup/TargetFramework";
var xml = new XmlDocument();
xml.LoadXml(File.ReadAllText(path));
return xml.DocumentElement.SelectSingleNode(node).InnerText;
}
static bool SingleRuntimeIdentifier()
{
var path = GetAbsolutePath($"{ProjectDir}/{Csproj}");
var node = "/Project/PropertyGroup/RuntimeIdentifier";
var xml = new XmlDocument();
xml.LoadXml(File.ReadAllText(path));
return xml.DocumentElement.SelectSingleNode(node) != null;
}
static void RestoreProject()
{
if (Verbose)
{
Console.WriteLine("Restoring .NET Core project dependencies...");
Bash.Command($"cd {ProjectDir} && dotnet restore", redirect: false);
}
else
{
Console.Write("Restoring .NET Core project dependencies...");
Bash.Command($"cd {ProjectDir} && dotnet restore", redirect: true);
}
CheckCommandOutput(errorCode: 20);
}
static void ComileProject()
{
string cmd;
if (SelfContainedDeployment)
cmd = $"cd {ProjectDir} && dotnet publish -c Release -r linux-x64 --no-restore";
else
cmd = $"cd {ProjectDir} && dotnet publish -c Release --no-restore";
if (Verbose)
{
Console.WriteLine("Compiling .NET Core project...");
Bash.Command(cmd, redirect: false);
}
else
{
Console.Write("Compiling .NET Core project...");
Bash.Command(cmd, redirect: true);
}
CheckCommandOutput(errorCode: 21);
}
static void TransferFiles()
{
var path = $"{Here}/file-transfer.sh";
string cmd;
if (SelfContainedDeployment)
cmd = $"{path} {ProjectDir} {DllName} {AppName} {DotNetVersion} {ToolVersion} true";
else
cmd = $"{path} {ProjectDir} {DllName} {AppName} {DotNetVersion} {ToolVersion}";
Console.Write($"Creating app directory at /tmp/{AppName}.temp...");
Bash.Command(cmd, redirect: true);
CheckCommandOutput(errorCode: 22);
}
static void RunAppImageTool()
{
var appimgtool = $"{Here}/appimagetool/AppRun";
var cmd = $"{appimgtool} -n /tmp/{AppName}.temp {Destination}/{AppName}";
if (Verbose)
{
Console.WriteLine($"Compressing app directory into an AppImage...");
Bash.Command(cmd, redirect: false);
}
else
{
Console.Write($"Compressing app directory into an AppImage...");
Bash.Command(cmd, redirect: true);
}
CheckCommandOutput(errorCode: 23);
}
static void DeleteTempFiles()
{
Console.Write("Deleting temporary files...");
Bash.Rm($"/tmp/{DllName}.temp", "-rf");
CheckCommandOutput(24);
}
static void SayHello()
{
var title = $" {ToolName} v{ToolVersion} ";
var newWidth = Width - title.Length;
var leftBar = new String('-', newWidth / 2);
string rightBar;
if (newWidth % 2 > 0)
rightBar = new String('-', newWidth / 2 + 1);
else
rightBar = new String('-', newWidth / 2);
Printer.WriteLine($"\n{leftBar}{Clr.Cyan}{Frmt.Bold}{title}{Reset.Code}{rightBar}");
}
static void HelpMenu()
{
Printer.WriteLine(
$"\n {Frmt.Bold}{Clr.Cyan}Usage:{Reset.Code}\n"
+ $" {Frmt.Bold}netpkg-tool{Frmt.UnBold} "
+ $"[{Frmt.Underline}Project{Reset.Code}] "
+ $"[{Frmt.Underline}Destination{Reset.Code}] "
+ $"[{Frmt.Underline}Flags{Reset.Code}]\n\n"
+ $" {Frmt.Bold}{Clr.Cyan}Flags:{Reset.Code}\n"
+ @" --verbose or -v: Verbose output\n"
+ @" --compile or -c: Skip restoring dependencies\n"
+ @" --name or -n: Set ouput file to a custom name\n"
+ @" --scd or -s: Self-Contained Deployment (SCD)\n"
+ @" --keep or -k: Keep /tmp/{AppName}.temp directory\n"
+ @" --help or -h: Help menu (this page)\n"
+ @" --clear-log: Delete error log at ~/.netpkg-tool\n\n"
+ @" More information & source code available on github:\n"
+ @" https://github.com/phil-harmoniq/netpkg-tool\n"
+ @" Copyright (c) 2017 - MIT License\n"
);
SayBye();
Environment.Exit(0);
}
static void ClearLogs()
{
Console.Write($"Clear error log at {GetRelativePath(ConfigDir)}/error.log...");
if (File.Exists($"{ConfigDir}/error.log"))
{
Bash.Rm($"{ConfigDir}/error.log");
CheckCommandOutput(errorCode: 5);
}
else
{
SayCaution();
Printer.WriteLine($"{Clr.Yellow}Error log file already removed.{Clr.Default}");
}
SayBye();
Environment.Exit(0);
}
static void ExitWithError(string message, int code)
{
if (Verbose)
{
WriteToErrorLog("[Error message was written to verbose output]", code);
}
else
{
Printer.WriteLine($"{Clr.Red}{message}{Clr.Default}");
WriteToErrorLog(message, code);
}
SayBye();
Environment.Exit(code);
}
static void WriteToErrorLog(string message, int code)
{
if (!Directory.Exists(ConfigDir))
Directory.CreateDirectory(ConfigDir);
using (var log = new StreamWriter($"{ConfigDir}/error.log", true))
{
var now = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss");
var dir = Directory.GetCurrentDirectory();
log.WriteLine($"{new string('-', Width)}");
log.WriteLine($"{GetRelativePath(dir)}$ netpkg-tool {string.Join(' ', Args)}");
log.WriteLine($"Errored with code {code} - ({now}):\n");
log.WriteLine(message.TrimEnd('\n'));
log.WriteLine($"{new string('-', Width)}");
}
}
/// <param name="errorCode">Desired error code if the command didn't run properly</param>
static void CheckCommandOutput(int errorCode = 1)
{
if (Bash.ExitCode != 0)
{
SayFail();
if (string.IsNullOrEmpty(Bash.ErrorMsg))
ExitWithError(Bash.Output, errorCode);
else
ExitWithError(Bash.ErrorMsg, errorCode);
}
SayPass();
}
static string GetRelativePath(string path) =>
Bash.Command($"cd {path} && dirs -0", redirect: true).Output;
static string GetAbsolutePath(string path) =>
Bash.Command($"readlink -f {path}", redirect: true).Output;
static void SayBye() =>
Console.WriteLine(new String('-', Width) + "\n");
static void SayTask(string project, string Destination) =>
Printer.WriteLine($"{Clr.Cyan}{project} => {Destination}{Clr.Default}");
static void SayFinished(string message) =>
Printer.WriteLine($"{Clr.Green}{message}{Clr.Default}");
static void SayPass() =>
Printer.WriteLine($" {Frmt.Bold}[ {Clr.Green}PASS{Clr.Default} ]{Reset.Code}");
static void SayCaution() =>
Printer.WriteLine($" {Frmt.Bold}[ {Clr.Yellow}PASS{Clr.Default} ]{Reset.Code}");
static void SayFail() =>
Printer.WriteLine($" {Frmt.Bold}[ {Clr.Red}FAIL{Clr.Default} ]{Reset.Code}");
}