How to create custom husky hook? (node.js/package.json) - husky

How to create custom husky hook?
I would like to do something like this:
// package.json
...
husky: {
"pre-commit": "node customHook.js"
},
...
How to get access to the commit params from the customHook.js file?
P.S. I found almost the same question, but unfortunately it doesn't work for me.

I found a solution.
Change "pre-commit" hook to "commit-msg" in the package.json file. After, you are able to get commit message by using the next line of code:
// terminal (cmd)
git commit -m "my commit message"
// customHook.js file
const message = require('fs').readFileSync(process.env.HUSKY_GIT_PARAMS, 'utf-8');
console.log(message); // "my commit message"

Related

Update package.json version with pre-commit hook

I'm trying to automate the version bump of a Node.js project hosted on a private github repo.
The project is meant to run locally, so it's not published, neither released. People in my organization just pull the main branch and run it on their machines with yarn && yarn start.
What I want to achieve
What I want to achieve is that in the pre-commit phase a version bump is made (major, patch or minor) to the package.json of this project and committed together with the code changed according to the commit message.
All I want to do is that my PR is including the change in the package.json without me having to do it manually. I don't need releases or CI for this.
What I did successfully
I have setup Husky and commitlint in order to validate conventional commit message and it works fine.
What I tried, but failed
I tried to use semantic-release and other packages to provide this functionality, but they all imply there's a CI build or release somewhere so I'm stuck.
Any idea?
in case you have any kind of CICD pipeline (not entirely limited to git hooks scope) you can use gitversion cli
it supports version bump per commit message regex configuration example:
major-version-bump-message: '\+semver:\s?(breaking|major)'
minor-version-bump-message: '\+semver:\s?(feature|minor)'
patch-version-bump-message: '\+semver:\s?(fix|patch)'
no-bump-message: '\+semver:\s?(none|skip)'
means that a commit with message my commit msg +semver: fix will trigger a patch version bump
see this article with detailed explanation for setup.
Instead of pre-commit you should use the commit-msg hook.
The pre-commit hook is triggered before there is a commit message yet, but if you use the commit-msg hook, it will be triggered after there is a commit message.
The hook will trigered your script and the first argument your script will receive will be the commit message itself.
Then you can write any logic on top of the commit message. You can check the message, and update version based of the message as you requested. There are many ways to it
npm version major
you can user updateCommitId modules to write custom node JS code to run during pre-commit hook. Sample working code can look like below. Please upgrade as deemed required.
{
"version": "1.12.0",
"dependencies": {},
"pre-commit": ["updateCommitId"],
"scripts": {
"updateCommitId": "node updateVersion.js"
},
"devDependencies": {
"pre-commit": "^1.2.2",
"semver": "^7.3.5",
"simple-git": "^3.2.6"
}
}
const semver = require("semver");
const simpleGit = require("simple-git");
const options = {
baseDir: process.cwd(),
binary: "git",
maxConcurrentProcesses: 6,
};
const git = simpleGit(options);
const json = require("./package.json");
function savePackage() {
require("fs").writeFileSync(
process.cwd() + "/package.json",
JSON.stringify(json, null, 2)
);
}
async function updateVersion() {
try {
if (json.version) {
const version = semver.parse(json.version);
version.inc("minor");
json.version = version.toString();
savePackage();
await git.add("package.json");
process.exit(0);
}
} catch (e) {
console.log(e);
process.exit(1);
}
}
updateVersion();

Executing a task after all test are launch cypress

I need to execute some code after all tests run. I add this test on after hook. But this task needs the report to be created, but on after hook, the report is not created yet.
I also tried to use
on('run:end', () => {
console.log("gdfgfdsafkañjsdfjñaldfkjsñkasfdñlassfjdskafmjassd");
});
but it does nothing.
You can't, there is an open issue for that.
At the moment you can only leverage a package.json post hook. So, if you have a dedicated command in your package.json file
"scripts": {
"cy:run": "cypress run"
}
you can add a postcy:run script
"scripts": {
"cy:run": "cypress run",
"postcy:run": "<YOUR_COMMAND>"
}
I hope it helps you 😊
You can now listen to after:run events in the plugins file:
on('after:run', (results) => { /* ... */ })
The event fires after the run.
See more info at After Run API
Be aware that the post hook might not run when the tests fail. I'm currently using a global after hook in support/index.ts for running after all tests
I'm currently using a global after hook in support/index.ts
after(() => {
// something here
});

Syntax error when start $ heroku open

