从 git 存储库中列出或归档非二进制文件

Listing or Archiving non binary files from a git repo

我目前正在使用 JGit 开发一个 Java 项目。我仍然没有使用 JGit,但我假设它的功能会像普通 git.

一样安静

我想要做的是从裸 git 回购分支中获取所有非二进制文件和特定大小以下的文件,并将它们存档在一个 zip 文件中。对于具有工作目录的存储库来说,这个任务可能很简单,因为我可以简单地使用 git grep -Ic '' 列出所有非二进制文件,然后将这些文件传递给 git archive,但是这对于裸存储库是不可行的.

非常感谢您的帮助。

该命令被命名为 git archive,它比费心工作树要好得多。

您可以使用 export-ignore attribute 排除不需要的文件,本地存储库 .git/info/attributes(或者像您一样在裸存储库中,只是 info/attributes)在这里很方便。此外,git ls-files|git check-attr --stdin --all 是一个方便的入门工具包,用于查找标记为 what 或任意提交的内容 (git ls-tree -r --name-only your.ref.here|git check-attr -a --stdin)。

您可以将任意模式放入您的属性文件中,例如

*.jpg export-ignore

您可以使用 JGit 的 ArchiveCommand 生成存档。它的 setPaths() 方法允许您 select 仅包含某些路径。

为了 assemble 路径列表,您需要分析要归档的提交树。例如:

TreeWalk treeWalk = new TreeWalk( repository );
treeWalk.setRecursive( true );
treeWalk.addTree( commit.getTree() );
while( treeWalk .next() ) {
  if( !isBinary( treeWalk ) {
    filesToArchive.add( treeWalk.getPathString() );
  }
}
treeWalk.close();

示例代码遍历要归档的提交的整个树,获取树中每个文件的内容并调用虚构的 isBinary() 方法来确定其内容是文本还是二进制。所有非二进制文件都添加到 filesToArchive 集合中,可以传递给 ArchiveCommand.

对于 isBinary() 实现,您可能会成功使用 JGit 的属性支持:

Attributes attributes = new AttributesHandler( treeWalk ).getAttributes();
boolean binary = attributes.isSet( "binary" );

AttributesHandler::getAttributes()returnsmerged属性为treeWalk.

表示的当前路径

或者,您可以使用 RawText::isBinary() 来实现 isBinary() 方法,如下所示:

ObjectId blobId = treeWalk.getObjectId( 0 );
ObjectReader objectReader = repository.newObjectReader();
ObjectLoader objectLoader = objectReader.open( blobId );
byte[] bytes = objectLoader.getBytes();
objectReader.close();
boolean binary = RawText.isBinary( bytes );

RawText::isBinary 使用与本机相同的启发式 Git 来确定给定内容是二进制还是文本。