Search in sources :

Example 6 with StoredConfig

use of org.eclipse.jgit.lib.StoredConfig in project gitblit by gitblit.

the class AddIndexedBranch method main.

public static void main(String... args) {
    Params params = new Params();
    CmdLineParser parser = new CmdLineParser(params);
    try {
        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));
}
Also used : LinkedHashSet(java.util.LinkedHashSet) RefModel(com.gitblit.models.RefModel) CmdLineParser(org.kohsuke.args4j.CmdLineParser) FileRepositoryBuilder(org.eclipse.jgit.storage.file.FileRepositoryBuilder) CmdLineException(org.kohsuke.args4j.CmdLineException) StoredConfig(org.eclipse.jgit.lib.StoredConfig) Repository(org.eclipse.jgit.lib.Repository) TreeSet(java.util.TreeSet) File(java.io.File) CmdLineException(org.kohsuke.args4j.CmdLineException)

Example 7 with StoredConfig

use of org.eclipse.jgit.lib.StoredConfig in project gitblit by gitblit.

the class ConfigUserService method write.

/**
	 * Writes the properties file.
	 *
	 * @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) {
                // 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);
            }
        }
        // can have a null users object
        if (!ArrayUtils.isEmpty(model.users)) {
            config.setStringList(TEAM, model.name, USER, new ArrayList<String>(model.users));
        }
        // TeamModel can have a null users object
        if (!ArrayUtils.isEmpty(model.mailingLists)) {
            config.setStringList(TEAM, model.name, MAILINGLIST, new ArrayList<String>(model.mailingLists));
        }
        // TeamModel can have a null preReceiveScripts object
        if (!ArrayUtils.isEmpty(model.preReceiveScripts)) {
            config.setStringList(TEAM, model.name, PRERECEIVE, model.preReceiveScripts);
        }
        // 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;
    // 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()));
    }
}
Also used : Locale(java.util.Locale) ArrayList(java.util.ArrayList) AccessPermission(com.gitblit.Constants.AccessPermission) IOException(java.io.IOException) StoredConfig(org.eclipse.jgit.lib.StoredConfig) UserModel(com.gitblit.models.UserModel) TeamModel(com.gitblit.models.TeamModel) FileBasedConfig(org.eclipse.jgit.storage.file.FileBasedConfig) File(java.io.File) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 8 with StoredConfig

use of org.eclipse.jgit.lib.StoredConfig in project gitblit by gitblit.

the class GitblitAuthority method saveSizeAndPosition.

private void saveSizeAndPosition() {
    try {
        // 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);
    }
}
Also used : StoredConfig(org.eclipse.jgit.lib.StoredConfig) Dimension(java.awt.Dimension) Point(java.awt.Point)

Example 9 with StoredConfig

use of org.eclipse.jgit.lib.StoredConfig in project gitblit by gitblit.

the class JGitUtils method repairFetchSpecs.

/**
	 * 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
	 * @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;
}
Also used : StoredConfig(org.eclipse.jgit.lib.StoredConfig) RefSpec(org.eclipse.jgit.transport.RefSpec) ArrayList(java.util.ArrayList) RevisionSyntaxException(org.eclipse.jgit.errors.RevisionSyntaxException) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) LargeObjectException(org.eclipse.jgit.errors.LargeObjectException) GitBlitException(com.gitblit.GitBlitException) AmbiguousObjectException(org.eclipse.jgit.errors.AmbiguousObjectException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) ConcurrentRefUpdateException(org.eclipse.jgit.api.errors.ConcurrentRefUpdateException) IOException(java.io.IOException) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) StopWalkException(org.eclipse.jgit.errors.StopWalkException)

Example 10 with StoredConfig

use of org.eclipse.jgit.lib.StoredConfig in project gitblit by gitblit.

the class ITicketService method renameMilestone.

/**
	 * Renames a milestone.
	 *
	 * @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;
}
Also used : StoredConfig(org.eclipse.jgit.lib.StoredConfig) Repository(org.eclipse.jgit.lib.Repository) TicketModel(com.gitblit.models.TicketModel) Change(com.gitblit.models.TicketModel.Change) IOException(java.io.IOException) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

StoredConfig (org.eclipse.jgit.lib.StoredConfig)40 IOException (java.io.IOException)26 Repository (org.eclipse.jgit.lib.Repository)19 File (java.io.File)9 ArrayList (java.util.ArrayList)8 URISyntaxException (java.net.URISyntaxException)6 GitException (org.eclipse.che.api.git.exception.GitException)6 SimpleDateFormat (java.text.SimpleDateFormat)5 GitBlitException (com.gitblit.GitBlitException)4 RepositoryModel (com.gitblit.models.RepositoryModel)4 Point (java.awt.Point)4 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)4 RemoteConfig (org.eclipse.jgit.transport.RemoteConfig)4 TeamModel (com.gitblit.models.TeamModel)3 Change (com.gitblit.models.TicketModel.Change)3 UserModel (com.gitblit.models.UserModel)3 HashSet (java.util.HashSet)3 Git (org.eclipse.jgit.api.Git)3 RefSpec (org.eclipse.jgit.transport.RefSpec)3 AccessPermission (com.gitblit.Constants.AccessPermission)2