Search in sources :

Example 21 with StoredConfig

use of org.eclipse.jgit.lib.StoredConfig in project gitiles by GerritCodeReview.

the class DefaultAccess method loadDescriptionText.

private String loadDescriptionText(Repository repo) throws IOException {
    String desc = null;
    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));
            if (DEFAULT_DESCRIPTION.equals(CharMatcher.whitespace().trimFrom(desc))) {
                desc = null;
            }
        } else if (configError != null) {
            throw configError;
        }
    }
    return desc;
}
Also used : StoredConfig(org.eclipse.jgit.lib.StoredConfig) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) IOException(java.io.IOException) File(java.io.File)

Example 22 with StoredConfig

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

the class GitblitManager method saveSizeAndPosition.

private void saveSizeAndPosition() {
    try {
        // save window size and position
        StoredConfig config = getConfig();
        Dimension sz = GitblitManager.this.getSize();
        config.setString("ui", null, "size", MessageFormat.format("{0,number,0}x{1,number,0}", sz.width, sz.height));
        Point pos = GitblitManager.this.getLocationOnScreen();
        config.setString("ui", null, "position", MessageFormat.format("{0,number,0},{1,number,0}", pos.x, pos.y));
        config.save();
    } catch (Throwable t) {
        Utils.showException(GitblitManager.this, t);
    }
}
Also used : StoredConfig(org.eclipse.jgit.lib.StoredConfig) Dimension(java.awt.Dimension) Point(java.awt.Point)

Example 23 with StoredConfig

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

the class JGitConnection method remoteUpdate.

@Override
public void remoteUpdate(RemoteUpdateParams params) throws GitException {
    String remoteName = params.getName();
    if (isNullOrEmpty(remoteName)) {
        throw new GitException(ERROR_UPDATE_REMOTE_NAME_MISSING);
    }
    StoredConfig config = repository.getConfig();
    Set<String> remoteNames = config.getSubsections(ConfigConstants.CONFIG_KEY_REMOTE);
    if (!remoteNames.contains(remoteName)) {
        throw new GitException("Remote " + remoteName + " not found. ");
    }
    RemoteConfig remoteConfig;
    try {
        remoteConfig = new RemoteConfig(config, remoteName);
    } catch (URISyntaxException e) {
        throw new GitException(e.getMessage(), e);
    }
    List<String> branches = params.getBranches();
    if (!branches.isEmpty()) {
        if (!params.isAddBranches()) {
            remoteConfig.setFetchRefSpecs(Collections.emptyList());
            remoteConfig.setPushRefSpecs(Collections.emptyList());
        } else {
            // Replace wildcard refSpec if any.
            remoteConfig.removeFetchRefSpec(new RefSpec(Constants.R_HEADS + "*" + ":" + Constants.R_REMOTES + remoteName + "/*").setForceUpdate(true));
            remoteConfig.removeFetchRefSpec(new RefSpec(Constants.R_HEADS + "*" + ":" + Constants.R_REMOTES + remoteName + "/*"));
        }
        // Add new refSpec.
        for (String branch : branches) {
            remoteConfig.addFetchRefSpec(new RefSpec(Constants.R_HEADS + branch + ":" + Constants.R_REMOTES + remoteName + "/" + branch).setForceUpdate(true));
        }
    }
    // Remove URLs first.
    for (String url : params.getRemoveUrl()) {
        try {
            remoteConfig.removeURI(new URIish(url));
        } catch (URISyntaxException e) {
            LOG.debug(ERROR_UPDATE_REMOTE_REMOVE_INVALID_URL);
        }
    }
    // Add new URLs.
    for (String url : params.getAddUrl()) {
        try {
            remoteConfig.addURI(new URIish(url));
        } catch (URISyntaxException e) {
            throw new GitException("Remote url " + url + " is invalid. ");
        }
    }
    // Remove URLs for pushing.
    for (String url : params.getRemovePushUrl()) {
        try {
            remoteConfig.removePushURI(new URIish(url));
        } catch (URISyntaxException e) {
            LOG.debug(ERROR_UPDATE_REMOTE_REMOVE_INVALID_URL);
        }
    }
    // Add URLs for pushing.
    for (String url : params.getAddPushUrl()) {
        try {
            remoteConfig.addPushURI(new URIish(url));
        } catch (URISyntaxException e) {
            throw new GitException("Remote push url " + url + " is invalid. ");
        }
    }
    remoteConfig.update(config);
    try {
        config.save();
    } catch (IOException exception) {
        throw new GitException(exception.getMessage(), exception);
    }
}
Also used : StoredConfig(org.eclipse.jgit.lib.StoredConfig) URIish(org.eclipse.jgit.transport.URIish) RefSpec(org.eclipse.jgit.transport.RefSpec) GitException(org.eclipse.che.api.git.exception.GitException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) RemoteConfig(org.eclipse.jgit.transport.RemoteConfig)

