<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Patrick Reagan</title>
  <link href="https://patrick-reagan.com/atom.xml" rel="self"/>
  <link href="https://patrick-reagan.com/"/>
  <updated>2026-11-05T17:25:50.343Z</updated>
  <id>https://patrick-reagan.com/</id>
  <author>
    <name>Patrick Reagan</name>
  </author>
  <entry>
    <title>Git Worktrees as Swimlanes</title>
    <id>/articles/git-worktrees-as-swimlanes</id>
    <updated>2026-04-16T00:00:00.000Z</updated>
    <link href="https://patrick-reagan.com/articles/git-worktrees-as-swimlanes"/>
    <content type="html">&lt;p&gt;Git worktrees let you have multiple branches checked out at the same time,
which is genuinely useful — but the advice you usually hear (&amp;quot;one worktree per
feature branch&amp;quot;) leaves you juggling a pile of ephemeral directories, each one
missing the &lt;code&gt;.env&lt;/code&gt; file, the &lt;code&gt;node_modules&lt;/code&gt;, or the install step that makes it
runnable. That friction keeps most people on a single checkout.&lt;/p&gt;
&lt;p&gt;Here's a different way to use worktrees: as &lt;strong&gt;persistent roles&lt;/strong&gt;, not
per-feature containers.&lt;/p&gt;
&lt;h2&gt;The Mental Flip&lt;/h2&gt;
&lt;p&gt;A worktree is a &lt;em&gt;directory with a role&lt;/em&gt;. The directory stays put; whichever
branch I need rotates through it.&lt;/p&gt;
&lt;p&gt;I open each one in its own VS Code window, so switching swimlanes is a
window switch. Once I'm in a swimlane, I pick the branch with &lt;code&gt;git checkout&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;That's it. The rest of this post is about how to make that comfortable in
practice.&lt;/p&gt;
&lt;h2&gt;The Swimlanes I Use&lt;/h2&gt;
&lt;p&gt;I keep four worktrees around at all times for any repo I spend real time in:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Swimlane&lt;/th&gt;
&lt;th&gt;Role&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;development&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Stays on the &lt;code&gt;development&lt;/code&gt; branch. Used to run the latest version of the app and as the base I branch off.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;work-queue&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Where I create new branches for each ticket I work on.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;review&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Where I check out whatever branch is currently under review.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;experiments&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Longer-running spikes that may or may not produce commits.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;code&gt;development&lt;/code&gt; and &lt;code&gt;experiments&lt;/code&gt; are stable: the branch checked out in each one
rarely changes. &lt;code&gt;work-queue&lt;/code&gt; and &lt;code&gt;review&lt;/code&gt; are different — the &lt;em&gt;directory&lt;/em&gt; is
stable, but the branch checked out inside it rotates constantly.&lt;/p&gt;
&lt;p&gt;Set them up once. Clone your repo into a directory you'll treat as the main
checkout — I name mine after the default branch (&lt;code&gt;development&lt;/code&gt;), but any name
works. Then add the rest as siblings:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ git clone &amp;lt;repo-url&amp;gt; ~/Projects/&amp;lt;project&amp;gt;/&amp;lt;main-checkout&amp;gt;
$ cd ~/Projects/&amp;lt;project&amp;gt;/&amp;lt;main-checkout&amp;gt;
$ git worktree add ../work-queue
$ git worktree add ../review
$ git worktree add ../experiments
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Without a branch argument, &lt;code&gt;git worktree add&lt;/code&gt; creates a new branch named
after the directory (so &lt;code&gt;../work-queue&lt;/code&gt; gets a branch called &lt;code&gt;work-queue&lt;/code&gt;)
off HEAD. I never commit to these — they exist only so the worktree has
&lt;em&gt;some&lt;/em&gt; branch to initialize with. The real work happens on branches I check
out into the directory later.&lt;/p&gt;
&lt;h2&gt;Rotating Branches through a Directory&lt;/h2&gt;
&lt;p&gt;When a new task comes in, I switch to my &lt;code&gt;work-queue&lt;/code&gt; window and check
out a fresh branch off &lt;code&gt;development&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ git fetch origin
$ git checkout -b TICKET-1234-fix-login origin/development
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That's the whole ceremony. The directory doesn't care what branch it hosts.
When the work is done and the PR is opened, I leave the branch where it is and
move on to the next one — &lt;code&gt;git checkout -b TICKET-1235-...&lt;/code&gt; — and the previous
branch keeps living on the remote.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;review&lt;/code&gt; works the same way, but the branches it hosts already exist. When a
PR lands in my review queue, I switch to the &lt;code&gt;review&lt;/code&gt; window and pull it in:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ git fetch origin
$ git checkout TICKET-1234-fix-login
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I review in the directory, make any fixup commits directly, push, and when
I'm done I rotate to the next PR. No new worktrees to create, no old ones to
clean up.&lt;/p&gt;
&lt;p&gt;In practice I let an agent run most of these commands for me — the mechanics
are identical, just wrapped in a slash command. The next post in this series
covers that layer.&lt;/p&gt;
&lt;h2&gt;Solving the Untracked-File Tax&lt;/h2&gt;
&lt;p&gt;The real reason worktrees feel painful is untracked files. A new worktree is
a fresh checkout — no &lt;code&gt;.env&lt;/code&gt;, no installed dependencies, no local config.
Before you can run anything, you're copying files by hand or re-running setup
scripts.&lt;/p&gt;
&lt;p&gt;I had &lt;a href=&quot;https://claude.com/claude-code&quot;&gt;Claude Code&lt;/a&gt; write a small git subcommand called
&lt;a href=&quot;https://gist.github.com/reagent/a33e0c098f8f2229ce6a3b265f876a4d&quot;&gt;&lt;code&gt;git worktree-copy&lt;/code&gt;&lt;/a&gt; that handles this. It wraps &lt;code&gt;git worktree add&lt;/code&gt; and, after the new worktree is
created, reads a &lt;code&gt;.worktree-copy&lt;/code&gt; file from the repo root to decide what to
copy or run. The config is plain text:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Files and directories to copy from the source checkout
.env
.env.local
config/master.key

