Rewrite imports in packaging to redirect to vendored copies.
962897
def rewrite_packaging(pkg_files, new_root):
    
    for file in pkg_files.glob('*.py'):
        text = file.text()
        text = re.sub(r' (pyparsing|six)', rf' {new_root}.\1', text)
        file.write_text(text)
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
1289199
function rebundle() {
    var debug, min;

    debug = sourcemaps.init({loadMaps: true});
    debug.pipe(sourcemaps.write('./', {sourceRoot: './'}))
        .pipe(gulp.dest(paths.out));

    min = rename({ suffix: '.min' });
    min.pipe(sourcemaps.init({loadMaps: true}))
        .pipe(uglify())
        .pipe(sourcemaps.write('./', {sourceRoot: './', addComment: false}))
        .pipe(gulp.dest(paths.out));

    return this.bundle()
        .on('error', handleErrors.handler)
        .pipe(handleErrors())
        .pipe(source('pixi.js'))
        .pipe(buffer())
        .pipe(mirror(
            debug,
            min
        ));
}
518485
function preparePackage() {
    var ignoreFiles = ['package.json', 'README.md', 'LICENSE.md', '.gitignore', '.npmignore'];
    var ignoreCopyFiles = [];
    var copyRecursiveSync = function(src, dest) {
        var exists = fs.existsSync(src);
        var stats = exists && fs.statSync(src);
        var isDirectory = exists && stats.isDirectory();
        if (exists && isDirectory) {
            if (!fs.existsSync(dest)) {
                fs.mkdirSync(dest);
            }
            fs.readdirSync(src).forEach(function(filename) {
                copyRecursiveSync(upath.join(src, filename),
                    upath.join(dest, filename));
            });
        } else {
            if (ignoreCopyFiles.indexOf(upath.basename(src)) === -1) {
                fs.linkSync(src, dest);
            }
        }
    };
    var srcPkg = upath.join(process.cwd(), 'src');
    if (fs.existsSync(srcPkg)) {
        fs.readdirSync(process.cwd()).forEach(function(filename) {
            var curPath = upath.join(process.cwd(), filename);
            if (ignoreFiles.indexOf(upath.basename(curPath)) === -1 && fs.statSync(curPath).isFile()) {
                fs.unlinkSync(curPath);
            }
        });
        copyRecursiveSync(srcPkg, process.cwd());
    }
    deleteFolderRecursive(srcPkg);
    deleteFolderRecursive(upath.join(process.cwd(), 'test'));
    deleteFolderRecursive(upath.join(process.cwd(), 'env'));
}
109237
def __PrintAdditionalImports(self, imports):
        """"""
        google_imports = [x for x in imports if 'google' in x]
        other_imports = [x for x in imports if 'google' not in x]
        if other_imports:
            for import_ in sorted(other_imports):
                self.__printer(import_)
            self.__printer()
        # Note: If we ever were going to add imports from this package, we'd
        # need to sort those out and put them at the end.
        if google_imports:
            for import_ in sorted(google_imports):
                self.__printer(import_)
            self.__printer()
113911
function transform(args, opts, cb) {
  opts.config.relativeTo = opts.config.relativeTo || process.cwd();
  verbose = opts.config.verbose;

  var oldRequire = args[0];

  // Only look at non-local require statements
  if (oldRequire[0] !== ".") {
    log("Processing", oldRequire, "in", opts.file);
    var pathToRelative = path.relative(path.dirname(opts.file), opts.config.relativeTo);

    // Try and find a matching package
    var pkg = findPackage(opts.config, oldRequire);
    if (pkg) {
      var newRequire = "." + path.sep + path.join(pathToRelative, oldRequire.replace(pkg.name, pkg.src));

      // replace single backslashes with double backslashes for file paths in windows
      newRequire = newRequire.replace(/\\/gi, "/");

      log("Found pkg for", oldRequire, ":", pkg.name);
      log("Mapping to", newRequire);
      return cb(null, "require(\"" + newRequire + "\")");
    }

  }

  // Default behaviour - just return original
  return cb();
}
1267906
def apply_refactor(self, call_id, payload):
        """"""
        supported_refactorings = ["Rename", "InlineLocal", "AddImport", "OrganizeImports"]

        if payload["refactorType"]["typehint"] in supported_refactorings:
            diff_filepath = payload["diff"]
            path = self.editor.path()
            bname = os.path.basename(path)
            target = os.path.join(self.tmp_diff_folder, bname)
            reject_arg = "--reject-file={}.rej".format(target)
            backup_pref = "--prefix={}".format(self.tmp_diff_folder)
            # Patch utility is prepackaged or installed with vim
            cmd = ["patch", reject_arg, backup_pref, path, diff_filepath]
            failed = Popen(cmd, stdout=PIPE, stderr=PIPE).wait()
            if failed:
                self.editor.message("failed_refactoring")
            # Update file and reload highlighting
            self.editor.edit(self.editor.path())
            self.editor.doautocmd('BufReadPre', 'BufRead', 'BufEnter')
