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

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

Introduction

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

Prototype

public LogCommand log() 

Source Link

Document

Return a command object to execute a Log command

Usage

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

License:Open Source License

@Override
protected IStatus performJob() {

    try {//from  www . j a  v  a  2 s .c om
        File gitDir = GitUtils.getGitDir(path);
        Repository db = new FileRepository(gitDir);
        Git git = new Git(db);
        Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
        for (String configN : configNames) {
            if (configN.equals(configName)) {
                Remote remote = new Remote(cloneLocation, db, configN);
                JSONObject result = remote.toJSON();
                if (!result.has(ProtocolConstants.KEY_CHILDREN)) {
                    return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
                }
                JSONArray children = result.getJSONArray(ProtocolConstants.KEY_CHILDREN);
                if (children.length() == 0 || (commitsSize == 0 && pageSize < 0)) {
                    return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
                }

                int firstChild = pageSize > 0 ? pageSize * (pageNo - 1) : 0;
                int lastChild = pageSize > 0 ? firstChild + pageSize - 1 : children.length() - 1;
                lastChild = lastChild > children.length() - 1 ? children.length() - 1 : lastChild;
                if (pageNo > 1 && baseLocation != null) {
                    String prev = baseLocation + "?page=" + (pageNo - 1) + "&pageSize=" + pageSize;
                    if (commitsSize > 0) {
                        prev += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize;
                    }
                    result.put(ProtocolConstants.KEY_PREVIOUS_LOCATION, prev);
                }
                if (lastChild < children.length() - 1) {
                    String next = baseLocation + "?page=" + (pageNo + 1) + "&pageSize=" + pageSize;
                    if (commitsSize > 0) {
                        next += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize;
                    }
                    result.put(ProtocolConstants.KEY_NEXT_LOCATION, next);
                }

                JSONArray newChildren = new JSONArray();
                for (int i = firstChild; i <= lastChild; i++) {
                    JSONObject branch = children.getJSONObject(i);
                    if (commitsSize == 0) {
                        newChildren.put(branch);
                    } else {
                        LogCommand lc = git.log();
                        String branchName = branch.getString(ProtocolConstants.KEY_ID);
                        ObjectId toObjectId = db.resolve(branchName);
                        Ref toRefId = db.getRef(branchName);
                        if (toObjectId == null) {
                            String msg = NLS.bind("No ref or commit found: {0}", branchName);
                            return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null);
                        }
                        toObjectId = getCommitObjectId(db, toObjectId);

                        // set the commit range
                        lc.add(toObjectId);
                        lc.setMaxCount(this.commitsSize);
                        Iterable<RevCommit> commits = lc.call();
                        Log log = new Log(cloneLocation, db, commits, null, null, toRefId);
                        log.setPaging(1, commitsSize);
                        branch.put(GitConstants.KEY_TAG_COMMIT, log.toJSON());
                        newChildren.put(branch);
                    }
                }

                result.put(ProtocolConstants.KEY_CHILDREN, newChildren);

                return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
            }
        }
        String msg = NLS.bind("Couldn't find remote : {0}", configName);
        return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null);
    } catch (Exception e) {
        String msg = NLS.bind("Couldn't get remote details : {0}", configName);
        return new Status(IStatus.ERROR, GitActivator.PI_GIT, msg, e);
    }

}

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

License:Open Source License

