ensureGitAttributes ensures that .gitattributes contains the entry to mark .lock.yml files as generated. It returns true if the file was modified, false if it was already up to date.
()
| 328 | // ensureGitAttributes ensures that .gitattributes contains the entry to mark .lock.yml files as generated. |
| 329 | // It returns true if the file was modified, false if it was already up to date. |
| 330 | func ensureGitAttributes() (bool, error) { |
| 331 | gitLog.Print("Ensuring .gitattributes is updated") |
| 332 | gitRoot, err := gitutil.FindGitRoot() |
| 333 | if err != nil { |
| 334 | return false, err // Not in a git repository, skip |
| 335 | } |
| 336 | |
| 337 | gitAttributesPath := filepath.Join(gitRoot, ".gitattributes") |
| 338 | lockYmlEntry := constants.WorkflowsLockYmlGitAttributesEntry |
| 339 | requiredEntries := []string{lockYmlEntry} |
| 340 | |
| 341 | // Read existing .gitattributes file if it exists |
| 342 | var lines []string |
| 343 | if content, err := os.ReadFile(gitAttributesPath); err == nil { |
| 344 | lines = strings.Split(string(content), "\n") |
| 345 | gitLog.Printf("Read existing .gitattributes with %d lines", len(lines)) |
| 346 | } else { |
| 347 | gitLog.Print("No existing .gitattributes file found") |
| 348 | } |
| 349 | |
| 350 | modified := false |
| 351 | for _, required := range requiredEntries { |
| 352 | found := false |
| 353 | for i, line := range lines { |
| 354 | trimmedLine := strings.TrimSpace(line) |
| 355 | if trimmedLine == required { |
| 356 | found = true |
| 357 | break |
| 358 | } |
| 359 | // Check for old format entries that need updating |
| 360 | if strings.HasPrefix(trimmedLine, constants.WorkflowsLockYmlGlob) && required == lockYmlEntry { |
| 361 | gitLog.Print("Updating old .gitattributes entry format") |
| 362 | lines[i] = lockYmlEntry |
| 363 | found = true |
| 364 | modified = true |
| 365 | break |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | if !found { |
| 370 | gitLog.Printf("Adding new .gitattributes entry: %s", required) |
| 371 | if len(lines) > 0 && lines[len(lines)-1] != "" { |
| 372 | lines = append(lines, "") |
| 373 | } |
| 374 | lines = append(lines, required) |
| 375 | modified = true |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | if !modified { |
| 380 | gitLog.Print(".gitattributes already contains required entries") |
| 381 | return false, nil |
| 382 | } |
| 383 | |
| 384 | // Write back to file with owner-only read/write permissions (0600) for security best practices |
| 385 | content := strings.Join(lines, "\n") |
| 386 | if err := os.WriteFile(gitAttributesPath, []byte(content), constants.FilePermSensitive); err != nil { |
| 387 | gitLog.Printf("Failed to write .gitattributes: %v", err) |