or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-pretty-quick

A command-line tool that automatically runs Prettier formatting on changed files in Git and Mercurial repositories.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/pretty-quick@4.2.x

To install, run

npx @tessl/cli install tessl/npm-pretty-quick@4.2.0

index.mddocs/

Pretty Quick

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.

Package Information

  • Package Name: pretty-quick
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install -D prettier pretty-quick or yarn add -D prettier pretty-quick
  • Peer Dependency: prettier ^3.0.0

Core Imports

ESM (Node.js import):

import prettyQuick from "pretty-quick";

CommonJS (Node.js require):

const prettyQuick = require("pretty-quick");

Basic Usage

Programmatic API

import prettyQuick from "pretty-quick";

// Basic usage - format changed files in current directory
const result = await prettyQuick(process.cwd());
console.log(result.success); // boolean
console.log(result.errors);  // string[]

// With options
const result = await prettyQuick(process.cwd(), {
  staged: true,      // Only format staged files (Git only)
  verbose: true,     // Show files being processed
  pattern: "**/*.js", // Only process JavaScript files
  check: false,      // Format files (don't just check)
  bail: false,       // Don't exit on first formatting needed
});

Command Line Interface

# Format all changed files
npx pretty-quick

# Format only staged files (pre-commit mode)
npx pretty-quick --staged

# Check formatting without modifying files
npx pretty-quick --check

# Filter by pattern
npx pretty-quick --pattern "**/*.{js,ts}"

# Compare against specific branch
npx pretty-quick --branch develop

Architecture

Pretty Quick is built around several key components:

  • SCM Detection: Automatically detects Git or Mercurial repositories and finds changed files
  • File Filtering: Uses ignore files, patterns, and Prettier config to determine which files to process
  • Prettier Integration: Leverages Prettier's API for formatting and configuration resolution
  • Staging Workflow: For Git, supports restaging files after formatting in pre-commit scenarios

Capabilities

Main Function

The core pretty-quick function that formats changed files in a repository.

/**
 * Format changed files in a repository using Prettier
 * @param currentDirectory - Directory to run pretty-quick in
 * @param options - Configuration options
 * @returns Promise resolving to result with success status and any errors
 */
function prettyQuick(
  currentDirectory: string,
  options?: Partial<PrettyQuickOptions>
): Promise<PrettyQuickResult>;

interface PrettyQuickResult {
  /** Whether the operation completed successfully without errors */
  success: boolean;
  /** Array of error codes if any issues occurred */
  errors: string[];
}

Usage Example:

import prettyQuick from "pretty-quick";

async function formatChanges() {
  const result = await prettyQuick(process.cwd(), {
    staged: true,
    onWriteFile: (file) => console.log(`Formatted: ${file}`),
    onCheckFile: (file, isFormatted) => {
      if (!isFormatted) console.log(`Needs formatting: ${file}`);
    }
  });
  
  if (!result.success) {
    console.error("Formatting failed:", result.errors);
    process.exit(1);
  }
}

Configuration Options

Complete configuration interface for the pretty-quick function.

interface PrettyQuickOptions {
  /** Path to Prettier configuration file */
  config: string;
  /** SCM revision to compare against (e.g., git commit hash) */
  since: string;
  /** Only format staged files (Git only) */
  staged: boolean;
  /** File pattern(s) to filter which files are processed */
  pattern: string[] | string;
  /** Re-stage files after formatting when using --staged */
  restage: boolean;
  /** Branch to compare against (defaults to 'master' for Git, 'default' for Mercurial) */
  branch: string;
  /** Exit with error code if any files need formatting */
  bail: boolean;
  /** Check formatting without modifying files */
  check: boolean;
  /** Path to ignore file (alternative to .prettierignore) */
  ignorePath: string;
  /** Resolve Prettier config for file extensions */
  resolveConfig: boolean;
  /** Enable verbose output showing each file being processed */
  verbose: boolean;
  