private boolean handleGetCommitLog(HttpServletRequest request, HttpServletResponse response, Repository db,
        String refIdsRange, String path) throws AmbiguousObjectException, IOException, ServletException,
        JSONException, URISyntaxException, CoreException {
    int page = request.getParameter("page") != null ? new Integer(request.getParameter("page")).intValue() : 0; //$NON-NLS-1$ //$NON-NLS-2$
    int pageSize = request.getParameter("pageSize") != null //$NON-NLS-1$
            ? new Integer(request.getParameter("pageSize")).intValue() //$NON-NLS-1$
            : PAGE_SIZE;/*  w w w .j  av  a 2s . c o  m*/

    ObjectId toObjectId = null;
    ObjectId fromObjectId = null;

    Ref toRefId = null;
    Ref fromRefId = null;

    Git git = new Git(db);
    LogCommand log = git.log();

    if (refIdsRange != null) {
        // git log <since>..<until>
        if (refIdsRange.contains("..")) { //$NON-NLS-1$
            String[] commits = refIdsRange.split("\\.\\."); //$NON-NLS-1$
            if (commits.length != 2) {
                String msg = NLS.bind("Failed to generate commit log for ref {0}", refIdsRange);
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
            }

            fromObjectId = db.resolve(commits[0]);
            fromRefId = db.getRef(commits[0]);
            if (fromObjectId == null) {
                String msg = NLS.bind("Failed to generate commit log for ref {0}", commits[0]);
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
            }

            toObjectId = db.resolve(commits[1]);
            toRefId = db.getRef(commits[1]);
            if (toObjectId == null) {
                String msg = NLS.bind("No ref or commit found: {0}", commits[1]);
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
            }
        } else {
            toObjectId = db.resolve(refIdsRange);
            toRefId = db.getRef(refIdsRange);
            if (toObjectId == null) {
                String msg = NLS.bind("No ref or commit found: {0}", refIdsRange);
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
            }
        }

        // set the commit range
        log.add(toObjectId);

        if (fromObjectId != null)
            log.not(fromObjectId);
    } else {
        // git log --all
        // workaround for git log --all - see bug 353310
        List<Ref> branches = git.branchList().setListMode(ListMode.ALL).call();
        for (Ref branch : branches) {
            log.add(branch.getObjectId());
        }
    }

    // set the path filter
    TreeFilter filter = null;

    boolean isRoot = true;
    if (path != null && !"".equals(path)) { //$NON-NLS-1$
        filter = AndTreeFilter.create(PathFilterGroup.createFromStrings(Collections.singleton(path)),
                TreeFilter.ANY_DIFF);
        log.addPath(path);
        isRoot = false;
    }

    try {
        Iterable<RevCommit> commits = log.call();
        Map<ObjectId, JSONArray> commitToBranchMap = getCommitToBranchMap(db);
        JSONObject result = toJSON(db, OrionServlet.getURI(request), commits, commitToBranchMap, page, pageSize,
                filter, isRoot);

        result.put(GitConstants.KEY_REPOSITORY_PATH, isRoot ? "" : path); //$NON-NLS-1$
        if (refIdsRange == null)
            result.put(GitConstants.KEY_CLONE,
                    BaseToCloneConverter.getCloneLocation(getURI(request), BaseToCloneConverter.COMMIT));
        else
            result.put(GitConstants.KEY_CLONE, BaseToCloneConverter.getCloneLocation(getURI(request),
                    BaseToCloneConverter.COMMIT_REFRANGE));

        if (toRefId != null) {
            result.put(GitConstants.KEY_REMOTE, BaseToRemoteConverter.getRemoteBranchLocation(getURI(request),
                    Repository.shortenRefName(toRefId.getName()), db, BaseToRemoteConverter.REMOVE_FIRST_3));

            String refTargetName = toRefId.getTarget().getName();
            if (refTargetName.startsWith(Constants.R_HEADS)) {
                // this is a branch
                result.put(GitConstants.KEY_LOG_TO_REF,
                        BranchToJSONConverter.toJSON(toRefId.getTarget(), db, getURI(request), 3));
            }
        }
        if (fromRefId != null) {
            String refTargetName = fromRefId.getTarget().getName();
            if (refTargetName.startsWith(Constants.R_HEADS)) {
                // this is a branch
                result.put(GitConstants.KEY_LOG_FROM_REF,
                        BranchToJSONConverter.toJSON(fromRefId.getTarget(), db, getURI(request), 3));
            }
        }

        OrionServlet.writeJSONResponse(request, response, result);
        return true;
    } catch (NoHeadException e) {
        String msg = NLS.bind("No HEAD reference found when generating log for ref {0}", refIdsRange);
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
    } catch (JGitInternalException e) {
        String msg = NLS.bind("An internal error occured when generating log for ref {0}", refIdsRange);
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
    }
}

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

