-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
118 lines (93 loc) · 2.43 KB
/
index.js
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
var callsite = require('callsite')
, fs = require('fs')
, path = require('path')
, AssertionError = require('assert').AssertionError
/**
* Enable the module only if not in the `production` environment.
*/
module.exports = (process.env.NODE_ENV === 'production')
? function() {}
: assert
/**
* Asserts that `expression` is true.
*/
function assert(expression)
{
if (expression) return
var stack = callsite()
, file = stack[1].getFileName()
, line = stack[1].getLineNumber()
var err = new AssertionError({
message: getAssertionExpression(file, line),
stackStartFunction: stack[0].getFunction()
})
throw err
}
/**
* Gets the expression inside the assertion on line number
* `lineno` of `file`.
*/
function getAssertionExpression(file, lineno)
{
var ext = path.extname(file)
, line = null
switch (ext) {
case '.coffee':
case '.litcoffee':
line = readCoffeeLine(file, lineno)
break
default:
line = readJsLine(file, lineno)
break
}
return line.match(/assert\s*\((.*)\)/)[1]
}
/**
* Reads `file` and returns line number `lineno`.
*/
function readJsLine(file, lineno)
{
var src = fs.readFileSync(file, 'utf8')
return src.split('\n')[lineno - 1]
}
/**
* Reads `file`, compiles it as coffee-script, and returns line
* number `lineno` of the results.
*/
function readCoffeeLine(file, lineno)
{
var coffee = findCoffee()
, raw = fs.readFileSync(file, 'utf8')
, src = raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw
, options = { filename: file }
if (coffee.helpers.isLiterate) {
options.literate = coffee.helpers.isLiterate(file)
}
var src = coffee.compile(src, options)
return src.split('\n')[lineno - 1]
}
/**
* Attempts to find the coffee-script module.
*/
function findCoffee()
{
try { return require('coffee-script') } catch (e) {}
var coffeebin = null
if (isCoffeeBin(process.execPath)) {
coffeebin = process.execPath
} else if (isCoffeeBin(require.main.filename)) {
coffeebin = require.main.filename
}
if (coffeebin) {
return require(path.join(coffeebin, '../..'))
}
throw new Exception("coffee-script module not found")
}
/**
* Returns whether the file at `path` *looks like* it could be
* the coffee binary.
*/
function isCoffeeBin(path)
{
return /(\\|\/)coffee$/.test(path)
}