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.eclipse.oomph.setup.git.impl.GitCloneTaskImpl.java

License:Open Source License

private static void createBranch(SetupTaskContext context, Git git, String checkoutBranch, String remoteName)
        throws Exception {
    context.log("Creating local branch " + checkoutBranch);

    CreateBranchCommand command = git.branchCreate();
    command.setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM);
    command.setName(checkoutBranch);/*from w ww .j  a va  2s . c  o m*/
    command.setStartPoint("refs/remotes/" + remoteName + "/" + checkoutBranch);
    command.call();

    StoredConfig config = git.getRepository().getConfig();
    config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, checkoutBranch, ConfigConstants.CONFIG_KEY_REBASE,
            true);
    config.save();
}

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

License:Open Source License

private IStatus doClone() {
    try {//from www . j  ava  2  s  . c  o m
        File cloneFolder = new File(clone.getContentLocation().getPath());
        if (!cloneFolder.exists()) {
            cloneFolder.mkdir();
        }
        CloneCommand cc = Git.cloneRepository();
        cc.setBare(false);
        cc.setCredentialsProvider(credentials);
        cc.setDirectory(cloneFolder);
        cc.setRemote(Constants.DEFAULT_REMOTE_NAME);
        cc.setURI(clone.getUrl());
        Git git = cc.call();

        // Configure the clone, see Bug 337820
        GitCloneHandlerV1.doConfigureClone(git, user);
        git.getRepository().close();
    } catch (IOException e) {
        return new Status(IStatus.ERROR, GitActivator.PI_GIT, "Error cloning git repository", e);
    } catch (CoreException e) {
        return e.getStatus();
    } catch (GitAPIException e) {
        return getGitAPIExceptionStatus(e, "Error cloning git repository");
    } catch (JGitInternalException e) {
        return getJGitInternalExceptionStatus(e, "Error cloning git repository");
    } catch (Exception e) {
        return new Status(IStatus.ERROR, GitActivator.PI_GIT, "Error cloning git repository", e);
    }
    JSONObject jsonData = new JSONObject();
    try {
        jsonData.put(ProtocolConstants.KEY_LOCATION, URI.create(this.cloneLocation));
    } catch (JSONException e) {
        // Should not happen
    }
    return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, jsonData);
}

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

License:Open Source License

private IStatus doFetch() throws IOException, CoreException, URISyntaxException, GitAPIException {
    Repository db = getRepository();//from w  w  w .j a va2 s.co  m

    Git git = new Git(db);
    FetchCommand fc = git.fetch();

    RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
    credentials.setUri(remoteConfig.getURIs().get(0));

    fc.setCredentialsProvider(credentials);
    fc.setRemote(remote);
    if (branch != null) {
        // refs/heads/{branch}:refs/remotes/{remote}/{branch}
        RefSpec spec = new RefSpec(
                Constants.R_HEADS + branch + ":" + Constants.R_REMOTES + remote + "/" + branch); //$NON-NLS-1$ //$NON-NLS-2$
        spec = spec.setForceUpdate(force);
        fc.setRefSpecs(spec);
    }
    FetchResult fetchResult = fc.call();
    return handleFetchResult(fetchResult);
}

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

License:Open Source License

private IStatus doPush() throws IOException, CoreException, URISyntaxException, GitAPIException {
    // /git/remote/{remote}/{branch}/file/{path}
    File gitDir = GitUtils.getGitDir(path.removeFirstSegments(2));
    Repository db = new FileRepository(gitDir);
    Git git = new Git(db);

    PushCommand pushCommand = git.push();

    RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
    credentials.setUri(remoteConfig.getURIs().get(0));
    pushCommand.setCredentialsProvider(credentials);

    RefSpec spec = new RefSpec(srcRef + ':' + Constants.R_HEADS + branch);
    pushCommand.setRemote(remote).setRefSpecs(spec);
    if (tags)// w ww .  j  a v a2  s.  c  om
        pushCommand.setPushTags();
    pushCommand.setForce(force);
    Iterable<PushResult> resultIterable = pushCommand.call();
    PushResult pushResult = resultIterable.iterator().next();
    // this set will contain only OK status or UP_TO_DATE status
    Set<RemoteRefUpdate.Status> statusSet = new HashSet<RemoteRefUpdate.Status>();
    for (final RemoteRefUpdate rru : pushResult.getRemoteUpdates()) {
        final String rm = rru.getRemoteName();
        // check status only for branch given in the URL or tags
        if (branch.equals(Repository.shortenRefName(rm)) || rm.startsWith(Constants.R_TAGS)) {
            RemoteRefUpdate.Status status = rru.getStatus();
            // any status different from UP_TO_DATE and OK should generate warning
            if (status != RemoteRefUpdate.Status.OK && status != RemoteRefUpdate.Status.UP_TO_DATE)
                return new Status(IStatus.WARNING, GitActivator.PI_GIT, status.name(),
                        new Throwable(rru.getMessage()));
            // add OK or UP_TO_DATE status to the set
            statusSet.add(status);
        }
        // TODO: return results for all updated branches once push is available for remote, see bug 352202
    }
    if (statusSet.contains(RemoteRefUpdate.Status.OK))
        // if there is OK status in the set -> something was updated
        return Status.OK_STATUS;
    else
        // if there is no OK status in the set -> only UP_TO_DATE status is possible
        return new Status(IStatus.WARNING, GitActivator.PI_GIT, RemoteRefUpdate.Status.UP_TO_DATE.name());
}

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

