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:bluej.groupwork.git.GitCloneCommand.java

License:Open Source License

@Override
public TeamworkCommandResult getResult() {

    try {//from   ww w.j a v a2 s. c  om
        String reposUrl = getRepository().getReposUrl();
        CloneCommand cloneCommand = Git.cloneRepository();
        disableFingerprintCheck(cloneCommand);
        cloneCommand.setDirectory(clonePath);
        cloneCommand.setURI(reposUrl);
        StoredConfig repoConfig = cloneCommand.call().getRepository().getConfig(); //save the repo
        repoConfig.setString("user", null, "name", getRepository().getYourName()); //register the user name
        repoConfig.setString("user", null, "email", getRepository().getYourEmail()); //register the user email
        repoConfig.save();

        if (!isCancelled()) {
            return new TeamworkCommandResult();
        }

        return new TeamworkCommandAborted();
    } catch (GitAPIException | IOException ex) {
        return new TeamworkCommandError(ex.getMessage(), ex.getLocalizedMessage());
    }
}

From source file:com.athomas.androidkickstartr.util.GitHubber.java

License:Apache License

public Repository createCommit(File srcFolder, String applicationName) throws IOException, GitAPIException {
    Repository repository = repositoryService.createRepository(new Repository().setName(applicationName));

    String cloneUrl = repository.getCloneUrl();

    InitCommand init = new InitCommand();
    init.setDirectory(srcFolder);//  w  w  w.  j a  v  a2s . co m
    init.setBare(false);
    Git git = init.call();

    StoredConfig config = git.getRepository().getConfig();
    config.setString("remote", "origin", "url", cloneUrl);
    config.save();

    UsernamePasswordCredentialsProvider user = new UsernamePasswordCredentialsProvider(accessToken, "");
    git.add().addFilepattern(".").call();
    git.commit().setMessage(COMMIT_MESSAGE).call();
    git.push().setCredentialsProvider(user).call();

    return repository;
}

From source file:com.chungkwong.jgitgui.GitTreeItem.java

License:Open Source License

private void gitConfig() {
    try {/*from  w ww  .  j av  a  2s.c o m*/
        StoredConfig config = ((Git) getValue()).getRepository().getConfig();
        Dialog dialog = new Dialog();
        dialog.setTitle(
                java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("CONFIGURE"));
        TextArea area = new TextArea(config.toText());
        dialog.getDialogPane().setContent(area);
        dialog.getDialogPane().getButtonTypes().addAll(ButtonType.CANCEL, ButtonType.APPLY);
        dialog.showAndWait();
        if (dialog.getResult().equals(ButtonType.APPLY)) {
            config.fromText(area.getText());
            config.save();
        }
    } catch (Exception ex) {
        Logger.getLogger(GitTreeItem.class.getName()).log(Level.SEVERE, null, ex);
        Util.informUser(ex);
    }
}

From source file:com.genuitec.eclipse.gerrit.tools.internal.gps.model.GpsGitRepositoriesConfig.java

License:Open Source License

