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

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

Introduction

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

Prototype

public void setString(final String section, final String subsection, final String name, final String value) 

Source Link

Document

Add or modify a configuration value.

Usage

From source file:bluej.groupwork.git.GitCloneCommand.java

License:Open Source License

@Override
public TeamworkCommandResult getResult() {

    try {//from  w w  w  . ja  v  a  2s.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);/*from   ww w.  j  av a2  s  . c o  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.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);
        }/*from  w ww. ja va2 s  .  co m*/
        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.authority.GitblitAuthority.java

License:Apache License

private void saveSizeAndPosition() {
    try {/*from ww  w.  j av  a  2 s  . com*/
        // 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  ww  w.ja  v 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 {/*from  w w w . j  a v a  2 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.ConfigUserService.java

License:Apache License

/**
 * Writes the properties file.//from  ww  w . ja  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()));
    }
}

From source file:com.gitblit.GitBlit.java

License:Apache License

/**
 * Creates/updates the repository model keyed by reopsitoryName. Saves all
 * repository settings in .git/config. This method allows for renaming
 * repositories and will update user access permissions accordingly.
 * /*w  w  w.jav a  2 s.  c  o m*/
 * All repositories created by this method are bare and automatically have
 * .git appended to their names, which is the standard convention for bare
 * repositories.
 * 
 * @param repositoryName
 * @param repository
 * @param isCreate
 * @throws GitBlitException
 */
public void updateRepositoryModel(String repositoryName, RepositoryModel repository, boolean isCreate)
        throws GitBlitException {
    Repository r = null;
    if (isCreate) {
        // ensure created repository name ends with .git
        if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
            repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
        }
        if (new File(repositoriesFolder, repository.name).exists()) {
            throw new GitBlitException(MessageFormat
                    .format("Can not create repository ''{0}'' because it already exists.", repository.name));
        }
        // create repository
        logger.info("create repository " + repository.name);
        r = JGitUtils.createRepository(repositoriesFolder, repository.name);
    } else {
        // rename repository
        if (!repositoryName.equalsIgnoreCase(repository.name)) {
            if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
                repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
            }
            if (new File(repositoriesFolder, repository.name).exists()) {
                throw new GitBlitException(
                        MessageFormat.format("Failed to rename ''{0}'' because ''{1}'' already exists.",
                                repositoryName, repository.name));
            }
            closeRepository(repositoryName);
            File folder = new File(repositoriesFolder, repositoryName);
            File destFolder = new File(repositoriesFolder, repository.name);
            if (destFolder.exists()) {
                throw new GitBlitException(MessageFormat.format(
                        "Can not rename repository ''{0}'' to ''{1}'' because ''{1}'' already exists.",
                        repositoryName, repository.name));
            }
            File parentFile = destFolder.getParentFile();
            if (!parentFile.exists() && !parentFile.mkdirs()) {
                throw new GitBlitException(
                        MessageFormat.format("Failed to create folder ''{0}''", parentFile.getAbsolutePath()));
            }
            if (!folder.renameTo(destFolder)) {
                throw new GitBlitException(MessageFormat.format(
                        "Failed to rename repository ''{0}'' to ''{1}''.", repositoryName, repository.name));
            }
            // rename the roles
            if (!userService.renameRepositoryRole(repositoryName, repository.name)) {
                throw new GitBlitException(
                        MessageFormat.format("Failed to rename repository permissions ''{0}'' to ''{1}''.",
                                repositoryName, repository.name));
            }

            // rename fork origins in their configs
            if (!ArrayUtils.isEmpty(repository.forks)) {
                for (String fork : repository.forks) {
                    Repository rf = getRepository(fork);
                    try {
                        StoredConfig config = rf.getConfig();
                        String origin = config.getString("remote", "origin", "url");
                        origin = origin.replace(repositoryName, repository.name);
                        config.setString("remote", "origin", "url", origin);
                        config.save();
                    } catch (Exception e) {
                        logger.error("Failed to update repository fork config for " + fork, e);
                    }
                    rf.close();
                }
            }

            // clear the cache
            clearRepositoryMetadataCache(repositoryName);
            repository.resetDisplayName();
        }

        // load repository
        logger.info("edit repository " + repository.name);
        try {
            r = repositoryResolver.open(null, repository.name);
        } catch (RepositoryNotFoundException e) {
            logger.error("Repository not found", e);
        } catch (ServiceNotAuthorizedException e) {
            logger.error("Service not authorized", e);
        } catch (ServiceNotEnabledException e) {
            logger.error("Service not enabled", e);
        } catch (ServiceMayNotContinueException e) {
            logger.error("Service may not continue", e);
        }
    }

    // update settings
    if (r != null) {
        updateConfiguration(r, repository);
        // only update symbolic head if it changes
        String currentRef = JGitUtils.getHEADRef(r);
        if (!StringUtils.isEmpty(repository.HEAD) && !repository.HEAD.equals(currentRef)) {
            logger.info(MessageFormat.format("Relinking {0} HEAD from {1} to {2}", repository.name, currentRef,
                    repository.HEAD));
            if (JGitUtils.setHEADtoRef(r, repository.HEAD)) {
                // clear the cache
                clearRepositoryMetadataCache(repository.name);
            }
        }

        // close the repository object
        r.close();
    }

    // update repository cache
    removeFromCachedRepositoryList(repositoryName);
    // model will actually be replaced on next load because config is stale
    addToCachedRepositoryList(repository.name, repository);
}

From source file:com.gitblit.GitBlit.java

License:Apache License

/**
 * Updates the Gitblit configuration for the specified repository.
 * //  w ww. j  a v a 2  s  .  co  m
 * @param r
 *            the Git repository
 * @param repository
 *            the Gitblit repository model
 */
public void updateConfiguration(Repository r, RepositoryModel repository) {
    StoredConfig config = r.getConfig();
    config.setString(Constants.CONFIG_GITBLIT, null, "description", repository.description);
    config.setString(Constants.CONFIG_GITBLIT, null, "owner", repository.owner);
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "useTickets", repository.useTickets);
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "useDocs", repository.useDocs);
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "allowForks", repository.allowForks);
    config.setString(Constants.CONFIG_GITBLIT, null, "accessRestriction", repository.accessRestriction.name());
    config.setString(Constants.CONFIG_GITBLIT, null, "authorizationControl",
            repository.authorizationControl.name());
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "showRemoteBranches", repository.showRemoteBranches);
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "isFrozen", repository.isFrozen);
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "showReadme", repository.showReadme);
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "skipSizeCalculation", repository.skipSizeCalculation);
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "skipSummaryMetrics", repository.skipSummaryMetrics);
    config.setString(Constants.CONFIG_GITBLIT, null, "federationStrategy",
            repository.federationStrategy.name());
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "isFederated", repository.isFederated);

    updateList(config, "federationSets", repository.federationSets);
    updateList(config, "preReceiveScript", repository.preReceiveScripts);
    updateList(config, "postReceiveScript", repository.postReceiveScripts);
    updateList(config, "mailingList", repository.mailingLists);
    updateList(config, "indexBranch", repository.indexedBranches);

    // User Defined Properties
    if (repository.customFields != null) {
        if (repository.customFields.size() == 0) {
            // clear section
            config.unsetSection(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS);
        } else {
            for (Entry<String, String> property : repository.customFields.entrySet()) {
                // set field
                String key = property.getKey();
                String value = property.getValue();
                config.setString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, key, value);
            }
        }
    }

    try {
        config.save();
    } catch (IOException e) {
        logger.error("Failed to save repository config!", e);
    }
}

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. j  a v a 2s. c o m*/
 * @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;
}