Is it possible to know if a file has been patched already, before apply the patch?
I need to do this in a script, any thoughts?
Is it possible to know if a file has been patched already, before apply the patch?
I need to do this in a script, any thoughts?
Yep, just run patch with --dry-run option, it either would fail or succeed which can be found out with its exit status.
But in more general (and less error prone) way, you probably have to run it with -R option which means "reverse" since only if it was able to revert the whole patch it could be considered as "applied". Otherwise (without '-R') it could fail just due to some parts of the original file was changed. Below is a simple example:
if ! patch -R -p0 -s -f --dry-run <patchfile; then
patch -p0 <patchfile
fi
(Evenmore, in the snippet above you might even prefer to silence patch completely redirecting its stdout and stderr to /dev/null)
Just in case it helps someone, if you are using bash script then the example given by Omnifarious would not work. In bash the exit status of a successful command is 0
So the following would work:
patch -p0 -N --dry-run --silent < patchfile 2>/dev/null
#If the patch has not been applied then the $? which is the exit status
#for last command would have a success status code = 0
if [ $? -eq 0 ];
then
#apply the patch
patch -p0 -N < patchfile
fi
Here is a guess, assuming that you are using the patch utility and each file to be patched has its own patch:
if patch <options> -N --dry-run --silent <patchfile 2>/dev/null; then
echo The file has not had the patch applied,
echo and the patch will apply cleanly.
else
echo The file may not have had the patch applied.
echo Or maybe the patch doesn't apply to the file.
fi
In my case I wanted to make that check so that running the patch command wouldn't end up with an interactive terminal asking what to do (especially for CI).
Turns out that if you only need that you can also use the --forward argument and it'll skip the patch if already applied!
This worked to me.
"scripts": {
"symfony-scripts": [
"patch -N --silent -p0 < patches/vendor/somefile.js.patch &2>/dev/null",
"Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",