Example usage for org.eclipse.jgit.lib Config setString

List of usage examples for org.eclipse.jgit.lib Config setString

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Config setString.

Prototype

public void setString(final String section, final String subsection, final String name, final String value) 

Source Link

Document

Add or modify a configuration value.

Usage

From source file:com.gitblit.authority.NewCertificateConfig.java

License:Apache License

private void store(Config c, String section, String name, String value) {
    if (StringUtils.isEmpty(value)) {
        c.unset(section, null, name);//from  w  w  w  . j a v  a  2 s .co  m
    } else {
        c.setString(section, null, name, value);
    }
}

From source file:com.gitblit.authority.UserCertificateModel.java

License:Apache License

public void update(Config config) {
    if (expires == null) {
        config.unset("user", user.username, "expires");
    } else {// w ww  .j  av a2s. c om
        SimpleDateFormat df = new SimpleDateFormat(Constants.ISO8601);
        config.setString("user", user.username, "expires", df.format(expires));
    }
    if (StringUtils.isEmpty(notes)) {
        config.unset("user", user.username, "notes");
    } else {
        config.setString("user", user.username, "notes", notes);
    }
    if (ArrayUtils.isEmpty(revoked)) {
        config.unset("user", user.username, "revoked");
    } else {
        config.setStringList("user", user.username, "revoked", revoked);
    }
}

From source file:com.gitblit.wicket.pages.NewRepositoryPage.java

License:Apache License

/**
 * Prepare the initial commit for the repository.
 *
 * @param repository/*from  w  w  w.  ja v a 2 s.c  o  m*/
 * @param addReadme
 * @param gitignore
 * @param addGitFlow
 * @return true if an initial commit was created
 */