Example 24 with StoredConfig

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

the class JGitConnection method clone.

public void clone(CloneParams params) throws GitException, UnauthorizedException {
    String remoteUri = params.getRemoteUrl();
    boolean removeIfFailed = false;
    try {
        if (params.getRemoteName() == null) {
            params.setRemoteName(Constants.DEFAULT_REMOTE_NAME);
        }
        if (params.getWorkingDir() == null) {
            params.setWorkingDir(repository.getWorkTree().getCanonicalPath());
        }
        // If clone fails and the .git folder didn't exist we want to remove it.
        // We have to do this here because the clone command doesn't revert its own changes in case of failure.
        removeIfFailed = !repository.getDirectory().exists();
        CloneCommand cloneCommand = Git.cloneRepository().setDirectory(new File(params.getWorkingDir())).setRemote(params.getRemoteName()).setCloneSubmodules(params.isRecursive()).setURI(remoteUri);
        if (params.getBranchesToFetch().isEmpty()) {
            cloneCommand.setCloneAllBranches(true);
        } else {
            cloneCommand.setBranchesToClone(params.getBranchesToFetch());
        }
        LineConsumer lineConsumer = lineConsumerFactory.newLineConsumer();
        cloneCommand.setProgressMonitor(new BatchingProgressMonitor() {

            @Override
            protected void onUpdate(String taskName, int workCurr) {
                try {
                    lineConsumer.writeLine(taskName + ": " + workCurr + " completed");
                } catch (IOException exception) {
                    LOG.error(exception.getMessage(), exception);
                }
            }

            @Override
            protected void onEndTask(String taskName, int workCurr) {
            }

            @Override
            protected void onUpdate(String taskName, int workCurr, int workTotal, int percentDone) {
                try {
                    lineConsumer.writeLine(taskName + ": " + workCurr + " of " + workTotal + " completed, " + percentDone + "% done");
                } catch (IOException exception) {
                    LOG.error(exception.getMessage(), exception);
                }
            }

            @Override
            protected void onEndTask(String taskName, int workCurr, int workTotal, int percentDone) {
            }
        });
        ((Git) executeRemoteCommand(remoteUri, cloneCommand, params.getUsername(), params.getPassword())).close();
        StoredConfig repositoryConfig = getRepository().getConfig();
        GitUser gitUser = getUser();
        if (gitUser != null) {
            repositoryConfig.setString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_NAME, gitUser.getName());
            repositoryConfig.setString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_EMAIL, gitUser.getEmail());
        }
        repositoryConfig.save();
    } catch (IOException | GitAPIException exception) {
        // Delete .git directory in case it was created
        if (removeIfFailed) {
            deleteRepositoryFolder();
        }
        //try to clone repository by replacing http to https in the url if HTTP 301 redirect happened
        if (exception.getMessage().contains(": 301 Moved Permanently")) {
            remoteUri = "https" + remoteUri.substring(4);
            try {
                clone(params.withRemoteUrl(remoteUri));
            } catch (UnauthorizedException | GitException e) {
                throw new GitException("Failed to clone the repository", e);
            }
            return;
        }
        String message = generateExceptionMessage(exception);
        throw new GitException(message, exception);
    }
}
Also used : CloneCommand(org.eclipse.jgit.api.CloneCommand) GitException(org.eclipse.che.api.git.exception.GitException) IOException(java.io.IOException) GitUser(org.eclipse.che.api.git.shared.GitUser) StoredConfig(org.eclipse.jgit.lib.StoredConfig) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) LineConsumer(org.eclipse.che.api.core.util.LineConsumer) Git(org.eclipse.jgit.api.Git) BatchingProgressMonitor(org.eclipse.jgit.lib.BatchingProgressMonitor) DiffCommitFile(org.eclipse.che.api.git.shared.DiffCommitFile) File(java.io.File)

Example 25 with StoredConfig

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

the class ConfigUserService method read.

/**
	 * Reads the realm file and rebuilds the in-memory lookup tables.
	 */
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);
        }
    }
}
Also used : StoredConfig(org.eclipse.jgit.lib.StoredConfig) UserModel(com.gitblit.models.UserModel) TeamModel(com.gitblit.models.TeamModel) FileBasedConfig(org.eclipse.jgit.storage.file.FileBasedConfig) UserRepositoryPreferences(com.gitblit.models.UserRepositoryPreferences) IOException(java.io.IOException) HashSet(java.util.HashSet)

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