@hyperfrontend/workspace/git-hooks

git-hooks

Git hooks owned by the workspace: a typed configuration of named steps per hook, the runner behind hf hooks run and hf push, and the stubs Git starts.

Configuration

The hooks live in hooks.config.ts at the workspace root, declared with defineHooks. Each of pre-commit, commit-msg and pre-push is a list of named steps that run in order, and the first step that fails ends the hook. A fourth list, named push, holds the steps hf push runs before it pushes.

import { defineHooks } from '@hyperfrontend/workspace/git-hooks'

export default defineHooks({
  'pre-commit': [
    {
      name: 'format',
      run: ['hf', 'format', '--write'],
      stageFixed: true,
    },
  ],
  'commit-msg': [
    {
      name: 'message',
      run: ['cl'],
      passArgs: true,
      failText: 'Write a conventional commit message.',
    },
  ],
  'pre-push': [
    {
      name: 'version-check',
      run: ['hf', 'affected', '-t', 'version-check'],
      failText: 'Push with npx hf push.',
    },
    {
      name: 'checks',
      run: ['hf', 'affected', '-t', 'typecheck,lint', '-t', 'test'],
      env: { CI: '1' },
    },
  ],
  push: [
    {
      name: 'version',
      run: ['hf', 'run', 'workspace:version:all'],
    },
  ],
})
Field of a HookStepWhat it sets
nameWhat the step is listed, skipped and selected by
runThe program and its arguments, started without a shell from the workspace root
envVariables set for the step, over the environment the hook runs in
failTextWhat is printed when the step fails
stageFixedStage again the files that were fully staged before the step and that it changed
passArgsAppend the arguments Git gave the hook, such as the message file of commit-msg

A step is an argument array, so nothing is quoted and no variable is written in front of a command. hf starts this command line again the way it was started and node is the running Node.js. Any other program is found on the search path with the workspace's node_modules/.bin first; on Windows it starts through the command shim a package manager writes for it.

stageFixed never stashes and never touches unstaged content: a file that was only partly staged is left exactly as it was staged.

Installing

npx hf generate hooks

The generator writes one POSIX sh stub per hook that has steps into the repository's hooks directory, each starting hf hooks run <hook> with the arguments Git gave. It rewrites its own stubs, takes the place of Lefthook's, removes the stubs of hooks that no longer have steps, and refuses to replace a hook file somebody else wrote unless given --force. A workspace without a configuration gets a first one.

Installing the package runs nothing. A repository that wants its hooks installed on every install says so in its own root manifest:

{ "scripts": { "prepare": "hf generate hooks" } }

That is safe in a deploy build: where the CI variable is set or there is no repository, the generator writes nothing and succeeds. It also writes nothing, and says why, where the workspace is not the root of its repository or Git reads the hooks from a directory outside the workspace, as it does in a linked working tree.

Skipping

A clone that does not want a step names it in an untracked hooks.local.config.ts beside the configuration, declared with defineLocalHooks:

import { defineLocalHooks } from '@hyperfrontend/workspace/git-hooks'

export default defineLocalHooks({ skip: ['checks', 'pre-commit:format'] })

A name skips the step in every hook that has one; <hook>:<step> skips it in that hook alone. For one invocation, the variable HF_HOOKS_SKIP takes the same names separated by commas, and HF_HOOKS set to 0 skips every step:

HF_HOOKS_SKIP=checks git push

A skip is never silent. The hook ends on one line per step, and a skipped step is listed with what skipped it; a name that matches no step is reported too.

pre-push
  ✓ version-check  2.1s
  - checks         skipped by hooks.local.config.ts

Rehearsing and pushing

hf hooks run <hook> is what a stub starts, and by hand it rehearses the hook without committing or pushing. --only and --skip select steps by name:

npx hf hooks run pre-push
npx hf hooks run pre-push --only=version-check

hf push runs the push steps and then git push with the arguments it was given. Git resolves what a push sends before the pre-push hook runs, so a commit made inside that hook is left behind; a step that commits, such as a version bump, belongs among the push steps, where its commit is part of what the push carries and of what the pre-push hook then checks.

