0%

Xcode自动修改文件以及自动打包集合

Shell介绍

  • 当前文件的目录
1
BASE_PATH=$(cd `dirname $0`; pwd)
  • 获取父目录
1
2
3
4
5
6
7
8
9
fadir()
{
local this_dir=`pwd`
local child_dir="$1"
dirname "$child_dir"
cd $this_dir
}
father_dir=`fadir "/usr/ss/dd/aa"`
echo $father_dir
  • shell打印带颜色文本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
echo -e "\033[字背景颜色;文字颜色m字符串\033[0m"
echo -e "\033[30m 黑色字 \033[0m"
echo -e "\033[31m 红色字 \033[0m"
echo -e "\033[32m 绿色字 \033[0m"
echo -e "\033[33m 黄色字 \033[0m"
echo -e "\033[34m 蓝色字 \033[0m"
echo -e "\033[35m 紫色字 \033[0m"
echo -e "\033[36m 天蓝字 \033[0m"
echo -e "\033[37m 白色字 \033[0m"

echo -e "\033[40;37m 黑底白字 \033[0m"
echo -e "\033[41;37m 红底白字 \033[0m"
echo -e "\033[42;37m 绿底白字 \033[0m"
echo -e "\033[43;37m 黄底白字 \033[0m"
echo -e "\033[44;37m 蓝底白字 \033[0m"
echo -e "\033[45;37m 紫底白字 \033[0m"
echo -e "\033[46;37m 天蓝底白字 \033[0m"
echo -e "\033[47;30m 白底黑字 \033[0m"
  • 字符串中使用变量
1
2
# 变量前面加$即可
"===== $INFO_PLIST_FILE ====="
  • shell if 语句
1
2
3
4
5
6
7
if [[ ... ]]; then
# 不可以留空
elif [[ ... ]]; then
# 不可以留空
else
# 不可以留空
fi
  • shell case语句
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
case $cleanType in
"y" | "Y" | "yes" | "YES" )
echoB "============================== Begin Clean =============================="
xcodebuild clean
echoS "=========================== Success Of Clean ============================"
;;
"n" | "N" | "no" | "NO" )
echoS "============================= Skip To Clean ============================="
;;
* )
echoE " Error Input "
recoverInfo
removeBackupFile
exit 1
;;
esac
  • shell判断上一条命令是否成功
1
2
3
4
if [[ ! $? -eq 0 ]]; then
echoE " Failed Of Run xcodebuild: Clean "
exit 1
fi
  • 创建文件夹
1
2
3
4
5
6
7
8
9
10
11
12
13
14
if [ ! -x "$BACKUP_PATH" ]; then
mkdir "$BACKUP_PATH"
# check
if [ ! -x "$BACKUP_PATH" ]; then
echoE " Failed Of Create Folder ==> BackupPath: $BACKUP_PATH "
exit 1
else
echo "\t\c"
echoS " Success Of Create Folder ==> BackupPath: $BACKUP_PATH "
fi
else
echo "\t\c"
echoS " The Folder Already Exists ==> BackupPath: $BACKUP_PATH "
fi
  • copy file
1
2
3
cp -fr $INFO_PLIST_FILE                $BACKUP_PATH"/Info.plist.back"
cp -fr $PROJECT_FILE $BACKUP_PATH"/project.pbxproj.back"
cp -fr $EXPORT_ARCHIVE_OPTIONS_PILIST_FILE $BACKUP_PATH"/exportArchiveOptions.plist.back"
  • delete dir/file
1
2
rm -rf dir
rm -rf file

Ruby介绍

  • 变量

全局变量前面加$, 类型变量前面加@@, 对象属性前面加@, 普通变量不用处理

  • 函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 定义
def functionName1
...
end

# 调用
functionName1

# 定义
def functionName2 (parameter1 = default1, parameter2 = default2)
...
end

# 调用
functionName2
functionName2 parame1, parame2
  • 当前文件路径
1
currentPath = Pathname::new(File::dirname(__FILE__)).realpath
  • 文件的父路径
1
basePath = currentPath.parent
  • 字符串中使用变量
1
2
# 双引号括起来,#{变量名}即可
"#{basePath}/#{infoPlistDirName}/Info.plist"
  • ruby if 语句
1
2
3
4
5
6
7
if a < 0
...
elsif a > 0 and b < 0
...
else
...
end
  • ruby case 语句
1
2
3
4
5
6
7
8
case value
when 1, 2
...
when 3
...
else
...
end
  • 判断文件夹是否存在,删除、创建文件夹
1
2
3
4
5
6
7
8
9
10
11
# 判断
if File.directory?"#{backupPath}"
# 强制删除
FileUtils::rm backupPath
FileUtils::rm_r backupPath
# 非强制删除
Dir::rmdir backupPath
end
# 创建
Dir::mkdir backupPath
FileUtils::mkdir backupPath
  • copy file
1
2
FileUtils::cp infoPlistFile, "#{backupPath}/Info.plist.bak"
FileUtils::cp_r infoPlistFile, "#{backupPath}/Info.plist.bak"
  • delete dir/file
1
2
3
4
5
FileUtils::rm file
FileUtils::rm_r file

FileUtils::rm dirPath
FileUtils::rm_r dirPath

Xcode Build 工具

  • plist文件修改

/usr/libexec/PlistBuddy

1
/usr/libexec/PlistBuddy -c "Set :CFBundleDisplayName $DISPLAY_NAME" $INFO_PLIST_FILE
  • xcodebuild

    • clean

      1
      2
      3
      4
      xcodebuild clean\
      -workspace "./$WORKSPACE_NAME"\
      -scheme "$SCHEME_NAME"\
      -configuration "$configuration"
    • build archive

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      xcodebuild\
      build\
      -workspace "$WORKSPACE_NAME"\
      -scheme "$SCHEME_NAME"\
      -configuration "$configuration"\
      -archivePath "$archivePath"\
      CODE_SIGN_IDENTITY="$codeSignIdentity"\
      PROVISIONING_PROFILE="$profileName"

      xcodebuild\
      archive\
      -workspace "$WORKSPACE_NAME"\
      -scheme "$SCHEME_NAME"\
      -configuration "$configuration"\
      -archivePath "$archivePath"\
      CODE_SIGN_IDENTITY="$codeSignIdentity"\
      PROVISIONING_PROFILE="$profileName"
    • exportArchive

      1
      2
      3
      4
      5
      xcodebuild\
      -exportArchive\
      -exportOptionsPlist "$EXPORT_ARCHIVE_OPTIONS_PILIST_FILE"\
      -archivePath "$archivePath"\
      -exportPath "$exportPath"
    • exportOptionsPlist

      Available keys for -exportOptionsPlist:

