techtonik / python-patch

Library to parse and apply unified diffs
https://pypi.python.org/pypi/patch
106 stars 63 forks source link

Allow more flexibility in applying individual patches #20

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
I'm using patch in an app that needs to accept patch files and apply them 
safely contained within a certain directory. Namely, it needs to vet each file 
that is to be modified and fail if a patch attempts to modify any file outside 
the base directory that the patch is to be applied to - this could be due to 
symlinks, relative or absolute paths.

To enable this, I've split up the `apply` function into two parts:

patchset.file_patches()
 - returns a generator of (filename, patch) pairs - note that this is the filename that will be modified (so it may be either the source or target)

patchset.apply_patch(filename, i, p):
 - applies an inidivual patch to the given filename. I've left the variable names as-is for the sake of a minimal patch, but `fileno` and `patch` may be better names.

This makes `patchset.apply` a very simple piece of code that just hooks these 
two functions together. My app can now do the same thing, but insert some 
file-checking code before each patch gets applied. Previously it would have to 
duplicate the logic in `apply`, which is quite a huge undertaking.

Other bits:

 - I did have to move the `errors` count into a field on PatchSet, because there's no longer any shared scope between `apply` and `pply_patch`.

 - fixed `xstrip` function which never actually returned anything but `None`.

 - Added "normalize_filenames" params to `parse` (and init) function defaulting to True, to optionally prevent path normalization (which just confuses the matter for my application).

`patch` is the actual patch - I'm also attaching `patch_whitespace_indifferent` 
just for your information (since the change alters a lot of whitespace).

Original issue reported on code.google.com by gfxm...@gmail.com on 2 Jul 2012 at 10:02

Attachments:

GoogleCodeExporter commented 9 years ago
Could it make sense to have some unit tests for all these changes?

Original comment by pombreda...@nexb.com on 21 Aug 2012 at 7:22

GoogleCodeExporter commented 9 years ago
Perhaps - the main point is that it breaks nothing, but it would indeed be a 
good idea to ensure that the things it enables work as intended. Unfortunately 
I'm no longer planning to integrate python-patch, so it's unlikely I'll get 
around to this myself.

Original comment by gfxm...@gmail.com on 5 Sep 2012 at 4:54