From c73efcb7279922e8d48fa95f857ce81792252a63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C4=99drzej=20Lewandowski?= Date: Thu, 25 Oct 2018 22:40:41 +0200 Subject: [PATCH] fix: update cli for new version of core --- src/actions/DaemonAction.ts | 2 +- src/actions/DownloadRulesAction.ts | 4 +- src/actions/InitAction.ts | 4 +- src/actions/SendVoteorderAction.ts | 8 +-- src/actions/UploadRulesAction.ts | 8 +-- src/app.ts | 6 +- src/config/Config.ts | 4 +- src/log.ts | 85 +++++-------------------- src/util/PrioritizedFileObjectLoader.ts | 16 ++--- 9 files changed, 43 insertions(+), 94 deletions(-) diff --git a/src/actions/DaemonAction.ts b/src/actions/DaemonAction.ts index 944a94f..d2c0671 100644 --- a/src/actions/DaemonAction.ts +++ b/src/actions/DaemonAction.ts @@ -17,7 +17,7 @@ export class DaemonAction { return Promise.resolve() .then(() => ConfigLoader.askForCredentialsIfEmpty(config)) .then(() => { - api = new DirectBlockchainApi(config.postingWif); + api = new DirectBlockchainApi(Wise.constructDefaultProtocol(), config.postingWif); if (config.disableSend) api.setSendEnabled(false); delegatorWise = new Wise(config.username, api); }) diff --git a/src/actions/DownloadRulesAction.ts b/src/actions/DownloadRulesAction.ts index f100446..e162754 100644 --- a/src/actions/DownloadRulesAction.ts +++ b/src/actions/DownloadRulesAction.ts @@ -4,7 +4,7 @@ import * as _ from "lodash"; import * as prompt from "prompt"; import * as yaml from "js-yaml"; -import { Log } from "../log"; const log = Log.getLogger(); +import { Log } from "../log"; import { ConfigLoader, Config, ConfigLoadedFromFile } from "../config/Config"; import { Wise, DirectBlockchainApi, SetRulesForVoter, SteemOperationNumber, SetRules, EffectuatedSetRules } from "steem-wise-core"; import { StaticConfig } from "../config/StaticConfig"; @@ -60,7 +60,7 @@ export class DownloadRulesAction { } private static downloadRules(username: string): Promise { - const delegatorWise = new Wise(username, new DirectBlockchainApi()); + const delegatorWise = new Wise(username, new DirectBlockchainApi(Wise.constructDefaultProtocol())); return delegatorWise.downloadAllRulesets(username); } diff --git a/src/actions/InitAction.ts b/src/actions/InitAction.ts index f339ca5..42597a6 100644 --- a/src/actions/InitAction.ts +++ b/src/actions/InitAction.ts @@ -6,7 +6,7 @@ import * as yaml from "js-yaml"; import { Wise, DirectBlockchainApi, SendVoteorder, SteemOperationNumber } from "steem-wise-core"; -import { Log } from "../log"; const log = Log.getLogger(); +import { Log } from "../log"; import { Config } from "../config/Config"; import { StaticConfig } from "../config/StaticConfig"; import { DefaultRules } from "../config/DefaultRules"; @@ -116,7 +116,7 @@ export class InitAction { if (sinceBlock === undefined) { console.log("Fetching HEAD block number..."); - sinceBlock = (await new DirectBlockchainApi().getDynamicGlobalProperties()).head_block_number; + sinceBlock = (await new DirectBlockchainApi(Wise.constructDefaultProtocol()).getDynamicGlobalProperties()).head_block_number; console.log("HEAB block number is " + sinceBlock); } diff --git a/src/actions/SendVoteorderAction.ts b/src/actions/SendVoteorderAction.ts index 9e54b7b..8a35604 100644 --- a/src/actions/SendVoteorderAction.ts +++ b/src/actions/SendVoteorderAction.ts @@ -3,7 +3,7 @@ import * as _ from "lodash"; import { Wise, DirectBlockchainApi, SendVoteorder, SteemOperationNumber } from "steem-wise-core"; -import { Log } from "../log"; const log = Log.getLogger(); +import { Log } from "../log"; import { ConfigLoader, Config } from "../config/Config"; import { PrioritizedFileObjectLoader } from "../util/PrioritizedFileObjectLoader"; @@ -29,7 +29,7 @@ export class SendVoteorderAction { return Promise.resolve(data); // succes parsing inline json } catch (error) { - log.debug("Failed to parse " + voteordetIn + " as inline JSON. Proceeding to loading files. " + voteorderPaths + " will be loaded as file."); + Log.log().debug("Failed to parse " + voteordetIn + " as inline JSON. Proceeding to loading files. " + voteorderPaths + " will be loaded as file."); voteorderPaths.unshift(voteordetIn); } } @@ -49,11 +49,11 @@ export class SendVoteorderAction { console.log(JSON.stringify(voteorder)); if (!voteorder.delegator || voteorder.delegator.length == 0) throw new Error("You must specify delegator in voteorder JSON"); - const api: DirectBlockchainApi = new DirectBlockchainApi(config.postingWif); + const api: DirectBlockchainApi = new DirectBlockchainApi(Wise.constructDefaultProtocol(), config.postingWif); if (config.disableSend) api.setSendEnabled(false); const wise = new Wise(config.username, api); - return wise.sendVoteorder(voteorder.delegator, voteorder, undefined, (msg: string, proggress: number) => { + return wise.sendVoteorder(voteorder.delegator, voteorder, (msg: string, proggress: number) => { console.log("[voteorder sending][" + Math.floor(proggress * 100) + "%]: " + msg); }); }); diff --git a/src/actions/UploadRulesAction.ts b/src/actions/UploadRulesAction.ts index 84ebf4a..aa1cec1 100644 --- a/src/actions/UploadRulesAction.ts +++ b/src/actions/UploadRulesAction.ts @@ -1,7 +1,7 @@ import * as path from "path"; import * as _ from "lodash"; -import { Log } from "../log"; const log = Log.getLogger(); +import { Log } from "../log"; import { ConfigLoader, Config, ConfigLoadedFromFile } from "../config/Config"; import { Wise, DirectBlockchainApi, SetRulesForVoter, SteemOperationNumber } from "steem-wise-core"; import { StaticConfig } from "../config/StaticConfig"; @@ -36,7 +36,7 @@ export class UploadRulesAction { return Promise.resolve(data); // succes parsing inline json } catch (error) { - log.debug("Failed to parse " + rulesIn + " as inline JSON. Proceeding to loading files. Adding " + rulesIn + " as top-priority file."); + Log.log().debug("Failed to parse " + rulesIn + " as inline JSON. Proceeding to loading files. Adding " + rulesIn + " as top-priority file."); rulesPaths.unshift(rulesIn); } } @@ -60,11 +60,11 @@ export class UploadRulesAction { if (!element.rulesets) return Promise.reject(new Error("Rulesets should be specified for each voter")); }); - const api: DirectBlockchainApi = new DirectBlockchainApi(config.postingWif); + const api: DirectBlockchainApi = new DirectBlockchainApi(Wise.constructDefaultProtocol(), config.postingWif); if (config.disableSend) api.setSendEnabled(false); const delegatorWise = new Wise(config.username, api); - return delegatorWise.uploadAllRulesets(newRules, undefined, (msg: string, proggress: number) => { + return delegatorWise.uploadAllRulesets(newRules, (msg: string, proggress: number) => { console.log("[syncing a rule][" + Math.floor(proggress * 100) + "%]: " + msg); }); }); diff --git a/src/app.ts b/src/app.ts index e831960..0b92d3a 100755 --- a/src/app.ts +++ b/src/app.ts @@ -10,7 +10,7 @@ import { DownloadRulesAction } from "./actions/DownloadRulesAction"; import { SendVoteorderAction } from "./actions/SendVoteorderAction"; import { DaemonAction } from "./actions/DaemonAction"; import { InitAction } from "./actions/InitAction"; -import { Log } from "./log"; const log = Log.getLogger(); +import { Log } from "./log"; import * as eastereggs from "./eastereggs"; /** @@ -19,7 +19,7 @@ import * as eastereggs from "./eastereggs"; let commandCorrect = false; const prepareAction = (program: program.Command, loadConfig: boolean = true): Promise => { commandCorrect = true; - Log.configureLoggers(program); + Log.log().initialize(!!program.debug, !!program.verbose); if (loadConfig) return ConfigLoader.loadConfig(program); else return Promise.resolve({ ...StaticConfig.DEFAULT_CONFIG, configFilePath: process.cwd() }); }; @@ -28,7 +28,7 @@ const actionDone = (msg: String) => { console.log(); }; const actionError = (error: Error) => { - Log.exception(error); + Log.log().exception(Log.level.error, error); console.log(); console.log("> We apologize for this error. Maybe this wise sentence will improve your mood: " + eastereggs.wisdomQuote()); process.exit(1); diff --git a/src/config/Config.ts b/src/config/Config.ts index 5c7c47e..ceece19 100644 --- a/src/config/Config.ts +++ b/src/config/Config.ts @@ -4,7 +4,7 @@ import * as _ from "lodash"; import * as Promise from "bluebird"; import * as prompt from "prompt"; -import { Log } from "../log"; const log = Log.getLogger(); +import { Log } from "../log"; import { StaticConfig } from "./StaticConfig"; import { PrioritizedFileObjectLoader } from "../util/PrioritizedFileObjectLoader"; @@ -63,7 +63,7 @@ export class ConfigLoader { }) .then(config => ConfigLoader.loadEnv(config)) .then(config => ConfigLoader.validateConfig(config)) - .then(config => { log.debug("Loaded config: " + JSON.stringify(config)); return config; }); + .then(config => { Log.log().debug("Loaded config: " + JSON.stringify(config)); return config; }); } private static loadEnv(config: ConfigLoadedFromFile): ConfigLoadedFromFile { diff --git a/src/log.ts b/src/log.ts index 2950176..294925b 100644 --- a/src/log.ts +++ b/src/log.ts @@ -1,78 +1,27 @@ -import * as winston from "winston"; -import * as program from "commander"; +import { AbstractLog } from "steem-wise-core"; -import { Log as SteemWiseCoreLog } from "steem-wise-core"; +export class Log extends AbstractLog { + private static INSTANCE: Log = new Log(); -export class Log { - public static configureLoggers(program: program.Command) { - const verboseOrDebug = !!program.debug || !!program.verbose; - // cli logger - Log.getLogger().add( - new winston.transports.Console({ - format: winston.format.combine( - winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }), - winston.format.printf(info => { - if (verboseOrDebug) { - return `${info.timestamp} [${info.level}]: ${info.message}`; - } - else { - return `${info.message}`; - } - }) - ), - handleExceptions: true, - timestamp: true, - } as object) - ); - Log.getLogger().level = "warn"; - - if (program.debug) { - console.log("Setting steem-wise-core log level to \"debug\""); - SteemWiseCoreLog.setLevel("debug"); - - console.log("Setting steem-wise-cli log level to \"debug\""); - Log.getLogger().level = "debug"; - } - else if (program.verbose) { - console.log("Setting steem-wise-core log level to \"info\""); - SteemWiseCoreLog.setLevel("info"); - - console.log("Setting steem-wise-cli log level to \"info\""); - Log.getLogger().level = "info"; - } - } - - public static setLevel(level: string) { - Log.getLogger().level = level; - } - - public static getLogger(): winston.Logger { - return (winston.loggers as any).get("steem-wise-cli"); - } - - public static cheapDebug(debugStringReturnerFn: () => string): void { - const logger = Log.getLogger(); - if (logger.levels[logger.level] >= logger.levels["debug"]) logger.debug(debugStringReturnerFn()); - } - - public static cheapInfo(infoStringReturnerFn: () => string): void { - const logger = Log.getLogger(); - if (logger.levels[logger.level] >= logger.levels["info"]) logger.debug(infoStringReturnerFn()); + private constructor() { + super("steem-wise-cli"); } - public static exception(error: Error, level: string = "error"): void { - const logger = Log.getLogger(); - logger.log(level, error.name + ": " + error.message - + (logger.levels[logger.level] >= logger.levels["info"] && error.stack ? "\n" + error.stack : "")); + public initialize(debug: boolean, verbose: boolean) { + super.init([ + (debug ? "debug" : undefined ), + (verbose ? "verbose" : undefined ), + process.env.WISE_CLI_LOG_LEVEL, + process.env.WISE_LOG_LEVEL, + "info" + ]); } - public static promiseResolveDebug(msgBeginning: string, result: T): T { - Log.cheapDebug(() => msgBeginning + JSON.stringify(result)); - return result; + public init() { + throw new Error("Instead of #init() please call #initialize(debug, verbose) which indirectly overrides init"); } - public static promiseRejectionDebug(msgBeginning: string, error: T): T { - Log.cheapDebug(() => msgBeginning + JSON.stringify(error)); - throw error; + public static log(): Log { + return Log.INSTANCE; } } \ No newline at end of file diff --git a/src/util/PrioritizedFileObjectLoader.ts b/src/util/PrioritizedFileObjectLoader.ts index 008f918..39bd5a1 100644 --- a/src/util/PrioritizedFileObjectLoader.ts +++ b/src/util/PrioritizedFileObjectLoader.ts @@ -2,7 +2,7 @@ import * as fs from "fs"; import * as _ from "lodash"; import * as yaml from "js-yaml"; -import { Log } from "../log"; const log = Log.getLogger(); +import { Log } from "../log"; export class PrioritizedFileObjectLoader { public static loadFromFiles(defaultObject: T, filePaths: string [], descriptionForWarnings: string): Promise<{ loadedObject: T, path: string | undefined }> { @@ -22,39 +22,39 @@ export class PrioritizedFileObjectLoader { for (let i = 0; i < filePaths.length; i++) { const filePath = filePaths[i]; if (fs.existsSync(filePath)) { - log.debug("Trying to read " + descriptionForWarnings + " from " + filePath); + Log.log().debug("Trying to read " + descriptionForWarnings + " from " + filePath); let fileContents: string; try { fileContents = fs.readFileSync(filePath, "utf8").toString(); } catch (error) { - log.debug("Could not read " + descriptionForWarnings + " file (" + filePath + "): " + error.message); + Log.log().debug("Could not read " + descriptionForWarnings + " file (" + filePath + "): " + error.message); continue; // continue to next file } // if continue was not called, try to load as JSON: try { const loadedObj = JSON.parse(fileContents) as T; - log.debug("Successfully parsed " + filePath + " as JSON"); + Log.log().debug("Successfully parsed " + filePath + " as JSON"); if (merge) return { loadedObject: _.merge({}, defaultObject, loadedObj), path: filePath }; else return { loadedObject: loadedObj, path: filePath }; } catch (error) { - log.debug("Failed to parse " + descriptionForWarnings + " (" + filePath + ") as JSON: " + error.message); + Log.log().debug("Failed to parse " + descriptionForWarnings + " (" + filePath + ") as JSON: " + error.message); } // try to load as YAML: try { const loadedObj = yaml.safeLoad(fileContents) as T; - log.debug("Successfully parsed " + filePath + " as YAML"); + Log.log().debug("Successfully parsed " + filePath + " as YAML"); if (merge) return { loadedObject: _.merge({}, defaultObject, loadedObj), path: filePath }; else return { loadedObject: loadedObj, path: filePath }; } catch (error) { - log.debug("Failed to parse " + descriptionForWarnings + " (" + filePath + ") as YAML: " + error.message); + Log.log().debug("Failed to parse " + descriptionForWarnings + " (" + filePath + ") as YAML: " + error.message); throw new Error("The " + descriptionForWarnings + " file " + filePath + " is malformed. Failed to parse it as JSON or YAML."); } } } - log.warn("No " + descriptionForWarnings + " was loaded"); + Log.log().warn("No " + descriptionForWarnings + " was loaded"); if (merge) return { loadedObject: defaultObject, path: undefined }; else return { loadedObject: undefined, path: undefined }; });