Convert filepath to URI

I’ve been knocking my head against a wall trying to fix an issue in the .xspf (VLC) playlist generator I’m writing. I used “walkdir” to get the paths of the files but I can’t seem to convert them into the correct format (HTML/ANSI URL/URI?) that the .xspf file needs. I am working in Windows.

For instance, one of my entries says:
file:///C:\Music\Adiemus\Adiemus IV_ The Eternal Knot\04 The Wooing Of Etain.mp3

When it should say:
file:///C:/Music/Adiemus/Adiemus%20IV_%20The%20Eternal%20Knot/04%20The%20Wooing%20Of%20Etain.mp3

Can anyone tell me how to fix this?

The following does the job for the strings in the post:

julia> s = "file:///C:\\Music\\Adiemus\\Adiemus IV_ The Eternal Knot\\04 The Wooing Of Etain.mp3"
"file:///C:\\Music\\Adiemus\\Adiemus IV_ The Eternal Knot\\04 The Wooing Of Etain.mp3"

julia> println(s)
file:///C:\Music\Adiemus\Adiemus IV_ The Eternal Knot\04 The Wooing Of Etain.mp3

julia> t = replace(replace(s, ' '=>"%20"),'\\'=>"/")
"file:///C:/Music/Adiemus/Adiemus%20IV_%20The%20Eternal%20Knot/04%20The%20Wooing%20Of%20Etain.mp3"

But this is a brittle solution. There are many gotchas with these encodings and depending on the level of correctness and the degree to which the inputs are exposed to manipulation, there is much more care which can be taken.

Thanks, I’ll give it a try. I didn’t know if there was package that existed that would do the job that I missed :slight_smile:

See What to use for URL encoding? - #3 by quinnjthe HTTP.jl package the URIs.jl package has a function escapeuri to escape strings for URIs. It won’t convert backslash to forward slashes, but you can apply it to each component of the path (via splitpath, which splits by \ on Windows) to escape special characters like spaces. In particular, you can define the function:

import URIs
path2uri(path) = "file://" * join(map(URIs.escapeuri, splitpath(path)), '/')

and apply it to convert your path to a file:// URI.

(It might be nice to have a function like this in the URIs.jl package if someone feels like filing an issue or making a PR for the issue: filepath2uri function? · Issue #61 · JuliaWeb/URIs.jl · GitHub)

2 posts were split to a new topic: Splitpath/joinpath for non-native paths?

Thanks Dan and stevengj, I used both your methods to get it working. I used the path2uri function in which i did a replace for the Di which got mangled. It’s all working now.

We have been using the functions in JuliaWorkspaces.jl/src/URIs2/uri_helpers.jl at main · julia-vscode/JuliaWorkspaces.jl · GitHub for the LanguageServer.jl for this kind of stuff for a very long time, so in a way they are very battle tested.

I wanted to move this stuff out into its own package forever, but always got stuck. GitHub - davidanthoff/URIs2.jl is how far I got, should probably just finish that at some point.

See also: https://github.com/JuliaLang/julia/pull/55454 (for code copy/paste/inspiration purposes only, this is part of Base’s private API).