Example usage for org.eclipse.jgit.api Git open

List of usage examples for org.eclipse.jgit.api Git open

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git open.

Prototype

public static Git open(File dir) throws IOException 

Source Link

Document

Open repository

Usage

From source file:com.worldline.easycukes.scm.utils.GitHelper.java

License:Open Source License

/**
 * Delete a tag in the local git repository
 * (git tag -d tagname) and finally pushes new branch on the remote repository (git push)
 *
 * @param directory the directory in which the local git repository is located
 * @param username  the username to be used while pushing
 * @param password  the password matching with the provided username to be used
 *                  for authentication//w  w  w . j av a 2  s .  com
 * @param message   the commit message to be used    
 */
public static void deleteTag(@NonNull File directory, String tagName, String username, String password,
        String message) {
    try {
        final Git git = Git.open(directory);

        final UsernamePasswordCredentialsProvider userCredential = new UsernamePasswordCredentialsProvider(
                username, password);
        DeleteTagCommand deleteTagCommand = git.tagDelete();
        deleteTagCommand.setTags(tagName);
        deleteTagCommand.call();
        log.info("Tag deleted");

        // and then commit
        final PersonIdent author = new PersonIdent(username, "");
        git.commit().setCommitter(author).setMessage(message).setAuthor(author).call();
        log.info(message);

        git.push().setCredentialsProvider(userCredential).call();
        log.info("Pushed the changes in remote Git repository...");
    } catch (final GitAPIException | IOException e) {
        log.error(e.getMessage(), e);
    }
}

From source file:de.sjka.jenkins.view.branches.BranchOverviewAction.java

License:Open Source License

