Skip to content

Commit bd68902

Browse files
committed
Config: change extra_tracking to array and environment to table.
This is a cleaner way of setting the options instead of parsing a multi-line string. There are also some additional checks to ensure the examples in the configuration are valid.
1 parent d580485 commit bd68902

19 files changed

Lines changed: 141 additions & 160 deletions

File tree

data/share/matplotlib-pgfutils/pgfutils.toml

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -118,14 +118,11 @@ legend_font_size = 10.0
118118
separate_legend = false
119119

120120
# Extra library-specific file trackers to install.
121-
extra_tracking = ""
122-
123-
# Environment variables to set. This should be a multi-line value; place one or
124-
# more spaces between each subsequenct line (these spaces will be removed when
125-
# parsing the configuration). Each line should be in the format name = value,
126-
# with the value being read as a string, and leading and trailing spaces being
127-
# removed from both the name and the value.
128-
environment = ""
121+
extra_tracking = []
122+
123+
# Environment variables to set. This a table mapping variable name to value; both must
124+
# be strings.
125+
environment = {}
129126

130127

131128

doc/config.md

Lines changed: 41 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -234,50 +234,43 @@ calling `setup_figure`.
234234

235235
### Extra tracking
236236

237-
This is a comma-separated list of extra libraries to install file tracking on.
238-
See the [file tracking](file_tracking.md) documentation for more details.
237+
This is an array of strings naming extra libraries to install file tracking on. See the
238+
[file tracking](file_tracking.md) documentation for more details.
239239

240240

241241
### Environment variables
242242

243-
Environment variables to set can be specified using the multi-line option
244-
``environment``. Each line represents one environment variable in the format
245-
``name = value``:
243+
Environment variables to set can be specified using the table option `environment`. Each
244+
entry represents one environment variable:
246245

247246
```toml
248247
[pgfutils]
249-
environment = '''
250-
name1 = "value1"
251-
name2 = "value2"
252-
'''
248+
environment = {name1 = "value1", name2 = "value2"}
253249
```
254250

255-
Existing environment variables of the same name will be overwritten. This means that if
256-
you specify the same variable multiple times the last value will be used. For example,
257-
the configuration
251+
TOML requires inline tables as used in the previous example to be on a single line. If
252+
you prefer to split this over multiple lines, you can make `environment` an explicit
253+
table:
258254

259255
```toml
260-
[pgfutils]
261-
environment = '''
262-
name1 = "value1"
263-
name2 = "value2"
264-
name1 = "value3"
265-
'''
256+
[pgfutils.environment]
257+
name1 = "value1"
258+
name2 = "value2"
266259
```
267260

268-
will result in `name1` being set to `value3`. The variables are set during the call to
269-
`setup_figure()`, so any libraries that read the environment variables must be imported
270-
after this call.
261+
Existing environment variables of the same name will be overwritten. This means that
262+
environment variables given in the configuration file will override existing values, and
263+
that environment variables given in the `setup_figure` call will override values from
264+
the configuration file. The variables are set during the call to `setup_figure()`, so
265+
any libraries that read the environment variables must be imported after this call.
271266

272267
Note that the `PGFUTILS_TRACK_FILES` variable described in the [file tracking
273268
documentation](file_tracking.md) can be configured through this option, for example to
274269
output tracked files to stdout:
275270

276271
```toml
277272
[pgfutils]
278-
environment = '''
279-
PGFUTILS_TRACK_FILES = "1"
280-
'''
273+
environment = {PGFUTILS_TRACK_FILES = "1"}
281274
```
282275

283276

@@ -288,49 +281,49 @@ it is a dependency. If it is in one of the directories given under the `data` ke
288281
any subdirectory of one of these directories, then it is counted as a dependency. The
289282
top-level directory (the directory the script was run from) is always included as a data
290283
directory, so you only need to specify directories outside the top-level directory.
291-
Multiple entries must be specified on separate lines of the configuration.
284+
These paths must be given as an array of strings, each corresponding to one path.
292285

293286
```toml
294287
[paths]
295-
data = '''
296-
/data/common
297-
'''
288+
data = [
289+
'/data/common'
290+
]
298291
```
299292

