'Resolve hits from a CommonJS require() invocation'

def _hits_from_commonjs_require(self, requirename, scoperef):

    from codeintel2.database.langlib import LangDirsLib
    from codeintel2.database.multilanglib import MultiLangDirsLib
    from codeintel2.database.catalog import CatalogLib
    self.log('resolving    require(%r)    in    %r', requirename, scoperef[0])
    stdlib = self.nodejslib
    if stdlib.has_blob((requirename + '.js')):
        self.log('require(%r)    is    a    core    module', requirename)
        blob = stdlib.blobs_with_basename((requirename + '.js'), ctlr=self.ctlr)[0]
        exports = blob.names.get('exports')
        return self._hits_from_variable_type_inference(exports, [blob, ['exports']])
    srcdir = os.path.dirname((scoperef[0].get('src') or self.buf.path))
    if (srcdir == ''):
        self.log("no    source    directory    found,    can't    resolve    require(%r)", requirename)
        return []
    def get_hits_from_lib(lib, filename):
        'Get    the    hits    from    a    given    LangDirsLib,    or    None'
        hits = []
        basename = os.path.basename(filename)
        blobs = lib.blobs_with_basename(basename, ctlr=self.ctlr)
        for blob in (blobs or []):
            if (os.path.normpath(blob.get('src')) != filename):
                continue
            self.log('require()    found    at    %s', filename)
            exports = blob.names.get('exports')
            if ((exports is not None) and (exports.tag == 'variable')):
                hits += self._hits_from_variable_type_inference(exports, [blob, ['exports']])
            else:
                module = blob.names.get('module')
                if (module is not None):
                    exports = module.names.get('exports')
                    if ((exports is not None) and (exports.tag == 'variable')):
                        hits += self._hits_from_variable_type_inference(exports, [blob, ['module', 'exports']])
        return (hits or None)
    def load_as_file(path):
        'Load    "path"    as    a    file    and    return    hits    from    there\n                                                If    it    does    not    exist    /    isn\'t    a    valid    node.js    module,    return    None\n                                                '
        path = os.path.normpath(path)
        if os.path.isfile(path):
            filename = path
        elif os.path.isfile((path + '.js')):
            filename = (path + '.js')
        else:
            return None
        self.log('looking    to    resolve    require()    via    %s', path)
        dirname = os.path.dirname(filename)
        for lib in self.libs:
            if (lib == self.nodejslib):
                continue
            if (not isinstance(lib, (LangDirsLib, MultiLangDirsLib))):
                self.log("skipping    lib    %r,    don't    know    how    to    deal", lib)
                continue
            if (dirname in map(os.path.normpath, lib.dirs)):
                self.log('looking    up    lib    %r    (filename    %r)', lib.dirs, filename)
                return get_hits_from_lib(lib, filename)
        lib = self.mgr.db.get_lang_lib(self.lang, 'node_modules_lib', (dirname,))
        return get_hits_from_lib(lib, filename)
    def load_as_directory(path):
        'Load    "path"    as    a    directory    and    return    hits    from    there\n                                                If    it    does    not    exist    /    isn\'t    a    valid    node.js    module,    return    None\n                                                '
        path = os.path.normpath(path)
        if (not os.path.isdir(path)):
            return None
        hits = None
        manifest_path = os.path.join(path, 'package.json')
        if os.path.isfile(manifest_path):
            manifest_file = open(manifest_path)
            try:
                manifest = json.load(manifest_file)
                if ('main' in manifest):
                    main_path = os.path.join(path, manifest.get('main'))
                    main_path = os.path.normpath(main_path)
                    self.log('found    module    via    %r,    trying    %r', manifest_path, main_path)
                    hits = load_as_file(main_path)
            except ValueError as e:
                self.log('Error    loading    %r:    %r', manifest_path, e)
            finally:
                manifest_file.close()
        if (hits is None):
            hits = load_as_file(os.path.join(path, 'index'))
        return hits
    if requirename.lstrip('.').startswith('/'):
        self.log('require(%r)    is    file    system', requirename)
        if requirename.startswith('/'):
            filename = requirename
        elif (requirename.startswith('./') or requirename.startswith('../')):
            filename = os.path.join(srcdir, requirename)
        else:
            return []
        filename = os.path.normpath(filename)
        self.log('resolving    relative    require(%r)    via    %s', requirename, filename)
        hits = load_as_file(filename)
        if (hits is None):
            hits = load_as_directory(filename)
        return (hits or [])
    parts = os.path.normpath(srcdir).split(os.sep)
    try:
        root_index = (parts.index('node_modules') - 1)
    except ValueError:
        root_index = (-1)
    for part_index in range(len(parts), root_index, (-1)):
        if ((part_index > 0) and (parts[(part_index - 1)] == 'node_modules')):
            continue
        dir = os.sep.join((parts[:part_index] + ['node_modules']))
        hits = load_as_file(os.path.join(dir, requirename))
        if (hits is None):
            hits = load_as_directory(os.path.join(dir, requirename))
        if (hits is not None):
            return hits
    extra_dirs = []
    for pref in self.buf.env.get_all_prefs(self.langintel.extraPathsPrefName):
        if (not pref):
            continue
        for dir in pref.split(os.pathsep):
            dir = dir.strip()
            if (not os.path.isdir(dir)):
                continue
            if (not (dir in extra_dirs)):
                extra_dirs.append(dir)
    for dir in extra_dirs:
        hits = load_as_file(os.path.join(dir, requirename))
        if (hits is None):
            hits = load_as_directory(os.path.join(dir, requirename))
        if (hits is not None):
            return hits
    self.log('Failed    to    find    module    for    require(%r)', requirename)
    return []
