Search in sources :

Example 1 with Config

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

the class BugtraqConfig method getBaseConfig.

// Utils ==================================================================
@Nullable
private static Config getBaseConfig(@NotNull Repository repository, @NotNull String configFileName) throws IOException, ConfigInvalidException {
    final Config baseConfig;
    if (repository.isBare()) {
        // read bugtraq config directly from the repository
        String content = null;
        RevWalk rw = new RevWalk(repository);
        TreeWalk tw = new TreeWalk(repository);
        tw.setFilter(PathFilterGroup.createFromStrings(configFileName));
        try {
            final Ref ref = repository.getRef(Constants.HEAD);
            if (ref == null) {
                return null;
            }
            ObjectId headId = ref.getTarget().getObjectId();
            if (headId == null || ObjectId.zeroId().equals(headId)) {
                return null;
            }
            RevCommit commit = rw.parseCommit(headId);
            RevTree tree = commit.getTree();
            tw.reset(tree);
            while (tw.next()) {
                ObjectId entid = tw.getObjectId(0);
                FileMode entmode = tw.getFileMode(0);
                if (FileMode.REGULAR_FILE == entmode) {
                    ObjectLoader ldr = repository.open(entid, Constants.OBJ_BLOB);
                    content = new String(ldr.getCachedBytes(), commit.getEncoding());
                    break;
                }
            }
        } finally {
            rw.dispose();
            tw.close();
        }
        if (content == null) {
            // config not found
            baseConfig = null;
        } else {
            // parse the config
            Config config = new Config();
            config.fromText(content);
            baseConfig = config;
        }
    } else {
        // read bugtraq config from work tree
        final File baseFile = new File(repository.getWorkTree(), configFileName);
        if (baseFile.isFile()) {
            FileBasedConfig fileConfig = new FileBasedConfig(baseFile, repository.getFS());
            fileConfig.load();
            baseConfig = fileConfig;
        } else {
            baseConfig = null;
        }
    }
    return baseConfig;
}
Also used : FileMode(org.eclipse.jgit.lib.FileMode) Ref(org.eclipse.jgit.lib.Ref) ObjectId(org.eclipse.jgit.lib.ObjectId) Config(org.eclipse.jgit.lib.Config) FileBasedConfig(org.eclipse.jgit.storage.file.FileBasedConfig) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) RevWalk(org.eclipse.jgit.revwalk.RevWalk) FileBasedConfig(org.eclipse.jgit.storage.file.FileBasedConfig) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) File(java.io.File) RevTree(org.eclipse.jgit.revwalk.RevTree) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Nullable(org.jetbrains.annotations.Nullable)

Example 2 with Config

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

the class BugtraqConfig method read.

// Static =================================================================
@Nullable
public static BugtraqConfig read(@NotNull Repository repository) throws IOException, ConfigInvalidException {
    Config baseConfig = getBaseConfig(repository, DOT_GIT_BUGTRAQ);
    if (baseConfig == null) {
        baseConfig = getBaseConfig(repository, DOT_TGITCONFIG);
    }
    final Set<String> allNames = new HashSet<String>();
    final Config config;
    try {
        config = repository.getConfig();
    } catch (RuntimeException ex) {
        final Throwable cause = ex.getCause();
        if (cause instanceof IOException) {
            throw (IOException) cause;
        }
        throw ex;
    }
    if (getString(null, URL, config, baseConfig) != null) {
        allNames.add(null);
    } else {
        allNames.addAll(config.getSubsections(BUGTRAQ));
        if (baseConfig != null) {
            allNames.addAll(baseConfig.getSubsections(BUGTRAQ));
        }
    }
    final List<BugtraqEntry> entries = new ArrayList<BugtraqEntry>();
    for (String name : allNames) {
        final String url = getString(name, URL, config, baseConfig);
        if (url == null) {
            continue;
        }
        final String enabled = getString(name, ENABLED, config, baseConfig);
        if (enabled != null && !"true".equals(enabled)) {
            continue;
        }
        String idRegex = getString(name, LOG_REGEX, config, baseConfig);
        if (idRegex == null) {
            return null;
        }
        String filterRegex = getString(name, LOG_FILTERREGEX, config, baseConfig);
        final String linkRegex = getString(name, LOG_LINKREGEX, config, baseConfig);
        if (filterRegex == null && linkRegex == null) {
            final String[] split = idRegex.split("\n", Integer.MAX_VALUE);
            if (split.length == 2) {
                // Compatibility with TortoiseGit
                filterRegex = split[0];
                idRegex = split[1];
            } else {
                // Backwards compatibility with specification version < 0.3
                final List<String> logIdRegexs = new ArrayList<String>();
                for (int index = 1; index < Integer.MAX_VALUE; index++) {
                    final String logIdRegexN = getString(name, LOG_REGEX + index, config, baseConfig);
                    if (logIdRegexN == null) {
                        break;
                    }
                    logIdRegexs.add(logIdRegexN);
                }
                if (logIdRegexs.size() > 1) {
                    throw new ConfigInvalidException("More than three " + LOG_REGEX + " entries found. This is not supported anymore since bugtraq version 0.3, use " + LOG_FILTERREGEX + " and " + LOG_LINKREGEX + " instead.");
                } else if (logIdRegexs.size() == 1) {
                    filterRegex = idRegex;
                    idRegex = logIdRegexs.get(0);
                }
            }
        }
        final String linkText = getString(name, LOG_LINKTEXT, config, baseConfig);
        entries.add(new BugtraqEntry(url, idRegex, linkRegex, filterRegex, linkText));
    }
    if (entries.isEmpty()) {
        return null;
    }
    return new BugtraqConfig(entries);
}
Also used : ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) Config(org.eclipse.jgit.lib.Config) FileBasedConfig(org.eclipse.jgit.storage.file.FileBasedConfig) ArrayList(java.util.ArrayList) IOException(java.io.IOException) HashSet(java.util.HashSet) Nullable(org.jetbrains.annotations.Nullable)

