org.eclipse.jgit.api.Git类的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(16.3k)|赞(0)|评价(0)|浏览(1066)

本文整理了Java中org.eclipse.jgit.api.Git类的一些代码示例,展示了Git类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Git类的具体详情如下:
包路径:org.eclipse.jgit.api.Git
类名称:Git

Git介绍

[英]Offers a "GitPorcelain"-like API to interact with a git repository.

The GitPorcelain commands are described in the Git Documentation.

This class only offers methods to construct so-called command classes. Each GitPorcelain command is represented by one command class.
Example: this class offers a commit() method returning an instance of the CommitCommand class. The CommitCommand class has setters for all the arguments and options. The CommitCommand class also has a call method to actually execute the commit. The following code show's how to do a simple commit:

Git git = new Git(myRepo); 
git.commit().setMessage("Fix393").setAuthor(developerIdent).call();

All mandatory parameters for commands have to be specified in the methods of this class, the optional parameters have to be specified by the setter-methods of the Command class.

This class is intended to be used internally (e.g. by JGit tests) or by external components (EGit, third-party tools) when they need exactly the functionality of a GitPorcelain command. There are use-cases where this class is not optimal and where you should use the more low-level JGit classes. The methods in this class may for example offer too much functionality or they offer the functionality with the wrong arguments.
[中]提供一个类似于“GitCellar”的API来与git存储库交互。
GitCellar命令在Git Documentation中描述。
此类仅提供构造所谓命令类的方法。每个命令由一个命令类表示。
示例:此类提供了一个commit()方法,返回CommitCommand类的实例。CommitCommand类具有所有参数和选项的设置器。CommitCommand类还有一个调用方法来实际执行提交。下面的代码演示了如何执行简单的提交:

Git git = new Git(myRepo); 
git.commit().setMessage("Fix393").setAuthor(developerIdent).call();

命令的所有必需参数必须在此类的方法中指定,可选参数必须由命令类的setter方法指定。
当外部组件(EGit,第三方工具)需要git命令的功能时,该类用于内部(例如通过JGit测试)或外部组件(EGit,第三方工具)。在某些用例中,这个类不是最佳的,您应该使用更低级的JGit类。例如,此类中的方法可能提供了太多的功能,或者它们提供的功能带有错误的参数。

代码示例

代码示例来源:origin: gocd/gocd

@Test
public void shouldSwitchToMasterAndDeleteTempBranches() throws Exception, GitAPIException {
  configRepo.checkin(goConfigRevision("v1", "md5-1"));
  configRepo.createBranch(ConfigRepository.BRANCH_AT_HEAD, configRepo.getCurrentRevCommit());
  configRepo.createBranch(ConfigRepository.BRANCH_AT_REVISION, configRepo.getCurrentRevCommit());
  configRepo.git().checkout().setName(ConfigRepository.BRANCH_AT_REVISION).call();
  assertThat(configRepo.git().getRepository().getBranch(), is(ConfigRepository.BRANCH_AT_REVISION));
  assertThat(configRepo.git().branchList().call().size(), is(3));
  configRepo.cleanAndResetToMaster();
  assertThat(configRepo.git().getRepository().getBranch(), is("master"));
  assertThat(configRepo.git().branchList().call().size(), is(1));
}

代码示例来源:origin: apache/incubator-gobblin

private void addEdge(File edgeDir, File edgeFile, String fileContents) throws IOException, GitAPIException {
 createNewFile(edgeDir, edgeFile, fileContents);
 // add, commit, push edge
 this.gitForPush.add().addFilepattern(formEdgeFilePath(edgeDir.getParentFile().getName(), edgeDir.getName(), edgeFile.getName())).call();
 this.gitForPush.commit().setMessage("Edge commit").call();
 this.gitForPush.push().setRemote("origin").setRefSpecs(this.masterRefSpec).call();
}

代码示例来源:origin: checkstyle/checkstyle

