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:com.gitblit.manager.RepositoryManager.java

License:Apache License

/**
 * Creates/updates the repository model keyed by repositoryName. Saves all
 * repository settings in .git/config. This method allows for renaming
 * repositories and will update user access permissions accordingly.
 *
 * All repositories created by this method are bare and automatically have
 * .git appended to their names, which is the standard convention for bare
 * repositories./* ww w.  j a v  a2  s  .  co  m*/
 *
 * @param repositoryName
 * @param repository
 * @param isCreate
 * @throws GitBlitException
 */
@Override
public void updateRepositoryModel(String repositoryName, RepositoryModel repository, boolean isCreate)
        throws GitBlitException {
    if (isCollectingGarbage(repositoryName)) {
        throw new GitBlitException(
                MessageFormat.format("sorry, Gitblit is busy collecting garbage in {0}", repositoryName));
    }
    Repository r = null;
    String projectPath = StringUtils.getFirstPathElement(repository.name);
    if (!StringUtils.isEmpty(projectPath)) {
        if (projectPath.equalsIgnoreCase(settings.getString(Keys.web.repositoryRootGroupName, "main"))) {
            // strip leading group name
            repository.name = repository.name.substring(projectPath.length() + 1);
        }
    }
    boolean isRename = false;
    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 (hasRepository(repository.name)) {
            throw new GitBlitException(MessageFormat
                    .format("Can not create repository ''{0}'' because it already exists.", repository.name));
        }
        // create repository
        logger.info("create repository " + repository.name);
        String shared = settings.getString(Keys.git.createRepositoriesShared, "FALSE");
        r = JGitUtils.createRepository(repositoriesFolder, repository.name, shared);
    } else {
        // rename repository
        isRename = !repositoryName.equalsIgnoreCase(repository.name);
        if (isRename) {
            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));
            }
            close(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 (!userManager.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.setString(Constants.CONFIG_GITBLIT, null, "originRepository", repository.name);
                        config.save();
                    } catch (Exception e) {
                        logger.error("Failed to update repository fork config for " + fork, e);
                    }
                    rf.close();
                }
            }

            // update this repository's origin's fork list
            if (!StringUtils.isEmpty(repository.originRepository)) {
                String originKey = getRepositoryKey(repository.originRepository);
                RepositoryModel origin = repositoryListCache.get(originKey);
                if (origin != null && !ArrayUtils.isEmpty(origin.forks)) {
                    origin.forks.remove(repositoryName);
                    origin.forks.add(repository.name);
                }
            }

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

        // load repository
        logger.info("edit repository " + repository.name);
        r = getRepository(repository.name);
    }

    // update settings
    if (r != null) {
        updateConfiguration(r, repository);
        // Update the description file
        File descFile = new File(r.getDirectory(), "description");
        if (repository.description != null) {
            com.gitblit.utils.FileUtils.writeContent(descFile, repository.description);
        } else if (descFile.exists() && !descFile.isDirectory()) {
            descFile.delete();
        }
        // 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);
            }
        }

        // Adjust permissions in case we updated the config files
        JGitUtils.adjustSharedPerm(new File(r.getDirectory().getAbsolutePath(), "config"),
                settings.getString(Keys.git.createRepositoriesShared, "FALSE"));
        JGitUtils.adjustSharedPerm(new File(r.getDirectory().getAbsolutePath(), "HEAD"),
                settings.getString(Keys.git.createRepositoriesShared, "FALSE"));

        // 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);

    if (isCreate && pluginManager != null) {
        for (RepositoryLifeCycleListener listener : pluginManager
                .getExtensions(RepositoryLifeCycleListener.class)) {
            try {
                listener.onCreation(repository);
            } catch (Throwable t) {
                logger.error(String.format("failed to call plugin onCreation %s", repositoryName), t);
            }
        }
    } else if (isRename && pluginManager != null) {
        for (RepositoryLifeCycleListener listener : pluginManager
                .getExtensions(RepositoryLifeCycleListener.class)) {
            try {
                listener.onRename(repositoryName, repository);
            } catch (Throwable t) {
                logger.error(String.format("failed to call plugin onRename %s", repositoryName), t);
            }
        }
    }
}

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

