Compute an ns-package subpath for a filesystem or zipfile importer
437792
def file_ns_handler(importer, path_item, packageName, module):
    """"""

    subpath = os.path.join(path_item, packageName.split('.')[-1])
    normalized = _normalize_cached(subpath)
    for item in module.__path__:
        if _normalize_cached(item) == normalized:
            break
    else:
        # Only return the path if it's not already there
        return subpath
872259
def packageSplit(filepath):
        
        filepath = nstr(filepath).strip().strip('.')
        if not filepath:
            return '', ''

        basepath, module = os.path.split(nstr(filepath))
        module = os.path.splitext(module)[0]
        pathsplit = os.path.normpath(basepath).split(os.path.sep)
        packagesplit = []

        if module and module != '__init__':
            packagesplit.append(module)

        testpath = os.path.sep.join(pathsplit + ['__init__.py'])
        while os.path.exists(testpath):
            packagesplit.insert(0, pathsplit[-1])
            pathsplit = pathsplit[:-1]
            testpath = os.path.sep.join(pathsplit + ['__init__.py'])

        return os.path.sep.join(pathsplit), '.'.join(packagesplit)
1207419
def cnormpath (path):
    """"""
    path = normpath(path)
    if os.name == 'nt':
        # replace slashes with backslashes
        path = path.replace("/", "\\")
    if not os.path.isabs(path):
        path = normpath(os.path.join(sys.prefix, path))
    return path
790907
def lookup_path(bin_name):
    
    paths = ('/usr/local/sbin/', '/usr/local/bin/', '/usr/sbin/', '/usr/bin/')
    for p in paths:
        fq_path = p + bin_name
        found = os.path.isfile(fq_path) and os.access(fq_path, os.X_OK)
        if found:
            return fq_path
    return False
869473
def abspath(path, **kwargs):
    """"""
    import os.path
    return os.path.abspath(path, **kwargs)
327079
def file_containing_import(import_path, import_root):
    '''
    '''
    if not _import_paths:
        load_stdlib()

    if os.path.isfile(import_root):
        import_root = os.path.dirname(import_root)

    search_paths = [import_root] + _import_paths
    module_parts = import_path.split('.')
    for i in range(len(module_parts), 0, -1):
        module_path = os.path.join(*module_parts[:i])
        for sp in search_paths:
            p = os.path.join(sp, module_path)
            if os.path.isdir(p):
                return os.path.join(p, '__init__.py')
            elif os.path.isfile(p + '.py'):
                return p + '.py'
    return None
163026
def find_package(name: str) -> Tuple[Optional[Path], Path]:
    
    module = name.split(".")[0]
    loader = pkgutil.get_loader(module)
    if name == "__main__" or loader is None:
        package_path = Path.cwd()
    else:
        if hasattr(loader, 'get_filename'):
            filename = loader.get_filename(module)  # type: ignore
        else:
            __import__(name)
            filename = sys.modules[name].__file__
        package_path = Path(filename).resolve().parent
        if hasattr(loader, 'is_package'):
            is_package = loader.is_package(module)  # type: ignore
            if is_package:
                package_path = Path(package_path).resolve().parent
    sys_prefix = Path(sys.prefix).resolve()
    try:
        package_path.relative_to(sys_prefix)
    except ValueError:
        return None, package_path
    else:
        return sys_prefix, package_path
1074670
def find_subdirectories(package):
    
    try:
        subdirectories = os.walk(package_to_path(package)).next()[1]
    except StopIteration:
        subdirectories = []
    return subdirectories
