combo-layer 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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. from collections import OrderedDict
  31. __version__ = "0.2.1"
  32. def logger_create():
  33. logger = logging.getLogger("")
  34. loggerhandler = logging.StreamHandler()
  35. loggerhandler.setFormatter(logging.Formatter("[%(asctime)s] %(message)s","%H:%M:%S"))
  36. logger.addHandler(loggerhandler)
  37. logger.setLevel(logging.INFO)
  38. return logger
  39. logger = logger_create()
  40. def get_current_branch(repodir=None):
  41. try:
  42. if not os.path.exists(os.path.join(repodir if repodir else '', ".git")):
  43. # Repo not created yet (i.e. during init) so just assume master
  44. return "master"
  45. branchname = runcmd("git symbolic-ref HEAD 2>/dev/null", repodir).strip()
  46. if branchname.startswith("refs/heads/"):
  47. branchname = branchname[11:]
  48. return branchname
  49. except subprocess.CalledProcessError:
  50. return ""
  51. class Configuration(object):
  52. """
  53. Manages the configuration
  54. For an example config file, see combo-layer.conf.example
  55. """
  56. def __init__(self, options):
  57. for key, val in options.__dict__.items():
  58. setattr(self, key, val)
  59. def readsection(parser, section, repo):
  60. for (name, value) in parser.items(section):
  61. if value.startswith("@"):
  62. self.repos[repo][name] = eval(value.strip("@"))
  63. else:
  64. # Apply special type transformations for some properties.
  65. # Type matches the RawConfigParser.get*() methods.
  66. types = {'signoff': 'boolean'}
  67. if name in types:
  68. value = getattr(parser, 'get' + types[name])(section, name)
  69. self.repos[repo][name] = value
  70. logger.debug("Loading config file %s" % self.conffile)
  71. self.parser = ConfigParser.ConfigParser()
  72. with open(self.conffile) as f:
  73. self.parser.readfp(f)
  74. self.repos = {}
  75. for repo in self.parser.sections():
  76. self.repos[repo] = {}
  77. readsection(self.parser, repo, repo)
  78. # Load local configuration, if available
  79. self.localconffile = None
  80. self.localparser = None
  81. self.combobranch = None
  82. if self.conffile.endswith('.conf'):
  83. lcfile = self.conffile.replace('.conf', '-local.conf')
  84. if os.path.exists(lcfile):
  85. # Read combo layer branch
  86. self.combobranch = get_current_branch()
  87. logger.debug("Combo layer branch is %s" % self.combobranch)
  88. self.localconffile = lcfile
  89. logger.debug("Loading local config file %s" % self.localconffile)
  90. self.localparser = ConfigParser.ConfigParser()
  91. with open(self.localconffile) as f:
  92. self.localparser.readfp(f)
  93. for section in self.localparser.sections():
  94. if '|' in section:
  95. sectionvals = section.split('|')
  96. repo = sectionvals[0]
  97. if sectionvals[1] != self.combobranch:
  98. continue
  99. else:
  100. repo = section
  101. if repo in self.repos:
  102. readsection(self.localparser, section, repo)
  103. def update(self, repo, option, value, initmode=False):
  104. # If the main config has the option already, that is what we
  105. # are expected to modify.
  106. if self.localparser and not self.parser.has_option(repo, option):
  107. parser = self.localparser
  108. section = "%s|%s" % (repo, self.combobranch)
  109. conffile = self.localconffile
  110. if initmode and not parser.has_section(section):
  111. parser.add_section(section)
  112. else:
  113. parser = self.parser
  114. section = repo
  115. conffile = self.conffile
  116. parser.set(section, option, value)
  117. with open(conffile, "w") as f:
  118. parser.write(f)
  119. self.repos[repo][option] = value
  120. def sanity_check(self, initmode=False):
  121. required_options=["src_uri", "local_repo_dir", "dest_dir", "last_revision"]
  122. if initmode:
  123. required_options.remove("last_revision")
  124. msg = ""
  125. missing_options = []
  126. for name in self.repos:
  127. for option in required_options:
  128. if option not in self.repos[name]:
  129. msg = "%s\nOption %s is not defined for component %s" %(msg, option, name)
  130. missing_options.append(option)
  131. # Sanitize dest_dir so that we do not have to deal with edge cases
  132. # (unset, empty string, double slashes) in the rest of the code.
  133. # It not being set will still be flagged as error because it is
  134. # listed as required option above; that could be changed now.
  135. dest_dir = os.path.normpath(self.repos[name].get("dest_dir", "."))
  136. self.repos[name]["dest_dir"] = "." if not dest_dir else dest_dir
  137. if msg != "":
  138. logger.error("configuration file %s has the following error: %s" % (self.conffile,msg))
  139. if self.localconffile and 'last_revision' in missing_options:
  140. logger.error("local configuration file %s may be missing configuration for combo branch %s" % (self.localconffile, self.combobranch))
  141. sys.exit(1)
  142. # filterdiff is required by action_splitpatch, so check its availability
  143. if subprocess.call("which filterdiff > /dev/null 2>&1", shell=True) != 0:
  144. logger.error("ERROR: patchutils package is missing, please install it (e.g. # apt-get install patchutils)")
  145. sys.exit(1)
  146. def runcmd(cmd,destdir=None,printerr=True,out=None):
  147. """
  148. execute command, raise CalledProcessError if fail
  149. return output if succeed
  150. """
  151. logger.debug("run cmd '%s' in %s" % (cmd, os.getcwd() if destdir is None else destdir))
  152. if not out:
  153. out = os.tmpfile()
  154. err = out
  155. else:
  156. err = os.tmpfile()
  157. try:
  158. subprocess.check_call(cmd, stdout=out, stderr=err, cwd=destdir, shell=isinstance(cmd, str))
  159. except subprocess.CalledProcessError,e:
  160. err.seek(0)
  161. if printerr:
  162. logger.error("%s" % err.read())
  163. raise e
  164. err.seek(0)
  165. output = err.read()
  166. logger.debug("output: %s" % output )
  167. return output
  168. def action_init(conf, args):
  169. """
  170. Clone component repositories
  171. Check git is initialised; if not, copy initial data from component repos
  172. """
  173. for name in conf.repos:
  174. ldir = conf.repos[name]['local_repo_dir']
  175. if not os.path.exists(ldir):
  176. logger.info("cloning %s to %s" %(conf.repos[name]['src_uri'], ldir))
  177. subprocess.check_call("git clone %s %s" % (conf.repos[name]['src_uri'], ldir), shell=True)
  178. if not os.path.exists(".git"):
  179. runcmd("git init")
  180. if conf.history:
  181. # Need a common ref for all trees.
  182. runcmd('git commit -m "initial empty commit" --allow-empty')
  183. startrev = runcmd('git rev-parse master').strip()
  184. for name in conf.repos:
  185. repo = conf.repos[name]
  186. ldir = repo['local_repo_dir']
  187. branch = repo.get('branch', "master")
  188. lastrev = repo.get('last_revision', None)
  189. if lastrev and lastrev != "HEAD":
  190. initialrev = lastrev
  191. if branch:
  192. if not check_rev_branch(name, ldir, lastrev, branch):
  193. sys.exit(1)
  194. logger.info("Copying data from %s at specified revision %s..." % (name, lastrev))
  195. else:
  196. lastrev = None
  197. initialrev = branch
  198. logger.info("Copying data from %s..." % name)
  199. # Sanity check initialrev and turn it into hash (required for copying history,
  200. # because resolving a name ref only works in the component repo).
  201. rev = runcmd('git rev-parse %s' % initialrev, ldir).strip()
  202. if rev != initialrev:
  203. try:
  204. refs = runcmd('git show-ref -s %s' % initialrev, ldir).split('\n')
  205. if len(set(refs)) > 1:
  206. # Happens for example when configured to track
  207. # "master" and there is a refs/heads/master. The
  208. # traditional behavior from "git archive" (preserved
  209. # here) it to choose the first one. This might not be
  210. # intended, so at least warn about it.
  211. logger.warn("%s: initial revision '%s' not unique, picking result of rev-parse = %s" %
  212. (name, initialrev, refs[0]))
  213. initialrev = rev
  214. except:
  215. # show-ref fails for hashes. Skip the sanity warning in that case.
  216. pass
  217. initialrev = rev
  218. dest_dir = repo['dest_dir']
  219. if dest_dir != ".":
  220. extract_dir = os.path.join(os.getcwd(), dest_dir)
  221. if not os.path.exists(extract_dir):
  222. os.makedirs(extract_dir)
  223. else:
  224. extract_dir = os.getcwd()
  225. file_filter = repo.get('file_filter', "")
  226. exclude_patterns = repo.get('file_exclude', '').split()
  227. def copy_selected_files(initialrev, extract_dir, file_filter, exclude_patterns, ldir,
  228. subdir=""):
  229. # When working inside a filtered branch which had the
  230. # files already moved, we need to prepend the
  231. # subdirectory to all filters, otherwise they would
  232. # not match.
  233. if subdir == '.':
  234. subdir = ''
  235. elif subdir:
  236. subdir = os.path.normpath(subdir)
  237. file_filter = ' '.join([subdir + '/' + x for x in file_filter.split()])
  238. exclude_patterns = [subdir + '/' + x for x in exclude_patterns]
  239. # To handle both cases, we cd into the target
  240. # directory and optionally tell tar to strip the path
  241. # prefix when the files were already moved.
  242. subdir_components = len(subdir.split(os.path.sep)) if subdir else 0
  243. strip=('--strip-components=%d' % subdir_components) if subdir else ''
  244. # TODO: file_filter wild cards do not work (and haven't worked before either), because
  245. # a) GNU tar requires a --wildcards parameter before turning on wild card matching.
  246. # b) The semantic is not as intendend (src/*.c also matches src/foo/bar.c,
  247. # in contrast to the other use of file_filter as parameter of "git archive"
  248. # where it only matches .c files directly in src).
  249. files = runcmd("git archive %s %s | tar -x -v %s -C %s %s" %
  250. (initialrev, subdir,
  251. strip, extract_dir, file_filter),
  252. ldir)
  253. if exclude_patterns:
  254. # Implement file removal by letting tar create the
  255. # file and then deleting it in the file system
  256. # again. Uses the list of files created by tar (easier
  257. # than walking the tree).
  258. for file in files.split('\n'):
  259. for pattern in exclude_patterns:
  260. if fnmatch.fnmatch(file, pattern):
  261. os.unlink(os.path.join(*([extract_dir] + ['..'] * subdir_components + [file])))
  262. break
  263. if not conf.history:
  264. copy_selected_files(initialrev, extract_dir, file_filter, exclude_patterns, ldir)
  265. else:
  266. # First fetch remote history into local repository.
  267. # We need a ref for that, so ensure that there is one.
  268. refname = "combo-layer-init-%s" % name
  269. runcmd("git branch -f %s %s" % (refname, initialrev), ldir)
  270. runcmd("git fetch %s %s" % (ldir, refname))
  271. runcmd("git branch -D %s" % refname, ldir)
  272. # Make that the head revision.
  273. runcmd("git checkout -b %s %s" % (name, initialrev))
  274. # Optional: cut the history by replacing the given
  275. # start point(s) with commits providing the same
  276. # content (aka tree), but with commit information that
  277. # makes it clear that this is an artifically created
  278. # commit and nothing the original authors had anything
  279. # to do with.
  280. since_rev = repo.get('since_revision', '')
  281. if since_rev:
  282. committer = runcmd('git var GIT_AUTHOR_IDENT').strip()
  283. # Same time stamp, no name.
  284. author = re.sub('.* (\d+ [+-]\d+)', r'unknown <unknown> \1', committer)
  285. logger.info('author %s' % author)
  286. for rev in since_rev.split():
  287. # Resolve in component repo...
  288. rev = runcmd('git log --oneline --no-abbrev-commit -n1 %s' % rev, ldir).split()[0]
  289. # ... and then get the tree in current
  290. # one. The commit should be in both repos with
  291. # the same tree, but better check here.
  292. tree = runcmd('git show -s --pretty=format:%%T %s' % rev).strip()
  293. with tempfile.NamedTemporaryFile() as editor:
  294. editor.write('''cat >$1 <<EOF
  295. tree %s
  296. author %s
  297. committer %s
  298. %s: squashed import of component
  299. This commit copies the entire set of files as found in
  300. %s %s
  301. For more information about previous commits, see the
  302. upstream repository.
  303. Commit created by combo-layer.
  304. EOF
  305. ''' % (tree, author, committer, name, name, since_rev))
  306. editor.flush()
  307. os.environ['GIT_EDITOR'] = 'sh %s' % editor.name
  308. runcmd('git replace --edit %s' % rev)
  309. # Optional: rewrite history to change commit messages or to move files.
  310. if 'hook' in repo or dest_dir != ".":
  311. filter_branch = ['git', 'filter-branch', '--force']
  312. with tempfile.NamedTemporaryFile() as hookwrapper:
  313. if 'hook' in repo:
  314. # Create a shell script wrapper around the original hook that
  315. # can be used by git filter-branch. Hook may or may not have
  316. # an absolute path.
  317. hook = repo['hook']
  318. hook = os.path.join(os.path.dirname(conf.conffile), '..', hook)
  319. # The wrappers turns the commit message
  320. # from stdin into a fake patch header.
  321. # This is good enough for changing Subject
  322. # and commit msg body with normal
  323. # combo-layer hooks.
  324. hookwrapper.write('''set -e
  325. tmpname=$(mktemp)
  326. trap "rm $tmpname" EXIT
  327. echo -n 'Subject: [PATCH] ' >>$tmpname
  328. cat >>$tmpname
  329. if ! [ $(tail -c 1 $tmpname | od -A n -t x1) == '0a' ]; then
  330. echo >>$tmpname
  331. fi
  332. echo '---' >>$tmpname
  333. %s $tmpname $GIT_COMMIT %s
  334. tail -c +18 $tmpname | head -c -4
  335. ''' % (hook, name))
  336. hookwrapper.flush()
  337. filter_branch.extend(['--msg-filter', 'bash %s' % hookwrapper.name])
  338. if dest_dir != ".":
  339. parent = os.path.dirname(dest_dir)
  340. if not parent:
  341. parent = '.'
  342. # May run outside of the current directory, so do not assume that .git exists.
  343. filter_branch.extend(['--tree-filter', 'mkdir -p .git/tmptree && mv $(ls -1 -a | grep -v -e ^.git$ -e ^.$ -e ^..$) .git/tmptree && mkdir -p %s && mv .git/tmptree %s' % (parent, dest_dir)])
  344. filter_branch.append('HEAD')
  345. runcmd(filter_branch)
  346. runcmd('git update-ref -d refs/original/refs/heads/%s' % name)
  347. repo['rewritten_revision'] = runcmd('git rev-parse HEAD').strip()
  348. repo['stripped_revision'] = repo['rewritten_revision']
  349. # Optional filter files: remove everything and re-populate using the normal filtering code.
  350. # Override any potential .gitignore.
  351. if file_filter or exclude_patterns:
  352. runcmd('git rm -rf .')
  353. if not os.path.exists(extract_dir):
  354. os.makedirs(extract_dir)
  355. copy_selected_files('HEAD', extract_dir, file_filter, exclude_patterns, '.',
  356. subdir=dest_dir)
  357. runcmd('git add --all --force .')
  358. if runcmd('git status --porcelain'):
  359. # Something to commit.
  360. runcmd(['git', 'commit', '-m',
  361. '''%s: select file subset
  362. Files from the component repository were chosen based on
  363. the following filters:
  364. file_filter = %s
  365. file_exclude = %s''' % (name, file_filter or '<empty>', repo.get('file_exclude', '<empty>'))])
  366. repo['stripped_revision'] = runcmd('git rev-parse HEAD').strip()
  367. if not lastrev:
  368. lastrev = runcmd('git rev-parse %s' % initialrev, ldir).strip()
  369. conf.update(name, "last_revision", lastrev, initmode=True)
  370. if not conf.history:
  371. runcmd("git add .")
  372. else:
  373. # Create Octopus merge commit according to http://stackoverflow.com/questions/10874149/git-octopus-merge-with-unrelated-repositoies
  374. runcmd('git checkout master')
  375. merge = ['git', 'merge', '--no-commit']
  376. for name in conf.repos:
  377. repo = conf.repos[name]
  378. # Use branch created earlier.
  379. merge.append(name)
  380. # Root all commits which have no parent in the common
  381. # ancestor in the new repository.
  382. for start in runcmd('git log --pretty=format:%%H --max-parents=0 %s' % name).split('\n'):
  383. runcmd('git replace --graft %s %s' % (start, startrev))
  384. try:
  385. runcmd(merge)
  386. except Exception, error:
  387. logger.info('''Merging component repository history failed, perhaps because of merge conflicts.
  388. It may be possible to commit anyway after resolving these conflicts.
  389. %s''' % error)
  390. # Create MERGE_HEAD and MERGE_MSG. "git merge" itself
  391. # does not create MERGE_HEAD in case of a (harmless) failure,
  392. # and we want certain auto-generated information in the
  393. # commit message for future reference and/or automation.
  394. with open('.git/MERGE_HEAD', 'w') as head:
  395. with open('.git/MERGE_MSG', 'w') as msg:
  396. msg.write('repo: initial import of components\n\n')
  397. # head.write('%s\n' % startrev)
  398. for name in conf.repos:
  399. repo = conf.repos[name]
  400. # <upstream ref> <rewritten ref> <rewritten + files removed>
  401. msg.write('combo-layer-%s: %s %s %s\n' % (name,
  402. repo['last_revision'],
  403. repo['rewritten_revision'],
  404. repo['stripped_revision']))
  405. rev = runcmd('git rev-parse %s' % name).strip()
  406. head.write('%s\n' % rev)
  407. if conf.localconffile:
  408. localadded = True
  409. try:
  410. runcmd("git rm --cached %s" % conf.localconffile, printerr=False)
  411. except subprocess.CalledProcessError:
  412. localadded = False
  413. if localadded:
  414. localrelpath = os.path.relpath(conf.localconffile)
  415. runcmd("grep -q %s .gitignore || echo %s >> .gitignore" % (localrelpath, localrelpath))
  416. runcmd("git add .gitignore")
  417. logger.info("Added local configuration file %s to .gitignore", localrelpath)
  418. 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.")
  419. else:
  420. logger.info("Repository already initialised, nothing to do.")
  421. def check_repo_clean(repodir):
  422. """
  423. check if the repo is clean
  424. exit if repo is dirty
  425. """
  426. output=runcmd("git status --porcelain", repodir)
  427. r = re.compile('\?\? patch-.*/')
  428. dirtyout = [item for item in output.splitlines() if not r.match(item)]
  429. if dirtyout:
  430. logger.error("git repo %s is dirty, please fix it first", repodir)
  431. sys.exit(1)
  432. def check_patch(patchfile):
  433. f = open(patchfile)
  434. ln = f.readline()
  435. of = None
  436. in_patch = False
  437. beyond_msg = False
  438. pre_buf = ''
  439. while ln:
  440. if not beyond_msg:
  441. if ln == '---\n':
  442. if not of:
  443. break
  444. in_patch = False
  445. beyond_msg = True
  446. elif ln.startswith('--- '):
  447. # We have a diff in the commit message
  448. in_patch = True
  449. if not of:
  450. print('WARNING: %s contains a diff in its commit message, indenting to avoid failure during apply' % patchfile)
  451. of = open(patchfile + '.tmp', 'w')
  452. of.write(pre_buf)
  453. pre_buf = ''
  454. elif in_patch and not ln[0] in '+-@ \n\r':
  455. in_patch = False
  456. if of:
  457. if in_patch:
  458. of.write(' ' + ln)
  459. else:
  460. of.write(ln)
  461. else:
  462. pre_buf += ln
  463. ln = f.readline()
  464. f.close()
  465. if of:
  466. of.close()
  467. os.rename(patchfile + '.tmp', patchfile)
  468. def drop_to_shell(workdir=None):
  469. if not sys.stdin.isatty():
  470. print "Not a TTY so can't drop to shell for resolution, exiting."
  471. return False
  472. shell = os.environ.get('SHELL', 'bash')
  473. print('Dropping to shell "%s"\n' \
  474. 'When you are finished, run the following to continue:\n' \
  475. ' exit -- continue to apply the patches\n' \
  476. ' exit 1 -- abort\n' % shell);
  477. ret = subprocess.call([shell], cwd=workdir)
  478. if ret != 0:
  479. print "Aborting"
  480. return False
  481. else:
  482. return True
  483. def check_rev_branch(component, repodir, rev, branch):
  484. try:
  485. actualbranch = runcmd("git branch --contains %s" % rev, repodir, printerr=False)
  486. except subprocess.CalledProcessError as e:
  487. if e.returncode == 129:
  488. actualbranch = ""
  489. else:
  490. raise
  491. if not actualbranch:
  492. logger.error("%s: specified revision %s is invalid!" % (component, rev))
  493. return False
  494. branches = []
  495. branchlist = actualbranch.split("\n")
  496. for b in branchlist:
  497. branches.append(b.strip().split(' ')[-1])
  498. if branch not in branches:
  499. logger.error("%s: specified revision %s is not on specified branch %s!" % (component, rev, branch))
  500. return False
  501. return True
  502. def get_repos(conf, repo_names):
  503. repos = []
  504. for name in repo_names:
  505. if name.startswith('-'):
  506. break
  507. else:
  508. repos.append(name)
  509. for repo in repos:
  510. if not repo in conf.repos:
  511. logger.error("Specified component '%s' not found in configuration" % repo)
  512. sys.exit(1)
  513. if not repos:
  514. repos = conf.repos
  515. return repos
  516. def action_pull(conf, args):
  517. """
  518. update the component repos only
  519. """
  520. repos = get_repos(conf, args[1:])
  521. # make sure all repos are clean
  522. for name in repos:
  523. check_repo_clean(conf.repos[name]['local_repo_dir'])
  524. for name in repos:
  525. repo = conf.repos[name]
  526. ldir = repo['local_repo_dir']
  527. branch = repo.get('branch', "master")
  528. runcmd("git checkout %s" % branch, ldir)
  529. logger.info("git pull for component repo %s in %s ..." % (name, ldir))
  530. output=runcmd("git pull", ldir)
  531. logger.info(output)
  532. def action_update(conf, args):
  533. """
  534. update the component repos
  535. generate the patch list
  536. apply the generated patches
  537. """
  538. components = [arg.split(':')[0] for arg in args[1:]]
  539. revisions = {}
  540. for arg in args[1:]:
  541. if ':' in arg:
  542. a = arg.split(':', 1)
  543. revisions[a[0]] = a[1]
  544. repos = get_repos(conf, components)
  545. # make sure combo repo is clean
  546. check_repo_clean(os.getcwd())
  547. import uuid
  548. patch_dir = "patch-%s" % uuid.uuid4()
  549. if not os.path.exists(patch_dir):
  550. os.mkdir(patch_dir)
  551. # Step 1: update the component repos
  552. if conf.nopull:
  553. logger.info("Skipping pull (-n)")
  554. else:
  555. action_pull(conf, ['arg0'] + components)
  556. for name in repos:
  557. revision = revisions.get(name, None)
  558. repo = conf.repos[name]
  559. ldir = repo['local_repo_dir']
  560. dest_dir = repo['dest_dir']
  561. branch = repo.get('branch', "master")
  562. repo_patch_dir = os.path.join(os.getcwd(), patch_dir, name)
  563. # Step 2: generate the patch list and store to patch dir
  564. logger.info("Generating patches from %s..." % name)
  565. top_revision = revision or branch
  566. if not check_rev_branch(name, ldir, top_revision, branch):
  567. sys.exit(1)
  568. if dest_dir != ".":
  569. prefix = "--src-prefix=a/%s/ --dst-prefix=b/%s/" % (dest_dir, dest_dir)
  570. else:
  571. prefix = ""
  572. if repo['last_revision'] == "":
  573. logger.info("Warning: last_revision of component %s is not set, starting from the first commit" % name)
  574. patch_cmd_range = "--root %s" % top_revision
  575. rev_cmd_range = top_revision
  576. else:
  577. if not check_rev_branch(name, ldir, repo['last_revision'], branch):
  578. sys.exit(1)
  579. patch_cmd_range = "%s..%s" % (repo['last_revision'], top_revision)
  580. rev_cmd_range = patch_cmd_range
  581. file_filter = repo.get('file_filter',"")
  582. patch_cmd = "git format-patch -N %s --output-directory %s %s -- %s" % \
  583. (prefix,repo_patch_dir, patch_cmd_range, file_filter)
  584. output = runcmd(patch_cmd, ldir)
  585. logger.debug("generated patch set:\n%s" % output)
  586. patchlist = output.splitlines()
  587. rev_cmd = "git rev-list --no-merges %s -- %s" % (rev_cmd_range, file_filter)
  588. revlist = runcmd(rev_cmd, ldir).splitlines()
  589. # Step 3: Call repo specific hook to adjust patch
  590. if 'hook' in repo:
  591. # hook parameter is: ./hook patchpath revision reponame
  592. count=len(revlist)-1
  593. for patch in patchlist:
  594. runcmd("%s %s %s %s" % (repo['hook'], patch, revlist[count], name))
  595. count=count-1
  596. # Step 3a: Filter out unwanted files and patches.
  597. exclude = repo.get('file_exclude', '')
  598. if exclude:
  599. filter = ['filterdiff', '-p1']
  600. for path in exclude.split():
  601. filter.append('-x')
  602. filter.append('%s/%s' % (dest_dir, path) if dest_dir != '.' else path)
  603. for patch in patchlist[:]:
  604. filtered = patch + '.tmp'
  605. with open(filtered, 'w') as f:
  606. runcmd(filter + [patch], out=f)
  607. # Now check for empty patches.
  608. if runcmd(['filterdiff', '--list', filtered]):
  609. # Possibly modified.
  610. os.unlink(patch)
  611. os.rename(filtered, patch)
  612. else:
  613. # Empty, ignore it. Must also remove from revlist.
  614. with open(patch, 'r') as f:
  615. fromline = f.readline()
  616. if not fromline:
  617. # Patch must have been empty to start with. No need
  618. # to remove it.
  619. continue
  620. m = re.match(r'''^From ([0-9a-fA-F]+) .*\n''', fromline)
  621. rev = m.group(1)
  622. logger.debug('skipping empty patch %s = %s' % (patch, rev))
  623. os.unlink(patch)
  624. os.unlink(filtered)
  625. patchlist.remove(patch)
  626. revlist.remove(rev)
  627. # Step 4: write patch list and revision list to file, for user to edit later
  628. patchlist_file = os.path.join(os.getcwd(), patch_dir, "patchlist-%s" % name)
  629. repo['patchlist'] = patchlist_file
  630. f = open(patchlist_file, 'w')
  631. count=len(revlist)-1
  632. for patch in patchlist:
  633. f.write("%s %s\n" % (patch, revlist[count]))
  634. check_patch(os.path.join(patch_dir, patch))
  635. count=count-1
  636. f.close()
  637. # Step 5: invoke bash for user to edit patch and patch list
  638. if conf.interactive:
  639. print('You may now edit the patch and patch list in %s\n' \
  640. 'For example, you can remove unwanted patch entries from patchlist-*, so that they will be not applied later' % patch_dir);
  641. if not drop_to_shell(patch_dir):
  642. sys.exit(1)
  643. # Step 6: apply the generated and revised patch
  644. apply_patchlist(conf, repos)
  645. runcmd("rm -rf %s" % patch_dir)
  646. # Step 7: commit the updated config file if it's being tracked
  647. relpath = os.path.relpath(conf.conffile)
  648. try:
  649. output = runcmd("git status --porcelain %s" % relpath, printerr=False)
  650. except:
  651. # Outside the repository
  652. output = None
  653. if output:
  654. logger.info("Committing updated configuration file")
  655. if output.lstrip().startswith("M"):
  656. runcmd('git commit -m "Automatic commit to update last_revision" %s' % relpath)
  657. def apply_patchlist(conf, repos):
  658. """
  659. apply the generated patch list to combo repo
  660. """
  661. for name in repos:
  662. repo = conf.repos[name]
  663. lastrev = repo["last_revision"]
  664. prevrev = lastrev
  665. # Get non-blank lines from patch list file
  666. patchlist = []
  667. if os.path.exists(repo['patchlist']) or not conf.interactive:
  668. # Note: we want this to fail here if the file doesn't exist and we're not in
  669. # interactive mode since the file should exist in this case
  670. with open(repo['patchlist']) as f:
  671. for line in f:
  672. line = line.rstrip()
  673. if line:
  674. patchlist.append(line)
  675. ldir = conf.repos[name]['local_repo_dir']
  676. branch = conf.repos[name].get('branch', "master")
  677. branchrev = runcmd("git rev-parse %s" % branch, ldir).strip()
  678. if patchlist:
  679. logger.info("Applying patches from %s..." % name)
  680. linecount = len(patchlist)
  681. i = 1
  682. for line in patchlist:
  683. patchfile = line.split()[0]
  684. lastrev = line.split()[1]
  685. patchdisp = os.path.relpath(patchfile)
  686. if os.path.getsize(patchfile) == 0:
  687. logger.info("(skipping %d/%d %s - no changes)" % (i, linecount, patchdisp))
  688. else:
  689. cmd = "git am --keep-cr %s-p1 %s" % ('-s ' if repo.get('signoff', True) else '', patchfile)
  690. logger.info("Applying %d/%d: %s" % (i, linecount, patchdisp))
  691. try:
  692. runcmd(cmd)
  693. except subprocess.CalledProcessError:
  694. logger.info('Running "git am --abort" to cleanup repo')
  695. runcmd("git am --abort")
  696. logger.error('"%s" failed' % cmd)
  697. logger.info("Please manually apply patch %s" % patchdisp)
  698. logger.info("Note: if you exit and continue applying without manually applying the patch, it will be skipped")
  699. if not drop_to_shell():
  700. if prevrev != repo['last_revision']:
  701. conf.update(name, "last_revision", prevrev)
  702. sys.exit(1)
  703. prevrev = lastrev
  704. i += 1
  705. # Once all patches are applied, we should update
  706. # last_revision to the branch head instead of the last
  707. # applied patch. The two are not necessarily the same when
  708. # the last commit is a merge commit or when the patches at
  709. # the branch head were intentionally excluded.
  710. #
  711. # If we do not do that for a merge commit, the next
  712. # combo-layer run will only exclude patches reachable from
  713. # one of the merged branches and try to re-apply patches
  714. # from other branches even though they were already
  715. # copied.
  716. #
  717. # If patches were intentionally excluded, the next run will
  718. # present them again instead of skipping over them. This
  719. # may or may not be intended, so the code here is conservative
  720. # and only addresses the "head is merge commit" case.
  721. if lastrev != branchrev and \
  722. len(runcmd("git show --pretty=format:%%P --no-patch %s" % branch, ldir).split()) > 1:
  723. lastrev = branchrev
  724. else:
  725. logger.info("No patches to apply from %s" % name)
  726. lastrev = branchrev
  727. if lastrev != repo['last_revision']:
  728. conf.update(name, "last_revision", lastrev)
  729. def action_splitpatch(conf, args):
  730. """
  731. generate the commit patch and
  732. split the patch per repo
  733. """
  734. logger.debug("action_splitpatch")
  735. if len(args) > 1:
  736. commit = args[1]
  737. else:
  738. commit = "HEAD"
  739. patchdir = "splitpatch-%s" % commit
  740. if not os.path.exists(patchdir):
  741. os.mkdir(patchdir)
  742. # filerange_root is for the repo whose dest_dir is root "."
  743. # and it should be specified by excluding all other repo dest dir
  744. # like "-x repo1 -x repo2 -x repo3 ..."
  745. filerange_root = ""
  746. for name in conf.repos:
  747. dest_dir = conf.repos[name]['dest_dir']
  748. if dest_dir != ".":
  749. filerange_root = '%s -x "%s/*"' % (filerange_root, dest_dir)
  750. for name in conf.repos:
  751. dest_dir = conf.repos[name]['dest_dir']
  752. patch_filename = "%s/%s.patch" % (patchdir, name)
  753. if dest_dir == ".":
  754. cmd = "git format-patch -n1 --stdout %s^..%s | filterdiff -p1 %s > %s" % (commit, commit, filerange_root, patch_filename)
  755. else:
  756. cmd = "git format-patch --no-prefix -n1 --stdout %s^..%s -- %s > %s" % (commit, commit, dest_dir, patch_filename)
  757. runcmd(cmd)
  758. # Detect empty patches (including those produced by filterdiff above
  759. # that contain only preamble text)
  760. if os.path.getsize(patch_filename) == 0 or runcmd("filterdiff %s" % patch_filename) == "":
  761. os.remove(patch_filename)
  762. logger.info("(skipping %s - no changes)", name)
  763. else:
  764. logger.info(patch_filename)
  765. def action_error(conf, args):
  766. logger.info("invalid action %s" % args[0])
  767. actions = {
  768. "init": action_init,
  769. "update": action_update,
  770. "pull": action_pull,
  771. "splitpatch": action_splitpatch,
  772. }
  773. def main():
  774. parser = optparse.OptionParser(
  775. version = "Combo Layer Repo Tool version %s" % __version__,
  776. usage = """%prog [options] action
  777. Create and update a combination layer repository from multiple component repositories.
  778. Action:
  779. init initialise the combo layer repo
  780. update [components] get patches from component repos and apply them to the combo repo
  781. pull [components] just pull component repos only
  782. splitpatch [commit] generate commit patch and split per component, default commit is HEAD""")
  783. parser.add_option("-c", "--conf", help = "specify the config file (conf/combo-layer.conf is the default).",
  784. action = "store", dest = "conffile", default = "conf/combo-layer.conf")
  785. parser.add_option("-i", "--interactive", help = "interactive mode, user can edit the patch list and patches",
  786. action = "store_true", dest = "interactive", default = False)
  787. parser.add_option("-D", "--debug", help = "output debug information",
  788. action = "store_true", dest = "debug", default = False)
  789. parser.add_option("-n", "--no-pull", help = "skip pulling component repos during update",
  790. action = "store_true", dest = "nopull", default = False)
  791. parser.add_option("-H", "--history", help = "import full history of components during init",
  792. action = "store_true", default = False)
  793. options, args = parser.parse_args(sys.argv)
  794. # Dispatch to action handler
  795. if len(args) == 1:
  796. logger.error("No action specified, exiting")
  797. parser.print_help()
  798. elif args[1] not in actions:
  799. logger.error("Unsupported action %s, exiting\n" % (args[1]))
  800. parser.print_help()
  801. elif not os.path.exists(options.conffile):
  802. logger.error("No valid config file, exiting\n")
  803. parser.print_help()
  804. else:
  805. if options.debug:
  806. logger.setLevel(logging.DEBUG)
  807. confdata = Configuration(options)
  808. initmode = (args[1] == 'init')
  809. confdata.sanity_check(initmode)
  810. actions.get(args[1], action_error)(confdata, args[1:])
  811. if __name__ == "__main__":
  812. try:
  813. ret = main()
  814. except Exception:
  815. ret = 1
  816. import traceback
  817. traceback.print_exc(5)
  818. sys.exit(ret)