UNPKG

2.58 kBJavaScriptView Raw
1const path = require("path");
2const metadata = require("read-metadata");
3const exists = require("fs").existsSync;
4const {
5 userName,
6 email,
7 nameEmail
8} = require("./git-user");
9const validateName = require("validate-npm-package-name");
10global['talentui_info'] = {};
11/**
12 * Read prompts metadata.
13 *
14 * @param {String} dir
15 * @return {Object}
16 */
17
18module.exports = function options(name, dir) {
19 const opts = getMetadata(dir);
20
21 setDefault(opts, "name", name);
22 setDefault(opts, "version", "1.0.0");
23 if (nameEmail) {
24 setDefault(opts, "author", nameEmail);
25 }
26 setDefault(opts, "repository_type", "git");
27 setDefault(opts, "repository_url", `https://github.com/${userName}/${name}.git`);
28 setDefault(opts, "bugs_url", `https://github.com/${userName}/${name}/issues`);
29 setDefault(opts, "homePage", `https://github.com/${userName}/${name}#readme`)
30 setValidateName(opts);
31 setDefault(opts, "description", "");
32
33
34 return opts;
35};
36
37/**
38 * Gets the metadata from either a meta.json or meta.js file.
39 *
40 * @param {String} dir
41 * @return {Object}
42 */
43
44function getMetadata(dir) {
45 const json = path.join(dir, "meta.json");
46 const js = path.join(dir, "meta.js");
47 let opts = {};
48
49 if (exists(json)) {
50 opts = metadata.sync(json);
51 } else if (exists(js)) {
52 const req = require(path.resolve(js));
53 if (req !== Object(req)) {
54 throw new Error("meta.js needs to expose an object");
55 }
56 opts = req;
57 }
58
59 return opts;
60}
61
62/**
63 * Set the default value for a prompt question
64 *
65 * @param {Object} opts
66 * @param {String} key
67 * @param {String} val
68 */
69
70function setDefault(opts, key, val) {
71 if (opts.schema) {
72 opts.prompts = opts.schema;
73 delete opts.schema;
74 }
75 const prompts = opts.prompts || (opts.prompts = {});
76 global['talentui_info'][key] = val;
77 if (!prompts[key] || typeof prompts[key] !== "object") {
78 prompts[key] = {
79 type: "string",
80 default: val
81 };
82 } else {
83 prompts[key]["default"] = val;
84 }
85}
86
87function setValidateName(opts) {
88 const name = opts.prompts.name;
89 const customValidate = name.validate;
90 name.validate = name => {
91 const its = validateName(name);
92 if (!its.validForNewPackages) {
93 const errors = (its.errors || []).concat(its.warnings || []);
94 return "Sorry, " + errors.join(" and ") + ".";
95 }
96 if (typeof customValidate === "function") return customValidate(name);
97 return true;
98 };
99}
\No newline at end of file