0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Homebrewのパッケージリストをgit管理する

Last updated at Posted at 2025-02-15

はじめに

MacではHomebrewを使ったパッケージ管理が主流ですが、

「Homebrewのパッケージリストがカオスになってきた…」
「こんなパッケージいつインストールしたっけ…」
「整理したいけどどれを消していいかわからない…」

といった問題を抱えている方も多いはず。

そんな課題を解決するために、HomebrewとGitを組み合わせたパッケージ管理方法を紹介します!!

解決策

brewfileをgit管理することで、パッケージのインストール日時や実行コマンドをcommitとして残すことができます。
具体的には以下のように brew installbrew update 等を叩いたときに自動で差分がcommitされるようにすることが可能です。

> brew install postgresql@17
Running brew install postgresql@17 with brewfile commit...

...

[main d84d872] brew install postgresql@17
 1 file changed, 1 insertion(+)
Changes committed with message: brew install postgresql@17

image.png

設定手順

1. ディレクトリ作成とGitリポジトリの初期化

まず、Brewfileを管理するためのディレクトリを作成し、Gitリポジトリを初期化します。

mkdir brewfile
cd brewfile
git init

2. 初期Brewfileの作成

現在のHomebrew環境をBrewfileに記録します。

brew bundle dump --file=./Brewfile --force

これで、Brewfileにインストールされているパッケージ情報が記録されます。

3. 自動コミットスクリプトの作成

以下の内容でスクリプトbrew_with_commit.shを作成します。

#!/bin/bash

GIT_DIR=~/dev/brewfile
BREWFILE=$GIT_DIR/Brewfile

# 差分が発生するbrewコマンドのリスト
DIFF_COMMANDS=("install" "uninstall" "upgrade" "update" "tap" "untap")

# コマンドが差分を生じる場合のみBrewfile更新
if [[ " ${DIFF_COMMANDS[@]} " =~ " $1 " ]]; then
  cd "$GIT_DIR"
  brew bundle dump --file="$BREWFILE" --force

  # 差分がある場合のみgitコミット
  if ! git diff --quiet "$BREWFILE"; then
    git add "$BREWFILE"
    git commit -m "brew $*"
    echo "Changes committed with message: brew $*"
  else
    echo "No changes to commit."
  fi

  cd - > /dev/null
else
  echo "No Brewfile update required for command: brew $*"
fi

4. スクリプトに実行権限を付与

chmod +x ~/dev/brewfile/brew_with_commit.sh

5. zshrcまたはbashrcにエイリアスを設定

~/.zshrc または ~/.bashrc に以下を追記します。

brewfileディレクトリ配置先によって適宜書き換えてください

alias brew='~/brewfile/brew_with_commit.sh'

その後、設定を反映します。

source ~/.zshrc

使い方

通常のbrewコマンドを使うだけで、自動的にBrewfileが更新され、Gitにコミットされます。

> brew install wget
# => brew install wget 実行後 Brewfile更新 & コミット

> brew update
# => パッケージ更新後、自動でBrewfileをコミット

> brew search git
# => Brewfile更新なし、コミットもなし

おわりに

brewパッケージ一覧に変更差分が残るため、後から経緯を追いやすくなるはず。

拡張として

  • リモートリポジトリと紐づけてpushまで自動実行する
  • brewコマンド実行時に -m オプションでコメントを残せる
  • パッケージのバージョン履歴を残す

あたりを追加してみても面白いかも。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?