Skip to content

Commit

Permalink
Add '-p' (preserve) option to 'cp'
Browse files Browse the repository at this point in the history
  • Loading branch information
dwi2 committed May 3, 2018
1 parent d7b6a1f commit be4a2e1
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/cp.js
Expand Up @@ -11,6 +11,7 @@ common.register('cp', _cp, {
'r': 'recursive',
'L': 'followsymlink',
'P': 'noFollowsymlink',
'p': 'preserve',
},
wrapOutput: false,
});
Expand Down Expand Up @@ -51,6 +52,7 @@ function copyFileSync(srcFile, destFile, options) {
var pos = 0;
var fdr = null;
var fdw = null;
var srcStat = common.statFollowLinks(srcFile);

try {
fdr = fs.openSync(srcFile, 'r');
Expand All @@ -75,7 +77,11 @@ function copyFileSync(srcFile, destFile, options) {
fs.closeSync(fdr);
fs.closeSync(fdw);

fs.chmodSync(destFile, common.statFollowLinks(srcFile).mode);
if (options.preserve) {
fs.chownSync(destFile, srcStat.uid, srcStat.gid);
fs.utimesSync(destFile, srcStat.atime, srcStat.mtime);
}
fs.chmodSync(destFile, srcStat.mode);
}
}

Expand Down
26 changes: 26 additions & 0 deletions test/cp.js
Expand Up @@ -756,3 +756,29 @@ test('should not overwrite recently created files (not give error no-force mode)
// Ensure First file is copied
t.is(shell.cat(`${t.context.tmp}/file1`).toString(), 'test1');
});

test('cp -p should preserve mode, ownership, and timestamp', t => {
const result = shell.cp('-p', 'test/resources/file1', `${t.context.tmp}/preservedFile1`);
const stat = fs.statSync('test/resources/file1');
const statOfResult = fs.statSync(`${t.context.tmp}/preservedFile1`);
t.is(result.code, 0);

t.is(stat.mtime.getTime(), statOfResult.mtime.getTime());
t.is(stat.atime.getTime(), statOfResult.atime.getTime());
t.is(stat.mode, statOfResult.mode);
t.is(stat.uid, statOfResult.uid);
t.is(stat.gid, statOfResult.gid);
});

test('cp -p should preserve mode, ownership, and timestamp of symlink', t => {
const result = shell.exec(`cp -p test/resources/link ${t.context.tmp}/copiedLink`);
const stat = fs.statSync('test/resources/link');
const statOfResult = fs.statSync(`${t.context.tmp}/copiedLink`);
t.is(result.code, 0);

t.is(stat.mtime.getTime(), statOfResult.mtime.getTime());
t.is(stat.atime.getTime(), statOfResult.atime.getTime());
t.is(stat.mode, statOfResult.mode);
t.is(stat.uid, statOfResult.uid);
t.is(stat.rid, statOfResult.rid);
});

0 comments on commit be4a2e1

Please sign in to comment.