0
# Configuration Management
1
2
Configuration loading and management system with hierarchical config resolution and rule inheritance. Solhint supports flexible configuration through various sources and formats, with support for rule extension and per-file configuration.
3
4
## Capabilities
5
6
### Load Config
7
8
Loads configuration from file or searches for config files using cosmiconfig.
9
10
```javascript { .api }
11
/**
12
* Loads configuration from file or searches for config files
13
* @param {string} configFile - Path to specific config file (optional)
14
* @returns {Object} Configuration object with rules and settings
15
* @throws {Error} If specified config file doesn't exist or contains invalid configuration
16
*/
17
function loadConfig(configFile);
18
```
19
20
**Usage Examples:**
21
22
```javascript
23
const { loadConfig } = require('solhint/lib/config/config-file');
24
25
// Load from default search locations
26
const config = loadConfig();
27
console.log('Rules:', config.rules);
28
console.log('Extends:', config.extends);
29
30
// Load specific config file
31
const customConfig = loadConfig('./.solhint-custom.json');
32
33
// Handle errors
34
try {
35
const config = loadConfig('./nonexistent.json');
36
} catch (error) {
37
console.error('Config loading failed:', error.message);
38
}
39
```
40
41
**Default Search Locations:**
42
- `package.json` (solhint property)
43
- `.solhint.json`
44
- `.solhintrc`
45
- `.solhintrc.json`
46
- `.solhintrc.yaml`
47
- `.solhintrc.yml`
48
- `.solhintrc.js`
49
- `solhint.config.js`
50
51
### Load Config For File
52
53
Loads configuration for a specific file with hierarchical config merging from directory structure.
54
55
```javascript { .api }
56
/**
57
* Loads configuration for a specific file with hierarchical config merging
58
* @param {string} filePath - Path to file being linted
59
* @param {string} rootDir - Root directory for config search
60
* @param {string} explicitConfigPath - Explicit config file path (optional)
61
* @returns {Object} Merged configuration object
62
*/
63
function loadConfigForFile(filePath, rootDir, explicitConfigPath);
64
```
65
66
**Usage Examples:**
67
68
```javascript
69
const { loadConfigForFile } = require('solhint/lib/config/config-file');
70
71
// Load config for specific file with hierarchy
72
const fileConfig = loadConfigForFile(
73
'./src/contracts/Token.sol',
74
process.cwd()
75
);
76
77
// With explicit config file (bypasses hierarchy)
78
const explicitConfig = loadConfigForFile(
79
'./src/contracts/Token.sol',
80
process.cwd(),
81
'./.solhint-strict.json'
82
);
83
84
// Directory hierarchy example:
85
// /project/.solhint.json (base config)
86
// /project/src/.solhint.json (overrides for src)
87
// /project/src/contracts/.solhint.json (overrides for contracts)
88
// Results in merged config with contracts config taking precedence
89
```
90
91
### Apply Extends
92
93
Applies configuration inheritance via extends property with support for built-in and external configs.
94
95
```javascript { .api }
96
/**
97
* Applies configuration inheritance via extends property
98
* @param {Object} config - Base configuration object
99
* @param {Function} getter - Function to resolve extended configs (optional)
100
* @returns {Object} Extended configuration object with merged rules
101
*/
102
function applyExtends(config, getter);
103
```
104
105
**Usage Examples:**
106
107
```javascript
108
const { applyExtends } = require('solhint/lib/config/config-file');
109
110
// Basic extends usage
111
const baseConfig = {
112
extends: 'solhint:recommended',
113
rules: {
114
'max-line-length': ['warn', 120] // Override recommended setting
115
}
116
};
117
118
const extendedConfig = applyExtends(baseConfig);
119
console.log('Final rules:', extendedConfig.rules);
120
121
// Multiple extends
122
const multiConfig = {
123
extends: ['solhint:recommended', 'solhint:all'],
124
rules: {
125
'no-console': 'off' // Disable specific rule
126
}
127
};
128
129
const finalConfig = applyExtends(multiConfig);
130
131
// Custom getter for external configs
132
const customGetter = (path) => {
133
if (path === 'my-custom-config') {
134
return require('./my-config.js');
135
}
136
return require(`solhint-config-${path}`);
137
};
138
139
const customConfig = applyExtends(
140
{ extends: 'my-custom-config' },
141
customGetter
142
);
143
```
144
145
**Built-in Configurations:**
146
- `solhint:recommended` - Recommended rules for most projects
147
- `solhint:all` - All available rules enabled
148
149
### Config Getter
150
151
Resolves and loads configuration from various sources including built-in configs, external packages, and absolute paths.
152
153
```javascript { .api }
154
/**
155
* Resolves and loads configuration from various sources
156
* @param {string} path - Path or identifier to configuration
157
* @returns {Object} Configuration object
158
* @throws {ConfigMissingError} If configuration cannot be found
159
*/
160
function configGetter(path);
161
```
162
163
**Usage Examples:**
164
165
```javascript
166
const { configGetter } = require('solhint/lib/config/config-file');
167
168
// Load built-in config
169
const recommended = configGetter('solhint:recommended');
170
171
// Load external package config
172
const externalConfig = configGetter('strict'); // Loads solhint-config-strict
173
174
// Load absolute path config
175
const absoluteConfig = configGetter('/path/to/config.js');
176
```
177
178
### Validate Config
179
180
Validates configuration object against schema to ensure proper structure and rule definitions.
181
182
```javascript { .api }
183
/**
184
* Validates configuration object against schema
185
* @param {Object} config - Configuration object to validate
186
* @throws {ValidationError} If configuration is invalid
187
*/
188
function validate(config);
189
```
190
191
**Usage Examples:**
192
193
```javascript
194
const { validate } = require('solhint/lib/config/config-validator');
195
196
const config = {
197
rules: {
198
'func-visibility': 'error',
199
'max-line-length': ['warn', 120],
200
'invalid-rule': 'error' // This will cause validation error
201
}
202
};
203
204
try {
205
validate(config);
206
console.log('Configuration is valid');
207
} catch (error) {
208
console.error('Validation failed:', error.message);
209
}
210
```
211
212
## Configuration File Formats
213
214
### JSON Configuration
215
216
```json
217
{
218
"extends": "solhint:recommended",
219
"rules": {
220
"compiler-version": ["error", "^0.8.0"],
221
"func-visibility": "error",
222
"max-line-length": ["warn", 120]
223
},
224
"excludedFiles": ["contracts/test/**", "contracts/mocks/**"],
225
"plugins": ["prettier"]
226
}
227
```
228
229
### JavaScript Configuration
230
231
```javascript
232
module.exports = {
233
extends: 'solhint:recommended',
234
rules: {
235
'compiler-version': ['error', '^0.8.0'],
236
'func-visibility': 'error',
237
'max-line-length': ['warn', 120]
238
},
239
excludedFiles: ['contracts/test/**', 'contracts/mocks/**']
240
};
241
```
242
243
### Package.json Configuration
244
245
```json
246
{
247
"name": "my-project",
248
"solhint": {
249
"extends": "solhint:recommended",
250
"rules": {
251
"func-visibility": "error"
252
}
253
}
254
}
255
```
256
257
## Configuration Properties
258
259
```javascript { .api }
260
interface ConfigObject {
261
rules?: { [ruleId: string]: string | [string, ...any[]] };
262
extends?: string | string[];
263
excludedFiles?: string[];
264
plugins?: string[];
265
cache?: boolean;
266
cacheLocation?: string;
267
}
268
```
269
270
### Rules Configuration
271
272
Rules can be configured with different severity levels and options:
273
274
```javascript
275
{
276
"rules": {
277
"func-visibility": "error", // Simple severity
278
"max-line-length": ["warn", 120], // Severity with options
279
"compiler-version": ["error", "^0.8.0"], // Severity with version constraint
280
"no-console": "off" // Disabled rule
281
}
282
}
283
```
284
285
**Severity Levels:**
286
- `"error"` - Causes linting to fail with exit code 1
287
- `"warn"` - Issues warnings but doesn't fail linting
288
- `"off"` or `false` - Disables the rule completely
289
290
### File Exclusions
291
292
```javascript
293
{
294
"excludedFiles": [
295
"contracts/test/**", // Exclude test files
296
"contracts/mocks/**", // Exclude mock contracts
297
"node_modules/**", // Exclude dependencies
298
"**/*.temp.sol" // Exclude temporary files
299
]
300
}
301
```
302
303
### Plugin Configuration
304
305
```javascript
306
{
307
"plugins": ["prettier", "security"],
308
"rules": {
309
"prettier/prettier": "error",
310
"security/no-hardcoded-secrets": "warn"
311
}
312
}
313
```
314
315
## Hierarchical Configuration
316
317
Configuration files are searched and merged from root directory to file directory:
318
319
1. `/project/.solhint.json` (base configuration)
320
2. `/project/src/.solhint.json` (src-specific overrides)
321
3. `/project/src/contracts/.solhint.json` (contract-specific overrides)
322
323
Later configurations override earlier ones, allowing for fine-grained control.
324
325
## Comment Directives
326
327
Inline configuration using comment directives:
328
329
```solidity
330
// solhint-disable-next-line func-visibility
331
function test() {}
332
333
// solhint-disable max-line-length
334
function veryLongFunctionNameThatExceedsMaxLineLength() public pure returns (uint256) {}
335
// solhint-enable max-line-length
336
337
/* solhint-disable */
338
contract UnlintedContract {
339
// No rules applied here
340
}
341
/* solhint-enable */
342
```
343
344
**Available Directives:**
345
- `solhint-disable` - Disable rules from this point
346
- `solhint-enable` - Re-enable rules from this point
347
- `solhint-disable-next-line` - Disable rules for next line only
348
- `solhint-disable-line` - Disable rules for current line
349
350
## Error Handling
351
352
```javascript
353
const { ConfigMissingError } = require('solhint/lib/common/errors');
354
355
try {
356
const config = loadConfig('./missing-config.json');
357
} catch (error) {
358
if (error instanceof ConfigMissingError) {
359
console.log('Config file not found, using defaults');
360
} else {
361
console.error('Config loading failed:', error.message);
362
}
363
}
364
```