Read imports and follow them until all files have been handled
965413
function discoverAndReadFiles(options) {
    const FILES = {};
    const in_queue = Object.create(null);
    const queue = [];
    const enqueue = (moduleId) => {
        if (in_queue[moduleId]) {
            return;
        }
        in_queue[moduleId] = true;
        queue.push(moduleId);
    };
    options.entryPoints.forEach((entryPoint) => enqueue(entryPoint));
    while (queue.length > 0) {
        const moduleId = queue.shift();
        const dts_filename = path.join(options.sourcesRoot, moduleId + '.d.ts');
        if (fs.existsSync(dts_filename)) {
            const dts_filecontents = fs.readFileSync(dts_filename).toString();
            FILES[`${moduleId}.d.ts`] = dts_filecontents;
            continue;
        }
        const js_filename = path.join(options.sourcesRoot, moduleId + '.js');
        if (fs.existsSync(js_filename)) {
            // This is an import for a .js file, so ignore it...
            continue;
        }
        let ts_filename;
        if (options.redirects[moduleId]) {
            ts_filename = path.join(options.sourcesRoot, options.redirects[moduleId] + '.ts');
        }
        else {
            ts_filename = path.join(options.sourcesRoot, moduleId + '.ts');
        }
        const ts_filecontents = fs.readFileSync(ts_filename).toString();
        const info = ts.preProcessFile(ts_filecontents);
        for (let i = info.importedFiles.length - 1; i >= 0; i--) {
            const importedFileName = info.importedFiles[i].fileName;
            if (options.importIgnorePattern.test(importedFileName)) {
                // Ignore vs/css! imports
                continue;
            }
            let importedModuleId = importedFileName;
            if (/(^\.\/)|(^\.\.\/)/.test(importedModuleId)) {
                importedModuleId = path.join(path.dirname(moduleId), importedModuleId);
            }
            enqueue(importedModuleId);
        }
        FILES[`${moduleId}.ts`] = ts_filecontents;
    }
    return FILES;
}
1341849
function importerSync(options, handler) {
    var modulePath, recursive = false, parent = '';

    if (typeof options === 'string') {
        modulePath = options;

    } else {
        modulePath = options.path;
        recursive = options.recursive || recursive;
        parent = options.parent || parent;
        if (!modulePath) throw new Error("module directory path must be given.");
    }

    // absolute path? or relevant path?
    if (modulePath.indexOf('/') != 0) {
        // relevant. join with parent module's path
        modulePath = path.join(path.dirname(module.parent.parent.filename), modulePath);
    }

    var files = fs.readdirSync(modulePath);
    for (var i in files) {
        var name = files[i];

        if (recursive && fs.lstatSync(path.join(modulePath, name)).isDirectory()) {
            importerSync({
                path: path.join(modulePath, name),
                recursive: true,
                parent: path.join(parent, name)
            }, handler);
            continue;
        }
        if (name.lastIndexOf('.js') != name.length - 3) continue;

        name = name.substring(0, name.lastIndexOf('.')); // remove ext
        var moduleObj = require(path.join(modulePath, name));
        if (handler) handler(moduleObj, path.join(parent, name));
    }
}
1091432
def handle_import(self, name, compilation, rule):
        
        original_path = PurePath(name)

        search_exts = list(compilation.compiler.dynamic_extensions)
        if original_path.suffix and original_path.suffix in search_exts:
            basename = original_path.stem
        else:
            basename = original_path.name

        if original_path.is_absolute():
            # Remove the beginning slash
            search_path = original_path.relative_to('/').parent
        elif rule.source_file.origin:
            search_path = rule.source_file.origin
            if original_path.parent:
                search_path = os.path.normpath(str(search_path / original_path.parent))
        else:
            search_path = original_path.parent

        for prefix, suffix in product(('_', ''), search_exts):
            filename = PurePath(prefix + basename + suffix)

            full_filename, storage = get_file_and_storage(str(search_path / filename))

            if full_filename:
                with storage.open(full_filename) as f:
                    return SourceFile.from_file(f, origin=search_path, relpath=filename)
86224
def load_imports # :nodoc:
      while fn = @pending_imports.shift
        next if @imported.member?(fn)
        fn_task = lookup(fn) and fn_task.invoke
        ext = File.extname(fn)
        loader = @loaders[ext] || @default_loader
        loader.load(fn)
        if fn_task = lookup(fn) and fn_task.needed?
          fn_task.reenable
          fn_task.invoke
          loader.load(fn)
        end
        @imported << fn
      end
    end
573473
def install_import_hook():
    """"""
    saved_import = builtins.__import__
    @functools.wraps(saved_import)
    def import_hook(name, *args, **kwargs):
        if name == 'end':
            process_import()
        end
        return saved_import(name, *args, **kwargs)
    end
    builtins.__import__ = import_hook
