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

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

Introduction

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

Prototype

public CleanCommand clean() 

Source Link

Document

Return a command object to execute a clean command

Usage

From source file:org.eclipse.egit.ui.internal.clean.CleanRepositoryPage.java

License:Open Source License

/**
 * Do the cleaning with the selected values.
 *///www. ja v a  2 s  .  co  m
public void finish() {
    try {
        final Set<String> itemsToClean = getItemsToClean();

        getContainer().run(true, false, new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                monitor.beginTask(UIText.CleanRepositoryPage_cleaningItems, IProgressMonitor.UNKNOWN);

                Git git = Git.wrap(repository);
                CleanCommand command = git.clean().setDryRun(false);
                command.setCleanDirectories(cleanDirectories);
                command.setIgnore(!includeIgnored);
                command.setPaths(itemsToClean);
                try {
                    command.call();
                } catch (GitAPIException ex) {
                    Activator.logError("cannot call clean command!", ex); //$NON-NLS-1$
                }

                try {
                    IProject[] projects = ProjectUtil.getProjectsContaining(repository, itemsToClean);
                    ProjectUtil.refreshResources(projects, new SubProgressMonitor(monitor, 1));
                } catch (CoreException e) {
                    // could not refresh... not a "real" problem
                }

                monitor.done();
            }
        });
    } catch (Exception e) {
        Activator.logError("Unexpected exception while cleaning", e); //$NON-NLS-1$
    }
}

From source file:org.fusesource.fabric.git.internal.GitDataStore.java

License:Apache License

/**
 * Performs a pull so the git repo is pretty much up to date before we start performing operations on it
 *///  w  w w  .ja  v a  2 s  .c o  m
protected void doPull(Git git, CredentialsProvider credentialsProvider) {
    assertValid();
    try {
        Repository repository = git.getRepository();
        StoredConfig config = repository.getConfig();
        String url = config.getString("remote", remote, "url");
        if (Strings.isNullOrBlank(url)) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No remote repository defined for the git repository at "
                        + GitHelpers.getRootGitDirectory(git) + " so not doing a pull");
            }
            return;
        }
        /*
        String branch = repository.getBranch();
        String mergeUrl = config.getString("branch", branch, "merge");
        if (Strings.isNullOrBlank(mergeUrl)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No merge spec for branch." + branch + ".merge in the git repository at "
                    + GitHelpers.getRootGitDirectory(git) + " so not doing a pull");
        }
        return;
        }
        */
        if (LOG.isDebugEnabled()) {
            LOG.debug("Performing a fetch in git repository " + GitHelpers.getRootGitDirectory(git)
                    + " on remote URL: " + url);
        }

        boolean hasChanged = false;
        try {
            git.fetch().setCredentialsProvider(credentialsProvider).setRemote(remote).call();
        } catch (Exception e) {
            LOG.debug("Fetch failed. Ignoring");
            return;
        }

        // Get local and remote branches
        Map<String, Ref> localBranches = new HashMap<String, Ref>();
        Map<String, Ref> remoteBranches = new HashMap<String, Ref>();
        Set<String> gitVersions = new HashSet<String>();
        for (Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) {
            if (ref.getName().startsWith("refs/remotes/" + remote + "/")) {
                String name = ref.getName().substring(("refs/remotes/" + remote + "/").length());
                if (!name.endsWith("-tmp")) {
                    remoteBranches.put(name, ref);
                    gitVersions.add(name);
                }
            } else if (ref.getName().startsWith("refs/heads/")) {
                String name = ref.getName().substring(("refs/heads/").length());
                if (!name.endsWith("-tmp")) {
                    localBranches.put(name, ref);
                    gitVersions.add(name);
                }
            }
        }

        // Check git commmits
        for (String version : gitVersions) {
            // Delete unneeded local branches.
            //Check if any remote branches was found as a guard for unwanted deletions.
            if (!remoteBranches.containsKey(version) && !remoteBranches.isEmpty()) {
                //We never want to delete the master branch.
                if (!version.equals(MASTER_BRANCH)) {
                    try {
                        git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true)
                                .call();
                    } catch (CannotDeleteCurrentBranchException ex) {
                        git.checkout().setName(MASTER_BRANCH).setForce(true).call();
                        git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true)
                                .call();
                    }
                    hasChanged = true;
                }
            }
            // Create new local branches
            else if (!localBranches.containsKey(version)) {
                git.checkout().setCreateBranch(true).setName(version).setStartPoint(remote + "/" + version)
                        .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).setForce(true).call();
                hasChanged = true;
            } else {
                String localCommit = localBranches.get(version).getObjectId().getName();
                String remoteCommit = remoteBranches.get(version).getObjectId().getName();
                if (!localCommit.equals(remoteCommit)) {
                    git.clean().setCleanDirectories(true).call();
                    git.checkout().setName("HEAD").setForce(true).call();
                    git.checkout().setName(version).setForce(true).call();
                    MergeResult result = git.merge().setStrategy(MergeStrategy.THEIRS)
                            .include(remoteBranches.get(version).getObjectId()).call();
                    if (result.getMergeStatus() != MergeResult.MergeStatus.ALREADY_UP_TO_DATE) {
                        hasChanged = true;
                    }
                    // TODO: handle conflicts
                }
            }
        }
        if (hasChanged) {
            LOG.debug("Changed after pull!");
            if (credentialsProvider != null) {
                // TODO lets test if the profiles directory is present after checking out version 1.0?
                File profilesDirectory = getProfilesDirectory(git);
            }
            fireChangeNotifications();
        }
    } catch (Throwable e) {
        LOG.error("Failed to pull from the remote git repo " + GitHelpers.getRootGitDirectory(git)
                + ". Reason: " + e, e);
    }
}

