2013-03-17 17:06:52 -04:00
#
2013-10-27 21:59:47 +01:00
# Copyright 2006, 2013 Red Hat, Inc.
2013-03-17 17:06:52 -04:00
#
2018-04-04 14:35:41 +01:00
# This work is licensed under the GNU GPLv2 or later.
2018-03-20 15:00:02 -04:00
# See the COPYING file in the top-level directory.
2013-04-11 10:27:02 -04:00
#
2013-03-17 17:06:52 -04:00
2020-07-17 18:46:54 -04:00
import os
2013-04-13 14:34:52 -04:00
2020-07-17 18:58:00 -04:00
class DevError ( RuntimeError ) :
def __init__ ( self , msg ) :
RuntimeError . __init__ ( self , " programming error: %s " % msg )
2013-04-11 10:27:02 -04:00
def listify ( l ) :
if l is None :
return [ ]
2017-10-11 12:35:41 +01:00
elif not isinstance ( l , list ) :
2013-04-13 14:34:52 -04:00
return [ l ]
2013-04-11 10:27:02 -04:00
else :
return l
2013-04-13 14:34:52 -04:00
2013-04-12 08:26:21 -04:00
def xml_escape ( xml ) :
"""
Replaces chars ' " < > & with xml safe counterparts
"""
2019-06-09 16:39:15 -04:00
if xml :
xml = xml . replace ( " & " , " & " )
xml = xml . replace ( " ' " , " ' " )
xml = xml . replace ( " \" " , " " " )
xml = xml . replace ( " < " , " < " )
xml = xml . replace ( " > " , " > " )
2013-04-12 08:26:21 -04:00
return xml
2013-03-17 17:06:52 -04:00
2019-05-10 12:54:30 -04:00
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 )
2019-06-09 18:16:51 -04:00
2020-07-17 18:46:54 -04:00
def in_testsuite ( ) :
return " VIRTINST_TEST_SUITE " in os . environ
2020-09-05 08:29:04 -04:00
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 )
2022-08-03 10:45:18 -04:00
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