public void performConfiguration(Map<String, Object> options, SubMonitor monitor) throws CoreException {
    monitor.beginTask("", repo2branch.size() * 2);
    for (Entry<String, RepoSetup> entry : repo2branch.entrySet()) {
        if (monitor.isCanceled())
            return;

        RepoSetup repo = entry.getValue();

        String repositoryName = repo.name;
        String repositoryBranch = repo.branch;
        boolean localBranch = repositoryBranch.startsWith("refs/heads/"); //$NON-NLS-1$
        String branchName = null;
        if (localBranch) {
            branchName = repositoryBranch.substring(11);
        }//  ww w.  j  a v  a2  s.com
        switch (repo.state) {
        case LOCATED:
            org.eclipse.egit.ui.Activator.getDefault().getRepositoryUtil()
                    .addConfiguredRepository(new File(repo.location, ".git")); //$NON-NLS-1$
            break;
        case CLONE:
            monitor.setTaskName("Cloning repository " + repositoryName);
            monitor.subTask("");
            try {
                URIish uri = new URIish(repo.url);
                if (repo.userName != null) {
                    uri = uri.setUser(repo.userName);
                } else {
                    uri = uri.setUser(null);
                }
                CloneOperation co = new CloneOperation(uri, true, null, repo.location, repositoryBranch,
                        "origin", 5000); //$NON-NLS-1$
                co.setCredentialsProvider(new EGitCredentialsProvider());
                co.setCloneSubmodules(true);
                co.run(new SubProgressMonitor(monitor, 0, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK));

                org.eclipse.egit.ui.Activator.getDefault().getRepositoryUtil()
                        .addConfiguredRepository(co.getGitDir());

                break;
            } catch (Throwable e) {
                if (e instanceof InvocationTargetException) {
                    e = e.getCause();
                }
                throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                        (e instanceof InterruptedException) ? "Operation cancelled" : e.getMessage(), e));
            }
        default:
        }

        monitor.setTaskName("Preparing repository " + repositoryName);

        Repository repository = RepositoryUtils.getRepositoryForName(repositoryName);
        if (repository == null) {
            throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                    MessageFormat.format(
                            "Cannot continue. A required git repository named {0} is not configured.",
                            repositoryName)));
        }

        monitor.subTask(MessageFormat.format("Checking out branch \"{0}\" of git repository \"{1}\"",
                repositoryBranch, repositoryName));

        if (repositoryBranch != null && repositoryBranch.length() > 0) {
            //checkout the branch
            boolean newBranch = false;
            try {
                Ref ref = repository.getRef(repositoryBranch);
                if (localBranch && ref == null) {
                    String originBranch = "refs/remotes/origin/" + branchName; //$NON-NLS-1$
                    ref = repository.getRef(originBranch);
                    if (ref == null) {
                        try {
                            new Git(repository).fetch().setRemote("origin").call(); //$NON-NLS-1$
                        } catch (Exception e) {
                            throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                                    MessageFormat.format(
                                            "Cannot fetch from remote 'origin' of repository \"{0}\":\n{1}",
                                            repositoryName, e.getMessage(), e)));
                        }
                    }
                    ref = repository.getRef(originBranch);
                    if (ref == null) {
                        throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                                MessageFormat.format("Cannot find branch \"{1}\" in repository \"{0}\".",
                                        repositoryName, originBranch)));
                    }
                    //we need to create the local branch based on remote branch
                    new Git(repository).branchCreate().setName(branchName).setStartPoint(originBranch)
                            .setUpstreamMode(SetupUpstreamMode.TRACK).call();
                    newBranch = true;
                }
                if (monitor.isCanceled())
                    return;

                try {
                    new Git(repository).checkout().setName(repositoryBranch).call();
                } catch (Exception e) {
                    if (options.containsKey(PROP_FORCE_CHECKOUT)
                            && (Boolean) options.get(PROP_FORCE_CHECKOUT)) {
                        //try to reset
                        new Git(repository).reset().setMode(ResetType.HARD).call();

                        //and then checkout again
                        new Git(repository).checkout().setName(repositoryBranch).call();
                    } else {
                        throw e;
                    }
                }

                int fileCount = repository.getDirectory().getParentFile().list().length;
                if (fileCount == 1) {
                    //we need to hard reset the repository - there are no files in it
                    new Git(repository).reset().setMode(ResetType.HARD).call();
                }

            } catch (Exception e) {
                throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                        MessageFormat.format("Cannot checkout branch \"{1}\" of repository \"{0}\":\n{2}",
                                repositoryName, repositoryBranch, e.getMessage(), e)));
            }
            if (monitor.isCanceled())
                return;

            if (localBranch) {
                monitor.subTask(MessageFormat.format("Configuring branch \"{0}\" of git repository \"{1}\"",
                        repositoryBranch, repositoryName));
                try {
                    StoredConfig config = repository.getConfig();

                    if (options.get(PROP_CONFIGURE_PUSH_TO_UPSTREAM) != null
                            && (Boolean) options.get(PROP_CONFIGURE_PUSH_TO_UPSTREAM)) {
                        //configure push to upstream
                        config.setString("remote", "origin", "push", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                                repositoryBranch + ":refs/for/" + branchName); //$NON-NLS-1$
                    }
                    if (newBranch || (options.get(PROP_RECONFIGURE_BRANCH) != null
                            && (Boolean) options.get(PROP_RECONFIGURE_BRANCH))) {
                        config.setString("branch", branchName, "remote", "origin"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                        config.setString("branch", branchName, "merge", repositoryBranch); //$NON-NLS-1$ //$NON-NLS-2$
                        config.setString("branch", branchName, "rebase", "true"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                    }
                    config.save();
                } catch (Exception e) {
                    throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                            MessageFormat.format("Cannot configure branch \"{1}\" of repository \"{0}\":\n{2}",
                                    repositoryName, repositoryBranch, e.getMessage(), e)));
                }
            }
            if (monitor.isCanceled())
                return;

            if (options.containsKey(PROP_AUTO_PULL) && (Boolean) options.get(PROP_AUTO_PULL)) {
                monitor.subTask(MessageFormat.format("Pulling branch \"{0}\" from git repository \"{1}\"",
                        repositoryBranch, repositoryName));

                try {
                    new Git(repository).pull().call();
                } catch (Exception e) {
                    throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                            MessageFormat.format("Cannot pull branch \"{1}\" of repository \"{0}\":\n{2}",
                                    repositoryName, repositoryBranch, e.getMessage(), e)));
                }
            }
        }

        monitor.worked(1);
    }

}

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  .j  a v  a  2s  .  com*/
        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.authority.GitblitAuthority.java