From source file:org.jabylon.team.git.GitTeamProvider.java

License:Open Source License

@Override
public Collection<PropertyFileDiff> reset(ProjectVersion project, IProgressMonitor monitor)
        throws TeamProviderException {

    List<PropertyFileDiff> updatedFiles = new ArrayList<PropertyFileDiff>();
    try {/* w w w .ja v  a2  s  .co m*/
        Repository repository = createRepository(project);
        SubMonitor subMon = SubMonitor.convert(monitor, "Reset", 100);
        Git git = new Git(repository);
        subMon.subTask("Calculating Diff");
        DiffCommand diffCommand = git.diff();
        diffCommand.setProgressMonitor(new ProgressMonitorWrapper(subMon.newChild(30)));
        diffCommand.setOldTree(prepareTreeParser(repository, "refs/remotes/origin/" + project.getName()));
        diffCommand.setNewTree(null);
        List<DiffEntry> diffs = diffCommand.call();
        for (DiffEntry diffEntry : diffs) {
            checkCanceled(monitor);
            PropertyFileDiff fileDiff = createDiff(diffEntry, monitor);
            revertDiff(fileDiff);
            updatedFiles.add(fileDiff);
        }

        subMon.subTask("Executing Reset");
        ResetCommand reset = git.reset();
        reset.setMode(ResetType.HARD);
        reset.setRef("refs/remotes/origin/" + project.getName());
        reset.call();

        CleanCommand clean = git.clean();
        clean.setCleanDirectories(true);
        Set<String> call = clean.call();
        LOGGER.info("cleaned " + call);

    } catch (IOException e) {
        LOGGER.error("reset failed", e);
        throw new TeamProviderException(e);
    } catch (GitAPIException e) {
        LOGGER.error("reset failed", e);
        throw new TeamProviderException(e);
    }
    return updatedFiles;
}

From source file:org.ocpsoft.redoculous.model.impl.GitRepository.java

License:Open Source License

@Override
public void initRef(String ref) {
    File repoDir = getRepoDir();/* ww w  .ja v  a 2s.com*/

    File refDir = getRefDir(ref);
    File refCacheDir = getCachedRefDir(ref);

    ref = resolveRef(ref);

    if (!refDir.exists()) {
        log.info("Creating ref copy [" + getUrl() + "] [" + ref + "] [" + getKey() + "]");
        refDir.mkdirs();
        refCacheDir.mkdirs();
        Git git = null;
        try {
            git = Git.open(repoDir);
            git.reset().setMode(ResetType.HARD).call();
            git.clean().setCleanDirectories(true).call();
            git.checkout().setName(ref).call();

            log.info("Deleting cache for [" + getUrl() + "] [" + ref + "] [" + getKey() + "]");
            Files.delete(refDir, true);
            Files.delete(refCacheDir, true);
            refCacheDir.mkdirs();
            Files.copyDirectory(repoDir, refDir, new FileFilter() {
                @Override
                public boolean accept(File file) {
                    return !(file.getName().equals(".git") || file.getName().equals(".gitignore"));
                }
            });
        } catch (Exception e) {
            if (git != null) {
                git.getRepository().close();
                git = null;
            }
            Files.delete(refDir, true);
            Files.delete(refCacheDir, true);
            throw new RewriteException(
                    "Could checkout ref [" + ref + "] from repository [" + getUrl() + "] [" + getKey() + "].",
                    e);
        } finally {
            if (git != null) {
                git.getRepository().close();
            }
        }
    }
}

From source file:org.ocpsoft.redoculous.model.impl.GitRepository.java

License:Open Source License

@Override
public void update() {
    File repoDir = getRepoDir();//from w w  w. j  a v a 2 s . co  m

    Git git = null;
    RedoculousProgressMonitor monitor = new RedoculousProgressMonitor();
    try {
        log.info("Handling update request for [" + getUrl() + "] [" + getKey() + "]");
        git = Git.open(repoDir);

        git.fetch().setTagOpt(TagOpt.FETCH_TAGS).setRemote("origin")
                .setRefSpecs(new RefSpec("+refs/heads/*:refs/remotes/origin/*")).setProgressMonitor(monitor)
                .call();

        git.fetch().setTagOpt(TagOpt.FETCH_TAGS).setRemote("origin")
                .setRefSpecs(new RefSpec("+refs/tags/*:refs/tags/*")).setProgressMonitor(monitor).call();

        git.reset().setMode(ResetType.HARD).setRef("refs/remotes/origin/" + git.getRepository().getBranch())
                .call();

        git.clean().setCleanDirectories(true).call();

        Files.delete(getRefsDir(), true);
        Files.delete(getCacheDir(), true);
    } catch (Exception e) {
        throw new RuntimeException("Could not update repository [" + getUrl() + "] [" + getKey() + "]", e);
    } finally {
        if (git != null)
            git.getRepository().close();
    }
}

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

License:Open Source License

protected static void cleanUpCurrentBranch(Git git) throws GitAPIException {
    log.debug("git clean current work tree");
    git.clean().setCleanDirectories(true).setPaths(Sets.newHashSet(".")).call();
}