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?
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.
This answer is a good start, but as noted it doesn't handle special characters. The following fulfills that shortcoming.
Create a batch file, say, unc2url.bat
with this content:
powershell -Command "write-host ([System.Uri]""%1"").AbsoluteUri"
Then from a Windows command prompt:
> unc2url.bat "\\serverX\a long\and tedious\yet unexciting\path to\some Random #64# file.txt"
file://serverx/a%20long/and%20tedious/yet%20unexciting/path%20to/some%20Random%20%2364%23%20file.txt
To put the result in a variable that can be used in the rest of the batch file, you can use the FOR
syntax:
SET UNC2URL_CMD=powershell -Command "write-host ([System.Uri]""%CONDA_CHANNEL_PATH%"").AbsoluteUri"
FOR /f "delims=" %%X IN ('%UNC2URL_CMD%') do set "FILE_URL=%%X"
REM Now use it for whatever
ECHO %FILE_URL%
Drawback: This powershell command cannot handle relative paths. To remediate this, we can add a command that converts relative paths to absolute paths, if applicable, such as the first line in the aforementioned other answer, subject to the drawback that the "%%~fR%"
does not quite work as advertised to ensure a fully qualified path: it prepends %CD%
to a path that starts "//server/..."
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With