Example usage for org.eclipse.jgit.lib Repository getBranch

List of usage examples for org.eclipse.jgit.lib Repository getBranch

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository getBranch.

Prototype

@Nullable
public String getBranch() throws IOException 

Source Link

Document

Get the short name of the current branch that HEAD points to.

Usage

From source file:io.fabric8.maven.CreateBranchMojo.java

License:Apache License

protected void doPull() throws MojoExecutionException {
    //CredentialsProvider cp = getCredentials();
    CredentialsProvider cp = null;//  w w  w.  j a  v a2 s.c  o  m
    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);
    }
}

From source file:io.fabric8.maven.enricher.standard.GitEnricher.java

License:Apache License

@Override
public Map<String, String> getAnnotations(Kind kind) {
    Map<String, String> annotations = new HashMap<>();
    Repository repository = null;
    try {/*from  w  w  w. j  av  a2  s  .c  o m*/
        if (kind.isController() || kind == Kind.SERVICE) {
            // Git annotations (if git is used as SCM)
            repository = GitUtil.getGitRepository(getProject());
            if (repository != null) {
                String result;
                String branch = repository.getBranch();
                if (branch != null) {
                    annotations.put(Annotations.Builds.GIT_BRANCH, branch);
                }
                String id = GitUtil.getGitCommitId(repository);
                if (id != null) {
                    annotations.put(Annotations.Builds.GIT_COMMIT, id);
                }
            }
        }
        return annotations;
    } catch (IOException | GitAPIException e) {
        log.error("Cannot extract Git information for adding to annotations: " + e, e);
        return null;
    } finally {
        if (repository != null) {
            try {
                repository.close();
            } catch (Exception e) {
                // ignore
            }
        }
    }
}

From source file:io.fabric8.maven.plugin.mojo.internal.ImportMojo.java

License:Apache License

