Return Mercurial revision for the repository located at repopath
       Result is a tuple (global, local, branch), with None values on error
       For example:
           >>> get_hg_revision(".")
           ('eba7273c69df+', '2015+', 'default')
509465
def get_hg_revision(repopath):
    
    try:
        assert osp.isdir(osp.join(repopath, '.hg'))
        proc = programs.run_program('hg', ['id', '-nib', repopath])
        output, _err = proc.communicate()
        # output is now: ('eba7273c69df+ 2015+ default\n', None)
        # Split 2 times max to allow spaces in branch names.
        return tuple(output.decode().strip().split(None, 2))
    except (subprocess.CalledProcessError, AssertionError, AttributeError,
            OSError):
        return (None, None, None)
717997
def _get_revision(self, revision):
        

        is_null = lambda o: len(o) == revision.count('0')

        try:
            self.revisions[0]
        except (KeyError, IndexError):
            raise EmptyRepositoryError("There are no changesets yet")

        if revision in (None, '', 'tip', 'HEAD', 'head', -1):
            return self.revisions[-1]

        is_bstr = isinstance(revision, (str, unicode))
        if ((is_bstr and revision.isdigit() and len(revision) < 12)
            or isinstance(revision, int) or is_null(revision)):
            try:
                revision = self.revisions[int(revision)]
            except Exception:
                raise ChangesetDoesNotExistError("Revision %s does not exist "
                    "for this repository" % (revision))

        elif is_bstr:
            # get by branch/tag name
            _ref_revision = self._parsed_refs.get(revision)
            if _ref_revision:  # and _ref_revision[1] in ['H', 'RH', 'T']:
                return _ref_revision[0]

            _tags_shas = self.tags.values()
            # maybe it's a tag ? we don't have them in self.revisions
            if revision in _tags_shas:
                return _tags_shas[_tags_shas.index(revision)]

            elif not SHA_PATTERN.match(revision) or revision not in self.revisions:
                raise ChangesetDoesNotExistError("Revision %s does not exist "
                    "for this repository" % (revision))

        # Ensure we return full id
        if not SHA_PATTERN.match(str(revision)):
            raise ChangesetDoesNotExistError("Given revision %s not recognized"
                % revision)
        return revision
992910
def revision(directory=None, message=None, autogenerate=False, sql=False,
             head='head', splice=False, branch_label=None, version_path=None,
             rev_id=None):
    """"""
    config = current_app.extensions['migrate'].migrate.get_config(directory)
    if alembic_version >= (0, 7, 0):
        command.revision(config, message, autogenerate=autogenerate, sql=sql,
                         head=head, splice=splice, branch_label=branch_label,
                         version_path=version_path, rev_id=rev_id)
    else:
        command.revision(config, message, autogenerate=autogenerate, sql=sql)
550591
def get_git_version(cls):
        
        try:
            output = cls.run_git_shell('git version')
        except CalledProcessError:
            cls.LOG.warning("Unable to get Git version.")
            return None

        try:
            version = output.split()[2]
        except IndexError:
            cls.LOG.warning("Unable to parse Git version \"%s\".", output)
            return None

        try:
            return tuple(int(v) for v in version.split('.'))
        except ValueError:
            cls.LOG.warning("Unable to parse Git version \"%s\".", version)
            return None
1351338
def get_revision():
	
	git_bin = smoke_zephyr.utilities.which('git')
	if not git_bin:
		return None
	proc_h = subprocess.Popen(
		(git_bin, 'rev-parse', 'HEAD'),
		stdout=subprocess.PIPE,
		stderr=subprocess.PIPE,
		close_fds=True,
		cwd=os.path.dirname(os.path.abspath(__file__))
	)
	rev = proc_h.stdout.read().strip()
	proc_h.wait()
	if not len(rev):
		return None
	return rev.decode('utf-8')
