Files
matlab-python/CLAUDE_INTEGRATION.md
alex 77c0ad5e43 Add Claude Code batch/script integration
Created comprehensive guide and enhanced sync script for integrating Claude Code
into automated workflows:

1. CLAUDE_INTEGRATION.md:
   - 6 different integration options (CLI, file request, git hooks, GitHub Actions, API)
   - Detailed examples for each approach
   - Pros/cons and use case recommendations
   - Best practices and troubleshooting

2. sync_server_file_enhanced.sh:
   - Enhanced version of sync_server_file.sh
   - Automatic MATLAB file change detection
   - Intelligent module mapping (MATLAB → Python)
   - Auto-generates formatted request for Claude
   - Colored output with progress steps
   - Clipboard integration (xclip)
   - Editor auto-open option

Features:
 Detects which Python modules need updating
 Creates markdown request with diff preview
 Shows affected files and modules
 Copies request to clipboard automatically
 Provides step-by-step instructions
 Commits MATLAB changes with metadata

Workflow:
1. Run: ./sync_server_file_enhanced.sh
2. Script syncs MATLAB files from server
3. Auto-detects changes and creates request file
4. Open Claude Code and paste/provide the request
5. Claude updates Python code automatically
6. Validate with validation system

Typical usage:
  ./sync_server_file_enhanced.sh
  # → Generates CLAUDE_SYNC_REQUEST_YYYYMMDD_HHMMSS.md
  # → Copy to clipboard or open in editor
  # → Provide to Claude Code for automatic Python sync

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 16:03:21 +02:00

13 KiB

Integrazione Claude Code in Script Batch

Panoramica

Claude Code può essere integrato in script batch/shell per automatizzare l'aggiornamento del codice Python quando i file MATLAB vengono modificati.

Opzioni di Integrazione

Opzione 1: Claude Code CLI (se disponibile)

Se Claude Code ha una CLI:

#!/bin/bash

# Dopo sync MATLAB
CHANGED_FILES=$(git diff --staged --name-only | grep "\.m$")

if [ ! -z "$CHANGED_FILES" ]; then
    echo "File MATLAB modificati rilevati:"
    echo "$CHANGED_FILES"

    # Chiama Claude Code
    claude-code sync-matlab --files "$CHANGED_FILES" --auto-validate
fi

Opzione 2: File di Richiesta + Notifica

Script che genera richiesta automatica:

#!/bin/bash
# sync_and_notify.sh

# 1. Sync MATLAB files
rsync -avzm -e "ssh -p ${REMOTE_PORT}" \
  --include='*/' \
  --include='*.m' \
  --exclude='*' \
  "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_SRC}" "${LOCAL_DST}"

# 2. Rileva modifiche
cd "${LOCAL_DST}/matlab_func"
git add .
CHANGED_FILES=$(git diff --staged --name-only | grep "\.m$")

if [ -z "$CHANGED_FILES" ]; then
    echo "Nessun file MATLAB modificato"
    exit 0
fi

# 3. Crea file richiesta per Claude
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
REQUEST_FILE="/tmp/matlab_sync_request_${TIMESTAMP}.txt"

cat > "$REQUEST_FILE" <<EOF
# Richiesta Sincronizzazione MATLAB → Python
Data: $(date +"%Y-%m-%d %H:%M:%S")

## File MATLAB Modificati

$CHANGED_FILES

## Azione Richiesta
Aggiornare il codice Python corrispondente a questi file MATLAB.

## Dettagli Modifiche
$(git diff --staged $CHANGED_FILES | head -n 100)

## Commit Info
Commit MATLAB in attesa:
$(git log --oneline -1 2>/dev/null || echo "Primo commit")
EOF

echo "=========================================="
echo "File MATLAB modificati rilevati!"
echo "=========================================="
echo "$CHANGED_FILES"
echo ""
echo "Richiesta salvata in: $REQUEST_FILE"
echo ""
echo "Aprire Claude Code e fornire questo file per sincronizzare Python."
echo "=========================================="

# 4. Commit MATLAB changes
git commit -m "Sync from remote server: $(date +'%Y-%m-%d %H:%M:%S')"

# 5. Opzionale: copia negli appunti (se disponibile xclip)
if command -v xclip &> /dev/null; then
    cat "$REQUEST_FILE" | xclip -selection clipboard
    echo "✓ Richiesta copiata negli appunti"
