当前位置: 首页>>代码示例>>Python>>正文


Python common.run_shell_command函数代码示例

本文整理汇总了Python中vcstools.common.run_shell_command函数的典型用法代码示例。如果您正苦于以下问题:Python run_shell_command函数的具体用法?Python run_shell_command怎么用?Python run_shell_command使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了run_shell_command函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: checkout

 def checkout(self, url, version='', verbose=False, shallow=False):
     if self.path_exists():
         sys.stderr.write("Error: cannot checkout into existing directory\n")
         return False
     # make sure that the parent directory exists for #3497
     base_path = os.path.split(self.get_path())[0]
     try:
         os.makedirs(base_path)
     except OSError:
         # OSError thrown if directory already exists this is ok
         pass
     cmd = "hg clone %s %s" % (sanitized(url), self._path)
     value, _, _ = run_shell_command(cmd,
                                     shell=True,
                                     no_filter=True)
     if value != 0:
         if self.path_exists():
             sys.stderr.write("Error: cannot checkout into existing directory\n")
         return False
     if version is not None and version.strip() != '':
         cmd = "hg checkout %s" % sanitized(version)
         value, _, _ = run_shell_command(cmd,
                                         cwd=self._path,
                                         shell=True,
                                         no_filter=True)
         if value != 0:
             return False
     return True
开发者ID:trainman419,项目名称:vcstools,代码行数:28,代码来源:hg.py

示例2: get_version

 def get_version(self, spec=None):
     """
     :param spec: (optional) revisionspec of desired version.  May
       be any revisionspec as returned by 'bzr help revisionspec',
       e.g. a tagname or 'revno:<number>'
     :returns: the current revision number of the repository. Or if
       spec is provided, the number of a revision specified by some
       token.
     """
     if self.detect_presence():
         if spec is not None:
             command = ['bzr log -r %s .' % sanitized(spec)]
             _, output, _ = run_shell_command(command,
                                              shell=True,
                                              cwd=self._path,
                                              us_env=True)
             if output is None or output.strip() == '' or output.startswith("bzr:"):
                 return None
             else:
                 matches = [l for l in output.split('\n') if l.startswith('revno: ')]
                 if len(matches) == 1:
                     return matches[0].split()[1]
         else:
             _, output, _ = run_shell_command('bzr revno --tree',
                                              shell=True,
                                              cwd=self._path,
                                              us_env=True)
             return output.strip()
开发者ID:btubbs,项目名称:vcstools,代码行数:28,代码来源:bzr.py

示例3: _get_branch_parent

    def _get_branch_parent(self, fetch=False, current_branch=None):
        """
        :param fetch: if true, performs git fetch first
        :param current_branch: if not None, this is used as current branch (else extra shell call)
        :returns: (branch, remote) the name of the branch this branch tracks and its remote
        :raises: GitError if fetch fails
        """
        if not self.path_exists():
            return (None, None)
        # get name of configured merge ref.
        branchname = current_branch or self._get_branch()
        if branchname is None:
            return (None, None)

        cmd = 'git config --get %s' % sanitized('branch.%s.merge' % branchname)

        _, output, _ = run_shell_command(cmd,
                                         shell=True,
                                         cwd=self._path)
        if not output:
            return (None, None)
        lines = output.splitlines()
        if len(lines) > 1:
            sys.stderr.write("vcstools unable to handle multiple merge references for branch %s:\n%s\n"
                             % (branchname, output))
            return (None, None)

        # get name of configured remote
        cmd = 'git config --get "branch.%s.remote"' % branchname
        _, output2, _ = run_shell_command(cmd, shell=True, cwd=self._path)
        remote = output2 or self._get_default_remote()

        branch_reference = lines[0]
        # branch_reference is either refname, or /refs/heads/refname, or
        # heads/refname we would like to return refname however,
        # user could also have named any branch
        # "/refs/heads/refname", for some unholy reason check all
        # known branches on remote for refname, then for the odd
        # cases, as git seems to do
        candidate = branch_reference
        if candidate.startswith('refs/'):
            candidate = candidate[len('refs/'):]
        if candidate.startswith('heads/'):
            candidate = candidate[len('heads/'):]
        elif candidate.startswith('tags/'):
            candidate = candidate[len('tags/'):]
        elif candidate.startswith('remotes/'):
            candidate = candidate[len('remotes/'):]

        result = None
        if self._is_remote_branch(candidate, remote_name=remote, fetch=fetch):
            result = candidate
        elif branch_reference != candidate and self._is_remote_branch(branch_reference,
                                                                      remote_name=remote,
                                                                      fetch=False):
            result = branch_reference

        if result is not None:
            return (result, remote)
        return None, None
