convert.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. // Convert transforms standalone docker-compose args into CLI plugin compliant ones
  38. func Convert(args []string) []string {
  39. var rootFlags []string
  40. command := []string{compose.PluginName}
  41. l := len(args)
  42. for i := 0; i < l; i++ {
  43. arg := args[i]
  44. if arg[0] != '-' {
  45. // not a top-level flag anymore, keep the rest of the command unmodified
  46. if arg == compose.PluginName {
  47. i++
  48. }
  49. command = append(command, args[i:]...)
  50. break
  51. }
  52. if arg == "--verbose" {
  53. arg = "--debug"
  54. }
  55. if arg == "-h" {
  56. // docker cli has deprecated -h to avoid ambiguity with -H, while docker-compose still support it
  57. arg = "--help"
  58. }
  59. if arg == "--version" || arg == "-v" {
  60. // redirect --version pseudo-command to actual command
  61. arg = "version"
  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. }