Command line interface for Percy visual testing platform that enables developers to capture, upload, and manage visual snapshots for web applications.
npx @tessl/cli install tessl/npm-percy--cli@1.31.00
# Percy CLI
1
2
Percy CLI is a comprehensive command-line tool for visual testing that enables developers to capture, upload, and manage visual snapshots for web applications. It provides a unified interface for interacting with the Percy visual testing platform, offering commands for taking snapshots of static directories, executing test suites with visual capture, uploading images, and managing Percy builds and configurations.
3
4
## Package Information
5
6
- **Package Name**: @percy/cli
7
- **Package Type**: npm
8
- **Language**: JavaScript/Node.js
9
- **Installation**: `npm install --save-dev @percy/cli`
10
11
## Core Imports
12
13
The Percy CLI is primarily used as a command-line tool, but it also exports programmatic functions:
14
15
```javascript
16
import { percy, checkForUpdate } from "@percy/cli";
17
```
18
19
For CommonJS:
20
21
```javascript
22
const { percy, checkForUpdate } = require("@percy/cli");
23
```
24
25
## Basic Usage
26
27
### Command Line Interface
28
29
The primary interface is the `percy` command-line tool:
30
31
```bash
32
# Install Percy CLI
33
npm install --save-dev @percy/cli
34
35
# Set Percy token
36
export PERCY_TOKEN=your-percy-token
37
38
# Take snapshots of a test suite
39
percy exec -- npm test
40
41
# Snapshot a static directory
42
percy snapshot ./public
43
44
# Upload directory of images
45
percy upload ./screenshots
46
```
47
48
### Programmatic Interface
49
50
```javascript
51
import { percy } from "@percy/cli";
52
53
// Run Percy CLI programmatically
54
await percy(['exec', '--', 'npm', 'test']);
55
```
56
57
## Architecture
58
59
Percy CLI is built around several key components:
60
61
- **Command Framework**: Extensible command system that discovers and loads CLI commands from multiple packages
62
- **Core Engine**: `@percy/core` provides browser automation, asset discovery, and snapshot coordination
63
- **API Client**: `@percy/client` handles all communication with Percy's visual testing service
64
- **Configuration System**: `@percy/config` manages configuration loading, validation, and migration
65
- **Logging System**: `@percy/logger` provides consistent, structured logging across all components
66
67
## Capabilities
68
69
### Core CLI Operations
70
71
Essential Percy workflow commands for starting, stopping, and executing visual tests with any test runner or static content.
72
73
```bash { .api }
74
percy exec -- <command> # Start Percy, run command, then stop
75
percy start # Start Percy process in background
76
percy stop # Stop Percy process
77
percy ping # Check if Percy process is running
78
```
79
80
[Core Operations](./core-operations.md)
81
82
### Static Site Snapshots
83
84
Capture visual snapshots of static directories, file lists, or sitemaps without requiring a test runner.
85
86
```bash { .api }
87
percy snapshot <dir|file|sitemap> # Snapshot static content
88
--base-url <url> # Base URL for hosted pages
89
--include <pattern> # Include patterns (multiple)
90
--exclude <pattern> # Exclude patterns (multiple)
91
--clean-urls # Remove file extensions from URLs
92
```
93
94
[Static Snapshots](./static-snapshots.md)
95
96
### Build Management
97
98
Commands for managing Percy builds, including waiting for completion, finalizing parallel builds, and reviewing build results.
99
100
```bash { .api }
101
percy build wait # Wait for build completion
102
--build <build-id> # Specific build ID
103
--project <project> # Project slug
104
--commit <sha> # Commit SHA
105
--timeout <ms> # Timeout duration
106
--fail-on-changes # Exit with error on diffs
107
108
percy build finalize # Finalize parallel builds
109
percy build id # Print current build ID
110
percy build approve <build-id> # Approve build
111
percy build reject <build-id> # Reject build
112
percy build delete <build-id> # Delete build
113
```
114
115
[Build Management](./build-management.md)
116
117
### Configuration Management
118
119
Tools for creating, validating, and migrating Percy configuration files across different formats.
120
121
```bash { .api }
122
percy config create [filepath] # Create new config file
123
--rc # Create .percyrc
124
--yaml # Create .percy.yaml
125
--json # Create .percy.json
126
--js # Create .percy.js
127
128
percy config validate [filepath] # Validate config file
129
percy config migrate [filepath] # Migrate to latest format
130
--dry-run # Show migration without writing
131
```
132
133
[Configuration](./configuration.md)
134
135
### Image Uploads
136
137
Direct upload of image files as visual snapshots, useful for integrating with external screenshot tools.
138
139
```bash { .api }
140
percy upload <dirname> # Upload image directory
141
--files <pattern> # File patterns (default: **/*.{png,jpg,jpeg})
142
--ignore <pattern> # Ignore patterns
143
--strip-extensions # Remove extensions from snapshot names
144
```
145
146
[Image Uploads](./image-uploads.md)
147
148
### Native App Snapshots
149
150
Specialized commands for visual testing of native mobile applications with Percy's app testing platform.
151
152
```bash { .api }
153
percy app exec -- <command> # Execute with Percy for native apps
154
percy app start # Start Percy for native apps
155
percy app stop # Stop Percy app process
156
percy app ping # Ping Percy app process
157
```
158
159
[App Snapshots](./app-snapshots.md)
160
161
### Programmatic API
162
163
Advanced APIs for SDK development, custom integrations, and deep Percy automation. Includes the Percy core engine, configuration system, API client, environment detection, and utility libraries.
164
165
```javascript { .api }
166
import Percy from "@percy/core"; // Core visual testing engine
167
import { load, validate } from "@percy/config"; // Configuration system
168
import PercyClient from "@percy/client"; // Percy API client
169
import PercyEnv from "@percy/env"; // CI environment detection
170
```
171
172
[Programmatic API](./programmatic-api.md)
173
174
## Global Options
175
176
All Percy commands support these global flags:
177
178
```bash { .api }
179
# Logging Control
180
--verbose, -v # Log everything (debug level)
181
--quiet, -q # Log errors only
182
--silent, -s # Log nothing
183
184
# Percy Configuration
185
--config, -c <path> # Configuration file path
186
--dry-run, -d # Print snapshot names without uploading
187
--labels, -l <labels> # Build labels (comma-separated)
188
189
# Server Configuration
190
--port, -P <port> # Local server port (default: 5338)
191
192
# Asset Discovery
193
--allowed-hostname <pattern> # Allowed hostname patterns
194
--disallowed-hostname <pattern> # Disallowed hostname patterns
195
--network-idle-timeout <ms> # Network idle timeout
196
--disable-cache # Disable asset caching
197
--debug # Debug asset discovery
198
```
199
200
## Environment Variables
201
202
### Required Configuration
203
204
```bash { .api }
205
PERCY_TOKEN # Percy project token (required)
206
```
207
208
### Optional Configuration
209
210
```bash { .api }
211
# Build Configuration
212
PERCY_PARALLEL_TOTAL # Number of parallel processes
213
PERCY_PARALLEL_NONCE # Parallel build identifier
214
PERCY_PARTIAL_BUILD # Mark build as partial (1 to enable)
215
PERCY_BUILD_ID # Build identifier (set by percy exec)
216
PERCY_BUILD_URL # Build URL (set by percy exec)
217
PERCY_COMMIT # Override commit SHA
218
PERCY_BRANCH # Override branch name
219
220
# Logging Configuration
221
PERCY_DEBUG # Debug namespace patterns
222
PERCY_LOGLEVEL # Global log level
223
PERCY_SKIP_UPDATE_CHECK # Skip version checks (1 to enable)
224
PERCY_CLIENT_ERROR_LOGS # Enable client error logging (1 to enable)
225
226
# Advanced Configuration
227
PERCY_CLIENT_API_URL # Override Percy API URL
228
PERCY_CONFIG # Configuration file path
229
PERCY_GZIP # Enable gzip compression (1 to enable)
230
PERCY_RESOURCE_UPLOAD_CONCURRENCY # Upload concurrency limit
231
PERCY_SERVER_ADDRESS # Percy server address for SDK communication
232
PERCY_ENABLE # Enable/disable Percy (0 to disable)
233
PERCY_GITHUB_ACTION # GitHub Action identifier
234
PERCY_DISABLE_SYSTEM_MONITORING # Disable system monitoring (1 to disable)
235
236
# CI Environment Variables (detected automatically)
237
# Travis CI
238
TRAVIS_BUILD_ID # Travis build identifier
239
TRAVIS_COMMIT # Travis commit SHA
240
TRAVIS_PULL_REQUEST # Travis PR number
241
TRAVIS_BRANCH # Travis branch name
242
243
# Jenkins
244
JENKINS_URL # Jenkins server URL
245
GIT_COMMIT # Git commit SHA
246
ghprbPullId # GitHub PR builder pull ID
247
GIT_BRANCH # Git branch name
248
249
# CircleCI
250
CIRCLECI # CircleCI indicator
251
CIRCLE_SHA1 # Circle commit SHA
252
CIRCLE_BRANCH # Circle branch name
253
CIRCLE_BUILD_NUM # Circle build number
254
255
# GitHub Actions
256
GITHUB_ACTIONS # GitHub Actions indicator
257
GITHUB_SHA # GitHub commit SHA
258
GITHUB_REF # GitHub reference
259
260
# GitLab CI
261
GITLAB_CI # GitLab CI indicator
262
CI_COMMIT_SHA # GitLab commit SHA
263
CI_COMMIT_REF_NAME # GitLab branch name
264
CI_MERGE_REQUEST_IID # GitLab merge request ID
265
266
# Azure DevOps
267
TF_BUILD # Team Foundation indicator
268
BUILD_SOURCEVERSION # Azure commit SHA
269
BUILD_SOURCEBRANCH # Azure branch name
270
SYSTEM_PULLREQUEST_PULLREQUESTID # Azure PR ID
271
```
272
273
## Types
274
275
### Programmatic API Types
276
277
```javascript { .api }
278
/**
279
* Main Percy CLI function
280
* @param args - Command line arguments array
281
* @returns Promise that resolves when command completes
282
*/
283
function percy(args: string[]): Promise<void>;
284
285
/**
286
* Check for CLI updates and display warnings if newer version available
287
* @returns Promise that resolves when check completes
288
*/
289
function checkForUpdate(): Promise<void>;
290
```
291
292
### CLI Command Types
293
294
```typescript { .api }
295
// Command result types
296
interface CommandResult {
297
success: boolean;
298
exitCode: number;
299
output?: string;
300
error?: Error;
301
}
302
303
// Command options interfaces
304
interface ExecOptions {
305
parallel?: boolean;
306
partial?: boolean;
307
testing?: boolean;
308
}
309
310
interface SnapshotOptions {
311
baseUrl?: string;
312
include?: string[];
313
exclude?: string[];
314
cleanUrls?: boolean;
315
files?: string;
316
}
317
318
interface UploadOptions {
319
files?: string[];
320
ignore?: string[];
321
stripExtensions?: boolean;
322
}
323
324
interface BuildWaitOptions {
325
build?: string;
326
project?: string;
327
commit?: string;
328
timeout?: number;
329
interval?: number;
330
failOnChanges?: boolean;
331
passIfApproved?: boolean;
332
}
333
334
interface BuildReviewOptions {
335
username?: string;
336
accessKey?: string;
337
}
338
```
339
340
### Configuration Types
341
342
```typescript { .api }
343
interface PercyConfig {
344
// Core configuration
345
version?: number;
346
snapshot?: SnapshotConfig;
347
discovery?: DiscoveryConfig;
348
agent?: AgentConfig;
349
350
// Build configuration
351
parallel?: {
352
total?: number;
353
nonce?: string;
354
};
355
356
// Upload configuration
357
defer?: boolean;
358
delayUploads?: boolean;
359
deferUploads?: boolean;
360
361
// Static configuration
362
static?: StaticConfig;
363
364
// Upload specific configuration
365
upload?: UploadConfig;
366
}
367
368
interface SnapshotConfig {
369
widths?: number[];
370
minHeight?: number;
371
percyCSS?: string;
372
enableJavaScript?: boolean;
373
enableLayout?: boolean;
374
disableShadowDOM?: boolean;
375
deviceScaleFactor?: number;
376
scope?: string;
377
ignoreRegions?: IgnoreRegion[];
378
considerRegions?: ConsiderRegion[];
379
}
380
381
interface DiscoveryConfig {
382
allowedHostnames?: string[];
383
disallowedHostnames?: string[];
384
networkIdleTimeout?: number;
385
concurrency?: number;
386
launchOptions?: LaunchOptions;
387
userAgent?: string;
388
deviceScaleFactor?: number;
389
}
390
391
interface AgentConfig {
392
assetDiscovery?: {
393
networkIdleTimeout?: number;
394
pagePoolSizeMin?: number;
395
pagePoolSizeMax?: number;
396
allowedHostnames?: string[];
397
disallowedHostnames?: string[];
398
requestHeaders?: Record<string, string>;
399
authorization?: {
400
username: string;
401
password: string;
402
};
403
};
404
}
405
406
interface StaticConfig {
407
baseUrl?: string;
408
include?: string[];
409
exclude?: string[];
410
cleanUrls?: boolean;
411
rewrites?: RewriteRule[];
412
}
413
414
interface UploadConfig {
415
files?: string[];
416
ignore?: string[];
417
stripExtensions?: boolean;
418
concurrency?: number;
419
}
420
421
interface LaunchOptions {
422
headless?: boolean;
423
args?: string[];
424
timeout?: number;
425
slowMo?: number;
426
devtools?: boolean;
427
executablePath?: string;
428
}
429
430
interface RewriteRule {
431
source: string;
432
destination: string;
433
}
434
435
interface IgnoreRegion {
436
selector?: string;
437
xpath?: string;
438
coordinates?: {
439
top: number;
440
bottom: number;
441
left: number;
442
right: number;
443
};
444
}
445
446
interface ConsiderRegion {
447
selector?: string;
448
xpath?: string;
449
coordinates?: {
450
top: number;
451
bottom: number;
452
left: number;
453
right: number;
454
};
455
}
456
```
457
458
### Build and Snapshot Types
459
460
```typescript { .api }
461
interface Build {
462
id: string;
463
number: number;
464
url: string;
465
webUrl: string;
466
state: 'pending' | 'processing' | 'finished' | 'failed';
467
reviewState?: 'unreviewed' | 'approved' | 'rejected';
468
reviewStateReason?: string;
469
isApproved?: boolean;
470
totalComparisons: number;
471
totalComparisonsFinished: number;
472
totalComparisonsDiff: number;
473
branch?: string;
474
commitSha?: string;
475
commitMessage?: string;
476
pullRequestNumber?: string;
477
}
478
479
interface Snapshot {
480
name: string;
481
url?: string;
482
domSnapshot?: string;
483
clientInfo?: string;
484
environmentInfo?: string;
485
widths?: number[];
486
minHeight?: number;
487
enableJavaScript?: boolean;
488
percyCSS?: string;
489
scope?: string;
490
additionalSnapshots?: AdditionalSnapshot[];
491
requestHeaders?: Record<string, string>;
492
authorization?: {
493
username: string;
494
password: string;
495
};
496
}
497
498
interface AdditionalSnapshot {
499
prefix?: string;
500
suffix?: string;
501
name?: string;
502
waitForTimeout?: number;
503
waitForSelector?: string;
504
execute?: string | Function;
505
percyCSS?: string;
506
ignoreRegions?: IgnoreRegion[];
507
considerRegions?: ConsiderRegion[];
508
}
509
```
510
511
## Error Handling
512
513
Percy CLI provides structured error handling with specific exit codes and error types:
514
515
- **Exit Code 0**: Success
516
- **Exit Code 1**: General error (configuration, network, etc.)
517
- **Exit Code 2**: Build failed with visual differences (when using `--fail-on-changes`)
518
519
Common error scenarios include missing tokens, configuration validation failures, network connectivity issues, and build processing errors. The CLI provides detailed error messages and suggestions for resolution.