<commit_before>#!/usr/bin/env node
'use strict';

const fs = require('fs');
const inquirer = require('inquirer');
const axios = require('axios');
const chalk = require('chalk');
const pathExists = require('path-exists');
const fileExists = require('file-exists');

const gitmojiData = require('gitmoji-data/data/gitmojis.json');
const GITMOJI_DATA_URL = 'https://raw.githubusercontent.com/gyran/gitmoji-data/master/data/gitmojis.json';

const errorHandler = error => {
  console.error(chalk.red(`🚨  ERROR: ${error}`));
  process.exit(1);
};

let questions = []

const getGitmojiList = () => {
  return axios.get(GITMOJI_DATA_URL)
    .then((res) => {
      if (res && res.data && res.data.gitmojis) {
        return res.data.gitmojis;
      }

      throw new Error('Could not find gitmojis at url');
    })
    .catch(() => {
      return gitmojiData.gitmojis;
    });
};

if (process.argv[2] === '--init') {
  const path = `${process.env.PWD}/.git/hooks`;

  if (!pathExists.sync('.git')) {
    errorHandler('The directory is not a git repository.')
  }

  if (fileExists.sync(`${path}/prepare-commit-msg`)) {
    errorHandler(`A prepare-commit hook already exists, please remove the hook (rm ${path}/prepare-commit-msg)
    or install gitmoji-commit-hook manually by adding the following content info ${path}/prepare-commit-msg: \nexec < /dev/tty\ngitmoji-commit-hook $1`);
  }

  fs.writeFile(`${path}/prepare-commit-msg`, '#!/bin/sh\nexec < /dev/tty\ngitmoji-commit-hook $1', writeError => {
    if (writeError) {
      errorHandler(writeError);
    } else {
      fs.chmod(`${path}/prepare-commit-msg`, '755', chmodError => {
        if (chmodError) {
          errorHandler(chmodError);
        } else {
          console.log(`${chalk.green('🎉  SUCCESS 🎉')}  gitmoji-commit-hook initialized with success.`);
        }
      });
    }
  });
} else {
  getGitmojiList()
    .then((gitmojis) => {
      questions.push({
        type: 'checkbox',
        name: 'emoji',
        message: 'Select emoji(s) for your commit',
        choices: gitmojis.map(gitmoji => {
          return {
            name: gitmoji.emoji + '  ' + gitmoji.description,
            value: gitmoji.emoji
          };
        })
      });

      if(/COMMIT_EDITMSG/g.test(process.argv[2])) {
        return inquirer.prompt(questions).then((answers) => {
          let commitMsg = fs.readFileSync(process.argv[2]);
          commitMsg = `${answers.emoji.join(' ')}  ${commitMsg}`;
          fs.writeFileSync(process.argv[2], commitMsg);

          process.exit(0);
        });
      }
    })
    .catch(err => {
      errorHandler(err);
    });
}<commit_msg>🎨,🚧,♻️,💥  Rewrite code to be more testable<commit_after>#!/usr/bin/env node
'use strict';

const fs = require('fs');
const { promisify } = require('util');
const inquirer = require('inquirer');
const axios = require('axios');
const chalk = require('chalk');
const pathExists = require('path-exists');
const fileExists = require('file-exists');

const gitHookPath = `${process.env.PWD}/.git/hooks`;

const writeFile = promisify(fs.writeFile)
const readFile = promisify(fs.readFile)
const chmod = promisify(fs.chmod)

const errorHandler = error => {
  console.error(chalk.red(`🚨  ERROR: ${error}`));
  process.exit(1);
};

const getGitmojiList = () => {
  return axios.get(GITMOJI_DATA_URL)
    .then((res) => {
      if (res && res.data && res.data.gitmojis) {
        return res.data.gitmojis;
      }

      throw new Error('Could not find gitmojis at url');
    })
    .catch(() => {
      return gitmojiData.gitmojis;
    });
};

function assertGitRepository() {
  return pathExists('.git').then(exists => (
    exists ? null : Promise.reject(new Error('The directory is not a git repository.'))
  ))
}

function assertNoPrepareCommitHook() {
  return fileExists(`${gitHookPath}/prepare-commit-msg`).then(exists => {
    if (exists) {
      return Promise.reject(new Error(`A prepare-commit hook already exists, please remove the hook (rm ${path}/prepare-commit-msg)
      or install gitmoji-commit-hook manually by adding the following content info ${path}/prepare-commit-msg: \nexec < /dev/tty\ngitmoji-commit-hook $1`))
    } else {
      return null
    }
  })
}

function initProject() {
  return assertGitRepository()
    .then(assertNoPrepareCommitHook)
    .then(() => writeFile(`${path}/prepare-commit-msg`, '#!/bin/sh\nexec < /dev/tty\ngitmoji-commit-hook $1'))
    .then(() => chmod(`${path}/prepare-commit-msg`, '755'))
}

function prependMessageToFile(filepath) {
  return message => readFile(filepath)
    .then(fileContent => `${message}  ${commitMsg}`)
    .than(fileContent => writeFile(filepath, fileContent))
}

function printInitSuccess() {
  console.log(`${chalk.green('🎉  SUCCESS 🎉')}  gitmoji-commit-hook initialized with success.`)
}

function run() {
  if (process.argv[2] === '--init') {
    initProject().then(printInitSuccess).catch(errorHandler)
  } else if (/COMMIT_EDITMSG/g.test(process.argv[2])) {
    getGitmojiList()
      .then(gitmojis => ([{
        type: 'checkbox',
        name: 'emoji',
        message: 'Select emoji(s) for your commit',
        choices: gitmojis.map(gitmoji => ({
          name: gitmoji.emoji + '  ' + gitmoji.description,
          value: gitmoji.emoji
        }))
      }]))
      .then(inquirer.prompt)
      .than(answers => answers.emoji.join(' '))
      .than(prependMessageToFile(process.argv[2]))
      .catch(errorHandler)
  }
}

run()
{'fraction_non_alphanumeric': 0.17141282381039868, 'fraction_numerical': 0.0036744442403086534, 'mean_word_length': 3.1399239543726236, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 27, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2699166', 'n_tokens_mistral': 1877, 'n_tokens_neox': 1855, 'n_words': 349}