641436
function (path, currentFileInfo, callback) {
            var parserImporter = this;
            this.queue.push(path);

            //
            // Import a file asynchronously
            //
            less.Parser.importer(path, currentFileInfo, function (e, root, fullPath) {
                parserImporter.queue.splice(parserImporter.queue.indexOf(path), 1); // Remove the path from the queue

                var imported = fullPath in parserImporter.files;

                parserImporter.files[fullPath] = root;                        // Store the root

                if (e && !parserImporter.error) { parserImporter.error = e; }
                
                callback(e, root, imported);
            }, env);
        }
889640
function walkModules(dir, done) {

  var results = [];

  fs.readdir(dir, function(err, list) {
    if (err) return done(err);
    var pending = list.length;
    if (!pending) return done(null, results);

    list.forEach(function(file) {
      file = dir + path.sep + file;

      fs.stat(file, function(err, stat) {
        if (stat && stat.isDirectory()) {

          if (file.indexOf('node_modules') > -1) {
            walkModules(file, function(err, res) {
              results = results.concat(res);
              if (!--pending) done(null, results);
            });
          }
          else {
            if (!--pending) done(null, results);
          }

        } else {

          if (file.slice(-12) === 'package.json') {
            var parts = file.split(path.sep);
            if (parts[parts.length-3] === 'node_modules') {
              results.push(file);
            }
          }
          
          if (!--pending) done(null, results);
        }
      });
    });
  });
}
668820
function readFiles (filepaths, callback) {
  async.map(filepaths, readFile.bind(this), function (err, files) {

    if (err) callback(err);

    callback(null, files);
  });
}
1072591
def load(self, patterns, dirs, ignore=None):
        
        for _dir in dirs:
            data = self.read_file(_dir, ignore=ignore)
            if data:
                self.paths[_dir] = data
605521
def handle_import(self, name, compilation, rule):
        
        from .sprites import sprite_map

        # TODO check that the found file is actually under the root
        if callable(config.STATIC_ROOT):
            files = sorted(config.STATIC_ROOT(name))
        else:
            glob_path = os.path.join(config.STATIC_ROOT, name)
            files = glob.glob(glob_path)
            files = sorted((fn[len(config.STATIC_ROOT):], None) for fn in files)

        if not files:
            return

        # Build magic context
        calculator = compilation._make_calculator(rule.namespace)
        map_name = os.path.normpath(os.path.dirname(name)).replace('\\', '_').replace('/', '_')
        kwargs = {}

        # TODO this is all kinds of busted.  rule.context hasn't existed for
        # ages.
        def setdefault(var, val):
            _var = '$' + map_name + '-' + var
            if _var in rule.context:
                kwargs[var] = calculator.interpolate(rule.context[_var], rule, self._library)
            else:
                rule.context[_var] = val
                kwargs[var] = calculator.interpolate(val, rule, self._library)
            return rule.context[_var]

        setdefault('sprite-base-class', String('.' + map_name + '-sprite', quotes=None))
        setdefault('sprite-dimensions', Boolean(False))
        position = setdefault('position', Number(0, '%'))
        spacing = setdefault('spacing', Number(0))
        repeat = setdefault('repeat', String('no-repeat', quotes=None))
        names = tuple(os.path.splitext(os.path.basename(file))[0] for file, storage in files)
        for n in names:
            setdefault(n + '-position', position)
            setdefault(n + '-spacing', spacing)
            setdefault(n + '-repeat', repeat)
        rule.context['$' + map_name + '-' + 'sprites'] = sprite_map(name, **kwargs)
        generated_code = '''
            @import "compass/utilities/sprites/base";

            // All sprites should extend this class
            // The %(map_name)s-sprite mixin will do so for you.
            #{$%(map_name)s-sprite-base-class} {
                background: $%(map_name)s-sprites;
            }

            // Use this to set the dimensions of an element
            // based on the size of the original image.
            @mixin %(map_name)s-sprite-dimensions($name) {
                @include sprite-dimensions($%(map_name)s-sprites, $name);
            }

            // Move the background position to display the sprite.
            @mixin %(map_name)s-sprite-position($name, $offset-x: 0, $offset-y: 0) {
                @include sprite-position($%(map_name)s-sprites, $name, $offset-x, $offset-y);
            }

            // Extends the sprite base class and set the background position for the desired sprite.
            // It will also apply the image dimensions if $dimensions is true.
            @mixin %(map_name)s-sprite($name, $dimensions: $%(map_name)s-sprite-dimensions, $offset-x: 0, $offset-y: 0) {
                @extend #{$%(map_name)s-sprite-base-class};
                @include sprite($%(map_name)s-sprites, $name, $dimensions, $offset-x, $offset-y);
            }

            @mixin %(map_name)s-sprites($sprite-names, $dimensions: $%(map_name)s-sprite-dimensions) {
                @include sprites($%(map_name)s-sprites, $sprite-names, $%(map_name)s-sprite-base-class, $dimensions);
            }

            // Generates a class for each sprited image.
            @mixin all-%(map_name)s-sprites($dimensions: $%(map_name)s-sprite-dimensions) {
                @include %(map_name)s-sprites(%(sprites)s, $dimensions);
            }
        ''' % {'map_name': map_name, 'sprites': ' '.join(names)}

        return SourceFile.from_string(generated_code)
