Search in sources :

Example 76 with ConfigInvalidException

use of org.eclipse.jgit.errors.ConfigInvalidException in project gerrit by GerritCodeReview.

the class ExternalIdsUpdate method updateNoteMap.

private RefsMetaExternalIdsUpdate updateNoteMap(MyConsumer<OpenRepo> update) throws IOException, ConfigInvalidException, OrmException {
    try {
        return retryer.call(() -> {
            try (Repository repo = repoManager.openRepository(allUsersName);
                ObjectInserter ins = repo.newObjectInserter()) {
                ObjectId rev = readRevision(repo);
                afterReadRevision.run();
                try (RevWalk rw = new RevWalk(repo)) {
                    NoteMap noteMap = readNoteMap(rw, rev);
                    update.accept(OpenRepo.create(repo, rw, ins, noteMap));
                    return commit(repo, rw, ins, rev, noteMap);
                }
            }
        });
    } catch (ExecutionException | RetryException e) {
        if (e.getCause() != null) {
            Throwables.throwIfInstanceOf(e.getCause(), IOException.class);
            Throwables.throwIfInstanceOf(e.getCause(), ConfigInvalidException.class);
            Throwables.throwIfInstanceOf(e.getCause(), OrmException.class);
        }
        throw new OrmException(e);
    }
}
Also used : Repository(org.eclipse.jgit.lib.Repository) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ObjectId(org.eclipse.jgit.lib.ObjectId) OrmException(com.google.gwtorm.server.OrmException) NoteMap(org.eclipse.jgit.notes.NoteMap) ExternalIdReader.readNoteMap(com.google.gerrit.server.account.externalids.ExternalIdReader.readNoteMap) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) ExecutionException(java.util.concurrent.ExecutionException) RetryException(com.github.rholder.retry.RetryException)

Example 77 with ConfigInvalidException

use of org.eclipse.jgit.errors.ConfigInvalidException in project gerrit by GerritCodeReview.

the class VersionedMetaData method openUpdate.

/**
   * Open a batch of updates to the same metadata ref.
   *
   * <p>This allows making multiple commits to a single metadata ref, at the end of which is a
   * single ref update. For batching together updates to multiple refs (each consisting of one or
   * more commits against their respective refs), create the {@link MetaDataUpdate} with a {@link
   * BatchRefUpdate}.
   *
   * <p>A ref update produced by this {@link BatchMetaDataUpdate} is only committed if there is no
   * associated {@link BatchRefUpdate}. As a result, the configured ref updated event is not fired
   * if there is an associated batch.
   *
   * @param update helper info about the update.
   * @throws IOException if the update failed.
   */
