Example usage for org.eclipse.jgit.lib Repository getConfig

List of usage examples for org.eclipse.jgit.lib Repository getConfig

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository getConfig.

Prototype

@NonNull
public abstract StoredConfig getConfig();

Source Link

Document

Get the configuration of this repository.

Usage

From source file:com.genuitec.eclipse.gerrit.tools.utils.RepositoryUtils.java

License:Open Source License

public static String getUserId(Repository repository) {
    StoredConfig config;//w w w .  j a v  a  2s .  c om
    if (repository == null) {
        if (StringUtils.isEmptyOrNull(SystemReader.getInstance().getenv(Constants.GIT_CONFIG_NOSYSTEM_KEY))) {
            config = SystemReader.getInstance().openSystemConfig(null, FS.DETECTED);
        } else {
            config = new FileBasedConfig(null, FS.DETECTED) {
                public void load() {
                    // empty, do not load
                }

                public boolean isOutdated() {
                    // regular class would bomb here
                    return false;
                }
            };
        }
        try {
            config.load();
            config = SystemReader.getInstance().openUserConfig(config, FS.DETECTED);
            config.load();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    } else {
        config = repository.getConfig();
    }
    String email = config.getString("user", null, "email"); //$NON-NLS-1$ //$NON-NLS-2$
    if (email != null) {
        int ind = email.indexOf('@');
        if (ind > 0) {
            return email.substring(0, ind);
        }
    }
    return null;
}

From source file:com.genuitec.eclipse.gerrit.tools.utils.RepositoryUtils.java

License:Open Source License

public static void fetchOrigin(Shell shell, final Repository repository) {
    //perform branch operation
    try {/*from   w  ww  .  j a v a2  s  .  c om*/
        ProgressMonitorDialog progressDialog = new ProgressMonitorDialog(shell);
        progressDialog.run(true, true, new IRunnableWithProgress() {

            @Override
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                try {
                    monitor.beginTask("Fetching updates from origin", 100);
                    FetchOperationUI fetchOp = new FetchOperationUI(repository,
                            new RemoteConfig(repository.getConfig(), "origin"), 3000, false); //$NON-NLS-1$
                    fetchOp.setCredentialsProvider(new EGitCredentialsProvider());
                    fetchOp.execute(new SubProgressMonitor(monitor, 100));
                } catch (Exception e) {
                    throw new InvocationTargetException(e);
                }
            }
        });
    } catch (InterruptedException e) {
        //ignore
    } catch (Exception e) {
        RepositoryUtils.handleException(e);
    }
}

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 {//from   www .ja v a 2s.c o  m
        parser.parseArgument(args);
    } catch (CmdLineException t) {
        System.err.println(t.getMessage());
        parser.printUsage(System.out);
        return;
    }

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

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

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

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

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

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

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

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

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

From source file:com.gitblit.FederationPullExecutor.java

License:Apache License

/**
 * Mirrors a repository and, optionally, the server's users, and/or
 * configuration settings from a origin Gitblit instance.
 * //from  w  w w.  ja  va 2s .co m
 * @param registration
 * @throws Exception
 */
