combo-layer 60 KB

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