  /** Callback fired when SCM revision is determined */
  onFoundSinceRevision(name: string, revision: string | null): void;
  /** Callback fired when changed files are found */
  onFoundChangedFiles(changedFiles: string[]): void;
  /** Callback fired when a partially staged file is encountered */
  onPartiallyStagedFile(file: string): void;
  /** Callback fired when examining each file (only in verbose mode) */
  onExamineFile(relative: string): void;
  /** Callback fired when checking file formatting status */
  onCheckFile(relative: string, isFormatted: boolean): void;
  /** Callback fired when a file is written/formatted */
  onWriteFile(relative: string): Promise<void> | void;
}

CLI Command

The pretty-quick command-line interface.

# Command: pretty-quick [options]

# Core options
--staged              # Format only staged files (Git only)
--no-restage         # Skip re-staging files after formatting
--branch <branch>    # Branch to compare against
--pattern <pattern>  # File pattern filter (can be used multiple times)
--verbose           # Show each file being processed
--bail              # Exit with error if files need formatting
--check             # Check formatting without modifying files
--ignore-path <path> # Alternative ignore file path
--no-resolve-config  # Don't resolve Prettier config for extensions

# Hidden/undocumented options
--config <path>      # Path to Prettier config file
--since <revision>   # SCM revision to compare against

CLI Usage Examples:

# Basic formatting of changed files
pretty-quick

# Pre-commit hook usage
pretty-quick --staged

# Check formatting in CI
pretty-quick --check --branch main

# Format specific file types
pretty-quick --pattern "**/*.{js,ts,json}"
pretty-quick --pattern "src/**/*" --pattern "tests/**/*"

# Verbose output for debugging
pretty-quick --verbose

# Custom ignore file
pretty-quick --ignore-path .gitignore

# Don't resolve custom Prettier extensions
pretty-quick --no-resolve-config

Error Handling

Pretty Quick can fail with the following error types returned in the errors array:

  • "BAIL_ON_WRITE" - Files needed formatting and bail option was true
  • "PARTIALLY_STAGED_FILE" - Partially staged files were found when using --staged
  • "CHECK_FAILED" - Files were incorrectly formatted when using --check

The function throws exceptions for:

  • Unable to detect source control manager
  • SCM command execution failures
  • File system access issues
// Error handling example
try {
  const result = await prettyQuick(process.cwd(), { staged: true, bail: true });
  
  if (!result.success) {
    if (result.errors.includes('PARTIALLY_STAGED_FILE')) {
      console.log('Some files are partially staged. Please stage all changes.');
    }
    if (result.errors.includes('BAIL_ON_WRITE')) {
      console.log('Files needed formatting. Commit aborted.');
    }
    if (result.errors.includes('CHECK_FAILED')) {
      console.log('Files are not properly formatted.');
    }
  }
} catch (error) {
  console.error('Pretty Quick failed:', error.message);
}

SCM Support

Pretty Quick supports the following source control managers:

Git Support

  • Detects Git repositories by finding .git directory
  • Compares against branch or commit hash
  • Supports staged file workflows
  • Can restage files after formatting

Mercurial Support

  • Detects Mercurial repositories by finding .hg directory
  • Compares against branch (defaults to 'default')
  • Limited staging support (Mercurial doesn't have Git-style staging)

Configuration Files

Pretty Quick respects standard Prettier configuration:

  • .prettierrc - Prettier configuration file (found by searching up file system)
  • .prettierignore - Files to ignore (found from repository root and working directory)
  • .editorconfig - Editor configuration (used by Prettier)

Custom ignore file can be specified with --ignore-path option.

Integration Patterns

Pre-commit Hook with simple-git-hooks

{
  "simple-git-hooks": {
    "pre-commit": "pretty-quick --staged"
  }
}

CI/CD Integration

# In CI pipeline - check formatting
pretty-quick --check --branch main

# Fail CI if files are not formatted
if ! pretty-quick --check --branch main; then
  echo "Code formatting check failed"
  exit 1
fi

Package.json Scripts

{
  "scripts": {
    "format": "pretty-quick",
    "format:staged": "pretty-quick --staged",
    "format:check": "pretty-quick --check"
  }
}