AudioLab Development Standards & Style Guide¶
Sistema de estándares profesionales para desarrollo escalable¶
1. VERBOS APROBADOS DE POWERSHELL¶
Verbos Comunes (USAR ESTOS)¶
# Obtención de datos
Get- # Obtener información (no modifica)
Find- # Buscar con criterios específicos
Search- # Buscar con patrones amplios
Select- # Seleccionar subset de datos
# Creación/Modificación
New- # Crear nuevo objeto/recurso
Add- # Agregar a colección existente
Set- # Establecer/reemplazar valor
Update- # Actualizar parcialmente
# Eliminación
Remove- # Eliminar objeto/recurso
Clear- # Vaciar contenido (mantiene contenedor)
Reset- # Restaurar a estado inicial
# Estado/Control
Start- # Iniciar proceso/operación
Stop- # Detener proceso/operación
Restart- # Reiniciar proceso
Enable- # Habilitar funcionalidad
Disable- # Deshabilitar funcionalidad
# Datos
Import- # Traer datos externos al sistema
Export- # Enviar datos fuera del sistema
ConvertTo- # Convertir a otro formato
ConvertFrom-# Convertir desde otro formato
# Validación
Test- # Verificar condición (retorna bool)
Assert- # Validar y lanzar error si falla
Measure- # Medir/calcular métricas
# Sistema
Invoke- # Ejecutar comando/operación
Use- # Cambiar contexto activo
Enter- # Entrar a scope/sesión
Exit- # Salir de scope/sesión
Verbos NO Aprobados (EVITAR)¶
# MAL → BIEN
Create- → New-
Delete- → Remove-
Fetch- → Get-
Load- → Import-
Save- → Export- o Set-
Run- → Invoke- o Start-
Execute- → Invoke-
Check- → Test-
Verify- → Test-
Clean- → Clear- o Remove-
Build- → New- o Invoke-Build
Compile- → Build- (como sustantivo) o Invoke-Build
Generate- → New-
Make- → New-
2. CONVENCIONES DE NOMENCLATURA¶
Funciones y Cmdlets¶
# Formato: Verbo-PrefixSustantivo
Get-ALPath # AL = AudioLab prefix
New-ALPlugin # Sustantivo singular
Remove-ALBuildCache # PascalCase
Test-ALEnvironment # Sin guiones bajos
# Funciones privadas/internas
function script:Get-InternalData { } # Scope explícito
function _HelperFunction { } # O con underscore
Variables¶
# Variables locales - camelCase
$localVariable = "value"
$pluginCount = 0
# Variables globales - PascalCase con prefijo
$global:ALRootPath = "C:\AudioLab"
$script:CacheData = @{}
# Constantes - UPPER_SNAKE_CASE
$AUDIOLAB_VERSION = "3.0"
$MAX_RETRY_COUNT = 3
# Hashtables/Diccionarios
$config = @{
PluginName = "TestPlugin" # Keys en PascalCase
BuildType = "Release"
}
Parámetros¶
param(
[string]$PluginName, # PascalCase
[switch]$Force, # Switches sin valor
[int]$TimeoutSeconds = 30 # Unidades en el nombre
)
3. ESTRUCTURA DE ARCHIVOS¶
Scripts PowerShell¶
06_BRAIN/src/1_scripts/
├── 0_ADMIN/ # Mayúsculas para categorías
├── 1_GENERATORS/
├── LIB/
│ ├── HELPERS/ # Módulos reutilizables (.psm1)
│ ├── EXTENSIONS/ # Extensiones del sistema
│ └── COMMON/ # Funciones compartidas
├── ops.ps1 # Minúsculas para scripts principales
└── bootstrap.ps1
Nomenclatura de archivos¶
# Scripts ejecutables
new_plugin.ps1 # snake_case para scripts
build_latest_plugin.ps1
# Módulos
AL.Paths.psm1 # PascalCase con prefijo
AL.CMake.psm1
AL.Logging.psm1
# Configuración
config.json # Minúsculas
settings.yaml
.env
# Temporales/Cache
_cache/ # Underscore para temporales
_tmp/
.build/ # Dot para ocultos
4. DOCUMENTACIÓN¶
Comentarios de función¶
function Get-ALBuildStatus {
<#
.SYNOPSIS
Obtiene el estado actual del build
.DESCRIPTION
Consulta CMakeCache.txt y determina el estado
del último build, incluyendo errores y warnings
.PARAMETER PluginName
Nombre del plugin a consultar
.PARAMETER Detailed
Incluir información detallada de compilación
.EXAMPLE
Get-ALBuildStatus -PluginName "TS_Reverb"
.OUTPUTS
[PSCustomObject] con propiedades Status, Errors, Warnings
.NOTES
Requiere que exista CMakeCache.txt
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$PluginName,
[switch]$Detailed
)
# Implementation...
}
Comentarios inline¶
# Sección principal
# ================
# TODO: Implementar caché de resultados
# FIXME: Corregir path en Windows
# HACK: Workaround temporal para bug de CMake
# NOTE: Este comportamiento es intencional
# DEPRECATED: Usar Get-ALPath en su lugar
# Evitar comentarios obvios
$count++ # MAL: Incrementar contador
$count++ # BIEN: Máximo 100 iteraciones por límite de API
5. GESTIÓN DE ERRORES¶
Try-Catch estructurado¶
function Invoke-ALBuild {
[CmdletBinding()]
param([string]$Target)
# Validación de entrada
if (-not $Target) {
throw [System.ArgumentNullException]::new('Target')
}
try {
# Operación principal
$result = Start-Process cmake -ArgumentList $Target -Wait -PassThru
if ($result.ExitCode -ne 0) {
throw "Build failed with exit code: $($result.ExitCode)"
}
}
catch [System.IO.IOException] {
Write-Error "IO Error: $_"
throw
}
catch {
Write-Error "Unexpected error in Invoke-ALBuild: $_"
throw
}
finally {
# Limpieza siempre se ejecuta
Remove-Item temp -ErrorAction SilentlyContinue
}
}
Manejo de warnings¶
# Suprimir warnings específicos
Import-Module $module -WarningAction SilentlyContinue
# Capturar warnings
$warnings = @()
Import-Module $module -WarningVariable warnings
# Acción preferida para errores
$ErrorActionPreference = 'Stop' # Scripts críticos
$ErrorActionPreference = 'Continue' # Scripts de reporte
6. LOGGING Y OUTPUT¶
Niveles de mensaje¶
Write-Host "✅ Operación exitosa" -ForegroundColor Green # UI/Éxito
Write-Host "⚠️ Advertencia" -ForegroundColor Yellow # Warnings
Write-Host "❌ Error crítico" -ForegroundColor Red # Errores
Write-Host "🔍 Procesando..." -ForegroundColor Cyan # Info
Write-Verbose "Detalles de debug" # -Verbose
Write-Debug "Variable value: $var" # -Debug
Write-Information "Log estructurado" -InformationAction Continue
Formato de salida¶
# Tablas para datos estructurados
$results | Format-Table -AutoSize
# Listas para detalles
$object | Format-List *
# JSON para interoperabilidad
$data | ConvertTo-Json -Depth 3
# CSV para reportes
$data | Export-Csv -Path report.csv -NoTypeInformation
7. MODULARIZACIÓN¶
Estructura de módulo (.psm1)¶
#Requires -Version 5.1
using namespace System.IO
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
# Variables privadas del módulo
$script:ModuleData = @{}
# Funciones públicas
function Get-PublicFunction {
# Exportada
}
# Funciones privadas
function script:Get-PrivateHelper {
# No exportada
}
# Inicialización
Initialize-Module
# Export explícito
Export-ModuleMember -Function @(
'Get-PublicFunction'
'Set-PublicData'
) -Variable @() -Alias @()
8. TESTING Y VALIDACIÓN¶
Validación de parámetros¶
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$Name,
[ValidateSet('Debug','Release')]
[string]$BuildType = 'Release',
[ValidateRange(1,100)]
[int]$Threads = 4,
[ValidateScript({
Test-Path $_ -PathType Container
})]
[string]$Path
)
Asserts y validaciones¶
function Assert-ALEnvironment {
# Verificar prerrequisitos
if (-not (Get-Command cmake -ErrorAction SilentlyContinue)) {
throw "CMake no está instalado"
}
# Verificar rutas
$buildPath = Get-ALPath -Key 'varBuild' -MustExist
# Verificar estado
if (-not (Test-Path CMakeCache.txt)) {
throw "Proyecto no configurado. Ejecuta 'ops configure'"
}
}
9. PERFORMANCE Y OPTIMIZACIÓN¶
Caché y memoización¶
$script:Cache = @{}
function Get-ExpensiveData {
param([string]$Key)
if (-not $script:Cache.ContainsKey($Key)) {
$script:Cache[$Key] = Compute-ExpensiveOperation $Key
}
return $script:Cache[$Key]
}
Pipeline eficiente¶
# BIEN: Un solo pipeline
Get-ChildItem -Recurse -Filter *.ps1 |
Where-Object Length -gt 1000 |
Select-Object Name, Length
# MAL: Múltiples asignaciones
$files = Get-ChildItem -Recurse
$filtered = $files | Where-Object { $_.Extension -eq '.ps1' }
$large = $filtered | Where-Object { $_.Length -gt 1000 }
10. INTEGRACIÓN CI/CD¶
Variables de entorno¶
# Nomenclatura estándar
$env:AUDIOLAB_ROOT
$env:AUDIOLAB_BUILD_TYPE
$env:AUDIOLAB_VERSION
# Detección de CI
$IsCI = $env:CI -eq 'true' -or $env:TF_BUILD -eq 'True'
$IsGitHub = $env:GITHUB_ACTIONS -eq 'true'
$IsAzure = $null -ne $env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI
Exit codes¶
# Estándar de salida
exit 0 # Éxito
exit 1 # Error general
exit 2 # Uso incorrecto
exit 3 # Configuración inválida
exit 127 # Comando no encontrado
CHECKLIST DE REVISIÓN¶
Antes de commit: - [ ] Verbos aprobados en funciones públicas - [ ] Comentarios de ayuda en funciones exportadas - [ ] Manejo de errores con try-catch - [ ] Sin credenciales hardcodeadas - [ ] Variables con nombres descriptivos - [ ] Salidas con Write-Host para UI, Write-Output para datos - [ ] Export explícito en módulos - [ ] Validación de parámetros críticos - [ ] Pruebas manuales básicas ejecutadas