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

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

Introduction

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

Prototype

public void setBoolean(final String section, final String subsection, final String name, final boolean value) 

Source Link

Document

Add or modify a configuration value.

Usage

From source file:com.gitblit.ConfigUserService.java

License:Apache License

/**
 * Writes the properties file.//w ww.  jav a 2 s .  c o  m
 *
 * @throws IOException
 */
private synchronized void write() throws IOException {
    // Write a temporary copy of the users file
    File realmFileCopy = new File(realmFile.getAbsolutePath() + ".tmp");

    StoredConfig config = new FileBasedConfig(realmFileCopy, FS.detect());

    // write users
    for (UserModel model : users.values()) {
        if (!StringUtils.isEmpty(model.password)) {
            config.setString(USER, model.username, PASSWORD, model.password);
        }
        if (!StringUtils.isEmpty(model.cookie)) {
            config.setString(USER, model.username, COOKIE, model.cookie);
        }
        if (!StringUtils.isEmpty(model.displayName)) {
            config.setString(USER, model.username, DISPLAYNAME, model.displayName);
        }
        if (!StringUtils.isEmpty(model.emailAddress)) {
            config.setString(USER, model.username, EMAILADDRESS, model.emailAddress);
        }
        if (model.accountType != null) {
            config.setString(USER, model.username, ACCOUNTTYPE, model.accountType.name());
        }
        if (!StringUtils.isEmpty(model.organizationalUnit)) {
            config.setString(USER, model.username, ORGANIZATIONALUNIT, model.organizationalUnit);
        }
        if (!StringUtils.isEmpty(model.organization)) {
            config.setString(USER, model.username, ORGANIZATION, model.organization);
        }
        if (!StringUtils.isEmpty(model.locality)) {
            config.setString(USER, model.username, LOCALITY, model.locality);
        }
        if (!StringUtils.isEmpty(model.stateProvince)) {
            config.setString(USER, model.username, STATEPROVINCE, model.stateProvince);
        }
        if (!StringUtils.isEmpty(model.countryCode)) {
            config.setString(USER, model.username, COUNTRYCODE, model.countryCode);
        }
        if (model.disabled) {
            config.setBoolean(USER, model.username, DISABLED, true);
        }
        if (model.getPreferences() != null) {
            Locale locale = model.getPreferences().getLocale();
            if (locale != null) {
                String val;
                if (StringUtils.isEmpty(locale.getCountry())) {
                    val = locale.getLanguage();
                } else {
                    val = locale.getLanguage() + "_" + locale.getCountry();
                }
                config.setString(USER, model.username, LOCALE, val);
            }

            config.setBoolean(USER, model.username, EMAILONMYTICKETCHANGES,
                    model.getPreferences().isEmailMeOnMyTicketChanges());

            if (model.getPreferences().getTransport() != null) {
                config.setString(USER, model.username, TRANSPORT, model.getPreferences().getTransport().name());
            }
        }

        // user roles
        List<String> roles = new ArrayList<String>();
        if (model.canAdmin) {
            roles.add(Role.ADMIN.getRole());
        }
        if (model.canFork) {
            roles.add(Role.FORK.getRole());
        }
        if (model.canCreate) {
            roles.add(Role.CREATE.getRole());
        }
        if (model.excludeFromFederation) {
            roles.add(Role.NOT_FEDERATED.getRole());
        }
        if (roles.size() == 0) {
            // we do this to ensure that user record with no password
            // is written.  otherwise, StoredConfig optimizes that account
            // away. :(
            roles.add(Role.NONE.getRole());
        }
        config.setStringList(USER, model.username, ROLE, roles);

        // discrete repository permissions
        if (model.permissions != null && !model.canAdmin) {
            List<String> permissions = new ArrayList<String>();
            for (Map.Entry<String, AccessPermission> entry : model.permissions.entrySet()) {
                if (entry.getValue().exceeds(AccessPermission.NONE)) {
                    permissions.add(entry.getValue().asRole(entry.getKey()));
                }
            }
            config.setStringList(USER, model.username, REPOSITORY, permissions);
        }

        // user preferences
        if (model.getPreferences() != null) {
            List<String> starred = model.getPreferences().getStarredRepositories();
            if (starred.size() > 0) {
                config.setStringList(USER, model.username, STARRED, starred);
            }
        }
    }

    // write teams
    for (TeamModel model : teams.values()) {
        // team roles
        List<String> roles = new ArrayList<String>();
        if (model.canAdmin) {
            roles.add(Role.ADMIN.getRole());
        }
        if (model.canFork) {
            roles.add(Role.FORK.getRole());
        }
        if (model.canCreate) {
            roles.add(Role.CREATE.getRole());
        }
        if (roles.size() == 0) {
            // we do this to ensure that team record is written.
            // Otherwise, StoredConfig might optimizes that record away.
            roles.add(Role.NONE.getRole());
        }
        config.setStringList(TEAM, model.name, ROLE, roles);
        if (model.accountType != null) {
            config.setString(TEAM, model.name, ACCOUNTTYPE, model.accountType.name());
        }

        if (!model.canAdmin) {
            // write team permission for non-admin teams
            if (model.permissions == null) {
                // null check on "final" repositories because JSON-sourced TeamModel
                // can have a null repositories object
                if (!ArrayUtils.isEmpty(model.repositories)) {
                    config.setStringList(TEAM, model.name, REPOSITORY,
                            new ArrayList<String>(model.repositories));
                }
            } else {
                // discrete repository permissions
                List<String> permissions = new ArrayList<String>();
                for (Map.Entry<String, AccessPermission> entry : model.permissions.entrySet()) {
                    if (entry.getValue().exceeds(AccessPermission.NONE)) {
                        // code:repository (e.g. RW+:~james/myrepo.git
                        permissions.add(entry.getValue().asRole(entry.getKey()));
                    }
                }
                config.setStringList(TEAM, model.name, REPOSITORY, permissions);
            }
        }

        // null check on "final" users because JSON-sourced TeamModel
        // can have a null users object
        if (!ArrayUtils.isEmpty(model.users)) {
            config.setStringList(TEAM, model.name, USER, new ArrayList<String>(model.users));
        }

        // null check on "final" mailing lists because JSON-sourced
        // TeamModel can have a null users object
        if (!ArrayUtils.isEmpty(model.mailingLists)) {
            config.setStringList(TEAM, model.name, MAILINGLIST, new ArrayList<String>(model.mailingLists));
        }

        // null check on "final" preReceiveScripts because JSON-sourced
        // TeamModel can have a null preReceiveScripts object
        if (!ArrayUtils.isEmpty(model.preReceiveScripts)) {
            config.setStringList(TEAM, model.name, PRERECEIVE, model.preReceiveScripts);
        }

        // null check on "final" postReceiveScripts because JSON-sourced
        // TeamModel can have a null postReceiveScripts object
        if (!ArrayUtils.isEmpty(model.postReceiveScripts)) {
            config.setStringList(TEAM, model.name, POSTRECEIVE, model.postReceiveScripts);
        }
    }

    config.save();
    // manually set the forceReload flag because not all JVMs support real
    // millisecond resolution of lastModified. (issue-55)
    forceReload = true;

    // If the write is successful, delete the current file and rename
    // the temporary copy to the original filename.
    if (realmFileCopy.exists() && realmFileCopy.length() > 0) {
        if (realmFile.exists()) {
            if (!realmFile.delete()) {
                throw new IOException(
                        MessageFormat.format("Failed to delete {0}!", realmFile.getAbsolutePath()));
            }
        }
        if (!realmFileCopy.renameTo(realmFile)) {
            throw new IOException(MessageFormat.format("Failed to rename {0} to {1}!",
                    realmFileCopy.getAbsolutePath(), realmFile.getAbsolutePath()));
        }
    } else {
        throw new IOException(MessageFormat.format("Failed to save {0}!", realmFileCopy.getAbsolutePath()));
    }
}

