1

Imagine I want to:

  1. ask the user to enter a file path as a string (which could be something such as 'My' "a/b" folder which in macOS is an entirely acceptable file name.)
  2. create an absolute URL based on the string entered in step 1 eg /Users/john/Desktop/'My' "a/b" folder
  3. do something in a Process with that URL, for example run /bin/mkdir "/Users/john/Desktop/'My' \"a:b\" folder"*

I'm not sure how to achieve this in Swift. I've searched the URL docs and not seen anything to do with macOS's filesystem escaping. I am sure there must be a canonical method to achieve this, and not a series of hopefully-I-covered-the-edge-cases string replacements.

let pathString = """
/Users/john/Desktop/'My' "a/b" folder
"""

let url = URL(fileURLWithPath: pathString)

let urlString = "\"" + url.path + "\""

var process = Process()
process.launchPath = "/bin/mkdir"
process.arguments = [urlString]

I would like urlString to be something like "/Users/john/Desktop/'My' \"a:b\" folder". With that I could create a command such as:

mkdir "/Users/john/Desktop/\'My\'\ \"a\:b\"\ folder"
  1. This is a hypothetical example that illustrates the issue. Of course I'm not actually trying to create a directory using mkdir from within Swift :)
jeff-h
  • 2,184
  • 1
  • 22
  • 33
  • Does this help: https://stackoverflow.com/q/55383444/1187415 ? – Martin R Jan 17 '20 at 10:36
  • 1
    Why not simply `let urlString = pathString.replacingOccurrences(of: "/", with: ":")`? The slash is the only "banned" character. – vadian Jan 17 '20 at 10:51
  • @MartinR thanks for the link. My issue is a little different in that the primary difficulty is creating a string representation of the path which is escaped suitably for use in a command line tool, within double-quotes for safety. – jeff-h Jan 17 '20 at 20:33
  • @vadian Your comment gives me a little more confidence to simply manually escape double quotes, and string-replace any forward slashes (within the filename). – jeff-h Jan 17 '20 at 20:37
  • Starting to think it would be fun to rename my `Macintosh HD` to something like `My "small/ish" SSD` and see how many apps do horrible things lol :) – jeff-h Jan 17 '20 at 20:38
  • 1
    @jeff-h: You don't have to escape any quotes when you pass the arguments to Process, only when you invoke a shell. – Martin R Jan 17 '20 at 22:46

1 Answers1

1

Can you please try this .addingPercentEncoding(withAllowedCharacters: .urlUserAllowed)

Harsha
  • 760
  • 1
  • 7
  • 21