Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
export default async function fetchTemplate(destinationPath: string, template?: string) {
if (template && fse.existsSync(path.resolve(template))) {
// local template
Logger.global.info(`Using local template: ${chalk.bold(path.resolve(template))}.`);
await fse.copy(path.resolve(template), destinationPath);
} else if (template && isNpmPackage(template)) {
// npm package
Logger.global.info(`Using NPM package as template: ${chalk.bold(template)}`);
await pacote.extract(template, destinationPath);
} else {
// default npm packge
Logger.global.info(`Using default NPM package as template: ${chalk.bold(DEFAULT_TEMPLATE)}`);
await pacote.extract(DEFAULT_TEMPLATE, destinationPath);
}
if (await fse.pathExists(path.join(destinationPath, 'template-unimodule.json'))) {
await fse.move(
path.join(destinationPath, 'template-unimodule.json'),
path.join(destinationPath, 'unimodule.json')
);
}
}
async _installPackage({pkgName, version, targetDir}) {
try {
await stat(path.join(targetDir, "package.json"));
log.verbose(`Alrady installed: ${pkgName} in version ${version}`);
this._cachedCounter++;
} catch (err) {
if (err.code === "ENOENT") { // "File or directory does not exist"
log.info(`Installing ${pkgName}...`);
log.verbose(`Installing ${pkgName} in version ${version}...`);
await pacote.extract(`${pkgName}@${version}`, targetDir, this._getPacoteOptions());
this._installedCounter++;
} else {
throw err;
}
}
}
async function processPackageTarball(name, version, options) {
const { ref, tmpLocation } = options;
const dest = join(tmpLocation, `${name}@${version}`);
const free = await tarballLocker.acquireOne();
try {
await pacote.extract(ref.flags.isGit ? ref.gitUrl : `${name}@${version}`, dest, {
...token,
registry: REGISTRY_DEFAULT_ADDR,
cache: `${process.env.HOME}/.npm`
});
await new Promise((resolve) => setImmediate(resolve));
let isProjectUsingESM = false;
// Read the package.json file in the extracted tarball
try {
const packageStr = await readFile(join(dest, "package.json"), "utf-8");
const { type = "script", description = "", author = {}, scripts = {} } = JSON.parse(packageStr);
ref.description = description;
ref.author = author;
isProjectUsingESM = type === "module";
ref.flags.hasScript = [...Object.keys(scripts)].some((value) => NPM_SCRIPTS.has(value.toLowerCase()));
const specs = trySpecs(this.spec, this.adaptVersion);
// Remember errors that pertain to accessing the base spec, independent
// of version label.
const baseSpecErrs = new Map();
do {
const spec = specs.shift();
if (!spec) throw new InternalError(`empty spec list`);
try {
const prevErr = baseSpecErrs.get(spec.base);
if (prevErr) throw prevErr;
log(`Trying ${spec.complete}`);
await pacote.extract(spec.complete, this.starterDir, opts);
return;
} catch (err) {
err = ensureError(err);
if (err.code === "ENOENT" && err.path === path.join(this.starterDir, "package.json")) {
// SUCCESS. We don't require a package.json
return;
}
if (specs.length === 0) throw new SpecError(spec.complete, err.message);
// If we can't access the base spec (e.g. git repo or npm package
// doesn't exist), then don't try additional versions of that
// base spec.
if (isErrorWithBaseSpec(spec, err)) baseSpecErrs.set(spec.base, err);
}
} while (true);
} catch (err) {
log.error(err)
return CliExitCodes.ERROR.INPUT
}
const manifestId = new ManifestId(manifest)
const globalPackagePath = path.join(this.globalConfig.globalFolderPath,
manifestId.getPath())
const xpack = new Xpack({ xpackFolderAbsolutePath: config.cwd, log })
const packFullName = manifestId.getFullName()
// Read the cwd package.json
let globalJson = await xpack.hasPackageJson(globalPackagePath)
if (!globalJson) {
log.info(`Installing ${packFullName}...`)
await pacote.extract(config.template, globalPackagePath,
{ cache: cachePath })
log.info('Installing npm dependencies...')
const spawn = new Spawn()
const code = await spawn.executeShellPromise(
'npm install --production --color=false',
{
cwd: globalPackagePath
})
if (code !== 0) {
log.error(`Install dependencies failed (npm returned ${code}).`)
await del(globalPackagePath, { force: true })
return CliExitCodes.ERROR.APPLICATION
}
globalJson = await xpack.hasPackageJson(globalPackagePath)
}
async updateDatabase() {
// Download and extract the database package from npm
logger.info( `Downloading database update to ${this.tempFolder}` )
await remove( this.tempFolder )
await extract( databasePackage, this.tempFolder )
logger.info( 'Hot-patching database module' )
// Disconnect the Shabad OS database connection
await knex.destroy()
// Move across the updated npm database module
await move( this.tempFolder, DATABASE_FOLDER, { overwrite: true } )
// Reimport the database
//! Relies on knex being reinitialised globally
importFresh( '@shabados/database' )
}
export default async function fetchTemplate(destinationPath: string, template?: string) {
if (template && fse.existsSync(path.resolve(template))) {
// local template
Logger.global.info(`Using local template: ${chalk.bold(path.resolve(template))}.`);
await fse.copy(path.resolve(template), destinationPath);
} else if (template && isNpmPackage(template)) {
// npm package
Logger.global.info(`Using NPM package as template: ${chalk.bold(template)}`);
await pacote.extract(template, destinationPath);
} else {
// default npm packge
Logger.global.info(`Using default NPM package as template: ${chalk.bold(DEFAULT_TEMPLATE)}`);
await pacote.extract(DEFAULT_TEMPLATE, destinationPath);
}
if (await fse.pathExists(path.join(destinationPath, 'template-unimodule.json'))) {
await fse.move(
path.join(destinationPath, 'template-unimodule.json'),
path.join(destinationPath, 'unimodule.json')
);
}
}
.then(() => cacache.tmp.withTmp(npm.tmp, {tmpPrefix: 'unpacking'}, (tmp) => {
const tmpTarget = path.join(tmp, filename)
return pacote.extract(arg, tmpTarget, opts)
.then(() => readJson(path.join(tmpTarget, 'package.json')))
}))
.then((pkg) => getContents(pkg, target, filename))
async installInRepository (
{ packSpec, globalPackagePath, cachePath, manifestId }) {
assert(packSpec)
assert(globalPackagePath)
assert(cachePath)
assert(manifestId)
const log = this.log
await pacote.extract(packSpec, globalPackagePath, { cache: cachePath })
log.debug(`npm ${packSpec} package extracted.`)
await this.xpack.downloadBinaries(
{ packagePath: globalPackagePath, cachePath, manifestId })
log.verbose(`Write protecting folder '${globalPackagePath}'...`)
await this.xpack.changeModeWritableRecursive(
{ absolutePath: globalPackagePath, isWritable: false })
}