Skip to content

Commit

Permalink
fix: update cli for new version of core
Browse files Browse the repository at this point in the history
  • Loading branch information
Jblew committed Oct 25, 2018
1 parent f0d4edc commit c73efcb
Show file tree
Hide file tree
Showing 9 changed files with 43 additions and 94 deletions.
2 changes: 1 addition & 1 deletion src/actions/DaemonAction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
})
Expand Down
4 changes: 2 additions & 2 deletions src/actions/DownloadRulesAction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -60,7 +60,7 @@ export class DownloadRulesAction {
}

private static downloadRules(username: string): Promise<EffectuatedSetRules []> {
const delegatorWise = new Wise(username, new DirectBlockchainApi());
const delegatorWise = new Wise(username, new DirectBlockchainApi(Wise.constructDefaultProtocol()));
return delegatorWise.downloadAllRulesets(username);
}

Expand Down
4 changes: 2 additions & 2 deletions src/actions/InitAction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
}

Expand Down
8 changes: 4 additions & 4 deletions src/actions/SendVoteorderAction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -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);
}
}
Expand All @@ -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);
});
});
Expand Down
8 changes: 4 additions & 4 deletions src/actions/UploadRulesAction.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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);
}
}
Expand All @@ -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);
});
});
Expand Down
6 changes: 3 additions & 3 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

/**
Expand All @@ -19,7 +19,7 @@ import * as eastereggs from "./eastereggs";
let commandCorrect = false;
const prepareAction = (program: program.Command, loadConfig: boolean = true): Promise<ConfigLoadedFromFile> => {
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() });
};
Expand All @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions src/config/Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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 {
Expand Down
85 changes: 17 additions & 68 deletions src/log.ts
Original file line number Diff line number Diff line change
@@ -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<T>(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<T>(msgBeginning: string, error: T): T {
Log.cheapDebug(() => msgBeginning + JSON.stringify(error));
throw error;
public static log(): Log {
return Log.INSTANCE;
}
}
16 changes: 8 additions & 8 deletions src/util/PrioritizedFileObjectLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>(defaultObject: T, filePaths: string [], descriptionForWarnings: string): Promise<{ loadedObject: T, path: string | undefined }> {
Expand All @@ -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 };
});
Expand Down

0 comments on commit c73efcb

Please sign in to comment.