directory

  1. Tool profile
  2. Implementation approach
  3. The specific implementation
  4. conclusion
  5. The appendix

Tens of thousands of lines of code, the first line of specification. Code is not standard, colleagues two lines of tears.

I took on a project a few years back with a bunch of bugs and long, stinky code, It is said that the guy who wrote the code in the past often changed one bug and brought ten more. 🌝 The project is full of variables that don’t mean anything, functions that are not used and copied from somewhere, messy console, arbitrary blank lines, and meaningless comments…

Many programmers do not have the code specification consciousness, often feel as long as the function can be used, code specification waste time, so write the code after a period of time may not even understand what is tuo, let alone take over the colleagues.

Today I’m going to talk about how to technically implement the code specification and the code submission specification.

1. Introduction to the tool

  1. huskyGit hooks: a Git hooks tool that allows you to do things before and after Git commit. For example, you need to check if the code is normal before committing, you need to format it in a consistent way, you need to check the format of the Git commit, etc.
  2. eslint: a tool for checking Javascript code written with NodeJS, customizable rules
  3. lint-staged: a tool that allows you to code check only files changed in Git
  4. commitizen: a tool that provides interactive commands that can be used to standardize Git commit information.

So those are the four tools we’re going to use this time.

2. Implementation ideas

We can use the hooks provided by Husky:

  • Use esLint or Lint-Passage to check and format code uniformly before committing to Git.

  • When committing git, check the format of the Git commit. At the same time, use Commitizen to implement command line interaction to assist us in generating a compliant Git commit.

3. Concrete implementation

3.1 husky

Installation:

yarn add husky -D
Copy the code

In the script of package.json, add:

"scripts": {
  "prepare": "husky install"
}
Copy the code

Prepare is the lifecycle script for NPM.

When NPM install is executed, the script content husky install is automatically executed, resulting in a. Husky folder in the root directory of the current project.

The husky.sh configuration here is mainly to get the execution result of hook, and exit the process when an error occurs during the execution.

Now you can happily use Git hooks.

3.2 hook: pre – commit

Run yarn husky add. husky/pre-commit to generate the pre-commit script (manually, of course) :

#! /bin/sh
. "$(dirname "$0")/_/husky.sh"

undefined
Copy the code

Make a few changes to verify that this script is executed when git commit:

#! /bin/sh
. "$(dirname "$0")/_/husky.sh"

echo "Execute before commit"
Copy the code

Command line Git commit code:

Git add. Git commit -m "add husky config"Copy the code

You can see that the pre-commit script executes successfully and prints out the statement.

3.3 Adding ESLint checks to pre-commit

Installation:

Yarn add eslint - devCopy the code

After the installation is complete, go to

Yarn run eslint - initCopy the code

or

, / node_modules/bin/eslint - initCopy the code

After execution, the esLint configuration file.eslinttrc.js is automatically generated in the root directory.

Modify pre-commit to add ESLint format checking:

#! /bin/sh
. "$(dirname "$0")/_/husky.sh"


echo "Eslint Format validation" && ./node_modules/.bin/eslint src/*

Copy the code

As you can see, ESLint detects two errors and one Warning in the code.

Error must be fixed and can be automatically fixed using esLint –fix and git add. Add changes to git cache after fix:

#! /bin/sh
. "$(dirname "$0")/_/husky.sh"

echo "Eslint Format validation"

./node_modules/.bin/eslint src/* --fix # EsLint checks all files under SRC and fixes errors with --fix

git add . # Add esLint's fix content to git commit as well
Copy the code

Test it out:

Success!

Tip: If you are using a graphical tool such as the Github Desktop, the following error may occur

This is because we only have ESLint installed in projects, and when running on software, it is possible to have a path error. We simply need to install esLint globally:

yarn add eslint -g
Copy the code

The above ESLint check script checks all files in SRC. If it’s a new project, that’s fine. If it’s an older project, there’s a lot of change files involved.

If you don’t want to fully check every time, you can use git diff to retrieve the changed files:

Modify the pre – commit:

#! /bin/sh
. "$(dirname "$0")/_/husky.sh"

echo "Eslint Format validation"

arr=`git diff --name-only  HEAD` # View the changed file
for filepath in ${arr[@]}
do
    if [[ "$filepath" =~ ^[src/] ]]; then : Only check the format of files that have been modified under SRC
        if [ -f "$filepath" ];then Fix only existing files and skip delete files
            echo $filepath
            ./node_modules/.bin/eslint $filepath --fix
            git add $filepath
        fi
    fi
done
Copy the code

This code implements ESLint checks and fixes only for files whose SRC has changed and not been deleted.

A recommended tool, lint-Staged, can do the same thing but is much simpler to use.

“Lint-passage” (lANT.lant.package. json) :

Modify:

"lint-staged": {
    "src/*": "eslint --fix"
}
Copy the code

The pre – commit to:

#! /bin/sh
. "$(dirname "$0")/_/husky.sh"

echo "Eslint Format validation"

npx lint-staged
Copy the code

Test it out:

Success!

At this point, we have implemented the basic code specification configuration.

The detailed configuration parameters for ESLint are not expanded here, so you can explore them on the official website.

3.4 Using CommItizen specification for Git Commit

Installation:

npm install --save-dev commitizen
Copy the code

In package.json, configure:

  "scripts": {
    "commit": "cz"
  },
  "config": {
    "commitizen": {
      "path": "cz-conventional-changelog"}}Copy the code

Test it out:

Note that git commit is not available. Instead, if you use yarn Run commit or NPM run commit, there are interactive options on the command line to help you generate git commit.

See not used to English can also install Chinese package:

yarn add cz-conventional-changelog-zh
Copy the code

Commitizen can only help us generate standard Git commit. What if some teammates forget to use Yarn Run commit and write non-standard commit information directly with Git commit -m “XXX”?

Remember husky? We can verify git commit information with husky’s commit-msg hook.

3.5 hook: commit – MSG

yarn husky add .husky/commit-msg
Copy the code

Modify the commit – MSG:

#! /bin/sh
. "$(dirname "$0")/_/husky.sh"


commit_regex='^Merge.+|(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert|types)(\(.+\))? : {1, 50} '


if ! grep -iqE "$commit_regex" "The $1"; then

echo
echo "Commit message format error!!"

echo "Format: [Type]: [Summary]"

echo "Type of optional values for the Merge | feat | fix | computer | style | refactor | perf | test | build | ci | chore | revert | types"

echo "Notice the space in the middle."

echo "Git commit -m \"test: add something test\""

echo
exit 1

fi
Copy the code

Test it out:

And we’re done!

4, summarize

Canonical code can not only reduce merge conflicts, but also help improve code readability and reduce maintenance costs later.

For the team, it may be the programmer of iron code flow, the pit left by the predecessors has to be filled by later generations, the specification of the code is very necessary.

For individuals, canonical code not only reduces bugs, but also helps to better understand the features of a programming language, and growth is sometimes the accumulation of these details.

Technically, it can only play a part of the role of specification. More importantly, it is the subjective initiative of consciousness. Only by realizing the importance of code specification can the code standardization of the project be truly realized.

The appendix
  • husky
  • eslint
  • lint-staged
  • commitizen
  • Airbnb Code Specification