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

RFC: Writing create-neon in Rust as a neon module #1

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
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
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
node_modules
index.node

# Added by cargo

/target
Cargo.lock
25 changes: 25 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
[package]
name = "create-neon"
version = "0.1.0"
authors = ["Dave Herman <[email protected]>"]
description = "Script to create Neon projects"
readme = "README.md"
homepage = "https://www.neon-bindings.com"
repository = "https://github.com/neon-bindings/neon"
license = "MIT/Apache-2.0"
publish = false
edition = "2018"

[lib]
crate-type = ["cdylib"]

[build-dependencies]
neon-build = "0.6"

[dependencies]
structopt = "0.3"

[dependencies.neon]
version = "0.6"
default-features = false
features = ["napi-runtime"]
87 changes: 87 additions & 0 deletions cp-cargo-artifacts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
#!/usr/bin/env node

"use strict";

const { dirname } = require("path");
const { copyFile, mkdir } = require("fs");
const readline = require("readline");

const outputFiles = parseArgs(process.argv.slice(2));

const rl = readline.createInterface({ input: process.stdin });

rl.on("line", (line) => {
try {
processCargoBuildLine(line);
} catch (err) {
console.error(err);
}
});

function processCargoBuildLine(line) {
const data = JSON.parse(line);

if (!data || data.reason !== "compiler-artifact" || !data.target) {
return;
}

const outputFile = outputFiles[data.target.name];
const { kind } = data.target;

if (!outputFile || !Array.isArray(data.filenames)) {
return;
}

if (!Array.isArray(kind) || !kind.includes("cdylib")) {
return;
}

const [filename] = data.filenames;

if (!filename) {
return;
}

mkdir(dirname(outputFile), { recursive: true }, (err) => {
if (err) {
return console.error(err);
}

copyFile(filename, outputFile, (err) => {
if (err) {
console.error(err);
}
});
});
}

function parseArgs(args) {
return args
.map((arg, i, arr) => [arg, arr[i + 1]])
.filter(([arg]) => arg === "-o")
.map(([, arg]) => parseOutputArgs(arg))
.reduce((acc, { target, output }) => Object.assign(acc, {
[target]: output
}), {})
}

function printUsage() {
console.error("Expected arguments: -o [crate name]=[output file]");
process.exit(-1);
}

function parseOutputArgs(arg) {
if (!arg) {
return printUsage();
}

const splitAt = arg.indexOf("=");
const target = arg.slice(0, splitAt);
const output = arg.slice(splitAt + 1);

if (splitAt < 0 || !target || !output) {
return printUsage();
}

return { target, output };
}
3 changes: 0 additions & 3 deletions index.js

This file was deleted.

16 changes: 16 additions & 0 deletions package-lock.json

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

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@
"description": "Create Neon projects with zero configuration.",
"main": "index.js",
"scripts": {
"build": "cargo build --message-format=json --release | npm run copy",
"copy": "node cp-cargo-artifacts -o $npm_package_name=index.node",
"postinstall": "npm run build",
"test": "echo \"Error: no test specified\" && exit 1"
},
"bin": {
"create-neon": "./index.js"
"create-neon": "index.node"
},
"repository": {
"type": "git",
Expand Down
43 changes: 43 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use std::path::PathBuf;

use neon::context::{Context, ModuleContext};
use neon::object::Object;
use neon::result::NeonResult;
use neon::types::{JsArray, JsObject, JsString};
use structopt::StructOpt;

#[derive(Debug, StructOpt)]
#[structopt(bin_name = "npm init neon")]
struct Opt {
name: Option<String>,
#[structopt(short, long)]
submodule: Option<PathBuf>,
}

fn cli(argv: Vec<String>) {
let opts = Opt::from_iter(argv);
println!("{:?}", opts);
}

#[neon::main]
fn main(mut cx: ModuleContext) -> NeonResult<()> {
let global = cx.global();

let process = global.get(&mut cx, "process")?
.downcast_or_throw::<JsObject, _>(&mut cx)?;

let argv = process.get(&mut cx, "argv")?
.downcast_or_throw::<JsArray, _>(&mut cx)?
.to_vec(&mut cx)?
.into_iter()
.skip(1)
.map(|v| {
v.downcast_or_throw::<JsString, _>(&mut cx)
.map(|v| v.value(&mut cx))
})
.collect::<Result<_, _>>()?;

cli(argv);

Ok(())
}