zutils/cmd/read.go

48 lines
1.2 KiB
Go
Raw Normal View History

package cmd
import (
"fmt"
"os"
"github.com/zemenawi/zutils/pkg/formatter"
)
var ReadHelp = CommandHelp{
Name: "read",
Help: "Read and display file with smart detection.\nAutomatically detects file type:\n - Markdown (.md) - Renders with colored headings, lists, code blocks\n - Code files - Syntax highlighting with line numbers\n - Other files - Plain text display",
Examples: []string{
"z read README.md # Read markdown file",
"z read main.go # Read code with syntax highlighting",
"z read package.json # Read JSON file",
},
}
func ReadCommand(args []string) error {
if len(args) < 1 {
return fmt.Errorf("missing file path\n\nUsage: z read <file>")
}
filePath := args[0]
file, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("cannot open file '%s': %s", filePath, err)
}
defer file.Close()
fileInfo, err := file.Stat()
if err != nil {
return fmt.Errorf("cannot read file info '%s': %s", filePath, err)
}
if fileInfo.IsDir() {
return fmt.Errorf("'%s' is a directory\n\nUse: z info dir %s", filePath, filePath)
}
handler := formatter.ReadHandlers.GetHandler(filePath)
if handler != nil {
return handler(args)
}
return formatter.ReadFileWithHighlight(file, filePath)
}