npx hf push --set-upstream origin feature

Building on the parts

The commands are built from exported parts. loadHooks reads both files, skipReason says what skips a step, and runHook runs steps through a host you supply:

import { loadHooks, runHook, skipReason } from '@hyperfrontend/workspace/git-hooks'
import { createTerminal } from '@hyperfrontend/workspace/progress'

const { config, local } = await loadHooks(process.cwd())
const sources = { env: process.env, local, only: [], skip: [] }

const code = await runHook(
  {
    hook: 'pre-push',
    steps: config['pre-push'] ?? [],
    args: [],
    skipOf: (step) => skipReason('pre-push', step, sources),
  },
  {
    start: async (step) => (step.name === 'checks' ? 0 : 1),
    now: () => performance.now(),
    terminal: createTerminal(process.stderr, process.env),
    fullyStaged: () => [],
    restage: () => [],
  }
)

API Reference§

ƒ Functions

§function

checkHooks(value: unknown): HooksConfig

Reads a value as a hooks configuration.
Parameters
NameTypeDescription
§value
unknownWhat hooks.config.ts exports
Returns
HooksConfig
The configuration
Example

Reading what a configuration file exports

import { checkHooks } from '@hyperfrontend/workspace/git-hooks'

checkHooks({ 'pre-push': [{ name: 'lint', run: ['hf', 'affected', '-t', 'lint'] }] }) // => the same object
checkHooks({ 'post-merge': [] }) // throws: post-merge is not a hook this configures; the hooks are pre-commit, commit-msg, pre-push, push
§function

checkLocalHooks(value: unknown): LocalHooksConfig

Reads a value as one clone's preferences.
Parameters
NameTypeDescription
§value
unknownWhat hooks.local.config.ts exports
Returns
LocalHooksConfig
The preferences
Example

Reading what a local file exports

import { checkLocalHooks } from '@hyperfrontend/workspace/git-hooks'

checkLocalHooks({ skip: ['pipeline', 'pre-commit:format'] }) // => the same object
checkLocalHooks({ skip: 'pipeline' }) // throws: skip takes a list of step names
§function

defineHooks(config: HooksConfig): HooksConfig

Declares the hooks of a workspace, in hooks.config.ts at its root. Each hook is a list of named steps that run in order; the first that fails ends the hook.
Parameters
NameTypeDescription
§config
HooksConfigThe steps of each hook
Returns
HooksConfig
The configuration, checked
Example

Formatting what is committed and checking what is pushed

import { defineHooks } from '@hyperfrontend/workspace/git-hooks'

export default defineHooks({
  'pre-commit': [{ name: 'format', run: ['hf', 'format', '--write'], stageFixed: true }],
  'pre-push': [
    {
      name: 'checks',
      run: ['hf', 'affected', '-t', 'typecheck,lint', '-t', 'test'],
      failText: 'A check failed. Each task wrote its log under .hf/logs.',
    },
  ],
})
§function

defineLocalHooks(config: LocalHooksConfig): LocalHooksConfig

Declares what one clone changes about the workspace's hooks, in an untracked hooks.local.config.ts beside the configuration.
Parameters
NameTypeDescription
§config
LocalHooksConfigThe steps this clone does not run
Returns
LocalHooksConfig
The preferences, checked
Example

A clone that leaves the long step to the pull request

import { defineLocalHooks } from '@hyperfrontend/workspace/git-hooks'

export default defineLocalHooks({ skip: ['pipeline'] })
§function

fullyStaged(git: Git): string[]

The files whose staged content is all there is to them: staged, and with no unstaged change.
Parameters
NameTypeDescription
§git
GitRuns git in the workspace
Returns
string[]
The paths, relative to the directory git runs in
Example

Before a formatter runs

import { fullyStaged, gitIn } from '@hyperfrontend/workspace/git-hooks'

fullyStaged(gitIn(process.cwd())) // => ['src/a.ts'] when src/b.ts is staged too but was edited since
§function

gitIn(cwd: string): Git

Git, run from a directory.
Parameters
NameTypeDescription
§cwd
stringThe directory, absolute
Returns
Git
Runs git there
Example

