Example usage for org.eclipse.jgit.lib Constants HEAD

List of usage examples for org.eclipse.jgit.lib Constants HEAD

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Constants HEAD.

Prototype

String HEAD

To view the source code for org.eclipse.jgit.lib Constants HEAD.

Click Source Link

Document

Special name for the "HEAD" symbolic-ref.

Usage

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

License:Open Source License

private boolean handlePost(HttpServletRequest request, HttpServletResponse response, Repository db, IPath path)
        throws ServletException, NoFilepatternException, IOException, JSONException {
    JSONObject toReset = OrionServlet.readJSONRequest(request);
    String resetType = toReset.optString(GitConstants.KEY_RESET_TYPE, null);
    if (resetType != null) {
        JSONArray paths = toReset.optJSONArray(ProtocolConstants.KEY_PATH);
        if (paths != null) {
            String msg = NLS.bind("Mixing {0} and {1} parameters is not allowed.",
                    new Object[] { ProtocolConstants.KEY_PATH, GitConstants.KEY_RESET_TYPE });
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }//from w w  w  .  j av  a  2s  . c om
        String ref = toReset.optString(GitConstants.KEY_TAG_COMMIT, Constants.HEAD);
        try {
            ResetType type = ResetType.valueOf(resetType);
            switch (type) {
            case MIXED:
            case HARD:
                Git git = new Git(db);
                // "git reset --{type} HEAD ."
                git.reset().setMode(type).setRef(ref).call();
                return true;
            case KEEP:
            case MERGE:
            case SOFT:
                String msg = NLS.bind("The reset type is not yet supported: {0}.", resetType);
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_IMPLEMENTED, msg, null));
            }
        } catch (IllegalArgumentException e) {
            String msg = NLS.bind("Unknown or malformed reset type: {0}.", resetType);
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }
    } else {
        String commit = toReset.optString(GitConstants.KEY_TAG_COMMIT, null);
        if (commit != null) {
            String msg = NLS.bind("Mixing {0} and {1} parameters is not allowed.",
                    new Object[] { ProtocolConstants.KEY_PATH, GitConstants.KEY_TAG_COMMIT });
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }
        JSONArray paths = toReset.optJSONArray(ProtocolConstants.KEY_PATH);
        Git git = new Git(db);
        ResetCommand reset = git.reset().setRef(Constants.HEAD);
        if (paths != null) {
            for (int i = 0; i < paths.length(); i++) {
                reset.addPath(paths.getString(i));
            }
        } else {
            String p = path.removeFirstSegments(2).toString();
            if (p.isEmpty()) {
                String msg = "Path cannot be empty.";
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
            }
            reset.addPath(p);
        }
        reset.call();
        return true;
    }
    return false;
}

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

License:Open Source License