@SuppressWarnings("rawtypes")
public List<BranchState> getBranches() {
    // read remote branches from the repository
    Map<String, String> branches = new HashMap<String, String>();
    Map<String, String> messages = new HashMap<String, String>();
    try {//from  w w  w  .jav  a 2 s .  c  o  m
        if (target.getScm() instanceof GitSCM) {
            GitSCM gitSCM = (GitSCM) target.getScm();
            String location = target.getLastBuild().getWorkspace().getRemote() + gitSCM.getRelativeTargetDir();
            Git git = Git.open(new File(location));
            for (Ref ref : git.branchList().setListMode(ListMode.REMOTE).call()) {
                String name = ref.getName();
                if (name.endsWith("/HEAD")) {
                    continue;
                }
                if (name.startsWith("refs/remotes/")) {
                    name = name.replace("refs/remotes/", "");
                }
                branches.put(name, ref.getObjectId().getName());
                System.out.println(name);
                messages.put(name, git.log().add(ref.getObjectId()).call().iterator().next().getShortMessage());
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (GitAPIException e) {
        throw new RuntimeException(e);
    }

    // read commits from the build history
    Map<String, AbstractBuild> builds = new HashMap<String, AbstractBuild>();
    for (AbstractBuild build : target.getBuilds()) {
        for (Entry<String, Build> entry : ((Actionable) build).getAction(BuildData.class)
                .getBuildsByBranchName().entrySet()) {
            String sha1 = entry.getValue().getRevision().getSha1String();
            int number = entry.getValue().getBuildNumber();
            if (number == build.getNumber() && builds.get(sha1) == null) {
                builds.put(sha1, build);
                break;
            }
        }
    }

    // create model
    Map<String, BranchState> ret = new HashMap<String, BranchState>();
    for (Entry<String, String> branch : branches.entrySet()) {
        AbstractBuild build = builds.get(branch.getValue());
        BranchState state = new BranchState(branch.getKey(), branch.getValue(), messages.get(branch.getKey()),
                build);
        ret.put(branch.getKey(), state);
    }

    return new ArrayList<BranchState>(ret.values());
}

From source file:de._692b8c32.cdlauncher.tasks.GITCheckoutTask.java

License:Open Source License

@Override
public void doWork() {
    setProgress(-1);/*from w w w . j a  v a  2 s  .  co m*/

    try {
        Git git = Git.open(cacheDir);
        git.reset().setMode(ResetCommand.ResetType.HARD).call();
        git.checkout().setAllPaths(true).setForce(true).setName(branch).setStartPoint(startPoint.getValue())
                .call();

        if (destinationDir != null) {
            FileUtils.delete(destinationDir, FileUtils.RECURSIVE | FileUtils.SKIP_MISSING);
            destinationDir.mkdirs();
            Files.list(cacheDir.toPath()).filter(path -> !(".git".equals(path.getFileName().toString())))
                    .forEach(path -> {
                        try {
                            Files.move(path, destinationDir.toPath().resolve(path.getFileName()),
                                    StandardCopyOption.ATOMIC_MOVE);
                        } catch (IOException ex) {
                            throw new RuntimeException("Failed to move " + path.getFileName(), ex);
                        }
                    });
        }
        git.close();
    } catch (RepositoryNotFoundException | InvalidRemoteException ex) {
        throw new RuntimeException("Could not find repository");
    } catch (GitAPIException | IOException ex) {
        throw new RuntimeException("Could not checkout data", ex);
    }
}

From source file:de._692b8c32.cdlauncher.tasks.GITUpdateTask.java

License:Open Source License

@Override
public void doWork() {
    try {//from  www  .  ja  va  2 s .  c  o  m
        Git git;
        if (!cacheDir.exists()) {
            cacheDir.mkdirs();
            git = Git.cloneRepository().setURI(repoUri).setDirectory(cacheDir).setNoCheckout(true)
                    .setProgressMonitor(this).call();
        } else {
            git = Git.open(cacheDir);
            git.fetch().setProgressMonitor(this).call();
        }
        git.close();
    } catch (RepositoryNotFoundException | InvalidRemoteException ex) {
        Logger.getLogger(GITUpdateTask.class.getName()).log(Level.SEVERE, "Could not find repository", ex);
        try {
            FileUtils.delete(cacheDir);
            run();
        } catch (IOException | StackOverflowError ex1) {
            throw new RuntimeException("Fix of broken repository failed", ex1);
        }
    } catch (GitAPIException | IOException ex) {
        throw new RuntimeException("Could not download data", ex);
    }
}

From source file:es.logongas.openshift.ant.impl.OpenShiftUtil.java

License:Apache License

public void gitPushApplication(String serverUrl, String userName, String password, String domainName,
        String applicationName, String privateKeyFile, String path) throws GitAPIException, IOException {

    SshSessionFactory.setInstance(new CustomConfigSessionFactory(privateKeyFile));

    Git git = Git.open(new File(path));

    PushCommand push = git.push();//from www .  j ava  2  s.  c  om
    push.setProgressMonitor(new TextProgressMonitor());
    LOGGER.info("Finalizado push");
    LOGGER.info("Mostrando resultados");
    Iterable<PushResult> pushResults = push.call();
    for (PushResult pushResult : pushResults) {
        LOGGER.info(pushResult.getMessages());
    }

}

From source file:es.logongas.openshift.ant.impl.OpenShiftUtil.java

License:Apache License

private boolean existsBranch(String repositoryPath, String branchName) {
    try {/*from   w w w  .  jav  a2  s .  co  m*/
        Git git = Git.open(new File(repositoryPath));

        ListBranchCommand listBranchCommand = git.branchList();
        listBranchCommand.setListMode(ListBranchCommand.ListMode.ALL);
        List<Ref> refs = listBranchCommand.call();
        for (Ref ref : refs) {
            if (ref.getName().equals(branchName)) {
                return true;
            }
        }

        return false;
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } catch (GitAPIException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:es.logongas.openshift.ant.impl.OpenShiftUtil.java

License:Apache License

public String getCurrentBranch(String repositoryPath) {
    try {//from  w w  w  .j  av  a  2 s . c om
        Git git = Git.open(new File(repositoryPath));

        return git.getRepository().getBranch();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:es.logongas.openshift.ant.impl.OpenShiftUtil.java

License:Apache License

public boolean isRepositoryClean(String repositoryPath) {
    try {/* w ww .ja  va  2s .  com*/
        Git git = Git.open(new File(repositoryPath));

        List<DiffEntry> diffEntries = git.diff().call();

        if (diffEntries == null) {
            return true;
        } else {
            return diffEntries.isEmpty();
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } catch (GitAPIException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:eu.mihosoft.vrl.io.VersionedFile.java

License:Open Source License

/**
 * Returns names of all files that contain uncommitted changes.
 *
 * @return names of all files that contain uncommitted changes
 *//*from  www  . j a va2s. c om*/
public Set<String> getUncommittedChanges() {
    // file has to be opened
    if (!isOpened()) {
        throw new IllegalStateException("File \"" + getFile().getPath() + "\" not opened!");
    }

    Set<String> result = new HashSet<String>();

    Git git = null;

    try {
        git = Git.open(tmpFolder);

        Status status = git.status().call();

        for (String s : status.getAdded()) {
            result.add(s);
        }

        for (String s : status.getChanged()) {
            result.add(s);
        }

        for (String s : status.getMissing()) {
            result.add(s);
        }

        for (String s : status.getModified()) {
            result.add(s);
        }

        for (String s : status.getRemoved()) {
            result.add(s);
        }

        for (String s : status.getUntracked()) {
            result.add(s);
        }

    } catch (UnmergedPathException ex) {
        ex.printStackTrace(System.err);
        closeGit(git);
    } catch (IOException ex) {
        ex.printStackTrace(System.err);
        closeGit(git);
    }

    return result;
}

From source file:eu.mihosoft.vrl.io.VersionedFile.java

License:Open Source License

/**
 * Determines if this file has conflicts.
 *
 * @return <code>true</code> if conflicts exist; <code>false</code>
 * otherwise//from www.j  ava 2s .  co m
 * @throws IOException
 * @throws IllegalStateException if this file is currently not open
 */
private boolean hasConflicts() throws IOException {

    // file has to be opened
    if (!isOpened()) {
        throw new IllegalStateException("File \"" + getFile().getPath() + "\" not opened!");
    }

    Git git = null;

    try {
        git = Git.open(tmpFolder);

        Status status = git.status().call();

        closeGit(git);

        return !status.getConflicting().isEmpty();

    } catch (UnmergedPathException ex) {
        closeGit(git);
        throw new IOException("Git exception", ex);
    } catch (IOException ex) {
        closeGit(git);
        throw new IOException("Git exception", ex);
    }
}