1 | 'use strict';
|
2 |
|
3 | var _ = require('lodash'),
|
4 | fs = require('fs'),
|
5 | path = require('path');
|
6 |
|
7 |
|
8 | var isWindows = process.platform == 'win32';
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | var sepEscaped = _.escapeRegExp(path.sep);
|
17 |
|
18 |
|
19 | var rePrefixed = RegExp('^(?:' + (isWindows ? '[a-zA-Z]:|' : '') + '\\.?)' + sepEscaped);
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 | function Hash(properties) {
|
32 | return _.transform(properties, function(result, value, key) {
|
33 | result[key] = (_.isPlainObject(value) && !(value instanceof Hash))
|
34 | ? new Hash(value)
|
35 | : value;
|
36 | }, this);
|
37 | }
|
38 |
|
39 | Hash.prototype = Object.create(null);
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 | function mkdirpSync(dirname, mode) {
|
50 | var sep = path.sep;
|
51 | dirname = path.normalize(dirname);
|
52 |
|
53 |
|
54 | if (!rePrefixed.test(dirname)) {
|
55 | dirname = '.' + sep + dirname;
|
56 | }
|
57 | dirname.split(sep).reduce(function(currPath, segment) {
|
58 | currPath += sep + segment;
|
59 | try {
|
60 | currPath = fs.realpathSync(currPath);
|
61 | } catch (e) {
|
62 | fs.mkdirSync(currPath, mode);
|
63 | }
|
64 | return currPath;
|
65 | });
|
66 | }
|
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 | function rmrfSync(pathname) {
|
75 | var sep = path.sep;
|
76 | pathname = path.normalize(pathname);
|
77 |
|
78 |
|
79 | if (!_.startsWith(pathname, path.dirname(__dirname) + sep)) {
|
80 | return;
|
81 | }
|
82 | try {
|
83 | pathname = fs.realpathSync(pathname);
|
84 | } catch (e) {
|
85 | return;
|
86 | }
|
87 | if (!fs.statSync(pathname).isDirectory()) {
|
88 | fs.unlinkSync(pathname);
|
89 | return;
|
90 | }
|
91 | _.each(fs.readdirSync(pathname), function(identifier) {
|
92 | var currPath = path.join(pathname, identifier);
|
93 | if (fs.statSync(currPath).isDirectory()) {
|
94 | rmrfSync(currPath);
|
95 | } else {
|
96 | fs.unlinkSync(currPath);
|
97 | }
|
98 | });
|
99 | fs.rmdirSync(pathname);
|
100 | }
|
101 |
|
102 |
|
103 |
|
104 |
|
105 |
|
106 |
|
107 |
|
108 |
|
109 | var util = {
|
110 |
|
111 | 'Hash': Hash,
|
112 |
|
113 | |
114 |
|
115 |
|
116 |
|
117 |
|
118 |
|
119 | 'fs': _.defaults(_.cloneDeep(fs), {
|
120 | 'mkdirpSync': mkdirpSync,
|
121 | 'rmrfSync': rmrfSync
|
122 | }),
|
123 |
|
124 | |
125 |
|
126 |
|
127 |
|
128 |
|
129 |
|
130 | 'path': _.defaults(_.cloneDeep(path), {
|
131 | 'sepEscaped': sepEscaped
|
132 | })
|
133 | };
|
134 |
|
135 | module.exports = util;
|