From source file:com.gitblit.GitBlit.java

License:Apache License

/**
 * Updates the Gitblit configuration for the specified repository.
 * //from w w w . ja va 2 s  . c  o  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

/**
 * Updates the Gitblit configuration for the specified repository.
 *
 * @param r//ww w.ja va 2s. c  o  m
 *            the Git repository
 * @param repository
 *            the Gitblit repository model
 */
@Override
public void updateConfiguration(Repository r, RepositoryModel repository) {
    StoredConfig config = r.getConfig();
    config.setString(Constants.CONFIG_GITBLIT, null, "description", repository.description);
    config.setString(Constants.CONFIG_GITBLIT, null, "originRepository", repository.originRepository);
    config.setString(Constants.CONFIG_GITBLIT, null, "owner", ArrayUtils.toString(repository.owners));
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "acceptNewPatchsets", repository.acceptNewPatchsets);
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "acceptNewTickets", repository.acceptNewTickets);
    if (settings.getBoolean(Keys.tickets.requireApproval, false) == repository.requireApproval) {
        // use default
        config.unset(Constants.CONFIG_GITBLIT, null, "requireApproval");
    } else {
        // override default
        config.setBoolean(Constants.CONFIG_GITBLIT, null, "requireApproval", repository.requireApproval);
    }
    if (!StringUtils.isEmpty(repository.mergeTo)) {
        config.setString(Constants.CONFIG_GITBLIT, null, "mergeTo", repository.mergeTo);
    }
    if (repository.mergeType == null
            || repository.mergeType == MergeType.fromName(settings.getString(Keys.tickets.mergeType, null))) {
        // use default
        config.unset(Constants.CONFIG_GITBLIT, null, "mergeType");
    } else {
        // override default
        config.setString(Constants.CONFIG_GITBLIT, null, "mergeType", repository.mergeType.name());
    }
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "useIncrementalPushTags",
            repository.useIncrementalPushTags);
    if (StringUtils.isEmpty(repository.incrementalPushTagPrefix) || repository.incrementalPushTagPrefix
            .equals(settings.getString(Keys.git.defaultIncrementalPushTagPrefix, "r"))) {
        config.unset(Constants.CONFIG_GITBLIT, null, "incrementalPushTagPrefix");
    } else {
        config.setString(Constants.CONFIG_GITBLIT, null, "incrementalPushTagPrefix",
                repository.incrementalPushTagPrefix);
    }
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "allowForks", repository.allowForks);
    config.setString(Constants.CONFIG_GITBLIT, null, "accessRestriction", repository.accessRestriction.name());
    config.setString(Constants.CONFIG_GITBLIT, null, "authorizationControl",
            repository.authorizationControl.name());
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "verifyCommitter", repository.verifyCommitter);
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "showRemoteBranches", repository.showRemoteBranches);
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "isFrozen", repository.isFrozen);
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "skipSizeCalculation", repository.skipSizeCalculation);
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "skipSummaryMetrics", repository.skipSummaryMetrics);
    config.setString(Constants.CONFIG_GITBLIT, null, "federationStrategy",
            repository.federationStrategy.name());
    config.setBoolean(Constants.CONFIG_GITBLIT, null, "isFederated", repository.isFederated);
    config.setString(Constants.CONFIG_GITBLIT, null, "gcThreshold", repository.gcThreshold);
    if (repository.gcPeriod == settings.getInteger(Keys.git.defaultGarbageCollectionPeriod, 7)) {
        // use default from config
        config.unset(Constants.CONFIG_GITBLIT, null, "gcPeriod");
    } else {
        config.setInt(Constants.CONFIG_GITBLIT, null, "gcPeriod", repository.gcPeriod);
    }
    if (repository.lastGC != null) {
        config.setString(Constants.CONFIG_GITBLIT, null, "lastGC",
                new SimpleDateFormat(Constants.ISO8601).format(repository.lastGC));
    }
    if (repository.maxActivityCommits == settings.getInteger(Keys.web.maxActivityCommits, 0)) {
        // use default from config
        config.unset(Constants.CONFIG_GITBLIT, null, "maxActivityCommits");
    } else {
        config.setInt(Constants.CONFIG_GITBLIT, null, "maxActivityCommits", repository.maxActivityCommits);
    }

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

    updateList(config, "federationSets", repository.federationSets);
    updateList(config, "preReceiveScript", repository.preReceiveScripts);
    updateList(config, "postReceiveScript", repository.postReceiveScripts);
    updateList(config, "mailingList", repository.mailingLists);
    updateList(config, "indexBranch", repository.indexedBranches);
    updateList(config, "metricAuthorExclusions", repository.metricAuthorExclusions);

    // User Defined Properties
    if (repository.customFields != null) {
        if (repository.customFields.size() == 0) {
            // clear section
            config.unsetSection(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS);
        } else {
            for (Entry<String, String> property : repository.customFields.entrySet()) {
                // set field
                String key = property.getKey();
                String value = property.getValue();
                config.setString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, key, value);
            }
        }
    }

    try {
        config.save();
    } catch (IOException e) {
        logger.error("Failed to save repository config!", e);
    }
}

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