Key Type Description
compileBitcode Bool For non-App Store exports, should Xcode re-compile the app from bitcode? Defaults to YES.
embedOnDemandResourcesAssetPacksInBundle Bool For non-App Store exports, if the app uses On Demand Resources and this is YES, asset packs are embedded in the app bundle so that the app can be tested without a server to host asset packs. Defaults to YES unless onDemandResourcesAssetPacksBaseURL is specified.
iCloudContainerEnvironment \ For non-App Store exports, if the app is using CloudKit, this configures the “com.apple.developer.icloud-container-environment” entitlement. Available options: Development and Production. Defaults to Development.
manifest Dictionary For non-App Store exports, users can download your app over the web by opening your distribution manifest file in a web browser. To generate a distribution manifest, the value of this key should be a dictionary with three sub-keys: appURL, displayImageURL, fullSizeImageURL. The additional sub-key assetPackManifestURL is required when using on demand resources.
method String Describes how Xcode should export the archive. Available options: app-store, ad-hoc, package, enterprise, development, and developer-id. The list of options varies based on the type of archive. Defaults to development.
onDemandResourcesAssetPacksBaseURL String For non-App Store exports, if the app uses On Demand Resources and embedOnDemandResourcesAssetPacksInBundle isn’t YES, this should be a base URL specifying where asset packs are going to be hosted. This configures the app to download asset packs from the specified URL.
teamID String The Developer Portal team to use for this export. Defaults to the team used to build the archive.
thinning String For non-App Store exports, should Xcode thin the package for one or more device variants? Available options: (Xcode produces a non-thinned universal app), (Xcode produces a universal app and all available thinned variants), or a model identifier for a specific device (e.g. “iPhone7,1”). Defaults to .
uploadBitcode Bool For App Store exports, should the package include bitcode? Defaults to YES.
uploadSymbols Bool For App Store exports, should the package include symbols? Defaults to YES.

markdown表格解析不好,放张图吧:

export options plist

Fastlane介绍

fastlane logo

用于项目打包等,Fastlane的一套功能非常强大,远远不止只是打包一种功能,建议到官方文档或者github学习。

fastlane tree

官方文档

Github Link

xcode-select Install Command: xcode-select --install

fastlane Install Command: sudo gem install fastlane -NV

xcodeproj介绍

用于修改项目的配置,可以用它来修改Xcodeproject文件CocoaPods就是使用的xcodeproj进行创建Pods.xcodeproj项目的。

Github Link

Install Command: [sudo] gem install xcodeproj

使用方法

不太建议直接使用,建议学会之后自己写一套适合自己当前项目需求的脚本,这样更符合各个项目的需求。

第一种:run.sh + change_projectpbxproj.rb

将run.sh和change_projectpbxproj.rb放入项目的跟目录下

第二种:Fastfile + change_projectpbxproj.rb

将Fastfile和change_projectpbxproj.rb放入项目的fastlane目录下

注意修改代码

修改部分代码为自己的项目配置,scheme、证书等

代码

change_projectpbxproj.rb

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
# change_projectpbxproj.rb
# chmod u+x change_projectpbxproj.rb

require 'xcodeproj'

# ======================================================================================================================================= 获取rootTarget
# 获取rootTarget
def getRootTarget (project)
target = {}
project.targets.each do |tar|
if tar.name == "wanjia2B"
target = tar
break
end
end
return target
end

# ======================================================================================================================================= 获取对应target的sectionObject
# 从project中获取rootTarget对应的sectionObject
def getRootTargetSectionObject (project, target)
sectionObject = {}
project.objects.each do |obj|
if obj.uuid == target.uuid
sectionObject = obj
break
end
end
return sectionObject
end

# ======================================================================================================================================= 配置project/target/sectionObject
# 修改target的配置和sectionObject的配置
# target中主要是profile(PROVISIONING_PROFILE_SPECIFIER和PROVISIONING_PROFILE)和bundleID(PRODUCT_BUNDLE_IDENTIFIER)的设置
# sectionObject中主要是设置CODE_SIGN_ENTITLEMENTS=xxx.entitlements属性删除或添加(apple push相关)和证书CODE_SIGN_IDENTITY / CODE_SIGN_IDENTITY[sdk=iphoneos*]
# 如果需要修改开发团队标记:
# => project中需要修改DevelopmentTeam : project.root_object.attributes["TargetAttributes"][target.uuid]["DevelopmentTeam"] = "xxxxxx"
# => sectionObject中需要修改DEVELOPMENT_TEAM : config.build_settings["DEVELOPMENT_TEAM"] = "xxxxxx"
def settingProjectAndTargetAndSectionObject (project, target, sectionObject)

####################################设置target####################################
# 设置target的PROVISIONING_PROFILE_SPECIFIER(证书)和PRODUCT_BUNDLE_IDENTIFIER(bundleID)
target.build_configurations.each do |config|
if config.name == "Debug"
config.build_settings["PROVISIONING_PROFILE_SPECIFIER"] = $debugProfileName
elsif config.name == "Release"
config.build_settings["PROVISIONING_PROFILE_SPECIFIER"] = $releaseProfileName
end
config.build_settings["PROVISIONING_PROFILE"]=""
config.build_settings["PRODUCT_BUNDLE_IDENTIFIER"] = $bundleID
end


####################################设置project####################################
# 设置apple Push是否关闭,如果使用wanjiaWildcard的profile则关闭
if $debugProfileName == "wanjiaWildcard" || $releaseProfileName == "wanjiaWildcard"
project.root_object.attributes["TargetAttributes"][target.uuid]["SystemCapabilities"]["com.apple.Push"]["enabled"] = 0
else
project.root_object.attributes["TargetAttributes"][target.uuid]["SystemCapabilities"]["com.apple.Push"]["enabled"] = 1
end
# 修改DEVELOPMENT_TEAM
# project.root_object.attributes["TargetAttributes"][target.uuid]["DevelopmentTeam"] = "xxxxxx"


#################################设置sectionObject#################################
# 设置sectionObj中的修改CODE_SIGN_ENTITLEMENTS=xxx.entitlements属性删除
# 或添加(apple push相关)和证书的设置 CODE_SIGN_IDENTITY 删除CODE_SIGN_ENTITLEMENTS
sectionObject.build_configurations.each do |config|
if config.name == "Debug"
# 修改debug证书等操作
# 修改CODE_SIGN_IDENTITY
config.build_settings["CODE_SIGN_IDENTITY"] = $debugCodeSignIdentity
config.build_settings["CODE_SIGN_IDENTITY[sdk=iphoneos*]"] = $debugCodeSignIdentity

