Mercurial > hg > fetch
annotate fetch.py @ 23:12ad9ab11860
stubbing
| author | Jeff Hammel <jhammel@mozilla.com> |
|---|---|
| date | Wed, 09 Nov 2011 20:21:14 -0800 |
| parents | 0706968f01bb |
| children | b1f65f3bd1bc |
| rev | line source |
|---|---|
| 0 | 1 #!/usr/bin/env python |
| 2 | |
| 3 """ | |
| 4 fetch stuff from the interwebs | |
| 5 """ | |
| 6 | |
| 7 import os | |
| 23 | 8 import shutil |
| 0 | 9 import sys |
| 10 import optparse | |
| 11 | |
|
8
cf00d46b1bfb
pretend like we have a pluggable system to start debugging it
Jeff Hammel <jhammel@mozilla.com>
parents:
7
diff
changeset
|
12 __all__ = ['Fetcher', 'Fetch', 'main'] |
|
cf00d46b1bfb
pretend like we have a pluggable system to start debugging it
Jeff Hammel <jhammel@mozilla.com>
parents:
7
diff
changeset
|
13 |
|
cf00d46b1bfb
pretend like we have a pluggable system to start debugging it
Jeff Hammel <jhammel@mozilla.com>
parents:
7
diff
changeset
|
14 def which(executable, path=os.environ['PATH']): |
| 15 | 15 """python equivalent of which; should really be in the stdlib""" |
| 16 dirs = path.split(os.pathsep) | |
| 17 for dir in dirs: | |
| 18 if os.path.isfile(os.path.join(dir, executable)): | |
| 19 return os.path.join(dir, executable) | |
| 7 | 20 |
| 0 | 21 class Fetcher(object): |
| 15 | 22 """abstract base class for resource fetchers""" |
| 0 | 23 |
| 15 | 24 @classmethod |
| 25 def match(cls, _type): | |
| 26 return _type == cls.type | |
| 0 | 27 |
| 23 | 28 def __init__(self, url, clobber=True): |
| 17 | 29 self.subpath = None |
| 30 if '#' in url: | |
| 31 url, self.subpath = url.rsplit('#') | |
| 15 | 32 self.url = url |
| 23 | 33 self.clobber = clobber |
| 0 | 34 |
| 15 | 35 def __call__(self, dest): |
| 17 | 36 raise NotImplementedError("Should be called by implementing class") |
| 37 | |
| 38 @classmethod | |
| 39 def doc(cls): | |
| 40 """return docstring for the instance""" | |
| 41 retval = getattr(cls, '__doc__', '').strip() | |
| 42 return ' '.join(retval.split()) | |
| 0 | 43 |
| 7 | 44 ### standard dispatchers - always available |
| 0 | 45 |
| 7 | 46 import tarfile |
| 0 | 47 import urllib2 |
| 7 | 48 from StringIO import StringIO |
| 0 | 49 |
| 5 | 50 class FileFetcher(Fetcher): |
| 15 | 51 """fetch a single file""" |
| 0 | 52 |
| 15 | 53 type = 'file' |
| 0 | 54 |
| 15 | 55 @classmethod |
| 56 def download(cls, url): | |
| 57 return urllib2.urlopen(url).read() | |
| 0 | 58 |
| 15 | 59 def __call__(self, dest): |
| 60 if os.path.isdir(dest): | |
| 61 filename = self.url.rsplit('/', 1)[-1] | |
| 62 dest = os.path.join(dest, filename) | |
| 63 f = file(dest, 'w') | |
| 64 f.write(self.download(self.url)) | |
| 65 f.close() | |
| 0 | 66 |
|
6
86f6f99e421b
add types for unimplemented dispatchers
Jeff Hammel <jhammel@mozilla.com>
parents:
5
diff
changeset
|
67 |
| 5 | 68 class TarballFetcher(FileFetcher): |
| 15 | 69 """fetch and extract a tarball""" |
| 0 | 70 |
| 15 | 71 type = 'tar' |
| 0 | 72 |
| 15 | 73 def __call__(self, dest): |
| 74 assert os.path.isdir(dest) | |
| 17 | 75 if self.subpath: |
| 76 raise NotImplementedError("should extract only a subpath of a tarball but I haven't finished it yet") | |
| 15 | 77 buffer = StringIO() |
| 78 buffer.write(self.download(self.url)) | |
| 79 buffer.seek(0) | |
| 80 tf = tarfile.open(mode='r', fileobj=buffer) | |
| 81 tf.extract(dest) | |
| 7 | 82 |
|
8
cf00d46b1bfb
pretend like we have a pluggable system to start debugging it
Jeff Hammel <jhammel@mozilla.com>
parents:
7
diff
changeset
|
83 fetchers = [FileFetcher, TarballFetcher] |
|
cf00d46b1bfb
pretend like we have a pluggable system to start debugging it
Jeff Hammel <jhammel@mozilla.com>
parents:
7
diff
changeset
|
84 |
|
cf00d46b1bfb
pretend like we have a pluggable system to start debugging it
Jeff Hammel <jhammel@mozilla.com>
parents:
7
diff
changeset
|
85 ### VCS fetchers using executable |
|
cf00d46b1bfb
pretend like we have a pluggable system to start debugging it
Jeff Hammel <jhammel@mozilla.com>
parents:
7
diff
changeset
|
86 |
|
11
726c3d288733
* add convenience import in __init__
Jeff Hammel <jhammel@mozilla.com>
parents:
10
diff
changeset
|
87 import subprocess |
| 19 | 88 try: |
| 89 from subprocess import check_call as call | |
| 90 except ImportErorr: | |
| 91 raise # we need check_call, kinda | |
|
11
726c3d288733
* add convenience import in __init__
Jeff Hammel <jhammel@mozilla.com>
parents:
10
diff
changeset
|
92 |
| 17 | 93 class VCSFetcher(Fetcher): |
| 94 def __init__(self, url, export=True): | |
| 95 """ | |
| 96 - export : whether to strip the versioning information | |
| 97 """ | |
| 98 Fetcher.__init__(self, url) | |
| 99 self.export = export | |
| 100 | |
|
8
cf00d46b1bfb
pretend like we have a pluggable system to start debugging it
Jeff Hammel <jhammel@mozilla.com>
parents:
7
diff
changeset
|
101 if which('hg'): |
|
cf00d46b1bfb
pretend like we have a pluggable system to start debugging it
Jeff Hammel <jhammel@mozilla.com>
parents:
7
diff
changeset
|
102 |
| 17 | 103 class HgFetcher(VCSFetcher): |
| 15 | 104 """checkout a mercurial repository""" |
| 105 type = 'hg' | |
| 0 | 106 |
| 19 | 107 def __init__(self, url, export=True): |
| 108 VCSFetcher.__init__(self, url, export=True) | |
| 109 self.hg = which('hg') | |
| 110 | |
| 15 | 111 def __call__(self, dest): |
| 23 | 112 if os.path.exists(dest): |
| 15 | 113 assert os.path.isdir(dest) and os.path.exists(os.path.join(dest, '.hg')) |
| 19 | 114 call([self.hg, 'pull', self.url], cwd=dest) |
| 115 call([self.hg, 'update'], cwd=dest) | |
| 116 else: | |
| 23 | 117 if not os.path.exists(dest): |
| 118 os.mkdirs(dest) | |
| 119 call([self.hg, 'clone', self.url, dest]) | |
|
11
726c3d288733
* add convenience import in __init__
Jeff Hammel <jhammel@mozilla.com>
parents:
10
diff
changeset
|
120 |
| 15 | 121 fetchers.append(HgFetcher) |
|
6
86f6f99e421b
add types for unimplemented dispatchers
Jeff Hammel <jhammel@mozilla.com>
parents:
5
diff
changeset
|
122 |
| 15 | 123 if which('git'): |
| 17 | 124 |
| 15 | 125 class GitFetcher(Fetcher): |
| 126 """checkout a git repository""" | |
| 127 type = 'git' | |
|
8
cf00d46b1bfb
pretend like we have a pluggable system to start debugging it
Jeff Hammel <jhammel@mozilla.com>
parents:
7
diff
changeset
|
128 |
| 20 | 129 def __init__(self, url, export=True): |
| 130 VCSFetcher.__init__(self, url, export=True) | |
| 23 | 131 self.git = which('git') |
| 132 | |
| 133 def __call__(self, url | |
| 20 | 134 |
| 135 fetchers.append(GitFetcher) | |
| 17 | 136 |
| 16 | 137 __all__ += [i.__name__ for i in fetchers] |
|
8
cf00d46b1bfb
pretend like we have a pluggable system to start debugging it
Jeff Hammel <jhammel@mozilla.com>
parents:
7
diff
changeset
|
138 |
| 0 | 139 class Fetch(object): |
| 140 | |
| 21 | 141 def __init__(self, fetchers=fetchers[:], relative_to=None, strict=True): |
| 15 | 142 self.fetchers = fetchers |
| 143 self.relative_to = relative_to | |
| 144 self.strict = strict | |
| 0 | 145 |
| 15 | 146 def fetcher(self, _type): |
| 147 """find the fetcher for the appropriate type""" | |
| 148 for fetcher in fetchers: | |
| 149 if fetcher.match(_type): | |
| 150 return fetcher | |
| 0 | 151 |
| 15 | 152 def __call__(self, url, destination, type, **options): |
| 153 fetcher = self.fetcher(type) | |
| 154 assert fetcher is not None, "No fetcher found for type '%s'" % type | |
| 155 fetcher = fetcher(url, **options) | |
| 156 fetcher(destination) | |
| 2 | 157 |
| 15 | 158 def fetch(self, *items): |
| 2 | 159 |
| 15 | 160 if self.strict: |
| 161 # ensure all the required fetchers are available | |
| 162 types = set([i['type'] for i in items]) | |
| 163 assert not [i for i in types | |
| 164 if [True for fetcher in fetchers if fetcher.match(i)]] | |
| 4 | 165 |
| 15 | 166 for item in items: |
| 4 | 167 |
| 15 | 168 # fix up relative paths |
| 169 dest = item['dest'] | |
| 170 if not os.path.isabs(dest): | |
| 171 relative_to = self.relative_to or os.path.dirname(os.path.abspath(item['manifest'])) | |
| 172 dest = os.path.join(relative_to, dest) | |
| 4 | 173 |
| 15 | 174 # fetch the items |
| 175 self(item['url'], destination=dest, type=item['type'], **item['options']) | |
| 0 | 176 |
| 21 | 177 |
| 0 | 178 format_string = "[URL] [destination] [type] <options>" |
| 179 def read_manifests(*manifests): | |
| 15 | 180 """ |
| 181 read some manifests and return the items | |
| 182 | |
| 183 Format: | |
| 184 %s | |
| 185 """ % format_string | |
| 0 | 186 |
| 15 | 187 # sanity check |
| 188 assert not [i for i in manifests if not os.path.exists(i)] | |
| 0 | 189 |
| 15 | 190 retval = [] |
| 0 | 191 |
| 15 | 192 for manifest in manifests: |
| 193 for line in file(i).readlines(): | |
| 194 line = line.strip() | |
| 195 if line.startswith('#') or not line: | |
| 196 continue | |
| 197 line = line.split() | |
| 198 if len(line) not in (3,4): | |
| 199 raise Exception("Format should be: %s; line %s" % (format_string, line)) | |
| 200 options = {} | |
| 201 if len(line) == 4: | |
| 202 option_string = line.pop().rstrip(',') | |
| 203 try: | |
| 204 options = dict([[j.strip() for j in i.split('=', 1)] | |
| 205 for i in option_string.split(',')]) | |
| 206 except: | |
| 207 raise Exception("Options format should be: key=value,key2=value2,...; got %s" % option_string) | |
| 0 | 208 |
| 15 | 209 url, dest, _type = line |
| 210 retval.append(dict(url=url, dest=dest, type=_type, options=options, manifest=manifest)) | |
| 211 return retval | |
| 0 | 212 |
| 2 | 213 def main(args=sys.argv[1:]): |
| 0 | 214 |
| 15 | 215 # parse command line options |
| 216 usage = '%prog [options] manifest [manifest] [...]' | |
| 0 | 217 |
| 15 | 218 class PlainDescriptionFormatter(optparse.IndentedHelpFormatter): |
| 219 def format_description(self, description): | |
| 220 if description: | |
| 221 return description + '\n' | |
| 222 else: | |
| 223 return '' | |
| 0 | 224 |
| 15 | 225 parser = optparse.OptionParser(usage=usage, description=__doc__, formatter=PlainDescriptionFormatter()) |
| 226 parser.add_option('-o', '--output', | |
| 227 help="output relative to this location vs. the manifest location") | |
| 17 | 228 parser.add_option('-d', '--dest', # XXX unused |
| 15 | 229 action='append', |
| 230 help="output only these destinations") | |
| 231 parser.add_option('-s', '--strict', | |
| 232 action='store_true', default=False, | |
| 233 help="fail on error") | |
| 234 parser.add_option('--list-fetchers', dest='list_fetchers', | |
| 235 action='store_true', default=False, | |
| 236 help='list available fetchers and exit') | |
| 237 options, args = parser.parse_args(args) | |
| 0 | 238 |
| 15 | 239 if options.list_fetchers: |
| 17 | 240 types = set() |
| 241 for fetcher in fetchers: | |
| 242 if fetcher.type in types: | |
| 243 continue # occluded, should probably display separately | |
| 244 print '%s : %s' % (fetcher.type, fetcher.doc()) | |
| 245 types.add(fetcher.type) | |
| 15 | 246 parser.exit() |
|
8
cf00d46b1bfb
pretend like we have a pluggable system to start debugging it
Jeff Hammel <jhammel@mozilla.com>
parents:
7
diff
changeset
|
247 |
| 15 | 248 if not args: |
| 17 | 249 # TODO: could read from stdin |
| 15 | 250 parser.print_help() |
| 251 parser.exit() | |
| 0 | 252 |
| 15 | 253 items = read_manifests(*args) |
| 16 | 254 fetch = Fetch(fetchers, strict=options.strict) |
| 0 | 255 |
| 15 | 256 # download the files |
| 257 fetch.fetch(*items) | |
| 0 | 258 |
| 259 if __name__ == '__main__': | |
| 15 | 260 main() |
| 0 | 261 |
