summaryrefslogtreecommitdiff
path: root/scripts/sync-to-project.ps1
blob: 5c3fd9ce65dcb14a1e01d758bb901c681bc47c8e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# Script pour copier les fichiers de configuration vers le projet
# Lit files-config.txt et copie chaque fichier vers configs/{system}/

param(
    [string]$ConfigFile = "files-config.txt",
    [string]$MappingFile = "path-mapping.json"
)

$ErrorActionPreference = "Stop"

# Vérifier que le fichier de configuration existe
if (-not (Test-Path $ConfigFile)) {
    Write-Error "Le fichier de configuration '$ConfigFile' n'existe pas."
    exit 1
}

# Créer les répertoires de destination
$configsDir = "configs"
$windowsDir = Join-Path $configsDir "windows"
$wslDir = Join-Path $configsDir "wsl"

foreach ($dir in @($configsDir, $windowsDir, $wslDir)) {
    if (-not (Test-Path $dir)) {
        New-Item -ItemType Directory -Path $dir -Force | Out-Null
        Write-Host "Créé le répertoire: $dir"
    }
}

# Charger le mapping existant ou créer un nouveau
$mapping = @{
    windows = @{}
    wsl = @{}
}

if (Test-Path $MappingFile) {
    try {
        $existingMapping = Get-Content $MappingFile -Raw | ConvertFrom-Json
        if ($existingMapping.windows) {
            $mapping.windows = @{}
            $existingMapping.windows.PSObject.Properties | ForEach-Object {
                $mapping.windows[$_.Name] = $_.Value
            }
        }
        if ($existingMapping.wsl) {
            $mapping.wsl = @{}
            $existingMapping.wsl.PSObject.Properties | ForEach-Object {
                $mapping.wsl[$_.Name] = $_.Value
            }
        }
    } catch {
        Write-Warning "Impossible de charger le mapping existant, création d'un nouveau mapping."
    }
}

# Fonction pour résoudre un chemin Windows
function Resolve-WindowsPath {
    param([string]$path)
    
    # Remplacer les variables d'environnement
    $resolved = $path
    $resolved = $resolved -replace '%USERPROFILE%', $env:USERPROFILE
    $resolved = $resolved -replace '%APPDATA%', $env:APPDATA
    $resolved = $resolved -replace '%LOCALAPPDATA%', $env:LOCALAPPDATA
    $resolved = $resolved -replace '%HOME%', $env:HOME
    $resolved = $resolved -replace '%USERPROFILE%', $env:USERPROFILE
    
    # Remplacer les autres variables d'environnement
    $resolved = [System.Environment]::ExpandEnvironmentVariables($resolved)
    
    return $resolved
}

# Fonction pour résoudre un chemin WSL
function Resolve-WSLPath {
    param([string]$path)
    
    # Expansion de ~
    if ($path -match '^~') {
        $homePath = wsl bash -c "echo ~"
        $path = $path -replace '^~', $homePath
    }
    
    return $path
}

# Fonction pour obtenir le chemin relatif dans le projet
function Get-ProjectPath {
    param(
        [string]$system,
        [string]$originalPath
    )
    
    # Nettoyer le chemin original pour créer un nom de fichier sûr
    $safeName = $originalPath -replace '[\\/:*?"<>|]', '_'
    $safeName = $safeName -replace '^%', '' -replace '%$', ''
    $safeName = $safeName -replace '^~', 'home'
    
    # Si le chemin contient des séparateurs, préserver la structure
    if ($originalPath -match '[\\/]') {
        $parts = $originalPath -split '[\\/]'
        $fileName = $parts[-1]
        $parentDirs = $parts[0..($parts.Length - 2)] -join '_'
        if ($parentDirs) {
            $safeName = "${parentDirs}_${fileName}"
        } else {
            $safeName = $fileName
        }
    }
    
    return Join-Path "configs" $system $safeName
}

# Lire et traiter le fichier de configuration
$lines = Get-Content $ConfigFile | Where-Object { 
    $_ -notmatch '^\s*#' -and $_.Trim() -ne '' 
}

$copiedCount = 0
$skippedCount = 0
$errorCount = 0

foreach ($line in $lines) {
    $line = $line.Trim()
    if ($line -eq '' -or $line -match '^\s*#') {
        continue
    }
    
    # Parser la ligne: système|chemin
    if ($line -notmatch '^(\w+)\|(.+)$') {
        Write-Warning "Ligne ignorée (format invalide): $line"
        continue
    }
    
    $system = $matches[1]
    $originalPath = $matches[2]
    
    if ($system -notin @('windows', 'wsl')) {
        Write-Warning "Système invalide '$system' dans la ligne: $line"
        continue
    }
    
    try {
        # Résoudre le chemin selon le système
        if ($system -eq 'windows') {
            $resolvedPath = Resolve-WindowsPath $originalPath
        } else {
            # Pour WSL, utiliser wsl pour résoudre le chemin
            $wslPath = $originalPath
            if ($wslPath -match '^~') {
                $wslPath = wsl bash -c "echo $wslPath"
            }
            $resolvedPath = $wslPath
        }
        
        # Vérifier que le fichier existe
        if ($system -eq 'windows') {
            if (-not (Test-Path $resolvedPath)) {
                Write-Warning "Fichier introuvable: $resolvedPath (original: $originalPath)"
                $skippedCount++
                continue
            }
        } else {
            # Pour WSL, vérifier via wsl
            $exists = wsl test -f "$resolvedPath" 2>$null
            if ($LASTEXITCODE -ne 0) {
                Write-Warning "Fichier introuvable dans WSL: $resolvedPath (original: $originalPath)"
                $skippedCount++
                continue
            }
        }
        
        # Obtenir le chemin de destination dans le projet
        $projectPath = Get-ProjectPath $system $originalPath
        
        # Créer le répertoire parent si nécessaire
        $projectDir = Split-Path $projectPath -Parent
        if (-not (Test-Path $projectDir)) {
            New-Item -ItemType Directory -Path $projectDir -Force | Out-Null
        }
        
        # Copier le fichier
        if ($system -eq 'windows') {
            Copy-Item -Path $resolvedPath -Destination $projectPath -Force
        } else {
            # Pour WSL, utiliser wsl pour copier
            $wslSource = $resolvedPath
            $wslDest = (wsl wslpath -a $projectPath)
            wsl cp "$wslSource" "$wslDest"
            if ($LASTEXITCODE -ne 0) {
                # Fallback: utiliser PowerShell pour copier depuis WSL
                $tempFile = [System.IO.Path]::GetTempFileName()
                wsl cat "$wslSource" | Out-File -FilePath $tempFile -Encoding utf8
                Copy-Item -Path $tempFile -Destination $projectPath -Force
                Remove-Item $tempFile
            }
        }
        
        # Enregistrer le mapping
        $mapping[$system][$originalPath] = $projectPath
        
        Write-Host "Copié: $originalPath -> $projectPath"
        $copiedCount++
        
    } catch {
        Write-Error "Erreur lors du traitement de '$line': $_"
        $errorCount++
    }
}

# Sauvegarder le mapping
$mappingJson = @{
    windows = $mapping.windows
    wsl = $mapping.wsl
} | ConvertTo-Json -Depth 10

Set-Content -Path $MappingFile -Value $mappingJson -Encoding UTF8

Write-Host "`nRésumé:"
Write-Host "  Fichiers copiés: $copiedCount"
Write-Host "  Fichiers ignorés: $skippedCount"
Write-Host "  Erreurs: $errorCount"
Write-Host "  Mapping sauvegardé dans: $MappingFile"