Skip to content

Instantly share code, notes, and snippets.

@isuke01
Created September 25, 2026 10:29
Show Gist options
  • Select an option

  • Save isuke01/3d0fa0583dd41c94b889733eab3080e9 to your computer and use it in GitHub Desktop.

Select an option

Save isuke01/3d0fa0583dd41c94b889733eab3080e9 to your computer and use it in GitHub Desktop.
Fix Local CLI by adding socket to DB_HOST into env
#!/usr/bin/env bash
# fix-local-cli — Point DB_HOST in the project .env at this Local site's MySQL socket.
# Usage:
# fix-local-cli (run anywhere inside a project under ~/Local Sites/<site>/)
set -euo pipefail
LOCAL_DIR="$HOME/Library/Application Support/Local"
env_dir="$PWD"
while [[ "$env_dir" != "/" && ! -f "$env_dir/.env" ]]; do
env_dir="$(dirname "$env_dir")"
done
if [[ ! -f "$env_dir/.env" ]]; then
echo "✖ No .env found in $PWD or any parent directory." >&2
exit 1
fi
site=$(python3 - "$LOCAL_DIR/sites.json" "$PWD" <<'PY'
import json, os, sys
sites = json.load(open(sys.argv[1]))
cwd = os.path.realpath(sys.argv[2])
best = None
for site_id, site in sites.items():
path = os.path.realpath(os.path.expanduser(site.get('path', '')))
if (cwd == path or cwd.startswith(path + os.sep)) and (not best or len(path) > len(best[1])):
best = (site_id, path, site.get('name', ''))
if best:
print(f"{best[0]}\t{best[2]}")
PY
)
if [[ -z "$site" ]]; then
echo "✖ $PWD is not inside a Local site." >&2
exit 1
fi
site_id="${site%%$'\t'*}"
site_name="${site#*$'\t'}"
socket="$LOCAL_DIR/run/$site_id/mysql/mysqld.sock"
if [[ ! -S "$socket" ]]; then
echo "⚠ Socket not found — start \"$site_name\" in Local first. Writing it anyway."
fi
python3 - "$env_dir/.env" "localhost:$socket" <<'PY'
import re, sys
path, host = sys.argv[1], sys.argv[2]
lines = open(path).read().splitlines()
lines = [l for l in lines if not re.match(r'\s*MYSQLI_DEFAULT_SOCKET\s*=', l)]
line = f"DB_HOST='{host}'"
for i, l in enumerate(lines):
if re.match(r'\s*DB_HOST\s*=', l):
lines[i] = line
break
else:
lines.append(line)
open(path, 'w').write('\n'.join(lines) + '\n')
PY
echo "✔ $site_name ($site_id): DB_HOST → localhost:$socket"
echo " in $env_dir/.env"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment