Rewrite 'import xxx' and 'from xxx import' for vendored_libs
335729
def rewrite_file_imports(item, vendored_libs):
    """"""
    text = item.read_text(encoding='utf-8')
    for lib in vendored_libs:
        text = re.sub(
            r'(\n\s*)import %s(\n\s*)' % lib,
            r'\1from pythonfinder._vendor import %s\2' % lib,
            text,
        )
        text = re.sub(
            r'(\n\s*)from %s' % lib,
            r'\1from pythonfinder._vendor.%s' % lib,
            text,
        )
    item.write_text(text, encoding='utf-8')
394634
def force_single_imports(self):
        """"""
        for import_stmt in self.imports[:]:
            import_info = import_stmt.import_info
            if import_info.is_empty() or import_stmt.readonly:
                continue
            if len(import_info.names_and_aliases) > 1:
                for name_and_alias in import_info.names_and_aliases:
                    if hasattr(import_info, "module_name"):
                        new_import = importinfo.FromImport(
                            import_info.module_name, import_info.level,
                            [name_and_alias])
                    else:
                        new_import = importinfo.NormalImport([name_and_alias])
                    self.add_import(new_import)
                import_stmt.empty_import()
673758
def do_import(self):
        """"""
        tmp_import = None
        try:
            if self.args[0].startswith('@') and self.args[0] != '@-':
                import_file = os.path.expanduser(self.args[0][1:])
                if not os.path.isfile(import_file):
                    self.parser.error("File not found (or not a file): {}".format(import_file))
                args = (xmlrpc.NOHASH, os.path.abspath(import_file))
            else:
                script_text = '\n'.join(self.args + [''])
                if script_text == '@-\n':
                    script_text = sys.stdin.read()

                with tempfile.NamedTemporaryFile(suffix='.rc', prefix='rtxmlrpc-', delete=False) as handle:
                    handle.write(script_text)
                    tmp_import = handle.name
                args = (xmlrpc.NOHASH, tmp_import)

            self.execute(self.open(), 'import', args)
        finally:
            if tmp_import and os.path.exists(tmp_import):
                os.remove(tmp_import)
231379
def alias_package(package, alias, extra_modules={}):
    
    path = package.__path__
    alias_prefix = alias + '.'
    prefix = package.__name__ + '.'
    # Alias all importable modules recursively
    for _, name, _ in pkgutil.walk_packages(path, prefix):
        # Skip databaseds backends
        if name.startswith('tango.databaseds.db_access.'):
            continue
        try:
            if name not in sys.modules:
                __import__(name)
        except ImportError:
            continue
        alias_name = name.replace(prefix, alias_prefix)
        sys.modules[alias_name] = sys.modules[name]
    # Alias extra modules
    for key, value in extra_modules.items():
        name = prefix + value
        if name not in sys.modules:
            __import__(name)
        if not hasattr(package, key):
            setattr(package, key, sys.modules[name])
        sys.modules[alias_prefix + key] = sys.modules[name]
    # Alias root module
    sys.modules[alias] = sys.modules[package.__name__]
162056
def universal_import(imports, imp_from=None, target=""):
    """"""
    importmap = []  # [((imp | old_imp, imp, version_check), imp_as), ...]
    for imps in imports:
        if len(imps) == 1:
            imp, imp_as = imps[0], imps[0]
        else:
            imp, imp_as = imps
        if imp_from is not None:
            imp = imp_from + "./" + imp  # marker for from ... import ...
        old_imp = None
        path = imp.split(".")
        for i in reversed(range(1, len(path) + 1)):
            base, exts = ".".join(path[:i]), path[i:]
            clean_base = base.replace("/", "")
            if clean_base in py3_to_py2_stdlib:
                old_imp, version_check = py3_to_py2_stdlib[clean_base]
                if exts:
                    old_imp += "."
                    if "/" in base and "/" not in old_imp:
                        old_imp += "/"  # marker for from ... import ...
                    old_imp += ".".join(exts)
                break
        if old_imp is None:
            paths = (imp,)
        elif not target:  # universal compatibility
            paths = (old_imp, imp, version_check)
        elif get_target_info_len2(target) >= version_check:  # if lowest is above, we can safely use new
            paths = (imp,)
        elif target.startswith("2"):  # "2" and "27" can safely use old
            paths = (old_imp,)
        elif get_target_info(target) < version_check:  # "3" should be compatible with all 3+
            paths = (old_imp, imp, version_check)
        else:  # "35" and above can safely use new
            paths = (imp,)
        importmap.append((paths, imp_as))

    stmts = []
    for paths, imp_as in importmap:
        if len(paths) == 1:
            more_stmts = single_import(paths[0], imp_as)
            stmts.extend(more_stmts)
        else:
            first, second, version_check = paths
            stmts.append("if _coconut_sys.version_info < " + str(version_check) + ":")
            first_stmts = single_import(first, imp_as)
            first_stmts[0] = openindent + first_stmts[0]
            first_stmts[-1] += closeindent
            stmts.extend(first_stmts)
            stmts.append("else:")
            second_stmts = single_import(second, imp_as)
            second_stmts[0] = openindent + second_stmts[0]
            second_stmts[-1] += closeindent
            stmts.extend(second_stmts)
    return "\n".join(stmts)