619044
public void copyPackagesExcept(BuildState prev, Set<String> recompiled, Set<String> removed) {
        for (String pkg : prev.packages().keySet()) {
            // Do not copy recompiled or removed packages.
            if (recompiled.contains(pkg) || removed.contains(pkg)) continue;
            Module mnew = findModuleFromPackageName(pkg);
            Package pprev = prev.packages().get(pkg);
            mnew.addPackage(pprev);
            // Do not forget to update the flattened data.
            packages.put(pkg, pprev);
        }
    }
150557
def copyFuncVersionedLib(dest, source, env):
    """"""

    if os.path.isdir(source):
        raise SCons.Errors.UserError("cannot install directory `%s' as a version library" % str(source) )
    else:
        # remove the link if it is already there
        try:
            os.remove(dest)
        except:
            pass
        shutil.copy2(source, dest)
        st = os.stat(source)
        os.chmod(dest, stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE)
        installShlibLinks(dest, source, env)

    return 0
618347
def clone_from_upstream(pkg_name, repo_url):
        """"""
        msg = "Spawning a cloning task for %s from upstream due to API req."
        LOG.info(msg % pkg_name)

        upstream_url = settings.UPSTREAM_BOWER_REGISTRY
        upstream_pkg = bowerlib.get_package(upstream_url, pkg_name)

        if upstream_pkg is None:
            raise Http404

        task = tasks.clone_repo.delay(pkg_name, upstream_pkg['url'])
        try:
            result = task.get(timeout=5)
        except tasks.TimeoutError:
            # Not done yet. What to return?
            raise ServiceUnavailable

        return result.to_package(repo_url)
40478
def vendor_import(name):
    """"""
    parent_dir = os.path.abspath(os.path.dirname(__file__))
    vendor_dir = os.path.join(parent_dir, 'vendor')

    sys.path.insert(1, vendor_dir)
    return import_module(name)
1236093
def license_destination(vendor_dir, libname, filename):
    """"""
    normal = vendor_dir / libname
    if normal.is_dir():
        return normal / filename
    lowercase = vendor_dir / libname.lower().replace('-', '_')
    if lowercase.is_dir():
        return lowercase / filename
    rename_dict = LIBRARY_RENAMES if vendor_dir.name != 'patched' else PATCHED_RENAMES
    # Short circuit all logic if we are renaming the whole library
    if libname in rename_dict:
        return vendor_dir / rename_dict[libname] / filename
    if libname in LIBRARY_DIRNAMES:
        override = vendor_dir / LIBRARY_DIRNAMES[libname]
        if not override.exists() and override.parent.exists():
            # for flattened subdeps, specifically backports/weakref.py
            return (
                vendor_dir / override.parent
            ) / '{0}.{1}'.format(override.name, filename)
        return vendor_dir / LIBRARY_DIRNAMES[libname] / filename
    # fallback to libname.LICENSE (used for nondirs)
    return vendor_dir / '{}.{}'.format(libname, filename)
