blob: 464419fb0d89fdf70b6c27200a5a0ebf43ee5831 [file] [log] [blame]
maruel@chromium.org5f3eee32009-09-17 00:34:30 +00001# 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.org167b9e62009-09-17 17:41:02 +000015import errno
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000016import os
bradnelson@google.com8f9c69f2009-09-17 00:48:28 +000017import stat
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000018import subprocess
19import sys
maruel@chromium.org167b9e62009-09-17 17:41:02 +000020import time
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000021import xml.dom.minidom
maruel@chromium.org167b9e62009-09-17 17:41:02 +000022import xml.parsers.expat
maruel@chromium.org5f3eee32009-09-17 00:34:30 +000023
24## Generic utils
25
26
27def ParseXML(output):
28 try:
29 return xml.dom.minidom.parseString(output)
30 except xml.parsers.expat.ExpatError:
31 return None
32
33
34def 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
42def 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
50class Error(Exception):
51 """gclient exception class."""
52 pass
53
54
55class 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
65def 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
75def FileWrite(filename, content):
76 f = open(filename, "w")
77 try:
78 f.write(content)
79 finally:
80 f.close()
81
82
83def 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
167def 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
178def 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
186 is printed to stdout. If print_stdout is true, the command's stdout
187 is also forwarded to stdout.
188
189 If a filter function is specified, it is expected to take a single
190 string argument, and it will be called with each line of the
191 subprocess's output. Each line has had the trailing newline character
192 trimmed.
193
194 If the command fails, as indicated by a nonzero exit status, gclient will
195 exit with an exit status of fail_status. If fail_status is None (the
196 default), gclient will raise an Error exception.
197 """
198
199 if print_messages:
200 print("\n________ running \'%s\' in \'%s\'"
201 % (' '.join(command), in_directory))
202
203 # *Sigh*: Windows needs shell=True, or else it won't search %PATH% for the
204 # executable, but shell=True makes subprocess on Linux fail when it's called
205 # with a list because it only tries to execute the first item in the list.
206 kid = subprocess.Popen(command, bufsize=0, cwd=in_directory,
207 shell=(sys.platform == 'win32'), stdout=subprocess.PIPE)
208
209 # Also, we need to forward stdout to prevent weird re-ordering of output.
210 # This has to be done on a per byte basis to make sure it is not buffered:
211 # normally buffering is done for each line, but if svn requests input, no
212 # end-of-line character is output after the prompt and it would not show up.
213 in_byte = kid.stdout.read(1)
214 in_line = ""
215 while in_byte:
216 if in_byte != "\r":
217 if print_stdout:
maruel@chromium.org5f3eee32009-09-17 00:34:30 +0000218 sys.stdout.write(in_byte)
219 if in_byte != "\n":
220 in_line += in_byte
221 if in_byte == "\n" and filter:
222 filter(in_line)
223 in_line = ""
224 in_byte = kid.stdout.read(1)
225 rv = kid.wait()
226
227 if rv:
228 msg = "failed to run command: %s" % " ".join(command)
229
230 if fail_status != None:
231 print >>sys.stderr, msg
232 sys.exit(fail_status)
233
234 raise Error(msg)
235
236
237def IsUsingGit(root, paths):
238 """Returns True if we're using git to manage any of our checkouts.
239 |entries| is a list of paths to check."""
240 for path in paths:
241 if os.path.exists(os.path.join(root, path, '.git')):
242 return True
243 return False