1
1
mirror of https://github.com/walles/moar.git synced 2024-11-30 02:34:13 +03:00

Use a global logger

This saves us from a lot of passing-a-logger-around and makes the code
generally easier to read and to work with.
This commit is contained in:
Johan Walles 2019-11-27 18:43:46 +01:00
parent 69c007eab4
commit 1fa52b9bc7
5 changed files with 68 additions and 71 deletions

View File

@ -24,17 +24,17 @@ type Token struct {
// SetManPageFormatFromEnv parses LESS_TERMCAP_xx environment variables and
// adapts the moar output accordingly.
func SetManPageFormatFromEnv(logger *log.Logger) {
func SetManPageFormatFromEnv() {
// Requested here: https://github.com/walles/moar/issues/14
lessTermcapMd := os.Getenv("LESS_TERMCAP_md")
if lessTermcapMd != "" {
manPageBold = _TermcapToStyle(logger, lessTermcapMd)
manPageBold = _TermcapToStyle(lessTermcapMd)
}
lessTermcapUs := os.Getenv("LESS_TERMCAP_us")
if lessTermcapUs != "" {
manPageUnderline = _TermcapToStyle(logger, lessTermcapUs)
manPageUnderline = _TermcapToStyle(lessTermcapUs)
}
}
@ -44,20 +44,20 @@ func _ResetManPageFormatForTesting() {
manPageUnderline = tcell.StyleDefault.Underline(true)
}
func _TermcapToStyle(logger *log.Logger, termcap string) tcell.Style {
func _TermcapToStyle(termcap string) tcell.Style {
// Add a character to be sure we have one to take the format from
tokens, _ := TokensFromString(logger, termcap+"x")
tokens, _ := TokensFromString(termcap + "x")
return tokens[len(tokens)-1].Style
}
// TokensFromString turns a (formatted) string into a series of tokens,
// and an unformatted string
func TokensFromString(logger *log.Logger, s string) ([]Token, *string) {
func TokensFromString(s string) ([]Token, *string) {
var tokens []Token
styleBrokenUtf8 := tcell.StyleDefault.Background(7).Foreground(1)
for _, styledString := range _StyledStringsFromString(logger, s) {
for _, styledString := range _StyledStringsFromString(s) {
for _, token := range _TokensFromStyledString(styledString) {
switch token.Rune {
@ -168,7 +168,7 @@ type _StyledString struct {
Style tcell.Style
}
func _StyledStringsFromString(logger *log.Logger, s string) []_StyledString {
func _StyledStringsFromString(s string) []_StyledString {
// This function was inspired by the
// https://golang.org/pkg/regexp/#Regexp.Split source code
@ -193,7 +193,7 @@ func _StyledStringsFromString(logger *log.Logger, s string) []_StyledString {
}
matchedPart := s[match[0]:match[1]]
style = _UpdateStyle(logger, style, matchedPart)
style = _UpdateStyle(style, matchedPart)
beg = match[1]
}
@ -209,7 +209,7 @@ func _StyledStringsFromString(logger *log.Logger, s string) []_StyledString {
}
// _UpdateStyle parses a string of the form "ESC[33m" into changes to style
func _UpdateStyle(logger *log.Logger, style tcell.Style, escapeSequence string) tcell.Style {
func _UpdateStyle(style tcell.Style, escapeSequence string) tcell.Style {
numbers := strings.Split(escapeSequence[2:len(escapeSequence)-1], ";")
index := 0
for index < len(numbers) {
@ -253,7 +253,7 @@ func _UpdateStyle(logger *log.Logger, style tcell.Style, escapeSequence string)
var color *tcell.Color
index, color, err = consumeCompositeColor(numbers, index-1)
if err != nil {
logger.Printf("Foreground: %s", err.Error())
log.Printf("Foreground: %s", err.Error())
return style
}
style = style.Foreground(*color)
@ -282,7 +282,7 @@ func _UpdateStyle(logger *log.Logger, style tcell.Style, escapeSequence string)
var color *tcell.Color
index, color, err = consumeCompositeColor(numbers, index-1)
if err != nil {
logger.Printf("Background: %s", err.Error())
log.Printf("Background: %s", err.Error())
return style
}
style = style.Background(*color)
@ -290,7 +290,7 @@ func _UpdateStyle(logger *log.Logger, style tcell.Style, escapeSequence string)
style = style.Background(tcell.ColorDefault)
default:
logger.Printf("Unrecognized ANSI SGR code <%s>", number)
log.Printf("Unrecognized ANSI SGR code <%s>", number)
}
}

View File

@ -31,9 +31,9 @@ func TestTokenize(t *testing.T) {
lineNumber++
var loglines strings.Builder
logger := log.New(&loglines, "", 0)
log.SetOutput(&loglines)
tokens, plainString := TokensFromString(logger, line)
tokens, plainString := TokensFromString(line)
if len(tokens) != utf8.RuneCountInString(*plainString) {
t.Errorf("%s:%d: len(tokens)=%d, len(plainString)=%d for: <%s>",
fileName, lineNumber,
@ -51,7 +51,7 @@ func TestTokenize(t *testing.T) {
func testManPages(t *testing.T) {
// Bold
tokens, _ := TokensFromString(nil, "ab\bbc")
tokens, _ := TokensFromString("ab\bbc")
assert.Equal(t, []Token{
Token{Rune: 'a', Style: tcell.StyleDefault},
Token{Rune: 'b', Style: tcell.StyleDefault.Bold(true)},
@ -59,7 +59,7 @@ func testManPages(t *testing.T) {
}, tokens)
// Underline
tokens, _ = TokensFromString(nil, "ab\b_c")
tokens, _ = TokensFromString("ab\b_c")
assert.Equal(t, []Token{
Token{Rune: 'a', Style: tcell.StyleDefault},
Token{Rune: 'b', Style: tcell.StyleDefault.Underline(true)},

View File

@ -105,7 +105,7 @@ func NewPager(r *Reader) *Pager {
}
}
func (p *Pager) _AddLine(logger *log.Logger, fileLineNumber *int, maxPrefixLength int, screenLineNumber int, line string) {
func (p *Pager) _AddLine(fileLineNumber *int, maxPrefixLength int, screenLineNumber int, line string) {
screenWidth, _ := p.screen.Size()
prefixLength := 0
@ -123,14 +123,13 @@ func (p *Pager) _AddLine(logger *log.Logger, fileLineNumber *int, maxPrefixLengt
p.screen.SetContent(column, screenLineNumber, digit, nil, _NumberStyle)
}
tokens := _CreateScreenLine(logger, p.leftColumnZeroBased, screenWidth-prefixLength, line, p.searchPattern)
tokens := _CreateScreenLine(p.leftColumnZeroBased, screenWidth-prefixLength, line, p.searchPattern)
for column, token := range tokens {
p.screen.SetContent(column+prefixLength, screenLineNumber, token.Rune, nil, token.Style)
}
}
func _CreateScreenLine(
logger *log.Logger,
stringIndexAtColumnZero int,
screenColumnsCount int,
line string,
@ -147,7 +146,7 @@ func _CreateScreenLine(
searchHitDelta = -1
}
tokens, plainString := TokensFromString(logger, line)
tokens, plainString := TokensFromString(line)
if stringIndexAtColumnZero >= len(tokens) {
// Nothing (more) to display, never mind
return returnMe
@ -193,7 +192,7 @@ func (p *Pager) _AddSearchFooter() {
p.screen.SetContent(pos, height-1, ' ', nil, tcell.StyleDefault.Reverse(true))
}
func (p *Pager) _AddLines(logger *log.Logger, spinner string) {
func (p *Pager) _AddLines(spinner string) {
_, height := p.screen.Size()
wantedLineCount := height - 1
@ -218,7 +217,7 @@ func (p *Pager) _AddLines(logger *log.Logger, spinner string) {
screenLineNumber := 0
for i, line := range lines.lines {
lineNumber := p.firstLineOneBased + i
p._AddLine(logger, &lineNumber, maxPrefixLength, screenLineNumber, line)
p._AddLine(&lineNumber, maxPrefixLength, screenLineNumber, line)
screenLineNumber++
}
@ -227,7 +226,7 @@ func (p *Pager) _AddLines(logger *log.Logger, spinner string) {
// This happens when we're done
eofSpinner = "---"
}
p._AddLine(logger, nil, 0, screenLineNumber, _EofMarkerFormat+eofSpinner)
p._AddLine(nil, 0, screenLineNumber, _EofMarkerFormat+eofSpinner)
switch p.mode {
case _Searching:
@ -263,10 +262,10 @@ func (p *Pager) _SetFooter(footer string) {
}
}
func (p *Pager) _Redraw(logger *log.Logger, spinner string) {
func (p *Pager) _Redraw(spinner string) {
p.screen.Clear()
p._AddLines(logger, spinner)
p._AddLines(spinner)
p.screen.Show()
}
@ -286,13 +285,13 @@ func (p *Pager) Quit() {
p.preHelpState = nil
}
func (p *Pager) _ScrollToSearchHits(logger *log.Logger) {
func (p *Pager) _ScrollToSearchHits() {
if p.searchPattern == nil {
// This is not a search
return
}
firstHitLine := p._FindFirstHitLineOneBased(logger, p.firstLineOneBased, false)
firstHitLine := p._FindFirstHitLineOneBased(p.firstLineOneBased, false)
if firstHitLine == nil {
// No match, give up
return
@ -315,7 +314,7 @@ func (p *Pager) _GetLastVisibleLineOneBased() int {
return firstVisibleLineOneBased + windowHeight - 2
}
func (p *Pager) _FindFirstHitLineOneBased(logger *log.Logger, firstLineOneBased int, backwards bool) *int {
func (p *Pager) _FindFirstHitLineOneBased(firstLineOneBased int, backwards bool) *int {
lineNumber := firstLineOneBased
for {
line := p.reader.GetLine(lineNumber)
@ -324,7 +323,7 @@ func (p *Pager) _FindFirstHitLineOneBased(logger *log.Logger, firstLineOneBased
return nil
}
_, lineText := TokensFromString(logger, *line)
_, lineText := TokensFromString(*line)
if p.searchPattern.MatchString(*lineText) {
return &lineNumber
}
@ -337,7 +336,7 @@ func (p *Pager) _FindFirstHitLineOneBased(logger *log.Logger, firstLineOneBased
}
}
func (p *Pager) _ScrollToNextSearchHit(logger *log.Logger) {
func (p *Pager) _ScrollToNextSearchHit() {
if p.searchPattern == nil {
// Nothing to search for, never mind
return
@ -364,7 +363,7 @@ func (p *Pager) _ScrollToNextSearchHit(logger *log.Logger) {
panic(fmt.Sprint("Unknown search mode when finding next: ", p.mode))
}
firstHitLine := p._FindFirstHitLineOneBased(logger, firstSearchLineOneBased, false)
firstHitLine := p._FindFirstHitLineOneBased(firstSearchLineOneBased, false)
if firstHitLine == nil {
p.mode = _NotFound
return
@ -372,7 +371,7 @@ func (p *Pager) _ScrollToNextSearchHit(logger *log.Logger) {
p.firstLineOneBased = *firstHitLine
}
func (p *Pager) _ScrollToPreviousSearchHit(logger *log.Logger) {
func (p *Pager) _ScrollToPreviousSearchHit() {
if p.searchPattern == nil {
// Nothing to search for, never mind
return
@ -399,7 +398,7 @@ func (p *Pager) _ScrollToPreviousSearchHit(logger *log.Logger) {
panic(fmt.Sprint("Unknown search mode when finding previous: ", p.mode))
}
firstHitLine := p._FindFirstHitLineOneBased(logger, firstSearchLineOneBased, true)
firstHitLine := p._FindFirstHitLineOneBased(firstSearchLineOneBased, true)
if firstHitLine == nil {
p.mode = _NotFound
return
@ -407,10 +406,10 @@ func (p *Pager) _ScrollToPreviousSearchHit(logger *log.Logger) {
p.firstLineOneBased = *firstHitLine
}
func (p *Pager) _UpdateSearchPattern(logger *log.Logger) {
func (p *Pager) _UpdateSearchPattern() {
p.searchPattern = ToPattern(p.searchString)
p._ScrollToSearchHits(logger)
p._ScrollToSearchHits()
// FIXME: If the user is typing, indicate to user if we didn't find anything
}
@ -466,7 +465,7 @@ func removeLastChar(s string) string {
return s[:len(s)-size]
}
func (p *Pager) _OnSearchKey(logger *log.Logger, key tcell.Key) {
func (p *Pager) _OnSearchKey(key tcell.Key) {
switch key {
case tcell.KeyEscape, tcell.KeyEnter:
p.mode = _Viewing
@ -477,7 +476,7 @@ func (p *Pager) _OnSearchKey(logger *log.Logger, key tcell.Key) {
}
p.searchString = removeLastChar(p.searchString)
p._UpdateSearchPattern(logger)
p._UpdateSearchPattern()
case tcell.KeyUp:
// Clipping is done in _AddLines()
@ -500,7 +499,7 @@ func (p *Pager) _OnSearchKey(logger *log.Logger, key tcell.Key) {
p.mode = _Viewing
default:
logger.Printf("Unhandled search key event %v", key)
log.Printf("Unhandled search key event %v", key)
}
}
@ -523,9 +522,9 @@ func (p *Pager) _MoveRight(delta int) {
}
}
func (p *Pager) _OnKey(logger *log.Logger, key tcell.Key) {
func (p *Pager) _OnKey(key tcell.Key) {
if p.mode == _Searching {
p._OnSearchKey(logger, key)
p._OnSearchKey(key)
return
}
if p.mode != _Viewing && p.mode != _NotFound {
@ -568,18 +567,18 @@ func (p *Pager) _OnKey(logger *log.Logger, key tcell.Key) {
p.firstLineOneBased -= (height - 1)
default:
logger.Printf("Unhandled key event %v", key)
log.Printf("Unhandled key event %v", key)
}
}
func (p *Pager) _OnSearchRune(logger *log.Logger, char rune) {
func (p *Pager) _OnSearchRune(char rune) {
p.searchString = p.searchString + string(char)
p._UpdateSearchPattern(logger)
p._UpdateSearchPattern()
}
func (p *Pager) _OnRune(logger *log.Logger, char rune) {
func (p *Pager) _OnRune(char rune) {
if p.mode == _Searching {
p._OnSearchRune(logger, char)
p._OnSearchRune(char)
return
}
if p.mode != _Viewing && p.mode != _NotFound {
@ -639,22 +638,22 @@ func (p *Pager) _OnRune(logger *log.Logger, char rune) {
p.searchPattern = nil
case 'n':
p._ScrollToNextSearchHit(logger)
p._ScrollToNextSearchHit()
case 'p', 'N':
p._ScrollToPreviousSearchHit(logger)
p._ScrollToPreviousSearchHit()
default:
logger.Printf("Unhandled rune keypress '%s'", string(char))
log.Printf("Unhandled rune keypress '%s'", string(char))
}
}
// StartPaging brings up the pager on screen
func (p *Pager) StartPaging(logger *log.Logger, screen tcell.Screen) {
func (p *Pager) StartPaging(screen tcell.Screen) {
// We want to match the terminal theme, see screen.Init() source code
os.Setenv("TCELL_TRUECOLOR", "disable")
SetManPageFormatFromEnv(logger)
SetManPageFormatFromEnv()
if e := screen.Init(); e != nil {
fmt.Fprintf(os.Stderr, "%v\n", e)
@ -664,7 +663,7 @@ func (p *Pager) StartPaging(logger *log.Logger, screen tcell.Screen) {
p.screen = screen
screen.EnableMouse()
screen.Show()
p._Redraw(logger, "")
p._Redraw("")
go func() {
for {
@ -719,9 +718,9 @@ func (p *Pager) StartPaging(logger *log.Logger, screen tcell.Screen) {
switch ev := ev.(type) {
case *tcell.EventKey:
if ev.Key() == tcell.KeyRune {
p._OnRune(logger, ev.Rune())
p._OnRune(ev.Rune())
} else {
p._OnKey(logger, ev.Key())
p._OnKey(ev.Key())
}
case *tcell.EventMouse:
@ -755,16 +754,16 @@ func (p *Pager) StartPaging(logger *log.Logger, screen tcell.Screen) {
}
default:
logger.Printf("Unhandled event type: %v", ev)
log.Printf("Unhandled event type: %v", ev)
}
// FIXME: If more events are ready, skip this redraw, that
// should speed up mouse wheel scrolling
p._Redraw(logger, spinner)
p._Redraw(spinner)
}
if p.reader.err != nil {
logger.Printf("Reader reported an error: %s", p.reader.err.Error())
log.Printf("Reader reported an error: %s", p.reader.err.Error())
}
}

View File

@ -1,7 +1,6 @@
package m
import (
"log"
"os"
"regexp"
"runtime"
@ -103,8 +102,7 @@ func _StartPaging(t *testing.T, reader *Reader) []tcell.SimCell {
pager.Quit()
var loglines strings.Builder
logger := log.New(&loglines, "", 0)
pager.StartPaging(logger, screen)
pager.StartPaging(screen)
contents, _, _ := screen.GetContents()
if len(loglines.String()) > 0 {
@ -268,12 +266,12 @@ func assertTokenRangesEqual(t *testing.T, actual []Token, expected []Token) {
}
func TestCreateScreenLineBase(t *testing.T) {
line := _CreateScreenLine(nil, 0, 3, "", nil)
line := _CreateScreenLine(0, 3, "", nil)
assert.Assert(t, len(line) == 0)
}
func TestCreateScreenLineOverflowRight(t *testing.T) {
line := _CreateScreenLine(nil, 0, 3, "012345", nil)
line := _CreateScreenLine(0, 3, "012345", nil)
assertTokenRangesEqual(t, line, []Token{
_CreateExpectedCell('0', tcell.StyleDefault),
_CreateExpectedCell('1', tcell.StyleDefault),
@ -282,7 +280,7 @@ func TestCreateScreenLineOverflowRight(t *testing.T) {
}
func TestCreateScreenLineUnderflowLeft(t *testing.T) {
line := _CreateScreenLine(nil, 1, 3, "012", nil)
line := _CreateScreenLine(1, 3, "012", nil)
assertTokenRangesEqual(t, line, []Token{
_CreateExpectedCell('<', tcell.StyleDefault.Reverse(true)),
_CreateExpectedCell('1', tcell.StyleDefault),
@ -296,7 +294,7 @@ func TestCreateScreenLineSearchHit(t *testing.T) {
panic(err)
}
line := _CreateScreenLine(nil, 0, 3, "abc", pattern)
line := _CreateScreenLine(0, 3, "abc", pattern)
assertTokenRangesEqual(t, line, []Token{
_CreateExpectedCell('a', tcell.StyleDefault),
_CreateExpectedCell('b', tcell.StyleDefault.Reverse(true)),
@ -310,7 +308,7 @@ func TestCreateScreenLineUtf8SearchHit(t *testing.T) {
panic(err)
}
line := _CreateScreenLine(nil, 0, 3, "åäö", pattern)
line := _CreateScreenLine(0, 3, "åäö", pattern)
assertTokenRangesEqual(t, line, []Token{
_CreateExpectedCell('å', tcell.StyleDefault),
_CreateExpectedCell('ä', tcell.StyleDefault.Reverse(true)),
@ -321,7 +319,7 @@ func TestCreateScreenLineUtf8SearchHit(t *testing.T) {
func TestCreateScreenLineScrolledUtf8SearchHit(t *testing.T) {
pattern := regexp.MustCompile("ä")
line := _CreateScreenLine(nil, 1, 4, "ååäö", pattern)
line := _CreateScreenLine(1, 4, "ååäö", pattern)
assertTokenRangesEqual(t, line, []Token{
_CreateExpectedCell('<', tcell.StyleDefault.Reverse(true)),
@ -334,7 +332,7 @@ func TestCreateScreenLineScrolledUtf8SearchHit(t *testing.T) {
func TestCreateScreenLineScrolled2Utf8SearchHit(t *testing.T) {
pattern := regexp.MustCompile("ä")
line := _CreateScreenLine(nil, 2, 4, "åååäö", pattern)
line := _CreateScreenLine(2, 4, "åååäö", pattern)
assertTokenRangesEqual(t, line, []Token{
_CreateExpectedCell('<', tcell.StyleDefault.Reverse(true)),
@ -353,7 +351,7 @@ func TestFindFirstLineOneBasedSimple(t *testing.T) {
pager.searchPattern = ToPattern("AB")
hitLine := pager._FindFirstHitLineOneBased(nil, 1, false)
hitLine := pager._FindFirstHitLineOneBased(1, false)
assert.Check(t, hitLine != nil)
assert.Check(t, *hitLine == 1)
}
@ -367,7 +365,7 @@ func TestFindFirstLineOneBasedAnsi(t *testing.T) {
pager.searchPattern = ToPattern("AB")
hitLine := pager._FindFirstHitLineOneBased(nil, 1, false)
hitLine := pager._FindFirstHitLineOneBased(1, false)
assert.Check(t, hitLine != nil)
assert.Check(t, *hitLine == 1)
}

View File

@ -173,6 +173,6 @@ func _StartPaging(reader *m.Reader) {
}
}()
logger := log.New(&loglines, "", 0)
m.NewPager(reader).StartPaging(logger, screen)
log.SetOutput(&loglines)
m.NewPager(reader).StartPaging(screen)
}