All files / lib/setup hook-script.js

100% Statements 40/40
100% Branches 10/10
100% Functions 5/5
100% Lines 39/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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    3x 3x 3x   3x     3x 84x 84x     65x   3x 66x   3x 45x 45x   45x   45x 40x 40x     45x   45x 1x 1x   44x 42x 42x     2x     45x     3x 21x 21x   21x 21x 1x 1x     20x 20x   20x 20x 19x   1x      
'use strict';
 
const fs = require('fs');
const path = require('path');
const debug = require('debug')('gint:hook-script');
 
const shebang = '#!/bin/sh';
 
 
const write = (filename, data) => {
  fs.writeFileSync(filename, data);
  fs.chmodSync(filename, parseInt('0755', 8));
};
 
const read = (filename) => fs.readFileSync(filename, 'utf-8');
 
const makeSnippet = (gintDir, hookName) =>
  `HOOK_PARAMS="$*" HOOK_NAME="${hookName}" node_modules/gint/bin/bootstrap`;
 
exports.sync = (gintDir, hooksDir, hookName) => {
  const hookPath = path.join(hooksDir, hookName);
  const snippet = makeSnippet(gintDir, hookName);
 
  debug('Syncing %s hook', hookName);
 
  if (!fs.existsSync(hookPath)) {
    debug('Not found, creating dummy file with shebang');
    write(hookPath, shebang);
  }
 
  const hookScript = read(hookPath);
 
  if (hookScript.indexOf('#gint 0.') !== -1) {
    debug('Old version of gint script found, migrating');
    write(hookPath, `${shebang}\n\n${snippet}\n`);
 
  } else if (hookScript.indexOf(snippet) === -1) {
    debug('Snippet isnt found, amending hook script');
    write(hookPath, `${hookScript}\n\n${snippet}\n`);
 
  } else {
    debug('Snippet found, nothing to do');
  }
 
  debug('Snippet found, all good');
};
 
exports.unsync = (gintDir, hooksDir, hookName) => {
  const hookPath = path.join(hooksDir, hookName);
  const snippet = makeSnippet(gintDir, hookName);
 
  debug('Unsyncing %s hook', hookName, hookPath);
  if (!fs.existsSync(hookPath)) {
    debug('Not found, nothing more to do');
    return;
  }
 
  let hookScript = read(hookPath);
  hookScript = hookScript.replace(`${snippet}`, '').trim() + '\n';
 
  debug('Sanitizing script');
  if (hookScript.trim() === shebang) {
    fs.unlinkSync(hookPath);
  } else {
    write(hookPath, hookScript);
  }
};