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

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

Introduction

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

Prototype

public String[] getStringList(final String section, String subsection, final String name) 

Source Link

Document

Get a list of string values

If this instance was created with a base, the base's values are returned first (if any).

Usage

From source file:com.gitblit.AddIndexedBranch.java

License:Apache License

public static void main(String... args) {
    Params params = new Params();
    CmdLineParser parser = new CmdLineParser(params);
    try {// w  w  w .ja  va  2s.c o m
        parser.parseArgument(args);
    } catch (CmdLineException t) {
        System.err.println(t.getMessage());
        parser.printUsage(System.out);
        return;
    }

    // create a lowercase set of excluded repositories
    Set<String> exclusions = new TreeSet<String>();
    for (String exclude : params.exclusions) {
        exclusions.add(exclude.toLowerCase());
    }

    // determine available repositories
    File folder = new File(params.folder);
    List<String> repoList = JGitUtils.getRepositoryList(folder, false, true, -1, null);

    int modCount = 0;
    int skipCount = 0;
    for (String repo : repoList) {
        boolean skip = false;
        for (String exclusion : exclusions) {
            if (StringUtils.fuzzyMatch(repo, exclusion)) {
                skip = true;
                break;
            }
        }

        if (skip) {
            System.out.println("skipping " + repo);
            skipCount++;
            continue;
        }

        try {
            // load repository config
            File gitDir = FileKey.resolve(new File(folder, repo), FS.DETECTED);
            Repository repository = new FileRepositoryBuilder().setGitDir(gitDir).build();
            StoredConfig config = repository.getConfig();
            config.load();

            Set<String> indexedBranches = new LinkedHashSet<String>();

            // add all local branches to index
            if (params.addAllLocalBranches) {
                List<RefModel> list = JGitUtils.getLocalBranches(repository, true, -1);
                for (RefModel refModel : list) {
                    System.out.println(MessageFormat.format("adding [gitblit] indexBranch={0} for {1}",
                            refModel.getName(), repo));
                    indexedBranches.add(refModel.getName());
                }
            } else {
                // add only one branch to index ('default' if not specified)
                System.out.println(
                        MessageFormat.format("adding [gitblit] indexBranch={0} for {1}", params.branch, repo));
                indexedBranches.add(params.branch);
            }

            String[] branches = config.getStringList("gitblit", null, "indexBranch");
            if (!ArrayUtils.isEmpty(branches)) {
                for (String branch : branches) {
                    indexedBranches.add(branch);
                }
            }
            config.setStringList("gitblit", null, "indexBranch", new ArrayList<String>(indexedBranches));
            config.save();
            modCount++;
        } catch (Exception e) {
            System.err.println(repo);
            e.printStackTrace();
        }
    }

    System.out.println(
            MessageFormat.format("updated {0} repository configurations, skipped {1}", modCount, skipCount));
}

From source file:com.gitblit.client.GitblitManager.java

License:Apache License

private void loadRegistrations() {
    try {//from w  w w  .  j  a va  2 s .  co m
        StoredConfig config = getConfig();
        Set<String> servers = config.getSubsections(SERVER);
        for (String server : servers) {
            Date lastLogin = new Date(0);
            String date = config.getString(SERVER, server, "lastLogin");
            if (!StringUtils.isEmpty(date)) {
                lastLogin = dateFormat.parse(date);
            }
            String url = config.getString(SERVER, server, "url");
            String account = config.getString(SERVER, server, "account");
            char[] password;
            String pw = config.getString(SERVER, server, "password");
            if (StringUtils.isEmpty(pw)) {
                password = new char[0];
            } else {
                password = new String(Base64.decode(pw)).toCharArray();
            }
            GitblitRegistration reg = new GitblitRegistration(server, url, account, password) {
                private static final long serialVersionUID = 1L;

                @Override
                protected void cacheFeeds() {
                    writeFeedCache(this);
                }
            };
            String[] feeds = config.getStringList(SERVER, server, FEED);
            if (feeds != null) {
                // deserialize the field definitions
                for (String definition : feeds) {
                    FeedModel feed = new FeedModel(definition);
                    reg.feeds.add(feed);
                }
            }
            reg.lastLogin = lastLogin;
            loadFeedCache(reg);
            registrations.put(reg.name, reg);
        }
    } catch (Throwable t) {
        Utils.showException(GitblitManager.this, t);
    }
}