private boolean handleGet(HttpServletRequest request, HttpServletResponse response, String path)
        throws IOException, JSONException, ServletException, URISyntaxException, CoreException {
    Path p = new Path(path);
    // FIXME: what if a remote or branch is named "file"?
    if (p.segment(0).equals("file")) { //$NON-NLS-1$
        // /git/remote/file/{path}
        File gitDir = GitUtils.getGitDir(p);
        Repository db = new FileRepository(gitDir);
        Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
        JSONObject result = new JSONObject();
        JSONArray children = new JSONArray();
        URI baseLocation = getURI(request);
        for (String configName : configNames) {
            JSONObject o = new JSONObject();
            o.put(ProtocolConstants.KEY_NAME, configName);
            o.put(ProtocolConstants.KEY_TYPE, GitConstants.KEY_REMOTE_NAME);
            o.put(GitConstants.KEY_URL, db.getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION,
                    configName, "url" /*RemoteConfig.KEY_URL*/));
            String pushUrl = null;
            if ((pushUrl = db.getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, configName,
                    "pushurl" /*RemoteConfig.KEY_PUSHURL*/)) != null)
                o.put(GitConstants.KEY_PUSH_URL, pushUrl);
            o.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_2
                    .baseToRemoteLocation(baseLocation, configName, "" /* no branch name */)); //$NON-NLS-1$
            children.put(o);//from  w  w w .ja  v a2 s .c  o m
        }
        result.put(ProtocolConstants.KEY_CHILDREN, children);
        OrionServlet.writeJSONResponse(request, response, result);
        return true;
    } else if (p.segment(1).equals("file")) { //$NON-NLS-1$
        // /git/remote/{remote}/file/{path}
        File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1));
        Repository db = new FileRepository(gitDir);
        Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
        JSONObject result = new JSONObject();
        URI baseLocation = getURI(request);

        for (String configName : configNames) {
            if (configName.equals(p.segment(0))) {
                result.put(ProtocolConstants.KEY_NAME, configName);
                result.put(ProtocolConstants.KEY_TYPE, GitConstants.KEY_REMOTE_NAME);
                result.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_3
                        .baseToRemoteLocation(baseLocation, p.segment(0), "" /* no branch name */)); //$NON-NLS-1$

                JSONArray children = new JSONArray();
                List<Ref> refs = new ArrayList<Ref>();
                for (Entry<String, Ref> refEntry : db.getRefDatabase()
                        .getRefs(Constants.R_REMOTES + p.uptoSegment(1)).entrySet()) {
                    if (!refEntry.getValue().isSymbolic()) {
                        Ref ref = refEntry.getValue();
                        String name = ref.getName();
                        name = Repository.shortenRefName(name)
                                .substring(Constants.DEFAULT_REMOTE_NAME.length() + 1);
                        if (db.getBranch().equals(name)) {
                            refs.add(0, ref);
                        } else {
                            refs.add(ref);
                        }
                    }
                }
                for (Ref ref : refs) {
                    JSONObject o = new JSONObject();
                    String name = ref.getName();
                    o.put(ProtocolConstants.KEY_NAME, name.substring(Constants.R_REMOTES.length()));
                    o.put(ProtocolConstants.KEY_FULL_NAME, name);
                    o.put(ProtocolConstants.KEY_TYPE, GitConstants.REMOTE_TRACKING_BRANCH_TYPE);
                    o.put(ProtocolConstants.KEY_ID, ref.getObjectId().name());
                    // see bug 342602
                    // o.put(GitConstants.KEY_COMMIT, baseToCommitLocation(baseLocation, name));
                    o.put(ProtocolConstants.KEY_LOCATION,
                            BaseToRemoteConverter.REMOVE_FIRST_3.baseToRemoteLocation(baseLocation,
                                    "" /*short name is {remote}/{branch}*/, Repository.shortenRefName(name))); //$NON-NLS-1$
                    o.put(GitConstants.KEY_COMMIT, BaseToCommitConverter.getCommitLocation(baseLocation,
                            ref.getObjectId().name(), BaseToCommitConverter.REMOVE_FIRST_3));
                    o.put(GitConstants.KEY_HEAD, BaseToCommitConverter.getCommitLocation(baseLocation,
                            Constants.HEAD, BaseToCommitConverter.REMOVE_FIRST_3));
                    o.put(GitConstants.KEY_CLONE,
                            BaseToCloneConverter.getCloneLocation(baseLocation, BaseToCloneConverter.REMOTE));
                    o.put(GitConstants.KEY_BRANCH, BaseToBranchConverter.getBranchLocation(baseLocation,
                            BaseToBranchConverter.REMOTE));
                    o.put(GitConstants.KEY_INDEX,
                            BaseToIndexConverter.getIndexLocation(baseLocation, BaseToIndexConverter.REMOTE));
                    children.put(o);
                }
                result.put(ProtocolConstants.KEY_CHILDREN, children);
                OrionServlet.writeJSONResponse(request, response, result);
                return true;
            }
        }
        String msg = NLS.bind("Couldn't find remote : {0}", p.segment(0));
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
    } else if (p.segment(2).equals("file")) { //$NON-NLS-1$
        // /git/remote/{remote}/{branch}/file/{path}
        File gitDir = GitUtils.getGitDir(p.removeFirstSegments(2));
        Repository db = new FileRepository(gitDir);
        Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
        URI baseLocation = getURI(request);
        for (String configName : configNames) {
            if (configName.equals(p.segment(0))) {
                for (Entry<String, Ref> refEntry : db.getRefDatabase().getRefs(Constants.R_REMOTES)
                        .entrySet()) {
                    Ref ref = refEntry.getValue();
                    String name = ref.getName();
                    if (!ref.isSymbolic()
                            && name.equals(Constants.R_REMOTES + p.uptoSegment(2).removeTrailingSeparator())) {
                        JSONObject result = new JSONObject();
                        result.put(ProtocolConstants.KEY_NAME, name.substring(Constants.R_REMOTES.length()));
                        result.put(ProtocolConstants.KEY_FULL_NAME, name);
                        result.put(ProtocolConstants.KEY_TYPE, GitConstants.REMOTE_TRACKING_BRANCH_TYPE);
                        result.put(ProtocolConstants.KEY_ID, ref.getObjectId().name());
                        // see bug 342602
                        // result.put(GitConstants.KEY_COMMIT, baseToCommitLocation(baseLocation, name));
                        result.put(ProtocolConstants.KEY_LOCATION,
                                BaseToRemoteConverter.REMOVE_FIRST_4.baseToRemoteLocation(baseLocation,
                                        "" /*short name is {remote}/{branch}*/, //$NON-NLS-1$
                                        Repository.shortenRefName(name)));
                        result.put(GitConstants.KEY_COMMIT, BaseToCommitConverter.getCommitLocation(
                                baseLocation, ref.getObjectId().name(), BaseToCommitConverter.REMOVE_FIRST_4));
                        result.put(GitConstants.KEY_HEAD, BaseToCommitConverter.getCommitLocation(baseLocation,
                                Constants.HEAD, BaseToCommitConverter.REMOVE_FIRST_4));
                        result.put(GitConstants.KEY_CLONE, BaseToCloneConverter.getCloneLocation(baseLocation,
                                BaseToCloneConverter.REMOTE_BRANCH));
                        OrionServlet.writeJSONResponse(request, response, result);
                        return true;
                    }
                }
            }
        }
        JSONObject errorData = new JSONObject();
        errorData.put(GitConstants.KEY_CLONE,
                BaseToCloneConverter.getCloneLocation(baseLocation, BaseToCloneConverter.REMOTE_BRANCH));

        return statusHandler
                .handleRequest(request, response,
                        new ServerStatus(
                                new Status(IStatus.ERROR, ServerConstants.PI_SERVER_CORE,
                                        "No remote branch found: "
                                                + p.uptoSegment(2).removeTrailingSeparator()),
                                HttpServletResponse.SC_NOT_FOUND, errorData));
    }
    return statusHandler.handleRequest(request, response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
                    "Bad request, \"/git/remote/{remote}/{branch}/file/{path}\" expected", null));
}

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