elsif config.name == "Release"
# 修改release证书等操作
# 修改CODE_SIGN_IDENTITY
config.build_settings["CODE_SIGN_IDENTITY"] = $releaseCodeSingIdentity
config.build_settings["CODE_SIGN_IDENTITY[sdk=iphoneos*]"] = $releaseCodeSingIdentity
end
# 修改DEVELOPMENT_TEAM
# config.build_settings["DEVELOPMENT_TEAM"] = "xxxxxx"

# 删除CODE_SIGN_ENTITLEMENTS
if $debugProfileName == "wanjiaWildcard" || $releaseProfileName == "wanjiaWildcard"
config.build_settings.delete("CODE_SIGN_ENTITLEMENTS")
else
config.build_settings["CODE_SIGN_ENTITLEMENTS"] = "wanjia2B.entitlements"
end
end
######################################设置完成######################################
end

# ======================================================================================================================================= 设置信息(弃用)
# # 设置环境变量,现在提前在environment.sh中进行判断了
# def setEenvironmentValues
# case $projectEenvironment
# when 1
# $bundleID = "com.pingan.wanjiaBDev"
# $debugProfileName = "wanjiaWildcard"
# $releaseProfileName = "wanjiaWildcard"
# when 2
# $bundleID = "com.pingan.wanjiaBTest"
# $debugProfileName = "wanjiaWildcard"
# $releaseProfileName = "wanjiaWildcard"
# else
# $bundleID = "com.pingan.wanjiaB"
# $debugProfileName = "wanjiaBDev"
# $releaseProfileName = "wanjiaBAdhoc"
# end

# print "\t\tbundleID is: #{$bundleID}\n"
# print "\t\tdebugProfileName is: #{$debugProfileName}\n"
# print "\t\treleaseProfileName is: #{$releaseProfileName}\n"
# end



# ======================================================================================================================================= Begin
# $projectEenvironment = ARGV[0].to_i
$pbxprojFilePath = ARGV[0]
$bundleID = ARGV[1]
$debugCodeSignIdentity = ARGV[2]
$debugProfileName = ARGV[3]
$releaseCodeSingIdentity = ARGV[4]
$releaseProfileName = ARGV[5]

# setEenvironmentValues

project = Xcodeproj::Project.open($pbxprojFilePath)
target = getRootTarget project
sectionObject = getRootTargetSectionObject project, target

settingProjectAndTargetAndSectionObject project, target, sectionObject

project.save

# 运行成功 退出0
exit 0

# ======================================================================================================================================= End

Fastfile

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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# Customise this file, documentation can be found here:
# https://github.com/fastlane/fastlane/tree/master/fastlane/docs
# All available actions: https://docs.fastlane.tools/actions
# can also be listed using the `fastlane actions` command

# Change the syntax highlighting to Ruby
# All lines starting with a # are ignored when running `fastlane`

# If you want to automatically update fastlane if a new version is available:
# update_fastlane

# This is the minimum version number required.
# Update this, if you use features of a newer version


fastlane_version "2.28.3"

default_platform :ios

platform :ios do

schemeName = "wanjia2B"

infoPlistDirName = "wanjia"

xcodeprojFile = "#{schemeName}.xcodeproj"

workspaceName = "#{schemeName}.xcworkspace"

basePath = Pathname::new(File::dirname(__FILE__)).realpath.parent

infoPlistFile = "#{basePath}/#{infoPlistDirName}/Info.plist"

pbxprojFilePath = "#{basePath}/#{xcodeprojFile}"

pbxprojFile = "#{pbxprojFilePath}/project.pbxproj"

# 其他配置文件
configFile = "#{basePath}/wanjia/Headers/PAAppConfig.swift"

backupPath = "#{basePath}/.backup_info"

isBackup = false


# default env: AppStore
env = "appstore"
displayName = "万家医疗"
bundleID = "com.pingan.wanjiaB"
debugProfileName="wanjiaBDev"
releaseProfileName="wanjiaBDistribution"
debugCodeSignIdentity="iPhone Developer: bingyu zhou (ES59BFTTFG)"
releaseCodeSignIdentity="iPhone Distribution: PingAn Wanjia Healthcare Investment Management Co., Ltd (6GA5676ZM3)"
exportMethod="app-store"

desc "初始化信息"
private_lane :setupInfomations do |options|
putsB "Begin Get Environment Values"
env = String(options[:env] || "appstore")
case env
when "appstore", "0"
env = "appstore"
# 不操作
when "adhoc", "1"
#Ad-hoc
env = "adhoc"
displayName="万家医疗-AdHoc"
bundleID="com.pingan.wanjiaB"
debugProfileName="wanjiaBDev"
releaseProfileName="wanjiaBAdhoc"
debugCodeSignIdentity="iPhone Developer: bingyu zhou (ES59BFTTFG)"
releaseCodeSignIdentity="iPhone Distribution: PingAn Wanjia Healthcare Investment Management Co., Ltd (6GA5676ZM3)"
exportMethod="ad-hoc"
when "dev", "2"
#dev
env = "dev"
displayName="万家医疗-开发"
bundleID="com.pingan.wanjiaBDev"
debugProfileName="wanjiaWildcard"
releaseProfileName="wanjiaWildcard"
debugCodeSignIdentity="iPhone Developer: bingyu zhou (ES59BFTTFG)"
releaseCodeSignIdentity="iPhone Developer: bingyu zhou (ES59BFTTFG)"
exportMethod="development"
when "test", "3"
#test
env = "test"
displayName="万家医疗-测试"
bundleID="com.pingan.wanjiaBTest"
debugProfileName="wanjiaWildcard"
releaseProfileName="wanjiaWildcard"
debugCodeSignIdentity="iPhone Developer: bingyu zhou (ES59BFTTFG)"
releaseCodeSignIdentity="iPhone Developer: bingyu zhou (ES59BFTTFG)"
exportMethod="development"
else
putsE "Error Environment Type"
exit 1
end

putsI "\t DisplayName: #{displayName} "
putsI "\t BundleID: #{bundleID} "
putsI "\t DebugProfileName: #{debugProfileName} "
putsI "\t ReleaseProfileName: #{releaseProfileName} "
putsI "\t Project Base Path: #{basePath}"
putsI "\t Project File: #{pbxprojFilePath} "
putsI "\t pbxproj File Path: #{pbxprojFilePath} "
putsI "\t Workspace File: #{basePath}/#{workspaceName} "
putsI "\t Info.plist File: #{infoPlistFile} "
putsI "\t project.pbxproj File: #{pbxprojFile} "

putsS "Success Of Get Environment Values"
end