License:Apache License

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

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

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

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

From source file:com.google.gerrit.server.git.LocalDiskRepositoryManager.java

License:Apache License

private Repository createRepository(Path path, Project.NameKey name)
        throws RepositoryNotFoundException, RepositoryCaseMismatchException {
    if (isUnreasonableName(name)) {
        throw new RepositoryNotFoundException("Invalid name: " + name);
    }/*from  w w w. j  ava 2s . c o m*/

    File dir = FileKey.resolve(path.resolve(name.get()).toFile(), FS.DETECTED);
    FileKey loc;
    if (dir != null) {
        // Already exists on disk, use the repository we found.
        //
        loc = FileKey.exact(dir, FS.DETECTED);

        if (!names.contains(name)) {
            throw new RepositoryCaseMismatchException(name);
        }
    } else {
        // It doesn't exist under any of the standard permutations
        // of the repository name, so prefer the standard bare name.
        //
        String n = name.get() + Constants.DOT_GIT_EXT;
        loc = FileKey.exact(path.resolve(n).toFile(), FS.DETECTED);
    }

    try {
        Repository db = RepositoryCache.open(loc, false);
        db.create(true /* bare */);

        StoredConfig config = db.getConfig();
        config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
                ConfigConstants.CONFIG_KEY_LOGALLREFUPDATES, true);
        config.save();

        // JGit only writes to the reflog for refs/meta/config if the log file
        // already exists.
        //
        File metaConfigLog = new File(db.getDirectory(), "logs/" + RefNames.REFS_CONFIG);
        if (!metaConfigLog.getParentFile().mkdirs() || !metaConfigLog.createNewFile()) {
            log.error(String.format("Failed to create ref log for %s in repository %s", RefNames.REFS_CONFIG,
                    name));
        }

        onCreateProject(name);

        return db;
    } catch (IOException e1) {
        final RepositoryNotFoundException e2;
        e2 = new RepositoryNotFoundException("Cannot create repository " + name);
        e2.initCause(e1);
        throw e2;
    }
}

