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