generateHTML.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/alecthomas/chroma"
  5. "github.com/alecthomas/chroma/formatters/html"
  6. "github.com/alecthomas/chroma/lexers"
  7. "github.com/alecthomas/chroma/styles"
  8. "io/ioutil"
  9. "log"
  10. "os"
  11. )
  12. func readFile(path string) (string, error) {
  13. content, err := ioutil.ReadFile(path)
  14. if err != nil {
  15. return "", fmt.Errorf("Error reading file %s: %s", path, err)
  16. }
  17. return string(content), nil
  18. }
  19. func createHTML(content string, file *os.File) error {
  20. language := detectLanguage(content)
  21. lexer := lexers.Get(language)
  22. if lexer == nil {
  23. lexer = lexers.Fallback
  24. }
  25. lexer = chroma.Coalesce(lexer)
  26. style := styles.Get("dracula")
  27. if style == nil {
  28. style = styles.Fallback
  29. }
  30. formatter := html.New(html.Standalone(true), html.WithLineNumbers(true), html.LinkableLineNumbers(true, ""), html.LineNumbersInTable(true))
  31. iterator, err := lexer.Tokenise(nil, content)
  32. if err != nil {
  33. return fmt.Errorf("Error tokenizing content HTML: %s", err)
  34. }
  35. err = formatter.Format(file, style, iterator)
  36. if err != nil {
  37. return fmt.Errorf("Error writing HTML: %s", err)
  38. }
  39. return nil
  40. }
  41. func convert(files paths) error {
  42. content, err := readFile(files.textFile)
  43. if err != nil {
  44. return fmt.Errorf("Error reading file %s: %s", files.textFile, err)
  45. }
  46. file, err := os.Create(files.htmlFile)
  47. if err != nil {
  48. return fmt.Errorf("Error creating file: %s", err)
  49. }
  50. defer func() {
  51. err := file.Close()
  52. if err != nil {
  53. log.Printf("Error closing file: %s", err)
  54. }
  55. }()
  56. err = createHTML(content, file)
  57. if err != nil {
  58. return err
  59. }
  60. return nil
  61. }