License:Apache License

/**
 * Updates the Gitblit configuration for the specified repository.
 *
 * @param r//from   w  w w.  j  av  a 2  s .  c om
 *            the Git repository
 * @param repository
 *            the Gitblit repository model
 */
@Override
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, "originRepository", repository.originRepository);
    config.setString(Constants.CONFIG_GITBLIT, null, "owner", ArrayUtils.toString(repository.owners));
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "acceptNewPatchsets", repository.acceptNewPatchsets);
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "acceptNewTickets", repository.acceptNewTickets);
    if (settings.getBoolean(Keys.tickets.requireApproval, false) == repository.requireApproval) {
        // use default
        config.unset(Constants.CONFIG_GITBLIT, null, "requireApproval");
    } else {
        // override default
        config.setBoolean(Constants.CONFIG_GITBLIT, null, "requireApproval", repository.requireApproval);
    }
    if (!StringUtils.isEmpty(repository.mergeTo)) {
        config.setString(Constants.CONFIG_GITBLIT, null, "mergeTo", repository.mergeTo);
    }
    if (repository.mergeType == null
            || repository.mergeType == MergeType.fromName(settings.getString(Keys.tickets.mergeType, null))) {
        // use default
        config.unset(Constants.CONFIG_GITBLIT, null, "mergeType");
    } else {
        // override default
        config.setString(Constants.CONFIG_GITBLIT, null, "mergeType", repository.mergeType.name());
    }
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "useIncrementalPushTags",
            repository.useIncrementalPushTags);
    if (StringUtils.isEmpty(repository.incrementalPushTagPrefix) || repository.incrementalPushTagPrefix
            .equals(settings.getString(Keys.git.defaultIncrementalPushTagPrefix, "r"))) {
        config.unset(Constants.CONFIG_GITBLIT, null, "incrementalPushTagPrefix");
    } else {
        config.setString(Constants.CONFIG_GITBLIT, null, "incrementalPushTagPrefix",
                repository.incrementalPushTagPrefix);
    }
    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, "verifyCommitter", repository.verifyCommitter);
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "showRemoteBranches", repository.showRemoteBranches);
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "isFrozen", repository.isFrozen);
    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);
    config.setString(Constants.CONFIG_GITBLIT, null, "gcThreshold", repository.gcThreshold);
    if (repository.gcPeriod == settings.getInteger(Keys.git.defaultGarbageCollectionPeriod, 7)) {
        // use default from config
        config.unset(Constants.CONFIG_GITBLIT, null, "gcPeriod");
    } else {
        config.setInt(Constants.CONFIG_GITBLIT, null, "gcPeriod", repository.gcPeriod);
    }
    if (repository.lastGC != null) {
        config.setString(Constants.CONFIG_GITBLIT, null, "lastGC",
                new SimpleDateFormat(Constants.ISO8601).format(repository.lastGC));
    }
    if (repository.maxActivityCommits == settings.getInteger(Keys.web.maxActivityCommits, 0)) {
        // use default from config
        config.unset(Constants.CONFIG_GITBLIT, null, "maxActivityCommits");
    } else {
        config.setInt(Constants.CONFIG_GITBLIT, null, "maxActivityCommits", repository.maxActivityCommits);
    }

    CommitMessageRenderer defaultRenderer = CommitMessageRenderer
            .fromName(settings.getString(Keys.web.commitMessageRenderer, null));
    if (repository.commitMessageRenderer == null || repository.commitMessageRenderer == defaultRenderer) {
        // use default from config
        config.unset(Constants.CONFIG_GITBLIT, null, "commitMessageRenderer");
    } else {
        // repository overrides default
        config.setString(Constants.CONFIG_GITBLIT, null, "commitMessageRenderer",
                repository.commitMessageRenderer.name());
    }

    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);
    updateList(config, "metricAuthorExclusions", repository.metricAuthorExclusions);

    // 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.models.RepositoryModelTest.java

License:Apache License

@Before
public void initializeConfiguration() throws Exception {
    Repository r = GitBlitSuite.getHelloworldRepository();
    StoredConfig config = r.getConfig();

    config.unsetSection(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS);
    config.setString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, "commitMessageRegEx", "\\d");
    config.setString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, "anotherProperty", "Hello");

    config.save();/*from  w  w w . j av  a  2  s . co  m*/
}

