installZshCompletion installs zsh completion
(verbose bool, cmd *cobra.Command)
| 236 | |
| 237 | // installZshCompletion installs zsh completion |
| 238 | func installZshCompletion(verbose bool, cmd *cobra.Command) error { |
| 239 | shellCompletionLog.Print("Installing zsh completion") |
| 240 | |
| 241 | // Generate completion script using Cobra |
| 242 | var buf bytes.Buffer |
| 243 | if err := cmd.GenZshCompletion(&buf); err != nil { |
| 244 | return fmt.Errorf("failed to generate zsh completion: %w", err) |
| 245 | } |
| 246 | |
| 247 | completionScript := buf.String() |
| 248 | |
| 249 | // Determine installation path |
| 250 | homeDir, err := os.UserHomeDir() |
| 251 | if err != nil { |
| 252 | return fmt.Errorf("failed to get home directory: %w", err) |
| 253 | } |
| 254 | |
| 255 | // Check for fpath directories |
| 256 | var completionPath string |
| 257 | |
| 258 | // Try user's local completion directory first |
| 259 | userCompletionDir := filepath.Join(homeDir, ".zsh", "completions") |
| 260 | // Use restrictive permissions (0750) following principle of least privilege |
| 261 | if err := os.MkdirAll(userCompletionDir, constants.DirPermSensitive); err != nil { |
| 262 | return fmt.Errorf("failed to create completion directory: %w", err) |
| 263 | } |
| 264 | completionPath = filepath.Join(userCompletionDir, "_gh-aw") |
| 265 | |
| 266 | // Write completion file |
| 267 | // Use restrictive permissions (0600) following principle of least privilege |
| 268 | if err := os.WriteFile(completionPath, []byte(completionScript), constants.FilePermSensitive); err != nil { |
| 269 | return fmt.Errorf("failed to write completion file: %w", err) |
| 270 | } |
| 271 | |
| 272 | fmt.Fprintln(os.Stderr, console.FormatSuccessMessage("Installed zsh completion to: "+completionPath)) |
| 273 | |
| 274 | // Check if .zshrc configures fpath |
| 275 | zshrcPath := filepath.Join(homeDir, ".zshrc") |
| 276 | // Clean and validate the path to prevent path traversal |
| 277 | cleanZshrcPath := filepath.Clean(zshrcPath) |
| 278 | if !filepath.IsAbs(cleanZshrcPath) { |
| 279 | shellCompletionLog.Printf("Invalid zshrc path (not absolute): %s", zshrcPath) |
| 280 | return fmt.Errorf("invalid zshrc path: %s", zshrcPath) |
| 281 | } |
| 282 | // #nosec G304 -- zshrcPath is constructed from trusted os.UserHomeDir() and a constant filename |
| 283 | zshrcContent, err := os.ReadFile(cleanZshrcPath) |
| 284 | needsFpath := true |
| 285 | if err == nil { |
| 286 | if strings.Contains(string(zshrcContent), userCompletionDir) { |
| 287 | needsFpath = false |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | if needsFpath { |
| 292 | fmt.Fprintln(os.Stderr, "") |
| 293 | fmt.Fprintln(os.Stderr, console.FormatInfoMessage("To enable completions, add the following to your ~/.zshrc:")) |
| 294 | fmt.Fprintln(os.Stderr, "") |
| 295 | fmt.Fprintf(os.Stderr, " fpath=(~/.zsh/completions $fpath)\n") |
no test coverage detected