List of usage examples for org.eclipse.jgit.api Git Git
public Git(Repository repo)
From source file:com.google.gerrit.server.change.IncludedInResolverTest.java
License:Apache License
@Override @Before// w w w. j a v a2s. c o m public void setUp() throws Exception { super.setUp(); /*- The following graph will be created. o tag 2.5, 2.5_annotated, 2.5_annotated_twice |\ | o tag 2.0.1 | o tag 2.0 o | tag 1.3 |/ o c3 | o tag 1.0.1 |/ o tag 1.0 o c2 o c1 */ // TODO(dborowitz): Use try/finally when this doesn't double-close the repo. @SuppressWarnings("resource") Git git = new Git(db); revWalk = new RevWalk(db); // Version 1.0 commit_initial = git.commit().setMessage("c1").call(); git.commit().setMessage("c2").call(); RevCommit commit_v1_0 = git.commit().setMessage("version 1.0").call(); git.tag().setName(TAG_1_0).setObjectId(commit_v1_0).call(); RevCommit c3 = git.commit().setMessage("c3").call(); // Version 1.01 createAndCheckoutBranch(commit_v1_0, BRANCH_1_0); RevCommit commit_v1_0_1 = git.commit().setMessage("verREFS_HEADS_RELsion 1.0.1").call(); git.tag().setName(TAG_1_0_1).setObjectId(commit_v1_0_1).call(); // Version 1.3 createAndCheckoutBranch(c3, BRANCH_1_3); commit_v1_3 = git.commit().setMessage("version 1.3").call(); git.tag().setName(TAG_1_3).setObjectId(commit_v1_3).call(); // Version 2.0 createAndCheckoutBranch(c3, BRANCH_2_0); RevCommit commit_v2_0 = git.commit().setMessage("version 2.0").call(); git.tag().setName(TAG_2_0).setObjectId(commit_v2_0).call(); RevCommit commit_v2_0_1 = git.commit().setMessage("version 2.0.1").call(); git.tag().setName(TAG_2_0_1).setObjectId(commit_v2_0_1).call(); // Version 2.5 createAndCheckoutBranch(commit_v1_3, BRANCH_2_5); git.merge().include(commit_v2_0_1).setCommit(false).setFastForward(FastForwardMode.NO_FF).call(); commit_v2_5 = git.commit().setMessage("version 2.5").call(); git.tag().setName(TAG_2_5).setObjectId(commit_v2_5).setAnnotated(false).call(); Ref ref_tag_2_5_annotated = git.tag().setName(TAG_2_5_ANNOTATED).setObjectId(commit_v2_5).setAnnotated(true) .call(); RevTag tag_2_5_annotated = revWalk.parseTag(ref_tag_2_5_annotated.getObjectId()); git.tag().setName(TAG_2_5_ANNOTATED_TWICE).setObjectId(tag_2_5_annotated).setAnnotated(true).call(); }
From source file:com.google.gerrit.server.git.SubmoduleOpTest.java
License:Apache License
/** * It tests Submodule.update in the scenario a merged commit is an empty one * (it does not have a .gitmodules file) and the project the commit was merged * is not a submodule of other project.//from ww w . j av a 2 s.c o m * * @throws Exception If an exception occurs. */ @Test public void testEmptyCommit() throws Exception { expect(schemaFactory.open()).andReturn(schema); final Repository realDb = createWorkRepository(); final Git git = new Git(realDb); final RevCommit mergeTip = git.commit().setMessage("test").call(); final Branch.NameKey branchNameKey = new Branch.NameKey(new Project.NameKey("test-project"), "test-branch"); expect(urlProvider.get()).andReturn("http://localhost:8080"); expect(schema.submoduleSubscriptions()).andReturn(subscriptions); final ResultSet<SubmoduleSubscription> emptySubscriptions = new ListResultSet<>( new ArrayList<SubmoduleSubscription>()); expect(subscriptions.bySubmodule(branchNameKey)).andReturn(emptySubscriptions); schema.close(); doReplay(); final SubmoduleOp submoduleOp = new SubmoduleOp(branchNameKey, mergeTip, new RevWalk(realDb), urlProvider, schemaFactory, realDb, null, new ArrayList<Change>(), null, null, null, null, null, null); submoduleOp.update(); doVerify(); }
From source file:com.google.gerrit.server.git.SubmoduleOpTest.java
License:Apache License
/** * It tests SubmoduleOp.update in a scenario considering no .gitmodules file * in a merged commit to a destination project/branch that is a source one to * one called "target-project"./*from w ww.ja v a2 s. c o m*/ * <p> * It expects to update the git link called "source-project" to be in target * repository. * </p> * * @throws Exception If an exception occurs. */ @Test public void testOneSubscriberToUpdate() throws Exception { expect(schemaFactory.open()).andReturn(schema); final Repository sourceRepository = createWorkRepository(); final Git sourceGit = new Git(sourceRepository); addRegularFileToIndex("file.txt", "test content", sourceRepository); final RevCommit sourceMergeTip = sourceGit.commit().setMessage("test").call(); final Branch.NameKey sourceBranchNameKey = new Branch.NameKey(new Project.NameKey("source-project"), "refs/heads/master"); final CodeReviewCommit codeReviewCommit = new CodeReviewCommit(sourceMergeTip.toObjectId()); final Change submittedChange = new Change(new Change.Key(sourceMergeTip.toObjectId().getName()), new Change.Id(1), new Account.Id(1), sourceBranchNameKey, TimeUtil.nowTs()); final Map<Change.Id, CodeReviewCommit> mergedCommits = new HashMap<>(); mergedCommits.put(submittedChange.getId(), codeReviewCommit); final List<Change> submitted = new ArrayList<>(); submitted.add(submittedChange); final Repository targetRepository = createWorkRepository(); final Git targetGit = new Git(targetRepository); addGitLinkToIndex("a", sourceMergeTip.copy(), targetRepository); targetGit.commit().setMessage("test").call(); final Branch.NameKey targetBranchNameKey = new Branch.NameKey(new Project.NameKey("target-project"), sourceBranchNameKey.get()); expect(urlProvider.get()).andReturn("http://localhost:8080"); expect(schema.submoduleSubscriptions()).andReturn(subscriptions); final ResultSet<SubmoduleSubscription> subscribers = new ListResultSet<>(Collections.singletonList( new SubmoduleSubscription(targetBranchNameKey, sourceBranchNameKey, "source-project"))); expect(subscriptions.bySubmodule(sourceBranchNameKey)).andReturn(subscribers); expect(repoManager.openRepository(targetBranchNameKey.getParentKey())).andReturn(targetRepository) .anyTimes(); Capture<RefUpdate> ruCapture = new Capture<>(); gitRefUpdated.fire(eq(targetBranchNameKey.getParentKey()), capture(ruCapture)); changeHooks.doRefUpdatedHook(eq(targetBranchNameKey), anyObject(RefUpdate.class), EasyMock.<Account>isNull()); expect(schema.submoduleSubscriptions()).andReturn(subscriptions); final ResultSet<SubmoduleSubscription> emptySubscriptions = new ListResultSet<>( new ArrayList<SubmoduleSubscription>()); expect(subscriptions.bySubmodule(targetBranchNameKey)).andReturn(emptySubscriptions); schema.close(); final PersonIdent myIdent = new PersonIdent("test-user", "test-user@email.com"); doReplay(); final SubmoduleOp submoduleOp = new SubmoduleOp(sourceBranchNameKey, sourceMergeTip, new RevWalk(sourceRepository), urlProvider, schemaFactory, sourceRepository, new Project(sourceBranchNameKey.getParentKey()), submitted, mergedCommits, myIdent, repoManager, gitRefUpdated, null, changeHooks); submoduleOp.update(); doVerify(); RefUpdate ru = ruCapture.getValue(); assertEquals(ru.getName(), targetBranchNameKey.get()); }
From source file:com.google.gerrit.server.git.SubmoduleOpTest.java
License:Apache License
/** * It tests SubmoduleOp.update in a scenario considering established circular * reference in submodule_subscriptions table. * <p>//from w w w . j a v a 2s . co m * In the tested scenario there is no .gitmodules file in a merged commit to a * destination project/branch that is a source one to one called * "target-project". * <p> * submodule_subscriptions table will be incorrect due source appearing as a * subscriber or target-project: according to database target-project has as * source the source-project, and source-project has as source the * target-project. * <p> * It expects to update the git link called "source-project" to be in target * repository and ignoring the incorrect row in database establishing the * circular reference. * </p> * * @throws Exception If an exception occurs. */ @Test public void testAvoidingCircularReference() throws Exception { expect(schemaFactory.open()).andReturn(schema); final Repository sourceRepository = createWorkRepository(); final Git sourceGit = new Git(sourceRepository); addRegularFileToIndex("file.txt", "test content", sourceRepository); final RevCommit sourceMergeTip = sourceGit.commit().setMessage("test").call(); final Branch.NameKey sourceBranchNameKey = new Branch.NameKey(new Project.NameKey("source-project"), "refs/heads/master"); final CodeReviewCommit codeReviewCommit = new CodeReviewCommit(sourceMergeTip.toObjectId()); final Change submittedChange = new Change(new Change.Key(sourceMergeTip.toObjectId().getName()), new Change.Id(1), new Account.Id(1), sourceBranchNameKey, TimeUtil.nowTs()); final Map<Change.Id, CodeReviewCommit> mergedCommits = new HashMap<>(); mergedCommits.put(submittedChange.getId(), codeReviewCommit); final List<Change> submitted = new ArrayList<>(); submitted.add(submittedChange); final Repository targetRepository = createWorkRepository(); final Git targetGit = new Git(targetRepository); addGitLinkToIndex("a", sourceMergeTip.copy(), targetRepository); targetGit.commit().setMessage("test").call(); final Branch.NameKey targetBranchNameKey = new Branch.NameKey(new Project.NameKey("target-project"), sourceBranchNameKey.get()); expect(urlProvider.get()).andReturn("http://localhost:8080"); expect(schema.submoduleSubscriptions()).andReturn(subscriptions); final ResultSet<SubmoduleSubscription> subscribers = new ListResultSet<>(Collections.singletonList( new SubmoduleSubscription(targetBranchNameKey, sourceBranchNameKey, "source-project"))); expect(subscriptions.bySubmodule(sourceBranchNameKey)).andReturn(subscribers); expect(repoManager.openRepository(targetBranchNameKey.getParentKey())).andReturn(targetRepository) .anyTimes(); Capture<RefUpdate> ruCapture = new Capture<>(); gitRefUpdated.fire(eq(targetBranchNameKey.getParentKey()), capture(ruCapture)); changeHooks.doRefUpdatedHook(eq(targetBranchNameKey), anyObject(RefUpdate.class), EasyMock.<Account>isNull()); expect(schema.submoduleSubscriptions()).andReturn(subscriptions); final ResultSet<SubmoduleSubscription> incorrectSubscriptions = new ListResultSet<>( Collections.singletonList( new SubmoduleSubscription(sourceBranchNameKey, targetBranchNameKey, "target-project"))); expect(subscriptions.bySubmodule(targetBranchNameKey)).andReturn(incorrectSubscriptions); schema.close(); final PersonIdent myIdent = new PersonIdent("test-user", "test-user@email.com"); doReplay(); final SubmoduleOp submoduleOp = new SubmoduleOp(sourceBranchNameKey, sourceMergeTip, new RevWalk(sourceRepository), urlProvider, schemaFactory, sourceRepository, new Project(sourceBranchNameKey.getParentKey()), submitted, mergedCommits, myIdent, repoManager, gitRefUpdated, null, changeHooks); submoduleOp.update(); doVerify(); RefUpdate ru = ruCapture.getValue(); assertEquals(ru.getName(), targetBranchNameKey.get()); }
From source file:com.google.gerrit.server.git.SubmoduleOpTest.java
License:Apache License
/** * It calls SubmoduleOp.update method considering scenario only updating * Subscriptions table./* w ww . j a va2 s . c o m*/ * <p> * In this test a commit is created and considered merged to * {@code mergedBranch} branch. * </p> * <p> * The destination project the commit was merged is not considered to be a * source of another project (no subscribers found to this project). * </p> * * @param gitModulesFileContent The .gitmodules file content. * @param mergedBranch The {@code Branch.NameKey} instance representing the * project/branch the commit was merged. * @param extractedSubscriptions The subscription rows extracted from * gitmodules file. * @param previousSubscriptions The subscription rows to be considering as * existing and pointing as target to the {@code mergedBranch} * before updating the table. * @throws Exception If an exception occurs. */ private void doOnlySubscriptionTableOperations(final String gitModulesFileContent, final Branch.NameKey mergedBranch, final List<SubmoduleSubscription> extractedSubscriptions, final List<SubmoduleSubscription> previousSubscriptions) throws Exception { expect(schemaFactory.open()).andReturn(schema); final Repository realDb = createWorkRepository(); final Git git = new Git(realDb); addRegularFileToIndex(".gitmodules", gitModulesFileContent, realDb); final RevCommit mergeTip = git.commit().setMessage("test").call(); expect(urlProvider.get()).andReturn("http://localhost:8080").times(2); expect(schema.submoduleSubscriptions()).andReturn(subscriptions); expect(subscriptions.bySuperProject(mergedBranch)).andReturn(new ListResultSet<>(previousSubscriptions)); SortedSet<Project.NameKey> existingProjects = new TreeSet<>(); for (SubmoduleSubscription extracted : extractedSubscriptions) { existingProjects.add(extracted.getSubmodule().getParentKey()); } for (int index = 0; index < extractedSubscriptions.size(); index++) { expect(repoManager.list()).andReturn(existingProjects); } final Set<SubmoduleSubscription> alreadySubscribeds = new HashSet<>(); for (SubmoduleSubscription s : extractedSubscriptions) { if (previousSubscriptions.contains(s)) { alreadySubscribeds.add(s); } } final Set<SubmoduleSubscription> subscriptionsToRemove = new HashSet<>(previousSubscriptions); final List<SubmoduleSubscription> subscriptionsToInsert = new ArrayList<>(extractedSubscriptions); subscriptionsToRemove.removeAll(subscriptionsToInsert); subscriptionsToInsert.removeAll(alreadySubscribeds); if (!subscriptionsToRemove.isEmpty()) { expect(schema.submoduleSubscriptions()).andReturn(subscriptions); subscriptions.delete(subscriptionsToRemove); } expect(schema.submoduleSubscriptions()).andReturn(subscriptions); subscriptions.insert(subscriptionsToInsert); expect(schema.submoduleSubscriptions()).andReturn(subscriptions); expect(subscriptions.bySubmodule(mergedBranch)) .andReturn(new ListResultSet<>(new ArrayList<SubmoduleSubscription>())); schema.close(); doReplay(); final SubmoduleOp submoduleOp = new SubmoduleOp(mergedBranch, mergeTip, new RevWalk(realDb), urlProvider, schemaFactory, realDb, new Project(mergedBranch.getParentKey()), new ArrayList<Change>(), null, null, repoManager, null, null, null); submoduleOp.update(); }
From source file:com.google.gerrit.server.project.CreateTag.java
License:Apache License
@Override public TagInfo apply(ProjectResource resource, TagInput input) throws RestApiException, IOException { if (input == null) { input = new TagInput(); }//from www. ja v a 2s . com if (input.ref != null && !ref.equals(input.ref)) { throw new BadRequestException("ref must match URL"); } if (input.revision == null) { input.revision = Constants.HEAD; } while (ref.startsWith("/")) { ref = ref.substring(1); } if (ref.startsWith(R_REFS) && !ref.startsWith(R_TAGS)) { throw new BadRequestException("invalid tag name \"" + ref + "\""); } if (!ref.startsWith(R_TAGS)) { ref = R_TAGS + ref; } if (!Repository.isValidRefName(ref)) { throw new BadRequestException("invalid tag name \"" + ref + "\""); } RefControl refControl = resource.getControl().controlForRef(ref); try (Repository repo = repoManager.openRepository(resource.getNameKey())) { ObjectId revid = RefUtil.parseBaseRevision(repo, resource.getNameKey(), input.revision); RevWalk rw = RefUtil.verifyConnected(repo, revid); RevObject object = rw.parseAny(revid); rw.reset(); boolean isAnnotated = Strings.emptyToNull(input.message) != null; boolean isSigned = isAnnotated && input.message.contains("-----BEGIN PGP SIGNATURE-----\n"); if (isSigned) { throw new MethodNotAllowedException("Cannot create signed tag \"" + ref + "\""); } else if (isAnnotated && !refControl.canPerform(Permission.PUSH_TAG)) { throw new AuthException("Cannot create annotated tag \"" + ref + "\""); } else if (!refControl.canPerform(Permission.CREATE)) { throw new AuthException("Cannot create tag \"" + ref + "\""); } if (repo.getRefDatabase().exactRef(ref) != null) { throw new ResourceConflictException("tag \"" + ref + "\" already exists"); } try (Git git = new Git(repo)) { TagCommand tag = git.tag().setObjectId(object).setName(ref.substring(R_TAGS.length())) .setAnnotated(isAnnotated).setSigned(isSigned); if (isAnnotated) { tag.setMessage(input.message).setTagger( identifiedUser.get().newCommitterIdent(TimeUtil.nowTs(), TimeZone.getDefault())); } Ref result = tag.call(); tagCache.updateFastForward(resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId()); referenceUpdated.fire(resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId(), identifiedUser.get().getAccount()); try (RevWalk w = new RevWalk(repo)) { return ListTags.createTagInfo(result, w); } } } catch (InvalidRevisionException e) { throw new BadRequestException("Invalid base revision"); } catch (GitAPIException e) { log.error("Cannot create tag \"" + ref + "\"", e); throw new IOException(e); } }
From source file:com.google.gitiles.DescribeServlet.java
License:Open Source License
private NameRevCommand nameRevCommand(ObjectId id, HttpServletRequest req, HttpServletResponse res) throws IOException { Repository repo = ServletUtils.getRepository(req); GitilesView view = ViewFilter.getView(req); NameRevCommand cmd = new Git(repo).nameRev(); boolean all = getBooleanParam(view, ALL_PARAM); boolean tags = getBooleanParam(view, TAGS_PARAM); if (all && tags) { renderTextError(req, res, SC_BAD_REQUEST, "Cannot specify both \"all\" and \"tags\""); return null; }//from w w w . j a va2 s. c o m if (all) { cmd.addPrefix(Constants.R_REFS); } else if (tags) { cmd.addPrefix(Constants.R_TAGS); } else { cmd.addAnnotatedTags(); } cmd.add(id); return cmd; }
From source file:com.googlesource.gerrit.plugins.findowners.OwnersValidatorTest.java
License:Apache License
private static RevCommit makeCommit(RevWalk rw, Repository repo, String message, Map<File, byte[]> files) throws IOException, GitAPIException { try (Git git = new Git(repo)) { if (files != null) { addFiles(git, files);//from w w w. j av a2 s . c om } return rw.parseCommit(git.commit().setMessage(message).call()); } }
From source file:com.googlesource.gerrit.plugins.smartreviewers.SmartReviewers.java
License:Apache License
/** * Fill a map of all the possible reviewers based on the last reviews they made * on the modified file./*from ww w .ja va2 s . c om*/ * * @param entry {@link PatchListEntry} * @param reviewers the reviewer hash table to fill */ void getReviewersFromLastReviews(final PatchListEntry entry, Map<Account, Integer> reviewers) { Git git = new Git(repo); Iterable<RevCommit> commits; // Get the last 10 commits impacting the file try { commits = git.log().addPath(entry.getNewName()).setMaxCount(10).call(); } catch (Exception ex) { log.error("Couldn't execute log for file {}", entry.getNewName(), ex); return; } // For each commit... for (RevCommit commit : commits) { List<String> change_ids = commit.getFooterLines("Change-Id"); if (change_ids.size() != 1) { continue; } // Get the related changes List<Change> changes; try { Change.Key key = new Change.Key(change_ids.get(0)); changes = reviewDb.changes().byKey(key).toList(); } catch (Exception ex) { log.error("Couldn't get changes related to change-id {}", change_ids.get(0), ex); continue; } // For each related change, add accounts who reviewed the file before for (Change change : changes) { try { Set<Id> authors = new HashSet<Id>(); List<ChangeMessage> messages = reviewDb.changeMessages().byChange(change.getId()).toList(); for (ChangeMessage message : messages) { authors.add(message.getAuthor()); } List<PatchSetApproval> psas = reviewDb.patchSetApprovals().byChange(change.getId()).toList(); for (PatchSetApproval psa : psas) { if (psa.getValue() == 0) { continue; } Account account = reviewDb.accounts().get(psa.getAccountId()); if (!authors.isEmpty() && !authors.contains(psa.getAccountId())) { continue; } if (!psa.getLabel().contains("Code-Review")) { continue; } addAccount(account, reviewers, weightLastReviews); } } catch (OrmException e) { log.error("getReviewersFromLastReviews() failed"); e.printStackTrace(); } } } }
From source file:com.googlesource.gerrit.plugins.testplugin.OvirtPatchSetListener.java
License:Apache License
private Set<String> getAddedDbscripts(Project.NameKey projectName, RevTree targetRevTree) { try (Repository repository = repoFromProjectKey(projectName, manager).get(); ObjectReader reader = repository.newObjectReader(); RevWalk revWalk = new RevWalk(repository)) { CanonicalTreeParser oldTreeIter = new CanonicalTreeParser(); oldTreeIter.reset(reader,//from www .j a va 2 s .com revWalk.parseCommit(repository.resolve(Constants.HEAD).toObjectId()).getTree()); CanonicalTreeParser newTreeIter = new CanonicalTreeParser(); newTreeIter.reset(reader, targetRevTree); // finally get the list of changed files try (Git git = new Git(repository)) { List<DiffEntry> diffs = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call(); return diffs.stream().filter(entry -> entry.getChangeType() == DiffEntry.ChangeType.ADD) .filter(entry -> entry.getNewPath().startsWith(FOLDER_PREFIX)) .map(entry -> Paths.get(entry.getNewPath()).getFileName().toString()) .collect(Collectors.toSet()); } } catch (IOException | GitAPIException e) { throw new RuntimeException(e); } }