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.orion.server.tests.servlets.git.GitConfigTest.java

License:Open Source License

@Test
public void testInitializedRepoConfigUsingUserProfile() 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());

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

    String contentLocation = init(null, initPath, null).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,//  w w  w .  j a  v  a  2 s  .  c  o 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);
}

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

License:Open Source License

static void assertOnBranch(Git git, String branch) throws IOException {
    assertNotNull(git.getRepository().getRef(branch));
}

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

License:Open Source License

@Test
@Ignore("see bug 339397")
public void testResetAutocrlfTrue() throws Exception {

    // "git config core.autocrlf true"
    Git git = new Git(db);
    StoredConfig config = git.getRepository().getConfig();
    config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF,
            Boolean.TRUE);/*from   w  w  w .  j ava2  s. co m*/
    config.save();

    URI workspaceLocation = createWorkspace(getMethodName());

    String projectName = getMethodName();
    JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString());
    String projectId = project.getString(ProtocolConstants.KEY_ID);

    JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
    String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
    String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS);
    String gitCommitUri = gitSection.getString(GitConstants.KEY_COMMIT);

    // CRLF
    // TODO: don't create URIs out of thin air
    WebRequest request = getPutFileRequest(projectId + "/test.txt", "f" + "\r\n" + "older");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // "git add {path}"
    // TODO: don't create URIs out of thin air
    request = GitAddTest.getPutGitIndexRequest(gitIndexUri + "test.txt");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // commit
    request = GitCommitTest.getPostGitCommitRequest(gitCommitUri, "added new line - crlf", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // assert there is nothing to commit
    request = GitStatusTest.getGetGitStatusRequest(gitStatusUri);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject statusResponse = new JSONObject(response.getText());
    GitStatusTest.assertStatusClean(statusResponse);

    // create new file
    String fileName = "new.txt";
    request = getPostFilesRequest(projectId + "/", getNewFileJSON(fileName).toString(), fileName);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    JSONObject file = new JSONObject(response.getText());
    String location = file.optString(ProtocolConstants.KEY_LOCATION, null);
    assertNotNull(location);

    // LF
    request = getPutFileRequest(location, "i'm" + "\n" + "new");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // "git add ."
    request = GitAddTest.getPutGitIndexRequest(gitIndexUri /* stage all */);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // reset
    request = getPostGitIndexRequest(gitIndexUri /* reset all */, ResetType.MIXED);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    request = GitStatusTest.getGetGitStatusRequest(gitStatusUri);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    statusResponse = new JSONObject(response.getText());
    JSONArray statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_ADDED);
    assertEquals(0, statusArray.length());
    statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_CHANGED);
    assertEquals(0, statusArray.length());
    statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_MISSING);
    assertEquals(0, statusArray.length());
    statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_MODIFIED);
    assertEquals(0, statusArray.length());
    statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_REMOVED);
    assertEquals(0, statusArray.length());
    statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_UNTRACKED);
    assertEquals(1, statusArray.length());
}

From source file:org.eclipse.recommenders.snipmatch.GitSnippetRepository.java

License:Open Source License

private void configureGit() throws IOException {
    Git git = Git.open(gitFile);
    StoredConfig config = git.getRepository().getConfig();
    config.setString("remote", "origin", "url", getRepositoryLocation());
    config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
    config.setString("remote", "origin", "pushUrl", pushUrl);
    // prevents trust anchor errors when pulling from eclipse.org
    config.setBoolean("http", null, "sslVerify", false);
    config.save();//  w w w .j av  a 2 s .  c o m
}

From source file:org.eclipse.recommenders.snipmatch.GitSnippetRepository.java

License:Open Source License

private void configureGitBranch(String remoteBranch) throws IOException {
    Git git = Git.open(gitFile);
    StoredConfig config = git.getRepository().getConfig();
    String pushBranch = "HEAD:" + pushBranchPrefix + "/" + remoteBranch;
    config.setString("remote", "origin", "push", pushBranch);

    config.setString("branch", remoteBranch, "remote", "origin");
    String branch = "refs/heads/" + remoteBranch;
    config.setString("branch", remoteBranch, "merge", branch);
    config.save();//  w  w  w.jav a 2s  .com
}

From source file:org.enterprisedomain.classmaker.impl.ContributionImpl.java

License:Apache License

/**
 * <!-- begin-user-doc --> <!-- end-user-doc -->
 * // ww  w  .  j  a  v a2 s .co m
 * @generated NOT
 */
