refactor(string): modify string protoype, but only for shelljs/global

`require('shelljs/global')` extends String.prototype to have the `.to()` and
`.toEnd()` methods again. This also adds tests for the global require.
This commit is contained in:
Nate Fischer 2016-03-18 17:05:14 -07:00
parent f006fcd8b1
commit 6739aed69e
5 changed files with 52 additions and 4 deletions

View File

@ -330,7 +330,7 @@ containing the files if more than one file is given (a new line character is
introduced between each file). Wildcard `*` accepted.
### 'string'.to(file)
### ShellString.prototype.to(file)
Examples:
@ -343,7 +343,7 @@ ShellStrings (such as those returned by `cat`, `grep`, etc). _Like Unix
redirections, `to()` will overwrite any existing file!_
### 'string'.toEnd(file)
### ShellString.prototype.toEnd(file)
Examples:

View File

@ -1,3 +1,10 @@
var shell = require('./shell.js');
var common = require('./src/common');
for (var cmd in shell)
global[cmd] = shell[cmd];
var _to = require('./src/to');
String.prototype.to = common.wrap('to', _to);
var _toEnd = require('./src/toEnd');
String.prototype.toEnd = common.wrap('toEnd', _toEnd);

View File

@ -3,7 +3,7 @@ var fs = require('fs');
var path = require('path');
//@
//@ ### 'string'.to(file)
//@ ### ShellString.prototype.to(file)
//@
//@ Examples:
//@

View File

@ -3,7 +3,7 @@ var fs = require('fs');
var path = require('path');
//@
//@ ### 'string'.toEnd(file)
//@ ### ShellString.prototype.toEnd(file)
//@
//@ Examples:
//@

41
test/global.js Normal file
View File

@ -0,0 +1,41 @@
/* globals cat, config, cp, env, error, exit, mkdir, rm */
require('../global');
var assert = require('assert');
var fs = require('fs');
config.silent = true;
rm('-rf', 'tmp');
mkdir('tmp');
//
// Valids
//
assert.equal(process.env, env);
// cat
var result = cat('resources/cat/file1');
assert.equal(error(), null);
assert.equal(result.code, 0);
assert.equal(result, 'test1\n');
// rm
cp('-f', 'resources/file1', 'tmp/file1');
assert.equal(fs.existsSync('tmp/file1'), true);
result = rm('tmp/file1');
assert.equal(error(), null);
assert.equal(result.code, 0);
assert.equal(fs.existsSync('tmp/file1'), false);
// String.prototype is modified for global require
'foo'.to('tmp/testfile.txt');
assert.equal('foo', cat('tmp/testfile.txt'));
'bar'.toEnd('tmp/testfile.txt');
assert.equal('foobar', cat('tmp/testfile.txt'));
exit(123);