在基于 Windows 的 SVN 安装中(使用 CollabNet Subversion Edge),我有一个提交后挂钩批处理文件,我在其中构造了一个存储库文件夹名称,并且我需要使用指向该 Windows 文件夹svnsync
的URL 进行调用。file:
现在的问题是:如何将 Windows 文件夹或文件名转换为file:
URL,以使该 URL 至少可以为 SVN 命令行工具所接受?
在基于 Windows 的 SVN 安装中(使用 CollabNet Subversion Edge),我有一个提交后挂钩批处理文件,我在其中构造了一个存储库文件夹名称,并且我需要使用指向该 Windows 文件夹svnsync
的URL 进行调用。file:
现在的问题是:如何将 Windows 文件夹或文件名转换为file:
URL,以使该 URL 至少可以为 SVN 命令行工具所接受?
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.
这个答案是一个好的开始,但如前所述,它不处理特殊字符。以下内容弥补了这一缺点。
例如,unc2url.bat
使用以下内容创建一个批处理文件:
powershell -Command "write-host ([System.Uri]""%1"").AbsoluteUri"
然后从 Windows 命令提示符:
> 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
要将结果放入可以在批处理文件的其余部分中使用的变量中,您可以使用以下FOR
语法:
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%
缺点:这个 powershell 命令不能处理相对路径。为了解决这个问题,如果适用,我们可以添加一个将相对路径转换为绝对路径的命令,例如前面提到的其他答案中的第一行,但缺点是"%%~fR%"
它不能像宣传的那样工作以确保完全合格的路径:它%CD%
添加到开始的路径"//server/..."
。