desc "备份信息"
private_lane :backupCurrentInfo do
putsB "Begin Backup Current Infomation: plist xcodeproj"
if File.directory?"#{backupPath}"
FileUtils::rm_r backupPath
end
FileUtils::mkdir backupPath
FileUtils::cp_r infoPlistFile, "#{backupPath}/Info.plist.bak"
FileUtils::cp_r pbxprojFile, "#{backupPath}/project.pbxproj.bak"
FileUtils::cp_r configFile, "#{backupPath}/PAAppConfig.swift.bak"
putsS "Success Of Backup Current Infomation"
isBackup = true
end

desc "删除备份信息"
private_lane :removeBackupInfo do
putsB "Begin Remove Infomation Folder & File ==> BackupPath: #{backupPath}"
if File.directory?"#{backupPath}"
FileUtils::rm_r backupPath
end
putsS "Success Of Remove Infomation Folder & File ==> BackupPath: #{backupPath}"
isBackup = false
end

desc "修改当前信息"
private_lane :changeInfomations do |options|

putsB "Begin Change 'Info.plist' & .pbxproj File ==> Info.plist: #{infoPlistFile} , pbxprojFile: #{pbxprojFile}"
# available options: xcodeproj, plist_path, scheme, app_identifier, display_name, block
update_info_plist(
plist_path: "./wanjia/Info.plist",
app_identifier: bundleID,
display_name: displayName,
)
run_rubyFile_script = "ruby 'change_projectpbxproj.rb' '#{pbxprojFilePath}' '#{bundleID}' '#{debugCodeSignIdentity}' '#{debugProfileName}' '#{releaseCodeSignIdentity}' '#{releaseProfileName}'"
sh run_rubyFile_script

env = String(options[:env] || "appstore")
conf = String(options[:conf] || "debug")
isToAppStore = false
if (env == "appstore" || env == "0") && conf == "release"
isToAppStore = true
end
change_configFile_script = "sed -i '' 's/^.*static let isToAppStore.*$/ static let isToAppStore = #{isToAppStore}/g' #{configFile}"
sh change_configFile_script

# 因为除了改这些之外还要修改其他东西 所以直接用change_projectpbxproj.rb修改算了
# update_app_identifier(
# xcodeproj: xcodeprojFile,
# plist_path: "./#{infoPlistDirName}/Info.plist",
# app_identifier: bundleID,
# )

# update_project_provisioning(
# xcodeproj: xcodeprojFile,
# target_filter: schemeName,
# build_configuration: "Release",
# profile: releaseProfileName,
# certificate: releaseCodeSignIdentity,
# )

# update_project_provisioning(
# xcodeproj: xcodeprojFile,
# target_filter: schemeName,
# build_configuration: "Debug",
# profile: debugProfileName,
# certificate: debugCodeSignIdentity,
# )
putsS "Success Of Change 'Info.plist' & .pbxproj File ==> Info.plist: #{infoPlistFile} , pbxprojFile: #{pbxprojFile}"
end

desc "恢复备份信息并删除备份"
private_lane :recoverInfoations do
putsB "Begin Recover Infomation: plist xcodeproj"
FileUtils::cp_r "#{backupPath}/Info.plist.bak", infoPlistFile
FileUtils::cp_r "#{backupPath}/project.pbxproj.bak", pbxprojFile
FileUtils::cp_r "#{backupPath}/PAAppConfig.swift.bak", configFile
putsS "Success Of Recover Infomation"

removeBackupInfo
isBackup = false
end

desc "输出使用方式"
lane :options do
puts "\033[32m======================================================================================================================================\033[m"
puts "\033[47;30m Environment Configuration: \033[m"
puts " It's Need Install: \033[32mXcode & Ruby\033[m, and Install Ruby Library: \033[32mxcodeproj\033[m & \033[32mfastlane\033[m. "
puts " How To Install Ruby Library 'xcodeproj' ? "
puts " Install Command: \033[35m[sudo] gem install xcodeproj\033[m "
puts " Github Link: \033[35mhttps://github.com/CocoaPods/Xcodeproj\033[m "
puts " How To Install Ruby Library 'fastlane' ? "
puts " Before Install 'fastlane', Make Sure You Have The Latest Version Of The Xcode Command Line Tools Installed: "
puts " Xcode Command Line Install Command: \033[35mxcode-select --install\033[m "
puts " Then 'fastlane' Install Command: \033[35msudo gem install fastlane -NV\033[m "
puts " 'fastlane' Github Link: \033[35mhttps://github.com/fastlane/fastlane\033[m "
puts "\033[32m--------------------------------------------------------------------------------------------------------------------------------------\033[m"
puts "\033[47;30m Parameter Instructions: \033[m"
puts " \033[32m options \033[m"
puts " Show how to use this script. "
puts " eg: fastlane options "
puts " \033[32m setinfo env:'env' conf:'configuration' \033[m"
puts " 'env'can use 'appstore/adhoc/dev/test' or '0/1/2/3', default is 'appstore'; If input error, env is 'appstore'."
puts " 'configuration' can use 'debug' or 'release', default is 'debug; If input error, configuration is 'debug'. "
puts " Change info to 'env' environment & \033[31mSAVE backup\033[m. In the end, will open Xcode. "
puts " eg: fastlane setinfo env:test ; fastlane setinfo "
puts " \033[32m recoverinfo \033[m"
puts " Just recover infomation from the infomation backup, and then, remove backup folder. In the end, will open Xcode. "
puts " eg: fastlane recoverinfo "
puts " \033[32m resetinfo env:'env' conf:'configuration' \033[m"
puts " 'env' default is 'appstore'. Reset infomation to 'env' environment. In the end, will open Xcode. "
puts " 'configuration' can use 'debug' or 'release', default is 'debug; If input error, configuration is 'debug'. "
puts " \033[31mDON'T SAVE backup and REMOVE ALL backup folder/file\033[m. "
puts " eg: fastlane resetinfo env:dev "
puts " \033[32m build \033[m"
puts " Just build. "
puts " eg: fastlane build "
puts " \033[32m archive env:'env' conf:'configuration'\033[m"
puts " 'env' default is 'appstore'; "
puts " 'configuration' can use 'debug' or 'release', default is 'release'; If input error, configuration is 'release'. "
puts " eg: fastlane archive env:appstore conf:release ; fastlane archive env:adhoc; fastlane archive"
puts "\033[32m======================================================================================================================================\033[m"
end


before_all do

end

desc "设置信息,并保存备份;参数 => env:'env'"
lane :setinfo do |options|
setupInfomations options
backupCurrentInfo
changeInfomations options
end

desc "恢复备份信息并删除备份"
lane :recoverinfo do
recoverInfoations
end

