cleanFileName removes invalid characters for filesystem and truncates long names
(name string)
| 1346 | |
| 1347 | // cleanFileName removes invalid characters for filesystem and truncates long names |
| 1348 | func cleanFileName(name string) string { |
| 1349 | // Replace invalid filesystem characters |
| 1350 | invalidChars := []string{"/", "\\", ":", "*", "?", "\"", "<", ">", "|"} |
| 1351 | cleanName := name |
| 1352 | |
| 1353 | for _, char := range invalidChars { |
| 1354 | cleanName = strings.ReplaceAll(cleanName, char, "_") |
| 1355 | } |
| 1356 | |
| 1357 | // Remove or replace other problematic characters |
| 1358 | cleanName = strings.ReplaceAll(cleanName, "&", "and") |
| 1359 | cleanName = strings.ReplaceAll(cleanName, "'", "") |
| 1360 | cleanName = strings.ReplaceAll(cleanName, "`", "") |
| 1361 | |
| 1362 | // Remove URLs that might have been concatenated with the name |
| 1363 | // Look for patterns like "https___" or "http___" and remove everything after |
| 1364 | if idx := strings.Index(cleanName, "https___"); idx != -1 { |
| 1365 | cleanName = cleanName[:idx] |
| 1366 | } else if idx := strings.Index(cleanName, "http___"); idx != -1 { |
| 1367 | cleanName = cleanName[:idx] |
| 1368 | } |
| 1369 | |
| 1370 | // Trim whitespace |
| 1371 | cleanName = strings.TrimSpace(cleanName) |
| 1372 | |
| 1373 | // Truncate filename if it's still too long (max 100 characters to be safe) |
| 1374 | maxLength := 100 |
| 1375 | if len(cleanName) > maxLength { |
| 1376 | cleanName = cleanName[:maxLength] |
| 1377 | // Try to truncate at a word boundary |
| 1378 | if lastSpace := strings.LastIndex(cleanName, " "); lastSpace > maxLength/2 { |
| 1379 | cleanName = cleanName[:lastSpace] |
| 1380 | } |
| 1381 | } |
| 1382 | |
| 1383 | return cleanName |
| 1384 | } |