# Lines prefixed with ! are shell commands, run inside the new worktree
! bundle install
! pnpm install
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Each entry is either a path to copy over from the source checkout, a &lt;code&gt;!&lt;/code&gt;
prefix that runs the rest of the line as a shell command in the new
worktree, or a comment. I use it like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ git worktree-copy ../work-queue
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Everything after the path is passed straight through to &lt;code&gt;git worktree add&lt;/code&gt;,
so any flag that works there works here too. See the
&lt;a href=&quot;https://gist.github.com/reagent/a33e0c098f8f2229ce6a3b265f876a4d&quot;&gt;gist&lt;/a&gt; for the full script.&lt;/p&gt;
&lt;h2&gt;Shared Caches, Separate Databases&lt;/h2&gt;
&lt;p&gt;Two other gotchas, both about state that lives &lt;em&gt;alongside&lt;/em&gt; the worktree
rather than inside it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Node dependencies.&lt;/strong&gt; Copying &lt;code&gt;node_modules&lt;/code&gt; across worktrees burns disk and
install time quickly. If your project is on &lt;a href=&quot;https://pnpm.io/&quot;&gt;&lt;code&gt;pnpm&lt;/code&gt;&lt;/a&gt;, this is a non-issue
— packages land once in a global content-addressable store and get symlinked
into each worktree's &lt;code&gt;node_modules&lt;/code&gt;, so a fresh worktree costs almost no
disk. If you're still on &lt;code&gt;npm&lt;/code&gt; or &lt;code&gt;yarn&lt;/code&gt;, multiplying &lt;code&gt;node_modules&lt;/code&gt; across
worktrees is a reasonable excuse to switch.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Rails + Postgres databases.&lt;/strong&gt; If your worktrees share a database, they'll
step on each other's schema migrations and data. I parameterize
&lt;code&gt;config/database.yml&lt;/code&gt; so the database name derives from the worktree's
directory, with an environment variable escape hatch when I want to override
it:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;%
  database_base_name = ENV.fetch(&amp;quot;DATABASE_BASE_NAME&amp;quot;) do
    &amp;quot;myapp_#{Rails.root.basename.to_s.gsub(/\W+/, &amp;quot;_&amp;quot;)}&amp;quot;
  end
%&amp;gt;

development:
  database: &amp;lt;%= database_base_name %&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Each worktree now gets its own database keyed to its directory name. The
&lt;code&gt;gsub&lt;/code&gt; scrubs dashes and other non-word characters so Postgres identifiers
stay clean, and setting &lt;code&gt;DATABASE_BASE_NAME&lt;/code&gt; (in &lt;code&gt;.env&lt;/code&gt; or on the CLI)
overrides the auto-inferred name when I want to point two worktrees at a
shared database intentionally. SQLite doesn't need any of this — the
database file lives in the repo and gets its own copy per worktree
naturally.&lt;/p&gt;
&lt;h2&gt;A Note on Branch Naming&lt;/h2&gt;
&lt;p&gt;Because the &lt;code&gt;work-queue&lt;/code&gt; directory hosts many branches over its lifetime, the
branch names need to be self-descriptive. I prefix every branch with the
ticket ID from my tracker (for example, &lt;code&gt;TICKET-1234-fix-login&lt;/code&gt;). That way
&lt;code&gt;git branch --list&lt;/code&gt; and &lt;code&gt;gh pr list&lt;/code&gt; both tell me what I have in flight
without me having to remember which branch was about what. It also makes the
next post in this series — where I let Claude Code drive the pipeline —
possible, because the agent can match branches back to tickets without
guessing.&lt;/p&gt;
&lt;h2&gt;When Not to Use This&lt;/h2&gt;
&lt;p&gt;Worktrees-as-swimlanes earns its keep when:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;You regularly have more than one branch in flight.&lt;/li&gt;
&lt;li&gt;Your setup tax (install, migrate, configure) is non-trivial — enough that
a blank checkout is painful.&lt;/li&gt;
&lt;li&gt;You switch contexts often: feature work → review → hotfix → back to
feature.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;It is overkill when the repo is small enough that a single checkout and the
occasional &lt;code&gt;git stash&lt;/code&gt; is fine, or when branches are short-lived enough that
they merge before the overhead of setting up a worktree pays off.&lt;/p&gt;
&lt;h2&gt;What's Next&lt;/h2&gt;
&lt;p&gt;This setup is worth the effort on its own if you've ever lost ten minutes to
rebuilding a checkout after a context switch. But the real reason I landed on
it is that it lets me pipeline work with an AI agent — one swimlane executing
on the next ticket while I'm reviewing the previous one in another. That's
the subject of the next post.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Serve Your Rails App over SSL in Development Mode</title>
    <id>/articles/serve-your-rails-app-over-ssl-in-development-mode</id>
    <updated>2024-05-13T00:00:00.000Z</updated>
    <link href="https://patrick-reagan.com/articles/serve-your-rails-app-over-ssl-in-development-mode"/>
    <content type="html">&lt;p&gt;Serving your application over SSL in production is a minimum requirement in