Asking the repository of the working directory

import { gitIn } from '@hyperfrontend/workspace/git-hooks'

gitIn(process.cwd())(['rev-parse', '--show-prefix']) // => '\n' at the root of a working tree
§function

launchOf(run: unknown, started: StartedAs, platform: Platform): Launch

How to start what a step runs.
Parameters
NameTypeDescription
§run
unknownThe program and its arguments, as the step writes them
§started
StartedAsThe running process
§platform
Platformwin32 or another platform name
Returns
Launch
The executable, its arguments and whether a shell starts it
Example

The command line itself, and a package's executable

import { launchOf } from '@hyperfrontend/workspace/git-hooks'

launchOf(['hf', 'format', '--write'], process, process.platform)
// => { file: '/usr/bin/node', args: ['/repo/node_modules/@hyperfrontend/workspace/bin/hf.mjs', 'format', '--write'], shell: false }
launchOf(['cl', '.git/COMMIT_EDITMSG'], process, 'linux')
// => { file: 'cl', args: ['.git/COMMIT_EDITMSG'], shell: false }
§function

loadHooks(root: string): Promise<LoadedHooks>

Loads the hooks of a workspace.
Parameters
NameTypeDescription
§root
stringThe workspace root, absolute
Returns
Promise<LoadedHooks>
The configuration, and the local preferences when the clone has any
Example

Listing the steps a push runs here

import { loadHooks } from '@hyperfrontend/workspace/git-hooks'

const { config, local } = await loadHooks(process.cwd())
const skipped = local.skip ?? []
(config['pre-push'] ?? []).filter((step) => !skipped.includes(step.name)).map((step) => step.name)
// => ['binary-budget', 'audit', 'version-check'] in a clone whose local file skips 'pipeline'
§function

namesOf(value: string): string[]

The names a comma-separated value holds.
Parameters
NameTypeDescription
§value
stringThe value of a flag or a variable, if any
Returns
string[]
The names, none for an absent or empty value
Example

Reading the steps one push skips

import { namesOf } from '@hyperfrontend/workspace/git-hooks'

namesOf('pipeline, audit') // => ['pipeline', 'audit']
namesOf(undefined) // => []
§function

planStubs(existing: ReadonlyMap<string, string>, configured: unknown): StubPlan

What installing the stubs of the configured hooks does to a hooks directory.
Parameters
NameTypeDescription
§existing
ReadonlyMap<string, string>The content of each file in the directory, by name
§configured
unknownThe hooks that have steps
Returns
StubPlan
The stubs to write, the files to remove, and the configured hooks somebody else's file occupies
Example

A clone that Lefthook set up, with a hook of the committer's own

import { planStubs } from '@hyperfrontend/workspace/git-hooks'

planStubs(
  new Map([
    ['pre-commit', '#!/bin/sh\ncall_lefthook run "pre-commit" "$@"\n'],
    ['post-commit', '#!/bin/sh\ncall_lefthook run "post-commit" "$@"\n'],
    ['pre-push', '#!/bin/sh\ngit lfs pre-push "$@"\n'],
  ]),
  ['pre-commit', 'pre-push']
)
// => { write: ['pre-commit'], remove: ['post-commit'], foreign: ['pre-push'] }
§function

restage(git: Git, before: unknown): string[]

Stages again the files a step changed, among those that were fully staged before it.
Parameters
NameTypeDescription
§git
GitRuns git in the workspace
§before
unknownThe files that were fully staged before the step
Returns
string[]
The files staged again
Example

After a formatter ran

import { fullyStaged, gitIn, restage } from '@hyperfrontend/workspace/git-hooks'

const git = gitIn(process.cwd())
const before = fullyStaged(git)
// ... the formatter rewrites src/a.ts
restage(git, before) // => ['src/a.ts'], staged with the formatter's changes
§function

runHook(run: HookRun, host: HookHost): Promise<number>

Runs the steps of a hook in order and reports them.
Parameters
NameTypeDescription
§run
HookRunThe hook, its steps, Git's arguments and which steps are skipped
§host
HookHostHow steps run and where the report is written
Returns
Promise<number>
The exit code: 0 when every step that ran succeeded, 1 otherwise
Example