protected boolean initialCommit(RepositoryModel repository, boolean addReadme, String gitignore,
        boolean addGitFlow) {
    boolean initialCommit = addReadme || !StringUtils.isEmpty(gitignore) || addGitFlow;
    if (!initialCommit) {
        return false;
    }

    // build an initial commit
    boolean success = false;
    Repository db = app().repositories().getRepository(repositoryModel.name);
    ObjectInserter odi = db.newObjectInserter();
    try {

        UserModel user = GitBlitWebSession.get().getUser();
        String email = Optional.fromNullable(user.emailAddress).or(user.username + "@" + "gitblit");
        PersonIdent author = new PersonIdent(user.getDisplayName(), email);

        DirCache newIndex = DirCache.newInCore();
        DirCacheBuilder indexBuilder = newIndex.builder();

        if (addReadme) {
            // insert a README
            String title = StringUtils.stripDotGit(StringUtils.getLastPathElement(repositoryModel.name));
            String description = repositoryModel.description == null ? "" : repositoryModel.description;
            String readme = String.format("## %s\n\n%s\n\n", title, description);
            byte[] bytes = readme.getBytes(Constants.ENCODING);

            DirCacheEntry entry = new DirCacheEntry("README.md");
            entry.setLength(bytes.length);
            entry.setLastModified(System.currentTimeMillis());
            entry.setFileMode(FileMode.REGULAR_FILE);
            entry.setObjectId(odi.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, bytes));

            indexBuilder.add(entry);
        }

        if (!StringUtils.isEmpty(gitignore)) {
            // insert a .gitignore file
            File dir = app().runtime().getFileOrFolder(Keys.git.gitignoreFolder, "${baseFolder}/gitignore");
            File file = new File(dir, gitignore + ".gitignore");
            if (file.exists() && file.length() > 0) {
                byte[] bytes = FileUtils.readContent(file);
                if (!ArrayUtils.isEmpty(bytes)) {
                    DirCacheEntry entry = new DirCacheEntry(".gitignore");
                    entry.setLength(bytes.length);
                    entry.setLastModified(System.currentTimeMillis());
                    entry.setFileMode(FileMode.REGULAR_FILE);
                    entry.setObjectId(odi.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, bytes));

                    indexBuilder.add(entry);
                }
            }
        }

        if (addGitFlow) {
            // insert a .gitflow file
            Config config = new Config();
            config.setString("gitflow", null, "masterBranch", Constants.MASTER);
            config.setString("gitflow", null, "developBranch", Constants.DEVELOP);
            config.setString("gitflow", null, "featureBranchPrefix", "feature/");
            config.setString("gitflow", null, "releaseBranchPrefix", "release/");
            config.setString("gitflow", null, "hotfixBranchPrefix", "hotfix/");
            config.setString("gitflow", null, "supportBranchPrefix", "support/");
            config.setString("gitflow", null, "versionTagPrefix", "");

            byte[] bytes = config.toText().getBytes(Constants.ENCODING);

            DirCacheEntry entry = new DirCacheEntry(".gitflow");
            entry.setLength(bytes.length);
            entry.setLastModified(System.currentTimeMillis());
            entry.setFileMode(FileMode.REGULAR_FILE);
            entry.setObjectId(odi.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, bytes));

            indexBuilder.add(entry);
        }

        indexBuilder.finish();

        if (newIndex.getEntryCount() == 0) {
            // nothing to commit
            return false;
        }

        ObjectId treeId = newIndex.writeTree(odi);

        // Create a commit object
        CommitBuilder commit = new CommitBuilder();
        commit.setAuthor(author);
        commit.setCommitter(author);
        commit.setEncoding(Constants.ENCODING);
        commit.setMessage("Initial commit");
        commit.setTreeId(treeId);

        // Insert the commit into the repository
        ObjectId commitId = odi.insert(commit);
        odi.flush();

        // set the branch refs
        RevWalk revWalk = new RevWalk(db);
        try {
            // set the master branch
            RevCommit revCommit = revWalk.parseCommit(commitId);
            RefUpdate masterRef = db.updateRef(Constants.R_MASTER);
            masterRef.setNewObjectId(commitId);
            masterRef.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
            Result masterRC = masterRef.update();
            switch (masterRC) {
            case NEW:
                success = true;
                break;
            default:
                success = false;
            }

            if (addGitFlow) {
                // set the develop branch for git-flow
                RefUpdate developRef = db.updateRef(Constants.R_DEVELOP);
                developRef.setNewObjectId(commitId);
                developRef.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
                Result developRC = developRef.update();
                switch (developRC) {
                case NEW:
                    success = true;
                    break;
                default:
                    success = false;
                }
            }
        } finally {
            revWalk.close();
        }
    } catch (UnsupportedEncodingException e) {
        logger().error(null, e);
    } catch (IOException e) {
        logger().error(null, e);
    } finally {
        odi.close();
        db.close();
    }
    return success;
}

From source file:com.google.gerrit.acceptance.ConfigAnnotationParser.java

License:Apache License

private static void parseAnnotation(Config cfg, GerritConfig c) {
    ArrayList<String> l = Lists.newArrayList(splitter.split(c.name()));
    if (l.size() == 2) {
        if (!Strings.isNullOrEmpty(c.value())) {
            cfg.setString(l.get(0), null, l.get(1), c.value());
        } else {//from   w  w w  . j  av a2  s  . c o  m
            String[] values = c.values();
            cfg.setStringList(l.get(0), null, l.get(1), Arrays.asList(values));
        }
    } else if (l.size() == 3) {
        if (!Strings.isNullOrEmpty(c.value())) {
            cfg.setString(l.get(0), l.get(1), l.get(2), c.value());
        } else {
            cfg.setStringList(l.get(0), l.get(1), l.get(2), Arrays.asList(c.value()));
        }
    } else {
        throw new IllegalArgumentException(
                "GerritConfig.name must be of the format" + " section.subsection.name or section.name");
    }
}

From source file:com.google.gerrit.acceptance.GerritServer.java

License:Apache License