300293
Note that these directories are not added to any kind of search path, so any
301294
code which uses them still has to give a complete path.
302295

303-
If you have Python code in other libraries you want to be able to import in
304-
your scripts, you can use the `pythonpath` option in the `paths` section of the
305-
configuration file to specify custom search paths for Python. This is a
306-
multi-line entry with one path per line. The paths are inserted at the start
307-
of `sys.path` when you call `setup_figure()`. They are inserted in the order
308-
given in the configuration, which means the last path in the configuration will
309-
be the first entry in `sys.path`. They are not modified or checked in any way.
310-
Relative paths will therefore be interpreted by Python as being relative to the
311-
directory it was run from, which should be the top-level directory of your
312-
project.
296+
If you have Python code in other libraries you want to be able to import in your
297+
scripts, you can use the `pythonpath` option in the `paths` section of the configuration
298+
file to specify custom search paths for Python. This is an array of strings, each
299+
corresponding to one path entry. The paths are inserted at the start of `sys.path` when
300+
you call `setup_figure()`. They are inserted in the order given in the configuration,
301+
which means the last path in the configuration will be the first entry in `sys.path`.
302+
They are not modified or checked in any way. Relative paths will therefore be
303+
interpreted by Python as being relative to the directory it was run from, which should
304+
be the top-level directory of your project.
313305

314306
```toml
315307
[paths]
316-
pythonpath = '''
317-
pythonlib/
318-
/usr/share/myotherlib
319-
'''
308+
pythonpath = [
309+
'pythonlib/',
310+
'/usr/share/myotherlib',
311+
]
320312
```
321313

322314
Python imports can also be handled by the [file tracking](file_tracking.md). If
323315
enabled, any library imported from a directory (or subdirectory) specified in
324316
the `pythonpath` option is treated as a dependency and output as part of the
325317
file tracking details. If you have other libraries which are already in the
326318
Python path which you want to be tracked as dependencies, you can add the
327-
appropriate directories to the `extra_imports` option:
319+
appropriate directories to the `extra_imports` option. As with the other path settings,
320+
this must be an array of strings, each corresponding to a single path.
328321

329322
```toml
330323
[paths]
331-
extra_imports = '''
332-
/home/username/.local/lib/
333-
'''
324+
extra_imports = [
325+
'/home/username/.local/lib/'
326+
]
334327
```
335328

336329

@@ -339,10 +332,10 @@ Matplotlib rcParams
339332

340333
Matplotlib can be customised using its [rcParams][] system (this is how pgfutils does
341334
much of its setup). If you want to override rcParams settings, you can specify them in
342-
the `rcParams` section:
335+
the `rcparams` section:
343336

344337
```toml
345-
[rcParams]
338+
[rcparams]
346339
"figure.facecolor" = "blue"
347340
"xtick.labelsize" = 8
348341
```

doc/config_defaults_pgfutils.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ legend_font_size = 10
2121
separate_legend = false
2222

2323
# Extra libraries to install file tracking on.
24-
extra_tracking = ""
24+
extra_tracking = []
2525

2626
# Environment variables to set.
27-
environment = ""
27+
environment = {}

doc/file_tracking.md

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -92,19 +92,21 @@ Extra tracking
9292
By default, tracking is only installed on standard Python functions. If you use
9393
the [netCDF4][1] library, tracking can also be enabled for files opened by it
9494
(which includes other libraries that use netCDF4, such as xarray). To enable
95-
this project-wide, set the `extra_tracking` option to `netCDF4` in your
95+
this project-wide, add the `netCDF4` option to the `extra_tracking` option in your
9696
configuration:
9797