License:Apache License

private void saveSizeAndPosition() {
    try {/*  www .  j  a  v a 2s  .c o  m*/
        // save window size and position
        StoredConfig config = getConfig();
        Dimension sz = GitblitAuthority.this.getSize();
        config.setString("ui", null, "size",
                MessageFormat.format("{0,number,0}x{1,number,0}", sz.width, sz.height));
        Point pos = GitblitAuthority.this.getLocationOnScreen();
        config.setString("ui", null, "position",
                MessageFormat.format("{0,number,0},{1,number,0}", pos.x, pos.y));
        config.save();
    } catch (Throwable t) {
        Utils.showException(GitblitAuthority.this, t);
    }
}

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

License:Apache License

private void saveSizeAndPosition() {
    try {//from w  w  w  .  jav a2s . c o m
        // save window size and position
        StoredConfig config = getConfig();
        Dimension sz = GitblitManager.this.getSize();
        config.setString("ui", null, "size",
                MessageFormat.format("{0,number,0}x{1,number,0}", sz.width, sz.height));
        Point pos = GitblitManager.this.getLocationOnScreen();
        config.setString("ui", null, "position",
                MessageFormat.format("{0,number,0},{1,number,0}", pos.x, pos.y));
        config.save();
    } catch (Throwable t) {
        Utils.showException(GitblitManager.this, t);
    }
}

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

License:Apache License

@Override
public boolean saveRegistration(String name, GitblitRegistration reg) {
    try {// ww w.j a va2  s .co m
        StoredConfig config = getConfig();
        if (!StringUtils.isEmpty(name) && !name.equals(reg.name)) {
            // delete old registration
            registrations.remove(name);
            config.unsetSection(SERVER, name);
        }

        // update registration
        config.setString(SERVER, reg.name, "url", reg.url);
        config.setString(SERVER, reg.name, "account", reg.account);
        if (reg.savePassword) {
            config.setString(SERVER, reg.name, "password",
                    Base64.encodeBytes(new String(reg.password).getBytes("UTF-8")));
        } else {
            config.setString(SERVER, reg.name, "password", "");
        }
        if (reg.lastLogin != null) {
            config.setString(SERVER, reg.name, "lastLogin", dateFormat.format(reg.lastLogin));
        }
        // serialize the feed definitions
        List<String> definitions = new ArrayList<String>();
        for (FeedModel feed : reg.feeds) {
            definitions.add(feed.toString());
        }
        if (definitions.size() > 0) {
            config.setStringList(SERVER, reg.name, FEED, definitions);
        }
        config.save();
        return true;
    } catch (Throwable t) {
        Utils.showException(GitblitManager.this, t);
    }
    return false;
}

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

License:Apache License

