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

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

Introduction

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

Prototype

public String toText() 

Source Link

Document

Get this configuration, formatted as a Git style text file.

Usage

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

License:Apache License

/**
 * Prepare the initial commit for the repository.
 *
 * @param repository// www  .  j  a  v  a 2  s. c om
 * @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.git.AbstractSubmoduleSubscription.java

License:Apache License

protected void pushSubscriptionConfig(TestRepository<?> repo, String branch, Config config) throws Exception {

    repo.branch("HEAD").commit().insertChangeId().message("subject: adding new subscription")
            .add(".gitmodules", config.toText().toString()).create();

    repo.git().push().setRemote("origin").setRefSpecs(new RefSpec("HEAD:refs/heads/" + branch)).call();
}

From source file:com.google.gerrit.acceptance.rest.account.ExternalIdIT.java

License:Apache License

private String insertExternalIdWithoutAccountId(Repository repo, RevWalk rw, String externalId)
        throws IOException {
    ObjectId rev = ExternalIdReader.readRevision(repo);
    NoteMap noteMap = ExternalIdReader.readNoteMap(rw, rev);

    ExternalId extId = ExternalId.create(ExternalId.Key.parse(externalId), admin.id);

    try (ObjectInserter ins = repo.newObjectInserter()) {
        ObjectId noteId = extId.key().sha1();
        Config c = new Config();
        extId.writeToConfig(c);//from www.j  a  v  a  2s.co  m
        c.unset("externalId", extId.key().get(), "accountId");
        byte[] raw = c.toText().getBytes(UTF_8);
        ObjectId dataBlob = ins.insert(OBJ_BLOB, raw);
        noteMap.set(noteId, dataBlob);

        ExternalIdsUpdate.commit(repo, rw, ins, rev, noteMap, "Add external ID", admin.getIdent(),
                admin.getIdent());
        return noteId.getName();
    }
}

From source file:com.google.gerrit.acceptance.rest.account.ExternalIdIT.java

License:Apache License

private String insertExternalIdWithKeyThatDoesntMatchNoteId(Repository repo, RevWalk rw, String externalId)
        throws IOException {
    ObjectId rev = ExternalIdReader.readRevision(repo);
    NoteMap noteMap = ExternalIdReader.readNoteMap(rw, rev);

    ExternalId extId = ExternalId.create(ExternalId.Key.parse(externalId), admin.id);

    try (ObjectInserter ins = repo.newObjectInserter()) {
        ObjectId noteId = ExternalId.Key.parse(externalId + "x").sha1();
        Config c = new Config();
        extId.writeToConfig(c);//from  w ww.j av a2 s  .co  m
        byte[] raw = c.toText().getBytes(UTF_8);
        ObjectId dataBlob = ins.insert(OBJ_BLOB, raw);
        noteMap.set(noteId, dataBlob);

        ExternalIdsUpdate.commit(repo, rw, ins, rev, noteMap, "Add external ID", admin.getIdent(),
                admin.getIdent());
        return noteId.getName();
    }
}

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

License:Apache License

private PushOneCommit.Result createConfigChange(Config cfg) throws Exception {
    PushOneCommit.Result r = pushFactory
            .create(db, user.getIdent(), testRepo, "Update project config", "project.config", cfg.toText())
            .to("refs/for/refs/meta/config");
    r.assertOkStatus();/*  w ww.  j av a 2 s  . c  o m*/
    return r;
}

From source file:com.google.gerrit.acceptance.rest.project.AccessIT.java

License:Apache License

@Test
public void unknownPermissionRemainsUnchanged() throws Exception {
    String access = "access";
    String unknownPermission = "unknownPermission";
    String registeredUsers = "group Registered Users";
    String refsFor = "refs/for/*";
    // Clone repository to forcefully add permission
    TestRepository<InMemoryRepository> allProjectsRepo = cloneProject(allProjects, admin);

    // Fetch permission ref
    GitUtil.fetch(allProjectsRepo, "refs/meta/config:cfg");
    allProjectsRepo.reset("cfg");

    // Load current permissions
    String config = gApi.projects().name(allProjects.get()).branch(RefNames.REFS_CONFIG).file("project.config")
            .asString();/*from ww w .  ja v a2  s .  c o  m*/

    // Append and push unknown permission
    Config cfg = new Config();
    cfg.fromText(config);
    cfg.setString(access, refsFor, unknownPermission, registeredUsers);
    config = cfg.toText();
    PushOneCommit push = pushFactory.create(db, admin.getIdent(), allProjectsRepo, "Subject", "project.config",
            config);
    push.to(RefNames.REFS_CONFIG).assertOkStatus();

    // Verify that unknownPermission is present
    config = gApi.projects().name(allProjects.get()).branch(RefNames.REFS_CONFIG).file("project.config")
            .asString();
    cfg.fromText(config);
    assertThat(cfg.getString(access, refsFor, unknownPermission)).isEqualTo(registeredUsers);

    // Make permission change through API
    ProjectAccessInput accessInput = newProjectAccessInput();
    AccessSectionInfo accessSectionInfo = createDefaultAccessSectionInfo();
    accessInput.add.put(refsFor, accessSectionInfo);
    gApi.projects().name(allProjects.get()).access(accessInput);
    accessInput.add.clear();
    accessInput.remove.put(refsFor, accessSectionInfo);
    gApi.projects().name(allProjects.get()).access(accessInput);

    // Verify that unknownPermission is still present
    config = gApi.projects().name(allProjects.get()).branch(RefNames.REFS_CONFIG).file("project.config")
            .asString();
    cfg.fromText(config);
    assertThat(cfg.getString(access, refsFor, unknownPermission)).isEqualTo(registeredUsers);
}

