Skip to content

lab 32 Applying Patches

Goals

A patch is simply a special file that records changes to other files. Git can create these patches for you to send to other collaborators and it can apply patches from collaborators to your local repository.

Create the Patch

Switch back to the excited branch and add this change.

Execute:

git checkout excitement

lib/greeter.rb

  def initialize(who, excited = true, unsure = true)
    @who = who
    @excited = excited
    @unsure = unsure
  end
  def greet
    "Hello, #{@who}#{punctuation}"
  end
  def punctuation
    punct = ""
    if @excited
        punct += "!"
    else
        punct += "."
    end
    if @unsure
        punct += "?"
    end
    punct
  end
end

Now to create the patch all you need to do is show the changes and save the output.

Execute:

git diff
git diff > suspicion.patch

Output:

$ git diff
diff --git a/lib/greeter.rb b/lib/greeter.rb
index 95d9419..6fbb8b1 100644
--- a/lib/greeter.rb
+++ b/lib/greeter.rb
@@ -1,12 +1,21 @@
-class Greeter
-  def initialize(who, excited = true)
+  def initialize(who, excited = true, unsure = true)
     @who = who
     @excited = excited
+    @unsure = unsure
   end
   def greet
     "Hello, #{@who}#{punctuation}"
   end
   def punctuation
-    @excited ? "!" : "."
+    punct = ""
+    if @excited
+        punct += "!"
+    else
+        punct += "."
+    end
+    if @unsure
+        punct += "?"
+    end
+    punct
   end
 end
$ git diff > suspicion.patch

Switch Back to the Greet Branch

Switch back to the greet branch, resetting any local changes to the files to allow applying the patch manually.

Execute:

git checkout -f greet

Apply the Patch

Now you can apply the patch using git apply. Make sure to also confirm it applied successfully. The output from git diff should match the output from above.

Execute:

git apply suspicion.patch
git diff

Output:

$ git apply suspicion.patch
$ git diff
diff --git a/lib/greeter.rb b/lib/greeter.rb
index 95d9419..6fbb8b1 100644
--- a/lib/greeter.rb
+++ b/lib/greeter.rb
@@ -1,12 +1,21 @@
-class Greeter
-  def initialize(who, excited = true)
+  def initialize(who, excited = true, unsure = true)
     @who = who
     @excited = excited
+    @unsure = unsure
   end
   def greet
     "Hello, #{@who}#{punctuation}"
   end
   def punctuation
-    @excited ? "!" : "."
+    punct = ""
+    if @excited
+        punct += "!"
+    else
+        punct += "."
+    end
+    if @unsure
+        punct += "?"
+    end
+    punct
   end
 end

Notice that this did not commit the changes. You can commit them as usual.

Execute:

git add lib/greeter.rb
git commit -m "Add some suspicion"

Cleanup

You can remove the patch file now that it’s been applied.

Execute:

rm suspicion.patch