diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3f45699..42f1dbd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,6 +16,7 @@ jobs: run: | for f in install.sh uninstall.sh lib/*.sh linux/*.sh linux/debian/*.sh macos/*.sh; do bash -n "$f"; done jq . config/caelestia/shell.json >/dev/null + jq . config/windows-terminal/dotfiles.json >/dev/null for f in config/nvim/dotfiles.lua config/caelestia/*.lua; do luac5.4 -p "$f" 2>&1 || lua5.4 -e "assert(loadfile('$f'))"; done - name: Menu (scripted answers) run: tests/menu.sh @@ -56,3 +57,126 @@ jobs: zsh -ic 'echo zsh loads the config: $STARSHIP_CONFIG' /bin/bash "$GITHUB_WORKSPACE/uninstall.sh" --yes test ! -e "$HOME/.zshrc" + + # Windows: the checks run under both Windows PowerShell 5.1 (what every Windows has) and PowerShell 7. + windows: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - name: Parse, ASCII and menu checks (Windows PowerShell 5.1) + shell: powershell + run: powershell -NoProfile -ExecutionPolicy Bypass -File tests\windows.ps1 + - name: Parse, ASCII and menu checks (PowerShell 7) + shell: pwsh + run: pwsh -NoProfile -File tests\windows.ps1 + - name: PSScriptAnalyzer (errors) + shell: pwsh + run: | + Install-Module PSScriptAnalyzer -Force -Scope CurrentUser + $r = Invoke-ScriptAnalyzer -Path . -Recurse -Severity Error + $r | Format-Table -AutoSize + if ($r) { exit 1 } + - name: Dry run of every Windows component (through the entry script) + shell: powershell + run: powershell -NoProfile -ExecutionPolicy Bypass -File .\install.ps1 -DryRun -Yes -All + - name: winget on the runner + shell: pwsh + run: | + if (-not (Get-Command winget -ErrorAction SilentlyContinue)) { + Install-Module Microsoft.WinGet.Client -Force -Scope CurrentUser + Repair-WinGetPackageManager -AllUsers -Latest + } + winget --version + - name: Real run of shell and terminal in a throw-away home, then uninstall + shell: powershell + run: | + $t = Join-Path $env:RUNNER_TEMP 'home' + $env:DOTFILES_HOME = $t; $env:DOTFILES_DOCUMENTS = "$t\Documents"; $env:DOTFILES_LOCALAPPDATA = "$t\AppData\Local" + # a Windows Terminal settings.json with comments, as Terminal writes it: only defaultProfile may change + $wt = "$t\AppData\Local\Microsoft\Windows Terminal"; New-Item -ItemType Directory -Force $wt | Out-Null + $orig = "{`n // keep me`n `"defaultProfile`": `"{61c54bbd-c2c6-5271-96e7-009a87ff44bf}`",`n `"profiles`": { `"list`": [] }`n}`n" + [IO.File]::WriteAllText("$wt\settings.json", $orig) + powershell -NoProfile -ExecutionPolicy Bypass -File .\install.ps1 -Yes -Only shell,terminal + if ($LASTEXITCODE -ne 0) { throw "install failed: $LASTEXITCODE" } + $p7 = "$t\Documents\PowerShell\Microsoft.PowerShell_profile.ps1"; $p5 = "$t\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1" + foreach ($f in $p7, $p5, "$t\.config\starship.toml", "$t\AppData\Local\Microsoft\Windows Terminal\Fragments\rhmatzeka-dotfile\dotfiles.json") { + if (-not (Test-Path $f)) { throw "missing: $f" }; Write-Host "present: $f" + } + # the profile loads in both PowerShells and gives the starship prompt + $env:Path = [Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' + [Environment]::GetEnvironmentVariable('Path', 'User') + pwsh -NoProfile -Command ". '$p7'; if (-not (Get-Command starship -ErrorAction SilentlyContinue)) { exit 3 }; prompt | Out-Null; 'pwsh profile ok'" + if ($LASTEXITCODE -ne 0) { throw "pwsh profile failed: $LASTEXITCODE" } + powershell -NoProfile -ExecutionPolicy Bypass -Command ". '$p5'; prompt | Out-Null; 'powershell 5.1 profile ok'" + if ($LASTEXITCODE -ne 0) { throw "5.1 profile failed: $LASTEXITCODE" } + $now = [IO.File]::ReadAllText("$wt\settings.json") + if ($now -ne $orig.Replace('{61c54bbd-c2c6-5271-96e7-009a87ff44bf}', '{8af80b22-81dc-5325-91bc-4b9b947457a5}')) { throw "settings.json changed more than defaultProfile:`n$now" } + 'default profile set, comments kept' + powershell -NoProfile -ExecutionPolicy Bypass -File .\uninstall.ps1 -Yes + if (Test-Path $p7) { throw "uninstall left $p7" } + if ([IO.File]::ReadAllText("$wt\settings.json") -ne $orig) { throw 'uninstall did not put defaultProfile back' } + 'uninstall ok' + + # Windows, the heavy part: Neovim with NvChad, a C compiler, tree-sitter parsers and Mason, for real (10-20 minutes). + windows-nvim: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - name: winget on the runner + shell: pwsh + run: | + if (-not (Get-Command winget -ErrorAction SilentlyContinue)) { + Install-Module Microsoft.WinGet.Client -Force -Scope CurrentUser + Repair-WinGetPackageManager -AllUsers -Latest + } + winget --version + - name: Real run of nvim + shell: powershell + run: | + powershell -NoProfile -ExecutionPolicy Bypass -File .\install.ps1 -Yes -Only nvim + if ($LASTEXITCODE -ne 0) { throw "install failed: $LASTEXITCODE" } + - name: Parsers and LSP servers are there + shell: pwsh + run: | + $env:Path = [Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' + [Environment]::GetEnvironmentVariable('Path', 'User') + $data = "$env:LOCALAPPDATA\nvim-data" + Get-ChildItem "$data\site\parser" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Name + foreach ($p in 'lua', 'php', 'html', 'javascript') { + if (-not (Get-ChildItem "$data\site\parser" -Filter "$p.*" -ErrorAction SilentlyContinue)) { throw "parser missing: $p" } + } + Get-ChildItem "$data\mason\packages" | Select-Object -ExpandProperty Name + foreach ($m in (Get-Content config\nvim\mason-packages | Where-Object { $_ })) { + if (-not (Test-Path "$data\mason\packages\$m")) { + Get-ChildItem $data -Filter 'mason*.log' -Recurse -ErrorAction SilentlyContinue | ForEach-Object { Get-Content $_.FullName -Tail 40 } + throw "Mason package missing: $m" + } + } + nvim --headless "+lua print(vim.treesitter.language.add('php') and 'php parser loads' or 'no php')" +qa + + # Windows: the web tools for real (PHP + php.ini, Composer, MariaDB service, phpMyAdmin). + windows-web: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - name: Real run of web + shell: powershell + run: | + powershell -NoProfile -ExecutionPolicy Bypass -File .\install.ps1 -Yes -Only web + if ($LASTEXITCODE -ne 0) { throw "install failed: $LASTEXITCODE" } + - name: PHP extensions, Composer, MariaDB + shell: pwsh + run: | + $env:Path = [Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' + [Environment]::GetEnvironmentVariable('Path', 'User') + $php = (Get-ChildItem "$env:LOCALAPPDATA\Microsoft\WinGet\Packages" -Directory -Filter 'PHP.PHP.8.5_*' | Select-Object -First 1).FullName + '\php.exe' + & $php -v + $mods = & $php -m + foreach ($e in 'curl', 'mbstring', 'mysqli', 'openssl', 'pdo_mysql', 'zip') { if ($mods -notcontains $e) { throw "php extension missing: $e" } } + & $php "$env:USERPROFILE\.local\bin\composer.phar" --version + if ($LASTEXITCODE -ne 0) { throw 'composer does not run' } + Get-Service *maria*, *mysql* -ErrorAction SilentlyContinue | Format-Table Name, Status, StartType + $svc = Get-Service MariaDB + "MariaDB service: $($svc.Status), $($svc.StartType)" + if ($svc.StartType -ne 'Manual') { throw 'MariaDB should start by hand (the default answer is no)' } + Start-Service MariaDB + mariadb -u root -e "SELECT VERSION();" + if ($LASTEXITCODE -ne 0) { throw 'mariadb login failed' } + if (-not (Test-Path "$env:LOCALAPPDATA\rhmatzeka-dotfile-tools\phpmyadmin\index.php")) { throw 'phpMyAdmin missing' } diff --git a/README.md b/README.md index 7ad12e4..59b65cf 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Dotfiles for Linux (Debian, Ubuntu, Arch, Fedora, openSUSE) and macOS: zsh, tmux, Neovim, Ghostty and Hyprland in one command +# Dotfiles for Linux (Debian, Ubuntu, Arch, Fedora, openSUSE), macOS and Windows: zsh, tmux, Neovim, Ghostty and Hyprland in one command [![ci](https://github.com/rhmatzeka/dotfile/actions/workflows/ci.yml/badge.svg)](https://github.com/rhmatzeka/dotfile/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/github/license/rhmatzeka/dotfile)](LICENSE) @@ -8,9 +8,10 @@ ![Fedora 44](https://img.shields.io/badge/Fedora-44-51A2DA?logo=fedora&logoColor=white) ![openSUSE Tumbleweed](https://img.shields.io/badge/openSUSE-Tumbleweed-73BA25?logo=opensuse&logoColor=white) ![macOS beta](https://img.shields.io/badge/macOS-beta-000000?logo=apple&logoColor=white) +![Windows beta](https://img.shields.io/badge/Windows-beta-0078D4?logo=windows&logoColor=white) -A one-command **dotfiles installer** for Linux (Debian/Ubuntu, Arch, Fedora, openSUSE) and **macOS** (beta) for a fast -terminal and, on Linux, an optional **Hyprland** desktop with the **Caelestia** shell. A checklist lets you pick only the +A one-command **dotfiles installer** for Linux (Debian/Ubuntu, Arch, Fedora, openSUSE), **macOS** (beta) and +**Windows** (beta, [PowerShell + Windows Terminal](#windows)) for a fast terminal and, on Linux, an optional **Hyprland** desktop with the **Caelestia** shell. A checklist lets you pick only the parts you want, for example just the terminal setup on a Mac. It sets up **zsh** (Oh My Zsh, starship), **tmux**, **Neovim** with **NvChad** (tree-sitter, LSP), **Ghostty**, terminal browsers (Browsh, elinks, w3m) and a Dracula + cyan theme. Nothing is overwritten without a backup, and everything can be undone. @@ -19,6 +20,12 @@ backup, and everything can be undone. bash <(curl -fsSL https://dotfiles.rahmateka.my.id) ``` +On Windows, in PowerShell: + +```powershell +irm https://raw.githubusercontent.com/rhmatzeka/dotfile/main/install.ps1 | iex +``` + ## Preview @@ -133,6 +140,50 @@ shows up on the other machine after the next install (or `git pull` in `~/.local Your SSH keys, `.env` files and app logins are not part of this repository; copy them over yourself. +## Windows + +Windows has no zsh, tmux or Ghostty, so the Windows installer (beta) sets up the closest native equivalents with the +same look: **PowerShell** gets the same starship prompt, aliases and fzf keys as the zshrc, and **Windows Terminal** +gets the Ghostty colours, font, padding and cursor. Neovim, Rust and the web tools are the same as everywhere else. +Packages come from **winget**, which Windows 10 (1809 or newer) and 11 already have. The desktop parts (Hyprland, +Caelestia) and the Linux-only tools are listed but cannot be picked. + +Open **PowerShell** (a normal window, not as administrator) and run: + +```powershell +irm https://raw.githubusercontent.com/rhmatzeka/dotfile/main/install.ps1 | iex +``` + +To pass options, wrap it in a script block: + +```powershell +& ([scriptblock]::Create((irm https://raw.githubusercontent.com/rhmatzeka/dotfile/main/install.ps1))) -DryRun -All +& ([scriptblock]::Create((irm https://raw.githubusercontent.com/rhmatzeka/dotfile/main/install.ps1))) -Only shell,terminal +``` + +It installs git with winget if needed, fetches this repository to `%LOCALAPPDATA%\rhmatzeka-dotfile` and shows the same +checklist as on Linux and macOS (`-All`, `-Only`, `-DryRun`, `-Yes`, `-List` work like their `--` versions). + +| Part | On Windows | +|---|---| +| `base` | winget: git, ripgrep, fzf, jq, PowerShell 7, the JetBrainsMono Nerd Font; eza, zoxide, fastfetch and btop4win when available | +| `shell` | starship, and one PowerShell profile linked to both PowerShell 7 and Windows PowerShell 5.1: starship prompt, PSReadLine history suggestions and Dracula colours, fzf on **Ctrl+R** (history), **Ctrl+T** (files) and **Alt+C** (folders), zoxide (`z`), eza for `ls`/`ll`/`la`, `n` for nvim, and the git shortcuts `g ga gst gd gco gb glog`. If Windows PowerShell would refuse to run the profile (the default `Restricted` script policy), it offers `Set-ExecutionPolicy RemoteSigned -Scope CurrentUser`. Local tweaks go in `~\.config\powershell\local.ps1` | +| `nvim` | Neovim, Node.js, the tree-sitter CLI and NvChad in `%LOCALAPPDATA%\nvim`, with the same parsers and Mason servers. The parsers need a C compiler: if there is no Visual Studio, GCC from WinLibs is installed (about 1 GB) | +| `terminal` | Windows Terminal (when missing) and a **profile "dotfiles (PowerShell)"** with the colour scheme, added as a [JSON fragment](https://learn.microsoft.com/windows/terminal/json-fragment-extensions) so your `settings.json` is not rewritten. It offers to make it the default profile (one value in `settings.json` changes; `uninstall` puts it back) | +| `web` | PHP 8.5 (with a `php.ini` that turns on openssl, curl, mbstring, mysqli, pdo_mysql, zip), Composer (checked against its SHA-256), MariaDB and phpMyAdmin. MariaDB is a Windows service: it asks whether it should start with Windows (default no) | +| `rust` | The official `rustup-init.exe`. Without Visual Studio it uses the GNU toolchain, which needs nothing else; it offers the Visual Studio Build Tools (about 5 GB) for the MSVC toolchain instead | +| `tmux`, `browsers`, `desktop`, `apps` | not on Windows (use Windows Terminal panes: Alt+Shift+D splits, Alt+arrows moves) | + +For the real zsh/tmux setup on Windows, install **WSL** (`wsl --install`), open Ubuntu and run the Linux command inside it. + +Files are linked to the repository when Windows allows symbolic links (**Developer Mode** on, or an administrator +window); otherwise they are copied, and running the installer again after a `git pull` refreshes the copies. Undo +everything with: + +```powershell +irm https://raw.githubusercontent.com/rhmatzeka/dotfile/main/uninstall.ps1 | iex +``` + ## What you get | Component | Contents | @@ -191,6 +242,7 @@ If RAM is tight: | Fedora 44 (and RHEL-likes via `ID_LIKE`) | Installed and checked from scratch in the official Fedora container image. `starship` is not in the Fedora repositories: its official installer is used. Only Fedora itself was tested. `web` and `rust` also installed and checked from scratch | | openSUSE Tumbleweed | Installed and checked from scratch in the official Tumbleweed image. Leap and SLE were not tested. `web` and `rust` also installed and checked from scratch | | macOS 13 or newer (Apple Silicon and Intel) | **Beta.** Everything except `desktop` and `apps`, through Homebrew. Checked on every push by GitHub Actions on `macos-latest` with Apple's own `/bin/bash` 3.2: the menu, a dry run of every part, and a real install of `shell`, `tmux`, `browsers` and `rust` followed by `uninstall`. Not yet run by hand on a real Mac; `nvim`, `terminal` (Ghostty) and `web` were only dry-run | +| Windows 10 (1809+) and 11 | **Beta.** `base`, `shell`, `nvim`, `terminal`, `web`, `rust` through winget and PowerShell (see [Windows](#windows)). Checked on every push by GitHub Actions on `windows-latest` under Windows PowerShell 5.1 and PowerShell 7: every script parses, PSScriptAnalyzer, the menu with scripted answers, a dry run of every part, a real install of `shell` and `terminal` (the profile loads in both PowerShells; the default-profile edit keeps `settings.json` comments and is undone by `uninstall`) followed by `uninstall`, a real install of `nvim` (all 18 parsers and 7 Mason servers) and of `web` (PHP extensions, Composer, the MariaDB service left on Manual, a root login, phpMyAdmin). Not yet run by hand on a desktop Windows; `rust` was only dry-run, and the runner has Visual Studio, so the GCC and GNU-toolchain fallbacks were not exercised there | | Alpine, NixOS, Void, Gentoo | **Not supported.** Contributions are welcome (see below) | `desktop` (Hyprland + Caelestia) is **Debian 13 only** because it depends on `trixie-backports` and on pinned build diff --git a/config/nvim/dotfiles.lua b/config/nvim/dotfiles.lua index 3a49156..77b1439 100644 --- a/config/nvim/dotfiles.lua +++ b/config/nvim/dotfiles.lua @@ -1,5 +1,12 @@ -- Extra plugin specs on top of the NvChad starter. -- Linked to ~/.config/nvim/lua/plugins/dotfiles.lua by rhmatzeka/dotfile; edit it in ~/.dotfiles/config/nvim/. +-- (On Windows: %LOCALAPPDATA%\nvim\lua\plugins\dotfiles.lua.) + +-- Windows: tree-sitter builds parsers with Visual Studio's cl.exe unless CC names another compiler. The Windows +-- installer brings GCC (WinLibs) when there is no Visual Studio, so point CC at it. Nothing happens on Linux/macOS. +if vim.fn.has("win32") == 1 and (vim.env.CC or "") == "" and vim.fn.executable("cl") == 0 and vim.fn.executable("gcc") == 1 then + vim.env.CC = "gcc" +end return { -- Syntax highlighting. Without the html/css/js parsers, a .php or .vue file that is mostly markup stays plain white. diff --git a/config/powershell/profile.ps1 b/config/powershell/profile.ps1 new file mode 100644 index 0000000..7de0e94 --- /dev/null +++ b/config/powershell/profile.ps1 @@ -0,0 +1,106 @@ +# PowerShell profile (managed by rhmatzeka/dotfile). The Windows counterpart of config/zsh/zshrc. +# Linked to both $PROFILE files (PowerShell 7 and Windows PowerShell 5.1); machine-local tweaks go in +# ~\.config\powershell\local.ps1, which is not in the repo. ASCII only: 5.1 reads BOM-less scripts as ANSI. + +# -- PATH ---------------------------------------------------------------------- +foreach ($d in @("$HOME\.local\bin", "$HOME\.cargo\bin", "$HOME\.bun\bin")) { + if ((Test-Path -LiteralPath $d) -and (($env:Path -split ';') -notcontains $d)) { $env:Path = "$d;$env:Path" } +} +$env:EDITOR = 'nvim' +$env:VISUAL = 'nvim' + +function _has([string]$c) { [bool](Get-Command $c -ErrorAction SilentlyContinue) } + +# -- line editing and history (PSReadLine ships with both PowerShell versions) --- +if (Get-Module -ListAvailable PSReadLine) { + Import-Module PSReadLine -ErrorAction SilentlyContinue + Set-PSReadLineOption -HistoryNoDuplicates -MaximumHistoryCount 50000 -BellStyle None + # Dracula palette with a cyan accent, the same colours as zsh-syntax-highlighting in the zshrc. + # ([char]27 instead of `e: Windows PowerShell 5.1 does not know the `e escape) + $esc = [string][char]27 + Set-PSReadLineOption -Colors @{ + Command = "$esc[1;38;2;0;217;255m" + Parameter = "$esc[38;2;139;233;253m" + String = "$esc[38;2;241;250;140m" + Variable = "$esc[38;2;189;147;249m" + Number = "$esc[38;2;255;184;108m" + Comment = "$esc[38;2;108;117;125m" + Error = "$esc[38;2;255;85;85m" + } + # grey suggestions from history while you type (PSReadLine 2.1+, i.e. PowerShell 7 or an updated 5.1) + if ((Get-Module PSReadLine).Version -ge [version]'2.1.0') { + try { Set-PSReadLineOption -PredictionSource History -ErrorAction Stop } catch { } + } + Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete + Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward + Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward + + # fzf: Ctrl+R history, Ctrl+T files, Alt+C directories (like fzf's key-bindings.zsh) + if (_has 'fzf') { + Set-PSReadLineKeyHandler -Chord 'Ctrl+r' -BriefDescription 'fzf history' -ScriptBlock { + $hist = (Get-PSReadLineOption).HistorySavePath + if (-not (Test-Path -LiteralPath $hist)) { return } + $line = $null; $cursor = $null + [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) + $lines = [System.Collections.Generic.List[string]]::new() + foreach ($l in [IO.File]::ReadAllLines($hist)) { if ($l -and -not $lines.Contains($l)) { $lines.Add($l) } } + $lines.Reverse() + $pick = $lines | fzf --height 40% --reverse --no-sort --query $line + [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt() + if ($pick) { + [Microsoft.PowerShell.PSConsoleReadLine]::RevertLine() + [Microsoft.PowerShell.PSConsoleReadLine]::Insert($pick) + } + } + Set-PSReadLineKeyHandler -Chord 'Ctrl+t' -BriefDescription 'fzf file' -ScriptBlock { + $pick = if (_has 'rg') { rg --files --hidden --glob '!.git' 2>$null | fzf --height 40% --reverse } else { fzf --height 40% --reverse } + [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt() + if ($pick) { if ($pick -match '\s') { $pick = "'$pick'" }; [Microsoft.PowerShell.PSConsoleReadLine]::Insert($pick) } + } + Set-PSReadLineKeyHandler -Chord 'Alt+c' -BriefDescription 'fzf cd' -ScriptBlock { + $pick = Get-ChildItem -Directory -Recurse -Depth 4 -Name -ErrorAction SilentlyContinue | fzf --height 40% --reverse + if ($pick) { Set-Location -LiteralPath $pick } + [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt() + } + } +} + +# -- aliases, each one optional ---------------------------------------------------- +if (_has 'eza') { + Remove-Item Alias:ls -Force -ErrorAction SilentlyContinue + function ls { eza --group-directories-first --icons=auto @args } + function ll { eza -lh --group-directories-first --icons=auto --git @args } + function la { eza -lah --group-directories-first --icons=auto --git @args } +} else { + function ll { Get-ChildItem @args } + function la { Get-ChildItem -Force @args } +} +function n { nvim @args } +function .. { Set-Location .. } +function ... { Set-Location ..\.. } +function which([string]$name) { Get-Command $name -All -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source -ErrorAction SilentlyContinue } +function touch([string]$path) { if (Test-Path -LiteralPath $path) { (Get-Item -LiteralPath $path).LastWriteTime = Get-Date } else { New-Item -ItemType File -Path $path | Out-Null } } + +# a few of Oh My Zsh's git aliases (only those that do not hide a built-in PowerShell alias such as gc, gp, gl) +if (_has 'git') { + function g { git @args } + function ga { git add @args } + function gst { git status @args } + function gd { git diff @args } + function gco { git checkout @args } + function gb { git branch @args } + function glog { git log --oneline --decorate --graph @args } +} + +if (_has 'zoxide') { Invoke-Expression (& { (zoxide init powershell | Out-String) }) } + +# -- prompt -------------------------------------------------------------------------- +if (_has 'starship') { + $env:STARSHIP_CONFIG = "$HOME\.config\starship.toml" + Invoke-Expression (& starship init powershell --print-full-init | Out-String) +} + +# -- machine-local overrides (not in the repo) ------------------------------------------ +$local = "$HOME\.config\powershell\local.ps1" +if (Test-Path -LiteralPath $local) { . $local } +Remove-Variable local, d, esc -ErrorAction SilentlyContinue diff --git a/config/windows-terminal/dotfiles.json b/config/windows-terminal/dotfiles.json new file mode 100644 index 0000000..24c51d9 --- /dev/null +++ b/config/windows-terminal/dotfiles.json @@ -0,0 +1,43 @@ +{ + "profiles": [ + { + "guid": "{8af80b22-81dc-5325-91bc-4b9b947457a5}", + "name": "dotfiles (PowerShell)", + "commandline": "pwsh.exe -NoLogo", + "icon": "ms-appx:///ProfileIcons/pwsh.png", + "startingDirectory": "%USERPROFILE%", + "colorScheme": "rhmatzeka Dracula Cyan", + "font": { "face": "JetBrainsMono Nerd Font", "size": 12 }, + "opacity": 90, + "useAcrylic": false, + "padding": "10, 8", + "cursorShape": "bar", + "closeOnExit": "graceful" + } + ], + "schemes": [ + { + "name": "rhmatzeka Dracula Cyan", + "background": "#0D1117", + "foreground": "#EFF1F4", + "cursorColor": "#00D9FF", + "selectionBackground": "#1F3A4D", + "black": "#1B1F27", + "red": "#FF5555", + "green": "#50FA7B", + "yellow": "#F1FA8C", + "blue": "#BD93F9", + "purple": "#FF79C6", + "cyan": "#00D9FF", + "white": "#EFF1F4", + "brightBlack": "#6C757D", + "brightRed": "#FF6E6E", + "brightGreen": "#69FF94", + "brightYellow": "#FFFFA5", + "brightBlue": "#D6ACFF", + "brightPurple": "#FF92DF", + "brightCyan": "#01CBC6", + "brightWhite": "#FFFFFF" + } + ] +} diff --git a/install.ps1 b/install.ps1 new file mode 100644 index 0000000..b5b6cba --- /dev/null +++ b/install.ps1 @@ -0,0 +1,102 @@ +# rhmatzeka/dotfile - Windows entry point (Windows 10/11, Windows PowerShell 5.1 or PowerShell 7). +# +# irm https://raw.githubusercontent.com/rhmatzeka/dotfile/main/install.ps1 | iex +# & ([scriptblock]::Create((irm https://raw.githubusercontent.com/rhmatzeka/dotfile/main/install.ps1))) -DryRun -All +# .\install.ps1 -Only shell,terminal (from a checkout) +# .\install.ps1 -Uninstall +# +# This file only checks the system, fetches the repository to %LOCALAPPDATA%\rhmatzeka-dotfile (with git, which it +# installs through winget when missing) and hands over to windows\install.ps1 in a fresh PowerShell that is allowed to +# run it. Everything it will do is printed first; -DryRun changes nothing. Linux and macOS use install.sh instead. +# ASCII only: Windows PowerShell 5.1 reads BOM-less scripts as ANSI. +[CmdletBinding()] +param( + [switch]$Uninstall, + [switch]$All, + [string]$Only = '', + [switch]$DryRun, + [switch]$Yes, + [switch]$List, + [switch]$Help +) + +# Everything runs inside this script block, so `irm | iex` never closes the window (no `exit`) and leaves no +# variables or settings behind in the user's session. Its output is NOT captured: the installer it starts must keep +# the real console (colours, the menu, questions). The result travels in $LASTEXITCODE. +& { + $ErrorActionPreference = 'Stop' + function Quit([int]$c) { $global:LASTEXITCODE = $c } + function Say([string]$m) { Write-Host ' > ' -ForegroundColor Cyan -NoNewline; Write-Host $m } + function Good([string]$m) { Write-Host ' ok ' -ForegroundColor Green -NoNewline; Write-Host $m } + function Bad([string]$m) { Write-Host ' x ' -ForegroundColor Red -NoNewline; Write-Host $m } + + $repoUrl = 'https://github.com/rhmatzeka/dotfile.git'; if ($env:DOTFILES_REPO) { $repoUrl = $env:DOTFILES_REPO } + $branch = 'main'; if ($env:DOTFILES_BRANCH) { $branch = $env:DOTFILES_BRANCH } + $dir = Join-Path $env:LOCALAPPDATA 'rhmatzeka-dotfile'; if ($env:DOTFILES_DIR) { $dir = $env:DOTFILES_DIR } + $action = 'install'; if ($Uninstall) { $action = 'uninstall' } + + Write-Host '' + Write-Host " dotfiles $action" -ForegroundColor Cyan + Write-Host ' https://github.com/rhmatzeka/dotfile' -ForegroundColor DarkGray + Write-Host '' + + if ($env:OS -ne 'Windows_NT') { Bad 'This is the Windows installer. On Linux and macOS run: bash <(curl -fsSL https://dotfiles.rahmateka.my.id)'; Quit 1; return } + $os = [Environment]::OSVersion.Version + Good "Detected: Windows (build $($os.Build), $env:PROCESSOR_ARCHITECTURE), PowerShell $($PSVersionTable.PSVersion)" + + function Refresh-Path { + $env:Path = ([Environment]::GetEnvironmentVariable('Path', 'Machine'), [Environment]::GetEnvironmentVariable('Path', 'User'), $env:Path) -join ';' + } + + # Run from a checkout? Use it as is. Run through irm? Fetch the repository. + if ($PSScriptRoot -and (Test-Path (Join-Path $PSScriptRoot 'windows\install.ps1')) -and -not $env:DOTFILES_FORCE_CLONE) { + $dir = $PSScriptRoot + Good "Using this checkout: $dir" + } else { + if (-not (Get-Command git -ErrorAction SilentlyContinue)) { + if (-not (Get-Command winget -ErrorAction SilentlyContinue)) { + Bad 'git and winget are both missing. Install "App Installer" from the Microsoft Store (https://aka.ms/getwinget) and run this again.' + Quit 1; return + } + Say 'git is needed to fetch the repository: installing it with winget' + & winget install --id Git.Git --exact --source winget --accept-package-agreements --accept-source-agreements --disable-interactivity | Out-Host + Refresh-Path + if (-not (Get-Command git -ErrorAction SilentlyContinue)) { Bad 'git is still not on PATH; open a new PowerShell window and run this again.'; Quit 1; return } + } + $ErrorActionPreference = 'Continue' # git writes progress to stderr, which 5.1 would treat as an error + if (Test-Path (Join-Path $dir '.git')) { + $origin = (& git -C $dir remote get-url origin 2>$null) -replace '\.git$', '' + if ($origin -ne ($repoUrl -replace '\.git$', '')) { + Bad "$dir is a git repository of something else (origin: $origin); not touching it." + Say 'Set DOTFILES_DIR to another folder and run again.' + Quit 1; return + } + Say "Updating $dir" + if (& git -C $dir status --porcelain 2>$null) { Say "Local changes found in ${dir}: leaving them untouched and not updating." } + else { + & git -C $dir fetch -q origin $branch 2>&1 | Out-Null + & git -C $dir checkout -q $branch 2>&1 | Out-Null + & git -C $dir pull -q --ff-only origin $branch 2>&1 | Out-Null + if ($LASTEXITCODE -ne 0) { Say 'Could not fast-forward; continuing with what is already there.' } + } + } else { + Say "Fetching $repoUrl -> $dir" + & git clone -q --branch $branch $repoUrl $dir 2>&1 | Out-Host + if ($LASTEXITCODE -ne 0) { Bad 'git clone failed.'; Quit 1; return } + } + } + + $target = Join-Path $dir "windows\$action.ps1" + if (-not (Test-Path $target)) { Bad "Missing $target"; Quit 1; return } + $fwd = @() + foreach ($k in @('All', 'DryRun', 'Yes', 'List', 'Help')) { if ((Get-Variable $k -ValueOnly)) { $fwd += "-$k" } } + if ($Only) { $fwd += @('-Only', $Only) } + # the same kind of PowerShell that runs this (5.1 or 7); -ExecutionPolicy Bypass for this one process only + $exe = Join-Path $PSHOME 'powershell.exe'; if ($PSVersionTable.PSEdition -eq 'Core') { $exe = Join-Path $PSHOME 'pwsh.exe' } + $env:DOTFILES_DIR = $dir + Write-Host '' + & $exe -NoProfile -ExecutionPolicy Bypass -File $target @fwd + Quit $LASTEXITCODE +} +# started as a file: pass the exit code on. Started through irm | iex: keep it in $LASTEXITCODE, the window stays open. +if ($PSCommandPath) { exit $LASTEXITCODE } diff --git a/install.sh b/install.sh index 438703f..d7b3fbd 100755 --- a/install.sh +++ b/install.sh @@ -49,6 +49,10 @@ case "$(uname -s)" in say "Supported: macOS, and the Debian/Ubuntu, Arch, Fedora and openSUSE families." exit 1 ;; esac ;; + MINGW*|MSYS*|CYGWIN*) + bad "This is the Linux/macOS installer. On Windows, open PowerShell and run:" + say "irm https://raw.githubusercontent.com/rhmatzeka/dotfile/main/install.ps1 | iex" + exit 1 ;; *) bad "Unsupported OS: $(uname -s)"; exit 1 ;; esac if [ "$PLATFORM" = macos ]; then diff --git a/tests/windows.ps1 b/tests/windows.ps1 new file mode 100644 index 0000000..d710c95 --- /dev/null +++ b/tests/windows.ps1 @@ -0,0 +1,78 @@ +# Checks for the Windows installer that need no packages: every .ps1 parses, and the menu does what it says when it is +# fed scripted answers (DOTFILES_ANSWERS), all in a throw-away home. Run with Windows PowerShell 5.1 and PowerShell 7: +# powershell -NoProfile -ExecutionPolicy Bypass -File tests\windows.ps1 +$ErrorActionPreference = 'Stop' +# the installers are separate processes; under Stop, Windows PowerShell 5.1 would turn anything they write to stderr +# into an exception here, so native calls below run with Continue and are judged by their exit code and output +function Native([scriptblock]$b) { $ErrorActionPreference = 'Continue'; & $b } +$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path +$failures = 0 +function Check([string]$name, [bool]$ok) { + if ($ok) { Write-Host " ok $name" -ForegroundColor Green } else { Write-Host " FAIL $name" -ForegroundColor Red; $script:failures++ } +} + +# -- every PowerShell file parses, and is ASCII (5.1 reads BOM-less files as ANSI) -- +$files = @(Get-ChildItem -Path $root -Recurse -Filter '*.ps1' | Where-Object { $_.FullName -notmatch '\\\.git\\' }) +foreach ($f in $files) { + $tokens = $null; $errs = $null + [void][System.Management.Automation.Language.Parser]::ParseFile($f.FullName, [ref]$tokens, [ref]$errs) + Check "parses: $($f.Name)" ($errs.Count -eq 0) + if ($errs.Count) { $errs | ForEach-Object { Write-Host " $($_.Extent.StartLineNumber): $($_.Message)" } } + $bytes = [IO.File]::ReadAllBytes($f.FullName) + Check "ascii: $($f.Name)" (-not ($bytes | Where-Object { $_ -gt 127 } | Select-Object -First 1)) +} + +# -- the menu, driven by an answers file -- +$tmp = Join-Path ([IO.Path]::GetTempPath()) ("dotfiles-test-" + [guid]::NewGuid().ToString('N').Substring(0, 8)) +New-Item -ItemType Directory -Path $tmp | Out-Null +$env:DOTFILES_HOME = $tmp +$env:DOTFILES_DOCUMENTS = Join-Path $tmp 'Documents' +$env:DOTFILES_LOCALAPPDATA = Join-Path $tmp 'AppData\Local' +$exe = Join-Path $PSHOME 'powershell.exe'; if ($PSVersionTable.PSEdition -eq 'Core') { $exe = Join-Path $PSHOME 'pwsh.exe' } +$installer = Join-Path $root 'windows\install.ps1' + +function Run-Menu([string[]]$answers, [string[]]$extra) { + $file = Join-Path $tmp 'answers.txt' + Set-Content -LiteralPath $file -Value $answers -Encoding Ascii + $env:DOTFILES_ANSWERS = $file + $out = Native { & $exe -NoProfile -ExecutionPolicy Bypass -File $installer @extra 2>&1 | Out-String } + $script:rc = $LASTEXITCODE + Remove-Item Env:DOTFILES_ANSWERS + return $out +} + +# 5 = web: checked on top of the defaults; Enter continues; the dry run needs no "Continue?" +$out = Run-Menu @('5', '') @('-DryRun') +Check 'menu: toggling 5 adds web to the defaults' ($out -match 'Will install: base shell nvim terminal web') +Check 'menu: dry run exits 0' ($rc -eq 0) +Check 'menu: Linux-only parts are listed' ($out -match 'tmux' -and $out -match 'desktop') + +# n = none, then 2 and 6 by name/number +$out = Run-Menu @('n', '2 rust', '') @('-DryRun') +Check 'menu: none + "2 rust" selects shell and rust' ($out -match 'Will install: shell rust') + +# a Linux-only name typed into the menu is refused with a reason +$out = Run-Menu @('tmux', 'q') @('-DryRun') +Check 'menu: tmux is refused' ($out -match 'tmux is not available on Windows') +Check 'menu: q quits with 0' ($rc -eq 0 -and $out -match 'Nothing installed') + +# saying no at "Continue?" installs nothing +$out = Run-Menu @('', 'n') @() +Check 'menu: "n" at Continue? cancels' ($out -match 'Cancelled' -and $rc -eq 0) + +# -Only refuses Linux-only and unknown parts +$null = Native { & $exe -NoProfile -ExecutionPolicy Bypass -File $installer -DryRun -Yes -Only desktop 2>&1 } +Check '-Only desktop is refused' ($LASTEXITCODE -ne 0) +$null = Native { & $exe -NoProfile -ExecutionPolicy Bypass -File $installer -DryRun -Yes -Only nonsense 2>&1 } +Check '-Only nonsense is refused' ($LASTEXITCODE -ne 0) +$out = Native { & $exe -NoProfile -ExecutionPolicy Bypass -File $installer -List 2>&1 | Out-String } +Check '-List names every component' ($out -match 'base' -and $out -match 'rust' -and $out -match 'Not available on Windows') + +# nothing was written into the throw-away home by any of the above +Check 'no files written by menu tests' (-not (Get-ChildItem -LiteralPath $tmp -Recurse -File | Where-Object { $_.Name -ne 'answers.txt' })) + +Remove-Item -Recurse -Force $tmp +foreach ($v in 'DOTFILES_HOME', 'DOTFILES_DOCUMENTS', 'DOTFILES_LOCALAPPDATA') { Remove-Item "Env:$v" -ErrorAction SilentlyContinue } +Write-Host '' +if ($failures) { Write-Host " $failures check(s) failed" -ForegroundColor Red; exit 1 } +Write-Host ' all checks passed' -ForegroundColor Green diff --git a/uninstall.ps1 b/uninstall.ps1 new file mode 100644 index 0000000..0784910 --- /dev/null +++ b/uninstall.ps1 @@ -0,0 +1,21 @@ +# rhmatzeka/dotfile - undo the Windows install (your original files come back from ~\.dotfiles-backup). +# +# irm https://raw.githubusercontent.com/rhmatzeka/dotfile/main/uninstall.ps1 | iex +# .\uninstall.ps1 -DryRun +# +# winget packages and fonts are left alone; the uninstaller lists them at the end. +[CmdletBinding()] +param([switch]$DryRun, [switch]$Yes) + +& { + if ($PSScriptRoot -and (Test-Path (Join-Path $PSScriptRoot 'install.ps1'))) { + & (Join-Path $PSScriptRoot 'install.ps1') -Uninstall -DryRun:$DryRun -Yes:$Yes + return + } + # Started through irm: fetch the entry script from the repository itself. + $url = 'https://raw.githubusercontent.com/rhmatzeka/dotfile/main/install.ps1' + if ($env:DOTFILES_INSTALL_URL) { $url = $env:DOTFILES_INSTALL_URL } + $entry = [scriptblock]::Create((Invoke-RestMethod -Uri $url -UseBasicParsing)) + & $entry -Uninstall -DryRun:$DryRun -Yes:$Yes +} +if ($PSCommandPath) { exit $LASTEXITCODE } diff --git a/windows/install.ps1 b/windows/install.ps1 new file mode 100644 index 0000000..b49a3bf --- /dev/null +++ b/windows/install.ps1 @@ -0,0 +1,423 @@ +# Windows installer (beta): the terminal setup and the developer tools, split into components you pick from a menu. +# +# .\install.ps1 interactive menu +# .\install.ps1 -All every component that works on Windows +# .\install.ps1 -Only shell,nvim +# .\install.ps1 -DryRun show what would happen, change nothing +# .\install.ps1 -Yes no questions; answer each with its default +# .\install.ps1 -List list the components +# +# Normally started through the top-level install.ps1 (which also fetches the repository). Works in Windows +# PowerShell 5.1 and PowerShell 7. Packages come from winget (App Installer, built into Windows 10 and 11). +# Windows has no zsh, tmux or Ghostty: the shell is PowerShell with the same prompt, aliases and fzf keys, and the +# terminal is Windows Terminal with the same colours and font. The Linux-only parts are listed but cannot be selected. +[CmdletBinding()] +param( + [switch]$All, + [string]$Only = '', + [switch]$DryRun, + [switch]$Yes, + [switch]$List, + [switch]$Help +) +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version 2 + +$script:DotfilesDir = $env:DOTFILES_DIR +if (-not $script:DotfilesDir) { $script:DotfilesDir = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path } +$script:DryRun = [bool]$DryRun +$script:AssumeYes = [bool]$Yes +. (Join-Path $script:DotfilesDir 'windows\lib.ps1') + +$script:ConfigDir = Join-Path $script:DotfilesDir 'config' +$Arch = $env:PROCESSOR_ARCHITECTURE # AMD64 or ARM64 (x86 for a 32-bit shell on a 64-bit system) +if ($env:PROCESSOR_ARCHITEW6432) { $Arch = $env:PROCESSOR_ARCHITEW6432 } + +$ProfileTargets = @( + (Join-Path $script:Documents 'PowerShell\Microsoft.PowerShell_profile.ps1'), # PowerShell 7 + (Join-Path $script:Documents 'WindowsPowerShell\Microsoft.PowerShell_profile.ps1') # Windows PowerShell 5.1 +) +$NvimDir = Join-Path $script:LocalAppData 'nvim' +$FragmentDst = Join-Path $script:LocalAppData 'Microsoft\Windows Terminal\Fragments\rhmatzeka-dotfile\dotfiles.json' +$WtProfileGuid = '{8af80b22-81dc-5325-91bc-4b9b947457a5}' # same as in config/windows-terminal/dotfiles.json +$ToolsDir = Join-Path $script:LocalAppData 'rhmatzeka-dotfile-tools' + +# ------------------------------------------------------------------ menu ---- +$script:MenuTitle = 'Windows (beta)' +$script:MenuItems = @('base', 'shell', 'nvim', 'terminal', 'web', 'rust') +$script:MenuDefaults = @('base', 'shell', 'nvim', 'terminal') +$script:MenuOffOrder = @('tmux', 'browsers', 'desktop', 'apps') +$script:MenuOff = @{ + tmux = 'no tmux on Windows: use Windows Terminal panes (Alt+Shift+D splits), or WSL with the Linux installer' + browsers = 'Browsh, elinks and w3m are Linux/macOS only' + desktop = 'Hyprland + Caelestia desktop (Linux only)' + apps = 'Microsoft 365 web-app launchers (Linux only; Windows has Office itself)' +} + +$script:MenuDesc = { + param($c) + switch ($c) { + 'base' { 'winget packages: git, ripgrep, fzf, eza, zoxide, PowerShell 7 and the JetBrainsMono Nerd Font' } + 'shell' { 'PowerShell profile: starship prompt, fzf keys (Ctrl+R/Ctrl+T), zoxide, eza and git aliases' } + 'nvim' { 'Neovim (NvChad) with tree-sitter parsers and LSP servers' } + 'terminal' { 'Windows Terminal profile + colour scheme (the Ghostty look: Dracula + cyan, Nerd Font)' } + 'web' { 'Web development: PHP, Composer, MariaDB, phpMyAdmin (MariaDB does not start with Windows unless you say yes)' } + 'rust' { 'Rust toolchain via rustup (rustc, cargo, clippy, rustfmt, rust-analyzer)' } + } +} + +$script:MenuStatus = { + param($c) + switch ($c) { + 'base' { if ((Have 'git') -and (Have 'rg') -and (Have 'fzf') -and (Font-Present)) { 'installed' } } + 'shell' { if ((Installed-Here $ProfileTargets[0]) -and (Have 'starship')) { 'installed' } } + 'nvim' { if ((Installed-Here (Join-Path $NvimDir 'lua\plugins\dotfiles.lua')) -and (Have 'nvim')) { 'installed' } } + 'terminal' { if (Installed-Here $FragmentDst) { 'installed' } } + 'web' { if ((Have 'php') -and ((Have 'mariadb') -or (Find-MariaDB))) { 'installed' } } + 'rust' { if ((Have 'rustup') -or (Test-Path (Join-Path $script:UserHome '.cargo\bin\rustup.exe'))) { 'installed' } } + } +} + +$script:MenuNote = { + param($c) + switch ($c) { + 'nvim' { 'about 500 MB (Node.js, parsers and LSP servers) plus a C compiler (about 1 GB) if you have none, 5-15 minutes' } + 'web' { 'about 400 MB; MariaDB asks for administrator rights (a Windows prompt)' } + 'rust' { 'about 1 GB (toolchain in ~\.rustup)' } + } +} + +function Usage { Get-Content -LiteralPath $PSCommandPath | Select-Object -Skip 1 -First 7 | ForEach-Object { $_ -replace '^# ?', '' } } + +# --------------------------------------------------------------- helpers ---- +function Font-Present { + foreach ($d in @((Join-Path $env:WINDIR 'Fonts'), (Join-Path $env:LOCALAPPDATA 'Microsoft\Windows\Fonts'))) { + if (Get-ChildItem -LiteralPath $d -Filter 'JetBrainsMono*Nerd*' -ErrorAction SilentlyContinue | Select-Object -First 1) { return $true } + } + return $false +} + +function Find-MariaDB { + $dirs = @(Get-ChildItem -Path (Join-Path $env:ProgramFiles 'MariaDB *') -Directory -ErrorAction SilentlyContinue | Sort-Object Name -Descending) + foreach ($d in $dirs) { $bin = Join-Path $d.FullName 'bin'; if (Test-Path (Join-Path $bin 'mariadb.exe')) { return $bin } } + return $null +} + +function Has-CCompiler { return ((Have 'cl') -or (Have 'gcc') -or (Have 'clang')) } + +# Windows PowerShell 5.1 refuses to run any script (the profile included) until the user allows local scripts. +# PowerShell 7 already allows them. This checks the 5.1 policy and offers the usual fix: RemoteSigned for this user. +function Fix-ExecutionPolicy { + $ps51 = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe' + if (-not (Test-Path $ps51)) { return } + $ErrorActionPreference = 'Continue' + # no double quotes inside arguments for native programs: Windows PowerShell 5.1 passes them on mangled + $lines = @(& $ps51 -NoProfile -NonInteractive -Command 'Get-ExecutionPolicy -List | ForEach-Object { [string]$_.Scope + ''='' + [string]$_.ExecutionPolicy }') + $pol = @{} + foreach ($l in $lines) { $kv = ([string]$l).Split('='); if ($kv.Count -eq 2) { $pol[$kv[0].Trim()] = $kv[1].Trim() } } + foreach ($gpo in @('MachinePolicy', 'UserPolicy')) { + if ($pol[$gpo] -and $pol[$gpo] -ne 'Undefined') { Warn "script policy is set by your organisation ($gpo = $($pol[$gpo])); the profile only loads if it allows local scripts."; return } + } + $eff = 'Restricted' + if ($pol['CurrentUser'] -and $pol['CurrentUser'] -ne 'Undefined') { $eff = $pol['CurrentUser'] } + elseif ($pol['LocalMachine'] -and $pol['LocalMachine'] -ne 'Undefined') { $eff = $pol['LocalMachine'] } + if (@('RemoteSigned', 'Unrestricted', 'Bypass') -contains $eff) { Ok "PowerShell may run local scripts ($eff)"; return } + Info "Windows PowerShell's script policy is ${eff}: it would refuse to load the profile." + if ($script:DryRun) { Info '[dry-run] would offer: Set-ExecutionPolicy RemoteSigned -Scope CurrentUser'; return } + if (Confirm 'Allow local scripts for your user (Set-ExecutionPolicy RemoteSigned -Scope CurrentUser)?' 'y') { + & $ps51 -NoProfile -NonInteractive -Command 'Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force' | Out-Host + Ok 'local scripts allowed for your user (downloaded scripts still need a signature)' + } else { + Warn 'left as it is: Windows PowerShell 5.1 will not load the profile (PowerShell 7 will).' + } +} + +# Windows Terminal keeps settings.json in one of these, depending on how it was installed +function Find-WtSettings { + $cands = @( + (Join-Path $script:LocalAppData 'Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json'), + (Join-Path $script:LocalAppData 'Packages\Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe\LocalState\settings.json'), + (Join-Path $script:LocalAppData 'Microsoft\Windows Terminal\settings.json') + ) + return @($cands | Where-Object { Test-Path -LiteralPath $_ }) +} + +function Has-WindowsTerminal { + if (Have 'wt') { return $true } + try { return [bool](Get-AppxPackage -Name 'Microsoft.WindowsTerminal*' -ErrorAction Stop) } catch { return $false } +} + +function Write-Utf8([string]$path, [string]$text) { + [IO.File]::WriteAllText($path, $text, (New-Object Text.UTF8Encoding $false)) +} + +# Set-WtDefault SETTINGS -> point "defaultProfile" at our profile. A text edit, so comments and layout stay as they are. +function Set-WtDefault([string]$settings) { + $text = [IO.File]::ReadAllText($settings) + $re = '("defaultProfile"\s*:\s*")([^"]*)(")' + $m = [regex]::Match($text, $re) + if (-not $m.Success) { Warn "no defaultProfile in $(Short $settings); pick 'dotfiles (PowerShell)' in Settings > Startup."; return } + $old = $m.Groups[2].Value + if ($old -eq $WtProfileGuid) { Ok 'already the default Windows Terminal profile'; return } + if ($script:DryRun) { Info "[dry-run] would make 'dotfiles (PowerShell)' the default profile in $(Short $settings)"; return } + $backup = Join-Path (Join-Path $script:BackupRoot $script:Stamp) 'windows-terminal-settings.json' + New-Item -ItemType Directory -Force -Path (Split-Path -Parent $backup) | Out-Null + Copy-Item -LiteralPath $settings -Destination $backup -Force + $new = $text.Substring(0, $m.Groups[2].Index) + $WtProfileGuid + $text.Substring($m.Groups[2].Index + $m.Groups[2].Length) + Write-Utf8 $settings $new + Add-ManifestRow $settings $WtProfileGuid $backup 'wt-default' $old + Ok "default Windows Terminal profile: dotfiles (PowerShell) (it was $old; a copy of settings.json is in $(Short $backup))" +} + +# ------------------------------------------------------------ preflight ---- +function Preflight { + if ($env:OS -ne 'Windows_NT') { Die 'This installer is for Windows (use install.sh on Linux and macOS).' } + $build = [Environment]::OSVersion.Version.Build + if ($build -lt 17763) { Die "Windows 10 version 1809 or newer is needed for winget (this is build $build)." } + if (@('AMD64', 'ARM64') -notcontains $Arch) { Die "unsupported CPU: $Arch (64-bit Windows is needed)" } + $admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) + if ($admin) { Warn 'running as administrator: that works, but a normal window is better (Windows asks for permission when a step needs it).' } + if ($script:DryRun) { Info 'DRY RUN: nothing will be changed.' } + Refresh-Path +} + +# ----------------------------------------------------------- components ---- +function Comp-base { + Step 'Base: command-line tools, PowerShell 7, Nerd Font' + Need-Packages @('Git.Git', 'BurntSushi.ripgrep.MSVC', 'junegunn.fzf', 'jqlang.jq', 'Microsoft.PowerShell') + Optional-Packages @('eza-community.eza', 'ajeetdsouza.zoxide', 'Fastfetch-cli.Fastfetch', 'aristocratos.btop4win') + if (Font-Present) { Ok 'font already present: JetBrainsMono Nerd Font' } + elseif (-not (Winget-Install 'DEVCOM.JetBrainsMonoNerdFont')) { throw 'could not install the JetBrainsMono Nerd Font' } +} + +function Comp-shell { + Step 'Shell: PowerShell profile + starship' + Need-Packages @('Starship.Starship') + Fix-ExecutionPolicy + foreach ($t in $ProfileTargets) { Backup-And-Link (Join-Path $script:ConfigDir 'powershell\profile.ps1') $t } + Backup-And-Link (Join-Path $script:ConfigDir 'starship\starship.toml') (Join-Path $script:UserHome '.config\starship.toml') + Info 'zsh and Oh My Zsh are not native on Windows; for the full Linux shell, install WSL and run the Linux installer inside it.' +} + +function Comp-nvim { + Step 'Neovim (NvChad)' + Need-Packages @('Neovim.Neovim', 'OpenJS.NodeJS.LTS', 'Git.Git', 'BurntSushi.ripgrep.MSVC', 'tree-sitter.tree-sitter-cli') + # nvim-treesitter builds each parser with a C compiler. Without Visual Studio, WinLibs (GCC) is the light option. + if (Has-CCompiler) { Ok 'C compiler found' } + else { + Info 'no C compiler found: installing WinLibs (GCC, MinGW-w64) for the tree-sitter parsers' + Need-Packages @('BrechtSanders.WinLibs.POSIX.UCRT') + } + # tree-sitter asks for cl.exe (Visual Studio) unless CC says otherwise; config/nvim/dotfiles.lua does the same inside nvim + if (-not (Have 'cl') -and -not $env:CC -and (Have 'gcc')) { $env:CC = 'gcc' } + + $marker = Join-Path $NvimDir '.rhmatzeka-dotfiles' + if ((Test-Path -LiteralPath $NvimDir) -and -not (Test-Path -LiteralPath $marker)) { + Warn "an nvim config already exists at $(Short $NvimDir): leaving it untouched." + Warn "Add $script:ConfigDir\nvim\dotfiles.lua to its lua\plugins\ if you want the extra parsers/LSP." + return + } + if (-not (Test-Path -LiteralPath $NvimDir)) { + Info 'cloning the NvChad starter' + if ($script:DryRun) { Info '[dry-run] would clone NvChad/starter' } + else { + Git-Clone 'https://github.com/NvChad/starter' $NvimDir + Remove-Item -Recurse -Force -LiteralPath (Join-Path $NvimDir '.git') + New-Item -ItemType File -Path $marker | Out-Null + } + } + Backup-And-Link (Join-Path $script:ConfigDir 'nvim\dotfiles.lua') (Join-Path $NvimDir 'lua\plugins\dotfiles.lua') + + if ($script:DryRun) { Info '[dry-run] would sync plugins, build tree-sitter parsers and install LSP servers'; return } + $nvim = (Get-Command nvim).Source + Info 'syncing plugins (first run, a minute or two)' + if (-not (Invoke-Timeout 600 $nvim @('--headless', '+Lazy! sync', '+qa'))) { Warn 'plugin sync reported a problem; it will retry when you open nvim' } + Info 'building tree-sitter parsers' + $lua = "+lua local ok,e=pcall(function() require('nvim-treesitter').install(dofile(vim.fn.stdpath('config')..'/lua/plugins/dotfiles.lua')[1].opts.ensure_installed):wait(540000) end) if not ok then print(e) end" + if (-not (Invoke-Timeout 600 $nvim @('--headless', '+Lazy load nvim-treesitter', $lua, '+qa'))) { Warn 'parser build reported a problem; check :checkhealth nvim-treesitter' } + Info 'installing LSP servers and formatters (Mason)' + $mason = (Get-Content -LiteralPath (Join-Path $script:ConfigDir 'nvim\mason-packages') | Where-Object { $_ }) -join ' ' + if (-not (Invoke-Timeout 900 $nvim @('--headless', '+Lazy load mason.nvim', "+MasonInstall $mason", '+qall'))) { + # downloads time out now and then (seen in CI: schema downloads): try the missing packages once more + $pkgDir = Join-Path $env:LOCALAPPDATA 'nvim-data\mason\packages' + $missing = @($mason -split ' ' | Where-Object { -not (Test-Path -LiteralPath (Join-Path $pkgDir $_)) }) + if ($missing.Count -gt 0) { + Info "trying again: $($missing -join ' ')" + if (-not (Invoke-Timeout 900 $nvim @('--headless', '+Lazy load mason.nvim', "+MasonInstall $($missing -join ' ')", '+qall'))) { Warn 'Mason reported a problem; run :Mason inside nvim to see which package failed' } + } + } + Ok 'Neovim is ready (config in %LOCALAPPDATA%\nvim)' +} + +function Comp-terminal { + Step 'Terminal: Windows Terminal profile and colours' + # the profile starts PowerShell 7 (pwsh.exe) + Need-Packages @('Microsoft.PowerShell') + if (Has-WindowsTerminal) { Ok 'Windows Terminal already installed' } + elseif (-not (Winget-Install 'Microsoft.WindowsTerminal')) { throw 'could not install Windows Terminal' } + if (-not (Font-Present)) { Warn 'the JetBrainsMono Nerd Font is missing (the base component installs it); icons show as boxes until then.' } + Backup-And-Link (Join-Path $script:ConfigDir 'windows-terminal\dotfiles.json') $FragmentDst + $settings = @(Find-WtSettings) + if ($settings.Count -eq 0) { + Info "Windows Terminal has no settings yet: open it once, then choose 'dotfiles (PowerShell)' in Settings > Startup > Default profile (or run this again)." + } elseif (Confirm "Make 'dotfiles (PowerShell)' the default Windows Terminal profile?" 'y') { + foreach ($s in $settings) { Set-WtDefault $s } + } else { + Info "Open it from the tab menu (the arrow next to +): dotfiles (PowerShell)." + } + Info 'Ghostty has no Windows version; the profile uses the same colours, font, padding and cursor.' +} + +function Comp-web { + Step 'Web development: PHP, Composer, MariaDB, phpMyAdmin' + Need-Packages @('PHP.PHP.8.5') + # A silent MariaDB MSI creates no Windows service unless SERVICENAME is given (MariaDB's MSI documentation) + if (-not (Find-MariaDB) -and -not (Winget-Has 'MariaDB.Server')) { + if (-not (Winget-Install 'MariaDB.Server' @('--custom', 'SERVICENAME=MariaDB'))) { throw 'could not install MariaDB' } + } else { Ok 'already installed: MariaDB.Server' } + + # php.ini: the zip from php.net has none. Start from php.ini-development and turn on what Composer and MariaDB need. + if ($script:DryRun) { Info '[dry-run] would write php.ini (openssl, curl, mbstring, mysqli, pdo_mysql, zip, fileinfo)' } + else { + # winget's own PHP, not whatever php.exe comes first on PATH (XAMPP, Chocolatey...) + $phpDir = $null + $pkg = Get-ChildItem -Path (Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Packages') -Directory -Filter 'PHP.PHP.8.5_*' -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($pkg -and (Test-Path (Join-Path $pkg.FullName 'php.exe'))) { $phpDir = $pkg.FullName } + $php = Get-Command php -ErrorAction SilentlyContinue + if (-not $phpDir) { + if (-not $php) { throw 'php is not on PATH after installing it; open a new terminal and run this again' } + $phpDir = Split-Path -Parent $php.Source + $t = Get-LinkTarget $php.Source; if ($t) { $phpDir = Split-Path -Parent $t } + } elseif ($php -and -not $php.Source.StartsWith($phpDir, [StringComparison]::OrdinalIgnoreCase)) { + Warn "another PHP comes first on your PATH: $($php.Source). The one set up here is $phpDir\php.exe" + } + $ini = Join-Path $phpDir 'php.ini' + if (Test-Path -LiteralPath $ini) { Ok "php.ini already exists: $ini (left as it is)" } + elseif (Test-Path -LiteralPath (Join-Path $phpDir 'php.ini-development')) { + $text = [IO.File]::ReadAllText((Join-Path $phpDir 'php.ini-development')) + $ext = (Join-Path $phpDir 'ext') -replace '\\', '/' + $text = [regex]::Replace($text, '(?m)^;\s*extension_dir\s*=\s*"ext"', "extension_dir = `"$ext`"") + foreach ($e in @('curl', 'fileinfo', 'mbstring', 'mysqli', 'openssl', 'pdo_mysql', 'zip')) { + $text = [regex]::Replace($text, "(?m)^;extension=$e\s*$", "extension=$e") + } + Write-Utf8 $ini $text + Ok "wrote $ini (openssl, curl, mbstring, mysqli, pdo_mysql, zip, fileinfo)" + } else { Warn "php.ini-development not found next to php.exe ($phpDir); write php.ini by hand" } + } + + # Composer: the official composer.phar, checked against its published SHA-256, plus a composer.cmd shim + $phar = Join-Path $script:LocalBin 'composer.phar' + if (Test-Path -LiteralPath $phar) { Ok 'Composer already installed' } + elseif ($script:DryRun) { Info '[dry-run] would download composer.phar (checked against its SHA-256) into ~\.local\bin' } + else { + $tmp = [IO.Path]::GetTempFileName() + Fetch 'https://getcomposer.org/download/latest-stable/composer.phar' $tmp + $sum = (Invoke-WebRequest -Uri 'https://getcomposer.org/download/latest-stable/composer.phar.sha256' -UseBasicParsing).Content + if ($sum -is [byte[]]) { $sum = [Text.Encoding]::ASCII.GetString($sum) } + $want = ($sum.Trim() -split '\s+')[0] + $got = (Get-FileHash -LiteralPath $tmp -Algorithm SHA256).Hash + if ($got -ne $want.ToUpper()) { Remove-Item $tmp; throw "composer.phar checksum mismatch (got $got)" } + New-Item -ItemType Directory -Force -Path $script:LocalBin | Out-Null + Move-Item -LiteralPath $tmp -Destination $phar -Force + Set-Content -LiteralPath (Join-Path $script:LocalBin 'composer.cmd') -Value '@php "%~dp0composer.phar" %*' -Encoding Ascii + Ok 'Composer installed in ~\.local\bin' + } + Add-UserPath $script:LocalBin + + # MariaDB: the MSI installs a Windows service that starts with Windows. Ask, like brew services / systemctl elsewhere. + $bin = Find-MariaDB + if ($bin) { Add-UserPath $bin } + if ($script:DryRun) { Info '[dry-run] would ask whether MariaDB should start with Windows' } + elseif (-not (Get-Service -Name 'MariaDB' -ErrorAction SilentlyContinue)) { + if ($bin) { Info "MariaDB has no Windows service here (installed earlier without one); start it by hand with: mariadbd --console" } + } else { + if (Confirm 'Keep MariaDB starting with Windows?' 'n') { Ok 'MariaDB starts with Windows (service "MariaDB")' } + else { + Info 'setting the MariaDB service to start by hand (Windows asks for permission)' + try { + Start-Process -FilePath 'powershell.exe' -Verb RunAs -Wait -ArgumentList '-NoProfile -Command "Stop-Service MariaDB; Set-Service MariaDB -StartupType Manual"' + Ok 'MariaDB is stopped and starts only when you run: net start MariaDB (as administrator)' + } catch { Warn 'not changed (permission refused); turn it off in services.msc if you want' } + } + } + Info 'Log in with: mariadb -u root (root has no password and is only reachable from this PC; no password was set anywhere)' + + # phpMyAdmin: the official zip, served with PHP's own web server when you want it + $pma = Join-Path $ToolsDir 'phpmyadmin' + if (Test-Path -LiteralPath (Join-Path $pma 'index.php')) { Ok 'phpMyAdmin already there' } + elseif ($script:DryRun) { Info "[dry-run] would download phpMyAdmin into $(Short $pma)" } + else { + try { + $zip = Join-Path $env:TEMP 'phpmyadmin.zip' + Fetch 'https://www.phpmyadmin.net/downloads/phpMyAdmin-latest-all-languages.zip' $zip + $tmpDir = Join-Path $env:TEMP 'phpmyadmin-unzip' + if (Test-Path $tmpDir) { Remove-Item -Recurse -Force $tmpDir } + Expand-Archive -LiteralPath $zip -DestinationPath $tmpDir -Force + $inner = Get-ChildItem -LiteralPath $tmpDir -Directory | Select-Object -First 1 + New-Item -ItemType Directory -Force -Path $ToolsDir | Out-Null + Move-Item -LiteralPath $inner.FullName -Destination $pma + Remove-Item -Recurse -Force $tmpDir, $zip -ErrorAction SilentlyContinue + Ok "phpMyAdmin in $(Short $pma)" + } catch { Warn "phpMyAdmin skipped: $($_.Exception.Message)" } + } + Info "phpMyAdmin: php -S localhost:8080 -t `"$pma`" then open http://localhost:8080" +} + +function Comp-rust { + Step 'Rust (rustup)' + if ((Have 'rustup') -or (Test-Path (Join-Path $script:UserHome '.cargo\bin\rustup.exe'))) { Ok 'rustup already installed' } + else { + # The default (MSVC) toolchain links with Visual Studio's linker. Without Visual Studio, the GNU toolchain brings + # its own, so nothing else is needed; switch later with: rustup default stable-msvc + $vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe' + $hasMsvc = $false + if (Test-Path $vswhere) { $hasMsvc = [bool](& $vswhere -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath) } + $hostTriple = '' + if (-not $hasMsvc) { + if (Confirm 'No Visual Studio C++ tools found. Install Visual Studio Build Tools for the MSVC toolchain (about 5 GB)?' 'n') { + if (-not (Winget-Install 'Microsoft.VisualStudio.2022.BuildTools' @('--override', '--wait --passive --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended'))) { throw 'could not install the Visual Studio Build Tools' } + } elseif ($Arch -eq 'AMD64') { + $hostTriple = 'x86_64-pc-windows-gnu' + Info 'using the GNU toolchain (no Visual Studio needed)' + } else { Warn 'ARM64 has no GNU toolchain: Rust installs, but linking needs the Visual Studio Build Tools.' } + } + $triple = 'x86_64-pc-windows-msvc'; if ($Arch -eq 'ARM64') { $triple = 'aarch64-pc-windows-msvc' } + if ($script:DryRun) { Info "[dry-run] would run the official rustup-init.exe ($triple)$(if ($hostTriple) { " with --default-host $hostTriple" })" } + else { + $init = Join-Path $env:TEMP 'rustup-init.exe' + Fetch "https://static.rust-lang.org/rustup/dist/$triple/rustup-init.exe" $init + $a = @('-y', '--profile', 'default'); if ($hostTriple) { $a += @('--default-host', $hostTriple) } + $ErrorActionPreference = 'Continue' + & $init @a | Out-Host + if ($LASTEXITCODE -ne 0) { throw "rustup-init failed (exit $LASTEXITCODE)" } + Remove-Item $init -ErrorAction SilentlyContinue + $ErrorActionPreference = 'Stop' + } + } + if (-not $script:DryRun) { + Refresh-Path + $ErrorActionPreference = 'Continue' + & rustup component add rust-analyzer clippy rustfmt 2>&1 | Out-Null + if ($LASTEXITCODE -ne 0) { Warn 'could not add rust-analyzer/clippy/rustfmt' } + Ok "$(& rustc --version 2>$null)" + } + Info 'rustup put ~\.cargo\bin on your PATH; open a new terminal to use cargo.' +} + +# ----------------------------------------------------------------- main ---- +if ($Help) { Usage; exit 0 } +if ($List) { Menu-List; exit 0 } +Preflight +if ($All) { $selected = @($script:MenuItems) } +elseif ($Only) { $selected = Menu-FromList $Only } +else { $selected = Menu-Choose } +if (-not (Menu-Confirm $selected)) { Info 'Cancelled.'; exit 0 } + +Run-Selected $selected +if (-not $script:DryRun -and $script:OkList.Count -gt 0) { + if ($script:OkList -contains 'shell' -or $script:OkList -contains 'terminal') { Info "Open a new Windows Terminal tab ('dotfiles (PowerShell)') to load the new shell." } + $bk = Join-Path $script:BackupRoot $script:Stamp + if (Test-Path -LiteralPath $bk) { Info "Files that were replaced are in $(Short $bk)" } +} +if ($script:FailedList.Count -gt 0) { exit 1 } +exit 0 diff --git a/windows/lib.ps1 b/windows/lib.ps1 new file mode 100644 index 0000000..dd1bf30 --- /dev/null +++ b/windows/lib.ps1 @@ -0,0 +1,386 @@ +# Shared helpers for the Windows installer and uninstaller. Dot-source this file; do not run it. +# +# Written for Windows PowerShell 5.1 (what every Windows 10/11 has) and PowerShell 7. Keep this file ASCII only: +# PowerShell 5.1 reads a script without a BOM as ANSI, so a stray non-ASCII character breaks it. +# +# Conventions, the same as lib/common.sh on Linux and macOS: +# $script:DryRun print what would happen, change nothing +# $script:AssumeYes answer every question with its default (never turns a "no" default into a "yes") +# Every file we put in place is recorded in a manifest so uninstall can undo exactly that, and any file we would +# replace is moved to ~\.dotfiles-backup\\ first. +# +# Test hooks (environment variables): DOTFILES_HOME, DOTFILES_DOCUMENTS and DOTFILES_LOCALAPPDATA point the installer +# at a throw-away folder; DOTFILES_ANSWERS is a file whose lines are read as the answers to the menu and questions. + +if (-not $script:DryRun) { $script:DryRun = $false } +if (-not $script:AssumeYes) { $script:AssumeYes = $false } + +function Get-EnvOr([string]$name, [string]$fallback) { + $v = [Environment]::GetEnvironmentVariable($name) + if ($v) { return $v } else { return $fallback } +} + +$script:UserHome = Get-EnvOr 'DOTFILES_HOME' $env:USERPROFILE +$script:Documents = Get-EnvOr 'DOTFILES_DOCUMENTS' ([Environment]::GetFolderPath('MyDocuments')) +$script:LocalAppData = Get-EnvOr 'DOTFILES_LOCALAPPDATA' $env:LOCALAPPDATA +$script:StateDir = Join-Path $script:UserHome '.local\state\rhmatzeka-dotfiles' +$script:Manifest = Join-Path $script:StateDir 'links-windows.tsv' +$script:BackupRoot = Get-EnvOr 'DOTFILES_BACKUP_DIR' (Join-Path $script:UserHome '.dotfiles-backup') +$script:Stamp = Get-EnvOr 'DOTFILES_STAMP' (Get-Date -Format 'yyyyMMdd-HHmmss') +$script:LocalBin = Join-Path $script:UserHome '.local\bin' + +# ---------------------------------------------------------------- output ---- +$script:Tick = [string][char]0x2714 +$script:Arrow = [string][char]0x25B8 +$script:Cross = [string][char]0x2716 + +function Step([string]$m) { Write-Host ''; Write-Host " == $m" -ForegroundColor Cyan } +function Ok([string]$m) { Write-Host " $script:Tick " -ForegroundColor Green -NoNewline; Write-Host $m } +function Info([string]$m) { Write-Host " $script:Arrow " -ForegroundColor Cyan -NoNewline; Write-Host $m } +function Warn([string]$m) { Write-Host ' ! ' -ForegroundColor Yellow -NoNewline; Write-Host $m } +function Fail([string]$m) { Write-Host " $script:Cross " -ForegroundColor Red -NoNewline; Write-Host $m } +function Die([string]$m) { Fail $m; exit 1 } + +function Have([string]$cmd) { [bool](Get-Command $cmd -ErrorAction SilentlyContinue) } + +function Short([string]$p) { + if ($p -and $p.StartsWith($script:UserHome, [StringComparison]::OrdinalIgnoreCase)) { return '~' + $p.Substring($script:UserHome.Length) } + return $p +} + +# ----------------------------------------------------------------- input ---- +$script:Answers = $null +$script:AnswerIndex = 0 +$answersFile = [Environment]::GetEnvironmentVariable('DOTFILES_ANSWERS') +if ($answersFile -and (Test-Path -LiteralPath $answersFile)) { $script:Answers = @(Get-Content -LiteralPath $answersFile) } + +# Interactive -> $true when a person can answer (or a test feeds the answers) +function Interactive { + if ($null -ne $script:Answers) { return $true } + try { return ([Environment]::UserInteractive -and -not [Console]::IsInputRedirected) } catch { return $false } +} + +# Read-Answer PROMPT -> one line, from the answers file in tests, from the keyboard otherwise ($null when out of input) +function Read-Answer([string]$prompt) { + if ($null -ne $script:Answers) { + Write-Host $prompt -NoNewline + if ($script:AnswerIndex -ge $script:Answers.Count) { Write-Host ''; return $null } + $a = $script:Answers[$script:AnswerIndex]; $script:AnswerIndex++ + Write-Host $a + return $a + } + Write-Host $prompt -NoNewline + return [Console]::ReadLine() +} + +# Confirm "question" [y|n] -> $true for yes. Without a person, or with -Yes, the default answer is used. +function Confirm([string]$q, [string]$def = 'n') { + $hint = '[y/N]'; if ($def -eq 'y') { $hint = '[Y/n]' } + if ($script:AssumeYes -or -not (Interactive)) { return ($def -eq 'y') } + $ans = Read-Answer " ? $q $hint " + if ([string]::IsNullOrEmpty($ans)) { $ans = $def } + return ($ans -match '^(y|yes)$') +} + +# ----------------------------------------------------------------- paths ---- +# Refresh-Path -> pick up what an installer just added to PATH (winget, rustup, MSIs write it to the registry) +function Refresh-Path { + $machine = [Environment]::GetEnvironmentVariable('Path', 'Machine') + $user = [Environment]::GetEnvironmentVariable('Path', 'User') + $extra = @($script:LocalBin, (Join-Path $script:UserHome '.cargo\bin'), (Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Links')) + $parts = New-Object System.Collections.Generic.List[string] + foreach ($p in (@($extra) + ($machine -split ';') + ($user -split ';') + ($env:Path -split ';'))) { + if ($p -and -not $parts.Contains($p)) { $parts.Add($p) } + } + $env:Path = $parts -join ';' +} + +# Add-UserPath DIR -> put DIR on the user's PATH for good (registry), and on this process's PATH now +function Add-UserPath([string]$dir) { + $user = [Environment]::GetEnvironmentVariable('Path', 'User') + $list = @(); if ($user) { $list = $user -split ';' | Where-Object { $_ } } + if ($list -contains $dir) { return } + if ($script:DryRun) { Info "[dry-run] would add $(Short $dir) to your PATH"; return } + [Environment]::SetEnvironmentVariable('Path', (($list + $dir) -join ';'), 'User') + $env:Path = "$dir;$env:Path" + Info "added $(Short $dir) to your PATH (new terminals pick it up)" +} + +# ---------------------------------------------------------------- winget ---- +function Ensure-Winget { + if (Have 'winget') { return $true } + if ($script:DryRun) { Info '[dry-run] winget is missing: it would be needed (App Installer from the Microsoft Store)'; return $true } + Fail 'winget is missing. Install "App Installer" from the Microsoft Store (https://aka.ms/getwinget), then run this again.' + return $false +} + +function Winget-Has([string]$id) { + $ErrorActionPreference = 'Continue' # under Stop, PowerShell 5.1 turns a native program's stderr into an error + if (-not (Have 'winget')) { return $false } + $null = & winget list --id $id --exact --accept-source-agreements --disable-interactivity 2>$null + return ($LASTEXITCODE -eq 0) +} + +# Winget-Install ID [extra winget args...] -> $true when it is installed afterwards +function Winget-Install([string]$id, [string[]]$extra = @()) { + if ($script:DryRun) { Write-Host " [dry-run] winget install --id $id $($extra -join ' ')" -ForegroundColor DarkGray; return $true } + $ErrorActionPreference = 'Continue' + Info "winget install $id" + # Out-Host: winget's output must not become this function's return value + & winget install --id $id --exact --source winget --accept-package-agreements --accept-source-agreements --disable-interactivity @extra | Out-Host + $rc = $LASTEXITCODE + Refresh-Path + # -1978335189 = 0x8A15002B "no newer version", -1978335135 = 0x8A150061 "already installed": both mean it is there + if ($rc -eq 0 -or $rc -eq -1978335189 -or $rc -eq -1978335135) { return $true } + Fail "winget could not install $id (exit $rc)" + return $false +} + +# Need-Packages ID... -> install what is missing; throws when one of them cannot be installed (the component fails) +function Need-Packages([string[]]$ids) { + if (-not (Ensure-Winget)) { throw 'winget missing' } + $missing = @($ids | Where-Object { -not (Winget-Has $_) }) + if ($missing.Count -eq 0) { Ok "already installed: $($ids -join ', ')"; return } + foreach ($id in $missing) { if (-not (Winget-Install $id)) { throw "could not install $id" } } +} + +# Optional-Packages ID... -> try each one; warn instead of failing +function Optional-Packages([string[]]$ids) { + if (-not (Ensure-Winget)) { return } + foreach ($id in $ids) { + if (Winget-Has $id) { continue } + if (-not (Winget-Install $id)) { Warn "optional, skipped: $id" } + } +} + +# ----------------------------------------------------------------- files ---- +function Get-LinkTarget([string]$p) { + $item = Get-Item -LiteralPath $p -Force -ErrorAction SilentlyContinue + if ($item -and $item.LinkType -eq 'SymbolicLink') { return @($item.Target)[0] } + return $null +} + +function Read-Manifest { + if (-not (Test-Path -LiteralPath $script:Manifest)) { return @() } + $rows = @() + foreach ($line in (Get-Content -LiteralPath $script:Manifest)) { + if (-not $line) { continue } + $f = $line -split "`t" + while ($f.Count -lt 5) { $f += '' } + $rows += [pscustomobject]@{ Dst = $f[0]; Src = $f[1]; Backup = $f[2]; Kind = $f[3]; Extra = $f[4] } + } + return $rows +} + +function Add-ManifestRow([string]$dst, [string]$src, [string]$backup, [string]$kind, [string]$extra) { + New-Item -ItemType Directory -Force -Path $script:StateDir | Out-Null + Add-Content -LiteralPath $script:Manifest -Value (($dst, $src, $backup, $kind, $extra) -join "`t") -Encoding UTF8 +} + +# Installed-Here DST -> $true when DST is a file this installer put there (a link into the repo, or a recorded copy) +function Installed-Here([string]$dst) { + $t = Get-LinkTarget $dst + if ($t -and $t.StartsWith($script:DotfilesDir, [StringComparison]::OrdinalIgnoreCase)) { return $true } + if (-not (Test-Path -LiteralPath $dst)) { return $false } + foreach ($r in (Read-Manifest)) { if ($r.Dst -eq $dst -and $r.Kind -eq 'copy') { return $true } } + return $false +} + +# Backup-And-Link SRC DST -> a symbolic link to the repo file when Windows allows it (Developer Mode, or an admin +# shell), otherwise a copy (re-run the installer after `git pull` to refresh copies). The old file is backed up first. +function Backup-And-Link([string]$src, [string]$dst) { + if (-not (Test-Path -LiteralPath $src)) { Warn "missing in repo, skipped: $src"; return } + if ((Get-LinkTarget $dst) -eq $src) { Ok "already linked: $(Short $dst)"; return } + if ($script:DryRun) { + if (Test-Path -LiteralPath $dst) { Info "[dry-run] would back up $(Short $dst) and link it to the repo" } + else { Info "[dry-run] would link $(Short $dst)" } + return + } + $backup = '' + New-Item -ItemType Directory -Force -Path (Split-Path -Parent $dst) | Out-Null + if ((Test-Path -LiteralPath $dst) -or (Get-LinkTarget $dst)) { + $rel = $dst + if ($dst.StartsWith($script:UserHome, [StringComparison]::OrdinalIgnoreCase)) { $rel = $dst.Substring($script:UserHome.Length).TrimStart('\') } + else { $rel = $dst -replace ':', '' } + $backup = Join-Path (Join-Path $script:BackupRoot $script:Stamp) $rel + New-Item -ItemType Directory -Force -Path (Split-Path -Parent $backup) | Out-Null + Move-Item -LiteralPath $dst -Destination $backup -Force + Info "backed up $(Short $dst) -> $(Short $backup)" + } + $kind = 'link'; $extra = '' + try { New-Item -ItemType SymbolicLink -Path $dst -Target $src -ErrorAction Stop | Out-Null } + catch { + Copy-Item -LiteralPath $src -Destination $dst -Force + $kind = 'copy'; $extra = (Get-FileHash -LiteralPath $dst -Algorithm SHA256).Hash + } + Add-ManifestRow $dst $src $backup $kind $extra + if ($kind -eq 'link') { Ok "linked $(Short $dst)" } + else { Ok "copied $(Short $dst) (Windows did not allow a link: turn on Developer Mode to get links that follow git pull)" } +} + +# Fetch URL DEST -> download with a few retries +function Fetch([string]$url, [string]$dest) { + if ($script:DryRun) { Info "[dry-run] would download $url"; return } + New-Item -ItemType Directory -Force -Path (Split-Path -Parent $dest) | Out-Null + [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 + $old = $ProgressPreference; $ProgressPreference = 'SilentlyContinue' # the progress bar makes 5.1 downloads crawl + try { + for ($i = 1; $i -le 3; $i++) { + try { Invoke-WebRequest -Uri $url -OutFile $dest -UseBasicParsing -TimeoutSec 600; return } + catch { if ($i -eq 3) { throw "download failed: $url ($($_.Exception.Message))" }; Start-Sleep -Seconds 2 } + } + } finally { $ProgressPreference = $old } +} + +# Git-Clone URL DEST -> clone once; if it exists, leave it alone +function Git-Clone([string]$url, [string]$dest) { + if (Test-Path -LiteralPath (Join-Path $dest '.git')) { Ok "already cloned: $(Short $dest)"; return } + if ($script:DryRun) { Info "[dry-run] would clone $url"; return } + New-Item -ItemType Directory -Force -Path (Split-Path -Parent $dest) | Out-Null + $ErrorActionPreference = 'Continue' + & git clone -q --depth 1 $url $dest 2>&1 | Out-Host + if ($LASTEXITCODE -ne 0) { throw "git clone failed: $url" } +} + +# Invoke-Timeout SECONDS EXE ARG... -> run EXE with a time limit, output hidden; $true when it exits 0 in time. +# On failure the last lines of its output are shown. Arguments must not contain double quotes (they are joined into one +# command line). +function Invoke-Timeout([int]$seconds, [string]$exe, [string[]]$arguments) { + $ErrorActionPreference = 'Continue' + $line = ($arguments | ForEach-Object { if ($_ -match '\s') { '"' + $_ + '"' } else { $_ } }) -join ' ' + $log = [IO.Path]::GetTempFileName() + $p = Start-Process -FilePath $exe -ArgumentList $line -NoNewWindow -PassThru -RedirectStandardOutput $log -RedirectStandardError "$log.err" + $null = $p.Handle # without touching Handle now, .NET reports no ExitCode once the process is gone + $done = $p.WaitForExit($seconds * 1000) + if (-not $done) { try { $p.Kill() } catch { } } + else { $p.WaitForExit() } + $okay = $done -and ($p.ExitCode -eq 0) + if (-not $okay) { + $why = 'timed out'; if ($done) { $why = "exit $($p.ExitCode)" } + Warn "$(Split-Path -Leaf $exe) $why; its last output:" + Get-Content -LiteralPath $log, "$log.err" -ErrorAction SilentlyContinue | Where-Object { $_.Trim() } | Select-Object -Last 15 | ForEach-Object { Write-Host " $_" -ForegroundColor DarkGray } + } + Remove-Item -LiteralPath $log, "$log.err" -ErrorAction SilentlyContinue + return $okay +} + +# ------------------------------------------------------------------ menu ---- +# Same checklist as lib/menu.sh. The installer sets $MenuItems, $MenuDefaults, $MenuOff (hashtable name -> reason, +# kept in order with $MenuOffOrder) and defines the scriptblocks $MenuDesc, $MenuStatus and $MenuNote. + +function Menu-List { + foreach ($c in $script:MenuItems) { + $mark = ' '; if ($script:MenuDefaults -contains $c) { $mark = '*' } + Write-Host (' {0} {1,-9} {2}' -f $mark, $c, (& $script:MenuDesc $c)) + } + Write-Host ''; Write-Host ' * = checked by default' + if ($script:MenuOffOrder.Count -gt 0) { + Write-Host ''; Write-Host ' Not available on Windows:' + foreach ($c in $script:MenuOffOrder) { Write-Host (' - {0,-9} {1}' -f $c, $script:MenuOff[$c]) } + } +} + +function Menu-FromList([string]$list) { + $sel = @() + foreach ($c in ($list -split '[,\s]+' | Where-Object { $_ })) { + if ($script:MenuOff.ContainsKey($c)) { Die "$c cannot be installed on Windows: $($script:MenuOff[$c])" } + if ($script:MenuItems -notcontains $c) { Die "unknown component: $c (see -List)" } + if ($sel -notcontains $c) { $sel += $c } + } + return ,$sel +} + +function Menu-Draw($on, $status, [string]$msg) { + if (-not [Console]::IsOutputRedirected -and $null -eq $script:Answers) { Clear-Host } + Write-Host '' + Write-Host ' dotfiles installer' -ForegroundColor Cyan -NoNewline; Write-Host " - $script:MenuTitle" -ForegroundColor DarkGray + Write-Host '' + Write-Host ' Choose what to install (type a number to check or uncheck it):' + Write-Host '' + for ($i = 0; $i -lt $script:MenuItems.Count; $i++) { + $c = $script:MenuItems[$i] + if ($on[$i]) { Write-Host (' {0,2}. [x] {1,-9} ' -f ($i + 1), $c) -ForegroundColor Cyan -NoNewline } + else { Write-Host (' {0,2}. [ ] {1,-9} ' -f ($i + 1), $c) -ForegroundColor DarkGray -NoNewline } + Write-Host (& $script:MenuDesc $c) -ForegroundColor DarkGray -NoNewline + if ($status[$i]) { Write-Host " ($($status[$i]))" -ForegroundColor Green } else { Write-Host '' } + } + if ($script:MenuOffOrder.Count -gt 0) { + Write-Host ''; Write-Host ' Not available on Windows (cannot be selected):' + foreach ($c in $script:MenuOffOrder) { Write-Host (' - {0,-9} {1}' -f $c, $script:MenuOff[$c]) -ForegroundColor DarkGray } + } + Write-Host '' + Write-Host ' number check/uncheck | a all | n none | Enter continue | q quit' + if ($msg) { Write-Host ''; Write-Host " ! $msg" -ForegroundColor Yellow } + Write-Host '' +} + +# Menu-Choose -> the selected names. Without a person, or with -Yes, it takes the defaults without asking. +function Menu-Choose { + if ($script:AssumeYes -or -not (Interactive)) { return ,@($script:MenuDefaults) } + $n = $script:MenuItems.Count + $on = New-Object bool[] $n + $status = New-Object string[] $n + for ($i = 0; $i -lt $n; $i++) { + $c = $script:MenuItems[$i] + $status[$i] = [string](& $script:MenuStatus $c) + # already installed: nothing to do, so it starts unchecked (check it again to repair or update it) + $on[$i] = ($script:MenuDefaults -contains $c) -and -not $status[$i] + } + $msg = '' + while ($true) { + Menu-Draw $on $status $msg; $msg = '' + $ans = Read-Answer ' > ' + if ($null -eq $ans) { $ans = 'q' } + $ans = $ans.Trim() + if ($ans -eq '') { break } + if ($ans -eq 'a') { for ($i = 0; $i -lt $n; $i++) { $on[$i] = $true }; continue } + if ($ans -eq 'n') { for ($i = 0; $i -lt $n; $i++) { $on[$i] = $false }; continue } + if ($ans -eq 'q') { Write-Host ''; Info 'Nothing installed.'; exit 0 } + foreach ($tok in ($ans -split '[,\s]+' | Where-Object { $_ })) { + $i = -1 + if ($tok -match '^\d+$') { $k = [int]$tok; if ($k -ge 1 -and $k -le $n) { $i = $k - 1 } } + else { $i = [array]::IndexOf([string[]]$script:MenuItems, $tok) } + if ($i -ge 0) { $on[$i] = -not $on[$i] } + elseif ($script:MenuOff.ContainsKey($tok)) { $msg = "$tok is not available on Windows: $($script:MenuOff[$tok])" } + else { $msg = "not a valid choice: $tok (use the numbers 1-$n)" } + } + } + $sel = @() + for ($i = 0; $i -lt $n; $i++) { if ($on[$i]) { $sel += $script:MenuItems[$i] } } + Write-Host '' + return ,$sel +} + +# Menu-Confirm SELECTED -> $true to go ahead. Lists what will be installed, the heavy parts, and what Windows skips. +function Menu-Confirm($selected) { + if ($selected.Count -eq 0) { Info 'Nothing selected.'; exit 0 } + Write-Host '' + Write-Host " Will install: $($selected -join ' ')" + foreach ($c in $selected) { + if (& $script:MenuStatus $c) { continue } + $note = & $script:MenuNote $c + if ($note) { Write-Host (' ! {0,-9} {1}' -f $c, $note) -ForegroundColor Yellow } + } + if ($script:MenuOffOrder.Count -gt 0) { Write-Host " Not available on Windows, skipped: $($script:MenuOffOrder -join ' ')" -ForegroundColor DarkGray } + Write-Host '' + if ($script:DryRun) { return $true } + return (Confirm 'Continue?' 'y') +} + +# Run-Selected SELECTED -> runs Comp- for each one, in menu order. One failure does not stop the rest. +function Run-Selected($selected) { + $script:OkList = @(); $script:FailedList = @() + foreach ($c in $script:MenuItems) { + if ($selected -notcontains $c) { continue } + try { + & "Comp-$c" + $script:OkList += $c + } catch { + Fail "component failed: $c ($($_.Exception.Message))" + $script:FailedList += $c + } + } + Write-Host '' + if ($script:OkList.Count -gt 0) { Ok "Done: $($script:OkList -join ' ')" } + if ($script:FailedList.Count -gt 0) { Fail "Failed: $($script:FailedList -join ' ') (run again with -Only $($script:FailedList -join ',') after fixing the cause)" } +} diff --git a/windows/uninstall.ps1 b/windows/uninstall.ps1 new file mode 100644 index 0000000..ec56564 --- /dev/null +++ b/windows/uninstall.ps1 @@ -0,0 +1,87 @@ +# Undo what install.ps1 put in place on Windows, and bring back the files it replaced (from ~\.dotfiles-backup). +# +# .\uninstall.ps1 interactive +# .\uninstall.ps1 -DryRun show what would happen +# .\uninstall.ps1 -Yes no questions +# +# It only removes links that still point into this repository and copies that nobody has edited since. winget +# packages, fonts, the NvChad clone and the script policy are left alone; the list at the end says how to remove them. +[CmdletBinding()] +param([switch]$DryRun, [switch]$Yes, [switch]$Help) +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version 2 + +$script:DotfilesDir = $env:DOTFILES_DIR +if (-not $script:DotfilesDir) { $script:DotfilesDir = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path } +$script:DryRun = [bool]$DryRun +$script:AssumeYes = [bool]$Yes +. (Join-Path $script:DotfilesDir 'windows\lib.ps1') + +if ($Help) { Get-Content -LiteralPath $PSCommandPath | Select-Object -Skip 1 -First 4 | ForEach-Object { $_ -replace '^# ?', '' }; exit 0 } + +$rows = @(Read-Manifest) +if ($rows.Count -eq 0) { Info "Nothing to undo: no record of installed files at $(Short $script:Manifest)."; exit 0 } +Step 'Files recorded by the installer' +foreach ($r in $rows) { Write-Host " $(Short $r.Dst)" } +if (-not (Confirm 'Remove them and restore your original files?' 'y')) { Info 'Cancelled.'; exit 0 } + +$removed = 0; $restored = 0; $skipped = 0 +function Restore-Backup($r) { + if ($r.Backup -and (Test-Path -LiteralPath $r.Backup)) { + if ($script:DryRun) { Info "[dry-run] would restore $(Short $r.Dst)" } + else { New-Item -ItemType Directory -Force -Path (Split-Path -Parent $r.Dst) | Out-Null; Move-Item -LiteralPath $r.Backup -Destination $r.Dst -Force } + $script:restored++ + Ok "restored $(Short $r.Dst)" + } else { Ok "removed $(Short $r.Dst)" } +} + +# newest first, so a file replaced twice ends up as it was before the first install +[array]::Reverse($rows) +foreach ($r in $rows) { + switch ($r.Kind) { + 'link' { + if ((Get-LinkTarget $r.Dst) -eq $r.Src) { + if ($script:DryRun) { Info "[dry-run] would remove $(Short $r.Dst)" } else { (Get-Item -LiteralPath $r.Dst -Force).Delete() } + $removed++; Restore-Backup $r + } else { Warn "left alone (changed since install): $(Short $r.Dst)"; $skipped++ } + } + 'copy' { + if ((Test-Path -LiteralPath $r.Dst) -and (Get-FileHash -LiteralPath $r.Dst -Algorithm SHA256).Hash -eq $r.Extra) { + if ($script:DryRun) { Info "[dry-run] would remove $(Short $r.Dst)" } else { Remove-Item -LiteralPath $r.Dst -Force } + $removed++; Restore-Backup $r + } else { Warn "left alone (edited since install): $(Short $r.Dst)"; $skipped++ } + } + 'wt-default' { + # put Windows Terminal's default profile back, unless someone already chose another one + if (-not (Test-Path -LiteralPath $r.Dst)) { $skipped++; continue } + $text = [IO.File]::ReadAllText($r.Dst) + $m = [regex]::Match($text, '("defaultProfile"\s*:\s*")([^"]*)(")') + if ($m.Success -and $m.Groups[2].Value -eq $r.Src) { + if ($script:DryRun) { Info '[dry-run] would set the default Windows Terminal profile back' } + else { + $new = $text.Substring(0, $m.Groups[2].Index) + $r.Extra + $text.Substring($m.Groups[2].Index + $m.Groups[2].Length) + [IO.File]::WriteAllText($r.Dst, $new, (New-Object Text.UTF8Encoding $false)) + } + $restored++; Ok 'default Windows Terminal profile set back' + } else { Warn 'default Windows Terminal profile was changed since install: left alone'; $skipped++ } + } + } +} + +if (-not $script:DryRun) { + Remove-Item -LiteralPath $script:Manifest -Force + Remove-Item -LiteralPath $script:StateDir -ErrorAction SilentlyContinue # only goes when empty (Linux/macOS share it) +} +Write-Host '' +Ok "$removed file(s) removed, $restored restored, $skipped skipped." + +Step 'Not removed (delete by hand if you want them gone)' +@' + %LOCALAPPDATA%\nvim the NvChad starter (only if it has a .rhmatzeka-dotfiles marker), %LOCALAPPDATA%\nvim-data + %LOCALAPPDATA%\rhmatzeka-dotfile-tools phpMyAdmin + ~\.local\bin\composer.* Composer; php.ini next to php.exe + ~\.rustup, ~\.cargo Rust (rustup self uninstall) + winget packages winget list, then: winget uninstall --id + script policy Set-ExecutionPolicy Undefined -Scope CurrentUser (in Windows PowerShell) +'@ | Write-Host +exit 0