From 8da4368553472087ea3584133357e9ed99e4f9ef Mon Sep 17 00:00:00 2001 From: messense Date: Sat, 1 Oct 2022 15:28:39 +0800 Subject: [PATCH] feat(cli): parse `Cargo.toml` using `cargo read-manifest` --- cli/src/build.ts | 40 +++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/cli/src/build.ts b/cli/src/build.ts index 10dfb033b7..38ae9fed84 100644 --- a/cli/src/build.ts +++ b/cli/src/build.ts @@ -7,7 +7,6 @@ import { Instance } from 'chalk' import { Command, Option } from 'clipanion' import envPaths from 'env-paths' import { groupBy } from 'lodash-es' -import toml from 'toml' import { getNapiConfig } from './consts' import { debugFactory } from './debug' @@ -191,26 +190,25 @@ export class BuildCommand extends Command { const cwd = this.cargoCwd ? join(process.cwd(), this.cargoCwd) : process.cwd() + const cargoTomlPath = join(cwd, 'Cargo.toml') - let tomlContentString: string - let tomlContent: any - try { - debug('Start read toml') - tomlContentString = await readFileAsync(join(cwd, 'Cargo.toml'), 'utf-8') - } catch { - throw new TypeError(`Could not find Cargo.toml in ${cwd}`) - } + let cargoManifest: any try { debug('Start parse toml') - tomlContent = toml.parse(tomlContentString) + cargoManifest = JSON.parse( + execSync(`cargo read-manifest --manifest-path ${cargoTomlPath}`, { + stdio: 'pipe', + maxBuffer: 1024 * 1024 * 10, + }).toString('utf8'), + ) } catch { throw new TypeError('Could not parse the Cargo.toml') } let cargoPackageName: string - if (tomlContent.package?.name) { - cargoPackageName = tomlContent.package.name + if (cargoManifest.name) { + cargoPackageName = cargoManifest.name } else if (this.cargoName) { cargoPackageName = this.cargoName } else { @@ -218,10 +216,13 @@ export class BuildCommand extends Command { } const cargoMetadata = JSON.parse( - execSync('cargo metadata --format-version 1', { - stdio: 'pipe', - maxBuffer: 1024 * 1024 * 10, - }).toString('utf8'), + execSync( + `cargo metadata --format-version 1 --manifest-path ${cargoTomlPath}`, + { + stdio: 'pipe', + maxBuffer: 1024 * 1024 * 10, + }, + ).toString('utf8'), ) const packages = cargoMetadata.packages const cargoPackage = packages.find( @@ -369,7 +370,12 @@ export class BuildCommand extends Command { cargoArtifactName = cargoPackageName.replace(/-/g, '_') } - if (!this.bin && !tomlContent.lib?.['crate-type']?.includes?.('cdylib')) { + if ( + !this.bin && + !cargoManifest.targets.some((target: { crate_types: string[] }) => + target.crate_types.includes('cdylib'), + ) + ) { throw new TypeError( `Missing ${chalk.green('crate-type = ["cdylib"]')} in ${chalk.green( '[lib]',