-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
253 lines (214 loc) · 8.27 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
package main
import (
"fmt"
"os"
"github.com/bitrise-io/go-steputils/tools"
"github.com/bitrise-io/go-steputils/v2/stepconf"
v1log "github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/retry"
"github.com/bitrise-io/go-utils/v2/command"
"github.com/bitrise-io/go-utils/v2/env"
"github.com/bitrise-io/go-utils/v2/fileutil"
"github.com/bitrise-io/go-utils/v2/log"
"github.com/bitrise-io/go-xcode/certificateutil"
"github.com/bitrise-io/go-xcode/utility"
"github.com/bitrise-io/go-xcode/v2/autocodesign"
"github.com/bitrise-io/go-xcode/v2/autocodesign/certdownloader"
"github.com/bitrise-io/go-xcode/v2/autocodesign/codesignasset"
"github.com/bitrise-io/go-xcode/v2/autocodesign/devportalclient"
"github.com/bitrise-io/go-xcode/v2/autocodesign/keychain"
"github.com/bitrise-io/go-xcode/v2/autocodesign/localcodesignasset"
"github.com/bitrise-io/go-xcode/v2/autocodesign/projectmanager"
"github.com/bitrise-io/go-xcode/v2/codesign"
"github.com/bitrise-io/go-xcode/v2/devportalservice"
"github.com/bitrise-io/go-xcode/xcodebuild"
)
func failf(format string, args ...interface{}) {
v1log.Errorf(format, args...)
os.Exit(1)
}
func downloadCertificates(certDownloader autocodesign.CertificateProvider, logger log.Logger) ([]certificateutil.CertificateInfoModel, error) {
certificates, err := certDownloader.GetCertificates()
if err != nil {
return nil, fmt.Errorf("failed to download certificates: %s", err)
}
if len(certificates) == 0 {
logger.Warnf("No certificates are uploaded.")
return nil, nil
}
logger.Printf("%d certificates downloaded:", len(certificates))
for _, cert := range certificates {
logger.Printf("- %s", cert)
}
return certificates, nil
}
func main() {
// Parse and validate inputs
var cfg Config
parser := stepconf.NewInputParser(env.NewRepository())
if err := parser.Parse(&cfg); err != nil {
failf("Config: %s", err)
}
stepconf.Print(cfg)
logger := log.NewLogger()
logger.EnableDebugLog(cfg.VerboseLog)
v1log.SetEnableDebugLog(cfg.VerboseLog) // for compatibility
cmdFactory := command.NewFactory(env.NewRepository())
xcodebuildVersion, err := utility.GetXcodeVersion()
if err != nil {
failf("Failed to determine Xcode version: %s", err)
}
logger.Printf("%s (%s)", xcodebuildVersion.Version, xcodebuildVersion.BuildVersion)
logger.Println()
if xcodebuildVersion.MajorVersion >= 11 {
// Resolve Swift package dependencies, so running -showBuildSettings is faster
// Specifying a scheme is required for workspaces
resolveDepsCmd := xcodebuild.NewResolvePackagesCommandModel(cfg.ProjectPath, cfg.Scheme, cfg.Configuration)
if err := resolveDepsCmd.Run(); err != nil {
logger.Warnf("%s", err)
}
}
// Analyze project
fmt.Println()
logger.Infof("Analyzing project")
project, err := projectmanager.NewProject(projectmanager.InitParams{
ProjectOrWorkspacePath: cfg.ProjectPath,
SchemeName: cfg.Scheme,
ConfigurationName: cfg.Configuration,
})
if err != nil {
failf(err.Error())
}
appLayout, err := project.GetAppLayout(cfg.SignUITestTargets)
if err != nil {
failf(err.Error())
}
authType, err := parseAuthType(cfg.BitriseConnection)
if err != nil {
failf("Invalid input: unexpected value for Bitrise Apple Developer Connection (%s)", cfg.BitriseConnection)
}
codesignInputs := codesign.Input{
AuthType: authType,
DistributionMethod: cfg.Distribution,
CertificateURLList: cfg.CertificateURLList,
CertificatePassphraseList: cfg.CertificatePassphraseList,
KeychainPath: cfg.KeychainPath,
KeychainPassword: cfg.KeychainPassword,
}
codesignConfig, err := codesign.ParseConfig(codesignInputs, cmdFactory)
if err != nil {
failf(err.Error())
}
fileManager := fileutil.NewFileManager()
var connection *devportalservice.AppleDeveloperConnection
if cfg.BuildURL != "" && cfg.BuildAPIToken != "" {
f := devportalclient.NewFactory(logger, fileManager)
connection, err = f.CreateBitriseConnection(cfg.BuildURL, cfg.BuildAPIToken)
if err != nil {
failf(err.Error())
}
} else {
logger.Warnf(`Connected Apple Developer Portal Account not found: BITRISE_BUILD_URL and BITRISE_BUILD_API_TOKEN envs are not set.
The step will use the connection override inputs as a fallback.
For testing purposes please provide BITRISE_BUILD_URL as json file (file://path-to-json) while setting BITRISE_BUILD_API_TOKEN to any non-empty string.`)
}
connectionInputs := codesign.ConnectionOverrideInputs{
APIKeyPath: cfg.APIKeyPath,
APIKeyID: cfg.APIKeyID,
APIKeyIssuerID: cfg.APIKeyIssuerID,
APIKeyEnterpriseAccount: cfg.APIKeyEnterpriseAccount,
}
appleAuthCredentials, err := codesign.SelectConnectionCredentials(authType, connection, connectionInputs, logger)
if err != nil {
failf(err.Error())
}
keychain, err := keychain.New(cfg.KeychainPath, cfg.KeychainPassword, cmdFactory)
if err != nil {
failf(fmt.Sprintf("failed to initialize keychain: %s", err))
}
devPortalClientFactory := devportalclient.NewFactory(logger, fileManager)
certDownloader := certdownloader.NewDownloader(codesignConfig.CertificatesAndPassphrases, retry.NewHTTPClient().StandardClient())
assetWriter := codesignasset.NewWriter(*keychain)
localCodesignAssetManager := localcodesignasset.NewManager(localcodesignasset.NewProvisioningProfileProvider(), localcodesignasset.NewProvisioningProfileConverter())
devPortalClient, err := devPortalClientFactory.Create(appleAuthCredentials, cfg.TeamID)
if err != nil {
failf(err.Error())
}
if err := devPortalClient.Login(); err != nil {
failf(err.Error())
}
fmt.Println()
logger.TDebugf("Downloading certificates")
certs, err := downloadCertificates(certDownloader, logger)
if err != nil {
failf(err.Error())
}
typeToLocalCerts, err := autocodesign.GetValidLocalCertificates(certs)
if err != nil {
failf(err.Error())
}
// Create codesign manager
manager := autocodesign.NewCodesignAssetManager(devPortalClient, assetWriter, localCodesignAssetManager)
// Auto codesign
distribution := cfg.DistributionType()
var testDevices []devportalservice.TestDevice
if cfg.RegisterTestDevices && connection != nil {
testDevices = connection.TestDevices
}
codesignAssetsByDistributionType, err := manager.EnsureCodesignAssets(appLayout, autocodesign.CodesignAssetsOpts{
DistributionType: distribution,
TypeToLocalCertificates: typeToLocalCerts,
BitriseTestDevices: testDevices,
MinProfileValidityDays: cfg.MinProfileDaysValid,
VerboseLog: cfg.VerboseLog,
})
if err != nil {
failf(fmt.Sprintf("Automatic code signing failed: %s", err))
}
if err := project.ForceCodesignAssets(distribution, codesignAssetsByDistributionType); err != nil {
failf(fmt.Sprintf("Failed to force codesign settings: %s", err))
}
// Export output
fmt.Println()
logger.Infof("Exporting outputs")
teamID := codesignAssetsByDistributionType[distribution].Certificate.TeamID
outputs := map[string]string{
"BITRISE_EXPORT_METHOD": cfg.Distribution,
"BITRISE_DEVELOPER_TEAM": teamID,
}
settings, ok := codesignAssetsByDistributionType[autocodesign.Development]
if ok {
outputs["BITRISE_DEVELOPMENT_CODESIGN_IDENTITY"] = settings.Certificate.CommonName
bundleID, err := project.MainTargetBundleID()
if err != nil {
failf("Failed to read bundle ID for the main target: %s", err)
}
profile, ok := settings.ArchivableTargetProfilesByBundleID[bundleID]
if !ok {
failf("No provisioning profile ensured for the main target")
}
outputs["BITRISE_DEVELOPMENT_PROFILE"] = profile.Attributes().UUID
}
if distribution != autocodesign.Development {
settings, ok := codesignAssetsByDistributionType[distribution]
if !ok {
failf("No codesign settings ensured for the selected distribution type: %s", distribution)
}
outputs["BITRISE_PRODUCTION_CODESIGN_IDENTITY"] = settings.Certificate.CommonName
bundleID, err := project.MainTargetBundleID()
if err != nil {
failf(err.Error())
}
profile, ok := settings.ArchivableTargetProfilesByBundleID[bundleID]
if !ok {
failf("No provisioning profile ensured for the main target")
}
outputs["BITRISE_PRODUCTION_PROFILE"] = profile.Attributes().UUID
}
for k, v := range outputs {
logger.Donef("%s=%s", k, v)
if err := tools.ExportEnvironmentWithEnvman(k, v); err != nil {
failf("Failed to export %s=%s: %s", k, v, err)
}
}
}