You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
1.6KB

  1. package gotext
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "strconv"
  7. "strings"
  8. )
  9. type Po struct {
  10. translations map[string]string
  11. }
  12. // ParseFile tries to read the file by its provided path (f) and parse its content as a .po file.
  13. func (po *Po) ParseFile(f string) {
  14. // Check if file exists
  15. info, err := os.Stat(f)
  16. if err != nil {
  17. return
  18. }
  19. // Check that isn't a directory
  20. if info.IsDir() {
  21. return
  22. }
  23. // Parse file content
  24. data, err := ioutil.ReadFile(f)
  25. if err != nil {
  26. return
  27. }
  28. po.Parse(string(data))
  29. }
  30. // Parse loads the translations specified in the provided string (str)
  31. func (po *Po) Parse(str string) {
  32. if po.translations == nil {
  33. po.translations = make(map[string]string)
  34. }
  35. lines := strings.Split(str, "\n")
  36. var msgid, msgstr string
  37. for _, l := range lines {
  38. // Trim spaces
  39. l = strings.TrimSpace(l)
  40. // Skip empty lines
  41. if l == "" {
  42. continue
  43. }
  44. // Skip invalid lines
  45. if !strings.HasPrefix(l, "msgid") && !strings.HasPrefix(l, "msgstr") {
  46. continue
  47. }
  48. // Buffer msgid and continue
  49. if strings.HasPrefix(l, "msgid") {
  50. msgid = strings.TrimSpace(strings.TrimPrefix(l, "msgid"))
  51. msgid, _ = strconv.Unquote(msgid)
  52. continue
  53. }
  54. // Save translation for buffered msgid
  55. if strings.HasPrefix(l, "msgstr") {
  56. msgstr = strings.TrimSpace(strings.TrimPrefix(l, "msgstr"))
  57. msgstr, _ = strconv.Unquote(msgstr)
  58. po.translations[msgid] = msgstr
  59. }
  60. }
  61. }
  62. func (po *Po) Get(str string, vars ...interface{}) string {
  63. if po.translations != nil {
  64. if _, ok := po.translations[str]; ok {
  65. return fmt.Sprintf(po.translations[str], vars...)
  66. }
  67. }
  68. // Return the same we received by default
  69. return fmt.Sprintf(str, vars...)
  70. }