91274
def make_non_magical_flask_import(flask_ext_name):
    ''''''
    match = re.match(r'flask\.ext\.(.*)', flask_ext_name)
    if match is None:
        raise LookupError("Module name `{}` doesn't match"
                          "`flask.ext` style import.")
    from_name = match.group(1)
    actual_module_name = 'flask_{}'.format(from_name)
    return actual_module_name
597266
def join_import_from(self, import_spec):
    

    if not self.isroot and not self.ispkg:
      parent = self.name.rpartition('.')[0]
    else:
      parent = self.name
    return join_import_from(import_spec, parent)
140170
def resolve(tex):
    

    # soupify
    soup = TexSoup(tex)

    # resolve subimports
    for subimport in soup.find_all('subimport'):
        path = subimport.args[0] + subimport.args[1]
        subimport.replace_with(*resolve(open(path)).contents)

    # resolve imports
    for _import in soup.find_all('import'):
        _import.replace_with(*resolve(open(_import.args[0])).contents)

    # resolve includes
    for include in soup.find_all('include'):
        include.replace_with(*resolve(open(include.args[0])).contents)

    return soup
194578
def lssitepackages_cmd(argv):
    """"""
    site = sitepackages_dir()
    print(*sorted(site.iterdir()), sep=os.linesep)
    extra_paths = site / '_virtualenv_path_extensions.pth'
    if extra_paths.exists():
        print('from _virtualenv_path_extensions.pth:')
        with extra_paths.open() as extra:
            print(''.join(extra.readlines()))
