Compare commits

...

11 Commits

Author SHA1 Message Date
8ad1f5c4d0 chore(docs): bin/README.md tweaks
Signed-off-by: Ismo Vuorinen <ismo@ivuorinen.net>
2025-04-14 10:25:43 +03:00
ac0aa1fbc0 feat(bin): php-switcher for Brew based version changes
Signed-off-by: Ismo Vuorinen <ismo@ivuorinen.net>
2025-04-14 10:25:18 +03:00
e8c6794ff6 chore(repo): ignore yabai from repo
Signed-off-by: Ismo Vuorinen <ismo@ivuorinen.net>
2025-04-14 10:24:20 +03:00
4de9a649f0 chore(config): update zed config
Signed-off-by: Ismo Vuorinen <ismo@ivuorinen.net>
2025-04-14 10:23:50 +03:00
github-actions[bot]
e7f115680e chore: update pre-commit hooks (#98)
Co-authored-by: ivuorinen <11024+ivuorinen@users.noreply.github.com>
2025-04-14 09:06:55 +03:00
f3b4551d0c chore(config): ideavim config 2025-04-11 16:31:59 +03:00
64725c57dc chore(config): fish config tweaks 2025-04-11 16:31:58 +03:00
b32ee414e3 chore(config): tweak yabai config 2025-04-11 16:31:58 +03:00
renovate[bot]
6ea7807718 fix(container): update image python (3.13.2 → 3.13.3) (#97) 2025-04-10 22:14:50 +03:00
6a776bd3dd chore(config): nvim: cleanup and fixes
Signed-off-by: Ismo Vuorinen <ismo@ivuorinen.net>
2025-04-04 16:34:08 +03:00
6ffe581326 feat(config): use nvm with bass, simplify setup
Signed-off-by: Ismo Vuorinen <ismo@ivuorinen.net>
2025-04-04 16:33:32 +03:00
24 changed files with 526 additions and 296 deletions

2
.gitignore vendored
View File

@@ -46,3 +46,5 @@ config/vim/.netrwhist
config/vim/extra/*
config/gh/hosts.yml
dependency-check-report.html
local/bin/yabai
local/man/yabai.1

View File

@@ -49,7 +49,7 @@ repos:
- id: actionlint
- repo: https://github.com/renovatebot/pre-commit-hooks
rev: 39.227.2
rev: 39.240.1
hooks:
- id: renovate-config-validator

View File

@@ -1 +1 @@
3.13.2
3.13.3

View File

@@ -1,63 +0,0 @@
# NVM (https://github.com/creationix/nvm) completions for Fish shell
# Inspired on (https://github.com/derekstavis/plugin-nvm)
function __nvm_complete_ls_remote
if not test "$__nvm_ls_remote"
set -g __nvm_ls_remote (nvm ls-remote | grep -Po '(?:iojs-)?v[0-9]+\.[0-9]+\.[0-9]+')
end
printf "%s\n" $__nvm_ls_remote
end
function __nvm_complete_ls
if not test "$__nvm_ls"
set -g __nvm_ls (nvm ls | grep -Po '[[:space:]].\K(v[0-9]+\.[0-9]+\.[0-9]+)')
end
printf "%s\n" $__nvm_ls
end
#Install
complete -f -c nvm -n '__fish_use_subcommand' -a 'install' -d 'Download and install a <version>. Uses .nvmrc if available'
complete -f -c nvm -n "__fish_seen_subcommand_from install" -a "(__nvm_complete_ls_remote)"
complete -f -c nvm -n "__fish_seen_subcommand_from install" -l reinstall-packages-from= -d 'When installing, reinstall packages installed in <node|iojs|node version number>'
complete -f -c nvm -n "__fish_seen_subcommand_from install" -s s -d 'From source'
#Use
complete -f -c nvm -n '__fish_use_subcommand' -a 'use' -d 'Modify PATH to use <version>. Uses .nvmrc if available'
complete -f -c nvm -n "__fish_seen_subcommand_from use" -a "(__nvm_complete_ls)"
complete -f -c nvm -n "__fish_seen_subcommand_from use" -l silent
#Exec
complete -f -c nvm -n '__fish_use_subcommand' -a 'exec' -d 'Run <command> on <version>. Uses .nvmrc if available'
complete -f -c nvm -n "__fish_seen_subcommand_from exec" -a "(__nvm_complete_ls)"
complete -f -c nvm -n "__fish_seen_subcommand_from exec" -l silent
#Run
complete -f -c nvm -n '__fish_use_subcommand' -a 'run' -d 'Run <command> on <version>. Uses .nvmrc if available'
complete -f -c nvm -n "__fish_seen_subcommand_from run" -a "(__nvm_complete_ls)"
complete -f -c nvm -n "__fish_seen_subcommand_from run" -l silent
#Uninstall
complete -f -c nvm -n '__fish_use_subcommand' -a 'uninstall' -d 'Uninstall a version'
complete -f -c nvm -n "__fish_seen_subcommand_from uninstall" -a "(__nvm_complete_ls)"
#Which
complete -f -c nvm -n '__fish_use_subcommand' -a 'which' -d 'Display path to installed node version. Uses .nvmrc if available'
complete -f -c nvm -n "__fish_seen_subcommand_from which" -a "(__nvm_complete_ls)"
#Reinstall-Packages
complete -f -c nvm -n '__fish_use_subcommand' -a 'reinstall-packages' -d 'Reinstall global `npm` packages contained in <version> to current version'
complete -f -c nvm -n "__fish_seen_subcommand_from reinstall-packages" -a "(__nvm_complete_ls)"
#Completions
complete -f -c nvm -n '__fish_use_subcommand' -a 'current' -d 'Display currently activated version'
complete -f -c nvm -n '__fish_use_subcommand' -a 'ls' -d 'List installed versions'
complete -f -c nvm -n '__fish_use_subcommand' -a 'ls-remote' -d 'List remote versions available for install'
complete -f -c nvm -n '__fish_use_subcommand' -a 'version' -d 'Resolve the given description to a single local <version>'
complete -f -c nvm -n '__fish_use_subcommand' -a 'version-remote' -d 'Resolve the given description to a single remote <version>'
complete -f -c nvm -n '__fish_use_subcommand' -a 'deactivate' -d 'Undo effects of `nvm` on current shell'
complete -f -c nvm -n '__fish_use_subcommand' -a 'alias' -d 'Show all aliases beginning with <pattern> or set an alias named <name> pointing to <version>'
complete -f -c nvm -n '__fish_use_subcommand' -a 'unalias' -d 'Deletes the alias named <name>'
complete -f -c nvm -n '__fish_use_subcommand' -a 'unload' -d 'Unload `nvm` from shell'

View File

@@ -9,17 +9,21 @@ test -e "$HOME/.config/fish/exports.fish" &&
source "$HOME/.config/fish/exports.fish"
if status is-interactive
# Commands to run in interactive sessions can go here
# Commands to run in interactive shell
# Start tmux if not already running and not in SSH
open-tmux # defined in functions/open-tmux.fish
# version manager initializers
type -q rbenv; and source (rbenv init -|psub)
type -q pyenv; and source (pyenv init -|psub)
type -q pyenv; and source (pyenv virtualenv-init -)
type -q goenv; and source (goenv init -|psub)
# type -q fnm; and fnm env --use-on-cd --shell fish | source
type -q load_nvm; and load_nvm > /dev/stderr
# Start tmux if not already running and not in SSH
open-tmux # defined in functions/open-tmux.fish
end
# Added by LM Studio CLI (lms)
set -gx PATH $PATH $HOME/.lmstudio/bin
type -q rbenv; and source (rbenv init -|psub)
type -q pyenv; and source (pyenv init -|psub)
type -q goenv; and source (goenv init -|psub)
type -q fnm; and fnm env --use-on-cd --shell fish | source
# vim: ft=fish ts=4 sw=4 et:

View File

@@ -6,5 +6,3 @@ jgusta/paths
danhper/fish-ssh-agent
halostatue/fish-brew@v3
edc/bass
jorgebucaran/nvm.fish
fabioantunes/fish-nvm

View File

@@ -1,70 +0,0 @@
function __nvm_run
set count (count $argv)
if test "$count" -le 0
echo 'No params'
return 1
end
if test (uname -s) = 'Darwin'; and string match -q "*versions/node/*/bin" $PATH
set -l nvm_node_path (string match "*versions/node/*/bin" $PATH)
set -l nvm_index (contains -i -- $nvm_node_path $PATH)
if test $nvm_index -gt 1
set -gx PATH $nvm_node_path (string match -v $nvm_node_path $PATH)
end
end
function run_command
set stack (status stack-trace | grep called | cut -d " " -f 7)
set count (count $argv)
if type -fq $argv[1]; and test "$stack[1]" != (type -fP $argv[1])
set count (count $argv)
if test "$count" -ge 2
set args $argv[2..-1]
# https://stackoverflow.com/questions/45237675/proxying-arguments-from-one-function-to-a-command/45238056#45238056
eval (string escape -- (type -fP $argv[1]) $args)
else
eval (string escape -- (type -fP $argv[1]))
end
else
echo (set_color -o)"Fish nvm:"(set_color normal) "'$argv[1]' is currently not installed, try running npm i -g $argv[1]"
return 1
end
end
function can_run_command
if type -P $argv[1] > /dev/null 2>&1; or type -P node > /dev/null 2>&1
return
else
return 1
end
end
function run_default
nvm use default > /dev/null
set -gx NVM_HAS_RUN 1
if can_run_command $argv[1]
run_command $argv
end
end
if not test -n "$NVM_HAS_RUN"
if test -f .nvmrc;
set nvm_output (nvm use)
set nvm_status $status
if test $nvm_status -gt 0
echo $nvm_output
end
if test $nvm_status -eq 0; and can_run_command $argv[1]
set -gx NVM_HAS_RUN 1
run_command $argv
end
else
run_default $argv
end
else
run_command $argv
end
end

View File

@@ -0,0 +1,16 @@
function load_nvm --on-variable="PWD"
set -l default_node_version (nvm version default)
set -l node_version (nvm version)
set -l nvmrc_path (nvm_find_nvmrc)
if test -n "$nvmrc_path"
set -l nvmrc_node_version (nvm version (cat $nvmrc_path))
if test "$nvmrc_node_version" = "N/A"
nvm install (cat $nvmrc_path)
else if test "$nvmrc_node_version" != "$node_version"
nvm use $nvmrc_node_version
end
else if test "$node_version" != "$default_node_version"
echo "Reverting to default Node version"
nvm use default
end
end

View File

@@ -1,3 +0,0 @@
function node -d "Server-side JavaScript runtime" -w node
__nvm_run "node" $argv
end

View File

@@ -1,3 +0,0 @@
function npm -d "node package manager" -w npm
__nvm_run "npm" $argv
end

View File

@@ -1,3 +0,0 @@
function npx -d "execute npm package binaries" -w npx
__nvm_run "npx" $argv
end

View File

@@ -1,24 +1,4 @@
function nvm
if not type -q bass
echo 'Bass is not installed please install it running fisher edc/bass'
return
end
set -q NVM_DIR; or set -gx NVM_DIR ~/.nvm
set -q nvm_prefix; or set -gx nvm_prefix $NVM_DIR
bass source $nvm_prefix/nvm.sh --no-use ';' nvm $argv
set bstatus $status
if test $bstatus -gt 0
return $bstatus
end
if test (count $argv) -lt 1
return 0
end
if test $argv[1] = "use"; or test $argv[1] = "install"
set -gx NVM_HAS_RUN 1
end
bass source $NVM_DIR/nvm.sh --no-use ';' nvm $argv
end

View File

@@ -1,49 +0,0 @@
function nvm_alias_command -d "Create an alias command"
function __nvm_alias_output
if test -z "$nvm_alias_output"
echo "/usr/local/bin"
else
echo (string replace -r '/$' '' $nvm_alias_output)
end
end
function __create_alias_command
if test -e "$argv[1]"
set_color yellow
echo "Ignored: $argv[1] (already exists)"
set_color normal
return 0
else
set -l template "__nvm_run \"COMMAND\" \$argv"
printf "#!/usr/bin/env fish\n%s\n" (string replace COMMAND $argv[2] $template) > $argv[1]
if test $status -eq 0
printf "\U2705 %s alias command was created at %s\n" $argv[2] $argv[1]
return (chmod +x $argv[1])
else
printf "\U274C failed creating %s alias command at %s\n" $argv[2] $argv[1]
printf "Probably a permissions problem, try running sudo fish, and then nvm_alias_command\n"
end
end
end
set -l outputPath (__nvm_alias_output)
mkdir -p $outputPath
if test $status -ge 1
printf "\U274C failed creating dir $outputPath."
printf "Probably a permissions problem, try running sudo fish, and then nvm_alias_command\n"
exit 1
end
if test (count $argv) -le 0
set -l aliases node npm npx yarn
for alias in $aliases
__create_alias_command "$outputPath/$alias" $alias
end
else
for arg in $argv
__create_alias_command "$outputPath/$arg" $arg
end
end
end

View File

@@ -1,28 +0,0 @@
function nvm_alias_function -d "Create an alias function"
function __create_alias_function
if test -e "$argv[1]"
set_color yellow
echo "Ignored: $argv[1] (already exists)"
set_color normal
return 0
else
set -l line1 "function COMMAND -w COMMAND"
set -l line2 "__nvm_run \"COMMAND\" \$argv"
echo (string replace -a COMMAND $argv[2] $line1) > $argv[1]
echo (string replace COMMAND $argv[2] $line2) >> $argv[1]
echo "end" >> $argv[1]
return 0
end
end
if test (count $argv) -le 0
set_color yellow
echo "Please specify package(s) name(s)"
set_color normal
return 1
else
for arg in $argv
__create_alias_function "$fish_function_path[1]/$arg.fish" $argv
end
end
end

View File

@@ -0,0 +1,3 @@
function nvm_find_nvmrc
bass source $NVM_DIR/nvm.sh --no-use ';' nvm_find_nvmrc
end

View File

@@ -1,3 +0,0 @@
function yarn -d "yarn package manager" -w yarn
__nvm_run "yarn" $argv
end

View File

@@ -1,5 +1,5 @@
"" Source your .vimrc
source ~/.dotfiles/config/vim/vimrc
source $HOME/.dotfiles/config/vim/vimrc
" https://github.com/ville6000/dotfiles/blob/main/vimrc
" To get a list of Actions run `:actionlist `

View File

@@ -38,7 +38,7 @@ o.scrolloff = 8 -- Show context around cursor
o.sidescrolloff = 8 -- Show context around cursor
o.signcolumn = 'yes' -- Keep signcolumn on by default
o.spell = true -- Enable spell checking
o.spelllang = 'fi,en_us' -- Set the spell checking language
o.spelllang = 'en_gb,en_us' -- Set the spell checking language
o.splitbelow = true -- split to the bottom
o.splitright = true -- vsplit to the right
o.termguicolors = true -- Enable GUI colors

View File

@@ -5,12 +5,13 @@ return {
'folke/snacks.nvim',
priority = 1000,
lazy = false,
---@diagnostic disable-next-line: undefined-doc-name
---@type snacks.Config
opts = {
bigfile = { enabled = true },
input = {
input = { enabled = true },
notifier = {
enabled = true,
timeout = 3000,
},
gitbrowse = { enabled = true },
quickfile = { enabled = true },
@@ -43,6 +44,11 @@ return {
{
'folke/noice.nvim',
event = 'VeryLazy',
dependencies = {
-- if you lazy-load any plugin below, make sure to add proper `module="..."` entries
'MunifTanjim/nui.nvim',
'rcarriga/nvim-notify',
},
opts = {
lsp = {
-- override markdown rendering so that **cmp** and other plugins use **Treesitter**
@@ -65,7 +71,10 @@ return {
filter = {
event = 'msg_show',
kind = '',
find = 'written',
any = {
{ find = 'written' },
{ find = '%d of %d --%d%--' },
},
},
opts = { skip = true },
},
@@ -106,14 +115,6 @@ return {
},
},
},
dependencies = {
-- if you lazy-load any plugin below, make sure to add proper `module="..."` entries
'MunifTanjim/nui.nvim',
-- OPTIONAL:
-- `nvim-notify` is only needed, if you want to use the notification view.
-- If not available, we use `mini` as the fallback
'rcarriga/nvim-notify',
},
},
-- A pretty diagnostics, references, telescope results,
@@ -136,7 +137,7 @@ return {
},
modes = {
diagnostics = {
auto_open = true,
auto_open = false,
},
test = {
mode = 'diagnostics',
@@ -144,7 +145,7 @@ return {
type = 'split',
relative = 'win',
position = 'right',
size = 0.3,
size = 0.25,
},
},
cascade = {
@@ -163,13 +164,4 @@ return {
},
},
},
-- Navigate your code with search labels, enhanced
-- character motions and Treesitter integration
-- https://github.com/folke/flash.nvim
{
'folke/flash.nvim',
event = 'VeryLazy',
opts = {},
},
}

View File

@@ -25,6 +25,14 @@ return {
},
}
-- Better Around/Inside textobjects
--
-- Examples:
-- - va) - [V]isually select [A]round [)]paren
-- - yinq - [Y]ank [I]nside [N]ext [Q]uote
-- - ci' - [C]hange [I]nside [']quote
require('mini.ai').setup { n_lines = 500 }
-- Animate common Neovim actions
-- Replaced anuvyklack/windows.nvim
require('mini.animate').setup()

View File

@@ -7,7 +7,6 @@
# yabai -m signal --add event=dock_did_restart action="sudo yabai --load-sa"
yabai -m config \
active_window_border_color 0xff775759 \
auto_balance on \
layout bsp \
top_padding 0 \

View File

@@ -5,20 +5,14 @@
"assistant": {
"default_model": {
"provider": "copilot_chat",
"model": "claude-3-5-sonnet"
"model": "claude-3-7-sonnet"
},
"version": "2"
},
"formatter": {
"external": {
"command": "prettier",
"arguments": [
"--stdin-filepath",
"{buffer_path}"
]
}
},
"languages": {
"Shell Script": {
"enable_language_server": true
},
"JavaScript": {
"enable_language_server": true,
"code_actions_on_format": {

View File

@@ -6,8 +6,15 @@ Some problematic code has been fixed per `shellcheck` suggestions.
## Homegrown
- dfm
- git-dirty (based on git-extra-tools)
- git-fsck-dirs
- git-update-dirs
- php-switcher
- x-backup-folder
- x-backup-mysql-with-prefix
- x-check-git-attributes
- x-clean-vendordirs
- x-env-list
- x-open-ports
## Sourced
@@ -25,9 +32,15 @@ Some problematic code has been fixed per `shellcheck` suggestions.
| `x-when-up` | skx/sysadmin-util |
- Sources:
- [skx/sysadmin-utils](https://github.com/skx/sysadmin-util/)
- [skx/sysadmin-utils][skx]
- Tools for Linux/Unix sysadmins.
- [Licence](https://github.com/skx/sysadmin-util/blob/master/LICENSE)
- [onnimonni](https://github.com/onnimonni)
- [validate_sha256sum](https://gist.github.com/onnimonni/b49779ebc96216771a6be3de46449fa1)
- [mvdan/dotfiles](https://github.com/mvdan/dotfiles)
- [Licence][skx-license]
- [onnimonni][onnimonni]
- [validate_sha256sum][onnimonni-gist]
- [mvdan/dotfiles][mvdan]
[onnimonni]: https://github.com/onnimonni
[onnimonni-gist]: https://gist.github.com/onnimonni/b49779ebc96216771a6be3de46449fa1
[skx]: https://github.com/skx/sysadmin-util
[skx-license]: https://github.com/skx/sysadmin-util/blob/master/LICENSE
[mvdan]: https://github.com/mvdan/dotfiles

443
local/bin/php-switcher Executable file
View File

@@ -0,0 +1,443 @@
#!/usr/bin/env bash
#
# Brew PHP Switcher
#
# Use to switch between PHP versions installed via Homebrew.
#
# Usage: php-switcher <version> [--help|--installed|--current|--auto]
# Example: php-switcher 7.4
# Example: php-switcher 8.0
# Example: php-switcher latest
# Example: php-switcher --auto
#
# Created by Ismo Vuorinen <https://github.com/ivuorinen> (2025)
# Licensed under the MIT License (https://opensource.org/licenses/MIT)
set -euo pipefail # Add error handling
# Configuration
LATEST_VERSION_FORMULA="php" # The formula name for latest PHP version
PHP_VERSION_FILE=".php-version" # File name to look for when auto-switching
# Switch brew php version
function check_dependencies()
{
if ! command -v brew > /dev/null 2>&1; then
echo "Error: Homebrew is not installed"
exit 1
fi
}
function usage()
{
echo "Brew PHP Switcher - Switch between PHP versions installed via Homebrew"
echo ""
echo "Usage: php-switcher <version> [options]"
echo ""
echo "Options:"
echo " --help Show this help message"
echo " --installed List installed PHP versions"
echo " --current Show currently active PHP version"
echo " --auto Auto-switch based on .php-version file in current directory"
echo ""
echo "Examples:"
echo " php-switcher 7.4"
echo " php-switcher 8.0"
echo " php-switcher latest"
echo " php-switcher --auto"
echo ""
echo "Auto-switching:"
echo " Create a .php-version file in your project directory with a PHP version"
echo " Example .php-version content: 8.1"
echo ""
exit 0
}
function list_php_versions()
{
# Check Homebrew's installation path for PHP versions
local brew_cellar
brew_cellar="$(brew --cellar)"
local php_paths=()
local versions=()
local formulas=()
local active=()
# Look for all PHP installations in Homebrew Cellar
if [[ -d "$brew_cellar/php" ]]; then
php_paths+=("$brew_cellar/php")
fi
# Look for versioned PHP installations
while IFS= read -r dir; do
if [[ -d $dir ]]; then
php_paths+=("$dir")
fi
done < <(find "$brew_cellar" \
-maxdepth 1 -name 'php@*' \
-type d 2> /dev/null || echo "")
if [[ ${#php_paths[@]} -eq 0 ]]; then
echo "No PHP versions installed through Homebrew."
return 1
fi
# Find which version is currently linked
local current_bin
current_bin=$(readlink -f \
"$(command -v php 2> /dev/null)" \
2> /dev/null || echo "")
# Collect data for each installed PHP version
for path in "${php_paths[@]}"; do
local formula
formula=$(basename "$path")
local version_label
if [[ $formula == "php" ]]; then
version_label="latest"
else
version_label="${formula#php@}"
fi
# Find the actual version from the directory structure
local version_dir
version_dir=$(find "$path" -maxdepth 1 -type d \
| grep -v "^$path$" | sort -V | tail -1)
if [[ -n $version_dir && -d "$version_dir/bin" ]]; then
local full_version
full_version=$("$version_dir/bin/php" -v 2> /dev/null \
| grep -oE 'PHP [0-9]+\.[0-9]+\.[0-9]+' \
| head -1 \
| cut -d' ' -f2 \
|| echo "$version_label.x")
# Determine if this is the active version
local is_active="No"
if [[ -n $current_bin && $current_bin == "$version_dir/bin/php" ]]; then
is_active="Yes"
fi
# Handle the 'latest' case - replace with actual version number
local display_version
if [[ $version_label == "latest" ]]; then
display_version="${full_version%.*}" # Get major.minor version
else
display_version="$version_label"
fi
# Store data for table display
versions+=("$display_version")
formulas+=("$formula")
active+=("$is_active")
fi
done
# Calculate maximum column widths
local max_version_width=7 # "Version" header length
local max_formula_width=7 # "Formula" header length
local max_active_width=6 # "Active" header length
local count=${#versions[@]}
for ((i = 0; i < count; i++)); do
# Update max widths if needed
if [[ ${#versions[i]} -gt $max_version_width ]]; then
max_version_width=${#versions[i]}
fi
if [[ ${#formulas[i]} -gt $max_formula_width ]]; then
max_formula_width=${#formulas[i]}
fi
done
# Build header with correct widths
local header_format="| %-${max_version_width}s | %-${max_formula_width}s | "
header_format+="%-${max_active_width}s |"
local separator_line="|"
for ((i = 0; i < max_version_width + 2; i++)); do
separator_line="${separator_line}-"
done
separator_line="${separator_line}|"
for ((i = 0; i < max_formula_width + 2; i++)); do
separator_line="${separator_line}-"
done
separator_line="${separator_line}|"
for ((i = 0; i < max_active_width + 2; i++)); do
separator_line="${separator_line}-"
done
separator_line="${separator_line}|"
# Print table header
# shellcheck disable=SC2059
printf "$header_format\n" "Version" "Formula" "Active"
echo "$separator_line"
# Print table rows
local row_format="| %-${max_version_width}s | %-${max_formula_width}s | "
row_format+="%-${max_active_width}s |"
for ((i = 0; i < count; i++)); do
# shellcheck disable=SC2059
printf "$row_format\n" "${versions[i]}" "${formulas[i]}" "${active[i]}"
done
}
function get_php_formula_for_version()
{
local version="$1"
# Handle "latest" as a special case
if [[ $version == "latest" ]]; then
echo "$LATEST_VERSION_FORMULA"
return 0
fi
# The regular version case (e.g., 7.4, 8.1)
echo "php@$version"
}
function check_formula_installed()
{
local formula="$1"
local brew_cellar
brew_cellar="$(brew --cellar)"
if [[ $formula == "php" ]]; then
if [[ -d "$brew_cellar/php" ]]; then
return 0
fi
elif [[ -d "$brew_cellar/$formula" ]]; then
return 0
fi
return 1
}
function unlink_current_php()
{
local current_formula=""
# Find formulas more safely
while IFS= read -r formula; do
if [[ -n $formula ]]; then
local linked
linked=$(brew info --json=v1 "$formula" \
| grep -o '"linked_keg":"[^"]*"' \
| grep -v ':"null"')
if [[ -n $linked ]]; then
current_formula="$formula"
break
fi
fi
done < <(brew list --formula | grep -E '^php(@[0-9]+\.[0-9]+)?$' || echo "")
# If we found a linked formula, unlink it
if [[ -n $current_formula ]]; then
echo "Unlinking current PHP version ($current_formula)..."
brew unlink "$current_formula" > /dev/null 2>&1 || true
fi
}
function link_php_version()
{
local formula="$1"
if ! check_formula_installed "$formula"; then
echo "Error: PHP formula '$formula' is not installed"
echo "Available versions:"
list_php_versions
exit 1
fi
echo "Linking $formula..."
if ! brew link --force --overwrite "$formula" > /dev/null 2>&1; then
echo "Error: Failed to link $formula. Try running manually:"
echo " brew link --force --overwrite $formula"
exit 1
fi
# Verify the switch worked
if ! command -v php > /dev/null 2>&1; then
echo "Warning: PHP was linked but may not be working correctly"
fi
}
function get_current_version()
{
if ! command -v php > /dev/null 2>&1; then
echo "No PHP currently linked"
return 1
fi
local version
version=$(php -v 2> /dev/null \
| grep -oE 'PHP [0-9]+\.[0-9]+\.[0-9]+' \
| head -1)
if [[ -z $version ]]; then
echo "Unable to determine PHP version"
return 1
fi
# Find the corresponding formula
local current_version
current_version=$(echo "$version" | cut -d' ' -f2)
local major_minor
major_minor=$(echo "$current_version" | cut -d'.' -f1,2)
# Check if it's the latest version
if check_formula_installed "php" \
&& brew info --json=v1 php \
| grep -o '"linked_keg":"[^"]*"' \
| grep -v ':"null"' \
| grep -q .; then
echo "Current PHP version: $current_version (latest)"
else
echo "Current PHP version: $current_version (php@$major_minor)"
fi
}
function validate_version()
{
local version="$1"
# Valid formats: x.y or latest
if [[ ! $version =~ ^([0-9]+\.[0-9]+|latest)$ ]]; then
echo "Error: Invalid PHP version format. Use x.y format (e.g., 7.4) or"
echo " 'latest'"
exit 1
fi
}
function find_php_version_file()
{
local dir="$PWD"
# Look for .php-version file in current directory and all parent directories
while [[ $dir != "/" ]]; do
if [[ -f "$dir/$PHP_VERSION_FILE" ]]; then
echo "$dir/$PHP_VERSION_FILE"
return 0
fi
dir=$(dirname "$dir")
done
# Check the root directory as well
if [[ -f "/$PHP_VERSION_FILE" ]]; then
echo "/$PHP_VERSION_FILE"
return 0
fi
return 1
}
function auto_switch_php_version()
{
local version_file
# Try to find a .php-version file
version_file=$(find_php_version_file) || {
echo "No .php-version file found in current directory or any parent"
echo "directory. Create a $PHP_VERSION_FILE file with your desired"
echo "PHP version (e.g., 8.1)"
exit 1
}
# Read the version from the file
local version
version=$(tr -d '[:space:]' < "$version_file")
echo "Found $PHP_VERSION_FILE file at: $version_file"
echo "Requested PHP version: $version"
# Validate the version
validate_version "$version"
# Switch to the specified version
switch_php_version "$version"
}
function switch_php_version()
{
local version="$1"
# Get the formula name for the version
local formula
formula=$(get_php_formula_for_version "$version")
# Check if the requested PHP version is installed
if ! check_formula_installed "$formula"; then
echo "Error: PHP version $version is not installed"
echo ""
list_php_versions
exit 1
fi
# Get the current version info for comparison
local current_info
current_info=$(get_current_version 2> /dev/null || echo "None")
# Skip if we're already on the requested version
if [[ $current_info == *"$version"* ]]; then
echo "PHP version $version is already active"
exit 0
fi
# Perform the switch
unlink_current_php
link_php_version "$formula"
# Verify the switch
echo ""
echo "Switched to:"
get_current_version
echo ""
echo "PHP executable: $(command -v php)"
}
function main()
{
local version=""
# Parse arguments
case "${1:-}" in
--help)
usage
;;
--installed)
list_php_versions
exit 0
;;
--current)
get_current_version
exit 0
;;
--auto)
auto_switch_php_version
exit 0
;;
"")
usage
;;
*)
version="$1"
;;
esac
# Validate and switch to the specified version
validate_version "$version"
switch_php_version "$version"
}
# Run the script
check_dependencies
if [[ ${#@} -eq 0 ]]; then
usage
else
main "$@"
fi
# vim: ft=bash sw=4 ts=4 et tw=80 cc=80 :