tmpl.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package tmpl
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. //"log"
  7. "os"
  8. "surdeus.su/core/cli/mtool"
  9. )
  10. var (
  11. delim = '\n'
  12. Tool = mtool.T("tmpl").Func(Run).Desc(
  13. "substitute the inputted runes with the specified words",
  14. ).Usage(
  15. "[n_strings]",
  16. )
  17. )
  18. func Run(flags *mtool.Flags) {
  19. cargs := flags.CustomArgs()
  20. if len(cargs) == 0 {
  21. CustomRun(os.Stdin, os.Stdout, flags)
  22. return
  23. }
  24. input := cargs[0].(io.Reader)
  25. output := cargs[1].(io.Writer)
  26. CustomRun(input, output, flags)
  27. }
  28. func CustomRun(
  29. input io.Reader,
  30. output io.Writer,
  31. flags *mtool.Flags,
  32. ) {
  33. var (
  34. charsString string
  35. chrs []rune
  36. skip bool
  37. )
  38. flags.StringVar(
  39. &charsString,
  40. "c",
  41. "0123456789",
  42. "character set for substitution",
  43. "COMBO_CHARS",
  44. )
  45. flags.BoolVar(
  46. &skip,
  47. "skip",
  48. false,
  49. "skip and do not substitute not fitting chars",
  50. )
  51. args := flags.Parse()
  52. /*if len(args)<2 || len(args[0]) != len(args)-1 {
  53. flags.Usage()
  54. os.Exit(1)
  55. }*/
  56. chrs = []rune(charsString)
  57. //args = args[1:]
  58. tmpl := make(map[rune]string)
  59. for i, s := range args {
  60. tmpl[rune(chrs[i])] = s
  61. }
  62. r := bufio.NewReader(input)
  63. for {
  64. s, e := r.ReadString(byte(delim))
  65. if e == io.EOF {
  66. break
  67. }
  68. s = s[:len(s)-1]
  69. for _, c := range s {
  70. s, ok := tmpl[c]
  71. if !skip && !ok {
  72. s = string(c)
  73. }
  74. fmt.Printf("%s", s)
  75. }
  76. fmt.Fprintf(output, "%s", string(delim))
  77. }
  78. }