public BatchMetaDataUpdate openUpdate(final MetaDataUpdate update) throws IOException {
    final Repository db = update.getRepository();
    reader = db.newObjectReader();
    inserter = db.newObjectInserter();
    final RevWalk rw = new RevWalk(reader);
    final RevTree tree = revision != null ? rw.parseTree(revision) : null;
    newTree = readTree(tree);
    return new BatchMetaDataUpdate() {

        AnyObjectId src = revision;

        AnyObjectId srcTree = tree;

        @Override
        public void write(CommitBuilder commit) throws IOException {
            write(VersionedMetaData.this, commit);
        }

        private boolean doSave(VersionedMetaData config, CommitBuilder commit) throws IOException {
            DirCache nt = config.newTree;
            ObjectReader r = config.reader;
            ObjectInserter i = config.inserter;
            try {
                config.newTree = newTree;
                config.reader = reader;
                config.inserter = inserter;
                return config.onSave(commit);
            } catch (ConfigInvalidException e) {
                throw new IOException("Cannot update " + getRefName() + " in " + db.getDirectory() + ": " + e.getMessage(), e);
            } finally {
                config.newTree = nt;
                config.reader = r;
                config.inserter = i;
            }
        }

        @Override
        public void write(VersionedMetaData config, CommitBuilder commit) throws IOException {
            if (!doSave(config, commit)) {
                return;
            }
            ObjectId res = newTree.writeTree(inserter);
            if (res.equals(srcTree) && !update.allowEmpty() && (commit.getTreeId() == null)) {
                // If there are no changes to the content, don't create the commit.
                return;
            }
            // the tree for the updated DirCache.
            if (commit.getTreeId() == null) {
                commit.setTreeId(res);
            } else {
                // In this case, the caller populated the tree without using DirCache.
                res = commit.getTreeId();
            }
            if (src != null) {
                commit.addParentId(src);
            }
            if (update.insertChangeId()) {
                ObjectId id = ChangeIdUtil.computeChangeId(res, getRevision(), commit.getAuthor(), commit.getCommitter(), commit.getMessage());
                commit.setMessage(ChangeIdUtil.insertId(commit.getMessage(), id));
            }
            src = inserter.insert(commit);
            srcTree = res;
        }

        @Override
        public RevCommit createRef(String refName) throws IOException {
            if (Objects.equals(src, revision)) {
                return revision;
            }
            return updateRef(ObjectId.zeroId(), src, refName);
        }

        @Override
        public void removeRef(String refName) throws IOException {
            RefUpdate ru = db.updateRef(refName);
            ru.setForceUpdate(true);
            if (revision != null) {
                ru.setExpectedOldObjectId(revision);
            }
            RefUpdate.Result result = ru.delete();
            switch(result) {
                case FORCED:
                    update.fireGitRefUpdatedEvent(ru);
                    return;
                case LOCK_FAILURE:
                    throw new LockFailureException("Cannot delete " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult());
                case FAST_FORWARD:
                case IO_FAILURE:
                case NEW:
                case NOT_ATTEMPTED:
                case NO_CHANGE:
                case REJECTED:
                case REJECTED_CURRENT_BRANCH:
                case RENAMED:
                default:
                    throw new IOException("Cannot delete " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult());
            }
        }

        @Override
        public RevCommit commit() throws IOException {
            return commitAt(revision);
        }

        @Override
        public RevCommit commitAt(ObjectId expected) throws IOException {
            if (Objects.equals(src, expected)) {
                return revision;
            }
            return updateRef(MoreObjects.firstNonNull(expected, ObjectId.zeroId()), src, getRefName());
        }

        @Override
        public void close() {
            newTree = null;
            rw.close();
            if (inserter != null) {
                inserter.close();
                inserter = null;
            }
            if (reader != null) {
                reader.close();
                reader = null;
            }
        }

        private RevCommit updateRef(AnyObjectId oldId, AnyObjectId newId, String refName) throws IOException {
            BatchRefUpdate bru = update.getBatch();
            if (bru != null) {
                bru.addCommand(new ReceiveCommand(oldId.toObjectId(), newId.toObjectId(), refName));
                inserter.flush();
                revision = rw.parseCommit(newId);
                return revision;
            }
            RefUpdate ru = db.updateRef(refName);
            ru.setExpectedOldObjectId(oldId);
            ru.setNewObjectId(src);
            ru.setRefLogIdent(update.getCommitBuilder().getAuthor());
            String message = update.getCommitBuilder().getMessage();
            if (message == null) {
                message = "meta data update";
            }
            try (BufferedReader reader = new BufferedReader(new StringReader(message))) {
                // read the subject line and use it as reflog message
                ru.setRefLogMessage("commit: " + reader.readLine(), true);
            }
            inserter.flush();
            RefUpdate.Result result = ru.update();
            switch(result) {
                case NEW:
                case FAST_FORWARD:
                    revision = rw.parseCommit(ru.getNewObjectId());
                    update.fireGitRefUpdatedEvent(ru);
                    return revision;
                case LOCK_FAILURE:
                    throw new LockFailureException("Cannot update " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult());
                case FORCED:
                case IO_FAILURE:
                case NOT_ATTEMPTED:
                case NO_CHANGE:
                case REJECTED:
                case REJECTED_CURRENT_BRANCH:
                case RENAMED:
                default:
                    throw new IOException("Cannot update " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult());
            }
        }
    };
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) AnyObjectId(org.eclipse.jgit.lib.AnyObjectId) ObjectId(org.eclipse.jgit.lib.ObjectId) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) AnyObjectId(org.eclipse.jgit.lib.AnyObjectId) DirCache(org.eclipse.jgit.dircache.DirCache) Repository(org.eclipse.jgit.lib.Repository) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) ObjectReader(org.eclipse.jgit.lib.ObjectReader) RevTree(org.eclipse.jgit.revwalk.RevTree) BatchRefUpdate(org.eclipse.jgit.lib.BatchRefUpdate) RefUpdate(org.eclipse.jgit.lib.RefUpdate) BatchRefUpdate(org.eclipse.jgit.lib.BatchRefUpdate)

Example 78 with ConfigInvalidException

use of org.eclipse.jgit.errors.ConfigInvalidException in project gerrit by GerritCodeReview.

the class Schema_115 method migrateData.