desc "仅设置信息,并删除现有备份;参数 => env:'env'"
lane :resetinfo do |options|
setupInfomations options
changeInfomations options
removeBackupInfo
end

desc "编译项目"
lane :build do
cocoapods
xcodebuild(
silent: true,
clean: true,
build: true,
workspace: workspaceName,
scheme: schemeName,
configuration: "Release",
destination: "generic/platform=iOS",
build_settings: {
"CODE_SIGN_IDENTITY" => "",
"CODE_SIGNING_REQUIRED" => "NO"
},
)
end

desc "打包; 参数 => env:'env' conf:debug/release"
lane :archive do |options|
env = String(options[:env] || "appstore")
conf = String(options[:conf] || "release")
if conf == "debug"
configuration = "Debug"
profileName = debugProfileName
codeSignIdentity = debugCodeSignIdentity
else
configuration = "Release"
profileName = releaseProfileName
codeSignIdentity = releaseCodeSignIdentity
end
setinfo env:env, conf:conf


time = Time::new
currentTime = time.strftime("%Y-%m-%d/%H_%M_%S")
buildPath = "#{basePath}/build/#{schemeName}-#{env}/#{currentTime}"
exportPath = "~/Desktop/#{schemeName}-#{env}/#{currentTime}"
customName = "#{schemeName}-#{env}-#{configuration}"
# xcarchiveName ="#{customName}.xcarchive"
ipaName = "#{customName}.ipa"


cocoapods
# sigh(
# app_identifier: bundleID,
# provisioning_name: profileName,
# cert_owner_name: codeSignIdentity,
# skip_install: true,
# skip_fetch_profiles: true,
# skip_certificate_verification: true,
# )

# unlock_keychain(
# path: "/path/to/KeychainName.keychain",
# password: "mysecret"
# )

gym(
silent: true,
clean: true,
workspace: workspaceName,
scheme: schemeName,
configuration: configuration,
export_method: exportMethod,
build_path: buildPath,
output_directory: exportPath,
output_name: ipaName,
)

recoverinfo

putsS "IPA DIR & NAME IS : ipaDir ==> #{exportPath}, ipaName ==> #{ipaName}, archiveDir ==> #{buildPath}"
end


after_all do |lane|

end

error do |lane, exception, options|
putsE "#{lane} Is Failed: Runing Error, is backup? => #{isBackup}"
if "#{lane}" == "build" || "#{lane}" == "archive"
# 发邮件
end

if isBackup == true
recoverInfoations
end
end


# 输出infomation等信息
def putsI (option)
puts "\033[40;37m#{option}\033[m"
end
# 输出开始信息
def putsB (option)
puts "\033[33m#{option}\033[m"
puts ""
end
# 输出成功信息
def putsS (option)
puts "\033[32m#{option}\033[m"
puts ""
end
# 输出error信息
def putsE (option)
puts "\033[41;37m #{option} \033[m"
puts ""
end
end

# More information about multiple platforms in fastlane: https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Platforms.md
# All available actions: https://docs.fastlane.tools/actions

# fastlane reports which actions are used
# No personal data is recorded. Learn more at https://github.com/fastlane/enhancer

run.sh

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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
#bin/sh/
# run.sh
# chmod u+x run.sh

# 格式如下:
# echo -e "\033[字背景颜色;文字颜色m字符串\033[0m"
# echo -e "\033[30m 黑色字 \033[0m"
# echo -e "\033[31m 红色字 \033[0m"
# echo -e "\033[32m 绿色字 \033[0m"
# echo -e "\033[33m 黄色字 \033[0m"
# echo -e "\033[34m 蓝色字 \033[0m"
# echo -e "\033[35m 紫色字 \033[0m"
# echo -e "\033[36m 天蓝字 \033[0m"
# echo -e "\033[37m 白色字 \033[0m"

# echo -e "\033[40;37m 黑底白字 \033[0m"
# echo -e "\033[41;37m 红底白字 \033[0m"
# echo -e "\033[42;37m 绿底白字 \033[0m"
# echo -e "\033[43;37m 黄底白字 \033[0m"
# echo -e "\033[44;37m 蓝底白字 \033[0m"
# echo -e "\033[45;37m 紫底白字 \033[0m"
# echo -e "\033[46;37m 天蓝底白字 \033[0m"
# echo -e "\033[47;30m 白底黑字 \033[0m"

# 打印规则
# echo "\033[33m Begin info \033[m"
# echo "\033[41;37m Failed info \033[m \n"
# echo "\033[32m Success info \033[m \n"


# Available keys for -exportOptionsPlist:
# compileBitcode : Bool
# For non-App Store exports, should Xcode re-compile the app from bitcode? Defaults to YES.

# embedOnDemandResourcesAssetPacksInBundle : Bool
# For non-App Store exports, if the app uses On Demand Resources and this is YES, asset packs are embedded in the app bundle so that the app can be tested without a server to host asset packs. Defaults to YES unless onDemandResourcesAssetPacksBaseURL is specified.

# iCloudContainerEnvironment
# For non-App Store exports, if the app is using CloudKit, this configures the "com.apple.developer.icloud-container-environment" entitlement. Available options: Development and Production. Defaults to Development.

# manifest : Dictionary
# For non-App Store exports, users can download your app over the web by opening your distribution manifest file in a web browser. To generate a distribution manifest, the value of this key should be a dictionary with three sub-keys: appURL, displayImageURL, fullSizeImageURL. The additional sub-key assetPackManifestURL is required when using on demand resources.

# method : String
# Describes how Xcode should export the archive. Available options: app-store, ad-hoc, package, enterprise, development, and developer-id. The list of options varies based on the type of archive. Defaults to development.

# onDemandResourcesAssetPacksBaseURL : String
# For non-App Store exports, if the app uses On Demand Resources and embedOnDemandResourcesAssetPacksInBundle isn't YES, this should be a base URL specifying where asset packs are going to be hosted. This configures the app to download asset packs from the specified URL.

# teamID : String
# The Developer Portal team to use for this export. Defaults to the team used to build the archive.

# thinning : String
# For non-App Store exports, should Xcode thin the package for one or more device variants? Available options: <none> (Xcode produces a non-thinned universal app), <thin-for-all-variants> (Xcode produces a universal app and all available thinned variants), or a model identifier for a specific device (e.g. "iPhone7,1"). Defaults to <none>.

# uploadBitcode : Bool
# For App Store exports, should the package include bitcode? Defaults to YES.

# uploadSymbols : Bool
# For App Store exports, should the package include symbols? Defaults to YES.


# ======================================================================================================================================= 全局变量
SCHEME_NAME="wanjia2B"

INFO_PLIST_DIR="wanjia"

