summaryrefslogtreecommitdiff
path: root/lib/spack/spack/config.py
blob: 5494adc324a680d087a3e352b0a9af80c5c3474f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
##############################################################################
# Copyright (c) 2013, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Written by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://scalability-llnl.github.io/spack
# Please also see the LICENSE file for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License (as published by
# the Free Software Foundation) version 2.1 dated February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
"""This module implements Spack's configuration file handling.

Configuration file scopes
===============================

When Spack runs, it pulls configuration data from several config
files, much like bash shells.  In Spack, there are two configuration
scopes:

 1. ``site``: Spack loads site-wide configuration options from
   ``$(prefix)/etc/spackconfig``.

 2. ``user``: Spack next loads per-user configuration options from
    ~/.spackconfig.

If user options have the same names as site options, the user options
take precedence.


Configuration file format
===============================

Configuration files are formatted using .gitconfig syntax, which is
much like Windows .INI format.  This format is implemented by Python's
ConfigParser class, and it's easy to read and versatile.

The file is divided into sections, like this ``compiler`` section::

     [compiler]
         cc = /usr/bin/gcc

In each section there are options (cc), and each option has a value
(/usr/bin/gcc).

Borrowing from git, we also allow named sections, e.g.:

     [compiler "gcc@4.7.3"]
         cc = /usr/bin/gcc

This is a compiler section, but it's for the specific compiler,
``gcc@4.7.3``.  ``gcc@4.7.3`` is the name.


Keys
===============================

Together, the section, name, and option, separated by periods, are
called a ``key``.  Keys can be used on the command line to set
configuration options explicitly (this is also borrowed from git).

For example, to change the C compiler used by gcc@4.7.3, you could do
this:

    spack config compiler.gcc@4.7.3.cc /usr/local/bin/gcc

That will create a named compiler section in the user's .spackconfig
like the one shown above.
"""
import os
import re
import inspect
import ConfigParser as cp
from collections import OrderedDict

from llnl.util.lang import memoized

import spack.error

__all__ = [
    'SpackConfigParser', 'get_config', 'SpackConfigurationError',
    'InvalidConfigurationScopeError', 'InvalidSectionNameError',
    'ReadOnlySpackConfigError', 'ConfigParserError', 'NoOptionError',
    'NoSectionError']

_named_section_re = r'([^ ]+) "([^"]+)"'

"""Names of scopes and their corresponding configuration files."""
_scopes = OrderedDict({
    'site' : os.path.join(spack.etc_path, 'spackconfig'),
    'user' : os.path.expanduser('~/.spackconfig')
})

_field_regex = r'^([\w-]*)'        \
               r'(?:\.(.*(?=.)))?' \
               r'(?:\.([\w-]+))?$'

_section_regex = r'^([\w-]*)\s*' \
                 r'\"([^"]*\)\"$'


# Cache of configs -- we memoize this for performance.
_config = {}

def get_config(scope=None, **kwargs):
    """Get a Spack configuration object, which can be used to set options.

       With no arguments, this returns a SpackConfigParser with config
       options loaded from all config files.  This is how client code
       should read Spack configuration options.

       Optionally, a scope parameter can be provided.  Valid scopes
       are ``site`` and ``user``.  If a scope is provided, only the
       options from that scope's configuration file are loaded.  The
       caller can set or unset options, then call ``write()`` on the
       config object to write it back out to the original config file.

       By default, this will cache configurations and return the last
       read version of the config file.  If the config file is
       modified and you need to refresh, call get_config with the
       refresh=True keyword argument.  This will force all files to be
       re-read.
    """
    refresh = kwargs.get('refresh', False)
    if refresh:
        _config.clear()

    if scope not in _config:
        if scope is None:
            _config[scope] = SpackConfigParser([path for path in _scopes.values()])
        elif scope not in _scopes:
            raise UnknownConfigurationScopeError(scope)
        else:
            _config[scope] = SpackConfigParser(_scopes[scope])

    return _config[scope]


def get_filename(scope):
    """Get the filename for a particular config scope."""
    if not scope in _scopes:
        raise UnknownConfigurationScopeError(scope)
    return _scopes[scope]


def _parse_key(key):
    """Return the section, name, and option the field describes.
       Values are returned in a 3-tuple.

       e.g.:
       The field name ``compiler.gcc@4.7.3.cc`` refers to the 'cc' key
       in a section that looks like this:

          [compiler "gcc@4.7.3"]
              cc = /usr/local/bin/gcc

       * The section is ``compiler``
       * The name is ``gcc@4.7.3``
       * The key is ``cc``
    """
    match = re.search(_field_regex, key)
    if match:
        return match.groups()
    else:
        raise InvalidSectionNameError(key)


def _make_section_name(section, name):
    if not name:
        return section
    return '%s "%s"' % (section, name)


def _autokey(fun):
    """Allow a function to be called with a string key like
       'compiler.gcc.cc', or with the section, name, and option
       separated. Function should take at least three args, e.g.:

           fun(self, section, name, option, [...])

       This will allow the function above to be called normally or
       with a string key, e.g.:

           fun(self, key, [...])
    """
    argspec = inspect.getargspec(fun)
    fun_nargs = len(argspec[0])

    def string_key_func(*args):
        nargs = len(args)
        if nargs == fun_nargs - 2:
            section, name, option = _parse_key(args[1])
            return fun(args[0], section, name, option, *args[2:])

        elif nargs == fun_nargs:
            return fun(*args)

        else:
            raise TypeError(
                "%s takes %d or %d args (found %d)."
                % (fun.__name__, fun_nargs - 2, fun_nargs, len(args)))
    return string_key_func



class SpackConfigParser(cp.RawConfigParser):
    """Slightly modified from Python's raw config file parser to accept
       leading whitespace and preserve comments.
    """
    # Slightly modify Python option expressions to allow leading whitespace
    OPTCRE    = re.compile(r'\s*' + cp.RawConfigParser.OPTCRE.pattern)
    OPTCRE_NV = re.compile(r'\s*' + cp.RawConfigParser.OPTCRE_NV.pattern)

    def __init__(self, file_or_files):
        cp.RawConfigParser.__init__(self, dict_type=OrderedDict)

        if isinstance(file_or_files, basestring):
            self.read([file_or_files])
            self.filename = file_or_files

        else:
            self.read(file_or_files)
            self.filename = None


    @_autokey
    def set_value(self, section, name, option, value):
        """Set the value for a key.  If the key is in a section or named
           section that does not yet exist, add that section.
        """
        sn = _make_section_name(section, name)
        if not self.has_section(sn):
            self.add_section(sn)

        # Allow valueless config options to be set like this:
        #     spack config set mirror https://foo.bar.com
        #
        # Instead of this, which parses incorrectly:
        #     spack config set mirror.https://foo.bar.com
        #
        if option is None:
            option = value
            value = None

        self.set(sn, option, value)


    @_autokey
    def get_value(self, section, name, option):
        """Get the value for a key.  Raises NoOptionError or NoSectionError if
           the key is not present."""
        sn = _make_section_name(section, name)

        try:
            if not option:
                # TODO: format this better
                return self.items(sn)

            return self.get(sn, option)

        # Wrap ConfigParser exceptions in SpackExceptions
        except cp.NoOptionError, e:  raise NoOptionError(e)
        except cp.NoSectionError, e: raise NoSectionError(e)
        except cp.Error, e:          raise ConfigParserError(e)


    @_autokey
    def has_value(self, section, name, option):
        """Return whether the configuration file has a value for a
           particular key."""
        sn = _make_section_name(section, name)
        return self.has_option(sn, option)


    def has_named_section(self, section, name):
        sn = _make_section_name(section, name)
        return self.has_section(sn)


    def remove_named_section(self, section, name):
        sn = _make_section_name(section, name)
        self.remove_section(sn)


    def get_section_names(self, sectype):
        """Get all named sections with the specified type.
           A named section looks like this:

               [compiler "gcc@4.7"]

           Names of sections are returned as a list, e.g.:

               ['gcc@4.7', 'intel@12.3', 'pgi@4.2']

           You can get items in the sections like this:
        """
        sections = []
        for secname in self.sections():
            match = re.match(_named_section_re, secname)
            if match:
                t, name = match.groups()
                if t == sectype:
                    sections.append(name)
        return sections


    def write(self, path_or_fp=None):
        """Write this configuration out to a file.

           If called with no arguments, this will write the
           configuration out to the file from which it was read.  If
           this config was read from multiple files, e.g. site
           configuration and then user configuration, write will
           simply raise an error.

           If called with a path or file object, this will write the
           configuration out to the supplied path or file object.
        """
        if path_or_fp is None:
            if not self.filename:
                raise ReadOnlySpackConfigError()
            path_or_fp = self.filename

        if isinstance(path_or_fp, basestring):
            path_or_fp = open(path_or_fp, 'w')

        self._write(path_or_fp)


    def _read(self, fp, fpname):
        """This is a copy of Python 2.7's _read() method, with support for
           continuation lines removed.
        """
        cursect = None                        # None, or a dictionary
        optname = None
        lineno = 0
        comment = 0
        e = None                              # None, or an exception
        while True:
            line = fp.readline()
            if not line:
                break
            lineno = lineno + 1
            # comment or blank line?
            if ((line.strip() == '' or line[0] in '#;') or
                (line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR")):
                self._sections["comment-%d" % comment] = line
                comment += 1
                continue
            # a section header or option header?
            else:
                # is it a section header?
                mo = self.SECTCRE.match(line)
                if mo:
                    sectname = mo.group('header')
                    if sectname in self._sections:
                        cursect = self._sections[sectname]
                    elif sectname == cp.DEFAULTSECT:
                        cursect = self._defaults
                    else:
                        cursect = self._dict()
                        cursect['__name__'] = sectname
                        self._sections[sectname] = cursect
                    # So sections can't start with a continuation line
                    optname = None
                # no section header in the file?
                elif cursect is None:
                    raise cp.MissingSectionHeaderError(fpname, lineno, line)
                # an option line?
                else:
                    mo = self._optcre.match(line)
                    if mo:
                        optname, vi, optval = mo.group('option', 'vi', 'value')
                        optname = self.optionxform(optname.rstrip())
                        # This check is fine because the OPTCRE cannot
                        # match if it would set optval to None
                        if optval is not None:
                            if vi in ('=', ':') and ';' in optval:
                                # ';' is a comment delimiter only if it follows
                                # a spacing character
                                pos = optval.find(';')
                                if pos != -1 and optval[pos-1].isspace():
                                    optval = optval[:pos]
                            optval = optval.strip()
                            # allow empty values
                            if optval == '""':
                                optval = ''
                            cursect[optname] = [optval]
                        else:
                            # valueless option handling
                            cursect[optname] = optval
                    else:
                        # a non-fatal parsing error occurred.  set up the
                        # exception but keep going. the exception will be
                        # raised at the end of the file and will contain a
                        # list of all bogus lines
                        if not e:
                            e = cp.ParsingError(fpname)
                        e.append(lineno, repr(line))
        # if any parsing errors occurred, raise an exception
        if e:
            raise e

        # join the multi-line values collected while reading
        all_sections = [self._defaults]
        all_sections.extend(self._sections.values())
        for options in all_sections:
            # skip comments
            if isinstance(options, basestring):
                continue

            for name, val in options.items():
                if isinstance(val, list):
                    options[name] = '\n'.join(val)


    def _write(self, fp):
        """Write an .ini-format representation of the configuration state.

           This is taken from the default Python 2.7 source.  It writes 4
           spaces at the beginning of lines instead of no leading space.
        """
        if self._defaults:
            fp.write("[%s]\n" % cp.DEFAULTSECT)
            for (key, value) in self._defaults.items():
                fp.write("    %s = %s\n" % (key, str(value).replace('\n', '\n\t')))
            fp.write("\n")

        for section in self._sections:
            # Handles comments and blank lines.
            if isinstance(self._sections[section], basestring):
                fp.write(self._sections[section])
                continue

            else:
                # Allow leading whitespace
                fp.write("[%s]\n" % section)
                for (key, value) in self._sections[section].items():
                    if key == "__name__":
                        continue
                    if (value is not None) or (self._optcre == self.OPTCRE):
                        key = " = ".join((key, str(value).replace('\n', '\n\t')))
                    fp.write("    %s\n" % (key))


class SpackConfigurationError(spack.error.SpackError):
    def __init__(self, *args):
        super(SpackConfigurationError, self).__init__(*args)


class InvalidConfigurationScopeError(SpackConfigurationError):
    def __init__(self, scope):
        super(InvalidConfigurationScopeError, self).__init__(
            "Invalid configuration scope: '%s'" % scope,
            "Options are: %s" % ", ".join(*_scopes.values()))


class InvalidSectionNameError(SpackConfigurationError):
    """Raised when the name for a section is invalid."""
    def __init__(self, name):
        super(InvalidSectionNameError, self).__init__(
            "Invalid section specifier: '%s'" % name)


class ReadOnlySpackConfigError(SpackConfigurationError):
    """Raised when user attempts to write to a config read from multiple files."""
    def __init__(self):
        super(ReadOnlySpackConfigError, self).__init__(
            "Can only write to a single-file SpackConfigParser")


class ConfigParserError(SpackConfigurationError):
    """Wrapper for the Python ConfigParser's errors"""
    def __init__(self, error):
        super(ConfigParserError, self).__init__(str(error))
        self.error = error


class NoOptionError(ConfigParserError):
    """Wrapper for ConfigParser NoOptionError"""
    def __init__(self, error):
        super(NoOptionError, self).__init__(error)


class NoSectionError(ConfigParserError):
    """Wrapper for ConfigParser NoOptionError"""
    def __init__(self, error):
        super(NoSectionError, self).__init__(error)