2024, but testing your configuration locally can be a pain. Here's how you can
test SSL locally without using external dependencies or &amp;quot;doing it live&amp;quot;.&lt;/p&gt;
&lt;h2&gt;Generate Your Certificate Bundle&lt;/h2&gt;
&lt;p&gt;When first researching a solution, I found &lt;a href=&quot;https://stackoverflow.com/a/77009337&quot;&gt;this answer&lt;/a&gt;
on StackOverflow (&lt;a href=&quot;https://web.archive.org/web/20240528162639/https://stackoverflow.com/questions/59738140/why-is-firefox-not-trusting-my-self-signed-certificate/77009337#77009337&quot;&gt;archived&lt;/a&gt;) that went into great detail about
how to create a Certificate Authority that can then be used to generate multiple
SSL certificates. The general approach is:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Generate a private Certificate Authority (CA)&lt;/li&gt;
&lt;li&gt;Generate a Certificate Signing Request (CSR) using the Common Name of the
hostname you will be serving over SSL&lt;/li&gt;
&lt;li&gt;Generate a certificate that is signed by the private CA along with an
accompanying private key&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Rather than copy/pasting these commands into a terminal session each time you
want to generate a new SSL certificate, you can automate them with a
&lt;a href=&quot;https://gist.github.com/reagent/cd9abf8984548b055a0adf8cbae68b9b&quot;&gt;parameterized Rake task&lt;/a&gt;. Invoke it with the desired CN (hostname)
of your server:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;rails &amp;quot;cert:generate[host.example]&amp;quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When first invoked it will create the CA certificate, but subsequent invocations
will skip this step and just generate the necessary certificate files. Your
&lt;code&gt;config/certs&lt;/code&gt; directory will now look like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ tree config/certs
config/certs
├── host.example.crt &amp;lt;-- Server SSL certificate
├── host.example.csr &amp;lt;-- CSR file (ignore)
├── host.example.key &amp;lt;-- Private key for server certificate
├── root-ca.crt      &amp;lt;-- Root CA certificate (install in certificate store)
├── root-ca.key      &amp;lt;-- Root CA private key
└── root-ca.srl      &amp;lt;-- Certificate serial number store

1 directory, 6 files
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Configure Hostname Resolution&lt;/h2&gt;
&lt;p&gt;Whichever hostname you pick, you'll need to ensure it's resolvable. The easiest
way to do this is to add it to your local &lt;code&gt;/etc/hosts&lt;/code&gt; file:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;echo &amp;quot;127.0.0.1 host.example&amp;quot; | sudo tee -a /etc/hosts
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Repeat this for each hostname you want to resolve, but keep in mind that if you
shadow a publicly-resolvable hostname you'll want to remove it from &lt;code&gt;/etc/hosts&lt;/code&gt;
later to prevent conflicts when you go to production.&lt;/p&gt;
&lt;h2&gt;Configure Your Rails Application&lt;/h2&gt;
&lt;p&gt;Before you can connect to your server, you'll need to whitelist the hostname to
prevent the &lt;a href=&quot;https://guides.rubyonrails.org/configuring.html#actiondispatch-hostauthorization&quot;&gt;host authorization middleware&lt;/a&gt; from blocking your
requests. You can do this by adding the hostname to the approved list:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ruby&quot;&gt;# config/environments/development.rb
Rails.application.configure do
  config.hosts &amp;lt;&amp;lt; 'host.example'
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Or just disable the check if you're using multiple hostnames:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ruby&quot;&gt;# config/environments/development.rb
Rails.application.configure do
  config.hosts = []
end
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Scoping this configuration to the &lt;code&gt;development&lt;/code&gt; environment ensures you
won't accidentally open your production environment to &lt;code&gt;Host&lt;/code&gt; header attacks&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;A common reason for running HTTPS locally is to confirm that Rails's
&lt;a href=&quot;https://guides.rubyonrails.org/configuring.html#config-force-ssl&quot;&gt;&lt;code&gt;force_ssl&lt;/code&gt;&lt;/a&gt; option is working as expected, so go ahead and
configure that too:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ruby&quot;&gt;# config/environments/development.rb
Rails.application.configure do
  config.force_ssl = ENV['FORCE_SSL'].present?
end
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Start the Rails Server&lt;/h2&gt;
&lt;p&gt;When you ran the &lt;code&gt;cert:generate&lt;/code&gt; task, it provided some helpful output:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Files needed for configuration:

             Root CA: /path/to/config/certs/root-ca.crt (add to your browser certs)
  Server Certificate: /path/to/config/certs/host.example.crt
          Server Key: /path/to/config/certs/host.example.key

Run your server in SSL mode:

  sudo rails server -b 'ssl://host.example:443?key=/path/to/config/certs/host.example.key&amp;amp;cert=/path/to/config/certs/host.example.crt'
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;The &lt;code&gt;--binding&lt;/code&gt; option (aliased as &lt;code&gt;-b&lt;/code&gt;) allows us to specify a custom binding
other than the default of &lt;code&gt;127.0.0.1:3000&lt;/code&gt;. In this case we are binding to
port &lt;code&gt;443&lt;/code&gt; and providing the necessary certificate details. The use of &lt;code&gt;sudo&lt;/code&gt;
is required because we are binding to a privileged port.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Once the server is started in SSL mode, fire up another Rails server on port
&lt;code&gt;80&lt;/code&gt; to test the &lt;code&gt;force_ssl&lt;/code&gt; redirect configuration:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;FORCE_SSL=1 sudo -E rails server -b 'host.example' -p 80 -P tmp/pids/server-http.pid
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;The use of &lt;code&gt;-E&lt;/code&gt; ensures the &lt;code&gt;FORCE_SSL&lt;/code&gt; environment variable will be passed
to the &lt;code&gt;rails server&lt;/code&gt; command, and the the &lt;code&gt;--pid&lt;/code&gt; option (aliased as &lt;code&gt;-P&lt;/code&gt;) will
permit two Rails processes to track their PIDs separately instead of using the
default &lt;code&gt;tmp/pids/server.pid&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Now that we've simulated a common redirect scenario, we can use &lt;a href=&quot;https://curl.haxx.se&quot;&gt;cURL&lt;/a&gt; to
ensure everything works correctly.&lt;/p&gt;
&lt;h2&gt;Test the Connection&lt;/h2&gt;
&lt;p&gt;We'll connect to the &lt;a href=&quot;https://api.rubyonrails.org/classes/Rails/HealthController.html&quot;&gt;health check&lt;/a&gt; route that ships with modern versions of
Rails, but since we're using a private CA to sign our server certificate we'll
need to provide that PEM-encoded certificate to allow cURL to trust our server
certificate:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;curl \
  --include \
  --location \
  --cacert config/certs/root-ca.crt \
  http://host.example/up
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Using this command, we should see a &lt;code&gt;301&lt;/code&gt; redirect and the resulting status
served over SSL:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;HTTP/1.1 301 Moved Permanently
content-type: text/html; charset=utf-8
location: https://host.example/up
Content-Length: 0

HTTP/1.1 200 OK
x-frame-options: SAMEORIGIN
x-xss-protection: 0
x-content-type-options: nosniff
x-permitted-cross-domain-policies: none
referrer-policy: strict-origin-when-cross-origin
content-type: text/html; charset=utf-8
vary: Accept
etag: W/&amp;quot;7e6c9877b2dec7dfadc43e742246d94d&amp;quot;
cache-control: max-age=0, private, must-revalidate
x-request-id: ad037646-fe4f-44a0-9454-0461908e06e4
x-runtime: 0.010109
server-timing: start_processing.action_controller;dur=0.01, render_template.action_view;dur=0.01, process_action.action_controller;dur=0.87
Content-Length: 73

&amp;lt;!DOCTYPE html&amp;gt;&amp;lt;html&amp;gt;&amp;lt;body style=&amp;quot;background-color: green&amp;quot;&amp;gt;&amp;lt;/body&amp;gt;&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Success!&lt;/p&gt;
&lt;h2&gt;Trust Your CA Certificate&lt;/h2&gt;
&lt;p&gt;If you're connecting to your server using cURL, it's annoying to have to provide
the &lt;code&gt;--cacert&lt;/code&gt; option with every invocation, and if you're connecting via a
browser, your requests may get rejected due to the default security policy. If
you're on macOS, there are a couple of steps you need to take to ensure the
private CA cert we created is trusted in Firefox, Safari, Chrome, and cURL:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Open Keychain Access and add the CA certificate to your &amp;quot;login&amp;quot; keychain by
dragging and dropping it into the &amp;quot;Certificates&amp;quot; list:&lt;/p&gt;
 &lt;div style=&quot;display: flex; justify-content: center&quot;&gt;
   &lt;img src=&quot;/assets/images/rails-ssl/keychain-access.png&quot; /&gt;
 &lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Double-click the certificate in the list, expand the &amp;quot;Trust&amp;quot; section, and
select &amp;quot;Always Trust&amp;quot; from the drop-down (the setting will be updated when you
close the detail window):&lt;/p&gt;
 &lt;div style=&quot;display: flex; justify-content: center&quot;&gt;
   &lt;img src=&quot;/assets/images/rails-ssl/trust-certificate.png&quot; /&gt;
 &lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;For Firefox specifically, open
&amp;quot;Preferences &amp;gt; Privacy &amp;amp; Security &amp;gt; View Certificates ...&amp;quot;, click
&amp;quot;Import ...&amp;quot;, and import the root CA certificate:&lt;/p&gt;
 &lt;div style=&quot;display: flex; justify-content: center&quot;&gt;
   &lt;img src=&quot;/assets/images/rails-ssl/import-firefox-certificate.png&quot; /&gt;
 &lt;/div&gt;
&lt;blockquote&gt;
&lt;p&gt;See &lt;a href=&quot;https://javorszky.co.uk/2019/11/06/get-firefox-to-trust-your-self-signed-certificates/&quot;&gt;this post&lt;/a&gt; for a deeper dive on how to configure
this for Firefox&lt;/p&gt;
&lt;/blockquote&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Alternatively, if you're just using cURL, you can add your root certificate to
the local store and avoid having to use &lt;code&gt;--capath&lt;/code&gt; all over the place. First,
find out where the store is located:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;curl -v https://host.example 2&amp;gt;&amp;amp;1 | grep CAfile
*  CAfile: /etc/ssl/cert.pem
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then append the certificate to the list, making sure to keep a backup:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;sudo cp /etc/ssl/cert.pem{,.bak} &amp;amp;&amp;amp; cat config/certs/root-ca.crt | sudo tee -a /etc/ssl/cert.pem
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;With this streamlined setup, you can more easily test your SSL configuration and
test cases where external services require callbacks to be served over a secure
connection.&lt;/p&gt;
&lt;hr&gt;
</content>
  </entry>
  <entry>
    <title>Working with External Services in Nest.js</title>
    <id>/articles/working-with-external-services-in-nestjs</id>
    <updated>2021-09-30T00:00:00.000Z</updated>
    <link href="https://patrick-reagan.com/articles/working-with-external-services-in-nestjs"/>
    <content type="html">&lt;p&gt;At its core, &lt;a href=&quot;https://docs.nestjs.com/&quot;&gt;Nest.js&lt;/a&gt; provides a robust&lt;a href=&quot;https://en.wikipedia.org/wiki/Dependency_injection&quot;&gt; dependency injection&lt;/a&gt;
&lt;a href=&quot;https://docs.nestjs.com/providers#dependency-injection&quot;&gt;system&lt;/a&gt; for resolving dependencies within your application. While a
typical use case might be to inject a database connection into any service
classes that need it, where this can really shine is when your application
relies on one or more external service(s).&lt;/p&gt;
&lt;p&gt;A solution that we often employ in this situation looks like the following:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Create a TypeScript interface that provides an ergonomic surface area for how
we want to interact with the external service&lt;/li&gt;
&lt;li&gt;Create concrete classes that implement this interface that we can use in both
a local development environment and a remote production environment&lt;/li&gt;
&lt;li&gt;Create a referenceable service token that can be used to inject the right
dependency as needed&lt;/li&gt;
&lt;li&gt;Create a service fake that implements the above interface that can be
injected for use in our end-to-end (e2e) tests&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;In Practice&lt;/h2&gt;
&lt;p&gt;A server-side application will typically need to send email, so let's think
about how that looks in its simplest form. As promised, we'll tackle the
interface first:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;type Message = {
  from: string;
  to: string;
  subject: string;
  body: string;
};

interface Mailer {
  send(message: Message): Promise&amp;lt;void&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we can introduce some concrete classes that implement this interface. First,
we'll start with a class that will &lt;em&gt;actually&lt;/em&gt; send an email through an SMTP
relay (using &lt;a href=&quot;https://nodemailer.com/about/&quot;&gt;nodemailer&lt;/a&gt;):&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;type SMTPMailerOptions = {
  host: string;
  username: string;
  password: string;
};

class SMTPMailer implements Mailer {
  protected readonly transport: ReturnType&amp;lt;typeof createTransport&amp;gt;;

  constructor(options: SMTPMailerOptions) {
    this.transport = createTransport({
      host: options.host,
      auth: {
        user: options.username,
        pass: options.password,
      },
    });
  }

  async send(message: Message): Promise&amp;lt;void&amp;gt; {
    await this.transport.sendMail({
      from: message.from,
      to: message.to,
      subject: message.subject,
      text: message.body,
    });
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And a corresponding class that will satisfy this interface but will log the
message rather than attempting delivery:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;class LoggingMailer implements Mailer {
  send(message: Message): Promise&amp;lt;void&amp;gt; {
    return Promise.resolve(console.info(JSON.stringify(message)));
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Injecting Our Dependency&lt;/h2&gt;
&lt;p&gt;In order to use these mailer classes, we now need to make Nest's dependency
injection system aware of them. Because we're not providing a concrete class
(we'll be using our &lt;code&gt;Mailer&lt;/code&gt; interface), we need to specify a service token that
can be resolved to an instance of a &lt;code&gt;Mailer&lt;/code&gt; class.&lt;/p&gt;
&lt;p&gt;The service token can be a string, but I like taking the extra step of creating
a &lt;a href=&quot;https://www.typescriptlang.org/docs/handbook/enums.html#string-enums&quot;&gt;TypeScript &lt;code&gt;enum&lt;/code&gt;&lt;/a&gt; to make things less error-prone:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;enum ServiceTokens {
  Mailer = &amp;quot;SERVICE_TOKENS_MAILER&amp;quot;,
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, we can register our mailer as a provider -- I like the
&lt;a href=&quot;https://docs.nestjs.com/fundamentals/custom-providers#factory-providers-usefactory&quot;&gt;&lt;code&gt;useFactory&lt;/code&gt; approach&lt;/a&gt; for most cases:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// app.module.ts

@Module({
  providers: [
    {
      provide: ServiceTokens.Mailer,
      useFactory: (): Mailer =&amp;gt; {
        const env = process.env.NODE_ENV || &amp;quot;development&amp;quot;;

        if ([&amp;quot;development&amp;quot;, &amp;quot;test&amp;quot;].includes(env)) {
          return new LoggingMailer();
        }

        // Typically, this configuration would come
        // from external environment variables
        return new SMTPMailer({
          host: &amp;quot;smtp.relay&amp;quot;,
          username: &amp;quot;admin&amp;quot;,
          password: &amp;quot;d34db33f&amp;quot;,
        });
      },
    },
  ],
})
export class AppModule {}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So ... in our local environments we'll simply log all email messages, otherwise
we will try to send through the configured SMTP server.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The credentials in this example are hard-coded but you'll definitely want to
pull this configuration from your environment. The official
&lt;a href=&quot;https://docs.nestjs.com/techniques/configuration&quot;&gt;Nest documentation&lt;/a&gt; is a good place to research approaches.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Putting It All Together&lt;/h2&gt;
&lt;p&gt;Now that we've registered our mailer as a provider, we can inject it anywhere
we need to. Let's put together a simple controller that will send a message to
a target recipient:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;class Recipient {
  email: string;
}

@Controller(&amp;quot;notifications&amp;quot;)
@Injectable()
export class NotificationsController {
  constructor(
    @Inject(ServiceTokens.Mailer) protected readonly mailer: Mailer
  ) {}

  @Post()
  @HttpCode(HttpStatus.OK)
  async notify(@Body() recipient: Recipient) {
    await this.mailer.send({
      from: &amp;quot;noreply@host.example&amp;quot;,
      to: recipient.email,
      subject: &amp;quot;Notification&amp;quot;,
      body: &amp;quot;You have been notified!&amp;quot;,
    });

    return { status: &amp;quot;ok&amp;quot; };
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Make sure to add the controller to your &lt;code&gt;AppModule&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// app.module.ts

@Module({
  controllers: [NotificationsController],
  // ...
})
export class AppModule {}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You should now be able to boot your app with &lt;code&gt;yarn start:dev&lt;/code&gt; and use
&lt;a href=&quot;https://curl.se/&quot;&gt;cURL&lt;/a&gt; to initiate a message send:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;curl -s \
  -H &amp;quot;Content-Type: application/json&amp;quot; \
  -d '{&amp;quot;email&amp;quot;:&amp;quot;user@host.example&amp;quot;}' \
  &amp;quot;http://localhost:3000/notifications&amp;quot; | python -m json.tool
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You should see a response of &lt;code&gt;{&amp;quot;status&amp;quot;: &amp;quot;ok&amp;quot;}&lt;/code&gt; and see a message printed to the
Nest.js console:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{&amp;quot;from&amp;quot;:&amp;quot;noreply@host.example&amp;quot;,&amp;quot;to&amp;quot;:&amp;quot;user@host.example&amp;quot;,&amp;quot;subject&amp;quot;:&amp;quot;Notification&amp;quot;,&amp;quot;body&amp;quot;:&amp;quot;You have been notified!&amp;quot;}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Bonus: Adding a Fake for E2E Testing&lt;/h2&gt;
&lt;p&gt;We've already guarded against accidentally sending emails in our test
environment, but what about when we want to assert whether or not an email was
sent from our application? An approach that I prefer over using a tool like
&lt;a href=&quot;https://jestjs.io/docs/jest-object#jestspyonobject-methodname&quot;&gt;&lt;code&gt;jest.spyOn()&lt;/code&gt;&lt;/a&gt; is to introduce a
&lt;a href=&quot;https://tyrrrz.me/blog/fakes-over-mocks&quot;&gt;lightweight fake&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;We can again rely on the initial interface definition to help define our fake:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;class MailerFake implements Mailer {
  lastMessage?: Message;

  send(message: Message): Promise&amp;lt;void&amp;gt; {
    this.lastMessage = message;
    return Promise.resolve();
  }

  clear(): void {
    this.lastMessage = undefined;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Swapping out our mailer at test time is as easy as using &lt;code&gt;overrideProvider()&lt;/code&gt;
when creating our testing module:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// test/notifications.e2e-spec.ts

describe(&amp;quot;Notifications (e2e)&amp;quot;, () =&amp;gt; {
  let app: INestApplication;
  let mailer: MailerFake;

  beforeAll(async () =&amp;gt; {
    mailer = new MailerFake();

    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    })
      .overrideProvider(ServiceTokens.Mailer)
      .useValue(mailer)
      .compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  afterAll(async () =&amp;gt; await app.close());

  // prevent pollution between tests
  afterEach(() =&amp;gt; mailer.clear());

  it(&amp;quot;sends an email to the specified recipient&amp;quot;, async () =&amp;gt; {
    const { body, status } = await request(app.getHttpServer())
      .post(&amp;quot;/notifications&amp;quot;)
      .send({ email: &amp;quot;user@host.example&amp;quot; });

    expect(body).toEqual({ status: &amp;quot;ok&amp;quot; });
    expect(status).toBe(HttpStatus.OK);

    expect(mailer.lastMessage).toEqual({
      from: &amp;quot;noreply@host.example&amp;quot;,
      to: &amp;quot;user@host.example&amp;quot;,
      subject: &amp;quot;Notification&amp;quot;,
      body: &amp;quot;You have been notified!&amp;quot;,
    });
  });
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we have a robust solution that sends mail when we want, doesn't send mail
when we don't want, and allows us to have confidence that our application was
doing the right thing the whole time.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;em&gt;This article was originally posted on the &lt;a href=&quot;https://archive.today/PAoJ0&quot;&gt;KindHealth engineering blog&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Managing Connections in Express Apps</title>
    <id>/articles/managing-connections-in-express-apps</id>
    <updated>2021-06-02T00:00:00.000Z</updated>
    <link href="https://patrick-reagan.com/articles/managing-connections-in-express-apps"/>
    <content type="html">&lt;p&gt;Typically when building apps in &lt;a href=&quot;http://expressjs.com/&quot;&gt;Express&lt;/a&gt; you'll be using some sort of
persistence mechanism, whether that is a relational database, NoSQL database, or
another object store. Certain circumstances require using two stores
simultaneously, perhaps if you want to use an RDBMS as a source of truth but
leverage something like &lt;a href=&quot;https://redis.io/&quot;&gt;Redis&lt;/a&gt; as a cache to boost overall performance.
Whatever technology you're using in your application, you'll want to ensure that
connections are established (or have failed fast) before you fully boot your
app.&lt;/p&gt;
&lt;p&gt;Introductory tutorials often take the approach of initializing the database
connection independently from booting the Express app -- &lt;a href=&quot;https://stackabuse.com/using-sequelize-orm-with-nodejs-and-express&quot;&gt;this tutorial&lt;/a&gt; is a
top result but there are many like it. The typical approach is as follows (we're
using &lt;a href=&quot;https://sequelize.org/&quot;&gt;Sequelize&lt;/a&gt; with &lt;a href=&quot;https://sqlite.org/index.html&quot;&gt;sqlite&lt;/a&gt; here):&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;const app = express();
app.use(express.json());

sequelize
  .authenticate()
  .then(() =&amp;gt; {
    console.log(&amp;quot;Database connection established&amp;quot;);
  })
  .catch((err) =&amp;gt; {
    console.log(`Connection failed: ${err}`);
  });

app.get(&amp;quot;/users&amp;quot;, async (_, resp) =&amp;gt; {
  const users = await User.findAll(); // User is a Sequelize model
  resp.status(200).json({ users });
});

app.listen(3000, () =&amp;gt; {
  console.log(&amp;quot;Listening on port 3000&amp;quot;);
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The problem may not be obvious, but we've created a situation where 2 unintended
outcomes are possible:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Requests to the &lt;code&gt;/users&lt;/code&gt; endpoint return no data because a request is made
before the database connection is established&lt;/li&gt;
&lt;li&gt;The connection to the database fails, but the application starts in a broken
state (requests to &lt;code&gt;/users&lt;/code&gt; hang since the database is unavailable)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;We can handle the second scenario by exiting the process when the database
connection fails, but there could be a period of time where the app starts
handling requests waiting for the connection to finally time out.&lt;/p&gt;
&lt;p&gt;Fortunately, there are a couple of solutions to ensure that the application
starts in a valid state.&lt;/p&gt;
&lt;h2&gt;Wait for the Connection Promise to Resolve&lt;/h2&gt;
&lt;p&gt;What might be the quickest solution is to move the &amp;quot;listen&amp;quot; operation inside of
the resolved promise after the connection is established:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;app.get(&amp;quot;/users&amp;quot;, async (_, resp) =&amp;gt; {
  const users = await User.findAll(); // User is a Sequelize model
  resp.status(200).json({ users });
});

sequelize
  .authenticate()
  .then(() =&amp;gt; {
    console.log(&amp;quot;Database connection established&amp;quot;);

    app.listen(3000, () =&amp;gt; {
      console.log(&amp;quot;Listening on port 3000&amp;quot;);
    });
  })
  .catch((err) =&amp;gt; {
    console.error(`Connection failed: ${err}`);
    process.exit(1);
  });
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This way, the application will only be available once the database connection is
available, and the &lt;code&gt;process.exit&lt;/code&gt; call will ensure that the process exits with
an error status for anything monitoring it. This can also be accomplished using
&lt;code&gt;async&lt;/code&gt; / &lt;code&gt;await&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;(async () =&amp;gt; {
  try {
    await sequelize.authenticate();
    console.log(&amp;quot;Database connection established&amp;quot;);
  } catch (e) {
    console.error(e);
    process.exit(1);
  }

  app.listen(3000, () =&amp;gt; {
    console.log(&amp;quot;Listening on port 3000&amp;quot;);
  });
})();
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Use Node's Built-In Event Handling&lt;/h2&gt;
&lt;p&gt;Node supports an &lt;a href=&quot;https://nodejs.org/docs/latest-v14.x/api/events.html&quot;&gt;event-driven architecture&lt;/a&gt; at its core, and Express builds
on these core capabilities. Inspired by &lt;a href=&quot;https://blog.cloudboost.io/waiting-for-db-connections-before-app-listen-in-node-f568af8b9ec9&quot;&gt;this blog post&lt;/a&gt;, we can adopt an
approach that listens for events before starting the server:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;app.get(&amp;quot;/users&amp;quot;, async (_, resp) =&amp;gt; {
  const users = await User.findAll(); // User is a Sequelize model
  resp.status(200).json({ users });
});

app.once(&amp;quot;connected&amp;quot;, () =&amp;gt; {
  app.listen(3000, () =&amp;gt; {
    console.log(&amp;quot;Listening on port 3000&amp;quot;);
  });
});

sequelize
  .authenticate()
  .then(() =&amp;gt; {
    console.log(&amp;quot;Database connection established&amp;quot;);
    app.emit(&amp;quot;connected&amp;quot;);
  })
  .catch((e) =&amp;gt; {
    console.error(e);
    process.exit(1);
  });
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Similar to the previous example, the app will only boot once the event has been
emitted. Though this could result in some disconnect between the strings used in
the event handlers, that can be easily mitigated using a TypeScript &lt;code&gt;enum&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;enum Events {
  Connected = &amp;quot;connected&amp;quot;,
}

app.once(Events.Connected, () =&amp;gt; {
  app.listen(3000, () =&amp;gt; {
    console.log(&amp;quot;Listening on port 3000&amp;quot;);
  });
});

sequelize
  .authenticate()
  .then(() =&amp;gt; {
    console.log(&amp;quot;Database connection established&amp;quot;);
    app.emit(Events.Connected);
  })
  .catch((e) =&amp;gt; {
    console.error(e);
    process.exit(1);
  });
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Again, it's possible to use &lt;code&gt;async&lt;/code&gt; / &lt;code&gt;await&lt;/code&gt; semantics:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;(async () =&amp;gt; {
  try {
    await sequelize.authenticate();
    console.log(&amp;quot;Database connection established&amp;quot;);
  } catch (e) {
    console.error(e);
    process.exit(1);
  }

  app.emit(Events.Connected);
})();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Both of these approaches provide a cleaner way to ensure that your Express
applications boot successfully or fail fast.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;em&gt;This article was originally posted on the &lt;a href=&quot;https://archive.today/mO5iz&quot;&gt;KindHealth engineering blog&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>3 Uses of `git rebase` for Your Daily Workflow</title>
    <id>/articles/3-uses-of-git-rebase</id>
    <updated>2020-10-07T00:00:00.000Z</updated>
    <link href="https://patrick-reagan.com/articles/3-uses-of-git-rebase"/>
    <content type="html">&lt;p&gt;&lt;a href=&quot;https://git-scm.com/book/en/v2/Git-Branching-Rebasing&quot;&gt;Rebasing&lt;/a&gt; is a way of rewriting your local history by applying commits to your
working tree in a different order from how they were originally made.&lt;/p&gt;
&lt;p&gt;There are 3 flavors that I find useful in my daily work:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;code&gt;git rebase &amp;lt;branch-name&amp;gt;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;git rebase -i &amp;lt;commit&amp;gt;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;git rebase --onto &amp;lt;new-base&amp;gt; &amp;lt;old-base&amp;gt;&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Using &lt;code&gt;git rebase &amp;lt;branch-name&amp;gt;&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;I use this to get my local branch history up-to-date with the mainline
development branch. It allows for a linear history on my branch and optionally a
linear history on the main branch.&lt;/p&gt;
&lt;p&gt;For example, here I have branched off &lt;code&gt;master&lt;/code&gt; to &lt;code&gt;feature&lt;/code&gt; and the histories
have diverged:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;a--b--c--d   master
    \
     e--f--g feature
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I now want to apply my changes from &lt;code&gt;feature&lt;/code&gt; to &lt;code&gt;master&lt;/code&gt;, but I want to include
the current history of &lt;code&gt;master&lt;/code&gt; into &lt;code&gt;feature&lt;/code&gt; so that my main branch can have a
linear history. I can use &lt;code&gt;git rebase&lt;/code&gt; to make this happen:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ git checkout master
$ git pull # get my local master in sync with remote
$ git checkout feature
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;At this point, I'm ready to modify my branch to have a new &amp;quot;base&amp;quot; -- looking at
the previous history, the first commit on &lt;code&gt;feature&lt;/code&gt; (commit &lt;code&gt;e&lt;/code&gt;) has a &amp;quot;base&amp;quot;
(or parent commit) of &lt;code&gt;b&lt;/code&gt;. Instead, I want to change my history to be based off
of a different parent (&lt;code&gt;d&lt;/code&gt; or &lt;code&gt;master&lt;/code&gt; in this case):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ git rebase master
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This version of &lt;code&gt;rebase&lt;/code&gt; will get &lt;code&gt;feature&lt;/code&gt; up-to-date with the current &lt;code&gt;master&lt;/code&gt;
and then &lt;em&gt;re-apply&lt;/em&gt; all the commits from &lt;code&gt;feature&lt;/code&gt; on top of this new &amp;quot;base&amp;quot;. If
there are any conflicts, I'll have a chance to correct them and continue the
process.&lt;/p&gt;
&lt;p&gt;Once completed, my history will look like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;a--b--c--d   master
          \
           e'--f'--g' feature
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Each of these &lt;em&gt;new&lt;/em&gt; commits performs the same changes, but the &amp;quot;prime&amp;quot; (&lt;code&gt;'&lt;/code&gt;)
indicator designates that these have different SHAs and, due to our desired
rebase operation, different parents.&lt;/p&gt;
&lt;p&gt;Now, I can choose to merge this with master and maintain a linear history:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ git checkout master
$ git merge feature --ff-only # Don't create a merge commit
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now my history looks like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;a--b--c--d--e'--f'--g'  master
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Using &lt;code&gt;git rebase -i &amp;lt;commit&amp;gt;&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;Before rebasing &lt;code&gt;master&lt;/code&gt;, I'll typically use the &lt;code&gt;--interactive&lt;/code&gt; variant to
clean up my commit history by providing better comments and grouping related
changes together into a single commit.&lt;/p&gt;
&lt;p&gt;Let's say that I branched off of &lt;code&gt;master&lt;/code&gt; and made a few changes on my branch
that I'm about ready to merge back in:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  * update .gitignore
  |
  * moar config
  |
* * wip
| |
* * config
|/
*
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It's useful to just be able to add commits as backstops as I'm figuring out how
to actually get something working, but I don't want these unhelpful comments
showing up in the history. I can use an interactive rebase to reorder, change,
and even delete the commits that I've made.&lt;/p&gt;
&lt;p&gt;Now that I have a handle on what changes I actually need, I've decided that I
want to:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Combine the 2 commits that changed the config file&lt;/li&gt;
&lt;li&gt;Modify the commit message for the config file changes&lt;/li&gt;
&lt;li&gt;Modify the commit message for our WIP commmit&lt;/li&gt;
&lt;li&gt;Remove the commit that changes the &lt;code&gt;.gitignore&lt;/code&gt; file&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;If I invoke &lt;code&gt;git rebase&lt;/code&gt; with &lt;code&gt;-i&lt;/code&gt;, it will drop me into my default editor:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ git rebase -i HEAD~4 # can also take a commit SHA
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;My editor (in this case, vim) will be invoked and display the relevant commit
history:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pick 0cb4a62 config
pick 1f7c8d7 wip
pick 2151280 moar config
pick bcc7808 update .gitignore

# Rebase 0b4f673..bcc7808 onto 0b4f673 (4 commands)
#
# Commands:
# p, pick &amp;lt;commit&amp;gt; = use commit
# r, reword &amp;lt;commit&amp;gt; = use commit, but edit the commit message
# e, edit &amp;lt;commit&amp;gt; = use commit, but stop for amending
# s, squash &amp;lt;commit&amp;gt; = use commit, but meld into previous commit
# f, fixup &amp;lt;commit&amp;gt; = like &amp;quot;squash&amp;quot;, but discard this commit's log message
# x, exec &amp;lt;command&amp;gt; = run command (the rest of the line) using shell
# b, break = stop here (continue rebase later with 'git rebase --continue')
# d, drop &amp;lt;commit&amp;gt; = remove commit
# l, label &amp;lt;label&amp;gt; = label current HEAD with a name
# t, reset &amp;lt;label&amp;gt; = reset HEAD to a label
# m, merge [-C &amp;lt;commit&amp;gt; | -c &amp;lt;commit&amp;gt;] &amp;lt;label&amp;gt; [# &amp;lt;oneline&amp;gt;]
# .       create a merge commit using the original merge commit's
# .       message (or the oneline, if no original merge commit was
# .       specified). Use -c &amp;lt;commit&amp;gt; to reword the commit message.
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By default these are all marked as &lt;code&gt;pick&lt;/code&gt; -- exiting the editor without
modifications won't change the commit history. If I move the commits around and
label each like the following:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;reword 0cb4a62 config
fixup 2151280 moar config
reword 1f7c8d7 wip
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Exiting the editor will start the rebase operation and drop us into the editor
to update, or &amp;quot;reword&amp;quot; the commit messages we want to change. Once completed,
we'll be left with a history that might look like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;* * Add helper script to decrypt secrets in dev
| |
* * Add secrets to main config file
|/
*
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we're ready to rebase and merge into our &lt;code&gt;master&lt;/code&gt; branch.&lt;/p&gt;
&lt;h2&gt;Using &lt;code&gt;git rebase --onto &amp;lt;new-base&amp;gt; &amp;lt;old-base&amp;gt;&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;At times, I may make a feature branch that, while I'm waiting to merge it, I
would like to start another feature that requires changes made on that feature
branch:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;a--b--c--d     master
    \
     e--f      feature-1
         \
          g--h feature-2
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After merging my first feature to &lt;code&gt;master&lt;/code&gt;, my new feature branch &lt;code&gt;feature-2&lt;/code&gt;
has diverged:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;a--b--c--d--e'--f' master
    \
     e--f--g--h   feature-2
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can see that, although &lt;code&gt;e&lt;/code&gt; and &lt;code&gt;f&lt;/code&gt; are the same as what are on &lt;code&gt;master&lt;/code&gt;, they
have different SHAs, so if we merge these, we'll be in for a bad time. The
answer is to apply our commits from &lt;code&gt;feature-2&lt;/code&gt; on top of commit &lt;code&gt;f'&lt;/code&gt; while
dropping the duplicate commits on the floor. &lt;code&gt;git rebase --onto&lt;/code&gt; to the rescue:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ git rebase --onto f' f
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This will apply our new commits from &lt;code&gt;feature-2&lt;/code&gt; (commits &lt;code&gt;g&lt;/code&gt; and &lt;code&gt;h&lt;/code&gt;) on top of
&lt;code&gt;f'&lt;/code&gt; -- we now end up like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;a--b--c--d--e'--f' master
                 \
                  g--h   feature-2
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now I can do any other needed work to get &lt;code&gt;feature-2&lt;/code&gt; ready to merge with
&lt;code&gt;master&lt;/code&gt;.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Two Ways to Share Git Hooks with Your Team</title>
    <id>/articles/two-ways-to-share-git-hooks-with-your-team</id>
    <updated>2017-05-05T00:00:00.000Z</updated>
    <link href="https://patrick-reagan.com/articles/two-ways-to-share-git-hooks-with-your-team"/>
    <content type="html">&lt;p&gt;&lt;a href=&quot;https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks&quot;&gt;Git hooks&lt;/a&gt; are a useful feature that can be used to manage the integrity of
your source repository. On my current project, I wanted to ensure that all my Go
source files were formatted correctly before allowing them to be committed.&lt;/p&gt;
&lt;p&gt;Fortunately for me, there is a &lt;a href=&quot;https://web.archive.org/web/20170404181131/https://golang.org/misc/git/pre-commit?m=text&quot;&gt;simple hook&lt;/a&gt; available that I can save as
&lt;code&gt;.git/hooks/pre-commit&lt;/code&gt; to make this happen.&lt;/p&gt;
&lt;p&gt;This works well for my purposes, but I wanted to make it as simple as possible
when sharing with the rest of the team. &lt;a href=&quot;https://stackoverflow.com/questions/427207/can-git-hook-scripts-be-managed-along-with-the-repository&quot;&gt;This Stack Overflow post&lt;/a&gt; gives a
couple of possibilities that I'll go into more depth about.&lt;/p&gt;
&lt;h2&gt;Create Your Managed Hooks Directory&lt;/h2&gt;
&lt;p&gt;Since the &lt;code&gt;.git&lt;/code&gt; directory isn't versioned, I created &lt;code&gt;.githooks&lt;/code&gt; at the root
where all these hooks live. You can choose whatever makes the most sense for
your project. Remember that when adding hooks they must be executable, so make
sure you &lt;code&gt;chmod +x&lt;/code&gt; each of them to make that happen. Otherwise, you'll tear
your hair out when you think they should run but they don't.&lt;/p&gt;
&lt;h2&gt;Choose Your Sharing Strategy&lt;/h2&gt;
&lt;p&gt;If you're using Git &lt;a href=&quot;https://raw.githubusercontent.com/git/git/master/Documentation/RelNotes/2.9.0.txt&quot;&gt;version 2.9&lt;/a&gt; or greater, this is as simple as setting
the &lt;code&gt;core.hooksPath&lt;/code&gt; configuration variable to your managed hooks directory:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ git config core.hooksPath .githooks
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you're using an earlier version, you need to ensure that your managed hooks
make it into the &lt;code&gt;.git/hooks&lt;/code&gt; directory. I think symlinking is a good way to go,
just make sure to clear the old ones out first:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ find .git/hooks -type l -exec rm {} \; &amp;amp;&amp;amp; find .githooks -type f -exec ln -sf ../../{} .git/hooks/ \;
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Share with Your Team&lt;/h2&gt;
&lt;p&gt;That takes care of your local configuration, but each team member will need to
ensure the hooks are in the right place in their local repository each time they
do a new checkout. I like to just put this into my &lt;code&gt;Makefile&lt;/code&gt; and include it
into my general project setup. Here are the two variations expressed as make
targets:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;init:
  git config core.hooksPath .githooks
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;init:
  find .git/hooks -type l -exec rm {} \;
  find .githooks -type f -exec ln -sf ../../{} .git/hooks/ \;
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;p&gt;&lt;em&gt;A version of this article first appeared on the &lt;a href=&quot;https://www.viget.com/articles/two-ways-to-share-git-hooks-with-your-team/&quot;&gt;Viget&lt;/a&gt; blog&lt;/em&gt;&lt;/p&gt;
</content>
  </entry>
</feed>
