...
1
2
3
4
5
6
7
8
9
10
11
12
13
14 package inject
15
16 import "strings"
17
18
19
20
21 func MergeCommands(inject []string, origin []string, args []string) []string {
22
23 scripts := mergeCommandsAction(inject)
24
25
26 scripts += mergeOriginCommandsAndArgs(origin, args)
27
28 return []string{"/bin/sh", "-ec", scripts}
29 }
30
31 func mergeCommandsAction(commands []string) string {
32 scripts := ""
33
34 for i := 0; i < len(commands); i++ {
35 cmd := commands[i]
36 if isCommonScripts(cmd) {
37 if len(commands) <= i+1 {
38 scripts += cmd
39 scripts += "\n"
40 break
41 }
42
43 if strings.HasPrefix(commands[i+1], "-") {
44 i++
45 continue
46 }
47
48 tempScripts := cmd + " "
49 for j := i + 1; j < len(commands); j++ {
50 c := commands[j]
51 if j < len(commands)-1 {
52 c += " "
53 }
54
55 tempScripts += c
56 }
57
58 scripts += tempScripts
59 scripts += "\n"
60 break
61 }
62
63 if len(commands) <= i+1 {
64 scripts += cmd
65 scripts += "\n"
66 break
67 }
68
69 if strings.HasPrefix(commands[i+1], "-") {
70 tempScripts := cmd + " "
71 for j := i + 1; j < len(commands); j++ {
72 if strings.HasPrefix(commands[j], "-") {
73 c := commands[j]
74 if j < len(commands)-1 {
75 c += " "
76 }
77 tempScripts += c
78 continue
79 }
80 }
81 scripts += tempScripts
82 scripts += "\n"
83 break
84 }
85
86 scripts += cmd
87 scripts += "\n"
88 }
89
90 return scripts
91 }
92
93 func mergeOriginCommandsAndArgs(origin []string, args []string) string {
94 commands := append(origin, args...)
95
96 return mergeCommandsAction(commands)
97 }
98
99 func isCommonScripts(cmd string) bool {
100 if isShellScripts(cmd) || isPythonScripts(cmd) {
101 return true
102 }
103
104 return false
105 }
106
107 func isShellScripts(cmd string) bool {
108 if cmd == "bash" || cmd == "sh" ||
109 strings.HasPrefix(cmd, "bash ") || strings.HasPrefix(cmd, "sh ") ||
110 strings.HasPrefix(cmd, "/bin/sh") || strings.HasPrefix(cmd, "/bin/bash") ||
111 strings.HasPrefix(cmd, "/usr/bin/sh") || strings.HasPrefix(cmd, "/usr/bin/bash") ||
112 strings.HasPrefix(cmd, "/usr/share/bin/sh") || strings.HasPrefix(cmd, "/usr/share/bin/bash") {
113 return true
114 }
115
116 return false
117 }
118
119 func isPythonScripts(cmd string) bool {
120 if cmd == "python" || cmd == "python3" ||
121 strings.HasPrefix(cmd, "python ") || strings.HasPrefix(cmd, "python3 ") ||
122 strings.HasPrefix(cmd, "/bin/python") || strings.HasPrefix(cmd, "/bin/python3") ||
123 strings.HasPrefix(cmd, "/usr/bin/python") || strings.HasPrefix(cmd, "/usr/bin/python3") ||
124 strings.HasPrefix(cmd, "/usr/share/bin/python") || strings.HasPrefix(cmd, "/usr/share/bin/python3") {
125 return true
126 }
127
128 return false
129 }
130