Example usage for org.eclipse.jgit.lib StoredConfig save

List of usage examples for org.eclipse.jgit.lib StoredConfig save

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib StoredConfig save.

Prototype

public abstract void save() throws IOException;

Source Link

Document

Save the configuration to the persistent store.

Usage

From source file:org.eclipse.mylyn.internal.github.core.pr.PullRequestUtils.java

License:Open Source License

/**
 * Add remote for the head of a pull request if it doesn't exist
 *
 * @param repo/*from   w  w w  . ja  v  a 2 s.co  m*/
 * @param request
 * @return remote configuration
 * @throws IOException
 * @throws URISyntaxException
 */
public static RemoteConfig addRemote(Repository repo, PullRequest request)
        throws IOException, URISyntaxException {
    RemoteConfig remote = getRemote(repo, request);
    if (remote != null)
        return remote;

    StoredConfig config = repo.getConfig();
    org.eclipse.egit.github.core.Repository head = request.getHead().getRepo();
    remote = new RemoteConfig(config, head.getOwner().getLogin());
    if (head.isPrivate())
        remote.addURI(new URIish(UrlUtils.createRemoteSshUrl(head)));
    else
        remote.addURI(new URIish(UrlUtils.createRemoteReadOnlyUrl(head)));

    remote.addFetchRefSpec(new RefSpec(HEAD_SOURCE + ":" + getDesintationRef(remote))); //$NON-NLS-1$
    remote.update(config);
    config.save();
    return remote;
}

From source file:org.eclipse.oomph.setup.git.impl.GitCloneTaskImpl.java

License:Open Source License

private static void configureRepository(SetupTaskContext context, Repository repository, String checkoutBranch,
        String remoteName, String remoteURI, String pushURI, List<? extends ConfigSection> configSections)
        throws Exception, IOException {
    StoredConfig config = repository.getConfig();

    Map<String, Map<String, Map<String, List<String>>>> properties = new LinkedHashMap<String, Map<String, Map<String, List<String>>>>();

    for (ConfigSection section : configSections) {
        String sectionName = section.getName();
        if (!StringUtil.isEmpty(sectionName)) {
            for (ConfigProperty property : section.getProperties()) {
                handleProperty(properties, sectionName, null, property);
            }/*from  ww w  .  j  a va  2 s. co  m*/

            for (ConfigSubsection subsection : section.getSubsections()) {
                String subsectionName = subsection.getName();
                if (subsectionName != null) {
                    for (ConfigProperty property : subsection.getProperties()) {
                        handleProperty(properties, sectionName, subsectionName, property);
                    }
                }
            }
        }
    }

    boolean changed = false;
    boolean hasAutoCRLFProperty = false;

    for (Map.Entry<String, Map<String, Map<String, List<String>>>> sectionEntry : properties.entrySet()) {
        String sectionName = sectionEntry.getKey();
        for (Map.Entry<String, Map<String, List<String>>> subsectionEntry : sectionEntry.getValue()
                .entrySet()) {
            String subsectionName = subsectionEntry.getKey();
            for (Map.Entry<String, List<String>> propertyEntry : subsectionEntry.getValue().entrySet()) {
                String key = propertyEntry.getKey();
                if ("core".equals(sectionName) && subsectionName == null && "autocrlf".equals(key)) {
                    hasAutoCRLFProperty = true;
                }

                List<String> value = propertyEntry.getValue();
                String[] oldValue = config.getStringList(sectionName, subsectionName, key);
                if (value.isEmpty()) {
                    config.unset(sectionName, subsectionName, key);
                    changed |= oldValue.length != 0;
                } else {
                    config.setStringList(sectionName, subsectionName, key, value);
                    changed |= !Arrays.asList(oldValue).equals(value);
                }
            }
        }
    }

    if (!hasAutoCRLFProperty) {
        changed |= configureLineEndingConversion(context, config);
    }

    Set<String> gerritPatterns = new HashSet<String>();
    for (Object key : context.keySet()) {
        if (key instanceof String) {
            if (key.toString().endsWith(".gerrit.uri.pattern")) {
                Object value = context.get(key);
                if (value instanceof String) {
                    gerritPatterns.add(value.toString());
                }
            }
        }
    }

    if (!gerritPatterns.isEmpty()) {
        URI uri = URI.createURI(remoteURI);
        String uriString = uri.toString();
        for (String gerritPattern : gerritPatterns) {
            if (uriString.matches(gerritPattern)) {
                changed |= addGerritPullRefSpec(context, config, remoteName);
                changed |= addGerritPushRefSpec(context, config, checkoutBranch, remoteName);
                break;
            }
        }
    }

    changed |= addPushURI(context, config, remoteName, pushURI);
    if (changed) {
        config.save();
    }
}

From source file:org.eclipse.oomph.setup.git.impl.GitCloneTaskImpl.java

License:Open Source License

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

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

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

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

License:Open Source License

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

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

License:Open Source License

private boolean handleDelete(HttpServletRequest request, HttpServletResponse response, String path)
        throws CoreException, IOException, URISyntaxException, JSONException, ServletException {
    Path p = new Path(path);
    if (p.segment(1).equals("file")) { //$NON-NLS-1$
        // expected path: /gitapi/remote/{remote}/file/{path}
        String remoteName = p.segment(0);

        File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1));
        Repository db = new FileRepository(gitDir);
        StoredConfig config = db.getConfig();
        config.unsetSection(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName);
        config.save();
        //TODO: handle result
        return true;
    }/*from ww w  . j a  v a  2  s.  c o  m*/
    return false;
}

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

License:Open Source License