License:Open Source License

private IStatus doClone() {
    try {/*from w  w w .j a v a2s.  c o m*/
        File cloneFolder = new File(clone.getContentLocation().getPath());
        if (!cloneFolder.exists()) {
            cloneFolder.mkdir();
        }
        CloneCommand cc = Git.cloneRepository();
        cc.setBare(false);
        cc.setCredentialsProvider(credentials);
        cc.setDirectory(cloneFolder);
        cc.setRemote(Constants.DEFAULT_REMOTE_NAME);
        cc.setURI(clone.getUrl());
        Git git = cc.call();

        // Configure the clone, see Bug 337820
        task.setMessage(NLS.bind("Configuring {0}...", clone.getUrl()));
        updateTask(task);
        GitCloneHandlerV1.doConfigureClone(git, user);
        git.getRepository().close();
    } catch (IOException e) {
        return new Status(IStatus.ERROR, GitActivator.PI_GIT, "Error cloning git repository", e);
    } catch (CoreException e) {
        return e.getStatus();
    } catch (JGitInternalException e) {
        return getJGitInternalExceptionStatus(e, "An internal git error cloning git repository");
    } catch (Exception e) {
        return new Status(IStatus.ERROR, GitActivator.PI_GIT, "Error cloning git repository", e);
    }
    return Status.OK_STATUS;
}

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

License:Open Source License

private IStatus doFetch()
        throws IOException, CoreException, JGitInternalException, InvalidRemoteException, URISyntaxException {
    Repository db = getRepository();//www  . jav a2s .  c o  m
    String branch = getRemoteBranch();

    Git git = new Git(db);
    FetchCommand fc = git.fetch();

    RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
    credentials.setUri(remoteConfig.getURIs().get(0));

    fc.setCredentialsProvider(credentials);
    fc.setRemote(remote);
    if (branch != null) {
        // refs/heads/{branch}:refs/remotes/{remote}/{branch}
        RefSpec spec = new RefSpec(
                Constants.R_HEADS + branch + ":" + Constants.R_REMOTES + remote + "/" + branch); //$NON-NLS-1$ //$NON-NLS-2$
        spec = spec.setForceUpdate(force);
        fc.setRefSpecs(spec);
    }
    FetchResult fetchResult = fc.call();

    // handle result
    for (TrackingRefUpdate updateRes : fetchResult.getTrackingRefUpdates()) {
        Result res = updateRes.getResult();
        // handle status for given ref
        switch (res) {
        case NOT_ATTEMPTED:
        case NO_CHANGE:
        case NEW:
        case FORCED:
        case FAST_FORWARD:
        case RENAMED:
            // do nothing, as these statuses are OK
            break;
        case REJECTED:
        case REJECTED_CURRENT_BRANCH:
            // show warning, as only force fetch can finish successfully 
            return new Status(IStatus.WARNING, GitActivator.PI_GIT, res.name());
        default:
            return new Status(IStatus.ERROR, GitActivator.PI_GIT, res.name());
        }
    }
    return Status.OK_STATUS;
}

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

License:Open Source License

static void doConfigureClone(Git git, String user) throws IOException, CoreException {
    StoredConfig config = git.getRepository().getConfig();
    IOrionUserProfileNode userNode = UserServiceHelper.getDefault().getUserProfileService()
            .getUserProfileNode(user, true).getUserProfileNode(IOrionUserProfileConstants.GENERAL_PROFILE_PART);
    if (userNode.get(GitConstants.KEY_NAME, null) != null)
        config.setString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_NAME,
                userNode.get(GitConstants.KEY_NAME, null));
    if (userNode.get(GitConstants.KEY_MAIL, null) != null)
        config.setString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_EMAIL,
                userNode.get(GitConstants.KEY_MAIL, null));
    config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_FILEMODE, false);
    config.save();/*from   w ww  .j  av  a2 s .  c o  m*/
}

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

License:Open Source License

