0
# File Processing
1
2
Batch file processing system that can format and lint multiple files with glob patterns, Git integration, and configurable processing modes. The `run` function is the core engine that powers both the CLI and programmatic usage.
3
4
## Capabilities
5
6
### Run Function
7
8
Main execution function that processes files according to configuration with support for Git integration, linting, and various processing modes.
9
10
```javascript { .api }
11
/**
12
* Main execution function that processes files according to configuration
13
* @param cwd - Working directory path where files will be processed
14
* @param config - Configuration object defining processing behavior
15
* @returns Promise that resolves to undefined on success or Error object on failure
16
*/
17
async function run(cwd, config);
18
19
interface RunConfig {
20
patterns?: string[]; // File patterns to process (defaults to ['**/*'] in git repos)
21
check?: boolean; // Check formatting without modifying files (default: false)
22
lint?: boolean; // Perform ESLint linting after formatting (default: false)
23
changed?: boolean; // Process only changed files since HEAD (default: false)
24
since?: string; // Process changes since given branch/revision (default: undefined)
25
staged?: boolean; // Process only git staged files (default: false)
26
lines?: boolean; // Process only changed lines - experimental (default: false)
27
options?: PrettierOptions; // Prettier configuration options
28
onStart?: (params: { engine?: object }) => void; // Callback called at processing start
29
onProcessed?: (result: ProcessResult) => void; // Callback for each processed file
30
}
31
32
interface ProcessResult {
33
file: string; // Relative file path that was processed
34
runtime: number; // Processing time in milliseconds
35
formatted: boolean; // Whether file needed formatting (false if already formatted)
36
report?: object; // ESLint report object if linting enabled
37
check?: boolean; // Whether processing was in check mode
38
}
39
```
40
41
**Basic Usage Examples:**
42
43
```javascript
44
const { run } = require('prettier-standard');
45
46
// Format all supported files in current directory
47
await run(process.cwd(), {
48
patterns: ['**/*.js', '**/*.ts', '**/*.json']
49
});
50
51
// Check formatting without modifying files
52
await run(process.cwd(), {
53
patterns: ['src/**/*.js'],
54
check: true
55
});
56
57
// Format and lint with callbacks
58
await run(process.cwd(), {
59
patterns: ['src/**/*.js'],
60
lint: true,
61
onProcessed: (result) => {
62
console.log(`Processed ${result.file} in ${result.runtime}ms`);
63
if (result.report && result.report.errorCount > 0) {
64
console.log('Linting errors found');
65
}
66
}
67
});
68
```
69
70
**Git Integration Examples:**
71
72
```javascript
73
// Process only changed files since HEAD
74
await run(process.cwd(), {
75
changed: true,
76
lint: true
77
});
78
79
// Process changes since specific branch
80
await run(process.cwd(), {
81
since: 'master',
82
lint: true
83
});
84
85
// Process only staged files (useful for pre-commit hooks)
86
await run(process.cwd(), {
87
staged: true,
88
lint: true
89
});
90
91
// Process only changed lines (experimental)
92
await run(process.cwd(), {
93
lines: true,
94
changed: true
95
});
96
```
97
98
### File Pattern Matching
99
100
The `patterns` parameter supports glob patterns for flexible file selection:
101
102
```javascript { .api }
103
// Glob pattern examples
104
const patterns = [
105
'**/*.js', // All JS files recursively
106
'src/**/*.{ts,tsx}', // TypeScript files in src directory
107
'**/*.json', // All JSON files
108
'!node_modules/**', // Exclude node_modules (included by default)
109
'!**/*.min.js' // Exclude minified files (included by default)
110
];
111
```
112
113
**Default ignore patterns** (automatically applied):
114
- `!**/*.min.js` - Minified JavaScript files
115
- `!**/{node_modules,coverage,vendor}/**` - Common ignore directories
116
- `!./{node_modules,coverage,vendor}/**` - Local ignore directories
117
- `!**/.{git,svn,hg}/**` - Version control directories
118
- `!./.{git,svn,hg}/**` - Local version control directories
119
120
### Ignore File Support
121
122
The system respects ignore files for flexible exclusion:
123
124
- **`.prettierignore`**: Files/patterns to exclude from formatting
125
- **`.eslintignore`**: Files/patterns to format but exclude from linting
126
127
**Example `.prettierignore`:**
128
```
129
dist/
130
build/
131
**/*.min.js
132
coverage/
133
```
134
135
### Processing Modes
136
137
#### Check Mode
138
139
Validates formatting without modifying files:
140
141
```javascript
142
const results = [];
143
await run(process.cwd(), {
144
check: true,
145
patterns: ['src/**/*.js'],
146
onProcessed: (result) => {
147
if (!result.formatted) {
148
results.push(result.file); // File needs formatting
149
}
150
}
151
});
152
153
if (results.length > 0) {
154
console.log('Files need formatting:', results);
155
process.exit(1);
156
}
157
```
158
159
#### Lint Mode
160
161
Performs ESLint linting with Standard rules after formatting:
162
163
```javascript
164
let hasErrors = false;
165
await run(process.cwd(), {
166
lint: true,
167
patterns: ['src/**/*.js'],
168
onStart: ({ engine }) => {
169
console.log('ESLint engine initialized');
170
},
171
onProcessed: (result) => {
172
if (result.report && result.report.errorCount > 0) {
173
hasErrors = true;
174
}
175
}
176
});
177
178
if (hasErrors) {
179
console.log('Linting errors found');
180
process.exit(1);
181
}
182
```
183
184
#### Staged Mode
185
186
Processes only Git staged files using lint-staged integration:
187
188
```javascript
189
// This automatically handles git staging after processing
190
await run(process.cwd(), {
191
staged: true,
192
lint: true
193
});
194
```
195
196
### Git Integration
197
198
#### Changed Files Processing
199
200
Process files changed since a specific revision:
201
202
```javascript
203
// Files changed since HEAD
204
await run(process.cwd(), { changed: true });
205
206
// Files changed since master branch
207
await run(process.cwd(), { since: 'master' });
208
209
// Files changed since specific commit
210
await run(process.cwd(), { since: 'abc123' });
211
```
212
213
#### Line-based Processing (Experimental)
214
215
Process only the specific lines that have changed:
216
217
```javascript
218
// Only format changed lines within changed files
219
await run(process.cwd(), {
220
lines: true,
221
changed: true
222
});
223
```
224
225
**Note**: Line-based processing is experimental due to Prettier limitations with range formatting.
226
227
### Error Handling
228
229
The `run` function returns errors rather than throwing them:
230
231
```javascript
232
const error = await run(process.cwd(), {
233
patterns: ['invalid-pattern['],
234
lint: true
235
});
236
237
if (error instanceof Error) {
238
console.error('Processing failed:', error.message);
239
240
// Common error types:
241
if (error.message.includes('glob pattern')) {
242
console.error('Invalid glob pattern provided');
243
} else if (error.message.includes('git repository')) {
244
console.error('Git operations require a git repository');
245
} else if (error.message.includes('patterns should be an array')) {
246
console.error('Patterns must be provided as an array');
247
}
248
}
249
```
250
251
### Performance Considerations
252
253
#### File Filtering
254
255
Multiple filtering layers optimize performance:
256
257
1. **Extension filtering**: Only supported file extensions are processed
258
2. **Ignore file filtering**: `.prettierignore` patterns are applied
259
3. **Pattern matching**: Custom glob patterns are evaluated
260
4. **Git filtering**: Changed/staged file detection uses Git efficiently
261
262
#### Callback Usage
263
264
Use callbacks for progress tracking and early termination:
265
266
```javascript
267
let processedCount = 0;
268
const maxFiles = 100;
269
270
await run(process.cwd(), {
271
patterns: ['**/*.js'],
272
onProcessed: (result) => {
273
processedCount++;
274
console.log(`Progress: ${processedCount} files processed`);
275
276
if (processedCount >= maxFiles) {
277
console.log('Stopping after processing limit reached');
278
// Note: Cannot stop mid-processing, but useful for monitoring
279
}
280
}
281
});
282
```
283
284
## ESLint Configuration
285
286
When `lint: true` is specified, the system configures ESLint with:
287
288
- **Parser**: `babel-eslint` for JavaScript parsing
289
- **Base configuration**: Standard rules with Prettier compatibility
290
- **Plugins**: Jest, Import, Node, Promise, React, Standard, TypeScript
291
- **Extends**: Standard, Standard JSX, Prettier compatibility configs
292
293
**Custom ESLint configuration** can be provided via `.eslintrc` files in the project:
294
295
```json
296
{
297
"rules": {
298
"eqeqeq": "off",
299
"no-console": "warn"
300
}
301
}
302
```