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