From source file:com.tasktop.c2c.server.scm.service.GitServiceBean.java

License:Open Source License

@Secured({ Role.Admin })
@Override//from w ww.  ja va2 s . c  o  m
public void createEmptyRepository(ScmRepository repository) {
    File hostedDir = repositoryProvider.getTenantHostedBaseDir();
    File gitDir = new File(hostedDir, repository.getName());
    File descriptionFile = new File(gitDir, "description");
    gitDir.mkdirs();
    try {
        FileRepository repo = new FileRepository(gitDir);
        repo.create();
        descriptionFile.createNewFile();
        writeToDescription(descriptionFile, repository.getDescription());
        StoredConfig config = repo.getConfig();
        config.setBoolean("receive", null, "denynonfastforwards", true);
        config.save();
        repo.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:ezbake.deployer.publishers.openShift.RhcApplication.java

License:Apache License

/**
 * Sets the git repository object.  Probably not useful but here for Java Bean completeness
 *
 * @param gitRepo - git repository to set it to
 *///from w w w . jav  a2  s .  c  o m
public void setGitRepo(Git gitRepo) throws DeploymentException {
    this.gitRepo = gitRepo;

    try {
        StoredConfig config = gitRepo.getRepository().getConfig();
        config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_FILEMODE, true);
        config.save();
    } catch (IOException e) {
        log.error("There was an error saving the  git configuration to disk", e);
        throw new DeploymentException("Could not save git configuration: " + e.getMessage());
    }
}

From source file:org.apache.maven.scm.provider.git.jgit.command.checkin.JGitCheckInCommandCommitterAuthorTckTest.java

License:Apache License

@Override
public void testCheckInCommandTest() throws Exception {
    File fooJava = new File(getWorkingCopy(), "src/main/java/Foo.java");
    assertFalse("check Foo.java doesn't yet exist", fooJava.canRead());

    Git git = Git.open(getWorkingCopy());

    RevCommit head = getHeadCommit(git.getRepository());
    // Mark created the test repo...
    assertEquals("Mark Struberg", head.getCommitterIdent().getName());
    JGitUtils.closeRepo(git);// w w w. jav  a 2s .co m

    createAndCommitFile(fooJava, null);

    // change user in config
    git = Git.open(getWorkingCopy());
    StoredConfig config = git.getRepository().getConfig();
    unsetConfig(config);
    config.setString("user", null, "name", "Dominik");
    config.setString("user", null, "email", "domi@mycomp.com");
    config.save();

    // make a commit
    createAndCommitFile(fooJava, null);

    // check new commit is done with new user in config
    head = getHeadCommit(git.getRepository());
    assertEquals("Dominik", head.getCommitterIdent().getName());
    assertEquals("Dominik", head.getAuthorIdent().getName());
    assertEquals("domi@mycomp.com", head.getAuthorIdent().getEmailAddress());
    assertEquals("domi@mycomp.com", head.getCommitterIdent().getEmailAddress());
    JGitUtils.closeRepo(git);

    // change user in config
    git = Git.open(getWorkingCopy());
    config = git.getRepository().getConfig();
    unsetConfig(config);
    config.setString("user", null, "name", "dbartholdi");
    config.save();

    // make a change
    createAndCommitFile(fooJava, null);

    // check new commit is done with new user in config
    head = getHeadCommit(git.getRepository());
    assertEquals("dbartholdi", head.getCommitterIdent().getName());
    assertFalse("no mail domain is configured, git system default should be used",
            head.getCommitterIdent().getEmailAddress().contains("dbartholdi"));
    JGitUtils.closeRepo(git);

    // unset a user and maven user but set default mail domain
    git = Git.open(getWorkingCopy());
    config = git.getRepository().getConfig();
    unsetConfig(config);
    config.setString(JGitCheckInCommand.GIT_MAVEN_SECTION, null, JGitCheckInCommand.GIT_MAILDOMAIN, "comp.com");
    config.save();

    // make a change with an user on the commandline
    createAndCommitFile(fooJava, "dude");

    // check new commit is done with new maven user in config
    head = getHeadCommit(git.getRepository());
    assertEquals("dude", head.getCommitterIdent().getName());
    assertEquals("dude@comp.com", head.getCommitterIdent().getEmailAddress());
    assertEquals("dude", head.getAuthorIdent().getName());
    assertEquals("dude@comp.com", head.getAuthorIdent().getEmailAddress());
    JGitUtils.closeRepo(git);

    // unset a user and maven user but set default mail domain
    git = Git.open(getWorkingCopy());
    config = git.getRepository().getConfig();
    unsetConfig(config);
    config.setString("user", null, "name", "dbartholdi");
    config.setBoolean(JGitCheckInCommand.GIT_MAVEN_SECTION, null, JGitCheckInCommand.GIT_FORCE, true);
    config.setString(JGitCheckInCommand.GIT_MAVEN_SECTION, null, JGitCheckInCommand.GIT_MAILDOMAIN,
            "anycomp.com");
    config.save();

    // make a change with an user on the commandline
    createAndCommitFile(fooJava, "dude");

    // check new commit is done with new maven user in config
    head = getHeadCommit(git.getRepository());
    assertEquals("dude", head.getCommitterIdent().getName());
    assertEquals("dude@anycomp.com", head.getCommitterIdent().getEmailAddress());
    assertEquals("dude", head.getAuthorIdent().getName());
    assertEquals("dude@anycomp.com", head.getAuthorIdent().getEmailAddress());
    JGitUtils.closeRepo(git);

    // unset a user and maven user but set default mail domain
    git = Git.open(getWorkingCopy());
    config = git.getRepository().getConfig();
    unsetConfig(config);
    config.setString(JGitCheckInCommand.GIT_MAVEN_SECTION, null, JGitCheckInCommand.GIT_MAILDOMAIN,
            "anycomp.com");
    config.save();

    // make a change with no username given
    createAndCommitFile(fooJava, null);

    // check new commit does not contain the configured email domain
    head = getHeadCommit(git.getRepository());
    assertFalse(head.getCommitterIdent().getEmailAddress().contains("anycomp.com"));
    assertFalse(head.getAuthorIdent().getEmailAddress().contains("anycomp.com"));
    JGitUtils.closeRepo(git);

    // unset a user and full maven section
    git = Git.open(getWorkingCopy());
    config = git.getRepository().getConfig();
    unsetConfig(config);
    config.save();

    // make a change with an user on the commandline
    createAndCommitFile(fooJava, "dundy");

    // check new commit is done with new maven user in config
    head = getHeadCommit(git.getRepository());
    assertEquals("dundy", head.getCommitterIdent().getName());
    assertEquals("dundy", head.getAuthorIdent().getName());
    assertTrue(
            "the maven user (from parameter) name must be in the committer mail when nothing else is configured",
            head.getCommitterIdent().getEmailAddress().contains("dundy"));
    assertTrue("the user name (from parameter) must be in the author mail when nothing else is configured",
            head.getAuthorIdent().getEmailAddress().contains("dundy"));
    JGitUtils.closeRepo(git);

    // unset all configs
    git = Git.open(getWorkingCopy());
    config = git.getRepository().getConfig();
    unsetConfig(config);
    config.save();

    // make a change with no user on the commandline
    createAndCommitFile(fooJava, null);

    // check new commit is has a committer/author with email set
    head = getHeadCommit(git.getRepository());
    assertNotNull(head.getCommitterIdent().getName());
    assertNotNull(head.getAuthorIdent().getName());
    assertNotNull(head.getCommitterIdent().getEmailAddress());
    assertNotNull(head.getAuthorIdent().getEmailAddress());
    JGitUtils.closeRepo(git);
}

From source file:org.eclipse.oomph.setup.git.impl.GitCloneTaskImpl.java

License:Open Source License

private static void createBranch(SetupTaskContext context, Git git, String checkoutBranch, String remoteName)
        throws Exception {
    context.log("Creating local branch " + checkoutBranch);

    CreateBranchCommand command = git.branchCreate();
    command.setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM);
    command.setName(checkoutBranch);/*from w w  w .j a v  a 2 s . c om*/
    command.setStartPoint("refs/remotes/" + remoteName + "/" + checkoutBranch);
    command.call();

    StoredConfig config = git.getRepository().getConfig();
    config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, checkoutBranch, ConfigConstants.CONFIG_KEY_REBASE,
            true);
    config.save();
}

From source file:org.eclipse.orion.server.git.servlets.GitCloneHandlerV1.java

License:Open Source License

static void doConfigureClone(Git git, String user) throws IOException, CoreException {
    StoredConfig config = git.getRepository().getConfig();
    IOrionUserProfileNode userNode = UserServiceHelper.getDefault().getUserProfileService()
            .getUserProfileNode(user, true).getUserProfileNode(IOrionUserProfileConstants.GENERAL_PROFILE_PART);
    if (userNode.get(GitConstants.KEY_NAME, null) != null)
        config.setString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_NAME,
                userNode.get(GitConstants.KEY_NAME, null));
    if (userNode.get(GitConstants.KEY_MAIL, null) != null)
        config.setString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_EMAIL,
                userNode.get(GitConstants.KEY_MAIL, null));
    config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_FILEMODE, false);
    config.save();/*from   www  .ja v a2 s.  c  o  m*/
}