shelljs/test/sed.js
Nate Fischer 1ee696d824 fix: regexes are more consistent with sed and grep
sed will now convert search strings to regex form, so `'a*'` will now work like
`/a*/`. Also, new tests for grep and sed ensure that '*' is not expanded for
filename globbing.
2016-01-23 21:16:43 -08:00

78 lines
2.3 KiB
JavaScript

var shell = require('..');
var assert = require('assert'),
fs = require('fs');
shell.config.silent = true;
shell.rm('-rf', 'tmp');
shell.mkdir('tmp');
//
// Invalids
//
shell.sed();
assert.ok(shell.error());
shell.sed(/asdf/g); // too few args
assert.ok(shell.error());
shell.sed(/asdf/g, 'nada'); // too few args
assert.ok(shell.error());
assert.equal(fs.existsSync('/asdfasdf'), false); // sanity check
shell.sed(/asdf/g, 'nada', '/asdfasdf'); // no such file
assert.ok(shell.error());
//
// Valids
//
shell.cp('-f', 'resources/file1', 'tmp/file1');
var result = shell.sed('test1', 'hello', 'tmp/file1'); // search string
assert.equal(shell.error(), null);
assert.equal(result, 'hello');
var result = shell.sed(/test1/, 'hello', 'tmp/file1'); // search regex
assert.equal(shell.error(), null);
assert.equal(result, 'hello');
var result = shell.sed(/test1/, 1234, 'tmp/file1'); // numeric replacement
assert.equal(shell.error(), null);
assert.equal(result, '1234');
var replaceFun = function (match) {
return match.toUpperCase() + match;
};
var result = shell.sed(/test1/, replaceFun, 'tmp/file1'); // replacement function
assert.equal(shell.error(), null);
assert.equal(result, 'TEST1test1');
var result = shell.sed('-i', /test1/, 'hello', 'tmp/file1');
assert.equal(shell.error(), null);
assert.equal(result, 'hello');
assert.equal(shell.cat('tmp/file1'), 'hello');
// make sure * in regex is not globbed
var result = shell.sed(/alpha*beta/, 'hello', 'resources/grep/file');
assert.equal(shell.error(), null);
assert.equal(result, 'hello\nhowareyou\nhello\nthis line ends in.js\nlllllllllllllllll.js\n');
// make sure * in string-regex is not globbed
var result = shell.sed('alpha*beta', 'hello', 'resources/grep/file');
assert.ok(!shell.error());
assert.equal(result, 'hello\nhowareyou\nhello\nthis line ends in.js\nlllllllllllllllll.js\n');
// make sure * in regex is not globbed
var result = shell.sed(/l*\.js/, '', 'resources/grep/file');
assert.ok(!shell.error());
assert.equal(result, 'alphaaaaaaabeta\nhowareyou\nalphbeta\nthis line ends in\n\n');
// make sure * in string-regex is not globbed
var result = shell.sed('l*\\.js', '', 'resources/grep/file');
assert.ok(!shell.error());
assert.equal(result, 'alphaaaaaaabeta\nhowareyou\nalphbeta\nthis line ends in\n\n');
shell.exit(123);