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

人走茶凉 提交于 2019-12-19 09:03:19

问题


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?


回答1:


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.




回答2:


MarnixKlooster/ReinstateMonica's answer is a good start* but as noted it doesn't handle special characters. The following fulfills that shortcoming (in batch file syntax):

Create, 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

No errorchecking, not perfect, but better.

* the "%%~fR%" does not quite work as advertised to ensure a fully qualified path -- it prepends %CD% to a path that starts "//server/..."



来源:https://stackoverflow.com/questions/27817625/how-to-convert-windows-path-to-file-url-in-a-batch-file-suitable-for-svn-comm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!