private IStatus doPush() throws IOException, CoreException, JGitInternalException, InvalidRemoteException,
        URISyntaxException, JSONException {
    // /git/remote/{remote}/{branch}/file/{path}
    File gitDir = GitUtils.getGitDir(path.removeFirstSegments(2));
    Repository db = new FileRepository(gitDir);
    Git git = new Git(db);

    PushCommand pushCommand = git.push();

    RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), path.segment(0));
    credentials.setUri(remoteConfig.getURIs().get(0));
    pushCommand.setCredentialsProvider(credentials);

    // ObjectId ref = db.resolve(srcRef);
    RefSpec spec = new RefSpec(srcRef + ":" + Constants.R_HEADS + path.segment(1)); //$NON-NLS-1$
    pushCommand.setRemote(path.segment(0)).setRefSpecs(spec);
    if (tags)//from  w w w . ja v  a2  s.  c  om
        pushCommand.setPushTags();
    pushCommand.setForce(force);
    Iterable<PushResult> resultIterable = pushCommand.call();
    PushResult pushResult = resultIterable.iterator().next();
    // this set will contain only OK status or UP_TO_DATE status
    Set<RemoteRefUpdate.Status> statusSet = new HashSet<RemoteRefUpdate.Status>();
    for (final RemoteRefUpdate rru : pushResult.getRemoteUpdates()) {
        final String rm = rru.getRemoteName();
        // final String sr = rru.isDelete() ? null : rru.getSrcRef();
        // check status only for branch given in the URL or tags
        if (path.segment(1).equals(Repository.shortenRefName(rm)) || rm.startsWith(Constants.R_TAGS)) {
            RemoteRefUpdate.Status status = rru.getStatus();
            // any status different from UP_TO_DATE and OK should generate warning
            if (status != RemoteRefUpdate.Status.OK && status != RemoteRefUpdate.Status.UP_TO_DATE)
                return new Status(IStatus.WARNING, GitActivator.PI_GIT, status.name());
            // add OK or UP_TO_DATE status to the set
            statusSet.add(status);
        }
        // TODO: return results for all updated branches once push is available for remote, see bug 342727, comment 1
    }
    if (statusSet.contains(RemoteRefUpdate.Status.OK))
        // if there is OK status in the set -> something was updated
        return Status.OK_STATUS;
    else
        // if there is no OK status in the set -> only UP_TO_DATE status is possible
        return new Status(IStatus.WARNING, GitActivator.PI_GIT, RemoteRefUpdate.Status.UP_TO_DATE.name());
}

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

License:Open Source License

@Test
public void testGetCloneAndPull() throws Exception {
    // see bug 339254
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = getWorkspaceId(workspaceLocation);

    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath = new Path("file").append(project.getString(ProtocolConstants.KEY_ID)).makeAbsolute();
    String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

    // get clones for workspace
    WebRequest request = listGitClonesRequest(workspaceId, null);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject clones = new JSONObject(response.getText());
    JSONArray clonesArray = clones.getJSONArray(ProtocolConstants.KEY_CHILDREN);
    assertEquals(1, clonesArray.length());

    Git git = new Git(getRepositoryForContentLocation(contentLocation));
    // TODO: replace with RESTful API when ready, see bug 339114
    PullResult pullResult = git.pull().call();
    assertEquals(pullResult.getMergeResult().getMergeStatus(), MergeStatus.ALREADY_UP_TO_DATE);
    assertEquals(RepositoryState.SAFE, git.getRepository().getRepositoryState());
}

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

License:Open Source License

@Test
public void testClonedRepoConfigUsingUserProfile() throws Exception {
    // set Git name and mail in the user profile
    WebRequest request = getPutUserRequest();
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone a  repo
    URI workspaceLocation = createWorkspace(getMethodName());
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath = new Path("file").append(project.getString(ProtocolConstants.KEY_ID)).makeAbsolute();

    String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

    // check the repository configuration using JGit API
    Git git = new Git(getRepositoryForContentLocation(contentLocation));
    StoredConfig config = git.getRepository().getConfig();
    assertEquals(GIT_NAME,/*from w ww  . j  ava 2s .  co m*/
            config.getString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_NAME));
    assertEquals(GIT_MAIL,
            config.getString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_EMAIL));

    // now check if commits have the right committer set

    request = getGetFilesRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project = new JSONObject(response.getText());
    String childrenLocation = project.getString(ProtocolConstants.KEY_CHILDREN_LOCATION);
    assertNotNull(childrenLocation);

    // check if Git locations are in place
    JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection);
    String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
    String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

    // modify
    String projectLocation = project.getString(ProtocolConstants.KEY_LOCATION);
    request = getPutFileRequest(projectLocation + "/test.txt", "change to commit");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // add
    request = GitAddTest.getPutGitIndexRequest(gitIndexUri + "test.txt");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // commit all
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri /* all */, GIT_COMMIT_MESSAGE, false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // log
    // TODO: replace with RESTful API for git log when available
    Iterable<RevCommit> commits = git.log().call();
    PersonIdent testIdent = new PersonIdent(GIT_NAME, GIT_MAIL);
    PersonIdent[] expectedIdents = new PersonIdent[] { testIdent };
    int c = 0;
    for (RevCommit commit : commits) {
        if (commit.getFullMessage().equals(GIT_COMMIT_MESSAGE)) {
            assertEquals(expectedIdents[expectedIdents.length - 1 - c].getName(),
                    commit.getCommitterIdent().getName());
            assertEquals(expectedIdents[expectedIdents.length - 1 - c].getEmailAddress(),
                    commit.getCommitterIdent().getEmailAddress());
        }
        c++;
    }
    assertEquals(2, c);
}