开发者ID:esteve,项目名称:vcstools,代码行数:60,代码来源:git.py

示例4: checkout

 def checkout(self, url, version='', verbose=False, shallow=False):
     if url is None or url.strip() == '':
         raise ValueError('Invalid empty url : "%s"' % url)
     # make sure that the parent directory exists for #3497
     base_path = os.path.split(self.get_path())[0]
     try:
         os.makedirs(base_path)
     except OSError:
         # OSError thrown if directory already exists this is ok
         pass
     cmd = "hg clone %s %s" % (sanitized(url), self._path)
     value, _, msg = run_shell_command(cmd,
                                       shell=True,
                                       no_filter=True)
     if value != 0:
         if msg:
             sys.logger.error('%s' % msg)
         return False
     if version is not None and version.strip() != '':
         cmd = "hg checkout %s" % sanitized(version)
         value, _, msg = run_shell_command(cmd,
                                         cwd=self._path,
                                         shell=True,
                                         no_filter=True)
         if value != 0:
             if msg:
                 sys.stderr.write('%s\n' % msg)
             return False
     return True
开发者ID:jbohren-forks,项目名称:vcstools,代码行数:29,代码来源:hg.py

示例5: is_commit_in_orphaned_subtree

    def is_commit_in_orphaned_subtree(self, version, mask_self=False, fetch=True):
        """
        checks git log --all (the list of all commits reached by
        references, meaning branches or tags) for version. If it shows
        up, that means git garbage collection will not remove the
        commit. Else it would eventually be deleted.

        :param version: SHA IDs (if partial, caller is responsible for mismatch)
        :param mask_self: whether to consider direct references to this commit (rather than only references on descendants) as well
        :param fetch: whether fetch should be done first for remote refs
        :returns: True if version is not recursively referenced by a branch or tag
        """
        if fetch:
            self._do_fetch()
        if version is not None and version != "":
            cmd = "git show-ref -s"
            _, output, _ = run_shell_command(cmd, shell=True, cwd=self._path)
            refs = output.splitlines()
            # git log over all refs except HEAD
            cmd = "git log " + " ".join(refs)
            if mask_self:
                # %P: parent hashes
                cmd += " --pretty=format:%P"
            else:
                # %H: commit hash
                cmd += " --pretty=format:%H"
            _, output, _ = run_shell_command(cmd, shell=True, cwd=self._path)
            for line in output.splitlines():
                if line.strip("'").startswith(version):
                    return False
            return True
        return False
开发者ID:btubbs,项目名称:vcstools,代码行数:32,代码来源:git.py

示例6: get_status

 def get_status(self, basepath=None, untracked=False):
     response = None
     if basepath is None:
         basepath = self._path
     if self.path_exists():
         rel_path = normalized_rel_path(self._path, basepath)
         # git command only works inside repo
         # self._path is safe against command injection, as long as we check path.exists
         command = "git status -s "
         if not untracked:
             command += " -uno"
         _, response, _ = run_shell_command(command, shell=True, cwd=self._path)
         response_processed = ""
         for line in response.split("\n"):
             if len(line.strip()) > 0:
                 # prepend relative path
                 response_processed += "%s%s/%s\n" % (line[0:3], rel_path, line[3:])
         if LooseVersion(self.gitversion) > LooseVersion("1.7"):
             command = "git submodule foreach --recursive git status -s"
             if not untracked:
                 command += " -uno"
             _, response2, _ = run_shell_command(command, shell=True, cwd=self._path)
             for line in response2.split("\n"):
                 if line.startswith("Entering"):
                     continue
                 if len(line.strip()) > 0:
                     # prepend relative path
                     response_processed += line[0:3] + rel_path + "/" + line[3:] + "\n"
         response = response_processed
     return response
开发者ID:btubbs,项目名称:vcstools,代码行数:30,代码来源:git.py

示例7: build_debian_package

