From 43798d91c886fcedf5926fd4a8858e13cbceb27f Mon Sep 17 00:00:00 2001 From: banderson Date: Thu, 23 May 2013 00:34:20 -0600 Subject: [PATCH] rebase relative urls in inlined imports --- lib/clean.js | 34 +++++++++++++++++++++++++++++- test/data/partials/extra/down.gif | Bin 0 -> 59 bytes test/data/partials/four.css | 1 + test/data/partials/three.css | 1 + test/unit-test.js | 8 +++++++ 5 files changed, 43 insertions(+), 1 deletion(-) create mode 100755 test/data/partials/extra/down.gif create mode 100644 test/data/partials/four.css create mode 100644 test/data/partials/three.css diff --git a/lib/clean.js b/lib/clean.js index 1b897557..e0cd5b62 100644 --- a/lib/clean.js +++ b/lib/clean.js @@ -361,6 +361,7 @@ var CleanCSS = { var cursor = 0; options.relativeTo = options.relativeTo || options.root; + options._baseRelativeTo = options._baseRelativeTo || options.relativeTo; options.visited = options.visited || []; var inlinedFile = function() { @@ -383,9 +384,12 @@ var CleanCSS = { options.visited.push(fullPath); var importedData = fs.readFileSync(fullPath, 'utf8'); + var importRelativeTo = path.dirname(fullPath); + importedData = CleanCSS._rebaseRelativeURLs(importedData, importRelativeTo, options._baseRelativeTo); return CleanCSS._inlineImports(importedData, { root: options.root, - relativeTo: path.dirname(fullPath), + relativeTo: importRelativeTo, + _baseRelativeTo: options.baseRelativeTo, visited: options.visited }); } else { @@ -412,6 +416,34 @@ var CleanCSS = { data; }, + _rebaseRelativeURLs: function(data, fromBase, toBase) { + var tempData = []; + var nextStart = 0; + var nextEnd = 0; + var cursor = 0; + + for (; nextEnd < data.length; ) { + nextStart = data.indexOf('url(', nextEnd); + if (nextStart == -1) + break; + nextEnd = data.indexOf(')', nextStart + 4); + if (nextEnd == -1) + break; + + tempData.push(data.substring(cursor, nextStart)); + var url = data.substring(nextStart + 4, nextEnd).replace(/['"]/g, ''); + if (url[0] != '/' && url.substring(url.length - 4) != '.css') { + url = path.relative(toBase, path.join(fromBase, url)).replace(/\\/g, '/'); + } + tempData.push('url(' + url + ')'); + cursor = nextEnd + 1; + } + + return tempData.length > 0 ? + tempData.join('') + data.substring(cursor, data.length) : + data; + }, + // Strip special comments (/*! ... */) by replacing them by __CSSCOMMENT__ marker // for further restoring. Plain comments are removed. It's done by scanning datq using // String#indexOf scanning instead of regexps to speed up the process. diff --git a/test/data/partials/extra/down.gif b/test/data/partials/extra/down.gif new file mode 100755 index 0000000000000000000000000000000000000000..9bd9447552a7ee77440787a945ce61f26bd9a079 GIT binary patch literal 59 zcmZ?wbhEHb