MCPcopy Create free account
hub / github.com/WhyWhatHow/jenv / updateShellConfigFile

Function updateShellConfigFile

src/internal/env/env_unix.go:291–334  ·  view source on GitHub ↗

updateShellConfigFile 更新shell配置文件(bash/zsh/.profile通用)

(filePath, key, value, exportCmd string)

Source from the content-addressed store, hash-verified

289
290// updateShellConfigFile 更新shell配置文件(bash/zsh/.profile通用)
291func updateShellConfigFile(filePath, key, value, exportCmd string) error {
292 // 确保文件存在
293 if _, err := os.Stat(filePath); os.IsNotExist(err) {
294 if file, err := os.Create(filePath); err != nil {
295 return fmt.Errorf("failed to create config file %s: %v", filePath, err)
296 } else {
297 file.Close()
298 }
299 }
300
301 // 读取现有内容
302 content, err := os.ReadFile(filePath)
303 if err != nil {
304 return fmt.Errorf("failed to read config file %s: %v", filePath, err)
305 }
306
307 lines := strings.Split(string(content), "\n")
308 var newLines []string
309 keyFound := false
310 exportLine := fmt.Sprintf("%s %s=\"%s\"", exportCmd, key, value)
311 exportPrefix := fmt.Sprintf("%s %s=", exportCmd, key)
312
313 // 查找并更新现有的环境变量设置
314 for _, line := range lines {
315 trimmedLine := strings.TrimSpace(line)
316 if strings.HasPrefix(trimmedLine, exportPrefix) {
317 newLines = append(newLines, exportLine)
318 keyFound = true
319 } else {
320 newLines = append(newLines, line)
321 }
322 }
323
324 // 如果没有找到现有设置,添加新的
325 if !keyFound {
326 // 添加注释说明这是jenv设置的
327 newLines = append(newLines, "")
328 newLines = append(newLines, "# Added by jenv")
329 newLines = append(newLines, exportLine)
330 }
331
332 // 写回文件
333 return os.WriteFile(filePath, []byte(strings.Join(newLines, "\n")), 0644)
334}
335
336// updateFishConfigFile 更新fish配置文件
337func updateFishConfigFile(filePath, key, value string) error {

Callers 4

updateBashEnvironmentFunction · 0.70
updateZshEnvironmentFunction · 0.70
updateProfileEnvironmentFunction · 0.70

Calls

no outgoing calls

Tested by 1