combo-layer 36 KB

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