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

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

Introduction

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

Prototype

public abstract void load() throws IOException, ConfigInvalidException;

Source Link

Document

Load the configuration from the persistent store.

Usage

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

License:Open Source License

public static String getUserId(Repository repository) {
    StoredConfig config;
    if (repository == null) {
        if (StringUtils.isEmptyOrNull(SystemReader.getInstance().getenv(Constants.GIT_CONFIG_NOSYSTEM_KEY))) {
            config = SystemReader.getInstance().openSystemConfig(null, FS.DETECTED);
        } else {/*from  w  ww  .  j  a  va  2  s. co m*/
            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.gitblit.AddIndexedBranch.java

License:Apache License

public static void main(String... args) {
    Params params = new Params();
    CmdLineParser parser = new CmdLineParser(params);
    try {//from   w w  w.j  a  v a  2s .c  om
        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.ConfigUserService.java

License:Apache License

/**
 * Reads the realm file and rebuilds the in-memory lookup tables.
 *//*from w  w  w. ja  v  a2s  .  c om*/
protected synchronized void read() {
    if (realmFile.exists() && (forceReload || (realmFile.lastModified() != lastModified))) {
        forceReload = false;
        lastModified = realmFile.lastModified();
        users.clear();
        cookies.clear();
        teams.clear();

        try {
            StoredConfig config = new FileBasedConfig(realmFile, FS.detect());
            config.load();
            Set<String> usernames = config.getSubsections(USER);
            for (String username : usernames) {
                UserModel user = new UserModel(username.toLowerCase());
                user.password = config.getString(USER, username, PASSWORD);
                user.displayName = config.getString(USER, username, DISPLAYNAME);
                user.emailAddress = config.getString(USER, username, EMAILADDRESS);
                user.accountType = AccountType.fromString(config.getString(USER, username, ACCOUNTTYPE));
                user.disabled = config.getBoolean(USER, username, DISABLED, false);
                user.organizationalUnit = config.getString(USER, username, ORGANIZATIONALUNIT);
                user.organization = config.getString(USER, username, ORGANIZATION);
                user.locality = config.getString(USER, username, LOCALITY);
                user.stateProvince = config.getString(USER, username, STATEPROVINCE);
                user.countryCode = config.getString(USER, username, COUNTRYCODE);
                user.cookie = config.getString(USER, username, COOKIE);
                if (StringUtils.isEmpty(user.cookie) && !StringUtils.isEmpty(user.password)) {
                    user.cookie = user.createCookie();
                }

                // preferences
                user.getPreferences().setLocale(config.getString(USER, username, LOCALE));
                user.getPreferences().setEmailMeOnMyTicketChanges(
                        config.getBoolean(USER, username, EMAILONMYTICKETCHANGES, true));
                user.getPreferences()
                        .setTransport(Transport.fromString(config.getString(USER, username, TRANSPORT)));

                // user roles
                Set<String> roles = new HashSet<String>(
                        Arrays.asList(config.getStringList(USER, username, ROLE)));
                user.canAdmin = roles.contains(Role.ADMIN.getRole());
                user.canFork = roles.contains(Role.FORK.getRole());
                user.canCreate = roles.contains(Role.CREATE.getRole());
                user.excludeFromFederation = roles.contains(Role.NOT_FEDERATED.getRole());

                // repository memberships
                if (!user.canAdmin) {
                    // non-admin, read permissions
                    Set<String> repositories = new HashSet<String>(
                            Arrays.asList(config.getStringList(USER, username, REPOSITORY)));
                    for (String repository : repositories) {
                        user.addRepositoryPermission(repository);
                    }
                }

                // starred repositories
                Set<String> starred = new HashSet<String>(
                        Arrays.asList(config.getStringList(USER, username, STARRED)));
                for (String repository : starred) {
                    UserRepositoryPreferences prefs = user.getPreferences()
                            .getRepositoryPreferences(repository);
                    prefs.starred = true;
                }

                // update cache
                users.put(user.username, user);
                if (!StringUtils.isEmpty(user.cookie)) {
                    cookies.put(user.cookie, user);
                }
            }

            // load the teams
            Set<String> teamnames = config.getSubsections(TEAM);
            for (String teamname : teamnames) {
                TeamModel team = new TeamModel(teamname);
                Set<String> roles = new HashSet<String>(
                        Arrays.asList(config.getStringList(TEAM, teamname, ROLE)));
                team.canAdmin = roles.contains(Role.ADMIN.getRole());
                team.canFork = roles.contains(Role.FORK.getRole());
                team.canCreate = roles.contains(Role.CREATE.getRole());
                team.accountType = AccountType.fromString(config.getString(TEAM, teamname, ACCOUNTTYPE));

                if (!team.canAdmin) {
                    // non-admin team, read permissions
                    team.addRepositoryPermissions(
                            Arrays.asList(config.getStringList(TEAM, teamname, REPOSITORY)));
                }
                team.addUsers(Arrays.asList(config.getStringList(TEAM, teamname, USER)));
                team.addMailingLists(Arrays.asList(config.getStringList(TEAM, teamname, MAILINGLIST)));
                team.preReceiveScripts.addAll(Arrays.asList(config.getStringList(TEAM, teamname, PRERECEIVE)));
                team.postReceiveScripts
                        .addAll(Arrays.asList(config.getStringList(TEAM, teamname, POSTRECEIVE)));

                teams.put(team.name.toLowerCase(), team);

                // set the teams on the users
                for (String user : team.users) {
                    UserModel model = users.get(user);
                    if (model != null) {
                        model.teams.add(team);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(MessageFormat.format("Failed to read {0}", realmFile), e);
        }
    }
}

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.
 * //w ww .j  a  va2  s  .  c om
 * @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.utils.JGitUtils.java

License:Apache License

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

From source file:com.google.gitiles.DefaultAccess.java

License:Open Source License

private String loadDescriptionText(Repository repo) throws IOException {
    String desc = null;//from w w w  .ja v  a  2 s .c  om
    StoredConfig config = repo.getConfig();
    IOException configError = null;
    try {
        config.load();
        desc = config.getString("gitweb", null, "description");
    } catch (ConfigInvalidException e) {
        configError = new IOException(e);
    }
    if (desc == null) {
        File descFile = new File(repo.getDirectory(), "description");
        if (descFile.exists()) {
            desc = new String(IO.readFully(descFile));
        } else if (configError != null) {
            throw configError;
        }
    }
    return desc;
}

From source file:griffon.plugins.git.GitManager.java

License:Apache License

private PersonIdent personIdentFor(String key) {
    String name = (String) getConfigValue("git." + key + ".name", null);
    String email = (String) getConfigValue("git." + key + ".email", null);
    if (isBlank(name) || isBlank(email)) {
        try {// w w  w  . j  av  a 2  s . co  m
            StoredConfig storedConfig = git().getRepository().getConfig();
            storedConfig.load();
            name = storedConfig.getString("user", null, "name");
            email = storedConfig.getString("user", null, "email");
        } catch (IOException e) {
            // ignore
        } catch (ConfigInvalidException e) {
            // ignore
        }
    }

    if (!isBlank(name) && !isBlank(email)) {
        return new PersonIdent(name, email);
    }

    return null;
}

From source file:net.polydawn.mdm.commands.MdmAddCommand.java

License:Open Source License

public MdmExitMessage call() throws ConfigInvalidException, IOException, MdmException {
    assertInRepoRoot();//from  w w w . ja v a 2s.co  m

    // load other config (so we can error early on in case there's a problem)
    StoredConfig gitmodulesCfg = new FileBasedConfig(new File(repo.getWorkTree(), Constants.DOT_GIT_MODULES),
            repo.getFS());
    try {
        gitmodulesCfg.load();
    } catch (ConfigInvalidException e) {
        throw new MdmExitInvalidConfig(Constants.DOT_GIT_MODULES);
    }

    // git's behavior of assuming relative urls should be relative to the remote origin instead of relative to the local filesystem is almost certainly not what you want.
    if (url.startsWith("../") || url.startsWith("./"))
        os.println(
                "hey, heads up: when you use a relative url to describe a submodule location, git assumes it's relative to the remote origin of the parent project (NOT relative to the project location on the local filesystem, which is what you might have expected).  this... works, but it's not recommended because of the potential it has to surprise.");

    // give a look at the remote url and see what versions are physically available.
    List<String> versions = fetchVersions();
    if (versions.size() == 0)
        throw new MdmExitMessage(":(",
                "no releases could be found at the url you gave for a releases repository -- it doesn't look like releases that mdm understands are there.\nare you sure this is the releases repo?  keep in mind that the release repo and the source repo isn't the same for most projects -- check the project readme for the location of their release repo.");

    // if we didn't get a name argument yet, prompt for one.
    // note that this is *after* we tried to check that something at least exists on the far side of the url, in order to minimize bother.
    if (name == null)
        name = inputPrompt(os, "dependency name: ");

    File path = new File(pathLibs, name);

    // check for presence of other crap here already.  (`git submodule add` will also do this, but it's a more pleasant user experience to check this before popping up a prompt for version name.)
    if (path.exists())
        throw new MdmExitMessage(":'(", "there are already files at " + path
                + " !\nWe can't pull down a dependency there until this conflict is cleared away.");
    if (SubmoduleWalk.forIndex(repo).setFilter(PathFilter.create(path.getPath())).next())
        throw new MdmExitMessage(":'(", "there is already a submodule in the git index at " + path
                + " !\nWe can't pull down a dependency there until this conflict is cleared away.");

    // if a specific version name was given, we'll just go straight at it; otherwise we present options interactively from the manifest of versions the remote reported.
    if (version == null)
        version = Loco.promptForVersion(os, versions);

    // check yourself before you wreck yourself
    if (!versions.contains(version))
        throw new MdmExitMessage(":(",
                "no version labelled " + version + " available from the provided remote url.");

    // finally, let's actually do the submodule/dependency adding
    doSubmoduleConfig(gitmodulesCfg, path);
    gitmodulesCfg.save();
    doSubmoduleFetch(path, gitmodulesCfg);

    // commit the changes
    doGitStage(path);
    doGitCommit(path);

    return new MdmExitMessage(":D", "added dependency on " + name + "-" + version + " successfully!");
}

From source file:net.polydawn.mdm.commands.MdmAlterCommand.java

License:Open Source License

public MdmExitMessage call() throws ConfigInvalidException, IOException, MdmException {
    try {/*from   ww  w.  j a v a2 s. co m*/
        assertInRepoRoot();
    } catch (MdmExitMessage e) {
        return e;
    }

    // touch up args a tad.  tab completion in the terminal tends to suggest *almost* what you want, but with a trailing slash because it's a directory, and git doesn't like that slash.  so, we'll sand down that sharp corner a bit.
    String name = args.getString("name");
    if (name.endsWith("/"))
        name = name.substring(0, name.length() - 1);

    // load current module state
    StoredConfig gitmodulesCfg = new FileBasedConfig(new File(repo.getWorkTree(), Constants.DOT_GIT_MODULES),
            repo.getFS());
    try {
        gitmodulesCfg.load();
    } catch (ConfigInvalidException e) {
        throw new MdmExitInvalidConfig(Constants.DOT_GIT_MODULES);
    }
    MdmModuleDependency module;
    try {
        module = MdmModuleDependency.load(repo, name, gitmodulesCfg);
    } catch (MdmModuleTypeException e) {
        return new MdmExitMessage(":(", "there is no mdm dependency by that name.");
    }

    // give a look at the remote path and see what versions are physically available.
    List<String> versions;
    try {
        //XXX: here the triplicate-and-then-some configuration is a tanglefuck again.  do we use the origin, or the url in the submodule config, or the url that's initialized in the parent .git/config, or the url in the .gitmodules file, or some complicated fallback pattern that covers all of them, or initialize the ones that aren't yet, or...??  Original mdm took the value from .gitmodules, which is the least likely to be uninitialized, but also not the most correct.
        if (module.getRepo() == null)
            versions = Plumbing.getVersionManifest(repo, module.getUrlHistoric());
        else
            versions = Plumbing.getVersionManifest(module.getRepo(), "origin");
    } catch (InvalidRemoteException e) {
        return new MdmExitMessage(":(",
                "the submodule remote origin url isn't initialized.  maybe run `mdm update` first so there's something in place before we alter?");
    } catch (TransportException e) {
        return new MdmExitMessage(":'(",
                "transport failed!  check that the submodule remote origin url is correct and reachable and try again?\n  (error message: "
                        + e.getMessage() + ")");
    } catch (GitAPIException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    }
    if (versions.size() == 0)
        return new MdmExitMessage(":(",
                "no releases could be found at the submodule remote origin url -- it doesn't look like releases that mdm understands are there.\ncheck the origin url in the submodule's config.  if this url worked in the past, maybe the project maintainers moved their releases repo?");

    // if a specific version name was given, we'll just go straight at it; otherwise we present options interactively from the manifest of versions the remote reported.
    String version;
    if (args.getString("version") != null) {
        version = args.getString("version");
        if (!versions.contains(version))
            return new MdmExitMessage(":(",
                    "no version labelled " + version + " available from the provided remote url.");
    } else {
        version = Loco.promptForVersion(os, versions);
    }

    // if you specify the version you already had, okay, we'll just put our tools down.
    if (module.getVersionName().equals(version))
        return new MdmExitMessage(":I", "that version is already specified!  no changes made.");

    // do the submodule/dependency dancing
    gitmodulesCfg.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, module.getHandle(),
            MdmConfigConstants.Module.DEPENDENCY_VERSION.toString(), version);
    module = MdmModuleDependency.load(repo, module.getPath(), gitmodulesCfg); // reload the MdmModule completely because it's not yet implmented intelligently enough to be able to refresh a bunch of its cached state
    Plumbing.fetch(repo, module);
    gitmodulesCfg.save(); // don't do this save until after the fetch: if the fetch blows up, it's better that we don't have this mutated, because that leaves you with slightly stranger output from your next `mdm status` query.

    // commit the changes
    try {
        new Git(repo).add().addFilepattern(module.getPath()).addFilepattern(Constants.DOT_GIT_MODULES).call();
    } catch (NoFilepatternException e) {
        throw new MajorBug(e); // why would an api throw exceptions like this *checked*?
    } catch (GitAPIException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    }
    try {
        new Git(repo).commit().setOnly(module.getPath()).setOnly(Constants.DOT_GIT_MODULES)
                .setMessage("shifting dependency on " + name + " to version " + version + ".").call();
    } catch (NoHeadException e) {
        throw new MdmException("your repository is in an invalid state!", e);
    } catch (NoMessageException e) {
        throw new MajorBug(e); // why would an api throw exceptions like this *checked*?
    } catch (UnmergedPathsException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    } catch (ConcurrentRefUpdateException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    } catch (WrongRepositoryStateException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    } catch (GitAPIException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    }

    return new MdmExitMessage(":D",
            "altered dependency on " + name + " to version " + version + " successfully!");
}

From source file:net.polydawn.mdm.commands.MdmReleaseInitCommand.java

License:Open Source License

/**
 * Writes a new submodule block to the parentRepo's .gitmodules file declaring the
 * release repo, and initializes the local .git/config file to match.
 *
 * @param parentRepo/*ww  w.  j ava 2  s .  co  m*/
 * @throws IOException
 * @throws ConfigInvalidException
 */
void writeParentGitmoduleConfig(Repository parentRepo) throws IOException, ConfigInvalidException {
    // write gitmodule config for the new submodule
    StoredConfig gitmodulesCfg = new FileBasedConfig(
            new File(parentRepo.getWorkTree(), Constants.DOT_GIT_MODULES), parentRepo.getFS());
    gitmodulesCfg.load();
    gitmodulesCfg.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.CONFIG_KEY_PATH,
            path);
    gitmodulesCfg.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.CONFIG_KEY_URL,
            remotePublicUrl);
    gitmodulesCfg.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path,
            MdmConfigConstants.Module.MODULE_TYPE.toString(), MdmModuleType.RELEASES.toString());
    gitmodulesCfg.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.CONFIG_KEY_UPDATE,
            "none");
    gitmodulesCfg.save();

    // initialize local parent repo config for the submodule
    MdmModuleRelease module = MdmModuleRelease.load(parentRepo, path, gitmodulesCfg);
    Plumbing.initLocalConfig(parentRepo, module);
    parentRepo.getConfig().save();
}