-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathappconfig.go
More file actions
368 lines (335 loc) · 9.92 KB
/
appconfig.go
File metadata and controls
368 lines (335 loc) · 9.92 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
package sysproxy
import (
"bufio"
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
// AppName identifies a supported application for WriteAppConfig.
type AppName string
// Supported application names for WriteAppConfig and ClearAppConfig.
const (
AppCurl AppName = "curl" // ~/.curlrc
AppGit AppName = "git" // git config --global
AppNPM AppName = "npm" // npm config set
AppPip AppName = "pip" // ~/.config/pip/pip.conf
AppWget AppName = "wget" // ~/.wgetrc
)
// WriteAppConfig writes proxy settings to the tool-specific config for app.
// proxyURL must be a valid proxy URL (validated before writing).
//
// err := sysproxy.WriteAppConfig(sysproxy.AppGit, "http://proxy.example.com:8080")
func WriteAppConfig(app AppName, proxyURL string) error {
return WriteAppConfigContext(context.Background(), app, proxyURL)
}
// WriteAppConfigContext writes proxy settings to the tool-specific config for
// app. It aborts before side effects if ctx is already canceled.
// Context cancellation is honoured for AppGit and AppNPM (external commands);
// for AppCurl, AppPip and AppWget it is checked once before writing.
func WriteAppConfigContext(ctx context.Context, app AppName, proxyURL string) error {
if err := validateProxyURL(proxyURL); err != nil {
return err
}
ctx = normalizeContext(ctx)
if err := ctx.Err(); err != nil {
return err
}
var err error
switch app {
case AppCurl:
err = writeCurlRC(proxyURL)
case AppGit:
err = writeGitProxy(ctx, proxyURL)
case AppNPM:
err = writeNPMProxy(ctx, proxyURL)
case AppPip:
err = writePipConf(proxyURL)
case AppWget:
err = writeWgetRC(proxyURL)
default:
return fmt.Errorf("sysproxy: unsupported app %q", app)
}
logf("WriteAppConfig app=%s url=%s err=%v", app, proxyURL, err)
return err
}
// ClearAppConfig removes proxy settings from the tool-specific config for app.
func ClearAppConfig(app AppName) error {
return ClearAppConfigContext(context.Background(), app)
}
// ClearAppConfigContext removes proxy settings from the tool-specific config
// for app. It aborts before side effects if ctx is already canceled.
func ClearAppConfigContext(ctx context.Context, app AppName) error {
ctx = normalizeContext(ctx)
if err := ctx.Err(); err != nil {
return err
}
var err error
switch app {
case AppCurl:
err = clearCurlRC()
case AppGit:
err = clearGitProxy(ctx)
case AppNPM:
err = clearNPMProxy(ctx)
case AppPip:
err = clearPipConf()
case AppWget:
err = clearWgetRC()
default:
return fmt.Errorf("sysproxy: unsupported app %q", app)
}
logf("ClearAppConfig app=%s err=%v", app, err)
return err
}
// ── curl (~/.curlrc) ──────────────────────────────────────────────────────────
func writeCurlRC(proxyURL string) error {
path, err := userConfigFile(".curlrc")
if err != nil {
return err
}
return editKeyValueFile(path, "proxy", proxyURL, " = ")
}
func clearCurlRC() error {
path, err := userConfigFile(".curlrc")
if err != nil {
return err
}
return removeKeysFromFile(path, " = ", "proxy")
}
// ── git (git config --global) ─────────────────────────────────────────────────
func runGit(ctx context.Context, args ...string) error {
return exec.CommandContext(normalizeContext(ctx), "git", args...).Run() //nolint:gosec
}
func writeGitProxy(ctx context.Context, proxyURL string) error {
if !isAvailable("git") {
return fmt.Errorf("sysproxy: git not found in PATH")
}
if err := runGit(ctx, "config", "--global", "http.proxy", proxyURL); err != nil {
return fmt.Errorf("sysproxy: git config http.proxy: %w", err)
}
if err := runGit(ctx, "config", "--global", "https.proxy", proxyURL); err != nil {
return fmt.Errorf("sysproxy: git config https.proxy: %w", err)
}
return nil
}
func clearGitProxy(ctx context.Context) error {
if !isAvailable("git") {
return fmt.Errorf("sysproxy: git not found in PATH")
}
_ = runGit(ctx, "config", "--global", "--unset", "http.proxy")
_ = runGit(ctx, "config", "--global", "--unset", "https.proxy")
return nil
}
// ── npm (npm config set) ──────────────────────────────────────────────────────
func runNPM(ctx context.Context, args ...string) error {
return exec.CommandContext(normalizeContext(ctx), "npm", args...).Run() //nolint:gosec
}
func writeNPMProxy(ctx context.Context, proxyURL string) error {
if !isAvailable("npm") {
return fmt.Errorf("sysproxy: npm not found in PATH")
}
if err := runNPM(ctx, "config", "set", "proxy", proxyURL); err != nil {
return fmt.Errorf("sysproxy: npm config set proxy: %w", err)
}
if err := runNPM(ctx, "config", "set", "https-proxy", proxyURL); err != nil {
return fmt.Errorf("sysproxy: npm config set https-proxy: %w", err)
}
return nil
}
func clearNPMProxy(ctx context.Context) error {
if !isAvailable("npm") {
return fmt.Errorf("sysproxy: npm not found in PATH")
}
_ = runNPM(ctx, "config", "delete", "proxy")
_ = runNPM(ctx, "config", "delete", "https-proxy")
return nil
}
// ── pip (~/.config/pip/pip.conf) ─────────────────────────────────────────────
func writePipConf(proxyURL string) error {
path, err := pipConfPath()
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return err
}
return editINIFile(path, "global", "proxy", proxyURL)
}
func clearPipConf() error {
path, err := pipConfPath()
if err != nil {
return err
}
return removeINIKey(path, "global", "proxy")
}
func pipConfPath() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, ".config", "pip", "pip.conf"), nil
}
// ── wget (~/.wgetrc) ──────────────────────────────────────────────────────────
func writeWgetRC(proxyURL string) error {
path, err := userConfigFile(".wgetrc")
if err != nil {
return err
}
if err := editKeyValueFile(path, "http_proxy", proxyURL, " = "); err != nil {
return err
}
return editKeyValueFile(path, "https_proxy", proxyURL, " = ")
}
func clearWgetRC() error {
path, err := userConfigFile(".wgetrc")
if err != nil {
return err
}
return removeKeysFromFile(path, " = ", "http_proxy", "https_proxy")
}
// ── shared file helpers ───────────────────────────────────────────────────────
func userConfigFile(name string) (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, name), nil
}
// editKeyValueFile sets key=value in a simple key<sep>value file, replacing any
// existing line with the same key and appending if absent.
func editKeyValueFile(path, key, value, sep string) error {
lines, err := readLines(path)
if err != nil && !os.IsNotExist(err) {
return err
}
prefix := key + sep
found := false
for i, l := range lines {
if strings.HasPrefix(l, prefix) {
lines[i] = prefix + value
found = true
}
}
if !found {
lines = append(lines, prefix+value)
}
return writeLines(path, lines)
}
// removeKeysFromFile removes all lines whose key (before sep) matches any of keys.
func removeKeysFromFile(path, sep string, keys ...string) error {
lines, err := readLines(path)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
keySet := make(map[string]bool, len(keys))
for _, k := range keys {
keySet[k] = true
}
var kept []string
for _, l := range lines {
k := strings.SplitN(l, sep, 2)[0]
if !keySet[strings.TrimSpace(k)] {
kept = append(kept, l)
}
}
return writeLines(path, kept)
}
// editINIFile sets [section] key = value in an INI-style file.
func editINIFile(path, section, key, value string) error {
lines, err := readLines(path)
if err != nil && !os.IsNotExist(err) {
return err
}
header := "[" + section + "]"
entry := key + " = " + value
inSection := false
found := false
for i, l := range lines {
trimmed := strings.TrimSpace(l)
if trimmed == header {
inSection = true
continue
}
if strings.HasPrefix(trimmed, "[") {
inSection = false
}
if inSection && strings.HasPrefix(trimmed, key+" ") {
lines[i] = entry
found = true
}
}
if !found {
// Append section header if missing, then the key.
hasHeader := false
for _, l := range lines {
if strings.TrimSpace(l) == header {
hasHeader = true
break
}
}
if !hasHeader {
lines = append(lines, header)
}
lines = append(lines, entry)
}
return writeLines(path, lines)
}
// removeINIKey removes key from [section] in an INI file.
func removeINIKey(path, section, key string) error {
lines, err := readLines(path)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
header := "[" + section + "]"
inSection := false
var kept []string
for _, l := range lines {
trimmed := strings.TrimSpace(l)
if trimmed == header {
inSection = true
kept = append(kept, l)
continue
}
if strings.HasPrefix(trimmed, "[") {
inSection = false
}
if inSection && strings.HasPrefix(trimmed, key) {
continue
}
kept = append(kept, l)
}
return writeLines(path, kept)
}
func readLines(path string) ([]string, error) {
f, err := os.Open(path) //nolint:gosec
if err != nil {
return nil, err
}
defer func() {
if err := f.Close(); err != nil {
logf("appconfig: close error: %v", err)
}
}()
var lines []string
sc := bufio.NewScanner(f)
for sc.Scan() {
lines = append(lines, sc.Text())
}
return lines, sc.Err()
}
func writeLines(path string, lines []string) error {
content := strings.Join(lines, "\n")
if len(lines) > 0 {
content += "\n"
}
return os.WriteFile(path, []byte(content), 0o600)
}