session.go

 1package tui
 2
 3import (
 4	"encoding/json"
 5	"fmt"
 6	"log"
 7	"soft-serve/git"
 8	"time"
 9
10	tea "github.com/charmbracelet/bubbletea"
11	"github.com/gliderlabs/ssh"
12)
13
14func SessionHandler(reposPath string, repoPoll time.Duration) func(ssh.Session) (tea.Model, []tea.ProgramOption) {
15	rs := git.NewRepoSource(reposPath)
16	err := createDefaultConfigRepo(rs)
17	if err != nil {
18		if err != nil {
19			log.Fatalf("cannot create config repo: %s", err)
20		}
21	}
22	appCfg, err := loadConfig(rs)
23	if err != nil {
24		if err != nil {
25			log.Printf("cannot load config: %s", err)
26		}
27	}
28	go func() {
29		for {
30			time.Sleep(repoPoll)
31			err := rs.LoadRepos()
32			if err != nil {
33				log.Printf("cannot load repos: %s", err)
34				continue
35			}
36			cfg, err := loadConfig(rs)
37			if err != nil {
38				if err != nil {
39					log.Printf("cannot load config: %s", err)
40					continue
41				}
42			}
43			appCfg = cfg
44		}
45	}()
46
47	return func(s ssh.Session) (tea.Model, []tea.ProgramOption) {
48		cmd := s.Command()
49		cfg := &SessionConfig{}
50		switch len(cmd) {
51		case 0:
52			cfg.InitialRepo = ""
53		case 1:
54			cfg.InitialRepo = cmd[0]
55		default:
56			return nil, nil
57		}
58		pty, _, active := s.Pty()
59		if !active {
60			fmt.Println("not active")
61			return nil, nil
62		}
63		cfg.Width = pty.Window.Width
64		cfg.Height = pty.Window.Height
65		return NewBubble(appCfg, cfg), []tea.ProgramOption{tea.WithAltScreen()}
66	}
67}
68
69func loadConfig(rs *git.RepoSource) (*Config, error) {
70	cfg := &Config{}
71	cfg.RepoSource = rs
72	cr, err := rs.GetRepo("config")
73	if err != nil {
74		return nil, fmt.Errorf("cannot load config repo: %s", err)
75	}
76	cs, err := cr.LatestFile("config.json")
77	if err != nil {
78		return nil, fmt.Errorf("cannot load config.json: %s", err)
79	}
80	err = json.Unmarshal([]byte(cs), cfg)
81	if err != nil {
82		return nil, fmt.Errorf("bad json in config.json: %s", err)
83	}
84	return cfg, nil
85}