Skip to content

Instantly share code, notes, and snippets.

@aadmathijssen
Last active March 18, 2021 11:25
Show Gist options
  • Save aadmathijssen/56d3ae4efef584bb88dfd2d798dfd299 to your computer and use it in GitHub Desktop.
Save aadmathijssen/56d3ae4efef584bb88dfd2d798dfd299 to your computer and use it in GitHub Desktop.
Composer CLI version selector
#!/bin/bash
set -euo pipefail
for tool in jq composer1.phar composer2.phar; do
if ! [ -x "$(command -v ${tool})" ]; then
echo "Error: ${tool} is not installed." >&2
exit 1
fi
done
if [ ! -f composer.lock ] || jq -e '.["plugin-api-version"] | .[0:1] == "2"' composer.lock > /dev/null; then
composer2.phar "$@"
else
composer1.phar "$@"
fi
@aadmathijssen
Copy link
Author

Requirements

The following tools are installed and available in $PATH:

  • jq
  • composer1.phar
  • composer2.phar

Installation

Download the snippet file named composer to one of your $PATH folders, and give the file executable permissions.

Make sure the file is loaded before any other file named composer (such as a HomeBrew version in /usr/local/bin).

Usage

Run composer with any arguments from the root of your git repository to automatically run Composer using the best matching version; this also works with any tool that uses Composer and references composer without explicit paths.

The Composer version is matched by inspecting the plugin-api-version property of the project's composer.lock:

  • If the value starts with 2, Composer 2 is used, otherwise Composer 1 is used.
  • If the value is missing, Composer 1 is used: composer.lock files generated using a version of Composer older than 1.10.0 do not contain a plugin-api-version key (see also the corresponding commit).
  • If the composer.lock file itself is missing, Composer 2 is used; this makes sure Composer 2 is used when setting up Composer for the first time in a new project.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment