summaryrefslogtreecommitdiffstats
path: root/scribus/doc/it/scripterapi-layer.html
stat options
Period:
Authors:

Commits per author per week (path 'scribus/doc/it/scripterapi-layer.html')

AuthorW13 2026W14 2026W15 2026W16 2026Total
Total00000
408ec1af284af0ebe218832f3fab85c008'>root/ipalib/config.py
blob: e8958205dbe12e1bae1ac24351d46901a536f3e7 (plain)
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
# Authors:
#   Martin Nagy <mnagy@redhat.com>
#   Jason Gerard DeRose <jderose@redhat.com>
#
# Copyright (C) 2008  Red Hat
# see file 'COPYING' for use and warranty information
#
# 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, either version 3 of the License, or
# (at your option) any later version.
#
# 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
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""
Process-wide static configuration and environment.

The standard run-time instance of the `Env` class is initialized early in the
`ipalib` process and is then locked into a read-only state, after which no
further changes can be made to the environment throughout the remaining life
of the process.

For the per-request thread-local information, see `ipalib.request`.
"""

import urlparse
from ConfigParser import RawConfigParser, ParsingError
from types import NoneType
import os
from os import path
import sys
from ipapython.dn import DN

from base import check_name
from constants import CONFIG_SECTION
from constants import OVERRIDE_ERROR, SET_ERROR, DEL_ERROR


class Env(object):
    """
    Store and retrieve environment variables.

    First an foremost, the `Env` class provides a handy container for
    environment variables.  These variables can be both set *and* retrieved
    either as attributes *or* as dictionary items.

    For example, you can set a variable as an attribute:

    >>> env = Env()
    >>> env.attr = 'I was set as an attribute.'
    >>> env.attr
    u'I was set as an attribute.'
    >>> env['attr']  # Also retrieve as a dictionary item
    u'I was set as an attribute.'

    Or you can set a variable as a dictionary item:

    >>> env['item'] = 'I was set as a dictionary item.'
    >>> env['item']
    u'I was set as a dictionary item.'
    >>> env.item  # Also retrieve as an attribute
    u'I was set as a dictionary item.'

    The variable names must be valid lower-case Python identifiers that neither
    start nor end with an underscore.  If your variable name doesn't meet these
    criteria, a ``ValueError`` will be raised when you try to set the variable
    (compliments of the `base.check_name()` function).  For example:

    >>> env.BadName = 'Wont work as an attribute'
    Traceback (most recent call last):
      ...
    ValueError: name must match '^[a-z][_a-z0-9]*[a-z0-9]$|^[a-z]$'; got 'BadName'
    >>> env['BadName'] = 'Also wont work as a dictionary item'
    Traceback (most recent call last):
      ...
    ValueError: name must match '^[a-z][_a-z0-9]*[a-z0-9]$|^[a-z]$'; got 'BadName'

    The variable values can be ``str``, ``int``, or ``float`` instances, or the
    ``True``, ``False``, or ``None`` constants.  When the value provided is an
    ``str`` instance, some limited automatic type conversion is performed, which
    allows values of specific types to be set easily from configuration files or
    command-line options.

    So in addition to their actual values, the ``True``, ``False``, and ``None``
    constants can be specified with an ``str`` equal to what ``repr()`` would
    return.  For example:

    >>> env.true = True
    >>> env.also_true = 'True'  # Equal to repr(True)
    >>> env.true
    True
    >>> env.also_true
    True

    Note that the automatic type conversion is case sensitive.  For example:

    >>> env.not_false = 'false'  # Not equal to repr(False)!
    >>> env.not_false
    u'false'

    If an ``str`` value looks like an integer, it's automatically converted to
    the ``int`` type.

    >>> env.lucky = '7'
    >>> env.lucky
    7

    Leading and trailing white-space is automatically stripped from ``str``
    values.  For example:

    >>> env.message = '  Hello!  '  # Surrounded by double spaces
    >>> env.message
    u'Hello!'
    >>> env.number = ' 42 '  # Still converted to an int
    >>> env.number
    42
    >>> env.false = ' False '  # Still equal to repr(False)
    >>> env.false
    False

    Also, empty ``str`` instances are converted to ``None``.  For example:

    >>> env.empty = ''
    >>> env.empty is None
    True

    `Env` variables are all set-once (first-one-wins).  Once a variable has been
    set, trying to override it will raise an ``AttributeError``.  For example:

    >>> env.date = 'First'
    >>> env.date = 'Second'
    Traceback (most recent call last):
      ...
    AttributeError: cannot override Env.date value u'First' with 'Second'

    An `Env` instance can be *locked*, after which no further variables can be
    set.  Trying to set variables on a locked `Env` instance will also raise
    an ``AttributeError``.  For example:

    >>> env = Env()
    >>> env.okay = 'This will work.'
    >>> env.__lock__()
    >>> env.nope = 'This wont work!'
    Traceback (most recent call last):
      ...
    AttributeError: locked: cannot set Env.nope to 'This wont work!'

    `Env` instances also provide standard container emulation for membership
    testing, counting, and iteration.  For example:

    >>> env = Env()
    >>> 'key1' in env  # Has key1 been set?
    False
    >>> env.key1 = 'value 1'
    >>> 'key1' in env
    True
    >>> env.key2 = 'value 2'
    >>> len(env)  # How many variables have been set?
    2
    >>> list(env)  # What variables have been set?
    ['key1', 'key2']

    Lastly, in addition to all the handy container functionality, the `Env`
    class provides high-level methods for bootstraping a fresh `Env` instance
    into one containing all the run-time and configuration information needed
    by the built-in freeIPA plugins.

    These are the `Env` bootstraping methods, in the order they must be called:

        1. `Env._bootstrap()` - initialize the run-time variables and then
           merge-in variables specified on the command-line.

        2. `Env._finalize_core()` - merge-in variables from the configuration
           files and then merge-in variables from the internal defaults, after
           which at least all the standard variables will be set.  After this
           method is called, the plugins will be loaded, during which
           third-party plugins can merge-in defaults for additional variables
           they use (likely using the `Env._merge()` method).

        3. `Env._finalize()` - one last chance to merge-in variables and then
           the instance is locked.  After this method is called, no more
           environment variables can be set during the remaining life of the
           process.

    However, normally none of these three bootstraping methods are called
    directly and instead only `plugable.API.bootstrap()` is called, which itself
    takes care of correctly calling the `Env` bootstrapping methods.
    """

    __locked = False

    def __init__(self, **initialize):
        object.__setattr__(self, '_Env__d', {})
        object.__setattr__(self, '_Env__done', set())
        if initialize:
            self._merge(**initialize)

    def __lock__(self):
        """
        Prevent further changes to environment.
        """
        if self.__locked is True:
            raise StandardError(
                '%s.__lock__() already called' % self.__class__.__name__
            )
        object.__setattr__(self, '_Env__locked', True)

    def __islocked__(self):
        """
        Return ``True`` if locked.
        """
        return self.__locked

    def __setattr__(self, name, value):
        """
        Set the attribute named ``name`` to ``value``.

        This just calls `Env.__setitem__()`.
        """
        self[name] = value

    def __setitem__(self, key, value):
        """
        Set ``key`` to ``value``.
        """
        if self.__locked:
            raise AttributeError(
                SET_ERROR % (self.__class__.__name__, key, value)
            )
        check_name(key)
        if key in self.__d:
            raise AttributeError(OVERRIDE_ERROR %
                (self.__class__.__name__, key, self.__d[key], value)
            )
        assert not hasattr(self, key)
        if isinstance(value, basestring):
            value = value.strip()
            if isinstance(value, str):
                value = value.decode('utf-8')
            m = {
                'True': True,
                'False': False,
                'None': None,
                '': None,
            }
            if value in m:
                value = m[value]
            elif value.isdigit():
                value = int(value)
            elif key == 'basedn':
                value = DN(value)
        assert type(value) in (unicode, int, float, bool, NoneType, DN)
        object.__setattr__(self, key, value)
        self.__d[key] = value

    def __getitem__(self, key):
        """
        Return the value corresponding to ``key``.
        """
        return self.__d[key]

    def __delattr__(self, name):
        """
        Raise an ``AttributeError`` (deletion is never allowed).

        For example:

        >>> env = Env()
        >>> env.name = 'A value'
        >>> del env.name
        Traceback (most recent call last):
          ...
        AttributeError: locked: cannot delete Env.name
        """
        raise AttributeError(
            DEL_ERROR % (self.__class__.__name__, name)
        )

    def __contains__(self, key):
        """
        Return True if instance contains ``key``; otherwise return False.
        """
        return key in self.__d

    def __len__(self):
        """
        Return number of variables currently set.
        """
        return len(self.__d)

    def __iter__(self):
        """
        Iterate through keys in ascending order.
        """
        for key in sorted(self.__d):
            yield key

    def _merge(self, **kw):
        """
        Merge variables from ``kw`` into the environment.

        Any variables in ``kw`` that have already been set will be ignored
        (meaning this method will *not* try to override them, which would raise
        an exception).

        This method returns a ``(num_set, num_total)`` tuple containing first
        the number of variables that were actually set, and second the total
        number of variables that were provided.

        For example:

        >>> env = Env()
        >>> env._merge(one=1, two=2)
        (2, 2)
        >>> env._merge(one=1, three=3)
        (1, 2)
        >>> env._merge(one=1, two=2, three=3)
        (0, 3)