metrics.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 metrics
  14. import (
  15. "os"
  16. "strings"
  17. "github.com/docker/compose-cli/utils"
  18. )
  19. // Track sends the tracking analytics to Docker Desktop
  20. func Track(context string, args []string, status string) {
  21. if isInvokedAsCliBackend() {
  22. return
  23. }
  24. command := GetCommand(args)
  25. if command != "" {
  26. c := NewClient()
  27. c.Send(Command{
  28. Command: command,
  29. Context: context,
  30. Source: CLISource,
  31. Status: status,
  32. })
  33. }
  34. }
  35. func isInvokedAsCliBackend() bool {
  36. executable := os.Args[0]
  37. return strings.HasSuffix(executable, "-backend")
  38. }
  39. func isCommand(word string) bool {
  40. return utils.StringContains(commands, word) || isManagementCommand(word)
  41. }
  42. func isManagementCommand(word string) bool {
  43. return utils.StringContains(managementCommands, word)
  44. }
  45. func isCommandFlag(word string) bool {
  46. return utils.StringContains(commandFlags, word)
  47. }
  48. // GetCommand get the invoked command
  49. func GetCommand(args []string) string {
  50. result := ""
  51. onlyFlags := false
  52. for _, arg := range args {
  53. if arg == "--help" {
  54. result = strings.TrimSpace(arg + " " + result)
  55. continue
  56. }
  57. if arg == "--" {
  58. break
  59. }
  60. if isCommandFlag(arg) || (!onlyFlags && isCommand(arg)) {
  61. result = strings.TrimSpace(result + " " + arg)
  62. if isCommand(arg) && !isManagementCommand(arg) {
  63. onlyFlags = true
  64. }
  65. }
  66. }
  67. return result
  68. }