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