added the ability to initiate a plex library scan from the CLI. tab completions are supported as well.

This commit is contained in:
Peter Wood
2025-06-26 09:07:51 -04:00
parent 57cd60cdf3
commit 563daa51af
11 changed files with 2170 additions and 81 deletions

View File

@@ -8,7 +8,38 @@ The completion system provides intelligent tab completion for command-line flags
## Supported Scripts
### backup-immich.sh
### Plex Management Scripts ⭐ **NEW**
#### plex.sh
- `start` - Start Plex Media Server
- `stop` - Stop Plex Media Server
- `restart` - Restart Plex Media Server
- `status` - Show detailed service status
- `scan` - Launch library scanner (with sub-commands)
- `repair` - Repair database corruption issues
- `nuclear` - Nuclear database recovery (last resort)
- `help` - Show help message
#### scan-plex-libraries.sh
- `list` - List all library sections
- `scan` - Scan for new media (with optional section ID)
- `refresh` - Refresh metadata (with optional section ID and force flag)
- `analyze` - Analyze media (with optional section ID and deep flag)
- `generate` - Generate thumbnails (with optional section ID)
- `tree` - Show library tree structure (requires section ID)
- `interactive` - Interactive mode
- `-v`, `--verbose` - Enable verbose output
- `-h`, `--help` - Show help message
#### Plex Aliases
- `plex`, `px` - Main plex.sh script with command completion
- `plex-start`, `plex-stop`, `plex-restart`, `plex-status` - Direct service commands
- `plex-scan` - Library scanner via plex.sh (supports scanner sub-commands)
- `plex-scanner` - Direct access to scan-plex-libraries.sh
### Backup Scripts
#### backup-immich.sh
- `--help`, `-h` - Show help message
- `--dry-run` - Preview backup without executing
@@ -73,6 +104,16 @@ autoload -U compinit && compinit -u
if [ -f "$HOME/shell/completions/backup-scripts-completion.bash" ]; then
source "$HOME/shell/completions/backup-scripts-completion.bash"
fi
# Load Plex scripts completion
if [ -f "$HOME/shell/completions/plex-scripts-completion.bash" ]; then
source "$HOME/shell/completions/plex-scripts-completion.bash"
fi
# Load environment backup completion
if [ -f "$HOME/shell/completions/env-backup-completion.bash" ]; then
source "$HOME/shell/completions/env-backup-completion.bash"
fi
```
## Usage Examples
@@ -89,6 +130,40 @@ $ backup-immich.sh --d<TAB>
$ backup-immich.sh --dry-run
```
### Plex Script Completion ⭐ **NEW**
```bash
# Main plex.sh command completion
$ plex.sh <TAB>
start stop restart status scan repair nuclear help
# Scanner sub-command completion when using scan
$ plex.sh scan <TAB>
list scan refresh analyze generate tree interactive -v --verbose -h --help
# Direct scanner script completion
$ scan-plex-libraries.sh <TAB>
list scan refresh analyze generate tree interactive
# Scanner options completion
$ scan-plex-libraries.sh -<TAB>
-v --verbose -h --help
# Boolean flag completion for refresh and analyze
$ scan-plex-libraries.sh refresh 29 <TAB>
true false
$ scan-plex-libraries.sh analyze 29 <TAB>
true false
# Alias completion works too
$ plex-scan <TAB>
list scan refresh analyze generate tree interactive
$ plex-scanner <TAB>
list scan refresh analyze generate tree interactive
```
### Webhook URL Completion
```bash

View File

@@ -0,0 +1,273 @@
# Plex Scripts Bash Completion Implementation
## Overview
Implemented comprehensive bash completion for all Plex-related scripts to provide intelligent tab completion functionality. The completion system supports both the main `plex.sh` script and the new `scan-plex-libraries.sh` scanner script, along with all related aliases.
## Implementation Details
### New Completion Script
**File**: `/home/acedanger/shell/completions/plex-scripts-completion.bash`
**Features Implemented**:
-**plex.sh Command Completion**: Complete main commands (start, stop, restart, status, scan, repair, nuclear, help)
-**Scanner Sub-command Completion**: When using `plex.sh scan`, completes with scanner commands
-**Direct Scanner Completion**: Complete commands for `scan-plex-libraries.sh`
-**Option Completion**: Complete flags like `-v`, `--verbose`, `-h`, `--help`
-**Boolean Flag Completion**: For `refresh` and `analyze` commands, completes with `true`/`false`
-**Alias Support**: Completion for all plex-related aliases
-**Path-based Completion**: Works with relative and absolute paths
-**Advanced Features**: Optional library section ID completion (with timeout protection)
### Supported Scripts and Aliases
#### Main Scripts
- `plex.sh` - Main Plex management script
- `scan-plex-libraries.sh` - Library scanner script
- `./plex.sh` - Relative path execution
- `/home/acedanger/shell/plex/plex.sh` - Absolute path execution
#### Aliases
- `plex` - Main plex script
- `px` - Quick shortcut for plex script
- `plex-start` - Direct start command
- `plex-stop` - Direct stop command
- `plex-restart` - Direct restart command
- `plex-status` - Direct status command
- `plex-scan` - Scanner via plex.sh
- `plex-scanner` - Direct scanner access
### Completion Examples
#### plex.sh Commands
```bash
$ plex.sh <TAB>
start stop restart status scan repair nuclear help
$ plex.sh s<TAB>
start status scan
$ plex.sh scan <TAB>
list scan refresh analyze generate tree interactive -v --verbose -h --help
```
#### Scanner Commands
```bash
$ scan-plex-libraries.sh <TAB>
list scan refresh analyze generate tree interactive
$ scan-plex-libraries.sh -<TAB>
-v --verbose -h --help
$ scan-plex-libraries.sh refresh 29 <TAB>
true false
$ scan-plex-libraries.sh analyze 29 <TAB>
true false
```
#### Alias Completion
```bash
$ plex-scan <TAB>
list scan refresh analyze generate tree interactive
$ plex-scanner <TAB>
list scan refresh analyze generate tree interactive
```
## Installation Integration
### Setup Scripts Updated
#### bootstrap.sh
```bash
# Added plex completion to executable permissions
chmod +x "$DOTFILES_DIR/completions/plex-scripts-completion.bash" 2>/dev/null || true
```
#### setup.sh
```bash
# Enhanced completion installation section
# - Installs backup, plex, and environment backup completions
# - Creates ~/.local/share/bash-completion/completions/ directory
# - Copies and makes completion scripts executable
```
#### .zshrc
```bash
# Added plex completion loading
if [ -f "$HOME/shell/completions/plex-scripts-completion.bash" ]; then
source "$HOME/shell/completions/plex-scripts-completion.bash"
fi
```
### Manual Installation
For immediate testing or manual setup:
```bash
# Enable bash completion in zsh
autoload -U +X bashcompinit && bashcompinit
autoload -U compinit && compinit -u
# Source the completion script
source /home/acedanger/shell/completions/plex-scripts-completion.bash
```
## Advanced Features
### Context-Aware Completion
The completion system is context-aware and provides different suggestions based on:
- **Command Position**: Different completions for first argument vs subsequent arguments
- **Previous Word**: When previous word is specific command, shows relevant options
- **Script Type**: Different behavior for main plex.sh vs scanner script
### Intelligent Boolean Completion
For commands that accept boolean flags:
```bash
# Refresh with force flag
$ scan-plex-libraries.sh refresh 29 <TAB>
true false
# Analyze with deep flag
$ scan-plex-libraries.sh analyze 29 <TAB>
true false
```
### Optional Section ID Completion
The completion script includes an advanced feature (commented out by default) that can:
- Connect to the running Plex server
- Retrieve actual library section IDs
- Provide them as completion options
- Include timeout protection to prevent hanging
To enable:
```bash
# Uncomment this line in the completion script:
# complete -F _plex_scanner_with_sections plex-scanner
```
### Helper Functions
#### _plex_list_sections
Manual function to list available library sections:
```bash
$ _plex_list_sections
Available Plex library sections:
29: Movies
30: TV Shows
31: Music
```
## Error Handling and Safety
### Timeout Protection
- Advanced section ID completion includes 3-second timeout
- Prevents hanging if Plex server is unresponsive
- Gracefully falls back to basic completion
### Service Validation
- Checks if completion functions exist before calling
- Handles missing scripts gracefully
- Provides meaningful fallbacks
### Cross-Shell Compatibility
- Works in both bash and zsh
- Uses bash completion compatibility mode in zsh
- Handles shell-specific export differences
## Testing and Validation
### Manual Testing
```bash
# Test basic completion
source /home/acedanger/shell/completions/plex-scripts-completion.bash
# Test with specific commands
complete -p plex.sh
complete -p scan-plex-libraries.sh
complete -p plex-scan
```
### Integration Testing
- Completion works after setup script execution
- Aliases receive appropriate completion
- Path-based execution maintains completion
- No conflicts with existing backup script completion
## Documentation Updates
### Updated Files
1. **completions/README.md**: Added comprehensive Plex completion documentation
2. **completions/plex-scripts-completion.bash**: New completion script
3. **setup/setup.sh**: Enhanced completion installation
4. **setup/bootstrap.sh**: Added plex completion to executable permissions
5. **dotfiles/.zshrc**: Added plex completion loading
### Documentation Sections Added
- Plex Management Scripts section in completions README
- Usage examples with all plex commands
- Installation instructions including manual setup
- Troubleshooting information
## Benefits
### User Experience
- **Faster Command Entry**: Tab completion reduces typing
- **Discovery**: Users can discover available commands via tab
- **Error Prevention**: Reduces command typos and invalid options
- **Consistency**: Same completion experience across all scripts
### Developer Experience
- **Maintainable**: Completion logic is well-documented and modular
- **Extensible**: Easy to add new commands or options
- **Robust**: Handles edge cases and errors gracefully
- **Standard**: Follows bash completion best practices
### Integration Benefits
- **Seamless**: Works with existing alias system
- **Automatic**: Installed by setup scripts
- **Compatible**: Works with both direct script calls and aliases
- **Flexible**: Supports multiple invocation methods
## Future Enhancements
### Potential Improvements
1. **Dynamic Section IDs**: Enable real-time library section completion
2. **File Path Completion**: For commands that accept file paths
3. **History-based Completion**: Remember frequently used section IDs
4. **Custom Completions**: User-configurable completion preferences
5. **Performance Optimization**: Cache completion data for faster response
### Extensibility Points
- Easy to add new commands to existing completion functions
- Modular design allows for script-specific completion logic
- Helper functions can be extended for more intelligence
- Integration points for future plex-related scripts
## Best Practices Followed
### Code Quality
- **Modular Functions**: Separate completion functions for each script
- **Error Handling**: Graceful fallbacks and error prevention
- **Documentation**: Comprehensive inline comments
- **Consistency**: Follows existing completion script patterns
### Performance
- **Minimal Overhead**: Fast completion without unnecessary processing
- **Timeout Protection**: Prevents blocking on slow operations
- **Efficient Logic**: Optimized completion tree traversal
- **Resource Conscious**: Minimal memory and CPU usage
### Compatibility
- **Shell Agnostic**: Works in bash and zsh
- **Path Independent**: Handles various script invocation methods
- **Version Safe**: Compatible with different bash completion versions
- **System Independent**: Works across different Linux distributions
## Conclusion
The Plex scripts bash completion implementation provides a comprehensive, user-friendly tab completion system that enhances the command-line experience for all Plex-related operations. The system is well-integrated with the existing shell setup, follows best practices, and provides room for future enhancements while maintaining backward compatibility.

View File

@@ -0,0 +1,220 @@
#!/bin/bash
# Bash completion for Plex-related scripts
# Author: Peter Wood <peter@peterwood.dev>
#
# This file provides intelligent tab completion for:
# - plex.sh (main Plex management script)
# - scan-plex-libraries.sh (library scanner script)
# - plex-* aliases
#
# Installation:
# Source this file in your bash/zsh configuration or place it in:
# ~/.local/share/bash-completion/completions/
# Completion function for plex.sh
_plex_sh_completion() {
local cur="${COMP_WORDS[COMP_CWORD]}"
local prev="${COMP_WORDS[COMP_CWORD-1]}"
# Available commands for plex.sh
local commands="start stop restart status scan repair nuclear help"
# If we're completing the first argument (command)
if [[ ${COMP_CWORD} -eq 1 ]]; then
COMPREPLY=($(compgen -W "$commands" -- "$cur"))
return 0
fi
# If previous word was 'scan', complete with scanner options
if [[ "$prev" == "scan" ]]; then
local scanner_commands="list scan refresh analyze generate tree interactive"
local scanner_options="-v --verbose -h --help"
COMPREPLY=($(compgen -W "$scanner_commands $scanner_options" -- "$cur"))
return 0
fi
# For other commands, no additional completion needed
return 0
}
# Completion function for scan-plex-libraries.sh
_scan_plex_libraries_completion() {
local cur="${COMP_WORDS[COMP_CWORD]}"
local prev="${COMP_WORDS[COMP_CWORD-1]}"
# Available commands for scan-plex-libraries.sh
local commands="list scan refresh analyze generate tree interactive"
local options="-v --verbose -h --help"
# If we're completing the first argument
if [[ ${COMP_CWORD} -eq 1 ]]; then
# If it starts with -, show options
if [[ "$cur" == -* ]]; then
COMPREPLY=($(compgen -W "$options" -- "$cur"))
else
COMPREPLY=($(compgen -W "$commands" -- "$cur"))
fi
return 0
fi
# Handle specific command completions
case "${COMP_WORDS[1]}" in
refresh)
# For refresh command: refresh [section_id] [force]
if [[ ${COMP_CWORD} -eq 3 ]]; then
# Third argument can be 'true' or 'false' for force flag
COMPREPLY=($(compgen -W "true false" -- "$cur"))
fi
;;
analyze|analyse)
# For analyze command: analyze [section_id] [deep]
if [[ ${COMP_CWORD} -eq 3 ]]; then
# Third argument can be 'true' or 'false' for deep flag
COMPREPLY=($(compgen -W "true false" -- "$cur"))
fi
;;
tree)
# tree command requires section_id but we can't predict them
# Could potentially call the script to get section IDs but that's expensive
;;
esac
return 0
}
# Completion function for generic plex aliases that might pass through to plex.sh
_plex_alias_completion() {
local cur="${COMP_WORDS[COMP_CWORD]}"
# For plex-scan alias, complete with scanner commands
if [[ "${COMP_WORDS[0]}" == *"plex-scan"* ]]; then
local scanner_commands="list scan refresh analyze generate tree interactive"
local scanner_options="-v --verbose -h --help"
if [[ ${COMP_CWORD} -eq 1 ]]; then
if [[ "$cur" == -* ]]; then
COMPREPLY=($(compgen -W "$scanner_options" -- "$cur"))
else
COMPREPLY=($(compgen -W "$scanner_commands" -- "$cur"))
fi
elif [[ ${COMP_CWORD} -eq 2 && "${COMP_WORDS[1]}" == "refresh" ]]; then
COMPREPLY=($(compgen -W "true false" -- "$cur"))
elif [[ ${COMP_CWORD} -eq 2 && ("${COMP_WORDS[1]}" == "analyze" || "${COMP_WORDS[1]}" == "analyse") ]]; then
COMPREPLY=($(compgen -W "true false" -- "$cur"))
fi
return 0
fi
# For plex-scanner alias, use the full scanner completion
if [[ "${COMP_WORDS[0]}" == *"plex-scanner"* ]]; then
_scan_plex_libraries_completion
return 0
fi
# For other plex aliases, just complete with main plex.sh commands
local commands="start stop restart status scan repair nuclear help"
COMPREPLY=($(compgen -W "$commands" -- "$cur"))
return 0
}
# Advanced completion function that attempts to get library section IDs
# This is more expensive but provides better completion
_plex_scanner_with_sections() {
local cur="${COMP_WORDS[COMP_CWORD]}"
local prev="${COMP_WORDS[COMP_CWORD-1]}"
# First try the basic completion
_scan_plex_libraries_completion
# If we didn't get any completions and we're looking for a section ID
if [[ ${#COMPREPLY[@]} -eq 0 ]]; then
case "${COMP_WORDS[1]}" in
scan|refresh|analyze|generate|tree)
# Try to get section IDs if Plex is running
if [[ ${COMP_CWORD} -eq 2 ]]; then
# Attempt to get section IDs from the scanner
local script_dir="$(dirname "${COMP_WORDS[0]}")"
local scanner_script=""
# Try to find the scanner script
if [[ -f "$script_dir/scan-plex-libraries.sh" ]]; then
scanner_script="$script_dir/scan-plex-libraries.sh"
elif [[ -f "/home/acedanger/shell/plex/scan-plex-libraries.sh" ]]; then
scanner_script="/home/acedanger/shell/plex/scan-plex-libraries.sh"
fi
if [[ -n "$scanner_script" ]]; then
# Attempt to get section IDs (with timeout to avoid hanging)
local section_ids
if section_ids=$(timeout 3s "$scanner_script" list 2>/dev/null | grep -oE '^\s*[0-9]+:' | grep -oE '[0-9]+' 2>/dev/null); then
COMPREPLY=($(compgen -W "$section_ids" -- "$cur"))
fi
fi
fi
;;
esac
fi
return 0
}
# Register completion functions for the main scripts
complete -F _plex_sh_completion plex.sh
complete -F _plex_sh_completion ./plex.sh
complete -F _plex_sh_completion /home/acedanger/shell/plex/plex.sh
complete -F _scan_plex_libraries_completion scan-plex-libraries.sh
complete -F _scan_plex_libraries_completion ./scan-plex-libraries.sh
complete -F _scan_plex_libraries_completion /home/acedanger/shell/plex/scan-plex-libraries.sh
# Register completion functions for aliases
# These will be available when the aliases are defined in the shell
complete -F _plex_alias_completion plex
complete -F _plex_alias_completion px
complete -F _plex_alias_completion plex-start
complete -F _plex_alias_completion plex-stop
complete -F _plex_alias_completion plex-restart
complete -F _plex_alias_completion plex-status
complete -F _plex_alias_completion plex-scan
complete -F _scan_plex_libraries_completion plex-scanner
# Optional: Enable advanced completion with section ID lookup for plex-scanner
# Uncomment the following line if you want more intelligent section ID completion
# (Note: This may cause slight delays if Plex is not running)
# complete -F _plex_scanner_with_sections plex-scanner
# Helper function to list available Plex library sections
# This can be called manually: _plex_list_sections
_plex_list_sections() {
echo "Available Plex library sections:"
if command -v /home/acedanger/shell/plex/scan-plex-libraries.sh >/dev/null 2>&1; then
/home/acedanger/shell/plex/scan-plex-libraries.sh list 2>/dev/null || echo " (Plex Media Server not running)"
else
echo " (Scanner script not found)"
fi
}
# Completion for special plex commands that might be added in the future
_plex_extended_completion() {
local cur="${COMP_WORDS[COMP_CWORD]}"
local cmd="${COMP_WORDS[0]}"
# This function can be extended for future plex-related commands
case "$cmd" in
*plex-backup*)
# If backup scripts get their own completion, handle here
;;
*plex-restore*)
# If restore scripts get their own completion, handle here
;;
esac
return 0
}
# Export functions for manual use (zsh compatible)
if declare -f >/dev/null 2>&1; then
# In bash, export functions
export -f _plex_list_sections 2>/dev/null || true
fi