• Stars
    star
    169
  • Rank 219,869 (Top 5 %)
  • Language
    JavaScript
  • Created over 10 years ago
  • Updated 6 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Automatically install pre-commit / pre-push hooks in your git repo

pre-git

Important git hooks implemented using Nodejs for your project.

NPM

Build status Build Status dependencies devdependencies semantic-release manpm renovate-app badge

Why?

You can easily run the pre-commit and pre-push Git hooks to avoid breaking the local master branch or the remote master.

Installation

It's advised to install this module as devDependency in your package.json file so it doesn't get installed on production servers. Run:

npm install pre-git --save-dev

Configuration

Specify commands to run on commit and on push in your package.json under config > pre-git object.

"scripts": {
  "test": "node-qunit *.js"
},
"config": {
  "pre-git": {
    "enabled": true,
    "msg-pattern": "^(US|DE)\\d+ - .+",
    "commit-msg": "simple",
    "pre-commit": [
      "grunt jshint"
    ],
    "post-commit": "git status",
    "pre-push": [
      "rm -rf node_modules",
      "npm install",
      "grunt build",
      "grunt test"
    ],
    "post-checkout": "npm install",
    "post-merge": "npm install"
  }
}

If there are older settings like pre-commit, etc, you will have to move them to the config > pre-git object manually.

Related project: post-merge-make runs make post-merge after pull or merge.

Subprojects

If you have large repo, it is possible that there might be nested files with different package.json files. In this case, the search will proceed up from the current working directory until it finds package.json with valis config.pre-git object inside.

Windows

Thanks to ybiquitous for adding support for Windows.

  • Git Bash (Git for Windows): work fine!
  • Command prompt: work if sh.exe in PATH (e.g. set PATH=C:\Program Files\Git\bin;%PATH%)

Untracked files

Before the commit, we check if there are any untracked files. A commit does not continue if there are any. Please git ignore or delete unnecessary files before running the git commit command to ensure clean tests. In every case where I forgot to add files to the repo, this was by accident and caused breaking tests.

This can be disabled by setting the allow-untracked-files option to true

