Example usage for org.eclipse.jgit.storage.file FileRepositoryBuilder create

List of usage examples for org.eclipse.jgit.storage.file FileRepositoryBuilder create

Introduction

In this page you can find the example usage for org.eclipse.jgit.storage.file FileRepositoryBuilder create.

Prototype

public static Repository create(File gitDir) throws IOException 

Source Link

Document

Convenience factory method to construct a org.eclipse.jgit.internal.storage.file.FileRepository .

Usage

From source file:org.eclipse.orion.server.git.jobs.StatusJob.java

License:Open Source License

@Override
protected IStatus performJob() {
    Logger logger = LoggerFactory.getLogger("org.eclipse.orion.server.git");
    Repository db = null;//from  w  w  w  .  jav a2s. c  o m
    try {
        long t0 = System.currentTimeMillis();
        Set<Entry<IPath, File>> set = GitUtils.getGitDirs(this.filePath, Traverse.GO_UP).entrySet();
        File gitDir = set.iterator().next().getValue();
        if (gitDir == null) {
            logger.error("***** Git status failed to find Git directory for request: " + this.filePath);
            String msg = NLS.bind("Could not find repository for {0}", filePath);
            return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null);
        }
        long t1 = System.currentTimeMillis();
        db = FileRepositoryBuilder.create(gitDir);
        Git git = new Git(db);
        org.eclipse.jgit.api.Status gitStatus = git.status().call();
        long t2 = System.currentTimeMillis();

        String relativePath = GitUtils.getRelativePath(this.filePath, set.iterator().next().getKey());
        IPath basePath = new Path(relativePath);
        org.eclipse.orion.server.git.objects.Status status = new org.eclipse.orion.server.git.objects.Status(
                this.baseLocation, db, gitStatus, basePath);
        ServerStatus result = new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, status.toJSON());
        if (logger.isDebugEnabled() && (t2 - t0) > GIT_PERF_THRESHOLD) {
            logger.debug("Slow git status. Finding git dir: " + (t1 - t0) + "ms. JGit status call: " + (t2 - t1)
                    + "ms");
        }
        return result;
    } catch (Exception e) {
        String msg = NLS.bind("An error occured when generating status for ref {0}", this.filePath);
        return new Status(IStatus.ERROR, GitActivator.PI_GIT, msg, e);
    } finally {
        if (db != null) {
            // close the git repository
            db.close();
        }
    }
}

From source file:org.eclipse.orion.server.git.servlets.GitSubmoduleHandlerV1.java

License:Open Source License

@Override
protected boolean handleDelete(RequestInfo requestInfo) throws ServletException {
    HttpServletRequest request = requestInfo.request;
    HttpServletResponse response = requestInfo.response;
    Repository db = requestInfo.db;/* w  w w  .  j a v  a2 s  .c  o  m*/
    Repository parentRepo = null;
    try {
        Map<IPath, File> parents = GitUtils.getGitDirs(requestInfo.filePath.removeLastSegments(1),
                Traverse.GO_UP);
        if (parents.size() < 1)
            return false;
        parentRepo = FileRepositoryBuilder.create(parents.entrySet().iterator().next().getValue());
        String pathToSubmodule = db.getWorkTree().toString()
                .substring(parentRepo.getWorkTree().toString().length() + 1);
        removeSubmodule(db, parentRepo, pathToSubmodule);
        return true;
    } catch (Exception ex) {
        String msg = "An error occured for delete submodule command.";
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex));
    } finally {
        if (parentRepo != null) {
            parentRepo.close();
        }
    }

}

From source file:org.eclipse.wst.jsdt.bower.core.api.InstallCommand.java

License:Open Source License

/**
 * Downloads the package with the given packageId matching the given range.
 *
 * @param packageId//from  www .ja v  a2s  .  c o  m
 *            The package id
 * @param rangeExpression
 *            The range
 * @return The dependencies of the downloaded package
 */