98-
```INI
98+
```toml
9999
[pgfutils]
100-
extra_tracking = netCDF4
100+
extra_tracking = [
101+
"netCDF4"
102+
]
101103
```
102104

103105
To only enable it for a specific figure, add the option to the ``setup_figure``
104106
call:
105107

106108
```python
107-
setup_figure(width=1, height=0.4, extra_tracking="netCDF4")
109+
setup_figure(width=1, height=0.4, extra_tracking=["netCDF4"])
108110
```
109111

110112

pgfutils.py

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -350,8 +350,8 @@ class PGFUtilsConfig(TypedDict):
350350
legend_opacity: float
351351
figure_background: Color
352352
axes_background: Color
353-
extra_tracking: str
354-
environment: str
353+
extra_tracking: set[str]
354+
environment: dict[str, str]
355355
separate_legend: bool
356356

357357

@@ -410,8 +410,8 @@ def __init__(self, load_file: bool = True) -> None:
410410
legend_opacity=0.8,
411411
figure_background=parse_color("transparent"),
412412
axes_background=parse_color("white"),
413-
extra_tracking="",
414-
environment="",
413+
extra_tracking=set(),
414+
environment={},
415415
separate_legend=False,
416416
)
417417
self.post_processing = dict(fix_raster_paths=True, tikzpicture=False)
@@ -543,9 +543,23 @@ def update(self, new_settings: Mapping[str, Mapping[str, Any]]):
543543
if args == (Path,):
544544
for item in val:
545545
section[key].add(Path(item).resolve())
546+
elif args == (str,):
547+
for item in val:
548+
section[key].add(str(item))
546549
else:
547550
raise RuntimeError(f"unhandled set type {args}")
548551

552+
# For a dictionary, handle based on the type of the items.
553+
elif origin is dict:
554+
if not isinstance(val, dict):
555+
raise ConfigError(name, key, "value must be a dictionary")
556+
557+
if args == (str, str):
558+
for k, v in val.items():
559+
section[key][str(k)] = str(v)
560+
else:
561+
raise RuntimeError(f"unhandled dict type {args}")
562+
549563
# Assume a string.
550564
else:
551565
section[key] = val
@@ -713,26 +727,12 @@ def setup_figure(
713727
config.update({"pgfutils": kwargs})
714728

715729
# Set environment variables specified in the configuration.
716-
for line in config.pgfutils["environment"].splitlines():
717-
line = line.strip()
718-
if not line:
719-
continue
720-
721-
# Check the variables are formatted correctly.
722-
if "=" not in line:
723-
raise ValueError(
724-
"Environment variables should be in the form NAME=VALUE. "
725-
f"The line '{line}' does not match this."
726-
)
727-
728-
# And set them.
729-
key, value = line.split("=", 1)
730-
os.environ[key.strip()] = value.strip()
730+
os.environ.update(config.pgfutils["environment"])
731731

732732
# Install extra file trackers if desired.
733-
extra = config.pgfutils["extra_tracking"].strip()
733+
extra = config.pgfutils["extra_tracking"]
734734
if extra:
735-
_install_extra_file_trackers(extra.split(","))
735+
_install_extra_file_trackers(extra)
736736

737737
# Reset our interactive flag on each call.
738738
_interactive = False

tests/sources/environment/check_set/override.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
from pgfutils import save, setup_figure
99

10-
setup_figure()
10+
setup_figure(environment={"name2": "value3"})
1111

1212
import os
1313

@@ -18,7 +18,7 @@
1818
raise ValueError(
1919
"Incorrect value ({}) for environment variable name1".format(name1)
2020
)
21-
if name2 != "value2":
21+
if name2 != "value3":
2222
raise ValueError(
2323
"Incorrect value ({}) for environment variable name2".format(name2)
2424
)

tests/sources/environment/check_set/pgfutils.toml

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,4 @@
22
# SPDX-License-Identifier: BSD-3-Clause
33

44
[pgfutils]
5-
environment="""
6-
name1=value1
7-
name2 = value2
8-
"""
5+
environment = {name1="value1", name2="value2"}

tests/sources/environment/invalid/basic.py

Lines changed: 0 additions & 7 deletions
This file was deleted.

tests/sources/environment/invalid/pgfutils.toml

Lines changed: 0 additions & 8 deletions
This file was deleted.

tests/sources/environment/repeated/basic.py

Lines changed: 0 additions & 22 deletions
This file was deleted.

0 commit comments

Comments
 (0)