def build_debian_package(package_fetcher, package_name, apt_cache, rd_obj, levels=0, get_dependencies=False):
  unstable_target_distros = { 'groovy': 'quantal', 'hydro': 'raring' }
  target_ubuntu_distro = unstable_target_distros[rd_obj._rosdistro]
  level_prefix = '--' * levels
  print("%s> Building package %s" % (level_prefix, package_name))
  deb_package_name = rd_obj.debianize_package_name(package_name)
  deb_package_version = rd_obj.get_version(package_name, full_version=True) + target_ubuntu_distro
  print("%s--> Checking if installed (%s, %s).." % (level_prefix, deb_package_name, deb_package_version)),
  if deb_package_name in apt_cache:
    installed = apt_cache[deb_package_name].installed
    if installed is not None and installed.version == deb_package_version:
      print("OK")
      print("%s is installed already - remove the package if you want to re-install." % (package_name))
      return True
  print("missing!")
  if get_dependencies:
    dependencies = package_build_order([package_name], distro_name=rd_obj._rosdistro)
    print("%s--> Checking Dependencies:" % (level_prefix))
    for dep_pkg_name in dependencies:
      if dep_pkg_name != package_name:
        print("%s---- %s....." % (level_prefix, dep_pkg_name)),
        debian_pkg_name = rd_obj.debianize_package_name(dep_pkg_name)
        if debian_pkg_name in apt_cache and apt_cache[debian_pkg_name].installed is not None:
          print(" OK! (installed version %s)" % apt_cache[debian_pkg_name].installed.version)
        else:
          print(" Needs build, building...")
          build_debian_package(package_fetcher, dep_pkg_name, apt_cache, rd_obj, levels + 1)
    print("%s<<-- Dependencies OKAY." % (level_prefix))
  print("%s>>> Build debian package %s from repo %s" % (level_prefix, deb_package_name, package_fetcher.url(package_name)))
  repo_path = package_fetcher.checkout_package(package_name)
  client = GitClient(repo_path)
  deb_package_tag = deb_package_name + '_' + rd_obj.get_version(package_name, full_version=True) + '_' + target_ubuntu_distro
  bloom_package_version = 'debian/' + deb_package_tag
  client.update(bloom_package_version)
  installed_builddeps = install_debian_build_dependencies(repo_path)
  if not installed_builddeps:
    raise RosGitBuildError("%s!!! Error building %s from %s: Can't install build-dependencies!" % (level_prefix, deb_package_name, package_fetcher.url(package_name)))
  (returncode, result, message) = run_shell_command('debuild clean', repo_path, shell=True, show_stdout=False)
  if returncode != 0:
    raise RosGitBuildError("%s!!! Error building %s from %s: %s \n %s" % (level_prefix, deb_package_name, package_fetcher.url(package_name), 'debuild clean', message))
  (returncode, result, message) = run_shell_command('debuild binary', repo_path, shell=True, show_stdout=False)
  if returncode != 0:
    raise RosGitBuildError("%s!!! Error building %s from %s: %s \n %s" % (level_prefix, deb_package_name, package_fetcher.url(package_name), 'debuild binary', message))
  deb_files = glob.glob(os.path.join(repo_path, '..', '%s*.deb' % (deb_package_name + '_' + rd_obj.get_version(package_name, full_version=True))))
  if len(deb_files) > 0:
    # install the deb
    from apt.debfile import DebPackage
    deb_pkg = DebPackage(deb_files[0])
    deb_pkg.check()
    packages_needed = ' '.join(deb_pkg.missing_deps)
    (returncode, result, message) = run_shell_command('sudo apt-get -y install %s' % packages_needed, shell=True, show_stdout=True)
    if returncode != 0:
      raise RosGitBuildError("%s!!! Error building %s: can't install dependent packages %s" % (level_prefix, deb_package_name, packages_needed))
    (returncode, result, message) = run_shell_command('sudo dpkg -i %s' % deb_files[0], shell=True, show_stdout=True)
    if returncode != 0:
      raise RosGitBuildError("%s!!! Error building %s from %s: %s \n %s" % (level_prefix, deb_package_name, package_fetcher.url(package_name), 'debuild binary', message))
  else:
    raise RosGitBuildError("%s!!! Can't find a built debian package for %s after the build!" % (level_prefix, deb_package_name))
开发者ID:garyservin,项目名称:ros-debuild-install,代码行数:58,代码来源:ros_gbp_build_debians.py

