or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# Click Config File

1

2

Configuration file support for Click command-line applications through a simple decorator-based approach. This package enables developers to add configuration file capabilities to their Click applications with a single `@configuration_option()` decorator without mandatory arguments, supporting sensible defaults and proper resolution order (CLI > Environment > Config file > Default).

3

4

## Package Information

5

6

- **Package Name**: click-config-file

7

- **Package Type**: Python package (pypi)

8

- **Language**: Python

9

- **Installation**: `pip install click-config-file`

10

- **Dependencies**: click >= 6.7, configobj >= 5.0.6

11

12

## Core Imports

13

14

```python

15

import click_config_file

16

```

17

18

For typical usage:

19

20

```python

21

from click_config_file import configuration_option, configobj_provider

22

```

23

24

## Basic Usage

25

26

```python

27

import click

28

import click_config_file

29

30

@click.command()

31

@click.option('--name', default='World', help='Who to greet.')

32

@click_config_file.configuration_option()

33

def hello(name):

34

click.echo('Hello {}!'.format(name))

35

36

if __name__ == '__main__':

37

hello()

38

```

39

40

With a configuration file named `config` in the application directory:

41

42

```

43

name="Universe"

44

```

45

46

Running the command will use the configuration file value:

47

48

```bash

49

$ hello

50

Hello Universe!

51

```

52

53

Command line arguments override configuration file values:

54

55

```bash

56

$ hello --name Multiverse

57

Hello Multiverse!

58

```

59

60

## Capabilities

61

62

### Configuration Decorator

63

64

The primary decorator that adds configuration file support to Click commands.

65

66

```python { .api }

67

def configuration_option(*param_decls, **attrs):

68

"""

69

Adds configuration file support to a click application.

70

71

This creates an option of type click.Path expecting the path to a

72

configuration file. When specified, it overwrites the default values

73

for all other click arguments or options with corresponding values

74

from the configuration file.

75

76

Parameters:

77

- *param_decls: Parameter declarations (default: ('--config',))

78

- cmd_name (str, optional): Command name for configuration directory.

79

Default: ctx.info_name

80

- config_file_name (str, optional): Name of configuration file.

81

Default: 'config'

82

- implicit (bool, optional): Whether to implicitly create configuration

83

option value. Default: True

84

- provider (callable, optional): Configuration file parser.

85

Default: configobj_provider()

86

- exists (bool, optional): Whether config file must exist. Default: False

87

- file_okay (bool, optional): Whether files are allowed. Default: True

88

- dir_okay (bool, optional): Whether directories are allowed. Default: False

89

- writable (bool, optional): Whether file must be writable. Default: False

90

- readable (bool, optional): Whether file must be readable. Default: True

91

- resolve_path (bool, optional): Whether to resolve path. Default: False

92

- **attrs: All other standard click.option() arguments

93

94

Returns:

95

Decorator function for Click commands

96

97

Raises:

98

click.BadOptionUsage: If configuration file cannot be read or parsed

99

"""

100

```

101

102

### Configuration Provider

103

104

Parser for configobj configuration files with support for sections and unrepr mode.

105

106

```python { .api }

107

class configobj_provider:

108

"""

109

A parser for configobj configuration files.

110

111

Parameters:

112

- unrepr (bool, optional): Controls whether file parsed using

113

configobj's unrepr mode. Default: True

114

- section (str, optional): If set, looks for corresponding section

115

inside configuration file and returns only values from that section.

116

Default: None

117

"""

118

119

def __init__(self, unrepr=True, section=None):

120

"""Initialize the configobj provider."""

121

122

def __call__(self, file_path, cmd_name):

123

"""

124

Parse and return the configuration parameters.

125

126

Parameters:

127

- file_path (str): Path to the configuration file or file-like object

128

- cmd_name (str): Name of the click command

129

130

Returns:

131

dict: Dictionary containing the configuration parameters,

132

or empty dict if specified section doesn't exist

133

134

Raises:

135

configobj.ParseError: If configuration file has syntax errors

136

py.error.ENOENT: If configuration file doesn't exist

137

"""

138

```

139

140

## Advanced Usage

141

142

### Custom Configuration Provider

143

144

You can create custom configuration providers for different file formats:

145

146

```python

147

import json

148

import click

149

import click_config_file

150

151

def json_provider(file_path, cmd_name):

152

"""Custom provider for JSON configuration files."""

153

with open(file_path) as config_data:

154

return json.load(config_data)

155

156

@click.command()

157

@click.option('--name', default='World')

158

@click_config_file.configuration_option(provider=json_provider)

159

def hello(name):

160

click.echo('Hello {}!'.format(name))

161

```

162

163

### Section-based Configuration

164

165

For shared configuration files with command-specific sections:

166

167

```python

168

import click

169

import click_config_file

170

171

provider = click_config_file.configobj_provider(section='mycommand')

172

173

@click.command()

174

@click.option('--name', default='World')

175

@click_config_file.configuration_option(provider=provider)

176

def hello(name):

177

click.echo('Hello {}!'.format(name))

178

```

179

180

Configuration file format:

181

182

```

183

[mycommand]

184

name = "From Section"

185

186

[othercommand]

187

name = "Other Value"

188

```

189

190

### Explicit Configuration Mode

191

192

