-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwakatime.go
97 lines (84 loc) · 2.56 KB
/
wakatime.go
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
package main
import (
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
)
// SendHeartbeat launches a goroutine that checks for the wakatime CLI
// and, if found, runs it in the background with the --write flag to send a heartbeat.
// filename: the path (or name) of the file that triggered the heartbeat
// project: the name of the project
func SendHeartbeat(filename, project string) {
go func() {
if project == "" {
detectedProject, err := detectProjectName(filename)
if err != nil {
log.Printf("Warning: failed to detect project name: %v", err)
} else {
project = detectedProject
}
}
cli, err := findWakaTimeCLI()
if err != nil {
return
}
cmd := exec.Command(
cli,
"--write",
"--entity", filename,
"--project", project,
"--plugin", ApplicationName+"/"+ApplicationVersion,
"--category", "planning",
)
if err := cmd.Run(); err != nil {
log.Printf("Error sending heartbeat via WakaTime CLI: %v\n", err)
}
}()
}
// findWakaTimeCLI searches for the WakaTime CLI in the following order:
// 1. "wakatime-cli" in the current PATH
// 2. "wakatime" in the current PATH
// 3. "~/.wakatime/wakatime-cli" (expanding ~ to the user's home directory)
//
// If found, returns the absolute path to the CLI. Otherwise returns an error.
func findWakaTimeCLI() (string, error) {
if cliPath, err := exec.LookPath("wakatime-cli"); err == nil {
return cliPath, nil
}
if cliPath, err := exec.LookPath("wakatime"); err == nil {
return cliPath, nil
}
homeDir, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("failed to determine home directory: %w", err)
}
fallbackPath := filepath.Join(homeDir, ".wakatime", "wakatime-cli")
if fi, err := os.Stat(fallbackPath); err == nil && !fi.IsDir() {
return fallbackPath, nil
}
return "", fmt.Errorf("wakatime CLI not found in PATH or at %s", fallbackPath)
}
// detectProjectName walks up from filename's directory until it finds a .git folder.
// If found, returns the name of that directory (which we treat as the project name).
// If not found, returns the immediate parent folder’s name as a fallback.
func detectProjectName(filename string) (string, error) {
absPath, err := filepath.Abs(filename)
if err != nil {
return "", err
}
dir := filepath.Dir(absPath)
// Walk up the directory tree until root or until .git is found
for {
gitPath := filepath.Join(dir, ".git")
if fi, err := os.Stat(gitPath); err == nil && fi.IsDir() {
return filepath.Base(dir), nil
}
parent := filepath.Dir(dir)
if parent == dir {
return filepath.Base(dir), nil
}
dir = parent
}
}