/** Returns fully started Gerrit server */
static GerritServer start(Description desc, Config baseConfig) throws Exception {
    Config cfg = desc.buildConfig(baseConfig);
    Logger.getLogger("com.google.gerrit").setLevel(Level.DEBUG);
    final CyclicBarrier serverStarted = new CyclicBarrier(2);
    final Daemon daemon = new Daemon(new Runnable() {
        @Override// ww w  .j  a v a 2s.c o m
        public void run() {
            try {
                serverStarted.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                throw new RuntimeException(e);
            }
        }
    });
    daemon.setEmailModuleForTesting(new FakeEmailSender.Module());

    final File site;
    ExecutorService daemonService = null;
    if (desc.memory()) {
        site = null;
        mergeTestConfig(cfg);
        // Set the log4j configuration to an invalid one to prevent system logs
        // from getting configured and creating log files.
        System.setProperty(SystemLog.LOG4J_CONFIGURATION, "invalidConfiguration");
        cfg.setBoolean("httpd", null, "requestLog", false);
        cfg.setBoolean("sshd", null, "requestLog", false);
        cfg.setBoolean("index", "lucene", "testInmemory", true);
        cfg.setString("gitweb", null, "cgi", "");
        daemon.setEnableHttpd(desc.httpd());
        daemon.setLuceneModule(new LuceneIndexModule(ChangeSchemas.getLatest().getVersion(), 0, null));
        daemon.setDatabaseForTesting(ImmutableList.<Module>of(new InMemoryTestingDatabaseModule(cfg)));
        daemon.start();
    } else {
        site = initSite(cfg);
        daemonService = Executors.newSingleThreadExecutor();
        daemonService.submit(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                int rc = daemon.main(new String[] { "-d", site.getPath(), "--headless", "--console-log",
                        "--show-stack-trace" });
                if (rc != 0) {
                    System.err.println("Failed to start Gerrit daemon");
                    serverStarted.reset();
                }
                return null;
            }
        });
        serverStarted.await();
        System.out.println("Gerrit Server Started");
    }

    Injector i = createTestInjector(daemon);
    return new GerritServer(desc, i, daemon, daemonService);
}

From source file:com.google.gerrit.acceptance.GerritServer.java

License:Apache License

private static void mergeTestConfig(Config cfg) {
    String forceEphemeralPort = String.format("%s:0", getLocalHost().getHostName());
    String url = "http://" + forceEphemeralPort + "/";
    cfg.setString("gerrit", null, "canonicalWebUrl", url);
    cfg.setString("httpd", null, "listenUrl", url);
    cfg.setString("sshd", null, "listenAddress", forceEphemeralPort);
    cfg.setBoolean("sshd", null, "testUseInsecureRandom", true);
    cfg.unset("cache", null, "directory");
    cfg.setString("gerrit", null, "basePath", "git");
    cfg.setBoolean("sendemail", null, "enable", true);
    cfg.setInt("sendemail", null, "threadPoolSize", 0);
    cfg.setInt("cache", "projects", "checkFrequency", 0);
    cfg.setInt("plugins", null, "checkFrequency", 0);

    cfg.setInt("sshd", null, "threads", 1);
    cfg.setInt("sshd", null, "commandStartThreads", 1);
    cfg.setInt("receive", null, "threadPoolSize", 1);
    cfg.setInt("index", null, "threads", 1);
}

From source file:com.google.gerrit.acceptance.git.AbstractSubmoduleSubscription.java

License:Apache License

protected void prepareSubscriptionConfigEntry(Config config, String subscribeToRepo, String subscribeToBranch) {
    subscribeToRepo = name(subscribeToRepo);
    // The submodule subscription module checks for gerrit.canonicalWebUrl to
    // detect if it's configured for automatic updates. It doesn't matter if
    // it serves from that URL.
    String url = cfg.getString("gerrit", null, "canonicalWebUrl") + "/" + subscribeToRepo;
    config.setString("submodule", subscribeToRepo, "path", subscribeToRepo);
    config.setString("submodule", subscribeToRepo, "url", url);
    config.setString("submodule", subscribeToRepo, "branch", subscribeToBranch);
}

From source file:com.google.gerrit.acceptance.GitUtil.java

License:Apache License

