Regenerate all MDC rules with fresh Exa data and December 2025 best practices

- Refreshed all 241 library rules with current best practices
- Updated Exa search results for all libraries with 2025 content
- Fixed --regenerate-all flag logic to properly process all libraries
- Removed duplicate astro entry in rules.json (merged tags)
- Added missing docker.mdc and vim.mdc files
- All rules now include modern patterns and anti-patterns
- Updated with framework-specific recommendations for 2025

Technical improvements:
- Fixed retry_failed_only logic in generate_mdc_files.py
- Improved progress tracking for regeneration scenarios
- Ensured proper handling of --refresh-exa flag
This commit is contained in:
sanjeed5
2025-12-17 22:40:28 +05:30
parent 331fb6ffac
commit 8fbf269085
244 changed files with 66701 additions and 52708 deletions
+298 -180
View File
@@ -1,200 +1,318 @@
---
description: This rule enforces best practices and coding standards for Zsh scripting to enhance readability, maintainability, security, and performance. It covers code structure, common patterns, performance, security, testing, common pitfalls, and tooling.
globs: *.zsh
description: This guide defines the definitive best practices for writing Zsh scripts and configuration files, ensuring consistency, robustness, and maintainability across our projects.
globs: **/*
---
# Zsh Best Practices and Coding Standards
# zsh Best Practices
This document outlines the best practices and coding standards for Zsh scripting, aiming to enhance readability, maintainability, security, and performance of your scripts.
Zsh is our default shell for interactive use and scripting. This guide outlines mandatory practices to ensure all Zsh code is robust, readable, and performant.
## 1. Code Organization and Structure
## 1. Core Principles
* **Directory Structure Best Practices:**
* `bin/`: Executable scripts intended for general use.
* `lib/`: Library functions and modules.
* `conf/`: Configuration files.
* `test/`: Test scripts.
* `modules/`: Dynamically loaded modules.
* `data/`: Data files used by scripts.
* `tmp/`: Temporary files (ensure proper cleanup).
* **File Naming Conventions:**
* Use `.zsh` extension for Zsh scripts.
* Descriptive names using lowercase and underscores (e.g., `process_data.zsh`, `utility_functions.zsh`).
* Avoid spaces in file names.
* **Module Organization:**
* Split code into logical modules (e.g., `network_utils.zsh`, `string_manipulation.zsh`).
* Use `source` or `.` to include modules in your scripts.
zsh
source lib/network_utils.zsh
* Consider using Zsh's module loading capabilities for larger projects.
zsh
zmodload zsh/datetime
* **Component Architecture:**
* Design scripts with modular, reusable components.
* Encapsulate functionality within functions.
* Use meaningful function names that describe their purpose.
* **Code Splitting Strategies:**
* Split large scripts into smaller, manageable files.
* Group related functions into modules.
* Use functions to abstract complex logic.
### 1.1 Interpreter & Strict Mode
Always specify `zsh` as the interpreter and enable strict mode for early error detection.
## 2. Common Patterns and Anti-patterns
✅ **GOOD:**
```zsh
#!/usr/bin/env zsh
* **Design Patterns:**
* **Command Pattern:** Encapsulate commands as objects.
* **Strategy Pattern:** Define a family of algorithms, encapsulate each one, and make them interchangeable.
* **Template Method Pattern:** Define the skeleton of an algorithm in a function, deferring some steps to sub-functions.
* **Recommended Approaches for Common Tasks:**
* **Parsing Command-Line Arguments:** Use `getopts` or `zparseopts` for parsing command-line arguments.
zsh
while getopts 'a:b:c' opt;
do
case "$opt" in
a) arg_a="$OPTARG" ;;
b) arg_b="$OPTARG" ;;
c) flag_c=true ;;
\?) echo "Invalid option: -$OPTARG" >&2 ;;
esac
done
shift "$((OPTIND - 1))"
* **String Manipulation:** Use Zsh's built-in string manipulation features (e.g., parameter expansion, pattern matching).
* **File I/O:** Use redirection (`>`, `<`, `>>`) and pipes (`|`) for file input/output.
* **Anti-patterns and Code Smells:**
* **Global Variables:** Avoid global variables; use local variables within functions.
* **Magic Numbers:** Avoid hardcoding values directly; use named constants.
* **Code Duplication:** Refactor duplicated code into reusable functions or modules.
* **Long Functions:** Break down long functions into smaller, more manageable units.
* **Unclear Error Messages:** Provide informative error messages to the user.
* **State Management:**
* Minimize the use of global state.
* Pass state as arguments to functions.
* Use temporary files for persistent state (with proper cleanup).
* **Error Handling:**
* Use `set -e` to exit immediately if a command exits with a non-zero status.
* Use `set -u` to treat unset variables as an error.
* Check the exit status of commands using `$?`.
* Use `trap` to handle signals (e.g., `EXIT`, `INT`, `TERM`).
zsh
trap 'echo "Script interrupted."; exit 1' INT TERM
* Redirect stderr to a file for debugging.
# Enable strict mode:
# errreturn: Exit immediately if a command exits with a non-zero status.
# nounset: Treat unset variables as an error.
# pipefail: The exit status of a pipeline is the status of the last command to exit with a non-zero status, or zero if all commands exit successfully.
setopt errreturn nounset pipefail
```
## 3. Performance Considerations
❌ **BAD:**
```zsh
#!/bin/bash # Wrong interpreter
# No strict mode options
```
* **Optimization Techniques:**
* **Avoid Spawning External Processes:** Use Zsh's built-in commands whenever possible.
* **Minimize Disk I/O:** Use caching to reduce disk access.
* **Optimize Loops:** Use efficient looping constructs (e.g., `for` loops over arrays).
* **Use Arrays:** Arrays are generally faster than string manipulation for certain tasks.
* **Use `zcompile`:** Pre-compile your zsh scripts to improve startup time
zsh
zcompile script.zsh
* **Memory Management:**
* Be mindful of memory usage when working with large files or data sets.
* Use `unset` to free memory occupied by variables that are no longer needed.
* **Rendering Optimization (if applicable):**
* Optimize terminal output for speed and clarity.
* Avoid excessive use of colors and formatting.
* **Bundle Size Optimization:**
* Not applicable to Zsh scripts in the same way as web applications, but keep scripts concise and avoid unnecessary dependencies.
* **Lazy Loading:**
* Load modules and functions only when they are needed.
### 1.2 ShellCheck Integration
ShellCheck is non-negotiable. Integrate it into your editor and CI pipeline.
## 4. Security Best Practices
✅ **GOOD:**
```zsh
# .github/workflows/ci.yml
name: ShellCheck
* **Common Vulnerabilities:**
* **Command Injection:** Prevent command injection by properly quoting variables and avoiding the use of `eval`.
* **Path Traversal:** Sanitize user input to prevent path traversal attacks.
* **Denial of Service (DoS):** Limit resource consumption to prevent DoS attacks.
* **Input Validation:**
* Validate all user input before using it in commands.
* Use regular expressions to validate data formats.
* Use `typeset -i` to ensure variables are integers when expected.
* **Authentication and Authorization:**
* For scripts requiring authentication, consider using existing authentication mechanisms (e.g., SSH keys).
* Implement authorization checks to restrict access to sensitive resources.
* **Data Protection:**
* Store sensitive data securely (e.g., using encrypted files).
* Avoid storing passwords directly in scripts.
* Use environment variables for sensitive configuration information.
* **Secure API Communication:**
* Use HTTPS for all API communication.
* Validate API responses.
* Handle API errors gracefully.
on: [push, pull_request]
## 5. Testing Approaches
jobs:
shellcheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run ShellCheck
uses: ludeeus/action-shellcheck@v2
with:
scandir: './' # Scan all shell scripts in the repository
```
* **Unit Testing:**
* Test individual functions in isolation.
* Use a testing framework like `zunit` or `zrtest`.
* Write tests for both positive and negative scenarios.
* **Integration Testing:**
* Test the interaction between different modules and components.
* Simulate real-world scenarios.
* **End-to-End Testing:**
* Test the entire script from start to finish.
* Verify that the script produces the expected output.
* **Test Organization:**
* Create a separate directory for test scripts.
* Organize tests by module or component.
* **Mocking and Stubbing:**
* Use mocking and stubbing to isolate units of code during testing.
* Create mock objects for external dependencies.
## 2. Code Organization and Structure
## 6. Common Pitfalls and Gotchas
### 2.1 File Header & Comments
Every script must start with a descriptive header. Functions require clear comments.
* **Frequent Mistakes:**
* **Forgetting to Quote Variables:** Always quote variables to prevent word splitting and globbing.
* **Ignoring Exit Status:** Always check the exit status of commands.
* **Using `eval` Unnecessarily:** Avoid `eval` if possible, as it can lead to security vulnerabilities.
* **Not Handling Signals:** Handle signals like `INT` and `TERM` to ensure proper cleanup.
* **Edge Cases:**
* Handling empty or missing input.
* Dealing with special characters in filenames.
* Handling different locales and character encodings.
* **Version-Specific Issues:**
* Be aware of differences between Zsh versions.
* Use feature detection to ensure compatibility.
* **Compatibility Concerns:**
* Ensure that your scripts are compatible with different operating systems.
* Test your scripts on different environments.
* **Debugging Strategies:**
* Use `set -x` to trace the execution of your script.
* Use `echo` statements to print debugging information.
* Use a debugger like `gdb` or `lldb` (if available).
✅ **GOOD:**
```zsh
#!/usr/bin/env zsh
#
# Description: Manages project dependencies via a custom tool.
#
# setopt errreturn nounset pipefail
## 7. Tooling and Environment
#######################################
# Fetches and installs project dependencies.
# Globals:
# PROJECT_ROOT
# Arguments:
# None
# Outputs:
# Writes status messages to stderr.
# Returns:
# 0 if dependencies are installed, non-zero on error.
#######################################
function install_dependencies() {
# ... implementation ...
}
```
* **Recommended Development Tools:**
* **Text Editor:** Use a text editor with Zsh syntax highlighting and linting (e.g., VS Code with Zsh extensions).
* **Shellcheck:** Use Shellcheck to identify potential problems in your scripts.
* **Zsh Debugger:** If available, use a debugger to step through your code.
* **Build Configuration:**
* Use Makefiles or other build tools to automate the build process.
* Define dependencies and build targets.
* **Linting and Formatting:**
* Use Shellcheck for linting.
* Use a code formatter like `shfmt` to ensure consistent formatting.
* **Deployment Best Practices:**
* Package your scripts with any necessary dependencies.
* Use a version control system like Git to track changes.
* Automate the deployment process using tools like Ansible or Puppet.
* **CI/CD Integration:**
* Integrate your scripts with a CI/CD pipeline.
* Run tests and linters automatically.
* Deploy your scripts to production automatically.
### 2.2 Function Location & `main`
Define all functions before their first use. Use a `main` function for the script's entry point.
## Additional Considerations
✅ **GOOD:**
```zsh
#!/usr/bin/env zsh
setopt errreturn nounset pipefail
* **Shebang:** Always start your scripts with a shebang line specifying the Zsh interpreter:
zsh
#!/usr/bin/env zsh
* **Coding Style:** Follow a consistent coding style to improve readability.
* **Documentation:** Document your scripts and functions using comments.
* **Keep it Simple:** Aim for simplicity and clarity in your code.
function _log_info() {
echo "[INFO] $*" >&2
}
By following these best practices, you can write Zsh scripts that are more reliable, maintainable, and secure.
function _process_data() {
_log_info "Processing data for: $1"
# ...
}
function main() {
_log_info "Starting data processing..."
_process_data "report_A"
_process_data "report_B"
_log_info "Processing complete."
}
main "$@"
```
## 3. Formatting
### 3.1 Indentation & Line Length
Indent with 2 spaces. Limit lines to 80 characters.
✅ **GOOD:**
```zsh
if [[ -n "${VAR}" ]]; then
echo "Variable is set."
fi
long_command_name --option-one value \
--option-two another-value \
--final-option
```
❌ **BAD:**
```zsh
if [[ -n "${VAR}" ]]; then
echo "Variable is set."
fi # 4 spaces
long_command_name --option-one value --option-two another-value --final-option # Too long
```
### 3.2 Quoting & Variable Expansion
Always quote variables and command substitutions unless you explicitly need word splitting. Prefer `${parameter}`.
✅ **GOOD:**
```zsh
local my_file="report.txt"
local content="$(cat "${my_file}")" # Command substitution quoted
echo "Processing file: ${my_file}" # Variable quoted, preferred syntax
```
❌ **BAD:**
```zsh
local my_file=report.txt
local content=$(cat $my_file) # Unquoted, prone to word splitting/globbing
echo "Processing file: $my_file" # Legacy syntax
```
## 4. Naming Conventions
### 4.1 Functions & Variables
- **Functions:** `lower_snake_case`. Prefix internal functions with `_`.
- **Constants/Environment Variables:** `ALL_CAPS`.
- **Local Variables:** `local lower_snake_case`.
✅ **GOOD:**
```zsh
local MY_CONSTANT="fixed_value"
local _internal_helper_var="temp"
function calculate_total() {
local item_count="${1}"
local unit_price="${2}"
echo $(( item_count * unit_price ))
}
```
❌ **BAD:**
```zsh
local myConstant="value" # CamelCase
function CalculateTotal() { # PascalCase
local ItemCount="${1}" # PascalCase
}
```
## 5. Zsh-Specific Patterns
### 5.1 Zsh Arrays
Use Zsh's native array handling. `${array}` expands to all elements. Use `"${(@)array}"` to preserve empty entries.
✅ **GOOD:**
```zsh
local my_array=("apple" "" "banana")
echo "All elements: ${my_array}" # apple banana (empty removed)
echo "Preserving empty: ${(@)my_array}" # apple banana (empty preserved)
# Iterate safely
for item in "${(@)my_array}"; do
echo "Item: '${item}'"
done
```
❌ **BAD:**
```zsh
local my_array=("apple" "" "banana")
echo "Bash style: ${my_array[@]}" # Works, but not idiomatic Zsh
```
### 5.2 Extended Globbing
Enable `extended_glob` for powerful pattern matching.
✅ **GOOD:**
```zsh
setopt extended_glob
# Find files not ending with .txt or .log
ls -d *~*.(txt|log)
# Case-insensitive glob
ls -d (#i)*.txt
```
### 5.3 Parameter Expansion for Path Manipulation
Avoid `dirname` and `basename` external commands.
✅ **GOOD:**
```zsh
local full_path="/path/to/my/file.txt"
local dir_name="${full_path:h}" # /path/to/my
local base_name="${full_path:t}" # file.txt
local absolute_path="${full_path:A}" # Resolve symlinks and get absolute path
```
❌ **BAD:**
```zsh
local full_path="/path/to/my/file.txt"
local dir_name="$(dirname "${full_path}")"
local base_name="$(basename "${full_path}")"
```
### 5.4 Zsh-Native Filtering (Skipping `grep`/`tr`)
Leverage Zsh's parameter expansion for filtering and transformations.
✅ **GOOD:**
```zsh
# Filter array (like grep)
local lines=("line one" "another line" "third line")
local matched_lines=(${(M)lines:#*line*}) # Matches lines containing "line"
print -l "${matched_lines[@]}"
# Transform string (like tr)
local text="hello world"
local transformed_text="${text//[aeiou]/_}" # h_ll_ w_rld
```
❌ **BAD:**
```zsh
local lines=("line one" "another line" "third line")
local matched_lines="$(printf "%s\n" "${lines[@]}" | grep "line")" # External command, subshell
```
### 5.5 Ternary Expressions
Use `:+` and `:-` for concise conditional assignments.
✅ **GOOD:**
```zsh
local debug_mode="true"
local log_level="${debug_mode:+DEBUG}:INFO" # If debug_mode is set, prepend DEBUG
echo "Log level: ${log_level}" # Output: Log level: DEBUG:INFO
local debug_mode=""
local log_level="${debug_mode:+DEBUG}:INFO"
echo "Log level: ${log_level}" # Output: Log level: :INFO
```
## 6. Anti-Patterns & Pitfalls
### 6.1 Avoid `eval`
`eval` is a security risk and makes code hard to debug. Never use it.
❌ **BAD:**
```zsh
local cmd="ls -l"
eval "${cmd}" # Dangerous!
```
### 6.2 `source` with Caution
Only `source` trusted files. For external tools, prefer explicit execution or `eval "$(tool init zsh)"` if the tool is trusted and designed for it.
✅ **GOOD:**
```zsh
# .zshrc
# Source trusted local configuration
source "${ZDOTDIR:-$HOME}/.zsh_aliases"
# For trusted tools that provide init scripts
eval "$(zoxide init zsh)"
```
❌ **BAD:**
```zsh
source "/tmp/untrusted_script.zsh"
```
### 6.3 Minimal `.zshrc`
Keep your `.zshrc` lean. Avoid heavy frameworks like Oh My Zsh unless absolutely necessary. Prefer lightweight tools and manual configuration.
✅ **GOOD:**
```zsh
# .zshrc
HISTFILE=~/.zsh_history
HISTSIZE=100000
SAVEHIST=100000
setopt HIST_SAVE_NO_DUPS INC_APPEND_HISTORY AUTO_PUSHD PUSHD_IGNORE_DUPS PUSHD_SILENT autocd
autoload -U compinit; compinit
# Prompt via Starship (external, lightweight)
eval "$(starship init zsh)"
```
❌ **BAD:**
```zsh
# .zshrc
# Too many plugins, slow startup
source $ZSH/oh-my-zsh.sh
plugins=(git docker web-search history-substring-search ...)
```