parser.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package ansible
  15. import (
  16. "fmt"
  17. "strings"
  18. )
  19. // TODO
  20. //
  21. // quote parser
  22. // ParseHostLine parse string representation of an ansible host
  23. //
  24. // Input should be in format "name key=value"
  25. func ParseHostLine(s string) (host Host, err error) {
  26. s = strings.TrimSpace(s)
  27. parts := strings.Split(s, " ")
  28. if len(parts) == 0 {
  29. err = fmt.Errorf("Host name must not be empty")
  30. return
  31. }
  32. host.Name = parts[0]
  33. vars := map[string]string{}
  34. for _, kv := range parts[1:] {
  35. s := strings.SplitN(kv, "=", 2)
  36. if len(s) != 2 {
  37. err = fmt.Errorf("host var not in the form name=val: %s", kv)
  38. return
  39. }
  40. vars[s[0]] = s[1]
  41. }
  42. host.Vars = vars
  43. return
  44. }
  45. // ParseModuleLine parse string representation of an ansible module task
  46. //
  47. // The input should be in format "name key=value arg0 arg1". The argN form is
  48. // For module "command" and "shell"
  49. func ParseModuleLine(s string) (mod Module, err error) {
  50. s = strings.TrimSpace(s)
  51. parts := strings.Split(s, " ")
  52. if len(parts) == 0 {
  53. err = fmt.Errorf("Module name must not be empty")
  54. return
  55. }
  56. mod.Name = parts[0]
  57. args := []string{}
  58. command := ""
  59. freeForm := false // command and shell module take free form arguments
  60. for _, part := range parts[1:] {
  61. if freeForm {
  62. command = command + " " + part
  63. continue
  64. }
  65. if strings.Contains(part, "=") {
  66. args = append(args, part)
  67. } else {
  68. freeForm = true
  69. command = command + " " + part
  70. }
  71. }
  72. if command != "" {
  73. args = append(args, command)
  74. }
  75. mod.Args = args
  76. return
  77. }