- Add 'z read' command with chroma syntax highlighting and line numbers - Add 'z md' command for rendering markdown to terminal - Add Italic, Dim, Underline color constants - Move ReadFileContent to shared pkg/formatter/utils.go - Custom markdown parser with colored headings, lists, checkboxes - Code blocks in markdown use chroma syntax highlighting
77 lines
1.9 KiB
Go
77 lines
1.9 KiB
Go
package cmd
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/alecthomas/chroma/v2/formatters"
|
|
"github.com/alecthomas/chroma/v2/lexers"
|
|
"github.com/alecthomas/chroma/v2/styles"
|
|
"github.com/zemenawi/zutils/pkg/colors"
|
|
"github.com/zemenawi/zutils/pkg/formatter"
|
|
)
|
|
|
|
func ReadCommand(args []string) error {
|
|
if len(args) < 1 {
|
|
return fmt.Errorf("please specify a file path")
|
|
}
|
|
|
|
filePath := args[0]
|
|
|
|
file, err := os.Open(filePath)
|
|
if err != nil {
|
|
return fmt.Errorf("error opening file: %w", err)
|
|
}
|
|
defer file.Close()
|
|
|
|
fileInfo, err := file.Stat()
|
|
if err != nil {
|
|
return fmt.Errorf("error getting file info: %w", err)
|
|
}
|
|
|
|
if fileInfo.IsDir() {
|
|
return fmt.Errorf("'%s' is a directory, not a readable file", filePath)
|
|
}
|
|
|
|
content := formatter.ReadFileContent(file)
|
|
|
|
lexer := lexers.Match(filepath.Base(filePath))
|
|
if lexer == nil {
|
|
lexer = lexers.Fallback
|
|
}
|
|
|
|
iterator, err := lexer.Tokenise(nil, content)
|
|
if err != nil {
|
|
return fmt.Errorf("error tokenizing: %w", err)
|
|
}
|
|
|
|
formatter_ := formatters.TTY256
|
|
style := styles.Get("monokai")
|
|
if style == nil {
|
|
style = styles.Fallback
|
|
}
|
|
|
|
fmt.Printf("%s%s╔══════════════════════════════════════╗%s\n", colors.Cyan, colors.Bold, colors.Reset)
|
|
fmt.Printf("%s%s║%s %-38s %s%s║%s\n", colors.Cyan, colors.Bold, colors.Reset, filePath, colors.Cyan, colors.Bold, colors.Reset)
|
|
fmt.Printf("%s%s╚══════════════════════════════════════╝%s\n", colors.Cyan, colors.Bold, colors.Reset)
|
|
fmt.Println()
|
|
|
|
var buf bytes.Buffer
|
|
err = formatter_.Format(&buf, style, iterator)
|
|
if err != nil {
|
|
return fmt.Errorf("error formatting: %w", err)
|
|
}
|
|
|
|
lines := strings.Split(buf.String(), "\n")
|
|
for i, line := range lines {
|
|
if line != "" {
|
|
fmt.Printf("%s%4d: %s%s\n", colors.Gray, i+1, colors.Reset, line)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|