From source file:com.gitblit.ConfigUserService.java

License:Apache License

/**
 * Reads the realm file and rebuilds the in-memory lookup tables.
 *//*www  .ja  v a2  s . c  o m*/
protected synchronized void read() {
    if (realmFile.exists() && (forceReload || (realmFile.lastModified() != lastModified))) {
        forceReload = false;
        lastModified = realmFile.lastModified();
        users.clear();
        cookies.clear();
        teams.clear();

        try {
            StoredConfig config = new FileBasedConfig(realmFile, FS.detect());
            config.load();
            Set<String> usernames = config.getSubsections(USER);
            for (String username : usernames) {
                UserModel user = new UserModel(username.toLowerCase());
                user.password = config.getString(USER, username, PASSWORD);
                user.displayName = config.getString(USER, username, DISPLAYNAME);
                user.emailAddress = config.getString(USER, username, EMAILADDRESS);
                user.accountType = AccountType.fromString(config.getString(USER, username, ACCOUNTTYPE));
                user.disabled = config.getBoolean(USER, username, DISABLED, false);
                user.organizationalUnit = config.getString(USER, username, ORGANIZATIONALUNIT);
                user.organization = config.getString(USER, username, ORGANIZATION);
                user.locality = config.getString(USER, username, LOCALITY);
                user.stateProvince = config.getString(USER, username, STATEPROVINCE);
                user.countryCode = config.getString(USER, username, COUNTRYCODE);
                user.cookie = config.getString(USER, username, COOKIE);
                if (StringUtils.isEmpty(user.cookie) && !StringUtils.isEmpty(user.password)) {
                    user.cookie = user.createCookie();
                }

                // preferences
                user.getPreferences().setLocale(config.getString(USER, username, LOCALE));
                user.getPreferences().setEmailMeOnMyTicketChanges(
                        config.getBoolean(USER, username, EMAILONMYTICKETCHANGES, true));
                user.getPreferences()
                        .setTransport(Transport.fromString(config.getString(USER, username, TRANSPORT)));

                // user roles
                Set<String> roles = new HashSet<String>(
                        Arrays.asList(config.getStringList(USER, username, ROLE)));
                user.canAdmin = roles.contains(Role.ADMIN.getRole());
                user.canFork = roles.contains(Role.FORK.getRole());
                user.canCreate = roles.contains(Role.CREATE.getRole());
                user.excludeFromFederation = roles.contains(Role.NOT_FEDERATED.getRole());

                // repository memberships
                if (!user.canAdmin) {
                    // non-admin, read permissions
                    Set<String> repositories = new HashSet<String>(
                            Arrays.asList(config.getStringList(USER, username, REPOSITORY)));
                    for (String repository : repositories) {
                        user.addRepositoryPermission(repository);
                    }
                }

                // starred repositories
                Set<String> starred = new HashSet<String>(
                        Arrays.asList(config.getStringList(USER, username, STARRED)));
                for (String repository : starred) {
                    UserRepositoryPreferences prefs = user.getPreferences()
                            .getRepositoryPreferences(repository);
                    prefs.starred = true;
                }

                // update cache
                users.put(user.username, user);
                if (!StringUtils.isEmpty(user.cookie)) {
                    cookies.put(user.cookie, user);
                }
            }

            // load the teams
            Set<String> teamnames = config.getSubsections(TEAM);
            for (String teamname : teamnames) {
                TeamModel team = new TeamModel(teamname);
                Set<String> roles = new HashSet<String>(
                        Arrays.asList(config.getStringList(TEAM, teamname, ROLE)));
                team.canAdmin = roles.contains(Role.ADMIN.getRole());
                team.canFork = roles.contains(Role.FORK.getRole());
                team.canCreate = roles.contains(Role.CREATE.getRole());
                team.accountType = AccountType.fromString(config.getString(TEAM, teamname, ACCOUNTTYPE));

                if (!team.canAdmin) {
                    // non-admin team, read permissions
                    team.addRepositoryPermissions(
                            Arrays.asList(config.getStringList(TEAM, teamname, REPOSITORY)));
                }
                team.addUsers(Arrays.asList(config.getStringList(TEAM, teamname, USER)));
                team.addMailingLists(Arrays.asList(config.getStringList(TEAM, teamname, MAILINGLIST)));
                team.preReceiveScripts.addAll(Arrays.asList(config.getStringList(TEAM, teamname, PRERECEIVE)));
                team.postReceiveScripts
                        .addAll(Arrays.asList(config.getStringList(TEAM, teamname, POSTRECEIVE)));

                teams.put(team.name.toLowerCase(), team);

                // set the teams on the users
                for (String user : team.users) {
                    UserModel model = users.get(user);
                    if (model != null) {
                        model.teams.add(team);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(MessageFormat.format("Failed to read {0}", realmFile), e);
        }
    }
}

From source file:com.gitblit.GitBlit.java

License:Apache License

/**
 * Create a repository model from the configuration and repository data.
 * /*from  www. j a v a 2 s  . co m*/
 * @param repositoryName
 * @return a repositoryModel or null if the repository does not exist
 */
private RepositoryModel loadRepositoryModel(String repositoryName) {
    Repository r = getRepository(repositoryName);
    if (r == null) {
        return null;
    }
    RepositoryModel model = new RepositoryModel();
    model.name = repositoryName;
    model.hasCommits = JGitUtils.hasCommits(r);
    model.lastChange = JGitUtils.getLastChange(r);
    model.isBare = r.isBare();
    if (repositoryName.indexOf('/') == -1) {
        model.projectPath = "";
    } else {
        model.projectPath = repositoryName.substring(0, repositoryName.indexOf('/'));
    }

    StoredConfig config = r.getConfig();
    boolean hasOrigin = !StringUtils.isEmpty(config.getString("remote", "origin", "url"));

    if (config != null) {
        model.description = getConfig(config, "description", "");
        model.owner = getConfig(config, "owner", "");
        model.useTickets = getConfig(config, "useTickets", false);
        model.useDocs = getConfig(config, "useDocs", false);
        model.allowForks = getConfig(config, "allowForks", true);
        model.accessRestriction = AccessRestrictionType.fromName(getConfig(config, "accessRestriction",
                settings.getString(Keys.git.defaultAccessRestriction, null)));
        model.authorizationControl = AuthorizationControl.fromName(getConfig(config, "authorizationControl",
                settings.getString(Keys.git.defaultAuthorizationControl, null)));
        model.showRemoteBranches = getConfig(config, "showRemoteBranches", hasOrigin);
        model.isFrozen = getConfig(config, "isFrozen", false);
        model.showReadme = getConfig(config, "showReadme", false);
        model.skipSizeCalculation = getConfig(config, "skipSizeCalculation", false);
        model.skipSummaryMetrics = getConfig(config, "skipSummaryMetrics", false);
        model.federationStrategy = FederationStrategy.fromName(getConfig(config, "federationStrategy", null));
        model.federationSets = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "federationSets")));
        model.isFederated = getConfig(config, "isFederated", false);
        model.origin = config.getString("remote", "origin", "url");
        model.preReceiveScripts = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "preReceiveScript")));
        model.postReceiveScripts = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "postReceiveScript")));
        model.mailingLists = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "mailingList")));
        model.indexedBranches = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "indexBranch")));

        // Custom defined properties
        model.customFields = new LinkedHashMap<String, String>();
        for (String aProperty : config.getNames(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS)) {
            model.customFields.put(aProperty,
                    config.getString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, aProperty));
        }
    }
    model.HEAD = JGitUtils.getHEADRef(r);
    model.availableRefs = JGitUtils.getAvailableHeadTargets(r);
    r.close();

    if (model.origin != null && model.origin.startsWith("file://")) {
        // repository was cloned locally... perhaps as a fork
        try {
            File folder = new File(new URI(model.origin));
            String originRepo = com.gitblit.utils.FileUtils.getRelativePath(getRepositoriesFolder(), folder);
            if (!StringUtils.isEmpty(originRepo)) {
                // ensure origin still exists
                File repoFolder = new File(getRepositoriesFolder(), originRepo);
                if (repoFolder.exists()) {
                    model.originRepository = originRepo;
                }
            }
        } catch (URISyntaxException e) {
            logger.error("Failed to determine fork for " + model, e);
        }
    }
    return model;
}

