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

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

Introduction

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

Prototype

public Repository getRepository() 

Source Link

Document

Get repository

Usage

From source file:org.walkmod.git.constraints.JavaConstraintProvider.java

License:Open Source License

public JavaConstraintProvider() throws IOException {
    File file = new File(".git").getCanonicalFile();
    if (file.exists()) {
        Git git = Git.open(file.getAbsoluteFile().getParentFile().getCanonicalFile());

        formatter = new WalkmodDiffFormatter(git.getRepository());

        AbstractTreeIterator commitTreeIterator = prepareTreeParser(git.getRepository(), Constants.HEAD);
        FileTreeIterator workTreeIterator = new FileTreeIterator(git.getRepository());
        List<DiffEntry> diffEntries = formatter.scan(commitTreeIterator, workTreeIterator);

        for (DiffEntry entry : diffEntries) {
            File aux = new File(entry.getNewPath()).getCanonicalFile();
            this.diffEntries.put(aux.getPath(), entry);
        }/*from w  w  w. j  av  a 2  s .  c  o m*/
        formatter.close();
    }
}

From source file:org.walkmod.git.readers.GitFileReader.java

License:Open Source License

@Override
public Resource<File> read() throws Exception {
    File file = new File(".git");
    Resource<File> result = null;
    if (file.exists()) {

        Git git = Git.open(file.getAbsoluteFile().getParentFile().getCanonicalFile());

        try {/* ww w  . j a va  2 s  .co m*/
            StatusCommand cmd = git.status();
            List<String> cfgIncludesList = null;
            String[] cfgIncludes = getIncludes();
            if (cfgIncludes != null && cfgIncludes.length > 0) {
                cfgIncludesList = Arrays.asList(cfgIncludes);
            }
            String path = getPath();
            Status status = cmd.call();
            Set<String> uncommitted = status.getUncommittedChanges();
            uncommitted.addAll(status.getUntracked());
            Set<String> includes = new HashSet<String>();
            if (!uncommitted.isEmpty()) {

                for (String uncommittedFile : uncommitted) {
                    if (uncommittedFile.startsWith(path)) {
                        String fileName = uncommittedFile.substring(path.length() + 1);
                        if (cfgIncludesList == null || cfgIncludesList.contains(fileName)) {
                            includes.add(fileName);
                        }
                    }
                }

            } else {

                Set<String> filesInCommit = getFilesInHEAD(git.getRepository());
                for (String committedFile : filesInCommit) {
                    if (committedFile.startsWith(path)) {
                        String fileName = committedFile.substring(path.length() + 1);
                        if (cfgIncludesList == null || cfgIncludesList.contains(fileName)) {
                            includes.add(fileName);
                        }
                    }
                }

            }
            if (!includes.isEmpty()) {
                String[] includesArray = new String[includes.size()];
                includesArray = includes.toArray(includesArray);

                setIncludes(includesArray);
            }
        } finally {
            git.close();
        }
    }
    result = super.read();
    return result;
}

From source file:org.wandora.application.tools.git.Status.java

License:Open Source License

@Override
public void execute(Wandora wandora, Context context) {

    try {/*w w  w . j a v a 2 s .  c om*/
        Git git = getGit();
        if (git != null) {
            setDefaultLogger();
            setLogTitle("Git status");

            Repository repository = git.getRepository();
            StoredConfig config = repository.getConfig();

            log("Git conf:");
            log(config.toText());

            log("Git status:");
            org.eclipse.jgit.api.Status status = git.status().call();
            log("Added: " + status.getAdded());
            log("Changed: " + status.getChanged());
            log("Conflicting: " + status.getConflicting());
            log("ConflictingStageState: " + status.getConflictingStageState());
            log("IgnoredNotInIndex: " + status.getIgnoredNotInIndex());
            log("Missing: " + status.getMissing());
            log("Modified: " + status.getModified());
            log("Removed: " + status.getRemoved());
            log("Untracked: " + status.getUntracked());
            log("UntrackedFolders: " + status.getUntrackedFolders());
            log("Ready.");
        } else {
            logAboutMissingGitRepository();
        }
    } catch (Exception e) {
        log(e);
    }
    setState(WAIT);
}

From source file:org.wso2.security.tools.dependencycheck.scanner.scanner.DependencyCheckExecutor.java

License:Open Source License

