1
1
/*
2
2
This source file is part of the Swift.org open source project
3
3
4
- Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
4
+ Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
5
5
Licensed under Apache License v2.0 with Runtime Library Exception
6
6
7
7
See http://swift.org/LICENSE.txt for license information
15
15
///
16
16
/// - Returns: True if shell escaping is not needed.
17
17
private func inShellWhitelist( _ codeUnit: UInt8 ) -> Bool {
18
+ #if os(Windows)
19
+ if codeUnit == UInt8 ( ascii: " \\ " ) {
20
+ return true
21
+ }
22
+ #endif
18
23
switch codeUnit {
19
24
case UInt8 ( ascii: " a " ) ... UInt8 ( ascii: " z " ) ,
20
25
UInt8 ( ascii: " A " ) ... UInt8 ( ascii: " Z " ) ,
@@ -38,7 +43,7 @@ private func inShellWhitelist(_ codeUnit: UInt8) -> Bool {
38
43
extension String {
39
44
40
45
/// Creates a shell escaped string. If the string does not need escaping, returns the original string.
41
- /// Otherwise escapes using single quotes. For example:
46
+ /// Otherwise escapes using single quotes on Unix and double quotes on Windows . For example:
42
47
/// hello -> hello, hello$world -> 'hello$world', input A -> 'input A'
43
48
///
44
49
/// - Returns: Shell escaped string.
@@ -49,23 +54,30 @@ extension String {
49
54
return self
50
55
}
51
56
52
- // If there are no single quotes then we can just wrap the string around single quotes.
53
- guard let singleQuotePos = utf8 [ pos... ] . firstIndex ( of: UInt8 ( ascii: " ' " ) ) else {
54
- return " ' " + self + " ' "
57
+ #if os(Windows)
58
+ let quoteCharacter : Character = " \" "
59
+ let escapedQuoteCharacter = " \" \" "
60
+ #else
61
+ let quoteCharacter : Character = " ' "
62
+ let escapedQuoteCharacter = " ' \\ '' "
63
+ #endif
64
+ // If there are no quote characters then we can just wrap the string within the quotes.
65
+ guard let quotePos = utf8 [ pos... ] . firstIndex ( of: quoteCharacter. asciiValue!) else {
66
+ return String ( quoteCharacter) + self + String( quoteCharacter)
55
67
}
56
68
57
69
// Otherwise iterate and escape all the single quotes.
58
- var newString = " ' " + String( self [ ..< singleQuotePos ] )
70
+ var newString = String ( quoteCharacter ) + String( self [ ..< quotePos ] )
59
71
60
- for char in self [ singleQuotePos ... ] {
61
- if char == " ' " {
62
- newString += " ' \\ '' "
72
+ for char in self [ quotePos ... ] {
73
+ if char == quoteCharacter {
74
+ newString += escapedQuoteCharacter
63
75
} else {
64
76
newString += String ( char)
65
77
}
66
78
}
67
79
68
- newString += " ' "
80
+ newString += String ( quoteCharacter )
69
81
70
82
return newString
71
83
}
0 commit comments