@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
    Map<Account.Id, DiffPreferencesInfo> imports = new HashMap<>();
    try (Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM account_diff_preferences")) {
        Set<String> availableColumns = getColumns(rs);
        while (rs.next()) {
            Account.Id accountId = new Account.Id(rs.getInt("id"));
            DiffPreferencesInfo prefs = new DiffPreferencesInfo();
            if (availableColumns.contains("context")) {
                prefs.context = (int) rs.getShort("context");
            }
            if (availableColumns.contains("expand_all_comments")) {
                prefs.expandAllComments = toBoolean(rs.getString("expand_all_comments"));
            }
            if (availableColumns.contains("hide_line_numbers")) {
                prefs.hideLineNumbers = toBoolean(rs.getString("hide_line_numbers"));
            }
            if (availableColumns.contains("hide_top_menu")) {
                prefs.hideTopMenu = toBoolean(rs.getString("hide_top_menu"));
            }
            if (availableColumns.contains("ignore_whitespace")) {
                // Enum with char as value
                prefs.ignoreWhitespace = toWhitespace(rs.getString("ignore_whitespace"));
            }
            if (availableColumns.contains("intraline_difference")) {
                prefs.intralineDifference = toBoolean(rs.getString("intraline_difference"));
            }
            if (availableColumns.contains("line_length")) {
                prefs.lineLength = rs.getInt("line_length");
            }
            if (availableColumns.contains("manual_review")) {
                prefs.manualReview = toBoolean(rs.getString("manual_review"));
            }
            if (availableColumns.contains("render_entire_file")) {
                prefs.renderEntireFile = toBoolean(rs.getString("render_entire_file"));
            }
            if (availableColumns.contains("retain_header")) {
                prefs.retainHeader = toBoolean(rs.getString("retain_header"));
            }
            if (availableColumns.contains("show_line_endings")) {
                prefs.showLineEndings = toBoolean(rs.getString("show_line_endings"));
            }
            if (availableColumns.contains("show_tabs")) {
                prefs.showTabs = toBoolean(rs.getString("show_tabs"));
            }
            if (availableColumns.contains("show_whitespace_errors")) {
                prefs.showWhitespaceErrors = toBoolean(rs.getString("show_whitespace_errors"));
            }
            if (availableColumns.contains("skip_deleted")) {
                prefs.skipDeleted = toBoolean(rs.getString("skip_deleted"));
            }
            if (availableColumns.contains("skip_uncommented")) {
                prefs.skipUncommented = toBoolean(rs.getString("skip_uncommented"));
            }
            if (availableColumns.contains("syntax_highlighting")) {
                prefs.syntaxHighlighting = toBoolean(rs.getString("syntax_highlighting"));
            }
            if (availableColumns.contains("tab_size")) {
                prefs.tabSize = rs.getInt("tab_size");
            }
            if (availableColumns.contains("theme")) {
                // Enum with name as values; can be null
                prefs.theme = toTheme(rs.getString("theme"));
            }
            if (availableColumns.contains("hide_empty_pane")) {
                prefs.hideEmptyPane = toBoolean(rs.getString("hide_empty_pane"));
            }
            if (availableColumns.contains("auto_hide_diff_table_header")) {
                prefs.autoHideDiffTableHeader = toBoolean(rs.getString("auto_hide_diff_table_header"));
            }
            imports.put(accountId, prefs);
        }
    }
    if (imports.isEmpty()) {
        return;
    }
    try (Repository git = mgr.openRepository(allUsersName);
        RevWalk rw = new RevWalk(git)) {
        BatchRefUpdate bru = git.getRefDatabase().newBatchUpdate();
        for (Map.Entry<Account.Id, DiffPreferencesInfo> e : imports.entrySet()) {
            try (MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsersName, git, bru)) {
                md.getCommitBuilder().setAuthor(serverUser);
                md.getCommitBuilder().setCommitter(serverUser);
                VersionedAccountPreferences p = VersionedAccountPreferences.forUser(e.getKey());
                p.load(md);
                storeSection(p.getConfig(), UserConfigSections.DIFF, null, e.getValue(), DiffPreferencesInfo.defaults());
                p.commit(md);
            }
        }
        bru.execute(rw, NullProgressMonitor.INSTANCE);
    } catch (ConfigInvalidException | IOException ex) {
        throw new OrmException(ex);
    }
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) HashMap(java.util.HashMap) Statement(java.sql.Statement) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Repository(org.eclipse.jgit.lib.Repository) OrmException(com.google.gwtorm.server.OrmException) ResultSet(java.sql.ResultSet) VersionedAccountPreferences(com.google.gerrit.server.account.VersionedAccountPreferences) DiffPreferencesInfo(com.google.gerrit.extensions.client.DiffPreferencesInfo) HashMap(java.util.HashMap) Map(java.util.Map) BatchRefUpdate(org.eclipse.jgit.lib.BatchRefUpdate) MetaDataUpdate(com.google.gerrit.server.git.MetaDataUpdate)

Example 79 with ConfigInvalidException

use of org.eclipse.jgit.errors.ConfigInvalidException in project gerrit by GerritCodeReview.

the class Schema_120 method allowSubmoduleSubscription.