private void startScan() throws DependencyCheckScannerException, NotificationManagerException {
    boolean isProductAvailable = false;
    if (isFileUpload) {
        String folderName;//from  www .  j  a  va  2s  .  c o m
        try {
            folderName = FileHandler.extractZipFile(
                    ScannerProperties.getDefaultProductFolderPath() + File.separator + zipFileName);
            DependencyCheckExecutor.setProductPath(
                    ScannerProperties.getDefaultProductFolderPath() + File.separator + folderName);
            isProductAvailable = true;
            LOGGER.info("File successfully extracted");
            NotificationManager.notifyFileExtracted(true);
        } catch (IOException e) {
            NotificationManager.notifyFileExtracted(false);
            throw new DependencyCheckScannerException("Error occurred while extracting zip file", e);
        }
    } else {
        File productFile = new File(ScannerProperties.getDefaultProductFolderPath());
        Git git;
        if (productFile.exists() || productFile.mkdir()) {
            try {
                git = GitHandler.gitClone(gitUrl, gitUsername, gitPassword,
                        ScannerProperties.getDefaultProductFolderPath());
                isProductAvailable = GitHandler.hasAtLeastOneReference(git.getRepository());
                LOGGER.info("File successfully cloned");
                NotificationManager.notifyProductCloned(true);
            } catch (GitAPIException e) {
                NotificationManager.notifyProductCloned(false);
                throw new DependencyCheckScannerException("Error occurred while cloning product", e);
            }
        }
    }
    if (isProductAvailable) {
        DependencyCheckScanner dependencyCheckScanner = new DependencyCheckScanner();
        try {
            dependencyCheckScanner.runScan();
            LOGGER.info("Dependency Check scan completed");
            NotificationManager.notifyScanStatus(ScannerProperties.getScanStatusCompleted());
        } catch (MavenInvocationException | IOException e) {
            NotificationManager.notifyScanStatus(ScannerProperties.getScanStatusFailed());
            throw new DependencyCheckScannerException("Error occurred while running the scan", e);
        }
    }
}

From source file:org.wso2.security.tools.findsecbugs.scanner.scanner.FindSecBugsScannerExecutor.java

License:Open Source License

private void startScan() throws FindSecBugsScannerException, NotificationManagerException {
    boolean isProductAvailable = false;
    if (isFileUpload) {
        String folderName;//from w  w w  . j a v  a  2  s. co  m
        try {
            folderName = FileHandler
                    .extractZipFile(Constants.DEFAULT_PRODUCT_PATH + File.separator + zipFileName);
            FindSecBugsScannerExecutor
                    .setProductPath(Constants.DEFAULT_PRODUCT_PATH + File.separator + folderName);
            isProductAvailable = true;
            LOGGER.info("File successfully extracted");
            NotificationManager.notifyFileExtracted(true);
        } catch (IOException e) {
            NotificationManager.notifyFileExtracted(false);
            throw new FindSecBugsScannerException("Error occurred while extracting zip file", e);
        }
    } else {
        File productFile = new File(Constants.DEFAULT_PRODUCT_PATH);
        Git git;
        if (productFile.exists() || productFile.mkdir()) {
            try {
                git = GitHandler.gitClone(gitUrl, gitUsername, gitPassword, Constants.DEFAULT_PRODUCT_PATH);
                isProductAvailable = GitHandler.hasAtLeastOneReference(git.getRepository());
                LOGGER.info("File successfully cloned");
                NotificationManager.notifyProductCloned(true);
            } catch (GitAPIException e) {
                NotificationManager.notifyProductCloned(false);
                throw new FindSecBugsScannerException("Error occurred while cloning product", e);
            }
        }
    }
    if (isProductAvailable) {
        FindSecBugsScanner findSecBugsScanner = new FindSecBugsScanner();
        try {
            findSecBugsScanner.runScan();
        } catch (MavenInvocationException | TransformerException | IOException | ParserConfigurationException
                | SAXException e) {
            NotificationManager.notifyScanStatus("failed");
            throw new FindSecBugsScannerException("Error occurred while running the scan", e);
        }
    }
}

From source file:org.z2env.impl.helper.GitTools.java

License:Apache License

/**
 * Clones the given remote repository into the given destination folder. The method clones all branches but doesn't perform a checkout.
 *   /*w w  w  . j  a v  a  2s .co m*/
 * @param remoteUri URI of the remote repository
 * @param destFolder local destination folder
 * @param credentials user credentials
 * @return the cloned repository
 * @throws IOException if something went wrong
 */
