×

【CI】持续集成-第一篇 fastlane

96
微微雨雪
2017.06.09 10:14* 字数 988

安装 fastlane

fastlane 官方给出了3种安装方式,根据个人喜好自由选择。

Homebrew Installer Script Rubygems
macOS macOS macOS or </br>Linux with Ruby 2.0.0</br> or above
brew cask install fastlane Download the zip file. </br> Then double click on theinstall script (or run it in a terminal window). sudo gem install fastlane -NV

一、fastlane 使用入门

1、cd 到项目根目录
$ cd ./[工程目录]
2、配置fastlane至项目
$ fastlane install
这里会要求你输入appstore账户/密码,以及各种询问,不要盲目选择y。
这里有个坑:Would you like to create your app on iTunes Connect and the Developer Portal? (y/n)
如果你是测试工程的话,一定要选n,否则iTunes Connect生成应用之后没法删除。。

后面会输出一大堆log,这里略过

install 结束之后,会看到你的工程目录下会新增一个fastlane文件夹。

下面会有2个文件:

Appfile
# 这个文件里记录了刚才安装时的一些输入,里面内容可以按需更改
app_identifier "com.xxxxx" # The bundle identifier of your app
apple_id "" # Your Apple email address
team_id "[[DEV_PORTAL_TEAM_ID]]" # Developer Portal Team ID
# you can even provide different app identifiers, Apple IDs and team names per lane:
# More information: https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Appfile.md
Fastfile
platform :ios do
  desc "Runs all the tests"
  #此处 ↑ 省略
  lane :test do
    scan
  end
  #此处 ↓ 省略
end

为了更好阅读,无关代码已省略

在此之前,先介绍一下fastlane actions 可以理解为fastlane提供的一些api,一个action可以理解为一个方法,包括参数和返回值等等。

查询所有的actions

$ fastlane actions

几个常用的action

# gym 自动构建最核心的action
| gym                    | Easily build and sign  | KrauseFx         |
|                        | your app using _gym_   |                  |
# match 自动管理证书 配合github作为证书仓库使用
| match                  | Easily sync your       | KrauseFx         |
|                        | certificates and       |                  |
|                        | profiles across your   |                  |
|                        | team using git         |                  |
# pem 自动管理推送证书
| pem                    | Makes sure a valid     | KrauseFx         |
|                        | push profile is        |                  |
|                        | active and creates a   |                  |
|                        | new one if needed      |                  |

查询某个action的详情,以及需要传入的参数,例:查询gym的详情

$ fastalne action gym

Loading documentation for gym:
+----------------------------------------------+
|                     gym                      |
+----------------------------------------------+
| Easily build and sign your app using _gym_   |
|                                              |
| More information: https://fastlane.tools/gym |
|                                              |
| Created by KrauseFx                          |
+----------------------------------------------+

+------------------+------------------+------------------+------------------+
|                                gym Options                                |
+------------------+------------------+------------------+------------------+
| Key              | Description      | Env Var          | Default          |
+------------------+------------------+------------------+------------------+
| workspace        | Path the         | GYM_WORKSPACE    |                  |
|                  | workspace file   |                  |                  |
| project          | Path the         | GYM_PROJECT      |                  |
|                  | project file     |                  |                  |
| scheme           | The project's    | GYM_SCHEME       |                  |
|                  | scheme. Make     |                  |                  |
|                  | sure it's        |                  |                  |
|                  | marked as        |                  |                  |
|                  | `Shared`         |                  |                  |
3、fastlane 自定义 lane

这里讲一下 fastlane 配置文件 使用的是ruby语言。Fastfile作为fastlane的核心配置文件,我们可以自由修改

lane :test do
  #可以认为它是fastlane的一个方法,内部可按需更改
end

我们可以更改Fastfile,添加自定义方法,以便完成相应功能
推荐大家使用Sublime 选择ruby语言进行编辑

构建SIT环境ipa包

lane :sit do
    # snapshot
    currentTime = Time.new.strftime("%Y-%m-%d-%H-%M")
    ipaName = "SIT-#{currentTime}.ipa"
    gym(
        scheme: "xxxSIT",
        export_method:"ad-hoc",
        silent:true,
        archive_path:"./build/sit/",
        output_directory:"./build/sit/",
        output_name:ipaName

    ) # Build your app - more options available

    # You can also use other beta testing services here (run `fastlane actions`)
end

然后命令行执行它:

$ fastlane sit

执行顺利的话,会在你的 项目目录/build/sit/ 下新增一个xxx.ipa文件

到此,我们已经通过fastlane实现了自动打包功能,基本功能已实现

