forked from y4htse/desktop-xamarin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CommandLineEncoder.cs
74 lines (65 loc) · 2.47 KB
/
CommandLineEncoder.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
/* This was created by macropas at - https://stackoverflow.com/a/10489920/8737306
and modified for the target use case. Thanks! */
using System;
namespace TurtleWallet
{
class CLIEncoder
{
public static string Encode(string[] args)
{
if (args == null)
{
return null;
}
string result = "";
if (Environment.OSVersion.Platform == PlatformID.Unix ||
Environment.OSVersion.Platform == PlatformID.MacOSX)
{
foreach (string arg in args)
{
result += (result.Length > 0 ? " " : "");
/* Surround the argument in single quotes to prevent !
getting expanded by bash */
result += "'";
/* Make sure to replace the \ with \\ before other changes,
so we don't escape other later escaped characters twice */
result += arg.Replace(@"\", @"\\")
.Replace(@"'", @"'\''");
result += "'";
}
}
else //Windows family
{
bool enclosedInApo, wasApo;
string subResult;
foreach (string arg in args)
{
enclosedInApo = arg.LastIndexOfAny(
new char[] { ' ', '\t', '|', '@', '^', '<', '>', '&'}) >= 0;
wasApo = enclosedInApo;
subResult = "";
for (int i = arg.Length - 1; i >= 0; i--)
{
switch (arg[i])
{
case '"':
subResult = @"\""" + subResult;
wasApo = true;
break;
case '\\':
subResult = (wasApo ? @"\\" : @"\") + subResult;
break;
default:
subResult = arg[i] + subResult;
wasApo = false;
break;
}
}
result += (result.Length > 0 ? " " : "")
+ (enclosedInApo ? "\"" + subResult + "\"" : subResult);
}
}
return result;
}
}
}