Socket
Socket
Sign inDemoInstall

fs-jetpack

Package Overview
Dependencies
Maintainers
1
Versions
61
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

fs-jetpack - npm Package Compare versions

Comparing version 0.7.3 to 0.8.0

spec/find_directories.spec.js

44

benchmark/copy.js

@@ -12,6 +12,6 @@ /* eslint no-console: 0 */

var startTimer = function () {
var start = Date.now();
return function stop() {
return Date.now() - start;
};
var start = Date.now();
return function stop() {
return Date.now() - start;
};
};

@@ -23,4 +23,4 @@

for (var i = 0; i < 10000; i += 1) {
toCopyDir.file(i + '.txt', { content: 'text' });
toCopyDir.file(i + '.md', { content: 'markdown' });
toCopyDir.file(i + '.txt', { content: 'text' });
toCopyDir.file(i + '.md', { content: 'markdown' });
}

@@ -36,24 +36,24 @@

.then(function () {
jetpackTime = stop();
console.log('Jetpack took ' + jetpackTime + 'ms');
stop = startTimer();
return toCopyDir.copyAsync('.', testDir.path('copied-filtered-jetpack'), {
matching: '*.txt',
});
jetpackTime = stop();
console.log('Jetpack took ' + jetpackTime + 'ms');
stop = startTimer();
return toCopyDir.copyAsync('.', testDir.path('copied-filtered-jetpack'), {
matching: '*.txt'
});
})
.then(function () {
jetpackFilteredTime = stop();
console.log('Jetpack with *.txt filter took ' + jetpackFilteredTime + 'ms');
stop = startTimer();
return promisedExec('cp -R ' + toCopyDir.path() + ' ' + testDir.path('copied-native'));
jetpackFilteredTime = stop();
console.log('Jetpack with *.txt filter took ' + jetpackFilteredTime + 'ms');
stop = startTimer();
return promisedExec('cp -R ' + toCopyDir.path() + ' ' + testDir.path('copied-native'));
})
.then(function () {
nativeTime = stop();
console.log('Native took ' + nativeTime + 'ms');
var times = jetpackTime / nativeTime;
console.log('Jetpack is ' + times.toFixed(1) + ' times slower than native');
testDir.remove('.');
nativeTime = stop();
console.log('Native took ' + nativeTime + 'ms');
var times = jetpackTime / nativeTime;
console.log('Jetpack is ' + times.toFixed(1) + ' times slower than native');
testDir.remove('.');
})
.catch(function (err) {
console.log(err);
console.log(err);
});

@@ -0,1 +1,13 @@

0.8.0 (2016-04-09)
-------------------
* **(breaking change)** `find()` now distinguishes between files and directories and by default searches only for files (previously searched for both).
* **(breaking change)** `find()` no longer can be configured with `returnAs` parameter and returns always relative paths (previously returned absolute).
* **(breaking change)** `list()` no longer accepts `useInspect` as a parameter. To achieve old behaviour use `jetpack.list()` with `Array.map()`.
* **(deprecation)** Don't do `jetpack.read('sth', 'buf')`, do `jetpack.read('sth', 'buffer')` instead.
* `remove()`, `list()` and `find()` now can be called without provided `path`, and defaults to CWD in that case.
0.7.3 (2016-03-21)
-------------------
* Bugfixed `copy()` with symlink overwrite
0.7.2 (2016-03-09)

@@ -2,0 +14,0 @@ -------------------

@@ -1,2 +0,2 @@

"use strict";
'use strict';

@@ -15,29 +15,29 @@ var pathUtil = require('path');

var parseOptions = function (options, from) {
var parsedOptions = {};
options = options || {};
var parsedOptions = {};
options = options || {};
parsedOptions.overwrite = options.overwrite;
parsedOptions.overwrite = options.overwrite;
if (options.matching) {
parsedOptions.allowedToCopy = matcher.create(options.matching, from);
} else {
parsedOptions.allowedToCopy = function () {
// Default behaviour - copy everything.
return true;
};
}
if (options.matching) {
parsedOptions.allowedToCopy = matcher.create(options.matching, from);
} else {
parsedOptions.allowedToCopy = function () {
// Default behaviour - copy everything.
return true;
};
}
return parsedOptions;
return parsedOptions;
};
var generateNoSourceError = function (path) {
var err = new Error("Path to copy doesn't exist " + path);
err.code = 'ENOENT';
return err;
var err = new Error("Path to copy doesn't exist " + path);
err.code = 'ENOENT';
return err;
};
var generateDestinationExistsError = function (path) {
var err = new Error('Destination path already exists ' + path);
err.code = 'EEXIST';
return err;
var err = new Error('Destination path already exists ' + path);
err.code = 'EEXIST';
return err;
};

@@ -50,46 +50,45 @@

