-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExtensionMethods.cs
89 lines (73 loc) · 2.44 KB
/
ExtensionMethods.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
// Copyright (c) Doug Cook. All rights reserved.
// Licensed under the MIT License.
using System.Text;
namespace GitDiffWrapper
{
internal static class ExtensionMethods
{
private static readonly char[] NeedsEscaping = new char[] { ' ', '"', '\\' };
public static string String(this Side self)
{
switch (self)
{
case Side.Neither: return "Neither";
case Side.Left: return "Left";
case Side.Right: return "Right";
default: return "Unknown";
}
}
public static void AppendEscapedArg(this StringBuilder self, string arg)
{
int needsEscaping = arg == null
? -1
: arg.IndexOfAny(NeedsEscaping);
if (needsEscaping < 0)
{
self.Append(arg);
}
else
{
int equals = arg.IndexOf('=');
int i = 0;
if (0 < equals && equals < needsEscaping)
{
self.Append(arg, 0, equals + 1);
i = equals + 1;
}
self.Append('"');
int slashes = 0;
for (; i < arg.Length; i += 1)
{
char ch = arg[i];
switch (ch)
{
case '\\':
slashes += 1;
break;
case '"':
if (slashes != 0)
{
self.Append('\\', slashes * 2);
}
slashes = 0;
self.Append("\\\"");
break;
default:
if (slashes != 0)
{
self.Append('\\', slashes);
}
slashes = 0;
self.Append(ch);
break;
}
}
if (slashes != 0)
{
self.Append('\\', slashes * 2);
}
self.Append('"');
}
}
}
}