thelounge/src/helper.js

85 lines
1.8 KiB
JavaScript

"use strict";
const pkg = require("../package.json");
var _ = require("lodash");
var path = require("path");
var os = require("os");
var fs = require("fs");
var Helper = {
config: null,
expandHome: expandHome,
getUserConfigPath: getUserConfigPath,
getUserLogsPath: getUserLogsPath,
setHome: setHome,
getVersion: getVersion,
getGitCommit: getGitCommit,
};
module.exports = Helper;
Helper.config = require(path.resolve(path.join(
__dirname,
"..",
"defaults",
"config.js"
)));
function getVersion() {
const gitCommit = getGitCommit();
return gitCommit ? `source (${gitCommit})` : `v${pkg.version}`;
}
let _gitCommit;
function getGitCommit() {
if (_gitCommit !== undefined) {
return _gitCommit;
}
try {
_gitCommit = require("child_process")
.execSync("git rev-parse --short HEAD 2> /dev/null") // Returns hash of current commit
.toString()
.trim();
return _gitCommit;
} catch (e) {
// Not a git repository or git is not installed
_gitCommit = null;
return null;
}
}
function setHome(homePath) {
this.HOME = expandHome(homePath || "~/.lounge");
this.CONFIG_PATH = path.join(this.HOME, "config.js");
this.USERS_PATH = path.join(this.HOME, "users");
// Reload config from new home location
if (fs.existsSync(this.CONFIG_PATH)) {
var userConfig = require(this.CONFIG_PATH);
this.config = _.extend(this.config, userConfig);
}
}
function getUserConfigPath(name) {
return path.join(this.USERS_PATH, name + ".json");
}
function getUserLogsPath(name, network) {
return path.join(this.HOME, "logs", name, network);
}
function expandHome(shortenedPath) {
var home;
if (os.homedir) {
home = os.homedir();
}
if (!home) {
home = process.env.HOME || "";
}
home = home.replace("$", "$$$$");
return path.resolve(shortenedPath.replace(/^~($|\/|\\)/, home + "$1"));
}