UNPKG

2.7 kBJavaScriptView Raw
1var common = require('./common');
2var fs = require('fs');
3
4common.register('touch', _touch, {
5 cmdOptions: {
6 'a': 'atime_only',
7 'c': 'no_create',
8 'd': 'date',
9 'm': 'mtime_only',
10 'r': 'reference',
11 },
12});
13
14//@
15//@ ### touch([options,] file [, file ...])
16//@ ### touch([options,] file_array)
17//@ Available options:
18//@
19//@ + `-a`: Change only the access time
20//@ + `-c`: Do not create any files
21//@ + `-m`: Change only the modification time
22//@ + `-d DATE`: Parse DATE and use it instead of current time
23//@ + `-r FILE`: Use FILE's times instead of current time
24//@
25//@ Examples:
26//@
27//@ ```javascript
28//@ touch('source.js');
29//@ touch('-c', '/path/to/some/dir/source.js');
30//@ touch({ '-r': FILE }, '/path/to/some/dir/source.js');
31//@ ```
32//@
33//@ Update the access and modification times of each FILE to the current time.
34//@ A FILE argument that does not exist is created empty, unless -c is supplied.
35//@ This is a partial implementation of *[touch(1)](http://linux.die.net/man/1/touch)*.
36function _touch(opts, files) {
37 if (!files) {
38 common.error('no files given');
39 } else if (typeof files === 'string') {
40 files = [].slice.call(arguments, 1);
41 } else {
42 common.error('file arg should be a string file path or an Array of string file paths');
43 }
44
45 files.forEach(function (f) {
46 touchFile(opts, f);
47 });
48 return '';
49}
50
51function touchFile(opts, file) {
52 var stat = tryStatFile(file);
53
54 if (stat && stat.isDirectory()) {
55 // don't error just exit
56 return;
57 }
58
59 // if the file doesn't already exist and the user has specified --no-create then
60 // this script is finished
61 if (!stat && opts.no_create) {
62 return;
63 }
64
65 // open the file and then close it. this will create it if it doesn't exist but will
66 // not truncate the file
67 fs.closeSync(fs.openSync(file, 'a'));
68
69 //
70 // Set timestamps
71 //
72
73 // setup some defaults
74 var now = new Date();
75 var mtime = opts.date || now;
76 var atime = opts.date || now;
77
78 // use reference file
79 if (opts.reference) {
80 var refStat = tryStatFile(opts.reference);
81 if (!refStat) {
82 common.error('failed to get attributess of ' + opts.reference);
83 }
84 mtime = refStat.mtime;
85 atime = refStat.atime;
86 } else if (opts.date) {
87 mtime = opts.date;
88 atime = opts.date;
89 }
90
91 if (opts.atime_only && opts.mtime_only) {
92 // keep the new values of mtime and atime like GNU
93 } else if (opts.atime_only) {
94 mtime = stat.mtime;
95 } else if (opts.mtime_only) {
96 atime = stat.atime;
97 }
98
99 fs.utimesSync(file, atime, mtime);
100}
101
102module.exports = _touch;
103
104function tryStatFile(filePath) {
105 try {
106 return common.statFollowLinks(filePath);
107 } catch (e) {
108 return null;
109 }
110}