forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringExtensions.cs
More file actions
382 lines (328 loc) · 14.2 KB
/
Copy pathStringExtensions.cs
File metadata and controls
382 lines (328 loc) · 14.2 KB
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
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
namespace Microsoft.PackageManagement.Internal.Utility.Extensions {
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using Collections;
internal static class StringExtensions {
private static readonly char[] _wildcardCharacters = new[] {
'*', '?'
};
private static readonly Regex _escapeFilepathCharacters = new Regex(@"([\\|\$|\^|\{|\[|\||\)|\+|\.|\]|\}|\/])");
private static string FixMeFormat(string formatString, object[] args) {
return args.Aggregate(formatString.Replace('{', '\u00ab').Replace('}', '\u00bb'), (current, arg) => current + string.Format(CultureInfo.CurrentCulture, " \u00ab{0}\u00bb", arg));
}
public static IEnumerable<string> Quote(this IEnumerable<string> items) {
return items.Select(each => "'" + each + "'");
}
public static string JoinWithComma(this IEnumerable<string> items) {
return items.JoinWith(",");
}
public static string JoinWith(this IEnumerable<string> items, string delimiter) {
return items.SafeAggregate((current, each) => current + delimiter + each);
}
public static TSource SafeAggregate<TSource>(this IEnumerable<TSource> source, Func<TSource, TSource, TSource> func) {
var src = source.ReEnumerable();
if (source != null && src.Any()) {
return src.Aggregate(func);
}
return default(TSource);
}
#if !CORECLR
/// <summary>
/// encrypts the given collection of bytes with the user key and salt
/// </summary>
/// <param name="binaryData"> The binary data. </param>
/// <param name="salt"> The salt. </param>
/// <returns> </returns>
/// <remarks>
/// </remarks>
public static IEnumerable<byte> ProtectBinaryForUser(this IEnumerable<byte> binaryData, string salt) {
var data = binaryData.ToArray();
var s = salt.ToByteArray();
try {
return ProtectedData.Protect(data, s, DataProtectionScope.CurrentUser);
} finally {
Array.Clear(data, 0, data.Length);
Array.Clear(s, 0, s.Length);
}
}
/// <summary>
/// decrypts the given collection of bytes with the user key and salt returns an empty collection of bytes on failure
/// </summary>
/// <param name="binaryData"> The binary data. </param>
/// <param name="salt"> The salt. </param>
/// <returns> </returns>
/// <remarks>
/// </remarks>
public static IEnumerable<byte> UnprotectBinaryForUser(this IEnumerable<byte> binaryData, string salt) {
if (binaryData == null) {
return Enumerable.Empty<byte>();
}
try {
return ProtectedData.Unprotect(binaryData.ToArray(), salt.ToByteArray(), DataProtectionScope.CurrentUser);
} catch {
/* suppress */
}
return Enumerable.Empty<byte>();
}
public static SecureString ToSecureString(this string password) {
if (password == null) {
throw new ArgumentNullException("password");
}
var ss = new SecureString();
foreach (var ch in password.ToCharArray()) {
ss.AppendChar(ch);
}
return ss;
}
public static string ToProtectedString(this SecureString secureString, string salt) {
return Convert.ToBase64String(secureString.ToBytes().ProtectBinaryForUser(salt).ToArray());
}
public static SecureString FromProtectedString(this string str, string salt) {
return Convert.FromBase64String(str).UnprotectBinaryForUser(salt).ToUnicodeString().ToSecureString();
}
public static IEnumerable<byte> ToBytes(this SecureString securePassword) {
if (securePassword == null) {
throw new ArgumentNullException("securePassword");
}
var unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
var ofs = 0;
do {
var x = Marshal.ReadByte(unmanagedString, ofs++);
var y = Marshal.ReadByte(unmanagedString, ofs++);
if (x == 0 && y == 0) {
break;
}
// now we have two bytes!
yield return x;
yield return y;
} while (true);
Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
}
#endif
public static Version ToVersion(this string versionInput) {
if (string.IsNullOrWhiteSpace(versionInput)) {
return null;
}
Version result;
return Version.TryParse(versionInput, out result) ? result : null;
}
public static bool ContainsIgnoreCase(this IEnumerable<string> collection, string value) {
if (collection == null) {
return false;
}
return collection.Any(s => s.EqualsIgnoreCase(value));
}
public static bool ContainsAnyOfIgnoreCase(this IEnumerable<string> collection, params object[] values) {
return collection.ContainsAnyOfIgnoreCase(values.Select(value => value == null ? null : value.ToString()));
}
public static bool ContainsAnyOfIgnoreCase(this IEnumerable<string> collection, IEnumerable<string> values) {
if (collection == null) {
return false;
}
var set = values.ReEnumerable();
return collection.Any(set.ContainsIgnoreCase);
}
private static Regex WildcardToRegex(string wildcard, string noEscapePrefix = "^") {
return new Regex(noEscapePrefix + _escapeFilepathCharacters.Replace(wildcard, "\\$1")
.Replace("?", @".")
.Replace("**", @"?")
.Replace("*", @"[^\\\/\<\>\|]*")
.Replace("?", @".*") + '$', RegexOptions.IgnoreCase);
}
/// <summary>
/// Determines whether the specified input has wildcards.
/// </summary>
/// <param name="input"> The input. </param>
/// <returns>
/// <c>true</c> if the specified input has wildcards; otherwise, <c>false</c> .
/// </returns>
/// <remarks>
/// </remarks>
public static bool ContainsWildcards(this string input) {
return input.IndexOfAny(_wildcardCharacters) > -1;
}
/// <summary>
/// Determines whether the input string is equals to the source string
/// ignoring a single / at the end
/// </summary>
/// <param name="source"></param>
/// <param name="input"></param>
/// <returns></returns>
public static bool EqualsIgnoreEndSlash(this string source, string input)
{
return source.EqualsIgnoreCase(input)
|| (string.Concat(source, "/")).EqualsIgnoreCase(input)
|| (string.Concat(input, "/")).EqualsIgnoreCase(source);
}
/// <summary>
/// Determines whether the input string contains the specified substring
/// </summary>
public static bool ContainsIgnoreCase(this string source, string input) {
return source.IndexOf(input, StringComparison.OrdinalIgnoreCase) >= 0;
}
public static bool IsFile(this string input) {
if (string.IsNullOrWhiteSpace(input)) {
return false;
}
try {
Uri result;
if (Uri.TryCreate(input, UriKind.Absolute, out result)) {
return result.IsFile;
}
} catch {
}
return false;
}
public static bool IsWildcardMatch(this string input, string wildcardMask) {
if (input == null || string.IsNullOrWhiteSpace(wildcardMask)) {
return false;
}
return WildcardToRegex(wildcardMask).IsMatch(input);
}
private static byte FromHexChar(this char c) {
if ((c >= 'a') && (c <= 'f')) {
return (byte)(c - 'a' + 10);
}
if ((c >= 'A') && (c <= 'F')) {
return (byte)(c - 'A' + 10);
}
if ((c >= '0') && (c <= '9')) {
return (byte)(c - '0');
}
throw new ArgumentException("invalid hex char");
}
public static byte[] FromHex(this string hex) {
if (string.IsNullOrWhiteSpace(hex)) {
return new byte[0];
}
if ((hex.Length & 0x1) == 0x1) {
throw new ArgumentException("Length must be a multiple of 2");
}
var input = hex.ToCharArray();
var result = new byte[hex.Length >> 1];
for (var i = 0; i < input.Length; i += 2) {
result[i >> 1] = (byte)(((byte)(FromHexChar(input[i]) << 4)) | FromHexChar(input[i + 1]));
}
return result;
}
public static string FixVersion(this string versionString) {
if (!string.IsNullOrWhiteSpace(versionString)) {
if (versionString[0] == '.') {
// make sure we have a leading zero when someone says .5
versionString = "0" + versionString;
}
if (versionString.IndexOf('.') == -1) {
// make sure we make a 1 work like 1.0
versionString = versionString + ".0";
}
}
return versionString;
}
// ReSharper disable InconsistentNaming
/// <summary>
/// Formats the specified format string.
/// </summary>
/// <param name="formatString"> The format string. </param>
/// <param name="args"> The args. </param>
/// <returns> </returns>
/// <remarks>
/// </remarks>
public static string format(this string formatString, params object[] args) {
if (args == null || args.Length == 0) {
return formatString;
}
try {
var replacedByName = false;
// first, try to replace
formatString = new Regex(@"\$\{(?<macro>\w*?)\}").Replace(formatString, new MatchEvaluator((m) => {
var key = m.Groups["macro"].Value;
var p = args[0].GetType().GetProperty(key);
if (p != null) {
replacedByName = true;
return p.GetValue(args[0], null).ToString();
}
return "${{" + m.Groups["macro"].Value + "}}";
}));
// if it looks like it doesn't take parameters, (and yet we have args!)
// let's return a fix-me-format string.
if (!replacedByName && formatString.IndexOf('{') < 0) {
return FixMeFormat(formatString, args);
}
return String.Format(CultureInfo.CurrentCulture, formatString, args);
} catch (Exception) {
// if we got an exception, let's at least return a string that we can use to figure out what parameters should have been matched vs what was passed.
return FixMeFormat(formatString, args);
}
}
/// <summary>
/// Encodes the string as an array of UTF8 bytes.
/// </summary>
/// <param name="text"> The text. </param>
/// <returns> </returns>
/// <remarks>
/// </remarks>
internal static byte[] ToByteArray(this string text) {
return Encoding.UTF8.GetBytes(text);
}
internal static string ToUnicodeString(this IEnumerable<byte> bytes) {
var data = bytes.ToArray();
try {
return Encoding.Unicode.GetString(data);
} finally {
Array.Clear(data, 0, data.Length);
}
}
public static bool IsTrue(this string text) {
return !string.IsNullOrWhiteSpace(text) && text.Equals("true", StringComparison.CurrentCultureIgnoreCase);
}
public static bool? IsTruePreserveNull(this string text) {
if (text == null) {
return null;
}
return !string.IsNullOrWhiteSpace(text) && text.Equals("true", StringComparison.CurrentCultureIgnoreCase);
}
/// <summary>
/// coerces a string to an int32, defaults to zero.
/// </summary>
/// <param name="str"> The STR. </param>
/// <param name="defaultValue"> The default value if the string isn't a valid int. </param>
/// <returns> </returns>
/// <remarks>
/// </remarks>
public static int ToInt32(this string str, int defaultValue) {
int i;
return Int32.TryParse(str, out i) ? i : defaultValue;
}
public static bool EqualsIgnoreCase(this string str, string str2) {
if (str == null && str2 == null) {
return true;
}
if (str == null || str2 == null) {
return false;
}
return str.Equals(str2, StringComparison.OrdinalIgnoreCase);
}
// ReSharper restore InconsistentNaming
}
}