From 0f0c8a11115f6f41c4338df9e2b71e5a40b49b02 Mon Sep 17 00:00:00 2001 From: Johan Walles Date: Mon, 15 Jul 2019 18:46:53 +0200 Subject: [PATCH] Don't highlight files with unsupported file extensions --- m/reader.go | 42 ++++++++++++++++++++++++++++++++++++------ m/reader_test.go | 4 ---- moar.go | 2 ++ 3 files changed, 38 insertions(+), 10 deletions(-) diff --git a/m/reader.go b/m/reader.go index 2b35fad..718058b 100644 --- a/m/reader.go +++ b/m/reader.go @@ -9,6 +9,7 @@ import ( "os/exec" "path" "path/filepath" + "regexp" "strings" "sync" ) @@ -157,15 +158,44 @@ func NewReaderFromCommand(filename string, filterCommand ...string) (*Reader, er } func _CanHighlight(filename string) bool { - ext := filepath.Ext(filename) - if len(ext) == 0 { + extension := filepath.Ext(filename) + if len(extension) <= 1 { + // No extension or a single "." return false } - // FIXME: Check file extension vs "highlight --list-scripts=langs" before - // calling highlight, otherwise files with unsupported extensions (like - // .log) get messed upp. - return true + // Remove leading dot from the extension + extension = extension[1:] + + // Check file extension vs "highlight --list-scripts=langs" before calling + // highlight, otherwise files with unsupported extensions (like .log) get + // messed upp. + highlight := exec.Command("highlight", "--list-scripts=langs") + outBytes, err := highlight.CombinedOutput() + if err != nil { + return false + } + + extensionMatcher := regexp.MustCompile("[^() ]+") + + outString := string(outBytes) + outLines := strings.Split(outString, "\n") + for _, line := range outLines { + parts := strings.Split(line, ": ") + if len(parts) < 2 { + continue + } + + // Pick out all extensions from this line + for _, supportedExtension := range extensionMatcher.FindAllString(parts[1], -1) { + if extension == supportedExtension { + return true + } + } + } + + // No match + return false } // NewReaderFromFilename creates a new file reader diff --git a/m/reader_test.go b/m/reader_test.go index 99c23b6..ec6cbfb 100644 --- a/m/reader_test.go +++ b/m/reader_test.go @@ -127,10 +127,8 @@ func TestGetLines(t *testing.T) { continue } if err := reader._Wait(); err != nil { - /* FIXME: Re-enable this and fix the error that it uncovers t.Errorf("Error reading file <%s>: %s", file, err.Error()) continue - */ } _TestGetLines(t, reader) @@ -168,9 +166,7 @@ func TestStatusText(t *testing.T) { panic(err) } if err := testMe._Wait(); err != nil { - /* FIXME: Re-enable this and fix the problem it uncovers: panic(err) - */ } statusText := testMe.GetLines(0, 0).statusText diff --git a/moar.go b/moar.go index 492b844..7cbc9e5 100644 --- a/moar.go +++ b/moar.go @@ -47,6 +47,8 @@ func main() { printVersion := flag.Bool("version", false, "Prints the moar version number") // FIXME: Support --help + // FIXME: Have --help warn / explain if highlight is not installed + // FIXME: Have --help explain how to make moar your default pager // FIXME: Support --no-highlight