sync.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. #
  2. # Copyright (C) 2008 The Android Open Source Project
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import netrc
  16. from optparse import SUPPRESS_HELP
  17. import os
  18. import pickle
  19. import re
  20. import shutil
  21. import socket
  22. import subprocess
  23. import sys
  24. import time
  25. import urlparse
  26. import xmlrpclib
  27. try:
  28. import threading as _threading
  29. except ImportError:
  30. import dummy_threading as _threading
  31. try:
  32. import resource
  33. def _rlimit_nofile():
  34. return resource.getrlimit(resource.RLIMIT_NOFILE)
  35. except ImportError:
  36. def _rlimit_nofile():
  37. return (256, 256)
  38. try:
  39. import multiprocessing
  40. except ImportError:
  41. multiprocessing = None
  42. from git_command import GIT
  43. from git_refs import R_HEADS, HEAD
  44. from main import WrapperModule
  45. from project import Project
  46. from project import RemoteSpec
  47. from command import Command, MirrorSafeCommand
  48. from error import RepoChangedException, GitError
  49. from project import SyncBuffer
  50. from progress import Progress
  51. _ONE_DAY_S = 24 * 60 * 60
  52. class _FetchError(Exception):
  53. """Internal error thrown in _FetchHelper() when we don't want stack trace."""
  54. pass
  55. class Sync(Command, MirrorSafeCommand):
  56. jobs = 1
  57. common = True
  58. helpSummary = "Update working tree to the latest revision"
  59. helpUsage = """
  60. %prog [<project>...]
  61. """
  62. helpDescription = """
  63. The '%prog' command synchronizes local project directories
  64. with the remote repositories specified in the manifest. If a local
  65. project does not yet exist, it will clone a new local directory from
  66. the remote repository and set up tracking branches as specified in
  67. the manifest. If the local project already exists, '%prog'
  68. will update the remote branches and rebase any new local changes
  69. on top of the new remote changes.
  70. '%prog' will synchronize all projects listed at the command
  71. line. Projects can be specified either by name, or by a relative
  72. or absolute path to the project's local directory. If no projects
  73. are specified, '%prog' will synchronize all projects listed in
  74. the manifest.
  75. The -d/--detach option can be used to switch specified projects
  76. back to the manifest revision. This option is especially helpful
  77. if the project is currently on a topic branch, but the manifest
  78. revision is temporarily needed.
  79. The -s/--smart-sync option can be used to sync to a known good
  80. build as specified by the manifest-server element in the current
  81. manifest. The -t/--smart-tag option is similar and allows you to
  82. specify a custom tag/label.
  83. The -u/--manifest-server-username and -p/--manifest-server-password
  84. options can be used to specify a username and password to authenticate
  85. with the manifest server when using the -s or -t option.
  86. If -u and -p are not specified when using the -s or -t option, '%prog'
  87. will attempt to read authentication credentials for the manifest server
  88. from the user's .netrc file.
  89. '%prog' will not use authentication credentials from -u/-p or .netrc
  90. if the manifest server specified in the manifest file already includes
  91. credentials.
  92. The -f/--force-broken option can be used to proceed with syncing
  93. other projects if a project sync fails.
  94. The --no-clone-bundle option disables any attempt to use
  95. $URL/clone.bundle to bootstrap a new Git repository from a
  96. resumeable bundle file on a content delivery network. This
  97. may be necessary if there are problems with the local Python
  98. HTTP client or proxy configuration, but the Git binary works.
  99. SSH Connections
  100. ---------------
  101. If at least one project remote URL uses an SSH connection (ssh://,
  102. git+ssh://, or user@host:path syntax) repo will automatically
  103. enable the SSH ControlMaster option when connecting to that host.
  104. This feature permits other projects in the same '%prog' session to
  105. reuse the same SSH tunnel, saving connection setup overheads.
  106. To disable this behavior on UNIX platforms, set the GIT_SSH
  107. environment variable to 'ssh'. For example:
  108. export GIT_SSH=ssh
  109. %prog
  110. Compatibility
  111. ~~~~~~~~~~~~~
  112. This feature is automatically disabled on Windows, due to the lack
  113. of UNIX domain socket support.
  114. This feature is not compatible with url.insteadof rewrites in the
  115. user's ~/.gitconfig. '%prog' is currently not able to perform the
  116. rewrite early enough to establish the ControlMaster tunnel.
  117. If the remote SSH daemon is Gerrit Code Review, version 2.0.10 or
  118. later is required to fix a server side protocol bug.
  119. """
  120. def _Options(self, p, show_smart=True):
  121. self.jobs = self.manifest.default.sync_j
  122. p.add_option('-f', '--force-broken',
  123. dest='force_broken', action='store_true',
  124. help="continue sync even if a project fails to sync")
  125. p.add_option('-l','--local-only',
  126. dest='local_only', action='store_true',
  127. help="only update working tree, don't fetch")
  128. p.add_option('-n','--network-only',
  129. dest='network_only', action='store_true',
  130. help="fetch only, don't update working tree")
  131. p.add_option('-d','--detach',
  132. dest='detach_head', action='store_true',
  133. help='detach projects back to manifest revision')
  134. p.add_option('-c','--current-branch',
  135. dest='current_branch_only', action='store_true',
  136. help='fetch only current branch from server')
  137. p.add_option('-q','--quiet',
  138. dest='quiet', action='store_true',
  139. help='be more quiet')
  140. p.add_option('-j','--jobs',
  141. dest='jobs', action='store', type='int',
  142. help="projects to fetch simultaneously (default %d)" % self.jobs)
  143. p.add_option('-m', '--manifest-name',
  144. dest='manifest_name',
  145. help='temporary manifest to use for this sync', metavar='NAME.xml')
  146. p.add_option('--no-clone-bundle',
  147. dest='no_clone_bundle', action='store_true',
  148. help='disable use of /clone.bundle on HTTP/HTTPS')
  149. if show_smart:
  150. p.add_option('-s', '--smart-sync',
  151. dest='smart_sync', action='store_true',
  152. help='smart sync using manifest from a known good build')
  153. p.add_option('-t', '--smart-tag',
  154. dest='smart_tag', action='store',
  155. help='smart sync using manifest from a known tag')
  156. p.add_option('-u', '--manifest-server-username', action='store',
  157. dest='manifest_server_username',
  158. help='username to authenticate with the manifest server')
  159. p.add_option('-p', '--manifest-server-password', action='store',
  160. dest='manifest_server_password',
  161. help='password to authenticate with the manifest server')
  162. g = p.add_option_group('repo Version options')
  163. g.add_option('--no-repo-verify',
  164. dest='no_repo_verify', action='store_true',
  165. help='do not verify repo source code')
  166. g.add_option('--repo-upgraded',
  167. dest='repo_upgraded', action='store_true',
  168. help=SUPPRESS_HELP)
  169. def _FetchHelper(self, opt, project, lock, fetched, pm, sem, err_event):
  170. """Main function of the fetch threads when jobs are > 1.
  171. Args:
  172. opt: Program options returned from optparse. See _Options().
  173. project: Project object for the project to fetch.
  174. lock: Lock for accessing objects that are shared amongst multiple
  175. _FetchHelper() threads.
  176. fetched: set object that we will add project.gitdir to when we're done
  177. (with our lock held).
  178. pm: Instance of a Project object. We will call pm.update() (with our
  179. lock held).
  180. sem: We'll release() this semaphore when we exit so that another thread
  181. can be started up.
  182. err_event: We'll set this event in the case of an error (after printing
  183. out info about the error).
  184. """
  185. # We'll set to true once we've locked the lock.
  186. did_lock = False
  187. # Encapsulate everything in a try/except/finally so that:
  188. # - We always set err_event in the case of an exception.
  189. # - We always make sure we call sem.release().
  190. # - We always make sure we unlock the lock if we locked it.
  191. try:
  192. try:
  193. start = time.time()
  194. success = project.Sync_NetworkHalf(
  195. quiet=opt.quiet,
  196. current_branch_only=opt.current_branch_only,
  197. clone_bundle=not opt.no_clone_bundle)
  198. self._fetch_times.Set(project, time.time() - start)
  199. # Lock around all the rest of the code, since printing, updating a set
  200. # and Progress.update() are not thread safe.
  201. lock.acquire()
  202. did_lock = True
  203. if not success:
  204. print >>sys.stderr, 'error: Cannot fetch %s' % project.name
  205. if opt.force_broken:
  206. print >>sys.stderr, 'warn: --force-broken, continuing to sync'
  207. else:
  208. raise _FetchError()
  209. fetched.add(project.gitdir)
  210. pm.update()
  211. except _FetchError:
  212. err_event.set()
  213. except:
  214. err_event.set()
  215. raise
  216. finally:
  217. if did_lock:
  218. lock.release()
  219. sem.release()
  220. def _Fetch(self, projects, opt):
  221. fetched = set()
  222. pm = Progress('Fetching projects', len(projects))
  223. if self.jobs == 1:
  224. for project in projects:
  225. pm.update()
  226. if project.Sync_NetworkHalf(
  227. quiet=opt.quiet,
  228. current_branch_only=opt.current_branch_only,
  229. clone_bundle=not opt.no_clone_bundle):
  230. fetched.add(project.gitdir)
  231. else:
  232. print >>sys.stderr, 'error: Cannot fetch %s' % project.name
  233. if opt.force_broken:
  234. print >>sys.stderr, 'warn: --force-broken, continuing to sync'
  235. else:
  236. sys.exit(1)
  237. else:
  238. threads = set()
  239. lock = _threading.Lock()
  240. sem = _threading.Semaphore(self.jobs)
  241. err_event = _threading.Event()
  242. for project in projects:
  243. # Check for any errors before starting any new threads.
  244. # ...we'll let existing threads finish, though.
  245. if err_event.isSet():
  246. break
  247. sem.acquire()
  248. t = _threading.Thread(target = self._FetchHelper,
  249. args = (opt,
  250. project,
  251. lock,
  252. fetched,
  253. pm,
  254. sem,
  255. err_event))
  256. # Ensure that Ctrl-C will not freeze the repo process.
  257. t.daemon = True
  258. threads.add(t)
  259. t.start()
  260. for t in threads:
  261. t.join()
  262. # If we saw an error, exit with code 1 so that other scripts can check.
  263. if err_event.isSet():
  264. print >>sys.stderr, '\nerror: Exited sync due to fetch errors'
  265. sys.exit(1)
  266. pm.end()
  267. self._fetch_times.Save()
  268. self._GCProjects(projects)
  269. return fetched
  270. def _GCProjects(self, projects):
  271. if multiprocessing:
  272. cpu_count = multiprocessing.cpu_count()
  273. else:
  274. cpu_count = 1
  275. jobs = min(self.jobs, cpu_count)
  276. if jobs < 2:
  277. for project in projects:
  278. project.bare_git.gc('--auto')
  279. return
  280. config = {'pack.threads': cpu_count / jobs if cpu_count > jobs else 1}
  281. threads = set()
  282. sem = _threading.Semaphore(jobs)
  283. err_event = _threading.Event()
  284. def GC(project):
  285. try:
  286. try:
  287. project.bare_git.gc('--auto', config=config)
  288. except GitError:
  289. err_event.set()
  290. except:
  291. err_event.set()
  292. raise
  293. finally:
  294. sem.release()
  295. for project in projects:
  296. if err_event.isSet():
  297. break
  298. sem.acquire()
  299. t = _threading.Thread(target=GC, args=(project,))
  300. t.daemon = True
  301. threads.add(t)
  302. t.start()
  303. for t in threads:
  304. t.join()
  305. if err_event.isSet():
  306. print >>sys.stderr, '\nerror: Exited sync due to gc errors'
  307. sys.exit(1)
  308. def UpdateProjectList(self):
  309. new_project_paths = []
  310. for project in self.GetProjects(None, missing_ok=True):
  311. if project.relpath:
  312. new_project_paths.append(project.relpath)
  313. file_name = 'project.list'
  314. file_path = os.path.join(self.manifest.repodir, file_name)
  315. old_project_paths = []
  316. if os.path.exists(file_path):
  317. fd = open(file_path, 'r')
  318. try:
  319. old_project_paths = fd.read().split('\n')
  320. finally:
  321. fd.close()
  322. for path in old_project_paths:
  323. if not path:
  324. continue
  325. if path not in new_project_paths:
  326. # If the path has already been deleted, we don't need to do it
  327. if os.path.exists(self.manifest.topdir + '/' + path):
  328. project = Project(
  329. manifest = self.manifest,
  330. name = path,
  331. remote = RemoteSpec('origin'),
  332. gitdir = os.path.join(self.manifest.topdir,
  333. path, '.git'),
  334. worktree = os.path.join(self.manifest.topdir, path),
  335. relpath = path,
  336. revisionExpr = 'HEAD',
  337. revisionId = None,
  338. groups = None)
  339. if project.IsDirty():
  340. print >>sys.stderr, 'error: Cannot remove project "%s": \
  341. uncommitted changes are present' % project.relpath
  342. print >>sys.stderr, ' commit changes, then run sync again'
  343. return -1
  344. else:
  345. print >>sys.stderr, 'Deleting obsolete path %s' % project.worktree
  346. shutil.rmtree(project.worktree)
  347. # Try deleting parent subdirs if they are empty
  348. project_dir = os.path.dirname(project.worktree)
  349. while project_dir != self.manifest.topdir:
  350. try:
  351. os.rmdir(project_dir)
  352. except OSError:
  353. break
  354. project_dir = os.path.dirname(project_dir)
  355. new_project_paths.sort()
  356. fd = open(file_path, 'w')
  357. try:
  358. fd.write('\n'.join(new_project_paths))
  359. fd.write('\n')
  360. finally:
  361. fd.close()
  362. return 0
  363. def Execute(self, opt, args):
  364. if opt.jobs:
  365. self.jobs = opt.jobs
  366. if self.jobs > 1:
  367. soft_limit, _ = _rlimit_nofile()
  368. self.jobs = min(self.jobs, (soft_limit - 5) / 3)
  369. if opt.network_only and opt.detach_head:
  370. print >>sys.stderr, 'error: cannot combine -n and -d'
  371. sys.exit(1)
  372. if opt.network_only and opt.local_only:
  373. print >>sys.stderr, 'error: cannot combine -n and -l'
  374. sys.exit(1)
  375. if opt.manifest_name and opt.smart_sync:
  376. print >>sys.stderr, 'error: cannot combine -m and -s'
  377. sys.exit(1)
  378. if opt.manifest_name and opt.smart_tag:
  379. print >>sys.stderr, 'error: cannot combine -m and -t'
  380. sys.exit(1)
  381. if opt.manifest_server_username or opt.manifest_server_password:
  382. if not (opt.smart_sync or opt.smart_tag):
  383. print >>sys.stderr, 'error: -u and -p may only be combined with ' \
  384. '-s or -t'
  385. sys.exit(1)
  386. if None in [opt.manifest_server_username, opt.manifest_server_password]:
  387. print >>sys.stderr, 'error: both -u and -p must be given'
  388. sys.exit(1)
  389. if opt.manifest_name:
  390. self.manifest.Override(opt.manifest_name)
  391. if opt.smart_sync or opt.smart_tag:
  392. if not self.manifest.manifest_server:
  393. print >>sys.stderr, \
  394. 'error: cannot smart sync: no manifest server defined in manifest'
  395. sys.exit(1)
  396. manifest_server = self.manifest.manifest_server
  397. if not '@' in manifest_server:
  398. username = None
  399. password = None
  400. if opt.manifest_server_username and opt.manifest_server_password:
  401. username = opt.manifest_server_username
  402. password = opt.manifest_server_password
  403. else:
  404. try:
  405. info = netrc.netrc()
  406. except IOError:
  407. print >>sys.stderr, '.netrc file does not exist or could not be opened'
  408. else:
  409. try:
  410. parse_result = urlparse.urlparse(manifest_server)
  411. if parse_result.hostname:
  412. username, _account, password = \
  413. info.authenticators(parse_result.hostname)
  414. except TypeError:
  415. # TypeError is raised when the given hostname is not present
  416. # in the .netrc file.
  417. print >>sys.stderr, 'No credentials found for %s in .netrc' % \
  418. parse_result.hostname
  419. except netrc.NetrcParseError as e:
  420. print >>sys.stderr, 'Error parsing .netrc file: %s' % e
  421. if (username and password):
  422. manifest_server = manifest_server.replace('://', '://%s:%s@' %
  423. (username, password),
  424. 1)
  425. try:
  426. server = xmlrpclib.Server(manifest_server)
  427. if opt.smart_sync:
  428. p = self.manifest.manifestProject
  429. b = p.GetBranch(p.CurrentBranch)
  430. branch = b.merge
  431. if branch.startswith(R_HEADS):
  432. branch = branch[len(R_HEADS):]
  433. env = os.environ.copy()
  434. if (env.has_key('TARGET_PRODUCT') and
  435. env.has_key('TARGET_BUILD_VARIANT')):
  436. target = '%s-%s' % (env['TARGET_PRODUCT'],
  437. env['TARGET_BUILD_VARIANT'])
  438. [success, manifest_str] = server.GetApprovedManifest(branch, target)
  439. else:
  440. [success, manifest_str] = server.GetApprovedManifest(branch)
  441. else:
  442. assert(opt.smart_tag)
  443. [success, manifest_str] = server.GetManifest(opt.smart_tag)
  444. if success:
  445. manifest_name = "smart_sync_override.xml"
  446. manifest_path = os.path.join(self.manifest.manifestProject.worktree,
  447. manifest_name)
  448. try:
  449. f = open(manifest_path, 'w')
  450. try:
  451. f.write(manifest_str)
  452. finally:
  453. f.close()
  454. except IOError:
  455. print >>sys.stderr, 'error: cannot write manifest to %s' % \
  456. manifest_path
  457. sys.exit(1)
  458. self.manifest.Override(manifest_name)
  459. else:
  460. print >>sys.stderr, 'error: %s' % manifest_str
  461. sys.exit(1)
  462. except (socket.error, IOError, xmlrpclib.Fault) as e:
  463. print >>sys.stderr, 'error: cannot connect to manifest server %s:\n%s' % (
  464. self.manifest.manifest_server, e)
  465. sys.exit(1)
  466. except xmlrpclib.ProtocolError as e:
  467. print >>sys.stderr, 'error: cannot connect to manifest server %s:\n%d %s' % (
  468. self.manifest.manifest_server, e.errcode, e.errmsg)
  469. sys.exit(1)
  470. rp = self.manifest.repoProject
  471. rp.PreSync()
  472. mp = self.manifest.manifestProject
  473. mp.PreSync()
  474. if opt.repo_upgraded:
  475. _PostRepoUpgrade(self.manifest, quiet=opt.quiet)
  476. if not opt.local_only:
  477. mp.Sync_NetworkHalf(quiet=opt.quiet,
  478. current_branch_only=opt.current_branch_only)
  479. if mp.HasChanges:
  480. syncbuf = SyncBuffer(mp.config)
  481. mp.Sync_LocalHalf(syncbuf)
  482. if not syncbuf.Finish():
  483. sys.exit(1)
  484. self.manifest._Unload()
  485. if opt.jobs is None:
  486. self.jobs = self.manifest.default.sync_j
  487. all_projects = self.GetProjects(args, missing_ok=True)
  488. self._fetch_times = _FetchTimes(self.manifest)
  489. if not opt.local_only:
  490. to_fetch = []
  491. now = time.time()
  492. if _ONE_DAY_S <= (now - rp.LastFetch):
  493. to_fetch.append(rp)
  494. to_fetch.extend(all_projects)
  495. to_fetch.sort(key=self._fetch_times.Get, reverse=True)
  496. self._Fetch(to_fetch, opt)
  497. _PostRepoFetch(rp, opt.no_repo_verify)
  498. if opt.network_only:
  499. # bail out now; the rest touches the working tree
  500. return
  501. if self.manifest.IsMirror:
  502. # bail out now, we have no working tree
  503. return
  504. if self.UpdateProjectList():
  505. sys.exit(1)
  506. syncbuf = SyncBuffer(mp.config,
  507. detach_head = opt.detach_head)
  508. pm = Progress('Syncing work tree', len(all_projects))
  509. for project in all_projects:
  510. pm.update()
  511. if project.worktree:
  512. project.Sync_LocalHalf(syncbuf)
  513. pm.end()
  514. print >>sys.stderr
  515. if not syncbuf.Finish():
  516. sys.exit(1)
  517. # If there's a notice that's supposed to print at the end of the sync, print
  518. # it now...
  519. if self.manifest.notice:
  520. print self.manifest.notice
  521. def _PostRepoUpgrade(manifest, quiet=False):
  522. wrapper = WrapperModule()
  523. if wrapper.NeedSetupGnuPG():
  524. wrapper.SetupGnuPG(quiet)
  525. for project in manifest.projects.values():
  526. if project.Exists:
  527. project.PostRepoUpgrade()
  528. def _PostRepoFetch(rp, no_repo_verify=False, verbose=False):
  529. if rp.HasChanges:
  530. print >>sys.stderr, 'info: A new version of repo is available'
  531. print >>sys.stderr, ''
  532. if no_repo_verify or _VerifyTag(rp):
  533. syncbuf = SyncBuffer(rp.config)
  534. rp.Sync_LocalHalf(syncbuf)
  535. if not syncbuf.Finish():
  536. sys.exit(1)
  537. print >>sys.stderr, 'info: Restarting repo with latest version'
  538. raise RepoChangedException(['--repo-upgraded'])
  539. else:
  540. print >>sys.stderr, 'warning: Skipped upgrade to unverified version'
  541. else:
  542. if verbose:
  543. print >>sys.stderr, 'repo version %s is current' % rp.work_git.describe(HEAD)
  544. def _VerifyTag(project):
  545. gpg_dir = os.path.expanduser('~/.repoconfig/gnupg')
  546. if not os.path.exists(gpg_dir):
  547. print >>sys.stderr,\
  548. """warning: GnuPG was not available during last "repo init"
  549. warning: Cannot automatically authenticate repo."""
  550. return True
  551. try:
  552. cur = project.bare_git.describe(project.GetRevisionId())
  553. except GitError:
  554. cur = None
  555. if not cur \
  556. or re.compile(r'^.*-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur):
  557. rev = project.revisionExpr
  558. if rev.startswith(R_HEADS):
  559. rev = rev[len(R_HEADS):]
  560. print >>sys.stderr
  561. print >>sys.stderr,\
  562. "warning: project '%s' branch '%s' is not signed" \
  563. % (project.name, rev)
  564. return False
  565. env = os.environ.copy()
  566. env['GIT_DIR'] = project.gitdir.encode()
  567. env['GNUPGHOME'] = gpg_dir.encode()
  568. cmd = [GIT, 'tag', '-v', cur]
  569. proc = subprocess.Popen(cmd,
  570. stdout = subprocess.PIPE,
  571. stderr = subprocess.PIPE,
  572. env = env)
  573. out = proc.stdout.read()
  574. proc.stdout.close()
  575. err = proc.stderr.read()
  576. proc.stderr.close()
  577. if proc.wait() != 0:
  578. print >>sys.stderr
  579. print >>sys.stderr, out
  580. print >>sys.stderr, err
  581. print >>sys.stderr
  582. return False
  583. return True
  584. class _FetchTimes(object):
  585. _ALPHA = 0.5
  586. def __init__(self, manifest):
  587. self._path = os.path.join(manifest.repodir, '.repopickle_fetchtimes')
  588. self._times = None
  589. self._seen = set()
  590. def Get(self, project):
  591. self._Load()
  592. return self._times.get(project.name, _ONE_DAY_S)
  593. def Set(self, project, t):
  594. self._Load()
  595. name = project.name
  596. old = self._times.get(name, t)
  597. self._seen.add(name)
  598. a = self._ALPHA
  599. self._times[name] = (a*t) + ((1-a) * old)
  600. def _Load(self):
  601. if self._times is None:
  602. try:
  603. f = open(self._path)
  604. except IOError:
  605. self._times = {}
  606. return self._times
  607. try:
  608. try:
  609. self._times = pickle.load(f)
  610. except:
  611. try:
  612. os.remove(self._path)
  613. except OSError:
  614. pass
  615. self._times = {}
  616. finally:
  617. f.close()
  618. return self._times
  619. def Save(self):
  620. if self._times is None:
  621. return
  622. to_delete = []
  623. for name in self._times:
  624. if name not in self._seen:
  625. to_delete.append(name)
  626. for name in to_delete:
  627. del self._times[name]
  628. try:
  629. f = open(self._path, 'wb')
  630. try:
  631. pickle.dump(self._times, f)
  632. except (IOError, OSError, pickle.PickleError):
  633. try:
  634. os.remove(self._path)
  635. except OSError:
  636. pass
  637. finally:
  638. f.close()