main
Raw Download raw file
 1package bashrcd
 2
 3import (
 4	_ "embed"
 5	"bufio"
 6	"fmt"
 7	"os"
 8	"path/filepath"
 9	"strings"
10)
11
12//go:embed bashrc.part
13var bashrcPart string
14
15const (
16	startMarker = "# BEGIN BINDLE MANAGED SECTION"
17	endMarker   = "# END BINDLE MANAGED SECTION"
18)
19
20// Install ensures the bashrc.part content is properly integrated into ~/.bashrc
21// without duplication, using markers to manage the section
22func Install() error {
23	homeDir := os.Getenv("HOME")
24	bashrcPath := filepath.Join(homeDir, ".bashrc")
25
26	// Read existing bashrc or create empty content
27	var lines []string
28	if _, err := os.Stat(bashrcPath); err == nil {
29		file, err := os.Open(bashrcPath)
30		if err != nil {
31			return fmt.Errorf("opening bashrc: %w", err)
32		}
33		defer file.Close()
34
35		scanner := bufio.NewScanner(file)
36		for scanner.Scan() {
37			lines = append(lines, scanner.Text())
38		}
39		if err := scanner.Err(); err != nil {
40			return fmt.Errorf("reading bashrc: %w", err)
41		}
42	}
43
44	// Find and remove existing bindle section
45	var newLines []string
46	inBindleSection := false
47	
48	for _, line := range lines {
49		if strings.Contains(line, startMarker) {
50			inBindleSection = true
51			continue
52		}
53		if strings.Contains(line, endMarker) {
54			inBindleSection = false
55			continue
56		}
57		if !inBindleSection {
58			newLines = append(newLines, line)
59		}
60	}
61
62	// Add bindle section at the end
63	newLines = append(newLines, "")
64	newLines = append(newLines, startMarker)
65	
66	// Add each line from bashrc.part
67	partLines := strings.Split(strings.TrimSpace(bashrcPart), "\n")
68	for _, line := range partLines {
69		newLines = append(newLines, line)
70	}
71	
72	newLines = append(newLines, endMarker)
73
74	// Write back to bashrc
75	file, err := os.Create(bashrcPath)
76	if err != nil {
77		return fmt.Errorf("creating bashrc: %w", err)
78	}
79	defer file.Close()
80
81	for _, line := range newLines {
82		if _, err := fmt.Fprintln(file, line); err != nil {
83			return fmt.Errorf("writing bashrc: %w", err)
84		}
85	}
86
87	return nil
88}