I am new to Heroku and I am trying to deploy my first app onto Heroku.
I followed instruction, which were:
git init, add and commit my app's source code.
heroku create to create Heroku remote repo for my app.
git push heroku master to push my app's source code to heroku
heroku open
Problem happened when I tried to run heroku open, which was:
$ heroku open
(node:6192) SyntaxError Plugin:
heroku:C:\Users\hauph\AppData\Local\heroku\conf
ig.json: Unexpected string in JSON at position 72 module:
#oclif/config#1.6.33
task: runHook prerun
plugin: heroku
root: C:\Program Files\heroku\client
See more details with DEBUG=*
Image taken from that error
I checked file config.json at the direction as addressed above, and it was:
{
"schema": 1,
"install": "554c101b-d4de-496c-9768-710142ebfb20"
}
"skipAnalytics": false
}
So what did I do wrong here?
I would be grateful for any help.
Thank you very much!
I had the same problem. Not sure why it ends up corrupted, but the config.json should look like the following (get rid of the curly brace before skipAnalytics):
{
"schema": 1,
"install": "3265b92a-27f4-4adb-9c07-75d9213f0000",
"skipAnalytics": false
}
Your config.json contains invalid JSON (note the two closing brackets). Reinstall the Heroku CLI, and you should be in good shape.
I tried reinstalling but didn't work, just add curly braces in the config.json file.
{
}
Works perfectly now.
I had the same error when I tried to build on heroku as like below
(node:1179857) SyntaxError Plugin: heroku: /home/{...}/.local/share/heroku/config.json: Unexpected end of JSON input
module: #oclif/config#1.18.3
task: runHook prerun
plugin: heroku
root: /snap/heroku/4085
See more details with DEBUG=*
set git remote heroku to https://git.heroku.com/{...}.git
So I opened the config.json file from this path /home/{...}/.local/share/heroku/config.json and added blank curly braces
{
}
Then I run the command heroku git:remote -a {your project name} to set heroku git remote
Finally checked the config.json file and added valid json value automatically like this screenshot:
{
"schema": 1,
"install": "19975845-fr45-hfgt6-iu78-c27hgy243c46d",
"skipAnalytics": false
}
Finally set remote successfully. I hope it will make developers easier to deploy on heroku if this type of error comes.
USAGE
$ heroku apps:open [PATH]
OPTIONS
-a, --app=app (required) app to run command against
-r, --remote=remote git remote of app to use
EXAMPLES
$ heroku open -a myapp
# opens https://myapp.herokuapp.com
$ heroku open -a myapp /foo
# opens https://myapp.herokuapp.com/foo
Please visit heroku cli commands documentation here https://devcenter.heroku.com/articles/heroku-cli-commands

Add git information to create-react-app