1314469
def get_version(
    root=".",
    version_scheme="guess-next-dev",
    local_scheme="node-and-date",
    write_to=None,
    write_to_template=None,
    relative_to=None,
    tag_regex=None,
    fallback_version=None,
    parse=None,
    git_describe_command=None,
):
    

    config = Configuration()
    config.root = root
    config.version_scheme = version_scheme
    config.local_scheme = local_scheme
    config.write_to = write_to
    config.write_to_template = write_to_template
    config.relative_to = relative_to
    config.tag_regex = tag_regex
    config.fallback_version = fallback_version
    config.parse = parse
    config.git_describe_command = git_describe_command

    parsed_version = _do_parse(config)

    if parsed_version:
        version_string = format_version(
            parsed_version, version_scheme=version_scheme, local_scheme=local_scheme
        )
        dump_version(
            root=root,
            version=version_string,
            write_to=write_to,
            template=write_to_template,
        )

        return version_string
759024
def _get_local_rev_and_branch(target, user, password, output_encoding=None):
    '''
    
    '''
    log.info('Checking local revision for %s', target)
    try:
        local_rev = __salt__['git.revision'](
            target,
            user=user,
            password=password,
            ignore_retcode=True,
            output_encoding=output_encoding)
    except CommandExecutionError:
        log.info('No local revision for %s', target)
        local_rev = None

    log.info('Checking local branch for %s', target)
    try:
        local_branch = __salt__['git.current_branch'](
            target,
            user=user,
            password=password,
            ignore_retcode=True,
            output_encoding=output_encoding)
    except CommandExecutionError:
        log.info('No local branch for %s', target)
        local_branch = None

    return local_rev, local_branch
1267368
def do_tortoisehg_report(repos, output):
    
    import operator
    import xml.etree.ElementTree as ET

    root = ET.Element('reporegistry')
    item = ET.SubElement(root, 'treeitem')

    group = ET.SubElement(item, 'group', attrib=Dict(name='groupname'))

    def fullname_to_shortname(fullname):
        """
        Return a TortoiseHG-friendly path to a repository

        Args:
            fullname (str): path to repository

        Returns:
            str: path with $HOME replaced with ``~`` and leading ``./``
                stripped
        """
        shortname = fullname.replace(os.environ['HOME'], '~')
        shortname = shortname.lstrip('./')
        return shortname

    for repo in sorted(repos, key=operator.attrgetter('fpath')):
        fullname = os.path.join(
            os.path.dirname(repo.fpath),
            os.path.basename(repo.fpath))
        shortname = fullname_to_shortname(fullname)
        if repo.prefix != '.hg':
            shortname = "%s%s" % (shortname, repo.prefix)
        _ = ET.SubElement(group, 'repo',
                          attrib=Dict(
                              root=repo.fpath,
                              shortname=shortname,
                              basenode='0'*40))
        _
    print('<?xml version="1.0" encoding="UTF-8"?>', file=output)
    print("<!-- autogenerated: %s -->" % "TODO", file=output)
    print(ET.dump(root), file=output)
357429
def default_repository(self):
        
        default_dict_repo = {}
        for line in self.default_repositories_list.splitlines():
            line = line.lstrip()
            if not line.startswith("#"):
                if line.split()[0] in self.DEFAULT_REPOS_NAMES:
                    default_dict_repo[line.split()[0]] = line.split()[1]
                else:
                    print("\nslpkg: Error: Repository name '{0}' is not "
                          "default.\n              Please check file: "
                          "/etc/slpkg/default-repositories\n".format(
                              line.split()[0]))
                    raise SystemExit()
        return default_dict_repo
747470
def _svn_revision(filename):
  
  p = subprocess.Popen(['svn', 'status', '-v', filename],
             stdout=subprocess.PIPE,
             stderr=subprocess.PIPE)
  (stdout, stderr) = p.communicate()
  if p.returncode != 0 or stderr or not stdout:
    raise ValueError('Error determining svn_revision for %s: %s' %
             (os.path.split(filename)[1], textwrap.fill(stderr)))
  return stdout.split()[2]
