-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
508 lines (419 loc) · 12.8 KB
/
main.go
File metadata and controls
508 lines (419 loc) · 12.8 KB
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
package main
import (
"archive/zip"
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
)
// Build-time variables (set during build)
var (
Version = "dev"
BuildTime = "unknown"
)
// Constants
const (
githubUsername = "divyanshusahu"
repoName = "commit-celebration"
defaultVersion = "latest"
)
// getSoundsPackURL returns the URL for the sounds pack based on version
func getSoundsPackURL(version string) string {
return fmt.Sprintf("https://github.com/%s/%s/releases/download/%s/sounds-pack.zip",
githubUsername, repoName, version)
}
// getEffectiveVersion returns the version to use for downloading sounds
func getEffectiveVersion() string {
if Version != "dev" && Version != "" {
return Version
}
// Try to get latest release using GitHub API
if latestVersion := getLatestReleaseVersion(); latestVersion != "" {
return latestVersion
}
// Fallback to default
return defaultVersion
}
// getLatestReleaseVersion fetches the latest release version from GitHub API
func getLatestReleaseVersion() string {
url := fmt.Sprintf("https://api.github.com/repos/%s/%s/releases/latest", githubUsername, repoName)
resp, err := http.Get(url)
if err != nil {
return ""
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return ""
}
var release struct {
TagName string `json:"tag_name"`
}
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
return ""
}
return release.TagName
}
func main() {
// Handle version command
if len(os.Args) > 1 && os.Args[1] == "version" {
fmt.Printf("commit-celebration %s\n", Version)
fmt.Printf("Built: %s\n", BuildTime)
fmt.Printf("Repository: https://github.com/%s/%s\n", githubUsername, repoName)
return
}
// Handle update command
if len(os.Args) > 1 && os.Args[1] == "update" {
// 1) Update binary to latest release
if err := updateBinary(); err != nil {
fmt.Printf("Warning: binary update skipped or failed: %v\n", err)
} else {
fmt.Println("Binary updated to latest release.")
}
// 2) Update sounds pack
if err := updateSounds(); err != nil {
fmt.Printf("Error updating sounds: %v\n", err)
os.Exit(1)
}
fmt.Println("Sounds updated successfully!")
return
}
// Handle install command
if len(os.Args) > 1 && os.Args[1] == "install" {
if err := installGlobalHook(); err != nil {
fmt.Printf("Error installing global hook: %v\n", err)
os.Exit(1)
}
fmt.Println("Global git hook installed successfully!")
fmt.Println("This will now work for all your git repositories!")
return
}
// Handle uninstall command
if len(os.Args) > 1 && os.Args[1] == "uninstall" {
if err := uninstallGlobalHook(); err != nil {
fmt.Printf("Error uninstalling global hook: %v\n", err)
os.Exit(1)
}
fmt.Println("Global git hook uninstalled successfully!")
return
}
// Normal execution (called by git hook)
soundFile, err := selectRandomSound()
if err != nil {
fmt.Printf("Error selecting sound: %v\n", err)
return
}
if err := playSound(soundFile); err != nil {
fmt.Printf("Error playing sound: %v\n", err)
return
}
}
func selectRandomSound() (string, error) {
// Ensure sounds are available locally
soundFiles, err := ensureSoundsAvailable()
if err != nil {
return "", fmt.Errorf("failed to get sound files: %v", err)
}
if len(soundFiles) == 0 {
return "", fmt.Errorf("no sounds available")
}
// Select a random sound
selectedSound := soundFiles[rand.Intn(len(soundFiles))]
soundsDir := getSoundsDir()
soundPath := filepath.Join(soundsDir, selectedSound)
return soundPath, nil
}
func ensureSoundsAvailable() ([]string, error) {
soundsDir := getSoundsDir()
// Check if sounds directory exists and has files
if files := getSoundFiles(soundsDir); len(files) > 0 {
return files, nil
}
// Download and extract sounds pack
fmt.Println("Downloading sounds pack...")
if err := downloadAndExtractSounds(); err != nil {
return nil, fmt.Errorf("failed to download sounds pack: %v", err)
}
// Get the extracted sound files
return getSoundFiles(soundsDir), nil
}
func getSoundFiles(dir string) []string {
var soundFiles []string
extensions := []string{".mp3", ".wav", ".m4a"}
if _, err := os.Stat(dir); os.IsNotExist(err) {
return soundFiles
}
entries, err := os.ReadDir(dir)
if err != nil {
return soundFiles
}
for _, entry := range entries {
if !entry.IsDir() {
name := entry.Name()
for _, ext := range extensions {
if strings.HasSuffix(strings.ToLower(name), ext) {
soundFiles = append(soundFiles, name)
break
}
}
}
}
return soundFiles
}
func downloadAndExtractSounds() error {
soundsDir := getSoundsDir()
zipPath := filepath.Join(soundsDir, "sounds-pack.zip")
// Create sounds directory
if err := os.MkdirAll(soundsDir, 0o755); err != nil {
return fmt.Errorf("failed to create sounds directory: %v", err)
}
// Get the effective version and build download URL
version := getEffectiveVersion()
soundsPackURL := getSoundsPackURL(version)
fmt.Printf("Downloading sounds pack from version: %s\n", version)
// Download zip file
if err := downloadFile(soundsPackURL, zipPath); err != nil {
return fmt.Errorf("failed to download sounds pack: %v", err)
}
// Extract zip file
if err := extractZip(zipPath, soundsDir); err != nil {
return fmt.Errorf("failed to extract sounds pack: %v", err)
}
// Remove zip file after extraction
os.Remove(zipPath)
return nil
}
func extractZip(src, dest string) error {
r, err := zip.OpenReader(src)
if err != nil {
return err
}
defer r.Close()
// Extract files
for _, f := range r.File {
// Skip directories and hidden files
if f.FileInfo().IsDir() || strings.HasPrefix(f.Name, ".") {
continue
}
rc, err := f.Open()
if err != nil {
return err
}
path := filepath.Join(dest, f.Name)
// Create file
outFile, err := os.Create(path)
if err != nil {
rc.Close()
return err
}
// Copy file contents
_, err = io.Copy(outFile, rc)
outFile.Close()
rc.Close()
if err != nil {
return err
}
}
return nil
}
func downloadFile(url, filepath string) error {
// Create the file
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
// Get the data
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// Check for successful response
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s", resp.Status)
}
// Write the body to file
_, err = io.Copy(out, resp.Body)
return err
}
// updateSounds forces a fresh download of the sounds pack
func updateSounds() error {
soundsDir := getSoundsDir()
// Clear existing sounds
if err := os.RemoveAll(soundsDir); err != nil {
return fmt.Errorf("failed to clear existing sounds: %v", err)
}
// Download fresh sounds pack
fmt.Println("Downloading latest sounds pack...")
if err := downloadAndExtractSounds(); err != nil {
return fmt.Errorf("failed to download sounds pack: %v", err)
}
// Count new files
files := getSoundFiles(soundsDir)
fmt.Printf("Successfully updated! Found %d sound files.\n", len(files))
return nil
}
func getSoundsDir() string {
if Version == "dev" {
return "./sounds"
}
homeDir, err := os.UserHomeDir()
if err != nil {
return "./sounds"
}
return filepath.Join(homeDir, ".commit-celebration", "sounds")
}
// updateBinary downloads the latest release binary for the current OS/arch
// and replaces the current executable when possible.
func updateBinary() error {
// Determine latest version tag
latest := getLatestReleaseVersion()
if latest == "" {
return fmt.Errorf("could not resolve latest version from GitHub")
}
// Resolve OS/ARCH and asset name
osName := runtime.GOOS
arch := runtime.GOARCH
assetName := fmt.Sprintf("commit-celebration-%s-%s", osName, arch)
if osName == "windows" {
assetName += ".exe"
}
// Construct download URL for the asset
url := fmt.Sprintf("https://github.com/%s/%s/releases/download/%s/%s", githubUsername, repoName, latest, assetName)
// Current executable path
execPath, err := os.Executable()
if err != nil {
return fmt.Errorf("failed to locate current executable: %v", err)
}
// Download to a temporary file alongside the executable
dir := filepath.Dir(execPath)
tmpPath := filepath.Join(dir, ".commit-celebration.tmp")
if err := downloadFile(url, tmpPath); err != nil {
return fmt.Errorf("failed to download latest binary: %v", err)
}
// Ensure executable permissions on POSIX
if runtime.GOOS != "windows" {
if err := os.Chmod(tmpPath, 0o755); err != nil {
os.Remove(tmpPath)
return fmt.Errorf("failed to set executable permissions: %v", err)
}
}
// Attempt atomic replace
if runtime.GOOS == "windows" {
// On Windows, in-use executables cannot be replaced. Leave a .new file.
newPath := execPath + ".new"
// If a previous .new exists, remove it
_ = os.Remove(newPath)
if err := os.Rename(tmpPath, newPath); err != nil {
// Cleanup temp if rename fails
os.Remove(tmpPath)
return fmt.Errorf("cannot finalize update on Windows; wrote new binary to %s. Close running processes and replace manually", newPath)
}
return fmt.Errorf("new binary written to %s. Close shells using commit-celebration and replace the .exe manually", newPath)
}
// POSIX: rename over the current executable; the running process keeps the old inode
if err := os.Rename(tmpPath, execPath); err != nil {
os.Remove(tmpPath)
return fmt.Errorf("failed to replace executable: %v", err)
}
return nil
}
func playSound(soundFile string) error {
var cmd *exec.Cmd
switch runtime.GOOS {
case "darwin":
cmd = exec.Command("afplay", soundFile)
case "linux":
// Try multiple options for Linux
if _, err := exec.LookPath("paplay"); err == nil {
cmd = exec.Command("paplay", soundFile)
} else if _, err := exec.LookPath("aplay"); err == nil {
cmd = exec.Command("aplay", soundFile)
} else if _, err := exec.LookPath("mpg123"); err == nil {
cmd = exec.Command("mpg123", soundFile)
} else {
return fmt.Errorf("no suitable audio player found on Linux")
}
case "windows":
cmd = exec.Command("powershell", "-c", fmt.Sprintf("(New-Object Media.SoundPlayer '%s').PlaySync()", soundFile))
default:
return fmt.Errorf("unsupported operating system: %s", runtime.GOOS)
}
return cmd.Run()
}
func installGlobalHook() error {
// Get user's home directory
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("failed to get home directory: %v", err)
}
// Create global hooks directory
globalHooksDir := filepath.Join(homeDir, ".commit-celebration", "git-hooks")
if err := os.MkdirAll(globalHooksDir, 0o755); err != nil {
return fmt.Errorf("failed to create global hooks directory: %v", err)
}
// Get the path to the current executable
execPath, err := os.Executable()
if err != nil {
return fmt.Errorf("failed to get executable path: %v", err)
}
// Create the global hook content
hookContent := fmt.Sprintf(`#!/bin/bash
# Global post-commit hook for commit-celebration
"%s" &
`, execPath)
// Write the global hook file
hookPath := filepath.Join(globalHooksDir, "post-commit")
if err := os.WriteFile(hookPath, []byte(hookContent), 0o755); err != nil {
return fmt.Errorf("failed to write global hook file: %v", err)
}
// Configure git to use the global hooks directory
cmd := exec.Command("git", "config", "--global", "core.hooksPath", globalHooksDir)
if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to configure global hooks path: %v", err)
}
return nil
}
func uninstallGlobalHook() error {
// Get user's home directory
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("failed to get home directory: %v", err)
}
globalHooksDir := filepath.Join(homeDir, ".commit-celebration", "git-hooks")
hookPath := filepath.Join(globalHooksDir, "post-commit")
// Check if global hook exists
if _, err := os.Stat(hookPath); os.IsNotExist(err) {
return fmt.Errorf("global hook not found")
}
// Read the hook file to verify it's our hook
content, err := os.ReadFile(hookPath)
if err != nil {
return fmt.Errorf("failed to read global hook file: %v", err)
}
// Check if it contains commit-celebration
if !strings.Contains(string(content), "commit-celebration") {
return fmt.Errorf("global hook file doesn't appear to be a commit-celebration hook")
}
// Remove the global hook file
if err := os.Remove(hookPath); err != nil {
return fmt.Errorf("failed to remove global hook file: %v", err)
}
// Unset the global hooks path (this reverts to default behavior)
cmd := exec.Command("git", "config", "--global", "--unset", "core.hooksPath")
if err := cmd.Run(); err != nil {
// This might fail if the config wasn't set, which is okay
fmt.Println("Note: Global hooks path configuration may not have been reset")
}
// Try to remove the hooks directory if it's empty
if err := os.Remove(globalHooksDir); err != nil {
// This is okay - directory might not be empty or might not exist
}
return nil
}