-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathClassUtils.cs
492 lines (459 loc) · 20 KB
/
ClassUtils.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
using System;
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Security.Principal;
using System.Windows.Forms;
namespace GitForce
{
/// <summary>
/// Contains various utility functions
/// </summary>
public static class ClassUtils
{
/// <summary>
/// Set of environment variables used by the execution environment
/// </summary>
private static readonly Dictionary<string, string> Env = new Dictionary<string, string>();
/// <summary>
/// Adds an environment variable for the Run method
/// </summary>
public static void AddEnvar(string name, string value)
{
if (Env.ContainsKey(name))
Env[name] = value;
else
Env.Add(name, value);
}
/// <summary>
/// Returns the value of a specific environment variable or empty string if it's not defined
/// </summary>
public static string GetEnvar(string name)
{
return Env.ContainsKey(name) ? Env[name] : string.Empty;
}
/// <summary>
/// Returns a set of environment variables registered for this execution environment
/// </summary>
public static Dictionary<string, string> GetEnvars()
{
return Env;
}
/// <summary>
/// Writes binary resource to a temporary file
/// </summary>
public static string WriteResourceToFile(string pathName, string fileName, byte[] buffer)
{
string path = Path.Combine(pathName, fileName);
try
{
using (var sw = new BinaryWriter(File.Open(path, FileMode.Create)))
{
sw.Write(buffer);
}
}
catch (Exception ex)
{
App.PrintLogMessage(ex.Message, MessageType.Error);
}
return path;
}
/// <summary>
/// Returns true if the app is running on Mono (Linux), false if it is Windows
/// </summary>
public static bool IsMono()
{
return Type.GetType("Mono.Runtime") != null;
}
/// <summary>
/// Returns true is the application is run at the elevated privilege level
/// </summary>
public static bool IsAdmin()
{
bool isElevated;
using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
{
WindowsPrincipal principal = new WindowsPrincipal(identity);
isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
return isElevated;
}
/// <summary>
/// Open a command prompt at the specific directory
/// </summary>
public static void CommandPromptHere(string where)
{
try
{
Directory.SetCurrentDirectory(where);
App.PrintStatusMessage("Command prompt at " + where, MessageType.General);
Process proc = new Process();
proc.StartInfo.UseShellExecute = false;
// Add all environment variables listed
foreach (var envar in Env)
proc.StartInfo.EnvironmentVariables.Add(envar.Key, envar.Value);
if (IsMono())
{
// Opening an command terminal is platform-specific and depends on the desktop environment which you use,
// and which terminal application is installed
if (File.Exists(@"/usr/bin/gnome-terminal"))
{
proc.StartInfo.FileName = @"/usr/bin/gnome-terminal";
proc.StartInfo.Arguments = "--working-directory=" + where;
}
else if (File.Exists(@"/usr/bin/konsole"))
{
proc.StartInfo.FileName = @"/usr/bin/konsole";
proc.StartInfo.Arguments = "--workdir " + where;
}
else if (File.Exists(@"/usr/bin/xterm"))
{
proc.StartInfo.FileName = @"/usr/bin/xterm";
proc.StartInfo.Arguments = "-e \"cd " + where + "; bash\"";
}
else throw new Exception("Unable to identify a terminal shell program for this distro. Please report this issue - thank you!");
}
else
{
proc.StartInfo.FileName = "cmd.exe";
}
proc.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Command Prompt Here error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Open a file browser/Explorer at the specific directory, optionally selecting a file
/// </summary>
public static void ExplorerHere(string where, string selFile)
{
try
{
App.PrintStatusMessage("Opening a file browser at " + where, MessageType.General);
if (IsMono())
{
// Opening an "Explorer" is platform-specific and depends on the desktop environment which you use,
// each desktop environment comes with its own default file- manager.
// Ubuntu: nautilus
// Cinnamon: nemo
// Mate: caja
// xfce: thunar
// KDE: dolphin
if (File.Exists(@"/usr/bin/nautilus")) Process.Start(@"/usr/bin/nautilus", "--browser " + where);
else if (File.Exists(@"/usr/bin/nemo")) Process.Start(@"/usr/bin/nemo", where);
else if (File.Exists(@"/usr/bin/caja")) Process.Start(@"/usr/bin/caja", where);
else if (File.Exists(@"/usr/bin/thunar")) Process.Start(@"/usr/bin/thunar", where);
else if (File.Exists(@"/usr/bin/dolphin")) Process.Start(@"/usr/bin/dolphin", where);
else throw new Exception("Unable to identify a file browser program for this distro. Please report this issue - thank you!");
}
else
{
string path = selFile == string.Empty
? "/e,\"" + where + "\""
: "/e, /select,\"" + selFile + "\"";
App.PrintLogMessage(path, MessageType.Command);
Process.Start("explorer.exe", path);
}
}
catch (Exception ex)
{
App.PrintLogMessage(ex.Message, MessageType.Error);
MessageBox.Show(ex.Message, "Explorer Here error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Executes a shell command
/// </summary>
public static string ExecuteShellCommand(string cmd, string args)
{
App.PrintStatusMessage("Shell execute: " + cmd + " " + args, MessageType.Command);
// WAR: Shell execute is platform-specific
if (IsMono())
{
return Exec.Run(cmd, args).ToString();
}
else
{
args = "/c " + cmd + " " + args;
return Exec.Run("cmd.exe", args).ToString();
}
}
/// <summary>
/// Returns CMD/SHELL executable name to execute a command line command
/// </summary>
public static string GetShellExecCmd()
{
return IsMono() ? "sh" : "cmd.exe";
}
/// <summary>
/// Returns a string to be used by CMD/SHELL as argument when executing a command line command
/// </summary>
public static string GetShellExecFlags()
{
return IsMono() ? "-c" : "/K";
}
/// <summary>
/// Identical to NET4.0 IsNullOrWhiteSpace()
/// </summary>
public static bool IsNullOrWhiteSpace(string s)
{
if (s == null)
return true;
return s.Trim().Length == 0;
}
/// <summary>
/// This function is meaningful only on Windows: Given a long file path name,
/// return its short version. This is used mainly to avoid various problems with
/// paths containing spaces and the inability of git to handle them.
/// </summary>
public static string GetShortPathName(string path)
{
if (IsMono())
return path;
var pathBuilder = new StringBuilder(1024);
NativeMethods.GetShortPathName(path, pathBuilder, pathBuilder.Capacity);
return pathBuilder.ToString();
}
/// <summary>
/// Given the path to a local directory, return its "clean" version. At this time, that means:
/// - Make drive letter uppercased (on Windows)
/// - Strip multiple backslash characters (on Windows)
/// </summary>
public static string GetCleanPath(string path)
{
if (string.IsNullOrEmpty(path)) return string.Empty; // Check for empty string
if (IsMono()) return path; // Do nothing on Mono
var value = ((path.Length > 2) && (path[1] == ':')) ?
char.ToUpper(path[0]) + path.Substring(1) : // Make drive letter uppercased
path;
return value.Replace(@"\\", @"\"); // Trim possible double-slash
}
/// <summary>
/// This function is similar to Path.Combine, but it adds separator after drive letter which
/// is needed for some git operations on Windows (clone, for example). Strange things happen without it.
/// </summary>
public static string GetCombinedPath(string s1, string s2)
{
if (string.IsNullOrWhiteSpace(s1)) return s2;
if (string.IsNullOrWhiteSpace(s2)) return s1;
s1 = s1.TrimEnd('/').TrimEnd(Path.DirectorySeparatorChar);
return s1 + Path.DirectorySeparatorChar + s2;
}
/// <summary>
/// Retruns a path to the home directory.
/// </summary>
public static string GetHomePath()
{
if (IsMono())
return Environment.GetEnvironmentVariable("HOME");
// On Windows, path to the user's home is a combination of a drive and a path
string drive = Environment.GetEnvironmentVariable("HOMEDRIVE");
string path = Environment.GetEnvironmentVariable("HOMEPATH");
// On Windows, the Path.Combine is fundamentally broken can can't be used
return drive + path;
}
/// <summary>
/// List of possible directory types returned by DirStat() method
/// </summary>
public enum DirStatType
{
Invalid, // Specified path does not exist or is not a valid absolute directory path
Empty, // Specified path is a directory which contains no other sub-directories or files
Git, // Specified path is a root directory of a git repo
Nongit // Specified path is a general, non-git repo directory
}
/// <summary>
/// Given a fully qualified path to a local directory, return the stat on that folder
/// </summary>
public static DirStatType DirStat(string path)
{
// Check that the path is valid and that it specifies an existing directory
if (!Directory.Exists(path))
return DirStatType.Invalid;
// We don't allow relative paths, all paths need to be absolute or UNC
if (!Path.IsPathRooted(path)) // Note: This call may throw exceptions but the preceeding call to
return DirStatType.Invalid; // Directory.Exists() will reject such invalid paths w/o exceptions
// Second check if the directory is completely empty (no files of subdirectories within it)
if ((Directory.GetFiles(path).Length == 0) && (Directory.GetDirectories(path).Length == 0))
return DirStatType.Empty;
// Lastly, check if there is a subdirectory ".git" with a representative file ("config") which
// would make very likely that a given path is the root to a valid git folder structure
string testFile = Path.Combine(path, Path.Combine(".git", "config"));
return File.Exists(testFile) ? DirStatType.Git : DirStatType.Nongit;
}
/// <summary>
/// Remove given folder and all files and subfolders under it.
/// If fPreserveGit is true, all folders that are named ".git" will be preserved (not removed)
/// If fPreserveRootFolder is true, the first (root) folder will also be preserved
/// Return false if the function could not remove all folders, true otherwise.
/// </summary>
public static bool DeleteFolder(DirectoryInfo dirInfo, bool fPreserveGit, bool fPreserveRootFolder)
{
bool f = true;
try
{
foreach (var subDir in dirInfo.GetDirectories())
{
if (fPreserveGit == false || !subDir.Name.EndsWith(".git"))
f &= DeleteFolder(subDir, false, false);
}
foreach (var file in dirInfo.GetFiles())
f &= DeleteFile(file.FullName);
if (fPreserveRootFolder == false)
f &= DeleteFolder(dirInfo);
}
catch (Exception ex)
{
App.PrintLogMessage("Error deleting directory " + dirInfo.FullName + ": " + ex.Message, MessageType.Error);
}
return f;
}
/// <summary>
/// Deletes a folder from the local file system.
/// Returns true if delete succeeded, false otherwise.
/// </summary>
private static bool DeleteFolder(DirectoryInfo dirInfo)
{
try
{
dirInfo.Attributes = FileAttributes.Normal;
dirInfo.Delete();
}
catch (Exception ex)
{
App.PrintLogMessage("Error deleting directory " + dirInfo.FullName + ": " + ex.Message, MessageType.Error);
return false;
}
return true;
}
/// <summary>
/// Deletes a file from the local file system.
/// Returns true if delete succeeded, false otherwise.
/// </summary>
public static bool DeleteFile(string name)
{
try
{
FileInfo file = new FileInfo(name) {Attributes = FileAttributes.Normal};
file.Delete();
}
catch (Exception ex)
{
App.PrintLogMessage("Error deleting file " + name + ": " + ex.Message, MessageType.Error);
return false;
}
return true;
}
/// <summary>
/// Handle double-clicking on a file.
/// Depending on the saved options, we either do nothing ("0"), open a file
/// using a default Explorer file association ("1"), or open a file using a
/// specified application ("2")
/// </summary>
public static void FileDoubleClick(string file)
{
// Perform the required action on double-click
string option = Properties.Settings.Default.DoubleClick;
string program = Properties.Settings.Default.DoubleClickProgram;
try
{
if (option == "1")
Process.Start(file);
if (option == "2")
Process.Start(program, file);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Edit selected file using either the default editor (native OS file association,
/// if the tag is null, or the editor program specified in the tag field.
/// This is a handler for the context menu, edit tool bar button and also
/// revision history view menus.
/// </summary>
public static void FileOpenFromMenu(object sender, string file)
{
try
{
if (sender is ToolStripMenuItem)
{
object opt = (sender as ToolStripMenuItem).Tag;
if (opt != null)
{
App.PrintLogMessage("Exec: " + opt.ToString() + " " + file, MessageType.General);
Process.Start(opt.ToString(), file);
return;
}
}
App.PrintLogMessage("Exec: " + file, MessageType.General);
Process.Start(file);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Open an HTML link in an external web browser application.
/// </summary>
public static void OpenWebLink(string html)
{
try
{
Process.Start(html);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "GitForce", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
/// <summary>
/// Returns a copy of the input string, but with all non-ASCII characters stripped down.
/// This function also removes ANSI escape codes from the string.
/// </summary>
public static string ToPlainAscii(string s)
{
StringBuilder str = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
if (!Char.IsControl(s[i]) || s[i]=='\n')
str.Append(s[i]);
else
{ // Strip ANSI escape codes from the string
// http://ascii-table.com/ansi-escape-sequences.php
// Skip all non-characters (ANSI code terminates with a alpha character)
if (s[i] == 27 && i<s.Length-1 && s[i+1]=='[')
while (i < s.Length && !Char.IsLetter(s[i])) i++;
// Get rid of the terminating ANSI character
if (i<s.Length && Char.IsLetter(s[i]))
i++;
}
}
return str.ToString();
}
/// <summary>
/// Upgrades the application settings to a new version, if necessary
/// http://stackoverflow.com/questions/10121044/app-loses-all-settings-when-app-update-is-installed
/// </summary>
public static void UpgradeApplicationSettingsIfNecessary()
{
// Application settings are stored in a subfolder named after the full #.#.#.# version number of the program.
// This means that when a new version of the program is installed, the old settings will not be available.
// Fortunately, there's a method called Upgrade() that you can call to upgrade the settings from the old to the new folder.
// We control when to do this by having a boolean setting called 'NeedSettingsUpgrade' which is defaulted to true.
// Therefore, the first time a new version of this program is run, it will have its default value of true.
// This will cause the code below to call "Upgrade()" which copies the old settings to the new.
// It then sets "NeedSettingsUpgrade" to false so the upgrade won't be done the next time.
if (Properties.Settings.Default.NeedSettingsUpgrade)
{
Properties.Settings.Default.Upgrade();
Properties.Settings.Default.NeedSettingsUpgrade = false;
}
}
}
}