pycocci: few updates and add to install target
v3 cover pycocci: few updates and add to install target
From: "Luis R. Rodriguez" <[email protected]>
This v3 addresses the changes noted by Julia. Since this is extending features to help with SmPL patch development, in particular --show-proof, and since we're using quite a bit of heuristics useful to users of Coccinelle depending on their version installed document all this on a proper man page for pycocci and also add pycocci into the install target.
In the future we should probably just let pycocci read ini type of file on say your ~/.pycocci which will let you specify and customize further defaults we'd inherit depending on your target. Then you can further customize your options per project. Each upstream project can then also have their own .pycocci perhaps which promotes a set of options to use. For instance right now Linux scripts/coccinelle/ lets scripts gather options to use per SmPL patch. We shoul standardize on a format format for that and to enable project specific tuned variables.
If there are no issues with this v3 I'll merge soon.
Luis R. Rodriguez (5):
pycocci: add requirements class
pycocci: add git class
pycocci: figure out if to enable --jobs, --use-gitgrep or
--use-glimpse
pycocci: add Coccinelle SmPL patch proof support
pycocci: add man page and promote pycocci to install target
Makefile | 3 + docs/pycocci.1 | 217 ++++++++++++++++++++++++++ tools/pycocci | 486 ++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 687 insertions(+), 19 deletions(-) create mode 100644 docs/pycocci.1
Signature · 1 line
2.3.2.209.gd67f9d5.dirty
PATCH v3 1/5 pycocci: add requirements class
This will be used later to help examine different tools requirements. For instance, this will be used to fine tune spatch operation depending on the version of spatch you have. Later we'll also use this to add support for SmPL patch equivalence proof support.
This introduces has no functional changes.
--- tools/pycocci | 204 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 203 insertions(+), 1 deletion(-)
tools/pycocci +203 -1
@@ -10,9 +10,211 @@ # defaults, specifically for kernel developers. from multiprocessing import Process, cpu_count, Queue -import argparse, subprocess, os, sys +import argparse, subprocess, os, sys, re import tempfile, shutil +class ReqError(Exception): + pass +class ExecutionError(ReqError): + def __init__(self, errcode): + self.error_code = errcode + +class Req: + "To be used for verifying binay package dependencies on Python code" + def __init__(self, chatty=True): + self.all_reqs_ok = True + self.debug = False + self.chatty = chatty + def logwrite(self, msg): + if self.chatty: + sys.stdout.write(msg) + sys.stdout.flush() + def enable_debug(self): + self.debug = True + def reqs_match(self): + if self.all_reqs_ok: + return True + self.logwrite("You have unfulfilled binary requirements\n") + return False + def req_missing(self, program): + self.all_reqs_ok = False + self.logwrite("You need to have installed: %s\n" % program) + def req_old_program(self, program, version_req): + self.all_reqs_ok = False + self.logwrite("You need to have installed: %s >= %s\n" % (program, version_req)) + def which(self, program): + cmd = ['which', program] + process = subprocess.Popen(cmd, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + close_fds=True, universal_newlines=True) + stdout = process.communicate()[0] + process.wait() + if process.returncode != 0: + raise ExecutionError(process.returncode) + return stdout + def req_exists(self, program): + cmd = ['which', program] + process = subprocess.Popen(cmd, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + close_fds=True, universal_newlines=True) + stdout = process.communicate()[0] + process.wait() + if process.returncode == 0: + return True + return False + def req_get_prog_version(self, program, version_query, version_pos): + ''' + Suppose you have a binary that outputs: + $ spatch --version + spatch version 1.0.0-rc21 with Python support and with PCRE support + + Every program veries what it wants you to query it for a version string, + prog_version() is designed so that you pass what the program expects for + its version query, and the position you expect the version string to be + on using python list. + ''' + cmd = [program, version_query] + process = subprocess.Popen(cmd, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + close_fds=True, universal_newlines=True) + stdout = process.communicate()[0] + process.wait() + if process.returncode != 0: + raise ExecutionError(process.returncode) + if self.debug: + sys.stdout.write("Running '%s' got us this break down:\n%s\n" % + ( + ' '.join(cmd), + "\n".join(map(str, [[i, x] for i, x in enumerate(stdout.split())])), + )) + sys.stdout.write("You are using for version: %s\n" % stdout.split()[version_pos]) + sys.stdout.write("Specifically your idx, element: %s\n" % ([[i, x] for i, x in enumerate(stdout.split())][version_pos])) + return stdout.split()[version_pos] + + MAX_RC = 25 + def __compute_rel_weight(self, rel_specs): + weight = 0 + extra = 0 + sublevel = 0 + relmod = 0 + + if self.debug: + sys.stdout.write("VERSION = %s\n" % rel_specs['VERSION']) + sys.stdout.write("PATCHLEVEL = %s\n" % rel_specs['PATCHLEVEL']) + sys.stdout.write("SUBLEVEL = %s\n" % rel_specs['SUBLEVEL']) + sys.stdout.write("EXTRAVERSION = %s\n" % rel_specs['EXTRAVERSION']) + sys.stdout.write("RELMOD_UPDATE = %s\n" % rel_specs['RELMOD_UPDATE']) + + if rel_specs['EXTRAVERSION'] != '': + if ("." in rel_specs['EXTRAVERSION'] or + "rc" in rel_specs['EXTRAVERSION']): + rc = rel_specs['EXTRAVERSION'].lstrip("-rc") + if (rc == ""): + rc = 0 + else: + rc = int(rc) - (Req.MAX_RC + 1) + extra = int(rc) + else: + extra = int(rel_specs['EXTRAVERSION']) + 10 + + if rel_specs['SUBLEVEL'] != '': + sublevel = int(rel_specs['SUBLEVEL'].lstrip(".")) * 20 + else: + sublevel = 5 + + if rel_specs['RELMOD_UPDATE'] != '': + mod = rel_specs['RELMOD_UPDATE'] + if (mod == ""): + mod = 0 + else: + mod = int(mod) + relmod = int(mod) + + weight = (int(rel_specs['VERSION']) << 32) + \ + (int(rel_specs['PATCHLEVEL']) << 16) + \ + (sublevel << 8 ) + \ + (extra * 60) + (relmod * 2) + + return weight + def req_get_rel_spec(self, rel): + if "rc" in rel: + m = re.match(r"v*(?P<VERSION>\d+)\.+" + "(?P<PATCHLEVEL>\d+)[.]*" + "(?P<SUBLEVEL>\d*)" + "(?P<EXTRAVERSION>[-rc]+\w*)\-*" + "(?P<RELMOD_UPDATE>\d*)[-]*", + rel) + else: + m = re.match(r"v*(?P<VERSION>\d+)\.+" + "(?P<PATCHLEVEL>\d+)[.]*" + "(?P<SUBLEVEL>\d*)[.]*" + "(?P<EXTRAVERSION>\w*)\-*" + "(?P<RELMOD_UPDATE>\d*)[-]*", + rel) + if not m: + return m + rel_specs = m.groupdict() + return rel_specs + def compute_rel_weight(self, rel): + rel_specs = self.req_get_rel_spec(rel) + if not rel_specs: + return 0 + return self.__compute_rel_weight(rel_specs) + def linux_version_cmp(self, version_req, version): + ''' + If the program follows the linux version style scheme you can + use this to compare versions. + ''' + weight_has = self.compute_rel_weight(version) + weight_req = self.compute_rel_weight(version_req) + + if self.debug: + sys.stdout.write("You have program weight: %s\n" % weight_has) + sys.stdout.write("Required program weight: %s\n" % weight_req) + + if weight_has < weight_req: + return -1 + return 0 + def require_version(self, program, version_query, version_req, version_pos, version_cmp): + ''' + If you have a program version requirement you can specify it here, + as for the other flags refer to prog_version. + ''' + if not self.require(program): + return False + version = self.req_get_prog_version(program, version_query, version_pos) + if self.debug: + sys.stdout.write("Checking release specs and weight: for: %s\n" % program) + sys.stdout.write("You have version: %s\n" % version) + sys.stdout.write("Required version: %s\n" % version_req) + if version_cmp(version_req, version) != 0: + self.req_old_program(program, version_req) + return False + return True + def require(self, program): + if self.req_exists(program): + return True + self.req_missing(program) + return False + def require_hint(self, program, package_hint): + if self.require(program): + return True + sys.stdout.write("Try installing the package: %s\n" % package_hint) + return False + def coccinelle(self, version): + if self.require_version('spatch', '--version', version, 2, self.linux_version_cmp): + return True + self.logwrite("Try installing the package: coccinelle\n") + self.logwrite("If that is too old go grab the code from source:\n\n") + self.logwrite("git clone https://github.com/coccinelle/coccinelle.git\n\n") + self.logwrite("To build you will need: ocaml ncurses-devel\n\n") + self.logwrite("If on SUSE / OpenSUSE you will also need: ocaml-ocamldoc\n\n") + return False + def make(self, version): + return self.require_version('make', '--version', version, 2, self.linux_version_cmp) + def gcc(self, version): + return self.require_version('gcc', '--version', version, 3, self.linux_version_cmp) + # simple tempdir wrapper object for 'with' statement # # Usage:
Signature · 1 line
2.3.2.209.gd67f9d5.dirty
PATCH v3 2/5 pycocci: add git class
In reply to Luis R. RodriguezFrom: "Luis R. Rodriguez" <[email protected]>
This will let us check and use git for both inference of whether or not --use-gitgrep is needed later, and also for SmPL patch equivalence proof support later.
--- tools/pycocci | 80 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+)
tools/pycocci +80 -0
@@ -215,6 +215,86 @@ class Req: def gcc(self, version): return self.require_version('gcc', '--version', version, 3, self.linux_version_cmp) +class GitError(Exception): + pass +class ExecutionGitError(GitError): + def __init__(self, errcode): + self.error_code = errcode + +def _check(process): + if process.returncode != 0: + raise ExecutionError(process.returncode) + +def git_init(tree=None): + process = subprocess.Popen(['git', 'init'], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + close_fds=True, universal_newlines=True, cwd=tree) + stdout = process.communicate()[0] + process.wait() + _check(process) + +def git_rev_parse(tree=None, extra_args=None): + cmd = ['git', 'rev-parse' ] + extra_args + process = subprocess.Popen(cmd, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + close_fds=True, universal_newlines=True, cwd=tree) + stdout = process.communicate()[0] + process.wait() + if process.returncode != 0: + return None + return stdout.split('\n', 1)[0] + +def gitname(path=None): + work_dir = path + if not os.path.isdir(path): + work_dir = os.path.dirname(path) + process = subprocess.Popen(['git', 'rev-parse', '--show-toplevel', path], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + close_fds=True, universal_newlines=True, cwd=work_dir) + stdout = process.communicate()[0] + process.wait() + if process.returncode != 0: + return None + return stdout.split('\n', 1)[0] + +def git_add(path, tree=None): + process = subprocess.Popen(['git', 'add', '--ignore-removal', path], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + close_fds=True, universal_newlines=True, cwd=tree) + stdout = process.communicate()[0] + process.wait() + _check(process) + +def git_checkout(tree=None, extra_args=None): + cmd = ['git', 'checkout' ] + extra_args + process = subprocess.Popen(cmd, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + close_fds=True, universal_newlines=True, cwd=tree) + stdout = process.communicate()[0] + process.wait() + _check(process) + +def git_commit_all(message, tree=None): + git_add('.', tree=tree) + process = subprocess.Popen(['git', 'commit', '--allow-empty', '-a', '-m', message], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + close_fds=True, universal_newlines=True, cwd=tree) + stdout = process.communicate()[0] + process.wait() + _check(process) + +def git_diff(tree=None, extra_args=None): + cmd = ['git', 'diff', '--color=always'] + extra_args + + process = subprocess.Popen(cmd, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + close_fds=True, universal_newlines=True, cwd=tree) + stdout = process.communicate()[0] + process.wait() + _check(process) + + return stdout + # simple tempdir wrapper object for 'with' statement # # Usage:
Signature · 1 line
2.3.2.209.gd67f9d5.dirty
PATCH v3 3/5 pycocci: figure out if to enable --jobs, --use-gitgrep or --use-glimpse
In reply to Luis R. Rodriguezpycocci was originally written to set sensible defaults for doing development with Coccinelle with a git tree and to also add parallelism wrapper support. Coccinelle now has a '--jobs' argument which does the same but it works better. This feature is available as of 1.0.0 but will have some fixes which will go in on 1.0.2.
Likewise the 1.0.1 release has --use-gitgrep support which works better than --use-coccigrep but has some issues on the 1.0.1 release which are fixed on the 1.0.2 release. An old feature that has been in place for a long time is --use-glimpse, and since we have that code released now as open source we should provide support for it as its expected we'd get the best results with it. The glimpse code still needs a bit of work, as the public releases doesn't yet build correctly, but nevertheless we should support it as glimpse is now open sourced under the ISC license.
Instead of removing the old built-in wrapper for parallelism support lets keep it and instead check the version of coccinelle you have and let pycocci figure out what options you need.
For coccinelle 1.0.2, coccinelle will be able to let you default to always use --use-gitgrep by default safely, it will call 'git grep' for some cases, and if git was not installed or if your path was not part of a git tree it will fallback to using --use-coccicheck. We can optimize this a bit by checking both if you have git installed for you and since we already have code which can easily check if your path is part of a git tree we can check for that before using --use-gitgrep. This will avoid unnecessary failed calls to git grep even though as of coccinelle 1.0.2 it should be safe to default to it and use coccinelle's fallback.
The check to see if a target path is part of a git tree is implemented in gitname(), upon investingating git code setup_git_directory_gently() is the shortest possible path to determine if a path is part of a git tree, and respectively git rev-parse the easiest tool we can use to infer this from a given path. Something similar is not implemented but can be done for glimpse. This is not a priority however as glimpse can't even build yet as-is with the new public release of code.
If all index options fail to check out we resort to --use-coccigrep as the last-resort default.
--- tools/pycocci | 97 +++++++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 85 insertions(+), 12 deletions(-)
tools/pycocci +85 -12
@@ -346,14 +346,57 @@ class ExecutionErrorThread(CoccinelleError): tf.close() os.unlink(fn) -def spatch(cocci_file, outdir, - max_threads, thread_id, temp_dir, ret_q, extra_args=[]): +class ExecutionErrorCocci(CoccinelleError): + def __init__(self, errcode, output, cocci_file, logwrite, print_name): + self.error_code = errcode + logwrite("Failed to apply changes from %s\n" % print_name) + logwrite(output) + +def spatch(cocci_file, outdir, logwrite, num_jobs, print_name, extra_args=[]): + + req = Req(chatty=True) + req.coccinelle('1.0.2') + + if not req.reqs_match(): + sys.exit(1) + + num_cpus = cpu_count() + if num_jobs: + threads = int(num_jobs) + else: + threads = num_cpus + + cmd = ['spatch', + '--sp-file', cocci_file, + '--in-place', + '--recursive-includes', + '--relax-include-path', + '--timeout', '120', + '--dir', outdir ] + + if (threads > 1): + cmd.extend(['--jobs', str(threads)]) + + cmd.extend(extra_args) + + logwrite("%s\n" % " ".join(cmd)) + + sprocess = subprocess.Popen(cmd, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + close_fds=True, universal_newlines=True) + output = sprocess.communicate()[0] + sprocess.wait() + if sprocess.returncode != 0: + raise ExecutionErrorCocci(sprocess.returncode, output, cocci_file, logwrite, print_name) + return output + +def spatch_old(cocci_file, outdir, + max_threads, thread_id, temp_dir, ret_q, extra_args=[]): cmd = ['spatch', '--sp-file', cocci_file, '--in-place', '--recursive-includes', '--relax-include-path', - '--use-coccigrep', '--timeout', '120', '--dir', outdir ]
@@ -385,9 +428,9 @@ def threaded_spatch(cocci_file, outdir, logwrite, num_jobs, ret_q = Queue() with tempdir() as t: for num in range(threads): - p = Process(target=spatch, args=(cocci_file, outdir, - threads, num, t, ret_q, - extra_args)) + p = Process(target=spatch_old, args=(cocci_file, outdir, + threads, num, t, ret_q, + extra_args)) jobs.append(p) for p in jobs: p.start()
@@ -440,12 +483,42 @@ def _main(): if args.jobs > 0: jobs = args.jobs - output = threaded_spatch(args.cocci_file, - args.target_dir, - logwrite, - jobs, - os.path.basename(args.cocci_file), - extra_args=extra_spatch_args) + has_spatch_1_0_1 = Req(chatty=False) + has_spatch_1_0_1.coccinelle('1.0.1') + + has_spatch_1_0_2 = Req(chatty=False) + has_spatch_1_0_2.coccinelle('1.0.2') + + git_reqs = Req(chatty=False) + git_reqs.require('git') + + glimpse_index = os.path.abspath(os.path.join(args.target_dir, '.glimpse_index')) + git_dir = None + + if git_reqs.reqs_match(): + git_dir = gitname(args.target_dir) + + if os.path.isfile(glimpse_index): + extra_spatch_args.append('--use-glimpse') + elif has_spatch_1_0_2.reqs_match(): + if git_dir: + extra_spatch_args.append('--use-gitgrep') + else: + extra_spatch_args.append('--use-coccigrep') + else: + extra_spatch_args.append('--use-coccigrep') + + if has_spatch_1_0_2.reqs_match(): + output = spatch(args.cocci_file, args.target_dir, logwrite, jobs, + os.path.basename(args.cocci_file), + extra_args=extra_spatch_args) + else: + output = threaded_spatch(args.cocci_file, + args.target_dir, + logwrite, + jobs, + os.path.basename(args.cocci_file), + extra_args=extra_spatch_args) if args.verbose: logwrite(output) return 0
Signature · 1 line
2.3.2.209.gd67f9d5.dirty
PATCH v3 4/5 pycocci: add Coccinelle SmPL patch proof support
In reply to Luis R. RodriguezFrom: "Luis R. Rodriguez" <[email protected]>
At times you may need to replace a patch series with an SmPL patch, but how can you grow certain that a patch series replaces that patch series perfectly ? How do you visualize such differences ?
This provides support for such proof mechanism. It assumes you have a patch series and respective SmPL patch you wish to use to replace the patch series. Say you have a foo.cocci SmPL patch, you would also have a foo/ directory in which you have series of patches. The foo/ patches are the patches you wish to replace.
You can use then for instance:
pycocci --show-proof foo.cocci /path/some-src-tree/
If you don't have git yet set up on /path/some-src-tree/ we'll create a git repository for you there with the code there in place already as the base of the repository. Otherwise if you already have git set up we'll use that git tree to do work.
pycocci will create two git branches for proving the work. We leave your original branch intact, whatever it was, and we'll return you back to that same git branch.
As an example, you may end up with:
Current branch: master
Patch branch: pycocci-patch-dd6b2fa4
SmPL branch: pycocci-smpl-731f9863
A series of patches in the directory foo/ will be applied onto the pycocci-patch-dd6b2fa4 branch, the foo.cocci SmPL patch will be applied onto the pycocci-smpl-731f9863 branch.
You get a perfect patch equivalence when:
git diff pycocci-patch-dd6b2fa4..pycocci-smpl-731f9863
yields no results. If there is any delta we give you the diffstat through stdout, and tell you where to go and what to do (above command) to inspect the changes in detail.
Below is a screenshot run:
mcgrof at ergon ~ $ /home/mcgrof/devel/coccinelle/tools/pycocci \ --show-proof \ /home/mcgrof/backports/patches/collateral-evolutions/media/0002-no_dmabuf.cocci \ /home/mcgrof/build/backports-20150626-test
Current branch: master
Patch branch: pycocci-patch-3a9fc1a5
SmPL branch: pycocci-smpl-17d08bf3
Applying patch ...0002-no_dmabuf/v4l2.patch
spatch --sp-file ...0002-no_dmabuf.cocci --in-place --recursive-includes --relax-include-path --timeout 120 --dir ...backports-20150626-test -max 4 -index 0 --use-coccigrep spatch --sp-file ...0002-no_dmabuf.cocci --in-place --recursive-includes --relax-include-path --timeout 120 --dir ...backports-20150626-test -max 4 -index 1 --use-coccigrep spatch --sp-file ...0002-no_dmabuf.cocci --in-place --recursive-includes --relax-include-path --timeout 120 --dir ...backports-20150626-test -max 4 -index 2 --use-coccigrep spatch --sp-file ...0002-no_dmabuf.cocci --in-place --recursive-includes --relax-include-path --timeout 120 --dir ...backports-20150626-test -max 4 -index 3 --use-coccigrep
Differences found:
Change directory to /home/mcgrof/build/backports-20150626-test and run:
git diff pycocci-patch-3a9fc1a5..pycocci-smpl-17d08bf3
diffstat of the changes:
drivers/media/pci/cobalt/cobalt-v4l2.c | 2 ++ drivers/media/platform/blackfin/bfin_capture.c | 2 ++ drivers/media/platform/exynos-gsc/gsc-m2m.c | 4 +++ drivers/media/platform/s5p-mfc/s5p_mfc_dec.c | 4 +++ drivers/media/platform/s5p-mfc/s5p_mfc_enc.c | 4 +++ drivers/media/platform/s5p-tv/mixer_video.c | 4 +++ drivers/media/platform/soc_camera/soc_camera.c | 4 +++ drivers/media/platform/sti/bdisp/bdisp-v4l2.c | 2 ++ drivers/media/usb/uvc/uvc_queue.c | 2 -- drivers/media/usb/uvc/uvc_v4l2.c | 2 +- drivers/media/v4l2-core/Kconfig | 6 ++-- drivers/media/v4l2-core/v4l2-mem2mem.c | 4 --- drivers/media/v4l2-core/videobuf2-core.c | 20 ------------ drivers/media/v4l2-core/videobuf2-dma-contig.c | 34 ++++++++++++++++++-- drivers/media/v4l2-core/videobuf2-dma-sg.c | 38 +++++++++++++++++++++-- drivers/media/v4l2-core/videobuf2-vmalloc.c | 43 +++++++++++++++++++++++--- include/media/v4l2-mem2mem.h | 4 --- include/media/videobuf2-core.h | 8 ----- 18 files changed, 134 insertions(+), 53 deletions(-)
--- tools/pycocci | 94 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+)
tools/pycocci +94 -0
@@ -12,6 +12,7 @@ from multiprocessing import Process, cpu_count, Queue import argparse, subprocess, os, sys, re import tempfile, shutil +import uuid class ReqError(Exception): pass
@@ -321,6 +322,44 @@ class tempdir(object): else: shutil.rmtree(self._name) +def apply_patches(args, patch_src, target_dir, logwrite=lambda x:None): + """ + Given a path of a directories of patches apply the patches + """ + patches = [] + for root, dirs, files in os.walk(patch_src): + for f in files: + if f.endswith('.patch'): + patches.append(os.path.join(root, f)) + patches.sort() + prefix_len = len(patch_src) + 1 + for pfile in patches: + print_name = pfile[prefix_len:] + + logwrite("Applying patch %s\n" % pfile) + + process = subprocess.Popen(['patch', '-p1'], stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, stdin=subprocess.PIPE, + close_fds=True, universal_newlines=True, + cwd=target_dir) + output = process.communicate(input=open(pfile, 'r').read())[0] + output = output.split('\n') + if output[-1] == '': + output = output[:-1] + if process.returncode != 0: + if not args.verbose: + logwrite("Failed to apply changes from %s" % print_name) + for line in output: + logwrite('> %s' % line) + raise Exception('Patch failed') + + # remove orig/rej files that patch sometimes creates + for root, dirs, files in os.walk(target_dir): + for f in files: + if f[-5:] == '.orig' or f[-4:] == '.rej': + os.unlink(os.path.join(root, f)) + git_commit_all(tree=target_dir, message="apply patch %s" % (print_name)) + class CoccinelleError(Exception): pass
@@ -465,6 +504,8 @@ def _main(): help='Target source directory to modify') parser.add_argument('-p', '--profile-cocci', const=True, default=False, action="store_const", help='Enable profile, this will pass --profile to Coccinelle.') + parser.add_argument('-s', '--show-proof', const=True, default=False, action="store_const", + help='Show proof that the provided SmPL patch can replace a respective patch series') parser.add_argument('-j', '--jobs', metavar='<jobs>', type=str, default=None, help='Only use the cocci file passed for Coccinelle, don\'t do anything else, ' + 'also creates a git repo on the target directory for easy inspection ' +
@@ -475,6 +516,13 @@ def _main(): if not os.path.isfile(args.cocci_file): return -2 + if not os.path.isfile(args.target_dir) and not os.path.isdir(args.target_dir): + logwrite("Path (%s) is not a file or directory\n" % (args.target_dir)) + return -2 + + current_branch = None + smpl_branch_name = "pycocci-smpl-" + str(uuid.uuid4())[:8] + patch_branch_name = "pycocci-patch-" + str(uuid.uuid4())[:8] extra_spatch_args = [] if args.profile_cocci:
@@ -498,6 +546,40 @@ def _main(): if git_reqs.reqs_match(): git_dir = gitname(args.target_dir) + if args.show_proof: + # As an example if you use --show-proof patches/collateral-evolutions/network/09-threaded-irq.cocci + # the patches under 09-threaded-irq will be used for the proof. + patch_src = args.cocci_file.split('/')[-1].split('.cocci')[0] + dirname = os.path.dirname(args.cocci_file) + patch_src = os.path.abspath(os.path.join(dirname, patch_src)) + if not os.path.isdir(patch_src): + logwrite("Path given (%s) must be a directory with patches\n" % (patch_src)) + return -2 + git_reqs = Req(chatty=True) + git_reqs.require('git') + if not git_dir: + if os.path.isfile(args.target_dir): + logwrite("Path given (%s) is a file, try passing the directory " + "(%s) if you are certain you want us to create a git repo to provide a" + "a proof there\n" % (args.target_dir, os.path.dirname(args.target_dir))) + return -2 + logwrite("Path (%s) not part of a git tree, creating one for you...\n" % (args.target_dir)) + git_init(tree=args.target_dir) + git_commit_all(tree=args.target_dir, message="Initial commit") + cmd = [ '--abbrev-ref', 'HEAD' ] + current_branch = git_rev_parse(tree=args.target_dir, extra_args = cmd) + logwrite("\n") + logwrite("Current branch: %s\n" % (current_branch)) + logwrite("Patch branch: %s\n" % (patch_branch_name)) + logwrite("SmPL branch: %s\n" % (smpl_branch_name)) + logwrite("\n") + git_checkout(tree=args.target_dir, extra_args = ['-b', smpl_branch_name]) + git_checkout(tree=args.target_dir, extra_args = ['-b', patch_branch_name]) + + apply_patches(args, patch_src, args.target_dir, logwrite) + + git_checkout(tree=args.target_dir, extra_args = [smpl_branch_name]) + if os.path.isfile(glimpse_index): extra_spatch_args.append('--use-glimpse') elif has_spatch_1_0_2.reqs_match():
@@ -521,6 +603,18 @@ def _main(): extra_args=extra_spatch_args) if args.verbose: logwrite(output) + if args.show_proof: + git_commit_all(tree=args.target_dir, message="Initial commit") + git_checkout(tree=args.target_dir, extra_args = [current_branch]) + cmd = [ '--stat', patch_branch_name + ".." + smpl_branch_name ] + diff_stat = git_diff(tree=args.target_dir, extra_args = cmd) + if len(diff_stat) == 0: + logwrite('\nSmPL patch fully replaces patch series!') + else: + logwrite('\nDifferences found:\n\n') + logwrite('Change directory to %s and run:\n\n\tgit diff %s..%s\n\n' % (args.target_dir, patch_branch_name, smpl_branch_name)) + logwrite('diffstat of the changes:\n') + logwrite(diff_stat) return 0 if __name__ == '__main__':
Signature · 1 line
2.3.2.209.gd67f9d5.dirty
PATCH v3 5/5 pycocci: add man page and promote pycocci to install target
In reply to Luis R. RodriguezFrom: "Luis R. Rodriguez" <[email protected]>
pycocci now has a bit different uses and purposes:
- Check your version of coccinelle and enables sensible defaults known to work best for your environment. For instance:
* --jobs: although this was added as of 1.0.1 there are some issues with its implementation which will be fixe don 1.0.2, for older releases pycocci provides its own built-in multithreaded batched solution
* --use-gitgrep: although added for 1.0.1 this has some issues which will be fixed on 1.0.2
* although as of coccinelel 1.0.2 coccinelle users can safely use --use-gitgrep by default pycocci will avoid a failed 'git grep' call by checking if your target path is part of a git tree for you and that you have git installed, therefore avoiding a failed run to git grep.
* pycocci will check if you need --use-glimpse for you, otherwise it will use --use-gitgrep when your path is part of a git tree. It will always fall back to --use-cocci grep otherwise.
- Add features to supplement / make it easier to do SmPL patch development. One feature added in this release is to provide support for SmPL patch equivalence proof; you can use --show-proof to replace a patch series and then show any differences produced between your patch series and an SmPL patch. This can be used to find -- in the worst case bugs in Coccinelle (although highly uncommon these days) -- but also any changes you may have missed. In practice this tool so far has been used to enable to split up patch series in the backports project into proper separate atomic pieces, and showing you the areas where by switching to Coccinelle you have now enabled new automatic backports (a lot of new code additions).
pycocci can be used as a generic wrapper to call coccinelle for a variety of reasons and enables us to give home to expanding ideas to further enhance doing SmPL patch development. In the future we may also add statistics and metrics to help evaluate the efficiency and impact of an SmPL patch on code base.
--- Makefile | 3 + docs/pycocci.1 | 217 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ tools/pycocci | 11 ++- 3 files changed, 225 insertions(+), 6 deletions(-) create mode 100644 docs/pycocci.1
Makefile +3 -0
@@ -448,6 +448,7 @@ install-man: $(MKDIR_P) $(DESTDIR)$(MANDIR)/man1 $(MKDIR_P) $(DESTDIR)$(MANDIR)/man3 $(INSTALL_DATA) docs/spatch.1 $(DESTDIR)$(MANDIR)/man1/ + $(INSTALL_DATA) docs/pycocci.1 $(DESTDIR)$(MANDIR)/man1/ $(INSTALL_DATA) docs/Coccilib.3cocci $(DESTDIR)$(MANDIR)/man3/ install-bash:
@@ -487,6 +488,8 @@ install-stubs: install: install-man install-common install-stubs $(PYTHON_INSTALL_TARGET) rm -f $(DESTDIR)$(LIBDIR)/spatch rm -f $(DESTDIR)$(LIBDIR)/spatch.opt + rm -f $(DESTDIR)$(LIBDIR)/pycocci + $(INSTALL_PROGRAM) tools/pycoci $(DESTDIR)$(LIBDIR) @if test -x spatch -o -x spatch.opt; then \ $(MAKE) install-def;fi @if test -x spatch ; then \
docs/pycocci.1 new file +217 -0
217 lines not on this page · raw message
tools/pycocci +5 -6
@@ -495,13 +495,12 @@ def logwrite(msg): sys.stdout.flush() def _main(): - parser = argparse.ArgumentParser(description='Multithreaded Python wrapper for Coccinelle ' + - 'with sensible defaults, targetted specifically ' + - 'for git development environments') - parser.add_argument('cocci_file', metavar='<Coccinelle SmPL rules file>', type=str, + parser = argparse.ArgumentParser(description='Wrapper around Coccinelle spatch ' + + 'which infers which options to enable.') + parser.add_argument('cocci_file', metavar='<SmPL patch>', type=str, help='This is the Coccinelle file you want to use') - parser.add_argument('target_dir', metavar='<target directory>', type=str, - help='Target source directory to modify') + parser.add_argument('target_dir', metavar='<target>', type=str, + help='Target directory or file to modify') parser.add_argument('-p', '--profile-cocci', const=True, default=False, action="store_const", help='Enable profile, this will pass --profile to Coccinelle.') parser.add_argument('-s', '--show-proof', const=True, default=False, action="store_const",
Signature · 1 line
2.3.2.209.gd67f9d5.dirty
Re: [PATCH v3 5/5] pycocci: add man page and promote pycocci to install target
Quoted 13 lines · Luis R. Rodriguez
Makefile +1
-0@@ -448,6 +448,7 @@ install-man: $(MKDIR_P) $(DESTDIR)$(MANDIR)/man1 $(MKDIR_P) $(DESTDIR)$(MANDIR)/man3 $(INSTALL_DATA) docs/spatch.1 $(DESTDIR)$(MANDIR)/man1/ + $(INSTALL_DATA) docs/pycocci.1 $(DESTDIR)$(MANDIR)/man1/ $(INSTALL_DATA) docs/Coccilib.3cocci $(DESTDIR)$(MANDIR)/man3/ install-bash:
Makefile install-stubs: · line 495
Quoted 8 lines
Makefile +2
-0@@ -487,6 +488,8 @@ install-stubs: install: install-man install-common install-stubs $(PYTHON_INSTALL_TARGET) rm -f $(DESTDIR)$(LIBDIR)/spatch rm -f $(DESTDIR)$(LIBDIR)/spatch.opt + rm -f $(DESTDIR)$(LIBDIR)/pycocci + $(INSTALL_PROGRAM) tools/pycoci $(DESTDIR)$(LIBDIR) @if test -x spatch -o -x spatch.opt; then \ $(MAKE) install-def;fi @if test -x spatch ; then \
Whoops sorry this should be using $BINDIR instead. There was already a target for pycocci also on the install-tools target, but distros are not using that install target so we just would move that to the default install target to get distros to start carrying this.
Luis
Re: [Cocci] [PATCH v3 5/5] pycocci: add man page and promote pycocci to install target
Quoted 13 lines · Luis R. Rodriguez
Quoted 11 lines · Luis R. Rodriguez
Makefile +1
-0@@ -448,6 +448,7 @@ install-man: $(MKDIR_P) $(DESTDIR)$(MANDIR)/man1 $(MKDIR_P) $(DESTDIR)$(MANDIR)/man3 $(INSTALL_DATA) docs/spatch.1 $(DESTDIR)$(MANDIR)/man1/ + $(INSTALL_DATA) docs/pycocci.1 $(DESTDIR)$(MANDIR)/man1/ $(INSTALL_DATA) docs/Coccilib.3cocci $(DESTDIR)$(MANDIR)/man3/
Quoted 15 lines
Makefile install-stubs: · line 495
Quoted 10 lines
Makefile +2
-0install-bash:@@ -487,6 +488,8 @@ install-stubs: install: install-man install-common install-stubs $(PYTHON_INSTALL_TARGET) rm -f $(DESTDIR)$(LIBDIR)/spatch rm -f $(DESTDIR)$(LIBDIR)/spatch.opt + rm -f $(DESTDIR)$(LIBDIR)/pycocci + $(INSTALL_PROGRAM) tools/pycoci $(DESTDIR)$(LIBDIR) @if test -x spatch -o -x spatch.opt; then \ $(MAKE) install-def;fi @if test -x spatch ; then \Whoops sorry this should be using $BINDIR instead. There was already a target for pycocci also on the install-tools target, but distros are not using that install target so we just would move that to the default install target to get distros to start carrying this.
OK.
julia
Quoted 17 lines · Luis R. Rodriguez
From: "Luis R. Rodriguez" <[email protected]>
This v3 addresses the changes noted by Julia. Since this is extending features to help with SmPL patch development, in particular --show-proof, and since we're using quite a bit of heuristics useful to users of Coccinelle depending on their version installed document all this on a proper man page for pycocci and also add pycocci into the install target.
In the future we should probably just let pycocci read ini type of file on say your ~/.pycocci which will let you specify and customize further defaults we'd inherit depending on your target. Then you can further customize your options per project. Each upstream project can then also have their own .pycocci perhaps which promotes a set of options to use. For instance right now Linux
scripts/coccinelle/lets scripts gather options to use per SmPL patch. We shoul standardize on a format format for that and to enable project specific tuned variables.
Quoted 1 line
If there are no issues with this v3 I'll merge soon.
I'm OK with the concept of all of these.
julia
Quoted 22 lines
Luis R. Rodriguez (5):
pycocci: add requirements class
pycocci: add git class
pycocci: figure out if to enable --jobs, --use-gitgrep or
--use-glimpse
pycocci: add Coccinelle SmPL patch proof support
pycocci: add man page and promote pycocci to install targetMakefile | 3 + docs/pycocci.1 | 217 ++++++++++++++++++++++++++ tools/pycocci | 486 ++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 687 insertions(+), 19 deletions(-) create mode 100644 docs/pycocci.1Signature · 6 lines
2.3.2.209.gd67f9d5.dirty _______________________________________________ Cocci mailing list Cocci at systeme.lip6.fr https://systeme.lip6.fr/mailman/listinfo/cocci
Quoted 1 line · Julia Lawall
I'm OK with the concept of all of these
OK pushed!
Luis