<commit_before>'use strict'
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode')
const spawn = require('child_process').spawn
const fs = require('fs')
const path = require('path')

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed

function activate (context) {
  const outputChannel = vscode.window.createOutputChannel(vscode.workspace.getConfiguration('miramac.node').outputWindowName)
  let terminals = []
  let process
  let runningStatus = null

  // executes JS code with node
  let run = vscode.commands.registerCommand('extension.miramac.node.exec', function () {
    const config = vscode.workspace.getConfiguration('miramac.node')
    // test for running process
    if (runningStatus) {
      vscode.window.showErrorMessage('Process is already running!')
      return
    }

    let editor = vscode.window.activeTextEditor
    if (!editor) {
      return // No open text editor
    }
    if (editor._documentData._languageId === 'Log') {
      editor = vscode.window.visibleTextEditors[0]
    }

    let dirName = path.dirname(editor.document.fileName)
    if (!dirName || dirName === '' || dirName === '.') {
      vscode.window.showWarningMessage('Unknown working directory! Try to save the file before running.')
      return
    }

    let selection = editor.selection
    let text = editor.document.getText(selection)
    if ((text === '' && config.executeFileOrSelection === 'both') || config.executeFileOrSelection === 'file') {
      text = editor.document.getText()
    }
    if (config.includeCode) {
      text = config.includeCode.replace('${execPath}', dirName) + ';\n' + text // eslint-disable-line no-template-curly-in-string
    }

    // get config params object
    let options = {}
    if (config.env) {
      options.env = config.env
    }
    // get cwd from config, replace placeholder and add it to the params object
    options.cwd = (typeof config.cwd === 'string') ? config.cwd.replace('${execPath}', dirName) : dirName  // eslint-disable-line no-template-curly-in-string

    // set tempfile
    let tmpFile = path.join(dirName, `node_${require('crypto').createHash('sha1').update(Math.random().toString()).digest('hex').substr(0, 13)}.tmp`)
    // wirte code in temp file and exec the file with node
    fs.writeFileSync(tmpFile, text)

    let args = [tmpFile]
    if (Array.isArray(config.args) && config.args.length > 0) {
      args = args.concat(config.args)
    }

    let startTime = new Date()
    let nodeBin = (typeof config.nodeBin === 'string') ? config.nodeBin : 'node'

    if (!config.terminalMode) {
      runningStatus = vscode.window.setStatusBarMessage('Running...')
      outputChannel.show(vscode.window.visibleTextEditors.length + 1)
      if (config.clearOutput) {
        outputChannel.clear()
      }
      if (config.showInfo) {
        outputChannel.appendLine('Info: Start process (' + startTime.toLocaleTimeString() + ')')
      }
      // spawn new node.js process
      process = spawn(nodeBin, args, options)

      // process event handlers
      process.stdout.on('data', function (data) {
        if (!config.showStdout) return
        outputChannel.append(data.toString())
      })
      process.stderr.on('data', function (data) {
        if (!config.showStderr) return
        outputChannel.appendLine('Error: ')
        outputChannel.appendLine(data.toString())
      })
      process.on('close', function () {
        fs.unlink(tmpFile)
        if (runningStatus) {
          if (config.showInfo) {
            outputChannel.appendLine('Info: End process (' + new Date().toLocaleTimeString() + ')')
          }
          runningStatus.dispose()
          runningStatus = null
        }
      })
      process.on('error', function (err) {
        fs.unlink(tmpFile)
        outputChannel.appendLine('Process error: ')
        outputChannel.appendLine(err.toString())
        if (config.showInfo) {
          outputChannel.appendLine('Info: End process with errors (' + new Date().toLocaleTimeString() + ')')
        }
        if (runningStatus) {
          runningStatus.dispose()
          runningStatus = null
        }
      })
    } else { // Terminal Mode
      let terminalIndex = terminals.length
      let terminal = vscode.window.createTerminal(`Node.js (${startTime.toLocaleTimeString()})`)
      terminal.filePath = tmpFile
      terminal.index = terminalIndex
      terminal.show()
      terminal.sendText(`cd "${dirName}"`)
      terminal.sendText(`${config.nodeBin} "${path.basename(terminal.filePath)}" ${config.args.join(' ')}`)
      terminal.sendText(`rm "${terminal.filePath}"`) // try to delete the file after execution
      terminals.push(terminal)
    }
  })

  // event for closing an terminal window
  vscode.window.onDidCloseTerminal(function (terminal) {
    if (terminal.filePath) {
      if (fs.existsSync(terminal.filePath)) {
        fs.unlink(terminal.filePath) // if tmp file still exist, try to delete it
      }
      terminals.splice(terminal.index, 1)
    }
  })

  // cancel the exec process
  var cancel = vscode.commands.registerCommand('extension.miramac.node.cancel', function () {
    const config = vscode.workspace.getConfiguration('miramac.node')
    if (config.terminalMode) {
      return
    }
    if (runningStatus) {
      if (config.showInfo) {
        outputChannel.appendLine('Process canceled')
      }
      if (process) {
        process.kill()
      } else {
        runningStatus = null
      }
    }
  })

  context.subscriptions.push(run, cancel)
}

module.exports = activate<commit_msg>Show code total execution time on process end<commit_after>'use strict'
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode')
const spawn = require('child_process').spawn
const fs = require('fs')
const path = require('path')

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed

function activate (context) {
  const outputChannel = vscode.window.createOutputChannel(vscode.workspace.getConfiguration('miramac.node').outputWindowName)
  let terminals = []
  let process
  let runningStatus = null

  // executes JS code with node
  let run = vscode.commands.registerCommand('extension.miramac.node.exec', function () {
    const config = vscode.workspace.getConfiguration('miramac.node')
    // test for running process
    if (runningStatus) {
      vscode.window.showErrorMessage('Process is already running!')
      return
    }

    let editor = vscode.window.activeTextEditor
    if (!editor) {
      return // No open text editor
    }
    if (editor._documentData._languageId === 'Log') {
      editor = vscode.window.visibleTextEditors[0]
    }

    let dirName = path.dirname(editor.document.fileName)
    if (!dirName || dirName === '' || dirName === '.') {
      vscode.window.showWarningMessage('Unknown working directory! Try to save the file before running.')
      return
    }

    let selection = editor.selection
    let text = editor.document.getText(selection)
    if ((text === '' && config.executeFileOrSelection === 'both') || config.executeFileOrSelection === 'file') {
      text = editor.document.getText()
    }
    if (config.includeCode) {
      text = config.includeCode.replace('${execPath}', dirName) + ';\n' + text // eslint-disable-line no-template-curly-in-string
    }

    // get config params object
    let options = {}
    if (config.env) {
      options.env = config.env
    }
    // get cwd from config, replace placeholder and add it to the params object
    options.cwd = (typeof config.cwd === 'string') ? config.cwd.replace('${execPath}', dirName) : dirName  // eslint-disable-line no-template-curly-in-string

    // set tempfile
    let tmpFile = path.join(dirName, `node_${require('crypto').createHash('sha1').update(Math.random().toString()).digest('hex').substr(0, 13)}.tmp`)
    // wirte code in temp file and exec the file with node
    fs.writeFileSync(tmpFile, text)

    let args = [tmpFile]
    if (Array.isArray(config.args) && config.args.length > 0) {
      args = args.concat(config.args)
    }

    let startTime = new Date()
    let nodeBin = (typeof config.nodeBin === 'string') ? config.nodeBin : 'node'

    if (!config.terminalMode) {
      runningStatus = vscode.window.setStatusBarMessage('Running...')
      outputChannel.show(vscode.window.visibleTextEditors.length + 1)
      if (config.clearOutput) {
        outputChannel.clear()
      }
      if (config.showInfo) {
        outputChannel.appendLine('Info: Start process (' + startTime.toLocaleTimeString() + ')')
      }
      // spawn new node.js process
      process = spawn(nodeBin, args, options)

      // process event handlers
      process.stdout.on('data', function (data) {
        if (!config.showStdout) return
        outputChannel.append(data.toString())
      })
      process.stderr.on('data', function (data) {
        if (!config.showStderr) return
        outputChannel.appendLine('Error: ')
        outputChannel.appendLine(data.toString())
      })
      process.on('close', function () {
        fs.unlink(tmpFile)
        if (runningStatus) {
          if (config.showInfo) {
            outputChannel.appendLine('Info: End process in ' + getDuration(startTime, new Date()) + ' (mm:ss:fff)')
          }
          runningStatus.dispose()
          runningStatus = null
        }
      })
      process.on('error', function (err) {
        fs.unlink(tmpFile)
        outputChannel.appendLine('Process error: ')
        outputChannel.appendLine(err.toString())
        if (config.showInfo) {
          outputChannel.appendLine('Info: End process with errors in ' + getDuration(startTime, new Date()) + ' (mm:ss:fff)')
        }
        if (runningStatus) {
          runningStatus.dispose()
          runningStatus = null
        }
      })
    } else { // Terminal Mode
      let terminalIndex = terminals.length
      let terminal = vscode.window.createTerminal(`Node.js (${startTime.toLocaleTimeString()})`)
      terminal.filePath = tmpFile
      terminal.index = terminalIndex
      terminal.show()
      terminal.sendText(`cd "${dirName}"`)
      terminal.sendText(`${config.nodeBin} "${path.basename(terminal.filePath)}" ${config.args.join(' ')}`)
      terminal.sendText(`rm "${terminal.filePath}"`) // try to delete the file after execution
      terminals.push(terminal)
    }
  })

  // event for closing an terminal window
  vscode.window.onDidCloseTerminal(function (terminal) {
    if (terminal.filePath) {
      if (fs.existsSync(terminal.filePath)) {
        fs.unlink(terminal.filePath) // if tmp file still exist, try to delete it
      }
      terminals.splice(terminal.index, 1)
    }
  })

  // cancel the exec process
  var cancel = vscode.commands.registerCommand('extension.miramac.node.cancel', function () {
    const config = vscode.workspace.getConfiguration('miramac.node')
    if (config.terminalMode) {
      return
    }
    if (runningStatus) {
      if (config.showInfo) {
        outputChannel.appendLine('Process canceled')
      }
      if (process) {
        process.kill()
      } else {
        runningStatus = null
      }
    }
  })

  context.subscriptions.push(run, cancel)
}

module.exports = activate

// get a duration as Timestring (mm:ss.fff)
function getDuration (start, end) {
  let duration = new Date(end - start)
  return numPad(duration.getMinutes(), 1) + ':' + numPad(duration.getSeconds(), 2) + ':' + numPad(duration.getMilliseconds(), 3)
}

// Numberpadding
function numPad (number, size) {
  let result = number + ''
  while (result.length < size) {
    result = '0' + result
  }
  return result
}
{'fraction_non_alphanumeric': 0.12954583542818837, 'fraction_numerical': 0.0016758840288252053, 'mean_word_length': 2.89523498694517, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 5, 'https://': 0, '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': '604100', 'n_tokens_mistral': 3497, 'n_tokens_neox': 3423, 'n_words': 816}