private void allowSubmoduleSubscription(Branch.NameKey subbranch, Branch.NameKey superBranch) throws OrmException {
    try (Repository git = mgr.openRepository(subbranch.getParentKey());
        RevWalk rw = new RevWalk(git)) {
        BatchRefUpdate bru = git.getRefDatabase().newBatchUpdate();
        try (MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, subbranch.getParentKey(), git, bru)) {
            md.getCommitBuilder().setAuthor(serverUser);
            md.getCommitBuilder().setCommitter(serverUser);
            md.setMessage("Added superproject subscription during upgrade");
            ProjectConfig pc = ProjectConfig.read(md);
            SubscribeSection s = null;
            for (SubscribeSection s1 : pc.getSubscribeSections(subbranch)) {
                if (s1.getProject().equals(superBranch.getParentKey())) {
                    s = s1;
                }
            }
            if (s == null) {
                s = new SubscribeSection(superBranch.getParentKey());
                pc.addSubscribeSection(s);
            }
            RefSpec newRefSpec = new RefSpec(subbranch.get() + ":" + superBranch.get());
            if (!s.getMatchingRefSpecs().contains(newRefSpec)) {
                // For the migration we use only exact RefSpecs, we're not trying to
                // generalize it.
                s.addMatchingRefSpec(newRefSpec);
            }
            pc.commit(md);
        }
        bru.execute(rw, NullProgressMonitor.INSTANCE);
    } catch (ConfigInvalidException | IOException e) {
        throw new OrmException(e);
    }
}
Also used : ProjectConfig(com.google.gerrit.server.git.ProjectConfig) Repository(org.eclipse.jgit.lib.Repository) RefSpec(org.eclipse.jgit.transport.RefSpec) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) OrmException(com.google.gwtorm.server.OrmException) SubscribeSection(com.google.gerrit.common.data.SubscribeSection) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) BatchRefUpdate(org.eclipse.jgit.lib.BatchRefUpdate) MetaDataUpdate(com.google.gerrit.server.git.MetaDataUpdate)

Example 80 with ConfigInvalidException

use of org.eclipse.jgit.errors.ConfigInvalidException in project gerrit by GerritCodeReview.

the class Schema_125 method migrateData.

@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException {
    try (Repository git = repoManager.openRepository(allUsersName);
        MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsersName, git)) {
        ProjectConfig config = ProjectConfig.read(md);
        config.getAccessSection(RefNames.REFS_USERS + "*", true).remove(new Permission(Permission.READ));
        GroupReference registered = systemGroupBackend.getGroup(REGISTERED_USERS);
        AccessSection users = config.getAccessSection(RefNames.REFS_USERS + "${" + RefPattern.USERID_SHARDED + "}", true);
        grant(config, users, Permission.READ, true, registered);
        grant(config, users, Permission.PUSH, true, registered);
        grant(config, users, Permission.SUBMIT, true, registered);
        for (LabelType lt : getLabelTypes(config)) {
            if ("Code-Review".equals(lt.getName()) || "Verified".equals(lt.getName())) {
                grant(config, users, lt, lt.getMin().getValue(), lt.getMax().getValue(), registered);
            }
        }
        md.getCommitBuilder().setAuthor(serverUser);
        md.getCommitBuilder().setCommitter(serverUser);
        md.setMessage(COMMIT_MSG);
        config.commit(md);
    } catch (ConfigInvalidException | IOException ex) {
        throw new OrmException(ex);
    }
}
Also used : ProjectConfig(com.google.gerrit.server.git.ProjectConfig) Repository(org.eclipse.jgit.lib.Repository) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) OrmException(com.google.gwtorm.server.OrmException) LabelType(com.google.gerrit.common.data.LabelType) Permission(com.google.gerrit.common.data.Permission) GroupReference(com.google.gerrit.common.data.GroupReference) IOException(java.io.IOException) AccessSection(com.google.gerrit.common.data.AccessSection) MetaDataUpdate(com.google.gerrit.server.git.MetaDataUpdate)

Aggregations

ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)158 IOException (java.io.IOException)95 Inject (com.google.inject.Inject)38 Repository (org.eclipse.jgit.lib.Repository)37 Provider (com.google.inject.Provider)34 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)31 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)30 ArrayList (java.util.ArrayList)30 Account (com.google.gerrit.entities.Account)27 List (java.util.List)26 Set (java.util.Set)26 ObjectId (org.eclipse.jgit.lib.ObjectId)26 AuthException (com.google.gerrit.extensions.restapi.AuthException)25 Config (org.eclipse.jgit.lib.Config)24 Singleton (com.google.inject.Singleton)23 OrmException (com.google.gwtorm.server.OrmException)22 AccountGroup (com.google.gerrit.entities.AccountGroup)21 RevWalk (org.eclipse.jgit.revwalk.RevWalk)21 StorageException (com.google.gerrit.exceptions.StorageException)20 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)20