-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.go
263 lines (223 loc) · 8.57 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/bitrise-io/go-android/sdk"
"github.com/bitrise-io/go-android/sdkcomponent"
"github.com/bitrise-io/go-android/sdkmanager"
"github.com/bitrise-io/go-steputils/stepconf"
"github.com/bitrise-io/go-steputils/tools"
"github.com/bitrise-io/go-utils/fileutil"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/v2/env"
"github.com/bitrise-io/go-utils/v2/errorutil"
. "github.com/bitrise-io/go-utils/v2/exitcode"
"github.com/bitrise-io/go-utils/v2/log/colorstring"
"github.com/bitrise-steplib/steps-install-missing-android-tools/androidcomponents"
"github.com/hashicorp/go-version"
"github.com/kballard/go-shellquote"
)
const androidNDKHome = "ANDROID_NDK_HOME"
type Inputs struct {
GradlewPath string `env:"gradlew_path,file"`
AndroidHome string `env:"ANDROID_HOME"`
AndroidSDKRoot string `env:"ANDROID_SDK_ROOT"`
NDKVersion string `env:"ndk_version"`
GradlewDependenciesOptions string `env:"gradlew_dependencies_options"`
}
type Config struct {
GradlewPath string
AndroidHome string
AndroidSDKRoot string
NDKVersion string
GradlewDependenciesOptions []string
}
func main() {
exitCode := run()
os.Exit(int(exitCode))
}
func run() ExitCode {
androidToolsInstaller := AndroidToolsInstaller{}
config, err := androidToolsInstaller.ProcessInputs()
if err != nil {
log.Errorf(errorutil.FormattedError(fmt.Errorf("Failed to process Step inputs: %w", err)))
return Failure
}
if err := androidToolsInstaller.Run(config); err != nil {
log.Errorf(errorutil.FormattedError(fmt.Errorf("Failed to execute Step: %w", err)))
return Failure
}
return Success
}
type AndroidToolsInstaller struct {
}
func (i AndroidToolsInstaller) ProcessInputs() (Config, error) {
var inputs Inputs
if err := stepconf.Parse(&inputs); err != nil {
return Config{}, err
}
gradlewDependenciesOptions, err := shellquote.Split(inputs.GradlewDependenciesOptions)
if err != nil {
return Config{}, fmt.Errorf("provided gradlew_dependencies_options (%s) are not valid CLI parameters: %s", inputs.GradlewDependenciesOptions, err)
}
config := Config{
GradlewPath: inputs.GradlewPath,
AndroidHome: inputs.AndroidHome,
AndroidSDKRoot: inputs.AndroidSDKRoot,
NDKVersion: inputs.NDKVersion,
GradlewDependenciesOptions: gradlewDependenciesOptions,
}
fmt.Println()
stepconf.Print(config)
return config, nil
}
func (i AndroidToolsInstaller) Run(config Config) error {
fmt.Println()
log.Infof("Preparation")
// Set executable permission for gradlew
log.Printf("Set executable permission for gradlew")
if err := os.Chmod(config.GradlewPath, 0770); err != nil {
return fmt.Errorf("failed to set executable permission for gradlew: %w", err)
}
// Initialize Android SDK
fmt.Println()
log.Infof("Initialize Android SDK")
androidSdk, err := sdk.NewDefaultModel(sdk.Environment{
AndroidHome: config.AndroidHome,
AndroidSDKRoot: config.AndroidSDKRoot,
})
if err != nil {
return fmt.Errorf("failed to initialize Android SDK: %w", err)
}
fmt.Println()
if config.NDKVersion != "" {
log.Infof("Installing Android NDK")
_, err := version.NewVersion(config.NDKVersion)
if err != nil {
return fmt.Errorf("'%s' is not a valid NDK version. This should be the full version number, such as 23.0.7599858. To see all available versions, run 'sdkmanager --list'", config.NDKVersion)
}
if err := updateNDK(config.NDKVersion, androidSdk); err != nil {
return fmt.Errorf("install new NDK package: %w", err)
}
} else {
log.Infof("Clearing NDK environment")
log.Printf("Unset ANDROID_NDK_HOME")
if err := os.Unsetenv("ANDROID_NDK_HOME"); err != nil {
return fmt.Errorf("unset environment variable: %w", err)
}
if err := tools.ExportEnvironmentWithEnvman("ANDROID_NDK_HOME", ""); err != nil {
return fmt.Errorf("failed to set environment variable: %w", err)
}
}
// Ensure android licences
log.Printf("Ensure android licences")
if err := androidcomponents.InstallLicences(androidSdk); err != nil {
return fmt.Errorf("failed to ensure android licences: %w", err)
}
// Ensure required Android SDK components
fmt.Println()
log.Infof("Ensure required Android SDK components")
if err := androidcomponents.Ensure(androidSdk, config.GradlewPath, config.GradlewDependenciesOptions); err != nil {
return fmt.Errorf("failed to install missing android components: %w", err)
}
fmt.Println()
log.Donef("Required SDK components are installed")
return nil
}
// ndkVersion returns the full version string of a given install path
func ndkVersion(ndkPath string) string {
propertiesPath := filepath.Join(ndkPath, "source.properties")
content, err := fileutil.ReadStringFromFile(propertiesPath)
if err != nil {
return ""
}
for _, line := range strings.Split(content, "\n") {
if strings.Contains(strings.ToLower(line), "pkg.revision") {
lineParts := strings.Split(line, "=")
if len(lineParts) == 2 {
return strings.TrimSpace(lineParts[1])
}
}
}
return ""
}
// targetNDKPath picks the correct path where the requested NDK version should be installed,
// as well as returning if the path needs to be cleaned up before install.
// There are many (deprecated) ways to install NDK, the logic is based on the following:
// https://github.com/android/ndk-samples/wiki/Configure-NDK-Path
// https://developer.android.com/tools/variables
func targetNDKPath(envRepo env.Repository, requestedNDKVersion string) (string, bool) {
if v := envRepo.Get(androidNDKHome); v != "" {
// $ANDROID_NDK_HOME is old and AGP no longer takes it into account,
// but it's an explicit path, so use it if it's set on the system.
// And because we don't know if it's `ndk-bundle` or a specific side-by-side version,
// we return true for cleanup.
log.Warnf("$%s is set to %s", androidNDKHome, v)
log.Warnf("This variable is deprecated and modern Android Gradle Plugin versions no longer take it into account.")
return v, true
}
if androidHome := envRepo.Get("ANDROID_HOME"); androidHome != "" {
// The most modern way is to install NDK versions side-by-side at $ANDROID_HOME/ndk/version
// This is what `sdkmanager` does when installing a specific version (`sdkmanager "ndk;26.3.11579264"`).
ndkPath := filepath.Join(androidHome, "ndk", requestedNDKVersion)
return ndkPath, false
}
if sdkRoot := envRepo.Get("ANDROID_SDK_ROOT"); sdkRoot != "" {
// $ANDROID_SDK_ROOT is deprecated, so it's lower in priority than $ANDROID_HOME
ndkPath := filepath.Join(sdkRoot, "ndk", requestedNDKVersion)
return ndkPath, false
}
if v := envRepo.Get("HOME"); v != "" {
// Worst case: just install to home (and later export as $ANDROID_NDK_HOME)
return filepath.Join(v, "ndk-bundle"), true
}
return "ndk-bundle", true
}
// updateNDK installs the requested NDK version (if not already installed to the correct location).
func updateNDK(version string, androidSdk *sdk.Model) error {
envRepo := env.NewRepository()
targetNDKPath, doCleanup := targetNDKPath(envRepo, version)
currentVersionAtPath := ndkVersion(targetNDKPath)
if currentVersionAtPath != "" {
log.Printf("NDK %s found at %s", colorstring.Cyan(currentVersionAtPath), targetNDKPath)
} else {
log.Printf("NDK %s %s found at %s", colorstring.Cyan(version), colorstring.Yellow("not"), targetNDKPath)
}
if currentVersionAtPath == version {
log.Donef("NDK %s is already installed", version)
return nil
}
if currentVersionAtPath != "" || doCleanup {
log.Printf("Removing existing NDK...")
if err := os.RemoveAll(targetNDKPath); err != nil {
return err
}
log.Printf("Done")
}
log.Printf("Installing NDK %s with sdkmanager", colorstring.Cyan(version))
sdkManager, err := sdkmanager.New(androidSdk)
if err != nil {
return err
}
ndkComponent := sdkcomponent.NDK{Version: version}
cmd := sdkManager.InstallCommand(ndkComponent)
output, err := cmd.RunAndReturnTrimmedCombinedOutput()
if err != nil {
log.Errorf(output)
return fmt.Errorf("run %s: %w", cmd.PrintableCommandArgs(), err)
}
newNDKHome := filepath.Join(androidSdk.GetAndroidHome(), ndkComponent.InstallPathInAndroidHome())
log.Printf("Done")
log.Printf("Append NDK folder to $PATH")
// Old NDK folder was deleted above, its path can stay in $PATH
if err := tools.ExportEnvironmentWithEnvman("PATH", fmt.Sprintf("%s:%s", os.Getenv("PATH"), newNDKHome)); err != nil {
return err
}
if err := tools.ExportEnvironmentWithEnvman(androidNDKHome, newNDKHome); err != nil {
return err
}
log.Printf("Exported $%s: %s", androidNDKHome, newNDKHome)
return nil
}