Debian Codegraph @

augeas/__init__.py

raw
1 """
2 Augeas is a library for programmatically editing configuration files.
3 Augeas parses configuration files into a tree structure, which it exposes
4 through its public API. Changes made through the API are written back to
5 the initially read files.
6
7 The transformation works very hard to preserve comments and formatting
8 details. It is controlled by *lens* definitions that describe the file
9 format and the transformation into a tree.
10 """
11
12 #
13 # Copyright (C) 2008 Nathaniel McCallum
14 # Copyright (C) 2008 Jeff Schroeder <[email protected]>
15 # Copyright (C) 2009 Red Hat, Inc.
16 #
17 # This library is free software; you can redistribute it and/or
18 # modify it under the terms of the GNU Lesser General Public
19 # License as published by the Free Software Foundation; either
20 # version 2.1 of the License, or (at your option) any later version.
21 #
22 # This library is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25 # Lesser General Public License for more details.
26 #
27 # You should have received a copy of the GNU Lesser General Public
28 # License along with this library; if not, write to the Free Software
29 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 #
31 # Author: Nathaniel McCallum <[email protected]>
32
33 from sys import version_info as _pyver
34
35 from _augeas import ffi, lib
36
37 __author__ = "Nathaniel McCallum <[email protected]>"
38 __credits__ = """Jeff Schroeder <[email protected]>
39 Harald Hoyer <[email protected]> - initial python bindings, packaging
40 Nils Philippsen <[email protected]>
41 """
42 PY3 = _pyver >= (3,)
43 AUGENC = 'utf8'
44
45 if PY3:
46 string_types = str
47 else:
48 string_types = basestring
49
50
51 def enc(st):
52 if st:
53 return st.encode(AUGENC)
54 else:
55 return b''
56
57
58 def dec(st):
59 if st:
60 return st.decode(AUGENC)
61 else:
62 return b''
63
64
65 class AugeasIOError(IOError):
66 def __init__(self, ec, fullmessage, msg, minor, details, *args):
67 self.message = fullmessage
68 super(AugeasIOError, self).__init__(fullmessage, *args)
69 self.error = ec
70 self.msg = msg
71 self.minor = minor
72 self.details = details
73
74
75 class AugeasRuntimeError(RuntimeError):
76 def __init__(self, ec, fullmessage, msg, minor, details, *args):
77 self.message = fullmessage
78 super(AugeasRuntimeError, self).__init__(fullmessage, *args)
79 self.error = ec
80 self.msg = msg
81 self.minor = minor
82 self.details = details
83
84
85 class AugeasValueError(ValueError):
86 def __init__(self, ec, fullmessage, msg, minor, details, *args):
87 self.message = fullmessage
88 super(AugeasValueError, self).__init__(fullmessage, *args)
89 self.error = ec
90 self.msg = msg
91 self.minor = minor
92 self.details = details
93
94
95 class Augeas(object):
96 """
97 Class wrapper for the Augeas library.
98 """
99 # Augeas Flags
100 NONE = 0
101 #: Keep the original file with a :samp:`.augsave` extension
102 SAVE_BACKUP = 1 << 0
103 #: Save changes into a file with extension :samp:`.augnew`, and do not
104 #: overwrite the original file. Takes precedence over :attr:`SAVE_BACKUP`
105 SAVE_NEWFILE = 1 << 1
106 #: Typecheck lenses; since it can be very expensive it is not done by
107 #: default
108 TYPE_CHECK = 1 << 2
109 #: Do not use the builtin load path for modules
110 NO_STDINC = 1 << 3
111 #: Make save a no-op process, just record what would have changed
112 SAVE_NOOP = 1 << 4
113 #: Do not load the tree from :func:`~augeas.Augeas`
114 NO_LOAD = 1 << 5
115 NO_MODL_AUTOLOAD = 1 << 6
116 #: Track the span in the input of nodes
117 ENABLE_SPAN = 1 << 7
118
119 # Augeas errors
120 AUG_NOERROR = 0
121 AUG_ENOMEM = 1
122 AUG_EINTERNAL = 2
123 AUG_EPATHX = 3
124 AUG_ENOMATCH = 4
125 AUG_EMMATCH = 5
126 AUG_ESYNTAX = 6
127 AUG_ENOLENS = 7
128 AUG_EMXFM = 8
129 AUG_ENOSPAN = 9
130 AUG_EMVDESC = 10
131 AUG_ECMDRUN = 11
132 AUG_EBADARG = 12
133 AUG_ELABEL = 13
134 AUG_ECPDESC = 14
135
136 def _optffistring(self, cffistr):
137 if cffistr == ffi.NULL:
138 return None
139 else:
140 return dec(ffi.string(cffistr))
141
142 def _raise_error(self, errorclass, errmsg, *args):
143 ec = lib.aug_error(self.__handle)
144 if ec == Augeas.AUG_ENOMEM:
145 raise MemoryError()
146 msg = self._optffistring(lib.aug_error_message(self.__handle))
147 fullmessage = (errmsg + ": " + msg) % args
148 minor = self._optffistring(lib.aug_error_minor_message(self.__handle))
149 if minor:
150 fullmessage += ": " + minor
151 details = self._optffistring(lib.aug_error_details(self.__handle))
152 if details:
153 fullmessage += ": " + details
154 raise errorclass(ec, fullmessage, msg, minor, details)
155
156 def __init__(self, root=None, loadpath=None, flags=NONE):
157 """
158 Initialize the library.
159
160 :param root: the filesystem root. If `root` is :py:obj:`None`, use the
161 value of the environment variable :envvar:`AUGEAS_ROOT`.
162 If that doesn't exist either, use :samp:`/`.
163 :type root: str or None
164
165 :param loadpath: a colon-separated list of directories that modules
166 should be searched in. This is in addition to the
167 standard load path and the directories in
168 :envvar:`AUGEAS_LENS_LIB`.
169 :type loadpath: str or None
170
171 :param flags: a combination of values of :attr:`SAVE_BACKUP`,
172 :attr:`SAVE_NEWFILE`, :attr:`TYPE_CHECK`,
173 :attr:`NO_STDINC`, :attr:`SAVE_NOOP`, :attr:`NO_LOAD`,
174 :attr:`NO_MODL_AUTOLOAD`, and :attr:`ENABLE_SPAN`.
175 :type flags: int or :attr:`NONE`
176 """
177
178 # Sanity checks
179 if not isinstance(root, string_types) and root is not None:
180 raise TypeError("root MUST be a string or None!")
181 if not isinstance(loadpath, string_types) and loadpath is not None:
182 raise TypeError("loadpath MUST be a string or None!")
183 if not isinstance(flags, int):
184 raise TypeError("flag MUST be a flag!")
185
186 root = enc(root) if root else ffi.NULL
187 loadpath = enc(loadpath) if loadpath else ffi.NULL
188
189 # Create the Augeas object
190 self.__handle = ffi.gc(lib.aug_init(root, loadpath, flags),
191 lambda x: self.close())
192 if not self.__handle:
193 raise RuntimeError("Unable to create Augeas object!")
194
195 def get(self, path):
196 """
197 Lookup the value associated with `path`.
198 It is an error if more than one node matches `path`.
199
200 :returns: the value at the path specified
201 :rtype: str
202 """
203
204 # Sanity checks
205 if not isinstance(path, string_types):
206 raise TypeError("path MUST be a string!")
207 if not self.__handle:
208 raise RuntimeError("The Augeas object has already been closed!")
209
210 # Create the char * value
211 value = ffi.new("char*[]", 1)
212
213 # Call the function and pass value by reference (char **)
214 ret = lib.aug_get(self.__handle, enc(path), value)
215 if ret < 0:
216 self._raise_error(AugeasValueError, "Augeas.get() failed")
217
218 return self._optffistring(value[0])
219
220 def label(self, path):
221 """
222 Lookup the label associated with `path`.
223 It is an error if more than one node matches `path`.
224
225 :returns: the label of the path specified
226 :rtype: str
227 """
228
229 # Sanity checks
230 if not isinstance(path, string_types):
231 raise TypeError("path MUST be a string!")
232 if not self.__handle:
233 raise RuntimeError("The Augeas object has already been closed!")
234
235 # Create the char * value
236 label = ffi.new("char*[]", 1)
237
238 # Call the function and pass value by reference (char **)
239 ret = lib.aug_label(self.__handle, enc(path), label)
240 if ret < 0:
241 self._raise_error(AugeasValueError, "Augeas.label() failed")
242
243 return self._optffistring(label[0])
244
245 def set(self, path, value):
246 """
247 Set the value associated with `path` to `value`.
248 Intermediate entries are created if they don't exist.
249 It is an error if more than one node matches `path`.
250 """
251
252 # Sanity checks
253 if not isinstance(path, string_types):
254 raise TypeError("path MUST be a string!")
255 if not isinstance(value, string_types) and value is not None:
256 raise TypeError("value MUST be a string or None!")
257 if not self.__handle:
258 raise RuntimeError("The Augeas object has already been closed!")
259
260 # Call the function
261 ret = lib.aug_set(self.__handle, enc(path), enc(value))
262 if ret != 0:
263 self._raise_error(AugeasValueError, "Augeas.set() failed")
264
265 def setm(self, base, sub, value):
266 """
267 Set the value of multiple nodes in one operation.
268 Find or create a node matching `sub` by interpreting `sub`
269 as a path expression relative to each node matching `base`.
270 `sub` may be :py:obj:`None`, in which case all the nodes matching
271 `base` will be modified.
272 """
273
274 # Sanity checks
275 if type(base) != str:
276 raise TypeError("base MUST be a string!")
277 if type(sub) != str and sub is not None:
278 raise TypeError("sub MUST be a string or None!")
279 if type(value) != str and value is not None:
280 raise TypeError("value MUST be a string or None!")
281 if not self.__handle:
282 raise RuntimeError("The Augeas object has already been closed!")
283
284 # Call the function
285 ret = lib.aug_setm(
286 self.__handle, enc(base), enc(sub), enc(value))
287 if ret < 0:
288 self._raise_error(AugeasValueError, "Augeas.setm() failed")
289 return ret
290
291 def text_store(self, lens, node, path):
292 """
293 Use the value of node `node` as a string and transform it into a tree
294 using the lens `lens` and store it in the tree at `path`, which will be
295 overwritten. `path` and `node` are path expressions.
296 """
297
298 # Sanity checks
299 if not isinstance(lens, string_types):
300 raise TypeError("lens MUST be a string!")
301 if not isinstance(node, string_types):
302 raise TypeError("node MUST be a string!")
303 if not isinstance(path, string_types):
304 raise TypeError("path MUST be a string!")
305 if not self.__handle:
306 raise RuntimeError("The Augeas object has already been closed!")
307
308 # Call the function
309 ret = lib.aug_text_store(
310 self.__handle, enc(lens), enc(node), enc(path))
311 if ret != 0:
312 self._raise_error(AugeasValueError, "Augeas.text_store() failed")
313 return ret
314
315 def text_retrieve(self, lens, node_in, path, node_out):
316 """
317 Transform the tree at `path` into a string using lens `lens` and store
318 it in the node `node_out`, assuming the tree was initially generated
319 using the value of node `node_in`. `path`, `node_in`, and `node_out`
320 are path expressions.
321 """
322
323 # Sanity checks
324 if not isinstance(lens, string_types):
325 raise TypeError("lens MUST be a string!")
326 if not isinstance(node_in, string_types):
327 raise TypeError("node_in MUST be a string!")
328 if not isinstance(path, string_types):
329 raise TypeError("path MUST be a string!")
330 if not isinstance(node_out, string_types):
331 raise TypeError("node_out MUST be a string!")
332 if not self.__handle:
333 raise RuntimeError("The Augeas object has already been closed!")
334
335 # Call the function
336 ret = lib.aug_text_retrieve(
337 self.__handle, enc(lens), enc(node_in), enc(path), enc(node_out))
338 if ret != 0:
339 self._raise_error(AugeasValueError,
340 "Augeas.text_retrieve() failed")
341 return ret
342
343 def defvar(self, name, expr):
344 """
345 Define a variable `name` whose value is the result of
346 evaluating `expr`. If a variable `name` already exists, its
347 name will be replaced with the result of evaluating `expr`.
348
349 If `expr` is :py:obj:`None`, the variable `name` will be removed if it
350 is defined.
351
352 Path variables can be used in path expressions later on by
353 prefixing them with :samp:`$`.
354 """
355
356 # Sanity checks
357 if type(name) != str:
358 raise TypeError("name MUST be a string!")
359 if type(expr) != str and expr is not None:
360 raise TypeError("expr MUST be a string or None!")
361 if not self.__handle:
362 raise RuntimeError("The Augeas object has already been closed!")
363
364 # Call the function
365 ret = lib.aug_defvar(self.__handle, enc(name), enc(expr))
366 if ret < 0:
367 self._raise_error(AugeasValueError, "Augeas.defvar() failed")
368 return ret
369
370 def defnode(self, name, expr, value):
371 """
372 Define a variable `name` whose value is the result of
373 evaluating `expr`, which must not be :py:obj:`None` and evaluate to a
374 nodeset. If a variable `name` already exists, its name will
375 be replaced with the result of evaluating `expr`.
376
377 If `expr` evaluates to an empty nodeset, a node is created,
378 equivalent to calling ``set(expr, value)`` and `name` will be the
379 nodeset containing that single node.
380 """
381
382 # Sanity checks
383 if type(name) != str:
384 raise TypeError("name MUST be a string!")
385 if type(expr) != str:
386 raise TypeError("expr MUST be a string!")
387 if type(value) != str:
388 raise TypeError("value MUST be a string!")
389 if not self.__handle:
390 raise RuntimeError("The Augeas object has already been closed!")
391
392 # Call the function
393 ret = lib.aug_defnode(
394 self.__handle, enc(name), enc(expr), enc(value), ffi.NULL)
395 if ret < 0:
396 self._raise_error(AugeasValueError, "Augeas.defnode() failed")
397 return ret
398
399 def move(self, src, dst):
400 """
401 Move the node `src` to `dst`. `src` must match exactly one node
402 in the tree. `dst` must either match exactly one node in the
403 tree, or may not exist yet. If `dst` exists already, it and all
404 its descendants are deleted before moving `src` there. If `dst`
405 does not exist yet, it and all its missing ancestors are created.
406 """
407
408 # Sanity checks
409 if not isinstance(src, string_types):
410 raise TypeError("src MUST be a string!")
411 if not isinstance(dst, string_types):
412 raise TypeError("dst MUST be a string!")
413 if not self.__handle:
414 raise RuntimeError("The Augeas object has already been closed!")
415
416 # Call the function
417 ret = lib.aug_mv(self.__handle, enc(src), enc(dst))
418 if ret != 0:
419 self._raise_error(AugeasValueError, "Augeas.move() failed")
420
421 def copy(self, src, dst):
422 """
423 Copy the node `src` to `dst`. `src` must match exactly one node
424 in the tree. `dst` must either match exactly one node in the
425 tree, or may not exist yet. If `dst` exists already, it and all
426 its descendants are deleted before copying `src` there. If `dst`
427 does not exist yet, it and all its missing ancestors are created.
428 """
429
430 # Sanity checks
431 if not isinstance(src, string_types):
432 raise TypeError("src MUST be a string!")
433 if not isinstance(dst, string_types):
434 raise TypeError("dst MUST be a string!")
435 if not self.__handle:
436 raise RuntimeError("The Augeas object has already been closed!")
437
438 # Call the function
439 ret = lib.aug_cp(self.__handle, enc(src), enc(dst))
440 if ret != 0:
441 self._raise_error(AugeasValueError, "Augeas.copy() failed")
442
443 def rename(self, src, dst):
444 """
445 Rename the label of all nodes matching `src` to `dst`.
446 """
447
448 # Sanity checks
449 if not isinstance(src, string_types):
450 raise TypeError("src MUST be a string!")
451 if not isinstance(dst, string_types):
452 raise TypeError("dst MUST be a string!")
453 if not self.__handle:
454 raise RuntimeError("The Augeas object has already been closed!")
455
456 # Call the function
457 ret = lib.aug_rename(self.__handle, enc(src), enc(dst))
458 if ret < 0:
459 self._raise_error(AugeasValueError, "Augeas.rename() failed")
460 return ret
461
462 def insert(self, path, label, before=True):
463 """
464 Create a new sibling `label` for `path` by inserting into the tree
465 just before `path` (if `before` is :py:obj:`True`) or just after `path`
466 (if `before` is :py:obj:`False`).
467
468 `path` must match exactly one existing node in the tree, and `label`
469 must be a label, i.e. not contain a :samp:`/`, :samp:`*` or end with
470 a bracketed index :samp:`[N]`.
471 """
472
473 # Sanity checks
474 if not isinstance(path, string_types):
475 raise TypeError("path MUST be a string!")
476 if not isinstance(label, string_types):
477 raise TypeError("label MUST be a string!")
478 if not self.__handle:
479 raise RuntimeError("The Augeas object has already been closed!")
480
481 # Call the function
482 ret = lib.aug_insert(self.__handle, enc(path),
483 enc(label), before and 1 or 0)
484 if ret != 0:
485 self._raise_error(AugeasValueError, "Augeas.insert() failed")
486
487 def remove(self, path):
488 """
489 Remove `path` and all its children. Returns the number of entries
490 removed. All nodes that match `path`, and their descendants, are
491 removed.
492 """
493
494 # Sanity checks
495 if not isinstance(path, string_types):
496 raise TypeError("path MUST be a string!")
497 if not self.__handle:
498 raise RuntimeError("The Augeas object has already been closed!")
499
500 # Call the function
501 return lib.aug_rm(self.__handle, enc(path))
502
503 def match(self, path):
504 """
505 Return the matches of the path expression `path`. The returned paths
506 are sufficiently qualified to make sure that they match exactly one
507 node in the current tree.
508
509 Path expressions use a very simple subset of XPath: the path `path`
510 consists of a number of segments, separated by :samp:`/`; each segment
511 can either be a :samp:`*`, matching any tree node, or a string,
512 optionally followed by an index in brackets, matching tree nodes
513 labelled with exactly that string. If no index is specified, the
514 expression matches all nodes with that label; the index can be a
515 positive number N, which matches exactly the *N*-th node with that
516 label (counting from 1), or the special expression :samp:`last()` which
517 matches the last node with the given label. All matches are done in
518 fixed positions in the tree, and nothing matches more than one path
519 segment.
520 """
521
522 # Sanity checks
523 if not isinstance(path, string_types):
524 raise TypeError("path MUST be a string!")
525 if not self.__handle:
526 raise RuntimeError("The Augeas object has already been closed!")
527
528 parray = ffi.new('char***')
529
530 ret = lib.aug_match(self.__handle, enc(path), parray)
531 if ret < 0:
532 self._raise_error(AugeasRuntimeError,
533 "Augeas.match() failed: %s", path)
534
535 # Loop through the string array
536 array = parray[0]
537 matches = []
538 for i in range(ret):
539 if array[i] != ffi.NULL:
540 # Create a python string and append it to our matches list
541 item = ffi.string(array[i])
542 matches.append(dec(item))
543 lib.free(array[i])
544 lib.free(array)
545 return matches
546
547 def span(self, path):
548 """
549 Get the span according to input file of the node associated with
550 `path`. If the node is associated with a file, a tuple of 7 elements is
551 returned: ``(filename, label_start, label_end, value_start, value_end,
552 span_start, span_end)``. If the node associated with `path` doesn't
553 belong to a file or is doesn't exists, :py:obj:`ValueError` is raised.
554
555 :rtype: tuple(str, int, int, int, int, int, int)
556 """
557
558 # Sanity checks
559 if not isinstance(path, string_types):
560 raise TypeError("path MUST be a string!")
561 if not self.__handle:
562 raise RuntimeError("The Augeas object has already been closed!")
563
564 # TODO: Rewrite this
565
566 filename = ffi.new('char **')
567 label_start = ffi.new('unsigned int *')
568 label_end = ffi.new('unsigned int *')
569 value_start = ffi.new('unsigned int *')
570 value_end = ffi.new('unsigned int *')
571 span_start = ffi.new('unsigned int *')
572 span_end = ffi.new('unsigned int *')
573
574 ret = lib.aug_span(self.__handle, enc(path), filename,
575 label_start, label_end,
576 value_start, value_end,
577 span_start, span_end)
578 if (ret < 0):
579 self._raise_error(AugeasValueError, "Augeas.span() failed")
580 fname = self._optffistring(filename[0])
581 return (fname, int(label_start[0]), int(label_end[0]),
582 int(value_start[0]), int(value_end[0]),
583 int(span_start[0]), int(span_end[0]))
584
585 def save(self):
586 """
587 Write all pending changes to disk. Only files that had any changes
588 made to them are written.
589
590 If :attr:`SAVE_NEWFILE` is set in the creation `flags`, create changed
591 files as new files with the extension :samp:`.augnew`, and leave the
592 original file unmodified.
593
594 Otherwise, if :attr:`SAVE_BACKUP` is set in the creation `flags`, move
595 the original file to a new file with extension :samp:`.augsave`.
596
597 If neither of these flags is set, overwrite the original file.
598 """
599
600 # Sanity checks
601 if not self.__handle:
602 raise RuntimeError("The Augeas object has already been closed!")
603
604 # Call the function
605 ret = lib.aug_save(self.__handle)
606 if ret != 0:
607 self._raise_error(AugeasIOError, "Augeas.save() failed")
608
609 def load(self):
610 """
611 Load files into the tree. Which files to load and what lenses to use
612 on them is specified under :samp:`/augeas/load` in the tree; each entry
613 :samp:`/augeas/load/NAME` specifies a 'transform', by having itself
614 exactly one child 'lens' and any number of children labelled 'incl' and
615 'excl'. The value of :samp:`NAME` has no meaning.
616
617 The 'lens' grandchild of :samp:`/augeas/load` specifies which lens to
618 use, and can either be the fully qualified name of a lens
619 :samp:`Module.lens` or :samp:`@Module`. The latter form means that the
620 lens from the transform marked for autoloading in MODULE should be
621 used.
622
623 The 'incl' and 'excl' grandchildren of :samp:`/augeas/load` indicate
624 which files to transform. Their value are used as glob patterns. Any
625 file that matches at least one 'incl' pattern and no 'excl' pattern is
626 transformed. The order of 'incl' and 'excl' entries is irrelevant.
627
628 When AUG_INIT is first called, it populates :samp:`/augeas/load` with
629 the transforms marked for autoloading in all the modules it finds.
630
631 Before loading any files, :func:`load` will remove everything
632 underneath :samp:`/augeas/files` and :samp:`/files`, regardless of
633 whether any entries have been modified or not.
634 """
635
636 # Sanity checks
637 if not self.__handle:
638 raise RuntimeError("The Augeas object has already been closed!")
639
640 ret = lib.aug_load(self.__handle)
641 if ret != 0:
642 self._raise_error(AugeasRuntimeError, "Augeas.load() failed")
643
644 def load_file(self, filename):
645 # Sanity checks
646 if not isinstance(filename, string_types):
647 raise TypeError("filename MUST be a string!")
648 if not self.__handle:
649 raise RuntimeError("The Augeas object has already been closed!")
650
651 ret = lib.aug_load_file(self.__handle, enc(filename))
652 if ret != 0:
653 self._raise_error(AugeasRuntimeError, "Augeas.load_file() failed")
654
655 def source(self, path):
656 # Sanity checks
657 if not isinstance(path, string_types):
658 raise TypeError("path MUST be a string!")
659 if not self.__handle:
660 raise RuntimeError("The Augeas object has already been closed!")
661
662 # Create the char * value
663 value = ffi.new("char*[]", 1)
664
665 ret = lib.aug_source(self.__handle, enc(path), value)
666 if ret != 0:
667 self._raise_error(AugeasRuntimeError, "Augeas.source() failed")
668
669 return self._optffistring(value[0])
670
671 def srun(self, out, command):
672 # Sanity checks
673 if not hasattr(out, 'write'):
674 raise TypeError("out MUST be a file!")
675 if not isinstance(command, string_types):
676 raise TypeError("path MUST be a string!")
677 if not self.__handle:
678 raise RuntimeError("The Augeas object has already been closed!")
679
680 ret = lib.aug_srun(self.__handle, out, enc(command))
681 if ret < 0:
682 self._raise_error(AugeasRuntimeError,
683 "Augeas.srun() failed (%d)", ret)
684
685 def preview(self, path):
686 # Sanity checks
687 if not isinstance(path, string_types):
688 raise TypeError("path MUST be a string!")
689 if not self.__handle:
690 raise RuntimeError("The Augeas object has already been closed!")
691
692 # Create the char * value
693 out = ffi.new("char*[]", 1)
694
695 ret = lib.aug_preview(self.__handle, enc(path), out)
696 if ret < 0:
697 self._raise_error(AugeasRuntimeError, "Augeas.preview() failed")
698 return self._optffistring(out[0])
699
700 def ns_attr(self, name, index):
701 # Sanity checks
702 if not isinstance(name, string_types):
703 raise TypeError("name MUST be a string!")
704 if not isinstance(index, int):
705 raise TypeError("index MUST be an integer!")
706 value = ffi.new("char*[]", 1)
707 label = ffi.new("char*[]", 1)
708 file_path = ffi.new("char*[]", 1)
709
710 ret = lib.aug_ns_attr(self.__handle, enc(name), index, value, label, file_path)
711 if ret < 0:
712 self._raise_error(AugeasRuntimeError, "Augeas.ns_attr() failed")
713
714 return (self._optffistring(value[0]), self._optffistring(label[0]), self._optffistring(file_path[0]) )
715
716 def ns_label(self, name, index):
717 # Sanity checks
718 if not isinstance(name, string_types):
719 raise TypeError("name MUST be a string!")
720 if not isinstance(index, int):
721 raise TypeError("index MUST be an integer!")
722
723 # Create the char * value
724 label = ffi.new("char*[]", 1)
725 labelindex = ffi.new("int*", 1)
726
727 ret = lib.aug_ns_label(self.__handle, enc(name), index, label, labelindex)
728
729 if ret < 0:
730 self._raise_error(AugeasRuntimeError, "Augeas.ns_label() failed")
731
732 return (self._optffistring(label[0]), labelindex[0] )
733
734 def ns_value(self, name, index):
735 # Sanity checks
736 if not isinstance(name, string_types):
737 raise TypeError("name MUST be a string!")
738 if not isinstance(index, int):
739 raise TypeError("index MUST be an integer!")
740
741 # Create the char * value
742 value = ffi.new("char*[]", 1)
743
744 ret = lib.aug_ns_value(self.__handle, enc(name), index, value)
745 if ret < 0:
746 self._raise_error(AugeasRuntimeError, "Augeas.ns_value() failed")
747 return self._optffistring(value[0])
748
749 def ns_count(self, name):
750 # Sanity checks
751 if not isinstance(name, string_types):
752 raise TypeError("name MUST be a string!")
753 ret = lib.aug_ns_count(self.__handle, enc(name))
754 if ret < 0:
755 self._raise_error(AugeasRuntimeError, "Augeas.ns_count() failed")
756 return ret
757
758
759 def ns_path(self, name, index):
760 # Sanity checks
761 if not isinstance(name, string_types):
762 raise TypeError("name MUST be a string!")
763 if not isinstance(index, int):
764 raise TypeError("index MUST be an integer!")
765
766 # Create the char * value
767 path = ffi.new("char*[]", 1)
768
769 ret = lib.aug_ns_path(self.__handle, enc(name), index, path)
770 if ret < 0:
771 self._raise_error(AugeasRuntimeError, "Augeas.ns_path() failed")
772 return self._optffistring(path[0])
773
774
775 def clear_transforms(self):
776 """
777 Clear all transforms beneath :samp:`/augeas/load`. If :func:`load` is
778 called right after this, there will be no files beneath :samp:`/files`.
779 """
780 self.remove("/augeas/load/*")
781
782 def add_transform(self, lens, incl, name=None, excl=()):
783 """
784 Add a transform beneath :samp:`/augeas/load`.
785
786 :param lens: the (file)name of the lens to use
787 :type lens: str
788 :param incl: one or more glob patterns for the files to transform
789 :type incl: str or list(str)
790 :param name: deprecated parameter
791 :param excl: zero or more glob patterns of files to exclude from
792 transforming
793 :type excl: str or list(str)
794 """
795
796 if name:
797 import warnings
798 warnings.warn("name is now deprecated in this function",
799 DeprecationWarning, stacklevel=2)
800 if isinstance(incl, string_types):
801 incl = [incl]
802 if isinstance(excl, string_types):
803 excl = [excl]
804
805 for i in range(len(incl)):
806 self.transform(lens, incl[i], False)
807 for i in range(len(excl)):
808 self.transform(lens, excl[i], True)
809
810 def transform(self, lens, file, excl=False):
811 """
812 Add a transform for `file` using `lens`.
813
814 `excl` specifies if this the file is to be included (:py:obj:`False`)
815 or excluded (:py:obj:`True`) from the `lens`.
816 The `lens` may be a module name or a full lens name.
817 If a module name is given, then lns will be the lens assumed.
818 """
819
820 if not isinstance(lens, string_types):
821 raise TypeError("lens MUST be a string!")
822 if not isinstance(file, string_types):
823 raise TypeError("file MUST be a string!")
824 if not isinstance(excl, bool):
825 raise TypeError("excl MUST be a boolean!")
826 if not self.__handle:
827 raise RuntimeError("The Augeas object has already been closed!")
828
829 ret = lib.aug_transform(self.__handle, enc(lens), enc(file), excl)
830 if ret != 0:
831 self._raise_error(AugeasRuntimeError, "Augeas.transform() failed")
832
833 def close(self):
834 """
835 Close this Augeas instance and free any storage associated with it.
836 After this call, this Augeas instance is invalid and can not be used
837 for any more operations.
838 """
839
840 # If we are already closed, return
841 if not self.__handle or self.__handle == ffi.NULL:
842 return
843
844 # Call the function
845 lib.aug_close(self.__handle)
846
847 # Mark the object as closed
848 self.__handle = None
849
850
851 # for backwards compatibility
852 # pylint: disable-msg=C0103
853 class augeas(Augeas):
854 """
855 Compat class, obsolete. Use class Augeas directly.
856
857 :deprecated:
858 """
859
860 def __init__(self, *p, **k):
861 import warnings
862 warnings.warn("use Augeas instead of augeas", DeprecationWarning,
863 stacklevel=2)
864 super(augeas, self).__init__(*p, **k)
865
866
867 __all__ = ['Augeas', 'augeas']