Skip to content

Commit

Permalink
refactor(hook-console-log): pass line offset instead of hardcoding 1
Browse files Browse the repository at this point in the history
  • Loading branch information
zkochan committed Apr 23, 2016
1 parent b3746bb commit 7ecd36f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
6 changes: 4 additions & 2 deletions lib/hook-console-log.js
Expand Up @@ -7,13 +7,15 @@ const slice = Array.prototype.slice

const originalLog = console.log

function hookConsoleLog (filePath) {
function hookConsoleLog (filePath, opts) {
opts = opts || {}

console.log = function () {
const site = callsiteForFile(filePath)

originalLog('\n$\n' + JSON.stringify({
args: slice.call(arguments),
line: site.line - 1,
line: site.line - opts.lineOffset,
column: site.column,
}))
}
Expand Down
17 changes: 13 additions & 4 deletions lib/stdout-to-comments.js
Expand Up @@ -8,7 +8,6 @@ const spawn = require('cross-spawn-async')
const path = require('path')
const SourceMapConsumer = require('source-map').SourceMapConsumer
const normalizePath = require('normalize-path')
const hookPath = normalizePath(path.resolve(__dirname, './hook-console-log'))
const position = require('file-position')
const normalizeNewline = require('normalize-newline')
const consoleStringify = require('./console-stringify')
Expand Down Expand Up @@ -139,9 +138,19 @@ function outputSemanticPosition (ast, pos) {
return node.node.loc.end.line
}

const hookPath = normalizePath(path.resolve(__dirname, './hook-console-log'))

function addHook (opts) {
if (!opts.code.match(/['"]use strict['"]/)) {
return `require('${hookPath}')('${opts.filePath}');\n` + opts.code
return useStrictToBeginning(
`require('${hookPath}')('${opts.filePath}', {lineOffset: 1});\n${opts.code}`
)
}

// this is needed because the 'use strict' statement has to be before any
// other statement in the file
function useStrictToBeginning (code) {
if (!code.match(/['"]use strict['"]/)) {
return code
}
return `'use strict';require('${hookPath}')('${opts.filePath}');\n` + opts.code
return `'use strict';${code}`
}

0 comments on commit 7ecd36f

Please sign in to comment.