From source file:com.gitblit.manager.RepositoryManager.java

License:Apache License

/**
 * Create a repository model from the configuration and repository data.
 *
 * @param repositoryName// w  w  w .ja  va2  s.com
 * @return a repositoryModel or null if the repository does not exist
 */
private RepositoryModel loadRepositoryModel(String repositoryName) {
    Repository r = getRepository(repositoryName);
    if (r == null) {
        return null;
    }
    RepositoryModel model = new RepositoryModel();
    model.isBare = r.isBare();
    File basePath = getRepositoriesFolder();
    if (model.isBare) {
        model.name = com.gitblit.utils.FileUtils.getRelativePath(basePath, r.getDirectory());
    } else {
        model.name = com.gitblit.utils.FileUtils.getRelativePath(basePath, r.getDirectory().getParentFile());
    }
    if (StringUtils.isEmpty(model.name)) {
        // Repository is NOT located relative to the base folder because it
        // is symlinked.  Use the provided repository name.
        model.name = repositoryName;
    }
    model.projectPath = StringUtils.getFirstPathElement(repositoryName);

    StoredConfig config = r.getConfig();
    boolean hasOrigin = false;

    if (config != null) {
        // Initialize description from description file
        hasOrigin = !StringUtils.isEmpty(config.getString("remote", "origin", "url"));
        if (getConfig(config, "description", null) == null) {
            File descFile = new File(r.getDirectory(), "description");
            if (descFile.exists()) {
                String desc = com.gitblit.utils.FileUtils.readContent(descFile,
                        System.getProperty("line.separator"));
                if (!desc.toLowerCase().startsWith("unnamed repository")) {
                    config.setString(Constants.CONFIG_GITBLIT, null, "description", desc);
                }
            }
        }
        model.description = getConfig(config, "description", "");
        model.originRepository = getConfig(config, "originRepository", null);
        model.addOwners(ArrayUtils.fromString(getConfig(config, "owner", "")));
        model.acceptNewPatchsets = getConfig(config, "acceptNewPatchsets", true);
        model.acceptNewTickets = getConfig(config, "acceptNewTickets", true);
        model.requireApproval = getConfig(config, "requireApproval",
                settings.getBoolean(Keys.tickets.requireApproval, false));
        model.mergeTo = getConfig(config, "mergeTo", null);
        model.mergeType = MergeType
                .fromName(getConfig(config, "mergeType", settings.getString(Keys.tickets.mergeType, null)));
        model.useIncrementalPushTags = getConfig(config, "useIncrementalPushTags", false);
        model.incrementalPushTagPrefix = getConfig(config, "incrementalPushTagPrefix", null);
        model.allowForks = getConfig(config, "allowForks", true);
        model.accessRestriction = AccessRestrictionType.fromName(getConfig(config, "accessRestriction",
                settings.getString(Keys.git.defaultAccessRestriction, "PUSH")));
        model.authorizationControl = AuthorizationControl.fromName(getConfig(config, "authorizationControl",
                settings.getString(Keys.git.defaultAuthorizationControl, null)));
        model.verifyCommitter = getConfig(config, "verifyCommitter", false);
        model.showRemoteBranches = getConfig(config, "showRemoteBranches", hasOrigin);
        model.isFrozen = getConfig(config, "isFrozen", false);
        model.skipSizeCalculation = getConfig(config, "skipSizeCalculation", false);
        model.skipSummaryMetrics = getConfig(config, "skipSummaryMetrics", false);
        model.commitMessageRenderer = CommitMessageRenderer.fromName(getConfig(config, "commitMessageRenderer",
                settings.getString(Keys.web.commitMessageRenderer, null)));
        model.federationStrategy = FederationStrategy.fromName(getConfig(config, "federationStrategy", null));
        model.federationSets = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "federationSets")));
        model.isFederated = getConfig(config, "isFederated", false);
        model.gcThreshold = getConfig(config, "gcThreshold",
                settings.getString(Keys.git.defaultGarbageCollectionThreshold, "500KB"));
        model.gcPeriod = getConfig(config, "gcPeriod",
                settings.getInteger(Keys.git.defaultGarbageCollectionPeriod, 7));
        try {
            model.lastGC = new SimpleDateFormat(Constants.ISO8601)
                    .parse(getConfig(config, "lastGC", "1970-01-01'T'00:00:00Z"));
        } catch (Exception e) {
            model.lastGC = new Date(0);
        }
        model.maxActivityCommits = getConfig(config, "maxActivityCommits",
                settings.getInteger(Keys.web.maxActivityCommits, 0));
        model.origin = config.getString("remote", "origin", "url");
        if (model.origin != null) {
            model.origin = model.origin.replace('\\', '/');
            model.isMirror = config.getBoolean("remote", "origin", "mirror", false);
        }
        model.preReceiveScripts = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "preReceiveScript")));
        model.postReceiveScripts = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "postReceiveScript")));
        model.mailingLists = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "mailingList")));
        model.indexedBranches = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "indexBranch")));
        model.metricAuthorExclusions = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "metricAuthorExclusions")));

        // Custom defined properties
        model.customFields = new LinkedHashMap<String, String>();
        for (String aProperty : config.getNames(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS)) {
            model.customFields.put(aProperty,
                    config.getString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, aProperty));
        }
    }
    model.HEAD = JGitUtils.getHEADRef(r);
    if (StringUtils.isEmpty(model.mergeTo)) {
        model.mergeTo = model.HEAD;
    }
    model.availableRefs = JGitUtils.getAvailableHeadTargets(r);
    model.sparkleshareId = JGitUtils.getSparkleshareId(r);
    model.hasCommits = JGitUtils.hasCommits(r);
    updateLastChangeFields(r, model);
    r.close();

    if (StringUtils.isEmpty(model.originRepository) && model.origin != null
            && model.origin.startsWith("file://")) {
        // repository was cloned locally... perhaps as a fork
        try {
            File folder = new File(new URI(model.origin));
            String originRepo = com.gitblit.utils.FileUtils.getRelativePath(getRepositoriesFolder(), folder);
            if (!StringUtils.isEmpty(originRepo)) {
                // ensure origin still exists
                File repoFolder = new File(getRepositoriesFolder(), originRepo);
                if (repoFolder.exists()) {
                    model.originRepository = originRepo.toLowerCase();

                    // persist the fork origin
                    updateConfiguration(r, model);
                }
            }
        } catch (URISyntaxException e) {
            logger.error("Failed to determine fork for " + model, e);
        }
    }
    return model;
}