二、fastlane 进阶

第一部分配置成功之后,或许会有一点成就感,也是一件值得高兴的事,但不要松懈,好戏才刚刚开始。
有一种说法:懒人是推动社会进步的最重要力量
好吧,我承认我很懒,多一行代码都懒得敲
那么问题来了:自动打包完成了,那之后呢,得想办法让它自己跑到测试手里啊,反正我是懒得手动发给测试人员。

1、上传ipa至服务端

去fastlane官网逛了一遍,发现自定义action可以实现

$ fastlane new_action

紧接着输入action名称,然后会生成一个.rb文件

#部分注释已被省略
module Fastlane
  module Actions
    module SharedValues
      MY_ACTION_CUSTOM_VALUE = :MY_ACTION_CUSTOM_VALUE
    end

    class MyActionAction < Action
      def self.run(params)
      end
      def self.available_options
        [
          FastlaneCore::ConfigItem.new(key: :api_token,
                                       env_name: "FL_MY_ACTION_API_TOKEN", 
                                       description: "API Token for MyActionAction", 
                                       end),
        ]
      end

      def self.output
        [
          ['MY_ACTION_CUSTOM_VALUE', 'A description of what this value contains']
        ]
      end

      def self.is_supported?(platform)
        platform == :ios
      end
    end
  end
end

作为一个iOS开发人员,第一眼看到这个文件是懵逼的!
赶紧百度ruby 恶补一下 然后开始我的修改action之路

1、ruby的变量不需要声明
2、输出语句:UI.message("xxx")
3、FastlaneCore::ConfigItem 声明变量,作用为传入参数,每个参数对应一个声明
4、字典取值方式:params[:upload_url]
5、字典赋值方式:paramsDict = { 'envType' => "envType"}
6、ruby网络请求:require 'faraday'

准备工作差不多了,下面开始修改:

require 'faraday'
require 'faraday_middleware'

module Fastlane
    module Actions
        module SharedValues
            UPLOAD_TO_TTEL_CUSTOM_VALUE = :UPLOAD_TO_TTEL_CUSTOM_VALUE
        end

        class UploadToTtelAction < Action
            def self.run(params)
            # 执行到这里,会读传入参数,这里会使用变量接收
            # host, envType, prodType, changeLog
            upload_url = params[:upload_url]
            if upload_url.nil?
              UI.user_error!("You have to provide a upload url")
            end

            envType = params[:envType]
            if envType.nil?
              UI.user_error!("You have to provide the envType")
            end

            prodType = params[:prodType]
            if prodType.nil?
              UI.user_error!("You have to provide the prodType")
            end

            changeLog = params[:changeLog]
            if changeLog.nil?
              changeLog = ''
            end

            # 这里 IPA_OUTPUT_PATH 是一个全局变量 需在fastfile里进行赋值
            build_file = ENV["IPA_OUTPUT_PATH"]
            if build_file.nil?
              UI.user_error!("IPA_OUTPUT_PATH is nil.")
            end

            UI.message("upload_url: #{upload_url}")
            UI.message("envType: #{envType}")
            UI.message("prodType: #{prodType}")
            UI.message("changeLog: #{changeLog}")

            UI.message("build_file: #{build_file}")
            # start upload
            conn_options = {
              request: {
                timeout:       1000,
                open_timeout:  300
              }
            }

            # 网络请求客户端 初始化
            ttel_client = Faraday.new(nil, conn_options) do |c|
              c.request :multipart
              c.request :url_encoded
              c.response :json, content_type: /\bjson$/
              c.adapter :httpclient
              c.ssl.verify = false
            end

            # 网络请求参数
            paramsDict = {
              'envType' => "#{envType}",
              'prodType' => "#{prodType}",
              'changeLog' => "#{changeLog}",

              'package' => Faraday::UploadIO.new(build_file, 'application/octet-stream')
            }
            UI.message "Start upload #{build_file} to ttel server..."
            response = ttel_client.post upload_url, paramsDict
            info = response.body

            # 请求结束 验证返回值
            if info["code"] == 1
              UI.success "Upload success. "
            else
              UI.user_error!("Upload failed. error info : #{info}")
            end
          end

          #####################################################
          # @!group Documentation
          #####################################################

          def self.description
            "uploading ipa or apk file to ttel Server, Only use for Ttel project"
          end

          def self.details
            # Optional:
            # this is your chance to provide a more detailed description of this action
            "uploading ipa or apk file to ttel Server, Only use for Ttel project"
          end

          def self.available_options
            # Define all options your action supports.

            # Below a few examples
            [
            FastlaneCore::ConfigItem.new(key: :upload_url,
                                         env_name: "UPLOAD_URL",
                                         description: "The url of your upload archive file api, like https://172.16.32.23/app/upload",
                                         is_string: true, # true: verifies the input is a string, false: every kind of value
                                         default_value: ''), # the default value if the user didn't provide one

            FastlaneCore::ConfigItem.new(key: :envType,
                                         env_name: "ENV_TYPE",
                                         description: "envType",
                                         is_string: true, # true: verifies the input is a string, false: every kind of value
                                         default_value: ''), # the default value if the user didn't provide one

            #  host, envType, prodType, changeLog
            FastlaneCore::ConfigItem.new(key: :prodType,
                                         env_name: "PROD_TYPE",
                                         description: "prodType",
                                         is_string: true, # true: verifies the input is a string, false: every kind of value
                                         default_value: ''), # the default value if the user didn't provide one

            FastlaneCore::ConfigItem.new(key: :changeLog,
                                         env_name: "CHANGE_LOG",
                                         description: "changeLog",
                                         is_string: true, # true: verifies the input is a string, false: every kind of value
                                         default_value: '') # the default value if the user didn't provide one

            ]
          end

          def self.output
            [
            ['UPLOAD_TO_TTEL_CUSTOM_VALUE', 'A description of what this value contains']
            ]
          end

          def self.return_value
          end

          def self.authors
            ["https://github.com/xxx"]
          end

          def self.is_supported?(platform)
            platform == :ios
          end
        end
    end
