-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathentrypoints.go
More file actions
348 lines (323 loc) · 11.3 KB
/
entrypoints.go
File metadata and controls
348 lines (323 loc) · 11.3 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
package main
import (
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
)
func entrypointPath(manager bool) string {
root := defaultInstallRoot()
name := silentName
if manager {
name = managerName
}
switch runtime.GOOS {
case "darwin":
return filepath.Join(root, name+".app")
case "windows":
return filepath.Join(root, name+".lnk")
default:
return filepath.Join(root, name+".desktop")
}
}
func (s *server) installEntrypoints() commandResult {
err := installEntrypoints()
if err != nil {
return installActionResult("failed", err.Error())
}
return installActionResult("ok", "入口已安装。")
}
func (s *server) uninstallEntrypoints(args map[string]any) commandResult {
options := mapArg(args, "options")
removeOwnedData := boolArg(options, "removeOwnedData")
err := uninstallEntrypoints()
if err == nil && removeOwnedData {
_ = os.RemoveAll(stateDir())
}
if err != nil {
return installActionResult("failed", err.Error())
}
return installActionResult("ok", "入口已卸载。")
}
func installActionResult(status, message string) commandResult {
return commandResult{
"status": status,
"message": message,
"silent_shortcut": shortcutInstallState(entrypointPath(false)),
"management_shortcut": shortcutInstallState(entrypointPath(true)),
}
}
func shortcutInstallState(path string) map[string]any {
return map[string]any{"installed": fileExists(path), "path": path}
}
func installEntrypoints() error {
switch runtime.GOOS {
case "darwin":
if err := writeMacOSAppBundle(false); err != nil {
return err
}
return writeMacOSAppBundle(true)
case "windows":
if err := createWindowsShortcut(entrypointPath(false), companionBinaryPath(silentBinary+".exe"), "Launch Codex++ silently"); err != nil {
return err
}
return createWindowsShortcut(entrypointPath(true), companionBinaryPath(managerBinary+".exe"), "Open Codex++ management tool")
default:
if err := writeDesktopEntry(false); err != nil {
return err
}
return writeDesktopEntry(true)
}
}
func uninstallEntrypoints() error {
var firstErr error
for _, path := range []string{entrypointPath(false), entrypointPath(true)} {
if err := os.RemoveAll(path); err != nil && firstErr == nil && !errors.Is(err, os.ErrNotExist) {
firstErr = err
}
}
return firstErr
}
func writeMacOSAppBundle(manager bool) error {
appPath := entrypointPath(manager)
contents := filepath.Join(appPath, "Contents")
macos := filepath.Join(contents, "MacOS")
resources := filepath.Join(contents, "Resources")
if err := os.MkdirAll(macos, 0o755); err != nil {
return err
}
if err := os.MkdirAll(resources, 0o755); err != nil {
return err
}
displayName := silentName
executableName := "CodexPlusPlus"
binary := silentBinary
identifierSuffix := ""
if manager {
displayName = managerName
executableName = "CodexPlusPlusManager"
binary = managerBinary
identifierSuffix = ".manager"
}
plist := macOSInfoPlist(displayName, executableName, identifierSuffix)
if err := os.WriteFile(filepath.Join(contents, "Info.plist"), []byte(plist), 0o644); err != nil {
return err
}
target := companionBinaryPath(binary)
script := fmt.Sprintf("#!/bin/sh\nexport PATH=\"${PATH:-%s}:%s\"\nexec %q\n", defaultGUIPath, defaultGUIPath, target)
executable := filepath.Join(macos, executableName)
if err := os.WriteFile(executable, []byte(script), 0o755); err != nil {
return err
}
_ = copyFirstExistingFile([]string{
filepath.Join(filepath.Dir(target), "codex-plus-plus.icns"),
filepath.Join(filepath.Dir(target), "codex-plus-plus.png"),
}, resources)
return nil
}
func macOSInfoPlist(displayName, executableName, identifierSuffix string) string {
return fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key>
<string>%s</string>
<key>CFBundleDisplayName</key>
<string>%s</string>
<key>CFBundleIdentifier</key>
<string>com.bigpizzav3.codexplusplus%s</string>
<key>CFBundleVersion</key>
<string>%s</string>
<key>CFBundleShortVersionString</key>
<string>%s</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleExecutable</key>
<string>%s</string>
<key>CFBundleIconFile</key>
<string>codex-plus-plus</string>
<key>LSUIElement</key>
<true/>
<key>LSMinimumSystemVersion</key>
<string>12.0</string>
</dict>
</plist>`, displayName, displayName, identifierSuffix, version, version, executableName)
}
func copyFirstExistingFile(candidates []string, resources string) error {
for _, candidate := range candidates {
data, err := os.ReadFile(candidate)
if err != nil {
continue
}
return os.WriteFile(filepath.Join(resources, filepath.Base(candidate)), data, 0o644)
}
return nil
}
func createWindowsShortcut(shortcutPath, target, description string) error {
if runtime.GOOS != "windows" {
return errors.New("Windows shortcuts are only supported on Windows")
}
if err := os.MkdirAll(filepath.Dir(shortcutPath), 0o755); err != nil {
return err
}
script := fmt.Sprintf(`$shell = New-Object -ComObject WScript.Shell
$shortcut = $shell.CreateShortcut(%s)
$shortcut.TargetPath = %s
$shortcut.WorkingDirectory = %s
$shortcut.Description = %s
$shortcut.IconLocation = %s
$shortcut.Save()
`, psQuote(shortcutPath), psQuote(target), psQuote(filepath.Dir(target)), psQuote(description), psQuote(target))
return exec.Command("powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script).Run()
}
func createWindowsShortcutWithArgs(shortcutPath, target, arguments, description string) error {
if runtime.GOOS != "windows" {
return errors.New("Windows shortcuts are only supported on Windows")
}
if err := os.MkdirAll(filepath.Dir(shortcutPath), 0o755); err != nil {
return err
}
script := fmt.Sprintf(`$shell = New-Object -ComObject WScript.Shell
$shortcut = $shell.CreateShortcut(%s)
$shortcut.TargetPath = %s
$shortcut.Arguments = %s
$shortcut.WorkingDirectory = %s
$shortcut.Description = %s
$shortcut.IconLocation = %s
$shortcut.WindowStyle = 7
$shortcut.Save()
`, psQuote(shortcutPath), psQuote(target), psQuote(arguments), psQuote(filepath.Dir(target)), psQuote(description), psQuote(target))
return exec.Command("powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script).Run()
}
func windowsRegAddCurrentUserString(key, name, value string) error {
if runtime.GOOS != "windows" {
return errors.New("Windows registry is only supported on Windows")
}
return exec.Command("reg", "add", key, "/v", name, "/t", "REG_SZ", "/d", value, "/f").Run()
}
func windowsRegDeleteCurrentUserValue(key, name string) error {
if runtime.GOOS != "windows" {
return errors.New("Windows registry is only supported on Windows")
}
return exec.Command("reg", "delete", key, "/v", name, "/f").Run()
}
func psQuote(value string) string {
return "'" + strings.ReplaceAll(value, "'", "''") + "'"
}
func writeDesktopEntry(manager bool) error {
path := entrypointPath(manager)
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
name := silentName
binary := silentBinary
if manager {
name = managerName
binary = managerBinary
}
desktop := fmt.Sprintf("[Desktop Entry]\nType=Application\nName=%s\nExec=%s\nTerminal=false\n", name, companionBinaryPath(binary))
return os.WriteFile(path, []byte(desktop), 0o755)
}
func watcherPayload() map[string]any {
flag := filepath.Join(stateDir(), "watcher.disabled")
install := watcherInstallState()
return map[string]any{
"enabled": !fileExists(flag),
"disabled_flag": flag,
"platform": runtime.GOOS,
"install_supported": runtime.GOOS == "windows",
"run_value_name": watcherRunName,
"run_value": install.RunValue,
"startup_shortcut": install.ShortcutPath,
"launcher_path": install.LauncherPath,
"launcher_arguments": install.Arguments,
}
}
func watcherInstallState() watcherInstallPlan {
launcher := companionBinaryPath(silentBinary)
if runtime.GOOS == "windows" {
launcher += ".exe"
}
return buildWatcherInstallPlan(launcher, defaultWatcherDebugPort, watcherStartupShortcutPath())
}
func buildWatcherInstallPlan(launcherPath string, debugPort int, shortcutPath string) watcherInstallPlan {
arguments := fmt.Sprintf("--debug-port %d", debugPort)
return watcherInstallPlan{
LauncherPath: launcherPath,
Arguments: arguments,
RunValue: fmt.Sprintf("\"%s\" %s", strings.ReplaceAll(launcherPath, `"`, `\"`), arguments),
ShortcutPath: shortcutPath,
}
}
func watcherStartupShortcutPath() string {
appdata := os.Getenv("APPDATA")
if appdata == "" {
return ""
}
return filepath.Join(appdata, "Microsoft", "Windows", "Start Menu", "Programs", "Startup", watcherStartupLinkName)
}
func (s *server) installWatcher() commandResult {
payload := watcherPayload()
if runtime.GOOS != "windows" {
return failed("watcher 安装仅支持 Windows;macOS 只能手动从 Codex++ 入口启动并用启用/禁用控制本地标志。", payload)
}
install := watcherInstallState()
if install.ShortcutPath == "" {
return failed("安装 watcher 失败:无法定位 Windows 启动目录。", watcherPayload())
}
if !fileExists(install.LauncherPath) {
return failed("安装 watcher 失败:未找到静默启动器 "+install.LauncherPath, watcherPayload())
}
if err := windowsRegAddCurrentUserString(watcherRunKey, watcherRunName, install.RunValue); err != nil {
return failed("安装 watcher 失败:"+err.Error(), watcherPayload())
}
if err := createWindowsShortcutWithArgs(install.ShortcutPath, install.LauncherPath, install.Arguments, "Codex++ watcher"); err != nil {
return failed("安装 watcher 失败:"+err.Error(), watcherPayload())
}
spawnWatcherLauncher(install.LauncherPath, defaultWatcherDebugPort)
return ok("watcher 已安装。", watcherPayload())
}
func (s *server) uninstallWatcher() commandResult {
if runtime.GOOS != "windows" {
return ok("watcher 安装仅支持 Windows;当前平台没有需要移除的自动启动项。", watcherPayload())
}
if err := windowsRegDeleteCurrentUserValue(watcherRunKey, watcherRunName); err != nil {
// reg delete returns an error when the value does not exist; removal should remain idempotent.
_ = err
}
if shortcut := watcherStartupShortcutPath(); shortcut != "" {
_ = os.Remove(shortcut)
}
return ok("watcher 已移除。", watcherPayload())
}
func spawnWatcherLauncher(launcherPath string, debugPort int) {
if runtime.GOOS != "windows" {
return
}
cmd := exec.Command(launcherPath, "--debug-port", strconv.Itoa(debugPort))
cmd.Stdin = nil
cmd.Stdout = io.Discard
cmd.Stderr = io.Discard
_ = cmd.Start()
}
func (s *server) setWatcherDisabled(disabled bool) commandResult {
flag := filepath.Join(stateDir(), "watcher.disabled")
if disabled {
if err := os.MkdirAll(filepath.Dir(flag), 0o755); err != nil {
return failed("禁用 watcher 失败:"+err.Error(), watcherPayload())
}
if err := os.WriteFile(flag, []byte("disabled"), 0o644); err != nil {
return failed("禁用 watcher 失败:"+err.Error(), watcherPayload())
}
return ok("watcher 已禁用。", watcherPayload())
}
if err := os.Remove(flag); err != nil && !errors.Is(err, os.ErrNotExist) {
return failed("启用 watcher 失败:"+err.Error(), watcherPayload())
}
return ok("watcher 已启用。", watcherPayload())
}