var copySync = function (inspectData, to) {
var mod = mode.normalizeFileMode(inspectData.mode);
if (inspectData.type === 'dir') {
mkdirp.sync(to, { mode: mod });
} else if (inspectData.type === 'file') {
var data = fs.readFileSync(inspectData.absolutePath);
fileOps.write(to, data, { mode: mod });
} else if (inspectData.type === 'symlink') {
var symlinkPointsAt = fs.readlinkSync(inspectData.absolutePath);
try {
fs.symlinkSync(symlinkPointsAt, to);
} catch (err) {
// There is already file/symlink with this name on destination location.
// Must erase it manually, otherwise system won't allow us to place symlink there.
if (err.code === 'EEXIST') {
fs.unlinkSync(to);
// Retry...
fs.symlinkSync(symlinkPointsAt, to);
} else {
throw err;
}
}
var mod = mode.normalizeFileMode(inspectData.mode);
if (inspectData.type === 'dir') {
mkdirp.sync(to, { mode: mod });
} else if (inspectData.type === 'file') {
var data = fs.readFileSync(inspectData.absolutePath);
fileOps.write(to, data, { mode: mod });
} else if (inspectData.type === 'symlink') {
var symlinkPointsAt = fs.readlinkSync(inspectData.absolutePath);
try {
fs.symlinkSync(symlinkPointsAt, to);
} catch (err) {
// There is already file/symlink with this name on destination location.
// Must erase it manually, otherwise system won't allow us to place symlink there.
if (err.code === 'EEXIST') {
fs.unlinkSync(to);
// Retry...
fs.symlinkSync(symlinkPointsAt, to);
} else {
throw err;
}
}
}
};
var sync = function (from, to, options) {
options = parseOptions(options, from);
options = parseOptions(options, from);
if (!exists.sync(from)) {
throw generateNoSourceError(from);
}
if (!exists.sync(from)) {
throw generateNoSourceError(from);
}
if (exists.sync(to) && !options.overwrite) {
throw generateDestinationExistsError(to);
}
if (exists.sync(to) && !options.overwrite) {
throw generateDestinationExistsError(to);
var walker = inspector.createTreeWalkerSync(from);
while (walker.hasNext()) {
var inspectData = walker.getNext();
var destPath = pathUtil.join(to, inspectData.relativePath);
if (options.allowedToCopy(inspectData.absolutePath)) {
copySync(inspectData, destPath);
}
var walker = inspector.createTreeWalkerSync(from);
while (walker.hasNext()) {
var inspectData = walker.getNext();
var destPath = pathUtil.join(to, inspectData.relativePath);
if (options.allowedToCopy(inspectData.absolutePath)) {
copySync(inspectData, destPath);
}
}
}
};

@@ -108,84 +107,83 @@

var copyAsync = function (inspectData, to) {
var mod = mode.normalizeFileMode(inspectData.mode);
if (inspectData.type === 'dir') {
return promisedMkdirp(to, { mode: mod });
} else if (inspectData.type === 'file') {
return promisedReadFile(inspectData.absolutePath)
.then(function (data) {
return fileOps.writeAsync(to, data, { mode: mod });
});
} else if (inspectData.type === 'symlink') {
return promisedReadlink(inspectData.absolutePath)
.then(function (symlinkPointsAt) {
var deferred = Q.defer();
var mod = mode.normalizeFileMode(inspectData.mode);
if (inspectData.type === 'dir') {
return promisedMkdirp(to, { mode: mod });
} else if (inspectData.type === 'file') {
return promisedReadFile(inspectData.absolutePath)
.then(function (data) {
return fileOps.writeAsync(to, data, { mode: mod });
});
} else if (inspectData.type === 'symlink') {
return promisedReadlink(inspectData.absolutePath)
.then(function (symlinkPointsAt) {
var deferred = Q.defer();
promisedSymlink(symlinkPointsAt, to)
.then(deferred.resolve)
.catch(function (err) {
if (err.code === 'EEXIST') {
// There is already file/symlink with this name on destination location.
// Must erase it manually, otherwise system won't allow us to place symlink there.
promisedUnlink(to)
.then(function () {
// Retry...
return promisedSymlink(symlinkPointsAt, to)
})
.then(deferred.resolve, deferred.reject);
} else {
deferred.reject(err);
}
});
promisedSymlink(symlinkPointsAt, to)
.then(deferred.resolve)
.catch(function (err) {
if (err.code === 'EEXIST') {
// There is already file/symlink with this name on destination location.
// Must erase it manually, otherwise system won't allow us to place symlink there.
promisedUnlink(to)
.then(function () {
// Retry...
return promisedSymlink(symlinkPointsAt, to);
})
.then(deferred.resolve, deferred.reject);
} else {
deferred.reject(err);
}
});
return deferred.promise;
});
}
return deferred.promise;
});
}
};
var async = function (from, to, options) {
var deferred = Q.defer();
var deferred = Q.defer();
var startCopying = function () {
var startCopying = function () {
var copyNext = function (walker) {
if (walker.hasNext()) {
var inspectData = walker.getNext();
var destPath = pathUtil.join(to, inspectData.relativePath);
if (options.allowedToCopy(inspectData.absolutePath)) {
copyAsync(inspectData, destPath)
.then(function () {
copyNext(walker);
})
.catch(deferred.reject);
} else {
copyNext(walker);
}
} else {
deferred.resolve();
}
};
var copyNext = function (walker) {
if (walker.hasNext()) {
var inspectData = walker.getNext();
var destPath = pathUtil.join(to, inspectData.relativePath);
if (options.allowedToCopy(inspectData.absolutePath)) {
copyAsync(inspectData, destPath)
.then(function () {
copyNext(walker);
})
.catch(deferred.reject);
} else {
copyNext(walker);
}
} else {
deferred.resolve();
}
};
inspector.createTreeWalkerAsync(from).then(copyNext);
};
inspector.createTreeWalkerAsync(from).then(copyNext);
};
options = parseOptions(options, from);
options = parseOptions(options, from);
// Checks before copying
exists.async(from)
.then(function (srcPathExists) {
if (!srcPathExists) {
throw generateNoSourceError(from);
} else {
return exists.async(to);
}
})
.then(function (destPathExists) {
if (destPathExists && !options.overwrite) {
throw generateDestinationExistsError(to);
} else {
startCopying();
}
})
.catch(deferred.reject);
// Checks before copying
exists.async(from)
.then(function (srcPathExists) {
if (!srcPathExists) {
throw generateNoSourceError(from);
} else {
return exists.async(to);
}
})
.then(function (destPathExists) {
if (destPathExists && !options.overwrite) {
throw generateDestinationExistsError(to);
} else {
startCopying();
}
})
.catch(deferred.reject);
return deferred.promise;
return deferred.promise;
};

@@ -192,0 +190,0 @@

@@ -1,2 +0,2 @@

"use strict";
'use strict';

@@ -12,12 +12,12 @@ var pathUtil = require('path');

function getCriteriaDefaults(criteria) {
if (criteria === undefined) {
criteria = {};
}
if (typeof criteria.empty !== 'boolean') {
criteria.empty = false;
}
if (criteria.mode !== undefined) {
criteria.mode = modeUtil.normalizeFileMode(criteria.mode);
}
return criteria;
if (criteria === undefined) {
criteria = {};
}
if (typeof criteria.empty !== 'boolean') {
criteria.empty = false;
}
if (criteria.mode !== undefined) {
criteria.mode = modeUtil.normalizeFileMode(criteria.mode);
}
return criteria;
}

@@ -30,43 +30,39 @@

var sync = function (path, criteria) {
criteria = getCriteriaDefaults(criteria);
criteria = getCriteriaDefaults(criteria);
try {
var stat = fs.statSync(path);
} catch (err) {
// Detection if path already exists
if (err.code !== 'ENOENT') {
throw err;
}
try {
var stat = fs.statSync(path);
} catch (err) {
// Detection if path already exists
if (err.code !== 'ENOENT') {
throw err;
}
}
if (stat && stat.isFile()) {
// This is file, but should be directory.
fs.unlinkSync(path);
// Clear stat variable to indicate now nothing is there
stat = undefined;
if (stat && stat.isFile()) {
// This is file, but should be directory.
fs.unlinkSync(path);
// Clear stat variable to indicate now nothing is there
stat = undefined;
}
if (stat) {
// Ensure existing directory matches criteria
if (criteria.empty) {
// Delete everything inside this directory
var list = fs.readdirSync(path);
list.forEach(function (filename) {
rimraf.sync(pathUtil.resolve(path, filename));
});
}
if (stat) {
// Ensure existing directory matches criteria
if (criteria.empty) {
// Delete everything inside this directory
var list = fs.readdirSync(path);
list.forEach(function (filename) {
rimraf.sync(pathUtil.resolve(path, filename));
});
}
var mode = modeUtil.normalizeFileMode(stat.mode);
if (criteria.mode !== undefined && criteria.mode !== mode) {
// Mode is different than specified in criteria, fix that.
fs.chmodSync(path, criteria.mode);
}
} else {
// Directory doesn't exist now. Create it.
mkdirp.sync(path, { mode: criteria.mode });
var mode = modeUtil.normalizeFileMode(stat.mode);
if (criteria.mode !== undefined && criteria.mode !== mode) {
// Mode is different than specified in criteria, fix that.
fs.chmodSync(path, criteria.mode);
}
} else {
// Directory doesn't exist now. Create it.
mkdirp.sync(path, { mode: criteria.mode });
}
};

@@ -86,112 +82,110 @@

var empty = function (path) {
var deferred = Q.defer();
var deferred = Q.defer();
promisedReaddir(path)
.then(function (list) {
promisedReaddir(path)
.then(function (list) {
var doOne = function (index) {
if (index === list.length) {
deferred.resolve();
} else {
var subPath = pathUtil.resolve(path, list[index]);
promisedRimraf(subPath).then(function () {
doOne(index + 1);
});
}
};
var doOne = function (index) {
if (index === list.length) {
deferred.resolve();
} else {
var subPath = pathUtil.resolve(path, list[index]);
promisedRimraf(subPath).then(function () {
doOne(index + 1);
});
}
};
doOne(0);
})
.catch(deferred.reject);
doOne(0);
})
.catch(deferred.reject);
return deferred.promise;
return deferred.promise;
};
var async = function (path, criteria) {
var deferred = Q.defer();
var deferred = Q.defer();
criteria = getCriteriaDefaults(criteria);
criteria = getCriteriaDefaults(criteria);
var checkWhatWeHaveNow = function () {
var checkDeferred = Q.defer();
var checkWhatWeHaveNow = function () {
var checkDeferred = Q.defer();
promisedStat(path)
.then(function (stat) {
if (stat.isFile()) {
// This is not a directory, and should be.
promisedRimraf(path)
.then(function () {
// We just deleted that path, so can't
// pass stat further down.
checkDeferred.resolve(undefined);
})
.catch(checkDeferred.reject);
} else {
checkDeferred.resolve(stat);
}
promisedStat(path)
.then(function (stat) {
if (stat.isFile()) {
// This is not a directory, and should be.
promisedRimraf(path)
.then(function () {
// We just deleted that path, so can't
// pass stat further down.
checkDeferred.resolve(undefined);
})
.catch(function (err) {
if (err.code === 'ENOENT') {
// Path doesn't exist
checkDeferred.resolve(undefined);
} else {
// This is other error that nonexistent path, so end here.
checkDeferred.reject(err);
}
});
.catch(checkDeferred.reject);
} else {
checkDeferred.resolve(stat);
}
})
.catch(function (err) {
if (err.code === 'ENOENT') {
// Path doesn't exist
checkDeferred.resolve(undefined);
} else {
// This is other error that nonexistent path, so end here.
checkDeferred.reject(err);
}
});
return checkDeferred.promise;
};
return checkDeferred.promise;
};
var checkWhatShouldBe = function (stat) {
var checkDeferred = Q.defer();
var checkWhatShouldBe = function (stat) {
var checkDeferred = Q.defer();
var needToCheckMoreCriteria = function () {
var needToCheckMoreCriteria = function () {
var checkEmptiness = function () {
if (criteria.empty) {
// Delete everything inside this directory
empty(path)
.then(checkDeferred.resolve, checkDeferred.reject);
} else {
// Everything done!
checkDeferred.resolve();
}
};
var checkEmptiness = function () {
if (criteria.empty) {
// Delete everything inside this directory
empty(path)
.then(checkDeferred.resolve, checkDeferred.reject);
} else {
// Everything done!
checkDeferred.resolve();
}
};
var checkMode = function () {
var mode = modeUtil.normalizeFileMode(stat.mode);
if (criteria.mode !== undefined && criteria.mode !== mode) {
// Mode is different than specified in criteria, fix that
promisedChmod(path, criteria.mode)
.then(checkEmptiness, checkDeferred.reject);
} else {
checkEmptiness();
}
};
var checkMode = function () {
var mode = modeUtil.normalizeFileMode(stat.mode);
if (criteria.mode !== undefined && criteria.mode !== mode) {
// Mode is different than specified in criteria, fix that
promisedChmod(path, criteria.mode)
.then(checkEmptiness, checkDeferred.reject);
} else {
checkEmptiness();
}
};
checkMode();
};
checkMode();
};
var checkExistence = function () {
if (!stat) {
promisedMkdirp(path, { mode: criteria.mode })
.then(checkDeferred.resolve, checkDeferred.reject);
} else {
// Directory exists, but we still don't
// know if it matches all criteria.
needToCheckMoreCriteria();
}
};
var checkExistence = function () {
if (!stat) {
promisedMkdirp(path, { mode: criteria.mode })
.then(checkDeferred.resolve, checkDeferred.reject);
} else {
// Directory exists, but we still don't
// know if it matches all criteria.
needToCheckMoreCriteria();
}
};
checkExistence();
checkExistence();
return checkDeferred.promise;
};
return checkDeferred.promise;
};
checkWhatWeHaveNow()
.then(checkWhatShouldBe)
.then(deferred.resolve, deferred.reject);
checkWhatWeHaveNow()
.then(checkWhatShouldBe)
.then(deferred.resolve, deferred.reject);
return deferred.promise;
return deferred.promise;
};

@@ -198,0 +192,0 @@

@@ -1,2 +0,2 @@

"use strict";
'use strict';

@@ -11,18 +11,17 @@ var fs = require('fs');

var sync = function (path) {
try {
var stat = fs.statSync(path);
if (stat.isDirectory()) {
return 'dir';
} else if (stat.isFile()) {
return 'file';
}
return 'other';
} catch (err) {
if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') {
throw err;
}
try {
var stat = fs.statSync(path);
if (stat.isDirectory()) {
return 'dir';
} else if (stat.isFile()) {
return 'file';
}
return 'other';
} catch (err) {
if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') {
throw err;
}
}
return false;
return false;
};

@@ -35,21 +34,21 @@

var async = function (path) {
var deferred = Q.defer();
var deferred = Q.defer();
fs.stat(path, function (err, stat) {
if (err) {
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {
deferred.resolve(false);
} else {
deferred.reject(err);
}
} else if (stat.isDirectory()) {
deferred.resolve('dir');
} else if (stat.isFile()) {
deferred.resolve('file');
} else {
deferred.resolve('other');
}
});
fs.stat(path, function (err, stat) {
if (err) {
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {
deferred.resolve(false);
} else {
deferred.reject(err);
}
} else if (stat.isDirectory()) {
deferred.resolve('dir');
} else if (stat.isFile()) {
deferred.resolve('file');
} else {
deferred.resolve('other');
}
});
return deferred.promise;
return deferred.promise;
};

@@ -56,0 +55,0 @@

// Simple operations on a file: read, write, append.
"use strict";
'use strict';

@@ -11,3 +11,3 @@ var fs = require('fs');

// Temporary file extensions used for atomic file overwriting.
var newExt = ".__new__";
var newExt = '.__new__';

@@ -17,31 +17,32 @@ // Matches strings generated by Date.toJSON()

var jsonDateParser = function (key, value) {
var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/;
if (typeof value === 'string') {
if (reISO.exec(value)) {
return new Date(value);
}
var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/;
if (typeof value === 'string') {
if (reISO.exec(value)) {
return new Date(value);
}
return value;
}
return value;
};
var processDataToWrite = function (data, options) {
// If data is a s simple object convert it to JSON.
if (typeof data === 'object'
&& !Buffer.isBuffer(data)
&& data !== null) {
var indent = options.jsonIndent;
if (typeof indent !== 'number') {
indent = 2;
}
data = JSON.stringify(data, null, indent);
var indent = options.jsonIndent;
// If data is a s simple object convert it to JSON.
if (typeof data === 'object'
&& !Buffer.isBuffer(data)
&& data !== null) {
if (typeof indent !== 'number') {
indent = 2;
}
return JSON.stringify(data, null, indent);
}
return data;
return data;
};
var makeNicerJsonParsingError = function (path, err) {
var nicerError = new Error('JSON parsing failed while reading '
+ path + ' [' + err + ']');
nicerError.originalError = err;
return nicerError;
var nicerError = new Error('JSON parsing failed while reading '
+ path + ' [' + err + ']');
nicerError.originalError = err;
return nicerError;
};

@@ -54,81 +55,85 @@

var readSync = function (path, returnAs) {
returnAs = returnAs || 'utf8';
var retAs = returnAs || 'utf8';
var data;
var encoding = 'utf8';
if (returnAs === 'buf') {
encoding = null;
}
var encoding = 'utf8';
if (retAs === 'buffer') {
encoding = null;
} else if (retAs === 'buf') {
console.warn("[fs-jetpack] DEPRECATION WARNING: Please use 'buffer' " +
"instead of 'buf' in read() method.");
encoding = null;
}
var data;
try {
data = fs.readFileSync(path, { encoding: encoding });
} catch (err) {
if (err.code === 'ENOENT') {
// If file doesn't exist just return null, no need to throw
data = null;
} else {
// Otherwise rethrow the error
throw err;
}
try {
data = fs.readFileSync(path, { encoding: encoding });
} catch (err) {
if (err.code === 'ENOENT') {
// If file doesn't exist just return null, no need to throw
data = null;
} else {
// Otherwise rethrow the error
throw err;
}
}
try {
if (returnAs === 'json') {
data = JSON.parse(data);
} else if (returnAs === 'jsonWithDates') {
data = JSON.parse(data, jsonDateParser);
}
} catch (err) {
throw makeNicerJsonParsingError(path, err);
try {
if (retAs === 'json') {
data = JSON.parse(data);
} else if (retAs === 'jsonWithDates') {
data = JSON.parse(data, jsonDateParser);
}
} catch (err) {
throw makeNicerJsonParsingError(path, err);
}
return data;
return data;
};
var writeFileSync = function (path, data, options) {
try {
fs.writeFileSync(path, data, options);
} catch (err) {
if (err.code === 'ENOENT') {
// Means parent directory doesn't exist, so create it and try again.
mkdirp.sync(pathUtil.dirname(path));
fs.writeFileSync(path, data, options);
} else {
throw err;
}
try {
fs.writeFileSync(path, data, options);
} catch (err) {
if (err.code === 'ENOENT') {
// Means parent directory doesn't exist, so create it and try again.
mkdirp.sync(pathUtil.dirname(path));
fs.writeFileSync(path, data, options);
} else {
throw err;
}
}
};
var writeAtomicSync = function (path, data, options) {
// we are assuming there is file on given path, and we don't want
// to touch it until we are sure our data has been saved correctly,
// so write the data into temporary file...
writeFileSync(path + newExt, data, options);
// ...next rename temp file to replace real path.
fs.renameSync(path + newExt, path);
// we are assuming there is file on given path, and we don't want
// to touch it until we are sure our data has been saved correctly,
// so write the data into temporary file...
writeFileSync(path + newExt, data, options);
// ...next rename temp file to replace real path.
fs.renameSync(path + newExt, path);
};
var writeSync = function (path, data, options) {
options = options || {};
data = processDataToWrite(data, options);
var opts = options || {};
var processedData = processDataToWrite(data, opts);
var writeStrategy = writeFileSync;
if (options.atomic) {
writeStrategy = writeAtomicSync;
}
writeStrategy(path, data, { mode: options.mode });
var writeStrategy = writeFileSync;
if (opts.atomic) {
writeStrategy = writeAtomicSync;
}
writeStrategy(path, processedData, { mode: opts.mode });
};
var appendSync = function (path, data, options) {
try {
fs.appendFileSync(path, data, options);
} catch (err) {
if (err.code === 'ENOENT') {
// Parent directory doesn't exist,
// so just create it and write the file.
writeFileSync(path, data, options);
} else {
throw err;
}
try {
fs.appendFileSync(path, data, options);
} catch (err) {
if (err.code === 'ENOENT') {
// Parent directory doesn't exist,
// so just create it and write the file.
writeFileSync(path, data, options);
} else {
throw err;
}
}
};

@@ -147,110 +152,112 @@

var readAsync = function (path, returnAs) {
var deferred = Q.defer();
var deferred = Q.defer();
returnAs = returnAs || 'utf8';
var retAs = returnAs || 'utf8';
var encoding = 'utf8';
if (retAs === 'buffer') {
encoding = null;
} else if (retAs === 'buf') {
console.warn("[fs-jetpack] DEPRECATION WARNING: Please use 'buffer' " +
"instead of 'buf' in read() method.");
encoding = null;
}
var encoding = 'utf8';
if (returnAs === 'buf') {
encoding = null;
promisedReadFile(path, { encoding: encoding })
.then(function (data) {
// Make final parsing of the data before returning.
try {
if (retAs === 'json') {
deferred.resolve(JSON.parse(data));
} else if (retAs === 'jsonWithDates') {
deferred.resolve(JSON.parse(data, jsonDateParser));
} else {
deferred.resolve(data);
}
} catch (err) {
deferred.reject(makeNicerJsonParsingError(path, err));
}
})
.catch(function (err) {
if (err.code === 'ENOENT') {
// If file doesn't exist just return null,
// no need to raise an error.
deferred.resolve(null);
} else {
// Otherwise throw
deferred.reject(err);
}
});
promisedReadFile(path, { encoding: encoding })
.then(function (data) {
// Make final parsing of the data before returning.
try {
if (returnAs === 'json') {
data = JSON.parse(data);
} else if (returnAs === 'jsonWithDates') {
data = JSON.parse(data, jsonDateParser);
}
deferred.resolve(data);
} catch (err) {
deferred.reject(makeNicerJsonParsingError(path, err));
}
})
.catch(function (err) {
if (err.code === 'ENOENT') {
// If file doesn't exist just return null,
// no need to raise an error.
deferred.resolve(null);
} else {
// Otherwise throw
deferred.reject(err);
}
});
return deferred.promise;
return deferred.promise;
};
var writeFileAsync = function (path, data, options) {
var deferred = Q.defer();
var deferred = Q.defer();
promisedWriteFile(path, data, options)
.then(deferred.resolve)
.catch(function (err) {
// First attempt to write a file ended with error.
// Check if this is not due to nonexistent parent directory.
if (err.code === 'ENOENT') {
// Parent directory doesn't exist, so create it and try again.
promisedMkdirp(pathUtil.dirname(path))
.then(function () {
return promisedWriteFile(path, data, options);
})
.then(deferred.resolve, deferred.reject);
} else {
// Nope, some other error, throw it.
deferred.reject(err);
}
});
promisedWriteFile(path, data, options)
.then(deferred.resolve)
.catch(function (err) {
// First attempt to write a file ended with error.
// Check if this is not due to nonexistent parent directory.
if (err.code === 'ENOENT') {
// Parent directory doesn't exist, so create it and try again.
promisedMkdirp(pathUtil.dirname(path))
.then(function () {
return promisedWriteFile(path, data, options);
})
.then(deferred.resolve, deferred.reject);
} else {
// Nope, some other error, throw it.
deferred.reject(err);
}
});
return deferred.promise;
return deferred.promise;
};
var writeAtomicAsync = function (path, data, options) {
var deferred = Q.defer();
var deferred = Q.defer();
// We are assuming there is file on given path, and we don't want
// to touch it until we are sure our data has been saved correctly,
// so write the data into temporary file...
writeFileAsync(path + newExt, data, options)
.then(function () {
// ...next rename temp file to real path.
return promisedRename(path + newExt, path);
})
.then(deferred.resolve, deferred.reject);
// We are assuming there is file on given path, and we don't want
// to touch it until we are sure our data has been saved correctly,
// so write the data into temporary file...
writeFileAsync(path + newExt, data, options)
.then(function () {
// ...next rename temp file to real path.
return promisedRename(path + newExt, path);
})
.then(deferred.resolve, deferred.reject);
return deferred.promise;
return deferred.promise;
};
var writeAsync = function (path, data, options) {
options = options || {};
data = processDataToWrite(data, options);
var opts = options || {};
var processedData = processDataToWrite(data, opts);
var writeStrategy = writeFileAsync;
if (options.atomic) {
writeStrategy = writeAtomicAsync;
}
return writeStrategy(path, data, { mode: options.mode });
var writeStrategy = writeFileAsync;
if (opts.atomic) {
writeStrategy = writeAtomicAsync;
}
return writeStrategy(path, processedData, { mode: opts.mode });
};
var appendAsync = function (path, data, options) {
var deferred = Q.defer();
var deferred = Q.defer();
promisedAppendFile(path, data, options)
.then(deferred.resolve, function (err) {
promisedAppendFile(path, data, options)
.then(deferred.resolve, function (err) {
if (err.code === 'ENOENT') {
// If parent directory doesn't exist create it.
promisedMkdirp(pathUtil.dirname(path))
.then(function () {
return appendAsync(path, data, options);
})
.then(deferred.resolve, deferred.reject);
} else {
deferred.reject(err);
}
});
if (err.code === 'ENOENT') {
// If parent directory doesn't exist create it.
promisedMkdirp(pathUtil.dirname(path))
.then(function () {
return appendAsync(path, data, options);
})
.then(deferred.resolve, deferred.reject);
} else {
deferred.reject(err);
}
});
return deferred.promise;
return deferred.promise;
};

@@ -257,0 +264,0 @@

@@ -1,2 +0,2 @@

"use strict";
'use strict';

@@ -11,9 +11,9 @@ var fs = require('fs');

function getCriteriaDefaults(criteria) {
if (criteria === undefined) {
criteria = {};
}
if (criteria.mode !== undefined) {
criteria.mode = modeUtils.normalizeFileMode(criteria.mode);
}
return criteria;
if (criteria === undefined) {
criteria = {};
}
if (criteria.mode !== undefined) {
criteria.mode = modeUtils.normalizeFileMode(criteria.mode);
}
return criteria;
}

@@ -26,50 +26,45 @@

var sync = function (path, criteria) {
criteria = getCriteriaDefaults(criteria);
criteria = getCriteriaDefaults(criteria);
try {
var stat = fs.statSync(path);
} catch (err) {
// Detection if path exists
if (err.code !== 'ENOENT') {
throw err;
}
try {
var stat = fs.statSync(path);
} catch (err) {
// Detection if path exists
if (err.code !== 'ENOENT') {
throw err;
}
}
if (stat && !stat.isFile()) {
// This have to be file, so if is directory must be removed.
rimraf.sync(path);
// Clear stat variable to indicate now nothing is there.
stat = undefined;
if (stat && !stat.isFile()) {
// This have to be file, so if is directory must be removed.
rimraf.sync(path);
// Clear stat variable to indicate now nothing is there.
stat = undefined;
}
if (stat) {
// Ensure file mode
var mode = modeUtils.normalizeFileMode(stat.mode);
if (criteria.mode !== undefined && criteria.mode !== mode) {
fs.chmodSync(path, criteria.mode);
}
if (stat) {
// Ensure file mode
var mode = modeUtils.normalizeFileMode(stat.mode);
if (criteria.mode !== undefined && criteria.mode !== mode) {
fs.chmodSync(path, criteria.mode);
}
// Ensure file content
if (criteria.content !== undefined) {
fileOps.write(path, criteria.content, {
mode: mode,
jsonIndent: criteria.jsonIndent,
});
}
} else {
// File doesn't exist. Create it.
var content = '';
if (criteria.content !== undefined) {
content = criteria.content;
}
fileOps.write(path, content, {
mode: criteria.mode,
jsonIndent: criteria.jsonIndent,
});
// Ensure file content
if (criteria.content !== undefined) {
fileOps.write(path, criteria.content, {
mode: mode,
jsonIndent: criteria.jsonIndent
});
}
} else {
// File doesn't exist. Create it.
var content = '';
if (criteria.content !== undefined) {
content = criteria.content;
}
fileOps.write(path, content, {
mode: criteria.mode,
jsonIndent: criteria.jsonIndent
});
}
};

@@ -86,91 +81,87 @@

var async = function (path, criteria) {
var deferred = Q.defer();
var deferred = Q.defer();
criteria = getCriteriaDefaults(criteria);
criteria = getCriteriaDefaults(criteria);
var checkWhatWeHaveNow = function () {
var checkDeferred = Q.defer();
var checkWhatWeHaveNow = function () {
var checkDeferred = Q.defer();
promisedStat(path)
.then(function (stat) {
if (stat.isDirectory()) {
// This is not a file, so remove it.
promisedRimraf(path)
.then(function () {
// Clear stat variable to indicate now nothing is there
checkDeferred.resolve(undefined);
})
.catch(checkDeferred.reject);
} else {
checkDeferred.resolve(stat);
}
promisedStat(path)
.then(function (stat) {
if (stat.isDirectory()) {
// This is not a file, so remove it.
promisedRimraf(path)
.then(function () {
// Clear stat variable to indicate now nothing is there
checkDeferred.resolve(undefined);
})
.catch(function (err) {
if (err.code === 'ENOENT') {
// Path doesn't exist.
checkDeferred.resolve(undefined);
} else {
// This is other error. Must end here.
checkDeferred.reject(err);
}
});
.catch(checkDeferred.reject);
} else {
checkDeferred.resolve(stat);
}
})
.catch(function (err) {
if (err.code === 'ENOENT') {
// Path doesn't exist.
checkDeferred.resolve(undefined);
} else {
// This is other error. Must end here.
checkDeferred.reject(err);
}
});
return checkDeferred.promise;
};
return checkDeferred.promise;
};
var checkWhatShouldBe = function (stat) {
var checkDeferred = Q.defer();
var checkWhatShouldBe = function (stat) {
var checkDeferred = Q.defer();
if (!stat) {
if (!stat) {
// Path doesn't exist now. Put file there.
var content = '';
if (criteria.content !== undefined) {
content = criteria.content;
}
fileOps.writeAsync(path, content, {
mode: criteria.mode,
jsonIndent: criteria.jsonIndent
})
.then(checkDeferred.resolve, checkDeferred.reject);
} else {
// File already exists. Must do more checking.
// Path doesn't exist now. Put file there.
var mode = modeUtils.normalizeFileMode(stat.mode);
var content = '';
if (criteria.content !== undefined) {
content = criteria.content;
}
fileOps.writeAsync(path, content, {
mode: criteria.mode,
jsonIndent: criteria.jsonIndent,
})
.then(checkDeferred.resolve, checkDeferred.reject);
var checkMode = function () {
if (criteria.mode !== undefined && criteria.mode !== mode) {
promisedChmod(path, criteria.mode)
.then(checkDeferred.resolve, checkDeferred.reject);
} else {
checkDeferred.resolve();
}
};
var checkContent = function () {
if (criteria.content !== undefined) {
fileOps.writeAsync(path, criteria.content, {
mode: mode,
jsonIndent: criteria.jsonIndent
})
.then(checkDeferred.resolve, checkDeferred.reject);
} else {
checkMode();
}
};
// File already exists. Must do more checking.
checkContent();
}
var mode = modeUtils.normalizeFileMode(stat.mode);
return checkDeferred.promise;
};
var checkMode = function () {
if (criteria.mode !== undefined && criteria.mode !== mode) {
promisedChmod(path, criteria.mode)
.then(checkDeferred.resolve, checkDeferred.reject);
} else {
checkDeferred.resolve();
}
};
checkWhatWeHaveNow()
.then(checkWhatShouldBe)
.then(deferred.resolve, deferred.reject);
var checkContent = function () {
if (criteria.content !== undefined) {
fileOps.writeAsync(path, criteria.content, {
mode: mode,
jsonIndent: criteria.jsonIndent,
})
.then(checkDeferred.resolve, checkDeferred.reject);
} else {
checkMode();
}
};
checkContent();
}
return checkDeferred.promise;
};
checkWhatWeHaveNow()
.then(checkWhatShouldBe)
.then(deferred.resolve, deferred.reject);
return deferred.promise;
return deferred.promise;
};

@@ -177,0 +168,0 @@

@@ -1,3 +0,4 @@

"use strict";
'use strict';
var pathUtil = require('path');
var Q = require('q');

@@ -7,37 +8,48 @@ var inspector = require('./inspector');

var normalizeOptions = function (options) {
var opts = options || {};
// defaults:
if (opts.files === undefined) {
opts.files = true;
}
if (opts.directories === undefined) {
opts.directories = false;
}
return opts;
};
var filterTree = function (tree, options) {
var matchesAnyOfGlobs = matcher.create(options.matching, tree.absolutePath);
var matchesAnyOfGlobs = matcher.create(options.matching, tree.absolutePath);
return inspector.utils.flattenTree(tree).filter(function (inspectObj) {
return matchesAnyOfGlobs(inspectObj.absolutePath);
});
return inspector.utils.flattenTree(tree)
.filter(function (inspectObj) {
return matchesAnyOfGlobs(inspectObj.absolutePath);
})
.filter(function (inspectObj) {
if (inspectObj.type === 'file' && options.files === true) {
return true;
}
if (inspectObj.type === 'dir' && options.directories === true) {
return true;
}
return false;
});
};
var processFoundObjects = function (foundObjects, returnAs) {
returnAs = returnAs || 'absolutePath';
switch (returnAs) {
case 'absolutePath':
return foundObjects.map(function (inspectObj) {
return inspectObj.absolutePath;
});
case 'relativePath':
return foundObjects.map(function (inspectObj) {
return inspectObj.relativePath;
});
case 'inspect':
return foundObjects;
}
var processFoundObjects = function (foundObjects, cwd) {
return foundObjects.map(function (inspectObj) {
return pathUtil.relative(cwd, inspectObj.absolutePath);
});
};
var generatePathDoesntExistError = function (path) {
var err = new Error("Path you want to find stuff in doesn't exist " + path);
err.code = 'ENOENT';
return err;
var err = new Error("Path you want to find stuff in doesn't exist " + path);
err.code = 'ENOENT';
return err;
};
var generatePathNotDirectoryError = function (path) {
var err = new Error("Path you want to find stuff in must be a directory " + path);
err.code = 'ENOTDIR';
return err;
var err = new Error('Path you want to find stuff in must be a directory ' + path);
err.code = 'ENOTDIR';
return err;
};

@@ -49,17 +61,18 @@

var sync = function (path, options, returnAs) {
var sync = function (path, options) {
var foundInspectObjects;
var tree;
var tree = inspector.tree(path, {
relativePath: true,
absolutePath: true,
});
tree = inspector.tree(path, {
absolutePath: true
});
if (tree === null) {
throw generatePathDoesntExistError(path);
} else if (tree.type !== 'dir') {
throw generatePathNotDirectoryError(path);
}
if (tree === null) {
throw generatePathDoesntExistError(path);
} else if (tree.type !== 'dir') {
throw generatePathNotDirectoryError(path);
}
var foundInspectObjects = filterTree(tree, options);
return processFoundObjects(foundInspectObjects, returnAs);
foundInspectObjects = filterTree(tree, normalizeOptions(options));
return processFoundObjects(foundInspectObjects, options.cwd);
};

@@ -71,23 +84,26 @@

var async = function (path, options, returnAs) {
var deferred = Q.defer();
var async = function (path, options) {
var deferred = Q.defer();
inspector.treeAsync(path, {
relativePath: true,
absolutePath: true,
})
.then(function (tree) {
if (tree === null) {
throw generatePathDoesntExistError(path);
} else if (tree.type !== 'dir') {
throw generatePathNotDirectoryError(path);
}
inspector.treeAsync(path, {
relativePath: true,
absolutePath: true
})
.then(function (tree) {
var foundInspectObjects;
var toReturn;
var foundInspectObjects = filterTree(tree, options);
var toReturn = processFoundObjects(foundInspectObjects, returnAs);
deferred.resolve(toReturn);
})
.catch(deferred.reject);
if (tree === null) {
throw generatePathDoesntExistError(path);
} else if (tree.type !== 'dir') {
throw generatePathNotDirectoryError(path);
}
return deferred.promise;
foundInspectObjects = filterTree(tree, normalizeOptions(options));
toReturn = processFoundObjects(foundInspectObjects, options.cwd);
deferred.resolve(toReturn);
})
.catch(deferred.reject);
return deferred.promise;
};

@@ -94,0 +110,0 @@

@@ -1,2 +0,2 @@

"use strict";
'use strict';

@@ -9,32 +9,32 @@ var fs = require('fs');

var createInspectObj = function (path, options, stat) {
var obj = {};
var obj = {};
obj.name = pathUtil.basename(path);
obj.name = pathUtil.basename(path);
if (stat.isFile()) {
obj.type = 'file';
obj.size = stat.size;
} else if (stat.isDirectory()) {
obj.type = 'dir';
} else if (stat.isSymbolicLink()) {
obj.type = 'symlink';
} else {
obj.type = 'other';
}
if (stat.isFile()) {
obj.type = 'file';
obj.size = stat.size;
} else if (stat.isDirectory()) {
obj.type = 'dir';
} else if (stat.isSymbolicLink()) {
obj.type = 'symlink';
} else {
obj.type = 'other';
}
if (options.mode) {
obj.mode = stat.mode;
}
if (options.mode) {
obj.mode = stat.mode;
}
if (options.times) {
obj.accessTime = stat.atime;
obj.modifyTime = stat.mtime;
obj.changeTime = stat.ctime;
}
if (options.times) {
obj.accessTime = stat.atime;
obj.modifyTime = stat.mtime;
obj.changeTime = stat.ctime;
}
if (options.absolutePath) {
obj.absolutePath = path;
}
if (options.absolutePath) {
obj.absolutePath = path;
}
return obj;
return obj;
};

@@ -45,7 +45,7 @@

var checksumOfDir = function (inspectList, algo) {
var hash = crypto.createHash(algo);
inspectList.forEach(function (inspectObj) {
hash.update(inspectObj.name + inspectObj[algo]);
});
return hash.digest('hex');
var hash = crypto.createHash(algo);
inspectList.forEach(function (inspectObj) {
hash.update(inspectObj.name + inspectObj[algo]);
});
return hash.digest('hex');
};

@@ -55,14 +55,14 @@

var flattenTree = function (tree) {
var treeAsList = [];
var treeAsList = [];
var crawl = function (inspectObj) {
treeAsList.push(inspectObj);
if (inspectObj.children) {
inspectObj.children.forEach(crawl);
}
};
var crawl = function (inspectObj) {
treeAsList.push(inspectObj);
if (inspectObj.children) {
inspectObj.children.forEach(crawl);
}
};
crawl(tree);
crawl(tree);
return treeAsList;
return treeAsList;
};

@@ -75,123 +75,107 @@

var fileChecksum = function (path, algo) {
var hash = crypto.createHash(algo);
var data = fs.readFileSync(path);
hash.update(data);
return hash.digest('hex');
var hash = crypto.createHash(algo);
var data = fs.readFileSync(path);
hash.update(data);
return hash.digest('hex');
};
var inspectSync = function (path, options) {
options = options || {};
options = options || {};
var statFlavour = fs.statSync;
if (options.symlinks) {
statFlavour = fs.lstatSync;
}
var statFlavour = fs.statSync;
if (options.symlinks) {
statFlavour = fs.lstatSync;
}
try {
var stat = statFlavour(path);
} catch (err) {
// Detection if path exists
if (err.code === 'ENOENT') {
// Doesn't exist. Return null instead of throwing.
return null;
}
throw err;
try {
var stat = statFlavour(path);
} catch (err) {
// Detection if path exists
if (err.code === 'ENOENT') {
// Doesn't exist. Return null instead of throwing.
return null;
}
throw err;
}
var inspectObj = createInspectObj(path, options, stat);
var inspectObj = createInspectObj(path, options, stat);
if (inspectObj.type === 'file' && options.checksum) {
inspectObj[options.checksum] = fileChecksum(path, options.checksum);
} else if (inspectObj.type === 'symlink') {
inspectObj.pointsAt = fs.readlinkSync(path);
}
if (inspectObj.type === 'file' && options.checksum) {
inspectObj[options.checksum] = fileChecksum(path, options.checksum);
} else if (inspectObj.type === 'symlink') {
inspectObj.pointsAt = fs.readlinkSync(path);
}
return inspectObj;
return inspectObj;
};
var listSync = function (path, useInspect) {
try {
var simpleList = fs.readdirSync(path);
} catch (err) {
// Detection if path exists
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {
// Doesn't exist or is a file, not directory.
// Return null instead of throwing.
return null;
}
throw err;
var listSync = function (path) {
try {
return fs.readdirSync(path);
} catch (err) {
// Detection if path exists
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {
// Doesn't exist or is a file, not directory.
// Return null instead of throwing.
return null;
}
if (!useInspect) {
return simpleList;
}
var inspectConfig = {};
if (typeof useInspect === 'object') {
// useInspec contains config
inspectConfig = useInspect;
}
var inspectedList = simpleList.map(function (filename) {
return inspectSync(pathUtil.join(path, filename), inspectConfig);
});
return inspectedList;
throw err;
}
};
var crawlTreeSync = function (path, options, parent) {
var treeBranch = inspectSync(path, options);
var treeBranch = inspectSync(path, options);
if (treeBranch) {
if (treeBranch) {
if (options.relativePath) {
if (!parent) {
treeBranch.relativePath = '.';
} else {
treeBranch.relativePath = parent.relativePath + '/' + pathUtil.basename(path);
}
}
if (options.relativePath) {
if (!parent) {
treeBranch.relativePath = '.';
} else {
treeBranch.relativePath = parent.relativePath + '/' + pathUtil.basename(path);
}
}
if (treeBranch.type === 'dir') {
treeBranch.size = 0;
if (treeBranch.type === 'dir') {
treeBranch.size = 0;
// Process all children
treeBranch.children = listSync(path).map(function (filename) {
// Go one level deeper with crawling
var treeSubBranch = crawlTreeSync(pathUtil.join(path, filename), options, treeBranch);
// Add together all childrens' size
treeBranch.size += treeSubBranch.size || 0;
// Process all children
treeBranch.children = listSync(path).map(function (filename) {
// Go one level deeper with crawling
var treeSubBranch = crawlTreeSync(pathUtil.join(path, filename), options, treeBranch);
// Add together all childrens' size
treeBranch.size += treeSubBranch.size || 0;
return treeSubBranch;
});
return treeSubBranch;
});
if (options.checksum) {
treeBranch[options.checksum] = checksumOfDir(treeBranch.children, options.checksum);
}
}
if (options.checksum) {
treeBranch[options.checksum] = checksumOfDir(treeBranch.children, options.checksum);
}
}
}
return treeBranch;
return treeBranch;
};
var treeSync = function (path, options) {
options = options || {};
options.symlinks = true;
options = options || {};
options.symlinks = true;
return crawlTreeSync(path, options, null);
return crawlTreeSync(path, options, null);
};
var createTreeWalkerSync = function (startPath) {
var allFiles = flattenTree(treeSync(startPath, {
absolutePath: true,
relativePath: true,
mode: true,
}));
return {
hasNext: function () {
return allFiles.length > 0;
},
getNext: function () {
return allFiles.shift();
},
};
var allFiles = flattenTree(treeSync(startPath, {
absolutePath: true,
relativePath: true,
mode: true
}));
return {
hasNext: function () {
return allFiles.length > 0;
},
getNext: function () {
return allFiles.shift();
}
};
};

@@ -209,205 +193,174 @@

var fileChecksumAsync = function (path, algo) {
var deferred = Q.defer();
var deferred = Q.defer();
var hash = crypto.createHash(algo);
var s = fs.createReadStream(path);
s.on('data', function (data) {
hash.update(data);
});
s.on('end', function () {
deferred.resolve(hash.digest('hex'));
});
s.on('error', deferred.reject);
var hash = crypto.createHash(algo);
var s = fs.createReadStream(path);
s.on('data', function (data) {
hash.update(data);
});
s.on('end', function () {
deferred.resolve(hash.digest('hex'));
});
s.on('error', deferred.reject);
return deferred.promise;
return deferred.promise;
};
var inspectAsync = function (path, options) {
var deferred = Q.defer();
var deferred = Q.defer();
options = options || {};
options = options || {};
var statFlavour = promisedStat;
if (options.symlinks) {
statFlavour = promisedLstat;
var statFlavour = promisedStat;
if (options.symlinks) {
statFlavour = promisedLstat;
}
statFlavour(path)
.then(function (stat) {
var inspectObj = createInspectObj(path, options, stat);
if (inspectObj.type === 'file' && options.checksum) {
fileChecksumAsync(path, options.checksum)
.then(function (checksum) {
inspectObj[options.checksum] = checksum;
deferred.resolve(inspectObj);
})
.catch(deferred.reject);
} else if (inspectObj.type === 'symlink') {
promisedReadlink(path)
.then(function (linkPath) {
inspectObj.pointsAt = linkPath;
deferred.resolve(inspectObj);
})
.catch(deferred.reject);
} else {
deferred.resolve(inspectObj);
}
})
.catch(function (err) {
// Detection if path exists
if (err.code === 'ENOENT') {
// Doesn't exist. Return null instead of throwing.
deferred.resolve(null);
} else {
deferred.reject(err);
}
});
statFlavour(path)
.then(function (stat) {
var inspectObj = createInspectObj(path, options, stat);
if (inspectObj.type === 'file' && options.checksum) {
fileChecksumAsync(path, options.checksum)
.then(function (checksum) {
inspectObj[options.checksum] = checksum;
deferred.resolve(inspectObj);
})
.catch(deferred.reject);
} else if (inspectObj.type === 'symlink') {
promisedReadlink(path)
.then(function (linkPath) {
inspectObj.pointsAt = linkPath;
deferred.resolve(inspectObj);
})
.catch(deferred.reject);
} else {
deferred.resolve(inspectObj);
}
})
.catch(function (err) {
// Detection if path exists
if (err.code === 'ENOENT') {
// Doesn't exist. Return null instead of throwing.
deferred.resolve(null);
} else {
deferred.reject(err);
}
});
return deferred.promise;
return deferred.promise;
};
var listAsync = function (path, useInspect) {
var deferred = Q.defer();
var listAsync = function (path) {
var deferred = Q.defer();
var turnSimpleListIntoInspectObjectsList = function (pathsList) {
var inspectConfig = {};
if (typeof useInspect === 'object') {
// useInspec contains config
inspectConfig = useInspect;
}
promisedReaddir(path)
.then(function (list) {
deferred.resolve(list);
})
.catch(function (err) {
// Detection if path exists
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {
// Doesn't exist or is a file, not directory.
// Return null instead of throwing.
deferred.resolve(null);
} else {
deferred.reject(err);
}
});
var doOne = function (index) {
if (index === pathsList.length) {
deferred.resolve(pathsList);
} else {
var itemPath = pathUtil.join(path, pathsList[index]);
inspectAsync(itemPath, inspectConfig)
.then(function (inspectObj) {
pathsList[index] = inspectObj;
doOne(index + 1);
})
.catch(deferred.reject);
}
};
doOne(0);
};
promisedReaddir(path)
.then(function (simpleList) {
if (!useInspect) {
// Only list of paths is required. We are done.
deferred.resolve(simpleList);
} else {
turnSimpleListIntoInspectObjectsList(simpleList);
}
})
.catch(function (err) {
// Detection if path exists
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {
// Doesn't exist or is a file, not directory.
// Return null instead of throwing.
deferred.resolve(null);
} else {
deferred.reject(err);
}
});
return deferred.promise;
return deferred.promise;
};
var crawlTreeAsync = function (path, options, parent) {
var deferred = Q.defer();
var deferred = Q.defer();
inspectAsync(path, options)
.then(function (treeBranch) {
inspectAsync(path, options)
.then(function (treeBranch) {
if (!treeBranch) {
// Given path doesn't exist, or it is a file. We are done.
deferred.resolve(treeBranch);
return;
}
if (!treeBranch) {
// Given path doesn't exist, or it is a file. We are done.
deferred.resolve(treeBranch);
return;
}
if (options.relativePath) {
if (!parent) {
treeBranch.relativePath = '.';
} else {
treeBranch.relativePath = parent.relativePath + '/' + pathUtil.basename(path);
}
}
if (options.relativePath) {
if (!parent) {
treeBranch.relativePath = '.';
} else {
treeBranch.relativePath = parent.relativePath + '/' + pathUtil.basename(path);
}
}
if (treeBranch.type !== 'dir') {
// This is a file, we are done here.
deferred.resolve(treeBranch);
return;
}
if (treeBranch.type !== 'dir') {
// This is a file, we are done here.
deferred.resolve(treeBranch);
return;
}
// Ok, this is a directory, must inspect all its children as well.
// Ok, this is a directory, must inspect all its children as well.
listAsync(path)
.then(function (children) {
treeBranch.children = children;
treeBranch.size = 0;
listAsync(path)
.then(function (children) {
treeBranch.children = children;
treeBranch.size = 0;
var done = function () {
if (options.checksum) {
// We are done, but still have to calculate checksum of whole directory.
treeBranch[options.checksum] = checksumOfDir(treeBranch.children, options.checksum);
}
var done = function () {
if (options.checksum) {
// We are done, but still have to calculate checksum of whole directory.
treeBranch[options.checksum] = checksumOfDir(treeBranch.children, options.checksum);
}
deferred.resolve(treeBranch);
};
deferred.resolve(treeBranch);
};
var doOne = function (index) {
if (index === children.length) {
done();
} else {
var subPath = pathUtil.join(path, children[index]);
crawlTreeAsync(subPath, options, treeBranch)
.then(function (treeSubBranch) {
children[index] = treeSubBranch;
treeBranch.size += treeSubBranch.size || 0;
doOne(index + 1);
})
.catch(deferred.reject);
}
};
var doOne = function (index) {
if (index === children.length) {
done();
} else {
var subPath = pathUtil.join(path, children[index]);
crawlTreeAsync(subPath, options, treeBranch)
.then(function (treeSubBranch) {
children[index] = treeSubBranch;
treeBranch.size += treeSubBranch.size || 0;
doOne(index + 1);
})
.catch(deferred.reject);
}
};
doOne(0);
});
})
.catch(deferred.reject);
doOne(0);
});
})
.catch(deferred.reject);
return deferred.promise;
return deferred.promise;
};
var treeAsync = function (path, options) {
options = options || {};
options.symlinks = true;
options = options || {};
options.symlinks = true;
return crawlTreeAsync(path, options);
return crawlTreeAsync(path, options);
};
var createTreeWalkerAsync = function (startPath) {
var deferred = Q.defer();
var deferred = Q.defer();
treeAsync(startPath, {
absolutePath: true,
relativePath: true,
mode: true,
})
.then(function (wholeTree) {
var allFiles = flattenTree(wholeTree);
deferred.resolve({
hasNext: function () {
return allFiles.length > 0;
},
getNext: function () {
return allFiles.shift();
},
});
treeAsync(startPath, {
absolutePath: true,
relativePath: true,
mode: true
})
.then(function (wholeTree) {
var allFiles = flattenTree(wholeTree);
deferred.resolve({
hasNext: function () {
return allFiles.length > 0;
},
getNext: function () {
return allFiles.shift();
}
});
});
return deferred.promise;
return deferred.promise;
};

@@ -430,3 +383,3 @@

module.exports.utils = {
flattenTree: flattenTree,
flattenTree: flattenTree
};

@@ -1,4 +0,4 @@

// The main thing. Here everything starts.
/* eslint no-param-reassign:0 */
"use strict";
'use strict';

@@ -24,178 +24,193 @@ var pathUtil = require('path');

var jetpackContext = function (cwdPath) {
var getCwdPath = function () {
return cwdPath || process.cwd();
};
var getCwdPath = function () {
return cwdPath || process.cwd();
};
var cwd = function () {
var args;
var pathParts;
var cwd = function () {
// return current CWD if no arguments specified...
if (arguments.length === 0) {
return getCwdPath();
}
// ...create new CWD context otherwise
var args = Array.prototype.slice.call(arguments);
var pathParts = [getCwdPath()].concat(args);
return jetpackContext(pathUtil.resolve.apply(null, pathParts));
};
// return current CWD if no arguments specified...
if (arguments.length === 0) {
return getCwdPath();
}
// resolves path to inner CWD path of this jetpack instance
var resolvePath = function (path) {
return pathUtil.resolve(getCwdPath(), path);
};
// ...create new CWD context otherwise
args = Array.prototype.slice.call(arguments);
pathParts = [getCwdPath()].concat(args);
return jetpackContext(pathUtil.resolve.apply(null, pathParts));
};
var getPath = function () {
// add CWD base path as first element of arguments array
Array.prototype.unshift.call(arguments, getCwdPath());
return pathUtil.resolve.apply(null, arguments);
};
// resolves path to inner CWD path of this jetpack instance
var resolvePath = function (path) {
return pathUtil.resolve(getCwdPath(), path);
};
var normalizeOptions = function (options) {
options = options || {};
options.cwd = getCwdPath();
return options;
};
var getPath = function () {
// add CWD base path as first element of arguments array
Array.prototype.unshift.call(arguments, getCwdPath());
return pathUtil.resolve.apply(null, arguments);
};
// API
var normalizeOptions = function (options) {
var opts = options || {};
opts.cwd = getCwdPath();
return opts;
};
return {
cwd: cwd,
path: getPath,
// API
append: function (path, data, options) {
fileOps.append(resolvePath(path), data, options);
},
appendAsync: function (path, data, options) {
return fileOps.appendAsync(resolvePath(path), data, options);
},
return {
cwd: cwd,
path: getPath,
copy: function (from, to, options) {
options = normalizeOptions(options);
copy.sync(resolvePath(from), resolvePath(to), options);
},
copyAsync: function (from, to, options) {
options = normalizeOptions(options);
return copy.async(resolvePath(from), resolvePath(to), options);
},
append: function (path, data, options) {
fileOps.append(resolvePath(path), data, options);
},
appendAsync: function (path, data, options) {
return fileOps.appendAsync(resolvePath(path), data, options);
},
createWriteStream: function (path, options) {
return streams.createWriteStream(resolvePath(path), options);
},
createReadStream: function (path, options) {
return streams.createReadStream(resolvePath(path), options);
},
copy: function (from, to, options) {
var normalizedOptions = normalizeOptions(options);
copy.sync(resolvePath(from), resolvePath(to), normalizedOptions);
},
copyAsync: function (from, to, options) {
var normalizedOptions = normalizeOptions(options);
return copy.async(resolvePath(from), resolvePath(to), normalizedOptions);
},
dir: function (path, criteria) {
var normalizedPath = resolvePath(path);
dir.sync(normalizedPath, criteria);
return cwd(normalizedPath);
},
dirAsync: function (path, criteria) {
var deferred = Q.defer();
var normalizedPath = resolvePath(path);
dir.async(normalizedPath, criteria)
.then(function () {
deferred.resolve(cwd(normalizedPath));
}, deferred.reject);
return deferred.promise;
},
createWriteStream: function (path, options) {
return streams.createWriteStream(resolvePath(path), options);
},
createReadStream: function (path, options) {
return streams.createReadStream(resolvePath(path), options);
},
exists: function (path) {
return exists.sync(resolvePath(path));
},
existsAsync: function (path) {
return exists.async(resolvePath(path));
},
dir: function (path, criteria) {
var normalizedPath = resolvePath(path);
dir.sync(normalizedPath, criteria);
return cwd(normalizedPath);
},
dirAsync: function (path, criteria) {
var deferred = Q.defer();
var normalizedPath = resolvePath(path);
dir.async(normalizedPath, criteria)
.then(function () {
deferred.resolve(cwd(normalizedPath));
}, deferred.reject);
return deferred.promise;
},
file: function (path, criteria) {
file.sync(resolvePath(path), criteria);
return this;
},
fileAsync: function (path, criteria) {
var deferred = Q.defer();
var that = this;
file.async(resolvePath(path), criteria)
.then(function () {
deferred.resolve(that);
}, deferred.reject);
return deferred.promise;
},
exists: function (path) {
return exists.sync(resolvePath(path));
},
existsAsync: function (path) {
return exists.async(resolvePath(path));
},
find: function (startPath, options, returnAs) {
options = normalizeOptions(options);
return find.sync(resolvePath(startPath), options, returnAs);
},
findAsync: function (startPath, options, returnAs) {
options = normalizeOptions(options);
return find.async(resolvePath(startPath), options, returnAs);
},
file: function (path, criteria) {
file.sync(resolvePath(path), criteria);
return this;
},
fileAsync: function (path, criteria) {
var deferred = Q.defer();
var that = this;
file.async(resolvePath(path), criteria)
.then(function () {
deferred.resolve(that);
}, deferred.reject);
return deferred.promise;
},
inspect: function (path, fieldsToInclude) {
return inspector.inspect(resolvePath(path), fieldsToInclude);
},
inspectAsync: function (path, fieldsToInclude) {
return inspector.inspectAsync(resolvePath(path), fieldsToInclude);
},
find: function (startPath, options) {
// startPath is optional parameter, if not specified move rest of params
// to proper places and default startPath to CWD.
if (typeof startPath !== 'string') {
options = startPath;
startPath = '.';
}
return find.sync(resolvePath(startPath), normalizeOptions(options));
},
findAsync: function (startPath, options) {
// startPath is optional parameter, if not specified move rest of params
// to proper places and default startPath to CWD.
if (typeof startPath !== 'string') {
options = startPath;
startPath = '.';
}
return find.async(resolvePath(startPath), normalizeOptions(options));
},
inspectTree: function (path, options) {
return inspector.tree(resolvePath(path), options);
},
inspectTreeAsync: function (path, options) {
return inspector.treeAsync(resolvePath(path), options);
},
inspect: function (path, fieldsToInclude) {
return inspector.inspect(resolvePath(path), fieldsToInclude);
},
inspectAsync: function (path, fieldsToInclude) {
return inspector.inspectAsync(resolvePath(path), fieldsToInclude);
},
list: function (path, useInspect) {
return inspector.list(resolvePath(path), useInspect);
},
listAsync: function (path, useInspect) {
return inspector.listAsync(resolvePath(path), useInspect);
},
inspectTree: function (path, options) {
return inspector.tree(resolvePath(path), options);
},
inspectTreeAsync: function (path, options) {
return inspector.treeAsync(resolvePath(path), options);
},
move: function (from, to) {
move.sync(resolvePath(from), resolvePath(to));
},
moveAsync: function (from, to) {
return move.async(resolvePath(from), resolvePath(to));
},
list: function (path) {
return inspector.list(resolvePath(path || '.'));
},
listAsync: function (path) {
return inspector.listAsync(resolvePath(path || '.'));
},
read: function (path, returnAs) {
return fileOps.read(resolvePath(path), returnAs);
},
readAsync: function (path, returnAs) {
return fileOps.readAsync(resolvePath(path), returnAs);
},
move: function (from, to) {
move.sync(resolvePath(from), resolvePath(to));
},
moveAsync: function (from, to) {
return move.async(resolvePath(from), resolvePath(to));
},
remove: function (path) {
remove.sync(resolvePath(path));
},
removeAsync: function (path) {
return remove.async(resolvePath(path));
},
read: function (path, returnAs) {
return fileOps.read(resolvePath(path), returnAs);
},
readAsync: function (path, returnAs) {
return fileOps.readAsync(resolvePath(path), returnAs);
},
rename: function (path, newName) {
path = resolvePath(path);
var newPath = pathUtil.join(pathUtil.dirname(path), newName);
move.sync(path, newPath);
},
renameAsync: function (path, newName) {
path = resolvePath(path);
var newPath = pathUtil.join(pathUtil.dirname(path), newName);
return move.async(path, newPath);
},
remove: function (path) {
// If path not specified defaults to CWD
remove.sync(resolvePath(path || '.'));
},
removeAsync: function (path) {
// If path not specified defaults to CWD
return remove.async(resolvePath(path || '.'));
},
symlink: function (symlinkValue, path) {
symlink.sync(symlinkValue, resolvePath(path));
},
symlinkAsync: function (symlinkValue, path) {
return symlink.async(symlinkValue, resolvePath(path));
},
rename: function (path, newName) {
var resolvedPath = resolvePath(path);
var newPath = pathUtil.join(pathUtil.dirname(resolvedPath), newName);
move.sync(resolvedPath, newPath);
},
renameAsync: function (path, newName) {
var resolvedPath = resolvePath(path);
var newPath = pathUtil.join(pathUtil.dirname(resolvedPath), newName);
return move.async(resolvedPath, newPath);
},
write: function (path, data, options) {
fileOps.write(resolvePath(path), data, options);
},
writeAsync: function (path, data, options) {
return fileOps.writeAsync(resolvePath(path), data, options);
},
};
symlink: function (symlinkValue, path) {
symlink.sync(symlinkValue, resolvePath(path));
},
symlinkAsync: function (symlinkValue, path) {
return symlink.async(symlinkValue, resolvePath(path));
},
write: function (path, data, options) {
fileOps.write(resolvePath(path), data, options);
},
writeAsync: function (path, data, options) {
return fileOps.writeAsync(resolvePath(path), data, options);
}
};
};
module.exports = jetpackContext;

@@ -1,2 +0,2 @@

"use strict";
'use strict';

@@ -10,5 +10,5 @@ var pathUtil = require('path');

var generateSourceDoesntExistError = function (path) {
var err = new Error("Path to move doesn't exist " + path);
err.code = 'ENOENT';
return err;
var err = new Error("Path to move doesn't exist " + path);
err.code = 'ENOENT';
return err;
};

@@ -21,22 +21,22 @@

var sync = function (from, to) {
try {
try {
fs.renameSync(from, to);
} catch (err) {
if (err.code !== 'ENOENT') {
// We can't make sense of this error. Rethrow it.
throw err;
} else {
// Ok, source or destination path doesn't exist.
// Must do more investigation.
if (!exists.sync(from)) {
throw generateSourceDoesntExistError(from);
}
if (!exists.sync(to)) {
var destDir = pathUtil.dirname(to);
mkdirp.sync(destDir);
// Retry the attempt
fs.renameSync(from, to);
} catch (err) {
if (err.code !== 'ENOENT') {
// We can't make sense of this error. Rethrow it.
throw err;
} else {
// Ok, source or destination path doesn't exist.
// Must do more investigation.
if (!exists.sync(from)) {
throw generateSourceDoesntExistError(from);
}
if (!exists.sync(to)) {
var destDir = pathUtil.dirname(to);
mkdirp.sync(destDir);
// Retry the attempt
fs.renameSync(from, to);
}
}
}
}
}
};

@@ -52,50 +52,50 @@

var ensureDestinationPathExistsAsync = function (to) {
var deferred = Q.defer();
var deferred = Q.defer();
var destDir = pathUtil.dirname(to);
exists.async(destDir)
.then(function (dstExists) {
if (!dstExists) {
promisedMkdirp(destDir)
.then(deferred.resolve, deferred.reject);
} else {
// Hah, no idea.
deferred.reject();
}
})
.catch(deferred.reject);
var destDir = pathUtil.dirname(to);
exists.async(destDir)
.then(function (dstExists) {
if (!dstExists) {
promisedMkdirp(destDir)
.then(deferred.resolve, deferred.reject);
} else {
// Hah, no idea.
deferred.reject();
}
})
.catch(deferred.reject);
return deferred.promise;
return deferred.promise;
};
var async = function (from, to) {
var deferred = Q.defer();
var deferred = Q.defer();
promisedRename(from, to)
.then(deferred.resolve)
.catch(function (err) {
if (err.code !== 'ENOENT') {
// Something unknown. Rethrow original error.
deferred.reject(err);
promisedRename(from, to)
.then(deferred.resolve)
.catch(function (err) {
if (err.code !== 'ENOENT') {
// Something unknown. Rethrow original error.
deferred.reject(err);
} else {
// Ok, source or destination path doesn't exist.
// Must do more investigation.
exists.async(from)
.then(function (srcExists) {
if (!srcExists) {
deferred.reject(generateSourceDoesntExistError(from));
} else {
// Ok, source or destination path doesn't exist.
// Must do more investigation.
exists.async(from)
.then(function (srcExists) {
if (!srcExists) {
deferred.reject(generateSourceDoesntExistError(from));
} else {
ensureDestinationPathExistsAsync(to)
.then(function () {
// Retry the attempt
return promisedRename(from, to);
})
.then(deferred.resolve, deferred.reject);
}
})
.catch(deferred.reject);
ensureDestinationPathExistsAsync(to)
.then(function () {
// Retry the attempt
return promisedRename(from, to);
})
.then(deferred.resolve, deferred.reject);
}
});
})
.catch(deferred.reject);
}
});
return deferred.promise;
return deferred.promise;
};

@@ -102,0 +102,0 @@

@@ -1,2 +0,2 @@

"use strict";
'use strict';

@@ -11,3 +11,3 @@ var Q = require('q');

var sync = function (path) {
rimraf.sync(path);
rimraf.sync(path);
};

@@ -22,3 +22,3 @@

var async = function (path) {
return qRimraf(path);
return qRimraf(path);
};

@@ -25,0 +25,0 @@

@@ -1,2 +0,2 @@

"use strict";
'use strict';

@@ -3,0 +3,0 @@ var fs = require('fs');

@@ -1,2 +0,2 @@

"use strict";
'use strict';

@@ -13,13 +13,13 @@ var Q = require('q');

var sync = function (symlinkValue, path) {
try {
fs.symlinkSync(symlinkValue, path);
} catch (err) {
if (err.code === 'ENOENT') {
// Parent directories don't exist. Just create them and rety.
mkdirp.sync(pathUtil.dirname(path));
fs.symlinkSync(symlinkValue, path);
} else {
throw err;
}
try {
fs.symlinkSync(symlinkValue, path);
} catch (err) {
if (err.code === 'ENOENT') {
// Parent directories don't exist. Just create them and rety.
mkdirp.sync(pathUtil.dirname(path));
fs.symlinkSync(symlinkValue, path);
} else {
throw err;
}
}
};

@@ -35,20 +35,20 @@

var async = function (symlinkValue, path) {
var deferred = Q.defer();
var deferred = Q.defer();
promisedSymlink(symlinkValue, path)
.then(deferred.resolve)
.catch(function (err) {
if (err.code === 'ENOENT') {
// Parent directories don't exist. Just create them and rety.
promisedMkdirp(pathUtil.dirname(path))
.then(function () {
return promisedSymlink(symlinkValue, path);
})
.then(deferred.resolve, deferred.reject);
} else {
deferred.reject(err);
}
});
promisedSymlink(symlinkValue, path)
.then(deferred.resolve)
.catch(function (err) {
if (err.code === 'ENOENT') {
// Parent directories don't exist. Just create them and rety.
promisedMkdirp(pathUtil.dirname(path))
.then(function () {
return promisedSymlink(symlinkValue, path);
})
.then(deferred.resolve, deferred.reject);
} else {
deferred.reject(err);
}
});
return deferred.promise;
return deferred.promise;
};

@@ -55,0 +55,0 @@

// Matcher for glob patterns (e.g. *.txt, /a/b/**/z)
"use strict";
'use strict';

@@ -8,81 +8,80 @@ var Minimatch = require('minimatch').Minimatch;

var create = function (patterns, basePath) {
if (typeof patterns === 'string') {
patterns = [patterns];
}
if (typeof patterns === 'string') {
patterns = [patterns];
}
// Convert patterns to absolute paths
patterns = patterns.map(function (pattern) {
var hasSlash = (pattern.indexOf('/') !== -1);
// All patterns without slash are left as they are
if (hasSlash) {
// Maybe already is in the format we wanted
var isAbsolute = /^!?\//.test(pattern); // Starts with '/' or '!/'
if (!isAbsolute) {
var isNegated = (pattern[0] === '!');
// Convert patterns to absolute paths
patterns = patterns.map(function (pattern) {
var hasSlash = (pattern.indexOf('/') !== -1);
// All patterns without slash are left as they are
if (hasSlash) {
// Maybe already is in the format we wanted
var isAbsolute = /^!?\//.test(pattern); // Starts with '/' or '!/'
if (!isAbsolute) {
var isNegated = (pattern[0] === '!');
// Remove starting characters which have meaning '!' and '.'
// and first slash to normalize the path.
if (isNegated) {
pattern = pattern.substring(1);
}
if (pattern[0] === '.') {
pattern = pattern.substring(1);
}
if (pattern[0] === '/') {
pattern = pattern.substring(1);
}
// Remove starting characters which have meaning '!' and '.'
// and first slash to normalize the path.
if (isNegated) {
pattern = pattern.substring(1);
}
if (pattern[0] === '.') {
pattern = pattern.substring(1);
}
if (pattern[0] === '/') {
pattern = pattern.substring(1);
}
// Finally construct ready pattern
if (isNegated) {
pattern = '!' + basePath + '/' + pattern;
} else {
pattern = basePath + '/' + pattern;
}
}
// Finally construct ready pattern
if (isNegated) {
pattern = '!' + basePath + '/' + pattern;
} else {
pattern = basePath + '/' + pattern;
}
return pattern;
});
}
}
return pattern;
});
var matchers = patterns.map(function (pattern) {
return new Minimatch(pattern, {
matchBase: true,
nocomment: true,
dot: true,
});
var matchers = patterns.map(function (pattern) {
return new Minimatch(pattern, {
matchBase: true,
nocomment: true,
dot: true
});
});
var doMatch = function (path) {
var mode = 'matching';
var weHaveMatch = false;
var doMatch = function (path) {
var mode = 'matching';
var weHaveMatch = false;
for (var i = 0; i < matchers.length; i += 1) {
var ma = matchers[i];
for (var i = 0; i < matchers.length; i += 1) {
var ma = matchers[i];
if (ma.negate) {
mode = 'negation';
if (i === 0) {
// There are only negated patterns in the set,
// so make everything match by default and
// start to reject stuff.
weHaveMatch = true;
}
}
if (ma.negate) {
mode = 'negation';
if (i === 0) {
// There are only negated patterns in the set,
// so make everything match by default and
// start to reject stuff.
weHaveMatch = true;
}
}
if (mode === 'negation' && weHaveMatch && !ma.match(path)) {
// One negation match is enought to know we can reject this one.
return false;
}
if (mode === 'negation' && weHaveMatch && !ma.match(path)) {
// One negation match is enought to know we can reject this one.
return false;
}
if (mode === 'matching' && !weHaveMatch) {
weHaveMatch = ma.match(path);
}
}
if (mode === 'matching' && !weHaveMatch) {
weHaveMatch = ma.match(path);
}
}
return weHaveMatch;
};
return weHaveMatch;
};
return doMatch;
return doMatch;
};
module.exports.create = create;
// Logic for unix file mode operations.
"use strict";
'use strict';
// Converts mode to string 3 characters long.
module.exports.normalizeFileMode = function (rawMode) {
if (typeof rawMode === 'number') {
rawMode = rawMode.toString(8);
}
return rawMode.substring(rawMode.length - 3);
if (typeof rawMode === 'number') {
rawMode = rawMode.toString(8);
}
return rawMode.substring(rawMode.length - 3);
};

@@ -1,2 +0,2 @@

"use strict";
'use strict';

@@ -3,0 +3,0 @@ var jetpack = require('./lib/jetpack');

{
"name": "fs-jetpack",
"description": "Better file system API",
"version": "0.7.3",
"version": "0.8.0",
"author": "Jakub Szwacz <jakub@szwacz.com>",

@@ -13,3 +13,4 @@ "dependencies": {

"devDependencies": {
"eslint": "^1.6.0",
"eslint": "^2.6.0",
"eslint-config-airbnb": "^6.2.0",
"fs-extra": "^0.16.3",

@@ -16,0 +17,0 @@ "jasmine": "^2.2.1",

@@ -321,15 +321,13 @@ fs-jetpack [![Build Status](https://travis-ci.org/szwacz/fs-jetpack.svg?branch=master)](https://travis-ci.org/szwacz/fs-jetpack) [![Build status](https://ci.appveyor.com/api/projects/status/er206e91fpuuqf58?svg=true)](https://ci.appveyor.com/project/szwacz/fs-jetpack)

## <a name="find"></a> find(path, searchOptions, [returnAs])
asynchronous: **findAsync(path, searchOptions, [returnAs])**
## <a name="find"></a> find([path], searchOptions)
asynchronous: **findAsync([path], searchOptions)**
Finds in directory specified by `path` all files fulfilling `searchOptions`.
Finds in directory specified by `path` all files fulfilling `searchOptions`. Returned paths are relative to current CWD of jetpack instance.
**parameters:**
`path` path to start search in (all subdirectories will be searched).
`path` (optional, defaults to `'.'`) path to start search in (all subdirectories will be searched).
`searchOptions` is an `Object` with possible fields:
* `matching` glob patterns of files you would like to find.
`returnAs` (optional) how the results should be returned. Could be one of:
* `'absolutePath'` (default) returns array of absolute paths.
* `'relativePath'` returns array of relative paths. The paths are relative to `path` you started search in, not to CWD.
* `'inspect'` returns array of objects like you called [inspect](#inspect) on every of those files.
* `files` (default `true`) whether or not should search for files.
* `directories` (default `false`) whether or not should search for directories.

@@ -341,11 +339,14 @@ **returns:**

```javascript
// Finds all files or directories which has 2015 in the name
// Finds all files which has 2015 in the name
jetpack.find('my-work', { matching: '*2015*' });
// Finds all .js files inside 'my-project' but with exclusion of 'vendor' directory.
// Finds all .js files inside 'my-project' but excluding those in 'vendor' subtree.
jetpack.find('my-project', { matching: ['*.js', '!vendor/**/*'] });
// Finds all jpg and png files and gives you back the list of inspect objects
// (like you called jetpack.inspect on every of those paths)
jetpack.find('my-work', { matching: ['*.jpg', '*.png'] }, 'inspect');
// Looks for all directories named 'foo' (and will omit all files named 'foo').
jetpack.find('my-work', { matching: ['foo'], files: false, directories: true });
// Path parameter might be omitted and CWD is used as path in that case.
var myStuffDir = jetpack.cwd('my-stuff');
myStuffDir.find({ matching: ['*.md'] });
```

@@ -430,16 +431,12 @@

## <a name="list"></a> list(path, [useInspect])
## <a name="list"></a> list([path])
asynchronous: **listAsync(path, [useInspect])**
Lists the contents of directory.
Lists the contents of directory. Equivalent of `fs.readdir`.
**parameters:**
`path` path to directory you would like to list.
`useInspect` (optional) the type of data this call should return. Possible values:
* `false` (default) returns just a list of filenames (the same as `fs.readdir`)
* `true` performs [inspect](#inspect) on every item in directory, and returns array of those objects
* `object` if object has been passed to this parameter, it is treated as `options` parameter for [inspect](#inspect) method, and will alter returned inspect objects
`path` (optional) path to directory you would like to list. If not specified defaults to CWD.
**returns:**
`Array` of strings or objects depending on call properies. Or `null` if given path doesn't exist.
Array of file names inside given path, or `null` if given path doesn't exist.

@@ -487,3 +484,4 @@

* `'utf8'` (default) content will be returned as UTF-8 String.
* `'buf'` content will be returned as Buffer.
* `'buffer'` content will be returned as a Buffer.
* `'buf'` **deprecated** use `'buffer'` instead.
* `'json'` content will be returned as parsed JSON object.

@@ -496,4 +494,4 @@ * `'jsonWithDates'` content will be returned as parsed JSON object, and date strings in [ISO format](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) will be automatically turned into Date objects.

## <a name="remove"></a> remove(path)
asynchronous: **removeAsync(path)**
## <a name="remove"></a> remove([path])
asynchronous: **removeAsync([path])**

@@ -503,3 +501,3 @@ Deletes given path, no matter what it is (file or directory). If path already doesn't exist ends without throwing, so you can use it as 'ensure path doesn't exist'.

**parameters:**
`path` path to file or directory you want to remove.
`path` (optional) path to file or directory you want to remove. If not specified the remove action will be performed on current working directory (CWD).

@@ -516,2 +514,7 @@ **returns:**

jetpack.remove('my_work/important_stuff');
// Remove can be called with no parameters and will default to CWD then.
// In this example folder 'my_work' will cease to exist.
var myStuffDir = jetpack.cwd('my_stuff');
myStuffDir.remove();
```

@@ -553,3 +556,3 @@

`path` path to file.
`content` data to be written. This could be `String`, `Buffer`, `Object` or `Array` (if last two used, the data will be outputed into file as JSON).
`data` data to be written. This could be `String`, `Buffer`, `Object` or `Array` (if last two used, the data will be outputted into file as JSON).
`options` (optional) `Object` with possible fields:

@@ -556,0 +559,0 @@ * `atomic` (default `false`) if set to `true` the file will be written using strategy which is much more resistant to data loss. The trick is very simple, [read this to get the concept](http://stackoverflow.com/questions/17047994/transactionally-writing-files-in-node-js).

/* eslint-env jasmine */
"use strict";
'use strict';
describe('append |', function () {
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
it('appends String to file', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.writeFileSync('file.txt', 'abc');
};
var expectations = function () {
expect('file.txt').toBeFileWithContent('abcxyz');
};
it('appends String to file', function (done) {
// SYNC
preparations();
jetpack.append('file.txt', 'xyz');
expectations();
var preparations = function () {
helper.clearWorkingDir();
fse.writeFileSync('file.txt', 'abc');
};
// ASYNC
preparations();
jetpack.appendAsync('file.txt', 'xyz')
.then(function () {
expectations();
done();
});
});
var expectations = function () {
expect('file.txt').toBeFileWithContent('abcxyz');
};
it('appends Buffer to file', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.writeFileSync('file.txt', new Buffer([11]));
};
var expectations = function () {
var buf = fse.readFileSync('file.txt');
expect(buf[0]).toBe(11);
expect(buf[1]).toBe(22);
expect(buf.length).toBe(2);
};
// SYNC
preparations();
jetpack.append('file.txt', 'xyz');
expectations();
// SYNC
preparations();
jetpack.append('file.txt', new Buffer([22]));
expectations();
// ASYNC
preparations();
jetpack.appendAsync('file.txt', 'xyz')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.appendAsync('file.txt', new Buffer([22]))
.then(function () {
expectations();
done();
});
});
it('appends Buffer to file', function (done) {
it("if file doesn't exist creates it", function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('file.txt').toBeFileWithContent('xyz');
};
var preparations = function () {
helper.clearWorkingDir();
fse.writeFileSync('file.txt', new Buffer([11]));
};
// SYNC
preparations();
jetpack.append('file.txt', 'xyz');
expectations();
var expectations = function () {
var buf = fse.readFileSync('file.txt');
expect(buf[0]).toBe(11);
expect(buf[1]).toBe(22);
expect(buf.length).toBe(2);
};
// SYNC
preparations();
jetpack.append('file.txt', new Buffer([22]));
expectations();
// ASYNC
preparations();
jetpack.appendAsync('file.txt', new Buffer([22]))
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.appendAsync('file.txt', 'xyz')
.then(function () {
expectations();
done();
});
});
it("if file doesn't exist creates it", function (done) {
it("if parent directory doesn't exist creates it as well", function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('dir/dir/file.txt').toBeFileWithContent('xyz');
};
var preparations = function () {
helper.clearWorkingDir();
};
// SYNC
preparations();
jetpack.append('dir/dir/file.txt', 'xyz');
expectations();
var expectations = function () {
expect('file.txt').toBeFileWithContent('xyz');
};
// SYNC
preparations();
jetpack.append('file.txt', 'xyz');
expectations();
// ASYNC
preparations();
jetpack.appendAsync('file.txt', 'xyz')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.appendAsync('dir/dir/file.txt', 'xyz')
.then(function () {
expectations();
done();
});
});
it("if parent directory doesn't exist creates it as well", function (done) {
it('respects internal CWD of jetpack instance', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b.txt', 'abc');
};
var expectations = function () {
expect('a/b.txt').toBeFileWithContent('abcxyz');
};
var preparations = function () {
helper.clearWorkingDir();
};
var jetContext = jetpack.cwd('a');
var expectations = function () {
expect('dir/dir/file.txt').toBeFileWithContent('xyz');
};
// SYNC
preparations();
jetContext.append('b.txt', 'xyz');
expectations();
// SYNC
preparations();
jetpack.append('dir/dir/file.txt', 'xyz');
expectations();
// ASYNC
preparations();
jetpack.appendAsync('dir/dir/file.txt', 'xyz')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetContext.appendAsync('b.txt', 'xyz')
.then(function () {
expectations();
done();
});
});
it("respects internal CWD of jetpack instance", function (done) {
describe('*nix specyfic |', function () {
if (process.platform === 'win32') {
return;
}
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b.txt', 'abc');
};
it('sets file mode on created file', function (done) {
var expectations = function () {
expect('file.txt').toHaveMode('711');
};
var expectations = function () {
expect('a/b.txt').toBeFileWithContent('abcxyz');
};
// SYNC
jetpack.append('file.txt', 'abc', { mode: '711' });
expectations();
var jetContext = jetpack.cwd('a');
helper.clearWorkingDir();
// SYNC
preparations();
jetContext.append('b.txt', 'xyz');
// AYNC
jetpack.appendAsync('file.txt', 'abc', { mode: '711' })
.then(function () {
expectations();
// ASYNC
preparations();
jetContext.appendAsync('b.txt', 'xyz')
.then(function () {
expectations();
done();
});
done();
});
});
describe('*nix specyfic |', function () {
if (process.platform === 'win32') {
return;
}
it('sets file mode on created file', function (done) {
var expectations = function () {
expect('file.txt').toHaveMode('711');
};
// SYNC
jetpack.append('file.txt', 'abc', { mode: '711' });
expectations();
helper.clearWorkingDir();
// AYNC
jetpack.appendAsync('file.txt', 'abc', { mode: '711' })
.then(function () {
expectations();
done();
});
});
});
});
});
/* eslint-env jasmine */
"use strict";
'use strict';
describe('copy |', function () {
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
it('copies a file', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('file.txt', 'abc');
};
var expectations = function () {
expect('file.txt').toBeFileWithContent('abc');
expect('file_1.txt').toBeFileWithContent('abc');
};
it("copies a file", function (done) {
// SYNC
preparations();
jetpack.copy('file.txt', 'file_1.txt');
expectations();
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('file.txt', 'abc');
};
// ASYNC
preparations();
jetpack.copyAsync('file.txt', 'file_1.txt')
.then(function () {
expectations();
done();
});
});
var expectations = function () {
expect('file.txt').toBeFileWithContent('abc');
expect('file_1.txt').toBeFileWithContent('abc');
};
it('can copy file to nonexistent directory (will create directory)', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('file.txt', 'abc');
};
var expectations = function () {
expect('file.txt').toBeFileWithContent('abc');
expect('dir/dir/file.txt').toBeFileWithContent('abc');
};
// SYNC
preparations();
jetpack.copy('file.txt', 'file_1.txt');
expectations();
// SYNC
preparations();
jetpack.copy('file.txt', 'dir/dir/file.txt');
expectations();
// ASYNC
preparations();
jetpack.copyAsync('file.txt', 'file_1.txt')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.copyAsync('file.txt', 'dir/dir/file.txt')
.then(function () {
expectations();
done();
});
});
it("can copy file to nonexistent directory (will create directory)", function (done) {
it('copies empty directory', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirsSync('dir');
};
var expectations = function () {
expect('a/dir').toBeDirectory();
};
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('file.txt', 'abc');
};
// SYNC
preparations();
jetpack.copy('dir', 'a/dir');
expectations();
var expectations = function () {
expect('file.txt').toBeFileWithContent('abc');
expect('dir/dir/file.txt').toBeFileWithContent('abc');
};
// ASYNC
preparations();
jetpack.copyAsync('dir', 'a/dir')
.then(function () {
expectations();
done();
});
});
// SYNC
preparations();
jetpack.copy('file.txt', 'dir/dir/file.txt');
expectations();
it('copies a tree of files', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/f1.txt', 'abc');
fse.outputFileSync('a/b/f2.txt', '123');
fse.mkdirsSync('a/b/c');
};
var expectations = function () {
expect('dir/a/f1.txt').toBeFileWithContent('abc');
expect('dir/a/b/c').toBeDirectory();
expect('dir/a/b/f2.txt').toBeFileWithContent('123');
};
// ASYNC
preparations();
jetpack.copyAsync('file.txt', 'dir/dir/file.txt')
.then(function () {
expectations();
done();
});
// SYNC
preparations();
jetpack.copy('a', 'dir/a');
expectations();
// ASYNC
preparations();
jetpack.copyAsync('a', 'dir/a')
.then(function () {
expectations();
done();
});
});
it("copies empty directory", function (done) {
it("generates nice error if source path doesn't exist", function (done) {
var expectations = function (err) {
expect(err.code).toBe('ENOENT');
expect(err.message).toMatch(/^Path to copy doesn't exist/);
};
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirsSync('dir');
};
// SYNC
try {
jetpack.copy('a', 'b');
throw new Error('to make sure this code throws');
} catch (err) {
expectations(err);
}
var expectations = function () {
expect('a/dir').toBeDirectory();
};
// SYNC
preparations();
jetpack.copy('dir', 'a/dir');
expectations();
// ASYNC
preparations();
jetpack.copyAsync('dir', 'a/dir')
.then(function () {
expectations();
done();
});
// ASYNC
jetpack.copyAsync('a', 'b')
.catch(function (err) {
expectations(err);
done();
});
});
it("copies a tree of files", function (done) {
it('respects internal CWD of jetpack instance', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b.txt', 'abc');
};
var expectations = function () {
expect('a/b.txt').toBeFileWithContent('abc');
expect('a/x.txt').toBeFileWithContent('abc');
};
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/f1.txt', 'abc');
fse.outputFileSync('a/b/f2.txt', '123');
fse.mkdirsSync('a/b/c');
};
var jetContext = jetpack.cwd('a');
var expectations = function () {
expect('dir/a/f1.txt').toBeFileWithContent('abc');
expect('dir/a/b/c').toBeDirectory();
expect('dir/a/b/f2.txt').toBeFileWithContent('123');
};
// SYNC
preparations();
jetContext.copy('b.txt', 'x.txt');
expectations();
// SYNC
preparations();
jetpack.copy('a', 'dir/a');
expectations();
// ASYNC
preparations();
jetpack.copyAsync('a', 'dir/a')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetContext.copyAsync('b.txt', 'x.txt')
.then(function () {
expectations();
done();
});
});
it("generates nice error if source path doesn't exist", function (done) {
describe('overwriting behaviour', function () {
it('does not overwrite by default', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/file.txt', 'abc');
fse.mkdirsSync('b');
};
var expectations = function (err) {
expect(err.code).toBe('EEXIST');
expect(err.message).toMatch(/^Destination path already exists/);
};
var expectations = function (err) {
expect(err.code).toBe('ENOENT');
expect(err.message).toMatch(/^Path to copy doesn't exist/);
};
// SYNC
preparations();
try {
jetpack.copy('a', 'b');
throw new Error('to make sure this code throws');
} catch (err) {
expectations(err);
}
// SYNC
try {
jetpack.copy('a', 'b');
throw new Error("to make sure this code throws");
} catch (err) {
expectations(err);
}
// ASYNC
jetpack.copyAsync('a', 'b')
.catch(function (err) {
expectations(err);
done();
});
// ASYNC
preparations();
jetpack.copyAsync('a', 'b')
.catch(function (err) {
expectations(err);
done();
});
});
it("respects internal CWD of jetpack instance", function (done) {
it('overwrites if it was specified', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/file.txt', 'abc');
fse.outputFileSync('b/file.txt', 'xyz');
};
var expectations = function () {
expect('a/file.txt').toBeFileWithContent('abc');
expect('b/file.txt').toBeFileWithContent('abc');
};
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b.txt', 'abc');
};
// SYNC
preparations();
jetpack.copy('a', 'b', { overwrite: true });
expectations();
var expectations = function () {
expect('a/b.txt').toBeFileWithContent('abc');
expect('a/x.txt').toBeFileWithContent('abc');
};
var jetContext = jetpack.cwd('a');
// SYNC
preparations();
jetContext.copy('b.txt', 'x.txt');
// ASYNC
preparations();
jetpack.copyAsync('a', 'b', { overwrite: true })
.then(function () {
expectations();
// ASYNC
preparations();
jetContext.copyAsync('b.txt', 'x.txt')
.then(function () {
expectations();
done();
});
done();
});
});
});
describe('overwriting behaviour', function () {
describe('filter what to copy |', function () {
it('by simple pattern', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('dir/file.txt', '1');
fse.outputFileSync('dir/file.md', 'm1');
fse.outputFileSync('dir/a/file.txt', '2');
fse.outputFileSync('dir/a/file.md', 'm2');
fse.outputFileSync('dir/a/b/file.txt', '3');
fse.outputFileSync('dir/a/b/file.md', 'm3');
};
var expectations = function () {
expect('copy/file.txt').toBeFileWithContent('1');
expect('copy/file.md').not.toExist();
expect('copy/a/file.txt').toBeFileWithContent('2');
expect('copy/a/file.md').not.toExist();
expect('copy/a/b/file.txt').toBeFileWithContent('3');
expect('copy/a/b/file.md').not.toExist();
};
it("does not overwrite by default", function (done) {
// SYNC
preparations();
jetpack.copy('dir', 'copy', { matching: '*.txt' });
expectations();
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/file.txt', 'abc');
fse.mkdirsSync('b');
};
// ASYNC
preparations();
jetpack.copyAsync('dir', 'copy', { matching: '*.txt' })
.then(function () {
expectations();
done();
});
});
var expectations = function (err) {
expect(err.code).toBe('EEXIST');
expect(err.message).toMatch(/^Destination path already exists/);
};
it('by pattern anchored to copied directory', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('x/y/dir/file.txt', '1');
fse.outputFileSync('x/y/dir/a/file.txt', '2');
fse.outputFileSync('x/y/dir/a/b/file.txt', '3');
};
var expectations = function () {
expect('copy/file.txt').not.toExist();
expect('copy/a/file.txt').toBeFileWithContent('2');
expect('copy/a/b/file.txt').not.toExist();
};
// SYNC
preparations();
try {
jetpack.copy('a', 'b');
throw new Error("to make sure this code throws");
} catch (err) {
expectations(err);
}
// SYNC
preparations();
jetpack.copy('x/y/dir', 'copy', { matching: 'a/*.txt' });
expectations();
// ASYNC
preparations();
jetpack.copyAsync('a', 'b')
.catch(function (err) {
expectations(err);
done();
});
});
// ASYNC
preparations();
jetpack.copyAsync('x/y/dir', 'copy', { matching: 'a/*.txt' })
.then(function () {
expectations();
done();
});
});
it("overwrites if it was specified", function (done) {
it('can use ./ as indication of anchor directory', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('x/y/a.txt', '123');
fse.outputFileSync('x/y/b/a.txt', '456');
};
var expectations = function () {
expect('copy/a.txt').toExist();
expect('copy/b/a.txt').not.toExist();
};
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/file.txt', 'abc');
fse.outputFileSync('b/file.txt', 'xyz');
};
// SYNC
preparations();
jetpack.copy('x/y', 'copy', { matching: './a.txt' });
expectations();
var expectations = function () {
expect('a/file.txt').toBeFileWithContent('abc');
expect('b/file.txt').toBeFileWithContent('abc');
};
// ASYNC
preparations();
jetpack.copyAsync('x/y', 'copy', { matching: './a.txt' })
.then(function () {
expectations();
done();
});
});
// SYNC
preparations();
jetpack.copy('a', 'b', { overwrite: true });
expectations();
it('matching works also if copying single file', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a', '123');
fse.outputFileSync('x', '456');
};
var expectations = function () {
expect('a-copy').not.toExist();
expect('x-copy').toExist();
};
// ASYNC
preparations();
jetpack.copyAsync('a', 'b', { overwrite: true })
.then(function () {
expectations();
done();
});
});
// SYNC
preparations();
jetpack.copy('a', 'a-copy', { matching: 'x' });
jetpack.copy('x', 'x-copy', { matching: 'x' });
expectations();
// ASYNC
preparations();
jetpack.copyAsync('a', 'a-copy', { matching: 'x' })
.then(function () {
return jetpack.copyAsync('x', 'x-copy', { matching: 'x' });
})
.then(function () {
expectations();
done();
});
});
describe('filter what to copy |', function () {
it('can use negation in patterns', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirsSync('x/y/dir/a/b');
fse.mkdirsSync('x/y/dir/a/x');
fse.mkdirsSync('x/y/dir/a/y');
fse.mkdirsSync('x/y/dir/a/z');
};
var expectations = function () {
expect('copy/dir/a/b').toBeDirectory();
expect('copy/dir/a/x').not.toExist();
expect('copy/dir/a/y').not.toExist();
expect('copy/dir/a/z').not.toExist();
};
it("by simple pattern", function (done) {
// SYNC
preparations();
jetpack.copy('x/y', 'copy', {
matching: [
'**',
// Three different pattern types to test:
'!x',
'!dir/a/y',
'!./dir/a/z'
]
});
expectations();
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('dir/file.txt', '1');
fse.outputFileSync('dir/file.md', 'm1');
fse.outputFileSync('dir/a/file.txt', '2');
fse.outputFileSync('dir/a/file.md', 'm2');
fse.outputFileSync('dir/a/b/file.txt', '3');
fse.outputFileSync('dir/a/b/file.md', 'm3');
};
// ASYNC
preparations();
jetpack.copyAsync('x/y', 'copy', {
matching: [
'**',
// Three different pattern types to test:
'!x',
'!dir/a/y',
'!./dir/a/z'
]
})
.then(function () {
expectations();
done();
});
});
var expectations = function () {
expect('copy/file.txt').toBeFileWithContent('1');
expect('copy/file.md').not.toExist();
expect('copy/a/file.txt').toBeFileWithContent('2');
expect('copy/a/file.md').not.toExist();
expect('copy/a/b/file.txt').toBeFileWithContent('3');
expect('copy/a/b/file.md').not.toExist();
};
it('wildcard copies everything', function (done) {
var preparations = function () {
helper.clearWorkingDir();
// Just a file
fse.outputFileSync('x/file.txt', '123');
// Dot file
fse.outputFileSync('x/y/.dot', 'dot');
// Empty directory
fse.mkdirsSync('x/y/z');
};
var expectations = function () {
expect('copy/file.txt').toBeFileWithContent('123');
expect('copy/y/.dot').toBeFileWithContent('dot');
expect('copy/y/z').toBeDirectory();
};
// SYNC
preparations();
jetpack.copy('dir', 'copy', { matching: '*.txt' });
expectations();
// SYNC
preparations();
jetpack.copy('x', 'copy', { matching: '**' });
expectations();
// ASYNC
preparations();
jetpack.copyAsync('dir', 'copy', { matching: '*.txt' })
.then(function () {
expectations();
done();
});
});
// ASYNC
preparations();
jetpack.copyAsync('x', 'copy', { matching: '**' })
.then(function () {
expectations();
done();
});
});
});
it("by pattern anchored to copied directory", function (done) {
describe('*nix specific |', function () {
if (process.platform === 'win32') {
return;
}
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('x/y/dir/file.txt', '1');
fse.outputFileSync('x/y/dir/a/file.txt', '2');
fse.outputFileSync('x/y/dir/a/b/file.txt', '3');
};
it('copies also file permissions', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b/c.txt', 'abc');
fse.chmodSync('a/b', '700');
fse.chmodSync('a/b/c.txt', '711');
};
var expectations = function () {
expect('x/b').toHaveMode('700');
expect('x/b/c.txt').toHaveMode('711');
};
var expectations = function () {
expect('copy/file.txt').not.toExist();
expect('copy/a/file.txt').toBeFileWithContent('2');
expect('copy/a/b/file.txt').not.toExist();
};
// SYNC
preparations();
jetpack.copy('a', 'x');
expectations();
// SYNC
preparations();
jetpack.copy('x/y/dir', 'copy', { matching: 'a/*.txt' });
expectations();
// AYNC
preparations();
jetpack.copyAsync('a', 'x')
.then(function () {
expectations();
done();
});
});
// ASYNC
preparations();
jetpack.copyAsync('x/y/dir', 'copy', { matching: 'a/*.txt' })
.then(function () {
expectations();
done();
});
});
it('can copy symlink', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirsSync('to_copy');
fse.symlinkSync('some/file', 'to_copy/symlink');
};
var expectations = function () {
expect(fse.lstatSync('copied/symlink').isSymbolicLink()).toBe(true);
expect(fse.readlinkSync('copied/symlink')).toBe('some/file');
};
it("can use ./ as indication of anchor directory", function (done) {
// SYNC
preparations();
jetpack.copy('to_copy', 'copied');
expectations();
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('x/y/a.txt', '123');
fse.outputFileSync('x/y/b/a.txt', '456');
};
var expectations = function () {
expect('copy/a.txt').toExist();
expect('copy/b/a.txt').not.toExist();
};
// SYNC
preparations();
jetpack.copy('x/y', 'copy', { matching: './a.txt' });
expectations();
// ASYNC
preparations();
jetpack.copyAsync('x/y', 'copy', { matching: './a.txt' })
.then(function () {
expectations();
done();
});
});
it("matching works also if copying single file", function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a', '123');
fse.outputFileSync('x', '456');
};
var expectations = function () {
expect('a-copy').not.toExist();
expect('x-copy').toExist();
};
// SYNC
preparations();
jetpack.copy('a', 'a-copy', { matching: 'x' });
jetpack.copy('x', 'x-copy', { matching: 'x' });
expectations();
// ASYNC
preparations();
jetpack.copyAsync('a', 'a-copy', { matching: 'x' })
.then(function () {
return jetpack.copyAsync('x', 'x-copy', { matching: 'x' });
})
.then(function () {
expectations();
done();
});
});
it('can use negation in patterns', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirsSync('x/y/dir/a/b');
fse.mkdirsSync('x/y/dir/a/x');
fse.mkdirsSync('x/y/dir/a/y');
fse.mkdirsSync('x/y/dir/a/z');
};
var expectations = function () {
expect('copy/dir/a/b').toBeDirectory();
expect('copy/dir/a/x').not.toExist();
expect('copy/dir/a/y').not.toExist();
expect('copy/dir/a/z').not.toExist();
};
// SYNC
preparations();
jetpack.copy('x/y', 'copy', {
matching: [
'**',
// Three different pattern types to test:
'!x',
'!dir/a/y',
'!./dir/a/z',
],
});
expectations();
// ASYNC
preparations();
jetpack.copyAsync('x/y', 'copy', {
matching: [
'**',
// Three different pattern types to test:
'!x',
'!dir/a/y',
'!./dir/a/z',
],
})
.then(function () {
expectations();
done();
});
});
it("wildcard copies everything", function (done) {
var preparations = function () {
helper.clearWorkingDir();
// Just a file
fse.outputFileSync('x/file.txt', '123');
// Dot file
fse.outputFileSync('x/y/.dot', 'dot');
// Empty directory
fse.mkdirsSync('x/y/z');
};
var expectations = function () {
expect('copy/file.txt').toBeFileWithContent('123');
expect('copy/y/.dot').toBeFileWithContent('dot');
expect('copy/y/z').toBeDirectory();
};
// SYNC
preparations();
jetpack.copy('x', 'copy', { matching: '**' });
expectations();
// ASYNC
preparations();
jetpack.copyAsync('x', 'copy', { matching: '**' })
.then(function () {
expectations();
done();
});
});
// ASYNC
preparations();
jetpack.copyAsync('to_copy', 'copied')
.then(function () {
expectations();
done();
});
});
describe('*nix specific |', function () {
it('can overwrite symlink', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirsSync('to_copy');
fse.symlinkSync('some/file', 'to_copy/symlink');
fse.mkdirsSync('copied');
fse.symlinkSync('some/other_file', 'copied/symlink');
};
var expectations = function () {
expect(fse.lstatSync('copied/symlink').isSymbolicLink()).toBe(true);
expect(fse.readlinkSync('copied/symlink')).toBe('some/file');
};
if (process.platform === 'win32') {
return;
}
// SYNC
preparations();
jetpack.copy('to_copy', 'copied', { overwrite: true });
expectations();
it('copies also file permissions', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b/c.txt', 'abc');
fse.chmodSync('a/b', '700');
fse.chmodSync('a/b/c.txt', '711');
};
var expectations = function () {
expect('x/b').toHaveMode('700');
expect('x/b/c.txt').toHaveMode('711');
};
// SYNC
preparations();
jetpack.copy('a', 'x');
expectations();
// AYNC
preparations();
jetpack.copyAsync('a', 'x')
.then(function () {
expectations();
done();
});
});
it('can copy symlink', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirsSync('to_copy');
fse.symlinkSync('some/file', 'to_copy/symlink');
};
var expectations = function () {
expect(fse.lstatSync('copied/symlink').isSymbolicLink()).toBe(true);
expect(fse.readlinkSync('copied/symlink')).toBe('some/file');
};
// SYNC
preparations();
jetpack.copy('to_copy', 'copied');
expectations();
// ASYNC
preparations();
jetpack.copyAsync('to_copy', 'copied')
.then(function () {
expectations();
done();
});
});
it('can overwrite symlink', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirsSync('to_copy');
fse.symlinkSync('some/file', 'to_copy/symlink');
fse.mkdirsSync('copied');
fse.symlinkSync('some/other_file', 'copied/symlink');
};
var expectations = function () {
expect(fse.lstatSync('copied/symlink').isSymbolicLink()).toBe(true);
expect(fse.readlinkSync('copied/symlink')).toBe('some/file');
};
// SYNC
preparations();
jetpack.copy('to_copy', 'copied', { overwrite: true });
expectations();
// ASYNC
preparations();
jetpack.copyAsync('to_copy', 'copied', { overwrite: true })
.then(function () {
expectations();
done();
});
});
// ASYNC
preparations();
jetpack.copyAsync('to_copy', 'copied', { overwrite: true })
.then(function () {
expectations();
done();
});
});
});
});
/* eslint-env jasmine */
"use strict";
'use strict';
describe('cwd', function () {
var pathUtil = require('path');
var jetpack = require('..');
var pathUtil = require('path');
var jetpack = require('..');
it('returns the same path as process.cwd for main instance of jetpack', function () {
expect(jetpack.cwd()).toBe(process.cwd());
});
it('returns the same path as process.cwd for main instance of jetpack', function () {
expect(jetpack.cwd()).toBe(process.cwd());
});
it('can create new context with different cwd', function () {
var jetCwd = jetpack.cwd('/'); // absolute path
expect(jetCwd.cwd()).toBe(pathUtil.resolve(process.cwd(), '/'));
it('can create new context with different cwd', function () {
var jetCwd = jetpack.cwd('/'); // absolute path
expect(jetCwd.cwd()).toBe(pathUtil.resolve(process.cwd(), '/'));
jetCwd = jetpack.cwd('../..'); // relative path
expect(jetCwd.cwd()).toBe(pathUtil.resolve(process.cwd(), '../..'));
jetCwd = jetpack.cwd('../..'); // relative path
expect(jetCwd.cwd()).toBe(pathUtil.resolve(process.cwd(), '../..'));
expect(jetpack.cwd()).toBe(process.cwd()); // cwd of main lib should be intact
});
expect(jetpack.cwd()).toBe(process.cwd()); // cwd of main lib should be intact
});
it('cwd contexts can be created recursively', function () {
var jetCwd1;
var jetCwd2;
it('cwd contexts can be created recursively', function () {
var jetCwd1, jetCwd2;
jetCwd1 = jetpack.cwd('..');
expect(jetCwd1.cwd()).toBe(pathUtil.resolve(process.cwd(), '..'));
jetCwd1 = jetpack.cwd('..');
expect(jetCwd1.cwd()).toBe(pathUtil.resolve(process.cwd(), '..'));
jetCwd2 = jetCwd1.cwd('..');
expect(jetCwd2.cwd()).toBe(pathUtil.resolve(process.cwd(), '../..'));
});
jetCwd2 = jetCwd1.cwd('..');
expect(jetCwd2.cwd()).toBe(pathUtil.resolve(process.cwd(), '../..'));
});
it('cwd can join path parts', function () {
var jetCwd = jetpack.cwd('a', 'b', 'c');
expect(jetCwd.cwd()).toBe(pathUtil.resolve(process.cwd(), 'a', 'b', 'c'));
});
it('cwd can join path parts', function () {
var jetCwd = jetpack.cwd('a', 'b', 'c');
expect(jetCwd.cwd()).toBe(pathUtil.resolve(process.cwd(), 'a', 'b', 'c'));
});
});
/* eslint-env jasmine */
"use strict";
'use strict';
describe('dir |', function () {
var fse = require('fs-extra');
var pathUtil = require('path');
var helper = require('./support/spec_helper');
var jetpack = require('..');
var fse = require('fs-extra');
var pathUtil = require('path');
var helper = require('./support/spec_helper');
var jetpack = require('..');
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
describe('ensure dir exists |', function () {
it("creates dir if it doesn't exist", function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('x').toBeDirectory();
};
describe('ensure dir exists |', function () {
// SYNC
preparations();
jetpack.dir('x');
expectations();
it("creates dir if it doesn't exist", function (done) {
// ASYNC
preparations();
jetpack.dirAsync('x')
.then(function () {
expectations();
done();
});
});
var preparations = function () {
helper.clearWorkingDir();
};
it('does nothing if dir already exists', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirsSync('x');
};
var expectations = function () {
expect('x').toBeDirectory();
};
var expectations = function () {
expect('x').toBeDirectory();
};
// SYNC
preparations();
jetpack.dir('x');
expectations();
// SYNC
preparations();
jetpack.dir('x');
expectations();
// ASYNC
preparations();
jetpack.dirAsync('x')
.then(function () {
expectations();
done();
});
});
// ASYNC
preparations();
jetpack.dirAsync('x')
.then(function () {
expectations();
done();
});
});
it('creates nested directories if necessary', function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('a/b/c').toBeDirectory();
};
it('does nothing if dir already exists', function (done) {
// SYNC
preparations();
jetpack.dir('a/b/c');
expectations();
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirsSync('x');
};
// ASYNC
preparations();
jetpack.dirAsync('a/b/c')
.then(function () {
expectations();
done();
});
});
});
var expectations = function () {
expect('x').toBeDirectory();
};
describe('ensures dir empty |', function () {
it('not bothers about emptiness if not specified', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirsSync('a/b');
};
var expectations = function () {
expect('a/b').toExist();
};
// SYNC
preparations();
jetpack.dir('x');
expectations();
// SYNC
preparations();
jetpack.dir('a');
expectations();
// ASYNC
preparations();
jetpack.dirAsync('x')
.then(function () {
expectations();
done();
});
});
// ASYNC
preparations();
jetpack.dirAsync('a')
.then(function () {
expectations();
done();
});
});
it('creates nested directories if necessary', function (done) {
it('makes dir empty', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b/file.txt', 'abc');
};
var expectations = function () {
expect('a/b/file.txt').not.toExist();
expect('a').toExist();
};
var preparations = function () {
helper.clearWorkingDir();
};
// SYNC
preparations();
jetpack.dir('a', { empty: true });
expectations();
var expectations = function () {
expect('a/b/c').toBeDirectory();
};
// ASYNC
preparations();
jetpack.dirAsync('a', { empty: true })
.then(function () {
expectations();
done();
});
});
});
// SYNC
preparations();
jetpack.dir('a/b/c');
expectations();
it('if given path is file, deletes it and places dir instead', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a', 'abc');
};
var expectations = function () {
expect('a').toBeDirectory();
};
// ASYNC
preparations();
jetpack.dirAsync('a/b/c')
.then(function () {
expectations();
done();
});
});
// SYNC
preparations();
jetpack.dir('a');
expectations();
// ASYNC
preparations();
jetpack.dirAsync('a')
.then(function () {
expectations();
done();
});
});
describe('ensures dir empty |', function () {
it('respects internal CWD of jetpack instance', function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('a/b').toBeDirectory();
};
it('not bothers about emptiness if not specified', function (done) {
var jetContext = jetpack.cwd('a');
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirsSync('a/b');
};
// SYNC
preparations();
jetContext.dir('b');
expectations();
var expectations = function () {
expect('a/b').toExist();
};
// ASYNC
preparations();
jetContext.dirAsync('b')
.then(function () {
expectations();
done();
});
});
// SYNC
preparations();
jetpack.dir('a');
expectations();
it('returns jetack instance pointing on this directory', function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function (jetpackContext) {
expect(jetpackContext.cwd()).toBe(pathUtil.resolve('a'));
};
// ASYNC
preparations();
jetpack.dirAsync('a')
.then(function () {
expectations();
done();
});
});
// SYNC
preparations();
expectations(jetpack.dir('a'));
it('makes dir empty', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b/file.txt', 'abc');
};
var expectations = function () {
expect('a/b/file.txt').not.toExist();
expect('a').toExist();
};
// SYNC
preparations();
jetpack.dir('a', { empty: true });
expectations();
// ASYNC
preparations();
jetpack.dirAsync('a', { empty: true })
.then(function () {
expectations();
done();
});
});
// ASYNC
preparations();
jetpack.dirAsync('a')
.then(function (jetpackContext) {
expectations(jetpackContext);
done();
});
});
it('if given path is file, deletes it and places dir instead', function (done) {
describe('windows specyfic |', function () {
if (process.platform !== 'win32') {
return;
}
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a', 'abc');
};
it('specyfying mode have no effect, and throws no error', function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('x').toBeDirectory();
};
var expectations = function () {
expect('a').toBeDirectory();
};
// SYNC
preparations();
jetpack.dir('x', { mode: '511' });
expectations();
// SYNC
preparations();
jetpack.dir('a');
// ASYNC
preparations();
jetpack.dirAsync('x', { mode: '511' })
.then(function () {
expectations();
// ASYNC
preparations();
jetpack.dirAsync('a')
.then(function () {
expectations();
done();
});
done();
});
});
});
it("respects internal CWD of jetpack instance", function (done) {
describe('*nix specyfic |', function () {
if (process.platform === 'win32') {
return;
}
var preparations = function () {
helper.clearWorkingDir();
};
// Tests assume umask is not greater than 022
var expectations = function () {
expect('a/b').toBeDirectory();
};
it('sets mode to newly created directory', function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('a').toHaveMode('511');
};
var jetContext = jetpack.cwd('a');
// SYNC
// mode as a string
preparations();
jetpack.dir('a', { mode: '511' });
expectations();
// SYNC
preparations();
jetContext.dir('b');
// mode as a number
preparations();
jetpack.dir('a', { mode: parseInt('511', 8) });
expectations();
// ASYNC
// mode as a string
preparations();
jetpack.dirAsync('a', { mode: '511' })
.then(function () {
expectations();
// ASYNC
// mode as a number
preparations();
jetContext.dirAsync('b')
.then(function () {
expectations();
done();
});
return jetpack.dirAsync('a', { mode: parseInt('511', 8) });
})
.then(function () {
expectations();
done();
});
});
it("returns jetack instance pointing on this directory", function (done) {
it('sets that mode to every created directory', function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('a').toHaveMode('711');
expect('a/b').toHaveMode('711');
};
var preparations = function () {
helper.clearWorkingDir();
};
// SYNC
preparations();
jetpack.dir('a/b', { mode: '711' });
expectations();
var expectations = function (jetpackContext) {
expect(jetpackContext.cwd()).toBe(pathUtil.resolve('a'));
};
// SYNC
preparations();
var jetpackContextSync = jetpack.dir('a');
expectations(jetpackContextSync);
// ASYNC
preparations();
jetpack.dirAsync('a')
.then(function (jetpackContextAsync) {
expectations(jetpackContextAsync);
done();
});
// ASYNC
preparations();
jetpack.dirAsync('a/b', { mode: '711' })
.then(function () {
expectations();
done();
});
});
describe('windows specyfic |', function () {
it('changes mode of existing directory to desired', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirSync('a', '777');
};
var expectations = function () {
expect('a').toHaveMode('511');
};
if (process.platform !== 'win32') {
return;
}
// SYNC
preparations();
jetpack.dir('a', { mode: '511' });
expectations();
it('specyfying mode have no effect, and throws no error', function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('x').toBeDirectory();
};
// SYNC
preparations();
jetpack.dir('x', { mode: '511' });
expectations();
// ASYNC
preparations();
jetpack.dirAsync('x', { mode: '511' })
.then(function () {
expectations();
done();
});
});
// ASYNC
preparations();
jetpack.dirAsync('a', { mode: '511' })
.then(function () {
expectations();
done();
});
});
describe('*nix specyfic |', function () {
it('leaves mode of directory intact if this option was not specified', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirSync('a', '700');
};
var expectations = function () {
expect('a').toHaveMode('700');
};
if (process.platform === 'win32') {
return;
}
// SYNC
preparations();
jetpack.dir('a');
expectations();
// Tests assume umask is not greater than 022
it('sets mode to newly created directory', function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('a').toHaveMode('511');
};
// SYNC
// mode as string
preparations();
jetpack.dir('a', { mode: '511' });
expectations();
// mode as number
preparations();
jetpack.dir('a', { mode: parseInt('511', 8) });
expectations();
// ASYNC
// mode as string
preparations();
jetpack.dirAsync('a', { mode: '511' })
.then(function () {
expectations();
// mode as number
preparations();
return jetpack.dirAsync('a', { mode: parseInt('511', 8) });
})
.then(function () {
expectations();
done();
});
});
it('sets that mode to every created directory', function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('a').toHaveMode('711');
expect('a/b').toHaveMode('711');
};
// SYNC
preparations();
jetpack.dir('a/b', { mode: '711' });
expectations();
// ASYNC
preparations();
jetpack.dirAsync('a/b', { mode: '711' })
.then(function () {
expectations();
done();
});
});
it('changes mode of existing directory to desired', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirSync('a', '777');
};
var expectations = function () {
expect('a').toHaveMode('511');
};
// SYNC
preparations();
jetpack.dir('a', { mode: '511' });
expectations();
// ASYNC
preparations();
jetpack.dirAsync('a', { mode: '511' })
.then(function () {
expectations();
done();
});
});
it('leaves mode of directory intact if this option was not specified', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirSync('a', '700');
};
var expectations = function () {
expect('a').toHaveMode('700');
};
// SYNC
preparations();
jetpack.dir('a');
expectations();
// ASYNC
preparations();
jetpack.dirAsync('a')
.then(function () {
expectations();
done();
});
});
// ASYNC
preparations();
jetpack.dirAsync('a')
.then(function () {
expectations();
done();
});
});
});
});
/* eslint-env jasmine */
"use strict";
'use strict';
describe('exists', function () {
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
it("returns false if file doesn't exist", function (done) {
// SYNC
expect(jetpack.exists('file.txt')).toBe(false);
it("returns false if file doesn't exist", function (done) {
// SYNC
var existsSync = jetpack.exists('file.txt');
expect(existsSync).toBe(false);
// ASYNC
jetpack.existsAsync('file.txt')
.then(function (existsAsync) {
expect(existsAsync).toBe(false);
done();
});
// ASYNC
jetpack.existsAsync('file.txt')
.then(function (exists) {
expect(exists).toBe(false);
done();
});
});
it("returns 'dir' if directory exists on given path", function (done) {
fse.mkdirsSync('a');
it("returns 'dir' if directory exists on given path", function (done) {
fse.mkdirsSync('a');
// SYNC
var existsSync = jetpack.exists('a');
expect(existsSync).toBe('dir');
// SYNC
expect(jetpack.exists('a')).toBe('dir');
// ASYNC
jetpack.existsAsync('a')
.then(function (existsAsync) {
expect(existsAsync).toBe('dir');
done();
});
// ASYNC
jetpack.existsAsync('a')
.then(function (exists) {
expect(exists).toBe('dir');
done();
});
});
it("returns 'file' if file exists on given path", function (done) {
fse.outputFileSync('text.txt', 'abc');
it("returns 'file' if file exists on given path", function (done) {
fse.outputFileSync('text.txt', 'abc');
// SYNC
var existsSync = jetpack.exists('text.txt');
expect(existsSync).toBe('file');
// SYNC
expect(jetpack.exists('text.txt')).toBe('file');
// ASYNC
jetpack.existsAsync('text.txt')
.then(function (existsAsync) {
expect(existsAsync).toBe('file');
done();
});
// ASYNC
jetpack.existsAsync('text.txt')
.then(function (exists) {
expect(exists).toBe('file');
done();
});
});
it("respects internal CWD of jetpack instance", function (done) {
fse.outputFileSync('a/text.txt', 'abc');
it('respects internal CWD of jetpack instance', function (done) {
var jetContext = jetpack.cwd('a');
var jetContext = jetpack.cwd('a');
fse.outputFileSync('a/text.txt', 'abc');
// SYNC
var existsSync = jetContext.exists('text.txt');
expect(existsSync).toBe('file');
// SYNC
expect(jetContext.exists('text.txt')).toBe('file');
// ASYNC
jetContext.existsAsync('text.txt')
.then(function (existsAsync) {
expect(existsAsync).toBe('file');
done();
});
// ASYNC
jetContext.existsAsync('text.txt')
.then(function (exists) {
expect(exists).toBe('file');
done();
});
});
describe("edge cases", function () {
describe('edge cases', function () {
it("ENOTDIR error changes into 'false'", function (done) {
// We have here malformed path: /some/dir/file.txt/some_dir
// (so file is in the middle of path, not at the end).
// This leads to ENOTDIR error, but technically speaking this
// path doesn't exist so let's just return false.
it("ENOTDIR error changes into 'false'", function (done) {
// We have here malformed path: /some/dir/file.txt/some_dir
// (so file is in the middle of path, not at the end).
// This leads to ENOTDIR error, but technically speaking this
// path doesn't exist so let's just return false.
fse.outputFileSync('text.txt', 'abc');
fse.outputFileSync('text.txt', 'abc');
// SYNC
expect(jetpack.exists('text.txt/something')).toBe(false);
// SYNC
var existsSync = jetpack.exists('text.txt/something');
expect(existsSync).toBe(false);
// ASYNC
jetpack.existsAsync('text.txt/something')
.then(function (existsAsync) {
expect(existsAsync).toBe(false);
done();
});
});
// ASYNC
jetpack.existsAsync('text.txt/something')
.then(function (exists) {
expect(exists).toBe(false);
done();
});
});
});
});
/* eslint-env jasmine */
"use strict";
'use strict';
describe('file |', function () {
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
describe('ensure file exists |', function () {
it("file doesn't exist before call", function (done) {
var prepartions = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('file.txt').toBeFileWithContent('');
};
describe('ensure file exists |', function () {
// SYNC
prepartions();
jetpack.file('file.txt');
expectations();
it("file doesn't exist before call", function (done) {
// ASYNC
prepartions();
jetpack.fileAsync('file.txt')
.then(function () {
expectations();
done();
});
});
var prepartions = function () {
helper.clearWorkingDir();
};
it('file already exists', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('file.txt', 'abc');
};
var expectations = function () {
expect('file.txt').toBeFileWithContent('abc');
};
var expectations = function () {
expect('file.txt').toBeFileWithContent('');
};
// SYNC
preparations();
jetpack.file('file.txt');
expectations();
// SYNC
prepartions();
jetpack.file('file.txt');
expectations();
// ASYNC
preparations();
jetpack.fileAsync('file.txt')
.then(function () {
expectations();
done();
});
});
});
// ASYNC
prepartions();
jetpack.fileAsync('file.txt')
.then(function () {
expectations();
done();
});
});
describe('ensures file content |', function () {
it('from string', function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('file.txt').toBeFileWithContent('ąbć');
};
it("file already exists", function (done) {
// SYNC
preparations();
jetpack.file('file.txt', { content: 'ąbć' });
expectations();
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('file.txt', 'abc');
};
// ASYNC
preparations();
jetpack.fileAsync('file.txt', { content: 'ąbć' })
.then(function () {
expectations();
done();
});
});
var expectations = function () {
expect('file.txt').toBeFileWithContent('abc');
};
it('from buffer', function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
var buf = fse.readFileSync('file');
expect(buf[0]).toBe(11);
expect(buf[1]).toBe(22);
expect(buf.length).toBe(2);
};
// SYNC
preparations();
jetpack.file('file.txt');
expectations();
// SYNC
preparations();
jetpack.file('file', { content: new Buffer([11, 22]) });
expectations();
// ASYNC
preparations();
jetpack.fileAsync('file.txt')
.then(function () {
expectations();
done();
});
});
// ASYNC
preparations();
jetpack.fileAsync('file', { content: new Buffer([11, 22]) })
.then(function () {
expectations();
done();
});
});
describe('ensures file content |', function () {
it('from object (json)', function (done) {
var obj = {
a: 'abc',
b: 123
};
it("from string", function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
var data = JSON.parse(fse.readFileSync('file.txt', 'utf8'));
expect(data).toEqual(obj);
};
var preparations = function () {
helper.clearWorkingDir();
};
// SYNC
preparations();
jetpack.file('file.txt', { content: obj });
expectations();
var expectations = function () {
expect('file.txt').toBeFileWithContent('ąbć');
};
// ASYNC
preparations();
jetpack.fileAsync('file.txt', { content: obj })
.then(function () {
expectations();
done();
});
});
// SYNC
preparations();
jetpack.file('file.txt', { content: 'ąbć' });
expectations();
it('written JSON data can be indented', function (done) {
var obj = {
a: 'abc',
b: 123
};
// ASYNC
preparations();
jetpack.fileAsync('file.txt', { content: 'ąbć' })
.then(function () {
expectations();
done();
});
});
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
var sizeA = fse.statSync('a.json').size;
var sizeB = fse.statSync('b.json').size;
var sizeC = fse.statSync('c.json').size;
expect(sizeB).toBeGreaterThan(sizeA);
expect(sizeC).toBeGreaterThan(sizeB);
};
it("from buffer", function (done) {
// SYNC
preparations();
jetpack.file('a.json', { content: obj, jsonIndent: 0 });
jetpack.file('b.json', { content: obj }); // Default indent = 2
jetpack.file('c.json', { content: obj, jsonIndent: 4 });
expectations();
var preparations = function () {
helper.clearWorkingDir();
};
// ASYNC
preparations();
jetpack.fileAsync('a.json', { content: obj, jsonIndent: 0 })
.then(function () {
return jetpack.fileAsync('b.json', { content: obj }); // Default indent = 2
})
.then(function () {
return jetpack.fileAsync('c.json', { content: obj, jsonIndent: 4 });
})
.then(function () {
expectations();
done();
});
});
var expectations = function () {
var buf = fse.readFileSync('file');
expect(buf[0]).toBe(11);
expect(buf[1]).toBe(22);
expect(buf.length).toBe(2);
};
it('replaces content of already existing file', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.writeFileSync('file.txt', 'abc');
};
var expectations = function () {
expect('file.txt').toBeFileWithContent('123');
};
// SYNC
preparations();
jetpack.file('file', { content: new Buffer([11, 22]) });
expectations();
// SYNC
preparations();
jetpack.file('file.txt', { content: '123' });
expectations();
// ASYNC
preparations();
jetpack.fileAsync('file', { content: new Buffer([11, 22]) })
.then(function () {
expectations();
done();
});
});
// ASYNC
preparations();
jetpack.fileAsync('file.txt', { content: '123' })
.then(function () {
expectations();
done();
});
});
});
it("from object (json)", function (done) {
it('if given path is directory, should delete it and place file instead', function (done) {
var preparations = function () {
helper.clearWorkingDir();
// Create nested directories to be sure we can delete non-empty dir.
fse.outputFileSync('a/b/c.txt', 'abc');
};
var expectations = function () {
expect('a').toBeFileWithContent('');
};
var obj = { a: "abc", b: 123 };
// SYNC
preparations();
jetpack.file('a');
expectations();
var preparations = function () {
helper.clearWorkingDir();
};
// ASYNC
preparations();
jetpack.fileAsync('a')
.then(function () {
expectations();
done();
});
});
var expectations = function () {
var data = JSON.parse(fse.readFileSync('file.txt', 'utf8'));
expect(data).toEqual(obj);
};
it("if directory for file doesn't exist creates it too", function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('a/b/c.txt').toBeFileWithContent('');
};
// SYNC
preparations();
jetpack.file('file.txt', { content: obj });
expectations();
// SYNC
preparations();
jetpack.file('a/b/c.txt');
expectations();
// ASYNC
preparations();
jetpack.fileAsync('file.txt', { content: obj })
.then(function () {
expectations();
done();
});
});
// ASYNC
preparations();
jetpack.fileAsync('a/b/c.txt')
.then(function () {
expectations();
done();
});
});
it('written JSON data can be indented', function (done) {
it('returns currently used jetpack instance', function (done) {
// SYNC
expect(jetpack.file('file.txt')).toBe(jetpack);
var obj = { a: "abc", b: 123 };
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
var sizeA = fse.statSync('a.json').size;
var sizeB = fse.statSync('b.json').size;
var sizeC = fse.statSync('c.json').size;
expect(sizeB).toBeGreaterThan(sizeA);
expect(sizeC).toBeGreaterThan(sizeB);
};
// SYNC
preparations();
jetpack.file('a.json', { content: obj, jsonIndent: 0 });
jetpack.file('b.json', { content: obj }); // Default indent = 2
jetpack.file('c.json', { content: obj, jsonIndent: 4 });
expectations();
// ASYNC
preparations();
jetpack.fileAsync('a.json', { content: obj, jsonIndent: 0 })
.then(function () {
return jetpack.fileAsync('b.json', { content: obj }); // Default indent = 2
})
.then(function () {
return jetpack.fileAsync('c.json', { content: obj, jsonIndent: 4 });
})
.then(function () {
expectations();
done();
});
});
it("replaces content of already existing file", function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.writeFileSync('file.txt', 'abc');
};
var expectations = function () {
expect('file.txt').toBeFileWithContent('123');
};
// SYNC
preparations();
jetpack.file('file.txt', { content: '123' });
expectations();
// ASYNC
preparations();
jetpack.fileAsync('file.txt', { content: '123' })
.then(function () {
expectations();
done();
});
});
// ASYNC
jetpack.fileAsync('file.txt')
.then(function (jetpackContext) {
expect(jetpackContext).toBe(jetpack);
done();
});
});
it('if given path is directory, should delete it and place file instead', function (done) {
it('respects internal CWD of jetpack instance', function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('a/b.txt').toBeFileWithContent('');
};
var preparations = function () {
helper.clearWorkingDir();
// Create nested directories to be sure we can delete non-empty dir.
fse.outputFileSync('a/b/c.txt', 'abc');
};
var jetContext = jetpack.cwd('a');
var expectations = function () {
expect('a').toBeFileWithContent('');
};
// SYNC
preparations();
jetContext.file('b.txt');
expectations();
// SYNC
preparations();
jetpack.file('a');
expectations();
// ASYNC
preparations();
jetpack.fileAsync('a')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetContext.fileAsync('b.txt')
.then(function () {
expectations();
done();
});
});
it("if directory for file doesn't exist creates it too", function (done) {
describe('windows specyfic |', function () {
if (process.platform !== 'win32') {
return;
}
var preparations = function () {
helper.clearWorkingDir();
};
it('specyfying mode should have no effect, and throw no error', function (done) {
// SYNC
jetpack.file('file.txt', { mode: '511' });
var expectations = function () {
expect('a/b/c.txt').toBeFileWithContent('');
};
helper.clearWorkingDir();
// SYNC
preparations();
jetpack.file('a/b/c.txt');
expectations();
// ASYNC
preparations();
jetpack.fileAsync('a/b/c.txt')
.then(function () {
expectations();
done();
});
// ASYNC
jetpack.fileAsync('file.txt', { mode: '511' })
.then(function () {
done();
});
});
});
it('returns currently used jetpack instance', function (done) {
// SYNC
var jetpackContextSync = jetpack.file('file.txt');
expect(jetpackContextSync).toBe(jetpack);
describe('*nix specyfic |', function () {
if (process.platform === 'win32') {
return;
}
// ASYNC
jetpack.fileAsync('file.txt')
.then(function (jetpackContextAsync) {
expect(jetpackContextAsync).toBe(jetpack);
done();
});
});
// Tests assume umask is not greater than 022
it("respects internal CWD of jetpack instance", function (done) {
it('sets mode of newly created file', function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('file.txt').toHaveMode('511');
};
var preparations = function () {
helper.clearWorkingDir();
};
// SYNC
// mode as string
preparations();
jetpack.file('file.txt', { mode: '511' });
expectations();
var expectations = function () {
expect('a/b.txt').toBeFileWithContent('');
};
// mode as number
preparations();
jetpack.file('file.txt', { mode: parseInt('511', 8) });
expectations();
var jetContext = jetpack.cwd('a');
// AYNC
// mode as string
preparations();
jetpack.fileAsync('file.txt', { mode: '511' })
.then(function () {
expectations();
// SYNC
// mode as number
preparations();
jetContext.file('b.txt');
return jetpack.fileAsync('file.txt', { mode: parseInt('511', 8) });
})
.then(function () {
expectations();
// ASYNC
preparations();
jetContext.fileAsync('b.txt')
.then(function () {
expectations();
done();
});
done();
});
});
describe('windows specyfic |', function () {
it("changes mode of existing file if doesn't match", function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.writeFileSync('file.txt', 'abc', { mode: '700' });
};
var expectations = function () {
expect('file.txt').toHaveMode('511');
};
if (process.platform !== 'win32') {
return;
}
// SYNC
preparations();
jetpack.file('file.txt', { mode: '511' });
expectations();
it('specyfying mode should have no effect, and throw no error', function (done) {
// SYNC
jetpack.file('file.txt', { mode: '511' });
helper.clearWorkingDir();
// ASYNC
jetpack.fileAsync('file.txt', { mode: '511' })
.then(function () {
done();
});
});
// ASYNC
preparations();
jetpack.fileAsync('file.txt', { mode: '511' })
.then(function () {
expectations();
done();
});
});
describe('*nix specyfic |', function () {
it('leaves mode of file intact if not explicitly specified', function (done) {
var preparations = function () {
fse.writeFileSync('file.txt', 'abc', { mode: '700' });
};
var expectations = function () {
expect('file.txt').toHaveMode('700');
};
if (process.platform === 'win32') {
return;
}
preparations();
// Tests assume umask is not greater than 022
// SYNC
// ensure exists
jetpack.file('file.txt');
expectations();
it('sets mode of newly created file', function (done) {
// make file empty
jetpack.file('file.txt', { empty: true });
expectations();
var preparations = function () {
helper.clearWorkingDir();
};
// set file content
jetpack.file('file.txt', { content: '123' });
expectations();
var expectations = function () {
expect('file.txt').toHaveMode('511');
};
// AYNC
// ensure exists
jetpack.fileAsync('file.txt')
.then(function () {
expectations();
// SYNC
// mode as string
preparations();
jetpack.file('file.txt', { mode: '511' });
expectations();
// make file empty
return jetpack.fileAsync('file.txt', { empty: true });
})
.then(function () {
expectations();
// mode as number
preparations();
jetpack.file('file.txt', { mode: parseInt('511', 8) });
expectations();
// AYNC
// mode as string
preparations();
jetpack.fileAsync('file.txt', { mode: '511' })
.then(function () {
expectations();
// mode as number
preparations();
return jetpack.fileAsync('file.txt', { mode: parseInt('511', 8) });
})
.then(function () {
expectations();
done();
});
});
it("changes mode of existing file if doesn't match", function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.writeFileSync('file.txt', 'abc', { mode: '700' });
};
var expectations = function () {
expect('file.txt').toHaveMode('511');
};
// SYNC
preparations();
jetpack.file('file.txt', { mode: '511' });
expectations();
// ASYNC
preparations();
jetpack.fileAsync('file.txt', { mode: '511' })
.then(function () {
expectations();
done();
});
});
it('leaves mode of file intact if not explicitly specified', function (done) {
var preparations = function () {
fse.writeFileSync('file.txt', 'abc', { mode: '700' });
};
var expectations = function () {
expect('file.txt').toHaveMode('700');
};
preparations();
// SYNC
// ensure exists
jetpack.file('file.txt');
expectations();
// make file empty
jetpack.file('file.txt', { empty: true });
expectations();
// set file content
jetpack.file('file.txt', { content: '123' });
expectations();
// AYNC
// ensure exists
jetpack.fileAsync('file.txt')
.then(function () {
expectations();
// make file empty
return jetpack.fileAsync('file.txt', { empty: true });
})
.then(function () {
expectations();
// set file content
return jetpack.fileAsync('file.txt', { content: '123' });
})
.then(function () {
expectations();
done();
});
});
// set file content
return jetpack.fileAsync('file.txt', { content: '123' });
})
.then(function () {
expectations();
done();
});
});
});
});
/* eslint-env jasmine */
"use strict";
'use strict';
describe('find |', function () {
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
var fse = require('fs-extra');
var pathUtil = require('path');
var helper = require('./support/spec_helper');
var jetpack = require('..');
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
it('returns list of relative paths anchored to CWD', function (done) {
var expectations = function (found) {
var normalizedFound = helper.convertToUnixPathSeparators(found);
expect(normalizedFound).toEqual(['a/b/file.txt']);
};
it("returns list of absolute paths by default", function (done) {
fse.outputFileSync('a/b/file.txt', 'abc');
var preparations = function () {
fse.outputFileSync('a/b/file.txt', 'abc');
};
// SYNC
expectations(jetpack.find('a', { matching: '*.txt' }));
var expectations = function (found) {
var expectedPath = pathUtil.resolve('./a/b/file.txt');
expect(found).toEqual([expectedPath]);
};
preparations();
// SYNC
var foundSync = jetpack.find('a', { matching: '*.txt' }); // default
expectations(foundSync);
foundSync = jetpack.find('a', { matching: '*.txt' }, 'absolutePath'); // explicit
expectations(foundSync);
// ASYNC
jetpack.findAsync('a', { matching: '*.txt' }) // default
.then(function (foundAsync) {
expectations(foundAsync);
return jetpack.findAsync('a', { matching: '*.txt' }, 'absolutePath'); // explicit
})
.then(function (foundAsync) {
expectations(foundAsync);
done();
});
// ASYNC
jetpack.findAsync('a', { matching: '*.txt' })
.then(function (found) {
expectations(found);
done();
});
});
it("can return list of relative paths", function (done) {
it('defaults to CWD if no path provided', function (done) {
var expectations = function (found) {
var normalizedFound = helper.convertToUnixPathSeparators(found);
expect(normalizedFound).toEqual(['a/b/file.txt']);
};
var preparations = function () {
fse.outputFileSync('a/b/file.txt', 'abc');
};
fse.outputFileSync('a/b/file.txt', 'abc');
var expectations = function (found) {
var normalizedFound = helper.convertToUnixPathSeparators(found);
expect(normalizedFound).toEqual(['./b/file.txt']);
};
// SYNC
expectations(jetpack.find({ matching: '*.txt' }));
preparations();
// SYNC
var foundSync = jetpack.find('a', { matching: '*.txt' }, 'relativePath');
expectations(foundSync);
// ASYNC
jetpack.findAsync('a', { matching: '*.txt' }, 'relativePath')
.then(function (foundAsync) {
expectations(foundAsync);
done();
});
// ASYNC
jetpack.findAsync({ matching: '*.txt' })
.then(function (found) {
expectations(found);
done();
});
});
it("can return list of inspect objects", function (done) {
it('returns empty list if nothing found', function (done) {
var expectations = function (found) {
expect(found).toEqual([]);
};
var preparations = function () {
fse.outputFileSync('a/b/c.txt', 'abc');
};
fse.outputFileSync('a/b/c.md', 'abc');
var expectations = function (found) {
expect(found[0].name).toBe('c.txt');
};
// SYNC
expectations(jetpack.find('a', { matching: '*.txt' }));
preparations();
// SYNC
var foundSync = jetpack.find('a', { matching: '*.txt' }, 'inspect');
expectations(foundSync);
// ASYNC
jetpack.findAsync('a', { matching: '*.txt' }, 'inspect')
.then(function (foundAsync) {
expectations(foundAsync);
done();
});
// ASYNC
jetpack.findAsync('a', { matching: '*.txt' })
.then(function (found) {
expectations(found);
done();
});
});
it("returns empty list if nothing found", function (done) {
it('finds all paths which match globs', function (done) {
var expectations = function (found) {
var normalizedFound = helper.convertToUnixPathSeparators(found);
normalizedFound.sort();
expect(normalizedFound).toEqual([
'a/b/c/file.txt',
'a/b/file.txt',
'a/x/y/z'
]);
};
var preparations = function () {
fse.outputFileSync('a/b/c.md', 'abc');
};
fse.outputFileSync('a/b/file.txt', '1');
fse.outputFileSync('a/b/c/file.txt', '2');
fse.outputFileSync('a/b/c/file.md', '3');
fse.outputFileSync('a/x/y/z', 'Zzzzz...');
var expectations = function (found) {
expect(found).toEqual([]);
};
// SYNC
expectations(jetpack.find('a', { matching: ['*.txt', 'z'] }));
preparations();
// SYNC
var foundSync = jetpack.find('a', { matching: '*.txt' });
expectations(foundSync);
// ASYNC
jetpack.findAsync('a', { matching: '*.txt' })
.then(function (foundAsync) {
expectations(foundAsync);
done();
});
// ASYNC
jetpack.findAsync('a', { matching: ['*.txt', 'z'] })
.then(function (found) {
expectations(found);
done();
});
});
it("finds all paths which match globs", function (done) {
it("anchors globs to directory you're finding in", function (done) {
var expectations = function (found) {
var normalizedFound = helper.convertToUnixPathSeparators(found);
expect(normalizedFound).toEqual(['x/y/a/b/file.txt']);
};
var preparations = function () {
fse.outputFileSync('a/b/file.txt', '1');
fse.outputFileSync('a/b/c/file.txt', '2');
fse.outputFileSync('a/b/c/file.md', '3');
fse.mkdirsSync('a/x/y/z');
};
fse.outputFileSync('x/y/a/b/file.txt', '123');
fse.outputFileSync('x/y/a/b/c/file.txt', '456');
var expectations = function (found) {
var normalizedFound = helper.convertToUnixPathSeparators(found);
normalizedFound.sort();
expect(normalizedFound).toEqual([
'./b/c/file.txt',
'./b/file.txt',
'./x/y/z',
]);
};
// SYNC
expectations(jetpack.find('x/y/a', { matching: 'b/*.txt' }));
preparations();
// SYNC
var foundSync = jetpack.find('a', { matching: ['*.txt', 'z'] }, 'relativePath');
expectations(foundSync);
// ASYNC
jetpack.findAsync('a', { matching: ['*.txt', 'z'] }, 'relativePath')
.then(function (foundAsync) {
expectations(foundAsync);
done();
});
// ASYNC
jetpack.findAsync('x/y/a', { matching: 'b/*.txt' })
.then(function (found) {
expectations(found);
done();
});
});
it("anchors globs to directory you're finding in", function (done) {
it('can use ./ as indication of anchor directory', function (done) {
var expectations = function (found) {
var normalizedFound = helper.convertToUnixPathSeparators(found);
expect(normalizedFound).toEqual(['x/y/file.txt']);
};
var preparations = function () {
fse.outputFileSync('x/y/a/b/file.txt', '1');
fse.outputFileSync('x/y/a/b/file.md', '2');
fse.outputFileSync('x/y/a/b/c/file.txt', '3');
};
fse.outputFileSync('x/y/file.txt', '123');
fse.outputFileSync('x/y/b/file.txt', '456');
var expectations = function (found) {
var normalizedFound = helper.convertToUnixPathSeparators(found);
expect(normalizedFound).toEqual(['./b/file.txt']);
};
// SYNC
expectations(jetpack.find('x/y', { matching: './file.txt' }));
preparations();
// SYNC
var foundSync = jetpack.find('x/y/a', { matching: 'b/*.txt' }, 'relativePath');
expectations(foundSync);
// ASYNC
jetpack.findAsync('x/y/a', { matching: 'b/*.txt' }, 'relativePath')
.then(function (foundAsync) {
expectations(foundAsync);
done();
});
// ASYNC
jetpack.findAsync('x/y', { matching: './file.txt' })
.then(function (found) {
expectations(found);
done();
});
});
it("can use ./ as indication of anchor directory", function (done) {
it('deals with negation globs', function (done) {
var expectations = function (found) {
var normalizedFound = helper.convertToUnixPathSeparators(found);
expect(normalizedFound).toEqual(['x/y/a/b']);
};
var preparations = function () {
fse.outputFileSync('x/y/a.txt', '123');
fse.outputFileSync('x/y/b/a.txt', '456');
};
fse.outputFileSync('x/y/a/b', 'bbb');
fse.outputFileSync('x/y/a/x', 'xxx');
fse.outputFileSync('x/y/a/y', 'yyy');
fse.outputFileSync('x/y/a/z', 'zzz');
var expectations = function (found) {
var normalizedFound = helper.convertToUnixPathSeparators(found);
expect(normalizedFound).toEqual(['./a.txt']);
};
// SYNC
expectations(jetpack.find('x/y', {
matching: [
'a/*',
// Three different pattern types to test:
'!x',
'!a/y',
'!./a/z'
]
}));
preparations();
// SYNC
var foundSync = jetpack.find('x/y', { matching: './a.txt' }, 'relativePath');
expectations(foundSync);
// ASYNC
jetpack.findAsync('x/y', { matching: './a.txt' }, 'relativePath')
.then(function (foundAsync) {
expectations(foundAsync);
done();
});
// ASYNC
jetpack.findAsync('x/y', {
matching: [
'a/*',
// Three different pattern types to test:
'!x',
'!a/y',
'!./a/z'
]
})
.then(function (found) {
expectations(found);
done();
});
});
it('deals with negation globs', function (done) {
it("throws if path doesn't exist", function (done) {
var expectations = function (err) {
expect(err.code).toBe('ENOENT');
expect(err.message).toMatch(/^Path you want to find stuff in doesn't exist/);
};
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirsSync('x/y/a/b');
fse.mkdirsSync('x/y/a/x');
fse.mkdirsSync('x/y/a/y');
fse.mkdirsSync('x/y/a/z');
};
// SYNC
try {
jetpack.find('a', { matching: '*.txt' });
} catch (err) {
expectations(err);
}
var expectations = function (found) {
var normalizedFound = helper.convertToUnixPathSeparators(found);
expect(normalizedFound).toEqual(['./a/b']);
};
// SYNC
preparations();
var foundSync = jetpack.find('x/y', {
matching: [
'a/*',
// Three different pattern types to test:
'!x',
'!a/y',
'!./a/z',
],
}, 'relativePath');
expectations(foundSync);
// ASYNC
preparations();
jetpack.findAsync('x/y', {
matching: [
'a/*',
// Three different pattern types to test:
'!x',
'!a/y',
'!./a/z',
],
}, 'relativePath')
.then(function (foundAsync) {
expectations(foundAsync);
done();
});
// ASYNC
jetpack.findAsync('a', { matching: '*.txt' })
.catch(function (err) {
expectations(err);
done();
});
});
it("throws if path doesn't exist", function (done) {
it('throws if path is a file, not a directory', function (done) {
var expectations = function (err) {
expect(err.code).toBe('ENOTDIR');
expect(err.message).toContain('Path you want to find stuff in must be a directory');
};
var expectations = function (err) {
expect(err.code).toBe('ENOENT');
expect(err.message).toMatch(/^Path you want to find stuff in doesn't exist/);
};
fse.outputFileSync('a/b', 'abc');
// SYNC
try {
jetpack.find('a', { matching: '*.txt' });
} catch (err) {
expectations(err);
}
// SYNC
try {
jetpack.find('a/b', { matching: '*.txt' });
} catch (err) {
expectations(err);
}
// ASYNC
jetpack.findAsync('a', { matching: '*.txt' })
.catch(function (err) {
expectations(err);
done();
});
// ASYNC
jetpack.findAsync('a/b', { matching: '*.txt' })
.catch(function (err) {
expectations(err);
done();
});
});
it("throws if path is a file, not a directory", function (done) {
it('respects internal CWD of jetpack instance', function (done) {
var expectations = function (found) {
expect(found).toEqual(['b/c/d.txt']); // NOT a/b/c/d.txt
};
var preparations = function () {
fse.outputFileSync('a/b', 'abc');
};
var jetContext = jetpack.cwd('a');
var expectations = function (err) {
expect(err.code).toBe('ENOTDIR');
expect(err.message).toMatch(/^Path you want to find stuff in must be a directory/);
};
fse.outputFileSync('a/b/c/d.txt', 'abc');
preparations();
// SYNC
expectations(jetContext.find('b', { matching: '*.txt' }));
// SYNC
try {
jetpack.find('a/b', { matching: '*.txt' });
} catch (err) {
expectations(err);
}
// ASYNC
jetpack.findAsync('a/b', { matching: '*.txt' })
.catch(function (err) {
expectations(err);
done();
});
// ASYNC
jetContext.findAsync('b', { matching: '*.txt' })
.then(function (found) {
expectations(found);
done();
});
it("respects internal CWD of jetpack instance", function (done) {
var preparations = function () {
fse.outputFileSync('a/b/c.txt', 'abc');
};
var expectations = function (found) {
expect(found[0].name).toBe('c.txt');
};
preparations();
var jetContext = jetpack.cwd('a');
// SYNC
var foundSync = jetContext.find('b', { matching: '*.txt' }, 'inspect');
expectations(foundSync);
// ASYNC
jetContext.findAsync('b', { matching: '*.txt' }, 'inspect')
.then(function (foundAsync) {
expectations(foundAsync);
done();
});
});
});
});
/* eslint-env jasmine */
"use strict";
'use strict';
describe('inspectTree |', function () {
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
it('inspects whole tree of files', function (done) {
var expectations = function (data) {
expect(data).toEqual({
name: 'dir',
type: 'dir',
size: 7,
children: [
{
name: 'file.txt',
type: 'file',
size: 3
}, {
name: 'subdir',
type: 'dir',
size: 4,
children: [
{
name: 'file.txt',
type: 'file',
size: 4
}
]
}
]
});
};
it('inspects whole tree of files', function (done) {
fse.outputFileSync('dir/file.txt', 'abc');
fse.outputFileSync('dir/subdir/file.txt', 'defg');
var preparations = function () {
fse.outputFileSync('dir/file.txt', 'abc');
fse.outputFileSync('dir/subdir/file.txt', 'defg');
};
// SYNC
expectations(jetpack.inspectTree('dir'));
var expectations = function (data) {
expect(data).toEqual({
name: 'dir',
type: 'dir',
size: 7,
children: [
{
name: 'file.txt',
type: 'file',
size: 3,
}, {
name: 'subdir',
type: 'dir',
size: 4,
children: [
{
name: 'file.txt',
type: 'file',
size: 4,
},
],
},
],
});
};
preparations();
// SYNC
var treeSync = jetpack.inspectTree('dir');
expectations(treeSync);
// ASYNC
jetpack.inspectTreeAsync('dir')
.then(function (treeAsync) {
expectations(treeAsync);
done();
});
// ASYNC
jetpack.inspectTreeAsync('dir')
.then(function (tree) {
expectations(tree);
done();
});
});
it('can calculate size of a whole tree', function (done) {
it('can calculate size of a whole tree', function (done) {
var expectations = function (data) {
// dir
expect(data.size).toBe(7);
// dir/empty
expect(data.children[0].size).toBe(0);
// dir/empty.txt
expect(data.children[1].size).toBe(0);
// dir/file.txt
expect(data.children[2].size).toBe(3);
// dir/subdir
expect(data.children[3].size).toBe(4);
// dir/subdir/file.txt
expect(data.children[3].children[0].size).toBe(4);
};
var preparations = function () {
fse.mkdirsSync('dir/empty');
fse.outputFileSync('dir/empty.txt', '');
fse.outputFileSync('dir/file.txt', 'abc');
fse.outputFileSync('dir/subdir/file.txt', 'defg');
};
fse.mkdirsSync('dir/empty');
fse.outputFileSync('dir/empty.txt', '');
fse.outputFileSync('dir/file.txt', 'abc');
fse.outputFileSync('dir/subdir/file.txt', 'defg');
var expectations = function (data) {
// dir
expect(data.size).toBe(7);
// dir/empty
expect(data.children[0].size).toBe(0);
// dir/empty.txt
expect(data.children[1].size).toBe(0);
// dir/file.txt
expect(data.children[2].size).toBe(3);
// dir/subdir
expect(data.children[3].size).toBe(4);
// dir/subdir/file.txt
expect(data.children[3].children[0].size).toBe(4);
};
// SYNC
expectations(jetpack.inspectTree('dir'));
preparations();
// SYNC
var treeSync = jetpack.inspectTree('dir');
expectations(treeSync);
// ASYNC
jetpack.inspectTreeAsync('dir')
.then(function (treeAsync) {
expectations(treeAsync);
done();
});
// ASYNC
jetpack.inspectTreeAsync('dir')
.then(function (tree) {
expectations(tree);
done();
});
});
it('can compute checksum of a whole tree', function (done) {
it('can compute checksum of a whole tree', function (done) {
var expectations = function (data) {
// md5 of
// 'a.txt' + '900150983cd24fb0d6963f7d28e17f72' +
// 'b.txt' + '025e4da7edac35ede583f5e8d51aa7ec'
expect(data.md5).toBe('b0ff9df854172efe752cb36b96c8bccd');
// md5 of 'abc'
expect(data.children[0].md5).toBe('900150983cd24fb0d6963f7d28e17f72');
// md5 of 'defg'
expect(data.children[1].md5).toBe('025e4da7edac35ede583f5e8d51aa7ec');
};
var preparations = function () {
fse.outputFileSync('dir/a.txt', 'abc');
fse.outputFileSync('dir/b.txt', 'defg');
};
fse.outputFileSync('dir/a.txt', 'abc');
fse.outputFileSync('dir/b.txt', 'defg');
var expectations = function (data) {
// md5 of 'a.txt' + '900150983cd24fb0d6963f7d28e17f72' + 'b.txt' + '025e4da7edac35ede583f5e8d51aa7ec'
expect(data.md5).toBe('b0ff9df854172efe752cb36b96c8bccd');
// md5 of 'abc'
expect(data.children[0].md5).toBe('900150983cd24fb0d6963f7d28e17f72');
// md5 of 'defg'
expect(data.children[1].md5).toBe('025e4da7edac35ede583f5e8d51aa7ec');
};
// SYNC
expectations(jetpack.inspectTree('dir', { checksum: 'md5' }));
preparations();
// SYNC
var treeSync = jetpack.inspectTree('dir', { checksum: 'md5' });
expectations(treeSync);
// ASYNC
jetpack.inspectTreeAsync('dir', { checksum: 'md5' })
.then(function (treeAsync) {
expectations(treeAsync);
done();
});
// ASYNC
jetpack.inspectTreeAsync('dir', { checksum: 'md5' })
.then(function (tree) {
expectations(tree);
done();
});
});
it('can deal with empty directories while computing checksum', function (done) {
it('can deal with empty directories while computing checksum', function (done) {
var expectations = function (data) {
// md5 of
// 'empty_dir' + 'd41d8cd98f00b204e9800998ecf8427e' +
// 'file.txt' + '900150983cd24fb0d6963f7d28e17f72'
expect(data.md5).toBe('4715a354a7871a1db629b379e6267b95');
// md5 of empty directory -> md5 of empty string
expect(data.children[0].md5).toBe('d41d8cd98f00b204e9800998ecf8427e');
// md5 of 'abc'
expect(data.children[1].md5).toBe('900150983cd24fb0d6963f7d28e17f72');
};
var preparations = function () {
fse.mkdirsSync('dir/empty_dir');
fse.outputFileSync('dir/file.txt', 'abc');
};
fse.mkdirsSync('dir/empty_dir');
fse.outputFileSync('dir/file.txt', 'abc');
var expectations = function (data) {
// md5 of 'empty_dir' + 'd41d8cd98f00b204e9800998ecf8427e' + 'file.txt' + '900150983cd24fb0d6963f7d28e17f72'
expect(data.md5).toBe('4715a354a7871a1db629b379e6267b95');
// md5 of empty directory -> md5 of empty string
expect(data.children[0].md5).toBe('d41d8cd98f00b204e9800998ecf8427e');
// md5 of 'abc'
expect(data.children[1].md5).toBe('900150983cd24fb0d6963f7d28e17f72');
};
// SYNC
expectations(jetpack.inspectTree('dir', { checksum: 'md5' }));
preparations();
// SYNC
var treeSync = jetpack.inspectTree('dir', { checksum: 'md5' });
expectations(treeSync);
// ASYNC
jetpack.inspectTreeAsync('dir', { checksum: 'md5' })
.then(function (treeAsync) {
expectations(treeAsync);
done();
});
// ASYNC
jetpack.inspectTreeAsync('dir', { checksum: 'md5' })
.then(function (tree) {
expectations(tree);
done();
});
});
it('can output relative path for every tree node', function (done) {
it('can output relative path for every tree node', function (done) {
var expectations = function (data) {
// data will look like...
// {
// name: 'dir',
// relativePath: '.',
// children: [
// {
// name: 'subdir',
// relativePath: './subdir',
// children: [
// {
// name: 'file.txt',
// relativePath: './subdir/file.txt'
// }
// ]
// }
// ]
// }
expect(data.relativePath).toBe('.');
expect(data.children[0].relativePath).toBe('./subdir');
expect(data.children[0].children[0].relativePath).toBe('./subdir/file.txt');
};
var preparations = function () {
fse.outputFileSync('dir/subdir/file.txt', 'defg');
};
fse.outputFileSync('dir/subdir/file.txt', 'defg');
var expectations = function (data) {
// data will look like...
/* {
name: 'dir',
relativePath: '.',
children: [
{
name: 'subdir',
relativePath: './subdir',
children: [
{
name: 'file.txt',
relativePath: './subdir/file.txt'
}
]
}
]
} */
expect(data.relativePath).toBe('.');
expect(data.children[0].relativePath).toBe('./subdir');
expect(data.children[0].children[0].relativePath).toBe('./subdir/file.txt');
};
// SYNC
expectations(jetpack.inspectTree('dir', { relativePath: true }));
preparations();
// SYNC
var treeSync = jetpack.inspectTree('dir', { relativePath: true });
expectations(treeSync);
// ASYNC
jetpack.inspectTreeAsync('dir', { relativePath: true })
.then(function (treeAsync) {
expectations(treeAsync);
done();
});
// ASYNC
jetpack.inspectTreeAsync('dir', { relativePath: true })
.then(function (tree) {
expectations(tree);
done();
});
});
it('if given path is a file still works OK', function (done) {
it('if given path is a file still works OK', function (done) {
var expectations = function (data) {
expect(data).toEqual({
name: 'file.txt',
type: 'file',
size: 3
});
};
var preparations = function () {
fse.outputFileSync('dir/file.txt', 'abc');
};
fse.outputFileSync('dir/file.txt', 'abc');
var expectations = function (data) {
expect(data).toEqual({
name: 'file.txt',
type: 'file',
size: 3,
});
};
// SYNC
expectations(jetpack.inspectTree('dir/file.txt'));
preparations();
// SYNC
var treeSync = jetpack.inspectTree('dir/file.txt');
expectations(treeSync);
// ASYNC
jetpack.inspectTreeAsync('dir/file.txt')
.then(function (treeAsync) {
expectations(treeAsync);
done();
});
// ASYNC
jetpack.inspectTreeAsync('dir/file.txt')
.then(function (tree) {
expectations(tree);
done();
});
});
it('deals ok with empty directory', function (done) {
it('deals ok with empty directory', function (done) {
var expectations = function (data) {
expect(data).toEqual({
name: 'empty',
type: 'dir',
size: 0,
children: []
});
};
var preparations = function () {
fse.mkdirsSync('empty');
};
fse.mkdirsSync('empty');
var expectations = function (data) {
expect(data).toEqual({
name: 'empty',
type: 'dir',
size: 0,
children: [],
});
};
// SYNC
expectations(jetpack.inspectTree('empty'));
preparations();
// SYNC
var treeSync = jetpack.inspectTree('empty');
expectations(treeSync);
// ASYNC
jetpack.inspectTreeAsync('empty')
.then(function (treeAsync) {
expectations(treeAsync);
done();
});
// ASYNC
jetpack.inspectTreeAsync('empty')
.then(function (tree) {
expectations(tree);
done();
});
});
it("returns null if path doesn't exist", function (done) {
it("returns null if path doesn't exist", function (done) {
var expectations = function (data) {
expect(data).toBe(null);
};
var expectations = function (data) {
expect(data).toBe(null);
};
// SYNC
expectations(jetpack.inspectTree('nonexistent'));
// SYNC
var dataSync = jetpack.inspectTree('nonexistent');
expectations(dataSync);
// ASYNC
jetpack.inspectTreeAsync('nonexistent')
.then(function (dataAsync) {
expectations(dataAsync);
done();
});
// ASYNC
jetpack.inspectTreeAsync('nonexistent')
.then(function (dataAsync) {
expectations(dataAsync);
done();
});
});
it("respects internal CWD of jetpack instance", function (done) {
it('respects internal CWD of jetpack instance', function (done) {
var expectations = function (data) {
expect(data.name).toBe('b.txt');
};
var preparations = function () {
fse.outputFileSync('a/b.txt', 'abc');
};
var jetContext = jetpack.cwd('a');
var expectations = function (data) {
expect(data.name).toBe('b.txt');
};
fse.outputFileSync('a/b.txt', 'abc');
preparations();
// SYNC
expectations(jetContext.inspectTree('b.txt'));
var jetContext = jetpack.cwd('a');
// ASYNC
jetContext.inspectTreeAsync('b.txt')
.then(function (data) {
expectations(data);
done();
});
});
// SYNC
var dataSync = jetContext.inspectTree('b.txt');
expectations(dataSync);
describe('*nix specific', function () {
if (process.platform === 'win32') {
return;
}
// ASYNC
jetContext.inspectTreeAsync('b.txt')
.then(function (dataAsync) {
expectations(dataAsync);
done();
it('can deal with symlink', function (done) {
var expectations = function (tree) {
expect(tree).toEqual({
name: 'dir',
type: 'dir',
size: 3,
children: [{
name: 'file.txt',
type: 'file',
size: 3
}, {
name: 'symlinked_file.txt',
type: 'symlink',
pointsAt: 'dir/file.txt'
}]
});
});
};
describe('*nix specific', function () {
fse.outputFileSync('dir/file.txt', 'abc');
fse.symlinkSync('dir/file.txt', 'dir/symlinked_file.txt');
if (process.platform === 'win32') {
return;
}
// SYNC
expectations(jetpack.inspectTree('dir'));
it('can deal with symlink', function (done) {
var preparations = function () {
fse.outputFileSync('dir/file.txt', 'abc');
fse.symlinkSync('dir/file.txt', 'dir/symlinked_file.txt');
};
var expectations = function (data) {
expect(data).toEqual({
name: 'dir',
type: 'dir',
size: 3,
children: [{
name: 'file.txt',
type: 'file',
size: 3,
}, {
name: 'symlinked_file.txt',
type: 'symlink',
pointsAt: 'dir/file.txt',
}],
});
};
preparations();
// SYNC
var dataSync = jetpack.inspectTree('dir');
expectations(dataSync);
// ASYNC
jetpack.inspectTreeAsync('dir')
.then(function (dataAsync) {
expectations(dataAsync);
done();
});
});
// ASYNC
jetpack.inspectTreeAsync('dir')
.then(function (tree) {
expectations(tree);
done();
});
});
});
});
/* eslint-env jasmine */
"use strict";
'use strict';
describe('inspect |', function () {
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
it('can inspect a file', function (done) {
var expectations = function (data) {
expect(data).toEqual({
name: 'file.txt',
type: 'file',
size: 3
});
};
it('can inspect a file', function (done) {
fse.outputFileSync('dir/file.txt', 'abc');
var preparations = function () {
fse.outputFileSync('dir/file.txt', 'abc');
};
// SYNC
expectations(jetpack.inspect('dir/file.txt'));
var expectations = function (data) {
expect(data).toEqual({
name: 'file.txt',
type: 'file',
size: 3,
});
};
// ASYNC
jetpack.inspectAsync('dir/file.txt')
.then(function (data) {
expectations(data);
done();
});
});
preparations();
it('can inspect a directory', function (done) {
var expectations = function (data) {
expect(data).toEqual({
name: 'empty',
type: 'dir'
});
};
// SYNC
var dataSync = jetpack.inspect('dir/file.txt');
expectations(dataSync);
fse.mkdirsSync('dir/empty');
// ASYNC
jetpack.inspectAsync('dir/file.txt')
.then(function (dataAsync) {
expectations(dataAsync);
done();
});
// SYNC
expectations(jetpack.inspect('dir/empty'));
// ASYNC
jetpack.inspectAsync('dir/empty')
.then(function (data) {
expectations(data);
done();
});
});
it('can inspect a directory', function (done) {
it("returns null if path doesn't exist", function (done) {
var expectations = function (data) {
expect(data).toBe(null);
};
var preparations = function () {
fse.mkdirsSync('dir/empty');
};
// SYNC
expectations(jetpack.inspect('nonexistent'));
var expectations = function (data) {
expect(data).toEqual({
name: 'empty',
type: 'dir',
});
};
preparations();
// SYNC
var dataSync = jetpack.inspect('dir/empty');
expectations(dataSync);
// ASYNC
jetpack.inspectAsync('dir/empty')
.then(function (dataAsync) {
expectations(dataAsync);
done();
});
// ASYNC
jetpack.inspectAsync('nonexistent')
.then(function (data) {
expectations(data);
done();
});
});
it("returns null if path doesn't exist", function (done) {
it('can output file times (ctime, mtime, atime)', function (done) {
var expectations = function (data) {
expect(typeof data.accessTime.getTime).toBe('function');
expect(typeof data.modifyTime.getTime).toBe('function');
expect(typeof data.changeTime.getTime).toBe('function');
};
var expectations = function (data) {
expect(data).toBe(null);
};
fse.outputFileSync('dir/file.txt', 'abc');
// SYNC
var dataSync = jetpack.inspect('nonexistent');
expectations(dataSync);
// SYNC
expectations(jetpack.inspect('dir/file.txt', { times: true }));
// ASYNC
jetpack.inspectAsync('nonexistent')
.then(function (dataAsync) {
expectations(dataAsync);
done();
});
// ASYNC
jetpack.inspectAsync('dir/file.txt', { times: true })
.then(function (data) {
expectations(data);
done();
});
});
it('can output file times (ctime, mtime, atime)', function (done) {
it('can output absolute path', function (done) {
var expectations = function (data) {
expect(data.absolutePath).toBe(jetpack.path('dir/file.txt'));
};
var preparations = function () {
fse.outputFileSync('dir/file.txt', 'abc');
};
fse.outputFileSync('dir/file.txt', 'abc');
var expectations = function (data) {
expect(typeof data.accessTime.getTime).toBe('function');
expect(typeof data.modifyTime.getTime).toBe('function');
expect(typeof data.changeTime.getTime).toBe('function');
};
// SYNC
expectations(jetpack.inspect('dir/file.txt', { absolutePath: true }));
preparations();
// SYNC
var dataSync = jetpack.inspect('dir/file.txt', { times: true });
expectations(dataSync);
// ASYNC
jetpack.inspectAsync('dir/file.txt', { times: true })
.then(function (dataAsync) {
expectations(dataAsync);
done();
});
// ASYNC
jetpack.inspectAsync('dir/file.txt', { absolutePath: true })
.then(function (data) {
expectations(data);
done();
});
});
it('can output absolute path', function (done) {
it('respects internal CWD of jetpack instance', function (done) {
var expectations = function (data) {
expect(data.name).toBe('b.txt');
};
var preparations = function () {
fse.outputFileSync('dir/file.txt', 'abc');
};
var jetContext = jetpack.cwd('a');
var expectations = function (data) {
expect(data.absolutePath).toBe(jetpack.path('dir/file.txt'));
};
fse.outputFileSync('a/b.txt', 'abc');
preparations();
// SYNC
expectations(jetContext.inspect('b.txt'));
// SYNC
var dataSync = jetpack.inspect('dir/file.txt', { absolutePath: true });
expectations(dataSync);
// ASYNC
jetpack.inspectAsync('dir/file.txt', { absolutePath: true })
.then(function (dataAsync) {
expectations(dataAsync);
done();
});
// ASYNC
jetContext.inspectAsync('b.txt')
.then(function (data) {
expectations(data);
done();
});
});
it("respects internal CWD of jetpack instance", function (done) {
var preparations = function () {
fse.outputFileSync('a/b.txt', 'abc');
};
describe('checksums |', function () {
[
{
name: 'md5',
content: 'abc',
expected: '900150983cd24fb0d6963f7d28e17f72'
},
{
name: 'sha1',
content: 'abc',
expected: 'a9993e364706816aba3e25717850c26c9cd0d89d'
},
{
name: 'sha256',
content: 'abc',
expected: 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'
},
{
name: 'md5',
content: '', // just to check if we are counting checksums of empty file correctly
expected: 'd41d8cd98f00b204e9800998ecf8427e'
}
].forEach(function (test) {
it(test.name, function (done) {
var expectations = function (data) {
expect(data.name).toBe('b.txt');
expect(data[test.name]).toBe(test.expected);
};
preparations();
fse.outputFileSync('file.txt', test.content);
var jetContext = jetpack.cwd('a');
// SYNC
preparations();
var dataSync = jetContext.inspect('b.txt');
expectations(dataSync);
expectations(jetpack.inspect('file.txt', { checksum: test.name }));
// ASYNC
preparations();
jetContext.inspectAsync('b.txt')
.then(function (dataAsync) {
expectations(dataAsync);
done();
jetpack.inspectAsync('file.txt', { checksum: test.name })
.then(function (data) {
expectations(data);
done();
});
});
});
});
describe('checksums |', function () {
describe('*nix specific', function () {
if (process.platform === 'win32') {
return;
}
[
{
name: 'md5',
content: 'abc',
expected: '900150983cd24fb0d6963f7d28e17f72',
},
{
name: 'sha1',
content: 'abc',
expected: 'a9993e364706816aba3e25717850c26c9cd0d89d',
},
{
name: 'sha256',
content: 'abc',
expected: 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
},
{
name: 'md5',
content: '', // just to check if we are counting checksums of empty file correctly
expected: 'd41d8cd98f00b204e9800998ecf8427e',
},
].forEach(function (test) {
it('can output file mode', function (done) {
var expectations = function (data) {
expect(typeof data.mode).toBe('number');
};
it(test.name, function (done) {
fse.outputFileSync('dir/file.txt', 'abc');
var preparations = function () {
fse.outputFileSync('file.txt', test.content);
};
// SYNC
expectations(jetpack.inspect('dir/file.txt', { mode: true }));
var expectations = function (data) {
expect(data[test.name]).toBe(test.expected);
};
preparations();
// SYNC
var dataSync = jetpack.inspect('file.txt', { checksum: test.name });
expectations(dataSync);
// ASYNC
jetpack.inspectAsync('file.txt', { checksum: test.name })
.then(function (dataAsync) {
expectations(dataAsync);
done();
});
});
});
// ASYNC
jetpack.inspectAsync('dir/file.txt', { mode: true })
.then(function (data) {
expectations(data);
done();
});
});
describe('*nix specific', function () {
if (process.platform === 'win32') {
return;
}
it('can output file mode', function (done) {
var preparations = function () {
fse.outputFileSync('dir/file.txt', 'abc');
};
var expectations = function (data) {
expect(typeof data.mode).toBe('number');
};
preparations();
// SYNC
var dataSync = jetpack.inspect('dir/file.txt', { mode: true });
expectations(dataSync);
// ASYNC
jetpack.inspectAsync('dir/file.txt', { mode: true })
.then(function (dataAsync) {
expectations(dataAsync);
done();
});
it('follows symlink by default', function (done) {
var expectations = function (data) {
expect(data).toEqual({
name: 'symlinked_file.txt',
type: 'file',
size: 3
});
};
it('follows symlink by default', function (done) {
fse.outputFileSync('dir/file.txt', 'abc');
fse.symlinkSync('dir/file.txt', 'symlinked_file.txt');
var preparations = function () {
fse.outputFileSync('dir/file.txt', 'abc');
fse.symlinkSync('dir/file.txt', 'symlinked_file.txt');
};
// SYNC
expectations(jetpack.inspect('symlinked_file.txt'));
var expectations = function (data) {
expect(data).toEqual({
name: 'symlinked_file.txt',
type: 'file',
size: 3,
});
};
// ASYNC
jetpack.inspectAsync('symlinked_file.txt')
.then(function (data) {
expectations(data);
done();
});
});
preparations();
// SYNC
var dataSync = jetpack.inspect('symlinked_file.txt');
expectations(dataSync);
// ASYNC
jetpack.inspectAsync('symlinked_file.txt')
.then(function (dataAsync) {
expectations(dataAsync);
done();
});
it('stats symlink if option specified', function (done) {
var expectations = function (data) {
expect(data).toEqual({
name: 'symlinked_file.txt',
type: 'symlink',
pointsAt: 'dir/file.txt'
});
};
it('stats symlink if option specified', function (done) {
fse.outputFileSync('dir/file.txt', 'abc');
fse.symlinkSync('dir/file.txt', 'symlinked_file.txt');
var preparations = function () {
fse.outputFileSync('dir/file.txt', 'abc');
fse.symlinkSync('dir/file.txt', 'symlinked_file.txt');
};
// SYNC
expectations(jetpack.inspect('symlinked_file.txt', { symlinks: true }));
var expectations = function (data) {
expect(data).toEqual({
name: 'symlinked_file.txt',
type: 'symlink',
pointsAt: 'dir/file.txt',
});
};
preparations();
// SYNC
var dataSync = jetpack.inspect('symlinked_file.txt', { symlinks: true });
expectations(dataSync);
// ASYNC
jetpack.inspectAsync('symlinked_file.txt', { symlinks: true })
.then(function (dataAsync) {
expectations(dataAsync);
done();
});
});
// ASYNC
jetpack.inspectAsync('symlinked_file.txt', { symlinks: true })
.then(function (data) {
expectations(data);
done();
});
});
});
});
/* eslint-env jasmine */
"use strict";
'use strict';
describe('list |', function () {
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
it('lists file names in given path', function (done) {
var expectations = function (data) {
expect(data).toEqual(['empty', 'empty.txt', 'file.txt', 'subdir']);
};
it('lists file names by default', function (done) {
fse.mkdirsSync('dir/empty');
fse.outputFileSync('dir/empty.txt', '');
fse.outputFileSync('dir/file.txt', 'abc');
fse.outputFileSync('dir/subdir/file.txt', 'defg');
var preparations = function () {
fse.mkdirsSync('dir/empty');
fse.outputFileSync('dir/empty.txt', '');
fse.outputFileSync('dir/file.txt', 'abc');
fse.outputFileSync('dir/subdir/file.txt', 'defg');
};
// SYNC
expectations(jetpack.list('dir'));
var expectations = function (data) {
expect(data).toEqual(['empty', 'empty.txt', 'file.txt', 'subdir']);
};
preparations();
// SYNC
var listSync = jetpack.list('dir');
expectations(listSync);
// ASYNC
jetpack.listAsync('dir')
.then(function (listAsync) {
expectations(listAsync);
done();
});
// ASYNC
jetpack.listAsync('dir')
.then(function (listAsync) {
expectations(listAsync);
done();
});
});
it('lists inspect objects if true passed as second parameter', function (done) {
it('lists CWD if no path parameter passed', function (done) {
var expectations = function (data) {
expect(data).toEqual(['a', 'b']);
};
var preparations = function () {
fse.outputFileSync('dir/file.txt', 'abc');
fse.mkdirsSync('dir/next');
};
var jetContext = jetpack.cwd('dir');
var expectations = function (data) {
expect(data).toEqual([
{
name: 'file.txt',
type: 'file',
size: 3,
}, {
name: 'next',
type: 'dir',
},
]);
};
fse.mkdirsSync('dir/a');
fse.outputFileSync('dir/b');
preparations();
// SYNC
expectations(jetContext.list());
// SYNC
var listSync = jetpack.list('dir', true);
expectations(listSync);
// ASYNC
jetpack.listAsync('dir', true)
.then(function (listAsync) {
expectations(listAsync);
done();
});
// ASYNC
jetContext.listAsync()
.then(function (list) {
expectations(list);
done();
});
});
it('lists inspect objects with additional options if options passed as second parameter', function (done) {
it("returns null if path doesn't exist", function (done) {
var expectations = function (data) {
expect(data).toBe(null);
};
var preparations = function () {
fse.outputFileSync('dir/file.txt', 'abc');
};
// SYNC
expectations(jetpack.list('nonexistent'));
var expectations = function (data) {
expect(data[0].md5).toBeDefined();
};
preparations();
// SYNC
var listSync = jetpack.list('dir', { checksum: 'md5' });
expectations(listSync);
// ASYNC
jetpack.listAsync('dir', { checksum: 'md5' })
.then(function (listAsync) {
expectations(listAsync);
done();
});
// ASYNC
jetpack.listAsync('nonexistent')
.then(function (data) {
expectations(data);
done();
});
});
it("returns null if path doesn't exist", function (done) {
it('returns null if given path is a file', function (done) {
var expectations = function (list) {
expect(list).toBe(null);
};
var expectations = function (data) {
expect(data).toBe(null);
};
fse.outputFileSync('file.txt', 'abc');
// SYNC
var dataSync = jetpack.list('nonexistent');
expectations(dataSync);
// SYNC
expectations(jetpack.list('file.txt'));
// ASYNC
jetpack.listAsync('nonexistent')
.then(function (dataAsync) {
expectations(dataAsync);
done();
});
// ASYNC
jetpack.listAsync('file.txt')
.then(function (list) {
expectations(list);
done();
});
});
it("returns null if given path is a file", function (done) {
it('respects internal CWD of jetpack instance', function (done) {
var expectations = function (data) {
expect(data).toEqual(['c.txt']);
};
var preparations = function () {
fse.outputFileSync('file.txt', 'abc');
};
var jetContext = jetpack.cwd('a');
var expectations = function (list) {
expect(list).toBe(null);
};
fse.outputFileSync('a/b/c.txt', 'abc');
preparations();
// SYNC
expectations(jetContext.list('b'));
// SYNC
var listSync = jetpack.list('file.txt');
expectations(listSync);
// ASYNC
jetpack.listAsync('file.txt')
.then(function (listAsync) {
expectations(listAsync);
done();
});
// ASYNC
jetContext.listAsync('b')
.then(function (data) {
expectations(data);
done();
});
it("respects internal CWD of jetpack instance", function (done) {
var preparations = function () {
fse.outputFileSync('a/b/c.txt', 'abc');
};
var expectations = function (data) {
expect(data).toEqual(['c.txt']);
};
preparations();
var jetContext = jetpack.cwd('a');
// SYNC
preparations();
var dataSync = jetContext.list('b');
expectations(dataSync);
// ASYNC
preparations();
jetContext.listAsync('b')
.then(function (dataAsync) {
expectations(dataAsync);
done();
});
});
});
});
/* eslint-env jasmine */
"use strict";
'use strict';
describe('move |', function () {
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
it('moves file', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b.txt', 'abc');
};
var expectations = function () {
expect('a/b.txt').not.toExist();
expect('c.txt').toBeFileWithContent('abc');
};
it("moves file", function (done) {
// SYNC
preparations();
jetpack.move('a/b.txt', 'c.txt');
expectations();
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b.txt', 'abc');
};
var expectations = function () {
expect('a/b.txt').not.toExist();
expect('c.txt').toBeFileWithContent('abc');
};
// SYNC
preparations();
jetpack.move('a/b.txt', 'c.txt');
expectations();
// ASYNC
preparations();
jetpack.moveAsync('a/b.txt', 'c.txt')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.moveAsync('a/b.txt', 'c.txt')
.then(function () {
expectations();
done();
});
});
it("moves directory", function (done) {
it('moves directory', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b/c.txt', 'abc');
fse.mkdirsSync('x');
};
var expectations = function () {
expect('a').not.toExist();
expect('x/y/b/c.txt').toBeFileWithContent('abc');
};
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b/c.txt', 'abc');
fse.mkdirsSync('x');
};
// SYNC
preparations();
jetpack.move('a', 'x/y');
expectations();
var expectations = function () {
expect('a').not.toExist();
expect('x/y/b/c.txt').toBeFileWithContent('abc');
};
// SYNC
preparations();
jetpack.move('a', 'x/y');
expectations();
// ASYNC
preparations();
jetpack.moveAsync('a', 'x/y')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.moveAsync('a', 'x/y')
.then(function () {
expectations();
done();
});
});
it("creates nonexistent directories for destination path", function (done) {
it('creates nonexistent directories for destination path', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a.txt', 'abc');
};
var expectations = function () {
expect('a.txt').not.toExist();
expect('a/b/z.txt').toBeFileWithContent('abc');
};
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a.txt', 'abc');
};
// SYNC
preparations();
jetpack.move('a.txt', 'a/b/z.txt');
expectations();
var expectations = function () {
expect('a.txt').not.toExist();
expect('a/b/z.txt').toBeFileWithContent('abc');
};
// SYNC
preparations();
jetpack.move('a.txt', 'a/b/z.txt');
expectations();
// ASYNC
preparations();
jetpack.moveAsync('a.txt', 'a/b/z.txt')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.moveAsync('a.txt', 'a/b/z.txt')
.then(function () {
expectations();
done();
});
});
it("generates nice error when source path doesn't exist", function (done) {
it("generates nice error when source path doesn't exist", function (done) {
var expectations = function (err) {
expect(err.code).toBe('ENOENT');
expect(err.message).toMatch(/^Path to move doesn't exist/);
};
var expectations = function (err) {
expect(err.code).toBe('ENOENT');
expect(err.message).toMatch(/^Path to move doesn't exist/);
};
// SYNC
try {
jetpack.move('a', 'b');
throw new Error('to make sure this code throws');
} catch (err) {
expectations(err);
}
// SYNC
try {
jetpack.move('a', 'b');
throw new Error("to make sure this code throws");
} catch (err) {
expectations(err);
}
// ASYNC
jetpack.moveAsync('a', 'b')
.catch(function (err) {
expectations(err);
done();
});
// ASYNC
jetpack.moveAsync('a', 'b')
.catch(function (err) {
expectations(err);
done();
});
});
it("respects internal CWD of jetpack instance", function (done) {
it('respects internal CWD of jetpack instance', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b.txt', 'abc');
};
var expectations = function () {
expect('a/b.txt').not.toExist();
expect('a/x.txt').toBeFileWithContent('abc');
};
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b.txt', 'abc');
};
var jetContext = jetpack.cwd('a');
var expectations = function () {
expect('a/b.txt').not.toExist();
expect('a/x.txt').toBeFileWithContent('abc');
};
// SYNC
preparations();
jetContext.move('b.txt', 'x.txt');
expectations();
var jetContext = jetpack.cwd('a');
// SYNC
preparations();
jetContext.move('b.txt', 'x.txt');
expectations();
// ASYNC
preparations();
jetContext.moveAsync('b.txt', 'x.txt')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetContext.moveAsync('b.txt', 'x.txt')
.then(function () {
expectations();
done();
});
});
});
/* eslint-env jasmine */
"use strict";
'use strict';
describe('path', function () {
var pathUtil = require('path');
var jetpack = require('..');
var pathUtil = require('path');
var jetpack = require('..');
it('if empty returns same path as cwd()', function () {
expect(jetpack.path()).toBe(jetpack.cwd());
expect(jetpack.path('')).toBe(jetpack.cwd());
expect(jetpack.path('.')).toBe(jetpack.cwd());
});
it('if empty returns same path as cwd()', function () {
expect(jetpack.path()).toBe(jetpack.cwd());
expect(jetpack.path('')).toBe(jetpack.cwd());
expect(jetpack.path('.')).toBe(jetpack.cwd());
});
it('is absolute if prepending slash present', function () {
expect(jetpack.path('/blah')).toBe(pathUtil.resolve('/blah'));
});
it('is absolute if prepending slash present', function () {
expect(jetpack.path('/blah')).toBe(pathUtil.resolve('/blah'));
});
it('resolves to CWD path of this jetpack instance', function () {
var a = pathUtil.join(jetpack.cwd(), 'a');
// Create jetpack instance with other CWD
var jetpackSubdir = jetpack.cwd('subdir');
var b = pathUtil.join(jetpack.cwd(), 'subdir', 'b');
expect(jetpack.path('a')).toBe(a);
expect(jetpackSubdir.path('b')).toBe(b);
});
it('resolves to CWD path of this jetpack instance', function () {
var a = pathUtil.join(jetpack.cwd(), 'a');
expect(jetpack.path('a')).toBe(a);
// Create jetpack instance with other CWD
var jetpackSubdir = jetpack.cwd('subdir');
var b = pathUtil.join(jetpack.cwd(), 'subdir', 'b');
expect(jetpackSubdir.path('b')).toBe(b);
});
it('can take unlimited number of arguments as path parts', function () {
var abc = pathUtil.join(jetpack.cwd(), 'a', 'b', 'c');
expect(jetpack.path('a', 'b', 'c')).toBe(abc);
});
it('can take unlimited number of arguments as path parts', function () {
var abc = pathUtil.join(jetpack.cwd(), 'a', 'b', 'c');
expect(jetpack.path('a', 'b', 'c')).toBe(abc);
});
});
/* eslint-env jasmine */
"use strict";
'use strict';
describe('read |', function () {
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
it('reads file as a string', function (done) {
var expectations = function (content) {
expect(content).toBe('abc');
};
it('reads file as a string', function (done) {
fse.outputFileSync('file.txt', 'abc');
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('file.txt', 'abc');
};
// SYNC
expectations(jetpack.read('file.txt')); // defaults to 'utf8'
expectations(jetpack.read('file.txt', 'utf8')); // explicitly specified
var expectations = function (content) {
expect(content).toBe('abc');
};
// SYNC
preparations();
var contentSync = jetpack.read('file.txt'); // defaults to 'utf8'
expectations(contentSync);
contentSync = jetpack.read('file.txt', 'utf8'); // explicitly said
expectations(contentSync);
// ASYNC
preparations();
jetpack.readAsync('file.txt') // defaults to 'utf8'
.then(function (contentAsync) {
expectations(contentAsync);
return jetpack.readAsync('file.txt', 'utf8'); // explicitly said
})
.then(function (contentAsync) {
expectations(contentAsync);
done();
});
// ASYNC
jetpack.readAsync('file.txt') // defaults to 'utf8'
.then(function (content) {
expectations(content);
return jetpack.readAsync('file.txt', 'utf8'); // explicitly said
})
.then(function (content) {
expectations(content);
done();
});
});
it('reads file as a Buffer', function (done) {
it('reads file as a Buffer', function (done) {
var expectations = function (content) {
expect(Buffer.isBuffer(content)).toBe(true);
expect(content.length).toBe(2);
expect(content[0]).toBe(11);
expect(content[1]).toBe(22);
};
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('file.txt', new Buffer([11, 22]));
};
fse.outputFileSync('file.txt', new Buffer([11, 22]));
var expectations = function (content) {
expect(Buffer.isBuffer(content)).toBe(true);
expect(content.length).toBe(2);
expect(content[0]).toBe(11);
expect(content[1]).toBe(22);
};
// SYNC
expectations(jetpack.read('file.txt', 'buffer'));
// SYNC
preparations();
var contentSync = jetpack.read('file.txt', 'buf');
expectations(contentSync);
// ASYNC
preparations();
jetpack.readAsync('file.txt', 'buf')
.then(function (contentAsync) {
expectations(contentAsync);
done();
});
// ASYNC
jetpack.readAsync('file.txt', 'buffer')
.then(function (content) {
expectations(content);
done();
});
});
it('reads file as JSON', function (done) {
it('reads file as a Buffer (deprecated)', function (done) {
var expectations = function (content) {
expect(Buffer.isBuffer(content)).toBe(true);
expect(content.length).toBe(2);
expect(content[0]).toBe(11);
expect(content[1]).toBe(22);
};
var obj = {
utf8: "ąćłźż",
};
fse.outputFileSync('file.txt', new Buffer([11, 22]));
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('file.json', JSON.stringify(obj));
};
// SYNC
expectations(jetpack.read('file.txt', 'buf'));
var expectations = function (content) {
expect(content).toEqual(obj);
};
// SYNC
preparations();
var contentSync = jetpack.read('file.json', 'json');
expectations(contentSync);
// ASYNC
preparations();
jetpack.readAsync('file.json', 'json')
.then(function (contentAsync) {
expectations(contentAsync);
done();
});
// ASYNC
jetpack.readAsync('file.txt', 'buf')
.then(function (content) {
expectations(content);
done();
});
});
it('gives nice error message when JSON parsing failed', function (done) {
it('reads file as JSON', function (done) {
var obj = {
utf8: 'ąćłźż'
};
var expectations = function (content) {
expect(content).toEqual(obj);
};
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('file.json', '{ "abc: 123 }'); // Malformed JSON
};
fse.outputFileSync('file.json', JSON.stringify(obj));
var expectations = function (err) {
expect(err.message).toContain('JSON parsing failed while reading');
};
// SYNC
expectations(jetpack.read('file.json', 'json'));
// SYNC
preparations();
try {
jetpack.read('file.json', 'json');
} catch (err) {
expectations(err);
}
// ASYNC
preparations();
jetpack.readAsync('file.json', 'json')
.catch(function (err) {
expectations(err);
done();
});
// ASYNC
jetpack.readAsync('file.json', 'json')
.then(function (content) {
expectations(content);
done();
});
});
it('reads file as JSON with Date parsing', function (done) {
it('gives nice error message when JSON parsing failed', function (done) {
var expectations = function (err) {
expect(err.message).toContain('JSON parsing failed while reading');
};
var obj = {
utf8: "ąćłźż",
date: new Date(),
};
fse.outputFileSync('file.json', '{ "abc: 123 }'); // Malformed JSON
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('file.json', JSON.stringify(obj));
};
// SYNC
try {
jetpack.read('file.json', 'json');
} catch (err) {
expectations(err);
}
var expectations = function (content) {
expect(content).toEqual(obj);
};
// SYNC
preparations();
var contentSync = jetpack.read('file.json', 'jsonWithDates');
expectations(contentSync);
// ASYNC
preparations();
jetpack.readAsync('file.json', 'jsonWithDates')
.then(function (contentAsync) {
expectations(contentAsync);
done();
});
// ASYNC
jetpack.readAsync('file.json', 'json')
.catch(function (err) {
expectations(err);
done();
});
});
it("returns null if file doesn't exist", function (done) {
it('reads file as JSON with Date parsing', function (done) {
var obj = {
utf8: 'ąćłźż',
date: new Date()
};
var expectations = function (content) {
expect(content).toEqual(obj);
};
var expectations = function (content) {
expect(content).toBe(null);
};
fse.outputFileSync('file.json', JSON.stringify(obj));
// SYNC
var contentSync = jetpack.read('nonexistent.txt');
expectations(contentSync);
// SYNC
expectations(jetpack.read('file.json', 'jsonWithDates'));
// ASYNC
jetpack.readAsync('nonexistent.txt')
.then(function (contentAsync) {
expectations(contentAsync);
done();
});
// ASYNC
jetpack.readAsync('file.json', 'jsonWithDates')
.then(function (content) {
expectations(content);
done();
});
});
it("throws if given path is a directory", function (done) {
it("returns null if file doesn't exist", function (done) {
var expectations = function (content) {
expect(content).toBe(null);
};
var preparations = function () {
fse.mkdirsSync('dir');
};
// SYNC
expectations(jetpack.read('nonexistent.txt'));
var expectations = function (err) {
expect(err.code).toBe('EISDIR');
};
// ASYNC
jetpack.readAsync('nonexistent.txt')
.then(function (content) {
expectations(content);
done();
});
});
preparations();
it('throws if given path is a directory', function (done) {
var expectations = function (err) {
expect(err.code).toBe('EISDIR');
};
// SYNC
try {
jetpack.read('dir');
throw new Error('to make sure this code throws');
} catch (err) {
expectations(err);
}
fse.mkdirsSync('dir');
// ASYNC
jetpack.readAsync('dir')
.catch(function (err) {
expectations(err);
done();
});
// SYNC
try {
jetpack.read('dir');
throw new Error('to make sure this code throws');
} catch (err) {
expectations(err);
}
// ASYNC
jetpack.readAsync('dir')
.catch(function (err) {
expectations(err);
done();
});
});
it("respects internal CWD of jetpack instance", function (done) {
it('respects internal CWD of jetpack instance', function (done) {
var expectations = function (data) {
expect(data).toBe('abc');
};
var preparations = function () {
fse.outputFileSync('a/file.txt', 'abc');
};
var jetContext = jetpack.cwd('a');
fse.outputFileSync('a/file.txt', 'abc');
var expectations = function (data) {
expect(data).toBe('abc');
};
// SYNC
expectations(jetContext.read('file.txt'));
preparations();
var jetContext = jetpack.cwd('a');
// SYNC
var dataSync = jetContext.read('file.txt');
expectations(dataSync);
// ASYNC
jetContext.readAsync('file.txt')
.then(function (dataAsync) {
expectations(dataAsync);
done();
});
// ASYNC
jetContext.readAsync('file.txt')
.then(function (data) {
expectations(data);
done();
});
});
});
/* eslint-env jasmine */
"use strict";
'use strict';
describe('remove', function () {
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
it("doesn't throw if path already doesn't exist", function (done) {
// SYNC
jetpack.remove('dir');
it("doesn't throw if path already doesn't exist", function (done) {
// SYNC
jetpack.remove('dir');
// ASYNC
jetpack.removeAsync('dir')
.then(function () {
done();
});
// ASYNC
jetpack.removeAsync('dir')
.then(function () {
done();
});
});
it("should delete file", function (done) {
it('should delete file', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('file.txt', 'abc');
};
var expectations = function () {
expect('file.txt').not.toExist();
};
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('file.txt', 'abc');
};
// SYNC
preparations();
jetpack.remove('file.txt');
expectations();
var expectations = function () {
expect('file.txt').not.toExist();
};
// SYNC
preparations();
jetpack.remove('file.txt');
expectations();
// ASYNC
preparations();
jetpack.removeAsync('file.txt')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.removeAsync('file.txt')
.then(function () {
expectations();
done();
});
});
it("removes directory with stuff inside", function (done) {
it('removes directory with stuff inside', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirsSync('a/b/c');
fse.outputFileSync('a/f.txt', 'abc');
fse.outputFileSync('a/b/f.txt', '123');
};
var expectations = function () {
expect('a').not.toExist();
};
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirsSync('a/b/c');
fse.outputFileSync('a/f.txt', 'abc');
fse.outputFileSync('a/b/f.txt', '123');
};
// SYNC
preparations();
jetpack.remove('a');
expectations();
var expectations = function () {
expect('a').not.toExist();
};
// SYNC
preparations();
jetpack.remove('a');
expectations();
// ASYNC
preparations();
jetpack.removeAsync('a')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.removeAsync('a')
.then(function () {
expectations();
done();
});
});
it("respects internal CWD of jetpack instance", function (done) {
it('respects internal CWD of jetpack instance', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b/c.txt', '123');
};
var expectations = function () {
expect('a').toExist();
expect('a/b').not.toExist();
};
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b/c.txt', '123');
};
var jetContext = jetpack.cwd('a');
var expectations = function () {
expect('a').toExist();
expect('a/b').not.toExist();
};
// SYNC
preparations();
jetContext.remove('b');
expectations();
var jetContext = jetpack.cwd('a');
// SYNC
preparations();
jetContext.remove('b');
expectations();
// ASYNC
preparations();
jetContext.removeAsync('b')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetContext.removeAsync('b')
.then(function () {
expectations();
done();
});
});
describe('*nix specific', function () {
it('can be called witn no parameters, what will remove CWD directory', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b/c.txt', 'abc');
};
var expectations = function () {
expect('a').not.toExist();
};
if (process.platform === 'win32') {
return;
}
var jetContext = jetpack.cwd('a');
it('removes only symlinks, never real content where symlinks point', function (done) {
// SYNC
preparations();
jetContext.remove();
expectations();
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('have_to_stay_file', 'abc');
fse.mkdirsSync('to_remove');
fse.symlinkSync('../have_to_stay_file', 'to_remove/symlink');
// Make sure we symlinked it properly.
expect(fse.readFileSync('to_remove/symlink', 'utf8')).toBe('abc');
};
// ASYNC
preparations();
jetContext.removeAsync()
.then(function () {
expectations();
done();
});
});
var expectations = function () {
expect('have_to_stay_file').toBeFileWithContent('abc');
expect('to_remove').not.toExist();
};
describe('*nix specific', function () {
if (process.platform === 'win32') {
return;
}
// SYNC
preparations();
jetpack.remove('to_remove');
expectations();
it('removes only symlinks, never real content where symlinks point', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('have_to_stay_file', 'abc');
fse.mkdirsSync('to_remove');
fse.symlinkSync('../have_to_stay_file', 'to_remove/symlink');
// Make sure we symlinked it properly.
expect(fse.readFileSync('to_remove/symlink', 'utf8')).toBe('abc');
};
var expectations = function () {
expect('have_to_stay_file').toBeFileWithContent('abc');
expect('to_remove').not.toExist();
};
// ASYNC
preparations();
jetpack.removeAsync('to_remove')
.then(function () {
expectations();
done();
});
});
// SYNC
preparations();
jetpack.remove('to_remove');
expectations();
// ASYNC
preparations();
jetpack.removeAsync('to_remove')
.then(function () {
expectations();
done();
});
});
});
});
/* eslint-env jasmine */
"use strict";
'use strict';
describe('rename |', function () {
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
it('renames file', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b.txt', 'abc');
};
var expectations = function () {
expect('a/b.txt').not.toExist();
expect('a/x.txt').toBeFileWithContent('abc');
};
it("renames file", function (done) {
// SYNC
preparations();
jetpack.rename('a/b.txt', 'x.txt');
expectations();
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b.txt', 'abc');
};
var expectations = function () {
expect('a/b.txt').not.toExist();
expect('a/x.txt').toBeFileWithContent('abc');
};
// SYNC
preparations();
jetpack.rename('a/b.txt', 'x.txt');
expectations();
// ASYNC
preparations();
jetpack.renameAsync('a/b.txt', 'x.txt')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.renameAsync('a/b.txt', 'x.txt')
.then(function () {
expectations();
done();
});
});
it("renames directory", function (done) {
it('renames directory', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b/c.txt', 'abc');
};
var expectations = function () {
expect('a/b').not.toExist();
expect('a/x').toBeDirectory();
};
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b/c.txt', 'abc');
};
// SYNC
preparations();
jetpack.rename('a/b', 'x');
expectations();
var expectations = function () {
expect('a/b').not.toExist();
expect('a/x').toBeDirectory();
};
// SYNC
preparations();
jetpack.rename('a/b', 'x');
expectations();
// ASYNC
preparations();
jetpack.renameAsync('a/b', 'x')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.renameAsync('a/b', 'x')
.then(function () {
expectations();
done();
});
});
it("respects internal CWD of jetpack instance", function (done) {
it('respects internal CWD of jetpack instance', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b/c.txt', 'abc');
};
var expectations = function () {
expect('a/b').not.toExist();
expect('a/x').toBeDirectory();
};
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync('a/b/c.txt', 'abc');
};
var jetContext = jetpack.cwd('a');
var expectations = function () {
expect('a/b').not.toExist();
expect('a/x').toBeDirectory();
};
// SYNC
preparations();
jetContext.rename('b', 'x');
expectations();
var jetContext = jetpack.cwd('a');
// SYNC
preparations();
jetContext.rename('b', 'x');
expectations();
// ASYNC
preparations();
jetContext.renameAsync('b', 'x')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetContext.renameAsync('b', 'x')
.then(function () {
expectations();
done();
});
});
});
/* eslint-env jasmine */
"use strict";
'use strict';
describe('streams |', function () {
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
it('exposes vanilla stream methods', function (done) {
var input;
var output;
it("exposes vanilla stream methods", function (done) {
fse.outputFileSync('a.txt', 'abc');
fse.outputFileSync('a.txt', 'abc');
var output = jetpack.createWriteStream('b.txt');
var input = jetpack.createReadStream('a.txt');
output.on('finish', function () {
expect('b.txt').toBeFileWithContent('abc');
done();
});
input.pipe(output);
input = jetpack.createReadStream('a.txt');
output = jetpack.createWriteStream('b.txt');
output.on('finish', function () {
expect('b.txt').toBeFileWithContent('abc');
done();
});
input.pipe(output);
});
it("stream methods respect jetpack internal CWD", function (done) {
fse.outputFileSync('dir/a.txt', 'abc');
it('stream methods respect jetpack internal CWD', function (done) {
var input;
var output;
var dir = jetpack.cwd('dir');
var output = dir.createWriteStream('b.txt');
var input = dir.createReadStream('a.txt');
output.on('finish', function () {
expect('dir/b.txt').toBeFileWithContent('abc');
done();
});
input.pipe(output);
var dir = jetpack.cwd('dir');
fse.outputFileSync('dir/a.txt', 'abc');
input = dir.createReadStream('a.txt');
output = dir.createWriteStream('b.txt');
output.on('finish', function () {
expect('dir/b.txt').toBeFileWithContent('abc');
done();
});
input.pipe(output);
});
});

@@ -6,100 +6,102 @@ 'use strict';

module.exports.toExist = function () {
return {
compare: function (path) {
var pass = true;
var message = 'Path ' + path + ' should exist';
try {
fs.statSync(path);
} catch (err) {
pass = false;
}
return {
pass: pass,
message: message,
};
},
negativeCompare: function (path) {
var pass = false;
var message = "Path " + path + " shouldn't exist";
try {
fs.statSync(path);
} catch (err) {
pass = true;
}
return {
pass: pass,
message: message,
};
},
};
return {
compare: function (path) {
var pass = true;
var message = 'Path ' + path + ' should exist';
try {
fs.statSync(path);
} catch (err) {
pass = false;
}
return {
pass: pass,
message: message
};
},
negativeCompare: function (path) {
var pass = false;
var message = 'Path ' + path + " shouldn't exist";
try {
fs.statSync(path);
} catch (err) {
pass = true;
}
return {
pass: pass,
message: message
};
}
};
};
module.exports.toBeDirectory = function () {
return {
compare: function (path) {
var pass;
var message = 'Path ' + path + ' should be directory';
try {
var stat = fs.statSync(path);
pass = stat.isDirectory();
} catch (err) {
// For sure not a directory.
pass = false;
}
return {
pass: pass,
message: message,
};
},
};
return {
compare: function (path) {
var pass;
var message = 'Path ' + path + ' should be directory';
var stat;
try {
stat = fs.statSync(path);
pass = stat.isDirectory();
} catch (err) {
// For sure not a directory.
pass = false;
}
return {
pass: pass,
message: message
};
}
};
};
module.exports.toBeFileWithContent = function () {
return {
compare: function (path, expectedContent) {
var pass = true;
var message = 'File ' + path + ' should have content "'
+ expectedContent + '"';
try {
var fileContent = fs.readFileSync(path, 'utf8');
if (fileContent !== expectedContent) {
pass = false;
message = 'File ' + path + ' should have content "'
+ expectedContent + '" but have "' + fileContent + '"';
}
} catch (err) {
pass = false;
message = 'File ' + path + ' should exist';
}
return {
pass: pass,
message: message,
};
},
};
return {
compare: function (path, expectedContent) {
var pass = true;
var message = 'File ' + path + ' should have content "' + expectedContent + '"';
var fileContent;
try {
fileContent = fs.readFileSync(path, 'utf8');
if (fileContent !== expectedContent) {
pass = false;
message = 'File ' + path + ' should have content "'
+ expectedContent + '" but have "' + fileContent + '"';
}
} catch (err) {
pass = false;
message = 'File ' + path + ' should exist';
}
return {
pass: pass,
message: message
};
}
};
};
module.exports.toHaveMode = function () {
return {
compare: function (path, expectedMode) {
var pass = true;
var message = 'File ' + path + ' should have mode ' + expectedMode;
try {
var mode = fs.statSync(path).mode.toString(8);
mode = mode.substring(mode.length - 3);
if (mode !== expectedMode) {
pass = false;
message = 'File ' + path + ' should have mode '
+ expectedMode + ' but has ' + mode;
}
} catch (err) {
pass = false;
message = 'File ' + path + ' should exist';
}
return {
pass: pass,
message: message,
};
},
};
return {
compare: function (path, expectedMode) {
var pass = true;
var message = 'File ' + path + ' should have mode ' + expectedMode;
var mode;
try {
mode = fs.statSync(path).mode.toString(8);
mode = mode.substring(mode.length - 3);
if (mode !== expectedMode) {
pass = false;
message = 'File ' + path + ' should have mode '
+ expectedMode + ' but has ' + mode;
}
} catch (err) {
pass = false;
message = 'File ' + path + ' should exist';
}
return {
pass: pass,
message: message
};
}
};
};

@@ -5,3 +5,3 @@ /* eslint-env jasmine */

"use strict";
'use strict';

@@ -14,4 +14,2 @@ var fse = require('fs-extra');

jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
var originalCwd = process.cwd();

@@ -22,46 +20,48 @@ // The directory we will be using as CWD for tests.

var clearWorkingDir = function () {
// Clear all contents, but don't remove the main directory
// (you can't because it is CWD).
fse.readdirSync('.').forEach(function (filename) {
fse.removeSync(filename);
});
// Clear all contents, but don't remove the main directory
// (you can't because it is CWD).
fse.readdirSync('.').forEach(function (filename) {
fse.removeSync(filename);
});
if (fse.readdirSync('.').length > 0) {
throw new Error("Clearing working directory failed!");
}
if (fse.readdirSync('.').length > 0) {
throw new Error('Clearing working directory failed!');
}
};
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
module.exports.clearWorkingDir = clearWorkingDir;
module.exports.beforeEach = function (done) {
jasmine.addMatchers(customMatchers);
jasmine.addMatchers(customMatchers);
// Create brand new working directory
fse.remove(workingDir, function () {
fse.mkdirSync(workingDir);
// Create brand new working directory
fse.remove(workingDir, function () {
fse.mkdirSync(workingDir);
// Set CWD there
process.chdir(workingDir);
// Better to be safe than sorry
if (pathUtil.basename(process.cwd()) !== 'fs-jetpack-test') {
throw new Error("CWD switch failed!");
}
// Set CWD there
process.chdir(workingDir);
// Better to be safe than sorry
if (pathUtil.basename(process.cwd()) !== 'fs-jetpack-test') {
throw new Error('CWD switch failed!');
}
done();
});
done();
});
};
module.exports.afterEach = function (done) {
// Switch CWD back where we were, and clean the clutter.
process.chdir(originalCwd);
fse.remove(workingDir, done);
// Switch CWD back where we were, and clean the clutter.
process.chdir(originalCwd);
fse.remove(workingDir, done);
};
module.exports.convertToUnixPathSeparators = function (thing) {
if (Array.isArray(thing)) {
return thing.map(function (path) {
return path.replace(/\\/g, '/');
});
}
return thing.replace(/\\/g, '/');
if (Array.isArray(thing)) {
return thing.map(function (path) {
return path.replace(/\\/g, '/');
});
}
return thing.replace(/\\/g, '/');
};
/* eslint-env jasmine */
"use strict";
'use strict';
describe('symlink |', function () {
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
it('can create a symlink', function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect(fse.lstatSync('symlink').isSymbolicLink()).toBe(true);
expect(fse.readlinkSync('symlink')).toBe('some_path');
};
it("can create a symlink", function (done) {
// SYNC
preparations();
jetpack.symlink('some_path', 'symlink');
expectations();
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect(fse.lstatSync('symlink').isSymbolicLink()).toBe(true);
expect(fse.readlinkSync('symlink')).toBe('some_path');
};
// SYNC
preparations();
jetpack.symlink('some_path', 'symlink');
expectations();
// ASYNC
preparations();
jetpack.symlinkAsync('some_path', 'symlink')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.symlinkAsync('some_path', 'symlink')
.then(function () {
expectations();
done();
});
});
it("can create nonexistent parent directories", function (done) {
it('can create nonexistent parent directories', function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect(fse.lstatSync('a/b/symlink').isSymbolicLink()).toBe(true);
};
var preparations = function () {
helper.clearWorkingDir();
};
// SYNC
preparations();
jetpack.symlink('whatever', 'a/b/symlink');
expectations();
var expectations = function () {
expect(fse.lstatSync('a/b/symlink').isSymbolicLink()).toBe(true);
};
// SYNC
preparations();
jetpack.symlink('whatever', 'a/b/symlink');
expectations();
// ASYNC
preparations();
jetpack.symlinkAsync('whatever', 'a/b/symlink')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.symlinkAsync('whatever', 'a/b/symlink')
.then(function () {
expectations();
done();
});
});
it("respects internal CWD of jetpack instance", function (done) {
it('respects internal CWD of jetpack instance', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirsSync('a/b');
};
var expectations = function () {
expect(fse.lstatSync('a/b/symlink').isSymbolicLink()).toBe(true);
};
var preparations = function () {
helper.clearWorkingDir();
fse.mkdirsSync('a/b');
};
var jetContext = jetpack.cwd('a/b');
var expectations = function () {
expect(fse.lstatSync('a/b/symlink').isSymbolicLink()).toBe(true);
};
// SYNC
preparations();
jetContext.symlink('whatever', 'symlink');
expectations();
var jetContext = jetpack.cwd('a/b');
// SYNC
preparations();
jetContext.symlink('whatever', 'symlink');
expectations();
// ASYNC
preparations();
jetContext.symlinkAsync('whatever', 'symlink')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetContext.symlinkAsync('whatever', 'symlink')
.then(function () {
expectations();
done();
});
});
});
/* eslint-env jasmine */
"use strict";
'use strict';
describe('matcher |', function () {
var matcher = require('../../lib/utils/matcher');
var matcher = require('../../lib/utils/matcher');
it('can test against one pattern passed as a string', function () {
var test = matcher.create('a');
expect(test('/a')).toBe(true);
expect(test('/b')).toBe(false);
});
it("can test against one pattern passed as a string", function () {
var test = matcher.create('a');
expect(test('/a')).toBe(true);
expect(test('/b')).toBe(false);
it('can test against many patterns passed as an array', function () {
var test = matcher.create(['a', 'b']);
expect(test('/a')).toBe(true);
expect(test('/b')).toBe(true);
expect(test('/c')).toBe(false);
});
describe('possible mask tokens |', function () {
it('*', function () {
var test = matcher.create(['*']);
expect(test('/a')).toBe(true);
expect(test('/a/b.txt')).toBe(true);
test = matcher.create(['a*b']);
expect(test('/ab')).toBe(true);
expect(test('/a_b')).toBe(true);
expect(test('/a__b')).toBe(true);
});
it("can test against many patterns passed as an array", function () {
var test = matcher.create(['a', 'b']);
expect(test('/a')).toBe(true);
expect(test('/b')).toBe(true);
expect(test('/c')).toBe(false);
it('/*', function () {
var test = matcher.create(['/*']);
expect(test('/a')).toBe(true);
expect(test('/a/b')).toBe(false);
});
describe('possible mask tokens |', function () {
it('**', function () {
var test = matcher.create(['**']);
expect(test('/a')).toBe(true);
expect(test('/a/b')).toBe(true);
it("*", function () {
var test = matcher.create(['*']);
expect(test('/a')).toBe(true);
expect(test('/a/b.txt')).toBe(true);
test = matcher.create(['/a/**/d']);
expect(test('/a/d')).toBe(true);
expect(test('/a/b/d')).toBe(true);
expect(test('/a/b/c/d')).toBe(true);
expect(test('/a')).toBe(false);
expect(test('/d')).toBe(false);
});
test = matcher.create(['a*b']);
expect(test('/ab')).toBe(true);
expect(test('/a_b')).toBe(true);
expect(test('/a__b')).toBe(true);
});
it('/**/something', function () {
var test = matcher.create(['/**/a']);
expect(test('/a')).toBe(true);
expect(test('/x/a')).toBe(true);
expect(test('/x/y/a')).toBe(true);
expect(test('/a/b')).toBe(false);
});
it("/*", function () {
var test = matcher.create(['/*']);
expect(test('/a')).toBe(true);
expect(test('/a/b')).toBe(false);
});
it('+(option1|option2)', function () {
var test = matcher.create(['*.+(txt|md)']);
expect(test('/a.txt')).toBe(true);
expect(test('/b.md')).toBe(true);
expect(test('/c.rtf')).toBe(false);
});
it("**", function () {
var test = matcher.create(['**']);
expect(test('/a')).toBe(true);
expect(test('/a/b')).toBe(true);
it('{a,b}', function () {
var test = matcher.create(['*.{jpg,png}']);
expect(test('a.jpg')).toBe(true);
expect(test('b.png')).toBe(true);
expect(test('c.txt')).toBe(false);
});
test = matcher.create(['/a/**/d']);
expect(test('/a/d')).toBe(true);
expect(test('/a/b/d')).toBe(true);
expect(test('/a/b/c/d')).toBe(true);
expect(test('/a')).toBe(false);
expect(test('/d')).toBe(false);
});
it('?', function () {
var test = matcher.create(['a?c']);
expect(test('/abc')).toBe(true);
expect(test('/ac')).toBe(false);
expect(test('/abbc')).toBe(false);
});
it("/**/something", function () {
var test = matcher.create(['/**/a']);
expect(test('/a')).toBe(true);
expect(test('/x/a')).toBe(true);
expect(test('/x/y/a')).toBe(true);
expect(test('/a/b')).toBe(false);
});
it('comment character # havs no special meaning', function () {
var test = matcher.create(['#a']);
expect(test('/#a')).toBe(true);
});
});
it("+(option1|option2)", function () {
var test = matcher.create(['*.+(txt|md)']);
expect(test('/a.txt')).toBe(true);
expect(test('/b.md')).toBe(true);
expect(test('/c.rtf')).toBe(false);
});
describe('negation', function () {
it('selects everything except negated for one defined pattern', function () {
var test = matcher.create('!abc');
expect(test('/abc')).toBe(false);
expect(test('/xyz')).toBe(true);
});
it("{a,b}", function () {
var test = matcher.create(['*.{jpg,png}']);
expect(test('a.jpg')).toBe(true);
expect(test('b.png')).toBe(true);
expect(test('c.txt')).toBe(false);
});
it("?", function () {
var test = matcher.create(['a?c']);
expect(test('/abc')).toBe(true);
expect(test('/ac')).toBe(false);
expect(test('/abbc')).toBe(false);
});
it("comment character # havs no special meaning", function () {
var test = matcher.create(['#a']);
expect(test('/#a')).toBe(true);
});
it('selects everything except negated for multiple patterns', function () {
var test = matcher.create(['!abc', '!xyz']);
expect(test('/abc')).toBe(false);
expect(test('/xyz')).toBe(false);
expect(test('/whatever')).toBe(true);
});
describe("negation", function () {
it("selects everything except negated for one defined pattern", function () {
var test = matcher.create('!abc');
expect(test('/abc')).toBe(false);
expect(test('/xyz')).toBe(true);
});
it("selects everything except negated for multiple patterns", function () {
var test = matcher.create(['!abc', '!xyz']);
expect(test('/abc')).toBe(false);
expect(test('/xyz')).toBe(false);
expect(test('/whatever')).toBe(true);
});
it("filters previous match if negation is farther in order", function () {
var test = matcher.create(['abc', '123', '!/xyz/**', '!/789/**']);
expect(test('/abc')).toBe(true);
expect(test('/456/123')).toBe(true);
expect(test('/xyz/abc')).toBe(false);
expect(test('/789/123')).toBe(false);
expect(test('/whatever')).toBe(false);
});
it('filters previous match if negation is farther in order', function () {
var test = matcher.create(['abc', '123', '!/xyz/**', '!/789/**']);
expect(test('/abc')).toBe(true);
expect(test('/456/123')).toBe(true);
expect(test('/xyz/abc')).toBe(false);
expect(test('/789/123')).toBe(false);
expect(test('/whatever')).toBe(false);
});
});
});
/* eslint-env jasmine */
"use strict";
'use strict';
describe('atomic write |', function () {
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
var path = 'file.txt';
var newPath = path + '.__new__';
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
var path = 'file.txt';
var newPath = path + '.__new__';
it("fresh write (file doesn't exist yet)", function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect(path).toBeFileWithContent('abc');
expect(newPath).not.toExist();
};
it("fresh write (file doesn't exist yet)", function (done) {
// SYNC
preparations();
jetpack.write(path, 'abc', { atomic: true });
expectations();
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect(path).toBeFileWithContent('abc');
expect(newPath).not.toExist();
};
// SYNC
preparations();
jetpack.write(path, 'abc', { atomic: true });
expectations();
// ASYNC
preparations();
jetpack.writeAsync(path, 'abc', { atomic: true })
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.writeAsync(path, 'abc', { atomic: true })
.then(function () {
expectations();
done();
});
});
it('overwrite existing file', function (done) {
it('overwrite existing file', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync(path, 'xyz');
};
var expectations = function () {
expect(path).toBeFileWithContent('abc');
expect(newPath).not.toExist();
};
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync(path, 'xyz');
};
// SYNC
preparations();
jetpack.write(path, 'abc', { atomic: true });
expectations();
var expectations = function () {
expect(path).toBeFileWithContent('abc');
expect(newPath).not.toExist();
};
// SYNC
preparations();
jetpack.write(path, 'abc', { atomic: true });
expectations();
// ASYNC
preparations();
jetpack.writeAsync(path, 'abc', { atomic: true })
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.writeAsync(path, 'abc', { atomic: true })
.then(function () {
expectations();
done();
});
});
it('if previous operation failed', function (done) {
it('if previous operation failed', function (done) {
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync(path, 'xyz');
// File from interrupted previous operation remained.
fse.outputFileSync(newPath, '123');
};
var expectations = function () {
expect(path).toBeFileWithContent('abc');
expect(newPath).not.toExist();
};
var preparations = function () {
helper.clearWorkingDir();
fse.outputFileSync(path, 'xyz');
// File from interrupted previous operation remained.
fse.outputFileSync(newPath, '123');
};
// SYNC
preparations();
jetpack.write(path, 'abc', { atomic: true });
expectations();
var expectations = function () {
expect(path).toBeFileWithContent('abc');
expect(newPath).not.toExist();
};
// SYNC
preparations();
jetpack.write(path, 'abc', { atomic: true });
expectations();
// ASYNC
preparations();
jetpack.writeAsync(path, 'abc', { atomic: true })
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.writeAsync(path, 'abc', { atomic: true })
.then(function () {
expectations();
done();
});
});
});
/* eslint-env jasmine */
"use strict";
'use strict';
describe('write |', function () {
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
var fse = require('fs-extra');
var helper = require('./support/spec_helper');
var jetpack = require('..');
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
beforeEach(helper.beforeEach);
afterEach(helper.afterEach);
it('writes data from string', function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('file.txt').toBeFileWithContent('abc');
};
it('writes data from string', function (done) {
// SYNC
preparations();
jetpack.write('file.txt', 'abc');
expectations();
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('file.txt').toBeFileWithContent('abc');
};
// SYNC
preparations();
jetpack.write('file.txt', 'abc');
expectations();
// ASYNC
preparations();
jetpack.writeAsync('file.txt', 'abc')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.writeAsync('file.txt', 'abc')
.then(function () {
expectations();
done();
});
});
it('writes data from Buffer', function (done) {
it('writes data from Buffer', function (done) {
var buf = new Buffer([11, 22]);
var buf = new Buffer([11, 22]);
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
var content = fse.readFileSync('file.txt');
expect(content.length).toBe(2);
expect(content[0]).toBe(11);
expect(content[1]).toBe(22);
};
var preparations = function () {
helper.clearWorkingDir();
};
// SYNC
preparations();
jetpack.write('file.txt', buf);
expectations();
var expectations = function () {
var content = fse.readFileSync('file.txt');
expect(content.length).toBe(2);
expect(content[0]).toBe(11);
expect(content[1]).toBe(22);
};
// SYNC
preparations();
jetpack.write('file.txt', buf);
expectations();
// ASYNC
preparations();
jetpack.writeAsync('file.txt', buf)
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.writeAsync('file.txt', buf)
.then(function () {
expectations();
done();
});
});
it('writes data as JSON', function (done) {
it('writes data as JSON', function (done) {
var obj = {
utf8: 'ąćłźż'
};
var obj = {
utf8: "ąćłźż",
};
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
var content = JSON.parse(fse.readFileSync('file.json', 'utf8'));
expect(content).toEqual(obj);
};
var preparations = function () {
helper.clearWorkingDir();
};
// SYNC
preparations();
jetpack.write('file.json', obj);
expectations();
var expectations = function () {
var content = JSON.parse(fse.readFileSync('file.json', 'utf8'));
expect(content).toEqual(obj);
};
// SYNC
preparations();
jetpack.write('file.json', obj);
expectations();
// ASYNC
preparations();
jetpack.writeAsync('file.json', obj)
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.writeAsync('file.json', obj)
.then(function () {
expectations();
done();
});
});
it('written JSON data can be indented', function (done) {
it('written JSON data can be indented', function (done) {
var obj = {
utf8: 'ąćłźż'
};
var obj = {
utf8: "ąćłźż",
};
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
var sizeA = fse.statSync('a.json').size;
var sizeB = fse.statSync('b.json').size;
var sizeC = fse.statSync('c.json').size;
expect(sizeB).toBeGreaterThan(sizeA);
expect(sizeC).toBeGreaterThan(sizeB);
};
var preparations = function () {
helper.clearWorkingDir();
};
// SYNC
preparations();
jetpack.write('a.json', obj, { jsonIndent: 0 });
jetpack.write('b.json', obj); // Default indent = 2
jetpack.write('c.json', obj, { jsonIndent: 4 });
expectations();
var expectations = function () {
var sizeA = fse.statSync('a.json').size;
var sizeB = fse.statSync('b.json').size;
var sizeC = fse.statSync('c.json').size;
expect(sizeB).toBeGreaterThan(sizeA);
expect(sizeC).toBeGreaterThan(sizeB);
};
// SYNC
preparations();
jetpack.write('a.json', obj, { jsonIndent: 0 });
jetpack.write('b.json', obj); // Default indent = 2
jetpack.write('c.json', obj, { jsonIndent: 4 });
expectations();
// ASYNC
preparations();
jetpack.writeAsync('a.json', obj, { jsonIndent: 0 })
.then(function () {
return jetpack.writeAsync('b.json', obj); // Default indent = 2
})
.then(function () {
return jetpack.writeAsync('c.json', obj, { jsonIndent: 4 });
})
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.writeAsync('a.json', obj, { jsonIndent: 0 })
.then(function () {
return jetpack.writeAsync('b.json', obj); // Default indent = 2
})
.then(function () {
return jetpack.writeAsync('c.json', obj, { jsonIndent: 4 });
})
.then(function () {
expectations();
done();
});
});
it('writes and reads file as JSON with Date parsing', function (done) {
it('writes and reads file as JSON with Date parsing', function (done) {
var obj = {
date: new Date()
};
var obj = {
date: new Date(),
};
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
var content = JSON.parse(fse.readFileSync('file.json', 'utf8'));
expect(content.date).toBe(obj.date.toISOString());
};
var preparations = function () {
helper.clearWorkingDir();
};
// SYNC
preparations();
jetpack.write('file.json', obj);
expectations();
var expectations = function () {
var content = JSON.parse(fse.readFileSync('file.json', 'utf8'));
expect(content.date).toBe(obj.date.toISOString());
};
// SYNC
preparations();
jetpack.write('file.json', obj);
expectations();
// ASYNC
preparations();
jetpack.writeAsync('file.json', obj)
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.writeAsync('file.json', obj)
.then(function () {
expectations();
done();
});
});
it("write can create nonexistent parent directories", function (done) {
it('write can create nonexistent parent directories', function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('a/b/c.txt').toBeFileWithContent('abc');
};
var preparations = function () {
helper.clearWorkingDir();
};
// SYNC
preparations();
jetpack.write('a/b/c.txt', 'abc');
expectations();
var expectations = function () {
expect('a/b/c.txt').toBeFileWithContent('abc');
};
// SYNC
preparations();
jetpack.write('a/b/c.txt', 'abc');
expectations();
// ASYNC
preparations();
jetpack.writeAsync('a/b/c.txt', 'abc')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetpack.writeAsync('a/b/c.txt', 'abc')
.then(function () {
expectations();
done();
});
});
it("respects internal CWD of jetpack instance", function (done) {
it('respects internal CWD of jetpack instance', function (done) {
var preparations = function () {
helper.clearWorkingDir();
};
var expectations = function () {
expect('a/b/c.txt').toBeFileWithContent('abc');
};
var preparations = function () {
helper.clearWorkingDir();
};
var jetContext = jetpack.cwd('a');
var expectations = function () {
expect('a/b/c.txt').toBeFileWithContent('abc');
};
// SYNC
preparations();
jetContext.write('b/c.txt', 'abc');
expectations();
var jetContext = jetpack.cwd('a');
// SYNC
preparations();
jetContext.write('b/c.txt', 'abc');
expectations();
// ASYNC
preparations();
jetContext.writeAsync('b/c.txt', 'abc')
.then(function () {
expectations();
done();
});
// ASYNC
preparations();
jetContext.writeAsync('b/c.txt', 'abc')
.then(function () {
expectations();
done();
});
});
});

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc