Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge cargo-cp-artifact into monorepo #905

Merged
merged 16 commits into from
Jun 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 16 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions pkgs/cargo-cp-artifact/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 The Neon Project

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
93 changes: 93 additions & 0 deletions pkgs/cargo-cp-artifact/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# cargo-cp-artifact

`cargo-cp-artifact` is a small command line utility for parsing cargo metadata output and copying a compiler artifact to a desired location.

## Installation

```sh
npm install -g cargo-cp-artifact
```

## Usage

```
cargo-cp-artifact --artifact artifact-kind crate-name output-file -- wrapped-command
```

`cargo-cp-artifact` accepts a list of crate name and artifact kind to output file mappings and a command to wrap.`cargo-cp-artifact` will read `stdout` of the wrapped command and parse it as [cargo metadata](https://doc.rust-lang.org/cargo/reference/external-tools.html#json-messages). Compiler artifacts that match arguments provided will be copied to the target destination.

When wrapping a `cargo` command, it is necessary to include a `json` format to `--message-format`.

### Arguments

Multiple arguments are allowed to copy multiple build artifacts.

#### `--artifact`

_Alias: `-a`_

Followed by *three* arguments: `artifact-kind crate-name output-file`

#### `--npm`

_Alias: `-n`_

Followed by *two* arguments: `artifact-kind output-file`

The crate name will be read from the `npm_package_name` environment variable. If the package name includes a namespace (`@namespace/package`), the namespace will be removed when matching the crate name (`package`).

### Artifact Kind

Valid artifact kinds are `bin`, `cdylib`, and `dylib`. They may be abbreviated as `b`, `c`, and `d` respectively.

For example, `-ac` is the equivalent of `--artifact cdylib`.

## Examples

### Wrapping cargo

```sh
cargo-cp-artifact -a cdylib my-crate lib/index.node -- cargo build --message-format=json-render-diagnostics
```

### Parsing a file

```sh
cargo-cp-artifact -a cdylib my-crate lib/index.node -- cat build-output.txt
```

### `npm` script

`package.json`
```json
{
"name": "my-crate",
"scripts": {
"build": "cargo-cp-artifact -nc lib/index.node -- cargo build --message-format=json-render-diagnostics"
}
}
```

```sh
npm run build

# Additional arguments may be passed
npm run build -- --feature=serde
```

## Why does this exist?

At the time of writing, `cargo` does not include a configuration for outputting a library or binary to a specified location. An `--out-dir` option [exists on nightly](https://github.com/rust-lang/cargo/issues/6790), but does not allow specifying the name of the file.

It surprisingly difficult to reliably find the location of a cargo compiler artifact. It is impacted by many parameters, including:

* Build profile
* Target, default or specified
* Crate name and name transforms

However, `cargo` can emit metadata on `stdout` while continuing to provide human readable diagnostics on `stderr`. The metadata may be parsed to more easily and reliably find the location of compiler artifacts.

`cargo-cp-artifact` chooses to wrap a command as a child process instead of reading `stdin` for two reasons:

1. Removes the need for `-o pipefile` when integrating with build tooling which may need to be platform agnostic.
2. Allows additional arguments to be provided when used in an [`npm` script](https://docs.npmjs.com/cli/v6/using-npm/scripts).
6 changes: 6 additions & 0 deletions pkgs/cargo-cp-artifact/bin/cargo-cp-artifact.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/usr/bin/env node
"use strict";

const run = require("..");

run(process.argv.slice(2), process.env);
34 changes: 34 additions & 0 deletions pkgs/cargo-cp-artifact/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "cargo-cp-artifact",
"version": "0.1.6",
"description": "Copies compiler artifacts emitted by rustc by parsing Cargo metadata",
"main": "src/index.js",
"files": [
"bin",
"src"
],
"bin": {
"cargo-cp-artifact": "bin/cargo-cp-artifact.js"
},
"scripts": {
"test": "mocha test"
},
"repository": {
"type": "git",
"url": "git+https://github.com/neon-bindings/neon.git"
},
"keywords": [
"cargo",
"rust",
"neon"
],
"author": "K.J. Valencik",
"license": "MIT",
"bugs": {
"url": "https://github.com/neon-bindings/neon/issues"
},
"homepage": "https://github.com/neon-bindings/neon/tree/main/pkgs/cargo-cp-artifact",
"devDependencies": {
"mocha": "^9.1.0"
}
}
131 changes: 131 additions & 0 deletions pkgs/cargo-cp-artifact/src/args.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
"use strict";

class ParseError extends Error {}

const NPM_ENV = "npm_package_name";
const EXPECTED_COMMAND = [
"Missing command to execute.",
[
"cargo-cp-artifct -a cdylib my-crate index.node",
"--",
"cargo build --message-format=json-render-diagnostics",
].join(" "),
].join("\n");

function validateArtifactType(artifactType) {
switch (artifactType) {
case "b":
case "bin":
return "bin";
case "c":
case "cdylib":
return "cdylib";
case "d":
case "dylib":
return "dylib";
default:
}

throw new ParseError(`Unexpected artifact type: ${artifactType}`);
}

function getArtifactName({ artifactType, crateName }) {
return `${artifactType}:${crateName}`;
}

function getCrateNameFromEnv(env) {
if (!env.hasOwnProperty(NPM_ENV)) {
throw new ParseError(
[
`Could not find the \`${NPM_ENV}\` environment variable.`,
"Expected to be executed from an `npm` command.",
].join(" ")
);
}

const name = env[NPM_ENV];
const firstSlash = name.indexOf("/");

// This is a namespaced package; assume the crate is the un-namespaced version
if (name[0] === "@" && firstSlash > 0) {
return name.slice(firstSlash + 1);
}

return name;
}

function parse(argv, env) {
const artifacts = {};
let tokens = argv;

function getNext() {
if (!tokens.length) {
throw new ParseError(EXPECTED_COMMAND);
}

const next = tokens[0];
tokens = tokens.slice(1);
return next;
}

function getArtifactType(token) {
if (token[1] !== "-" && token.length === 3) {
return validateArtifactType(token[2]);
}

return validateArtifactType(getNext());
}

function pushArtifact(artifact) {
const name = getArtifactName(artifact);

artifacts[name] = artifacts[name] || [];
artifacts[name].push(artifact.outputFile);
}

while (tokens.length) {
const token = getNext();

// End of CLI arguments
if (token === "--") {
break;
}

if (
token === "--artifact" ||
(token.length <= 3 && token.startsWith("-a"))
) {
const artifactType = getArtifactType(token);
const crateName = getNext();
const outputFile = getNext();

pushArtifact({ artifactType, crateName, outputFile });
continue;
}

if (token === "--npm" || (token.length <= 3 && token.startsWith("-n"))) {
const artifactType = getArtifactType(token);
const crateName = getCrateNameFromEnv(env);
const outputFile = getNext();

pushArtifact({ artifactType, crateName, outputFile });
continue;
}

throw new ParseError(`Unexpected option: ${token}`);
}

if (!tokens.length) {
throw new ParseError(EXPECTED_COMMAND);
}

const cmd = getNext();

return {
artifacts,
cmd,
args: tokens,
};
}

module.exports = { ParseError, getArtifactName, parse };
Loading