License:Open Source License

@Override
public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, String gitPathInfo)
        throws ServletException {
    try {//  w w  w  . j  av  a  2 s  . com
        Path path = new Path(gitPathInfo);
        if (!path.hasTrailingSeparator()) {
            String msg = NLS.bind("Cannot get status on a file: {0}", gitPathInfo);
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }
        Set<Entry<IPath, File>> set = GitUtils.getGitDirs(path, Traverse.GO_UP).entrySet();
        File gitDir = set.iterator().next().getValue();
        if (gitDir == null)
            return false; // TODO: or an error response code, 405?
        Repository db = new FileRepository(gitDir);
        Git git = new Git(db);
        Status status = git.status().call();

        URI baseLocation = getURI(request);
        JSONObject result = new JSONObject();
        result.put(GitConstants.KEY_CLONE,
                BaseToCloneConverter.getCloneLocation(baseLocation, BaseToCloneConverter.STATUS));

        String relativePath = GitUtils.getRelativePath(path, set.iterator().next().getKey());
        IPath basePath = new Path(relativePath);

        JSONArray children = toJSONArray(status.getAdded(), basePath, baseLocation,
                GitConstants.KEY_DIFF_DEFAULT);
        result.put(GitConstants.KEY_STATUS_ADDED, children);
        // TODO: bug 338913
        // children = toJSONArray(diff.getAssumeUnchanged(), baseLocation, ?);
        // result.put(GitConstants.KEY_STATUS_ASSUME_UNCHANGED, children);
        children = toJSONArray(status.getChanged(), basePath, baseLocation, GitConstants.KEY_DIFF_CACHED);
        result.put(GitConstants.KEY_STATUS_CHANGED, children);
        children = toJSONArray(status.getMissing(), basePath, baseLocation, GitConstants.KEY_DIFF_DEFAULT);
        result.put(GitConstants.KEY_STATUS_MISSING, children);
        children = toJSONArray(status.getModified(), basePath, baseLocation, GitConstants.KEY_DIFF_DEFAULT);
        result.put(GitConstants.KEY_STATUS_MODIFIED, children);
        children = toJSONArray(status.getRemoved(), basePath, baseLocation, GitConstants.KEY_DIFF_CACHED);
        result.put(GitConstants.KEY_STATUS_REMOVED, children);
        children = toJSONArray(status.getUntracked(), basePath, baseLocation, GitConstants.KEY_DIFF_DEFAULT);
        result.put(GitConstants.KEY_STATUS_UNTRACKED, children);
        children = toJSONArray(status.getConflicting(), basePath, baseLocation, GitConstants.KEY_DIFF_DEFAULT);
        result.put(GitConstants.KEY_STATUS_CONFLICTING, children);

        // return repository state
        result.put(GitConstants.KEY_REPOSITORY_STATE, db.getRepositoryState().name());

        result.put(GitConstants.KEY_INDEX, statusToIndexLocation(baseLocation));
        result.put(GitConstants.KEY_COMMIT, statusToCommitLocation(baseLocation, Constants.HEAD));

        OrionServlet.writeJSONResponse(request, response, result);
        return true;

    } catch (Exception e) {
        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error generating status response", e));
    }
}

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

