or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-validate-commit-msg

Script to validate a commit message follows the conventional changelog standard

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/validate-commit-msg@2.14.x

To install, run

npx @tessl/cli install tessl/npm-validate-commit-msg@2.14.0

0

# validate-commit-msg

1

2

validate-commit-msg is a Node.js tool that validates Git commit messages against the conventional changelog standard. It enforces commit message format requirements and can be integrated into Git hooks to automatically validate commits during development workflow.

3

4

## Package Information

5

6

- **Package Name**: validate-commit-msg

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install --save-dev validate-commit-msg` (typically installed as dev dependency for git hooks)

10

11

## Core Imports

12

13

```javascript

14

const validateMessage = require('validate-commit-msg');

15

```

16

17

For accessing configuration utilities:

18

19

```javascript

20

const { getConfig, getRcConfig, getPackageConfig, getConfigObject } = require('validate-commit-msg/lib/config');

21

const getGitFolder = require('validate-commit-msg/lib/getGitFolder');

22

```

23

24

## Basic Usage

25

26

```javascript

27

const validateMessage = require('validate-commit-msg');

28

29

// Validate a commit message programmatically

30

const isValid = validateMessage('feat(auth): add user login functionality');

31

console.log(isValid); // true

32

33

// Invalid commit message

34

const isInvalid = validateMessage('bad commit message');

35

console.log(isInvalid); // false

36

37

// Validate with auto-fix (requires source file path)

38

const result = validateMessage('FEAT: uppercase type', '.git/COMMIT_EDITMSG');

39

// Auto-fixes the type to lowercase if autoFix is enabled in config

40

```

41

42

## CLI Usage

43

44

The package provides a command-line tool for Git hooks:

45

46

```bash

47

# Install as git hook (using husky)

48

npm install --save-dev husky validate-commit-msg

49

50

# Add to package.json scripts

51

{

52

"scripts": {

53

"commitmsg": "validate-commit-msg"

54

}

55

}

56

57

# Direct CLI usage

58

validate-commit-msg "feat(scope): commit message"

59

validate-commit-msg # reads from COMMIT_EDITMSG file

60

validate-commit-msg GITGUI_EDITMSG # reads from specified git file

61

```

62

63

## Configuration

64

65

Configuration can be provided through `.vcmrc` file (JSON format) or `package.json`:

66

67

```json

68

{

69

"config": {

70

"validate-commit-msg": {

71

"types": ["feat", "fix", "docs", "style", "refactor", "test", "chore"],

72

"scope": {

73

"required": false,

74

"allowed": ["*"],

75

"validate": false,

76

"multiple": false

77

},

78

"warnOnFail": false,

79

"maxSubjectLength": 100,

80

"subjectPattern": ".+",

81

"subjectPatternErrorMsg": "subject does not match subject pattern!",

82

"helpMessage": "",

83

"autoFix": false

84

}

85

}

86

}

87

```

88

89

## Capabilities

90

91

### Message Validation

92

93

Validates commit messages against conventional changelog format.

94

95

```javascript { .api }

96

/**

97

* Validates a commit message against conventional changelog format

98

* @param {string} raw - Raw commit message text to validate

99

* @param {string} [sourceFile] - Optional path to commit message file for auto-fixing

100

* @returns {boolean} true if message is valid, false otherwise

101

*/

102

function validateMessage(raw, sourceFile);

103

```

104

105

**Validation Rules:**

106

- Message format: `<type>(<scope>): <subject>` or `<type>: <subject>`

107

- Supported types: configurable, defaults to conventional-commit-types

108

- Maximum subject length: configurable, defaults to 100 characters

109

- Scope validation: optional, configurable

110

- Subject pattern matching: configurable regex support

111

- Auto-fix capabilities: lowercase type and subject first letter

112

113

**Special Cases:**

114

- Merge commits (`Merge ...`) are automatically valid

115

- WIP commits and semver-tagged commits are ignored

116

- Fixup and squash commits are handled appropriately

117

118

### Configuration Management

119

120

Access and manage validation configuration. The configuration system supports two sources: `.vcmrc` files (JSON format) and `package.json` under the `config.validate-commit-msg` key. Configuration from `.vcmrc` takes precedence over `package.json`.

121

122

```javascript { .api }

123

/**

124

* Get merged configuration from .vcmrc and package.json

125

* @returns {object} Configuration object with validation settings

126

*/

127

function getConfig();

128

129

/**

130

* Get configuration from .vcmrc file

131

* @returns {object|null} Configuration from .vcmrc or null if not found

132

*/

133

function getRcConfig();

134

135

/**

136

* Get configuration from package.json

137

* @returns {object|null} Configuration from package.json config.validate-commit-msg or null if not found

138

*/

139

function getPackageConfig();

140

141

/**

142

* Get configuration from specified file

143

* @param {string} filename - Configuration file name to read (e.g., '.vcmrc', 'package.json')

144

* @returns {object|null} Parsed configuration object or null if not found

145

*/

146

function getConfigObject(filename);

147

```

148

149

### Git Integration

150

151

Utilities for Git repository integration.

152

153

```javascript { .api }

154

/**

155

* Locate .git folder in current directory tree

156

* @returns {string} Path to .git folder

157

* @throws {Error} If .git folder cannot be found

158

*/

159

