@@ -39,6 +39,68 @@ test("doubles an embedded quote", () => {
3939 assert . equal ( quoteWinArg ( 'a"b c' ) , '"a""b c"' ) ;
4040} ) ;
4141
42+ test ( "doubles a trailing backslash run, which the closing quote follows (#5111)" , ( ) => {
43+ // Undoubled, `"C:\dir with space\"` ends in `\"`, an escaped quote, and the
44+ // CRT parser runs the argument on into the next one.
45+ assert . equal ( quoteWinArg ( "C:\\a b\\" ) , '"C:\\a b\\\\"' ) ;
46+ assert . equal ( quoteWinArg ( "C:\\a b\\\\" ) , '"C:\\a b\\\\\\\\"' ) ;
47+ } ) ;
48+
49+ test ( "doubles backslashes before an embedded quote, then doubles the quote" , ( ) => {
50+ assert . equal ( quoteWinArg ( 'a\\"b c' ) , '"a\\\\""b c"' ) ;
51+ assert . equal ( quoteWinArg ( 'a\\\\"b' ) , '"a\\\\\\\\""b"' ) ;
52+ } ) ;
53+
54+ test ( "leaves backslashes not followed by a quote alone" , ( ) => {
55+ assert . equal ( quoteWinArg ( "C:\\a b\\c" ) , '"C:\\a b\\c"' ) ;
56+ // An inert trailing-backslash path is not quoted, so nothing follows it.
57+ assert . equal ( quoteWinArg ( "C:\\dir\\" ) , "C:\\dir\\" ) ;
58+ } ) ;
59+
60+ test ( "quoted output parses back to the original under the CRT rules" , ( ) => {
61+ // A reference parser for one quoted argument (the MSVCRT 2008+ rules), so
62+ // the expectations above are checked against what the child actually sees.
63+ const parse = ( s ) => {
64+ let out = "" ;
65+ let inQuotes = false ;
66+ for ( let i = 0 ; i < s . length ; ) {
67+ let n = 0 ;
68+ while ( s [ i ] === "\\" ) {
69+ n ++ ;
70+ i ++ ;
71+ }
72+ if ( s [ i ] === '"' ) {
73+ out += "\\" . repeat ( n >> 1 ) ;
74+ if ( n & 1 ) {
75+ out += '"' ;
76+ } else if ( inQuotes && s [ i + 1 ] === '"' ) {
77+ out += '"' ;
78+ i ++ ;
79+ } else {
80+ inQuotes = ! inQuotes ;
81+ }
82+ i ++ ;
83+ } else {
84+ out += "\\" . repeat ( n ) ;
85+ if ( i < s . length ) out += s [ i ++ ] ;
86+ }
87+ }
88+ return out ;
89+ } ;
90+ for ( const arg of [
91+ "C:\\a b\\" ,
92+ "C:\\a b\\\\" ,
93+ 'a\\"b c' ,
94+ 'a\\\\"b' ,
95+ 'a"b c' ,
96+ '"' ,
97+ "\\ \\" ,
98+ "C:\\Temp(1)\\" ,
99+ ] ) {
100+ assert . equal ( parse ( quoteWinArg ( arg ) ) , arg , `round trip: ${ arg } ` ) ;
101+ }
102+ } ) ;
103+
42104test ( "throws on `%` rather than silently mis-expanding it" , ( ) => {
43105 // cmd.exe expands %NAME% before it processes quotes, so quoting cannot save
44106 // this one — the child would receive a different path than we passed.
0 commit comments