summaryrefslogtreecommitdiff
path: root/virtinst/xmlutil.py
blob: 418e7b820fef6dddd6e5d4a05ede043df5ab54d4 (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
#
# Copyright 2006, 2013 Red Hat, Inc.
#
# This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory.
#

import os


class DevError(RuntimeError):
    def __init__(self, msg):
        RuntimeError.__init__(self, "programming error: %s" % msg)


def listify(l):
    if l is None:
        return []
    elif not isinstance(l, list):
        return [l]
    else:
        return l


def xml_escape(xml):
    """
    Replaces chars ' " < > & with xml safe counterparts
    """
    if xml:
        xml = xml.replace("&", "&amp;")
        xml = xml.replace("'", "&apos;")
        xml = xml.replace("\"", "&quot;")
        xml = xml.replace("<", "&lt;")
        xml = xml.replace(">", "&gt;")
    return xml


def get_prop_path(obj, prop_path):
    """Return value of attribute identified by `prop_path`

    Look up the attribute of `obj` identified by `prop_path`
    (separated by "."). If any component along the path is missing an
    `AttributeError` is raised.

    """
    parent = obj
    pieces = prop_path.split(".")
    for piece in pieces[:-1]:
        parent = getattr(parent, piece)

    return getattr(parent, pieces[-1])


def set_prop_path(obj, prop_path, value):
    """Set value of attribute identified by `prop_path`

    Set the attribute of `obj` identified by `prop_path` (separated by
    ".") to `value`. If any component along the path is missing an
    `AttributeError` is raised.
    """
    parent = obj
    pieces = prop_path.split(".")
    for piece in pieces[:-1]:
        parent = getattr(parent, piece)

    return setattr(parent, pieces[-1], value)


def in_testsuite():
    return "VIRTINST_TEST_SUITE" in os.environ


def diff(origstr, newstr, fromfile="Original", tofile="New"):
    import difflib
    dlist = difflib.unified_diff(
            origstr.splitlines(1), newstr.splitlines(1),
            fromfile=fromfile, tofile=tofile)
    return "".join(dlist)


def unindent_device_xml(xml):
    import re
    lines = xml.splitlines()
    if not lines:
        return xml  # pragma: no cover

    ret = ""
    unindent = 0
    for c in lines[0]:
        if c != " ":
            break
        unindent += 1

    for line in lines:
        if re.match(r"^%s *<.*$" % (unindent * " "), line):
            line = line[unindent:]
        ret += line + "\n"
    return ret