generateHTML.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. err = formatter.Format(file, style, iterator)
  33. if err != nil {
  34. return fmt.Errorf("Error writing HTML: %s", err)
  35. }
  36. return nil
  37. }
  38. func convert(files paths) error {
  39. content, err := readFile(files.textFile)
  40. if err != nil {
  41. return fmt.Errorf("Error reading file %s: %s", files.textFile, err)
  42. }
  43. file, err := os.Create(files.htmlFile)
  44. if err != nil {
  45. return fmt.Errorf("Error creating file: %s", err)
  46. }
  47. defer func() {
  48. err := file.Close()
  49. if err != nil {
  50. log.Printf("Error closing file: %s", err)
  51. }
  52. }()
  53. err = createHTML(content, file)
  54. if err != nil {
  55. return err
  56. }
  57. return nil
  58. }