Rework API for sourcemap filenames and paths.

This commit is contained in:
Jason Walton 2013-03-07 21:26:09 -05:00
parent 185b2ce632
commit f85d19b459
10 changed files with 61 additions and 247 deletions

View File

@ -1,6 +1,6 @@
// Generated by CoffeeScript 1.6.1
(function() {
var Lexer, compile, ext, fs, generateV3SourceMapOptions, helpers, lexer, loadFile, parser, path, sourcemap, vm, _i, _len, _ref,
var Lexer, compile, ext, fs, helpers, lexer, loadFile, parser, path, sourcemap, vm, _i, _len, _ref,
__hasProp = {}.hasOwnProperty;
fs = require('fs');
@ -39,33 +39,8 @@
exports.helpers = helpers;
generateV3SourceMapOptions = function(options) {
var cwd, sourceRoot;
if (options == null) {
options = {};
}
console.log("Generating v3 source map");
cwd = options.workingDirectory;
if (!options.filename) {
return {};
}
if (options.jsPath) {
sourceRoot = helpers.relativePath(options.jsPath, ".", cwd);
return {
sourceRoot: sourceRoot,
sourceFile: helpers.relativePath(".", options.filename, cwd),
generatedFile: helpers.baseFileName(options.jsPath)
};
}
return {
sourceRoot: "",
sourceFile: helpers.baseFileName(options.filename),
generatedFile: helpers.baseFileName(options.filename, true) + ".js"
};
};
exports.compile = compile = function(code, options) {
var answer, currentColumn, currentLine, err, fragment, fragments, header, js, merge, newLines, sourceMap, v3Options, _j, _len1;
var answer, currentColumn, currentLine, err, fragment, fragments, header, js, merge, newLines, sourceMap, _j, _len1;
if (options == null) {
options = {};
}
@ -112,8 +87,7 @@
};
if (sourceMap) {
answer.sourceMap = sourceMap;
v3Options = generateV3SourceMapOptions(options);
answer.v3SourceMap = sourcemap.generateV3SourceMap(sourceMap, v3Options);
answer.v3SourceMap = sourcemap.generateV3SourceMap(sourceMap, options);
}
return answer;
} else {

View File

@ -483,15 +483,34 @@
};
compileOptions = function(filename, base) {
return {
var answer, cwd, jsDir, jsPath;
answer = {
filename: filename,
literate: helpers.isLiterate(filename),
bare: opts.bare,
header: opts.compile,
sourceMap: opts.map,
jsPath: filename !== null && base !== null ? outputPath(filename, base) : null,
workingDirectory: process.cwd()
sourceMap: opts.map
};
if (filename) {
if (base) {
cwd = process.cwd();
jsPath = outputPath(filename, base);
jsDir = path.dirname(jsPath);
answer = helpers.merge(answer, {
jsPath: jsPath,
sourceRoot: path.relative(jsDir, cwd),
sourceFiles: [path.relative(cwd, filename)],
generatedFile: helpers.baseFileName(jsPath)
});
} else {
answer = helpers.merge(answer, {
sourceRoot: "",
sourceFiles: [helpers.baseFileName(filename)],
generatedFile: helpers.baseFileName(filename, true) + ".js"
});
}
}
return answer;
};
forkNode = function() {

View File

@ -1,6 +1,6 @@
// Generated by CoffeeScript 1.6.1
(function() {
var buildLocationData, extend, flatten, last, normalizePath, repeat, _ref;
var buildLocationData, extend, flatten, last, repeat, _ref;
exports.starts = function(string, literal, start) {
return literal === string.substr(start, literal.length);
@ -179,67 +179,4 @@
return /\.(litcoffee|coffee\.md)$/.test(file);
};
exports.normalizePath = normalizePath = function(path, removeTrailingSlash) {
var i, newParts, part, parts, root, _i, _len;
if (removeTrailingSlash == null) {
removeTrailingSlash = false;
}
root = false;
parts = path.split('/');
newParts = [];
i = 0;
if (parts.length > 1 && parts[0] === '') {
parts.shift();
root = true;
}
for (i = _i = 0, _len = parts.length; _i < _len; i = ++_i) {
part = parts[i];
if (part === '.' || part === '') {
if ((i === parts.length - 1) && !removeTrailingSlash) {
newParts.push('');
}
} else if (part === '..') {
if (newParts.length === 0 || (newParts.length && last(newParts === '..'))) {
newParts.push('..');
} else {
newParts.pop();
}
} else {
newParts.push(part);
}
}
if (root) {
if (newParts.length === 0) {
return '/';
}
if (newParts.length[0] === '..') {
throw new Error("Invalid path: " + path);
}
newParts.unshift('');
}
return newParts.join('/');
};
exports.relativePath = function(from, to, cwd) {
var answer;
if (cwd == null) {
cwd = null;
}
if (cwd) {
from = cwd + "/" + from;
to = cwd + "/" + to;
}
from = (normalizePath(from)).split('/');
to = (normalizePath(to)).split('/');
while (from.length > 0 && to.length > 0 && from[0] === to[0]) {
from.shift();
to.shift();
}
if (from.length && from[0] === "..") {
throw new Error("'cwd' must be specified if 'from' references parent directory: " + (from.join('/')) + " -> " + (to.join('/')));
}
answer = repeat("../", from.length - 1);
return answer + ("" + (to.join('/')));
};
}).call(this);

View File

@ -114,13 +114,13 @@
})();
exports.generateV3SourceMap = function(sourceMap, options) {
var answer, generatedFile, lastGeneratedColumnWritten, lastSourceColumnWritten, lastSourceLineWritten, mappings, needComma, sourceFile, sourceRoot, writingGeneratedLine;
var answer, generatedFile, lastGeneratedColumnWritten, lastSourceColumnWritten, lastSourceLineWritten, mappings, needComma, sourceFiles, sourceRoot, writingGeneratedLine;
if (options == null) {
options = {};
}
sourceRoot = options.sourceRoot || "";
sourceFile = options.sourceFile || null;
generatedFile = options.generatedFile || null;
sourceFiles = options.sourceFiles || [""];
generatedFile = options.generatedFile || "";
writingGeneratedLine = 0;
lastGeneratedColumnWritten = 0;
lastSourceLineWritten = 0;
@ -151,7 +151,7 @@
version: 3,
file: generatedFile,
sourceRoot: sourceRoot,
sources: sourceFile ? [sourceFile] : [],
sources: sourceFiles,
names: [],
mappings: mappings
};

View File

@ -30,41 +30,10 @@ exports.VERSION = '1.6.1'
# Expose helpers for testing.
exports.helpers = helpers
# Generate v3 Source Map options from compile options.
#
# options.filename is required, and is the path and filename of the file being compiled,
# relative to the current working directory.
#
# `options.jsPath` and `options.workingDirectory` may also be specified to customize the output
# in the resulting v3 source map, where `options.jsPath` is the path where the .js file will be
# written relative to the current working directory, and `options.workingDirectory` is the absolute
# path of the current working directory (required if jsPath references a parent directory.) If
# these options are provided, then "sourceRoot" in the output will be a relative path to the
# current working directory, and source files will be given relative to the "sourceRoot".
#
generateV3SourceMapOptions = (options = {}) ->
console.log "Generating v3 source map"
cwd = options.workingDirectory
return {} unless options.filename
if options.jsPath
sourceRoot = helpers.relativePath options.jsPath, ".", cwd
return {
sourceRoot
sourceFile: helpers.relativePath ".", options.filename, cwd
generatedFile: helpers.baseFileName(options.jsPath)
}
{
sourceRoot: ""
sourceFile: helpers.baseFileName options.filename
generatedFile: helpers.baseFileName(options.filename, yes) + ".js"
}
# Compile CoffeeScript code to JavaScript, using the Coffee/Jison compiler.
#
# If `options.sourceMap` is specified, then `options.filename` must also be specified. See
# `generateV3SourceMapOptions()` for other options that can be passed to control source map
# generation.
# If `options.sourceMap` is specified, then `options.filename` must also be specified. All
# options that can be passed to `generateV3SourceMap()` may also be passed here.
#
# This returns a javascript string, unless `options.sourceMap` is passed,
# in which case this returns a `{js, v3SourceMap, sourceMap}
@ -110,8 +79,7 @@ exports.compile = compile = (code, options = {}) ->
answer = {js}
if sourceMap
answer.sourceMap = sourceMap
v3Options = generateV3SourceMapOptions options
answer.v3SourceMap = sourcemap.generateV3SourceMap(sourceMap, v3Options)
answer.v3SourceMap = sourcemap.generateV3SourceMap(sourceMap, options)
answer
else
js

View File

@ -323,17 +323,30 @@ parseOptions = ->
# The compile-time options to pass to the CoffeeScript compiler.
compileOptions = (filename, base) ->
{
answer = {
filename
literate: helpers.isLiterate(filename)
bare: opts.bare
header: opts.compile
sourceMap: opts.map
jsPath: if (filename isnt null and base isnt null) then (outputPath filename, base) else null
workingDirectory: process.cwd()
}
if filename
if base
cwd = process.cwd()
jsPath = outputPath filename, base
jsDir = path.dirname jsPath
answer = helpers.merge answer, {
jsPath
sourceRoot: path.relative jsDir, cwd
sourceFiles: [path.relative cwd, filename]
generatedFile: helpers.baseFileName(jsPath)
}
else
answer = helpers.merge answer,
sourceRoot: ""
sourceFiles: [helpers.baseFileName filename]
generatedFile: helpers.baseFileName(filename, yes) + ".js"
answer
# Start up a new Node.js instance with the arguments in `--nodejs` passed to
# the `node` binary, preserving the other options.

View File

@ -128,59 +128,3 @@ exports.isCoffee = (file) -> /\.((lit)?coffee|coffee\.md)$/.test file
# Determine if a filename represents a Literate CoffeeScript file.
exports.isLiterate = (file) -> /\.(litcoffee|coffee\.md)$/.test file
# Remove any "." components in a path, any ".."s in the middle of a path. Leaves a trailing '/'
# if present, unless removeTrailingSlash is set.
exports.normalizePath = normalizePath = (path, removeTrailingSlash=no) ->
root = no # Does this path start with the root?
parts = path.split '/'
newParts = []
i = 0
# If the path started with a '/', set the root flag.
if parts.length > 1 and parts[0] == ''
parts.shift()
root = yes
for part, i in parts
if part in ['.', '']
if (i is parts.length - 1) and not removeTrailingSlash
# Leave the trailing '/'. Note that we're pushing a '', but because we join with '/'s
# later, this will become a '/'.
newParts.push ''
else if part is '..'
if newParts.length is 0 or (newParts.length and last newParts is '..')
# Leave the ".."
newParts.push '..'
else
# Drop the '..' and remote the previous element
newParts.pop()
else
newParts.push part
if root
if newParts.length is 0 then return '/'
if newParts.length[0] is '..'
# Uhh... This doesn't make any sense.
throw new Error "Invalid path: #{path}"
newParts.unshift '' # Add back the leading "/"
newParts.join '/'
# Solve the relative path from `from` to `to`.
#
# This is the same as node's `path.relative()`, but can be used even if we're not running in node.
# If paths are relative (don't have a leading '/') then we assume they are both relative to to
# same working directory.
#
# If `from` is a relative path that starts with '..', then `cwd` must be provided to resolve
# parent path names.
exports.relativePath = (from, to, cwd=null) ->
if cwd
from = cwd + "/" + from
to = cwd + "/" + to
from = normalizePath(from).split '/'
to = normalizePath(to).split '/'
while from.length > 0 and to.length > 0 and from[0] == to[0]
from.shift()
to.shift()
if from.length and from[0] is ".." then throw new Error "'cwd' must be specified if 'from' references parent directory: #{from.join '/'} -> #{to.join '/'}"
answer = repeat "../", from.length - 1
answer + "#{to.join '/'}"

View File

@ -91,11 +91,15 @@ class exports.SourceMap
# Builds a V3 source map from a SourceMap object.
# Returns the generated JSON as a string.
#
# `options.sourceRoot` may be used to specify the sourceRoot written to the source map. Also,
# `options.sourceFiles` and `options.generatedFile` may be passed to set "sources" and "file",
# respectively. Note that `sourceFiles` must be an array.
exports.generateV3SourceMap = (sourceMap, options={}) ->
sourceRoot = options.sourceRoot or ""
sourceFile = options.sourceFile or null
generatedFile = options.generatedFile or null
sourceFiles = options.sourceFiles or [""]
generatedFile = options.generatedFile or ""
writingGeneratedLine = 0
lastGeneratedColumnWritten = 0
@ -151,7 +155,7 @@ exports.generateV3SourceMap = (sourceMap, options={}) ->
version: 3
file: generatedFile
sourceRoot
sources: if sourceFile then [sourceFile] else []
sources: sourceFiles
names: []
mappings
}

View File

@ -94,48 +94,3 @@ test "the `last` helper returns the last item of an array-like object", ->
test "the `last` helper allows one to specify an optional offset", ->
ary = [0, 1, 2, 3, 4]
eq 2, last(ary, 2)
# `normalizePath`
test "various tests for normalizePath", ->
eq "/", normalizePath "/"
eq "", normalizePath "."
eq "", normalizePath ""
eq "/a/b", normalizePath "/a/b"
eq "/a/c/", normalizePath "/a/c/"
eq "/a/c", normalizePath "/a/c/", true
eq "/a/d", normalizePath "/a/../a/./d/c/.."
eq "/a/e/", normalizePath "/a/../a/./e/c/../"
eq "/a/e", normalizePath "/a/../a/./e/c/../", true
eq "../a", normalizePath "../a"
eq "../b", normalizePath "a/../../b"
# `relativePath`
test "various tests for relativePath", ->
# Same level
eq "foo.js", relativePath "foo.coffee", "foo.js"
eq "foo.js", relativePath "foo.coffee", "foo.js", "/work/src"
# Same level, but both down one level
eq "bar.js", relativePath "src/bar.coffee", "src/bar.js"
eq "bar.js", relativePath "src/bar.coffee", "src/bar.js", "/work/src"
# Sam level, using '.'' as from
eq "baz.js", relativePath ".", "baz.js"
eq "baz.js", relativePath ".", "baz.js", "/work/src"
eq "o/qux.js", relativePath ".", "o/qux.js"
eq "o/qux.js", relativePath ".", "o/qux.js", "/work/src"
# Up one level
eq "../", relativePath "src/bar.js", "."
eq "../", relativePath "src/bar.js", ".", "/work/src"
# Up and over one directory
eq "../dest/foo.js", relativePath "src/foo.coffee", "dest/foo.js"
eq "../dest/foo.js", relativePath "src/foo.coffee", "dest/foo.js", "/work/src"
# Absolute paths
eq "dest1/dest2/bar.js", relativePath "/bar.coffee", "/dest1/dest2/bar.js"
# File vs. directory - keep trailing '/'
eq "../c", relativePath "a/b/", "a/c"
eq "../d/", relativePath "a/b/", "a/d/"
# This should throw, since relativePath can't know the name of the directory that foo.coffee is in.
throws -> relativePath "../o/foo.js", "foo.coffee"
# With the CWD, this should pass.
eq "../src/foo.coffee", relativePath "../o/foo.js", "foo.coffee", "/work/src"

View File

@ -38,10 +38,10 @@ test "SourceMap tests", ->
testWithFilenames = sourcemap.generateV3SourceMap map, {
sourceRoot: "",
sourceFile: "source.coffee",
sourceFiles: ["source.coffee"],
generatedFile: "source.js"}
eqJson testWithFilenames, '{"version":3,"file":"source.js","sourceRoot":"","sources":["source.coffee"],"names":[],"mappings":"AAAA;;IACK,GAAC,CAAG;IAET"}'
eqJson (sourcemap.generateV3SourceMap map), '{"version":3,"file":null,"sourceRoot":"","sources":[],"names":[],"mappings":"AAAA;;IACK,GAAC,CAAG;IAET"}'
eqJson (sourcemap.generateV3SourceMap map), '{"version":3,"file":"","sourceRoot":"","sources":[""],"names":[],"mappings":"AAAA;;IACK,GAAC,CAAG;IAET"}'
# Look up a generated column - should get back the original source position.
arrayEq map.getSourcePosition([2,8]), [1,9]