How to use the dbutils.Branch function in DBUtils

To help you get started, we’ve selected a few DBUtils examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jensl / critic / src / background / maintenance.py View on Github external
WHERE scheduledreviewbrancharchivals.deadline <= NOW()
                                     AND reviews.state IN ('closed', 'dropped')
                                     AND NOT branches.archived
                                ORDER BY branches.repository""",
                               for_update=True)

                for repository_id, branch_id, branch_name in cursor:
                    if not repository or repository.id != repository_id:
                        if repository:
                            repository.stopBatch()
                        repository = gitutils.Repository.fromId(db, repository_id)
                        self.info("archiving branches in: " + repository.name)

                    self.info("  " + branch_name)

                    branch = dbutils.Branch.fromId(db, branch_id, repository=repository)

                    try:
                        branch.archive(db)
                    except Exception:
                        self.exception(as_warning=True)

                # Since NOW() returns the same value each time within a single
                # transaction, this is guaranteed to delete only the set of
                # archivals we selected above.
                cursor.execute("""DELETE
                                    FROM scheduledreviewbrancharchivals
                                   WHERE deadline <= NOW()""")

                db.commit()

            # Run a garbage collect in all Git repositories, to keep them neat
github jensl / critic / src / maintenance / check-branches.py View on Github external
continue
                    except KeyboardInterrupt: sys.exit(1)
                    except:
                        progress.write("  reachable contains missing commits")
        except KeyboardInterrupt: sys.exit(1)
        except:
            progress.write("WARNING[%s]: %s missing!" % (repository.name, branch_name))

            if branch_type == "normal":
                cursor.execute("SELECT id FROM branches WHERE base=%s", (branch_id,))

                sub_branches = cursor.fetchall()
                if sub_branches:
                    progress.write("  branch has sub-branches")

                    base_branch = dbutils.Branch.fromId(db, branch_base_id)

                    for (sub_branch_id,) in sub_branches:
                        sub_branch = dbutils.Branch.fromId(db, sub_branch_id)
                        sub_branch.rebase(db, base_branch)
                        progress.write("    rebased sub-branch %s" % sub_branch.name)

                try:
                    if force:
                        cursor.execute("DELETE FROM branches WHERE id=%s", (branch_id,))
                        db.commit()
                    progress.write("  deleted from database")
                except KeyboardInterrupt: sys.exit(1)
                except:
                    progress.write("  failed to delete from database")
                    db.rollback()
            else:
github jensl / critic / src / reviewing / utils.py View on Github external
def createReview(db, user, repository, commits, branch_name, summary, description, from_branch_name=None, via_push=False, reviewfilters=None, applyfilters=True, applyparentfilters=False, recipientfilters=None):
    cursor = db.cursor()

    if via_push:
        applyparentfilters = bool(user.getPreference(db, 'review.applyUpstreamFilters'))

    branch = dbutils.Branch.fromName(db, repository, branch_name)

    if branch is not None:
        raise OperationFailure(
            code="branchexists",
            title="Invalid review branch name",
            message="""\
<p>There is already a branch named <code>%s</code> in the repository.  You have
to select a different name.</p>

<p>If you believe the existing branch was created during an earlier (failed)
attempt to create this review, you can try to delete it from the repository
using the command</p><p>

</p><pre>  git push &lt;remote&gt; :%s</pre>

<p>and then press the "Submit Review" button on this page again."""</p>
github jensl / critic / src / index.py View on Github external
def deleteBranch(db, user, repository, name, old):
    try:
        update(repository.path, "refs/heads/" + name, old, None)
    except Reject as rejected:
        raise IndexException(str(rejected))
    except Exception:
        pass

    branch = dbutils.Branch.fromName(db, repository, name)

    if branch:
        review = dbutils.Review.fromBranch(db, branch)

        if review:
            raise IndexException("This is Critic refusing to delete a branch that belongs to a review.")

        cursor = db.cursor()
        cursor.execute("SELECT COUNT(*) FROM reachable WHERE branch=%s", (branch.id,))

        ncommits = cursor.fetchone()[0]

        if branch.base:
            cursor.execute("UPDATE branches SET base=%s WHERE base=%s", (branch.base.id, branch.id))

        cursor.execute("DELETE FROM branches WHERE id=%s", (branch.id,))
github jensl / critic / src / gitutils.py View on Github external
def getHeadBranch(self, db):
        """Return the branch that HEAD references

           None is returned if HEAD is not a symbolic ref or if it references a
           ref not under refs/heads/."""
        import dbutils
        try:
            ref_name = self.run("symbolic-ref", "--quiet", "HEAD").strip()
        except GitCommandError:
            # HEAD is not a symbolic ref.
            pass
        else:
            if ref_name.startswith("refs/heads/"):
                branch_name = ref_name[len("refs/heads/"):]
                return dbutils.Branch.fromName(db, self, branch_name)
github jensl / critic / src / index.py View on Github external
commits = set()
    commit_list = []
    processed = set()

    while stack:
        sha1 = stack.pop()

        if sha1 not in commits and not isreachable(sha1):
            commits.add(sha1)
            commit_list.append(sha1)

            stack.extend([parent_sha1 for parent_sha1 in gitutils.Commit.fromSHA1(db, repository, sha1).parents if parent_sha1 not in processed])

        processed.add(sha1)

    branch = dbutils.Branch.fromName(db, repository, name)
    review = dbutils.Review.fromBranch(db, branch)

    if review:
        if review.state != "open":
            raise IndexException("""\