From source file:com.gitblit.tickets.ITicketService.java

License:Apache License

/**
 * Creates a label.//from   w w w .  j a v a 2  s.c om
 *
 * @param repository
 * @param milestone
 * @param createdBy
 * @return the label
 * @since 1.4.0
 */
public synchronized TicketLabel createLabel(RepositoryModel repository, String label, String createdBy) {
    TicketLabel lb = new TicketMilestone(label);
    Repository db = null;
    try {
        db = repositoryManager.getRepository(repository.name);
        StoredConfig config = db.getConfig();
        config.setString(LABEL, label, COLOR, lb.color);
        config.save();
    } catch (IOException e) {
        log.error("failed to create label " + label + " in " + repository, e);
    } finally {
        if (db != null) {
            db.close();
        }
    }
    return lb;
}

From source file:com.gitblit.tickets.ITicketService.java

License:Apache License

/**
 * Updates a label./*  ww w  .j a  v a2  s  .  c o  m*/
 *
 * @param repository
 * @param label
 * @param createdBy
 * @return true if the update was successful
 * @since 1.4.0
 */
public synchronized boolean updateLabel(RepositoryModel repository, TicketLabel label, String createdBy) {
    Repository db = null;
    try {
        db = repositoryManager.getRepository(repository.name);
        StoredConfig config = db.getConfig();
        config.setString(LABEL, label.name, COLOR, label.color);
        config.save();

        return true;
    } catch (IOException e) {
        log.error("failed to update label " + label + " in " + repository, e);
    } finally {
        if (db != null) {
            db.close();
        }
    }
    return false;
}

From source file:com.gitblit.tickets.ITicketService.java

License:Apache License

/**
 * Renames a label./*www.  j a v a2s.co  m*/
 *
 * @param repository
 * @param oldName
 * @param newName
 * @param createdBy
 * @return true if the rename was successful
 * @since 1.4.0
 */
public synchronized boolean renameLabel(RepositoryModel repository, String oldName, String newName,
        String createdBy) {
    if (StringUtils.isEmpty(newName)) {
        throw new IllegalArgumentException("new label can not be empty!");
    }
    Repository db = null;
    try {
        db = repositoryManager.getRepository(repository.name);
        TicketLabel label = getLabel(repository, oldName);
        StoredConfig config = db.getConfig();
        config.unsetSection(LABEL, oldName);
        config.setString(LABEL, newName, COLOR, label.color);
        config.save();

        for (QueryResult qr : label.tickets) {
            Change change = new Change(createdBy);
            change.unlabel(oldName);
            change.label(newName);
            updateTicket(repository, qr.number, change);
        }

        return true;
    } catch (IOException e) {
        log.error("failed to rename label " + oldName + " in " + repository, e);
    } finally {
        if (db != null) {
            db.close();
        }
    }
    return false;
}

From source file:com.gitblit.tickets.ITicketService.java

License:Apache License

/**
 * Creates a milestone.//w  w w .  j a va 2 s  .c o  m
 *
 * @param repository
 * @param milestone
 * @param createdBy
 * @return the milestone
 * @since 1.4.0
 */
public synchronized TicketMilestone createMilestone(RepositoryModel repository, String milestone,
        String createdBy) {
    TicketMilestone ms = new TicketMilestone(milestone);
    Repository db = null;
    try {
        db = repositoryManager.getRepository(repository.name);
        StoredConfig config = db.getConfig();
        config.setString(MILESTONE, milestone, STATUS, ms.status.name());
        config.setString(MILESTONE, milestone, COLOR, ms.color);
        config.save();

        milestonesCache.remove(repository.name);
    } catch (IOException e) {
        log.error("failed to create milestone " + milestone + " in " + repository, e);
    } finally {
        if (db != null) {
            db.close();
        }
    }
    return ms;
}

From source file:com.gitblit.tickets.ITicketService.java

License:Apache License

/**
 * Updates a milestone.//w  w  w .j av  a  2  s.  co  m
 *
 * @param repository
 * @param milestone
 * @param createdBy
 * @return true if successful
 * @since 1.4.0
 */