fi

# 6. Opzionale: apri file in editor
if [ -n "$EDITOR" ]; then
    $EDITOR "$REQUEST_FILE"
fi

Opzione 3: Git Hook Automatico

File: .git/hooks/post-commit

#!/bin/bash
# Post-commit hook per notificare modifiche MATLAB

# Solo se il commit contiene file .m
MATLAB_FILES=$(git diff-tree --no-commit-id --name-only -r HEAD | grep "\.m$")

if [ -z "$MATLAB_FILES" ]; then
    exit 0
fi

# Crea notifica
HOOK_LOG="/tmp/matlab_changes_$(date +%Y%m%d).log"

cat >> "$HOOK_LOG" <<EOF

========================================
Commit: $(git rev-parse --short HEAD)
Date: $(date +"%Y-%m-%d %H:%M:%S")
========================================

File MATLAB modificati:
$MATLAB_FILES

Azione necessaria:
Sincronizzare codice Python con Claude Code

Comando rapido:
  cd $(pwd)
  cat "$HOOK_LOG"

========================================
EOF

echo "⚠️  File MATLAB modificati rilevati!"
echo "📝 Log salvato in: $HOOK_LOG"
echo ""
echo "File modificati:"
echo "$MATLAB_FILES"
echo ""
echo "→ Aprire Claude Code per sincronizzare Python"

Opzione 4: Integrazione con GitHub Actions / CI

File: .github/workflows/matlab-sync-notify.yml

name: MATLAB Sync Notification

on:
  push:
    paths:
      - '**.m'

jobs:
  notify-matlab-changes:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 2

      - name: Detect MATLAB changes
        id: changes
        run: |
          CHANGED_FILES=$(git diff --name-only HEAD~1 HEAD | grep "\.m$" || echo "")
          echo "files=$CHANGED_FILES" >> $GITHUB_OUTPUT
          echo "count=$(echo "$CHANGED_FILES" | wc -l)" >> $GITHUB_OUTPUT

      - name: Create Issue for Sync
        if: steps.changes.outputs.count > 0
        uses: actions/github-script@v6
        with:
          script: |
            const files = process.env.CHANGED_FILES.split('\n');
            const body = `
            ## 🔄 MATLAB Files Changed - Python Sync Required

            **Date**: ${new Date().toISOString()}
            **Commit**: ${{ github.sha }}

            ### Changed Files
            ${files.map(f => `- ${f}`).join('\n')}

            ### Action Required
            Please update corresponding Python code using Claude Code:

            1. Open Claude Code
            2. Provide this list of changed files
            3. Run validation after sync

            ### Quick Reference
            See [MATLAB_SYNC_GUIDE.md](../blob/main/MATLAB_SYNC_GUIDE.md) for mapping.
            `;

            github.rest.issues.create({
              owner: context.repo.owner,
              repo: context.repo.repo,
              title: '🔄 MATLAB Sync Required - ' + new Date().toLocaleDateString(),
              body: body,
              labels: ['matlab-sync', 'python-update']
            });

Opzione 5: Script Interattivo Avanzato

File: sync_with_claude.sh

#!/bin/bash
# Script di sincronizzazione con richiesta formattata per Claude

set -e

# Configurazione
REMOTE_USER="alex"
REMOTE_HOST="80.211.60.65"
REMOTE_PORT="2022"
REMOTE_SRC="/usr/local/matlab_func"
LOCAL_DST="/home/alex/devel/matlab-ase"
PYTHON_DIR="${LOCAL_DST}/matlab_func"

# Colori per output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}MATLAB → Python Sync Script${NC}"
echo -e "${BLUE}========================================${NC}"

# 1. Sync MATLAB files
echo -e "\n${YELLOW}[1/5]${NC} Sincronizzazione file MATLAB da server remoto..."
rsync -avzm -e "ssh -p ${REMOTE_PORT}" \
  --include='*/' \
  --include='*.m' \
  --exclude='*' \
  "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_SRC}" "${LOCAL_DST}"

if [ $? -ne 0 ]; then
    echo -e "${RED}✗ Errore durante sincronizzazione${NC}"
    exit 1
fi

echo -e "${GREEN}✓ Sincronizzazione completata${NC}"

# 2. Rileva modifiche
echo -e "\n${YELLOW}[2/5]${NC} Rilevamento modifiche..."
cd "${LOCAL_DST}/matlab_func"

