util.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // This file is subject to a 1-clause BSD license.
  2. // Its contents can be found in the enclosed LICENSE file.
  3. // Package util defines a few commonly used utility functions.
  4. package util
  5. import (
  6. "compress/gzip"
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "os"
  12. )
  13. // Action returns the given, formatted message as a user action.
  14. // E.g.: /me <something something>
  15. func Action(f string, argv ...interface{}) string {
  16. return fmt.Sprintf("\x01ACTION %s\x01", fmt.Sprintf(f, argv...))
  17. }
  18. // Bold returns the given value as bold text.
  19. func Bold(f string, argv ...interface{}) string {
  20. return fmt.Sprintf("\x02%s\x02", fmt.Sprintf(f, argv...))
  21. }
  22. // Italic returns the given value as italicized text.
  23. func Italic(f string, argv ...interface{}) string {
  24. return fmt.Sprintf("\x1d%s\x1d", fmt.Sprintf(f, argv...))
  25. }
  26. // Underline returns the given value as underlined text.
  27. func Underline(f string, argv ...interface{}) string {
  28. return fmt.Sprintf("\x1f%s\x1f", fmt.Sprintf(f, argv...))
  29. }
  30. // ReadFile loads the, optionally compressed, contents of the given
  31. // file and unmarshals it into the specified value v.
  32. //
  33. // This is a utility function which can be used by plugins to load
  34. // custom configuration info or data from disk.
  35. func ReadFile(file string, v interface{}, compressed bool) error {
  36. fd, err := os.Open(file)
  37. if err != nil {
  38. return err
  39. }
  40. defer fd.Close()
  41. var r io.Reader
  42. if compressed {
  43. gz, err := gzip.NewReader(fd)
  44. if err != nil {
  45. return err
  46. }
  47. defer gz.Close()
  48. r = gz
  49. } else {
  50. r = fd
  51. }
  52. return json.NewDecoder(r).Decode(v)
  53. }
  54. // WriteFile writes the marshaled version of v to the given file.
  55. // It is optionally gzip compressed.
  56. //
  57. // This is a utility function which can be used by plugins to save
  58. // custom configuration info or data to disk.
  59. func WriteFile(file string, v interface{}, compressed bool) error {
  60. if compressed {
  61. fd, err := os.OpenFile(file, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
  62. if err != nil {
  63. return err
  64. }
  65. defer fd.Close()
  66. gz := gzip.NewWriter(fd)
  67. defer gz.Close()
  68. return json.NewEncoder(gz).Encode(v)
  69. }
  70. data, err := json.MarshalIndent(v, "", " ")
  71. if err != nil {
  72. return err
  73. }
  74. return ioutil.WriteFile(file, data, 0600)
  75. }