A push whose audit fails before the long step starts

import { createTerminal } from '@hyperfrontend/workspace/progress'
import { runHook } from '@hyperfrontend/workspace/git-hooks'

const code = await runHook(
  {
    hook: 'pre-push',
    steps: [
      { name: 'audit', run: ['hf', 'run-many', '-t', 'audit', '--all'], failText: 'The audit failed.' },
      { name: 'pipeline', run: ['hf', 'affected', '-t', 'test'] },
    ],
    args: ['origin', 'git@example.com:acme/repo.git'],
    skipOf: () => null,
  },
  {
    start: async (step) => (step.name === 'audit' ? 1 : 0),
    now: () => performance.now(),
    terminal: createTerminal(process.stderr, process.env),
    fullyStaged: () => [],
    restage: () => [],
  }
)
// => 1, after the lines:
//   pre-push
//     ✗ audit     0s
//     · pipeline  not run
//   The audit failed.
§function

runHooksCommand(argv: unknown, session: HooksSession): Promise<number>

Runs hooks run <hook>: the steps of a hook, in order, as the stub of that hook starts them.
Parameters
NameTypeDescription
§argv
unknownThe arguments after hooks
§session
HooksSessionThe workspace root and the stream written to
Returns
Promise<number>
The exit code: 0 when every step that ran succeeded, 1 otherwise
Example

Rehearsing a push without the long step

import { runHooksCommand } from '@hyperfrontend/workspace/git-hooks'

const code = await runHooksCommand(['run', 'pre-push', '--skip=pipeline'], { root: process.cwd(), sink: process.stderr })
// => 0 when the other steps of pre-push succeeded; the list says pipeline was skipped by --skip
§function

runPushCommand(argv: unknown, session: HooksSession): Promise<number>

Runs push: the configuration's push steps, then git push with the arguments given. The pre-push hook then runs as on any push, on the commits the push carries. Asked for help, it prints its usage and runs nothing.
Parameters
NameTypeDescription
§argv
unknownThe arguments after push, passed to git push
§session
HooksSessionThe workspace root and the stream written to
Returns
Promise<number>
The exit code of the first step that failed, else of git push
Example

Pushing a branch for the first time

import { runPushCommand } from '@hyperfrontend/workspace/git-hooks'

const code = await runPushCommand(['--set-upstream', 'origin', 'feature'], { root: process.cwd(), sink: process.stderr })
// => 0 once the push steps succeeded and git pushed
§function

skipReason(hook: HookName, step: string, sources: SkipSources): string

Why a step is skipped, if it is.
Parameters
NameTypeDescription
§hook
HookNameThe hook the step belongs to
§step
stringThe step's name
§sources
SkipSourcesThe flags, the environment and the local file
Returns
string
What skipped the step, or null when it runs
Example

A step this clone's local file names

import { skipReason } from '@hyperfrontend/workspace/git-hooks'

const sources = { env: process.env, local: { skip: ['pipeline'] }, only: [], skip: [] }
skipReason('pre-push', 'pipeline', sources) // => 'hooks.local.config.ts'
skipReason('pre-push', 'audit', sources) // => null
§function

stepNames(config: HooksConfig): ReadonlySet<string>

The names of every step a configuration holds, plain and qualified by hook.
Parameters
NameTypeDescription
§config
HooksConfigThe hooks
Returns
ReadonlySet<string>
Each step as <step> and as <hook>:<step>
Example

Telling a skip that names nothing from one that names a step

import { stepNames } from '@hyperfrontend/workspace/git-hooks'

stepNames({ 'pre-push': [{ name: 'audit', run: ['hf', 'run-many', '-t', 'audit', '--all'] }] }).has('pre-push:audit') // => true
§function

stubEntry(root: string, from: string): string

The entry module a stub starts: the hf executable of the package this module belongs to, as a path from the workspace root where the package lies inside it.
Parameters
NameTypeDescription
§root
stringThe workspace root, absolute
§from
stringA directory of the package, absolute
Returns
string
The entry module, workspace-relative where it can be, POSIX
Example