@Override
public void executeInternal() throws MojoExecutionException, MojoFailureException {
    if (!basedir.isDirectory() || !basedir.exists()) {
        throw new MojoExecutionException("No directory for base directory: " + basedir);
    }//from  ww w.  j a  va 2  s .c o m

    // lets check for a git repo
    String gitRemoteURL = null;
    Repository repository = null;
    try {
        repository = GitUtils.findRepository(basedir);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to find local git repository in current directory: " + e, e);
    }
    try {
        gitRemoteURL = GitUtils.getRemoteURL(repository);
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to get the current git branch: " + e, e);
    }

    try {
        clusterAccess = new ClusterAccess(this.namespace);
        if (Strings.isNullOrBlank(projectName)) {
            projectName = basedir.getName();
        }

        KubernetesClient kubernetes = clusterAccess.createDefaultClient(log);
        KubernetesResourceUtil.validateKubernetesMasterUrl(kubernetes.getMasterUrl());

        String namespace = clusterAccess.getNamespace();
        OpenShiftClient openShiftClient = getOpenShiftClientOrJenkinsShift(kubernetes, namespace);

        if (gitRemoteURL != null) {
            // lets check we don't already have this project imported
            String branch = repository.getBranch();
            BuildConfig buildConfig = findBuildConfigForGitRepo(openShiftClient, namespace, gitRemoteURL,
                    branch);
            if (buildConfig != null) {
                logBuildConfigLink(kubernetes, namespace, buildConfig, log);
                throw new MojoExecutionException("Project already imported into build " + getName(buildConfig)
                        + " for URI: " + gitRemoteURL + " and branch: " + branch);
            } else {
                Map<String, String> annotations = new HashMap<>();
                annotations.put(Annotations.Builds.GIT_CLONE_URL, gitRemoteURL);
                buildConfig = createBuildConfig(kubernetes, namespace, projectName, gitRemoteURL, annotations);

                openShiftClient.buildConfigs().inNamespace(namespace).create(buildConfig);

                ensureExternalGitSecretsAreSetupFor(kubernetes, namespace, gitRemoteURL);

                logBuildConfigLink(kubernetes, namespace, buildConfig, log);
            }
        } else {
            // lets create an import a new project
            UserDetails userDetails = createGogsUserDetails(kubernetes, namespace);
            BuildConfigHelper.CreateGitProjectResults createGitProjectResults;
            try {
                createGitProjectResults = BuildConfigHelper.importNewGitProject(kubernetes, userDetails,
                        basedir, namespace, projectName, originBranchName,
                        "Importing project from mvn fabric8:import", false);
            } catch (WebApplicationException e) {
                Response response = e.getResponse();
                if (response.getStatus() > 400) {
                    String message = getEntityMessage(response);
                    log.warn("Could not create the git repository: %s %s", e, message);
                    log.warn("Are your username and password correct in the Secret %s/%s?", secretNamespace,
                            gogsSecretName);
                    log.warn(
                            "To re-enter your password rerun this command with -Dfabric8.passsword.retry=true");

                    throw new MojoExecutionException("Could not create the git repository. "
                            + "Are your username and password correct in the Secret " + secretNamespace + "/"
                            + gogsSecretName + "?" + e + message, e);
                } else {
                    throw e;
                }
            }

            BuildConfig buildConfig = createGitProjectResults.getBuildConfig();
            openShiftClient.buildConfigs().inNamespace(namespace).create(buildConfig);
            logBuildConfigLink(kubernetes, namespace, buildConfig, log);
        }
    } catch (KubernetesClientException e) {
        KubernetesResourceUtil.handleKubernetesClientException(e, this.log);
    } catch (Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.AgentVcsSupportTest.java

License:Apache License

@TestFor(issues = "TW-23707")
public void do_not_create_remote_branch_unexisting_in_remote_repository() throws Exception {
    myRoot.addProperty(Constants.BRANCH_NAME, "refs/changes/1/1");
    myVcsSupport.updateSources(myRoot, CheckoutRules.DEFAULT, "5711cbfe566b6c92e331f95d4b236483f4532eed",
            myCheckoutDir, myBuild, false);
    Repository r = new RepositoryBuilder().setWorkTree(myCheckoutDir).build();
    assertEquals("5711cbfe566b6c92e331f95d4b236483f4532eed", r.getBranch());//checkout a detached commit
    Map<String, Ref> refs = r.getAllRefs();
    assertFalse(refs.containsKey("refs/heads/refs/changes/1/1"));
    assertFalse(refs.containsKey("refs/remotes/origin/changes/1/1"));
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.AgentVcsSupportTest.java

License:Apache License

@Test(dataProvider = "mirrors")
public void should_use_branch_specified_in_build_parameter(Boolean useMirrors) throws Exception {
    final File remote = myTempFiles.createTempDir();
    copyRepository(dataFile("repo_for_fetch.2.personal"), remote);
    VcsRootImpl root = createRoot(remote, "master");

    AgentRunningBuild build = createRunningBuild(map(PluginConfigImpl.USE_MIRRORS, String.valueOf(useMirrors)));
    String commitFromFeatureBranch = "d47dda159b27b9a8c4cee4ce98e4435eb5b17168";
    myVcsSupport.updateSources(root, CheckoutRules.DEFAULT, commitFromFeatureBranch, myCheckoutDir, build,
            false);/* w  w w . jav a2s. co m*/
    Repository r = new RepositoryBuilder().setWorkTree(myCheckoutDir).build();
    assertEquals("master", r.getBranch());

    build = createRunningBuild(map(PluginConfigImpl.USE_MIRRORS, String.valueOf(useMirrors),
            GitUtils.getGitRootBranchParamName(root), "refs/heads/personal"));
    myVcsSupport.updateSources(root, CheckoutRules.DEFAULT, commitFromFeatureBranch, myCheckoutDir, build,
            false);
    r = new RepositoryBuilder().setWorkTree(myCheckoutDir).build();
    assertEquals("personal", r.getBranch());
}

From source file:me.cmoz.gradle.snapshot.GitSCMCommand.java

License:Apache License

@Override
@SneakyThrows(IOException.class)
public Commit getLatestCommit(@NonNull final String dateFormat) {
    if (repoDir == null) {
        throw new IllegalStateException("'.git' folder could not be found.");
    }// w  w  w. j  av a2s. c o m

    final FileRepositoryBuilder builder = new FileRepositoryBuilder();

    final Repository repo = builder.setGitDir(repoDir).readEnvironment().build();
    final StoredConfig conf = repo.getConfig();

    int abbrev = Commit.ABBREV_LENGTH;
    if (conf != null) {
        abbrev = conf.getInt("core", "abbrev", abbrev);
    }

    final SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

    final Ref HEAD = repo.getRef(Constants.HEAD);
    if (HEAD.getObjectId() == null) {
        throw new RuntimeException("Could not find any commits from HEAD ref.");
    }

    final RevWalk revWalk = new RevWalk(repo);
    if (HEAD.getObjectId() == null) {
        throw new RuntimeException("Could not find any commits from HEAD ref.");
    }
    final RevCommit revCommit = revWalk.parseCommit(HEAD.getObjectId());
    revWalk.markStart(revCommit);

    try {
        // git commit time in sec and java datetime is in ms
        final Date commitTime = new Date(revCommit.getCommitTime() * 1000L);
        final PersonIdent ident = revCommit.getAuthorIdent();
        final UserConfig userConf = conf.get(UserConfig.KEY);

        return Commit.builder().buildTime(sdf.format(new Date())).buildAuthorName(userConf.getAuthorName())
                .buildAuthorEmail(userConf.getAuthorEmail()).branchName(repo.getBranch())
                .commitId(revCommit.getName()).commitTime(sdf.format(commitTime))
                .commitUserName(ident.getName()).commitUserEmail(ident.getEmailAddress())
                .commitMessage(revCommit.getFullMessage().trim()).build();
    } finally {
        revWalk.dispose();
        repo.close();
    }
}

From source file:net.erdfelt.android.sdkfido.git.internal.GitInfo.java

License:Apache License

public static void infoAll(Repository db) throws IOException {
    System.out.printf("Repository - %s%n", db.getDirectory());
    System.out.printf("      state: %s%n", db.getRepositoryState());
    System.out.printf("     branch: %s%n", db.getBranch());
    System.out.printf("full-branch: %s%n", db.getFullBranch());
    infoRefs(db);//from  w w w.j  a va2s.c  om
    infoBranches(db);
    infoTags(db);
}

From source file:net.morimekta.idltool.IdlUtils.java

License:Apache License

public static String getLocalRemoteName(Repository repository, String remoteName) throws IOException {
    Config config = repository.getConfig();
    String currentBranch = repository.getBranch();
    if (currentBranch == null) {
        throw new RuntimeException("No current branch!");
    }//w ww .j  a  va2 s.co  m

    if (remoteName == null) {
        String branch = config.getString("default", null, "branch");
        if (branch == null) {
            branch = "master";
        }

        remoteName = config.getString("branch", branch, "remote");
        if (remoteName == null) {
            remoteName = config.getString("branch", "master", "remote");
            if (remoteName == null) {
                remoteName = "origin";
            }
        }
    }
    String remoteUrl = config.getString("remote", remoteName, "url");
    if (remoteUrl == null) {
        throw new RuntimeException("No URL for remote " + remoteName);
    }

    return remoteUrl.replaceAll("^.*://", "").replaceAll("^.*@", "").replaceAll("[.]git$", "").replaceAll(":",
            "/");
}

From source file:net.tietema.versioning.GitJavaVersioning.java

License:Apache License

public String getRevision(File projectDir) throws MojoExecutionException {
    // XXX we use our own findGitDir because they JGit one doesn't find the git dir in a multi project build
    File gitDir = findGitDir(projectDir);
    String revision = "Unknown";
    if (gitDir == null)
        return revision;

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = null;
    try {/*from   ww  w.ja  v  a2  s  .co m*/
        repository = builder.setGitDir(gitDir).readEnvironment() // scan environment GIT_* variables
                .findGitDir(projectDir) // scan up the file system tree
                .build();

        log.info("Git dir: " + gitDir.toString());
        RepositoryState state = repository.getRepositoryState();
        log.info(state.getDescription());
        String branch = repository.getBranch();
        log.info("Branch is: " + branch);
        Git git = new Git(repository);
        String fullBranch = repository.getFullBranch();
        log.info("Full branch is: " + fullBranch);
        ObjectId id = repository.resolve(fullBranch);
        log.info("Branch " + repository.getBranch() + " points to " + id.name());

        Status status = git.status().call();
        boolean strictClean = status.isClean();
        // no untracked files
        boolean loseClean = status.getAdded().isEmpty() && status.getChanged().isEmpty()
                && status.getConflicting().isEmpty() && status.getMissing().isEmpty()
                && status.getModified().isEmpty() && status.getRemoved().isEmpty();

        StringWriter buffer = new StringWriter();
        JavaWriter writer = new JavaWriter(buffer);
        writer.emitPackage(packageName)
                .beginType(packageName + "." + className, "class", Modifier.PUBLIC | Modifier.FINAL)
                .emitField("String", "BRANCH", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC,
                        String.format(Locale.US, "\"%s\"", branch))
                .emitField("String", "REVISION", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC,
                        String.format(Locale.US, "\"%s\"", id.name()))
                .emitField("String", "REVISION_SHORT", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC,
                        String.format(Locale.US, "\"%s\"", id.name().substring(0, 8)))
                .emitJavadoc("Strict Clean means no changes, not even untracked files")
                .emitField("boolean", "STRICT_CLEAN", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC,
                        (strictClean ? "true" : "false"))
                .emitJavadoc("Lose Clean means no changes except untracked files.")
                .emitField("boolean", "LOSE_CLEAN", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC,
                        (loseClean ? "true" : "false"))
                .endType();
        revision = buffer.toString();

        return revision;
    } catch (IOException e) {
        log.error(e);
        throw new MojoExecutionException(e.getMessage());
    } catch (GitAPIException e) {
        log.error(e);
        throw new MojoExecutionException(e.getMessage());
    } finally {
        if (repository != null)
            repository.close();
    }
}

From source file:net.yacy.grid.tools.GitTool.java

License:Open Source License

public GitTool() {
    File gitWorkDir = new File(".");
    try {//  ww  w .  j a  v  a 2 s . co m
        Git git = Git.open(gitWorkDir);
        Iterable<RevCommit> commits = git.log().all().call();
        Repository repo = git.getRepository();
        branch = repo.getBranch();
        RevCommit latestCommit = commits.iterator().next();
        name = latestCommit.getName();
        message = latestCommit.getFullMessage();
    } catch (Throwable e) {
        name = "";
        message = "";
        branch = "";
    }
}