command_line.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. }
  22. // parseCommandLineParams breaks the comma-separated list of key=value pairs
  23. // in the parameter (a member of the request protobuf) into a key/value map.
  24. // It then sets command line parameter mappings defined by those entries.
  25. func parseCommandLineParams(parameter string) (*commandLineParams, error) {
  26. ps := make(map[string]string)
  27. for _, p := range strings.Split(parameter, ",") {
  28. if p == "" {
  29. continue
  30. }
  31. i := strings.Index(p, "=")
  32. if i < 0 {
  33. return nil, fmt.Errorf("invalid parameter %q: expected format of parameter to be k=v", p)
  34. }
  35. k := p[0:i]
  36. v := p[i+1:]
  37. if v == "" {
  38. return nil, fmt.Errorf("invalid parameter %q: expected format of parameter to be k=v", k)
  39. }
  40. ps[k] = v
  41. }
  42. clp := &commandLineParams{
  43. importMap: make(map[string]string),
  44. }
  45. for k, v := range ps {
  46. switch {
  47. case k == "import_prefix":
  48. clp.importPrefix = v
  49. // Support import map 'M' prefix per https://github.com/golang/protobuf/blob/6fb5325/protoc-gen-go/generator/generator.go#L497.
  50. case len(k) > 0 && k[0] == 'M':
  51. clp.importMap[k[1:]] = v // 1 is the length of 'M'.
  52. case len(k) > 0 && strings.HasPrefix(k, "go_import_mapping@"):
  53. clp.importMap[k[18:]] = v // 18 is the length of 'go_import_mapping@'.
  54. default:
  55. return nil, fmt.Errorf("unknown parameter %q", k)
  56. }
  57. }
  58. return clp, nil
  59. }