List of usage examples for org.eclipse.jgit.lib Repository getBranch
@Nullable public String getBranch() throws IOException
From source file:com.rimerosolutions.ant.git.tasks.CurrentBranchTask.java
License:Apache License
@Override protected void doExecute() { try {//from www. j a va 2 s .co m Repository repository = git.getRepository(); String branch = repository.getBranch(); // Backward compatibility getProject().setProperty(outputProperty, branch); ObjectId objectId = repository.getRef(Constants.HEAD).getObjectId(); // Extended (nested) properties if (objectId != null) { getProject().setProperty(outputProperty + ".name", branch); getProject().setProperty(outputProperty + ".id", objectId.name()); getProject().setProperty(outputProperty + ".shortId", objectId.abbreviate(8).name()); } } catch (IOException e) { throw new GitBuildException("Could not query the current branch.", e); } }
From source file:com.verigreen.collector.jobs.BranchCleanerJob.java
License:Apache License
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);/*from w w w .j av a2 s .c om*/ 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; }
From source file:com.wadpam.gimple.GimpleMojo.java
License:Open Source License
@Override public void execute() throws MojoExecutionException, MojoFailureException { FileRepositoryBuilder builder = new FileRepositoryBuilder(); try {// w w w . j a v a2s.c o m Repository repo = builder.setGitDir(new File(new File(gitDir), ".git")).readEnvironment().findGitDir() .build(); final String branch = repo.getBranch(); if (null != branch) { if (!currentVersion.endsWith(SUFFIX_SNAPSHOT)) { throw new MojoExecutionException("Maven project version not in SNAPSHOT: " + currentVersion); } getLog().info("gimple executing on " + gitDir); getLog().info("branch " + branch); if (null == releaseVersion) { releaseVersion = currentVersion.substring(0, currentVersion.length() - SUFFIX_SNAPSHOT.length()); } getLog().info( "Transforming version from " + currentVersion + " to release version " + releaseVersion); Git git = new Git(repo); StatusCommand statusCommand = git.status(); Status status = statusCommand.call(); if (!status.isClean()) { throw new MojoExecutionException("Git project is not clean: " + status.getUncommittedChanges()); } // versions:set releaseVersion transformPomVersions(git, releaseVersion); // tag release Ref tagRef = git.tag().setMessage(GIMPLE_MAVEN_PLUGIN + "tagging release " + releaseVersion) .setName(releaseVersion).call(); // next development version if (null == nextVersion) { nextVersion = getNextDevelopmentVersion(releaseVersion); } // versions:set nextVersion RevCommit nextRef = transformPomVersions(git, nextVersion); // push it all String developerConnection = mavenProject.getScm().getDeveloperConnection(); if (developerConnection.startsWith(PREFIX_SCM_GIT)) { developerConnection = developerConnection.substring(PREFIX_SCM_GIT.length()); } RefSpec spec = new RefSpec(branch + ":" + branch); git.push().setRemote(developerConnection).setRefSpecs(spec).add(tagRef).call(); } } catch (IOException e) { throw new MojoExecutionException("executing", e); } catch (GitAPIException e) { throw new MojoExecutionException("status", e); } }
From source file:de.unihalle.informatik.Alida.version.ALDVersionProviderGit.java
License:Open Source License
/** * Returns information about current commit. * <p>//from www . ja v a 2 s .c om * If no git repository is found, the method checks for a file * "revision.txt" as it is present in Alida jar files. * If the file does not exist or is empty, a dummy string is returned. * * @return Info string. */ private static String getRepositoryInfo() { ALDVersionProviderGit.localVersion = "Unknown"; FileRepositoryBuilder builder = new FileRepositoryBuilder(); try { Repository repo = null; try { repo = builder.readEnvironment().build(); } catch (IllegalArgumentException e) { // problem accessing environment... fall back to default if (repo != null) repo.close(); return ALDVersionProviderGit.localVersion; } // check if GIT_DIR is set if (!builder.getGitDir().isDirectory()) { if (repo != null) repo.close(); return ALDVersionProviderGit.localVersion; } // extract the active branch String activeBranch = repo.getBranch(); // extract last commit Ref HEAD = repo.findRef(activeBranch); // safety check if everything is alright with repository if (HEAD == null) { repo.close(); throw new IOException(); } // extract state of repository String state = repo.getRepositoryState().toString(); ALDVersionProviderGit.localVersion = activeBranch + " : " + HEAD.toString() + " ( " + state + " ) "; // clean-up repo.close(); } catch (IOException e) { // accessing the Git repository failed, search for file InputStream is = null; BufferedReader br = null; String vLine = null; // initialize file reader and extract version information try { System.out.print("Searching for local revision file..."); is = ALDVersionProviderGit.class.getResourceAsStream("/" + ALDVersionProviderGit.revFile); br = new BufferedReader(new InputStreamReader(is)); vLine = br.readLine(); if (vLine == null) { System.err.println("ALDVersionProviderGit: " + "revision file is empty...!?"); br.close(); is.close(); return ALDVersionProviderGit.localVersion; } ALDVersionProviderGit.localVersion = vLine; br.close(); is.close(); return vLine; } catch (Exception ex) { try { if (br != null) br.close(); if (is != null) is.close(); } catch (IOException eo) { // nothing to do here } return ALDVersionProviderGit.localVersion; } } return ALDVersionProviderGit.localVersion; }
From source file:edu.tum.cs.mylyn.provisioning.git.GitProvisioningUtil.java
License:Open Source License
public static URIish getCloneUri(Repository repository) { try {/*from w w w .jav a 2 s . c o m*/ return getCloneUri(repository.getConfig(), repository.getBranch()); } catch (IOException e) { return null; } }
From source file:eu.hohenegger.gitmine.ui.views.StatisticsView.java
License:Open Source License
@Inject @Optional/* www. ja v a2 s . c o m*/ private void openRepository(@UIEventTopic(VIEWCOM_STATISTICS_OPEN) Repository repository, UISynchronize sync) { try { part.setLabel(repository.getDirectory() + " - " + repository.getBranch()); // If you want to update the UI, run it in the UI thread sync.syncExec(new Runnable() { @Override public void run() { reset(); } }); graph.addCurve("Commits", miningservice.scanCommitsPerDay(repository), new RGB(0, 0, 255), "#", true); } catch (IOException e) { // TODO log MessageDialog.openError(activeShell, "Error", e.getLocalizedMessage()); } }
From source file:eu.trentorise.opendata.josman.test.GitTest.java
@Test public void testReadRepo() throws IOException, GitAPIException { File repoFile = createSampleGitRepo(); FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repo = builder.setGitDir(repoFile).readEnvironment() // scan environment GIT_* variables .findGitDir() // scan up the file system tree .build();//w w w.j av a 2 s . co m LOG.log(Level.INFO, "directory: {0}", repo.getDirectory().getAbsolutePath()); LOG.log(Level.INFO, "Having repository: {0}", repo.getDirectory().getAbsolutePath()); LOG.log(Level.INFO, "current branch: {0}", repo.getBranch()); }
From source file:hd3gtv.configuration.GitInfo.java
License:Open Source License
public GitInfo(File repository_file) throws IOException { if (repository_file == null) { throw new NullPointerException("\"repository_file\" can't to be null"); }/*from w w w . j a va2 s. c om*/ if (repository_file.exists() == false) { throw new IOException("Can't found \"" + repository_file + "\""); } if (repository_file.isDirectory() == false) { throw new IOException("\"" + repository_file + "\" is not a directory"); } try { FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(repository_file).readEnvironment().findGitDir().build(); if (repository.getBranch() == null) { throw new FileNotFoundException("Can't found branch in \"" + repository_file + "\""); } branch = repository.getBranch(); commit = repository.getRef(Constants.HEAD).getObjectId().abbreviate(8).name(); } catch (Exception e) { throw new IOException("Can't load git repository \"" + repository_file + "\""); } }
From source file:io.fabric8.kubernetes.pipeline.devops.git.GitInfoCallback.java
License:Apache License
/** * {@inheritDoc}/* w ww.j a v a 2 s . co m*/ */ @Override public GitConfig invoke(Repository repository, VirtualChannel channel) throws IOException, InterruptedException { Git git = new Git(repository); Iterable<RevCommit> log; try { log = git.log().call(); } catch (GitAPIException e) { listener.error("Unable to get git log: " + e); GitConfig config = new GitConfig(); config.setAuthor("UNKNOWN"); config.setCommit("UNKNOWN"); config.setBranch("UNKNOWN"); return config; } RevCommit commit = log.iterator().next(); GitConfig config = new GitConfig(); config.setAuthor(commit.getCommitterIdent().getName()); config.setCommit(commit.getId().getName()); config.setBranch(repository.getBranch()); return config; }
From source file:io.fabric8.maven.AbstractFabric8Mojo.java
License:Apache License
/** * Tries to default some environment variables if they are not already defined. * * This can happen if using Jenkins Workflow which doens't seem to define BUILD_URL or GIT_URL for example * * @return the value of the environment variable name if it can be found or calculated *//*from w w w .java2 s . com*/ protected String tryDefaultAnnotationEnvVar(String envVarName) { // only do this if enabled if (extendedMetadata != null && !extendedMetadata) { return null; } MavenProject rootProject = getRootProject(); File basedir = rootProject.getBasedir(); if (basedir == null) { basedir = getProject().getBasedir(); } if (basedir == null) { basedir = new File(System.getProperty("basedir", ".")); } ProjectConfig projectConfig = ProjectConfigs.loadFromFolder(basedir); String repoName = rootProject.getArtifactId(); String userEnvVar = "JENKINS_GOGS_USER"; String username = Systems.getEnvVarOrSystemProperty(userEnvVar); if (Objects.equal("BUILD_URL", envVarName)) { String jobUrl = projectConfig.getLink("Job"); if (Strings.isNullOrBlank(jobUrl)) { String name = projectConfig.getBuildName(); if (Strings.isNullOrBlank(name)) { // lets try deduce the jenkins build name we'll generate if (Strings.isNotBlank(repoName)) { name = repoName; if (Strings.isNotBlank(username)) { name = ProjectRepositories.createBuildName(username, repoName); } else { warnIfInCDBuild("Cannot auto-default BUILD_URL as there is no environment variable `" + userEnvVar + "` defined so we can't guess the Jenkins build URL"); } } } if (Strings.isNotBlank(name)) { try { // this requires online access to kubernetes so we should silently fail if no connection String jenkinsUrl = KubernetesHelper.getServiceURLInCurrentNamespace(getKubernetes(), ServiceNames.JENKINS, "http", null, true); jobUrl = URLUtils.pathJoin(jenkinsUrl, "/job", name); } catch (Throwable e) { Throwable cause = e; boolean notFound = false; boolean connectError = false; Iterable<Throwable> it = createExceptionIterable(e); for (Throwable t : it) { connectError = t instanceof ConnectException || "No route to host".equals(t.getMessage()); notFound = t instanceof IllegalArgumentException || t.getMessage() != null && t.getMessage().startsWith("No kubernetes service could be found for name"); if (connectError || notFound) { cause = t; break; } } if (connectError) { warnIfInCDBuild("Cannot connect to Kubernetes to find jenkins service URL: " + cause.getMessage()); } else if (notFound) { // the message from the exception is good as-is warnIfInCDBuild(cause.getMessage()); } else { warnIfInCDBuild("Cannot find jenkins service URL: " + cause, cause); } } } } if (Strings.isNotBlank(jobUrl)) { String buildId = Systems.getEnvVarOrSystemProperty("BUILD_ID"); if (Strings.isNotBlank(buildId)) { jobUrl = URLUtils.pathJoin(jobUrl, buildId); } else { warnIfInCDBuild( "Cannot find BUILD_ID to create a specific jenkins build URL. So using: " + jobUrl); } } return jobUrl; } else if (Objects.equal("GIT_URL", envVarName)) { if (Strings.isNotBlank(repoName) && Strings.isNotBlank(username)) { try { // this requires online access to kubernetes so we should silently fail if no connection String gogsUrl = KubernetesHelper.getServiceURLInCurrentNamespace(getKubernetes(), ServiceNames.GOGS, "http", null, true); String rootGitUrl = URLUtils.pathJoin(gogsUrl, username, repoName); String gitCommitId = getGitCommitId(envVarName, basedir); if (Strings.isNotBlank(gitCommitId)) { rootGitUrl = URLUtils.pathJoin(rootGitUrl, "commit", gitCommitId); } return rootGitUrl; } catch (Throwable e) { Throwable cause = e; boolean notFound = false; boolean connectError = false; Iterable<Throwable> it = createExceptionIterable(e); for (Throwable t : it) { notFound = t instanceof IllegalArgumentException || t.getMessage() != null && t.getMessage().startsWith("No kubernetes service could be found for name"); connectError = t instanceof ConnectException || "No route to host".equals(t.getMessage()); if (connectError) { cause = t; break; } } if (connectError) { warnIfInCDBuild( "Cannot connect to Kubernetes to find gogs service URL: " + cause.getMessage()); } else if (notFound) { // the message from the exception is good as-is warnIfInCDBuild(cause.getMessage()); } else { warnIfInCDBuild("Cannot find gogs service URL: " + cause, cause); } } } else { warnIfInCDBuild("Cannot auto-default GIT_URL as there is no environment variable `" + userEnvVar + "` defined so we can't guess the Gogs build URL"); } /* TODO this is the git clone url; while we could try convert from it to a browse URL its probably too flaky? try { url = GitHelpers.extractGitUrl(basedir); } catch (IOException e) { warnIfInCDBuild("Failed to find git url in directory " + basedir + ". " + e, e); } if (Strings.isNotBlank(url)) { // for gogs / github style repos we trim the .git suffix for browsing return Strings.stripSuffix(url, ".git"); } */ } else if (Objects.equal("GIT_COMMIT", envVarName)) { return getGitCommitId(envVarName, basedir); } else if (Objects.equal("GIT_BRANCH", envVarName)) { Repository repository = getGitRepository(basedir, envVarName); try { if (repository != null) { return repository.getBranch(); } } catch (IOException e) { warnIfInCDBuild("Failed to find git commit id. " + e, e); } finally { if (repository != null) { repository.close(); } } } return null; }