1""" 2Useful support routines (for internal use). 3 4These functions aren't really Zero Install specific; they're things we might 5wish were in the standard library. 6 7@since: 0.27 8""" 9 10# Copyright (C) 2009, Thomas Leonard 11# See the README file for details, or visit http://0install.net. 12 13fromzeroinstallimport_,logger 14importsys,os 15
17"""Search $PATH for prog. 18 If prog is an absolute path, return it unmodified. 19 @param prog: name of executable to find 20 @type prog: str 21 @return: the full path of prog, or None if not found 22 @rtype: str 23 @since: 0.27""" 24ifos.path.isabs(prog):returnprog 25ifos.name=="nt": 26prog+='.exe' 27fordinos.environ.get('PATH','/bin:/usr/bin').split(os.pathsep): 28path=os.path.join(d,prog) 29ifos.path.isfile(path): 30returnpath 31returnNone
34"""Read exactly nbytes from fd. 35 @param fd: file descriptor to read from 36 @type fd: int 37 @param nbytes: number of bytes to read 38 @type nbytes: int 39 @param null_ok: if True, it's OK to receive EOF immediately (we then return None) 40 @type null_ok: bool 41 @return: the bytes read 42 @rtype: bytes 43 @raise Exception: if we received less than nbytes of data""" 44data=b'' 45whilenbytes: 46got=os.read(fd,nbytes) 47ifnotgot: 48ifnull_okandnotdata: 49returnNone 50raiseException(_("Unexpected end-of-stream. Data so far %(data)s; expecting %(bytes)d bytes more.") 51%{'data':repr(data),'bytes':nbytes}) 52data+=got 53nbytes-=len(got) 54logger.debug(_("Message received: %r"),data) 55returndata
76"""Like shutil.rmtree, except that we also delete read-only items. 77 @param root: the root of the subtree to remove 78 @type root: str 79 @since: 0.28""" 80importshutil 81importplatform 82if(os.getcwd()+os.path.sep).startswith(root+os.path.sep): 83importwarnings 84warnings.warn("Removing tree ({tree}) containing the current directory ({cwd}) - this will not work on Windows".format(cwd=os.getcwd(),tree=root),stacklevel=2) 85 86ifos.path.isfile(root): 87os.chmod(root,0o700) 88os.remove(root) 89else: 90ifplatform.system()=='Windows': 91formain,dirs,filesinos.walk(root): 92foriinfiles+dirs: 93os.chmod(os.path.join(main,i),0o700) 94os.chmod(root,0o700) 95else: 96formain,dirs,filesinos.walk(root): 97os.chmod(main,0o700) 98shutil.rmtree(root)
101"""Raise an exception in a way that works on Python 2 and Python 3102 @type ex: BaseException"""103ifhasattr(ex,'with_traceback'):104raiseex# Python 3105exec("raise ex, None, tb",{'ex':ex,'tb':tb})# Python 2106assert0
109"""Rename 'src' to 'dst', which must be on the same filesystem.110 On POSIX systems, this operation is atomic.111 On Windows, do the best we can by deleting dst and then renaming.112 @type src: str113 @type dst: str114 @since: 1.9"""115ifos.name=="nt"andos.path.exists(dst):116os.unlink(dst)117os.rename(src,dst)
120"""Combines multiple strings into one for use as a Windows command-line argument.121 This coressponds to Windows' handling of command-line arguments as specified in: http://msdn.microsoft.com/library/17w5ykft.122 @type args: [str]123 @rtype: str124 @since: 1.11"""125def_escape(arg):126# Add leading quotation mark if there are whitespaces127importstring128contains_whitespace=any(whitespaceinargforwhitespaceinstring.whitespace)129result='"'ifcontains_whitespaceelse''130131# Split by quotation marks132parts=arg.split('"')133fori,partinenumerate(parts):134# Count slashes preceeding the quotation mark135slashes_count=len(part)-len(part.rstrip('\\'))136137result=result+part138ifi<len(parts)-1:139# Not last part140result=result+("\\"*slashes_count)# Double number of slashes141result=result+"\\"+'"'# Escaped quotation mark142elifcontains_whitespace:143# Last part if there are whitespaces144result=result+("\\"*slashes_count)# Double number of slashes145result=result+'"'# Non-escaped quotation mark146147returnresult