示例8: _do_fast_forward

    def _do_fast_forward(self, branch_parent, fetch=True, verbose=False):
        """Execute git fetch if necessary, and if we can fast-foward,
        do so to the last fetched version using git rebase.

        :param branch_parent: name of branch we track
        :param fetch: whether fetch should be done first for remote refs
        :returns: True if up-to-date or after succesful fast-forward
        :raises: GitError when git fetch fails
        """
        assert branch_parent is not None
        current_version = self.get_version()
        default_remote = self._get_default_remote()
        parent_version = self.get_version("remotes/%s/%s" % (default_remote, branch_parent))
        if current_version == parent_version:
            return True
        # check if we are true ancestor of tracked branch
        if not self._rev_list_contains(parent_version,
                                       current_version,
                                       fetch=fetch):
            # if not rev_list_contains this version, we are on same
            # commit (checked before), have advanced, or have diverged.
            # Now check whether tracked branch is a true ancestor of us
            if self._rev_list_contains(current_version,
                                       parent_version,
                                       fetch=False):
                return True
            print("Cannot fast-forward, local repository and remote '%s' have diverged." % branch_parent)
            return False
        if verbose:
            print("Rebasing repository")
        # Rebase, do not pull, because somebody could have
        # commited in the meantime.
        if LooseVersion(self.gitversion) >= LooseVersion('1.7.1'):
            # --keep allows o rebase even with local changes, as long as
            # local changes are not in files that change between versions
            cmd = "git reset --keep remotes/%s/%s" % (default_remote, branch_parent)
            value, _, _ = run_shell_command(cmd,
                                            shell=True,
                                            cwd=self._path,
                                            show_stdout=True,
                                            verbose=verbose)
            if value == 0:
                return True
        else:
            verboseflag = ''
            if verbose:
                verboseflag = '-v'
            # prior to version 1.7.1, git does not know --keep
            # Do not merge, rebase does nothing when there are local changes
            cmd = "git rebase %s remotes/%s/%s" % (verboseflag, default_remote, branch_parent)
            value, _, _ = run_shell_command(cmd,
                                            shell=True,
                                            cwd=self._path,
                                            show_stdout=True,
                                            verbose=verbose)
            if value == 0:
                return True
        return False
开发者ID:esteve,项目名称:vcstools,代码行数:58,代码来源:git.py

示例9: install_debian_build_dependencies

def install_debian_build_dependencies(package_dir):
  (returncode, result, message) = run_shell_command('dpkg-checkbuilddeps', package_dir, shell=True, show_stdout=True)
  if returncode != 0:
    missing_deps = message.split(':')[-1].split(' ')
    # things with parens are versions, ignore them
    missing_deps = [x.strip() for x in missing_deps if x != '' and (not (x.startswith('(') or x.endswith(')')))]
    print ("Warning: Attempting to install missing build-deps: %s" % missing_deps)
    (returncode, result, message) = run_shell_command('sudo apt-get -y install %s' % ' '.join(missing_deps), package_dir, shell=True, show_stdout=True)
    return returncode == 0
  else:
    return True
开发者ID:garyservin,项目名称:ros-debuild-install,代码行数:11,代码来源:ros_gbp_build_debians.py

示例10: get_branch_parent

    def get_branch_parent(self, fetch=False, current_branch=None):
        """
        return the name of the branch this branch tracks, if any

        :raises: GitError if fetch fails
        """
        if self.path_exists():
            # get name of configured merge ref.
            branchname = current_branch or self.get_branch()
            if branchname is None:
                return None
            cmd = 'git config --get %s' % sanitized('branch.%s.merge' % branchname)

            _, output, _ = run_shell_command(cmd,
                                             shell=True,
                                             cwd=self._path)
            if not output:
                return None
            lines = output.splitlines()
            if len(lines) > 1:
                print("vcstools unable to handle multiple merge references for branch %s:\n%s" % (branchname, output))
                return None
            # get name of configured remote
            cmd = 'git config --get "branch.%s.remote"' % branchname
            _, output2, _ = run_shell_command(cmd, shell=True, cwd=self._path)
            if output2 != "origin":
                print("vcstools only handles branches tracking remote 'origin'," +
                      " branch '%s' tracks remote '%s'" % (branchname, output2))
                return None
            output = lines[0]
            # output is either refname, or /refs/heads/refname, or
            # heads/refname we would like to return refname however,
            # user could also have named any branch
            # "/refs/heads/refname", for some unholy reason check all
            # known branches on remote for refname, then for the odd
            # cases, as git seems to do
            candidate = output
            if candidate.startswith('refs/'):
                candidate = candidate[len('refs/'):]
            if candidate.startswith('heads/'):
                candidate = candidate[len('heads/'):]
            elif candidate.startswith('tags/'):
                candidate = candidate[len('tags/'):]
            elif candidate.startswith('remotes/'):
                candidate = candidate[len('remotes/'):]
            if self.is_remote_branch(candidate, fetch=fetch):
                return candidate
            if output != candidate and self.is_remote_branch(output, fetch=False):
                return output
        return None
