All files / src gitmoji.js

26.55% Statements 30/113
26.19% Branches 11/42
8.7% Functions 4/46
28.3% Lines 30/106
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 2251x 1x 1x 1x 1x 1x 1x   1x 1x 1x   1x           1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                           2x 2x     2x     2x 2x 2x   2x       2x         2x       2x                         3x 3x                                                                                                       1x  
const chalk = require('chalk')
const execa = require('execa')
const fs = require('fs')
const inquirer = require('inquirer')
const parentDirs = require('parent-dirs')
const path = require('path')
const pathExists = require('path-exists')
 
const config = require('./config')
const prompts = require('./prompts')
const constants = require('./constants')
 
inquirer.registerPrompt(
  'autocomplete', require('inquirer-autocomplete-prompt')
)
 
class GitmojiCli {
  constructor (gitmojiApiClient, gitmojis) {
    this._gitmojiApiClient = gitmojiApiClient
    this._gitmojis = gitmojis
    Iif (config.getAutoAdd() === undefined) config.setAutoAdd(true)
    Iif (!config.getIssueFormat()) config.setIssueFormat(constants.GITHUB)
    Iif (!config.getEmojiFormat()) config.setEmojiFormat(constants.CODE)
    Iif (config.getSignedCommit() === undefined) config.setSignedCommit(true)
  }
 
  config () {
    inquirer.prompt(prompts.config).then(answers => {
      config.setAutoAdd(answers[constants.AUTO_ADD])
      config.setIssueFormat(answers[constants.ISSUE_FORMAT])
      config.setEmojiFormat(answers[constants.EMOJI_FORMAT])
      config.setSignedCommit(answers[constants.SIGNED_COMMIT])
    })
  }
 
  init () {
    if (!this._isAGitRepo()) {
      return this._errorMessage('Not a git repository - @init')
    }
 
    execa('git', ['rev-parse', '--absolute-git-dir'])
      .then(result => {
        fs.writeFile(
          result.stdout.trim() + constants.HOOK_PATH,
          constants.HOOK_FILE_CONTENTS,
          { mode: constants.HOOK_PERMISSIONS },
          (err) => {
            if (err) this._errorMessage(err)
            console.log(
              `${chalk.yellow('gitmoji')} commit hook created successfully.`
            )
          }
        )
      })
      .catch(err => {
        return this._errorMessage(err)
      })
  }
 
  remove () {
    if (!this._isAGitRepo()) {
      return this._errorMessage('Couldn\'t remove hook, not a git repository')
    }
 
    execa('git', ['rev-parse', '--absolute-git-dir'])
      .then(result => {
        fs.unlink(result.stdout.trim() + constants.HOOK_PATH, (err) => {
          if (err) return this._errorMessage(err)
          return console.log(
            `${chalk.yellow('gitmoji')} commit hook unlinked successfully.`
          )
        })
      })
      .catch(err => {
        return this._errorMessage(err)
      })
  }
 
  list () {
    return this._fetchEmojis()
      .then(gitmojis => this._parseGitmojis(gitmojis))
      .catch(err => this._errorMessage(`gitmoji list not found - ${err.code}`))
  }
 
  search (query) {
    return this._fetchEmojis()
      .then((gitmojis) => gitmojis.filter((gitmoji) => {
        const emoji = gitmoji.name.concat(gitmoji.description).toLowerCase()
        return (emoji.indexOf(query.toLowerCase()) !== -1)
      }))
      .then((gitmojisFiltered) => this._parseGitmojis(gitmojisFiltered))
      .catch((err) => this._errorMessage(err.code))
  }
 
  ask (mode) {
    if (!this._isAGitRepo()) {
      return this._errorMessage('This directory is not a git repository.')
    }
 
    return this._fetchEmojis()
      .then((gitmojis) => prompts.gitmoji(gitmojis))
      .then((questions) => {
        inquirer.prompt(questions).then((answers) => {
          if (mode === constants.HOOK_MODE) this._hook(answers)
          return this._commit(answers)
        })
      })
      .catch(err => this._errorMessage(err.code))
  }
 
  updateCache () {
    this._fetchRemoteEmojis()
      .then(emojis => this._createCache(this._getCachePath(), emojis))
  }
 
  _errorMessage (message) {
    console.error(chalk.red(`ERROR: ${message}`))
  }
 
  _hook (answers) {
    const title = `${answers.gitmoji} ${answers.title}`
    const reference = (answers.reference) ? `#${answers.reference}` : ''
    const body = `${answers.message} ${reference}`
 
    try {
      fs.writeFileSync(process.argv[3], `${title}\n\n${body}`)
    } catch (error) {
      return this._errorMessage(error)
    }
    process.exit(0)
  }
 
  _commit (answers) {
    const title = `${answers.gitmoji} ${answers.title}`
    const prefixReference = config.getIssueFormat() === constants.GITHUB
      ? '#'
      : ''
    const reference = (answers.reference)
      ? `${prefixReference}${answers.reference}`
      : ''
    const signed = config.getSignedCommit() ? '-S' : ''
    const body = `${answers.message} ${reference}`
    const commit = `git commit ${signed} -m "${title}" -m "${body}"`
 
    Iif (!this._isAGitRepo()) {
      return this._errorMessage('Not a git repository')
    }
 
    Iif (config.getAutoAdd()) {
      execa.stdout('git', ['add', '.'])
        .then((res) => console.log(chalk.blue(res)))
        .catch((err) => this._errorMessage(err.stderr))
    }
    execa.shell(commit)
      .then((res) => console.log(chalk.blue(res.stdout)))
      .catch((err) => this._errorMessage(err.stderr ? err.stderr : err.stdout))
 
    return commit
  }
 
  _parseGitmojis (gitmojis) {
    return gitmojis.map(gitmoji => {
      const emoji = gitmoji.emoji
      const code = gitmoji.code
      const description = gitmoji.description
      return console.log(`${emoji} - ${chalk.blue(code)} - ${description}`)
    })
  }
 
  _isAGitRepo () {
    return parentDirs(process.cwd())
      .some((directory) => pathExists.sync(path.resolve(directory, '.git')))
  }
 
  _getCachePath () {
    const home = process.env.HOME || process.env.USERPROFILE
    return path.join(home, '.gitmoji', 'gitmojis.json')
  }
 
  _cacheAvailable (cachePath) {
    return pathExists.sync(cachePath)
  }
 
  _createCache (cachePath, emojis) {
    const cacheDir = path.dirname(cachePath)
 
    if (emojis !== undefined) {
      if (!pathExists.sync(cacheDir)) {
        fs.mkdirSync(cacheDir)
      }
      fs.writeFileSync(cachePath, JSON.stringify(emojis))
    }
  }
 
  _fetchRemoteEmojis () {
    return this._gitmojiApiClient.request({
      method: 'GET',
      url: '/src/data/gitmojis.json'
    }).then((res) => {
      console.log(`${chalk.yellow('Gitmojis')} updated successfully!`)
      return res.data.gitmojis
    })
      .catch((error) =>
        this._errorMessage(`Network connection not found - ${error.code}`)
      )
  }
 
  _fetchCachedEmojis (cachePath) {
    return Promise.resolve(JSON.parse(fs.readFileSync(cachePath)))
  }
 
  _fetchEmojis () {
    const cachePath = this._getCachePath()
    if (this._cacheAvailable(cachePath)) {
      return this._fetchCachedEmojis(cachePath)
    }
    return this._fetchRemoteEmojis().then((emojis) => {
      this._createCache(cachePath, emojis)
      return emojis
    })
  }
}
 
module.exports = GitmojiCli