The executable of the installed package

import { stubEntry } from '@hyperfrontend/workspace/git-hooks'

stubEntry('/repo', '/repo/node_modules/@hyperfrontend/workspace/git-hooks')
// => 'node_modules/@hyperfrontend/workspace/bin/hf.mjs'
§function

stubOf(hook: "pre-commit" | "commit-msg" | "pre-push", entry: string): string

The stub of a hook.
Parameters
NameTypeDescription
§hook
"pre-commit" | "commit-msg" | "pre-push"Which hook the stub starts
§entry
stringThe command line's entry module, relative to the workspace root or absolute, POSIX
Returns
string
The file's content
Example

The stub Git runs before a commit

import { stubOf } from '@hyperfrontend/workspace/git-hooks'

stubOf('pre-commit', 'node_modules/@hyperfrontend/workspace/bin/hf.mjs')
// => '#!/bin/sh\n# hf-hooks: ...\nexec node "node_modules/@hyperfrontend/workspace/bin/hf.mjs" hooks run pre-commit "$@"\n'
§function

stubOrigin(content: string): StubOrigin

Who wrote a stub.
Parameters
NameTypeDescription
§content
stringThe file's content
Returns
StubOrigin
This package, Lefthook, or somebody else
Example

Telling a stub that may be replaced from one that may not

import { stubOf, stubOrigin } from '@hyperfrontend/workspace/git-hooks'

stubOrigin(stubOf('pre-push', 'node_modules/@hyperfrontend/workspace/bin/hf.mjs')) // => 'own'
stubOrigin('#!/bin/sh\ncall_lefthook run "pre-push" "$@"\n') // => 'lefthook'
stubOrigin('#!/bin/sh\ngit lfs pre-push "$@"\n') // => 'foreign'
§function

stubPlace(root: string, env: Readonly<Record<string, string | undefined>>, git: Git): StubPlace

Where the stubs of a workspace go. None is written under CI or outside a repository, quietly, because the installing command also runs from the prepare script of deploy builds; none is written, with the reason, where the workspace is not the root of its repository or Git reads the repository's hooks from a directory outside the workspace.
Parameters
NameTypeDescription
§root
stringThe workspace root, absolute
§env
Readonly<Record<string, string | undefined>>The environment
§git
GitRuns git in the workspace
Returns
StubPlace
The hooks directory, or why there is none to write to
Example

A clone, and a deploy build of the same repository

import { gitIn, stubPlace } from '@hyperfrontend/workspace/git-hooks'

stubPlace(process.cwd(), {}, gitIn(process.cwd())) // => { directory: '.git/hooks', reason: null }
stubPlace(process.cwd(), { CI: 'true' }, gitIn(process.cwd())) // => { directory: null, reason: null }
§function

unknownSkips(config: HooksConfig, sources: SkipSources): string[]

The names that were meant to select or skip a step and match none, so a misspelt skip is said rather than silently ignored.
Parameters
NameTypeDescription
§config
HooksConfigThe hooks
§sources
SkipSourcesThe flags, the environment and the local file
Returns
string[]
One line per source that names a step no hook has
Example

A skip that names nothing

import { unknownSkips } from '@hyperfrontend/workspace/git-hooks'

const config = { 'pre-push': [{ name: 'pipeline', run: ['hf', 'affected', '-t', 'test'] }] }
unknownSkips(config, { env: { HF_HOOKS_SKIP: 'pipline' }, local: {}, only: [], skip: [] })
// => ['HF_HOOKS_SKIP names no step: pipline']

◈ Interfaces

§interface

HookHost

What the runner is given to run steps and say how they ended.
Properties
§readonly start:(step: HookStep, args: unknown) => Promise<number>Starts a step with its arguments and settles on its exit code.
§readonly now:() => numberThe time, in milliseconds.
§readonly terminal:TerminalWhere the lines are written.
§readonly fullyStaged:() => string[]The files that are fully staged.
§readonly restage:(before: unknown) => unknownStages again the files a step changed, among those given.
§interface

HookRun