private boolean addRemote(HttpServletRequest request, HttpServletResponse response, String path)
        throws IOException, JSONException, ServletException, CoreException, URISyntaxException {
    // expected path: /git/remote/file/{path}
    Path p = new Path(path);
    JSONObject toPut = OrionServlet.readJSONRequest(request);
    String remoteName = toPut.optString(GitConstants.KEY_REMOTE_NAME, null);
    // remoteName is required
    if (remoteName == null || remoteName.isEmpty()) {
        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "Remote name must be provided", null));
    }//from w w w .j  av  a2 s.  co  m
    String remoteURI = toPut.optString(GitConstants.KEY_REMOTE_URI, null);
    // remoteURI is required
    if (remoteURI == null || remoteURI.isEmpty()) {
        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "Remote URI must be provided", null));
    }
    String fetchRefSpec = toPut.optString(GitConstants.KEY_REMOTE_FETCH_REF, null);
    String remotePushURI = toPut.optString(GitConstants.KEY_REMOTE_PUSH_URI, null);
    String pushRefSpec = toPut.optString(GitConstants.KEY_REMOTE_PUSH_REF, null);

    File gitDir = GitUtils.getGitDir(p);
    Repository db = new FileRepository(gitDir);
    StoredConfig config = db.getConfig();

    RemoteConfig rc = new RemoteConfig(config, remoteName);
    rc.addURI(new URIish(remoteURI));
    // FetchRefSpec is required, but default version can be generated
    // if it isn't provided
    if (fetchRefSpec == null || fetchRefSpec.isEmpty()) {
        fetchRefSpec = String.format("+refs/heads/*:refs/remotes/%s/*", remoteName); //$NON-NLS-1$
    }
    rc.addFetchRefSpec(new RefSpec(fetchRefSpec));
    // pushURI is optional
    if (remotePushURI != null && !remotePushURI.isEmpty())
        rc.addPushURI(new URIish(remotePushURI));
    // PushRefSpec is optional
    if (pushRefSpec != null && !pushRefSpec.isEmpty())
        rc.addPushRefSpec(new RefSpec(pushRefSpec));

    rc.update(config);
    config.save();

    URI baseLocation = getURI(request);
    JSONObject result = toJSON(remoteName, baseLocation);
    OrionServlet.writeJSONResponse(request, response, result);
    response.setHeader(ProtocolConstants.HEADER_LOCATION, result.getString(ProtocolConstants.KEY_LOCATION));
    response.setStatus(HttpServletResponse.SC_CREATED);
    return true;
}

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

License:Open Source License

public static void removeSubmodule(Repository db, Repository parentRepo, String pathToSubmodule)
        throws Exception {
    pathToSubmodule = pathToSubmodule.replace("\\", "/");
    StoredConfig gitSubmodulesConfig = getGitSubmodulesConfig(parentRepo);
    gitSubmodulesConfig.unsetSection(CONFIG_SUBMODULE_SECTION, pathToSubmodule);
    gitSubmodulesConfig.save();
    StoredConfig repositoryConfig = parentRepo.getConfig();
    repositoryConfig.unsetSection(CONFIG_SUBMODULE_SECTION, pathToSubmodule);
    repositoryConfig.save();//w  w w  . ja  v a2  s. c om
    Git git = Git.wrap(parentRepo);
    git.add().addFilepattern(DOT_GIT_MODULES).call();
    RmCommand rm = git.rm().addFilepattern(pathToSubmodule);
    if (gitSubmodulesConfig.getSections().size() == 0) {
        rm.addFilepattern(DOT_GIT_MODULES);
    }
    rm.call();
    FileUtils.delete(db.getWorkTree(), FileUtils.RECURSIVE);
    FileUtils.delete(db.getDirectory(), FileUtils.RECURSIVE);
}

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 ww  .j  a  v a 2 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.orion.server.tests.servlets.git.GitSubmoduleTest.java

License:Open Source License

@Test
public void testSyncSubmodule()
        throws IOException, SAXException, JSONException, CoreException, ConfigInvalidException {
    createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
    String workspaceId = getWorkspaceId(workspaceLocation);

    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName().concat("Project1"), null);
    JSONObject clone = clone(workspaceId, project);
    String contentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
    String submoduleLocation = clone.getString(GitConstants.KEY_SUBMODULE);
    String location = clone.getString(ProtocolConstants.KEY_LOCATION);

    Repository repository = getRepositoryForContentLocation(contentLocation);
    File file = new File(repository.getWorkTree(), DOT_GIT_MODULES);
    assertFalse(file.exists());/*from w  w w  .jav  a  2 s . com*/

    URIish uri = new URIish(gitDir.toURI().toURL());
    WebRequest request = postSubmoduleRequest(submoduleLocation, "test", uri.toString(), location);
    WebResponse response = webConversation.getResponse(request);

    file = new File(repository.getWorkTree(), DOT_GIT_MODULES);
    assertTrue(file.exists());

    assertNotNull(repository);

    StoredConfig repoConfig = repository.getConfig();
    String originalUrl = repoConfig.getString("submodule", "test", "url");
    repoConfig.setString("submodule", "test", "url", "value");
    repoConfig.save();
    assertEquals(repoConfig.getString("submodule", "test", "url"), "value");

    WebRequest reqSync = putSubmoduleRequest(submoduleLocation, "sync");
    WebResponse resSync = webConversation.getResponse(reqSync);

    repoConfig = repository.getConfig();
    assertEquals(repoConfig.getString("submodule", "test", "url"), originalUrl);

}

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

License:Open Source License

private void configureGit() throws IOException {
    Git git = Git.open(gitFile);// w w  w . ja v  a 2  s  .co m
    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();
}