List of usage examples for org.eclipse.jgit.lib Repository getBranch
@Nullable public String getBranch() throws IOException
From source file:pl.project13.maven.git.GitCommitIdMojo.java
License:Open Source License
/** * If running within Jenkins/Hudosn, honor the branch name passed via GIT_BRANCH env var. This * is necessary because Jenkins/Hudson alwways invoke build in a detached head state. * * @param git/*ww w .j a va 2 s .com*/ * @param env * @return results of git.getBranch() or, if in Jenkins/Hudson, value of GIT_BRANCH */ protected String determineBranchName(Repository git, Map<String, String> env) throws IOException { if (runningOnBuildServer(env)) { return determineBranchNameOnBuildServer(git, env); } else { return git.getBranch(); } }
From source file:pl.project13.maven.git.GitCommitIdMojo.java
License:Open Source License
/** * Is "Jenkins aware", and prefers {@code GIT_BRANCH} to getting the branch via git if that enviroment variable is set. * The {@GIT_BRANCH} variable is set by Jenkins/Hudson when put in detached HEAD state, but it still knows which branch was cloned. *//* ww w . j a v a 2s .c o m*/ protected String determineBranchNameOnBuildServer(Repository git, Map<String, String> env) throws IOException { String enviromentBasedBranch = env.get("GIT_BRANCH"); if (isNullOrEmpty(enviromentBasedBranch)) { log("Detected that running on CI enviroment, but using repository branch, no GIT_BRANCH detected."); return git.getBranch(); } else { log("Using environment variable based branch name.", "GIT_BRANCH =", enviromentBasedBranch); return enviromentBasedBranch; } }
From source file:pl.project13.maven.git.GitCommitIdMojoTest.java
License:Open Source License
@Test public void shouldUseJenkinsBranchInfoWhenAvailable() throws IOException { // given// ww w. j a v a2 s .c o m Repository git = mock(Repository.class); Map<String, String> env = Maps.newHashMap(); String detachedHeadSHA1 = "16bb801934e652f5e291a003db05e364d83fba25"; String ciUrl = "http://myciserver.com"; when(git.getBranch()).thenReturn(detachedHeadSHA1); // when // in a detached head state, getBranch() will return the SHA1...standard behavior assertThat(detachedHeadSHA1).isEqualTo(mojo.determineBranchName(git, env)); // again, SHA1 will be returned if we're in jenkins, but GIT_BRANCH is not set env.put("JENKINS_URL", "http://myjenkinsserver.com"); assertThat(detachedHeadSHA1).isEqualTo(mojo.determineBranchName(git, env)); // now set GIT_BRANCH too and see that the branch name from env var is returned env.clear(); env.put("JENKINS_URL", ciUrl); env.put("GIT_BRANCH", "mybranch"); assertThat("mybranch").isEqualTo(mojo.determineBranchName(git, env)); // same, but for hudson env.clear(); env.put("GIT_BRANCH", "mybranch"); env.put("HUDSON_URL", ciUrl); assertThat("mybranch").isEqualTo(mojo.determineBranchName(git, env)); // GIT_BRANCH but no HUDSON_URL or JENKINS_URL env.clear(); env.put("GIT_BRANCH", "mybranch"); assertThat(detachedHeadSHA1).isEqualTo(mojo.determineBranchName(git, env)); }
From source file:replicatorg.app.ui.panels.UpdateChecker.java
License:Open Source License
private void updateFilaments() { final FileRepositoryBuilder repoBuilder = new FileRepositoryBuilder(); final Git git; final Status repoStatus; final RemoteAddCommand remoteAddCmd; ResetCommand resetCmd;/*from w w w.j av a 2s.c om*/ CheckoutCommand checkoutCmd; final String currentBranch, newBranch; final List<Ref> branchList; Repository filamentsRepo; boolean branchFoundLocally = false; RevCommit stash = null; repoBuilder.setMustExist(true); repoBuilder.setGitDir(new File(FILAMENTS_REPO_PATH + ".git")); try { try { Base.writeLog("Attempting to open repo at " + FILAMENTS_REPO_PATH, this.getClass()); filamentsRepo = repoBuilder.build(); } catch (RepositoryNotFoundException ex) { try { Base.writeLog("Repository wasn't initialized, initializing it to the given URL: " + FILAMENTS_REPO_URL, this.getClass()); repoBuilder.setMustExist(false); filamentsRepo = repoBuilder.build(); filamentsRepo.create(); } catch (IOException ex1) { Base.writeLog("IOException while attempting to initialize repository, not updating filaments", this.getClass()); return; } } currentBranch = filamentsRepo.getBranch(); } catch (IOException ex) { Base.writeLog("IOException while attempting to open repository, not updating filaments", this.getClass()); return; } git = new Git(filamentsRepo); try { // it should be only 1, but it shortens the code needed, as the call() // method returns an iterable for (RevCommit commit : git.log().setMaxCount(1).call()) { Base.writeLog("Current commit hash: " + commit, this.getClass()); } } catch (GitAPIException ex) { Base.writeLog( "GitAPIException while attempting to get current commit's hash. Not a critical error, so proceeding with update", this.getClass()); } try { remoteAddCmd = git.remoteAdd(); remoteAddCmd.setName("origin"); remoteAddCmd.setUri(new URIish(FILAMENTS_REPO_URL)); remoteAddCmd.call(); } catch (URISyntaxException ex) { Base.writeLog("Invalid git filament repo remote URL!", this.getClass()); return; } catch (GitAPIException ex) { Base.writeLog("GitAPIException thrown when adding remote to git filament repo", this.getClass()); return; } try { if (currentBranch.equals(FILAMENTS_REPO_BRANCH) == false) { Base.writeLog("Repo branch is " + currentBranch + " and it should be " + FILAMENTS_REPO_BRANCH + ", searching for it", this.getClass()); checkoutCmd = git.checkout(); checkoutCmd.setName(FILAMENTS_REPO_BRANCH); branchList = git.branchList().call(); for (Ref ref : branchList) { if (ref.getName().contains(FILAMENTS_REPO_BRANCH)) { Base.writeLog("Correct branch was found locally", this.getClass()); branchFoundLocally = true; break; } } if (branchFoundLocally == false) { Base.writeLog( "No correct branch was found locally, attempting to checkout a new branch tracking the remote", this.getClass()); checkoutCmd.setCreateBranch(true); checkoutCmd.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK); checkoutCmd.setStartPoint(FILAMENTS_REPO_BRANCH); git.fetch().call(); } RevCommit backup = null; if (git.status().call().isClean() == false) { git.add().addFilepattern(".").call(); backup = git.commit().setMessage("local backup of user modifications").call(); } newBranch = checkoutCmd.call().getName(); if (newBranch.contains(FILAMENTS_REPO_BRANCH) == false) { Base.writeLog("Unable to change to correct branch, aborting update", this.getClass()); return; } else { Base.writeLog("Changed to correct branch, " + newBranch, this.getClass()); } try { for (RevCommit commit : git.log().setMaxCount(1).call()) { Base.writeLog("Commit hash after branch change: " + commit, this.getClass()); } } catch (GitAPIException ex) { // we don't want all the process to stop just because we couldn't acquire the hash here, // hence this catch Base.writeLog( "GitAPIException while attempting to get current commit's hash, after changing branch. Not a critical error, so proceeding with update", this.getClass()); } if (backup != null) { // TODO: restore backup of user modifications //git.cherryPick().setNoCommit(true).include(backup).call(); } } repoStatus = git.status().call(); checkoutCmd = git.checkout(); checkoutCmd.setName(FILAMENTS_REPO_BRANCH); checkoutCmd.call(); git.fetch(); resetCmd = git.reset(); resetCmd.setMode(ResetType.HARD); resetCmd.call(); git.pull().call(); /* repoStatus = git.status().call(); if (repoStatus.hasUncommittedChanges()) { Base.writeLog("Repo has uncommited changes, stashing and pulling...", this.getClass()); stash = git.stashCreate().call(); git.pull().call(); git.stashApply().call(); // will apply the last stash made git.stashDrop().call(); // remove the last stash made } else { Base.writeLog("Repo has no uncommited changes, a simple pull will suffice", this.getClass()); git.pull().call(); } */ Base.writeLog("Filament update concluded successfully!", this.getClass()); try { for (RevCommit commit : git.log().setMaxCount(1).call()) { Base.writeLog("Commit hash after update process finished: " + commit, this.getClass()); } } catch (GitAPIException ex) { // we don't want all the process to stop just because we couldn't acquire the hash here, // hence this catch Base.writeLog( "GitAPIException while attempting to get current commit's hash, after the process finished with success. Not a critical error, so proceeding with update", this.getClass()); } } catch (GitAPIException ex) { Base.writeLog("GitAPIException while attempting to update filaments, aborting update", this.getClass()); try { resetCmd = git.reset(); resetCmd.setMode(ResetType.HARD); resetCmd.call(); if (stash != null) { git.stashApply().call(); git.stashDrop().call(); } } catch (GitAPIException ex1) { Base.writeLog("GitAPIException while attempting to reset after an error, uh oh...", this.getClass()); } } }
From source file:services.player.ZoneManager.java
License:Open Source License
private void loadCommitHistory() { File repoDir = new File("./" + Constants.DOT_GIT); int commitCount = 3; int iterations = 0; try {//from w w w . j a v a 2 s . co m Git git = Git.open(repoDir); Repository repo = git.getRepository(); try { commitHistory = "The " + commitCount + " most recent commits in branch '" + repo.getBranch() + "':\n"; for (RevCommit commit : git.log().setMaxCount(commitCount).call()) { commitHistory += commit.getName().substring(0, 7) + " " + commit.getShortMessage(); if (commitCount > iterations++) commitHistory += "\n"; } } catch (GitAPIException e) { e.printStackTrace(); } } catch (IOException e) { System.err.println("ZoneManager: Failed to open " + repoDir + " to read commit history"); // An exception is thrown if bash isn't installed. // https://www.eclipse.org/forums/index.php/t/1031740/ } }
From source file:svnserver.SvnTestServer.java
License:GNU General Public License
private SvnTestServer(@NotNull Repository repository, @Nullable String branch, @NotNull String prefix, boolean safeBranch, @Nullable UserDBConfig userDBConfig, boolean anonymousRead) throws Exception { SVNFileUtil.setSleepForTimestamp(false); this.repository = repository; this.safeBranch = safeBranch; this.prefix = prefix; tempDirectory = TestHelper.createTempDir("git-as-svn"); final String srcBranch = branch == null ? repository.getBranch() : branch; if (safeBranch) { cleanupBranches(repository);/*from w w w . java2 s. co m*/ testBranch = TEST_BRANCH_PREFIX + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8); new Git(repository).branchCreate().setName(testBranch).setStartPoint(srcBranch).call(); } else { testBranch = srcBranch; } final Config config = new Config(BIND_HOST, 0); config.setCompressionEnabled(false); config.setCacheConfig(new MemoryCacheConfig()); config.setRepositoryMapping(new TestRepositoryConfig(repository, testBranch, prefix, anonymousRead)); if (userDBConfig != null) { config.setUserDB(userDBConfig); } else { config.setUserDB(new LocalUserDBConfig(new LocalUserDBConfig.UserEntry[] { new LocalUserDBConfig.UserEntry(USER_NAME, REAL_NAME, EMAIL, PASSWORD), new LocalUserDBConfig.UserEntry(USER_NAME_NO_MAIL, REAL_NAME, null, PASSWORD), })); } config.getShared().add(context -> context.add(LfsStorageFactory.class, new LfsMemoryStorage.Factory())); server = new SvnServer(tempDirectory, config); server.start(); log.info("Temporary server started (url: {}, path: {}, branch: {} as {})", getUrl(), repository.getDirectory(), srcBranch, testBranch); log.info("Temporary directory: {}", tempDirectory); }
From source file:wherehows.common.utils.GitUtil.java
License:Open Source License
/** * Fetch all commit metadata from the repo * @param repoDir repository directory//from w w w . ja v a2 s . c om * @return list of commit metadata * @throws IOException * @throws GitAPIException */ public static List<CommitMetadata> getRepoMetadata(String repoDir) throws IOException, GitAPIException { List<CommitMetadata> metadataList = new ArrayList<>(); FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(new File(repoDir, ".git")).readEnvironment().findGitDir().build(); // Current branch may not be master. Instead of hard coding determine the current branch String currentBranch = repository.getBranch(); Ref head = repository.getRef("refs/heads/" + currentBranch); // current branch may not be "master" if (head == null) { return metadataList; } Git git = new Git(repository); RevWalk walk = new RevWalk(repository); RevCommit commit = walk.parseCommit(head.getObjectId()); TreeWalk treeWalk = new TreeWalk(repository); treeWalk.addTree(commit.getTree()); treeWalk.setRecursive(true); while (treeWalk.next()) { String filePath = treeWalk.getPathString(); Iterable<RevCommit> commitLog = git.log().add(repository.resolve(Constants.HEAD)).addPath(filePath) .call(); for (RevCommit r : commitLog) { CommitMetadata metadata = new CommitMetadata(r.getName()); metadata.setFilePath(filePath); metadata.setFileName(FilenameUtils.getName(filePath)); metadata.setMessage(r.getShortMessage().trim()); // Difference between committer and author // refer to: http://git-scm.com/book/ch2-3.html PersonIdent committer = r.getCommitterIdent(); PersonIdent author = r.getAuthorIdent(); metadata.setAuthor(author.getName()); metadata.setAuthorEmail(author.getEmailAddress()); metadata.setCommitter(committer.getName()); metadata.setCommitterEmail(committer.getEmailAddress()); metadata.setCommitTime(committer.getWhen()); metadataList.add(metadata); } } git.close(); return metadataList; }