Skip to content

Commit

Permalink
refactor: adopt for npmlog and npm-registry-client
Browse files Browse the repository at this point in the history
  • Loading branch information
favoyang committed Aug 8, 2020
1 parent 4b4584c commit 09bd329
Show file tree
Hide file tree
Showing 21 changed files with 356 additions and 757 deletions.
6 changes: 3 additions & 3 deletions lib/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,15 +94,15 @@ program
const retCode = await login(options);
if (retCode) process.exit(retCode);
} catch (err) {
log.error(err.message);
log.error("", err.message);
process.exit(1);
}
});

// prompt for invalid command
program.on("command:*", function() {
log.error(`invalid command: ${program.args.join(" ")}
see --help for a list of available commands`);
log.warn("", `unknown command: ${program.args.join(" ")}`);
log.warn("", "see --help for a list of available commands");
process.exit(1);
});

Expand Down
23 changes: 23 additions & 0 deletions lib/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const { promisify } = require("util");
const RegClient = require("npm-registry-client");

const { log } = require("./logger");

/**
* Return npm client
*/
const getNpmClient = function() {
// create client
const client = new RegClient({ log });
return {
// The instance of raw npm client
rawClient: client,
// Promisified methods
get: promisify(client.get.bind(client)),
adduser: promisify(client.adduser.bind(client))
};
};

module.exports = {
getNpmClient
};
19 changes: 11 additions & 8 deletions lib/cmd-add.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
const _ = require("lodash");
const { log } = require("./logger");
const url = require("url");
const {
Expand Down Expand Up @@ -26,7 +25,7 @@ const add = async function(pkgs, options) {
};
// print manifest notice
if (result.dirty)
log.info("manifest updated, please open unity project to apply changes");
log.notice("", "please open Unity project to apply changes");
return result.code;
};