From source file:com.gitblit.utils.JGitUtils.java

License:Apache License

/**
 * Automatic repair of (some) invalid refspecs.  These are the result of a
 * bug in JGit cloning where a double forward-slash was injected.  :(
 *
 * @param repository//from w  w w  .jav  a2  s  . c  om
 * @return true, if the refspecs were repaired
 */
public static boolean repairFetchSpecs(Repository repository) {
    StoredConfig rc = repository.getConfig();

    // auto-repair broken fetch ref specs
    for (String name : rc.getSubsections("remote")) {
        int invalidSpecs = 0;
        int repairedSpecs = 0;
        List<String> specs = new ArrayList<String>();
        for (String spec : rc.getStringList("remote", name, "fetch")) {
            try {
                RefSpec rs = new RefSpec(spec);
                // valid spec
                specs.add(spec);
            } catch (IllegalArgumentException e) {
                // invalid spec
                invalidSpecs++;
                if (spec.contains("//")) {
                    // auto-repair this known spec bug
                    spec = spec.replace("//", "/");
                    specs.add(spec);
                    repairedSpecs++;
                }
            }
        }

        if (invalidSpecs == repairedSpecs && repairedSpecs > 0) {
            // the fetch specs were automatically repaired
            rc.setStringList("remote", name, "fetch", specs);
            try {
                rc.save();
                rc.load();
                LOGGER.debug("repaired {} invalid fetch refspecs for {}", repairedSpecs,
                        repository.getDirectory());
                return true;
            } catch (Exception e) {
                LOGGER.error(null, e);
            }
        } else if (invalidSpecs > 0) {
            LOGGER.error("mirror executor found {} invalid fetch refspecs for {}", invalidSpecs,
                    repository.getDirectory());
        }
    }
    return false;
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.egit.repositories.GitRepositoriesMap.java

License:Open Source License

private Map<String, String> getMappedBranches(final TfsGitRepositoryJson serverRepository,
        final Repository localRepository) {
    Map<String, String> mappedBranches = null;
    String upstreamURL = serverRepository.getRemoteUrl();
    try {/*from  w  ww  .  j av a 2s  .  com*/
        upstreamURL = URIUtil.encodePath(serverRepository.getRemoteUrl());
    } catch (final URIException e) {
        log.error("Error encoding repository URL " + upstreamURL, e); //$NON-NLS-1$
    }

    final StoredConfig repositoryConfig = localRepository.getConfig();
    final Set<String> remotes = repositoryConfig.getSubsections(REMOTES_SECTION_NAME);

    for (final String remoteName : remotes) {
        final String remoteURL = repositoryConfig.getString(REMOTES_SECTION_NAME, remoteName, URL_VALUE_NAME);

        if (remoteURL != null && remoteURL.equalsIgnoreCase(upstreamURL)) {
            if (mappedBranches == null) {
                mappedBranches = new HashMap<String, String>();
            }

            final Set<String> branches = repositoryConfig.getSubsections(BRANCHES_SECTION_NAME);

            for (final String branch : branches) {
                final String fullBranchName = Constants.R_HEADS + branch;

                final String[] remoteNames = repositoryConfig.getStringList(BRANCHES_SECTION_NAME, branch,
                        REMOTE_VALUE_NAME);
                final String[] mappedBrancheNames = repositoryConfig.getStringList(BRANCHES_SECTION_NAME,
                        branch, MERGE_VALUE_NAME);

                for (int k = 0; k < remoteNames.length; k++) {
                    if (remoteNames[k].equals(remoteName)) {
                        final String remoteBranchName = mappedBrancheNames[k];

                        if (!mappedBranches.containsKey(remoteBranchName)) {
                            mappedBranches.put(remoteBranchName, fullBranchName);
                        }

                        break;
                    }
                }
            }

            break;
        }
    }

    return mappedBranches;
}

From source file:org.eclipse.egit.ui.internal.repository.tree.command.DeleteFetchCommand.java

License:Open Source License

public Object execute(ExecutionEvent event) throws ExecutionException {
    FetchNode node = getSelectedNodes(event).get(0);
    RemoteNode remote = (RemoteNode) node.getParent();

    StoredConfig config = node.getRepository().getConfig();
    String fetchUrl = config.getString(REMOTE, remote.getObject(), URL);
    config.unset(REMOTE, remote.getObject(), FETCH);
    config.unset(REMOTE, remote.getObject(), URL);
    // the push URL may still be needed for fetch
    if (fetchUrl != null) {
        boolean hasPush = config.getStringList(REMOTE, remote.getObject(), PUSH).length > 0;
        if (hasPush) {
            String[] pushurls = config.getStringList(REMOTE, remote.getObject(), PUSHURL);
            // if there are not specific push urls,
            // copy the former fetch url into push url
            if (pushurls.length == 0)
                config.setString(REMOTE, remote.getObject(), PUSHURL, fetchUrl);
        }/*from w w w.  j  a v  a 2s  . c  o  m*/
    }

    try {
        config.save();
    } catch (IOException e1) {
        Activator.handleError(e1.getMessage(), e1, true);
    }

    return null;
}

From source file:org.eclipse.mylyn.internal.gerrit.core.egit.GerritToGitMappingTest.java

License:Open Source License

private Repository createRepository(String project) {
    StoredConfig config = mock(StoredConfig.class);
    Set<String> configSubSections = new HashSet<String>();
    String remoteName = "remotename"; //$NON-NLS-1$
    configSubSections.add(remoteName);/*from   w w w. java  2s .c  o m*/
    String remoteSection = "remote"; //$NON-NLS-1$
    when(config.getSubsections(remoteSection)).thenReturn(configSubSections);
    when(config.getStringList(eq(remoteSection), eq(remoteName), anyString())).thenReturn(new String[0]);
    when(config.getStringList(eq(remoteSection), eq(remoteName), matches("url"))).thenReturn( //$NON-NLS-1$
            new String[] { "git://" + GERRIT_GIT_HOST + "/" + project }); //$NON-NLS-1$//$NON-NLS-2$
    Repository repo = mock(Repository.class);
    when(repo.getConfig()).thenReturn(config);
    return repo;
}

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 .  j a  va2  s .  c o  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();
    }
}