0
# Pretty Quick
1
2
Pretty Quick is a command-line tool that automatically runs Prettier formatting on changed files in Git and Mercurial repositories. It enables developers to selectively format only the files they've modified, making it ideal for incremental code formatting in large codebases and as a pre-commit hook.
3
4
## Package Information
5
6
- **Package Name**: pretty-quick
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install -D prettier pretty-quick` or `yarn add -D prettier pretty-quick`
10
- **Peer Dependency**: prettier ^3.0.0
11
12
## Core Imports
13
14
ESM (Node.js import):
15
16
```typescript
17
import prettyQuick from "pretty-quick";
18
```
19
20
CommonJS (Node.js require):
21
22
```javascript
23
const prettyQuick = require("pretty-quick");
24
```
25
26
## Basic Usage
27
28
### Programmatic API
29
30
```typescript
31
import prettyQuick from "pretty-quick";
32
33
// Basic usage - format changed files in current directory
34
const result = await prettyQuick(process.cwd());
35
console.log(result.success); // boolean
36
console.log(result.errors); // string[]
37
38
// With options
39
const result = await prettyQuick(process.cwd(), {
40
staged: true, // Only format staged files (Git only)
41
verbose: true, // Show files being processed
42
pattern: "**/*.js", // Only process JavaScript files
43
check: false, // Format files (don't just check)
44
bail: false, // Don't exit on first formatting needed
45
});
46
```
47
48
### Command Line Interface
49
50
```bash
51
# Format all changed files
52
npx pretty-quick
53
54
# Format only staged files (pre-commit mode)
55
npx pretty-quick --staged
56
57
# Check formatting without modifying files
58
npx pretty-quick --check
59
60
# Filter by pattern
61
npx pretty-quick --pattern "**/*.{js,ts}"
62
63
# Compare against specific branch
64
npx pretty-quick --branch develop
65
```
66
67
## Architecture
68
69
Pretty Quick is built around several key components:
70
71
- **SCM Detection**: Automatically detects Git or Mercurial repositories and finds changed files
72
- **File Filtering**: Uses ignore files, patterns, and Prettier config to determine which files to process
73
- **Prettier Integration**: Leverages Prettier's API for formatting and configuration resolution
74
- **Staging Workflow**: For Git, supports restaging files after formatting in pre-commit scenarios
75
76
## Capabilities
77
78
### Main Function
79
80
The core pretty-quick function that formats changed files in a repository.
81
82
```typescript { .api }
83
/**
84
* Format changed files in a repository using Prettier
85
* @param currentDirectory - Directory to run pretty-quick in
86
* @param options - Configuration options
87
* @returns Promise resolving to result with success status and any errors
88
*/
89
function prettyQuick(
90
currentDirectory: string,
91
options?: Partial<PrettyQuickOptions>
92
): Promise<PrettyQuickResult>;
93
94
interface PrettyQuickResult {
95
/** Whether the operation completed successfully without errors */
96
success: boolean;
97
/** Array of error codes if any issues occurred */
98
errors: string[];
99
}
100
```
101
102
**Usage Example:**
103
104
```typescript
105
import prettyQuick from "pretty-quick";
106
107
async function formatChanges() {
108
const result = await prettyQuick(process.cwd(), {
109
staged: true,
110
onWriteFile: (file) => console.log(`Formatted: ${file}`),
111
onCheckFile: (file, isFormatted) => {
112
if (!isFormatted) console.log(`Needs formatting: ${file}`);
113
}
114
});
115
116
if (!result.success) {
117
console.error("Formatting failed:", result.errors);
118
process.exit(1);
119
}
120
}
121
```
122
123
### Configuration Options
124
125
Complete configuration interface for the pretty-quick function.
126
127
```typescript { .api }
128
interface PrettyQuickOptions {
129
/** Path to Prettier configuration file */
130
config: string;
131
/** SCM revision to compare against (e.g., git commit hash) */
132
since: string;
133
/** Only format staged files (Git only) */
134
staged: boolean;
135
/** File pattern(s) to filter which files are processed */
136
pattern: string[] | string;
137
/** Re-stage files after formatting when using --staged */
138
restage: boolean;
139
/** Branch to compare against (defaults to 'master' for Git, 'default' for Mercurial) */
140
branch: string;
141
/** Exit with error code if any files need formatting */
142
bail: boolean;
143
/** Check formatting without modifying files */
144
check: boolean;
145
/** Path to ignore file (alternative to .prettierignore) */
146
ignorePath: string;
147
/** Resolve Prettier config for file extensions */
148
resolveConfig: boolean;
149
/** Enable verbose output showing each file being processed */
150
verbose: boolean;
151
152
/** Callback fired when SCM revision is determined */
153
onFoundSinceRevision(name: string, revision: string | null): void;
154
/** Callback fired when changed files are found */
155
onFoundChangedFiles(changedFiles: string[]): void;
156
/** Callback fired when a partially staged file is encountered */
157
onPartiallyStagedFile(file: string): void;
158
/** Callback fired when examining each file (only in verbose mode) */
159
onExamineFile(relative: string): void;
160
/** Callback fired when checking file formatting status */
161
onCheckFile(relative: string, isFormatted: boolean): void;
162
/** Callback fired when a file is written/formatted */
163
onWriteFile(relative: string): Promise<void> | void;
164
}
165
```
166
167
### CLI Command
168
169
The pretty-quick command-line interface.
170
171
```bash { .api }
172
# Command: pretty-quick [options]
173
174
# Core options
175
--staged # Format only staged files (Git only)
176
--no-restage # Skip re-staging files after formatting
177
--branch <branch> # Branch to compare against
178
--pattern <pattern> # File pattern filter (can be used multiple times)
179
--verbose # Show each file being processed
180
--bail # Exit with error if files need formatting
181
--check # Check formatting without modifying files
182
--ignore-path <path> # Alternative ignore file path
183
--no-resolve-config # Don't resolve Prettier config for extensions
184
185
# Hidden/undocumented options
186
--config <path> # Path to Prettier config file
187
--since <revision> # SCM revision to compare against
188
```
189
190
**CLI Usage Examples:**
191
192
```bash
193
# Basic formatting of changed files
194
pretty-quick
195
196
# Pre-commit hook usage
197
pretty-quick --staged
198
199
# Check formatting in CI
200
pretty-quick --check --branch main
201
202
# Format specific file types
203
pretty-quick --pattern "**/*.{js,ts,json}"
204
pretty-quick --pattern "src/**/*" --pattern "tests/**/*"
205
206
# Verbose output for debugging
207
pretty-quick --verbose
208
209
# Custom ignore file
210
pretty-quick --ignore-path .gitignore
211
212
# Don't resolve custom Prettier extensions
213
pretty-quick --no-resolve-config
214
```
215
216
## Error Handling
217
218
Pretty Quick can fail with the following error types returned in the `errors` array:
219
220
- `"BAIL_ON_WRITE"` - Files needed formatting and `bail` option was true
221
- `"PARTIALLY_STAGED_FILE"` - Partially staged files were found when using `--staged`
222
- `"CHECK_FAILED"` - Files were incorrectly formatted when using `--check`
223
224
The function throws exceptions for:
225
- Unable to detect source control manager
226
- SCM command execution failures
227
- File system access issues
228
229
```typescript
230
// Error handling example
231
try {
232
const result = await prettyQuick(process.cwd(), { staged: true, bail: true });
233
234
if (!result.success) {
235
if (result.errors.includes('PARTIALLY_STAGED_FILE')) {
236
console.log('Some files are partially staged. Please stage all changes.');
237
}
238
if (result.errors.includes('BAIL_ON_WRITE')) {
239
console.log('Files needed formatting. Commit aborted.');
240
}
241
if (result.errors.includes('CHECK_FAILED')) {
242
console.log('Files are not properly formatted.');
243
}
244
}
245
} catch (error) {
246
console.error('Pretty Quick failed:', error.message);
247
}
248
```
249
250
## SCM Support
251
252
Pretty Quick supports the following source control managers:
253
254
### Git Support
255
- Detects Git repositories by finding `.git` directory
256
- Compares against branch or commit hash
257
- Supports staged file workflows
258
- Can restage files after formatting
259
260
### Mercurial Support
261
- Detects Mercurial repositories by finding `.hg` directory
262
- Compares against branch (defaults to 'default')
263
- Limited staging support (Mercurial doesn't have Git-style staging)
264
265
## Configuration Files
266
267
Pretty Quick respects standard Prettier configuration:
268
269
- **`.prettierrc`** - Prettier configuration file (found by searching up file system)
270
- **`.prettierignore`** - Files to ignore (found from repository root and working directory)
271
- **`.editorconfig`** - Editor configuration (used by Prettier)
272
273
Custom ignore file can be specified with `--ignore-path` option.
274
275
## Integration Patterns
276
277
### Pre-commit Hook with simple-git-hooks
278
279
```json
280
{
281
"simple-git-hooks": {
282
"pre-commit": "pretty-quick --staged"
283
}
284
}
285
```
286
287
### CI/CD Integration
288
289
```bash
290
# In CI pipeline - check formatting
291
pretty-quick --check --branch main
292
293
# Fail CI if files are not formatted
294
if ! pretty-quick --check --branch main; then
295
echo "Code formatting check failed"
296
exit 1
297
fi
298
```
299
300
### Package.json Scripts
301
302
```json
303
{
304
"scripts": {
305
"format": "pretty-quick",
306
"format:staged": "pretty-quick --staged",
307
"format:check": "pretty-quick --check"
308
}
309
}
310
```