PROJECT_FILE_NAME="$SCHEME_NAME.xcodeproj"

WORKSPACE_NAME="$SCHEME_NAME.xcworkspace"

BASE_PATH=$(cd `dirname $0`; pwd)

INFO_PLIST_FILE="$BASE_PATH/$INFO_PLIST_DIR/Info.plist"

PROJECT_FILE_PATH="$BASE_PATH/$PROJECT_FILE_NAME"

PROJECT_FILE="$PROJECT_FILE_PATH/project.pbxproj"

BACKUP_PATH="$BASE_PATH/.backup_info"

EXPORT_ARCHIVE_OPTIONS_PILIST_FILE="$BASE_PATH/exportArchiveOptions.plist"

# 输出开始信息
echoB() {
echo "\033[33m$1\033[m"
}

# 输出成功信息
echoS() {
echo "\033[32m$1\033[m \n"
}

# 输出error信息
echoE() {
echo "\033[41;37m$1\033[m \n "
}

# 输出infomation等信息
echoI() {
echo "\033[40;37m$1\033[m"
}

# ======================================================================================================================================= 设置信息
setupInfomations() {
echoB " Begin Get Environment Values "
if [[ $ENV_TYPE == "" ]]; then
ENV_TYPE=0
fi
ENV_TYPE=`expr $ENV_TYPE + 0`
# method = app-store, ad-hoc, package, enterprise, development, and developer-id
case $ENV_TYPE in
0 ) # AppStore
DISPLAY_NAME="万家医疗"
BUNDLE_ID="com.pingan.wanjiaB"
DEBUG_PROFILE_NAME="wanjiaBDev"
RELEASE_PROFILE_NAME="wanjiaBDistribution"
DEBUG_CODE_SIGN_IDENTITY="iPhone Developer: bingyu zhou (ES59BFTTFG)"
RELEASE_CODE_SIGN_IDENTITY="iPhone Distribution: PingAn Wanjia Healthcare Investment Management Co., Ltd (6GA5676ZM3)"
EXPORT_MRTHOD="app-store"
;;
1 ) # AdHoc
DISPLAY_NAME="万家医疗"
BUNDLE_ID="com.pingan.wanjiaB"
DEBUG_PROFILE_NAME="wanjiaBDev"
RELEASE_PROFILE_NAME="wanjiaBAdhoc"
DEBUG_CODE_SIGN_IDENTITY="iPhone Developer: bingyu zhou (ES59BFTTFG)"
RELEASE_CODE_SIGN_IDENTITY="iPhone Distribution: PingAn Wanjia Healthcare Investment Management Co., Ltd (6GA5676ZM3)"
EXPORT_MRTHOD="ad-hoc"
;;
2 ) # Dev
DISPLAY_NAME="万家医疗-开发"
BUNDLE_ID="com.pingan.wanjiaBDev"
DEBUG_PROFILE_NAME="wanjiaWildcard"
RELEASE_PROFILE_NAME="wanjiaWildcard"
DEBUG_CODE_SIGN_IDENTITY="iPhone Developer: bingyu zhou (ES59BFTTFG)"
RELEASE_CODE_SIGN_IDENTITY="iPhone Developer: bingyu zhou (ES59BFTTFG)"
EXPORT_MRTHOD="development"
;;
3 ) # Test
DISPLAY_NAME="万家医疗-测试"
BUNDLE_ID="com.pingan.wanjiaBTest"
DEBUG_PROFILE_NAME="wanjiaWildcard"
RELEASE_PROFILE_NAME="wanjiaWildcard"
DEBUG_CODE_SIGN_IDENTITY="iPhone Developer: bingyu zhou (ES59BFTTFG)"
RELEASE_CODE_SIGN_IDENTITY="iPhone Developer: bingyu zhou (ES59BFTTFG)"
EXPORT_MRTHOD="development"
;;
* )
echoE " Error Environment Type "
exit 1
;;
esac

echoI "\t DisplayName: $DISPLAY_NAME "
echoI "\t BundleID: $BUNDLE_ID "
echoI "\t DebugProfileName: $DEBUG_PROFILE_NAME "
echoI "\t ReleaseProfileName: $RELEASE_PROFILE_NAME "
echoI "\t Project Path: $BASE_PATH "
echoI "\t Project File Path: $PROJECT_FILE_PATH "
echoI "\t Workspace File Path: $BASE_PATH/$WORKSPACE_NAME "
echoI "\t Info.plist File: $INFO_PLIST_FILE "
echoI "\t project.pbxproj File: $PROJECT_FILE "

echoS " Success Of Get Environment Values "
}

# ======================================================================================================================================= 备份函数
backupCurrentInfo() {
echoB " Begin Backup Current Infomation: plist xcodeproj "

if [ ! -x "$BACKUP_PATH" ]; then
mkdir "$BACKUP_PATH"
# check
if [ ! -x "$BACKUP_PATH" ]; then
echoE " Failed Of Create Folder ==> BackupPath: $BACKUP_PATH "
exit 1
else
echo "\t\c"
echoS " Success Of Create Folder ==> BackupPath: $BACKUP_PATH "
fi
else
echo "\t\c"
echoS " The Folder Already Exists ==> BackupPath: $BACKUP_PATH "
fi
# unaslias cp
cp -fr $INFO_PLIST_FILE $BACKUP_PATH"/Info.plist.back"
cp -fr $PROJECT_FILE $BACKUP_PATH"/project.pbxproj.back"
cp -fr $EXPORT_ARCHIVE_OPTIONS_PILIST_FILE $BACKUP_PATH"/exportArchiveOptions.plist.back"
echoS " Success Of Backup Current Infomation "
}

# ======================================================================================================================================= 修改Info.plist
changeInfoPlist() {
echoB " Begin Change 'Info.plist' File ==> Info.plist: $INFO_PLIST_FILE "
# 设置CFBundleDisplayName
/usr/libexec/PlistBuddy -c "Set :CFBundleDisplayName $DISPLAY_NAME" $INFO_PLIST_FILE

# # 获取buildNumber并+1
# buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFO_PLIST_FILE")
# echo "New buildNumber is: $buildNumber"
# buildNumber=`expr "$buildNumber + 1"|bc`
# # 设置CFBundleVersion
# /usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" $INFO_PLIST_FILE
echoS " Success Of Change 'Info.plist' File ==> Info.plist: $INFO_PLIST_FILE "
}

