combo-layer 37 KB

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