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