private Map<String, String> download(String packageId, String rangeExpression) {
    Map<String, String> dependencies = new HashMap<String, String>();

    Optional<String> packageUrl = this.getGitUrlFromPackageId(packageId);
    String packageName = this.getNameFromPackageId(packageId);

    if (packageUrl.isPresent() && this.monitor.isPresent() && !this.monitor.get().isCancelled()) {
        if (this.monitor.isPresent()) {
            this.monitor.get().beginTask(I18n.getString(I18nKeys.DOWNLOADING_LABEL, packageName), 10);
        }

        try {
            File tempFile = new File("/tmp"); //$NON-NLS-1$
            final Repository db = FileRepositoryBuilder.create(tempFile);
            Collection<Ref> refs = new Git(db).lsRemote().setRemote(packageUrl.get()).setTags(true).call();

            Optional<Ref> bestMatch = this.findBestMatch(refs, rangeExpression);
            if (bestMatch.isPresent() && outputDirectory.isPresent()) {
                File downloadedDependencyFolder = new File(outputDirectory.get(), packageName);
                if (!downloadedDependencyFolder.exists()) {
                    Git git = Git.cloneRepository().setProgressMonitor(monitor.get()).setURI(packageUrl.get())
                            .setDirectory(downloadedDependencyFolder).setBranch(bestMatch.get().getName())
                            .setBare(false).setNoCheckout(false).call();
                    git.close();

                    File gitFolder = new File(downloadedDependencyFolder, IBowerConstants.GIT_EXTENSION);
                    this.delete(gitFolder);

                    File bowerJsonFile = new File(downloadedDependencyFolder, IBowerConstants.BOWER_JSON);
                    Optional<BowerJson> dependencyBowerJson = this.getBowerJson(bowerJsonFile);
                    if (dependencyBowerJson.isPresent()) {
                        dependencies.putAll(dependencyBowerJson.get().getDependencies());
                    }
                }
            }

            db.close();
        } catch (GitAPIException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (this.monitor.isPresent()) {
            this.monitor.get().endTask();
        }
    }
    return dependencies;
}

From source file:org.opentravel.otm.forum2016.GitRepositorySynchronizer.java

License:Apache License

/**
 * Constructor that specifies the URL of the remote Git repository and the local
 * file system location of its clone./*from   w  ww.j  a va  2  s .  c  om*/
 * 
 * @param repositoryUrl  the URL of the remote Git repository
 * @param branch  the branch to be synchronized from the remote repository
 * @param localRepository  the local folder location to which the repository is to be cloned
 * @throws IOException  thrown if the local repository cannot be created
 */
public GitRepositorySynchronizer(String repositoryUrl, String branch, File localRepository) throws IOException {
    this.repositoryUrl = repositoryUrl;
    this.localRepository = localRepository;
    this.configFolder = new File(localRepository, "/.git");
    this.branch = (branch == null) ? "master" : branch;

    if (!localRepository.exists()) {
        if (!localRepository.mkdirs()) {
            throw new IOException("Unable to create local directory for Git repository clone.");
        }
    }
    this.gitRepo = FileRepositoryBuilder.create(configFolder);
}

From source file:org.wise.portal.presentation.web.controllers.author.project.JGitUtils.java

License:Open Source License

/**
 * @param directoryPath//  w  w  w  . j  a  v a 2 s.co m
 * @param doCreate create the directory if it doesn't exit
 * @return
 * @throws IOException
 */
public static Repository getGitRepository(String directoryPath, boolean doCreate) throws IOException {
    // prepare a new folder
    File localPath = new File(directoryPath);
    File gitDir = new File(localPath, ".git");
    if (!doCreate && !gitDir.exists()) {
        return null;
    } else {
        Repository repository = FileRepositoryBuilder.create(gitDir);
        if (doCreate && !gitDir.exists()) {
            repository.create();
        }
        return repository;
    }
}

From source file:org.wso2.developerstudio.appfactory.core.repository.JgitRepoManager.java

License:Open Source License

public JgitRepoManager(String localPath, String uri) throws IOException {
    this.localPath = localPath;
    this.remotePath = uri;
    File gitDir = new File(localPath + File.separator + ".git");
    localRepo = FileRepositoryBuilder.create(gitDir);
    git = new Git(localRepo);
    if (remotePath.equals(git.getRepository().getConfig().getString("remote", "origin", "url"))) {
        setCloned(true);/*  w ww.j a  va  2s.com*/
    }
    UserPasswordCredentials credentials = Authenticator.getInstance().getCredentials();
    provider = new UsernamePasswordCredentialsProvider(credentials.getGitUser(), credentials.getPassword());

}

From source file:org.wso2.developerstudio.appfactory.core.repository.JgitRepoManager.java

License:Open Source License

public void createGitRepo() {
    try {// ww w  . java2s  . com
        File gitDir = new File(localPath + File.separator + ".git");
        localRepo = FileRepositoryBuilder.create(gitDir);
        // localRepo = new FileRepository(localPath +File.separator +".git");
        localRepo.create();
    } catch (Exception e) {
        log.error("Git Repository creation Error : ", e);
    }
}

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

License:Open Source License

@Override
protected boolean doExecute() {
    Repository repo = null;//from   w  w  w  . jav a 2 s . c  om
    try {
        File gitDir = getProject();
        if (!gitDir.exists()) {
            getLogger().error("Git repository is not available in provided location");
            return false;
        }
        repo = FileRepositoryBuilder.create(gitDir);
    } catch (IOException e) {
        getLogger().error(e);
        return false;
    }
    if (repo != null) {
        String repoName = getReposiotryName(getRepo(), repo);
        if (repoName == null) {
            getLogger().error("Invalid repository URL :" + getRepo());
            return false;
        }
        try {
            RemoteConfig config = new RemoteConfig(repo.getConfig(), repoName);
            config.addURI(new URIish(getRepo()));
            String dst = Constants.R_REMOTES + config.getName();
            RefSpec refSpec = new RefSpec();
            refSpec = refSpec.setForceUpdate(true);
            refSpec = refSpec.setSourceDestination(Constants.R_HEADS + "*", dst + "/*"); //$NON-NLS-1$ //$NON-NLS-2$
            config.addFetchRefSpec(refSpec);
            config.update(repo.getConfig());
            repo.getConfig().save();
            getLogger().info(
                    MessageFormat.format("New remote called \"{0}\" was added successfully", config.getName()));
        } catch (URISyntaxException e) {
            getLogger().error("Invalid repository URL :" + getRepo());
            return false;
        } catch (IOException e) {
            getLogger().error(e);
            return false;
        }
    }
    return true;
}

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

License:Open Source License

@Override
protected boolean doExecute() {
    Repository repo = null;// w  w w.ja va 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:test.CookBookHelper.java

License:Apache License

public static Repository createNewRepository() throws IOException {

    String path = "C:\\VOTSH";
    File index = new File(path);
    // prepare a new folder
    File localPath = File.createTempFile("NewRepository", "", index);
    localPath.delete();//from  ww  w .  java  2  s .com

    // create the directory
    Repository repository = FileRepositoryBuilder.create(new File(localPath, ".git"));
    repository.create();

    return repository;
}