Disable implicit configuration file discovery:

193

194

```python

195

@click.command()

196

@click.option('--name', default='World')

197

@click_config_file.configuration_option(implicit=False)

198

def hello(name):

199

click.echo('Hello {}!'.format(name))

200

```

201

202

### Custom Configuration File Name and Location

203

204

```python

205

@click.command()

206

@click.option('--name', default='World')

207

@click_config_file.configuration_option(

208

cmd_name='myapp',

209

config_file_name='settings.conf'

210

)

211

def hello(name):

212

click.echo('Hello {}!'.format(name))

213

```

214

215

### Click Arguments Support

216

217

The library supports both Click options and arguments from configuration files:

218

219

```python

220

@click.command()

221

@click.argument('input_file')

222

@click.option('--output', default='output.txt')

223

@click_config_file.configuration_option()

224

def process(input_file, output):

225

"""Process files with config support for both arguments and options."""

226

click.echo(f'Processing {input_file} -> {output}')

227

```

228

229

Configuration file:

230

```

231

input_file = "data.txt"

232

output = "processed.txt"

233

```

234

235

For multi-value arguments:

236

```python

237

@click.command()

238

@click.argument('files', nargs=-1)

239

@click_config_file.configuration_option()

240

def process_multiple(files):

241

for file in files:

242

click.echo(f'Processing {file}')

243

```

244

245

Configuration file:

246

```

247

files = ["file1.txt", "file2.txt", "file3.txt"]

248

```

249

250

### File Handle Support

251

252

Configuration files can be passed as file handles instead of paths:

253

254

```python

255

@click.command()

256

@click.argument('data')

257

@click_config_file.configuration_option(type=click.File())

258

def process_with_handle(data):

259

click.echo(f'Data: {data}')

260

```

261

262

## Configuration File Formats

263

264

### Default Format (ConfigObj with unrepr)

265

266

The default provider supports ConfigObj format with unrepr mode:

267

268

```

269

# Simple key-value pairs

270

name = "World"

271

count = 42

272

enabled = True

273

274

# Lists

275

items = ["item1", "item2", "item3"]

276

277

# Nested sections

278

[database]

279

host = "localhost"

280

port = 5432

281

```

282

283

### Multi-value Options

284

285

Configuration files support Click's multi-value options:

286

287

```

288

# For options like: @click.option('--item', multiple=True)

289

item = ["value1", "value2", "value3"]

290

```

291

292

## Resolution Order

293

294

Configuration values are resolved in the following priority order:

295

296

1. **Command Line Arguments** (highest priority)

297

2. **Environment Variables**

298

3. **Configuration File**

299

4. **Default Values** (lowest priority)

300

301

This ensures command line arguments always override configuration file settings, maintaining expected CLI behavior.

302

303

## Error Handling

304

305

The library handles configuration file errors gracefully:

306

307

- **Missing files**: Silently ignored when using implicit mode, raises `py.error.ENOENT` when file specified explicitly

308

- **Parse errors**: Original `configobj.ParseError` is caught and re-raised as `click.BadOptionUsage` with descriptive error message

309

- **Invalid sections**: Returns empty dictionary for missing sections

310

- **Permission errors**: Standard file system exceptions propagate normally

311

312

### Exception Types

313

314

```python { .api }

315

# Import required for exception handling

316

import click

317

import configobj

318

319

# Exceptions that may be raised:

320

click.BadOptionUsage: # Configuration file parsing or reading errors

321

configobj.ParseError: # Configuration file syntax errors (wrapped in BadOptionUsage)

322

py.error.ENOENT: # Missing configuration file (in explicit mode)

323

```

324

325

## Complete API Reference

326

327

```python { .api }

328

# Main exports available via __all__

329

from click_config_file import configuration_option, configobj_provider

330

331

class configobj_provider:

332

"""Configuration file parser for configobj format files."""

333

334

def __init__(self, unrepr=True, section=None):

335

"""

336

Initialize configobj provider.

337

338

Parameters:

339

- unrepr (bool): Whether to use unrepr mode for evaluation. Default: True

340

- section (str, optional): Section name to extract from config. Default: None

341

"""

342

343

def __call__(self, file_path, cmd_name):

344

"""

345

Parse configuration file and return parameters.

346

347

Parameters:

348

- file_path (str or file-like): Path to config file or file handle

349

- cmd_name (str): Click command name (for context)

350

351

Returns:

352

dict: Configuration parameters, empty dict if section not found

353

354

Raises:

355

configobj.ParseError: If config file has syntax errors

356

py.error.ENOENT: If config file doesn't exist

357

"""

358

359

def configuration_option(*param_decls, **attrs):

360

"""

361

Decorator that adds configuration file support to Click commands.

362

363

Parameters:

364

- *param_decls: Parameter declarations, default: ('--config',)

365

- implicit (bool): Whether to create implicit config value. Default: True

366

- cmd_name (str, optional): Command name for config directory. Default: ctx.info_name

367

- config_file_name (str): Config file name. Default: 'config'

368

- provider (callable): Config parser function. Default: configobj_provider()

369

- **attrs: All click.option() and click.Path() parameters

370

371

Returns:

372

callable: Click decorator function

373

374

Raises:

375

click.BadOptionUsage: If config file cannot be read or parsed

376

"""

377

```