697239
def cxx(source, libraries=[]):
    
    """
    path = _cc_build_shared_lib(source, '.cc', libraries)
    return ctypes.cdll.LoadLibrary(path)
786645
def visit_Import(self, node):
        
        for alias in node.names:
            current_module = MODULES
            # Recursive check for submodules
            for path in alias.name.split('.'):
                if path not in current_module:
                    raise PythranSyntaxError(
                        "Module '{0}' unknown.".format(alias.name),
                        node)
                else:
                    current_module = current_module[path]
1075879
def _versioned_lib_symlinks(env, libnode, version, prefix, suffix, name_func, soname_func):
    
    Verbose = False

    if Verbose:
        print("_versioned_lib_symlinks: libnode={:r}".format(libnode.get_path()))
        print("_versioned_lib_symlinks: version={:r}".format(version))

    if sys.platform.startswith('openbsd'):
        # OpenBSD uses x.y shared library versioning numbering convention
        # and doesn't use symlinks to backwards-compatible libraries
        if Verbose:
            print("_versioned_lib_symlinks: return symlinks={:r}".format(None))
        return None

    linkdir = libnode.get_dir()
    if Verbose:
        print("_versioned_lib_symlinks: linkdir={:r}".format(linkdir.get_path()))

    name = name_func(env, libnode, version, prefix, suffix)
    if Verbose:
        print("_versioned_lib_symlinks: name={:r}".format(name))

    soname = soname_func(env, libnode, version, prefix, suffix)

    link0 = env.fs.File(soname, linkdir)
    link1 = env.fs.File(name, linkdir)

    # We create direct symlinks, not daisy-chained.
    if link0 == libnode:
        # This enables SHLIBVERSION without periods (e.g. SHLIBVERSION=1)
        symlinks = [ (link1, libnode) ]
    else:
        # This handles usual SHLIBVERSION, i.e. '1.2', '1.2.3', etc.
        symlinks = [ (link0, libnode), (link1, libnode) ]

    if Verbose:
        print("_versioned_lib_symlinks: return symlinks={:r}".format(SCons.Tool.StringizeLibSymlinks(symlinks)))

    return symlinks
1150433
def inject_config(self, config, from_args):
    

    load_libs = self._get_libs()

    all_libs = {}
    found_libs = []
    
    for root, dirs, files in os.walk(library_path):
      for f in files:
        if not f.endswith('.so'):
          continue

        full_path = os.path.join(root, f)
        if '.' in f:
          name, ext = f.split('.', 1)
        else:
          name = f

        if name in all_libs:
          all_libs[name].append(full_path)
        else:
          all_libs[name] = [full_path]

    for lib in load_libs:
      if 'lib' + lib in all_libs:
        p = list(sorted(all_libs['lib' + lib], key=lambda x: len(x))).pop()
        v = '--volume={0}:{1}'.format(os.path.realpath(p), p)
        config.append(v)
      else:
        print('*** Unknown lib: {}'.format(lib))
        sys.exit(1)
1358101
def cmd_version(unused_conf):
    """"""
    import pkg_resources
    print('This is {} version {}, imported from {}'
          .format(__oneliner__, __version__, __file__))
    if len(Plugin.builders) > 0:
        print('setuptools registered builders:')
    for entry_point in pkg_resources.iter_entry_points('yabt.builders'):
        print('  {0.module_name}.{0.name} (dist {0.dist})'.format(entry_point))
615569
def generate_import_from(module_, names):
        
        regular_names = [n for n in names if "::" not in n]
        as_names = [n for n in names if "::" in n]

        line = ""
        if len(regular_names) > 0:
            slots = {"m": module_, "n": ", ".join(sorted(regular_names))}
            line = "from %(m)s import %(n)s" % slots
            if len(line) > LINE_LENGTH_LIMIT:
                slots["n"] = INDENT + (",\n" + INDENT).join(sorted(regular_names)) + ","
                line = "from %(m)s import (\n%(n)s\n)" % slots
            if len(as_names) > 0:
                line += "\n"

        for as_name in as_names:
            a, n = as_name.split("::")
            line += "from %(m)s import %(n)s as %(a)s" % {"m": module_, "n": n, "a": a}
        return line
171347
def install_libs(self):
        """"""
        # default or current python version
        lib_data = [{'python_executable': sys.executable, 'lib_dir': self.lib_directory}]

        # check for requirements.txt
        if not os.path.isfile(self.requirements_file):
            self.handle_error('A requirements.txt file is required to install modules.')

        # if branch arg is provide use git branch instead of pypi
        if self.args.branch is not None:
            self._create_temp_requirements()

        # overwrite default with config data
        if self.tcex_json.get('lib_versions'):
            lib_data = self.tcex_json.get('lib_versions')
            print('{}Using "lib" directories defined in tcex.json file.'.format(c.Style.BRIGHT))

        # configure proxy settings
        proxy_enabled = self._configure_proxy()

        # install all requested lib directories
        for data in lib_data:
            # pattern to match env vars in data
            env_var = re.compile(r'\$env\.([a-zA-Z0-9]+)')

            lib_dir = data.get('lib_dir')
            # replace env vars with env val in the lib dir
            matches = re.findall(env_var, lib_dir)
            if matches:
                env_val = os.environ.get(matches[0])
                if env_val is None:
                    self.handle_error(
                        '"{}" env variable set in tcex.json, but could not be resolved.'.format(
                            matches[0]
                        )
                    )
                lib_dir = re.sub(env_var, env_val, lib_dir)
            lib_dir_fq = os.path.join(self.app_path, lib_dir)

            if os.access(lib_dir_fq, os.W_OK):
                # remove lib directory from previous runs
                shutil.rmtree(lib_dir_fq)

            # replace env vars with env val in the python executable
            python_executable = data.get('python_executable')
            matches = re.findall(env_var, python_executable)
            if matches:
                env_val = os.environ.get(matches[0])
                python_executable = re.sub(env_var, env_val, python_executable)

            print('Building Lib Dir: {}{}{}'.format(c.Style.BRIGHT, c.Fore.CYAN, lib_dir_fq))
            exe_command = self._build_command(python_executable, lib_dir_fq, proxy_enabled)

            print('Running: {}{}{}'.format(c.Style.BRIGHT, c.Fore.GREEN, ' '.join(exe_command)))
            p = subprocess.Popen(
                exe_command,
                shell=False,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
            out, err = p.communicate()  # pylint: disable=W0612

            if p.returncode != 0:
                print('{}{}FAIL'.format(c.Style.BRIGHT, c.Fore.RED))
                print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, err.decode('utf-8')))
                sys.exit('ERROR: {}'.format(err.decode('utf-8')))

            # version comparison
            try:
                python_version = lib_dir.split('_', 1)[1]
            except IndexError:
                self.handle_error('Could not determine version from lib string.')

            # track the latest Python version
            if self.latest_version is None:
                self.latest_version = python_version
            elif StrictVersion(python_version) > StrictVersion(self.latest_version):
                self.latest_version = python_version

        # cleanup temp file if required
        if self.use_temp_requirements_file:
            os.remove(self.requirements_file)

        # create lib_latest
        self._create_lib_latest()
1183021
def _at_dump_imports(self, calculator, rule, scope, block):
        
        sys.stderr.write("%s\n" % repr(rule.namespace._imports))