From source file:com.google.gerrit.acceptance.rest.project.ProjectLevelConfigIT.java

License:Apache License

@Test
public void accessProjectSpecificConfig() throws Exception {
    String configName = "test.config";
    Config cfg = new Config();
    cfg.setString("s1", null, "k1", "v1");
    cfg.setString("s2", "ss", "k2", "v2");
    PushOneCommit push = pushFactory.create(db, admin.getIdent(), testRepo, "Create Project Level Config",
            configName, cfg.toText());
    push.to(RefNames.REFS_CONFIG);/* w w  w.java2 s. c o m*/

    ProjectState state = projectCache.get(project);
    assertThat(state.getConfig(configName).get().toText()).isEqualTo(cfg.toText());
}

From source file:com.google.gerrit.acceptance.rest.project.ProjectLevelConfigIT.java

License:Apache License

@Test
public void withInheritance() throws Exception {
    String configName = "test.config";

    Config parentCfg = new Config();
    parentCfg.setString("s1", null, "k1", "parentValue1");
    parentCfg.setString("s1", null, "k2", "parentValue2");
    parentCfg.setString("s2", "ss", "k3", "parentValue3");
    parentCfg.setString("s2", "ss", "k4", "parentValue4");

    pushFactory.create(db, admin.getIdent(), testRepo, "Create Project Level Config", configName,
            parentCfg.toText()).to(RefNames.REFS_CONFIG).assertOkStatus();

    Project.NameKey childProject = createProject("child", project);
    TestRepository<?> childTestRepo = cloneProject(childProject);
    fetch(childTestRepo, RefNames.REFS_CONFIG + ":refs/heads/config");
    childTestRepo.reset("refs/heads/config");

    Config cfg = new Config();
    cfg.setString("s1", null, "k1", "childValue1");
    cfg.setString("s2", "ss", "k3", "childValue2");

    pushFactory.create(db, admin.getIdent(), childTestRepo, "Create Project Level Config", configName,
            cfg.toText()).to(RefNames.REFS_CONFIG).assertOkStatus();

    ProjectState state = projectCache.get(childProject);

    Config expectedCfg = new Config();
    expectedCfg.setString("s1", null, "k1", "childValue1");
    expectedCfg.setString("s1", null, "k2", "parentValue2");
    expectedCfg.setString("s2", "ss", "k3", "childValue2");
    expectedCfg.setString("s2", "ss", "k4", "parentValue4");

    assertThat(state.getConfig(configName).getWithInheritance().toText()).isEqualTo(expectedCfg.toText());

    assertThat(state.getConfig(configName).get().toText()).isEqualTo(cfg.toText());
}

From source file:com.google.gerrit.server.account.externalids.ExternalId.java

License:Apache License

/**
 * Exports this external ID as Git config file text.
 *
 * <p>The Git config has exactly one externalId subsection with an accountId and optionally email
 * and password:/*from   w  ww.jav a 2  s. com*/
 *
 * <pre>
 * [externalId "username:jdoe"]
 *   accountId = 1003407
 *   email = jdoe@example.com
 *   password = bcrypt:4:LCbmSBDivK/hhGVQMfkDpA==:XcWn0pKYSVU/UJgOvhidkEtmqCp6oKB7
 * </pre>
 */
@Override
public String toString() {
    Config c = new Config();
    writeToConfig(c);
    return c.toText();
}

From source file:com.google.gerrit.server.account.externalids.ExternalIdsUpdate.java

License:Apache License

/**
 * Insert or updates an new external ID and sets it in the note map.
 *
 * <p>If the external ID already exists it is overwritten.
 *///from   w  ww  .ja va  2 s. c o  m
public static void upsert(RevWalk rw, ObjectInserter ins, NoteMap noteMap, ExternalId extId)
        throws IOException, ConfigInvalidException {
    ObjectId noteId = extId.key().sha1();
    Config c = new Config();
    if (noteMap.contains(extId.key().sha1())) {
        byte[] raw = rw.getObjectReader().open(noteMap.get(noteId), OBJ_BLOB).getCachedBytes(MAX_NOTE_SZ);
        try {
            c.fromText(new String(raw, UTF_8));
        } catch (ConfigInvalidException e) {
            throw new ConfigInvalidException(
                    String.format("Invalid external id config for note %s: %s", noteId, e.getMessage()));
        }
    }
    extId.writeToConfig(c);
    byte[] raw = c.toText().getBytes(UTF_8);
    ObjectId dataBlob = ins.insert(OBJ_BLOB, raw);
    noteMap.set(noteId, dataBlob);
}