@Test public void testUpdateTrackingBranchIfSpecifiedInRemoteRefUpdate() throws Exception { // Commit on repository 2 // RevCommit commit = repository2.addAndCommit(project, new File(workdir2, "test.txt"), "Commit // in repository 2"); System.out.println(repository2.getBranch()); new Git(repository2).checkout().setName("refs/heads/test").call(); System.out.println(repository2.getBranch()); ArrayList<String> files = new ArrayList<String>(); File file = new File(workdir2, "test.txt"); FileUtils.createNewFile(file); repositoryUtil.appendFileContent(file, "create file of test.txt in repository 2"); files.add(repositoryUtil.getRepoRelativePath(file.getAbsolutePath())); AddToIndexOperation trop = new AddToIndexOperation(files, repository2); trop.execute(); CommitOperation cop = new CommitOperation(repository2, files, files, AUTHOR, COMMITTER, "Commit in repository 2"); cop.execute(); // We want to push from repository 2 to 1 (because repository 2 already // has tracking set up) // URIish remote = repository1.getUri(); URIish remote = new URIish("file:///" + repository1.getDirectory().toString()); String trackingRef = "refs/remotes/origin/master"; RemoteRefUpdate update = new RemoteRefUpdate(repository2, "HEAD", "refs/heads/master", false, trackingRef, null); PushOperationSpecification spec = new PushOperationSpecification(); spec.addURIRefUpdates(remote, Arrays.asList(update)); PushOperation push = new PushOperation(repository2, spec, false, 0); push.execute(); PushOperationResult result = push.getOperationResult(); PushResult pushResult = result.getPushResult(remote); TrackingRefUpdate trf = pushResult.getTrackingRefUpdate(trackingRef); System.out.println(trf.getLocalName()); System.out.println(trf.getRemoteName()); assertNotNull( "Expected result to have tracking ref update", pushResult.getTrackingRefUpdate(trackingRef)); ObjectId trackingId = repository2.resolve(trackingRef); assertEquals("Expected tracking branch to be updated", cop.getCommit().getId(), trackingId); new Git(repository1).checkout().setName("refs/heads/master").call(); File testFile = new File(workdir2, repositoryUtil.getRepoRelativePath(file.getAbsolutePath())); assertTrue(testFile.exists()); }
// 2. Get branch/commit hash for the source repo - the actual source code @Test public void existsIn() throws IOException { // final String repo = "binrepo-devex"; // final String repo = "search_raptor_binary"; // String githubUrl = "https://github.scm.corp.ebay.com/api/v3"; // String accessToken = "1cf7d9792235b8592eda18bd7dcc2de37f99b3bc"; final String path = "D:\\dev\\devex\\binrepo-devex\\.git"; File gitDir = new File(path); org.eclipse.jgit.lib.Repository repository = new org.eclipse.jgit.storage.file.FileRepository(gitDir); String branch = repository.getBranch(); System.out.println(branch); RevWalk revWalk = new RevWalk(repository); // Pop the most recent commit off from RevWalk // RevCommit commit = revWalk.next(); returns null :-( // System.out.println(commit); ObjectId resolve = repository.resolve(Constants.HEAD); RevCommit commit = revWalk.parseCommit(resolve); String commitHash = commit.getName(); System.out.println(commitHash + "\t" + commit.getFullMessage()); // RefDatabase refDatabase = repository.getRefDatabase(); }
private String getBranch(final Repository repository) throws IOException { if (this.branch != null) { return this.branch; } else { return repository.getBranch(); } }
private static String getCurrentBranch(Repository repository) throws CoreException { String branch = null; try { branch = repository.getBranch(); } catch (IOException e) { throw new CoreException( createStatus( e, "Could not get current branch on repository \"{0}\"", repository.toString())); } return branch; }
/** * Push from repository1 "master" into "test" of repository2. * * @throws Exception */ @Test public void testPush() throws Exception { // push from repository1 to repository2 System.out.println(repository2.getBranch()); PushOperation pop = createPushOperation(); pop.execute(); assertEquals( org.eclipse.jgit.transport.RemoteRefUpdate.Status.UP_TO_DATE, getStatus(pop.getOperationResult())); System.out.println(pop.toString()); ArrayList<String> files = new ArrayList<String>(); File file = new File(workdir, "file2.txt"); FileUtils.createNewFile(file); repositoryUtil.appendFileContent(file, "new file"); files.add(repositoryUtil.getRepoRelativePath(file.getAbsolutePath())); AddToIndexOperation trop = new AddToIndexOperation(files, repository1); trop.execute(); CommitOperation cop = new CommitOperation(repository1, files, files, AUTHOR, COMMITTER, "added files"); cop.execute(); pop = createPushOperation(); pop.execute(); assertEquals( org.eclipse.jgit.transport.RemoteRefUpdate.Status.OK, getStatus(pop.getOperationResult())); System.out.println(pop.toString()); try { // assert that we cannot run this again pop.execute(); fail("Expected Exception not thrown"); } catch (IllegalStateException e) { // expected } pop = createPushOperation(); pop.execute(); assertEquals( org.eclipse.jgit.transport.RemoteRefUpdate.Status.UP_TO_DATE, getStatus(pop.getOperationResult())); System.out.println(pop.toString()); File testFile = new File(workdir2, repositoryUtil.getRepoRelativePath(file.getAbsolutePath())); assertFalse(testFile.exists()); testFile = new File(workdir, repositoryUtil.getRepoRelativePath(file.getAbsolutePath())); assertTrue(testFile.exists()); // check out test and verify the file is there new Git(repository2).checkout().setName("refs/heads/test").call(); testFile = new File(workdir2, repositoryUtil.getRepoRelativePath(file.getAbsolutePath())); assertTrue(testFile.exists()); }
protected void doPull() throws MojoExecutionException { // CredentialsProvider cp = getCredentials(); CredentialsProvider cp = null; try { Repository repository = git.getRepository(); StoredConfig config = repository.getConfig(); String url = config.getString("remote", "origin", "url"); if (Strings.isNullOrBlank(url)) { getLog() .info( "No remote repository defined for the git repository at " + getGitBuildPathDescription() + " so not doing a pull"); return; } String branch = repository.getBranch(); String mergeUrl = config.getString("branch", branch, "merge"); if (Strings.isNullOrBlank(mergeUrl)) { getLog() .info( "No merge spec for branch." + branch + ".merge in the git repository at " + getGitBuildPathDescription() + " so not doing a pull"); return; } getLog() .info( "Performing a pull in git repository " + getGitBuildPathDescription() + " on remote URL: " + url); git.pull().setCredentialsProvider(cp).setRebase(true).call(); } catch (Throwable e) { String credText = ""; if (cp instanceof UsernamePasswordCredentialsProvider) {} String message = "Failed to pull from the remote git repo with credentials " + cp + " due: " + e.getMessage() + ". This exception is ignored."; getLog().error(message, e); throw new MojoExecutionException(message, e); } }
private List<String> branchesToBeDelete(List<String> branchesList) { List<String> result = new ArrayList<>(); Repository repo = null; Map<String, List<String>> branchesMap = new HashMap<>(); for (String branch : branchesList) { List<String> values = null; if (!branchesMap.containsKey(branch.subSequence(0, 10))) { values = new ArrayList<>(); values.add(branch); branchesMap.put(branch.subSequence(0, 10).toString(), values); } else if (!branchesMap.get(branch.subSequence(0, 10)).contains(branch)) { values = branchesMap.get(branch.subSequence(0, 10)); values.add(branch); branchesMap.put(branch.subSequence(0, 10).toString(), values); } } List<CommitItem> allBranches = CollectorApi.getCommitItemContainer().getAll(); for (CommitItem branch : allBranches) { if (branchesMap.containsKey(branch.getBranchDescriptor().getNewBranch().subSequence(0, 10))) { branchesMap.remove(branch.getBranchDescriptor().getNewBranch().subSequence(0, 10)); } } for (String key : branchesMap.keySet()) { result.addAll(branchesMap.get(key)); } try { repo = new FileRepository(VerigreenNeededLogic.properties.getProperty("git.repositoryLocation")); if (result.contains(repo.getBranch())) { _jgit.checkout(VerigreenNeededLogic.VerigreenMap.get("_protectedBranches"), false, false); } } catch (IOException e) { VerigreenLogger.get() .error( getClass().getName(), RuntimeUtils.getCurrentMethodName(), String.format( "Failed creating git repository for path [%s]", VerigreenNeededLogic.properties.getProperty("git.repositoryLocation")), e); } return result; }
// 2. Get branch/commit hash for the source repo - the actual source code @Test public void existsIn2() throws IOException { final String repo = "binrepo-devex"; // final String repo = "search_raptor_binary"; // String githubUrl = "https://github.scm.corp.ebay.com/api/v3"; // String accessToken = "1cf7d9792235b8592eda18bd7dcc2de37f99b3bc"; final String path = "D:\\dev\\devex\\.binrepo-devex\\.git"; File gitDir = new File(path); org.eclipse.jgit.lib.Repository repository = new org.eclipse.jgit.storage.file.FileRepository(gitDir); String branch = repository.getBranch(); System.out.println("Branch=" + branch); final Map<String, Ref> allRefs = repository.getAllRefs(); for (String s : allRefs.keySet()) { System.out.println("Here" + s); } RevWalk revWalk = new RevWalk(repository); ObjectId resolve = repository.resolve(Constants.HEAD); RevCommit commitRev = revWalk.parseCommit(resolve); String commitHash = commitRev.getName(); System.out.println(commitHash + "\t" + commitRev.getFullMessage()); Git binaryRepo = Git.open(gitDir); final ListBranchCommand listBranchCommand = binaryRepo.branchList(); System.out.println(listBranchCommand.getRepository().getFullBranch()); // get "status" final StatusCommand statusCommand = binaryRepo.status(); Collection<String> toadd = GitUtils.getFilesToStage(statusCommand); for (String s : toadd) { System.out.println("To be added:" + s); } // add files to "staging" if (toadd.size() > 0) { AddCommand addCmd = binaryRepo.add(); for (String file : toadd) { addCmd.addFilepattern(file); } try { addCmd.call(); } catch (Exception e) { e.printStackTrace(); } } final StoredConfig config = repository.getConfig(); String url = config.getString("remote", "origin", "url"); if (url != null) { System.out.println("Origin comes from " + url); } // commit final CommitCommand commit = binaryRepo.commit(); String msg = "Saving Repo:%s Branch:%s CommitHash:%s Time:%s"; final String formattedMsg = String.format(msg, repo, branch, commitHash, new Date().toString()); commit.setMessage(formattedMsg); try { commit.call(); } catch (Exception e) { e.printStackTrace(); } // push to origin now final PushCommand push = binaryRepo.push(); final String remote = push.getRemote(); System.out.println("Remote to push to:'" + remote + "'"); try { push.call(); } catch (Exception e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } }
public String getProjectVersion(File repoDir) throws IOException, GitAPIException { Git git = Git.open(repoDir); Repository repo = git.getRepository(); // Find base commit between current branch and "master": String branch = repo.getBranch(); RevCommit base = CommitUtils.getBase(repo, "master", branch); CommitCountFilter count = new CommitCountFilter(); CommitFinder finder = new CommitFinder(repo).setFilter(count); finder.findBetween(branch, base); long commitsSinceBase = count.getCount(); // Find tags in "master" before base commit: RevWalk rw = new RevWalk(repo); rw.markStart(base); rw.setRetainBody(false); Ref master = repo.getRef("master"); List<Ref> masterAsList = Arrays.asList(master); List<Ref> tags = git.tagList().call(); Map<RevCommit, Ref> masterTags = new HashMap<RevCommit, Ref>(); for (Ref tag : tags) { tag = repo.peel(tag); ObjectId commitID = tag.getPeeledObjectId(); if (commitID == null) continue; RevCommit commit = rw.parseCommit(commitID); // Only remember tags reachable from "master": if (!RevWalkUtils.findBranchesReachableFrom(commit, rw, masterAsList).isEmpty()) { masterTags.put(commit, tag); } } // Find the shortest distance in commits between base tag in "master": long commitsBetweenBaseAndTag = Long.MAX_VALUE; String tagName = ""; for (RevCommit tagCommit : masterTags.keySet()) { count.reset(); finder.findBetween(base, tagCommit); if (count.getCount() < commitsBetweenBaseAndTag) { commitsBetweenBaseAndTag = count.getCount(); tagName = masterTags.get(tagCommit).getName(); } } if (commitsBetweenBaseAndTag == Long.MAX_VALUE) { // If no tag, get total number of commits: commitsBetweenBaseAndTag = repo.getRefDatabase().getRefs("").size(); } long commitsSinceLastMasterTag = commitsSinceBase + commitsBetweenBaseAndTag; // Construct version string: String version = branch.equals("master") ? "" : (branch + "-"); if (tagName.startsWith("refs/tags/")) { tagName = tagName.substring("refs/tags/".length()); } // v1.1 -> 1.1 if (tagName.matches("v\\d+.*")) { tagName = tagName.substring(1); } if (tagName.isEmpty()) { version = "0"; } version += tagName + ((!tagonly) ? "." + commitsSinceLastMasterTag : ""); return version; }
public void updateBinaryRepository() throws IOException, GitException, MapServiceException { // 1. Check if repository exists remotely [email protected]/Binary/Repo_Binary.git // find the name of the "source repository" final String repoUrl = getSourceRemoteUrl(); // find where ".git" folder is found // SourceRepository = D:\dev\devex\binrepo-devex // BinaryRepository = D:\dev\devex\.binrepo-devex final File srcRepoDir = sourceRepository.getDirectory(); final File sourceDir = srcRepoDir.getParentFile(); final String sourceRepoFolder = srcRepoDir.getParentFile().getCanonicalPath(); final File parent = srcRepoDir.getParentFile().getParentFile(); final File binaryRepoDir = new File(parent, "." + srcRepoDir.getParentFile().getName()); System.out.println( "SourceRepository = " + sourceRepoFolder + "\nBinaryRepository = " + binaryRepoDir.getCanonicalPath()); // 2. Get branch/commit hash for the source repo - the actual source code final org.eclipse.jgit.lib.Repository repository = new org.eclipse.jgit.storage.file.FileRepository(srcRepoDir); final String branch = repository.getBranch(); final RevWalk revWalk = new RevWalk(repository); final ObjectId resolve = repository.resolve(Constants.HEAD); final RevCommit commit = revWalk.parseCommit(resolve); String commitHash = commit.getName(); System.out.println("CommitHash:" + commitHash + "\tMessage:" + commit.getFullMessage()); // 3. Call the BinRepo service and check if a corresponding BinRepo entry exists final String url = getUrlForFindByRepoBranchCommit() + "repourl=" + URLEncoder.encode(repoUrl, UTF_8) + "&branch=" + URLEncoder.encode(branch, UTF_8) + "&commitid=" + URLEncoder.encode(commitHash, UTF_8); System.out.println("svc url : " + url); WebResource webResource = client.resource(url); boolean noContent = false; BinRepoBranchCommitDO binRepoBranchCommitDO1 = null; try { binRepoBranchCommitDO1 = webResource.accept(MediaType.APPLICATION_JSON).get(BinRepoBranchCommitDO.class); } catch (UniformInterfaceException e) { int statusCode = e.getResponse().getClientResponseStatus().getStatusCode(); System.out.println("Service Status Code : " + statusCode); noContent = (statusCode == 204 || statusCode == 404); // HTTP 204 is NO CONTENT which is ok for us } catch (Exception e) { // Catch-all to deal with network problems etc. e.printStackTrace(); } System.out.println( binRepoBranchCommitDO1 != null ? binRepoBranchCommitDO1.toString() : "Resource not found on server"); // 4. If not copy all the target folders from the source repo to the binary repo - root to root // copy of artifacts if (noContent) { System.out.println( "Source Directory:'" + sourceDir.getCanonicalPath() + "' Destination Directory:'" + binaryRepoDir.getCanonicalPath() + "'"); FileUtil.copyBinaries(sourceDir, binaryRepoDir); } // 5. Call git status to get the delta (Use StatusCommand and refine it) Git binaryRepo; try { binaryRepo = Git.open(binaryRepoDir); } catch (IOException e) { throw new GitException("Unable to open repository" + binaryRepoDir, e); } // get "status" final StatusCommand statusCommand = binaryRepo.status(); // TODO: RGIROTI Ask Nambi if we should actually filter this to only add .class files and // nothing else Collection<String> filesToStage = GitUtils.getFilesToStage(statusCommand); /*for (String file : filesToStage) { System.out.println("File to be added:" + file); }*/ // add files to "staging" - if there is nothing to stage none of the other operations make any // sense at all if (filesToStage.size() > 0) { final AddCommand addCmd = binaryRepo.add(); for (String file : filesToStage) { addCmd.addFilepattern(file); } final String[] filesArr = filesToStage.toArray(new String[filesToStage.size()]); final String files = StringUtils.join(filesArr, ","); try { addCmd.call(); } catch (Exception e) { throw new GitException("Unable to add files to repository" + files, e); } // 6. Commit the changes to local and call push after that (use JGit API for this) // 6a. COmmit message should use format "Saving url:branch:commit:UTC time" // commit final CommitCommand commitCommand = binaryRepo.commit(); String msg = "Saving Repo:%s Branch:%s CommitHash:%s Time:%s"; final String formattedMsg = String.format(msg, repoUrl, branch, commitHash, new Date().toString()); commitCommand.setMessage(formattedMsg); String commitHashBinRepo; try { final RevCommit call = commitCommand.call(); commitHashBinRepo = call.getName(); } catch (Exception e) { throw new GitException("Unable to read commit hash from commit command", e); } // push to origin now final PushCommand push = binaryRepo.push(); final String remote = push.getRemote(); final String remoteBranch = push.getRepository().getBranch(); System.out.println("Remote to push to:'" + remote + "'"); try { push.call(); } catch (Exception e) { throw new GitException("Unable to push to remote", e); } // Calculate the remote url for binary repository String binRepoUrl = calculateBinaryRepositoryUrl(); // 7. Call the BinRepo service and create a new entity for this change - repoUrl, branch, and // commit System.out.println( "Update Bin Repo Service with the new changes - POST new object to service"); final BinRepoBranchCommitDO binRepoBranchCommitDO = newInstance(repoUrl, branch, commitHash, binRepoUrl, remoteBranch, commitHashBinRepo); webResource = client.resource(getUrlForPost()); BinRepoBranchCommitDO postedDO = null; try { postedDO = webResource .accept(MediaType.APPLICATION_XML) .post(BinRepoBranchCommitDO.class, binRepoBranchCommitDO); } catch (UniformInterfaceException e) { int statusCode = e.getResponse().getClientResponseStatus().getStatusCode(); System.out.println("status code: " + statusCode); throw new MapServiceException("Unable to register the commit details in update binrepo", e); } System.out.println(postedDO != null ? postedDO.toString() : "Post failed"); } }
private void testPushToOrigin(boolean useRemote) throws Exception { Activator.getDefault().getRepositoryUtil().addConfiguredRepository(clonedRepositoryFile); shareProjects(clonedRepositoryFile); Repository repository = lookupRepository(clonedRepositoryFile); // add the configuration for push repository .getConfig() .setString("remote", "origin", "push", "refs/heads/*:refs/remotes/origin/*"); repository.getConfig().save(); // make sure to have a "new" branch name so that the // dialog will return with a corresponding message String currentBranch = repository.getBranch(); new Git(repository) .branchRename() .setOldName(currentBranch) .setNewName("" + System.currentTimeMillis()) .call(); SWTBotTree tree = getOrOpenView().bot().tree(); tree.select(0); TestUtil.waitForJobs(50, 5000); selectNode(tree, useRemote, false); runPush(tree); String destinationString = clonedRepositoryFile.getParentFile().getName() + " - " + "origin"; String dialogTitle = NLS.bind(UIText.PushResultDialog_title, destinationString); // first time: expect new branch SWTBotShell confirmed = bot.shell(dialogTitle); SWTBotTreeItem[] treeItems = confirmed.bot().tree().getAllItems(); boolean newBranch = false; for (SWTBotTreeItem item : treeItems) { newBranch = item.getText().contains(UIText.PushResultTable_statusOkNewBranch); if (newBranch) break; } confirmed.close(); assertTrue("New branch expected", newBranch); // second time: expect up to date selectNode(tree, useRemote, false); runPush(tree); confirmed = bot.shell(dialogTitle); treeItems = confirmed.bot().tree().getAllItems(); boolean uptodate = false; for (SWTBotTreeItem item : treeItems) { uptodate = item.getText().contains(UIText.PushResultTable_statusUpToDate); if (uptodate) break; } confirmed.close(); assertTrue("Up to date expected", uptodate); // touch and run again: expect new branch String objectIdBefore = repository.getRef(repository.getFullBranch()).getLeaf().getObjectId().name(); objectIdBefore = objectIdBefore.substring(0, 7); touchAndSubmit(null); SWTBotTree updatedTree = getOrOpenView().bot().tree(); updatedTree.select(0); selectNode(updatedTree, useRemote, false); runPush(updatedTree); confirmed = bot.shell(dialogTitle); treeItems = confirmed.bot().tree().getAllItems(); newBranch = false; for (SWTBotTreeItem item : treeItems) { newBranch = item.getText().contains(objectIdBefore); if (newBranch) break; } confirmed.close(); assertTrue("New branch expected", newBranch); }
public StyledString getStyledText(Object element) { if (!(element instanceof RepositoryTreeNode)) return null; RepositoryTreeNode node = (RepositoryTreeNode) element; try { switch (node.getType()) { case REPO: Repository repository = (Repository) node.getObject(); File directory = repository.getDirectory(); StyledString string = new StyledString(directory.getParentFile().getName()); string.append( " - " + directory.getAbsolutePath(), StyledString.QUALIFIER_STYLER); // $NON-NLS-1$ String branch = repository.getBranch(); if (repository.getRepositoryState() != RepositoryState.SAFE) branch += " - " + repository.getRepositoryState().getDescription(); // $NON-NLS-1$ string.append( " [" + branch + "]", StyledString.DECORATIONS_STYLER); // $NON-NLS-1$//$NON-NLS-2$ return string; case ADDITIONALREF: Ref ref = (Ref) node.getObject(); // shorten the name StyledString refName = new StyledString(Repository.shortenRefName(ref.getName())); if (ref.isSymbolic()) { refName.append(" - ", StyledString.QUALIFIER_STYLER); // $NON-NLS-1$ refName.append(ref.getLeaf().getName(), StyledString.QUALIFIER_STYLER); refName.append(" - ", StyledString.QUALIFIER_STYLER); // $NON-NLS-1$ refName.append( ObjectId.toString(ref.getLeaf().getObjectId()), StyledString.QUALIFIER_STYLER); } else { refName.append(" - ", StyledString.QUALIFIER_STYLER); // $NON-NLS-1$ refName.append(ObjectId.toString(ref.getObjectId()), StyledString.QUALIFIER_STYLER); } return refName; case WORKINGDIR: StyledString dirString = new StyledString(UIText.RepositoriesView_WorkingDir_treenode); dirString.append(" - ", StyledString.QUALIFIER_STYLER); // $NON-NLS-1$ if (node.getRepository().isBare()) { dirString.append( UIText.RepositoriesViewLabelProvider_BareRepositoryMessage, StyledString.QUALIFIER_STYLER); } else { dirString.append( node.getRepository().getWorkTree().getAbsolutePath(), StyledString.QUALIFIER_STYLER); } return dirString; case PUSH: // fall through case FETCH: // fall through case FILE: // fall through case FOLDER: // fall through case BRANCHES: // fall through case LOCAL: // fall through case REMOTETRACKING: // fall through case BRANCHHIERARCHY: // fall through case TAGS: // fall through; case ADDITIONALREFS: // fall through case REMOTES: // fall through case REMOTE: // fall through case ERROR: // fall through case REF: // fall through case TAG: { String label = getSimpleText(node); if (label != null) return new StyledString(label); } } } catch (IOException e) { Activator.logError(e.getMessage(), e); } return null; }