998427
function resolvePath(filepath) {
  filepath = filepath.replace(RE_TRAILING, '');
  const cwd = process.cwd();
  const npmPackage = filepath.includes('node_modules');

  // Find nearest node_modules directory
  if (npmPackage) {
    const parts = filepath.split(path.sep);
    let idx = parts.lastIndexOf('node_modules');

    if (idx < parts.length - 1) idx += 2;
    // Handle scoped
    if (parts[idx - 1].charAt(0) == '@') idx++;

    const dir = parts.slice(0, idx).join(path.sep);

    // Installed packages must have manifest, otherwise continue
    if (exists(path.join(dir, 'package.json'))) return dir;
  }

  // Find nearest directory with node_modules subdirectory
  if (filepath.includes(cwd)) {
    let depth = maxFileSystemDepth;
    let dir = filepath;
    let parent = '';

    while (true) {
      parent = path.dirname(dir);
      // Stop if we hit max file system depth or root
      // Convert to lowercase to fix problems on Windows
      if (!--depth || parent.toLowerCase() === dir.toLowerCase()) {
        break;
      }

      // Stop at nearest directory with node_modules or cwd
      if (dir == cwd || exists(path.resolve(dir, 'node_modules'))) return dir;

      // Walk
      dir = parent;
    }
  }

  // Return project directory if file isn't a project file
  return cwd;
}
638131
def subst_path(self, path, target=None, source=None):
        """"""

        if not SCons.Util.is_List(path):
            path = [path]

        def s(obj):
            """This is the "string conversion" routine that we have our
            substitutions use to return Nodes, not strings.  This relies
            on the fact that an EntryProxy object has a get() method that
            returns the underlying Node that it wraps, which is a bit of
            architectural dependence that we might need to break or modify
            in the future in response to additional requirements."""
            try:
                get = obj.get
            except AttributeError:
                obj = SCons.Util.to_String_for_subst(obj)
            else:
                obj = get()
            return obj

        r = []
        for p in path:
            if SCons.Util.is_String(p):
                p = self.subst(p, target=target, source=source, conv=s)
                if SCons.Util.is_List(p):
                    if len(p) == 1:
                        p = p[0]
                    else:
                        # We have an object plus a string, or multiple
                        # objects that we need to smush together.  No choice
                        # but to make them into a string.
                        p = ''.join(map(SCons.Util.to_String_for_subst, p))
            else:
                p = s(p)
            r.append(p)
        return r
1256998
function getPackagePath(p) {
      if (p.path) {
        return p.path;
      } else if (p.polyfill) {
        return path.join('polyfills', p.namespace.toLowerCase(), p.name);
      } else if (p.type === 'fix') {
        return path.join(p.module.toLowerCase(), 'fixes', p.name);
      } else if (p.type === 'locale') {
        return path.join(p.module.toLowerCase(), p.code);
      } else if (sourcePackageIsDependency(p)) {
        return path.join(p.module.toLowerCase(), p.type, p.name);
      } else {
        return path.join(p.namespace.toLowerCase(), p.name);
      }
    }
1032949
def path_to(self, p):
        """"""
        if os.path.isabs(p):
            return p

        return os.sep.join([self._original_dir, p])
625669
def nearest_subpackage(cls, package, all_packages):
    """"""
    def shared_prefix(candidate):
      zipped = zip(package.split('.'), candidate.split('.'))
      matching = itertools.takewhile(lambda pair: pair[0] == pair[1], zipped)
      return [pair[0] for pair in matching]
    shared_packages = [_f for _f in map(shared_prefix, all_packages) if _f]
    return '.'.join(max(shared_packages, key=len)) if shared_packages else package
585108
def ls(ctx, available):
    ""

    path = ctx.obj['path']
    global_ = ctx.obj['global_']

    _ls(available=available, **ctx.obj)
359294
function resolveImportPaths(filePath, importPaths){
  var dir = path.dirname(filePath);
  return importPaths.map(function(relativePath){
    if(!path.extname(relativePath)){
      relativePath += '.less';
    }
    return path.resolve(dir, relativePath);
  });
}
446870
def get_modules(root_path):
    """"""
    for dir_path, dir_names, file_names in os.walk(root_path):
        assert dir_path[:len(root_path)] == root_path
        subdir_path = dir_path[len(root_path):]
        package_parts = list(filter(lambda x: x, subdir_path.split('/')))
        for name in file_names:
            if name.endswith('.py'):
                path = os.path.join(dir_path, name)
                pkgpath = '.'.join(package_parts)
                modpath = (pkgpath if name == '__init__.py' else
                           '.'.join(package_parts + [name[:-3]]))
                try:
                    node = ast.parse(open(path).read())
                except SyntaxError:
                    print('ERROR: Invalid syntax in %s' % path, file=sys.stderr)
                else:
                    yield (pkgpath, modpath, path, node)
1126797
def path(self):
        
        return pathlib.Path(self.package.__file__).resolve().parent.parent