Example 3 with Config

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

the class NewRepositoryPage method initialCommit.

/**
	 * Prepare the initial commit for the repository.
	 *
	 * @param repository
	 * @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;
}
Also used : DirCacheBuilder(org.eclipse.jgit.dircache.DirCacheBuilder) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) ObjectId(org.eclipse.jgit.lib.ObjectId) Config(org.eclipse.jgit.lib.Config) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Result(org.eclipse.jgit.lib.RefUpdate.Result) UserModel(com.gitblit.models.UserModel) DirCache(org.eclipse.jgit.dircache.DirCache) Repository(org.eclipse.jgit.lib.Repository) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) PersonIdent(org.eclipse.jgit.lib.PersonIdent) File(java.io.File) RevCommit(org.eclipse.jgit.revwalk.RevCommit) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Example 4 with Config

use of org.eclipse.jgit.lib.Config in project gerrit by GerritCodeReview.

the class SubmoduleSubscriptionsWholeTopicMergeIT method sameProjectSameBranchDifferentPaths.

@Test
public void sameProjectSameBranchDifferentPaths() throws Exception {
    TestRepository<?> superRepo = createProjectWithPush("super-project");
    TestRepository<?> sub = createProjectWithPush("sub");
    allowMatchingSubmoduleSubscription("sub", "refs/heads/master", "super-project", "refs/heads/master");
    Config config = new Config();
    prepareSubmoduleConfigEntry(config, "sub", "master");
    prepareSubmoduleConfigEntry(config, "sub", "sub-copy", "master");
    pushSubmoduleConfig(superRepo, "master", config);
    ObjectId superPreviousId = pushChangeTo(superRepo, "master");
    ObjectId subId = pushChangeTo(sub, "refs/for/master", "some message", "");
    approve(getChangeId(sub, subId).get());
    gApi.changes().id(getChangeId(sub, subId).get()).current().submit();
    expectToHaveSubmoduleState(superRepo, "master", "sub", sub, "master");
    expectToHaveSubmoduleState(superRepo, "master", "sub-copy", sub, "master");
    superRepo.git().fetch().setRemote("origin").call().getAdvertisedRef("refs/heads/master").getObjectId();
    assertWithMessage("submodule subscription update should have made one commit").that(superRepo.getRepository().resolve("origin/master^")).isEqualTo(superPreviousId);
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) Config(org.eclipse.jgit.lib.Config) Test(org.junit.Test)

Example 5 with Config

use of org.eclipse.jgit.lib.Config in project gerrit by GerritCodeReview.

the class AbstractSubmoduleSubscription method createSubmoduleSubscription.

protected void createSubmoduleSubscription(TestRepository<?> repo, String branch, String subscribeToRepo, String subscribeToBranch) throws Exception {
    Config config = new Config();
    prepareSubmoduleConfigEntry(config, subscribeToRepo, subscribeToBranch);
    pushSubmoduleConfig(repo, branch, config);
}
Also used : Config(org.eclipse.jgit.lib.Config) ProjectConfig(com.google.gerrit.server.git.ProjectConfig)

Aggregations

Config (org.eclipse.jgit.lib.Config)123 Test (org.junit.Test)41 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)19 Project (com.google.gerrit.reviewdb.client.Project)18 ProjectConfig (com.google.gerrit.server.git.ProjectConfig)15 Branch (com.google.gerrit.reviewdb.client.Branch)14 SubmoduleSubscription (com.google.gerrit.reviewdb.client.SubmoduleSubscription)14 SubmoduleSectionParser (com.google.gerrit.server.util.SubmoduleSectionParser)14 GerritServerConfig (com.google.gerrit.server.config.GerritServerConfig)11 ObjectId (org.eclipse.jgit.lib.ObjectId)9 Before (org.junit.Before)8 PluginConfig (com.google.gerrit.server.config.PluginConfig)6 InMemoryModule (com.google.gerrit.testutil.InMemoryModule)6 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)6 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)5 Injector (com.google.inject.Injector)5 ArrayList (java.util.ArrayList)5 Account (com.google.gerrit.reviewdb.client.Account)4 SitePaths (com.google.gerrit.server.config.SitePaths)4 InMemoryRepository (org.eclipse.jgit.internal.storage.dfs.InMemoryRepository)4