@Override
public boolean deleteRegistrations(List<GitblitRegistration> list) {
    boolean success = false;
    try {// w  w  w. j  a v a  2  s  . c om
        StoredConfig config = getConfig();
        for (GitblitRegistration reg : list) {
            config.unsetSection(SERVER, reg.name);
            registrations.remove(reg.name);
        }
        config.save();
        success = true;
    } catch (Throwable t) {
        Utils.showException(GitblitManager.this, t);
    }
    return success;
}

From source file:com.gitblit.ConfigUserService.java

License:Apache License

/**
 * Writes the properties file.//  www .  j a  v  a 2 s. c  o m
 *
 * @throws IOException
 */
private synchronized void write() throws IOException {
    // Write a temporary copy of the users file
    File realmFileCopy = new File(realmFile.getAbsolutePath() + ".tmp");

    StoredConfig config = new FileBasedConfig(realmFileCopy, FS.detect());

    // write users
    for (UserModel model : users.values()) {
        if (!StringUtils.isEmpty(model.password)) {
            config.setString(USER, model.username, PASSWORD, model.password);
        }
        if (!StringUtils.isEmpty(model.cookie)) {
            config.setString(USER, model.username, COOKIE, model.cookie);
        }
        if (!StringUtils.isEmpty(model.displayName)) {
            config.setString(USER, model.username, DISPLAYNAME, model.displayName);
        }
        if (!StringUtils.isEmpty(model.emailAddress)) {
            config.setString(USER, model.username, EMAILADDRESS, model.emailAddress);
        }
        if (model.accountType != null) {
            config.setString(USER, model.username, ACCOUNTTYPE, model.accountType.name());
        }
        if (!StringUtils.isEmpty(model.organizationalUnit)) {
            config.setString(USER, model.username, ORGANIZATIONALUNIT, model.organizationalUnit);
        }
        if (!StringUtils.isEmpty(model.organization)) {
            config.setString(USER, model.username, ORGANIZATION, model.organization);
        }
        if (!StringUtils.isEmpty(model.locality)) {
            config.setString(USER, model.username, LOCALITY, model.locality);
        }
        if (!StringUtils.isEmpty(model.stateProvince)) {
            config.setString(USER, model.username, STATEPROVINCE, model.stateProvince);
        }
        if (!StringUtils.isEmpty(model.countryCode)) {
            config.setString(USER, model.username, COUNTRYCODE, model.countryCode);
        }
        if (model.disabled) {
            config.setBoolean(USER, model.username, DISABLED, true);
        }
        if (model.getPreferences() != null) {
            Locale locale = model.getPreferences().getLocale();
            if (locale != null) {
                String val;
                if (StringUtils.isEmpty(locale.getCountry())) {
                    val = locale.getLanguage();
                } else {
                    val = locale.getLanguage() + "_" + locale.getCountry();
                }
                config.setString(USER, model.username, LOCALE, val);
            }

            config.setBoolean(USER, model.username, EMAILONMYTICKETCHANGES,
                    model.getPreferences().isEmailMeOnMyTicketChanges());

            if (model.getPreferences().getTransport() != null) {
                config.setString(USER, model.username, TRANSPORT, model.getPreferences().getTransport().name());
            }
        }

        // user roles
        List<String> roles = new ArrayList<String>();
        if (model.canAdmin) {
            roles.add(Role.ADMIN.getRole());
        }
        if (model.canFork) {
            roles.add(Role.FORK.getRole());
        }
        if (model.canCreate) {
            roles.add(Role.CREATE.getRole());
        }
        if (model.excludeFromFederation) {
            roles.add(Role.NOT_FEDERATED.getRole());
        }
        if (roles.size() == 0) {
            // we do this to ensure that user record with no password
            // is written.  otherwise, StoredConfig optimizes that account
            // away. :(
            roles.add(Role.NONE.getRole());
        }
        config.setStringList(USER, model.username, ROLE, roles);

        // discrete repository permissions
        if (model.permissions != null && !model.canAdmin) {
            List<String> permissions = new ArrayList<String>();
            for (Map.Entry<String, AccessPermission> entry : model.permissions.entrySet()) {
                if (entry.getValue().exceeds(AccessPermission.NONE)) {
                    permissions.add(entry.getValue().asRole(entry.getKey()));
                }
            }
            config.setStringList(USER, model.username, REPOSITORY, permissions);
        }

        // user preferences
        if (model.getPreferences() != null) {
            List<String> starred = model.getPreferences().getStarredRepositories();
            if (starred.size() > 0) {
                config.setStringList(USER, model.username, STARRED, starred);
            }
        }
    }

    // write teams
    for (TeamModel model : teams.values()) {
        // team roles
        List<String> roles = new ArrayList<String>();
        if (model.canAdmin) {
            roles.add(Role.ADMIN.getRole());
        }
        if (model.canFork) {
            roles.add(Role.FORK.getRole());
        }
        if (model.canCreate) {
            roles.add(Role.CREATE.getRole());
        }
        if (roles.size() == 0) {
            // we do this to ensure that team record is written.
            // Otherwise, StoredConfig might optimizes that record away.
            roles.add(Role.NONE.getRole());
        }
        config.setStringList(TEAM, model.name, ROLE, roles);
        if (model.accountType != null) {
            config.setString(TEAM, model.name, ACCOUNTTYPE, model.accountType.name());
        }

        if (!model.canAdmin) {
            // write team permission for non-admin teams
            if (model.permissions == null) {
                // null check on "final" repositories because JSON-sourced TeamModel
                // can have a null repositories object
                if (!ArrayUtils.isEmpty(model.repositories)) {
                    config.setStringList(TEAM, model.name, REPOSITORY,
                            new ArrayList<String>(model.repositories));
                }
            } else {
                // discrete repository permissions
                List<String> permissions = new ArrayList<String>();
                for (Map.Entry<String, AccessPermission> entry : model.permissions.entrySet()) {
                    if (entry.getValue().exceeds(AccessPermission.NONE)) {
                        // code:repository (e.g. RW+:~james/myrepo.git
                        permissions.add(entry.getValue().asRole(entry.getKey()));
                    }
                }
                config.setStringList(TEAM, model.name, REPOSITORY, permissions);
            }
        }

        // null check on "final" users because JSON-sourced TeamModel
        // can have a null users object
        if (!ArrayUtils.isEmpty(model.users)) {
            config.setStringList(TEAM, model.name, USER, new ArrayList<String>(model.users));
        }

        // null check on "final" mailing lists because JSON-sourced
        // TeamModel can have a null users object
        if (!ArrayUtils.isEmpty(model.mailingLists)) {
            config.setStringList(TEAM, model.name, MAILINGLIST, new ArrayList<String>(model.mailingLists));
        }

        // null check on "final" preReceiveScripts because JSON-sourced
        // TeamModel can have a null preReceiveScripts object
        if (!ArrayUtils.isEmpty(model.preReceiveScripts)) {
            config.setStringList(TEAM, model.name, PRERECEIVE, model.preReceiveScripts);
        }

        // null check on "final" postReceiveScripts because JSON-sourced
        // TeamModel can have a null postReceiveScripts object
        if (!ArrayUtils.isEmpty(model.postReceiveScripts)) {
            config.setStringList(TEAM, model.name, POSTRECEIVE, model.postReceiveScripts);
        }
    }

    config.save();
    // manually set the forceReload flag because not all JVMs support real
    // millisecond resolution of lastModified. (issue-55)
    forceReload = true;

    // If the write is successful, delete the current file and rename
    // the temporary copy to the original filename.
    if (realmFileCopy.exists() && realmFileCopy.length() > 0) {
        if (realmFile.exists()) {
            if (!realmFile.delete()) {
                throw new IOException(
                        MessageFormat.format("Failed to delete {0}!", realmFile.getAbsolutePath()));
            }
        }
        if (!realmFileCopy.renameTo(realmFile)) {
            throw new IOException(MessageFormat.format("Failed to rename {0} to {1}!",
                    realmFileCopy.getAbsolutePath(), realmFile.getAbsolutePath()));
        }
    } else {
        throw new IOException(MessageFormat.format("Failed to save {0}!", realmFileCopy.getAbsolutePath()));
    }
}