#! /usr/bin/env node
const spawn = require('child_process').spawn
const exec = require('child_process').exec

exec('hg branch', (error, stdout, stderr) => {
  if (error) throw (error)

  const COMMIT_MESSAGE = process.argv[process.argv.indexOf('-m') + 1]
  const JIRA_ISSUE_KEY = stdout.match(/\D{3,4}-\d{1,4}/)

  if (!COMMIT_MESSAGE) throw ('No commit message provided while it is required.\nUse the following terminal syntax when using hgco:\n"hgco -m \'your commit message goes here\'"')
  if (!JIRA_ISSUE_KEY) throw ('No JIRA issue key found on your current branch. Make sure your branch name contains a JIRA issue key.')

  const hgco = spawn('hg', ['commit', '-m', `${process.argv[process.argv.indexOf('-m') + 1]} [${JIRA_ISSUE_KEY}]`], {stdio: 'inherit'})

  process.stdout.on('data', (data) => {
    console.log(data)
  })

  process.stderr.on('data', (data) => {
    console.log(`Error: ${data}`)
  })

  hgco.on('close', () => {
    exec('hg log -l 1', (error, stdout, stderr) => {
      if (error) throw (error)
      console.log('\n' + stdout)
      if (require.main === module) process.exit()
    })
  })
})

@@ -169,23 +169,21 @@
 ) throw 
-(
 error
-)
 %0A%0A  cons
@@ -325,24 +325,79 @@
 _MESSAGE
-) throw 
+ %7C%7C !JIRA_ISSUE_KEY) %7B%0A    if (!COMMIT_MESSAGE) throw new Error
 ('No com
@@ -538,16 +538,18 @@
 re%5C'%22')%0A
+  
   if (!J
@@ -569,16 +569,25 @@
 ) throw 
+new Error
 ('No JIR
@@ -684,17 +684,29 @@
  key.')%0A
-%0A
+  %7D else %7B%0A  
   const 
@@ -748,52 +748,22 @@
  %60$%7B
-process.argv%5Bprocess.argv.indexOf('-m') + 1%5D
+COMMIT_MESSAGE
 %7D %5B$
@@ -800,24 +800,26 @@
 inherit'%7D)%0A%0A
+  
   process.st
@@ -842,32 +842,34 @@
 (data) =%3E %7B%0A    
+ 
+ 
 console.log(data
@@ -870,22 +870,26 @@
 g(data)%0A
+  
   %7D)%0A%0A
+  
   proces
@@ -920,24 +920,26 @@
 a) =%3E %7B%0A    
+  
 console.log(
@@ -956,24 +956,26 @@
 data%7D%60)%0A
+  
   %7D)%0A%0A  
 hgco.on(
@@ -966,16 +966,18 @@
   %7D)%0A%0A  
+ 
+ 
 hgco.on(
@@ -989,24 +989,26 @@
 e', () =%3E %7B%0A
+  
     exec('hg
@@ -1044,24 +1044,26 @@
 tderr) =%3E %7B%0A
+  
       if (er
@@ -1077,16 +1077,16 @@
 row 
-(
 error
-)
 %0A
+  
     
@@ -1116,24 +1116,26 @@
 dout)%0A      
+ 
+ 
 if (require.
@@ -1166,16 +1166,25 @@
 .exit()%0A
+      %7D)%0A
     %7D)%0A 
@@ -1185,13 +1185,12 @@
   %7D)%0A  %7D
-)
 %0A%7D)%0A

refactor index.js