License:Open Source License

@Test
public void testCreateTrackingBranch() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    JSONObject projectTop = createProjectOrLink(workspaceLocation, getMethodName() + "-top", null);
    IPath clonePathTop = new Path("file").append(projectTop.getString(ProtocolConstants.KEY_ID)).makeAbsolute();

    JSONObject projectFolder = createProjectOrLink(workspaceLocation, getMethodName() + "-folder", null);
    IPath clonePathFolder = new Path("file").append(projectFolder.getString(ProtocolConstants.KEY_ID))
            .append("folder").makeAbsolute();

    IPath[] clonePaths = new IPath[] { clonePathTop, clonePathFolder };

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        JSONObject clone = clone(clonePath);
        String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION);
        String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
        String branchesLocation = clone.getString(GitConstants.KEY_BRANCH);

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

        String projectLocation = project.getString(ProtocolConstants.KEY_LOCATION);
        JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
        String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);
        String gitRemoteUri = gitSection.optString(GitConstants.KEY_REMOTE);

        // create local branch tracking origin/master
        final String BRANCH_NAME = "a";
        final String REMOTE_BRANCH = Constants.DEFAULT_REMOTE_NAME + "/" + Constants.MASTER;

        branch(branchesLocation, BRANCH_NAME, REMOTE_BRANCH);

        // modify
        request = getPutFileRequest(projectLocation + "test.txt", "some change");
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // add/* ww w.  jav  a  2 s.  co  m*/
        request = GitAddTest.getPutGitIndexRequest(gitIndexUri + "test.txt");
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

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

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

        // TODO: replace with RESTful API for git pull when available
        // try to pull - up to date status is expected
        Git git = new Git(getRepositoryForContentLocation(cloneContentLocation));
        PullResult pullResults = git.pull().call();
        assertEquals(Constants.DEFAULT_REMOTE_NAME, pullResults.getFetchedFrom());
        assertEquals(MergeStatus.ALREADY_UP_TO_DATE, pullResults.getMergeResult().getMergeStatus());
        assertNull(pullResults.getRebaseResult());

        // checkout branch which was created a moment ago
        response = checkoutBranch(cloneLocation, BRANCH_NAME);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // TODO: replace with RESTful API for git pull when available
        // try to pull again - now fast forward update is expected
        pullResults = git.pull().call();
        assertEquals(Constants.DEFAULT_REMOTE_NAME, pullResults.getFetchedFrom());
        assertEquals(MergeStatus.FAST_FORWARD, pullResults.getMergeResult().getMergeStatus());
        assertNull(pullResults.getRebaseResult());
    }
}

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

