windowsbatch-filesvnsvnsyncfile-uri

How to convert Windows path to file: URL, in a batch file, suitable for SVN command line use


In a Windows-based SVN installation (using CollabNet Subversion Edge), I have a post-commit hook batch file where I construct a repository folder name, and I need to call svnsync with a file: URL pointing to that Windows folder.

The question now is: How can I convert a Windows folder or file name to a file: URL, in such a way that that URL is at least acceptable for the SVN command line tools?


Solution

  • In a batch file, if the variable FILE_OR_FOLDER_NAME contains the (absolute or relative, local or UNC, with or without spaces, existing or not existing) Windows file or directory name, then the following commands put the corresponding file: URL in variable FILE_URL:

    for /f "delims=" %%R in ("%FILE_OR_FOLDER_NAME%") do set FILE_URL=%%~fR%
    set FILE_URL=file:///%FILE_URL%
    set FILE_URL=%FILE_URL:///\\=//%
    set FILE_URL=%FILE_URL:\=/%
    

    Line 1 expands the relative file name to an absolute one; line 2 prepends file:///; line 3 handles the special case of a UNC path; and line 4 makes sure we only use forward slashes.

    Taken together, these transform \\remotehost\share\folder to file://remotehost/share/folder, and d:\folder to file:///d:/folder.

    As far as my testing goes, the above commands always result in to a file: URL that is acceptable for an SVN command line, and probably also for other uses.

    The only thing that is not really correct, is that spaces and other special characters like # are not properly URL-encoded in the resulting file: URL: D:/my test#repo becomes file:///D:/my test#repo, which is technically not correct. However, in my specific use case this poses no problem, since the SVN command line parser finds the repository regardless.