public static Repository cloneRepository(URIish remoteUri, File destFolder, CredentialsProvider credentials,
        int timeout) throws IOException {

    // workaround for http://redmine.z2-environment.net/issues/902:
    // split clone into its piece in order to get the chance to set "core.autocrlf"
    Git gitResult;
    try {
        gitResult = Git.init().setBare(false).setDirectory(destFolder).call();
    } catch (Exception e) {
        throw new IOException("Failed to initialize a new Git repository at " + destFolder.getAbsolutePath(),
                e);
    }

    Repository repo = gitResult.getRepository();

    // setting "core.autocrlf=false" helps to solve http://redmine.z2-environment.net/issues/902
    StoredConfig config = repo.getConfig();
    config.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF,
            String.valueOf(false));

    // add origin - clone all branches
    RemoteConfig remoteCfg = null;
    try {
        remoteCfg = new RemoteConfig(config, "origin");
    } catch (URISyntaxException e) {
        throw new IOException("Failed to configure origin repository", e);
    }
    remoteCfg.addURI(remoteUri);
    remoteCfg.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
    remoteCfg.update(config);
    config.save();

    // fetch all branches from origin
    try {
        gitResult.fetch().setRemote("origin").setCredentialsProvider(credentials).setTimeout(timeout).call();
    } catch (Exception e) {
        throw new IOException("Failed to fetch from origin!", e);
    }

    return repo;
}

From source file:org.zanata.sync.jobs.plugin.git.service.impl.GitSyncService.java

License:Open Source License

protected static void checkOutBranch(Git git, String branch) throws GitAPIException, IOException {
    String currentBranch = git.getRepository().getBranch();
    if (currentBranch.equals(branch)) {
        log.info("already on branch: {}. will do a git pull", branch);
        PullResult pullResult = git.pull().call();
        log.debug("pull result: {}", pullResult);
        Preconditions.checkState(pullResult.isSuccessful());
        return;//from  www. j  ava 2s  .c o  m
    }

    List<Ref> refs = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
    /* refs will have name like these:
    refs/heads/master,
    refs/heads/trans,
    refs/heads/zanata,
    refs/remotes/origin/HEAD,
    refs/remotes/origin/master,
    refs/remotes/origin/trans,
    refs/remotes/origin/zanata
            
    where the local branches are: master, trans, zanata
    remote branches are: master, trans, zanata
    */
    Optional<Ref> localBranchRef = Optional.empty();
    Optional<Ref> remoteBranchRef = Optional.empty();
    for (Ref ref : refs) {
        String refName = ref.getName();
        if (refName.equals("refs/heads/" + branch)) {
            localBranchRef = Optional.of(ref);
        }
        if (refName.equals("refs/remotes/origin/" + branch)) {
            remoteBranchRef = Optional.of(ref);
        }
    }

    // if local branch exists and we are now on a different branch,
    // we delete it first then re-checkout
    if (localBranchRef.isPresent()) {
        log.debug("deleting local branch {}", branch);
        git.branchDelete().setBranchNames(branch).call();
    }

    if (remoteBranchRef.isPresent()) {
        // if remote branch exists, we create a new local branch based on it.
        git.checkout().setCreateBranch(true).setForce(true).setName(branch).setStartPoint("origin/" + branch)
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();
    } else {
        // If branch does not exists in remote, create new local branch based on master branch.
        git.checkout().setCreateBranch(true).setForce(true).setName(branch).setStartPoint("origin/master")
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();
    }
    if (log.isDebugEnabled()) {
        log.debug("current branch is: {}", git.getRepository().getBranch());
    }
}

From source file:org.zanata.sync.plugin.git.service.impl.GitSyncService.java

License:Open Source License

private void checkOutBranch(File destPath, String branch) {
    try {/*from   w  w w.  ja  v a  2  s .c  om*/
        Git git = Git.open(destPath);
        List<Ref> refs = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
        /* refs will have name like these:
        refs/heads/master
        refs/remotes/origin/master
        refs/remotes/origin/zanata
        */
        Optional<Ref> localBranchRef = Optional.empty();
        Optional<Ref> remoteBranchRef = Optional.empty();
        for (Ref ref : refs) {
            String refName = ref.getName();
            if (refName.equals("refs/heads/" + branch)) {
                localBranchRef = Optional.of(ref);
            }
            if (refName.equals("refs/remotes/origin/" + branch)) {
                remoteBranchRef = Optional.of(ref);
            }
        }

        if (branch.equals("master")) {
            log.debug("merging origin/master");
            git.checkout().setName("master").call();
            git.merge().setFastForward(MergeCommand.FastForwardMode.FF_ONLY).include(remoteBranchRef.get())
                    .call();
            return;
        }

        /**
         * If branch found in local and is not master, delete it, create new local branch from remote.
         * If branch does not exists in remote, create new local branch based on master branch.
         */
        Ref ref;
        if (localBranchRef.isPresent()) {
            git.checkout().setName("master").setForce(true).call();
            git.branchDelete().setBranchNames(branch).call();
        }

        if (remoteBranchRef.isPresent()) {
            ref = git.branchCreate().setForce(true).setName(branch).setStartPoint("origin/" + branch)
                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM).call();
        } else {
            ref = git.branchCreate().setForce(true).setName(branch).setStartPoint("origin/master")
                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM).call();
        }
        log.debug("checked out {}", ref);
        git.checkout().setName(branch).call();
        if (log.isDebugEnabled()) {
            log.debug("current branch is: {}", git.getRepository().getBranch());
        }
    } catch (IOException | GitAPIException e) {
        throw new RepoSyncException(e);
    }
}