License:Open Source License

@Test
public void testCommitAmend() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());

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

    // TODO: don't create URIs out of thin air
    WebRequest request = getPutFileRequest(projectId + "/test.txt", "change to commit");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection);/*from  w  ww.  j a v  a  2  s .co m*/
    String gitIndexUri = gitSection.optString(GitConstants.KEY_INDEX, null);
    assertNotNull(gitIndexUri);
    String gitHeadUri = gitSection.optString(GitConstants.KEY_HEAD, null);
    assertNotNull(gitHeadUri);

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

    // commit all
    request = getPostGitCommitRequest(gitHeadUri, "Comit massage", false); // typos
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // amend last commit
    request = getPostGitCommitRequest(gitHeadUri, "Commit message", true);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // TODO: replace with RESTful API for git log when available
    Git git = new Git(db);
    Iterable<RevCommit> commits = git.log().call();
    String expectedMessages[] = new String[] { "Initial commit", "Commit message" };
    int c = 0;
    for (RevCommit commit : commits) {
        assertEquals(expectedMessages[expectedMessages.length - 1 - c], commit.getFullMessage());
        c++;
    }
    assertEquals(expectedMessages.length, c);
}

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,/* w ww .  ja va 2s .  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.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,//from   w  w w.  j  a  va  2s  .  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.GitFetchTest.java

License:Open Source License

@Test
public void testPushCommitAndFetch() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());

    // clone1/*from w  w w  .  j a va 2  s. com*/
    JSONObject project1 = createProjectOrLink(workspaceLocation, getMethodName() + "1", null);
    IPath clonePath1 = new Path("file").append(project1.getString(ProtocolConstants.KEY_ID)).makeAbsolute();
    String contentLocation1 = clone(clonePath1).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

    // get project1 metadata
    WebRequest request = getGetFilesRequest(project1.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project1 = new JSONObject(response.getText());
    JSONObject gitSection1 = project1.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection1);
    String gitRemoteUri1 = gitSection1.getString(GitConstants.KEY_REMOTE);

    // clone2
    JSONObject project2 = createProjectOrLink(workspaceLocation, getMethodName() + "2", null);
    String projectId2 = project2.getString(ProtocolConstants.KEY_ID);
    IPath clonePath2 = new Path("file").append(project2.getString(ProtocolConstants.KEY_ID)).makeAbsolute();
    clone(clonePath2);

    // get project2 metadata
    request = getGetFilesRequest(project2.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project2 = new JSONObject(response.getText());
    JSONObject gitSection2 = project2.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection2);
    String gitRemoteUri2 = gitSection2.getString(GitConstants.KEY_REMOTE);
    String gitIndexUri2 = gitSection2.getString(GitConstants.KEY_INDEX);
    String gitHeadUri2 = gitSection2.getString(GitConstants.KEY_HEAD);

    // clone2: change
    request = getPutFileRequest(projectId2 + "/test.txt", "incoming change");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone2: add
    request = GitAddTest.getPutGitIndexRequest(gitIndexUri2);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone2: commit
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri2, "incoming change commit", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone2: push
    ServerStatus pushStatus = push(gitRemoteUri2, 1, 0, Constants.MASTER, Constants.HEAD, false);
    assertEquals(true, pushStatus.isOK());

    JSONObject masterDetails = getRemoteBranch(gitRemoteUri1, 1, 0, Constants.MASTER);
    String refId1 = masterDetails.getString(ProtocolConstants.KEY_ID);
    String remoteBranchLocation = masterDetails.getString(ProtocolConstants.KEY_LOCATION);

    // clone1: fetch
    fetch(remoteBranchLocation);

    masterDetails = getRemoteBranch(gitRemoteUri1, 1, 0, Constants.MASTER);
    String newRefId1 = masterDetails.getString(ProtocolConstants.KEY_ID);
    assertFalse(newRefId1.equals(refId1));

    // clone1: log master..origin/master
    // TODO replace with tests methods from GitLogTest, bug 340051
    Repository db1 = getRepositoryForContentLocation(contentLocation1);
    ObjectId master = db1.resolve(Constants.MASTER);
    ObjectId originMaster = db1
            .resolve(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + '/' + Constants.MASTER);
    Git git = new Git(db1);
    Iterable<RevCommit> commits = git.log().addRange(master, originMaster).call();
    int c = 0;
    for (RevCommit commit : commits) {
        assertEquals("incoming change commit", commit.getFullMessage());
        c++;
    }
    // a single incoming commit
    assertEquals(1, c);
}

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