Expand All @@ -52,16 +51,20 @@ const _add = async function({ pkg, testables }) {
if (pkgInfo) useUpstream = true;
}
if (!pkgInfo) {
log.error(`package not found: ${name}`);
log.error("404", `package not found: ${name}`);
return { code: 1, dirty };
}
// verify version
const versions = Object.keys(pkgInfo.versions);
// eslint-disable-next-line require-atomic-updates
if (!version || version == "latest") version = getLatestVersion(pkgInfo);
if (versions.filter(x => x == version).length <= 0) {
log.info(`version ${version} is not a valid choice of:`);
log.info(`${versions.reverse().join(", ")}`);
log.warn(
"404",
`version ${version} is not a valid choice of: ${versions
.reverse()
.join(", ")}`
);
return { code: 1, dirty };
}
// pkgsInScope
Expand Down Expand Up @@ -89,15 +92,15 @@ const _add = async function({ pkg, testables }) {
manifest.dependencies[name] = version;
if (!oldVersion) {
// Log the added package
log.info(`added: ${name}@${version}`);
log.notice("manifest", `added ${name}@${version}`);
dirty = true;
} else if (oldVersion != version) {
// Log the modified package version
log.info(`modified: ${name} ${oldVersion} => ${version}`);
log.notice("manifest", `modified ${name} ${oldVersion} => ${version}`);
dirty = true;
} else {
// Log the existed package
log.info(`existed: ${name}@${version}`);
log.notice("manifest", `existed ${name}@${version}`);
}
if (!useUpstream) {
// add to scopedRegistries
Expand Down
2 changes: 1 addition & 1 deletion lib/cmd-deps.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const _deps = async function({ name, version, deep }) {
const results = await fetchPackageDependencies({ name, version, deep });
results
.filter(x => !x.self)
.forEach(x => log.info(`- ${x.name}@${x.version}`));
.forEach(x => log.notice("dependency", `${x.name}@${x.version}`));
};

module.exports = deps;
26 changes: 12 additions & 14 deletions lib/cmd-login.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@ const path = require("path");
const _ = require("lodash");
const mkdirp = require("mkdirp");
const promptly = require("promptly");
const { promisify } = require("util");
const isWsl = require("is-wsl");
const RegClient = require("npm-registry-client");
const TOML = require("@iarna/toml");

const { log, dummyLogger } = require("./logger");
const { getNpmClient } = require("./client");
const { log } = require("./logger");
const { parseEnv } = require("./core");
const { execute } = require("./utils/process");

Expand Down Expand Up @@ -41,7 +40,7 @@ const login = async function(options) {
});
if (result.code == 1) return result.code;
if (!result.token) {
log.error("can not find npm token from server response");
log.error("auth", "can not find token from server response");
return 1;
}
token = result.token;
Expand All @@ -68,27 +67,26 @@ const login = async function(options) {
* @param {*} param0
*/
const npmLogin = async function({ username, password, email, registry }) {
const client = new RegClient({ log: dummyLogger });
const adduserAsync = promisify(client.adduser.bind(client));
const client = getNpmClient();
try {
const data = await adduserAsync(registry, {
const data = await client.adduser(registry, {
auth: {
username,
password,
email
}
});
if (_.isString(data.ok)) log.info(data.ok);
else if (data.ok) log.info(`you are authenticated as '${username}'`);
else if (data.ok) log.info(`token: '${username}'`);
if (_.isString(data.ok)) log.notice("auth", data.ok);
else if (data.ok)
log.notice("auth", `you are authenticated as '${username}'`);
const token = data.token;
return { code: 0, token };
} catch (err) {
if (err.statusCode == 401 || err.code == "EAUTHUNKNOWN") {
log.warn("Incorrect username or password");
log.warn("401", "Incorrect username or password");
return { code: 1 };
} else {
log.error(err.message);
log.error(err.statusCode ? err.statusCode.toString() : "", err.message);
return { code: 1 };
}
}
Expand All @@ -109,7 +107,7 @@ const writeNpmToken = async function({ registry, token }) {
const lines = generateNpmrcLines(content, registry, token);
const newContent = lines.join("\n") + "\n";
fs.writeFileSync(configPath, newContent);
log.info(`saved to npm config: ${configPath}`);
log.notice("config", `saved to npm config: ${configPath}`);
};

/**
Expand Down Expand Up @@ -204,7 +202,7 @@ const writeUnityToken = async function({
// Write config file
const newContent = TOML.stringify(config);
fs.writeFileSync(configPath, newContent, "utf8");
log.info("saved to unity config: " + configPath);
log.notice("config", "saved to unity config: " + configPath);
};

/**
Expand Down
8 changes: 4 additions & 4 deletions lib/cmd-remove.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const remove = async function(pkgs, options) {
};
// print manifest notice
if (result.dirty)
log.info("manifest updated, please open unity project to apply changes");
log.notice("", "please open Unity project to apply changes");
return result.code;
};

Expand All @@ -30,7 +30,7 @@ const _remove = async function(pkg) {
// parse name
let { name, version } = parseName(pkg);
if (version) {
log.error("command doesn't support name@version, using name instead");
log.warn("", `please replace '${name}@${version}' with '${name}'`);
return { code: 1, dirty };
}
// load manifest
Expand All @@ -42,7 +42,7 @@ const _remove = async function(pkg) {
if (manifest.dependencies) {
version = manifest.dependencies[name];
if (version) {
log.info(`removed: ${name}@${version}`);
log.notice("manifest", `removed ${name}@${version}`);
delete manifest.dependencies[name];
dirty = true;
} else pkgsNotFound.push(pkg);
Expand Down Expand Up @@ -72,7 +72,7 @@ const _remove = async function(pkg) {
if (!saveManifest(manifest)) return { code: 1, dirty };
}
if (pkgsNotFound.length) {
log.error(`package not found: ${pkgsNotFound.join(", ")}`);
log.error("404", `package not found: ${pkgsNotFound.join(", ")}`);
return { code: 1, dirty };
}
return { code: 0, dirty };
Expand Down
37 changes: 19 additions & 18 deletions lib/cmd-search.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ const searchEndpoint = async function(keyword, registry) {
if (!registry) registry = env.registry;
let serverUrl = `${registry}/-/v1/search?text=${keyword}&size=20&from=0&quality=0.65&popularity=0.98&maintenance=0.5`;
try {
log.debug(`http get ${serverUrl}`);
log.http("request", `GET ${serverUrl}`);
const response = await httpGet(serverUrl).accept("json");
response.body = JSON.parse(response.text);
log.debug(`status ${response.status}`);
log.debug(response.body);
log.http(`${response.status}`, serverUrl);
log.verbose("response", response.body);
const objects = response.body.objects || [];
return objects.map(x => {
let pkg = x.package;
Expand All @@ -29,16 +29,15 @@ const searchEndpoint = async function(keyword, registry) {
pkg.time && pkg.time.modified ? pkg.time.modified.split("T")[0] : "";
let keywords = (pkg.keywords || []).join(", ");
let item = [name, version, author, date, keywords];
log.debug(item);
return item;
});
} catch (err) {
if (err.response && err.response.status)
log.debug(`status ${err.response.status}`);
log.http(`${err.response.status}`, serverUrl);
if (isConnectionError(err))
log.error(`can not reach to registry ${registry}`);
else if (!is404Error(err)) log.error(err.message);
log.warn("fast search endpoint is not available, using old search.");
log.http("request", `can not reach to ${serverUrl}`);
else if (!is404Error(err)) log.error("", err.message);
log.warn("", "fast search endpoint is not available, using old search.");
}
};

Expand All @@ -50,17 +49,20 @@ const searchOld = async function(keyword) {
cacheKey = cacheKey + ".json";
let cached = cache[cacheKey] || {};
let cachedLen = (cached.objects || []).length;
log.debug(`cache has ${cachedLen} package(s), updated at ${cached._updated}`);
log.verbose(
"cache",
`has ${cachedLen} package(s), updated at ${cached._updated}`
);
// all endpoint
let serverUrl = cached._updated
? `${env.registry}/-/all/since?stale=update_after&startkey=${cached._updated}`
: `${env.registry}/-/all`;
try {
log.debug(`http get ${serverUrl}`);
log.http("request", `GET ${serverUrl}`);
const response = await httpGet(serverUrl).accept("json");
response.body = JSON.parse(response.text);
log.debug(`status ${response.status}`);
log.debug(response.body);
log.http(`${response.status}`, serverUrl);
log.http("response", response.body);
let objects = [];
if (response.body) {
// resposne.body is an array of objects
Expand Down Expand Up @@ -96,10 +98,10 @@ const searchOld = async function(keyword) {
);
} catch (err) {
if (err.response && err.response.status)
log.debug(`status ${err.response.status}`);
log.http(`${err.response.status}`, serverUrl);
if (isConnectionError(err))
log.error(`can not reach to registry ${env.registry}`);
else if (!is404Error(err)) log.error(err.message);
log.http("request", `can not reach to ${serverUrl}`);
else if (!is404Error(err)) log.error("", err.message);
}
};

Expand All @@ -114,7 +116,6 @@ const getTable = function() {
module.exports = async function(keyword, options) {
// parse env
if (!parseEnv(options, { checkPath: false })) return 1;
log.debug(`keyword: ${keyword}`);
let table = getTable();
// search endpoint
let results = await searchEndpoint(keyword);
Expand All @@ -130,7 +131,7 @@ module.exports = async function(keyword, options) {
// }
if (results && results.length) {
results.forEach(x => table.push(x.slice(0, -1)));
log.info(table.toString());
} else log.info(`No matches found for "${keyword}"`);
console.log(table.toString());
} else log.notice("", `No matches found for "${keyword}"`);
return 0;
};
42 changes: 20 additions & 22 deletions lib/cmd-view.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ const view = async function(pkg, options) {
// parse name
let { name, version } = parseName(pkg);
if (version) {
log.error("command doesn't support name@version, using name instead");
log.warn("", `please replace '${name}@${version}' with '${name}'`);
return 1;
}
// verify name
let pkgInfo = await fetchPackageInfo(name);
if (!pkgInfo && env.upstream)
pkgInfo = await fetchPackageInfo(name, env.upstreamRegistry);
if (!pkgInfo) {
log.error(`package not found: ${name}`);
log.error("404", `package not found: ${name}`);
return 1;
}
// print info
Expand All @@ -30,8 +30,7 @@ const view = async function(pkg, options) {
};

const printInfo = function(pkg) {
// log.info(pkg);
log.info();
console.log();
const versionCount = Object.keys(pkg.versions).length;
const ver = getLatestVersion(pkg);
const verInfo = pkg.versions[ver];
Expand All @@ -44,33 +43,32 @@ const printInfo = function(pkg) {
const dependencies = verInfo.dependencies;
const time = (pkg.time.modified || "").split("T")[0];

log.info(`${pkg.name}@${ver} | ${license} | versions: ${versionCount}`);
log.info();
if (displayName) log.info(`display name: ${displayName}`);
if (description) log.info(`description: ${description}`);
if (description && description.includes("\n")) log.info();
if (homepage) log.info(`homepage: ${homepage}`);
if (keywords) log.info(`keywords: ${keywords.join(", ")}`);
console.log(`${pkg.name}@${ver} | ${license} | versions: ${versionCount}`);
console.log();
if (displayName) console.log(`display name: ${displayName}`);
if (description) console.log(`description: ${description}`);
if (description && description.includes("\n")) console.log();
if (homepage) console.log(`homepage: ${homepage}`);
if (keywords) console.log(`keywords: ${keywords.join(", ")}`);

if (dist) {
log.info();
log.info("dist");
log.info(`.tarball: ${dist.tarball}`);
if (dist.shasum) log.info(`.shasum: ${dist.shasum}`);
if (dist.integrity) log.info(`.integrity: ${dist.integrity}`);
console.log();
console.log("dist");
console.log(`.tarball: ${dist.tarball}`);
if (dist.shasum) console.log(`.shasum: ${dist.shasum}`);
if (dist.integrity) console.log(`.integrity: ${dist.integrity}`);
}

if (dependencies && Object.keys(dependencies).length > 0) {
log.info();
log.info("dependencies");
console.log();
console.log("dependencies");
Object.keys(dependencies)
.sort()
.forEach(n => log.info(`${n} ${dependencies[n]}`));
// log.info(dependencies);
.forEach(n => console.log(`${n} ${dependencies[n]}`));
}

log.info();
log.info(`published at ${time}`);
console.log();
console.log(`published at ${time}`);
};

module.exports = view;
Loading

0 comments on commit 09bd329

Please sign in to comment.