# ======================================================================================================================================= 运行ruby脚本修改project文件
runRubyScriptToChangeProjectFile() {
rubyFile="change_projectpbxproj.rb"
echoB " Begin Run Ruby Script To Change 'ProjectFile' ==> Ruby: $rubyFile; ProjectFile: $PROJECT_FILE "
ruby "$rubyFile" "$PROJECT_FILE_PATH" "$BUNDLE_ID" "$DEBUG_CODE_SIGN_IDENTITY" "$DEBUG_PROFILE_NAME" "$RELEASE_CODE_SIGN_IDENTITY" "$RELEASE_PROFILE_NAME"

if [[ $? != 0 ]]; then
echoE " Failed Of Run Ruby Script ==> Ruby: $rubyFile; ProjectFile: $PROJECT_FILE "
# error退出之前恢复并清空备份信息
recoverInfo
removeBackupFile
exit 1
fi
echoS " Success Of Run Ruby Script ==> Ruby: $rubyFile; ProjectFile: $PROJECT_FILE "
}

# ======================================================================================================================================= 更改信息函数: 会更改info.plist和projec文件不会修改exportArchiveOptions.plist
changeInfomation() {
setupInfomations
changeInfoPlist
runRubyScriptToChangeProjectFile
}
# changeInfomation() {
# # change environment value
# setupInfomations
# shellFile="change_infoplist_projectpbxproj.sh"
# echoB " Begin Run Shell To Change Environment Values ==> $shellFile "
# sh "$shellFile" "$BASE_PATH" "$INFO_PLIST_FILE" "$PROJECT_FILE_PATH" "$DISPLAY_NAME" "$BUNDLE_ID" "$DEBUG_PROFILE_NAME" "$RELEASE_PROFILE_NAME"
# if [[ $? != 0 ]]; then
# echoE " Failed Of Run Shell ==> $shellFile "
# # error退出之前恢复并清空备份信息
# recoverInfo
# removeBackupFile
# exit 1
# fi
# echoS " Success Of Run Shell ==> $shellFile "
# # change environment value success
# }

# ======================================================================================================================================= 恢复函数
recoverInfo() {
echoB " Begin Recover Infomation: plist xcodeproj "
cp -fr $BACKUP_PATH"/Info.plist.back" $INFO_PLIST_FILE
cp -fr $BACKUP_PATH"/project.pbxproj.back" $PROJECT_FILE
cp -fr $BACKUP_PATH"/exportArchiveOptions.plist.back" $EXPORT_ARCHIVE_OPTIONS_PILIST_FILE
echoS " Success Of Recover Infomation "
}

# ======================================================================================================================================= 删除备份函数
removeBackupFile() {
echoB " Begin Remove Infomation Folder & File ==> BackupPath: $BACKUP_PATH "
### !!!Dangerous Command, Please Do Not Optionally Modify!!! ###
if [[ $BACKUP_PATH == "" ]]; then
echoE " It Will Run Dangerous Command 'rm -rf' "
exit 1
fi
rm -rf $BACKUP_PATH
echoS " Success Of Remove Infomation Folder & File ==> BackupPath: $BACKUP_PATH "
}

# # ======================================================================================================================================= clean函数
# cleanProjectWithType() {
# cleanType="$1"
# case $cleanType in
# "y" | "Y" | "yes" | "YES" )
# echoB "============================== Begin Clean =============================="
# xcodebuild clean
# echoS "=========================== Success Of Clean ============================"
# ;;
# "n" | "N" | "no" | "NO" )
# echoS "============================= Skip To Clean ============================="
# ;;
# * )
# echoE " Error Input "
# recoverInfo
# removeBackupFile
# exit 1
# ;;
# esac
# }
#
# # ======================================================================================================================================= build函数
# buildProject() {
# # clean?
# cleanType="$1"
# case $cleanType in
# "y" | "Y" | "yes" | "YES" | "n" | "N" | "no" | "NO" )
# ;;
# * )
# read -p " would you need clean(y/n): " cleanType
# ;;
# esac
# cleanProjectWithType $cleanType

# # 编译
# echoB "============================== Begin Compail Source File =============================="
# xcodebuild\
# -workspace $WORKSPACE_NAME\
# -scheme $SCHEME_NAME
# echoS "=========================== Success Of Compail Source File ============================"
# }

# ======================================================================================================================================= 修改export配置: 只有archive时候才需要修改
changeExportArchiveOptionsPlist() {
echoB " Begin Change 'exportArchiveOptions.plist' File ==> exportArchiveOptions.plist: $EXPORT_ARCHIVE_OPTIONS_PILIST_FILE "
/usr/libexec/PlistBuddy -c "Set :method $EXPORT_MRTHOD" "$EXPORT_ARCHIVE_OPTIONS_PILIST_FILE"
echoS " Success Of Change 'exportArchiveOptions.plist' File ==> exportArchiveOptions.plist: $EXPORT_ARCHIVE_OPTIONS_PILIST_FILE "
}

