cmdline.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 qemutils
  15. import (
  16. "strings"
  17. "yunion.io/x/pkg/errors"
  18. )
  19. type Cmdline struct {
  20. options []Option
  21. }
  22. func NewCmdline(content string) (*Cmdline, error) {
  23. cl := &Cmdline{
  24. options: make([]Option, 0),
  25. }
  26. parts := strings.Split(content, " -")
  27. for i := range parts {
  28. part := parts[i]
  29. segs := strings.Split(part, " ")
  30. if len(segs) == 0 {
  31. return nil, errors.Errorf("Invalid part %q", part)
  32. } else if len(segs) == 1 {
  33. cl.options = append(cl.options, newOption(segs[0], ""))
  34. } else {
  35. cl.options = append(cl.options, newOption(segs[0], strings.Join(segs[1:], " ")))
  36. }
  37. }
  38. return cl, nil
  39. }
  40. type Option struct {
  41. Key string
  42. Value string
  43. }
  44. func newOption(key string, val string) Option {
  45. val = strings.TrimRight(val, " ")
  46. return Option{
  47. Key: key,
  48. Value: val,
  49. }
  50. }
  51. func (o Option) ToString() string {
  52. if o.Value == "" {
  53. return o.Key
  54. }
  55. return o.Key + " " + o.Value
  56. }
  57. type OptionFilter func(Option) bool
  58. func (cl *Cmdline) FilterOption(filter OptionFilter) {
  59. opts := make([]Option, 0)
  60. for _, op := range cl.options {
  61. if filter(op) {
  62. continue
  63. }
  64. opts = append(opts, op)
  65. }
  66. cl.options = opts
  67. }
  68. func (cl *Cmdline) AddOption(opts ...Option) *Cmdline {
  69. cl.options = append(cl.options, opts...)
  70. return cl
  71. }
  72. func (cl *Cmdline) ToString() string {
  73. opts := make([]string, 0)
  74. for i := range cl.options {
  75. opts = append(opts, cl.options[i].ToString())
  76. }
  77. return strings.Join(opts, " -")
  78. }