macでherokuに初回pushするときに起こるエラー、herokuのプラットフォームを指定する

最初に

Linux以外でherokuにRailsアプリをpushすると、おそらく起こるエラーがある。
それについて、説明していく。
(もしかしたら、nokogiri等を使ってないとエラーにならないかも)

実際のエラー

$ git push heroku main
(中略)
remote: -----> Ruby app detected
remote: -----> Installing bundler 2.2.21
remote: -----> Removing BUNDLED WITH version in the Gemfile.lock
remote: -----> Compiling Ruby/Rails
remote: -----> Using Ruby version: ruby-3.0.2
remote: -----> Installing dependencies using bundler 2.2.21
remote:        Running: BUNDLE_WITHOUT='development:test' BUNDLE_PATH=vendor/bundle BUNDLE_BIN=vendor/bundle/bin BUNDLE_DEPLOYMENT=1 bundle install -j4
remote:        Your bundle only supports platforms ["x86_64-darwin-20"] but your local platform
remote:        is x86_64-linux. Add the current platform to the lockfile with `bundle lock
remote:        --add-platform x86_64-linux` and try again.
remote:        Bundler Output: Your bundle only supports platforms ["x86_64-darwin-20"] but your local platform
remote:        is x86_64-linux. Add the current platform to the lockfile with `bundle lock
remote:        --add-platform x86_64-linux` and try again.
remote: 
remote:  !
remote:  !     Failed to install gems via Bundler.
remote:  !

エラーでない部分

まず、本題から逸れて、エラーでない部分について説明する。

remote: -----> Ruby app detected
remote: -----> Installing bundler 2.2.21
remote: -----> Removing BUNDLED WITH version in the Gemfile.lock
remote: -----> Compiling Ruby/Rails
remote: -----> Using Ruby version: ruby-3.0.2
remote: -----> Installing dependencies using bundler 2.2.21

Rubyで作られたアプリだと検知して、bundler 2.2.21をインストールし始める。
herokuの標準環境では、bundler 2.2.21を使うようだ。
Gemfile.lockに書かれたBundlerのバージョンを削除する。
で、2.2.21 bundlerを使って、Gemfile.lockから依存gemをインストールしてる。

エラーが起こる部分

依存gemをインストールする際にエラーになる。
微妙なところで改行されてて読みにくいので、わかりやすい文単位で改行する。

Your bundle only supports platforms ["x86_64-darwin-20"] but your local platform is x86_64-linux. 
Add the current platform to the lockfile with `bundle lock --add-platform x86_64-linux` and try again.

このエラーを説明する。 "x86_64-darwin-20"ってのがmacOSの1つで、x86_64-linuxが書かれているようにLinux。 (Gemfile.lockからわかることで)bundlerによる依存関係の前提としては["x86_64-darwin-20"]しかサポートしてないけど、Heroku環境(local platform)がLinuxだからx86_64-linuxも使われることをGemfile.lockに指定しろという話の模様。
nokogiriとかは、環境によってちょっと異なるバージョンが入るらしい。環境ごとにバージョンがあるという感じだろうか。 bundle lock --add-platform x86_64-linuxというコマンドを使えばいいことを教えてくれてるので、それをそのまま実行する。 そうすると、Gemfile.lockに使われる環境(プラットフォーム)の情報にx86_64-linuxが追加される。 追加されることで、bundle installする際に、Linux用(x86_64-linux)のnokogiri gemが入るようになる。 これで、改めて、git push heroku mainとすると、このエラーは消えて、他にエラーがなければデプロイできる。

最後に

ちょっと慣れてないと、色々表示されて読みにくい気がするが、紐解ければ単純。