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