# Backup dello stato attuale
git stash push -q -m "Pre-sync backup $(date +'%Y%m%d_%H%M%S')" || true

# Aggiungi file .m
find . -type f -name "*.m" -exec git add {} \;

# Ottieni lista modifiche
CHANGED_FILES=$(git diff --staged --name-only | grep "\.m$" || echo "")
CHANGED_COUNT=$(echo "$CHANGED_FILES" | grep -v '^$' | wc -l)

if [ -z "$CHANGED_FILES" ] || [ "$CHANGED_COUNT" -eq 0 ]; then
    echo -e "${GREEN}✓ Nessun file MATLAB modificato${NC}"
    git stash pop -q 2>/dev/null || true
    exit 0
fi

echo -e "${GREEN}✓ Rilevati ${CHANGED_COUNT} file modificati${NC}"

# 3. Analizza tipo di modifiche
echo -e "\n${YELLOW}[3/5]${NC} Analisi modifiche..."

declare -A module_map
module_map["CalcoloRSN"]="RSN"
module_map["CalcoloTLHR"]="Tilt"
module_map["CalcoloBL"]="Tilt"
module_map["CalcoloPL"]="Tilt"
module_map["CalcoloRL"]="ATD"
module_map["CalcoloLL"]="ATD"
module_map["CalcoloBiax"]="ATD"
module_map["CalcoloStella"]="ATD"
module_map["arot"]="Tilt"
module_map["asse_"]="Tilt"
module_map["database"]="Common"
module_map["carica"]="Common"

declare -A affected_modules
for file in $CHANGED_FILES; do
    basename=$(basename "$file" .m)
    for pattern in "${!module_map[@]}"; do
        if [[ "$basename" == *"$pattern"* ]]; then
            affected_modules[${module_map[$pattern]}]=1
        fi
    done
done

echo "Moduli Python interessati:"
for module in "${!affected_modules[@]}"; do
    echo -e "  ${BLUE}${NC} $module"
done

# 4. Crea richiesta formattata per Claude
echo -e "\n${YELLOW}[4/5]${NC} Generazione richiesta per Claude Code..."

REQUEST_FILE="${PYTHON_DIR}/SYNC_REQUEST_$(date +%Y%m%d_%H%M%S).md"

cat > "$REQUEST_FILE" <<EOF
# Richiesta Sincronizzazione MATLAB → Python

**Data**: $(date +"%Y-%m-%d %H:%M:%S")
**Commit MATLAB**: Pending
**File modificati**: ${CHANGED_COUNT}

---

## File MATLAB Modificati

\`\`\`
$CHANGED_FILES
\`\`\`

## Moduli Python Interessati

EOF

for module in "${!affected_modules[@]}"; do
    echo "- **${module}**" >> "$REQUEST_FILE"
done

cat >> "$REQUEST_FILE" <<EOF

---

## Diff Preview (primi 50 righe per file)

EOF

for file in $CHANGED_FILES; do
    if [ -f "$file" ]; then
        echo -e "\n### ${file}\n" >> "$REQUEST_FILE"
        echo '```matlab' >> "$REQUEST_FILE"
        git diff --staged "$file" | head -n 50 >> "$REQUEST_FILE"
        echo '```' >> "$REQUEST_FILE"
    fi
done

cat >> "$REQUEST_FILE" <<EOF

---

## Azione Richiesta

Aggiornare il codice Python corrispondente seguendo [MATLAB_SYNC_GUIDE.md](MATLAB_SYNC_GUIDE.md).

### Prossimi Step