private static RevCommitsPair resolveRevCommitsPair(Repository repo) {
  RevCommitsPair revCommitIteratorPair;
  try (RevWalk revWalk = new RevWalk(repo); Git git = new Git(repo)) {
    final Iterator<RevCommit> first;
    final Iterator<RevCommit> second;
    final ObjectId headId = repo.resolve(Constants.HEAD);
    final RevCommit headCommit = revWalk.parseCommit(headId);
    if (isMergeCommit(headCommit)) {
      final RevCommit firstParent = headCommit.getParent(0);
      final RevCommit secondParent = headCommit.getParent(1);
      first = git.log().add(firstParent).call().iterator();
      second = git.log().add(secondParent).call().iterator();
    }
    else {
      first = git.log().call().iterator();
      second = Collections.emptyIterator();
    }
    revCommitIteratorPair =
        new RevCommitsPair(new OmitMergeCommitsIterator(first),
            new OmitMergeCommitsIterator(second));
  }
  catch (GitAPIException | IOException ignored) {
    revCommitIteratorPair = new RevCommitsPair();
  }
  return revCommitIteratorPair;
}

代码示例来源:origin: gocd/gocd

void cleanAndResetToMaster() throws IOException {
  try {
    git.reset().setMode(ResetCommand.ResetType.HARD).call();
    checkout("master");
    deleteBranch(BRANCH_AT_REVISION);
    deleteBranch(BRANCH_AT_HEAD);
  } catch (Exception e) {
    String currentBranch = git.getRepository().getBranch();
    LOGGER.error("Error while trying to clean up config repository, CurrentBranch: {} \n : \n Message: {} \n StackTrace: {}", currentBranch, e.getMessage(), e.getStackTrace(), e);
    throw new RuntimeException(e);
  }
}

代码示例来源:origin: jphp-group/jphp

@Signature
public void __construct(File directory, boolean create) throws IOException, GitAPIException {
  try {
    __wrappedObject = Git.open(directory, FS.DETECTED);
  } catch (RepositoryNotFoundException e) {
    if (create) {
      Git.init().setBare(false).setDirectory(directory).call();
      __wrappedObject = Git.open(directory, FS.DETECTED);
    }
  }
}

代码示例来源:origin: apache/usergrid

/**
 * @param gitConfigFolder e.g. /your/project/root/.git
 *
 * @return Returns true if 'git status' has modified files inside the 'Changes to be committed' section
 */
public static boolean isCommitNecessary( String gitConfigFolder ) throws MojoExecutionException {
  try {
    Repository repo = new FileRepository( gitConfigFolder );
    Git git = new Git( repo );
    Status status = git.status().call();
    Set<String> modified = status.getModified();
    return ( modified.size() != 0 );
  }
  catch ( Exception e ) {
    throw new MojoExecutionException( "Error trying to find out if git commit is needed", e );
  }
}

代码示例来源:origin: centic9/jgit-cookbook

private static void createCommit(Repository repository, Git git, String fileName, String content) throws IOException, GitAPIException {
    // create the file
    File myFile = new File(repository.getDirectory().getParent(), fileName);
    FileUtils.writeStringToFile(myFile, content, "UTF-8");

    // run the add
    git.add()
        .addFilepattern(fileName)
        .call();

    // and then commit the changes
    RevCommit revCommit = git.commit()
        .setMessage("Added " + fileName)
        .call();

    System.out.println("Committed file " + myFile + " as " + revCommit + " to repository at " + repository.getDirectory());
  }
}

代码示例来源:origin: centic9/jgit-cookbook

