jgit addFilePattern 不适用于我的文件绝对路径

jgit addFilePattern not working for my absolute path to a file

jgit 版本 4.6.0 , java 1.8 , windows10

我写了一个 java 程序来推送到 git 存储库,因为我想一次推送特定文件而不是推送所有文件。

git.add.addFilePattern(".").call(); 工作正常。 但是

git.add.addFilePattern("D:\myGitRepo\files\file1.txt").call(); 无效。

"myGitRepo" 文件夹包含 .git 文件夹。

总结

方法 AddCommand#addFilepattern(String) 的 Javadoc 说:参数 filepattern 是要添加的 file/directory 的存储库相对路径(以 / 作为分隔符)。所以你不能使用绝对路径,也不能使用反斜杠\。事实上,你应该:

  • 使用存储库相对路径
  • 使用斜杠 / 在所有平台上分隔目录,甚至在 Windows
  • 上也是如此

详情

在幕后AddCommand, JGit calls PathFilterGroup to create the file patterns, which calls PathFilter执行call()时。从PathFilter中,我们可以看到关于文件模式更详细的定义:

/**
 * Create a new tree filter for a user supplied path.
 * <p>
 * Path strings are relative to the root of the repository. If the user's
 * input should be assumed relative to a subdirectory of the repository the
 * caller must prepend the subdirectory's path prior to creating the filter.
 * <p>
 * Path strings use '/' to delimit directories on all platforms.
 *
 * @param path
 *            the path to filter on. Must not be the empty string. All
 *            trailing '/' characters will be trimmed before string's length
 *            is checked or is used as part of the constructed filter.
 * @return a new filter for the requested path.
 * @throws IllegalArgumentException
 *             the path supplied was the empty string.
 */
public static PathFilter create(String path) { ... }