From a8e83206fda3a1d989d4f2011e1a1edd4d17707a Mon Sep 17 00:00:00 2001 From: Marco Gallegos Date: Thu, 20 Nov 2025 22:34:09 -0600 Subject: [PATCH] refactor: Improve setup script robustness, modularity, and Docker handling, and remove example zshrc. --- .zshrc.example | 153 ++++++++++---------------- readme.md | 83 ++++++++++++-- vanity_setup.sh | 281 +++++++++++++++++++++++++++++++----------------- 3 files changed, 312 insertions(+), 205 deletions(-) diff --git a/.zshrc.example b/.zshrc.example index 17401ef..3bf0d23 100644 --- a/.zshrc.example +++ b/.zshrc.example @@ -1,95 +1,28 @@ -# .zshrc.example -# Archivo de ejemplo para configurar Zsh + Oh My Zsh. -# Bien documentado para entender qué hace cada sección. -# Puedes copiarlo a ~/.zshrc y modificarlo según tus preferencias. - -# ------------------------------------------------------------ -# 1. PATH y variables básicas -# ------------------------------------------------------------ -# Añade rutas personalizadas al PATH si usas Homebrew, Node, Python, etc. -export PATH="/opt/homebrew/bin:/opt/homebrew/sbin:$PATH" -export PATH="$HOME/.local/bin:$PATH" - -# ------------------------------------------------------------ -# 2. Oh My Zsh: tema y plugins -# ------------------------------------------------------------ -# Tema visual del prompt. "powerlevel10k" es rápido y bonito. -ZSH_THEME="powerlevel10k/powerlevel10k" - -# Lista de plugins que se cargarán al iniciar Zsh. -# Se recomienda no abusar de plugins para evitar lentitud. -plugins=( - git # shortcuts de git - sudo # permite repetir comandos con sudo (!!) - history # historial mejorado - colorize # colorear salida de comandos - docker # autocompletado para Docker - docker-compose # autocompletado para Docker Compose - npm # utilidades para Node - node # autocompletado Node.js - python # autocompletado Python - pip # autocompletado pip - golang # autocompletado Go - copypath # copiar rutas al portapapeles - copyfile # copiar archivos al portapapeles -) - -# Carga Oh My Zsh -export ZSH="$HOME/.oh-my-zsh" -source $ZSH/oh-my-zsh.sh - -# ------------------------------------------------------------ -# 3. Configuraciones de historial -# ------------------------------------------------------------ -HISTSIZE=5000 # tamaño en memoria -SAVEHIST=5000 # tamaño en disco -HISTFILE=~/.zsh_history # archivo donde se guarda -setopt SHARE_HISTORY # compartir historial entre sesiones -setopt HIST_IGNORE_DUPS # no guardar duplicados -setopt HIST_IGNORE_SPACE # no guardar comandos que comiencen con espacio - -# ------------------------------------------------------------ -# 4. Alias útiles -# ------------------------------------------------------------ -alias ll="ls -lah" -alias gs="git status" -alias gl="git log --oneline --graph --decorate" -alias please="sudo !!" # magia pura ;) - -# ------------------------------------------------------------ -# 5. Mejoras de terminal -# ------------------------------------------------------------ -# Colores más bonitos en 'ls' -export CLICOLOR=1 -export LSCOLORS="GxFxCxDxBxegedabagacad" - -# Editor de texto por defecto -export EDITOR="nano" - -# ------------------------------------------------------------ -# 6. Powerlevel10k (si está instalado) -# ------------------------------------------------------------ -# Este archivo se genera automáticamente cuando configuras p10k. -# Si no existe, puedes generarlo ejecutando: p10k configure -[[ ! -f ~/.p10k.zsh ]] || source ~/.p10k.zsh -# ~/.zshrc.example — Configuración adaptada para Vanity Shell en macOS # --------------------------------------------------------------- -# Archivo totalmente documentado para uso dentro del entorno Vanity Shell. -# Este archivo será copiado a ~/.zshrc por vanity_setup.sh. -# Incluye: Oh My Zsh, Oh My Posh, plugins, historial, alias y funciones. +# Vanity Shell — Configuración base para Zsh en macOS +# --------------------------------------------------------------- +# Incluye Oh My Zsh, Oh My Posh, historial afinado y alias útiles. +# Este archivo es copiado automáticamente a ~/.zshrc por vanity_setup.sh. # --------------------------------------------------------------- -# PATH — rutas básicas del sistema +# PATH — añade rutas clave antes del resto del sistema # --------------------------------------------------------------- -export PATH="$HOME/bin:/usr/local/bin:/opt/homebrew/bin:$PATH" +if [ -d /opt/homebrew/bin ]; then + export PATH="/opt/homebrew/bin:/opt/homebrew/sbin:$PATH" +fi +if [ -d "$HOME/.local/bin" ]; then + export PATH="$HOME/.local/bin:$PATH" +fi +if [ -d "$HOME/bin" ]; then + export PATH="$HOME/bin:$PATH" +fi # --------------------------------------------------------------- -# Oh My Zsh — Framework principal +# Oh My Zsh — Framework principal + plugins # --------------------------------------------------------------- export ZSH="$HOME/.oh-my-zsh" -ZSH_THEME="robbyrussell" +ZSH_THEME="robbyrussell" # el prompt real lo gestiona Oh My Posh -# Lista de plugins para mejorar la experiencia de ZSH. plugins=( git sudo history colorize docker docker-compose @@ -103,38 +36,68 @@ plugins=( source $ZSH/oh-my-zsh.sh # --------------------------------------------------------------- -# Oh My Posh — Prompt con tema Catppuccin +# Oh My Posh — Prompt moderno (tema Catppuccin) # --------------------------------------------------------------- -eval "$(oh-my-posh init zsh --config ~/.poshthemes/catppuccin.omp.json)" +if command -v oh-my-posh >/dev/null 2>&1; then + eval "$(oh-my-posh init zsh --config ~/.poshthemes/catppuccin.omp.json)" +fi # --------------------------------------------------------------- -# Historial — configuración avanzada +# Historial y opciones de shell # --------------------------------------------------------------- +HISTFILE=~/.zsh_history HISTSIZE=50000 SAVEHIST=50000 -HISTFILE=~/.zsh_history +setopt SHARE_HISTORY setopt HIST_IGNORE_SPACE setopt HIST_IGNORE_DUPS setopt HIST_VERIFY - -# --------------------------------------------------------------- -# Corrección y calidad de vida -# --------------------------------------------------------------- setopt AUTO_CD setopt CORRECT setopt COMPLETE_ALIASES # --------------------------------------------------------------- -# Alias útiles — Comandos abreviados para velocidad +# Preferencias básicas +# --------------------------------------------------------------- +export CLICOLOR=1 +export LSCOLORS="GxFxCxDxBxegedabagacad" +export EDITOR="nano" + +# --------------------------------------------------------------- +# Alias — accesos rápidos de uso frecuente # --------------------------------------------------------------- alias ll="ls -lah" -alias gs="git status" +alias gs="git status -sb" +alias gl="git log --oneline --graph --decorate" alias gc="git commit" alias gp="git push" alias d="docker" alias dc="docker compose" +alias reload-zsh="source ~/.zshrc" +alias portainer="open https://localhost:9443" +alias ytv='yt-dlp -P "$HOME/videos/youtube"' +alias ytm='yt-dlp -x --audio-format mp3 --audio-quality 0 -o "%(title)s.%(ext)s" -P "$HOME/musica/youtube"' # --------------------------------------------------------------- -# Docker + Portainer +# Integraciones opcionales # --------------------------------------------------------------- -alias portainer="open http://localhost:9000" +if command -v direnv >/dev/null 2>&1; then + eval "$(direnv hook zsh)" +fi + +# --------------------------------------------------------------- +# Ayuda rápida de Vanity Shell +# --------------------------------------------------------------- +help() { + cat <<'EOF' +Vanity Shell — comandos rápidos: + ytv -> Descarga el video completo en ~/videos/youtube + ytm -> Descarga solo el audio (mp3) en ~/musica/youtube + +Ejemplos: + ytv https://youtu.be/videoID + ytm https://youtu.be/trackID + +Recuerda que ambos comandos requieren yt-dlp/ffmpeg instalados (el setup ya los incluye). +EOF +} diff --git a/readme.md b/readme.md index 4ef993e..a6ea84d 100644 --- a/readme.md +++ b/readme.md @@ -1,19 +1,82 @@ # VanityOS Shell — macOS Developer Setup 🚀 -VanityOS Shell es el instalador oficial para preparar un entorno de desarrollo en macOS con: - -- ZSH optimizado (Oh My Zsh + Oh My Posh) -- Plugins profesionales de terminal -- Node, Python, Git, y herramientas CLI esenciales -- Docker Desktop + Portainer -- Lazydocker -- Configuración `.zshrc` lista para usarse +Automatiza en pocos minutos un entorno de desarrollo moderno para macOS. VanityOS Shell instala Zsh optimizado, Oh My Posh, utilidades CLI esenciales, Docker Desktop con Portainer y Lazydocker, dejando tu `.zshrc` listo para trabajar. --- -## 📦 Instalación +## ✨ Qué incluye +- Homebrew configurado para Apple Silicon o Intel. +- Zsh + Oh My Zsh con plugins (`zsh-autosuggestions`, `zsh-syntax-highlighting`, `zsh-completions`). +- Oh My Posh (tema Catppuccin) + fuente Meslo Nerd Font. +- Node.js, Python, Git, direnv y herramientas base de terminal. +- yt-dlp + ffmpeg para descargas directas desde YouTube (video y audio). +- Docker Desktop, Lazydocker y despliegue automático de Portainer CE. +- Archivo `.zshrc` documentado para seguir personalizando tu shell. -Ejecuta este comando en tu terminal: +## ✅ Requisitos previos +- macOS 12+ (Intel o Apple Silicon). +- Conexión estable a internet y espacio libre (~5 GB para Docker). +- Se recomienda instalar las Xcode Command Line Tools antes de iniciar: + ```bash + xcode-select --install + ``` +## 🚀 Instalación rápida +Ejecuta el instalador directamente desde la terminal (usa bash, no zsh): ```bash curl -fsSL https://raw.githubusercontent.com/marcogll/mac_vntySet/main/vanity_setup.sh | bash +``` +El script muestra un menú para elegir qué componentes instalar. + +## 🧩 Opciones del menú +| Opción | Descripción | Incluye | +|--------|-------------|---------| +| `A` | Instalación completa (recomendada). | Homebrew + stack Zsh + Docker/Portainer/Lazydocker. | +| `C` | Solo configura la terminal. | Homebrew + Zsh, Oh My Zsh, Oh My Posh, utilidades CLI. | +| `D` | Solo herramientas de contenedores. | Homebrew + Docker Desktop, Portainer, Lazydocker. | +| `Q` | Salir. | — | + +## 🔧 Detalles de la configuración Zsh +- Copia `~/.zshrc` desde `.zshrc.example` (incluye comentarios en español). +- Instala los plugins necesarios y refresca sus repositorios si ya existen. +- Coloca el tema Catppuccin en `~/.poshthemes` y activa Oh My Posh automáticamente. +- Copia `source ~/.zshrc` al portapapeles para que puedas recargar la shell al finalizar. +- Genera los directorios `~/videos/youtube` y `~/musica/youtube` y define alias listos para descargar con `ytv ` (video completo) y `ytm ` (solo audio MP3). +- Añade un comando `help` dentro de Zsh que describe el uso de estos alias. + +## 🐳 Stack Docker + Portainer +1. Instala Docker Desktop via Homebrew Cask. +2. Inicia la app automáticamente y espera a que el daemon esté listo. +3. Instala Lazydocker (`brew install lazydocker`). +4. Lanza Portainer CE con los puertos `8000` y `9443`. Acceso: `https://localhost:9443`. + +> Si Docker Desktop aún no ha terminado de iniciar, el script dejará Portainer pendiente y te indicará que abras la app manualmente y ejecutes de nuevo la opción `D`. + +## ✅ Verificación rápida +- Recargar Zsh: `source ~/.zshrc` +- Comprobar Oh My Posh: el prompt debe mostrar colores y símbolos; si no, ejecuta `oh-my-posh init zsh --config ~/.poshthemes/catppuccin.omp.json`. +- Verificar Docker: `docker info` +- Confirmar Portainer: abre `https://localhost:9443` en el navegador. +- Lanzar Lazydocker: `lazydocker` +- Descargar un video de prueba: `ytv https://youtu.be/` +- Descargar solo audio: `ytm https://youtu.be/` +- Ver ayuda rápida: ejecuta `help` + +## 🧰 Personalización +- Edita `~/.zshrc` para añadir alias o funciones propios; el archivo viene por secciones comentadas. +- Cambia el tema de Oh My Posh apuntando a otro `.omp.json` (guárdalo en `~/.poshthemes`). +- Añade paquetes con `brew install `; el shell ya tiene Homebrew disponible. + +## ❗️ Solución de problemas +- **“command not found: brew”**: ejecuta `eval "$(/opt/homebrew/bin/brew shellenv)"` (o `/usr/local/bin/brew`) y vuelve a correr la opción deseada. +- **Docker no arranca**: abre manualmente Docker Desktop desde Launchpad y espera a que el icono indique “Running” antes de reintentar la opción `D`. +- **Oh My Posh sin fuente correcta**: instala Meslo manualmente desde `~/Library/Fonts` o selecciona *Meslo LG S DZ Nerd Font* en tu terminal. +- **Conflictos con un `.zshrc` previo**: el instalador hace backup implícito sobrescribiendo `~/.zshrc`. Asegúrate de versionar tu archivo antes si necesitas conservarlo. + +## 🧽 Desinstalación rápida +- Elimina Portainer: `docker stop portainer && docker rm portainer && docker volume rm portainer_data`. +- Borra la config Zsh (opcional): `rm -rf ~/.oh-my-zsh ~/.poshthemes ~/.zshrc`. +- Desinstala apps con Homebrew: `brew uninstall --cask docker` o `brew uninstall lazydocker oh-my-posh`. + +## 📄 Licencia +Distribuido bajo la licencia MIT. Consulta `LICENSE` para más detalles. diff --git a/vanity_setup.sh b/vanity_setup.sh index 5062a93..d38e26e 100644 --- a/vanity_setup.sh +++ b/vanity_setup.sh @@ -1,134 +1,215 @@ #!/usr/bin/env bash -set -e +set -euo pipefail -clear -echo "" -echo "==============================================" -echo " V A N I T Y S H E L L" -echo " macOS Development Installer" -echo "==============================================" -echo "" +readonly POSH_THEME_URL="https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/catppuccin.omp.json" +readonly ZSHRC_URL="https://raw.githubusercontent.com/marcogll/mac_vntySet/main/.zshrc.example" +readonly POSH_THEME_PATH="$HOME/.poshthemes/catppuccin.omp.json" -echo "Selecciona una opción:" -echo " A) Instalar TODO (recomendado)" -echo " C) Instalar solo configuración ZSH" -echo " D) Instalar Docker + Portainer + Lazydocker" -echo " Q) Salir" -echo "" -read -p "Opción [A/C/D/Q]: " choice -choice=${choice:-A} +if [[ "$(uname -s)" != "Darwin" ]]; then + echo "Este instalador solo funciona en macOS." >&2 + exit 1 +fi +trap 'echo -e "\nSe produjo un error. Revisa los mensajes anteriores para más detalles." >&2' ERR + +BREW_BIN="" + +ensure_brew_shellenv() { + if command -v brew >/dev/null 2>&1; then + BREW_BIN=$(command -v brew) + eval "$("$BREW_BIN" shellenv)" + return + fi + + for candidate in /opt/homebrew/bin/brew /usr/local/bin/brew; do + if [ -x "$candidate" ]; then + BREW_BIN="$candidate" + eval "$("$BREW_BIN" shellenv)" + return + fi + done +} install_homebrew() { - if ! command -v brew >/dev/null 2>&1; then - echo "Instalando Homebrew…" - NONINTERACTIVE=1 /bin/bash -c \ - "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" - echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile - eval "$(/opt/homebrew/bin/brew shellenv)" - else - echo "Homebrew ya está instalado." - fi + if [ -z "$BREW_BIN" ] && [ ! -x /opt/homebrew/bin/brew ] && [ ! -x /usr/local/bin/brew ]; then + echo "Instalando Homebrew…" + NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" + fi - brew update + ensure_brew_shellenv + + if [ -n "$BREW_BIN" ]; then + local shell_line="eval \"\$($BREW_BIN shellenv)\"" + if ! grep -qsF "$shell_line" "$HOME/.zprofile" 2>/dev/null; then + printf '%s\n' "$shell_line" >> "$HOME/.zprofile" + fi + fi + + brew update +} + +install_cli_dependencies() { + echo "Instalando herramientas base de desarrollo…" + brew install zsh curl wget git jq yq node python go direnv yt-dlp ffmpeg + + echo "Instalando Oh My Posh y fuentes Nerd Font…" + brew tap homebrew/cask-fonts >/dev/null 2>&1 || true + brew install --cask font-meslo-lg-nerd-font + brew install jandedobbeleer/oh-my-posh/oh-my-posh +} + +setup_media_dirs() { + mkdir -p "$HOME/videos/youtube" "$HOME/musica/youtube" +} + +install_oh_my_zsh() { + echo "Instalando Oh My Zsh y plugins…" + if [ ! -d "$HOME/.oh-my-zsh" ]; then + RUNZSH=no CHSH=no KEEP_ZSHRC=yes \ + sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" + fi + + mkdir -p "$HOME/.oh-my-zsh/custom/plugins" + + local repos=( + "zsh-users/zsh-autosuggestions" + "zsh-users/zsh-syntax-highlighting" + "zsh-users/zsh-completions" + ) + + for repo in "${repos[@]}"; do + local destination="$HOME/.oh-my-zsh/custom/plugins/$(basename "$repo")" + if [ -d "$destination/.git" ]; then + git -C "$destination" pull --ff-only >/dev/null 2>&1 || true + else + git clone "https://github.com/${repo}.git" "$destination" + fi + done } install_zsh_config() { - echo "Instalando ZSH base…" - brew install zsh curl wget git yq jq xclip node python + install_cli_dependencies + install_oh_my_zsh + setup_media_dirs - echo "Instalando Oh My Zsh…" - if [ ! -d "$HOME/.oh-my-zsh" ]; then - RUNZSH=no CHSH=no KEEP_ZSHRC=yes \ - sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" - fi + echo "Configurando Oh My Posh…" + mkdir -p "$HOME/.poshthemes" + curl -fsSL "$POSH_THEME_URL" -o "$POSH_THEME_PATH" - echo "Instalando plugins…" - mkdir -p ~/.oh-my-zsh/custom/plugins - - repos=( - "zsh-users/zsh-autosuggestions" - "zsh-users/zsh-syntax-highlighting" - "zsh-users/zsh-completions" - ) - - for r in "${repos[@]}"; do - folder=$(basename "$r") - if [ ! -d "$HOME/.oh-my-zsh/custom/plugins/$folder" ]; then - git clone https://github.com/$r ~/.oh-my-zsh/custom/plugins/$folder - fi - done - - echo "Instalando Oh My Posh…" - brew install jandedobbeleer/oh-my-posh/oh-my-posh - - mkdir -p ~/.poshthemes - curl -fsSL \ - https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/catppuccin.omp.json \ - -o ~/.poshthemes/catppuccin.omp.json - - oh-my-posh font install meslo - - echo "Descargando tu .zshrc.example…" - curl -fsSL https://raw.githubusercontent.com/marcogll/mac_vntySet/main/.zshrc.example \ - -o ~/.zshrc + echo "Descargando .zshrc de Vanity Shell…" + if ! curl -fsSL "$ZSHRC_URL" -o "$HOME/.zshrc"; then + echo "No se pudo descargar la configuración de ZSH." >&2 + exit 1 + fi + if command -v pbcopy >/dev/null 2>&1; then echo "source ~/.zshrc" | pbcopy - echo "" - echo "Tu configuración ZSH está instalada." - echo "El comando 'source ~/.zshrc' ya está copiado al portapapeles." - echo "" + echo "El comando 'source ~/.zshrc' fue copiado al portapapeles." + fi + + echo "Configuración de ZSH instalada correctamente." +} + +ensure_docker_daemon() { + if ! command -v docker >/dev/null 2>&1; then + echo "El CLI de Docker no está disponible todavía." >&2 + return 1 + fi + + if docker info >/dev/null 2>&1; then + return 0 + fi + + if command -v open >/dev/null 2>&1; then + echo "Iniciando Docker Desktop…" + open -g -a Docker >/dev/null 2>&1 || true + else + echo "Abre Docker Desktop manualmente para continuar." >&2 + fi + + for _ in {1..20}; do + sleep 6 + if docker info >/dev/null 2>&1; then + return 0 + fi + done + + echo "Docker Desktop no está listo. Abre la aplicación y vuelve a ejecutar la opción D." >&2 + return 1 } install_docker_stack() { - echo "Instalando Docker Desktop…" - brew install --cask docker + echo "Instalando Docker Desktop…" + brew install --cask docker - echo "Instalando Lazydocker…" - brew install lazydocker + echo "Instalando Lazydocker…" + brew install lazydocker - echo "Instalando Portainer…" - docker volume create portainer_data || true - docker stop portainer >/dev/null 2>&1 || true - docker rm portainer >/dev/null 2>&1 || true + if ! ensure_docker_daemon; then + echo "Se omitió Portainer porque Docker no está operativo." + return + fi - docker run -d \ - -p 8000:8000 -p 9443:9443 \ - --name=portainer \ - --restart=always \ - -v /var/run/docker.sock:/var/run/docker.sock \ - -v portainer_data:/data \ - portainer/portainer-ce:latest + echo "Desplegando Portainer…" + docker volume create portainer_data >/dev/null 2>&1 || true + docker stop portainer >/dev/null 2>&1 || true + docker rm portainer >/dev/null 2>&1 || true + + docker run -d \ + -p 8000:8000 -p 9443:9443 \ + --name=portainer \ + --restart=always \ + -v /var/run/docker.sock:/var/run/docker.sock \ + -v portainer_data:/data \ + portainer/portainer-ce:latest >/dev/null } - -case "$choice" in +main_menu() { + echo "Selecciona una opción:" + echo " A) Instalar TODO (recomendado)" + echo " C) Instalar solo configuración ZSH" + echo " D) Instalar Docker + Portainer + Lazydocker" + echo " Q) Salir" + echo "" + read -r -p "Opción [A/C/D/Q]: " choice + echo "" + case "${choice:-A}" in A|a) - install_homebrew - install_zsh_config - install_docker_stack - ;; + install_homebrew + install_zsh_config + install_docker_stack + ;; C|c) - install_homebrew - install_zsh_config - ;; + install_homebrew + install_zsh_config + ;; D|d) - install_homebrew - install_docker_stack - ;; + install_homebrew + install_docker_stack + ;; Q|q) - echo "Saliendo…" - exit 0 - ;; + echo "Saliendo…" + exit 0 + ;; *) - echo "Opción inválida." - exit 1 - ;; -esac + echo "Opción inválida." >&2 + exit 1 + ;; + esac +} +clear +cat <<'BANNER' +============================================== + V A N I T Y S H E L L + macOS Development Installer +============================================== +BANNER echo "" +main_menu + echo "==============================================" echo " Instalación completada." echo "=============================================="