1 | var common = require('./common');
|
2 | var fs = require('fs');
|
3 |
|
4 | common.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 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 | function _touch(opts, files) {
|
38 | if (!files) {
|
39 | common.error('no files given');
|
40 | } else if (typeof files === 'string') {
|
41 | files = [].slice.call(arguments, 1);
|
42 | } else {
|
43 | common.error('file arg should be a string file path or an Array of string file paths');
|
44 | }
|
45 |
|
46 | files.forEach(function (f) {
|
47 | touchFile(opts, f);
|
48 | });
|
49 | return '';
|
50 | }
|
51 |
|
52 | function touchFile(opts, file) {
|
53 | var stat = tryStatFile(file);
|
54 |
|
55 | if (stat && stat.isDirectory()) {
|
56 |
|
57 | return;
|
58 | }
|
59 |
|
60 |
|
61 |
|
62 | if (!stat && opts.no_create) {
|
63 | return;
|
64 | }
|
65 |
|
66 |
|
67 |
|
68 | fs.closeSync(fs.openSync(file, 'a'));
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 | var now = new Date();
|
76 | var mtime = opts.date || now;
|
77 | var atime = opts.date || now;
|
78 |
|
79 |
|
80 | if (opts.reference) {
|
81 | var refStat = tryStatFile(opts.reference);
|
82 | if (!refStat) {
|
83 | common.error('failed to get attributess of ' + opts.reference);
|
84 | }
|
85 | mtime = refStat.mtime;
|
86 | atime = refStat.atime;
|
87 | } else if (opts.date) {
|
88 | mtime = opts.date;
|
89 | atime = opts.date;
|
90 | }
|
91 |
|
92 | if (opts.atime_only && opts.mtime_only) {
|
93 |
|
94 | } else if (opts.atime_only) {
|
95 | mtime = stat.mtime;
|
96 | } else if (opts.mtime_only) {
|
97 | atime = stat.atime;
|
98 | }
|
99 |
|
100 | fs.utimesSync(file, atime, mtime);
|
101 | }
|
102 |
|
103 | module.exports = _touch;
|
104 |
|
105 | function tryStatFile(filePath) {
|
106 | try {
|
107 | return common.statFollowLinks(filePath);
|
108 | } catch (e) {
|
109 | return null;
|
110 | }
|
111 | }
|