License:Open Source License

@Test
public void testPushAndFetchWithPrivateKeyAndPassphrase() throws Exception {

    Assume.assumeTrue(sshRepo2 != null);
    Assume.assumeTrue(knownHosts2 != null);
    Assume.assumeTrue(privateKey != null);
    Assume.assumeTrue(passphrase != null);

    URI workspaceLocation = createWorkspace(getMethodName());
    URIish uri = new URIish(sshRepo2);

    // clone1: create
    JSONObject project1 = createProjectOrLink(workspaceLocation, getMethodName() + "1", null);
    IPath clonePath = new Path("file").append(project1.getString(ProtocolConstants.KEY_ID)).makeAbsolute();
    WebRequest request = new PostGitCloneRequest().setURIish(uri).setFilePath(clonePath)
            .setKnownHosts(knownHosts2).setPrivateKey(privateKey).setPublicKey(publicKey)
            .setPassphrase(passphrase).getWebRequest();
    String cloneContentLocation1 = clone(request);

    // clone1: get project/folder metadata
    request = getGetFilesRequest(cloneContentLocation1);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project1 = new JSONObject(response.getText());

    // clone1: get git links
    JSONObject gitSection1 = project1.getJSONObject(GitConstants.KEY_GIT);
    String gitRemoteUri1 = gitSection1.getString(GitConstants.KEY_REMOTE);

    // clone2: create
    JSONObject project2 = createProjectOrLink(workspaceLocation, getMethodName() + "2", null);
    String projectId2 = project2.getString(ProtocolConstants.KEY_ID);
    clonePath = new Path("file").append(projectId2).makeAbsolute();
    request = new PostGitCloneRequest().setURIish(uri).setFilePath(clonePath).setKnownHosts(knownHosts2)
            .setPrivateKey(privateKey).setPublicKey(publicKey).setPassphrase(passphrase).getWebRequest();
    String cloneContentLocation2 = clone(request);

    // clone2: get project/folder metadata
    request = getGetFilesRequest(cloneContentLocation2);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project2 = new JSONObject(response.getText());

    // clone2: get git links
    JSONObject gitSection2 = project2.getJSONObject(GitConstants.KEY_GIT);
    String gitRemoteUri2 = gitSection2.getString(GitConstants.KEY_REMOTE);
    String gitIndexUri2 = gitSection2.getString(GitConstants.KEY_INDEX);
    String gitHeadUri2 = gitSection2.getString(GitConstants.KEY_HEAD);

    // clone2: change
    request = getPutFileRequest(projectId2 + "/test.txt", "incoming change");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone2: add
    request = GitAddTest.getPutGitIndexRequest(gitIndexUri2);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone2: commit
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri2, "incoming change commit", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone2: push
    ServerStatus pushStatus = push(gitRemoteUri2, 1, 0, Constants.MASTER, Constants.HEAD, false, null,
            knownHosts2, privateKey, publicKey, passphrase, true);
    assertEquals(true, pushStatus.isOK());

    JSONObject details = getRemoteBranch(gitRemoteUri1, 1, 0, Constants.MASTER);
    String refId1 = details.getString(ProtocolConstants.KEY_ID);
    String remoteBranchLocation = details.getString(ProtocolConstants.KEY_LOCATION);

    // clone1: fetch
    fetch(remoteBranchLocation, null, knownHosts2, privateKey, publicKey, passphrase, true);

    details = getRemoteBranch(gitRemoteUri1, 1, 0, Constants.MASTER);
    String newRefId1 = details.getString(ProtocolConstants.KEY_ID);
    assertFalse(newRefId1.equals(refId1));

    // clone1: log master..origin/master
    // TODO replace with tests methods from GitLogTest, bug 340051
    Repository db1 = getRepositoryForContentLocation(cloneContentLocation1);
    ObjectId master = db1.resolve(Constants.MASTER);
    ObjectId originMaster = db1/*from   w  ww . ja  v a2  s  .  c  o  m*/
            .resolve(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + '/' + Constants.MASTER);
    Git git = new Git(db1);
    Iterable<RevCommit> commits = git.log().addRange(master, originMaster).call();
    int c = 0;
    for (RevCommit commit : commits) {
        assertEquals("incoming change commit", commit.getFullMessage());
        c++;
    }
    // a single incoming commit
    assertEquals(1, c);
}

