project.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  1. # Copyright (C) 2008 The Android Open Source Project
  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. import errno
  15. import filecmp
  16. import os
  17. import re
  18. import shutil
  19. import stat
  20. import sys
  21. import urllib2
  22. from color import Coloring
  23. from git_command import GitCommand
  24. from git_config import GitConfig, IsId
  25. from error import GitError, ImportError, UploadError
  26. from error import ManifestInvalidRevisionError
  27. from remote import Remote
  28. HEAD = 'HEAD'
  29. R_HEADS = 'refs/heads/'
  30. R_TAGS = 'refs/tags/'
  31. R_PUB = 'refs/published/'
  32. R_M = 'refs/remotes/m/'
  33. def _error(fmt, *args):
  34. msg = fmt % args
  35. print >>sys.stderr, 'error: %s' % msg
  36. def not_rev(r):
  37. return '^' + r
  38. def sq(r):
  39. return "'" + r.replace("'", "'\''") + "'"
  40. hook_list = None
  41. def repo_hooks():
  42. global hook_list
  43. if hook_list is None:
  44. d = os.path.abspath(os.path.dirname(__file__))
  45. d = os.path.join(d , 'hooks')
  46. hook_list = map(lambda x: os.path.join(d, x), os.listdir(d))
  47. return hook_list
  48. def relpath(dst, src):
  49. src = os.path.dirname(src)
  50. top = os.path.commonprefix([dst, src])
  51. if top.endswith('/'):
  52. top = top[:-1]
  53. else:
  54. top = os.path.dirname(top)
  55. tmp = src
  56. rel = ''
  57. while top != tmp:
  58. rel += '../'
  59. tmp = os.path.dirname(tmp)
  60. return rel + dst[len(top) + 1:]
  61. class DownloadedChange(object):
  62. _commit_cache = None
  63. def __init__(self, project, base, change_id, ps_id, commit):
  64. self.project = project
  65. self.base = base
  66. self.change_id = change_id
  67. self.ps_id = ps_id
  68. self.commit = commit
  69. @property
  70. def commits(self):
  71. if self._commit_cache is None:
  72. self._commit_cache = self.project.bare_git.rev_list(
  73. '--abbrev=8',
  74. '--abbrev-commit',
  75. '--pretty=oneline',
  76. '--reverse',
  77. '--date-order',
  78. not_rev(self.base),
  79. self.commit,
  80. '--')
  81. return self._commit_cache
  82. class ReviewableBranch(object):
  83. _commit_cache = None
  84. def __init__(self, project, branch, base):
  85. self.project = project
  86. self.branch = branch
  87. self.base = base
  88. self.replace_changes = None
  89. @property
  90. def name(self):
  91. return self.branch.name
  92. @property
  93. def commits(self):
  94. if self._commit_cache is None:
  95. self._commit_cache = self.project.bare_git.rev_list(
  96. '--abbrev=8',
  97. '--abbrev-commit',
  98. '--pretty=oneline',
  99. '--reverse',
  100. '--date-order',
  101. not_rev(self.base),
  102. R_HEADS + self.name,
  103. '--')
  104. return self._commit_cache
  105. @property
  106. def unabbrev_commits(self):
  107. r = dict()
  108. for commit in self.project.bare_git.rev_list(
  109. not_rev(self.base),
  110. R_HEADS + self.name,
  111. '--'):
  112. r[commit[0:8]] = commit
  113. return r
  114. @property
  115. def date(self):
  116. return self.project.bare_git.log(
  117. '--pretty=format:%cd',
  118. '-n', '1',
  119. R_HEADS + self.name,
  120. '--')
  121. def UploadForReview(self, people):
  122. self.project.UploadForReview(self.name,
  123. self.replace_changes,
  124. people)
  125. @property
  126. def tip_url(self):
  127. me = self.project.GetBranch(self.name)
  128. commit = self.project.bare_git.rev_parse(R_HEADS + self.name)
  129. return 'http://%s/r/%s' % (me.remote.review, commit[0:12])
  130. @property
  131. def owner_email(self):
  132. return self.project.UserEmail
  133. class StatusColoring(Coloring):
  134. def __init__(self, config):
  135. Coloring.__init__(self, config, 'status')
  136. self.project = self.printer('header', attr = 'bold')
  137. self.branch = self.printer('header', attr = 'bold')
  138. self.nobranch = self.printer('nobranch', fg = 'red')
  139. self.added = self.printer('added', fg = 'green')
  140. self.changed = self.printer('changed', fg = 'red')
  141. self.untracked = self.printer('untracked', fg = 'red')
  142. class DiffColoring(Coloring):
  143. def __init__(self, config):
  144. Coloring.__init__(self, config, 'diff')
  145. self.project = self.printer('header', attr = 'bold')
  146. class _CopyFile:
  147. def __init__(self, src, dest, abssrc, absdest):
  148. self.src = src
  149. self.dest = dest
  150. self.abs_src = abssrc
  151. self.abs_dest = absdest
  152. def _Copy(self):
  153. src = self.abs_src
  154. dest = self.abs_dest
  155. # copy file if it does not exist or is out of date
  156. if not os.path.exists(dest) or not filecmp.cmp(src, dest):
  157. try:
  158. # remove existing file first, since it might be read-only
  159. if os.path.exists(dest):
  160. os.remove(dest)
  161. shutil.copy(src, dest)
  162. # make the file read-only
  163. mode = os.stat(dest)[stat.ST_MODE]
  164. mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
  165. os.chmod(dest, mode)
  166. except IOError:
  167. _error('Cannot copy file %s to %s', src, dest)
  168. class Project(object):
  169. def __init__(self,
  170. manifest,
  171. name,
  172. remote,
  173. gitdir,
  174. worktree,
  175. relpath,
  176. revision):
  177. self.manifest = manifest
  178. self.name = name
  179. self.remote = remote
  180. self.gitdir = gitdir
  181. self.worktree = worktree
  182. self.relpath = relpath
  183. self.revision = revision
  184. self.snapshots = {}
  185. self.extraRemotes = {}
  186. self.copyfiles = []
  187. self.config = GitConfig.ForRepository(
  188. gitdir = self.gitdir,
  189. defaults = self.manifest.globalConfig)
  190. if self.worktree:
  191. self.work_git = self._GitGetByExec(self, bare=False)
  192. else:
  193. self.work_git = None
  194. self.bare_git = self._GitGetByExec(self, bare=True)
  195. @property
  196. def Exists(self):
  197. return os.path.isdir(self.gitdir)
  198. @property
  199. def CurrentBranch(self):
  200. """Obtain the name of the currently checked out branch.
  201. The branch name omits the 'refs/heads/' prefix.
  202. None is returned if the project is on a detached HEAD.
  203. """
  204. b = self.work_git.GetHead()
  205. if b.startswith(R_HEADS):
  206. return b[len(R_HEADS):]
  207. return None
  208. def IsDirty(self, consider_untracked=True):
  209. """Is the working directory modified in some way?
  210. """
  211. self.work_git.update_index('-q',
  212. '--unmerged',
  213. '--ignore-missing',
  214. '--refresh')
  215. if self.work_git.DiffZ('diff-index','-M','--cached',HEAD):
  216. return True
  217. if self.work_git.DiffZ('diff-files'):
  218. return True
  219. if consider_untracked and self.work_git.LsOthers():
  220. return True
  221. return False
  222. _userident_name = None
  223. _userident_email = None
  224. @property
  225. def UserName(self):
  226. """Obtain the user's personal name.
  227. """
  228. if self._userident_name is None:
  229. self._LoadUserIdentity()
  230. return self._userident_name
  231. @property
  232. def UserEmail(self):
  233. """Obtain the user's email address. This is very likely
  234. to be their Gerrit login.
  235. """
  236. if self._userident_email is None:
  237. self._LoadUserIdentity()
  238. return self._userident_email
  239. def _LoadUserIdentity(self):
  240. u = self.bare_git.var('GIT_COMMITTER_IDENT')
  241. m = re.compile("^(.*) <([^>]*)> ").match(u)
  242. if m:
  243. self._userident_name = m.group(1)
  244. self._userident_email = m.group(2)
  245. else:
  246. self._userident_name = ''
  247. self._userident_email = ''
  248. def GetRemote(self, name):
  249. """Get the configuration for a single remote.
  250. """
  251. return self.config.GetRemote(name)
  252. def GetBranch(self, name):
  253. """Get the configuration for a single branch.
  254. """
  255. return self.config.GetBranch(name)
  256. def GetBranches(self):
  257. """Get all existing local branches.
  258. """
  259. current = self.CurrentBranch
  260. all = self.bare_git.ListRefs()
  261. heads = {}
  262. pubd = {}
  263. for name, id in all.iteritems():
  264. if name.startswith(R_HEADS):
  265. name = name[len(R_HEADS):]
  266. b = self.GetBranch(name)
  267. b.current = name == current
  268. b.published = None
  269. b.revision = id
  270. heads[name] = b
  271. for name, id in all.iteritems():
  272. if name.startswith(R_PUB):
  273. name = name[len(R_PUB):]
  274. b = heads.get(name)
  275. if b:
  276. b.published = id
  277. return heads
  278. ## Status Display ##
  279. def PrintWorkTreeStatus(self):
  280. """Prints the status of the repository to stdout.
  281. """
  282. if not os.path.isdir(self.worktree):
  283. print ''
  284. print 'project %s/' % self.relpath
  285. print ' missing (run "repo sync")'
  286. return
  287. self.work_git.update_index('-q',
  288. '--unmerged',
  289. '--ignore-missing',
  290. '--refresh')
  291. di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
  292. df = self.work_git.DiffZ('diff-files')
  293. do = self.work_git.LsOthers()
  294. if not di and not df and not do:
  295. return 'CLEAN'
  296. out = StatusColoring(self.config)
  297. out.project('project %-40s', self.relpath + '/')
  298. branch = self.CurrentBranch
  299. if branch is None:
  300. out.nobranch('(*** NO BRANCH ***)')
  301. else:
  302. out.branch('branch %s', branch)
  303. out.nl()
  304. paths = list()
  305. paths.extend(di.keys())
  306. paths.extend(df.keys())
  307. paths.extend(do)
  308. paths = list(set(paths))
  309. paths.sort()
  310. for p in paths:
  311. try: i = di[p]
  312. except KeyError: i = None
  313. try: f = df[p]
  314. except KeyError: f = None
  315. if i: i_status = i.status.upper()
  316. else: i_status = '-'
  317. if f: f_status = f.status.lower()
  318. else: f_status = '-'
  319. if i and i.src_path:
  320. line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
  321. i.src_path, p, i.level)
  322. else:
  323. line = ' %s%s\t%s' % (i_status, f_status, p)
  324. if i and not f:
  325. out.added('%s', line)
  326. elif (i and f) or (not i and f):
  327. out.changed('%s', line)
  328. elif not i and not f:
  329. out.untracked('%s', line)
  330. else:
  331. out.write('%s', line)
  332. out.nl()
  333. return 'DIRTY'
  334. def PrintWorkTreeDiff(self):
  335. """Prints the status of the repository to stdout.
  336. """
  337. out = DiffColoring(self.config)
  338. cmd = ['diff']
  339. if out.is_on:
  340. cmd.append('--color')
  341. cmd.append(HEAD)
  342. cmd.append('--')
  343. p = GitCommand(self,
  344. cmd,
  345. capture_stdout = True,
  346. capture_stderr = True)
  347. has_diff = False
  348. for line in p.process.stdout:
  349. if not has_diff:
  350. out.nl()
  351. out.project('project %s/' % self.relpath)
  352. out.nl()
  353. has_diff = True
  354. print line[:-1]
  355. p.Wait()
  356. ## Publish / Upload ##
  357. def WasPublished(self, branch):
  358. """Was the branch published (uploaded) for code review?
  359. If so, returns the SHA-1 hash of the last published
  360. state for the branch.
  361. """
  362. try:
  363. return self.bare_git.rev_parse(R_PUB + branch)
  364. except GitError:
  365. return None
  366. def CleanPublishedCache(self):
  367. """Prunes any stale published refs.
  368. """
  369. heads = set()
  370. canrm = {}
  371. for name, id in self._allrefs.iteritems():
  372. if name.startswith(R_HEADS):
  373. heads.add(name)
  374. elif name.startswith(R_PUB):
  375. canrm[name] = id
  376. for name, id in canrm.iteritems():
  377. n = name[len(R_PUB):]
  378. if R_HEADS + n not in heads:
  379. self.bare_git.DeleteRef(name, id)
  380. def GetUploadableBranches(self):
  381. """List any branches which can be uploaded for review.
  382. """
  383. heads = {}
  384. pubed = {}
  385. for name, id in self._allrefs.iteritems():
  386. if name.startswith(R_HEADS):
  387. heads[name[len(R_HEADS):]] = id
  388. elif name.startswith(R_PUB):
  389. pubed[name[len(R_PUB):]] = id
  390. ready = []
  391. for branch, id in heads.iteritems():
  392. if branch in pubed and pubed[branch] == id:
  393. continue
  394. rb = self.GetUploadableBranch(branch)
  395. if rb:
  396. ready.append(rb)
  397. return ready
  398. def GetUploadableBranch(self, branch_name):
  399. """Get a single uploadable branch, or None.
  400. """
  401. branch = self.GetBranch(branch_name)
  402. base = branch.LocalMerge
  403. if branch.LocalMerge:
  404. rb = ReviewableBranch(self, branch, base)
  405. if rb.commits:
  406. return rb
  407. return None
  408. def UploadForReview(self, branch=None, replace_changes=None, people=([],[])):
  409. """Uploads the named branch for code review.
  410. """
  411. if branch is None:
  412. branch = self.CurrentBranch
  413. if branch is None:
  414. raise GitError('not currently on a branch')
  415. branch = self.GetBranch(branch)
  416. if not branch.LocalMerge:
  417. raise GitError('branch %s does not track a remote' % branch.name)
  418. if not branch.remote.review:
  419. raise GitError('remote %s has no review url' % branch.remote.name)
  420. dest_branch = branch.merge
  421. if not dest_branch.startswith(R_HEADS):
  422. dest_branch = R_HEADS + dest_branch
  423. if not branch.remote.projectname:
  424. branch.remote.projectname = self.name
  425. branch.remote.Save()
  426. if branch.remote.ReviewProtocol == 'ssh':
  427. if dest_branch.startswith(R_HEADS):
  428. dest_branch = dest_branch[len(R_HEADS):]
  429. rp = ['gerrit receive-pack']
  430. for e in people[0]:
  431. rp.append('--reviewer=%s' % sq(e))
  432. for e in people[1]:
  433. rp.append('--cc=%s' % sq(e))
  434. cmd = ['push']
  435. cmd.append('--receive-pack=%s' % " ".join(rp))
  436. cmd.append(branch.remote.SshReviewUrl(self.UserEmail))
  437. cmd.append('%s:refs/for/%s' % (R_HEADS + branch.name, dest_branch))
  438. if replace_changes:
  439. for change_id,commit_id in replace_changes.iteritems():
  440. cmd.append('%s:refs/changes/%s/new' % (commit_id, change_id))
  441. if GitCommand(self, cmd, bare = True).Wait() != 0:
  442. raise UploadError('Upload failed')
  443. else:
  444. raise UploadError('Unsupported protocol %s' \
  445. % branch.remote.review)
  446. msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
  447. self.bare_git.UpdateRef(R_PUB + branch.name,
  448. R_HEADS + branch.name,
  449. message = msg)
  450. ## Sync ##
  451. def Sync_NetworkHalf(self):
  452. """Perform only the network IO portion of the sync process.
  453. Local working directory/branch state is not affected.
  454. """
  455. if not self.Exists:
  456. print >>sys.stderr
  457. print >>sys.stderr, 'Initializing project %s ...' % self.name
  458. self._InitGitDir()
  459. self._InitRemote()
  460. for r in self.extraRemotes.values():
  461. if not self._RemoteFetch(r.name):
  462. return False
  463. if not self._RemoteFetch():
  464. return False
  465. if self.worktree:
  466. self._InitMRef()
  467. else:
  468. self._InitMirrorHead()
  469. try:
  470. os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
  471. except OSError:
  472. pass
  473. return True
  474. def PostRepoUpgrade(self):
  475. self._InitHooks()
  476. def _CopyFiles(self):
  477. for file in self.copyfiles:
  478. file._Copy()
  479. def Sync_LocalHalf(self, syncbuf):
  480. """Perform only the local IO portion of the sync process.
  481. Network access is not required.
  482. """
  483. self._InitWorkTree()
  484. self.CleanPublishedCache()
  485. rem = self.GetRemote(self.remote.name)
  486. rev = rem.ToLocal(self.revision)
  487. try:
  488. self.bare_git.rev_parse('--verify', '%s^0' % rev)
  489. except GitError:
  490. raise ManifestInvalidRevisionError(
  491. 'revision %s in %s not found' % (self.revision, self.name))
  492. branch = self.CurrentBranch
  493. if branch is None or syncbuf.detach_head:
  494. # Currently on a detached HEAD. The user is assumed to
  495. # not have any local modifications worth worrying about.
  496. #
  497. if os.path.exists(os.path.join(self.worktree, '.dotest')) \
  498. or os.path.exists(os.path.join(self.worktree, '.git', 'rebase-apply')):
  499. syncbuf.fail(self, _PriorSyncFailedError())
  500. return
  501. lost = self._revlist(not_rev(rev), HEAD)
  502. if lost:
  503. syncbuf.info(self, "discarding %d commits", len(lost))
  504. try:
  505. self._Checkout(rev, quiet=True)
  506. except GitError, e:
  507. syncbuf.fail(self, e)
  508. return
  509. self._CopyFiles()
  510. return
  511. branch = self.GetBranch(branch)
  512. merge = branch.LocalMerge
  513. if not merge:
  514. # The current branch has no tracking configuration.
  515. # Jump off it to a deatched HEAD.
  516. #
  517. syncbuf.info(self,
  518. "leaving %s; does not track upstream",
  519. branch.name)
  520. try:
  521. self._Checkout(rev, quiet=True)
  522. except GitError, e:
  523. syncbuf.fail(self, e)
  524. return
  525. self._CopyFiles()
  526. return
  527. upstream_gain = self._revlist(not_rev(HEAD), rev)
  528. pub = self.WasPublished(branch.name)
  529. if pub:
  530. not_merged = self._revlist(not_rev(rev), pub)
  531. if not_merged:
  532. if upstream_gain:
  533. # The user has published this branch and some of those
  534. # commits are not yet merged upstream. We do not want
  535. # to rewrite the published commits so we punt.
  536. #
  537. syncbuf.info(self,
  538. "branch %s is published but is now %d commits behind",
  539. branch.name,
  540. len(upstream_gain))
  541. return
  542. elif upstream_gain:
  543. # We can fast-forward safely.
  544. #
  545. def _doff():
  546. self._FastForward(rev)
  547. self._CopyFiles()
  548. syncbuf.later1(self, _doff)
  549. return
  550. else:
  551. # Trivially no changes in the upstream.
  552. #
  553. return
  554. if merge == rev:
  555. try:
  556. old_merge = self.bare_git.rev_parse('%s@{1}' % merge)
  557. except GitError:
  558. old_merge = merge
  559. if old_merge == '0000000000000000000000000000000000000000' \
  560. or old_merge == '':
  561. old_merge = merge
  562. else:
  563. # The upstream switched on us. Time to cross our fingers
  564. # and pray that the old upstream also wasn't in the habit
  565. # of rebasing itself.
  566. #
  567. syncbuf.info(self, "manifest switched %s...%s", merge, rev)
  568. old_merge = merge
  569. if rev == old_merge:
  570. upstream_lost = []
  571. else:
  572. upstream_lost = self._revlist(not_rev(rev), old_merge)
  573. if not upstream_lost and not upstream_gain:
  574. # Trivially no changes caused by the upstream.
  575. #
  576. return
  577. if self.IsDirty(consider_untracked=False):
  578. syncbuf.fail(self, _DirtyError())
  579. return
  580. if upstream_lost:
  581. # Upstream rebased. Not everything in HEAD
  582. # may have been caused by the user.
  583. #
  584. syncbuf.info(self,
  585. "discarding %d commits removed from upstream",
  586. len(upstream_lost))
  587. branch.remote = rem
  588. branch.merge = self.revision
  589. branch.Save()
  590. my_changes = self._revlist(not_rev(old_merge), HEAD)
  591. if my_changes:
  592. def _dorebase():
  593. self._Rebase(upstream = old_merge, onto = rev)
  594. self._CopyFiles()
  595. syncbuf.later2(self, _dorebase)
  596. elif upstream_lost:
  597. try:
  598. self._ResetHard(rev)
  599. self._CopyFiles()
  600. except GitError, e:
  601. syncbuf.fail(self, e)
  602. return
  603. else:
  604. def _doff():
  605. self._FastForward(rev)
  606. self._CopyFiles()
  607. syncbuf.later1(self, _doff)
  608. def AddCopyFile(self, src, dest, absdest):
  609. # dest should already be an absolute path, but src is project relative
  610. # make src an absolute path
  611. abssrc = os.path.join(self.worktree, src)
  612. self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
  613. def DownloadPatchSet(self, change_id, patch_id):
  614. """Download a single patch set of a single change to FETCH_HEAD.
  615. """
  616. remote = self.GetRemote(self.remote.name)
  617. cmd = ['fetch', remote.name]
  618. cmd.append('refs/changes/%2.2d/%d/%d' \
  619. % (change_id % 100, change_id, patch_id))
  620. cmd.extend(map(lambda x: str(x), remote.fetch))
  621. if GitCommand(self, cmd, bare=True).Wait() != 0:
  622. return None
  623. return DownloadedChange(self,
  624. remote.ToLocal(self.revision),
  625. change_id,
  626. patch_id,
  627. self.bare_git.rev_parse('FETCH_HEAD'))
  628. ## Branch Management ##
  629. def StartBranch(self, name):
  630. """Create a new branch off the manifest's revision.
  631. """
  632. try:
  633. self.bare_git.rev_parse(R_HEADS + name)
  634. exists = True
  635. except GitError:
  636. exists = False;
  637. if exists:
  638. if name == self.CurrentBranch:
  639. return True
  640. else:
  641. cmd = ['checkout', name, '--']
  642. return GitCommand(self, cmd).Wait() == 0
  643. else:
  644. branch = self.GetBranch(name)
  645. branch.remote = self.GetRemote(self.remote.name)
  646. branch.merge = self.revision
  647. rev = branch.LocalMerge
  648. cmd = ['checkout', '-b', branch.name, rev]
  649. if GitCommand(self, cmd).Wait() == 0:
  650. branch.Save()
  651. return True
  652. else:
  653. return False
  654. def CheckoutBranch(self, name):
  655. """Checkout a local topic branch.
  656. """
  657. # Be sure the branch exists
  658. try:
  659. tip_rev = self.bare_git.rev_parse(R_HEADS + name)
  660. except GitError:
  661. return False;
  662. # Do the checkout
  663. cmd = ['checkout', name, '--']
  664. return GitCommand(self, cmd).Wait() == 0
  665. def AbandonBranch(self, name):
  666. """Destroy a local topic branch.
  667. """
  668. try:
  669. tip_rev = self.bare_git.rev_parse(R_HEADS + name)
  670. except GitError:
  671. return
  672. if self.CurrentBranch == name:
  673. self._Checkout(
  674. self.GetRemote(self.remote.name).ToLocal(self.revision),
  675. quiet=True)
  676. cmd = ['branch', '-D', name]
  677. GitCommand(self, cmd, capture_stdout=True).Wait()
  678. def PruneHeads(self):
  679. """Prune any topic branches already merged into upstream.
  680. """
  681. cb = self.CurrentBranch
  682. kill = []
  683. left = self._allrefs
  684. for name in left.keys():
  685. if name.startswith(R_HEADS):
  686. name = name[len(R_HEADS):]
  687. if cb is None or name != cb:
  688. kill.append(name)
  689. rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
  690. if cb is not None \
  691. and not self._revlist(HEAD + '...' + rev) \
  692. and not self.IsDirty(consider_untracked = False):
  693. self.work_git.DetachHead(HEAD)
  694. kill.append(cb)
  695. if kill:
  696. old = self.bare_git.GetHead()
  697. if old is None:
  698. old = 'refs/heads/please_never_use_this_as_a_branch_name'
  699. try:
  700. self.bare_git.DetachHead(rev)
  701. b = ['branch', '-d']
  702. b.extend(kill)
  703. b = GitCommand(self, b, bare=True,
  704. capture_stdout=True,
  705. capture_stderr=True)
  706. b.Wait()
  707. finally:
  708. self.bare_git.SetHead(old)
  709. left = self._allrefs
  710. for branch in kill:
  711. if (R_HEADS + branch) not in left:
  712. self.CleanPublishedCache()
  713. break
  714. if cb and cb not in kill:
  715. kill.append(cb)
  716. kill.sort()
  717. kept = []
  718. for branch in kill:
  719. if (R_HEADS + branch) in left:
  720. branch = self.GetBranch(branch)
  721. base = branch.LocalMerge
  722. if not base:
  723. base = rev
  724. kept.append(ReviewableBranch(self, branch, base))
  725. return kept
  726. ## Direct Git Commands ##
  727. def _RemoteFetch(self, name=None):
  728. if not name:
  729. name = self.remote.name
  730. cmd = ['fetch']
  731. if not self.worktree:
  732. cmd.append('--update-head-ok')
  733. cmd.append(name)
  734. return GitCommand(self, cmd, bare = True).Wait() == 0
  735. def _Checkout(self, rev, quiet=False):
  736. cmd = ['checkout']
  737. if quiet:
  738. cmd.append('-q')
  739. cmd.append(rev)
  740. cmd.append('--')
  741. if GitCommand(self, cmd).Wait() != 0:
  742. if self._allrefs:
  743. raise GitError('%s checkout %s ' % (self.name, rev))
  744. def _ResetHard(self, rev, quiet=True):
  745. cmd = ['reset', '--hard']
  746. if quiet:
  747. cmd.append('-q')
  748. cmd.append(rev)
  749. if GitCommand(self, cmd).Wait() != 0:
  750. raise GitError('%s reset --hard %s ' % (self.name, rev))
  751. def _Rebase(self, upstream, onto = None):
  752. cmd = ['rebase']
  753. if onto is not None:
  754. cmd.extend(['--onto', onto])
  755. cmd.append(upstream)
  756. if GitCommand(self, cmd).Wait() != 0:
  757. raise GitError('%s rebase %s ' % (self.name, upstream))
  758. def _FastForward(self, head):
  759. cmd = ['merge', head]
  760. if GitCommand(self, cmd).Wait() != 0:
  761. raise GitError('%s merge %s ' % (self.name, head))
  762. def _InitGitDir(self):
  763. if not os.path.exists(self.gitdir):
  764. os.makedirs(self.gitdir)
  765. self.bare_git.init()
  766. if self.manifest.IsMirror:
  767. self.config.SetString('core.bare', 'true')
  768. else:
  769. self.config.SetString('core.bare', None)
  770. hooks = self._gitdir_path('hooks')
  771. try:
  772. to_rm = os.listdir(hooks)
  773. except OSError:
  774. to_rm = []
  775. for old_hook in to_rm:
  776. os.remove(os.path.join(hooks, old_hook))
  777. self._InitHooks()
  778. m = self.manifest.manifestProject.config
  779. for key in ['user.name', 'user.email']:
  780. if m.Has(key, include_defaults = False):
  781. self.config.SetString(key, m.GetString(key))
  782. def _InitHooks(self):
  783. hooks = self._gitdir_path('hooks')
  784. if not os.path.exists(hooks):
  785. os.makedirs(hooks)
  786. for stock_hook in repo_hooks():
  787. dst = os.path.join(hooks, os.path.basename(stock_hook))
  788. try:
  789. os.symlink(relpath(stock_hook, dst), dst)
  790. except OSError, e:
  791. if e.errno == errno.EEXIST:
  792. pass
  793. elif e.errno == errno.EPERM:
  794. raise GitError('filesystem must support symlinks')
  795. else:
  796. raise
  797. def _InitRemote(self):
  798. if self.remote.fetchUrl:
  799. remote = self.GetRemote(self.remote.name)
  800. url = self.remote.fetchUrl
  801. while url.endswith('/'):
  802. url = url[:-1]
  803. url += '/%s.git' % self.name
  804. remote.url = url
  805. remote.review = self.remote.reviewUrl
  806. if remote.projectname is None:
  807. remote.projectname = self.name
  808. if self.worktree:
  809. remote.ResetFetch(mirror=False)
  810. else:
  811. remote.ResetFetch(mirror=True)
  812. remote.Save()
  813. for r in self.extraRemotes.values():
  814. remote = self.GetRemote(r.name)
  815. remote.url = r.fetchUrl
  816. remote.review = r.reviewUrl
  817. if r.projectName:
  818. remote.projectname = r.projectName
  819. elif remote.projectname is None:
  820. remote.projectname = self.name
  821. remote.ResetFetch()
  822. remote.Save()
  823. def _InitMRef(self):
  824. if self.manifest.branch:
  825. msg = 'manifest set to %s' % self.revision
  826. ref = R_M + self.manifest.branch
  827. if IsId(self.revision):
  828. dst = self.revision + '^0'
  829. self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
  830. else:
  831. remote = self.GetRemote(self.remote.name)
  832. dst = remote.ToLocal(self.revision)
  833. self.bare_git.symbolic_ref('-m', msg, ref, dst)
  834. def _InitMirrorHead(self):
  835. dst = self.GetRemote(self.remote.name).ToLocal(self.revision)
  836. msg = 'manifest set to %s' % self.revision
  837. self.bare_git.SetHead(dst, message=msg)
  838. def _InitWorkTree(self):
  839. dotgit = os.path.join(self.worktree, '.git')
  840. if not os.path.exists(dotgit):
  841. os.makedirs(dotgit)
  842. for name in ['config',
  843. 'description',
  844. 'hooks',
  845. 'info',
  846. 'logs',
  847. 'objects',
  848. 'packed-refs',
  849. 'refs',
  850. 'rr-cache',
  851. 'svn']:
  852. try:
  853. src = os.path.join(self.gitdir, name)
  854. dst = os.path.join(dotgit, name)
  855. os.symlink(relpath(src, dst), dst)
  856. except OSError, e:
  857. if e.errno == errno.EPERM:
  858. raise GitError('filesystem must support symlinks')
  859. else:
  860. raise
  861. rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
  862. rev = self.bare_git.rev_parse('%s^0' % rev)
  863. f = open(os.path.join(dotgit, HEAD), 'wb')
  864. f.write("%s\n" % rev)
  865. f.close()
  866. cmd = ['read-tree', '--reset', '-u']
  867. cmd.append('-v')
  868. cmd.append('HEAD')
  869. if GitCommand(self, cmd).Wait() != 0:
  870. raise GitError("cannot initialize work tree")
  871. def _gitdir_path(self, path):
  872. return os.path.join(self.gitdir, path)
  873. def _revlist(self, *args):
  874. cmd = []
  875. cmd.extend(args)
  876. cmd.append('--')
  877. return self.work_git.rev_list(*args)
  878. @property
  879. def _allrefs(self):
  880. return self.bare_git.ListRefs()
  881. class _GitGetByExec(object):
  882. def __init__(self, project, bare):
  883. self._project = project
  884. self._bare = bare
  885. def ListRefs(self, *args):
  886. cmdv = ['for-each-ref', '--format=%(objectname) %(refname)']
  887. cmdv.extend(args)
  888. p = GitCommand(self._project,
  889. cmdv,
  890. bare = self._bare,
  891. capture_stdout = True,
  892. capture_stderr = True)
  893. r = {}
  894. for line in p.process.stdout:
  895. id, name = line[:-1].split(' ', 2)
  896. r[name] = id
  897. if p.Wait() != 0:
  898. raise GitError('%s for-each-ref %s: %s' % (
  899. self._project.name,
  900. str(args),
  901. p.stderr))
  902. return r
  903. def LsOthers(self):
  904. p = GitCommand(self._project,
  905. ['ls-files',
  906. '-z',
  907. '--others',
  908. '--exclude-standard'],
  909. bare = False,
  910. capture_stdout = True,
  911. capture_stderr = True)
  912. if p.Wait() == 0:
  913. out = p.stdout
  914. if out:
  915. return out[:-1].split("\0")
  916. return []
  917. def DiffZ(self, name, *args):
  918. cmd = [name]
  919. cmd.append('-z')
  920. cmd.extend(args)
  921. p = GitCommand(self._project,
  922. cmd,
  923. bare = False,
  924. capture_stdout = True,
  925. capture_stderr = True)
  926. try:
  927. out = p.process.stdout.read()
  928. r = {}
  929. if out:
  930. out = iter(out[:-1].split('\0'))
  931. while out:
  932. try:
  933. info = out.next()
  934. path = out.next()
  935. except StopIteration:
  936. break
  937. class _Info(object):
  938. def __init__(self, path, omode, nmode, oid, nid, state):
  939. self.path = path
  940. self.src_path = None
  941. self.old_mode = omode
  942. self.new_mode = nmode
  943. self.old_id = oid
  944. self.new_id = nid
  945. if len(state) == 1:
  946. self.status = state
  947. self.level = None
  948. else:
  949. self.status = state[:1]
  950. self.level = state[1:]
  951. while self.level.startswith('0'):
  952. self.level = self.level[1:]
  953. info = info[1:].split(' ')
  954. info =_Info(path, *info)
  955. if info.status in ('R', 'C'):
  956. info.src_path = info.path
  957. info.path = out.next()
  958. r[info.path] = info
  959. return r
  960. finally:
  961. p.Wait()
  962. def GetHead(self):
  963. if self._bare:
  964. path = os.path.join(self._project.gitdir, HEAD)
  965. else:
  966. path = os.path.join(self._project.worktree, '.git', HEAD)
  967. line = open(path, 'r').read()
  968. if line.startswith('ref: '):
  969. return line[5:-1]
  970. return line[:-1]
  971. def SetHead(self, ref, message=None):
  972. cmdv = []
  973. if message is not None:
  974. cmdv.extend(['-m', message])
  975. cmdv.append(HEAD)
  976. cmdv.append(ref)
  977. self.symbolic_ref(*cmdv)
  978. def DetachHead(self, new, message=None):
  979. cmdv = ['--no-deref']
  980. if message is not None:
  981. cmdv.extend(['-m', message])
  982. cmdv.append(HEAD)
  983. cmdv.append(new)
  984. self.update_ref(*cmdv)
  985. def UpdateRef(self, name, new, old=None,
  986. message=None,
  987. detach=False):
  988. cmdv = []
  989. if message is not None:
  990. cmdv.extend(['-m', message])
  991. if detach:
  992. cmdv.append('--no-deref')
  993. cmdv.append(name)
  994. cmdv.append(new)
  995. if old is not None:
  996. cmdv.append(old)
  997. self.update_ref(*cmdv)
  998. def DeleteRef(self, name, old=None):
  999. if not old:
  1000. old = self.rev_parse(name)
  1001. self.update_ref('-d', name, old)
  1002. def rev_list(self, *args):
  1003. cmdv = ['rev-list']
  1004. cmdv.extend(args)
  1005. p = GitCommand(self._project,
  1006. cmdv,
  1007. bare = self._bare,
  1008. capture_stdout = True,
  1009. capture_stderr = True)
  1010. r = []
  1011. for line in p.process.stdout:
  1012. r.append(line[:-1])
  1013. if p.Wait() != 0:
  1014. raise GitError('%s rev-list %s: %s' % (
  1015. self._project.name,
  1016. str(args),
  1017. p.stderr))
  1018. return r
  1019. def __getattr__(self, name):
  1020. name = name.replace('_', '-')
  1021. def runner(*args):
  1022. cmdv = [name]
  1023. cmdv.extend(args)
  1024. p = GitCommand(self._project,
  1025. cmdv,
  1026. bare = self._bare,
  1027. capture_stdout = True,
  1028. capture_stderr = True)
  1029. if p.Wait() != 0:
  1030. raise GitError('%s %s: %s' % (
  1031. self._project.name,
  1032. name,
  1033. p.stderr))
  1034. r = p.stdout
  1035. if r.endswith('\n') and r.index('\n') == len(r) - 1:
  1036. return r[:-1]
  1037. return r
  1038. return runner
  1039. class _PriorSyncFailedError(Exception):
  1040. def __str__(self):
  1041. return 'prior sync failed; rebase still in progress'
  1042. class _DirtyError(Exception):
  1043. def __str__(self):
  1044. return 'contains uncommitted changes'
  1045. class _InfoMessage(object):
  1046. def __init__(self, project, text):
  1047. self.project = project
  1048. self.text = text
  1049. def Print(self, syncbuf):
  1050. syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
  1051. syncbuf.out.nl()
  1052. class _Failure(object):
  1053. def __init__(self, project, why):
  1054. self.project = project
  1055. self.why = why
  1056. def Print(self, syncbuf):
  1057. syncbuf.out.fail('error: %s/: %s',
  1058. self.project.relpath,
  1059. str(self.why))
  1060. syncbuf.out.nl()
  1061. class _Later(object):
  1062. def __init__(self, project, action):
  1063. self.project = project
  1064. self.action = action
  1065. def Run(self, syncbuf):
  1066. out = syncbuf.out
  1067. out.project('project %s/', self.project.relpath)
  1068. out.nl()
  1069. try:
  1070. self.action()
  1071. out.nl()
  1072. return True
  1073. except GitError, e:
  1074. out.nl()
  1075. return False
  1076. class _SyncColoring(Coloring):
  1077. def __init__(self, config):
  1078. Coloring.__init__(self, config, 'reposync')
  1079. self.project = self.printer('header', attr = 'bold')
  1080. self.info = self.printer('info')
  1081. self.fail = self.printer('fail', fg='red')
  1082. class SyncBuffer(object):
  1083. def __init__(self, config, detach_head=False):
  1084. self._messages = []
  1085. self._failures = []
  1086. self._later_queue1 = []
  1087. self._later_queue2 = []
  1088. self.out = _SyncColoring(config)
  1089. self.out.redirect(sys.stderr)
  1090. self.detach_head = detach_head
  1091. self.clean = True
  1092. def info(self, project, fmt, *args):
  1093. self._messages.append(_InfoMessage(project, fmt % args))
  1094. def fail(self, project, err=None):
  1095. self._failures.append(_Failure(project, err))
  1096. self.clean = False
  1097. def later1(self, project, what):
  1098. self._later_queue1.append(_Later(project, what))
  1099. def later2(self, project, what):
  1100. self._later_queue2.append(_Later(project, what))
  1101. def Finish(self):
  1102. self._PrintMessages()
  1103. self._RunLater()
  1104. self._PrintMessages()
  1105. return self.clean
  1106. def _RunLater(self):
  1107. for q in ['_later_queue1', '_later_queue2']:
  1108. if not self._RunQueue(q):
  1109. return
  1110. def _RunQueue(self, queue):
  1111. for m in getattr(self, queue):
  1112. if not m.Run(self):
  1113. self.clean = False
  1114. return False
  1115. setattr(self, queue, [])
  1116. return True
  1117. def _PrintMessages(self):
  1118. for m in self._messages:
  1119. m.Print(self)
  1120. for m in self._failures:
  1121. m.Print(self)
  1122. self._messages = []
  1123. self._failures = []
  1124. class MetaProject(Project):
  1125. """A special project housed under .repo.
  1126. """
  1127. def __init__(self, manifest, name, gitdir, worktree):
  1128. repodir = manifest.repodir
  1129. Project.__init__(self,
  1130. manifest = manifest,
  1131. name = name,
  1132. gitdir = gitdir,
  1133. worktree = worktree,
  1134. remote = Remote('origin'),
  1135. relpath = '.repo/%s' % name,
  1136. revision = 'refs/heads/master')
  1137. def PreSync(self):
  1138. if self.Exists:
  1139. cb = self.CurrentBranch
  1140. if cb:
  1141. base = self.GetBranch(cb).merge
  1142. if base:
  1143. self.revision = base
  1144. @property
  1145. def HasChanges(self):
  1146. """Has the remote received new commits not yet checked out?
  1147. """
  1148. rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
  1149. if self._revlist(not_rev(HEAD), rev):
  1150. return True
  1151. return False