884074
function patchRequire(require) {
        if (require.patched) {
            return require;
        }
        function fromPackageJson(module, dir) {
            var pkgPath, pkgContents, pkg;
            pkgPath = fs.pathJoin(dir, module, 'package.json');
            if (!fs.exists(pkgPath)) {
                return;
            }
            pkgContents = fs.read(pkgPath);
            if (!pkgContents) {
                return;
            }
            try {
                pkg = JSON.parse(pkgContents);
            } catch (e) {
                return;
            }
            if (typeof pkg === "object" && pkg.main) {
                return fs.absolute(fs.pathJoin(dir, module, pkg.main));
            }
        }
        function resolveFile(path, dir) {
            var extensions = ['js', 'coffee', 'json'];
            var basenames = [path, path + '/index'];
            var paths = [];
            var nodejsScript = fromPackageJson(path, dir);
            if (nodejsScript) {
                return nodejsScript;
            }
            basenames.forEach(function(basename) {
                paths.push(fs.absolute(fs.pathJoin(dir, basename)));
                extensions.forEach(function(extension) {
                    paths.push(fs.absolute(fs.pathJoin(dir, [basename, extension].join('.'))));
                });
            });
            for (var i = 0; i < paths.length; i++) {
                if (fs.isFile(paths[i])) {
                    return paths[i];
                }
            }
            return null;
        }
        function getCurrentScriptRoot() {
            if ((phantom.casperScriptBaseDir || "").indexOf(fs.workingDirectory) === 0) {
                return phantom.casperScriptBaseDir;
            }
            return fs.absolute(fs.pathJoin(fs.workingDirectory, phantom.casperScriptBaseDir));
        }
        function casperBuiltinPath(path) {
            return resolveFile(path, fs.pathJoin(phantom.casperPath, 'modules'));
        }
        function nodeModulePath(path) {
            var resolved, prevBaseDir;
            var baseDir = getCurrentScriptRoot();
            do {
                resolved = resolveFile(path, fs.pathJoin(baseDir, 'node_modules'));
                prevBaseDir = baseDir;
                baseDir = fs.absolute(fs.pathJoin(prevBaseDir, '..'));
            } while (!resolved && baseDir !== '/' && prevBaseDir !== '/' && baseDir !== prevBaseDir);
            return resolved;
        }
        function localModulePath(path) {
            return resolveFile(path, phantom.casperScriptBaseDir || fs.workingDirectory);
        }
        var patchedRequire = function patchedRequire(path) {
            try {
                return require(casperBuiltinPath(path) ||
                               nodeModulePath(path)    ||
                               localModulePath(path)   ||
                               path);
            } catch (e) {
                throw new CasperError("Can't find module " + path);
            }
        };
        patchedRequire.cache = require.cache;
        patchedRequire.extensions = require.extensions;
        patchedRequire.stubs = require.stubs;
        patchedRequire.patched = true;
        return patchedRequire;
    }
1310271
function convertForPackage(context, pkg) {
	var name = pkg.name;
	var version = pkg.version;

	var conv = context.deferredConversions;
	var pkgConv = conv[name];
	var depPkg, fns, keys = 0;
	if(pkgConv) {
		for(var range in pkgConv) {
			depPkg = crawl.matchedVersion(context, name, range);
			if(depPkg) {
				fns = pkgConv[range];
				for(var i = 0, len = fns.length; i < len; i++) {
					fns[i].call(context);
				}
				delete pkgConv[range];
			} else {
				keys++;
			}
		}
		if(keys === 0) {
			delete conv[name];
		}
	}
}
128080
def rename(oldPath, newPath, **kwargs):
    """"""
    import os
    return os.rename(oldPath, newPath, **kwargs)
142217
def _rewrite_paths_in_file(config_file, paths_to_replace):
        
        lines = []
        # make a copy of config
        import shutil
        shutil.copyfile(config_file, str(config_file + '_original'))
        with open(config_file) as infile:
            for line in infile:
                for old_path in paths_to_replace:
                    if old_path in line:
                        new_path = os.path.split(old_path)[-1]
                        line = line.replace(old_path, new_path)
                        logger.debug("Changed path {0} ---> {1} in file {2}".format(old_path, new_path, config_file))
                lines.append(line)
        with open(config_file, 'w') as outfile:
            for line in lines:
                outfile.write(line)
143952
def fromimportupdate(cls, bundle, import_reg):
        # type: (Bundle, ImportRegistration) -> RemoteServiceAdminEvent
        
        exc = import_reg.get_exception()
        if exc:
            return RemoteServiceAdminEvent(
                RemoteServiceAdminEvent.IMPORT_ERROR,
                bundle,
                import_reg.get_import_container_id(),
                import_reg.get_remoteservice_id(),
                None,
                None,
                exc,
                import_reg.get_description(),
            )

        return RemoteServiceAdminEvent(
            RemoteServiceAdminEvent.IMPORT_UPDATE,
            bundle,
            import_reg.get_import_container_id(),
            import_reg.get_remoteservice_id(),
            import_reg.get_import_reference(),
            None,
            None,
            import_reg.get_description(),
        )