Python clone of /usr/bin/which
484923
def which(exe=None):
    '''
    
    '''

    if not exe:
        log.error('No executable was passed to be searched by salt.utils.path.which()')
        return None

    ## define some utilities (we use closures here because our predecessor used them)
    def is_executable_common(path):
        '''
        This returns truth if posixy semantics (which python simulates on
        windows) states that this is executable.
        '''
        return os.path.isfile(path) and os.access(path, os.X_OK)

    def resolve(path):
        '''
        This will take a path and recursively follow the link until we get to a
        real file.
        '''
        while os.path.islink(path):
            res = os.readlink(path)

            # if the link points to a relative target, then convert it to an
            # absolute path relative to the original path
            if not os.path.isabs(res):
                directory, _ = os.path.split(path)
                res = join(directory, res)
            path = res
        return path

    # windows-only
    def has_executable_ext(path, ext_membership):
        '''
        Extract the extension from the specified path, lowercase it so we
        can be insensitive, and then check it against the available exts.
        '''
        p, ext = os.path.splitext(path)
        return ext.lower() in ext_membership

    ## prepare related variables from the environment
    res = salt.utils.stringutils.to_unicode(os.environ.get('PATH', ''))
    system_path = res.split(os.pathsep)

    # add some reasonable defaults in case someone's PATH is busted
    if not salt.utils.platform.is_windows():
        res = set(system_path)
        extended_path = ['/sbin', '/bin', '/usr/sbin', '/usr/bin', '/usr/local/sbin', '/usr/local/bin']
        system_path.extend([p for p in extended_path if p not in res])

    ## now to define the semantics of what's considered executable on a given platform
    if salt.utils.platform.is_windows():
        # executable semantics on windows requires us to search PATHEXT
        res = salt.utils.stringutils.to_str(os.environ.get('PATHEXT', str('.EXE')))

        # generate two variables, one of them for O(n) searches (but ordered)
        # and another for O(1) searches. the previous guy was trying to use
        # memoization with a function that has no arguments, this provides
        # the exact same benefit
        pathext = res.split(os.pathsep)
        res = {ext.lower() for ext in pathext}

        # check if our caller already specified a valid extension as then we don't need to match it
        _, ext = os.path.splitext(exe)
        if ext.lower() in res:
            pathext = ['']

            is_executable = is_executable_common

        # The specified extension isn't valid, so we just assume it's part of the
        # filename and proceed to walk the pathext list
        else:
            is_executable = lambda path, membership=res: is_executable_common(path) and has_executable_ext(path, membership)

    else:
        # in posix, there's no such thing as file extensions..only zuul
        pathext = ['']

        # executable semantics are pretty simple on reasonable platforms...
        is_executable = is_executable_common

    ## search for the executable

    # check to see if the full path was specified as then we don't need
    # to actually walk the system_path for any reason
    if is_executable(exe):
        return exe

    # now to search through our system_path
    for path in system_path:
        p = join(path, exe)

        # iterate through all extensions to see which one is executable
        for ext in pathext:
            pext = p + ext
            rp = resolve(pext)
            if is_executable(rp):
                return p + ext
            continue
        continue

    ## if something was executable, we should've found it already...
    log.trace(
        '\'%s\' could not be found in the following search path: \'%s\'',
        exe, system_path
    )
    return None
134334
def clone(self):
        
        base_dir = '/'.join(self.path.split('/')[:-2])
        try:
            os.makedirs(base_dir, 0o700)
        except OSError:
            # Raises an error exception if the leaf directory already exists.
            pass

        self._cmd(['git', 'clone', self._clone_url, self.path], cwd=os.getcwd())
1120632
def bin_path(self, release=None):
        """"""
        if release:
            for r in self.releases:
                if release in r:
                    return self.releases[r]
            raise MongoOrchestrationError("No such release '%s' in %r"
                                          % (release, self.releases))
        if self.default_release:
            return self.releases[self.default_release]
        if self.releases:
            return list(self.releases.values())[0]
        return ''
962879
def get_bin_version_str(bin_path, version_flag='-v', kw={}):
    

    try:
        prog = _get_exec_binary(bin_path, kw)
        version_str = version_expr.search(
            check_output([prog, version_flag], **kw).decode(locale)
        ).groups()[0]
    except OSError:
        logger.warning("failed to execute '%s'", bin_path)
        return None
    except Exception:
        logger.exception(
            "encountered unexpected error while trying to find version of "
            "'%s':", bin_path
        )
        return None
    logger.info("'%s' is version '%s'", bin_path, version_str)
    return version_str
9703
def get_or_create_environment(self, repo: str, branch: str, git_repo: Repo, repo_path: Path) -> str:
        
        return str(self.get_or_create_venv(repo_path).resolve() / "bin" / "python")