From source file:org.zend.sdkcli.internal.commands.GitPushApplicationCommand.java

License:Open Source License

@Override
protected boolean doExecute() {
    Repository repo = null;/*w ww. java  2 s. c o  m*/
    try {
        File gitDir = getRepo();
        if (!gitDir.exists()) {
            getLogger().error("Git repository is not available in provided location");
            return false;
        }
        repo = FileRepositoryBuilder.create(getRepo());
    } catch (IOException e) {
        getLogger().error(e);
        return false;
    }
    if (repo != null) {
        Git git = new Git(repo);

        String remote = doGetRemote(repo);
        if (remote == null) {
            getLogger().error("Invalid remote value: " + getRemote());
            return false;
        }

        // perform operation only if it is clone of phpCloud repository
        String repoUrl = git.getRepository().getConfig().getString("remote", remote, "url");

        AddCommand addCommand = git.add();
        addCommand.setUpdate(false);
        // add all new files
        addCommand.addFilepattern(".");
        try {
            addCommand.call();
        } catch (NoFilepatternException e) {
            // should not occur because '.' is used
            getLogger().error(e);
            return false;
        } catch (GitAPIException e) {
            getLogger().error(e);
            return false;
        }

        CommitCommand commitCommand = git.commit();
        // automatically stage files that have been modified and deleted
        commitCommand.setAll(true);
        PersonIdent ident = getPersonalIdent(repoUrl);
        if (ident == null) {
            getLogger().error("Invalid author information provided: " + getAuthor());
            return false;
        }
        commitCommand.setAuthor(ident);
        commitCommand.setInsertChangeId(true);
        commitCommand.setMessage(getMessage());
        try {
            commitCommand.call();
        } catch (Exception e) {
            getLogger().error(e);
            return false;
        }

        // at the end push all changes
        PushCommand pushCommand = git.push();
        pushCommand.setPushAll();
        pushCommand.setRemote(remote);
        pushCommand.setProgressMonitor(new TextProgressMonitor(new PrintWriter(System.out)));

        try {
            URIish uri = new URIish(repoUrl);
            if (GITHUB_HOST.equals(uri.getHost()) && "git".equals(uri.getUser())) {
                if (!prepareSSHFactory()) {
                    return false;
                }
            } else {
                CredentialsProvider credentials = getCredentials(repoUrl);
                if (credentials != null) {
                    pushCommand.setCredentialsProvider(credentials);
                }
            }
            Iterable<PushResult> result = pushCommand.call();
            for (PushResult pushResult : result) {
                pushResult.getAdvertisedRefs();
                Collection<RemoteRefUpdate> updates = pushResult.getRemoteUpdates();
                for (RemoteRefUpdate remoteRefUpdate : updates) {
                    TrackingRefUpdate trackingRefUpdate = remoteRefUpdate.getTrackingRefUpdate();
                    getLogger().info(MessageFormat.format("Remote name: {0}, status: {1}",
                            remoteRefUpdate.getRemoteName(), remoteRefUpdate.getStatus().toString()));
                    getLogger().info(MessageFormat.format("Remote name: {0}, result: {1}",
                            trackingRefUpdate.getRemoteName(), trackingRefUpdate.getResult().toString()));
                }
            }
        } catch (JGitInternalException e) {
            getLogger().error(e);
            return false;
        } catch (InvalidRemoteException e) {
            // should not occur because selected remote is available
            getLogger().error(e);
            return false;
        } catch (URISyntaxException e) {
            getLogger().error(e);
            return false;
        } catch (TransportException e) {
            getLogger().error(e);
            return false;
        } catch (GitAPIException e) {
            getLogger().error(e);
            return false;
        }

    }
    return true;
}

From source file:playRepository.GitRepositoryTest.java

License:Apache License

public RevCommit addCommit(Git git, String fileName, String contents, String commitMessage, User author)
        throws IOException, GitAPIException {
    File newFile = new File(git.getRepository().getWorkTree().getAbsolutePath(), fileName);
    BufferedWriter out = new BufferedWriter(new FileWriter(newFile));
    out.write(contents);// w  w  w .jav  a2  s .  c  o  m
    out.flush();
    git.add().addFilepattern(fileName).call();
    CommitCommand commit = git.commit().setMessage(commitMessage);
    if (author != null) {
        commit.setAuthor(author.loginId, author.email).setCommitter(author.loginId, author.email);
    }
    return commit.call();
}