public static TestRepository<InMemoryRepository> cloneProject(Project.NameKey project, String uri)
        throws Exception {
    DfsRepositoryDescription desc = new DfsRepositoryDescription("clone of " + project.get());
    InMemoryRepository dest = new InMemoryRepository.Builder().setRepositoryDescription(desc)
            // SshTransport depends on a real FS to read ~/.ssh/config, but
            // InMemoryRepository by default uses a null FS.
            // TODO(dborowitz): Remove when we no longer depend on SSH.
            .setFS(FS.detect()).build();
    Config cfg = dest.getConfig();
    cfg.setString("remote", "origin", "url", uri);
    cfg.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
    TestRepository<InMemoryRepository> testRepo = newTestRepository(dest);
    FetchResult result = testRepo.git().fetch().setRemote("origin").call();
    String originMaster = "refs/remotes/origin/master";
    if (result.getTrackingRefUpdate(originMaster) != null) {
        testRepo.reset(originMaster);/*from w w w.j  a va 2 s  .c  o m*/
    }
    return testRepo;
}

From source file:com.google.gerrit.acceptance.rest.change.ConfigChangeIT.java

License:Apache License

@Test
@TestProjectInput(cloneAs = "user")
public void updateProjectConfig() throws Exception {
    Config cfg = readProjectConfig();
    assertThat(cfg.getString("project", null, "description")).isNull();
    String desc = "new project description";
    cfg.setString("project", null, "description", desc);

    PushOneCommit.Result r = createConfigChange(cfg);
    String id = r.getChangeId();/*from   w  w  w  .java  2 s  .co m*/

    gApi.changes().id(id).current().review(ReviewInput.approve());
    gApi.changes().id(id).current().submit();

    assertThat(gApi.changes().id(id).info().status).isEqualTo(ChangeStatus.MERGED);
    assertThat(gApi.projects().name(project.get()).get().description).isEqualTo(desc);
    fetchRefsMetaConfig();
    assertThat(readProjectConfig().getString("project", null, "description")).isEqualTo(desc);
}

From source file:com.google.gerrit.acceptance.rest.change.ConfigChangeIT.java

License:Apache License

@Test
@TestProjectInput(cloneAs = "user")
public void onlyAdminMayUpdateProjectParent() throws Exception {
    setApiUser(admin);/*from   ww  w  .j a v a  2  s  . com*/
    ProjectInput parent = new ProjectInput();
    parent.name = name("parent");
    parent.permissionsOnly = true;
    gApi.projects().create(parent);

    setApiUser(user);
    Config cfg = readProjectConfig();
    assertThat(cfg.getString("access", null, "inheritFrom")).isAnyOf(null, allProjects.get());
    cfg.setString("access", null, "inheritFrom", parent.name);

    PushOneCommit.Result r = createConfigChange(cfg);
    String id = r.getChangeId();

    gApi.changes().id(id).current().review(ReviewInput.approve());
    try {
        gApi.changes().id(id).current().submit();
        fail("expected submit to fail");
    } catch (ResourceConflictException e) {
        int n = gApi.changes().id(id).info()._number;
        assertThat(e).hasMessage("Failed to submit 1 change due to the following problems:\n" + "Change " + n
                + ": Change contains a project configuration that" + " changes the parent project.\n"
                + "The change must be submitted by a Gerrit administrator.");
    }

    assertThat(gApi.projects().name(project.get()).get().parent).isEqualTo(allProjects.get());
    fetchRefsMetaConfig();
    assertThat(readProjectConfig().getString("access", null, "inheritFrom")).isAnyOf(null, allProjects.get());

    setApiUser(admin);
    gApi.changes().id(id).current().submit();
    assertThat(gApi.changes().id(id).info().status).isEqualTo(ChangeStatus.MERGED);
    assertThat(gApi.projects().name(project.get()).get().parent).isEqualTo(parent.name);
    fetchRefsMetaConfig();
    assertThat(readProjectConfig().getString("access", null, "inheritFrom")).isEqualTo(parent.name);
}