Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Reverting recent changes until we get this under tests.

  • Loading branch information...
commit 508455664b3804365616479b0effc2a674361ff0 1 parent e311503
mde authored
Showing with 157 additions and 258 deletions.
  1. +157 −258 lib/file.js
View
415 lib/file.js
@@ -16,11 +16,6 @@
*
*/
-/**
- @name file
- @namespace file
-*/
-
var fs = require('fs')
, path = require('path')
, JS_PAT = /\.(js|coffee)$/
@@ -41,179 +36,161 @@ var logger = new (function () {
})();
var fileUtils = new (function () {
- var _copyFile
- , _readDir
- , _rmDir
- , _watch;
-
- // Recursively copy files and directories
- _copyFile = function (fromPath, toPath, opts) {
- var from = path.normalize(fromPath)
- , to = path.normalize(toPath)
- , options = opts || {}
- , fromStat = fs.statSync(from)
- , toStat
- , destExists
- , destDoesNotExistErr
- , content
- , filename
- , dirContents
- , targetDir;
+ var _copyFile = function(fromPath, toPath, opts) {
+ var from = path.normalize(fromPath)
+ , to = path.normalize(toPath)
+ , options = opts || {}
+ , fromStat
+ , toStat
+ , destExists
+ , destDoesNotExistErr
+ , content
+ , filename
+ , dirContents
+ , targetDir;
+
+ fromStat = fs.statSync(from);
- // Check if the destination path exists then set the path stat
- try {
- toStat = fs.statSync(to);
- destExists = true;
- }
- catch (err) {
- destDoesNotExistErr = err;
- destExists = true;
- }
-
- // Destination exists so copy into directory or overwrite file
- if (destExists) {
- // If rename option is given use it otherwise
- // use original name
- filename = options.rename || path.basename(from);
-
- // Copying a directory
- if (fromStat.isDirectory()) {
- dirContents = fs.readdirSync(from);
- targetDir = path.join(to, filename);
-
- // Overwrite to directory
try {
- fs.mkdirSync(targetDir, options.mode || 0755)
+ //console.dir(to + ' destExists');
+ toStat = fs.statSync(to);
+ destExists = true;
}
- catch (err) {
- if (err.code != 'EEXIST') {
- throw err;
- }
+ catch(e) {
+ //console.dir(to + ' does not exist');
+ destDoesNotExistErr = e;
+ destExists = false;
}
-
- // Copy all files
- for (var i = 0, len = dirContents.length; i < len; i++) {
- _copyFile(path.join(from, dirContents[i]), targetDir);
- }
- }
- // Copying a file
- else {
- content = fs.readFileSync(from);
-
- // Copying into a directory
- if (toStat.isDirectory()) {
- fs.writeFileSync(path.join(to, filename), content)
+ // Destination dir or file exists, copy into (directory)
+ // or overwrite (file)
+ if (destExists) {
+
+ // If there's a rename-via-copy file/dir name passed, use it.
+ // Otherwise use the actual file/dir name
+ filename = options.rename || path.basename(from);
+
+ // Copying a directory
+ if (fromStat.isDirectory()) {
+ dirContents = fs.readdirSync(from);
+ targetDir = path.join(to, filename);
+ // We don't care if the target dir already exists
+ try {
+ fs.mkdirSync(targetDir, options.mode || 0755);
+ }
+ catch(e) {
+ if (e.code != 'EEXIST') {
+ throw e;
+ }
+ }
+ for (var i = 0, ii = dirContents.length; i < ii; i++) {
+ //console.log(dirContents[i]);
+ _copyFile(path.join(from, dirContents[i]), targetDir);
+ }
+ }
+ // Copying a file
+ else {
+ content = fs.readFileSync(from);
+ // Copy into dir
+ if (toStat.isDirectory()) {
+ //console.log('copy into dir ' + to);
+ fs.writeFileSync(path.join(to, filename), content);
+ }
+ // Overwrite file
+ else {
+ //console.log('overwriting ' + to);
+ fs.writeFileSync(to, content);
+ }
+ }
}
- // Overwriting a file
+ // Dest doesn't exist, can't create it
else {
- fs.writeFileSync(to, content);
+ throw destDoesNotExistErr;
}
}
- }
- // Destination dosn't exist
- else {
- throw destDoesNotExistErr;
- }
- };
-
- // Return the contents of a given directory
- _readDir = function (dirPath) {
- var dir = path.normalize(dirPath)
- , paths = []
- , ret = [dir];
- try {
- paths = fs.readdirSync(dir);
- }
- catch (err) {
- throw new Error('Could not read path ' + dir);
- }
-
- paths.forEach(function (p) {
- var curr = path.join(dir, p)
- , stat = fs.statSync(curr);
-
- if (stat.isDirectory()) {
- ret = ret.concat(_readDir(curr));
+ , _copyDir = function (from, to, opts) {
+ var createDir = opts.createDir;
}
- else {
- ret.push(curr);
- }
- });
- return ret;
- };
+ , _readDir = function (dirPath) {
+ var dir = path.normalize(dirPath)
+ , paths = []
+ , ret = [dir];
- // Remove the given directory
- _rmDir = function (dirPath) {
- var dir = path.normalize(dirPath)
- , paths = fs.readdirSync(dir);
+ try {
+ paths = fs.readdirSync(dir);
+ }
+ catch (e) {
+ throw new Error('Could not read path ' + dir);
+ }
- // Remove each child path
- paths.forEach(function (p) {
- var curr = path.join(dir, p)
- , stat = fs.statSync(curr);
+ paths.forEach(function (p) {
+ var curr = path.join(dir, p);
+ var stat = fs.statSync(curr);
+ if (stat.isDirectory()) {
+ ret = ret.concat(_readDir(curr));
+ }
+ else {
+ ret.push(curr);
+ }
+ });
- if (stat.isDirectory()) {
- _rmDir(curr);
+ return ret;
}
- else {
- fs.unlinkSync(curr);
- }
- });
- fs.rmdirSync(dir);
- };
-
- // Recursively watch js/cs files with a callback
- _watch = function (p, callback) {
- fs.stat(p, function (err, stats) {
- if (err) {
- return false;
+ , _rmDir = function (dirPath) {
+ var dir = path.normalize(dirPath)
+ , paths = [];
+ paths = fs.readdirSync(dir);
+ paths.forEach(function (p) {
+ var curr = path.join(dir, p);
+ var stat = fs.statSync(curr);
+ if (stat.isDirectory()) {
+ _rmDir(curr);
+ }
+ else {
+ fs.unlinkSync(curr);
+ }
+ });
+ fs.rmdirSync(dir);
}
- // If file then watch it
- if (stats.isFile() && JS_PAT.test(p)) {
- fs.watchFile(p, callback);
- }
- // If directory then recursively watch all it's children
- else if (stats.isDirectory()) {
- fs.readdir(p, function (err, files) {
+ // Recursively watch files with a callback
+ , _watch = function (path, callback) {
+ fs.stat(path, function (err, stats) {
if (err) {
- return log.fatal(err);
+ return false;
}
-
- for (var f in files) {
- _watch(path.join(p, files[f]), callback);
+ if (stats.isFile() && JS_PAT.test(path)) {
+ fs.watchFile(path, callback);
+ }
+ else if (stats.isDirectory()) {
+ fs.readdir(path, function (err, files) {
+ if (err) {
+ return log.fatal(err);
+ }
+ for (var f in files) {
+ _watch(path + '/' + files[f], callback);
+ }
+ });
}
});
- }
- });
- };
+ };
- /**
- @name file#cpR
- @public
- @function
- @description Copies a directory/file to a destination
- @param {String} fromPath The source path to copy from
- @param {String} toPath The destination path to copy to
- @param {Object} opts Options to use
- @param {Boolean} [opts.silent] If false then will log the command
- */
- this.cpR = function (fromPath, toPath, opts) {
+ this.cpR = function (fromPath, toPath, options) {
var from = path.normalize(fromPath)
, to = path.normalize(toPath)
, toStat
, doesNotExistErr
, paths
, filename
- , options = opts || {};
+ , opts = options || {};
- if (!options.silent) {
+ if (!opts.silent) {
logger.log('cp -r ' + fromPath + ' ' + toPath);
}
- options = {}; // Reset
+
+ opts = {}; // Reset
if (from == to) {
throw new Error('Cannot copy ' + from + ' to itself.');
@@ -223,30 +200,28 @@ var fileUtils = new (function () {
try {
toStat = fs.statSync(to);
}
- catch (err) {
- doesNotExistErr = err;
+ catch(e) {
+ doesNotExistErr = e;
// Get abs path so it's possible to check parent dir
if (!this.isAbsolute(to)) {
- to = path.join(process.cwd(), to);
+ to = path.join(process.cwd() , to);
}
// Save the file/dir name
filename = path.basename(to);
-
// See if a parent dir exists, so there's a place to put the
/// renamed file/dir (resets the destination for the copy)
to = path.dirname(to);
-
try {
toStat = fs.statSync(to);
}
- catch (err) {}
-
+ catch(e) {}
if (toStat && toStat.isDirectory()) {
// Set the rename opt to pass to the copy func, will be used
// as the new file/dir name
- options.rename = filename;
+ opts.rename = filename;
+ //console.log('filename ' + filename);
}
else {
throw doesNotExistErr;
@@ -256,14 +231,6 @@ var fileUtils = new (function () {
_copyFile(from, to, opts);
};
- /**
- @name file#mkdirP
- @public
- @function
- @description Create the given directory(ies) using the given mode permissions
- @param {String} dir The directory to create
- @param {Number} mode The mode to give the created directory(ies)(Default: 0755)
- */
this.mkdirP = function (dir, mode) {
var dirPath = path.normalize(dir)
, paths = dirPath.split(/\/|\\/)
@@ -273,66 +240,42 @@ var fileUtils = new (function () {
if (paths[0] == '' || /^[A-Za-z]+:/.test(paths[0])) {
currPath = paths.shift() || '/';
currPath = path.join(currPath, paths.shift());
+ //console.log('basedir');
}
-
- while (paths.length) {
- next = paths.shift();
-
+ while ((next = paths.shift())) {
if (next == '..') {
currPath = path.join(currPath, next);
continue;
}
currPath = path.join(currPath, next);
-
try {
+ //console.log('making ' + currPath);
fs.mkdirSync(currPath, mode || 0755);
}
- catch (err) {
- if (err.code != 'EEXIST') {
+ catch(e) {
+ if (e.code != 'EEXIST') {
throw e;
}
}
}
};
- /**
- @name file#readdirR
- @public
- @function
- @return {Array} Returns the contents as an Array, can be configured via opts.format
- @description Reads the given directory returning it's contents
- @param {String} dir The directory to read
- @param {Object} opts Options to use
- @param {String} [opts.format] Set the format to return(Default: Array)
- */
this.readdirR = function (dir, opts) {
var options = opts || {}
, format = options.format || 'array'
- , ret = _readDir(dir);
-
+ , ret;
+ ret = _readDir(dir);
return format == 'string' ? ret.join('\n') : ret;
};
- /**
- @name file#rmRf
- @public
- @function
- @description Deletes the given directory/file
- @param {String} p The path to delete, can be a directory or file
- @param {Object} opts Options to use
- @param {String} [opts.silent] If false then logs the command
- */
- this.rmRf = function (p, opts) {
+ this.rmRf = function (p, options) {
var stat
- , options = opts || {};
-
- if (!options.silent) {
+ , opts = options || {};
+ if (!opts.silent) {
logger.log('rm -rf ' + p);
}
-
try {
stat = fs.statSync(p);
-
if (stat.isDirectory()) {
_rmDir(p);
}
@@ -340,34 +283,17 @@ var fileUtils = new (function () {
fs.unlinkSync(p);
}
}
- catch (err) {}
+ catch (e) {}
};
- /**
- @name file#isAbsolute
- @public
- @function
- @return {Boolean/String} If it's absolute the first char is returned otherwise false
- @description Checks if a given path is absolute or relative
- @param {String} p Path to check
- */
this.isAbsolute = function (p) {
var match = /^[A-Za-z]+:\\|^\//.exec(p);
-
if (match && match.length) {
return match[0];
}
return false;
};
- /**
- @name file#absolutize
- @public
- @function
- @return {String} Returns the absolute path for the given path
- @description Returns the absolute path for the given path
- @param {String} p The path to get the absolute path for
- */
this.absolutize = function (p) {
if (this.isAbsolute(p)) {
return p;
@@ -380,13 +306,11 @@ var fileUtils = new (function () {
this.basedir = function (p) {
var str = p || ''
, abs = this.isAbsolute(p);
-
if (abs) {
return abs;
}
// Split into segments
str = str.split(/\\|\//)[0];
-
// If the path has a leading asterisk, basedir is the current dir
if (str.indexOf('*') > -1) {
return '.';
@@ -397,38 +321,29 @@ var fileUtils = new (function () {
}
};
- /**
- @name file#searchParentPath
- @public
- @function
- @description Search for a directory/file in the current directory and parent directories
- @param {String} p The path to search for
- @param {Function} callback The function to call once the path is found
- */
- this.searchParentPath = function (p, callback) {
- if (!p) {
+ // Search for a directory in parent directories if it can't be found in cwd
+ this.searchParentPath = function(location, callback) {
+ var cwd = process.cwd();
+
+ if(!location) {
// Return if no path is given
return;
}
- var cwd = process.cwd()
- , relPath = ''
+ var relPath = ''
, i = 5 // Only search up to 5 directories
, pathLoc
, pathExists;
- while (--i >= 0) {
- pathLoc = path.join(cwd, relPath, p);
+ while(--i >= 0) {
+ pathLoc = path.join(cwd, relPath, location);
pathExists = this.existsSync(pathLoc);
- // If path exists call the callback with the full path
- if (pathExists) {
+ if(pathExists) {
callback && callback(undefined, pathLoc);
break;
- }
- // Path doesn't exist so search the parent
- else {
+ } else {
// Dir could not be found
- if (i === 0) {
+ if(i === 0) {
callback && callback(new Error("Path \"" + pathLoc + "\" not found"), undefined);
break;
}
@@ -441,14 +356,6 @@ var fileUtils = new (function () {
}
};
- /**
- @name file#watch
- @public
- @function
- @description Watch a given path then calls the callback once a change occurs
- @param {String} path The path to watch
- @param {Function} callback The function to call when a change occurs
- */
this.watch = function () {
_watch.apply(this, arguments);
};
@@ -459,33 +366,25 @@ var fileUtils = new (function () {
// Compatibility for fs.existsSync(0.8) and path.existsSync(0.6)
this.existsSync = (typeof fs.existsSync === 'function') ? fs.existsSync : path.existsSync;
- /**
- @name file#requireLocal
- @public
- @function
- @return {Object} The given module is returned
- @description Require a local module from the node_modules in the current directory
- @param {String} module The module to require
- @param {String} message An option message to throw if the module doesn't exist
- */
- this.requireLocal = function (module, message) {
+ // Require a module locally, i.e., in the node_modules directory
+ // in the current directory
+ this.requireLocal = function(module, message) {
// Try to require in the application directory
try {
dep = require(path.join(process.cwd(), 'node_modules', module));
}
- catch (err) {
- if (message) {
+ catch(err) {
+ if(message) {
throw new Error(message);
}
-
throw new Error('Module "' + module + '" could not be found as a ' +
'local module.\n Please make sure there is a node_modules directory in the ' +
'current directory,\n and install it by doing "npm install ' +
module + '"');
}
-
return dep;
};
+
})();
module.exports = fileUtils;
Please sign in to comment.
Something went wrong with that request. Please try again.