License:Open Source License

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

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

    JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection);//from   w  ww  . ja v  a2s .com
    String gitDiffUri = gitSection.getString(GitConstants.KEY_DIFF);
    String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
    String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

    // modify
    WebRequest request = getPutFileRequest(projectId + "/test.txt", "first change");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

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

    // commit1
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit1", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // modify again
    request = getPutFileRequest(projectId + "/test.txt", "second change");
    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());

    // commit2
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit2", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    String initialCommit = Constants.HEAD + "^^";
    String commit1 = Constants.HEAD + "^";
    String commit2 = Constants.HEAD;
    // TODO: don't create URIs out of thin air
    String enc = URLEncoder.encode(initialCommit + ".." + commit1, "UTF-8");
    gitDiffUri = gitDiffUri.replaceAll(GitConstants.KEY_DIFF_DEFAULT, enc);
    request = getGetGitDiffRequest(gitDiffUri + "test.txt");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    StringBuilder sb = new StringBuilder();
    sb.append("diff --git a/test.txt b/test.txt").append("\n");
    sb.append("index 30d74d2..3c26ed4 100644").append("\n");
    sb.append("--- a/test.txt").append("\n");
    sb.append("+++ b/test.txt").append("\n");
    sb.append("@@ -1 +1 @@").append("\n");
    sb.append("-test").append("\n");
    sb.append("\\ No newline at end of file").append("\n");
    sb.append("+first change").append("\n");
    sb.append("\\ No newline at end of file").append("\n");
    String[] parts = parseMultiPartResponse(response);
    assertEquals(sb.toString(), parts[1]);

    String initialCommitId = db.resolve(initialCommit).getName();
    String commit2Id = db.resolve(commit2).getName();
    gitDiffUri = gitSection.getString(GitConstants.KEY_DIFF);
    // TODO: don't create URIs out of thin air
    gitDiffUri = gitDiffUri.replaceAll(GitConstants.KEY_DIFF_DEFAULT, initialCommitId + ".." + commit2Id);
    request = getGetGitDiffRequest(gitDiffUri + "test.txt");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    sb.setLength(0);
    sb.append("diff --git a/test.txt b/test.txt").append("\n");
    sb.append("index 30d74d2..58bcb48 100644").append("\n");
    sb.append("--- a/test.txt").append("\n");
    sb.append("+++ b/test.txt").append("\n");
    sb.append("@@ -1 +1 @@").append("\n");
    sb.append("-test").append("\n");
    sb.append("\\ No newline at end of file").append("\n");
    sb.append("+second change").append("\n");
    sb.append("\\ No newline at end of file").append("\n");
    parts = parseMultiPartResponse(response);
    assertEquals(sb.toString(), parts[1]);
}

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

License:Open Source License

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

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

    JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection);//from  www .j av a2 s .  c o m
    String gitDiffUri = gitSection.getString(GitConstants.KEY_DIFF);
    String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
    String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

    // modify
    WebRequest request = getPutFileRequest(projectId + "/test.txt", "first change");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

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

    // commit1
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit1", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // modify again
    request = getPutFileRequest(projectId + "/test.txt", "second change");
    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());

    // commit2
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit2", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // modify again and leave the change in the working tree only
    request = getPutFileRequest(projectId + "/test.txt", "third change (in tree only)");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    String commit1 = db.resolve(Constants.HEAD + "^").getName();
    String commit2 = db.resolve(Constants.HEAD).getName();

    // TODO: don't create URIs out of thin air
    String enc = URLEncoder.encode(commit1, "UTF-8");
    request = getGetGitDiffRequest(
            new String(gitDiffUri).replaceAll(GitConstants.KEY_DIFF_DEFAULT, enc) + "test.txt");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    StringBuilder sb = new StringBuilder();
    sb.append("diff --git a/test.txt b/test.txt").append("\n");
    sb.append("index 3c26ed4..4cb5d38 100644").append("\n");
    sb.append("--- a/test.txt").append("\n");
    sb.append("+++ b/test.txt").append("\n");
    sb.append("@@ -1 +1 @@").append("\n");
    sb.append("-first change").append("\n");
    sb.append("\\ No newline at end of file").append("\n");
    sb.append("+third change (in tree only)").append("\n");
    sb.append("\\ No newline at end of file").append("\n");
    String[] parts = parseMultiPartResponse(response);
    assertEquals(sb.toString(), parts[1]);

    // TODO: don't create URIs out of thin air
    enc = URLEncoder.encode(commit2, "UTF-8");
    request = getGetGitDiffRequest(
            new String(gitDiffUri).replaceAll(GitConstants.KEY_DIFF_DEFAULT, enc) + "test.txt");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    sb = new StringBuilder();
    sb.append("diff --git a/test.txt b/test.txt").append("\n");
    sb.append("index 58bcb48..4cb5d38 100644").append("\n");
    sb.append("--- a/test.txt").append("\n");
    sb.append("+++ b/test.txt").append("\n");
    sb.append("@@ -1 +1 @@").append("\n");
    sb.append("-second change").append("\n");
    sb.append("\\ No newline at end of file").append("\n");
    sb.append("+third change (in tree only)").append("\n");
    sb.append("\\ No newline at end of file").append("\n");
    parts = parseMultiPartResponse(response);
    assertEquals(sb.toString(), parts[1]);
}

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

