@hyperfrontend/workspace/git-hooksgit-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 HookStep | What it sets |
|---|---|
name | What the step is listed, skipped and selected by |
run | The program and its arguments, started without a shell from the workspace root |
env | Variables set for the step, over the environment the hook runs in |
failText | What is printed when the step fails |
stageFixed | Stage again the files that were fully staged before the step and that it changed |
passArgs | Append 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
Parameters
| Name | Type | Description |
|---|---|---|
§value | unknown | What hooks.config.ts exports |
Returns
HooksConfigExample
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, pushParameters
| Name | Type | Description |
|---|---|---|
§value | unknown | What hooks.local.config.ts exports |
Returns
LocalHooksConfigExample
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 nameshooks.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
| Name | Type | Description |
|---|---|---|
§config | HooksConfig | The steps of each hook |
Returns
HooksConfigExample
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.',
},
],
})hooks.local.config.ts beside the configuration.Parameters
| Name | Type | Description |
|---|---|---|
§config | LocalHooksConfig | The steps this clone does not run |
Returns
LocalHooksConfigExample
A clone that leaves the long step to the pull request
import { defineLocalHooks } from '@hyperfrontend/workspace/git-hooks'
export default defineLocalHooks({ skip: ['pipeline'] })Returns
string[ ]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 sinceParameters
| Name | Type | Description |
|---|---|---|
§cwd | string | The directory, absolute |
Returns
GitExample
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 treeParameters
Returns
LaunchExample
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 }Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
Promise< LoadedHooks>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'Parameters
| Name | Type | Description |
|---|---|---|
§value | string | The value of a flag or a variable, if any |
Returns
string[ ]Example
Reading the steps one push skips
import { namesOf } from '@hyperfrontend/workspace/git-hooks'
namesOf('pipeline, audit') // => ['pipeline', 'audit']
namesOf(undefined) // => []Parameters
| Name | Type | Description |
|---|---|---|
§existing | ReadonlyMap< | The content of each file in the directory, by name |
§configured | unknown | The hooks that have steps |
Returns
StubPlanExample
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'] }Parameters
Returns
string[ ]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 changesParameters
Returns
Promise< number>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.hooks run <hook>: the steps of a hook, in order, as the stub of that hook starts them.Parameters
| Name | Type | Description |
|---|---|---|
§argv | unknown | The arguments after hooks |
§session | HooksSession | The workspace root and the stream written to |
Returns
Promise< number>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 --skippush: 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
| Name | Type | Description |
|---|---|---|
§argv | unknown | The arguments after push, passed to git push |
§session | HooksSession | The workspace root and the stream written to |
Returns
Promise< number>git pushExample
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 pushedParameters
| Name | Type | Description |
|---|---|---|
§hook | HookName | The hook the step belongs to |
§step | string | The step's name |
§sources | SkipSources | The flags, the environment and the local file |
Returns
stringExample
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) // => nullParameters
| Name | Type | Description |
|---|---|---|
§config | HooksConfig | The hooks |
Returns
ReadonlySet< string><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') // => truehf executable of the package this module belongs to, as a path from the workspace root where the package lies inside it.Parameters
Returns
stringExample
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'Parameters
Returns
stringExample
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'Parameters
| Name | Type | Description |
|---|---|---|
§content | string | The file's content |
Returns
StubOriginExample
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'stubPlace( root: string, env: Readonly< Record< string, string | undefined>>, git: Git): StubPlace
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
Returns
StubPlaceExample
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 }Parameters
| Name | Type | Description |
|---|---|---|
§config | HooksConfig | The hooks |
§sources | SkipSources | The flags, the environment and the local file |
Returns
string[ ]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
Properties
Properties
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 stageFixed?:booleanWhether the files that were fully staged before the step, and that it changed, are staged again after it.Properties
Properties
Properties
readonly skip?:unknownThe steps this clone does not run: a step's name, or <hook>:<step> for the step of one hook.Properties
Properties
Properties
◆ Types
type Git = ( args: unknown, input?: string) => stringhf push runs first.type HookName = GitHook | unknowntype HooksConfig = mapped● Variables
hf push go by: they run before the push, outside any Git hook.