public String initialize(boolean commit) {
    @SuppressWarnings("unchecked")
    SCMOperator<Git> operator = (SCMOperator<Git>) getWorkspace().getSCMRegistry().get(getProjectName());
    setName(getProjectName());
    try {
        Git git = operator.getRepositorySCM();
        // if (git == null)
        // return "";
        String currentBranch = git.getRepository().getBranch();

        ListBranchCommand listBranches = git.branchList();
        List<Ref> branches = listBranches.call();
        Iterator<Ref> it = branches.iterator();
        Ref branch = null;
        long timestamp = -1;
        String commitId = "";
        do {
            Version version = null;
            if (it.hasNext()) {
                branch = it.next();
                String[] name = branch.getName().split("/"); //$NON-NLS-1$
                try {
                    version = operator.decodeVersion(name[name.length - 1]);
                    ReflogCommand reflog = git.reflog();
                    reflog.setRef(branch.getName().toString());
                    Collection<ReflogEntry> refs = reflog.call();
                    for (ReflogEntry ref : refs)
                        if (ref.getNewId().equals(branch.getObjectId())) {
                            timestamp = operator.decodeTimestamp(ref.getComment());
                            if (timestamp == -1)
                                timestamp = operator.decodeTimestamp(version.getQualifier());
                        }
                } catch (IllegalArgumentException e) {
                    continue;
                }
            }
            if (version != null && !getRevisions().containsKey(version)) {
                Revision newRevision = newBareRevision(version);
                newRevision.setTimestamp(timestamp);
                newRevision.setProject(this);
                doNewRevision(newRevision);
                commitId = newRevision.initialize(commit);
            }
        } while (it.hasNext());
        if (!getRevisions().isEmpty() && getVersion().equals(Version.emptyVersion))
            setVersion(ListUtil.getLast(getRevisions()).getKey());
        else if (!getVersion().equals(Version.emptyVersion))
            checkout(getVersion(), timestamp);
        if (currentBranch.equals(SCMOperator.MASTER_BRANCH))
            checkout(getVersion(), timestamp);
        getWorkspace().getResourceSet().eAdapters().add(resourceAdapter);
        addResourceChangeListener(getResourceReloadListener());
        return commitId;
    } catch (Exception e) {
        ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(e));
        return null;
    } finally {
        try {
            operator.ungetRepositorySCM();
        } catch (Exception e) {
            ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(e));
        }
    }

}

From source file:org.enterprisedomain.classmaker.impl.ProjectImpl.java

License:Apache License

/**
 * <!-- begin-user-doc --> <!-- end-user-doc -->
 * //  w  ww. j a v a 2s  . c o  m
 * @generated NOT
 */
public void checkout(Version version, long time) {
    Revision revision = null;
    if (getRevisions().containsKey(version)) {
        setProjectVersion(version);
        if (getProjectName().isEmpty())
            return;
        Git git = null;
        @SuppressWarnings("unchecked")
        SCMOperator<Git> operator = (SCMOperator<Git>) getWorkspace().getSCMRegistry().get(getProjectName());
        Ref ref = null;
        try {
            git = operator.getRepositorySCM();
            ref = git.getRepository().findRef(version.toString());
            if (ref != null)
                git.checkout().setName(ref.getName()).call();
        } catch (CheckoutConflictException e) {
            if (git != null) {
                try {
                    ResetCommand reset = git.reset().setMode(ResetType.HARD);
                    if (ref != null)
                        reset.setRef(ref.getName());
                    reset.call();
                } catch (CheckoutConflictException ex) {
                    ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(ex));
                } catch (GitAPIException ex) {
                    ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(ex));
                }
            }
        } catch (Exception e) {
            ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(e));
        } finally {
            try {
                operator.ungetRepositorySCM();
            } catch (Exception e) {
                ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(e));
            }
        }
        revision = getRevisions().get(version);
        if (revision.getStateHistory().containsKey(time)) {
            State state = revision.getStateHistory().get((Object) time);
            EList<String> commits = state.getCommitIds();
            if (!commits.isEmpty()) {
                revision.checkout(time, state.getCommitId());
            } else
                revision.checkout(time);
        }
    } else
        throw new IllegalStateException(NLS.bind(Messages.VersionNotExists, version));
}

From source file:org.enterprisedomain.classmaker.impl.RevisionImpl.java

License:Apache License