The review is closed and can't be extended.  You need to reopen it at
%s
before you can add commits to it.""" % review.getURL(db, user, 2))

        all_commits = [gitutils.Commit.fromSHA1(db, repository, sha1) for sha1 in reversed(commit_list)]

        tails = CommitSet(all_commits).getTails()

        if old not in tails:
            raise IndexException("""\
Push rejected; would break the review.
github jensl / critic / dbutils.py View on Github external
    @staticmethod
    def fromId(db, review_id, branch=None, load_commits=True, profiler=None):
        cursor = db.cursor()
        cursor.execute("SELECT type, branch, state, serial, summary, description, applyfilters, applyparentfilters FROM reviews WHERE id=%s", [review_id])
        row = cursor.fetchone()
        if not row: return None

        type, branch_id, state, serial, summary, description, applyfilters, applyparentfilters = row

        if profiler: profiler.check("Review.fromId: basic")

        if branch is None:
            branch = Branch.fromId(db, branch_id, load_review=False, load_commits=load_commits, profiler=profiler)

        cursor.execute("SELECT uid FROM reviewusers WHERE review=%s AND owner", (review_id,))

        owners = User.fromIds(db, [user_id for (user_id,) in cursor])

        if profiler: profiler.check("Review.fromId: owners")

        review = Review(review_id, owners, type, branch, state, serial, summary, description, applyfilters, applyparentfilters)
        branch.review = review

        # Reviewers: all users that have at least one review file assigned to them.
        cursor.execute("""SELECT DISTINCT uid, assignee IS NOT NULL, type
                            FROM reviewusers
                 LEFT OUTER JOIN fullreviewuserfiles ON (fullreviewuserfiles.review=reviewusers.review AND assignee=uid)
                           WHERE reviewusers.review=%s""",
                       (review_id,))
github jensl / critic / src / dbutils / review.py View on Github external
def fromId(db, review_id, branch=None, profiler=None):
        from dbutils import User

        cursor = db.cursor()
        cursor.execute("SELECT type, branch, state, serial, summary, description, applyfilters, applyparentfilters FROM reviews WHERE id=%s", [review_id])
        row = cursor.fetchone()
        if not row: raise NoSuchReview(review_id)

        type, branch_id, state, serial, summary, description, applyfilters, applyparentfilters = row

        if profiler: profiler.check("Review.fromId: basic")

        if branch is None:
            from dbutils import Branch
            branch = Branch.fromId(db, branch_id, load_review=False, profiler=profiler)

        cursor.execute("SELECT uid FROM reviewusers WHERE review=%s AND owner", (review_id,))

        owners = User.fromIds(db, [user_id for (user_id,) in cursor])

        if profiler: profiler.check("Review.fromId: owners")

        review = Review(review_id, owners, type, branch, state, serial, summary, description, applyfilters, applyparentfilters)
        branch.review = review

        # Reviewers: all users that have at least one review file assigned to them.
        cursor.execute("""SELECT DISTINCT uid, assignee IS NOT NULL, type
                            FROM reviewusers
                 LEFT OUTER JOIN fullreviewuserfiles ON (fullreviewuserfiles.review=reviewusers.review AND assignee=uid)
                           WHERE reviewusers.review=%s""",
                       (review_id,))
github jensl / critic / src / page / showbranch.py View on Github external
repository = req.getParameter("repository", user.getPreference(db, "defaultRepository"))
    if not repository:
        raise request.MissingParameter("repository")
    repository = gitutils.Repository.fromParameter(db, repository)

    cursor = db.cursor()

    cursor.execute("SELECT id, type, base, head, tail FROM branches WHERE name=%s AND repository=%s", (branch_name, repository.id))

    try:
        branch_id, branch_type, base_id, head_id, tail_id = cursor.fetchone()
    except:
        return page.utils.displayMessage(db, req, user, "'%s' doesn't name a branch!" % branch_name)

    branch = dbutils.Branch.fromName(db, repository, branch_name)
    rebased = False

    if base_name:
        base = dbutils.Branch.fromName(db, repository, base_name)

        if base is None:
            return page.utils.displayMessage(db, req, user, "'%s' doesn't name a branch!" % base_name)

        old_count, new_count, base_old_count, base_new_count = branch.rebase(db, base)

        if base_old_count is not None:
            new_base_base_name = base.base.name
        else:
            new_base_base_name = None

        rebased = True