A hook to run.
Properties
§readonly hook:HookNameThe hook, as the step list is headed.
§readonly steps:unknownIts steps, in order.
§readonly args:unknownThe arguments Git gave the hook.
§readonly skipOf:(step: string) => stringWhy a step is skipped, or null when it runs.
§interface

HooksSession

Where a command of the hooks runs and writes.
Properties
§readonly root:stringThe workspace root, absolute.
§readonly sink:ProgressSinkThe stream the step list goes to.
§interface

HookStep

One step of a hook.
Properties
§readonly name:stringThe name the step is listed, skipped and selected by: letters, digits, ., _ and -.
§readonly run:unknownThe program and its arguments, started without a shell from the workspace root. hf is this command line and node the running Node.js; any other program is found on the search path, the workspace's node_modules/.bin first.
§readonly env?:Readonly<Record<string, string>>Variables set for the step, over the environment the hook runs in.
§readonly failText?:stringWhat is printed when the step fails.
§readonly stageFixed?:booleanWhether the files that were fully staged before the step, and that it changed, are staged again after it.
§readonly passArgs?:booleanWhether the arguments Git gave the hook follow the step's own.
§interface

Launch

A program ready to be spawned.
Properties
§readonly file:stringThe executable, or on Windows the whole command line of a shim.
§readonly args:unknownIts arguments.
§readonly shell:booleanWhether it starts through the platform shell, which only a Windows shim needs.
§interface

LoadedHooks

A workspace's hooks and what this clone changes about them.
Properties
§readonly config:HooksConfigThe steps of each hook.
§readonly local:LocalHooksConfigThis clone's preferences; none where it keeps no local file.
§interface

LocalHooksConfig

What one clone changes about the workspace's hooks.
Properties
§readonly skip?:unknownThe steps this clone does not run: a step's name, or <hook>:<step> for the step of one hook.
§interface

SkipSources

Everything that can keep a step from running.
Properties
§readonly env:Readonly<Record<string, string | undefined>>The environment the hook runs in.
§readonly local:LocalHooksConfigThis clone's preferences.
§readonly only:unknownThe steps --only names; none runs every step.
§readonly skip:unknownThe steps --skip names.
§interface

StubPlace

Where stubs go, or why none is written.
Properties
§readonly directory:stringThe hooks directory, workspace-relative and POSIX; null when no stub is written.
§readonly reason:stringWhy no stub is written, when that is worth saying; null where staying quiet is the point.
§interface

StubPlan

What installing does to the hooks directory.
Properties
§readonly write:unknownThe hooks whose stub is written.
§readonly remove:unknownThe files removed: this package's and Lefthook's stubs of hooks no longer configured.
§readonly foreign:unknownThe configured hooks whose file somebody else wrote.

◆ Types

§type

Git

Runs git with arguments and, when given, standard input; answers what it printed.
type Git = (args: unknown, input?: string) => string
§type

GitHook

One of the Git hooks.
type GitHook = indexedAccess
§type

HookName

A list of steps a configuration names: a Git hook, or the steps hf push runs first.
type HookName = GitHook | unknown
§type

HooksConfig

A workspace's hooks: the steps of each, in the order they run.
type HooksConfig = mapped
§type

StubOrigin

One of the origins.
type StubOrigin = indexedAccess

● Variables

§type

GIT_HOOKS

The Git hooks a workspace configures, in the order a commit and a push reach them.
§type

HOOKS_CONFIG

The file holding a workspace's hooks, at its root.
§type

HOOKS_USAGE

What the command line expects.
§type

HOOKS_VARIABLE

The variable that switches every hook off when it holds 0.
§type

LOCAL_HOOKS_CONFIG

The file holding one clone's preferences, at the workspace root and never tracked.
§type

PUSH_STEPS

The name the steps of hf push go by: they run before the push, outside any Git hook.
§type

PUSH_USAGE

What the command line expects.
§type

SKIP_VARIABLE

The variable naming the steps one invocation skips, separated by commas.
§type

STUB_MARKER

The comment that marks a stub as this package's own.
§type

StubOrigin

Who wrote a stub.