public synchronized boolean updateMilestone(RepositoryModel repository, TicketMilestone milestone,
        String createdBy) {
    Repository db = null;
    try {
        db = repositoryManager.getRepository(repository.name);
        StoredConfig config = db.getConfig();
        config.setString(MILESTONE, milestone.name, STATUS, milestone.status.name());
        config.setString(MILESTONE, milestone.name, COLOR, milestone.color);
        if (milestone.due != null) {
            config.setString(MILESTONE, milestone.name, DUE,
                    new SimpleDateFormat(DUE_DATE_PATTERN).format(milestone.due));
        }
        config.save();

        milestonesCache.remove(repository.name);
        return true;
    } catch (IOException e) {
        log.error("failed to update milestone " + milestone + " in " + repository, e);
    } finally {
        if (db != null) {
            db.close();
        }
    }
    return false;
}

From source file:com.gitblit.tickets.ITicketService.java

License:Apache License

/**
 * Renames a milestone./*from   www .j  a va 2 s.  com*/
 *
 * @param repository
 * @param oldName
 * @param newName
 * @param createdBy
 * @param notifyOpenTickets
 * @return true if successful
 * @since 1.6.0
 */
public synchronized boolean renameMilestone(RepositoryModel repository, String oldName, String newName,
        String createdBy, boolean notifyOpenTickets) {
    if (StringUtils.isEmpty(newName)) {
        throw new IllegalArgumentException("new milestone can not be empty!");
    }
    Repository db = null;
    try {
        db = repositoryManager.getRepository(repository.name);
        TicketMilestone tm = getMilestone(repository, oldName);
        if (tm == null) {
            return false;
        }
        StoredConfig config = db.getConfig();
        config.unsetSection(MILESTONE, oldName);
        config.setString(MILESTONE, newName, STATUS, tm.status.name());
        config.setString(MILESTONE, newName, COLOR, tm.color);
        if (tm.due != null) {
            config.setString(MILESTONE, newName, DUE, new SimpleDateFormat(DUE_DATE_PATTERN).format(tm.due));
        }
        config.save();

        milestonesCache.remove(repository.name);

        TicketNotifier notifier = createNotifier();
        for (QueryResult qr : tm.tickets) {
            Change change = new Change(createdBy);
            change.setField(Field.milestone, newName);
            TicketModel ticket = updateTicket(repository, qr.number, change);
            if (notifyOpenTickets && ticket.isOpen()) {
                notifier.queueMailing(ticket);
            }
        }
        if (notifyOpenTickets) {
            notifier.sendAll();
        }

        return true;
    } catch (IOException e) {
        log.error("failed to rename milestone " + oldName + " in " + repository, e);
    } finally {
        if (db != null) {
            db.close();
        }
    }
    return false;
}

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

License:Apache License

/**
 * Creates a bare, shared repository./*  w  w w  .ja v a  2  s . co  m*/
 *
 * @param repositoriesFolder
 * @param name
 * @param shared
 *          the setting for the --shared option of "git init".
 * @return Repository
 */
public static Repository createRepository(File repositoriesFolder, String name, String shared) {
    try {
        Repository repo = null;
        try {
            Git git = Git.init().setDirectory(new File(repositoriesFolder, name)).setBare(true).call();
            repo = git.getRepository();
        } catch (GitAPIException e) {
            throw new RuntimeException(e);
        }

        GitConfigSharedRepository sharedRepository = new GitConfigSharedRepository(shared);
        if (sharedRepository.isShared()) {
            StoredConfig config = repo.getConfig();
            config.setString("core", null, "sharedRepository", sharedRepository.getValue());
            config.setBoolean("receive", null, "denyNonFastforwards", true);
            config.save();

            if (!JnaUtils.isWindows()) {
                Iterator<File> iter = org.apache.commons.io.FileUtils.iterateFilesAndDirs(repo.getDirectory(),
                        TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
                // Adjust permissions on file/directory
                while (iter.hasNext()) {
                    adjustSharedPerm(iter.next(), sharedRepository);
                }
            }
        }

        return repo;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}