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 | function _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 |
|
51 | function touchFile(opts, file) {
|
52 | var stat = tryStatFile(file);
|
53 |
|
54 | if (stat && stat.isDirectory()) {
|
55 |
|
56 | return;
|
57 | }
|
58 |
|
59 |
|
60 |
|
61 | if (!stat && opts.no_create) {
|
62 | return;
|
63 | }
|
64 |
|
65 |
|
66 |
|
67 | fs.closeSync(fs.openSync(file, 'a'));
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 | var now = new Date();
|
75 | var mtime = opts.date || now;
|
76 | var atime = opts.date || now;
|
77 |
|
78 |
|
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 |
|
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 |
|
102 | module.exports = _touch;
|
103 |
|
104 | function tryStatFile(filePath) {
|
105 | try {
|
106 | return common.statFollowLinks(filePath);
|
107 | } catch (e) {
|
108 | return null;
|
109 | }
|
110 | }
|