1. Applicare modifiche Python equivalenti
2. Eseguire validazione:
   \`\`\`bash
   python -m src.validation.cli CU001 A --output validation_report.txt
   \`\`\`
3. Verificare report validazione
4. Commit con tag:
   \`\`\`bash
   git commit -m "Sync Python from MATLAB changes"
   git tag matlab-sync-$(date +%Y%m%d)
   \`\`\`

---

## Reference

- Mapping: [MATLAB_SYNC_GUIDE.md](MATLAB_SYNC_GUIDE.md)
- Quick ref: [sync_matlab_changes.md](sync_matlab_changes.md)

EOF

echo -e "${GREEN}✓ Richiesta salvata: ${REQUEST_FILE}${NC}"

# 5. Commit MATLAB changes
echo -e "\n${YELLOW}[5/5]${NC} Commit modifiche MATLAB..."
git commit -m "Sync from remote server: $(date +'%Y-%m-%d %H:%M:%S')" -m "Files changed: ${CHANGED_COUNT}" -m "$CHANGED_FILES"

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Commit MATLAB completato${NC}"
    MATLAB_COMMIT=$(git rev-parse --short HEAD)
    echo -e "   Commit hash: ${MATLAB_COMMIT}"
else
    echo -e "${RED}✗ Errore durante commit${NC}"
    exit 1
fi

# 6. Summary e istruzioni
echo -e "\n${BLUE}========================================${NC}"
echo -e "${BLUE}Sincronizzazione Completata${NC}"
echo -e "${BLUE}========================================${NC}"
echo -e "\n${GREEN}${NC} File MATLAB sincronizzati: ${CHANGED_COUNT}"
echo -e "${GREEN}${NC} Commit MATLAB: ${MATLAB_COMMIT}"
echo -e "${GREEN}${NC} Richiesta Claude: ${REQUEST_FILE}"

echo -e "\n${YELLOW}⚠️  Azione Richiesta:${NC}"
echo -e "   1. Aprire Claude Code"
echo -e "   2. Fornire il file: ${REQUEST_FILE}"
echo -e "   3. Claude aggiornerà Python automaticamente"
echo -e "   4. Validare risultato"

# Copia negli appunti se disponibile
if command -v xclip &> /dev/null; then
    cat "$REQUEST_FILE" | xclip -selection clipboard
    echo -e "\n${GREEN}${NC} Richiesta copiata negli appunti"
fi

# Opzione per aprire editor
echo -e "\n${BLUE}Premere ENTER per aprire la richiesta in editor...${NC}"
read -r
${EDITOR:-nano} "$REQUEST_FILE"

echo -e "\n${BLUE}========================================${NC}"
echo -e "${GREEN}Processo completato!${NC}"
echo -e "${BLUE}========================================${NC}"

Opzione 6: API Integration (se disponibile)

#!/bin/bash
# Integrazione tramite API Claude (ipotetica)

CLAUDE_API_KEY="your_api_key"
CHANGED_FILES=$(git diff --staged --name-only | grep "\.m$")

if [ ! -z "$CHANGED_FILES" ]; then
    # Crea payload JSON
    PAYLOAD=$(jq -n \
        --arg files "$CHANGED_FILES" \
        '{
            action: "sync-matlab",
            files: $files,
            auto_validate: true,
            create_commit: true
        }')

    # Chiama API Claude
    curl -X POST https://api.claude.ai/v1/code-sync \
        -H "Authorization: Bearer $CLAUDE_API_KEY" \
        -H "Content-Type: application/json" \
        -d "$PAYLOAD"
fi

Raccomandazioni

Per il Tuo Caso

Dato il tuo script sync_server_file.sh, consiglio:

Opzione Migliore: Script Interattivo Avanzato (Opzione 5)

Vantaggi:

  • Genera richiesta formattata automaticamente
  • Analizza quali moduli Python sono interessati
  • Mostra diff preview
  • Copia negli appunti per uso immediato
  • Istruzioni chiare per next step

Quick Start

  1. Sostituire il tuo sync_server_file.sh con sync_with_claude.sh
  2. Eseguire script
  3. Ottenere file markdown formattato con tutte le info
  4. Fornire file a Claude Code
  5. Claude aggiorna Python automaticamente

File di Output Example

Lo script genera file come questo:

# Richiesta Sincronizzazione MATLAB → Python

**Data**: 2025-10-13 16:30:00
**File modificati**: 3

## File MATLAB Modificati

- CalcoloBiax_TuL.m
- CalcoloRSN.m
- arot.m

## Moduli Python Interessati

- ATD
- RSN
- Tilt

## Azione Richiesta

Aggiornare codice Python...

Che posso facilmente leggere e processare!

Conclusione

Risposta: Sì! Ci sono multiple opzioni:

  1. Script che genera file di richiesta (consigliato)
  2. Git hooks per notifiche automatiche
  3. GitHub Actions per workflow CI/CD
  4. API calls (se disponibile CLI Claude)

La soluzione più pratica per te è lo script interattivo che genera una richiesta formattata che poi mi fornisci in Claude Code.

Vuoi che implementi una di queste soluzioni specificatamente per il tuo caso?