DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (4f4487cc2d30)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import json
import os
import subprocess
import sys
from abc import ABCMeta, abstractmethod, abstractproperty

GIT_CINNABAR_NOT_FOUND = """
Could not detect `git-cinnabar`.

The `mach try` command requires git-cinnabar to be installed when
pushing from git. For more information and installation instruction,
please see:

    https://github.com/glandium/git-cinnabar
""".lstrip()

HG_PUSH_TO_TRY_NOT_FOUND = """
Could not detect `push-to-try`.

The `mach try` command requires the push-to-try extension enabled
when pushing from hg. Please install it by running:

    $ ./mach mercurial-setup
""".lstrip()

VCS_NOT_FOUND = """
Could not detect version control. Only `hg` or `git` are supported.
""".strip()

UNCOMMITTED_CHANGES = """
ERROR please commit changes before continuing
""".strip()


class VCSHelper(object):
    """A abstract base VCS helper that detects hg or git"""
    __metaclass__ = ABCMeta

    def __init__(self, root):
        self.root = root

    @classmethod
    def find_vcs(cls):
        # First check if we're in an hg repo, if not try git
        commands = (
            ['hg', 'root'],
            ['git', 'rev-parse', '--show-toplevel'],
        )

        for cmd in commands:
            try:
                output = subprocess.check_output(cmd, stderr=open(os.devnull, 'w')).strip()
            except (subprocess.CalledProcessError, OSError):
                continue

            return cmd[0], output
        return None, ''

    @classmethod
    def create(cls):
        vcs, root = cls.find_vcs()
        if not vcs:
            print(VCS_NOT_FOUND)
            sys.exit(1)
        return vcs_class[vcs](root)

    def run(self, cmd):
        try:
            return subprocess.check_output(cmd, stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            print("Error running `{}`:".format(' '.join(cmd)))
            print(e.output)
            raise

    def write_task_config(self, labels, templates=None):
        config = os.path.join(self.root, 'try_task_config.json')
        with open(config, 'w') as fh:
            try_task_config = {'tasks': sorted(labels)}
            if templates:
                try_task_config['templates'] = templates

            json.dump(try_task_config, fh, indent=2)
        return config

    def check_working_directory(self):
        if self.has_uncommitted_changes:
            print(UNCOMMITTED_CHANGES)
            sys.exit(1)

    @abstractmethod
    def push_to_try(self, msg, labels=None):
        pass

    @abstractproperty
    def files_changed(self):
        pass

    @abstractproperty
    def has_uncommitted_changes(self):
        pass


class HgHelper(VCSHelper):

    def push_to_try(self, msg, labels=None, templates=None):
        self.check_working_directory()

        if labels:
            config = self.write_task_config(labels, templates)
            self.run(['hg', 'add', config])

        try:
            return subprocess.check_call(['hg', 'push-to-try', '-m', msg])
        except subprocess.CalledProcessError:
            try:
                self.run(['hg', 'showconfig', 'extensions.push-to-try'])
            except subprocess.CalledProcessError:
                print(HG_PUSH_TO_TRY_NOT_FOUND)
            return 1
        finally:
            self.run(['hg', 'revert', '-a'])

            if labels and os.path.isfile(config):
                os.remove(config)

    @property
    def files_changed(self):
        return self.run(['hg', 'log', '-r', '::. and not public()',
                         '--template', '{join(files, "\n")}\n'])

    @property
    def has_uncommitted_changes(self):
        stat = [s for s in self.run(['hg', 'status', '-amrn']).split() if s]
        return len(stat) > 0


class GitHelper(VCSHelper):

    def push_to_try(self, msg, labels=None, templates=None):
        self.check_working_directory()

        try:
            subprocess.check_output(['git', 'cinnabar', '--version'], stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError:
            print(GIT_CINNABAR_NOT_FOUND)
            return 1

        if labels:
            config = self.write_task_config(labels, templates)
            self.run(['git', 'add', config])

        subprocess.check_call(['git', 'commit', '--allow-empty', '-m', msg])
        try:
            return subprocess.call(['git', 'push', 'hg::ssh://hg.mozilla.org/try',
                                    '+HEAD:refs/heads/branches/default/tip'])
        finally:
            self.run(['git', 'reset', 'HEAD~'])

    @property
    def files_changed(self):
        # This finds the files changed on the current branch based on the
        # diff of the current branch its merge-base base with other branches.
        current_branch = self.run(['git', 'rev-parse', 'HEAD']).strip()
        all_branches = self.run(['git', 'for-each-ref', 'refs/heads', 'refs/remotes',
                                 '--format=%(objectname)']).splitlines()
        other_branches = set(all_branches) - set([current_branch])
        base_commit = self.run(['git', 'merge-base', 'HEAD'] + list(other_branches)).strip()
        return self.run(['git', 'diff', '--name-only', '-z', 'HEAD',
                         base_commit]).strip('\0').split('\0')

    @property
    def has_uncommitted_changes(self):
        stat = [s for s in self.run(['git', 'diff', '--cached', '--name-only',
                                     '--diff-filter=AMD']).split() if s]
        return len(stat) > 0


vcs_class = {
    'git': GitHelper,
    'hg': HgHelper,
}