public static void main(String[] args) throws IOException, GitAPIException {
  final File path;
  try (Repository repository = CookbookHelper.createNewRepository()) {
    try (Git git = new Git(repository)) {
      path = repository.getWorkTree();
      System.out.println("Repository at " + path);
      git.add().addFilepattern("file1.txt").call();
      RevCommit rev1 = git.commit().setAuthor("test", "test@test.com").setMessage("Commit Log 1").call();
      System.out.println("Rev1: " + rev1);
      git.add().addFilepattern("file1.txt").call();
      RevCommit rev2 = git.commit().setAll(true).setAuthor("test", "test@test.com").setMessage("Commit Log 2").call();
      System.out.println("Rev2: " + rev2);
      git.add().addFilepattern("file1.txt").call();
      RevCommit rev3 = git.commit().setAll(true).setAuthor("test", "test@test.com").setMessage("Commit Log 3").call();
      System.out.println("Rev3: " + rev3);
      Iterable<RevCommit> gitLog = git.log().call();
      for (RevCommit logMessage : gitLog) {
        System.out.println("Before revert: " + logMessage.getName() + " - " + logMessage.getFullMessage());
      RevertCommand revertCommand = git.revert();
      gitLog = git.log().call();
      for (RevCommit logMessage : gitLog) {
        System.out.println("After revert: " + logMessage.getName() + " - " + logMessage.getFullMessage());

代码示例来源:origin: centic9/jgit-cookbook

public static void main(String[] args) throws IOException, GitAPIException {
  final File localPath;
  try (Repository repository = CookbookHelper.createNewRepository()) {
    localPath = repository.getWorkTree();
    try (Git git = new Git(repository)) {
      File tempFile = new File(repository.getDirectory().getParentFile(), fileName);
      if(!tempFile.createNewFile()) {
        throw new IOException("Could not create temporary file " + tempFile);
      git.add().addFilepattern(fileName).call();
      git.commit().setMessage("Added untracked file " + fileName + "to repo").call();
      git.checkout().addPath(fileName).call();

代码示例来源:origin: centic9/jgit-cookbook

try (Git git = new Git(repository)) {
  git.add()
      .addFilepattern("testfile")
      .call();
  git.add()
      .addFilepattern("testfile2")
      .call();
  git.commit()
      .setMessage("Added testfiles")
      .call();
  RevCommit stash = git.stashCreate()
      .call();
  stash = git.stashCreate()
      .call();
  Collection<RevCommit> stashes = git.stashList().call();
  for(RevCommit rev : stashes) {
    System.out.println("Found stash: " + rev + ": " + rev.getFullMessage());
  ObjectId call = git.stashDrop().setStashRef(0).call();
  System.out.println("StashDrop returned: " + call);
  ObjectId applied = git.stashApply().setStashRef(stash.getName()).call();
  System.out.println("Applied 2nd stash as: " + applied);

代码示例来源:origin: org.eclipse.jgit/org.eclipse.jgit

checkCallable();
try (RevWalk revWalk = new RevWalk(repo)) {
  newHead = revWalk.parseCommit(headRef.getObjectId());
    if (srcObjectId == null)
      srcObjectId = src.getObjectId();
    RevCommit srcCommit = revWalk.parseCommit(srcObjectId);
    String cherryPickName = srcCommit.getId().abbreviate(7).name()
        + " " + srcCommit.getShortMessage(); //$NON-NLS-1$
    merger.setBase(srcParent.getTree());
    merger.setCommitNames(new String[] { "BASE", ourName, //$NON-NLS-1$
        cherryPickName });
      dco.checkout();
      if (!noCommit)
        newHead = new Git(getRepository()).commit()
            .setMessage(srcCommit.getFullMessage())
            .setReflogComment(reflogPrefix + " " //$NON-NLS-1$
                + srcCommit.getShortMessage())
            .setAuthor(srcCommit.getAuthorIdent())
        repo.writeCherryPickHead(srcCommit.getId());

代码示例来源:origin: apache/incubator-gobblin

fileKey.open(false).create(true);
this.gitForPush = Git.cloneRepository().setURI(GIT_REMOTE_REPO_DIR).setDirectory(new File(GIT_CLONE_DIR)).call();
this.gitForPush.commit().setMessage("First commit").call();
this.gitForPush.push().setRemote("origin").setRefSpecs(new RefSpec("master")).call();

代码示例来源:origin: org.eclipse.jgit/org.eclipse.jgit

checkCallable();
try (RevWalk revWalk = new RevWalk(repo)) {
    if (srcObjectId == null)
      srcObjectId = src.getObjectId();
    RevCommit srcCommit = revWalk.parseCommit(srcObjectId);
        continue;
      DirCacheCheckout dco = new DirCacheCheckout(repo,
          headCommit.getTree(), repo.lockDirCache(),
          merger.getResultTreeId());
      dco.setFailOnConflict(true);
      dco.setProgressMonitor(monitor);
      dco.checkout();
      try (Git git = new Git(getRepository())) {
        newHead = git.commit().setMessage(newMessage)
            .setReflogComment("revert: " + shortMessage) //$NON-NLS-1$
            .call();
        .formatWithConflicts(newMessage,
            merger.getUnmergedPaths());
        repo.writeRevertHead(srcCommit.getId());

代码示例来源:origin: e-biz/androidkickstartr

public Repository createCommit(File srcFolder, String applicationName) throws IOException, GitAPIException {
    Repository repository = repositoryService.createRepository(new Repository().setName(applicationName));

    String cloneUrl = repository.getCloneUrl();

    InitCommand init = new InitCommand();
    init.setDirectory(srcFolder);
    init.setBare(false);
    Git git = init.call();

    StoredConfig config = git.getRepository().getConfig();
    config.setString("remote", "origin", "url", cloneUrl);
    config.save();

    UsernamePasswordCredentialsProvider user = new UsernamePasswordCredentialsProvider(accessToken, "");
    git.add().addFilepattern(".").call();
    git.commit().setMessage(COMMIT_MESSAGE).call();
    git.push().setCredentialsProvider(user).call();

    return repository;
  }
}

代码示例来源:origin: apache/incubator-gobblin

remoteRepo.create(true);
Git gitForPush = Git.cloneRepository().setURI(remoteRepo.getDirectory().getAbsolutePath()).setDirectory(cloneDir).call();
gitForPush.commit().setMessage("First commit").call();
RefSpec masterRefSpec = new RefSpec("master");
gitForPush.push().setRemote("origin").setRefSpecs(masterRefSpec).call();
    + ConfigurationKeys.GIT_MONITOR_REPO_URI, remoteRepo.getDirectory().getAbsolutePath())
  .addPrimitive(GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "." + ConfigurationKeys.GIT_MONITOR_REPO_DIR, TESTDIR + "/git-flowgraph")
  .addPrimitive(GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "." + ConfigurationKeys.GIT_MONITOR_POLLING_INTERVAL, 5)
gitForPush.add().addFilepattern(formNodeFilePath(flowGraphDir, nodeDir.getName(), nodeFile.getName())).call();
gitForPush.commit().setMessage("Node commit").call();
gitForPush.push().setRemote("origin").setRefSpecs(masterRefSpec).call();

代码示例来源:origin: centic9/jgit-cookbook

public static void main(String[] args) throws IOException, GitAPIException {
    try (Git git = new Git(repository)) {
      git.tagDelete().setTags("tag_for_testing").call();
      Ref tag = git.tag().setName("tag_for_testing").call();
      System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory());
      git.tagDelete().setTags("tag_for_testing").call();
      ObjectId id = repository.resolve("HEAD^");
      try (RevWalk walk = new RevWalk(repository)) {
        RevCommit commit = walk.parseCommit(id);
        tag = git.tag().setObjectId(commit).setName("tag_for_testing").call();
        System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory());
        git.tagDelete().setTags("tag_for_testing").call();
        tag = git.tag().setName("tag_for_testing").setAnnotated(true).call();
        System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory());
        git.tagDelete().setTags("tag_for_testing").call();
        walk.dispose();

代码示例来源:origin: centic9/jgit-cookbook

public static void main(String[] args) throws IOException, GitAPIException {
  final File localPath;
  try (Repository repository = CookbookHelper.createNewRepository()) {
    localPath = repository.getWorkTree();
    try (Git git = new Git(repository)) {
      Ref changes = git.branchCreate().setName("changes").call();
      System.out.println("Result of creating the branch: " + changes);
      Ref checkout = git.checkout().setName("changes").call();
      System.out.println("Result of checking out the branch: " + checkout);
      checkout = git.checkout().setName("master").call();
      System.out.println("Result of checking out master: " + checkout);
      ObjectId mergeBase = repository.resolve("changes");
      MergeResult merge = git.merge().
          include(mergeBase).
          setCommit(true).

代码示例来源:origin: org.eclipse.jgit/org.eclipse.jgit

private void addSubmodule(String name, String url, String path,
    String revision, List<CopyFile> copyfiles, List<LinkFile> linkfiles,
    Git git) throws GitAPIException, IOException {
  assert (!repo.isBare());
  assert (git != null);
  if (!linkfiles.isEmpty()) {
    throw new UnsupportedOperationException(
        JGitText.get().nonBareLinkFilesNotSupported);
  }
  SubmoduleAddCommand add = git.submoduleAdd().setName(name).setPath(path)
      .setURI(url);
  if (monitor != null)
    add.setProgressMonitor(monitor);
  Repository subRepo = add.call();
  if (revision != null) {
    try (Git sub = new Git(subRepo)) {
      sub.checkout().setName(findRef(revision, subRepo)).call();
    }
    subRepo.close();
    git.add().addFilepattern(path).call();
  }
  for (CopyFile copyfile : copyfiles) {
    copyfile.copy();
    git.add().addFilepattern(copyfile.dest).call();
  }
}

代码示例来源:origin: org.eclipse.jgit/org.eclipse.jgit

try (Git git = new Git(repo)) {
    CreateBranchCommand command = git.branchCreate();
    command.setName(name);
    if (startCommit != null)
Ref headRef = repo.exactRef(Constants.HEAD);
if (headRef == null) {
if (orphan) {
  if (startPoint == null && startCommit == null) {
    Result r = repo.updateRef(Constants.HEAD).link(
          r.name()));
    this.status = CheckoutResult.NOT_TRIED_RESULT;
    return repo.exactRef(Constants.HEAD);
try (RevWalk revWalk = new RevWalk(repo)) {
  AnyObjectId headId = headRef.getObjectId();
  headCommit = headId == null ? null
      : revWalk.parseCommit(headId);
  newCommit = revWalk.parseCommit(branch);
RevTree headTree = headCommit == null ? null : headCommit.getTree();
  dco = new DirCacheCheckout(repo, headTree, dc,
      newCommit.getTree());
  dco.setFailOnConflict(!force);
  dco.setProgressMonitor(monitor);

代码示例来源:origin: org.eclipse.jgit/org.eclipse.jgit

writeRewrittenHashes();
ObjectReader or = repo.newObjectReader();
  throw new JGitInternalException(
      JGitText.get().cannotResolveUniquelyAbbrevObjectId);
RevCommit commitToPick = walk.parseCommit(ids.iterator().next());
if (shouldPick) {
  if (monitor.isCancelled())
  return null; // continue rebase process on pick command
case REWORD:
  String oldMessage = commitToPick.getFullMessage();
  String newMessage = interactiveHandler
      .modifyCommitMessage(oldMessage);
  try (Git git = new Git(repo)) {
    newHead = git.commit().setMessage(newMessage).setAmend(true)
        .setNoVerify(true).call();
  rebaseState.createFile(AMEND, commitToPick.name());
  return stop(commitToPick, Status.EDIT);
case COMMENT:
  List<RebaseTodoLine> steps = repo.readRebaseTodo(
      rebaseState.getPath(GIT_REBASE_TODO), false);
  RebaseTodoLine nextStep = steps.size() > 0 ? steps.get(0) : null;

相关文章