function getGitFolder();

160

```

161

162

### Current Configuration Access

163

164

Access the currently loaded configuration object from the main validation module.

165

166

```javascript { .api }

167

const { config } = require('validate-commit-msg/lib/validateMessage');

168

169

/**

170

* Current configuration object used by the validator

171

* Contains merged settings from .vcmrc and package.json

172

* @type {object}

173

*/

174

const config;

175

```

176

177

## Configuration Schema

178

179

### Core Configuration Options

180

181

```javascript { .api }

182

/**

183

* Configuration object structure for validate-commit-msg

184

*/

185

interface ValidateCommitMsgConfig {

186

/**

187

* Allowed commit types. Can be:

188

* - Array of strings: ["feat", "fix", "docs"]

189

* - "*" for any type

190

* - Module name: "conventional-commit-types" (default)

191

*/

192

types?: string[] | "*" | string;

193

194

/** Scope validation configuration */

195

scope?: {

196

/** Whether scope is required for all commits */

197

required?: boolean;

198

/** Array of allowed scopes or "*" for any scope */

199

allowed?: string[] | "*";

200

/** Whether to validate scope names against allowed list */

201

validate?: boolean;

202

/** Whether multiple scopes are allowed (comma-separated) */

203

multiple?: boolean;

204

};

205

206

/** If true, validation errors are warnings instead of failures */

207

warnOnFail?: boolean;

208

209

/** Maximum allowed subject length (default: 100) */

210

maxSubjectLength?: number;

211

212

/** Regular expression pattern for subject validation (default: ".+") */

213

subjectPattern?: string;

214

215

/** Error message when subject doesn't match pattern */

216

subjectPatternErrorMsg?: string;

217

218

/** Custom help message shown on validation failure */

219

helpMessage?: string;

220

221

/** Enable automatic fixing of common formatting issues (requires sourceFile parameter) */

222

autoFix?: boolean;

223

}

224

```

225

226

## Error Handling

227

228

The validator provides detailed error messages for validation failures:

229

230

- Invalid format errors for malformed commit messages

231

- Type validation errors for unsupported commit types

232

- Length validation errors for overly long subjects

233

- Scope validation errors for invalid or disallowed scopes

234

- Pattern matching errors for subjects that don't match configured patterns

235

236

When `warnOnFail` is enabled, validation errors are logged as warnings but don't cause the commit to fail.

237

238

## Examples

239

240

### Basic Validation

241

242

```javascript

243

const validateMessage = require('validate-commit-msg');

244

245

// Valid messages

246

console.log(validateMessage('feat: add new feature')); // true

247

console.log(validateMessage('fix(auth): resolve login issue')); // true

248

console.log(validateMessage('docs: update README')); // true

249

250

// Invalid messages

251

console.log(validateMessage('bad message')); // false

252

console.log(validateMessage('FEAT: uppercase type')); // false (unless autoFix enabled)

253

254

// Auto-merge commits are always valid

255

console.log(validateMessage('Merge branch "feature" into main')); // true

256

257

// WIP and semver commits are ignored

258

console.log(validateMessage('WIP: work in progress')); // true

259

console.log(validateMessage('v1.2.3')); // true

260

```

261

262

### Configuration Access

263

264

```javascript

265

const { getConfig, getRcConfig, getPackageConfig, getConfigObject } = require('validate-commit-msg/lib/config');

266

267

// Get current merged configuration

268

const config = getConfig();

269

console.log('Max subject length:', config.maxSubjectLength);

270

console.log('Allowed types:', config.types);

271

272

// Check specific config sources

273

const rcConfig = getRcConfig(); // From .vcmrc

274

const pkgConfig = getPackageConfig(); // From package.json

275

276

// Read any config file

277

const customConfig = getConfigObject('my-config.json');

278

```

279

280

### Git Hook Integration

281

282

```javascript

283

// In a git hook script

284

const validateMessage = require('validate-commit-msg');

285

const getGitFolder = require('validate-commit-msg/lib/getGitFolder');

286

const fs = require('fs');

287

const path = require('path');

288

289

try {

290

const gitDir = getGitFolder();

291

const commitMsgPath = path.join(gitDir, 'COMMIT_EDITMSG');

292

const commitMsg = fs.readFileSync(commitMsgPath, 'utf8');

293

294

// Validate with auto-fix capability

295

if (!validateMessage(commitMsg, commitMsgPath)) {

296

console.error('Invalid commit message format');

297

process.exit(1);

298

}

299

} catch (error) {

300

console.error('Error reading commit message:', error.message);

301

process.exit(1);

302

}

303

```

304

305

### Advanced Configuration Example

306

307

```javascript

308

// .vcmrc configuration file

309

{

310

"types": ["feat", "fix", "docs", "style", "refactor", "test", "chore"],

311

"scope": {

312

"required": true,

313

"allowed": ["auth", "api", "ui", "core"],

314

"validate": true,

315

"multiple": false

316

},

317

"warnOnFail": false,

318

"maxSubjectLength": 72,

319

"subjectPattern": "^[a-z].*[^.]$",

320

"subjectPatternErrorMsg": "Subject must start with lowercase and not end with period",

321

"helpMessage": "Please follow the conventional commit format: <type>(<scope>): <subject>",

322

"autoFix": true

323

}

324

```