in internal/npm_install/generate_build_file.ts [469:537]
async function generateBazelWorkspace(pkg: Dep, workspace: string) {
let bzlFile = `# Generated by the yarn_install/npm_install rule
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@build_bazel_rules_nodejs//internal/copy_repository:copy_repository.bzl", "copy_repository")
`;
const rootPath = pkg.bazelWorkspaces[workspace].rootPath;
if (!rootPath) {
console.error(
`Malformed bazelWorkspaces attribute in ${pkg._dir}@${pkg.version}. ` +
`Missing rootPath for workspace ${workspace}.`);
process.exit(1);
}
// Copy all files for this workspace to a folder under _workspaces
// to restore the Bazel files which have be renamed from the npm package
const workspaceSourcePath = path.posix.join('_workspaces', workspace);
const nodeModules = nodeModulesFolder();
await mkdirp(workspaceSourcePath);
await Promise.all(pkg._files.map(async (file) => {
if (/^node_modules[/\\]/.test(file)) {
// don't copy over nested node_modules
return;
}
let destFile = path.relative(rootPath, file);
if (destFile.startsWith('..')) {
// this file is not under the rootPath
return;
}
const basename = path.basename(file);
const basenameUc = basename.toUpperCase();
// Bazel BUILD files from npm distribution of rules_nodejs 1.x
// would have been renamed before publishing with a _ prefix so
// we restore the name on the copy
if (basenameUc === '_BUILD' || basenameUc === '_BUILD.BAZEL') {
destFile = path.posix.join(path.dirname(destFile), basename.substr(1));
}
const src = path.posix.join(nodeModules, pkg._dir, file);
const dest = path.posix.join(workspaceSourcePath, destFile);
await mkdirp(path.dirname(dest));
await fs.copyFile(src, dest);
}));
// We create _bazel_workspace_marker that is used by the custom copy_repository
// rule to resolve the path to the repository source root. A root BUILD file
// is required to reference _bazel_workspace_marker as a target so we also create
// an empty one if one does not exist.
if (!hasRootBuildFile(pkg, rootPath)) {
await writeFile(
path.posix.join(workspaceSourcePath, 'BUILD.bazel'),
'# Marker file that this directory is a bazel package');
}
const sha256sum = crypto.createHash('sha256');
sha256sum.update(await fs.readFile(config.package_lock, {encoding: 'utf8'}));
await writeFile(
path.posix.join(workspaceSourcePath, '_bazel_workspace_marker'),
`# Marker file to used by custom copy_repository rule\n${sha256sum.digest('hex')}`);
bzlFile += `def install_${workspace}():
maybe(
copy_repository,
name = "${workspace}",
marker_file = "@${config.workspace}//_workspaces/${workspace}:_bazel_workspace_marker",
)
`;
await writeFile(`install_${workspace}.bzl`, bzlFile);
}