log.go

  1package repo
  2
  3import (
  4	"fmt"
  5	"strings"
  6	"time"
  7
  8	"github.com/charmbracelet/bubbles/key"
  9	tea "github.com/charmbracelet/bubbletea"
 10	"github.com/charmbracelet/glamour"
 11	gansi "github.com/charmbracelet/glamour/ansi"
 12	"github.com/charmbracelet/lipgloss"
 13	ggit "github.com/charmbracelet/soft-serve/git"
 14	"github.com/charmbracelet/soft-serve/ui/common"
 15	"github.com/charmbracelet/soft-serve/ui/components/selector"
 16	"github.com/charmbracelet/soft-serve/ui/components/viewport"
 17	"github.com/charmbracelet/soft-serve/ui/git"
 18	"github.com/muesli/reflow/wrap"
 19	"github.com/muesli/termenv"
 20)
 21
 22type logView int
 23
 24const (
 25	logViewCommits logView = iota
 26	logViewDiff
 27)
 28
 29// LogCountMsg is a message that contains the number of commits in a repo.
 30type LogCountMsg int64
 31
 32// LogItemsMsg is a message that contains a slice of LogItem.
 33type LogItemsMsg []selector.IdentifiableItem
 34
 35// LogCommitMsg is a message that contains a git commit.
 36type LogCommitMsg *ggit.Commit
 37
 38// LogDiffMsg is a message that contains a git diff.
 39type LogDiffMsg *ggit.Diff
 40
 41// Log is a model that displays a list of commits and their diffs.
 42type Log struct {
 43	common         common.Common
 44	selector       *selector.Selector
 45	vp             *viewport.Viewport
 46	activeView     logView
 47	repo           git.GitRepo
 48	ref            *ggit.Reference
 49	count          int64
 50	nextPage       int
 51	activeCommit   *ggit.Commit
 52	selectedCommit *ggit.Commit
 53	currentDiff    *ggit.Diff
 54}
 55
 56// NewLog creates a new Log model.
 57func NewLog(common common.Common) *Log {
 58	l := &Log{
 59		common:     common,
 60		vp:         viewport.New(),
 61		activeView: logViewCommits,
 62	}
 63	selector := selector.New(common, []selector.IdentifiableItem{}, LogItemDelegate{common.Styles})
 64	selector.SetShowFilter(false)
 65	selector.SetShowHelp(false)
 66	selector.SetShowPagination(false)
 67	selector.SetShowStatusBar(false)
 68	selector.SetShowTitle(false)
 69	selector.SetFilteringEnabled(false)
 70	selector.DisableQuitKeybindings()
 71	selector.KeyMap.NextPage = common.KeyMap.NextPage
 72	selector.KeyMap.PrevPage = common.KeyMap.PrevPage
 73	l.selector = selector
 74	return l
 75}
 76
 77// SetSize implements common.Component.
 78func (l *Log) SetSize(width, height int) {
 79	l.common.SetSize(width, height)
 80	l.selector.SetSize(width, height)
 81	l.vp.SetSize(width, height)
 82}
 83
 84// ShortHelp implements key.KeyMap.
 85func (l *Log) ShortHelp() []key.Binding {
 86	switch l.activeView {
 87	case logViewCommits:
 88		return []key.Binding{
 89			key.NewBinding(
 90				key.WithKeys(
 91					"l",
 92					"right",
 93				),
 94				key.WithHelp(
 95					"→",
 96					"select",
 97				),
 98			),
 99		}
100	case logViewDiff:
101		return []key.Binding{
102			l.common.KeyMap.UpDown,
103			key.NewBinding(
104				key.WithKeys(
105					"h",
106					"left",
107				),
108				key.WithHelp(
109					"←",
110					"back",
111				),
112			),
113		}
114	default:
115		return []key.Binding{}
116	}
117}
118
119// Init implements tea.Model.
120func (l *Log) Init() tea.Cmd {
121	cmds := make([]tea.Cmd, 0)
122	cmds = append(cmds, l.updateCommitsCmd)
123	return tea.Batch(cmds...)
124}
125
126// Update implements tea.Model.
127func (l *Log) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
128	cmds := make([]tea.Cmd, 0)
129	switch msg := msg.(type) {
130	case RepoMsg:
131		l.count = 0
132		l.selector.Select(0)
133		l.nextPage = 0
134		l.activeView = 0
135		l.repo = git.GitRepo(msg)
136	case RefMsg:
137		l.ref = msg
138		l.count = 0
139		cmds = append(cmds, l.countCommitsCmd)
140	case LogCountMsg:
141		l.count = int64(msg)
142	case LogItemsMsg:
143		cmds = append(cmds, l.selector.SetItems(msg))
144		l.selector.SetPage(l.nextPage)
145		l.SetSize(l.common.Width, l.common.Height)
146		l.activeCommit = l.selector.SelectedItem().(LogItem).Commit
147	case tea.KeyMsg, tea.MouseMsg:
148		switch l.activeView {
149		case logViewCommits:
150			switch key := msg.(type) {
151			case tea.KeyMsg:
152				switch key.String() {
153				case "l", "right":
154					cmds = append(cmds, l.selector.SelectItem)
155				}
156			}
157			// This is a hack for loading commits on demand based on list.Pagination.
158			curPage := l.selector.Page()
159			s, cmd := l.selector.Update(msg)
160			m := s.(*selector.Selector)
161			l.selector = m
162			if m.Page() != curPage {
163				l.nextPage = m.Page()
164				l.selector.SetPage(curPage)
165				cmds = append(cmds, l.updateCommitsCmd)
166			}
167			cmds = append(cmds, cmd)
168		case logViewDiff:
169			switch key := msg.(type) {
170			case tea.KeyMsg:
171				switch key.String() {
172				case "h", "left":
173					l.activeView = logViewCommits
174				}
175			}
176		}
177	case selector.ActiveMsg:
178		switch sel := msg.IdentifiableItem.(type) {
179		case LogItem:
180			l.activeCommit = sel.Commit
181		}
182		cmds = append(cmds, updateStatusBarCmd)
183	case selector.SelectMsg:
184		switch sel := msg.IdentifiableItem.(type) {
185		case LogItem:
186			cmds = append(cmds, l.selectCommitCmd(sel.Commit))
187		}
188	case LogCommitMsg:
189		l.selectedCommit = msg
190		cmds = append(cmds, l.loadDiffCmd)
191	case LogDiffMsg:
192		l.currentDiff = msg
193		l.vp.SetContent(
194			lipgloss.JoinVertical(lipgloss.Top,
195				l.renderCommit(l.selectedCommit),
196				l.renderSummary(msg),
197				l.renderDiff(msg),
198			),
199		)
200		l.vp.GotoTop()
201		l.activeView = logViewDiff
202		cmds = append(cmds, updateStatusBarCmd)
203	case tea.WindowSizeMsg:
204		if l.selectedCommit != nil && l.currentDiff != nil {
205			l.vp.SetContent(
206				lipgloss.JoinVertical(lipgloss.Top,
207					l.renderCommit(l.selectedCommit),
208					l.renderSummary(l.currentDiff),
209					l.renderDiff(l.currentDiff),
210				),
211			)
212		}
213		if l.repo != nil {
214			cmds = append(cmds, l.updateCommitsCmd)
215		}
216	}
217	switch l.activeView {
218	case logViewDiff:
219		vp, cmd := l.vp.Update(msg)
220		l.vp = vp.(*viewport.Viewport)
221		if cmd != nil {
222			cmds = append(cmds, cmd)
223		}
224	}
225	return l, tea.Batch(cmds...)
226}
227
228// View implements tea.Model.
229func (l *Log) View() string {
230	switch l.activeView {
231	case logViewCommits:
232		return l.selector.View()
233	case logViewDiff:
234		return l.vp.View()
235	default:
236		return ""
237	}
238}
239
240// StatusBarValue returns the status bar value.
241func (l *Log) StatusBarValue() string {
242	c := l.activeCommit
243	if c == nil {
244		return ""
245	}
246	return fmt.Sprintf("%s by %s on %s",
247		c.ID.String()[:7],
248		c.Author.Name,
249		c.Author.When.Format("02 Jan 2006"),
250	)
251}
252
253// StatusBarInfo returns the status bar info.
254func (l *Log) StatusBarInfo() string {
255	switch l.activeView {
256	case logViewCommits:
257		// We're using l.nextPage instead of l.selector.Paginator.Page because
258		// of the paginator hack above.
259		return fmt.Sprintf("%d/%d", l.nextPage+1, l.selector.TotalPages())
260	case logViewDiff:
261		return fmt.Sprintf("%.f%%", l.vp.ScrollPercent()*100)
262	default:
263		return ""
264	}
265}
266
267func (l *Log) countCommitsCmd() tea.Msg {
268	count, err := l.repo.CountCommits(l.ref)
269	if err != nil {
270		return common.ErrorMsg(err)
271	}
272	return LogCountMsg(count)
273}
274
275func (l *Log) updateCommitsCmd() tea.Msg {
276	count := l.count
277	if l.count == 0 {
278		switch msg := l.countCommitsCmd().(type) {
279		case common.ErrorMsg:
280			return msg
281		case LogCountMsg:
282			count = int64(msg)
283		}
284	}
285	items := make([]selector.IdentifiableItem, count)
286	page := l.nextPage
287	limit := l.selector.PerPage()
288	skip := page * limit
289	// CommitsByPage pages start at 1
290	cc, err := l.repo.CommitsByPage(l.ref, page+1, limit)
291	if err != nil {
292		return common.ErrorMsg(err)
293	}
294	for i, c := range cc {
295		idx := i + skip
296		if int64(idx) >= count {
297			break
298		}
299		items[idx] = LogItem{c}
300	}
301	return LogItemsMsg(items)
302}
303
304func (l *Log) selectCommitCmd(commit *ggit.Commit) tea.Cmd {
305	return func() tea.Msg {
306		return LogCommitMsg(commit)
307	}
308}
309
310func (l *Log) loadDiffCmd() tea.Msg {
311	diff, err := l.repo.Diff(l.selectedCommit)
312	if err != nil {
313		return common.ErrorMsg(err)
314	}
315	return LogDiffMsg(diff)
316}
317
318func styleConfig() gansi.StyleConfig {
319	noColor := ""
320	s := glamour.DarkStyleConfig
321	s.Document.StylePrimitive.Color = &noColor
322	s.CodeBlock.Chroma.Text.Color = &noColor
323	s.CodeBlock.Chroma.Name.Color = &noColor
324	return s
325}
326
327func renderCtx() gansi.RenderContext {
328	return gansi.NewRenderContext(gansi.Options{
329		ColorProfile: termenv.TrueColor,
330		Styles:       styleConfig(),
331	})
332}
333
334func (l *Log) renderCommit(c *ggit.Commit) string {
335	s := strings.Builder{}
336	// FIXME: lipgloss prints empty lines when CRLF is used
337	// sanitize commit message from CRLF
338	msg := strings.ReplaceAll(c.Message, "\r\n", "\n")
339	s.WriteString(fmt.Sprintf("%s\n%s\n%s\n%s\n",
340		l.common.Styles.LogCommitHash.Render("commit "+c.ID.String()),
341		l.common.Styles.LogCommitAuthor.Render(fmt.Sprintf("Author: %s <%s>", c.Author.Name, c.Author.Email)),
342		l.common.Styles.LogCommitDate.Render("Date:   "+c.Committer.When.Format(time.UnixDate)),
343		l.common.Styles.LogCommitBody.Render(msg),
344	))
345	return wrap.String(s.String(), l.common.Width-2)
346}
347
348func (l *Log) renderSummary(diff *ggit.Diff) string {
349	stats := strings.Split(diff.Stats().String(), "\n")
350	for i, line := range stats {
351		ch := strings.Split(line, "|")
352		if len(ch) > 1 {
353			adddel := ch[len(ch)-1]
354			adddel = strings.ReplaceAll(adddel, "+", l.common.Styles.LogCommitStatsAdd.Render("+"))
355			adddel = strings.ReplaceAll(adddel, "-", l.common.Styles.LogCommitStatsDel.Render("-"))
356			stats[i] = strings.Join(ch[:len(ch)-1], "|") + "|" + adddel
357		}
358	}
359	return wrap.String(strings.Join(stats, "\n"), l.common.Width-2)
360}
361
362func (l *Log) renderDiff(diff *ggit.Diff) string {
363	var s strings.Builder
364	var pr strings.Builder
365	diffChroma := &gansi.CodeBlockElement{
366		Code:     diff.Patch(),
367		Language: "diff",
368	}
369	err := diffChroma.Render(&pr, renderCtx())
370	if err != nil {
371		s.WriteString(fmt.Sprintf("\n%s", err.Error()))
372	} else {
373		s.WriteString(fmt.Sprintf("\n%s", pr.String()))
374	}
375	return wrap.String(s.String(), l.common.Width-2)
376}