问题
I'm trying to create a simple application that executes a "git push --mirror" operation from the Java domain.
The JGit library, specifically the PushCommand class, doesn't seem to support the "--mirror" option even though it supports "--all" and "--tags".
Am I missing something? How do we use JGit to do "git push --mirror ..."?
回答1:
Try it manually by using the following ref spec:
git.push().setRefSpecs(new RefSpec("+refs/*:refs/*")).call();
回答2:
There is no exact equivalent to --mirror
in JGit yet, but you should be able to emulate this behaviour. To force-push all local refs you can configure the PushCommand with
PushCommand pushCommand = git.push();
pushCommand.setForce( true );
pushCommand.add( "refs/*:refs/*" );
That would leave the refs that have been deleted locally. Therefore you can obtain a list of remote-refs to determine what has been deleted locally and publish those deletions to the remote:
Collection<Ref> remoteRefs = git.lsRemote().setRemote( "origin" ).setHeads( true ).setTags( true ).call();
Collection<String> deletedRefs = new ArrayList<String>();
for( Ref remoteRef : remoteRefs ) {
if( git.getRepository().getRef( remoteRef.getName() ) == null ) {
deletedRefs.add( remoteRef.getName() );
}
}
for( String deletedRef : deletedRefs ) {
pushCommand.add( ":" + deletedRef );
}
The git
variable references the repository that you want to push from, i.e. the one from the first block. The LsRemoteCommand
returns all heads and tags from the remote repository that is configured as origin
in the local repository's configuration. In the usual case, the one you cloned from.
Please note that there is a small gap to the approach how deleted local refs are propagated. The LsRemoteCommand
only returns refs under heads
and tags
(e.g. no custom refs like pulls
), hence you would not detect a local deletion of e.g. refs/foo/bar
.
Does that work for you?
来源:https://stackoverflow.com/questions/25294554/how-to-use-jgit-to-do-equivalent-of-git-push-mirror