1149920
def clone(cls, repo_url, dest, binary='git'):
    
    cmd = [binary, 'clone', repo_url, dest]
    process, out = cls._invoke(cmd)
    cls._check_result(cmd, process.returncode)
    return cls(binary=binary, worktree=dest)
902040
def clone(cls, srcpath, destpath, encoding='utf-8'):
        """"""
        cmd = [GIT, 'clone', '--quiet', '--bare', srcpath, destpath]
        subprocess.check_call(cmd)
        return cls(destpath, encoding)
1072354
def remove_from_bin(self, name):
        
        self.__remove_path(os.path.join(self.root_dir, "bin", name))
1051934
def _copy_update(sourcepath, destname):
    """"""
    if sys.platform.startswith('linux'):
        return os.system("/bin/cp -ua '%s' '%s'" % (sourcepath, destname))
    else:
        return os.system("rsync -ua '%s' '%s'" % (sourcepath, destname))
1117232
def bin_dir(venv):
    """"""
    bin_part = 'Scripts' if os.name == 'nt' else 'bin'
    return os.path.join(venv, bin_part)
721779
def which(fname):
    """"""
    if "PATH" not in os.environ or not os.environ["PATH"]:
        path = os.defpath
    else:
        path = os.environ["PATH"]

    for p in [fname] + [os.path.join(x, fname) for x in path.split(os.pathsep)]:
        p = os.path.abspath(p)
        if os.access(p, os.X_OK) and not os.path.isdir(p):
            return p

    p = sp.Popen("locate %s" % fname, shell=True, stdout=sp.PIPE, stderr=sp.PIPE)
    (stdout, stderr) = p.communicate()
    if not stderr:
        for p in stdout.decode().split("\n"):
            if (os.path.basename(p) == fname) and (
                os.access(p, os.X_OK)) and (
                not os.path.isdir(p)):
                return p
514812
def clone(cls, srcpath, destpath):
        """"""
        try:
            os.makedirs(destpath)
        except OSError as e:
            if not e.errno == errno.EEXIST:
                raise
        cmd = [SVNADMIN, 'dump', '--quiet', '.']
        dump = subprocess.Popen(
               cmd, cwd=srcpath, stdout=subprocess.PIPE,
               stderr=subprocess.PIPE,
        )
        repo = cls.create(destpath)
        repo.load(dump.stdout)
        stderr = dump.stderr.read()
        dump.stdout.close()
        dump.stderr.close()
        dump.wait()
        if dump.returncode != 0:
            raise subprocess.CalledProcessError(dump.returncode, cmd, stderr)
        return repo
230282
def clone_repo(self):
        """"""
        tempdir_path = tempfile.mkdtemp()

        if self.args.git:
            self.log.debug('Cloning git source repository from %s to %s',
                           self.source, tempdir_path)
            self.sh('git clone', self.source, tempdir_path)

        else:
            raise NotImplementedError('Unknown repo type')

        self.source = tempdir_path
474759
def find_binary_of_command(candidates):
    
    from distutils.spawn import find_executable
    for c in candidates:
        binary_path = find_executable(c)
        if c and binary_path:
            return c, binary_path
    raise RuntimeError('No binary located for candidates: {}'.format(
        candidates))
216777
def which(prog, path = ENV['PATH'])
      path.split(File::PATH_SEPARATOR).each do |dir|
        file = File.join(dir, prog)
        return file if File.executable?(file) && !File.directory?(file)
      end

      nil
    end
477577
def _copy_dist_from_dir(link_path, location):
    

    # Note: This is currently VERY SLOW if you have a lot of data in the
    # directory, because it copies everything with `shutil.copytree`.
    # What it should really do is build an sdist and install that.
    # See https://github.com/pypa/pip/issues/2195

    if os.path.isdir(location):
        rmtree(location)

    # build an sdist
    setup_py = 'setup.py'
    sdist_args = [sys.executable]
    sdist_args.append('-c')
    sdist_args.append(SETUPTOOLS_SHIM % setup_py)
    sdist_args.append('sdist')
    sdist_args += ['--dist-dir', location]
    logger.info('Running setup.py sdist for %s', link_path)

    with indent_log():
        call_subprocess(sdist_args, cwd=link_path, show_stdout=False)

    # unpack sdist into `location`
    sdist = os.path.join(location, os.listdir(location)[0])
    logger.info('Unpacking sdist %s into %s', sdist, location)
    unpack_file(sdist, location, content_type=None, link=None)
406301
def _get_path():
    """"""
    if _path:
        return _path[0]
    environ_paths = set(os.environ['PATH'].split(':'))
    environ_paths.add('/usr/local/bin')
    environ_paths.add('/usr/bin')
    _path.append(':'.join(environ_paths))
    logger.debug('PATH = %s', _path[-1])
    return _path[0]