From 9c322a5af36fa1de0c3cdac89ca2754986c9526f Mon Sep 17 00:00:00 2001 From: Dragory Date: Tue, 13 Mar 2018 07:59:27 +0200 Subject: [PATCH] Add !version command --- src/main.js | 2 ++ src/modules/version.js | 47 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 src/modules/version.js diff --git a/src/main.js b/src/main.js index 0ba2f56..a8e7875 100644 --- a/src/main.js +++ b/src/main.js @@ -17,6 +17,7 @@ const suspend = require('./modules/suspend'); const webserver = require('./modules/webserver'); const greeting = require('./modules/greeting'); const typingProxy = require('./modules/typingProxy'); +const version = require('./modules/version'); const attachments = require("./data/attachments"); const {ACCIDENTAL_THREAD_MESSAGES} = require('./data/constants'); @@ -167,6 +168,7 @@ module.exports = { await greeting(bot); await webserver(bot); await typingProxy(bot); + await version(bot); // Connect to Discord console.log('Connecting to Discord...'); diff --git a/src/modules/version.js b/src/modules/version.js new file mode 100644 index 0000000..b2b6fcb --- /dev/null +++ b/src/modules/version.js @@ -0,0 +1,47 @@ +const path = require('path'); +const fs = require('fs'); +const {promisify} = require('util'); +const utils = require("../utils"); +const threadUtils = require("../threadUtils"); + +const access = promisify(fs.access); +const readFile = promisify(fs.readFile); + +const GIT_DIR = path.join(__dirname, '..', '..', '.git'); + +module.exports = bot => { + const addInboxServerCommand = (...args) => threadUtils.addInboxServerCommand(bot, ...args); + + addInboxServerCommand('version', async (msg, args, thread) => { + const packageJson = require('../../package.json'); + const packageVersion = packageJson.version; + + let response = `Modmail v${packageVersion}`; + + let isGit; + try { + await access(GIT_DIR); + isGit = true; + } catch (e) { + isGit = false; + } + + if (isGit) { + let commitHash; + const HEAD = await readFile(path.join(GIT_DIR, 'HEAD'), {encoding: 'utf8'}); + + if (HEAD.startsWith('ref:')) { + // Branch + const ref = HEAD.match(/^ref: (.*)$/m)[1]; + commitHash = (await readFile(path.join(GIT_DIR, ref), {encoding: 'utf8'})).trim(); + } else { + // Detached head + commitHash = HEAD.trim(); + } + + response += ` (${commitHash.slice(0, 7)})`; + } + + utils.postSystemMessageWithFallback(msg.channel, thread, response); + }); +};