combo-layer 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373
  1. #!/usr/bin/env python
  2. # ex:ts=4:sw=4:sts=4:et
  3. # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
  4. #
  5. # Copyright 2011 Intel Corporation
  6. # Authored-by: Yu Ke <ke.yu@intel.com>
  7. # Paul Eggleton <paul.eggleton@intel.com>
  8. # Richard Purdie <richard.purdie@intel.com>
  9. #
  10. # This program is free software; you can redistribute it and/or modify
  11. # it under the terms of the GNU General Public License version 2 as
  12. # published by the Free Software Foundation.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. import fnmatch
  23. import os, sys
  24. import optparse
  25. import logging
  26. import subprocess
  27. import tempfile
  28. import ConfigParser
  29. import re
  30. import copy
  31. import pipes
  32. import shutil
  33. from collections import OrderedDict
  34. from string import Template
  35. __version__ = "0.2.1"
  36. def logger_create():
  37. logger = logging.getLogger("")
  38. loggerhandler = logging.StreamHandler()
  39. loggerhandler.setFormatter(logging.Formatter("[%(asctime)s] %(message)s","%H:%M:%S"))
  40. logger.addHandler(loggerhandler)
  41. logger.setLevel(logging.INFO)
  42. return logger
  43. logger = logger_create()
  44. def get_current_branch(repodir=None):
  45. try:
  46. if not os.path.exists(os.path.join(repodir if repodir else '', ".git")):
  47. # Repo not created yet (i.e. during init) so just assume master
  48. return "master"
  49. branchname = runcmd("git symbolic-ref HEAD 2>/dev/null", repodir).strip()
  50. if branchname.startswith("refs/heads/"):
  51. branchname = branchname[11:]
  52. return branchname
  53. except subprocess.CalledProcessError:
  54. return ""
  55. class Configuration(object):
  56. """
  57. Manages the configuration
  58. For an example config file, see combo-layer.conf.example
  59. """
  60. def __init__(self, options):
  61. for key, val in options.__dict__.items():
  62. setattr(self, key, val)
  63. def readsection(parser, section, repo):
  64. for (name, value) in parser.items(section):
  65. if value.startswith("@"):
  66. self.repos[repo][name] = eval(value.strip("@"))
  67. else:
  68. # Apply special type transformations for some properties.
  69. # Type matches the RawConfigParser.get*() methods.
  70. types = {'signoff': 'boolean', 'update': 'boolean', 'history': 'boolean'}
  71. if name in types:
  72. value = getattr(parser, 'get' + types[name])(section, name)
  73. self.repos[repo][name] = value
  74. def readglobalsection(parser, section):
  75. for (name, value) in parser.items(section):
  76. if name == "commit_msg":
  77. self.commit_msg_template = value
  78. logger.debug("Loading config file %s" % self.conffile)
  79. self.parser = ConfigParser.ConfigParser()
  80. with open(self.conffile) as f:
  81. self.parser.readfp(f)
  82. # initialize default values
  83. self.commit_msg_template = "Automatic commit to update last_revision"
  84. self.repos = {}
  85. for repo in self.parser.sections():
  86. if repo == "combo-layer-settings":
  87. # special handling for global settings
  88. readglobalsection(self.parser, repo)
  89. else:
  90. self.repos[repo] = {}
  91. readsection(self.parser, repo, repo)
  92. # Load local configuration, if available
  93. self.localconffile = None
  94. self.localparser = None
  95. self.combobranch = None
  96. if self.conffile.endswith('.conf'):
  97. lcfile = self.conffile.replace('.conf', '-local.conf')
  98. if os.path.exists(lcfile):
  99. # Read combo layer branch
  100. self.combobranch = get_current_branch()
  101. logger.debug("Combo layer branch is %s" % self.combobranch)
  102. self.localconffile = lcfile
  103. logger.debug("Loading local config file %s" % self.localconffile)
  104. self.localparser = ConfigParser.ConfigParser()
  105. with open(self.localconffile) as f:
  106. self.localparser.readfp(f)
  107. for section in self.localparser.sections():
  108. if '|' in section:
  109. sectionvals = section.split('|')
  110. repo = sectionvals[0]
  111. if sectionvals[1] != self.combobranch:
  112. continue
  113. else:
  114. repo = section
  115. if repo in self.repos:
  116. readsection(self.localparser, section, repo)
  117. def update(self, repo, option, value, initmode=False):
  118. # If the main config has the option already, that is what we
  119. # are expected to modify.
  120. if self.localparser and not self.parser.has_option(repo, option):
  121. parser = self.localparser
  122. section = "%s|%s" % (repo, self.combobranch)
  123. conffile = self.localconffile
  124. if initmode and not parser.has_section(section):
  125. parser.add_section(section)
  126. else:
  127. parser = self.parser
  128. section = repo
  129. conffile = self.conffile
  130. parser.set(section, option, value)
  131. with open(conffile, "w") as f:
  132. parser.write(f)
  133. self.repos[repo][option] = value
  134. def sanity_check(self, initmode=False):
  135. required_options=["src_uri", "local_repo_dir", "dest_dir", "last_revision"]
  136. if initmode:
  137. required_options.remove("last_revision")
  138. msg = ""
  139. missing_options = []
  140. for name in self.repos:
  141. for option in required_options:
  142. if option not in self.repos[name]:
  143. msg = "%s\nOption %s is not defined for component %s" %(msg, option, name)
  144. missing_options.append(option)
  145. # Sanitize dest_dir so that we do not have to deal with edge cases
  146. # (unset, empty string, double slashes) in the rest of the code.
  147. # It not being set will still be flagged as error because it is
  148. # listed as required option above; that could be changed now.
  149. dest_dir = os.path.normpath(self.repos[name].get("dest_dir", "."))
  150. self.repos[name]["dest_dir"] = "." if not dest_dir else dest_dir
  151. if msg != "":
  152. logger.error("configuration file %s has the following error: %s" % (self.conffile,msg))
  153. if self.localconffile and 'last_revision' in missing_options:
  154. logger.error("local configuration file %s may be missing configuration for combo branch %s" % (self.localconffile, self.combobranch))
  155. sys.exit(1)
  156. # filterdiff is required by action_splitpatch, so check its availability
  157. if subprocess.call("which filterdiff > /dev/null 2>&1", shell=True) != 0:
  158. logger.error("ERROR: patchutils package is missing, please install it (e.g. # apt-get install patchutils)")
  159. sys.exit(1)
  160. def runcmd(cmd,destdir=None,printerr=True,out=None,env=None):
  161. """
  162. execute command, raise CalledProcessError if fail
  163. return output if succeed
  164. """
  165. logger.debug("run cmd '%s' in %s" % (cmd, os.getcwd() if destdir is None else destdir))
  166. if not out:
  167. out = os.tmpfile()
  168. err = out
  169. else:
  170. err = os.tmpfile()
  171. try:
  172. subprocess.check_call(cmd, stdout=out, stderr=err, cwd=destdir, shell=isinstance(cmd, str), env=env or os.environ)
  173. except subprocess.CalledProcessError,e:
  174. err.seek(0)
  175. if printerr:
  176. logger.error("%s" % err.read())
  177. raise e
  178. err.seek(0)
  179. output = err.read()
  180. logger.debug("output: %s" % output.replace(chr(0), '\\0'))
  181. return output
  182. def action_init(conf, args):
  183. """
  184. Clone component repositories
  185. Check git is initialised; if not, copy initial data from component repos
  186. """
  187. for name in conf.repos:
  188. ldir = conf.repos[name]['local_repo_dir']
  189. if not os.path.exists(ldir):
  190. logger.info("cloning %s to %s" %(conf.repos[name]['src_uri'], ldir))
  191. subprocess.check_call("git clone %s %s" % (conf.repos[name]['src_uri'], ldir), shell=True)
  192. if not os.path.exists(".git"):
  193. runcmd("git init")
  194. if conf.history:
  195. # Need a common ref for all trees.
  196. runcmd('git commit -m "initial empty commit" --allow-empty')
  197. startrev = runcmd('git rev-parse master').strip()
  198. for name in conf.repos:
  199. repo = conf.repos[name]
  200. ldir = repo['local_repo_dir']
  201. branch = repo.get('branch', "master")
  202. lastrev = repo.get('last_revision', None)
  203. if lastrev and lastrev != "HEAD":
  204. initialrev = lastrev
  205. if branch:
  206. if not check_rev_branch(name, ldir, lastrev, branch):
  207. sys.exit(1)
  208. logger.info("Copying data from %s at specified revision %s..." % (name, lastrev))
  209. else:
  210. lastrev = None
  211. initialrev = branch
  212. logger.info("Copying data from %s..." % name)
  213. # Sanity check initialrev and turn it into hash (required for copying history,
  214. # because resolving a name ref only works in the component repo).
  215. rev = runcmd('git rev-parse %s' % initialrev, ldir).strip()
  216. if rev != initialrev:
  217. try:
  218. refs = runcmd('git show-ref -s %s' % initialrev, ldir).split('\n')
  219. if len(set(refs)) > 1:
  220. # Happens for example when configured to track
  221. # "master" and there is a refs/heads/master. The
  222. # traditional behavior from "git archive" (preserved
  223. # here) it to choose the first one. This might not be
  224. # intended, so at least warn about it.
  225. logger.warn("%s: initial revision '%s' not unique, picking result of rev-parse = %s" %
  226. (name, initialrev, refs[0]))
  227. initialrev = rev
  228. except:
  229. # show-ref fails for hashes. Skip the sanity warning in that case.
  230. pass
  231. initialrev = rev
  232. dest_dir = repo['dest_dir']
  233. if dest_dir != ".":
  234. extract_dir = os.path.join(os.getcwd(), dest_dir)
  235. if not os.path.exists(extract_dir):
  236. os.makedirs(extract_dir)
  237. else:
  238. extract_dir = os.getcwd()
  239. file_filter = repo.get('file_filter', "")
  240. exclude_patterns = repo.get('file_exclude', '').split()
  241. def copy_selected_files(initialrev, extract_dir, file_filter, exclude_patterns, ldir,
  242. subdir=""):
  243. # When working inside a filtered branch which had the
  244. # files already moved, we need to prepend the
  245. # subdirectory to all filters, otherwise they would
  246. # not match.
  247. if subdir == '.':
  248. subdir = ''
  249. elif subdir:
  250. subdir = os.path.normpath(subdir)
  251. file_filter = ' '.join([subdir + '/' + x for x in file_filter.split()])
  252. exclude_patterns = [subdir + '/' + x for x in exclude_patterns]
  253. # To handle both cases, we cd into the target
  254. # directory and optionally tell tar to strip the path
  255. # prefix when the files were already moved.
  256. subdir_components = len(subdir.split(os.path.sep)) if subdir else 0
  257. strip=('--strip-components=%d' % subdir_components) if subdir else ''
  258. # TODO: file_filter wild cards do not work (and haven't worked before either), because
  259. # a) GNU tar requires a --wildcards parameter before turning on wild card matching.
  260. # b) The semantic is not as intendend (src/*.c also matches src/foo/bar.c,
  261. # in contrast to the other use of file_filter as parameter of "git archive"
  262. # where it only matches .c files directly in src).
  263. files = runcmd("git archive %s %s | tar -x -v %s -C %s %s" %
  264. (initialrev, subdir,
  265. strip, extract_dir, file_filter),
  266. ldir)
  267. if exclude_patterns:
  268. # Implement file removal by letting tar create the
  269. # file and then deleting it in the file system
  270. # again. Uses the list of files created by tar (easier
  271. # than walking the tree).
  272. for file in files.split('\n'):
  273. for pattern in exclude_patterns:
  274. if fnmatch.fnmatch(file, pattern):
  275. os.unlink(os.path.join(*([extract_dir] + ['..'] * subdir_components + [file])))
  276. break
  277. if not conf.history:
  278. copy_selected_files(initialrev, extract_dir, file_filter, exclude_patterns, ldir)
  279. else:
  280. # First fetch remote history into local repository.
  281. # We need a ref for that, so ensure that there is one.
  282. refname = "combo-layer-init-%s" % name
  283. runcmd("git branch -f %s %s" % (refname, initialrev), ldir)
  284. runcmd("git fetch %s %s" % (ldir, refname))
  285. runcmd("git branch -D %s" % refname, ldir)
  286. # Make that the head revision.
  287. runcmd("git checkout -b %s %s" % (name, initialrev))
  288. # Optional: cut the history by replacing the given
  289. # start point(s) with commits providing the same
  290. # content (aka tree), but with commit information that
  291. # makes it clear that this is an artifically created
  292. # commit and nothing the original authors had anything
  293. # to do with.
  294. since_rev = repo.get('since_revision', '')
  295. if since_rev:
  296. committer = runcmd('git var GIT_AUTHOR_IDENT').strip()
  297. # Same time stamp, no name.
  298. author = re.sub('.* (\d+ [+-]\d+)', r'unknown <unknown> \1', committer)
  299. logger.info('author %s' % author)
  300. for rev in since_rev.split():
  301. # Resolve in component repo...
  302. rev = runcmd('git log --oneline --no-abbrev-commit -n1 %s' % rev, ldir).split()[0]
  303. # ... and then get the tree in current
  304. # one. The commit should be in both repos with
  305. # the same tree, but better check here.
  306. tree = runcmd('git show -s --pretty=format:%%T %s' % rev).strip()
  307. with tempfile.NamedTemporaryFile() as editor:
  308. editor.write('''cat >$1 <<EOF
  309. tree %s
  310. author %s
  311. committer %s
  312. %s: squashed import of component
  313. This commit copies the entire set of files as found in
  314. %s %s
  315. For more information about previous commits, see the
  316. upstream repository.
  317. Commit created by combo-layer.
  318. EOF
  319. ''' % (tree, author, committer, name, name, since_rev))
  320. editor.flush()
  321. os.environ['GIT_EDITOR'] = 'sh %s' % editor.name
  322. runcmd('git replace --edit %s' % rev)
  323. # Optional: rewrite history to change commit messages or to move files.
  324. if 'hook' in repo or dest_dir != ".":
  325. filter_branch = ['git', 'filter-branch', '--force']
  326. with tempfile.NamedTemporaryFile() as hookwrapper:
  327. if 'hook' in repo:
  328. # Create a shell script wrapper around the original hook that
  329. # can be used by git filter-branch. Hook may or may not have
  330. # an absolute path.
  331. hook = repo['hook']
  332. hook = os.path.join(os.path.dirname(conf.conffile), '..', hook)
  333. # The wrappers turns the commit message
  334. # from stdin into a fake patch header.
  335. # This is good enough for changing Subject
  336. # and commit msg body with normal
  337. # combo-layer hooks.
  338. hookwrapper.write('''set -e
  339. tmpname=$(mktemp)
  340. trap "rm $tmpname" EXIT
  341. echo -n 'Subject: [PATCH] ' >>$tmpname
  342. cat >>$tmpname
  343. if ! [ $(tail -c 1 $tmpname | od -A n -t x1) == '0a' ]; then
  344. echo >>$tmpname
  345. fi
  346. echo '---' >>$tmpname
  347. %s $tmpname $GIT_COMMIT %s
  348. tail -c +18 $tmpname | head -c -4
  349. ''' % (hook, name))
  350. hookwrapper.flush()
  351. filter_branch.extend(['--msg-filter', 'bash %s' % hookwrapper.name])
  352. if dest_dir != ".":
  353. parent = os.path.dirname(dest_dir)
  354. if not parent:
  355. parent = '.'
  356. # May run outside of the current directory, so do not assume that .git exists.
  357. filter_branch.extend(['--tree-filter', 'mkdir -p .git/tmptree && find . -mindepth 1 -maxdepth 1 ! -name .git -print0 | xargs -0 -I SOURCE mv SOURCE .git/tmptree && mkdir -p %s && mv .git/tmptree %s' % (parent, dest_dir)])
  358. filter_branch.append('HEAD')
  359. runcmd(filter_branch)
  360. runcmd('git update-ref -d refs/original/refs/heads/%s' % name)
  361. repo['rewritten_revision'] = runcmd('git rev-parse HEAD').strip()
  362. repo['stripped_revision'] = repo['rewritten_revision']
  363. # Optional filter files: remove everything and re-populate using the normal filtering code.
  364. # Override any potential .gitignore.
  365. if file_filter or exclude_patterns:
  366. runcmd('git rm -rf .')
  367. if not os.path.exists(extract_dir):
  368. os.makedirs(extract_dir)
  369. copy_selected_files('HEAD', extract_dir, file_filter, exclude_patterns, '.',
  370. subdir=dest_dir)
  371. runcmd('git add --all --force .')
  372. if runcmd('git status --porcelain'):
  373. # Something to commit.
  374. runcmd(['git', 'commit', '-m',
  375. '''%s: select file subset
  376. Files from the component repository were chosen based on
  377. the following filters:
  378. file_filter = %s
  379. file_exclude = %s''' % (name, file_filter or '<empty>', repo.get('file_exclude', '<empty>'))])
  380. repo['stripped_revision'] = runcmd('git rev-parse HEAD').strip()
  381. if not lastrev:
  382. lastrev = runcmd('git rev-parse %s' % initialrev, ldir).strip()
  383. conf.update(name, "last_revision", lastrev, initmode=True)
  384. if not conf.history:
  385. runcmd("git add .")
  386. else:
  387. # Create Octopus merge commit according to http://stackoverflow.com/questions/10874149/git-octopus-merge-with-unrelated-repositoies
  388. runcmd('git checkout master')
  389. merge = ['git', 'merge', '--no-commit']
  390. for name in conf.repos:
  391. repo = conf.repos[name]
  392. # Use branch created earlier.
  393. merge.append(name)
  394. # Root all commits which have no parent in the common
  395. # ancestor in the new repository.
  396. for start in runcmd('git log --pretty=format:%%H --max-parents=0 %s' % name).split('\n'):
  397. runcmd('git replace --graft %s %s' % (start, startrev))
  398. try:
  399. runcmd(merge)
  400. except Exception, error:
  401. logger.info('''Merging component repository history failed, perhaps because of merge conflicts.
  402. It may be possible to commit anyway after resolving these conflicts.
  403. %s''' % error)
  404. # Create MERGE_HEAD and MERGE_MSG. "git merge" itself
  405. # does not create MERGE_HEAD in case of a (harmless) failure,
  406. # and we want certain auto-generated information in the
  407. # commit message for future reference and/or automation.
  408. with open('.git/MERGE_HEAD', 'w') as head:
  409. with open('.git/MERGE_MSG', 'w') as msg:
  410. msg.write('repo: initial import of components\n\n')
  411. # head.write('%s\n' % startrev)
  412. for name in conf.repos:
  413. repo = conf.repos[name]
  414. # <upstream ref> <rewritten ref> <rewritten + files removed>
  415. msg.write('combo-layer-%s: %s %s %s\n' % (name,
  416. repo['last_revision'],
  417. repo['rewritten_revision'],
  418. repo['stripped_revision']))
  419. rev = runcmd('git rev-parse %s' % name).strip()
  420. head.write('%s\n' % rev)
  421. if conf.localconffile:
  422. localadded = True
  423. try:
  424. runcmd("git rm --cached %s" % conf.localconffile, printerr=False)
  425. except subprocess.CalledProcessError:
  426. localadded = False
  427. if localadded:
  428. localrelpath = os.path.relpath(conf.localconffile)
  429. runcmd("grep -q %s .gitignore || echo %s >> .gitignore" % (localrelpath, localrelpath))
  430. runcmd("git add .gitignore")
  431. logger.info("Added local configuration file %s to .gitignore", localrelpath)
  432. logger.info("Initial combo layer repository data has been created; please make any changes if desired and then use 'git commit' to make the initial commit.")
  433. else:
  434. logger.info("Repository already initialised, nothing to do.")
  435. def check_repo_clean(repodir):
  436. """
  437. check if the repo is clean
  438. exit if repo is dirty
  439. """
  440. output=runcmd("git status --porcelain", repodir)
  441. r = re.compile('\?\? patch-.*/')
  442. dirtyout = [item for item in output.splitlines() if not r.match(item)]
  443. if dirtyout:
  444. logger.error("git repo %s is dirty, please fix it first", repodir)
  445. sys.exit(1)
  446. def check_patch(patchfile):
  447. f = open(patchfile)
  448. ln = f.readline()
  449. of = None
  450. in_patch = False
  451. beyond_msg = False
  452. pre_buf = ''
  453. while ln:
  454. if not beyond_msg:
  455. if ln == '---\n':
  456. if not of:
  457. break
  458. in_patch = False
  459. beyond_msg = True
  460. elif ln.startswith('--- '):
  461. # We have a diff in the commit message
  462. in_patch = True
  463. if not of:
  464. print('WARNING: %s contains a diff in its commit message, indenting to avoid failure during apply' % patchfile)
  465. of = open(patchfile + '.tmp', 'w')
  466. of.write(pre_buf)
  467. pre_buf = ''
  468. elif in_patch and not ln[0] in '+-@ \n\r':
  469. in_patch = False
  470. if of:
  471. if in_patch:
  472. of.write(' ' + ln)
  473. else:
  474. of.write(ln)
  475. else:
  476. pre_buf += ln
  477. ln = f.readline()
  478. f.close()
  479. if of:
  480. of.close()
  481. os.rename(patchfile + '.tmp', patchfile)
  482. def drop_to_shell(workdir=None):
  483. if not sys.stdin.isatty():
  484. print("Not a TTY so can't drop to shell for resolution, exiting.")
  485. return False
  486. shell = os.environ.get('SHELL', 'bash')
  487. print('Dropping to shell "%s"\n' \
  488. 'When you are finished, run the following to continue:\n' \
  489. ' exit -- continue to apply the patches\n' \
  490. ' exit 1 -- abort\n' % shell);
  491. ret = subprocess.call([shell], cwd=workdir)
  492. if ret != 0:
  493. print("Aborting")
  494. return False
  495. else:
  496. return True
  497. def check_rev_branch(component, repodir, rev, branch):
  498. try:
  499. actualbranch = runcmd("git branch --contains %s" % rev, repodir, printerr=False)
  500. except subprocess.CalledProcessError as e:
  501. if e.returncode == 129:
  502. actualbranch = ""
  503. else:
  504. raise
  505. if not actualbranch:
  506. logger.error("%s: specified revision %s is invalid!" % (component, rev))
  507. return False
  508. branches = []
  509. branchlist = actualbranch.split("\n")
  510. for b in branchlist:
  511. branches.append(b.strip().split(' ')[-1])
  512. if branch not in branches:
  513. logger.error("%s: specified revision %s is not on specified branch %s!" % (component, rev, branch))
  514. return False
  515. return True
  516. def get_repos(conf, repo_names):
  517. repos = []
  518. for name in repo_names:
  519. if name.startswith('-'):
  520. break
  521. else:
  522. repos.append(name)
  523. for repo in repos:
  524. if not repo in conf.repos:
  525. logger.error("Specified component '%s' not found in configuration" % repo)
  526. sys.exit(1)
  527. if not repos:
  528. repos = [ repo for repo in conf.repos if conf.repos[repo].get("update", True) ]
  529. return repos
  530. def action_pull(conf, args):
  531. """
  532. update the component repos only
  533. """
  534. repos = get_repos(conf, args[1:])
  535. # make sure all repos are clean
  536. for name in repos:
  537. check_repo_clean(conf.repos[name]['local_repo_dir'])
  538. for name in repos:
  539. repo = conf.repos[name]
  540. ldir = repo['local_repo_dir']
  541. branch = repo.get('branch', "master")
  542. logger.info("update branch %s of component repo %s in %s ..." % (branch, name, ldir))
  543. if not conf.hard_reset:
  544. # Try to pull only the configured branch. Beware that this may fail
  545. # when the branch is currently unknown (for example, after reconfiguring
  546. # combo-layer). In that case we need to fetch everything and try the check out
  547. # and pull again.
  548. try:
  549. runcmd("git checkout %s" % branch, ldir, printerr=False)
  550. except subprocess.CalledProcessError:
  551. output=runcmd("git fetch", ldir)
  552. logger.info(output)
  553. runcmd("git checkout %s" % branch, ldir)
  554. runcmd("git pull --ff-only", ldir)
  555. else:
  556. output=runcmd("git pull --ff-only", ldir)
  557. logger.info(output)
  558. else:
  559. output=runcmd("git fetch", ldir)
  560. logger.info(output)
  561. runcmd("git checkout %s" % branch, ldir)
  562. runcmd("git reset --hard FETCH_HEAD", ldir)
  563. def action_update(conf, args):
  564. """
  565. update the component repos
  566. either:
  567. generate the patch list
  568. apply the generated patches
  569. or:
  570. re-creates the entire component history and merges them
  571. into the current branch with a merge commit
  572. """
  573. components = [arg.split(':')[0] for arg in args[1:]]
  574. revisions = {}
  575. for arg in args[1:]:
  576. if ':' in arg:
  577. a = arg.split(':', 1)
  578. revisions[a[0]] = a[1]
  579. repos = get_repos(conf, components)
  580. # make sure combo repo is clean
  581. check_repo_clean(os.getcwd())
  582. # Check whether we keep the component histories. Must be
  583. # set either via --history command line parameter or consistently
  584. # in combo-layer.conf. Mixing modes is (currently, and probably
  585. # permanently because it would be complicated) not supported.
  586. if conf.history:
  587. history = True
  588. else:
  589. history = None
  590. for name in repos:
  591. repo = conf.repos[name]
  592. repo_history = repo.get('history', False)
  593. if history is None:
  594. history = repo_history
  595. elif history != repo_history:
  596. logger.error("'history' property is set inconsistently")
  597. sys.exit(1)
  598. # Step 1: update the component repos
  599. if conf.nopull:
  600. logger.info("Skipping pull (-n)")
  601. else:
  602. action_pull(conf, ['arg0'] + components)
  603. if history:
  604. update_with_history(conf, components, revisions, repos)
  605. else:
  606. update_with_patches(conf, components, revisions, repos)
  607. def update_with_patches(conf, components, revisions, repos):
  608. import uuid
  609. patch_dir = "patch-%s" % uuid.uuid4()
  610. if not os.path.exists(patch_dir):
  611. os.mkdir(patch_dir)
  612. for name in repos:
  613. revision = revisions.get(name, None)
  614. repo = conf.repos[name]
  615. ldir = repo['local_repo_dir']
  616. dest_dir = repo['dest_dir']
  617. branch = repo.get('branch', "master")
  618. repo_patch_dir = os.path.join(os.getcwd(), patch_dir, name)
  619. # Step 2: generate the patch list and store to patch dir
  620. logger.info("Generating patches from %s..." % name)
  621. top_revision = revision or branch
  622. if not check_rev_branch(name, ldir, top_revision, branch):
  623. sys.exit(1)
  624. if dest_dir != ".":
  625. prefix = "--src-prefix=a/%s/ --dst-prefix=b/%s/" % (dest_dir, dest_dir)
  626. else:
  627. prefix = ""
  628. if repo['last_revision'] == "":
  629. logger.info("Warning: last_revision of component %s is not set, starting from the first commit" % name)
  630. patch_cmd_range = "--root %s" % top_revision
  631. rev_cmd_range = top_revision
  632. else:
  633. if not check_rev_branch(name, ldir, repo['last_revision'], branch):
  634. sys.exit(1)
  635. patch_cmd_range = "%s..%s" % (repo['last_revision'], top_revision)
  636. rev_cmd_range = patch_cmd_range
  637. file_filter = repo.get('file_filter',".")
  638. # Filter out unwanted files
  639. exclude = repo.get('file_exclude', '')
  640. if exclude:
  641. for path in exclude.split():
  642. p = "%s/%s" % (dest_dir, path) if dest_dir != '.' else path
  643. file_filter += " ':!%s'" % p
  644. patch_cmd = "git format-patch -N %s --output-directory %s %s -- %s" % \
  645. (prefix,repo_patch_dir, patch_cmd_range, file_filter)
  646. output = runcmd(patch_cmd, ldir)
  647. logger.debug("generated patch set:\n%s" % output)
  648. patchlist = output.splitlines()
  649. rev_cmd = "git rev-list --no-merges %s -- %s" % (rev_cmd_range, file_filter)
  650. revlist = runcmd(rev_cmd, ldir).splitlines()
  651. # Step 3: Call repo specific hook to adjust patch
  652. if 'hook' in repo:
  653. # hook parameter is: ./hook patchpath revision reponame
  654. count=len(revlist)-1
  655. for patch in patchlist:
  656. runcmd("%s %s %s %s" % (repo['hook'], patch, revlist[count], name))
  657. count=count-1
  658. # Step 4: write patch list and revision list to file, for user to edit later
  659. patchlist_file = os.path.join(os.getcwd(), patch_dir, "patchlist-%s" % name)
  660. repo['patchlist'] = patchlist_file
  661. f = open(patchlist_file, 'w')
  662. count=len(revlist)-1
  663. for patch in patchlist:
  664. f.write("%s %s\n" % (patch, revlist[count]))
  665. check_patch(os.path.join(patch_dir, patch))
  666. count=count-1
  667. f.close()
  668. # Step 5: invoke bash for user to edit patch and patch list
  669. if conf.interactive:
  670. print('You may now edit the patch and patch list in %s\n' \
  671. 'For example, you can remove unwanted patch entries from patchlist-*, so that they will be not applied later' % patch_dir);
  672. if not drop_to_shell(patch_dir):
  673. sys.exit(1)
  674. # Step 6: apply the generated and revised patch
  675. apply_patchlist(conf, repos)
  676. runcmd("rm -rf %s" % patch_dir)
  677. # Step 7: commit the updated config file if it's being tracked
  678. commit_conf_file(conf, components)
  679. def conf_commit_msg(conf, components):
  680. # create the "components" string
  681. component_str = "all components"
  682. if len(components) > 0:
  683. # otherwise tell which components were actually changed
  684. component_str = ", ".join(components)
  685. # expand the template with known values
  686. template = Template(conf.commit_msg_template)
  687. msg = template.substitute(components = component_str)
  688. return msg
  689. def commit_conf_file(conf, components, commit=True):
  690. relpath = os.path.relpath(conf.conffile)
  691. try:
  692. output = runcmd("git status --porcelain %s" % relpath, printerr=False)
  693. except:
  694. # Outside the repository
  695. output = None
  696. if output:
  697. if output.lstrip().startswith("M"):
  698. logger.info("Committing updated configuration file")
  699. if commit:
  700. msg = conf_commit_msg(conf, components)
  701. runcmd('git commit -m'.split() + [msg, relpath])
  702. else:
  703. runcmd('git add %s' % relpath)
  704. return True
  705. return False
  706. def apply_patchlist(conf, repos):
  707. """
  708. apply the generated patch list to combo repo
  709. """
  710. for name in repos:
  711. repo = conf.repos[name]
  712. lastrev = repo["last_revision"]
  713. prevrev = lastrev
  714. # Get non-blank lines from patch list file
  715. patchlist = []
  716. if os.path.exists(repo['patchlist']) or not conf.interactive:
  717. # Note: we want this to fail here if the file doesn't exist and we're not in
  718. # interactive mode since the file should exist in this case
  719. with open(repo['patchlist']) as f:
  720. for line in f:
  721. line = line.rstrip()
  722. if line:
  723. patchlist.append(line)
  724. ldir = conf.repos[name]['local_repo_dir']
  725. branch = conf.repos[name].get('branch', "master")
  726. branchrev = runcmd("git rev-parse %s" % branch, ldir).strip()
  727. if patchlist:
  728. logger.info("Applying patches from %s..." % name)
  729. linecount = len(patchlist)
  730. i = 1
  731. for line in patchlist:
  732. patchfile = line.split()[0]
  733. lastrev = line.split()[1]
  734. patchdisp = os.path.relpath(patchfile)
  735. if os.path.getsize(patchfile) == 0:
  736. logger.info("(skipping %d/%d %s - no changes)" % (i, linecount, patchdisp))
  737. else:
  738. cmd = "git am --keep-cr %s-p1 %s" % ('-s ' if repo.get('signoff', True) else '', patchfile)
  739. logger.info("Applying %d/%d: %s" % (i, linecount, patchdisp))
  740. try:
  741. runcmd(cmd)
  742. except subprocess.CalledProcessError:
  743. logger.info('Running "git am --abort" to cleanup repo')
  744. runcmd("git am --abort")
  745. logger.error('"%s" failed' % cmd)
  746. logger.info("Please manually apply patch %s" % patchdisp)
  747. logger.info("Note: if you exit and continue applying without manually applying the patch, it will be skipped")
  748. if not drop_to_shell():
  749. if prevrev != repo['last_revision']:
  750. conf.update(name, "last_revision", prevrev)
  751. sys.exit(1)
  752. prevrev = lastrev
  753. i += 1
  754. # Once all patches are applied, we should update
  755. # last_revision to the branch head instead of the last
  756. # applied patch. The two are not necessarily the same when
  757. # the last commit is a merge commit or when the patches at
  758. # the branch head were intentionally excluded.
  759. #
  760. # If we do not do that for a merge commit, the next
  761. # combo-layer run will only exclude patches reachable from
  762. # one of the merged branches and try to re-apply patches
  763. # from other branches even though they were already
  764. # copied.
  765. #
  766. # If patches were intentionally excluded, the next run will
  767. # present them again instead of skipping over them. This
  768. # may or may not be intended, so the code here is conservative
  769. # and only addresses the "head is merge commit" case.
  770. if lastrev != branchrev and \
  771. len(runcmd("git show --pretty=format:%%P --no-patch %s" % branch, ldir).split()) > 1:
  772. lastrev = branchrev
  773. else:
  774. logger.info("No patches to apply from %s" % name)
  775. lastrev = branchrev
  776. if lastrev != repo['last_revision']:
  777. conf.update(name, "last_revision", lastrev)
  778. def action_splitpatch(conf, args):
  779. """
  780. generate the commit patch and
  781. split the patch per repo
  782. """
  783. logger.debug("action_splitpatch")
  784. if len(args) > 1:
  785. commit = args[1]
  786. else:
  787. commit = "HEAD"
  788. patchdir = "splitpatch-%s" % commit
  789. if not os.path.exists(patchdir):
  790. os.mkdir(patchdir)
  791. # filerange_root is for the repo whose dest_dir is root "."
  792. # and it should be specified by excluding all other repo dest dir
  793. # like "-x repo1 -x repo2 -x repo3 ..."
  794. filerange_root = ""
  795. for name in conf.repos:
  796. dest_dir = conf.repos[name]['dest_dir']
  797. if dest_dir != ".":
  798. filerange_root = '%s -x "%s/*"' % (filerange_root, dest_dir)
  799. for name in conf.repos:
  800. dest_dir = conf.repos[name]['dest_dir']
  801. patch_filename = "%s/%s.patch" % (patchdir, name)
  802. if dest_dir == ".":
  803. cmd = "git format-patch -n1 --stdout %s^..%s | filterdiff -p1 %s > %s" % (commit, commit, filerange_root, patch_filename)
  804. else:
  805. cmd = "git format-patch --no-prefix -n1 --stdout %s^..%s -- %s > %s" % (commit, commit, dest_dir, patch_filename)
  806. runcmd(cmd)
  807. # Detect empty patches (including those produced by filterdiff above
  808. # that contain only preamble text)
  809. if os.path.getsize(patch_filename) == 0 or runcmd("filterdiff %s" % patch_filename) == "":
  810. os.remove(patch_filename)
  811. logger.info("(skipping %s - no changes)", name)
  812. else:
  813. logger.info(patch_filename)
  814. def update_with_history(conf, components, revisions, repos):
  815. '''Update all components with full history.
  816. Works by importing all commits reachable from a component's
  817. current head revision. If those commits are rooted in an already
  818. imported commit, their content gets mixed with the content of the
  819. combined repo of that commit (new or modified files overwritten,
  820. removed files removed).
  821. The last commit is an artificial merge commit that merges all the
  822. updated components into the combined repository.
  823. The HEAD ref only gets updated at the very end. All intermediate work
  824. happens in a worktree which will get garbage collected by git eventually
  825. after a failure.
  826. '''
  827. # Remember current HEAD and what we need to add to it.
  828. head = runcmd("git rev-parse HEAD").strip()
  829. additional_heads = {}
  830. # Track the mapping between original commit and commit in the
  831. # combined repo. We do not have to distinguish between components,
  832. # because commit hashes are different anyway. Often we can
  833. # skip find_revs() entirely (for example, when all new commits
  834. # are derived from the last imported revision).
  835. #
  836. # Using "head" (typically the merge commit) instead of the actual
  837. # commit for the component leads to a nicer history in the combined
  838. # repo.
  839. old2new_revs = {}
  840. for name in repos:
  841. repo = conf.repos[name]
  842. revision = repo['last_revision']
  843. if revision:
  844. old2new_revs[revision] = head
  845. def add_p(parents):
  846. '''Insert -p before each entry.'''
  847. parameters = []
  848. for p in parents:
  849. parameters.append('-p')
  850. parameters.append(p)
  851. return parameters
  852. # Do all intermediate work with a separate work dir and index,
  853. # chosen via env variables (can't use "git worktree", it is too
  854. # new). This is useful (no changes to current work tree unless the
  855. # update succeeds) and required (otherwise we end up temporarily
  856. # removing the combo-layer hooks that we currently use when
  857. # importing a new component).
  858. #
  859. # Not cleaned up after a failure at the moment.
  860. wdir = os.path.join(os.getcwd(), ".git", "combo-layer")
  861. windex = wdir + ".index"
  862. if os.path.isdir(wdir):
  863. shutil.rmtree(wdir)
  864. os.mkdir(wdir)
  865. wenv = copy.deepcopy(os.environ)
  866. wenv["GIT_WORK_TREE"] = wdir
  867. wenv["GIT_INDEX_FILE"] = windex
  868. # This one turned out to be needed in practice.
  869. wenv["GIT_OBJECT_DIRECTORY"] = os.path.join(os.getcwd(), ".git", "objects")
  870. wargs = {"destdir": wdir, "env": wenv}
  871. for name in repos:
  872. revision = revisions.get(name, None)
  873. repo = conf.repos[name]
  874. ldir = repo['local_repo_dir']
  875. dest_dir = repo['dest_dir']
  876. branch = repo.get('branch', "master")
  877. hook = repo.get('hook', None)
  878. largs = {"destdir": ldir, "env": None}
  879. file_include = repo.get('file_filter', '').split()
  880. file_include.sort() # make sure that short entries like '.' come first.
  881. file_exclude = repo.get('file_exclude', '').split()
  882. def include_file(file):
  883. if not file_include:
  884. # No explicit filter set, include file.
  885. return True
  886. for filter in file_include:
  887. if filter == '.':
  888. # Another special case: include current directory and thus all files.
  889. return True
  890. if os.path.commonprefix((filter, file)) == filter:
  891. # Included in directory or direct file match.
  892. return True
  893. # Check for wildcard match *with* allowing * to match /, i.e.
  894. # src/*.c does match src/foobar/*.c. That's not how it is done elsewhere
  895. # when passing the filtering to "git archive", but it is unclear what
  896. # the intended semantic is (the comment on file_exclude that "append a * wildcard
  897. # at the end" to match the full content of a directories implies that
  898. # slashes are indeed not special), so here we simply do what's easy to
  899. # implement in Python.
  900. logger.debug('fnmatch(%s, %s)' % (file, filter))
  901. if fnmatch.fnmatchcase(file, filter):
  902. return True
  903. return False
  904. def exclude_file(file):
  905. for filter in file_exclude:
  906. if fnmatch.fnmatchcase(file, filter):
  907. return True
  908. return False
  909. def file_filter(files):
  910. '''Clean up file list so that only included files remain.'''
  911. index = 0
  912. while index < len(files):
  913. file = files[index]
  914. if not include_file(file) or exclude_file(file):
  915. del files[index]
  916. else:
  917. index += 1
  918. # Generate the revision list.
  919. logger.info("Analyzing commits from %s..." % name)
  920. top_revision = revision or branch
  921. if not check_rev_branch(name, ldir, top_revision, branch):
  922. sys.exit(1)
  923. last_revision = repo['last_revision']
  924. rev_list_args = "--full-history --sparse --topo-order --reverse"
  925. if not last_revision:
  926. logger.info("Warning: last_revision of component %s is not set, starting from the first commit" % name)
  927. rev_list_args = rev_list_args + ' ' + top_revision
  928. else:
  929. if not check_rev_branch(name, ldir, last_revision, branch):
  930. sys.exit(1)
  931. rev_list_args = "%s %s..%s" % (rev_list_args, last_revision, top_revision)
  932. # By definition, the current HEAD contains the latest imported
  933. # commit of each component. We use that as initial mapping even
  934. # though the commits do not match exactly because
  935. # a) it always works (in contrast to find_revs, which relies on special
  936. # commit messages)
  937. # b) it is faster than find_revs, which will only be called on demand
  938. # and can be skipped entirely in most cases
  939. # c) last but not least, the combined history looks nicer when all
  940. # new commits are rooted in the same merge commit
  941. old2new_revs[last_revision] = head
  942. # We care about all commits (--full-history and --sparse) and
  943. # we want reconstruct the topology and thus do not care
  944. # about ordering by time (--topo-order). We ask for the ones
  945. # we need to import first to be listed first (--reverse).
  946. revs = runcmd("git rev-list %s" % rev_list_args, **largs).split()
  947. logger.debug("To be imported: %s" % revs)
  948. # Now 'revs' contains all revisions reachable from the top revision.
  949. # All revisions derived from the 'last_revision' definitely are new,
  950. # whereas the others may or may not have been imported before. For
  951. # a linear history in the component, that second set will be empty.
  952. # To distinguish between them, we also get the shorter list
  953. # of revisions starting at the ancestor.
  954. if last_revision:
  955. ancestor_revs = runcmd("git rev-list --ancestry-path %s" % rev_list_args, **largs).split()
  956. else:
  957. ancestor_revs = []
  958. logger.debug("Ancestors: %s" % ancestor_revs)
  959. # Now import each revision.
  960. logger.info("Importing commits from %s..." % name)
  961. def import_rev(rev):
  962. global scanned_revs
  963. # If it is part of the new commits, we definitely need
  964. # to import it. Otherwise we need to check, we might have
  965. # imported it before. If it was imported and we merely
  966. # fail to find it because commit messages did not track
  967. # the mapping, then we end up importing it again. So
  968. # combined repos using "updating with history" really should
  969. # enable the "From ... rev:" commit header modifications.
  970. if rev not in ancestor_revs and rev not in old2new_revs and not scanned_revs:
  971. logger.debug("Revision %s triggers log analysis." % rev)
  972. find_revs(old2new_revs, head)
  973. scanned_revs = True
  974. new_rev = old2new_revs.get(rev, None)
  975. if new_rev:
  976. return new_rev
  977. # If the commit is not in the original list of revisions
  978. # to be imported, then it must be a parent of one of those
  979. # commits and it was skipped during earlier imports or not
  980. # found. Importing such merge commits leads to very ugly
  981. # history (long cascade of merge commits which all point
  982. # to to older commits) when switching from "update via
  983. # patches" to "update with history".
  984. #
  985. # We can avoid importing merge commits if all non-merge commits
  986. # reachable from it were already imported. In that case we
  987. # can root the new commits in the current head revision.
  988. def is_imported(prev):
  989. parents = runcmd("git show --no-patch --pretty=format:%P " + prev, **largs).split()
  990. if len(parents) > 1:
  991. for p in parents:
  992. if not is_imported(p):
  993. logger.debug("Must import %s because %s is not imported." % (rev, p))
  994. return False
  995. return True
  996. elif prev in old2new_revs:
  997. return True
  998. else:
  999. logger.debug("Must import %s because %s is not imported." % (rev, prev))
  1000. return False
  1001. if rev not in revs and is_imported(rev):
  1002. old2new_revs[rev] = head
  1003. return head
  1004. # Need to import rev. Collect some information about it.
  1005. logger.debug("Importing %s" % rev)
  1006. (parents, author_name, author_email, author_timestamp, body) = \
  1007. runcmd("git show --no-patch --pretty=format:%P%x00%an%x00%ae%x00%at%x00%B " + rev, **largs).split(chr(0))
  1008. parents = parents.split()
  1009. if parents:
  1010. # Arbitrarily pick the first parent as base. It may or may not have
  1011. # been imported before. For example, if the parent is a merge commit
  1012. # and previously the combined repository used patching as update
  1013. # method, then the actual merge commit parent never was imported.
  1014. # To cover this, We recursively import parents.
  1015. parent = parents[0]
  1016. new_parent = import_rev(parent)
  1017. # Clean index and working tree. TODO: can we combine this and the
  1018. # next into one command with less file IO?
  1019. # "git reset --hard" does not work, it changes HEAD of the parent
  1020. # repo, which we wanted to avoid. Probably need to keep
  1021. # track of the rev that corresponds to the index and use apply_commit().
  1022. runcmd("git rm -q --ignore-unmatch -rf .", **wargs)
  1023. # Update index and working tree to match the parent.
  1024. runcmd("git checkout -q -f %s ." % new_parent, **wargs)
  1025. else:
  1026. parent = None
  1027. # Clean index and working tree.
  1028. runcmd("git rm -q --ignore-unmatch -rf .", **wargs)
  1029. # Modify index and working tree such that it mirrors the commit.
  1030. apply_commit(parent, rev, largs, wargs, dest_dir, file_filter=file_filter)
  1031. # Now commit.
  1032. new_tree = runcmd("git write-tree", **wargs).strip()
  1033. env = copy.deepcopy(wenv)
  1034. env['GIT_AUTHOR_NAME'] = author_name
  1035. env['GIT_AUTHOR_EMAIL'] = author_email
  1036. env['GIT_AUTHOR_DATE'] = author_timestamp
  1037. if hook:
  1038. # Need to turn the verbatim commit message into something resembling a patch header
  1039. # for the hook.
  1040. with tempfile.NamedTemporaryFile(delete=False) as patch:
  1041. patch.write('Subject: [PATCH] ')
  1042. patch.write(body)
  1043. patch.write('\n---\n')
  1044. patch.close()
  1045. runcmd([hook, patch.name, rev, name])
  1046. with open(patch.name) as f:
  1047. body = f.read()[len('Subject: [PATCH] '):][:-len('\n---\n')]
  1048. # We can skip non-merge commits that did not change any files. Those are typically
  1049. # the result of file filtering, although they could also have been introduced
  1050. # intentionally upstream, in which case we drop some information here.
  1051. if len(parents) == 1:
  1052. parent_rev = import_rev(parents[0])
  1053. old_tree = runcmd("git show -s --pretty=format:%T " + parent_rev, **wargs).strip()
  1054. commit = old_tree != new_tree
  1055. if not commit:
  1056. new_rev = parent_rev
  1057. else:
  1058. commit = True
  1059. if commit:
  1060. new_rev = runcmd("git commit-tree".split() + add_p([import_rev(p) for p in parents]) +
  1061. ["-m", body, new_tree],
  1062. env=env).strip()
  1063. old2new_revs[rev] = new_rev
  1064. return new_rev
  1065. if revs:
  1066. for rev in revs:
  1067. import_rev(rev)
  1068. # Remember how to update our current head. New components get added,
  1069. # updated components get the delta between current head and the updated component
  1070. # applied.
  1071. additional_heads[old2new_revs[revs[-1]]] = head if repo['last_revision'] else None
  1072. repo['last_revision'] = revs[-1]
  1073. # Now construct the final merge commit. We create the tree by
  1074. # starting with the head and applying the changes from each
  1075. # components imported head revision.
  1076. if additional_heads:
  1077. runcmd("git reset --hard", **wargs)
  1078. for rev, base in additional_heads.iteritems():
  1079. apply_commit(base, rev, wargs, wargs, None)
  1080. # Commit with all component branches as parents as well as the previous head.
  1081. logger.info("Writing final merge commit...")
  1082. msg = conf_commit_msg(conf, components)
  1083. new_tree = runcmd("git write-tree", **wargs).strip()
  1084. new_rev = runcmd("git commit-tree".split() +
  1085. add_p([head] + additional_heads.keys()) +
  1086. ["-m", msg, new_tree],
  1087. **wargs).strip()
  1088. # And done! This is the first time we change the HEAD in the actual work tree.
  1089. runcmd("git reset --hard %s" % new_rev)
  1090. # Update and stage the (potentially modified)
  1091. # combo-layer.conf, but do not commit separately.
  1092. for name in repos:
  1093. repo = conf.repos[name]
  1094. rev = repo['last_revision']
  1095. conf.update(name, "last_revision", rev)
  1096. if commit_conf_file(conf, components, False):
  1097. # Must augment the previous commit.
  1098. runcmd("git commit --amend -C HEAD")
  1099. scanned_revs = False
  1100. def find_revs(old2new, head):
  1101. '''Construct mapping from original commit hash to commit hash in
  1102. combined repo by looking at the commit messages. Depends on the
  1103. "From ... rev: ..." convention.'''
  1104. logger.info("Analyzing log messages to find previously imported commits...")
  1105. num_known = len(old2new)
  1106. log = runcmd("git log --grep='From .* rev: [a-fA-F0-9][a-fA-F0-9]*' --pretty=format:%H%x00%B%x00 " + head).split(chr(0))
  1107. regex = re.compile(r'From .* rev: ([a-fA-F0-9]+)')
  1108. for new_rev, body in zip(*[iter(log)]* 2):
  1109. # Use the last one, in the unlikely case there are more than one.
  1110. rev = regex.findall(body)[-1]
  1111. if rev not in old2new:
  1112. old2new[rev] = new_rev.strip()
  1113. logger.info("Found %d additional commits, leading to: %s" % (len(old2new) - num_known, old2new))
  1114. def apply_commit(parent, rev, largs, wargs, dest_dir, file_filter=None):
  1115. '''Compare revision against parent, remove files deleted in the
  1116. commit, re-write new or modified ones. Moves them into dest_dir.
  1117. Optionally filters files.
  1118. '''
  1119. if not dest_dir:
  1120. dest_dir = "."
  1121. # -r recurses into sub-directories, given is the full overview of
  1122. # what changed. We do not care about copy/edits or renames, so we
  1123. # can disable those with --no-renames (but we still parse them,
  1124. # because it was not clear from git documentation whether C and M
  1125. # lines can still occur).
  1126. logger.debug("Applying changes between %s and %s in %s" % (parent, rev, largs["destdir"]))
  1127. delete = []
  1128. update = []
  1129. if parent:
  1130. # Apply delta.
  1131. changes = runcmd("git diff-tree --no-commit-id --no-renames --name-status -r --raw -z %s %s" % (parent, rev), **largs).split(chr(0))
  1132. for status, name in zip(*[iter(changes)]*2):
  1133. if status[0] in "ACMRT":
  1134. update.append(name)
  1135. elif status[0] in "D":
  1136. delete.append(name)
  1137. else:
  1138. logger.error("Unknown status %s of file %s in revision %s" % (status, name, rev))
  1139. sys.exit(1)
  1140. else:
  1141. # Copy all files.
  1142. update.extend(runcmd("git ls-tree -r --name-only -z %s" % rev, **largs).split(chr(0)))
  1143. # Include/exclude files as define in the component config.
  1144. # Both updated and deleted file lists get filtered, because it might happen
  1145. # that a file gets excluded, pulled from a different component, and then the
  1146. # excluded file gets deleted. In that case we must keep the copy.
  1147. if file_filter:
  1148. file_filter(update)
  1149. file_filter(delete)
  1150. # We export into a tar archive here and extract with tar because it is simple (no
  1151. # need to implement file and symlink writing ourselves) and gives us some degree
  1152. # of parallel IO. The downside is that we have to pass the list of files via
  1153. # command line parameters - hopefully there will never be too many at once.
  1154. if update:
  1155. target = os.path.join(wargs["destdir"], dest_dir)
  1156. if not os.path.isdir(target):
  1157. os.makedirs(target)
  1158. quoted_target = pipes.quote(target)
  1159. # os.sysconf('SC_ARG_MAX') is lying: running a command with
  1160. # string length 629343 already failed with "Argument list too
  1161. # long" although SC_ARG_MAX = 2097152. "man execve" explains
  1162. # the limitations, but those are pretty complicated. So here
  1163. # we just hard-code a fixed value which is more likely to work.
  1164. max_cmdsize = 64 * 1024
  1165. while update:
  1166. quoted_args = []
  1167. unquoted_args = []
  1168. cmdsize = 100 + len(quoted_target)
  1169. while update:
  1170. quoted_next = pipes.quote(update[0])
  1171. size_next = len(quoted_next) + len(dest_dir) + 1
  1172. logger.debug('cmdline length %d + %d < %d?' % (cmdsize, size_next, os.sysconf('SC_ARG_MAX')))
  1173. if cmdsize + size_next < max_cmdsize:
  1174. quoted_args.append(quoted_next)
  1175. unquoted_args.append(update.pop(0))
  1176. cmdsize += size_next
  1177. else:
  1178. logger.debug('Breaking the cmdline at length %d' % cmdsize)
  1179. break
  1180. logger.debug('Final cmdline length %d / %d' % (cmdsize, os.sysconf('SC_ARG_MAX')))
  1181. cmd = "git archive %s %s | tar -C %s -xf -" % (rev, ' '.join(quoted_args), quoted_target)
  1182. logger.debug('First cmdline length %d' % len(cmd))
  1183. runcmd(cmd, **largs)
  1184. cmd = "git add -f".split() + [os.path.join(dest_dir, x) for x in unquoted_args]
  1185. logger.debug('Second cmdline length %d' % reduce(lambda x, y: x + len(y), cmd, 0))
  1186. runcmd(cmd, **wargs)
  1187. if delete:
  1188. for path in delete:
  1189. if dest_dir:
  1190. path = os.path.join(dest_dir, path)
  1191. runcmd("git rm -f --ignore-unmatch".split() + [os.path.join(dest_dir, x) for x in delete], **wargs)
  1192. def action_error(conf, args):
  1193. logger.info("invalid action %s" % args[0])
  1194. actions = {
  1195. "init": action_init,
  1196. "update": action_update,
  1197. "pull": action_pull,
  1198. "splitpatch": action_splitpatch,
  1199. }
  1200. def main():
  1201. parser = optparse.OptionParser(
  1202. version = "Combo Layer Repo Tool version %s" % __version__,
  1203. usage = """%prog [options] action
  1204. Create and update a combination layer repository from multiple component repositories.
  1205. Action:
  1206. init initialise the combo layer repo
  1207. update [components] get patches from component repos and apply them to the combo repo
  1208. pull [components] just pull component repos only
  1209. splitpatch [commit] generate commit patch and split per component, default commit is HEAD""")
  1210. parser.add_option("-c", "--conf", help = "specify the config file (conf/combo-layer.conf is the default).",
  1211. action = "store", dest = "conffile", default = "conf/combo-layer.conf")
  1212. parser.add_option("-i", "--interactive", help = "interactive mode, user can edit the patch list and patches",
  1213. action = "store_true", dest = "interactive", default = False)
  1214. parser.add_option("-D", "--debug", help = "output debug information",
  1215. action = "store_true", dest = "debug", default = False)
  1216. parser.add_option("-n", "--no-pull", help = "skip pulling component repos during update",
  1217. action = "store_true", dest = "nopull", default = False)
  1218. parser.add_option("--hard-reset",
  1219. help = "instead of pull do fetch and hard-reset in component repos",
  1220. action = "store_true", dest = "hard_reset", default = False)
  1221. parser.add_option("-H", "--history", help = "import full history of components during init",
  1222. action = "store_true", default = False)
  1223. options, args = parser.parse_args(sys.argv)
  1224. # Dispatch to action handler
  1225. if len(args) == 1:
  1226. logger.error("No action specified, exiting")
  1227. parser.print_help()
  1228. elif args[1] not in actions:
  1229. logger.error("Unsupported action %s, exiting\n" % (args[1]))
  1230. parser.print_help()
  1231. elif not os.path.exists(options.conffile):
  1232. logger.error("No valid config file, exiting\n")
  1233. parser.print_help()
  1234. else:
  1235. if options.debug:
  1236. logger.setLevel(logging.DEBUG)
  1237. confdata = Configuration(options)
  1238. initmode = (args[1] == 'init')
  1239. confdata.sanity_check(initmode)
  1240. actions.get(args[1], action_error)(confdata, args[1:])
  1241. if __name__ == "__main__":
  1242. try:
  1243. ret = main()
  1244. except Exception:
  1245. ret = 1
  1246. import traceback
  1247. traceback.print_exc()
  1248. sys.exit(ret)