Yield sys.path directories that might contain "old-style" packages
970701
def expand_paths(inputs):
    """"""

    seen = {}

    for dirname in inputs:
        dirname = normalize_path(dirname)
        if dirname in seen:
            continue

        seen[dirname] = 1
        if not os.path.isdir(dirname):
            continue

        files = os.listdir(dirname)
        yield dirname, files

        for name in files:
            if not name.endswith('.pth'):
                # We only care about the .pth files
                continue
            if name in ('easy-install.pth', 'setuptools.pth'):
                # Ignore .pth files that we control
                continue

            # Read the .pth file
            f = open(os.path.join(dirname, name))
            lines = list(yield_lines(f))
            f.close()

            # Yield existing non-dupe, non-import directory lines from it
            for line in lines:
                if not line.startswith("import"):
                    line = normalize_path(line.rstrip())
                    if line not in seen:
                        seen[line] = 1
                        if not os.path.isdir(line):
                            continue
                        yield line, os.listdir(line)
515702
def add_sys_paths(paths):
    
    original_syspath = sys.path[:]
    sys.path.extend(paths)

    try:
        yield
    finally:
        sys.path = original_syspath
44282
function _processPathsAndPackages(paths, packages, options) {
    var result = {
        paths: {},
        packages: []
    };
    _.each(paths, function (path, pathName) {
        result.paths[pathName] = _.contains(options.notMerge, pathName) ? 'empty:' : path;
    });
    _.each(packages, function (pkg, i) {
        if (_.contains(options.notMerge, pkg.name)) {
            result.paths[pkg.name] = 'empty:';
        } else {
            result.packages.push(pkg);
        }
    });
    return result;
}
19707
def _find_observable_paths(extra_files=None):
    """"""
    rv = set(
        os.path.dirname(os.path.abspath(x)) if os.path.isfile(x) else os.path.abspath(x)
        for x in sys.path
    )

    for filename in extra_files or ():
        rv.add(os.path.dirname(os.path.abspath(filename)))

    for module in list(sys.modules.values()):
        fn = getattr(module, "__file__", None)
        if fn is None:
            continue
        fn = os.path.abspath(fn)
        rv.add(os.path.dirname(fn))

    return _find_common_roots(rv)
178405
def extract_package_dir(self):  # type: () -> Optional[str]
        
        # package_dir={'': 'lib'},
        source = self.setup_py_source()
        if not source:
            # this happens when the setup.py file is missing
            return None

        # sometime
        # 'package_dir'      : {'': 'src'},
        # sometimes
        # package_dir={...}
        if "package_dir=" in source:
            line = source.replace("\n", "")
            line = line.split("package_dir")[1]
            fixed = ""
            for char in line:
                fixed += char
                if char == "}":
                    break
            line = fixed

            simplified_line = line.strip(" ,").replace("'", '"')

            parts = simplified_line.split("=")

            dict_src = parts[1].strip(" \t")
            if not dict_src.endswith("}"):
                raise JiggleVersionException(
                    "Either this is hard to parse or we have 2+ src foldrs"
                )
            try:
                paths_dict = ast.literal_eval(dict_src)
            except ValueError as ve:
                logger.error(source + ": " + dict_src)
                return ""

            if "" in paths_dict:
                candidate = paths_dict[""]
                if os.path.isdir(candidate):
                    return unicode(candidate)
            if len(paths_dict) == 1:
                candidate = first_value_in_dict(paths_dict)
                if os.path.isdir(candidate):
                    return unicode(candidate)
            else:
                raise JiggleVersionException(
                    "Have path_dict, but has more than one path."
                )
        return None
721903
def find_packages(name, pkg_dir):
    """"""
    for c in (FileSystemPackageBuilder, ZipPackageBuilder, ExcelPackageBuilder):

        package_path, cache_path = c.make_package_path(pkg_dir, name)

        if package_path.exists():

            yield c.type_code, package_path, cache_path
949754
def existing_versions(self):
        
        import glob
        pattern = self.fname + '_*' + self.ext
        for fname in glob.glob1(self.dpath, pattern):
            fpath = join(self.dpath, fname)
            yield fpath
1162988
def _recurmatch(path, aug):
    '''
    
    '''
    if path:
        clean_path = path.rstrip('/*')
        yield (clean_path, aug.get(path))

        for i in aug.match(clean_path + '/*'):
            i = i.replace('!', '\\!')  # escape some dirs
            for _match in _recurmatch(i, aug):
                yield _match
861792
def _get_relative_pythonpath(self):
        """"""
        # Workaround to replace os.path.relpath (new in Python v2.6):
        offset = len(self.root_path)+len(os.pathsep)
        return [path[offset:] for path in self.pythonpath]
1117232
def bin_dir(venv):
    """"""
    bin_part = 'Scripts' if os.name == 'nt' else 'bin'
    return os.path.join(venv, bin_part)
662952
def _parse_g_dir(repo, gdirpath):
    """"""
    for f in repo.get_contents(gdirpath):
        if f.type == "dir":
            for sf in repo.get_contents(f.path):
                yield sf
        else:
            yield f
1233429
def find_repositories_by_walking_and_following_symlinks(path):
    """"""
    repos = []

    # This is for detecting symlink loops and escaping them. This is similar to
    # http://stackoverflow.com/questions/36977259/avoiding-infinite-recursion-with-os-walk/36977656#36977656
    def inode(path):
        stats = os.stat(path)
        return stats.st_dev, stats.st_ino
    seen_inodes = {inode(path)}

    for dirpath, dirnames, filenames in os.walk(path, followlinks=True):
        inodes = [inode(os.path.join(dirpath, p)) for p in dirnames]
        dirnames[:] = [p for p, i in zip(dirnames, inodes)
                       if not i in seen_inodes]
        seen_inodes.update(inodes)

        for dotdir in set(dirnames) & DOTDIRS:
            repos.append((dirpath, dotdir))
    return repos
154406
def extender(path=None, cache=None):
    """"""
    old_path = sys.path[:]
    extend(path, cache=None)

    try:
        yield
    finally:
        sys.path = old_path
1261912
def resource_path(package_name: str, relative_path: typing.Union[str, Path]) -> Path:
    
    relative_path = Path(relative_path)
    methods = [
        _get_from_dev,
        _get_from_package,
        _get_from_sys,
    ]
    for method in methods:
        path = method(package_name, relative_path)
        if path.exists():
            return path

    raise FileNotFoundError(relative_path)
1076173
def walkfiles(startdir, regex=None, recurse=True):
    """"""
    for r,_,fs in os.walk(startdir):
        if not recurse and startdir != r:
            return
        for f in fs:
            path = op.abspath(op.join(r,f))
            if regex and not _is_match(regex, path):
                    continue
            if op.isfile(path):
                yield path
539691
def rmtree(path, ignore_errors=False, onerror=None):
    """"""
    if ignore_errors:
        def onerror(*args):
            pass
    elif onerror is None:
        def onerror(*args):
            raise
    for root, dirs, unused_files in os.walk(path):
        for directory in dirs:
            try:
                abs_directory = os.path.join(root, directory)
                os.chmod(abs_directory, stat.S_IRWXU)
            except EnvironmentError as e:
                onerror(os.chmod, abs_directory, e)
    shutil.rmtree(path, ignore_errors=ignore_errors, onerror=onerror)
1308013
def cd(dir_name):
    
    old_path = os.path.abspath('.')
    os.chdir(dir_name)
    try:
        yield
        os.chdir(old_path)
    except Exception:
        os.chdir(old_path)
        raise