@Override
public String initialize(boolean commit) {
    super.initialize(commit);
    @SuppressWarnings("unchecked")
    SCMOperator<Git> operator = (SCMOperator<Git>) getProject().getWorkspace().getSCMRegistry()
            .get(getProject().getProjectName());
    try {/*from  ww w. j  a  v a  2 s .  c o  m*/
        Git git = operator.getRepositorySCM();

        LogCommand log = git.log();
        Ref branch = git.getRepository().findRef(getVersion().toString());
        if (branch != null) {
            log.add(branch.getObjectId());
            Iterable<RevCommit> commits = log.call();
            for (RevCommit c : commits) {
                long timestamp = operator.decodeTimestamp(c.getShortMessage());
                if (timestamp == -1) {
                    timestamp = operator.decodeTimestamp(getVersion().getQualifier());
                    if (timestamp == -1)
                        continue;
                }
                State state = null;
                if (getStateHistory().containsKey(timestamp))
                    state = (State) getStateHistory().get((Object) timestamp);
                else {
                    state = ClassMakerFactory.eINSTANCE.createState();
                    state.setTimestamp(timestamp);
                    getStateHistory().put(timestamp, state);
                    state.getProject().setVersion(getVersion());
                }
                String commitId = c.getId().toString();
                state.getCommitIds().add(commitId);
                state.setCommitId(commitId);
                setTimestamp(timestamp);
                state.initialize(commit);
            }
            if (getStateHistory().isEmpty())
                return null;
            checkout(ListUtil.getLast(getStateHistory()).getKey());
        }
    } catch (NoHeadException e) {
        return null;
    } catch (Exception e) {
        ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(e));
        return null;
    } finally {
        try {
            operator.ungetRepositorySCM();
        } catch (Exception e) {
            ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(e));
        }
    }
    return getState().getCommitId();
}

From source file:org.enterprisedomain.classmaker.impl.RevisionImpl.java

License:Apache License

@Override
public void load(boolean create) throws CoreException {
    initialize(false);/* w  ww .  ja  v  a 2  s  .  c  o m*/
    getProject().initAdapters(this);
    if (create && isStateSet()) {
        @SuppressWarnings("unchecked")
        SCMOperator<Git> operator = (SCMOperator<Git>) getProject().getWorkspace().getSCMRegistry()
                .get(getProject().getProjectName());
        Git git = null;
        try {
            git = operator.getRepositorySCM();
            Ref branch = git.getRepository().findRef(getVersion().toString());
            if (branch == null) {
                if (create) {
                    create(ClassMakerPlugin.getProgressMonitor());
                }
                getState().initialize(false);
            }
        } catch (Exception e) {
            throw new CoreException(ClassMakerPlugin.createErrorStatus(e));
        } finally {
            try {
                operator.ungetRepositorySCM();
            } catch (Exception e) {
                throw new CoreException(ClassMakerPlugin.createErrorStatus(e));
            }
        }
    }
    if (isStateSet())
        getState().load(create);
}

From source file:org.enterprisedomain.classmaker.impl.StateImpl.java

License:Apache License

@Override
public String initialize(boolean commit) {
    if (!eIsSet(ClassMakerPackage.STATE__MODEL_NAME))
        super.initialize(commit);
    if (eIsSet(ClassMakerPackage.STATE__PROJECT)
            && getProject().eIsSet(ClassMakerPackage.Literals.PROJECT__PROJECT_NAME)
            && ResourceUtils.isProjectExists(getProjectName())) {
        URI modelURI = getModelURI();
        loadResource(modelURI, !eIsSet(ClassMakerPackage.STATE__RESOURCE), true);
        saveResource();/*  ww  w .  jav a  2s  .  c  om*/
        setPhase(Stage.MODELED);
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        if (commit)
            try {
                String[] segments = modelURI.deresolve(URI.createFileURI(root.getRawLocation().toString()))
                        .segments();
                String[] path = new String[segments.length - 2];
                System.arraycopy(segments, 2, path, 0, segments.length - 2);
                add(URI.createHierarchicalURI(path, null, null).toString());
                String result = commit();
                return result;
            } catch (Exception e) {
                ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(e));
                return null;
            }
        else {
            @SuppressWarnings("unchecked")
            SCMOperator<Git> operator = (SCMOperator<Git>) getProject().getWorkspace().getSCMRegistry()
                    .get(getProjectName());
            try {
                Git git = operator.getRepositorySCM();
                Ref branch = git.getRepository().findRef(getRevision().getVersion().toString());
                LogCommand log = git.log();
                log.add(branch.getObjectId());
                Iterable<RevCommit> commits = log.call();
                for (RevCommit c : commits) {
                    if (operator.decodeTimestamp(c.getShortMessage()) == getTimestamp()) {
                        String id = c.getId().toString();
                        getCommitIds().add(id);
                        setCommitId(id);
                    }
                }
            } catch (Exception e) {
            } finally {
                try {
                    operator.ungetRepositorySCM();
                } catch (Exception e) {
                    ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(e));
                }
            }
            getProject().checkout(getRevision().getVersion(), getTimestamp(), getCommitId());
        }
    }
    return getCommitId(); // $NON-NLS-1$
}