convert.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package compatibility
  14. import (
  15. "fmt"
  16. "os"
  17. "github.com/docker/compose/v2/cmd/compose"
  18. )
  19. func getBoolFlags() []string {
  20. return []string{
  21. "--debug", "-D",
  22. "--verbose",
  23. "--tls",
  24. "--tlsverify",
  25. }
  26. }
  27. func getStringFlags() []string {
  28. return []string{
  29. "--tlscacert",
  30. "--tlscert",
  31. "--tlskey",
  32. "--host", "-H",
  33. "--context",
  34. "--log-level",
  35. }
  36. }
  37. var argToActualFlag = map[string]string{
  38. "--verbose": "--debug",
  39. // docker cli has deprecated -h to avoid ambiguity with -H, while docker-compose still support it
  40. "-h": "--help",
  41. // redirect --version pseudo-command to actual command
  42. "--version": "version",
  43. "-v": "version",
  44. }
  45. // Convert transforms standalone docker-compose args into CLI plugin compliant ones
  46. func Convert(args []string) []string {
  47. var rootFlags []string
  48. command := []string{compose.PluginName}
  49. l := len(args)
  50. for i := 0; i < l; i++ {
  51. arg := args[i]
  52. if arg[0] != '-' {
  53. // not a top-level flag anymore, keep the rest of the command unmodified
  54. if arg == compose.PluginName {
  55. i++
  56. }
  57. command = append(command, args[i:]...)
  58. break
  59. }
  60. if actualFlag, ok := argToActualFlag[arg]; ok {
  61. arg = actualFlag
  62. }
  63. if contains(getBoolFlags(), arg) {
  64. rootFlags = append(rootFlags, arg)
  65. continue
  66. }
  67. if contains(getStringFlags(), arg) {
  68. i++
  69. if i >= l {
  70. fmt.Fprintf(os.Stderr, "flag needs an argument: '%s'\n", arg)
  71. os.Exit(1)
  72. }
  73. rootFlags = append(rootFlags, arg, args[i])
  74. continue
  75. }
  76. command = append(command, arg)
  77. }
  78. return append(rootFlags, command...)
  79. }
  80. func contains(array []string, needle string) bool {
  81. for _, val := range array {
  82. if val == needle {
  83. return true
  84. }
  85. }
  86. return false
  87. }