-
Notifications
You must be signed in to change notification settings - Fork 3
/
indent.js
73 lines (61 loc) · 1.91 KB
/
indent.js
1
2
3
4
5
6
7
8
9
10
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
* grunt-indent
* https://github.com/stevenbenner/grunt-indent
*
* Copyright (c) 2017 Steven Benner
* Licensed under the MIT license.
*/
'use strict';
var path = require('path');
module.exports = function(grunt) {
grunt.registerMultiTask('indent', 'Change the indentation of files.', function() {
// get options object with defaults
var options = this.options({
style: 'tab',
size: 1,
change: 0
});
// define one indent string
var indent = '';
if (options.style === 'tab') {
indent = grunt.util._.repeat('\t', options.size);
} else if (options.style === 'space') {
indent = grunt.util._.repeat(' ', options.size);
}
// process the files
this.files.forEach(function(file) {
file.src.filter(function(filePath) {
// filter out nonexistent files
if (!grunt.file.exists(filePath)) {
grunt.log.warn('Source file "' + filePath + '" not found.');
return false;
}
return true;
}).forEach(function(src) {
var dest = file.dest,
newFile = [];
// if dest is a folder use the src file name
if (grunt.util._.endsWith(dest, '/')) {
dest += path.basename(src);
}
// walk the file line-by-line
grunt.file.read(src).split(/\r\n?|\n/).forEach(function(line) {
if (line) {
if (options.change > 0) {
line = grunt.util._.repeat(indent, options.change) + line;
} else if (options.change < 0) {
var i = options.change;
while (grunt.util._.startsWith(line, indent) && i < 0) {
line = line.substring(options.size);
i++;
}
}
}
newFile.push(line);
});
grunt.file.write(dest, newFile.join(grunt.util.linefeed));
grunt.log.writeln('File "' + dest + '" saved.');
});
});
});
};