private void pull(FederationModel registration) throws Exception {
    Map<String, RepositoryModel> repositories = FederationUtils.getRepositories(registration, true);
    String registrationFolder = registration.folder.toLowerCase().trim();
    // confirm valid characters in server alias
    Character c = StringUtils.findInvalidCharacter(registrationFolder);
    if (c != null) {
        logger.error(MessageFormat.format(
                "Illegal character ''{0}'' in folder name ''{1}'' of federation registration {2}!", c,
                registrationFolder, registration.name));
        return;
    }
    File repositoriesFolder = new File(GitBlit.getString(Keys.git.repositoriesFolder, "git"));
    File registrationFolderFile = new File(repositoriesFolder, registrationFolder);
    registrationFolderFile.mkdirs();

    // Clone/Pull the repository
    for (Map.Entry<String, RepositoryModel> entry : repositories.entrySet()) {
        String cloneUrl = entry.getKey();
        RepositoryModel repository = entry.getValue();
        if (!repository.hasCommits) {
            logger.warn(MessageFormat.format(
                    "Skipping federated repository {0} from {1} @ {2}. Repository is EMPTY.", repository.name,
                    registration.name, registration.url));
            registration.updateStatus(repository, FederationPullStatus.SKIPPED);
            continue;
        }

        // Determine local repository name
        String repositoryName;
        if (StringUtils.isEmpty(registrationFolder)) {
            repositoryName = repository.name;
        } else {
            repositoryName = registrationFolder + "/" + repository.name;
        }

        if (registration.bare) {
            // bare repository, ensure .git suffix
            if (!repositoryName.toLowerCase().endsWith(DOT_GIT_EXT)) {
                repositoryName += DOT_GIT_EXT;
            }
        } else {
            // normal repository, strip .git suffix
            if (repositoryName.toLowerCase().endsWith(DOT_GIT_EXT)) {
                repositoryName = repositoryName.substring(0, repositoryName.indexOf(DOT_GIT_EXT));
            }
        }

        // confirm that the origin of any pre-existing repository matches
        // the clone url
        String fetchHead = null;
        Repository existingRepository = GitBlit.self().getRepository(repositoryName);
        if (existingRepository != null) {
            StoredConfig config = existingRepository.getConfig();
            config.load();
            String origin = config.getString("remote", "origin", "url");
            RevCommit commit = JGitUtils.getCommit(existingRepository,
                    org.eclipse.jgit.lib.Constants.FETCH_HEAD);
            if (commit != null) {
                fetchHead = commit.getName();
            }
            existingRepository.close();
            if (!origin.startsWith(registration.url)) {
                logger.warn(MessageFormat.format(
                        "Skipping federated repository {0} from {1} @ {2}. Origin does not match, consider EXCLUDING.",
                        repository.name, registration.name, registration.url));
                registration.updateStatus(repository, FederationPullStatus.SKIPPED);
                continue;
            }
        }

        // clone/pull this repository
        CredentialsProvider credentials = new UsernamePasswordCredentialsProvider(Constants.FEDERATION_USER,
                registration.token);
        logger.info(MessageFormat.format("Pulling federated repository {0} from {1} @ {2}", repository.name,
                registration.name, registration.url));

        CloneResult result = JGitUtils.cloneRepository(registrationFolderFile, repository.name, cloneUrl,
                registration.bare, credentials);
        Repository r = GitBlit.self().getRepository(repositoryName);
        RepositoryModel rm = GitBlit.self().getRepositoryModel(repositoryName);
        repository.isFrozen = registration.mirror;
        if (result.createdRepository) {
            // default local settings
            repository.federationStrategy = FederationStrategy.EXCLUDE;
            repository.isFrozen = registration.mirror;
            repository.showRemoteBranches = !registration.mirror;
            logger.info(MessageFormat.format("     cloning {0}", repository.name));
            registration.updateStatus(repository, FederationPullStatus.MIRRORED);
        } else {
            // fetch and update
            boolean fetched = false;
            RevCommit commit = JGitUtils.getCommit(r, org.eclipse.jgit.lib.Constants.FETCH_HEAD);
            String newFetchHead = commit.getName();
            fetched = fetchHead == null || !fetchHead.equals(newFetchHead);

            if (registration.mirror) {
                // mirror
                if (fetched) {
                    // update local branches to match the remote tracking branches
                    for (RefModel ref : JGitUtils.getRemoteBranches(r, false, -1)) {
                        if (ref.displayName.startsWith("origin/")) {
                            String branch = org.eclipse.jgit.lib.Constants.R_HEADS
                                    + ref.displayName.substring(ref.displayName.indexOf('/') + 1);
                            String hash = ref.getReferencedObjectId().getName();

                            JGitUtils.setBranchRef(r, branch, hash);
                            logger.info(MessageFormat.format("     resetting {0} of {1} to {2}", branch,
                                    repository.name, hash));
                        }
                    }

                    String newHead;
                    if (StringUtils.isEmpty(repository.HEAD)) {
                        newHead = newFetchHead;
                    } else {
                        newHead = repository.HEAD;
                    }
                    JGitUtils.setHEADtoRef(r, newHead);
                    logger.info(MessageFormat.format("     resetting HEAD of {0} to {1}", repository.name,
                            newHead));
                    registration.updateStatus(repository, FederationPullStatus.MIRRORED);
                } else {
                    // indicate no commits pulled
                    registration.updateStatus(repository, FederationPullStatus.NOCHANGE);
                }
            } else {
                // non-mirror
                if (fetched) {
                    // indicate commits pulled to origin/master
                    registration.updateStatus(repository, FederationPullStatus.PULLED);
                } else {
                    // indicate no commits pulled
                    registration.updateStatus(repository, FederationPullStatus.NOCHANGE);
                }
            }

            // preserve local settings
            repository.isFrozen = rm.isFrozen;
            repository.federationStrategy = rm.federationStrategy;

            // merge federation sets
            Set<String> federationSets = new HashSet<String>();
            if (rm.federationSets != null) {
                federationSets.addAll(rm.federationSets);
            }
            if (repository.federationSets != null) {
                federationSets.addAll(repository.federationSets);
            }
            repository.federationSets = new ArrayList<String>(federationSets);

            // merge indexed branches
            Set<String> indexedBranches = new HashSet<String>();
            if (rm.indexedBranches != null) {
                indexedBranches.addAll(rm.indexedBranches);
            }
            if (repository.indexedBranches != null) {
                indexedBranches.addAll(repository.indexedBranches);
            }
            repository.indexedBranches = new ArrayList<String>(indexedBranches);

        }
        // only repositories that are actually _cloned_ from the origin
        // Gitblit repository are marked as federated. If the origin
        // is from somewhere else, these repositories are not considered
        // "federated" repositories.
        repository.isFederated = cloneUrl.startsWith(registration.url);

        GitBlit.self().updateConfiguration(r, repository);
        r.close();
    }

    IUserService userService = null;

    try {
        // Pull USERS
        // TeamModels are automatically pulled because they are contained
        // within the UserModel. The UserService creates unknown teams
        // and updates existing teams.
        Collection<UserModel> users = FederationUtils.getUsers(registration);
        if (users != null && users.size() > 0) {
            File realmFile = new File(registrationFolderFile, registration.name + "_users.conf");
            realmFile.delete();
            userService = new ConfigUserService(realmFile);
            for (UserModel user : users) {
                userService.updateUserModel(user.username, user);

                // merge the origin permissions and origin accounts into
                // the user accounts of this Gitblit instance
                if (registration.mergeAccounts) {
                    // reparent all repository permissions if the local
                    // repositories are stored within subfolders
                    if (!StringUtils.isEmpty(registrationFolder)) {
                        List<String> permissions = new ArrayList<String>(user.repositories);
                        user.repositories.clear();
                        for (String permission : permissions) {
                            user.addRepository(registrationFolder + "/" + permission);
                        }
                    }

                    // insert new user or update local user
                    UserModel localUser = GitBlit.self().getUserModel(user.username);
                    if (localUser == null) {
                        // create new local user
                        GitBlit.self().updateUserModel(user.username, user, true);
                    } else {
                        // update repository permissions of local user
                        for (String repository : user.repositories) {
                            localUser.addRepository(repository);
                        }
                        localUser.password = user.password;
                        localUser.canAdmin = user.canAdmin;
                        GitBlit.self().updateUserModel(localUser.username, localUser, false);
                    }

                    for (String teamname : GitBlit.self().getAllTeamnames()) {
                        TeamModel team = GitBlit.self().getTeamModel(teamname);
                        if (user.isTeamMember(teamname) && !team.hasUser(user.username)) {
                            // new team member
                            team.addUser(user.username);
                            GitBlit.self().updateTeamModel(teamname, team, false);
                        } else if (!user.isTeamMember(teamname) && team.hasUser(user.username)) {
                            // remove team member
                            team.removeUser(user.username);
                            GitBlit.self().updateTeamModel(teamname, team, false);
                        }

                        // update team repositories
                        TeamModel remoteTeam = user.getTeam(teamname);
                        if (remoteTeam != null && !ArrayUtils.isEmpty(remoteTeam.repositories)) {
                            int before = team.repositories.size();
                            team.addRepositories(remoteTeam.repositories);
                            int after = team.repositories.size();
                            if (after > before) {
                                // repository count changed, update
                                GitBlit.self().updateTeamModel(teamname, team, false);
                            }
                        }
                    }
                }
            }
        }
    } catch (ForbiddenException e) {
        // ignore forbidden exceptions
    } catch (IOException e) {
        logger.warn(MessageFormat.format("Failed to retrieve USERS from federated gitblit ({0} @ {1})",
                registration.name, registration.url), e);
    }

    try {
        // Pull TEAMS
        // We explicitly pull these even though they are embedded in
        // UserModels because it is possible to use teams to specify
        // mailing lists or push scripts without specifying users.
        if (userService != null) {
            Collection<TeamModel> teams = FederationUtils.getTeams(registration);
            if (teams != null && teams.size() > 0) {
                for (TeamModel team : teams) {
                    userService.updateTeamModel(team);
                }
            }
        }
    } catch (ForbiddenException e) {
        // ignore forbidden exceptions
    } catch (IOException e) {
        logger.warn(MessageFormat.format("Failed to retrieve TEAMS from federated gitblit ({0} @ {1})",
                registration.name, registration.url), e);
    }

    try {
        // Pull SETTINGS
        Map<String, String> settings = FederationUtils.getSettings(registration);
        if (settings != null && settings.size() > 0) {
            Properties properties = new Properties();
            properties.putAll(settings);
            FileOutputStream os = new FileOutputStream(
                    new File(registrationFolderFile, registration.name + "_" + Constants.PROPERTIES_FILE));
            properties.store(os, null);
            os.close();
        }
    } catch (ForbiddenException e) {
        // ignore forbidden exceptions
    } catch (IOException e) {
        logger.warn(MessageFormat.format("Failed to retrieve SETTINGS from federated gitblit ({0} @ {1})",
                registration.name, registration.url), e);
    }

    try {
        // Pull SCRIPTS
        Map<String, String> scripts = FederationUtils.getScripts(registration);
        if (scripts != null && scripts.size() > 0) {
            for (Map.Entry<String, String> script : scripts.entrySet()) {
                String scriptName = script.getKey();
                if (scriptName.endsWith(".groovy")) {
                    scriptName = scriptName.substring(0, scriptName.indexOf(".groovy"));
                }
                File file = new File(registrationFolderFile, registration.name + "_" + scriptName + ".groovy");
                FileUtils.writeContent(file, script.getValue());
            }
        }
    } catch (ForbiddenException e) {
        // ignore forbidden exceptions
    } catch (IOException e) {
        logger.warn(MessageFormat.format("Failed to retrieve SCRIPTS from federated gitblit ({0} @ {1})",
                registration.name, registration.url), e);
    }
}

