gitgithookshuskycommitlint

Customise commitlint header format


I am using Husky to set my git hooks, and am trying to change to default format of the header expected by Commitlint:

type(scope?): subject

I am specifically trying to have this formatting:

:gitmoji:? [scope] subject

With :gitmoji: one of Gitmoji's emoji and being optional, with square brackets around the scope (and not optional) instead of the parentheses, and without the : to separate the type + the scope from the subject. Also I'd like the scope to have a formatting kind of like TCKT-666 (to refer a Jira's ticket, for example),

Right now, I've been trying a lot of things using the parserPreset, parserOpts, headerPattern and headerCorrespondence properties from commitlint.config.js, but I encountered several issues:


Solution

  • This should work for :gitmoji:? [scope] subject

    module.exports = {
      parserPreset: {
        parserOpts: {
          headerPattern: /^(?:(:\w+:)\s)?\[(\w+)\] (.+)/,
          headerCorrespondence: ["type", "scope", "subject"],
        },
      },
      plugins: [
        {
          rules: {
            "header-match-team-pattern": (parsed) => {
              const { type, scope, subject } = parsed;
              if (type === null && scope === null && subject === null) {
                return [
                  false,
                  "header must be in format ':gitmoji:? [scope] subject'",
                ];
              }
              return [true, ""];
            },
            "gitmoji-type-enum": (parsed, _when, expectedValue) => {
              const { type } = parsed;
              if (type && !expectedValue.includes(type)) {
                return [
                  false,
                  `type must be one of ${expectedValue}
        see https://gitmoji.dev`,
                ];
              }
              return [true, ""];
            },
          },
        },
      ],
      rules: {
        // "type-empty": [2, "never"],
        "header-match-team-pattern": [2, "always"],
        "gitmoji-type-enum": [2, "always", [":bug:", ":sparkle:"]], // custom rule defined in plugins
        // "subject-case": [2, "always", "sentence-case"],
      },
    };
    

    Looks like it's required to have a custom rule like header-match-team-pattern that makes sure that RegExp matched.