开发者ID:po1,项目名称:vcstools,代码行数:50,代码来源:git.py

示例11: update

 def update(self, version="", verbose=False, timeout=None):
     if not self.detect_presence():
         return False
     value, _, _ = run_shell_command("bzr pull", cwd=self._path, shell=True, show_stdout=True, verbose=verbose)
     if value != 0:
         return False
     # Ignore verbose param, bzr is pretty verbose on update anyway
     if version is not None and version != "":
         cmd = "bzr update -r %s" % (version)
     else:
         cmd = "bzr update"
     value, _, _ = run_shell_command(cmd, cwd=self._path, shell=True, show_stdout=True, verbose=verbose)
     if value == 0:
         return True
     return False
开发者ID:k-okada,项目名称:vcstools,代码行数:15,代码来源:bzr.py

示例12: get_branch

 def get_branch(self):
     if self.path_exists():
         command = "hg branch --repository %s" % self.get_path()
         _, output, _ = run_shell_command(command, shell=True)
         if output is not None:
             return output.strip()
     return None
开发者ID:mocudev,项目名称:vcstools,代码行数:7,代码来源:hg.py

示例13: checkout

    def checkout(self, url, refname=None, verbose=False, shallow=False):
        """calls git clone and then, if refname was given, update(refname)"""
        if url is None or url.strip() == '':
            raise ValueError('Invalid empty url : "%s"' % url)

        #since we cannot know whether refname names a branch, clone master initially
        cmd = 'git clone'
        if shallow:
            cmd += ' --depth 1'
            if LooseVersion(self.gitversion) >= LooseVersion('1.7.10'):
                cmd += ' --no-single-branch'
        cmd += ' --recursive %s %s' % (url, self._path)
        value, _, msg = run_shell_command(cmd,
                                          shell=True,
                                          show_stdout=verbose,
                                          verbose=verbose)
        if value != 0:
            if msg:
                self.logger.error('%s' % msg)
            return False

        try:
            # update to make sure we are on the right branch. Do not
            # check for "master" here, as default branch could be anything
            if refname is not None:
                return self._do_update(refname,
                                       verbose=verbose,
                                       fast_foward=True,
                                       update_submodules=False)
            else:
                return True
        except GitError:
            return False
开发者ID:jbohren-forks,项目名称:vcstools,代码行数:33,代码来源:git.py

示例14: _do_checkout

    def _do_checkout(self, refname, fetch=True, verbose=False):
        """
        meaning git checkout, not vcstools checkout. This works
        for local branches, remote branches, tagnames, hashes, etc.
        git will create local branch of same name when no such local
        branch exists, and also setup tracking. Git decides with own
        rules whether local changes would cause conflicts, and refuses
        to checkout else.

        :raises GitError: when checkout fails
        """
        # since refname may relate to remote branch / tag we do not
        # know about yet, do fetch if not already done
        if fetch:
            self._do_fetch()
        cmd = "git checkout %s" % (refname)
        value, _, _ = run_shell_command(cmd,
                                        shell=True,
                                        cwd=self._path,
                                        show_stdout=verbose,
                                        verbose=verbose)
        if self.cache:
            self.version = None
        if value != 0:
            raise GitError('Git Checkout failed')
开发者ID:trainman419,项目名称:vcstools,代码行数:25,代码来源:git.py

示例15: _do_fetch

 def _do_fetch(self, with_tags=False):
     """calls git fetch"""
     cmd = "git fetch"
     if with_tags:
         cmd += " --tags"
     value, _, _ = run_shell_command(cmd, cwd=self._path, shell=True, show_stdout=True)
     return value == 0
开发者ID:btubbs,项目名称:vcstools,代码行数:7,代码来源:git.py


注:本文中的vcstools.common.run_shell_command函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。