maruel@chromium.org | 5f3eee3 | 2009-09-17 00:34:30 +0000 | [diff] [blame] | 1 | # Copyright 2009 Google Inc. All Rights Reserved. |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | # |
| 9 | # Unless required by applicable law or agreed to in writing, software |
| 10 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
| 14 | |
maruel@chromium.org | 167b9e6 | 2009-09-17 17:41:02 +0000 | [diff] [blame] | 15 | import errno |
maruel@chromium.org | 5f3eee3 | 2009-09-17 00:34:30 +0000 | [diff] [blame] | 16 | import os |
bradnelson@google.com | 8f9c69f | 2009-09-17 00:48:28 +0000 | [diff] [blame] | 17 | import stat |
maruel@chromium.org | 5f3eee3 | 2009-09-17 00:34:30 +0000 | [diff] [blame] | 18 | import subprocess |
| 19 | import sys |
maruel@chromium.org | 167b9e6 | 2009-09-17 17:41:02 +0000 | [diff] [blame] | 20 | import time |
maruel@chromium.org | 5f3eee3 | 2009-09-17 00:34:30 +0000 | [diff] [blame] | 21 | import xml.dom.minidom |
maruel@chromium.org | 167b9e6 | 2009-09-17 17:41:02 +0000 | [diff] [blame] | 22 | import xml.parsers.expat |
maruel@chromium.org | 5f3eee3 | 2009-09-17 00:34:30 +0000 | [diff] [blame] | 23 | |
| 24 | ## Generic utils |
| 25 | |
| 26 | |
| 27 | def ParseXML(output): |
| 28 | try: |
| 29 | return xml.dom.minidom.parseString(output) |
| 30 | except xml.parsers.expat.ExpatError: |
| 31 | return None |
| 32 | |
| 33 | |
| 34 | def GetNamedNodeText(node, node_name): |
| 35 | child_nodes = node.getElementsByTagName(node_name) |
| 36 | if not child_nodes: |
| 37 | return None |
| 38 | assert len(child_nodes) == 1 and child_nodes[0].childNodes.length == 1 |
| 39 | return child_nodes[0].firstChild.nodeValue |
| 40 | |
| 41 | |
| 42 | def GetNodeNamedAttributeText(node, node_name, attribute_name): |
| 43 | child_nodes = node.getElementsByTagName(node_name) |
| 44 | if not child_nodes: |
| 45 | return None |
| 46 | assert len(child_nodes) == 1 |
| 47 | return child_nodes[0].getAttribute(attribute_name) |
| 48 | |
| 49 | |
| 50 | class Error(Exception): |
| 51 | """gclient exception class.""" |
| 52 | pass |
| 53 | |
| 54 | |
| 55 | class PrintableObject(object): |
| 56 | def __str__(self): |
| 57 | output = '' |
| 58 | for i in dir(self): |
| 59 | if i.startswith('__'): |
| 60 | continue |
| 61 | output += '%s = %s\n' % (i, str(getattr(self, i, ''))) |
| 62 | return output |
| 63 | |
| 64 | |
| 65 | def FileRead(filename): |
| 66 | content = None |
| 67 | f = open(filename, "rU") |
| 68 | try: |
| 69 | content = f.read() |
| 70 | finally: |
| 71 | f.close() |
| 72 | return content |
| 73 | |
| 74 | |
| 75 | def FileWrite(filename, content): |
| 76 | f = open(filename, "w") |
| 77 | try: |
| 78 | f.write(content) |
| 79 | finally: |
| 80 | f.close() |
| 81 | |
| 82 | |
| 83 | def RemoveDirectory(*path): |
| 84 | """Recursively removes a directory, even if it's marked read-only. |
| 85 | |
| 86 | Remove the directory located at *path, if it exists. |
| 87 | |
| 88 | shutil.rmtree() doesn't work on Windows if any of the files or directories |
| 89 | are read-only, which svn repositories and some .svn files are. We need to |
| 90 | be able to force the files to be writable (i.e., deletable) as we traverse |
| 91 | the tree. |
| 92 | |
| 93 | Even with all this, Windows still sometimes fails to delete a file, citing |
| 94 | a permission error (maybe something to do with antivirus scans or disk |
| 95 | indexing). The best suggestion any of the user forums had was to wait a |
| 96 | bit and try again, so we do that too. It's hand-waving, but sometimes it |
| 97 | works. :/ |
| 98 | |
| 99 | On POSIX systems, things are a little bit simpler. The modes of the files |
| 100 | to be deleted doesn't matter, only the modes of the directories containing |
| 101 | them are significant. As the directory tree is traversed, each directory |
| 102 | has its mode set appropriately before descending into it. This should |
| 103 | result in the entire tree being removed, with the possible exception of |
| 104 | *path itself, because nothing attempts to change the mode of its parent. |
| 105 | Doing so would be hazardous, as it's not a directory slated for removal. |
| 106 | In the ordinary case, this is not a problem: for our purposes, the user |
| 107 | will never lack write permission on *path's parent. |
| 108 | """ |
| 109 | file_path = os.path.join(*path) |
| 110 | if not os.path.exists(file_path): |
| 111 | return |
| 112 | |
| 113 | if os.path.islink(file_path) or not os.path.isdir(file_path): |
| 114 | raise Error("RemoveDirectory asked to remove non-directory %s" % file_path) |
| 115 | |
| 116 | has_win32api = False |
| 117 | if sys.platform == 'win32': |
| 118 | has_win32api = True |
| 119 | # Some people don't have the APIs installed. In that case we'll do without. |
| 120 | try: |
| 121 | win32api = __import__('win32api') |
| 122 | win32con = __import__('win32con') |
| 123 | except ImportError: |
| 124 | has_win32api = False |
| 125 | else: |
| 126 | # On POSIX systems, we need the x-bit set on the directory to access it, |
| 127 | # the r-bit to see its contents, and the w-bit to remove files from it. |
| 128 | # The actual modes of the files within the directory is irrelevant. |
| 129 | os.chmod(file_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) |
| 130 | for fn in os.listdir(file_path): |
| 131 | fullpath = os.path.join(file_path, fn) |
| 132 | |
| 133 | # If fullpath is a symbolic link that points to a directory, isdir will |
| 134 | # be True, but we don't want to descend into that as a directory, we just |
| 135 | # want to remove the link. Check islink and treat links as ordinary files |
| 136 | # would be treated regardless of what they reference. |
| 137 | if os.path.islink(fullpath) or not os.path.isdir(fullpath): |
| 138 | if sys.platform == 'win32': |
| 139 | os.chmod(fullpath, stat.S_IWRITE) |
| 140 | if has_win32api: |
| 141 | win32api.SetFileAttributes(fullpath, win32con.FILE_ATTRIBUTE_NORMAL) |
| 142 | try: |
| 143 | os.remove(fullpath) |
| 144 | except OSError, e: |
| 145 | if e.errno != errno.EACCES or sys.platform != 'win32': |
| 146 | raise |
| 147 | print 'Failed to delete %s: trying again' % fullpath |
| 148 | time.sleep(0.1) |
| 149 | os.remove(fullpath) |
| 150 | else: |
| 151 | RemoveDirectory(fullpath) |
| 152 | |
| 153 | if sys.platform == 'win32': |
| 154 | os.chmod(file_path, stat.S_IWRITE) |
| 155 | if has_win32api: |
| 156 | win32api.SetFileAttributes(file_path, win32con.FILE_ATTRIBUTE_NORMAL) |
| 157 | try: |
| 158 | os.rmdir(file_path) |
| 159 | except OSError, e: |
| 160 | if e.errno != errno.EACCES or sys.platform != 'win32': |
| 161 | raise |
| 162 | print 'Failed to remove %s: trying again' % file_path |
| 163 | time.sleep(0.1) |
| 164 | os.rmdir(file_path) |
| 165 | |
| 166 | |
| 167 | def SubprocessCall(command, in_directory, fail_status=None): |
| 168 | """Runs command, a list, in directory in_directory. |
| 169 | |
| 170 | This function wraps SubprocessCallAndFilter, but does not perform the |
| 171 | filtering functions. See that function for a more complete usage |
| 172 | description. |
| 173 | """ |
| 174 | # Call subprocess and capture nothing: |
| 175 | SubprocessCallAndFilter(command, in_directory, True, True, fail_status) |
| 176 | |
| 177 | |
| 178 | def SubprocessCallAndFilter(command, |
| 179 | in_directory, |
| 180 | print_messages, |
| 181 | print_stdout, |
| 182 | fail_status=None, filter=None): |
| 183 | """Runs command, a list, in directory in_directory. |
| 184 | |
| 185 | If print_messages is true, a message indicating what is being done |
dpranke@google.com | 22e29d4 | 2009-10-28 00:48:26 +0000 | [diff] [blame] | 186 | is printed to stdout. If print_messages is false, the message is printed |
| 187 | only if we actually need to print something else as well, so you can |
| 188 | get the context of the output. If print_messages is false and print_stdout |
| 189 | is false, no output at all is generated. |
| 190 | |
| 191 | Also, if print_stdout is true, the command's stdout is also forwarded |
| 192 | to stdout. |
maruel@chromium.org | 5f3eee3 | 2009-09-17 00:34:30 +0000 | [diff] [blame] | 193 | |
| 194 | If a filter function is specified, it is expected to take a single |
| 195 | string argument, and it will be called with each line of the |
| 196 | subprocess's output. Each line has had the trailing newline character |
| 197 | trimmed. |
| 198 | |
| 199 | If the command fails, as indicated by a nonzero exit status, gclient will |
| 200 | exit with an exit status of fail_status. If fail_status is None (the |
| 201 | default), gclient will raise an Error exception. |
| 202 | """ |
| 203 | |
| 204 | if print_messages: |
| 205 | print("\n________ running \'%s\' in \'%s\'" |
| 206 | % (' '.join(command), in_directory)) |
| 207 | |
| 208 | # *Sigh*: Windows needs shell=True, or else it won't search %PATH% for the |
| 209 | # executable, but shell=True makes subprocess on Linux fail when it's called |
| 210 | # with a list because it only tries to execute the first item in the list. |
| 211 | kid = subprocess.Popen(command, bufsize=0, cwd=in_directory, |
| 212 | shell=(sys.platform == 'win32'), stdout=subprocess.PIPE) |
| 213 | |
| 214 | # Also, we need to forward stdout to prevent weird re-ordering of output. |
| 215 | # This has to be done on a per byte basis to make sure it is not buffered: |
| 216 | # normally buffering is done for each line, but if svn requests input, no |
| 217 | # end-of-line character is output after the prompt and it would not show up. |
| 218 | in_byte = kid.stdout.read(1) |
| 219 | in_line = "" |
| 220 | while in_byte: |
| 221 | if in_byte != "\r": |
| 222 | if print_stdout: |
dpranke@google.com | 22e29d4 | 2009-10-28 00:48:26 +0000 | [diff] [blame] | 223 | if not print_messages: |
| 224 | print("\n________ running \'%s\' in \'%s\'" |
| 225 | % (' '.join(command), in_directory)) |
| 226 | print_messages = True |
dpranke@google.com | 9e890f9 | 2009-10-28 01:32:29 +0000 | [diff] [blame^] | 227 | sys.stdout.write(in_byte) |
maruel@chromium.org | 5f3eee3 | 2009-09-17 00:34:30 +0000 | [diff] [blame] | 228 | if in_byte != "\n": |
| 229 | in_line += in_byte |
| 230 | if in_byte == "\n" and filter: |
| 231 | filter(in_line) |
| 232 | in_line = "" |
| 233 | in_byte = kid.stdout.read(1) |
| 234 | rv = kid.wait() |
| 235 | |
| 236 | if rv: |
| 237 | msg = "failed to run command: %s" % " ".join(command) |
| 238 | |
| 239 | if fail_status != None: |
| 240 | print >>sys.stderr, msg |
| 241 | sys.exit(fail_status) |
| 242 | |
| 243 | raise Error(msg) |
| 244 | |
| 245 | |
| 246 | def IsUsingGit(root, paths): |
| 247 | """Returns True if we're using git to manage any of our checkouts. |
| 248 | |entries| is a list of paths to check.""" |
| 249 | for path in paths: |
| 250 | if os.path.exists(os.path.join(root, path, '.git')): |
| 251 | return True |
| 252 | return False |