From source file:com.gitblit.git.GitDaemonService.java

License:Eclipse Distribution License

private boolean isEnabledFor(final Repository db) {
    if (isOverridable())
        return db.getConfig().get(configKey).enabled;
    return isEnabled();
}

From source file:com.gitblit.GitBlit.java

License:Apache License

/**
 * Workaround JGit.  I need to access the raw config object directly in order
 * to see if the config is dirty so that I can reload a repository model.
 * If I use the stock JGit method to get the config it already reloads the
 * config.  If the config changes are made within Gitblit this is fine as
 * the returned config will still be flagged as dirty.  BUT... if the config
 * is manipulated outside Gitblit then it fails to recognize this as dirty.
 *  // ww  w. j  a  v  a 2  s  .c  o  m
 * @param r
 * @return a config
 */
private StoredConfig getRepositoryConfig(Repository r) {
    try {
        Field f = r.getClass().getDeclaredField("repoConfig");
        f.setAccessible(true);
        StoredConfig config = (StoredConfig) f.get(r);
        return config;
    } catch (Exception e) {
        logger.error("Failed to retrieve \"repoConfig\" via reflection", e);
    }
    return r.getConfig();
}

From source file:com.gitblit.GitBlit.java

License:Apache License

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

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

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

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

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

From source file:com.gitblit.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  .  j  a  v a2 s .  com
 * 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.
 * //from w  ww .j av  a2 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//ww w. ja v  a2 s.  com
 * @return a repositoryModel or null if the repository does not exist
 */
private RepositoryModel loadRepositoryModel(String repositoryName) {
    Repository r = getRepository(repositoryName);
    if (r == null) {
        return null;
    }
    RepositoryModel model = new RepositoryModel();
    model.isBare = r.isBare();
    File basePath = getRepositoriesFolder();
    if (model.isBare) {
        model.name = com.gitblit.utils.FileUtils.getRelativePath(basePath, r.getDirectory());
    } else {
        model.name = com.gitblit.utils.FileUtils.getRelativePath(basePath, r.getDirectory().getParentFile());
    }
    if (StringUtils.isEmpty(model.name)) {
        // Repository is NOT located relative to the base folder because it
        // is symlinked.  Use the provided repository name.
        model.name = repositoryName;
    }
    model.projectPath = StringUtils.getFirstPathElement(repositoryName);

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

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

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

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

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