DEV Community

Nick F
Nick F

Posted on

Using "git diff" and "git apply" to share small changes.

Sometimes in a Pull Request Review you want to tell someone about a little change to make. You make your change locally, maybe a few lines different, and note that it works locally. Your git diff output will show your change. How can you share this little snippit? Just copy the output of git diff and sent that to your team mate. Here is a small change I've made locally:

diff --git a/conf/local.rb b/conf/local.rb
index 57672691..28fd024c 100644
--- a/conf/local.rb
+++ b/conf/local.rb
@@ -1,6 +1,6 @@
-@whitePagesCacheTtl = "60s"
-
-@executionEnvironment = "local"
+@whitePagesCacheTtl = "120s"
+@considerEnv = "false"
+@executionEnvironment = "external"

 @lightstep_collector_host = "HO123"

Enter fullscreen mode Exit fullscreen mode

Let's say I copied all that. On a mac, we have the cool pbcopy command to capture stdout and put it on the clipboard. So git diff | pbcopy will copy it for us. Now you can put it in a pull request comment or send it to someone on chat.

Ok so a team mate sent you that. You can read it as a human and see it changes a few lines. You could edit the file to make it match, but git can do it for you. Pipe the output to git apply. Again on mac we have the nice pbpaste command to send our clipboard to stdout. So one option is to copy the text from the pull request comment and pipe it to git apply.

$ pbpaste | git apply
Enter fullscreen mode Exit fullscreen mode

Another option is to put the contents into a file and point git apply to that. Say you paste the diff into new.patch, you can apply the changes with:

$ git apply new.patch && rm new.patch
Enter fullscreen mode Exit fullscreen mode

I delete the patch since we are done with it and don't want to commit it to git.

This is something I do often. I used git for a long time without knowing about apply or that the output of diff can be used as input. It has helped me a few times.

Top comments (0)