command_line.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2018 Twitch Interactive, Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"). You may not
  4. // use this file except in compliance with the License. A copy of the License is
  5. // located at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // or in the "license" file accompanying this file. This file is distributed on
  10. // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  11. // express or implied. See the License for the specific language governing
  12. // permissions and limitations under the License.
  13. package main
  14. import (
  15. "fmt"
  16. "strings"
  17. )
  18. type commandLineParams struct {
  19. importPrefix string // String to prefix to imported package file names.
  20. importMap map[string]string // Mapping from .proto file name to import path.
  21. tpl bool // generate grpc compatible interface
  22. }
  23. // parseCommandLineParams breaks the comma-separated list of key=value pairs
  24. // in the parameter (a member of the request protobuf) into a key/value map.
  25. // It then sets command line parameter mappings defined by those entries.
  26. func parseCommandLineParams(parameter string) (*commandLineParams, error) {
  27. ps := make(map[string]string)
  28. for _, p := range strings.Split(parameter, ",") {
  29. if p == "" {
  30. continue
  31. }
  32. i := strings.Index(p, "=")
  33. if i < 0 {
  34. return nil, fmt.Errorf("invalid parameter %q: expected format of parameter to be k=v", p)
  35. }
  36. k := p[0:i]
  37. v := p[i+1:]
  38. if v == "" {
  39. return nil, fmt.Errorf("invalid parameter %q: expected format of parameter to be k=v", k)
  40. }
  41. ps[k] = v
  42. }
  43. clp := &commandLineParams{
  44. importMap: make(map[string]string),
  45. }
  46. for k, v := range ps {
  47. switch {
  48. case k == "tpl":
  49. if v == "true" || v == "1" {
  50. clp.tpl = true
  51. }
  52. case k == "import_prefix":
  53. clp.importPrefix = v
  54. // Support import map 'M' prefix per https://github.com/golang/protobuf/blob/6fb5325/protoc-gen-go/generator/generator.go#L497.
  55. case len(k) > 0 && k[0] == 'M':
  56. clp.importMap[k[1:]] = v // 1 is the length of 'M'.
  57. case len(k) > 0 && strings.HasPrefix(k, "go_import_mapping@"):
  58. clp.importMap[k[18:]] = v // 18 is the length of 'go_import_mapping@'.
  59. default:
  60. return nil, fmt.Errorf("unknown parameter %q", k)
  61. }
  62. }
  63. return clp, nil
  64. }