end

大功告成,action写好之后,需要在fastfile调用:

my_action(upload_url:"https://xxx:8081/apiv1/app/upload", envType:envType, prodType: "1001", changeLog:"")

这样,我们就可以在打包完成之后,执行此action,将ipa包上传至我们自己的文件服务器。
又取得了一个阶段性进展,先小小的庆祝一下!

然而,懒是没有止境的···

问题又来了:我其它项目也需要自动打包怎么办,总不能每次都copy文件吧

2、制作插件

由于篇幅原因,请参考fastlane官方文档,亲测不难,半小时左右即可搞定,先准备好梯子。
https://docs.fastlane.tools/plugins/create-plugin/

3、版本号自增

既然我们的目的是打造全自动持续集成,那么版本号还要手动修改也太low了吧

  def auto_add_build_num
    # fastlane build 号 处理代码
    # => https://developer.apple.com/library/content/qa/qa1827/_index.html
    # => currentTime    当前时间 20170401       string
    # => build          build 号               string
    # => lastStr        小数点后2位             string
    # => lastNum        小数点后2位(用于计算)   int
    
    #Build版本文件名
    buildVerFileName = "buildVersion.txt"
    
    buildNumber = ""
    currentTime = Time.new.strftime("%Y%m%d")

    #文件是否存在
    if File.file?(buildVerFileName)
        #存在
        #读取
        buildNumber = File.read(buildVerFileName)
        
         if buildNumber.include?"#{currentTime}."
            # => 为当天版本 计算迭代版本号
           lastStr      = buildNumber[buildNumber.length-2..buildNumber.length-1]
           lastNum      = lastStr.to_i
           lastNum      = lastNum + 1
           lastStr = lastNum.to_s
           
           if lastNum < 10
               lastStr = lastStr.insert(0,"0")
           end
           buildNumber = "#{currentTime}.#{lastStr}"
        else
           buildNumber = "#{currentTime}.01"
        end
    else
         #不存在
         # => 非当天版本 build 号重置
         buildNumber = "#{currentTime}.01"
    end

    puts("*************|    #{buildNumber}   |*************")
    
    # => 更改项目 build 号
    increment_build_number(
                           build_number: buildNumber
                           )
    #读取文件
    buildNumberFile = File.new(buildVerFileName, "w+")
    #将新版本号写入文件
    buildNumberFile.syswrite(buildNumber)
    #关闭
    buildNumberFile.close
  end

自增版本的时候需要注意一点,首次配置一定要修改buildsettings里面的version配置

current project version 随便填
versionsystem 选择apple generic
如果不更改,则可能会出现自增失败


step1.png
step2.png

小结

fastlane提供了一些非常方便的action来帮助我们完成持续集成的任务,并且扩展性很强,支持插件,本文只是粗略的引导各位入门,还有很多action没有一一介绍,如果大家有时间的话可以参考官方文档:https://docs.fastlane.tools

持续集成 fastlane 介绍到此结束,接下来我会更新 gitlab 搭建并集成 fastlane,敬请期待。

CI 持续集成
Web note ad 1