License:Open Source License

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

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

    JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection);/* ww w.  j  ava 2 s. co m*/
    String gitDiffUri = gitSection.getString(GitConstants.KEY_DIFF);
    String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
    String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

    // modify
    WebRequest request = getPutFileRequest(projectId + "/test.txt", "change");
    WebResponse 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
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit1", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // TODO: don't create URIs out of thin air
    // replace with REST API for git log when ready, see bug 339104
    String enc = URLEncoder.encode(Constants.HEAD + "^", "UTF-8");
    gitDiffUri = gitDiffUri.replaceAll(GitConstants.KEY_DIFF_DEFAULT, enc);
    request = getPostGitDiffRequest(gitDiffUri + "/test.txt", Constants.HEAD);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    String location = response.getHeaderField(ProtocolConstants.HEADER_LOCATION);
    assertNotNull(location);
    gitDiffUri = gitSection.optString(GitConstants.KEY_DIFF, null);
    enc = URLEncoder.encode(Constants.HEAD + "^.." + Constants.HEAD, "UTF-8");
    // TODO: don't create URIs out of thin air
    String expectedLocation = gitDiffUri.replaceAll(GitConstants.KEY_DIFF_DEFAULT, enc);
    expectedLocation += "test.txt";
    assertEquals(expectedLocation, location);

    request = getGetFilesRequest(location);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    String[] parts = parseMultiPartResponse(response);

    assertDiffUris(expectedLocation, new String[] { "test", "change", "test" }, new JSONObject(parts[0]));

    StringBuilder sb = new StringBuilder();
    sb.append("diff --git a/test.txt b/test.txt").append("\n");
    sb.append("index 30d74d2..8013df8 100644").append("\n");
    sb.append("--- a/test.txt").append("\n");
    sb.append("+++ b/test.txt").append("\n");
    sb.append("@@ -1 +1 @@").append("\n");
    sb.append("-test").append("\n");
    sb.append("\\ No newline at end of file").append("\n");
    sb.append("+change").append("\n");
    sb.append("\\ No newline at end of file").append("\n");
    assertEquals(sb.toString(), parts[1]);
}

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

License:Open Source License

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

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

    JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection);//from   w  w w. j  a  v  a  2s  .c  om
    String gitDiffUri = gitSection.getString(GitConstants.KEY_DIFF);
    String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
    String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

    // modify
    WebRequest request = getPutFileRequest(projectId + "/test.txt", "change");
    WebResponse 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
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit1", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // TODO: replace with REST API for git log when ready, see bug 339104
    String initialCommit = Constants.HEAD + "^";
    String commit = Constants.HEAD;
    // TODO: don't create URIs out of thin air
    String enc = URLEncoder.encode(initialCommit + ".." + commit, "UTF-8");
    String location = gitDiffUri.replaceAll(GitConstants.KEY_DIFF_DEFAULT, enc);
    location += "test.txt";

    request = getGetFilesRequest(location + "?parts=uris,diff");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    String[] parts = parseMultiPartResponse(response);

    assertDiffUris(location, new String[] { "test", "change", "test" }, new JSONObject(parts[0]));

    StringBuilder sb = new StringBuilder();
    sb.append("diff --git a/test.txt b/test.txt").append("\n");
    sb.append("index 30d74d2..8013df8 100644").append("\n");
    sb.append("--- a/test.txt").append("\n");
    sb.append("+++ b/test.txt").append("\n");
    sb.append("@@ -1 +1 @@").append("\n");
    sb.append("-test").append("\n");
    sb.append("\\ No newline at end of file").append("\n");
    sb.append("+change").append("\n");
    sb.append("\\ No newline at end of file").append("\n");
    assertEquals(sb.toString(), parts[1]);

    request = getGetFilesRequest(location + "?parts=diff,uris");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    parseMultiPartResponse(response);

    assertDiffUris(location, new String[] { "test", "change", "test" }, new JSONObject(parts[0]));
    assertEquals(sb.toString(), parts[1]);

    request = getGetFilesRequest(location + "?parts=diff");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    assertEquals(sb.toString(), response.getText());

    request = getGetFilesRequest(location + "?parts=uris");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    assertDiffUris(location, new String[] { "test", "change", "test" }, new JSONObject(response.getText()));
}

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  .  jav a2 s.  c o m*/
    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//  www . ja  va2  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);
}