project.py 36 KB

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