# ======================================================================================================================================= archive函数
archiveProject() {

setupInfomations

if [[ "$1" == "-d" ]]; then
configuration="Debug"
codeSignIdentity="$DEBUG_CODE_SIGN_IDENTITY"
profileName="$DEBUG_PROFILE_NAME"
else
configuration="Release"
codeSignIdentity="$RELEASE_CODE_SIGN_IDENTITY"
profileName="$RELEASE_PROFILE_NAME"
fi

changeExportArchiveOptionsPlist

currentTime="`date +%Y-%m-%d/%H_%M_%S`"
archivePath="build/$SCHEME_NAME-$EXPORT_MRTHOD/$currentTime.xcarchive"
exportPath="~/Desktop/$SCHEME_NAME-$EXPORT_MRTHOD/$currentTime"


# # clean
# echoB "=================================== Begin Clean =================================="
# # xcodebuild clean -project TestAutoPacking.xcodeproj -scheme TestAutoPacking -configuration Release
# # xcodebuild clean -workspace TestAutoPacking.xcworkspace -scheme TestAutoPacking -configuration Release
# # 上面的命令中:
# #   -project TestAutoPacking.xcodeproj:编译项目名称
# #   -workspace TestAutoPacking.xcworkspace:编译工作空间名称
# #   -scheme TestAutoPacking:scheme名称(一般会与你的项目名称相同)
# #   -configuration Release:(Debug/Release)
# xcodebuild clean\
# -workspace "./$WORKSPACE_NAME"\
# -scheme "$SCHEME_NAME"\
# -configuration "$configuration"
# if [[ ! $? -eq 0 ]]; then
# echoE " Failed Of Run xcodebuild: Clean "
# exit 1
# fi
# echoS "================================ Success Of Clean ================================"

# build and archive
echoB "============================= Begin Build & Archive =============================="
# xcodebuild archive -project TestAutoPacking.xcodeproj -scheme TestAutoPacking -archivePath /dandy/xmeAutoArchive/TestAutoPacking.xcarchive
# xcodebuild archive -workspace TestAutoPacking.xcworkspace -scheme TestAutoPacking -archivePath /dandy/xmeAutoArchive/TestAutoPacking.xcarchive


# =========---------------
# xcodebuild\
# archive\
# -workspace "$WORKSPACE_NAME"\
# -scheme "$SCHEME_NAME"\
# -configuration "$configuration"\
# -archivePath "$archivePath"\
# CODE_SIGN_IDENTITY="$codeSignIdentity"\
# PROVISIONING_PROFILE="$profileName"\
# # PRODUCT_BUNDLE_IDENTIFIER="$BUNDLE_ID"

# if [[ ! $? -eq 0 ]]; then
# echoE " Failed Of Run xcodebuild: Build & Archive "
# exit 1
# fi
# echoS "=========================== Success Of Build & Archive ==========================="

# # exportArchive
# echoB "============================== Begin Export Archive =============================="
# # 上面的命令中:
# #   -archivePath /dandy/xmeAutoArchive/TestAutoPacking.xcarchive:刚刚导出的.xcarchive文件的目录
# #   -exportPath /dandy/xmeAutoArchive/TestAutoPacking:将要导出的ipa文件的目录以及文件名
# #   -exportFormat ipa:导出为ipa文件
# #   -exportProvisioningProfile "developmentProfile":你配置的profile文件的名称:
# xcodebuild\
# -exportArchive\
# -exportOptionsPlist "$EXPORT_ARCHIVE_OPTIONS_PILIST_FILE"\
# -archivePath "$archivePath"\
# -exportPath "$exportPath"
# ----------------

pod install

fastlane sigh\
--username "null"\
--app_identifier "${BUNDLE_ID}"\
--provisioning_name "${profileName}"\
--cert_owner_name "${codeSignIdentity}"\
--skip_fetch_profiles "true"\
--skip_certificate_verification "true"\

fastlane gym\
--clean "true"\
--silent "true"\
--workspace "${WORKSPACE_NAME}"\
--scheme "${SCHEME_NAME}"\
--configuration "${configuration}"\
--export_method "${EXPORT_MRTHOD}"\
--output_directory "${exportPath}"\
--output_name "wanjia2B-${EXPORT_MRTHOD}-${configuration}.ipa"
--provisioning_profile_path "${profileName}"
--codesigning_identity "${codeSignIdentity}"
# --archive_path "${archivePath}"\
# fastlane sigh resign ./path/app.ipa --signing_identity "iPhone Distribution: Felix Krause" -p "my.mobileprovision"


if [[ ! $? -eq 0 ]]; then
echoE " Failed Of Run xcodebuild: Export Archive "
exit 1
fi
echoS "============================ Success Of Export Archive ============================"
echo "\033[42;37m Export ipa File Path ==> wanjia2B.ipa: $exportPath \033[0m"
open -a Finder "${exportPath}"
}

# ======================================================================================================================================= help函数
echoHelp() {
echo ""
echo "\033[47;30m Environment Configuration: \033[m"
echo " First: Move The Files To You Project Root Directory;"
echo " And Then: It's Need Install: \033[32mXcode & Ruby\033[m, and Install Ruby Library: \033[32mxcodeproj\033[m. "
echo " How To Install Ruby Library 'xcodeproj' ? "
echo " Install Command: \033[35m[sudo] gem install xcodeproj\033[m "
echo " Github Link: \033[35mhttps://github.com/CocoaPods/Xcodeproj\033[m "
echo ""
echo "\033[47;30m Parameter Instructions: \033[m"
echo " \033[32m -h | --help \033[m"
echo " Show how to use this shell script. "
echo " \033[32m 'num'\033[m"
echo " It will run: setInfo 'num' ; 0 is AppStore; 1 is AdHoc; 2 is Dev; 3 is Test. "
echo " eg: info.sh 1 "
echo " \033[32m setInfo 'num'\033[m"
echo " 'num' default is 0. Change info to 'num' environment & \033[31mSAVE backup\033[m. In the end, will open Xcode. "
echo " eg: info.sh changeInfo 1 "
echo " \033[32m recoverInfo\033[m"
echo " Just recover infomation from the infomation backup, and then, remove backup folder. In the end, will open Xcode. "
echo " eg: info.sh recoverInfo "
echo " \033[32m reset 'num'\033[m"
echo " 'num' default is 0. Just reset infomation to 'num' environment & \033[31mDON'T SAVE backup and REMOVE ALL backup folder/file\033[m. In the end, will open Xcode. "
echo " eg: info.sh reset 0 "
echo " \033[32m archive 'num' 'configuration'\033[m"
echo " 'num' default is 0; 'configuration' can use '-d' or '-r', default is '-r', if input error, configuration is '-r'. "
echo " eg: info.sh archive 0 -d "
echo ""
}

# ======================================================================================================================================= 解析运行参数函数
parserParameter() {
parameter="$1"
case $parameter in
"" | "-h" | "--help" )
echoHelp
;;

# 仅仅修改信息
"setInfo" )
ENV_TYPE=$2
backupCurrentInfo
changeInfomation
open -a Xcode $WORKSPACE_NAME
;;

# # 仅仅进行编译
# "build" )
# buildProject
# ;;

# 仅仅恢复信息
"recoverInfo" )
echo " recover is copy the backup files to cover current files, if you change some infomation before this command, you will lose the change, suggest you run 'reset' command. "
read -p " would you need recover from backup; maybe lose some infomation (only input 'Y/y' will recoverInfo): " recoverSureType
if [[ "$recoverSureType" == "y" || "$recoverSureType" == "Y" ]]; then
recoverInfo
removeBackupFile
open -a Xcode $WORKSPACE_NAME
fi
;;

# reset所有信息并不保存且删除所有备份
"reset" )
read -p " would you need reset to normal(only input 'Y/y' will reset): " resetSureType
if [[ "$resetSureType" == "y" || "$resetSureType" == "Y" ]]; then
ENV_TYPE=$2
changeInfomation
changeExportArchiveOptionsPlist
removeBackupFile
open -a Xcode $WORKSPACE_NAME
fi
;;
# 打包
"archive" )
ENV_TYPE=$2
archiveProject $3
;;

* )
# 判断是否是数字
# if grep '^[[:digit:]]*$' <<< "$1"; then
expr $1 + 1 &> /dev/null
if [[ $1 == -1 || $? -eq 0 ]]; then
# 是数字
parserParameter "setInfo" $1
else
# 不是数字
echoE " Error Parameter Type "
exit 1
fi
;;
esac
exit 0
}

# ======================================================================================================================================= Begin
parserParameter $1 $2 $3
# ======================================================================================================================================= End