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 // createDefaultConfigRepo runs rs.LoadRepos()
17 err := createDefaultConfigRepo(rs)
18 if err != nil {
19 if err != nil {
20 log.Fatalf("cannot create config repo: %s", err)
21 }
22 }
23 appCfg, err := loadConfig(rs)
24 if err != nil {
25 if err != nil {
26 log.Printf("cannot load config: %s", err)
27 }
28 }
29
30 return func(s ssh.Session) (tea.Model, []tea.ProgramOption) {
31 cmd := s.Command()
32 // reload repos and config on git push
33 if len(cmd) > 0 && cmd[0] == "git-receive-pack" {
34 ct := time.Now()
35 err := rs.LoadRepos()
36 if err != nil {
37 log.Printf("cannot load repos: %s", err)
38 }
39 cfg, err := loadConfig(rs)
40 if err != nil {
41 if err != nil {
42 log.Printf("cannot load config: %s", err)
43 }
44 }
45 appCfg = cfg
46 log.Printf("Repo bubble loaded in %s", time.Since(ct))
47 }
48 cfg := &SessionConfig{}
49 switch len(cmd) {
50 case 0:
51 cfg.InitialRepo = ""
52 case 1:
53 cfg.InitialRepo = cmd[0]
54 default:
55 return nil, nil
56 }
57 pty, _, active := s.Pty()
58 if !active {
59 fmt.Println("not active")
60 return nil, nil
61 }
62 cfg.Width = pty.Window.Width
63 cfg.Height = pty.Window.Height
64 return NewBubble(appCfg, cfg), []tea.ProgramOption{tea.WithAltScreen()}
65 }
66}
67
68func loadConfig(rs *git.RepoSource) (*Config, error) {
69 cfg := &Config{}
70 cfg.RepoSource = rs
71 cr, err := rs.GetRepo("config")
72 if err != nil {
73 return nil, fmt.Errorf("cannot load config repo: %s", err)
74 }
75 cs, err := cr.LatestFile("config.json")
76 if err != nil {
77 return nil, fmt.Errorf("cannot load config.json: %s", err)
78 }
79 err = json.Unmarshal([]byte(cs), cfg)
80 if err != nil {
81 return nil, fmt.Errorf("bad json in config.json: %s", err)
82 }
83 return cfg, nil
84}