{
"config": {
  "pre-git": {
     "allow-untracked-files": true
  }
}

Details

You can disable all pre-git hooks by setting the configuration option to false

{
"config": {
  "pre-git": {
     "enabled": false
  }
}

If the 'config.pre-git' object has the option 'enabled' missing, it is assumed to be "true" and the hooks are executed.

You can always skip pre-commit hook (but not pre-push hook!) by using -n option

git commit -m "done, don't check me" -n

You can skip the pre-push hook using --no-verify option

To run just the hook (for example to test what it does), execute

.git/hooks/pre-commit
.git/hooks/pre-push

Since there might be no changes to push, you can force the pre-commit hook to execute using -f or --force argument

.git/hooks/pre-commit -f

Validating commit message

By default, this package will install both the message validator and the message format helper. You can disable the validation by removing the below command.

"config": {
  "pre-git": {
    "commit-msg": "conventional"
  }
}

When you run git commit -m "message ..." the hook will enforce the default style type(scope): message .... To better form the message, there is a CLI wizard installed based on commitizen project, very well shown in the tutorial video. The commit wizard is available under "node_modules/.bin/commit-wizard" link and can be started from command line

node --harmony node_modules/.bin/commit-wizard

or via a script

"scripts": {
  "commit": "commit-wizard"
}

Then run

npm run commit

The wizard will look something like this

? Select the type of change that you're committing:
  feat:     A new feature
❯ fix:      A bug fix
  chore:    Changes to the build process or auxiliary tools
            and libraries such as documentation generation

There are 2 plugins included with pre-git:

I recommend sticking with "simple" unless you need more release types.

Development

In order to locally test this package, from another git repo execute the install script using -f or --force argument. For example

$ node ../pre-git/src/install.js -f
pre-git 0.7.2 in /Users/kensho/git/test-git-hooks
/Users/kensho/git/test-git-hooks
read target package from /Users/kensho/git/test-git-hooks/package.json
added empty command list for hook commit-msg
added empty command list for hook pre-commit
added empty command list for hook pre-push
added empty command list for hook post-commit
added empty command list for hook post-merge
saving updated files /Users/kensho/git/test-git-hooks/package.json
"config": {
  "pre-git": {
    "msg-pattern": "whatever-regex-without-delimiters"
  }
}

When using msg-pattern, the pre-git will match the commit message against the given pattern, if the test fails, then it will stop the execution and will exit the commit, this feature is optional and can be used along with any of the commit wizards, however those can be omitted using only the pattern, this is a useful manner of checking a custom message, as some commit may require custom codes as user story prefixes and so on.

It is also possible to customize your own msg-pattern-error along with msg-pattern to be more descriptive as to why the pattern fails.

"config": {
  "pre-git": {
    "msg-pattern": "whatever-regex-without-delimiters",
    "msg-pattern-error": "whatever error message that will be thrown when the pattern fails"
  }
}

I am using a small project test-pre-git as a test playground for these hooks.

End to end testing

To create a sample project and test the hooks, just run the included script npm run e2e which should finish with status zero.

To see how pre-git stops a commit when a hook fails, run npm run test-no-commit-on-test-fail command, which should exit with status 1.

You can verify the git hooks are not running when the pre-git is disabled via a config option by running npm run e2e-pre-git-disabled which allows the commit to go through.

To see how allow-untracked-files option lets the commit go through, run npm run test-allow-untracked-files

Debugging

If a hook does not behave as expected, you can see verbose log messages by setting the environment variable DEBUG=pre-git when running a git command. For example, to see the messages when committing

DEBUG=pre-git git commit -m "a message"
running pre-commit script
pre-git pre-commit +0ms arguments [ 'node',
  '/instant-vdom-todo/node_modules/.bin/pre-commit' ]
pre-commit No changes detected, bailing out.
pre-git found package in folder +0ms /instant-vdom-todo
pre-git commit message wizard name from +5ms
...

This should provide plenty of information to debug the hooks

Desktop Git clients

The Git hooks should work in desktop clients, like GitHub Desktop app. If something does not work, it is usually because the desktop App cannot find node. See what Git Tower application suggests you do in that case.

Local development

To execute commit message validation, run npm run demo-commit-message and vary the test message to see how the hook validates it.

Recent contributors

Small print

Author: Gleb Bahmutov © 2014

License: MIT - do anything with the code, but don't blame me if it does not work.

Spread the word: tweet, star on github, etc.

Support: if you find any problems with this module, email / tweet / open issue on Github

More Repositories

1

code-snippets

Chrome DevTools code snippets
JavaScript
1,798
star
2

start-server-and-test

Starts server, waits for URL, then runs test command; when the tests end, shuts down server
JavaScript
1,417
star
3

npm-install

GitHub Action for install npm dependencies with caching without any configuration
JavaScript
642
star
4

next-update

Tests if module's dependencies can be updated to latest version
JavaScript
558
star
5

bottle-service

Instant web applications restored from ServiceWorker cache
JavaScript
331
star
6

javascript-journey

Source code for blog post Journey from procedural to reactive JavaScript with stops
JavaScript
329
star
7

babel-service

On demand targeted transpiling inside the browser's ServiceWorker
JavaScript
209
star
8

dont-break

Checks if the current version of your package would break dependent projects
JavaScript
206
star
9

cy-api

Cypress custom command "cy.api" for end-to-end API testing
TypeScript
206
star
10

cypress-and-jest

Cypress and Jest both with code coverage running unit tests
JavaScript
205
star
11

express-service

Package ExpressJS server to run inside a ServiceWorker
JavaScript
203
star
12

cypress-failed-log

Saves the Cypress test command log as a JSON file if a test fails
JavaScript
179
star
13

snap-shot

Jest-like snapshot feature for the rest of us, works magically by finding the right caller function
JavaScript
171
star
14

cypress-svelte-unit-test

Unit testing Svelte components in Cypress E2E test runner
JavaScript
160
star
15

cypress-angular-unit-test

Trying to load and bootstrap Angular component dynamically inside Cypress
TypeScript
157
star
16

cypress-dark

Dark and Halloween color themes for Cypress.io test runner
CSS
155
star
17

snap-shot-it

Smarter snapshot utility for Mocha and BDD test runners + data-driven testing!
JavaScript
155
star
18

draw-cycle

Simple Cycle.js application visualized: streams, events, DOM
HTML
146
star
19

now-pipeline

Simple CI pipeline with goal to deploy new version at Zeit Now cloud if tests pass
JavaScript
143
star
20

console.table

Adds console.table method that prints an array of objects as a table in console
JavaScript
140
star
21

npm-quick-run

Quickly run NPM script by prefix without typing the full name
JavaScript
139
star
22

next-and-cypress-example

Next.js example instrumented for code coverage from Cypress tests
JavaScript
129
star
23

cypress-skip-and-only-ui

Client-side buttons to run a single test or skip it for Cypress test runner
TypeScript
128
star
24

cache-require-paths

Caches resolved paths in module require to avoid Node hunting for right module. Speeds up app load.
JavaScript
127
star
25

npm-module-checklist

Steps to check when starting, working and publishing a module to NPM
124
star
26

really-need

Node require wrapper with options for cache busting, pre- and post-processing
JavaScript
109
star
27

add-typescript-to-cypress

Quickly adds TypeScript spec support to Cypress
JavaScript
108
star
28

cypress-examples

Static site with Cypress examples tested right from the Markdown sources
JavaScript
105
star
29

cypress-select-tests

User space solution for picking Cypress tests to run
JavaScript
98
star
30

test-todomvc-using-app-actions

Example Cypress tests going from page objects to app actions
TypeScript
97
star
31

cypress-movie

Generate movies from your Cypress end-to-end tests
JavaScript
95
star
32

eslint-rules

My custom eslint rules in addition to the ones provided at http://eslint.org/
JavaScript
95
star
33

console-log-div

Clones console.log calls to a created div in the page. Great for demos and experiments.
JavaScript
94
star
34

rambo

Automatic Ramda solution bot
JavaScript
92
star
35

git-branches

Bash shell to show current branches and their descriptions using only default Git features
JavaScript
89
star
36

cypress-recurse

A way to re-run Cypress commands until a predicate function returns true
JavaScript
88
star
37

game-of-github

Play Game of Life in your GitHub contributions
JavaScript
83
star
38

have-it

The fastest NPM install does nothing because you already have it
JavaScript
75
star
39

node-rx-cycle

Example using RxJS and Cycle.js on the server to handle requests (NOT server-side rendering)
JavaScript
73
star
40

lazy-ass

Lazy node assertions without performance penalty
TypeScript
68
star
41

talks

Public presentations
JavaScript
67
star
42

node-hook

Run source transform function on node require call
JavaScript
66
star
43

as-a

Runs a given command with additional environment settings for simple local development
JavaScript
64
star
44

ban-sensitive-files

Checks filenames to be committed against a library of filename rules to prevent sensitive files in Git
JavaScript
62
star
45

cypress-split

Split Cypress specs across parallel CI machines for speed
JavaScript
59
star
46

js-complexity-viz

JavaScript source code complexity tool
JavaScript
58
star
47

changed-log

Returns all commit messages between 2 versions of an NPM module
JavaScript
58
star
48

cypress-network-idle

A little Cypress.io plugin for waiting for network to be idle before continuing with the test
JavaScript
55
star
49

rollem

Roll up multiple ES6 bundles at once
JavaScript
54
star
50

cypress-watch-and-reload

Reloads Cypress when one of the watched files changes
JavaScript
53
star
51

cypress-data-session

Cypress command for flexible test data setup
JavaScript
51
star
52

cypress-esbuild-preprocessor

Bundle Cypress specs using esbuild
JavaScript
48
star
53

functional-pipeline

Quickly chain method calls, property access and functions into a pipeline
JavaScript
48
star
54

cypress-if

Easy conditional if-else logic for your Cypress tests when there is no other way
JavaScript
46
star
55

demo-docker-cypress-included

Demo running the complete Docker image `cypress/included`
Shell
45
star
56

vue-vuex-todomvc

Example TodoMVC Vue.js app with Vuex store and server backend via REST
JavaScript
44
star
57

manpm

Shows the relevant part of NPM module's README file right in your terminal
JavaScript
42
star
58

mocked-env

Easy way to mock process.env during BDD testing
JavaScript
42
star
59

compiled

Compiles the ES* bundle to your NodeJS version on install
JavaScript
41
star
60

ng-simple-webrtc

AngularJS wrapper for SimpleWebRTC client from https://simplewebrtc.com/
JavaScript
41
star
61

cypress-playwright

Run Cypress tests using Playwright and Playwright tests using Cypress
JavaScript
41
star
62

next-updater

Dependable and safe automatic dependency updater for Nodejs packages
JavaScript
41
star
63

rocha

Runs Mocha unit tests but randomizes their order
JavaScript
40
star
64

node-mock-examples

Examples of tests that mock Node system APIs: fs, http, child_process, timers
JavaScript
39
star
65

generator-node-bahmutov

My personal Node project boilerplate generator
JavaScript
38
star
66

center-code

Shows the file's source centered in the terminal
JavaScript
38
star
67

bdd-stdin

Utility for easily feeding mock responses to unit tests that require command line input from the user
JavaScript
38
star
68

instant-vdom-todo

Prehydrated, self-rewriting TodoMVC using Virtual-Dom and bottle-service
JavaScript
37
star
69

hydrate-app

Quick app pre-loading using saved HTML snapshot
JavaScript
36
star
70

cypress-workshop-basics

Basics of end-to-end testing with Cypress.io test runner
JavaScript
35
star
71

iframe-api

Bidirectional method calls API between external and iframed code.
JavaScript
35
star
72

cly

A prototype of Cypress CLI for quicker project scaffolding
JavaScript
34
star
73

condition-circle

Checks CircleCI environment before publishing successful build using semantic-release
JavaScript
33
star
74

cy-spok

Playing with spok inside Cypress
JavaScript
33
star
75

cypress-extends

Cypress plugin that adds "extends" support to the configuration file
JavaScript
33
star
76

schema-shot

Framework-agnostic snapshot testing using "schema by example" for highly dynamic data
JavaScript
33
star
77

spots

Partial function argument binding with placeholders
JavaScript
33
star
78

change-by-example

Finds a function that transforms a given object into another given object.
JavaScript
33
star
79

cypress-repeat

Run Cypress multiple times in a row
JavaScript
32
star
80

grunty

Run any grunt plugin as NPM script without Gruntfile.js
JavaScript
31
star
81

cypress-gh-action-example

Example running Cypress tests inside GitHub Action
JavaScript
31
star
82

all-nvm

Run any NPM command (including install) in all versions of Node managed by NVM
JavaScript
30
star
83

ci-publish

Poor man's semantic release utility. Let the CI do the `npm publish` step after the build passes
JavaScript
30
star
84

find-cypress-specs

Find Cypress spec files using the config settings
JavaScript
29
star
85

prettier-config-example

Example project with different per-folder prettier config and VSCode formatting on save
JavaScript
28
star
86

next-ver

Tells you the next semantic version for your local package
JavaScript
28
star
87

xplain

JavaScript API documentation generator that uses unit tests as examples, see example API doc at
JavaScript
28
star
88

todo-graphql-example

Example Todo app on top of json-graphql-server
JavaScript
27
star
89

local-cypress

Use Cypress without global objects
JavaScript
27
star
90

comment-value

Instruments a Node program and updates its comments with computed expression values
JavaScript
27
star
91

d3-helpers

Little utility D3 functions
JavaScript
27
star
92

cypress-hyperapp-unit-test

Unit test Hyperapp components using Cypress
JavaScript
26
star
93

google-cloud-build-example

Example running Cypress end-to-end tests on Google Cloud Build
JavaScript
26
star
94

heroin

Strong and addictive dependency injection for JavaScript
JavaScript
25
star
95

ggit

Local git command wrappers
JavaScript
25
star
96

wiseli

See the repo's example while installing it with NPM
JavaScript
24
star
97

cypress-timings

A Cypress plugin for reporting individual command timings
JavaScript
24
star
98

term-to-html

Stream terminal output with ansi codes into nicely formatted HTML
JavaScript
24
star
99

cypress-angularjs-unit-test

Unit test Angularjs code using Cypress.io test runner
JavaScript
23
star
100

cypress-get-it

Get elements by data attribute by creating a Cy command on the fly
JavaScript
23
star