Example usage for org.eclipse.jgit.lib Repository getConfig

List of usage examples for org.eclipse.jgit.lib Repository getConfig

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository getConfig.

Prototype

@NonNull
public abstract StoredConfig getConfig();

Source Link

Document

Get the configuration of this repository.

Usage

From source file:org.eclipse.oomph.gitbash.decorators.BranchDecorator.java

License:Open Source License

private String getDecoration(org.eclipse.egit.ui.internal.repository.tree.RefNode node) {
    String branchName = Repository.shortenRefName(node.getObject().getName());
    Repository repository = node.getRepository();
    StoredConfig config = repository.getConfig();

    String branch = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
            ConfigConstants.CONFIG_KEY_MERGE);

    if (branch != null) {
        String remote = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                ConfigConstants.CONFIG_KEY_REMOTE);

        boolean rebaseFlag = config.getBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                ConfigConstants.CONFIG_KEY_REBASE, false);

        if (branch.startsWith(DEFAULT_PATH)) {
            branch = branch.substring(DEFAULT_PATH.length());
        }/*  w  ww .j  a  va  2s.  c om*/

        String prefix = ".".equals(remote) ? "" : remote + "/";
        String result = (rebaseFlag ? "REBASE" : "MERGE") + ": " + prefix + branch;

        try {
            BranchTrackingStatus trackingStatus = BranchTrackingStatus.of(repository, branchName);
            if (trackingStatus != null
                    && (trackingStatus.getAheadCount() != 0 || trackingStatus.getBehindCount() != 0)) {
                result += " " + formatBranchTrackingStatus(trackingStatus);
            }
        } catch (Throwable t) {
            //$FALL-THROUGH$
        }

        return result;
    }

    return null;
}

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);
            }/*www.ja 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.orion.server.git.BaseToRemoteConverter.java

License:Open Source License

public static URI getRemoteBranchLocation(URI base, String branchName, Repository db,
        BaseToRemoteConverter converter) throws IOException, URISyntaxException {
    Config repoConfig = db.getConfig();
    String remote = repoConfig.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
            ConfigConstants.CONFIG_KEY_REMOTE);
    if (remote == null)
        // fall back to default remote
        remote = Constants.DEFAULT_REMOTE_NAME;
    String fetch = repoConfig.getString(ConfigConstants.CONFIG_REMOTE_SECTION, remote, "fetch"); //$NON-NLS-1$
    if (fetch != null) {
        // expecting something like: +refs/heads/*:refs/remotes/origin/*
        String[] split = fetch.split(":"); //$NON-NLS-1$
        if (split[0].endsWith("*") /*src*/ && split[1].endsWith("*") /*dst*/) { //$NON-NLS-1$ //$NON-NLS-2$
            return converter.baseToRemoteLocation(base, remote, branchName);
        }/*from   w ww  .jav a2 s  . co m*/
    }
    return null;
}

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

License:Open Source License

@Override
protected IStatus performJob() {

    try {/*  w w w  . j ava  2s. com*/
        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.GitPullRequestHandlerV1.java

License:Open Source License

protected boolean handlePost(RequestInfo requestInfo) throws ServletException {
    HttpServletRequest request = requestInfo.request;
    HttpServletResponse response = requestInfo.response;
    Repository db = requestInfo.db;
    JSONObject credentials = requestInfo.getJSONRequest();
    try {//  w  w w .j av a2  s.c o m

        String username = credentials.optString(GitConstants.KEY_USERNAME, "");
        String password = credentials.optString(GitConstants.KEY_PASSWORD, "");
        String url = credentials.optString(GitConstants.KEY_URL,
                db.getConfig().getString("remote", "origin", "url"));
        if (url != null) {
            Object cookie = request.getAttribute(GitConstants.KEY_SSO_TOKEN);
            String[] parsedUrl = parseSshGitUrl(url);
            String apiHost = getAPIHost(parsedUrl[0]);
            String user = parsedUrl[1];
            String project = parsedUrl[2];
            URI cloneLocation = BaseToCloneConverter.getCloneLocation(getURI(request),
                    BaseToCloneConverter.BRANCH_LIST);
            ListPullRequestsJob job = new ListPullRequestsJob(TaskJobHandler.getUserId(request), url,
                    cloneLocation, apiHost, user, project, username, password, cookie);
            return TaskJobHandler.handleTaskJob(request, response, job, statusHandler,
                    JsonURIUnqualificationStrategy.ALL_NO_GIT);

        }
        OrionServlet.writeJSONResponse(request, response, new JSONArray(),
                JsonURIUnqualificationStrategy.ALL_NO_GIT);
        return true;

    } catch (Exception ex) {
        String msg = "An error occured for pull request list command.";
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex));
    }
}

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  www . jav a  2s  .co  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.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();//from www . ja v  a2 s.co m
        //TODO: handle result
        return true;
    }
    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 a  v a2 s . c o  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();/*from   w  w w  . j a v a 2 s.c  om*/
    StoredConfig repositoryConfig = parentRepo.getConfig();
    repositoryConfig.unsetSection(CONFIG_SUBMODULE_SECTION, pathToSubmodule);
    repositoryConfig.save();
    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.GitRemoteTest.java

License:Open Source License

@Test
public void testRemoteProperties()
        throws IOException, SAXException, JSONException, CoreException, URISyntaxException {
    URI workspaceLocation = createWorkspace(getMethodName());

    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath path = new Path("file").append(project.getString(ProtocolConstants.KEY_ID)).makeAbsolute();
    JSONObject clone = clone(path);/*w ww.ja  v a2s .  c o m*/
    String remotesLocation = clone.getString(GitConstants.KEY_REMOTE);
    String contentLocation = project.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

    // create remote
    final String remoteName = "remote1";
    final String remoteUri = "remote1.com";
    final String fetchRefSpec = "+refs/heads/*:refs/remotes/%s/*";
    final String pushUri = "remote2.com";
    final String pushRefSpec = "refs/heads/*:refs/heads/*";
    WebResponse response = addRemote(remotesLocation, remoteName, remoteUri, fetchRefSpec, pushUri,
            pushRefSpec);

    Repository db = new FileRepository(GitUtils.getGitDir(path));
    StoredConfig config = db.getConfig();
    RemoteConfig rc = new RemoteConfig(config, remoteName);

    assertNotNull(rc);
    // main uri
    assertEquals(1, rc.getURIs().size());
    assertEquals(new URIish(remoteUri), rc.getURIs().get(0));
    // fetchRefSpec
    assertEquals(1, rc.getFetchRefSpecs().size());
    assertEquals(new RefSpec(fetchRefSpec), rc.getFetchRefSpecs().get(0));
    // pushUri
    assertEquals(1, rc.getPushURIs().size());
    assertEquals(new URIish(pushUri), rc.getPushURIs().get(0));
    // pushRefSpec
    assertEquals(1, rc.getPushRefSpecs().size());
    assertEquals(new RefSpec(pushRefSpec), rc.getPushRefSpecs().get(0));
}