547575
function getVersion(repo) {
    const git = path.join(repo, '.git');
    const headPath = path.join(git, 'HEAD');
    let head;
    try {
        head = fs.readFileSync(headPath, 'utf8').trim();
    }
    catch (e) {
        return undefined;
    }
    if (/^[0-9a-f]{40}$/i.test(head)) {
        return head;
    }
    const refMatch = /^ref: (.*)$/.exec(head);
    if (!refMatch) {
        return undefined;
    }
    const ref = refMatch[1];
    const refPath = path.join(git, ref);
    try {
        return fs.readFileSync(refPath, 'utf8').trim();
    }
    catch (e) {
        // noop
    }
    const packedRefsPath = path.join(git, 'packed-refs');
    let refsRaw;
    try {
        refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
    }
    catch (e) {
        return undefined;
    }
    const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
    let refsMatch;
    let refs = {};
    while (refsMatch = refsRegex.exec(refsRaw)) {
        refs[refsMatch[2]] = refsMatch[1];
    }
    return refs[ref];
}
876386
def find_revision_number(self, revision=None):
        """"""
        # Make sure the local repository exists.
        self.create()
        # Try to find the revision number of the specified revision.
        revision = self.expand_branch_name(revision)
        output = self.context.capture('git', 'rev-list', revision, '--count')
        if not (output and output.isdigit()):
            msg = "Failed to find local revision number! ('git rev-list --count' gave unexpected output)"
            raise ValueError(msg)
        return int(output)
1051581
def find_tags(self):
        """"""
        listing = self.context.capture('hg', 'tags')
        for line in listing.splitlines():
            tokens = line.split()
            if len(tokens) >= 2 and ':' in tokens[1]:
                revision_number, revision_id = tokens[1].split(':')
                yield Revision(
                    repository=self,
                    revision_id=revision_id,
                    revision_number=int(revision_number),
                    tag=tokens[0],
                )
488603
def get_changeset(self, revision=None):
        
        if isinstance(revision, GitChangeset):
            return revision
        revision = self._get_revision(revision)
        changeset = GitChangeset(repository=self, revision=revision)
        return changeset
117872
def git_repo():
    
    try:
        reldir = subprocess.check_output(
            ["git", "rev-parse", "--git-dir"])
        reldir = reldir.decode("utf-8")
        return os.path.basename(os.path.dirname(os.path.abspath(reldir)))
    except subprocess.CalledProcessError:
        return None
466118
def fetch_git_sha(path, head=None):
    
    if not head:
        head_path = os.path.join(path, '.git', 'HEAD')
        if not os.path.exists(head_path):
            raise InvalidGitRepository(
                'Cannot identify HEAD for git repository at %s' % (path,))

        with open(head_path, 'r') as fp:
            head = text_type(fp.read()).strip()

        if head.startswith('ref: '):
            head = head[5:]
            revision_file = os.path.join(
                path, '.git', *head.split('/')
            )
        else:
            return head
    else:
        revision_file = os.path.join(path, '.git', 'refs', 'heads', head)

    if not os.path.exists(revision_file):
        if not os.path.exists(os.path.join(path, '.git')):
            raise InvalidGitRepository(
                '%s does not seem to be the root of a git repository' % (path,))

        # Check for our .git/packed-refs' file since a `git gc` may have run
        # https://git-scm.com/book/en/v2/Git-Internals-Maintenance-and-Data-Recovery
        packed_file = os.path.join(path, '.git', 'packed-refs')
        if os.path.exists(packed_file):
            with open(packed_file) as fh:
                for line in fh:
                    line = line.rstrip()
                    if line and line[:1] not in ('#', '^'):
                        try:
                            revision, ref = line.split(' ', 1)
                        except ValueError:
                            continue
                        if ref == head:
                            return text_type(revision)

        raise InvalidGitRepository(
            'Unable to find ref to head "%s" in repository' % (head,))

    with open(revision_file) as fh:
        return text_type(fh.read()).strip()
387818
def revision(self):
        """"""
        location, _, revision = self.expression.partition('#')
        return revision if location and revision else self.expression