From source file:org.eclipse.osee.ote.version.git.GitVersion.java

License:Open Source License

public RevCommit getLastCommit() throws IOException, NoHeadException, GitAPIException {
    if (!file.exists()) {
        return null;
    }//w ww. ja v a 2s.c o m
    File gitFolder = findGitDirUp(file);
    if (gitFolder == null) {
        return null;
    }
    Repository repository = buildRepository(gitFolder);
    Git git = new Git(repository);
    LogCommand log = git.log();
    String pathFilter = getPathFilterFromFullPathAndGitFolder(file, gitFolder);
    log.addPath(pathFilter);
    Iterable<RevCommit> iterable = log.call();
    Iterator<RevCommit> it = iterable.iterator();
    if (it.hasNext()) {
        return it.next();
    } else {
        return null;
    }
}

From source file:org.eclipse.osee.ote.version.git.GitVersions.java

License:Open Source License

public Map<File, RevCommit> getLastCommits() {
    Map<File, RevCommit> commits = new HashMap<File, RevCommit>();
    Map<File, List<File>> gitToFiles = new HashMap<File, List<File>>();
    for (File file : files) {
        if (!file.exists()) {
            continue;
        }//from   w ww.j  av a  2s.c om
        File gitFolder = findGitDirUp(file);
        if (gitFolder == null) {
            continue;
        }
        List<File> gitfiles = gitToFiles.get(gitFolder);
        if (gitfiles == null) {
            gitfiles = new ArrayList<File>();
            gitToFiles.put(gitFolder, gitfiles);
        }
        gitfiles.add(file);
    }
    for (Entry<File, List<File>> entry : gitToFiles.entrySet()) {
        try {
            Repository repository = buildRepository(entry.getKey());
            Git git = new Git(repository);

            for (File gitfile : entry.getValue()) {
                LogCommand log = git.log();
                log.setMaxCount(1);
                String pathFilter = getPathFilterFromFullPathAndGitFolder(gitfile, entry.getKey());
                log.addPath(pathFilter);
                Iterable<RevCommit> iterable = log.call();
                Iterator<RevCommit> it = iterable.iterator();
                if (it.hasNext()) {
                    RevCommit commit = it.next();
                    commits.put(gitfile, commit);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoHeadException e) {
            e.printStackTrace();
        } catch (GitAPIException e) {
            e.printStackTrace();
        }
    }
    return commits;
}

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 {// www  . j av a 2s. com
        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();
}