884700
function (source, options, verbose) {
    /* Single file import */
    if ( 'string' == typeof source ) {
        return imports(source, options, verbose);
    }

    /* Multiple files import */
    else if ( 'object' == typeof source ) {
        /* Creating scripts holder */
        var scripts = '', result;

        /* Files in array */
        if ( Array.isArray(source) ) {
            source.forEach(function (file, i) {
                var scr = imports(file, options, verbose);

                if ( scr ) {
                    scripts += scr.text;

                    if ( i == 0 ) {
                        result = scr;
                    }
                }
            });

            if ( result ) {
                return result;
            }
        }

        /* Files in object */
        else {
            var start = 0;

            source.forEach(function (file, options) {
                var scr = imports(file, options, verbose);

                if ( scr ) {
                    scripts += scr.text;

                    if ( start == 0 ) {
                        result = scr;
                    }
                }

                start++;
            });

            if ( result ) {
                return result;
            }
        }
    }
}
580882
def handle(self, *file_paths, **options):
        
        import os

        for file_path in file_paths:
            if not os.path.isfile(file_path):
                print("File %s not found." % file_path)
                continue
            f = open(file_path, 'r')
            data = f.readlines()
            f.close()

            self.parse_lines(data)
249167
async function main(inputDir) {
  const index = new Index();
  try {
    const files = await readdir(inputDir);

    // Get a list of all files in the directory (filter out other directories)
    const allImageFiles = (await Promise.all(
      files.map(async file => {
        const filename = path.join(inputDir, file);
        const stats = await stat(filename);
        if (!stats.isDirectory()) {
          return filename;
        }
      })
    )).filter(f => !!f);

    // Figure out which files have already been processed
    let imageFilesToProcess = (await Promise.all(
      allImageFiles.map(async filename => {
        const processed = await index.documentIsProcessed(filename);
        if (!processed) {
          // Forward this filename on for further processing
          return filename;
        }
      })
    )).filter(file => !!file);

    // The batch endpoint won't handle
    if (imageFilesToProcess.length > 15) {
      console.log(
        'Maximum of 15 images allowed. Analyzing the first 15 found.'
      );
      imageFilesToProcess = imageFilesToProcess.slice(0, 15);
    }

    // Analyze any remaining unprocessed files
    if (imageFilesToProcess.length > 0) {
      console.log('Files to process: ');
      await getTextFromFiles(index, imageFilesToProcess);
    }
    console.log('All files processed!');
  } catch (e) {
    console.error(e);
  }
  index.quit();
}
265654
def visit_Import(self, node, frame):
        """"""
        self.writeline('%s = ' % frame.symbols.ref(node.target), node)
        if frame.toplevel:
            self.write('context.vars[%r] = ' % node.target)
        if self.environment.is_async:
            self.write('await ')
        self.write('environment.get_template(')
        self.visit(node.template, frame)
        self.write(', %r).' % self.name)
        if node.with_context:
            self.write('make_module%s(context.get_all(), True, %s)'
                       % (self.environment.is_async and '_async' or '',
                          self.dump_local_context(frame)))
        elif self.environment.is_async:
            self.write('_get_default_module_async()')
        else:
            self.write('_get_default_module()')
        if frame.toplevel and not node.target.startswith('_'):
            self.writeline('context.exported_vars.discard(%r)' % node.target)
374629
protected function processImports($imports, $dir)
    {
        foreach ($imports as $import) {
            $this->setCurrentDir($dir);
            $this->import($import);
        }
    }
1362175
def global_include(self, pattern):
        
        if self.allfiles is None:
            self.findall()
        match = translate_pattern(os.path.join('**', pattern))
        found = [f for f in self.allfiles if match.match(f)]
        self.extend(found)
        return bool(found)
561724
function(path) {
      var code = require('fs').readFileSync(path);
      var context = vm.createContext(initContext);
      context.flow = _conn.flow;
      vm.runInContext(code, context);
      for (var key in context) {
        if (!initContext[key]) {
          global[key] = context[key];
        }
      }
    }