In development, I want to be able to see the build information (git commit hash, author, last commit message, etc) from the web. I have tried:
use child_process to execute a git command line, and read the result (Does not work because browser environment)
generate a buildInfo.txt file during npm build and read from the file (Does not work because fs is also unavailable in browser environment)
use external libraries such as "git-rev"
The only thing left to do seems to be doing npm run eject and applying https://www.npmjs.com/package/git-revision-webpack-plugin , but I really don't want to eject out of create-react-app. Anyone got any ideas?
On a slight tangent (no need to eject and works in develop),
this may be of help to other folk looking to add their current git commit SHA into their index.html as a meta-tag by adding:
REACT_APP_GIT_SHA=`git rev-parse --short HEAD`
to the build script in the package.json and then adding (note it MUST start with REACT_APP... or it will be ignored):
<meta name="ui-version" content="%REACT_APP_GIT_SHA%">
into the index.html in the public folder.
Within react components, do it like this:
<Component>{process.env.REACT_APP_GIT_SHA}</Component>
I created another option inspired by Yifei Xu's response that utilizes es6 modules with create-react-app. This option creates a javascript file and imports it as a constant inside of the build files. While having it as a text file makes it easy to update, this option ensures it is a js file packaged into the javascript bundle. The name of this file is _git_commit.js
package.json scripts:
"git-info": "echo export default \"{\\\"logMessage\\\": \\\"$(git log -1 --oneline)\\\"}\" > src/_git_commit.js",
"precommit": "lint-staged",
"start": "yarn git-info; react-scripts start",
"build": "yarn git-info; react-scripts build",
A sample component that consumes this commit message:
import React from 'react';
/**
* This is the commit message of the last commit before building or running this project
* #see ./package.json git-info for how to generate this commit
*/
import GitCommit from './_git_commit';
const VersionComponent = () => (
<div>
<h1>Git Log: {GitCommit.logMessage}</h1>
</div>
);
export default VersionComponent;
Note that this will automatically put your commit message in the javascript bundle, so do ensure no secure information is ever entered into the commit message. I also add the created _git_commit.js to .gitignore so it's not checked in (and creates a crazy git commit loop).
It was impossible to be able to do this without ejecting until Create React App 2.0 (Release Notes) which brought with it automatic configuration of Babel Plugin Macros which run at compile time. To make the job simpler for everyone, I wrote one of those macros and published an NPM package that you can import to get git information into your React pages: https://www.npmjs.com/package/react-git-info
With it, you can do it like this:
import GitInfo from 'react-git-info/macro';
const gitInfo = GitInfo();
...
render() {
return (
<p>{gitInfo.commit.hash}</p>
);
}
The project README has some more information. You can also see a live demo of the package working here.
So, turns out there is no way to achieve this without ejecting, so the workaround I used is:
1) in package.json, define a script "git-info": "git log -1 --oneline > src/static/gitInfo.txt"
2) add npm run git-info for both start and build
3) In the config js file (or whenever you need the git info), i have
const data = require('static/gitInfo.txt')
fetch(data).then(result => {
return result.text()
})
My approach is slightly different from #uidevthing's answer. I don't want to pollute package.json file with environment variable settings.
You simply have to run another script that save those environment variables into .env file at the project root. That's it.
In the example below, I'll use typescript but it should be trivial to convert to javascript anyway.
package.json
If you use javascript it's node scripts/start.js
...
"start": "ts-node scripts/start.ts && react-scripts start",
scripts/start.ts
Create a new script file scripts/start.ts
const childProcess = require("child_process");
const fs = require("fs");
function writeToEnv(key: string = "", value: string = "") {
const empty = key === "" && value === "";
if (empty) {
fs.writeFile(".env", "", () => {});
} else {
fs.appendFile(".env", `${key}='${value.trim()}'\n`, (err) => {
if (err) console.log(err);
});
}
}
// reset .env file
writeToEnv();
childProcess.exec("git rev-parse --abbrev-ref HEAD", (err, stdout) => {
writeToEnv("REACT_APP_GIT_BRANCH", stdout);
});
childProcess.exec("git rev-parse --short HEAD", (err, stdout) => {
writeToEnv("REACT_APP_GIT_SHA", stdout);
});
// trick typescript to think it's a module
// https://stackoverflow.com/a/56577324/9449426
export {};
The code above will setup environment variables and save them to .env file at the root folder. They must start with REACT_APP_. React script then automatically reads .env at build time and then defines them in process.env.
App.tsx
...
console.log('REACT_APP_GIT_BRANCH', process.env.REACT_APP_GIT_BRANCH)
console.log('REACT_APP_GIT_SHA', process.env.REACT_APP_GIT_SHA)
Result
REACT_APP_GIT_BRANCH master
REACT_APP_GIT_SHA 042bbc6
More references:
https://create-react-app.dev/docs/adding-custom-environment-variables/#adding-development-environment-variables-in-env
If your package.json scripts are always executed in a unix environment you can achieve the same as in #NearHuscarl answer, but with fewer lines of code by initializing your .env dotenv file from a shell script. The generated .env is then picked up by the react-scripts in the subsequent step.
"scripts": {
"start": "sh ./env.sh && react-scripts start"
"build": "sh ./env.sh && react-scripts build",
}
where .env.sh is placed in your project root and contains code similar to the one below to override you .env file content on each build or start.
{
echo BROWSER=none
echo REACT_APP_FOO=bar
echo REACT_APP_VERSION=$(git rev-parse --short HEAD)
echo REACT_APP_APP_BUILD_DATE=$(date)
# ...
} > .env
Since the .env is overridden on each build, you may consider putting it on the .gitignore list to avoid too much noise in your commit diffs.
Again the disclaimer: This solution only works for environments where a bourne shell interpreter or similar exists, i.e. unix.
You can easily inject your git information like commit hash into your index.html using CRACO and craco-interpolate-html-plugin. Such way you won't have to use yarn eject and it also works for development server environment along with production builds.
After installing CRACO the following config in craco.config.js worked for me:
const interpolateHtml = require('craco-interpolate-html-plugin');
module.exports = {
plugins: [
{
plugin: interpolateHtml,
// Enter the variable to be interpolated in the html file
options: {
BUILD_VERSION: require('child_process')
.execSync('git rev-parse HEAD', { cwd: __dirname })
.toString().trim(),
},
},
],
};
and in your index.html:
<meta name="build-version" content="%BUILD_VERSION%" />
Here are the lines of code to add in package.json to make it all work:
"scripts": {
"start": "craco start",
"build": "craco build"
}

problems deploying node.js application

I'm having trouble deploying node.js application to appfog, according to the instruction on appfog i made a new package.json file with the next content:
{
"name":"<my app name>",
"version":"0.0.1",
"dependencies":{
"express":""
}
}
and a new app.js file with the next content:
var app = require('express').createServer();
app.get('/', function(req, res) {
res.send('Hello from AppFog');
});
app.listen(process.env.VCAP_APP_PORT || 3000);
then i wrote the command:
$ npm install
and got the next warning:
npm WARN package.json methods#0.0.1 No README.md file found!
and when i try to push my app to appfog i get the next message:
No such file or directory - /Applications/Flip Player.app
what am i missing here? am i doing something wrong?
Thanks.
Ignore the WARN, as it's just a signal to package maintainers that they should add a Readme.
Your real bug is that your app is missing Flip Player. Somehow, you've added Flip Player to your repository, or indicated it was required with adding it.
If you just started your project, I would try blowing away your git repository and then creating a new one, this time being careful to leave Flip Player out.

Resources