Class: Fastlane::Actions::AndroidSendAppSizeMetricsAction

Inherits:
Action
  • Object
show all
Defined in:
lib/fastlane/plugin/wpmreleasetoolkit/actions/android/android_send_app_size_metrics.rb

Constant Summary collapse

AAB_FILE_SIZE_KEY =

Keys used by the metrics payload

'AAB File Size'.freeze
UNIVERSAL_APK_FILE_SIZE_KEY =

value from ‘File.size` of the `.aab`

'Universal APK File Size'.freeze
UNIVERSAL_APK_SPLIT_NAME =

value from ‘File.size` of the Universal `.apk`

'Universal'.freeze
APK_OPTIMIZED_FILE_SIZE_KEY =

pseudo-name of the split representing the Universal ‘.apk`

'Optimized APK File Size'.freeze
APK_OPTIMIZED_DOWNLOAD_SIZE_KEY =

value from ‘apkanalyzer apk file-size`

'Download Size'.freeze

Documentation collapse

Class Method Summary collapse

Class Method Details

.add_apk_size_metrics(helper:, apkanalyzer_bin:, apk:, split_name:) ⇒ Object

Add the ‘file-size` and `download-size` values of an APK to the helper, as reported by the corresponding `apkanalyzer apk …` commands

Parameters:

  • helper (Fastlane::Helper::AppSizeMetricsHelper)

    The helper to add the metrics to

  • apkanalyzer_bin (String)

    The path to the ‘apkanalyzer` binary to use to extract those file and download sizes from the `.apk`

  • apk (String)

    The path to the ‘.apk` file to extract the sizes from

  • split_name (String)

    The name to use for the value of the ‘split` metadata key in the metrics being added



103
104
105
106
107
108
109
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/android/android_send_app_size_metrics.rb', line 103

def add_apk_size_metrics(helper:, apkanalyzer_bin:, apk:, split_name:)
  UI.message("[App Size Metrics] Computing file and download size of #{File.basename(apk)}...")
  file_size = Action.sh(apkanalyzer_bin, 'apk', 'file-size', apk, print_command: false, print_command_output: false).chomp.to_i
  download_size = Action.sh(apkanalyzer_bin, 'apk', 'download-size', apk, print_command: false, print_command_output: false).chomp.to_i
  helper.add_metric(name: APK_OPTIMIZED_FILE_SIZE_KEY, value: file_size, metadata: { split: split_name })
  helper.add_metric(name: APK_OPTIMIZED_DOWNLOAD_SIZE_KEY, value: download_size, metadata: { split: split_name })
end

.authorsObject



265
266
267
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/android/android_send_app_size_metrics.rb', line 265

def self.authors
  ['Automattic']
end

.available_optionsObject



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
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/android/android_send_app_size_metrics.rb', line 150

def self.available_options
  [
    FastlaneCore::ConfigItem.new(
      key: :api_url,
      env_name: 'FL_ANDROID_SEND_APP_SIZE_METRICS_API_URL',
      description: 'The endpoint API URL to publish metrics to. (Note: you can also point to a `file://` URL to write the payload to a file instead)',
      type: String,
      optional: false
    ),
    FastlaneCore::ConfigItem.new(
      key: :api_token,
      env_name: 'FL_ANDROID_SEND_APP_SIZE_METRICS_API_TOKEN',
      description: 'The bearer token to call the API. Required, unless `api_url` is a `file://` URL',
      type: String,
      optional: true
    ),
    FastlaneCore::ConfigItem.new(
      key: :use_gzip_content_encoding,
      env_name: 'FL_ANDROID_SEND_APP_SIZE_METRICS_USE_GZIP_CONTENT_ENCODING',
      description: 'Specify that we should use `Content-Encoding: gzip` and gzip the body when sending the request',
      type: FastlaneCore::Boolean,
      default_value: true
    ),
    FastlaneCore::ConfigItem.new(
      key: :app_name,
      env_name: 'FL_ANDROID_SEND_APP_SIZE_METRICS_APP_NAME',
      description: 'The name of the app for which we are publishing metrics, to help filter by app in the dashboard',
      type: String,
      optional: false
    ),
    FastlaneCore::ConfigItem.new(
      key: :app_version_name,
      env_name: 'FL_ANDROID_SEND_APP_SIZE_METRICS_APP_VERSION_NAME',
      description: 'The version name of the app for which we are publishing metrics, to help filter by version in the dashboard',
      type: String,
      optional: false
    ),
    FastlaneCore::ConfigItem.new(
      key: :app_version_code,
      env_name: 'FL_ANDROID_SEND_APP_SIZE_METRICS_APP_VERSION_CODE',
      description: 'The version code of the app for which we are publishing metrics, to help filter by version in the dashboard',
      type: Integer,
      optional: true
    ),
    FastlaneCore::ConfigItem.new(
      key: :product_flavor,
      env_name: 'FL_ANDROID_SEND_APP_SIZE_METRICS_PRODUCT_FLAVOR',
      description: 'The product flavor for which we are publishing metrics, to help filter by flavor in the dashboard. E.g. `Vanilla`, `Jalapeno`, `Wasabi`',
      type: String,
      optional: true
    ),
    FastlaneCore::ConfigItem.new(
      key: :build_type,
      env_name: 'FL_ANDROID_SEND_APP_SIZE_METRICS_BUILD_TYPE',
      description: 'The build type for which we are publishing metrics, to help filter by build type in the dashboard. E.g. `Debug`, `Release`',
      type: String,
      optional: true
    ),
    FastlaneCore::ConfigItem.new(
      key: :source,
      env_name: 'FL_ANDROID_SEND_APP_SIZE_METRICS_SOURCE',
      description: 'The type of event at the origin of that build, to help filter data in the dashboard. E.g. `pr`, `beta`, `final-release`',
      type: String,
      optional: true
    ),
    FastlaneCore::ConfigItem.new(
      key: :aab_path,
      env_name: 'FL_ANDROID_SEND_APP_SIZE_METRICS_AAB_PATH',
      description: 'The path to the .aab to extract size information from',
      type: String,
      optional: true, # We can have `aab_path` only, or `universal_apk_path` only, or both (but not none)
      verify_block: proc do |value|
        UI.user_error!('You must provide an path to an existing `.aab` file') unless File.exist?(value)
      end
    ),
    FastlaneCore::ConfigItem.new(
      key: :include_split_sizes,
      env_name: 'FL_ANDROID_SEND_APP_SIZE_METRICS_INCLUDE_SPLIT_SIZES',
      description: 'Indicate if we should use `bundletool` and `apkanalyzer` to also compute and send "split apk" sizes per architecture. ' \
        + 'Setting this to `true` adds a bit of extra time to generate the `.apk` and extract the data, but provides more detailed metrics',
      type: FastlaneCore::Boolean,
      default_value: true
    ),
    FastlaneCore::ConfigItem.new(
      key: :universal_apk_path,
      env_name: 'FL_ANDROID_SEND_APP_SIZE_METRICS_UNIVERSAL_APK_PATH',
      description: 'The path to the Universal `.apk` to extract size information from',
      type: String,
      optional: true, # We can have `aab_path` only, or `universal_apk_path` only, or both (but not none)
      verify_block: proc do |value|
        UI.user_error!('You must provide a path to an existing `.apk` file') unless File.exist?(value)
      end
    ),
    FastlaneCore::ConfigItem.new(
      key: :apkanalyzer_binary,
      env_name: 'FL_ANDROID_SEND_APP_SIZE_METRICS_APKANALYZER_BINARY',
      description: 'The path to the `apkanalyzer` binary to use. If not provided explicitly, we will use `$PATH` and `$ANDROID_SDK_HOME` to try to find it',
      type: String,
      default_value: find_apkanalyzer_binary,
      default_value_dynamic: true,
      verify_block: proc do |value|
        UI.user_error!('You must provide a path to an existing executable for `apkanalyzer`') unless File.executable?(value)
      end
    ),
  ]
end

.check_bundletool_installed!Object

Raises:

  • if ‘bundletool` can not be found in `$PATH`



66
67
68
69
70
71
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/android/android_send_app_size_metrics.rb', line 66

def check_bundletool_installed!
  Action.sh('command', '-v', 'bundletool', print_command: false, print_command_output: false)
rescue StandardError
  UI.user_error!('`bundletool` is required to build the split APKs. Install it with `brew install bundletool`')
  raise
end

.descriptionObject



135
136
137
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/android/android_send_app_size_metrics.rb', line 135

def self.description
  'Send Android app size metrics to our metrics server'
end

.detailsObject



139
140
141
142
143
144
145
146
147
148
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/android/android_send_app_size_metrics.rb', line 139

def self.details
  <<~DETAILS
    Send Android app size metrics to our metrics server.

    See https://github.com/Automattic/apps-metrics for the API contract expected by the Metrics server you will send those metrics to.

    Tip: If you provide a `file://` URL for the `api_url`, the action will write the payload on disk at the specified path instead of sending
    the data to a endpoint over network. This can be useful e.g. to inspect the payload and debug it, or to store the metrics data as CI artefacts.
  DETAILS
end

.find_apkanalyzer_binaryString, Nil

The path where the ‘apkanalyzer` binary was found, after searching it:

- in priority in `$ANDROID_HOME` (or `$ANDROID_SDK_ROOT` for legacy setups), under `cmdline-tools/latest/bin/` or `cmdline-tools/tools/bin`
- and falling back by trying to find it in `$PATH`

Returns:

  • (String, Nil)

    The path to ‘apkanalyzer`, or `nil` if it wasn’t found in any of the above tested paths.



79
80
81
82
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/android/android_send_app_size_metrics.rb', line 79

def find_apkanalyzer_binary
  @tools ||= Fastlane::Helper::Android::ToolsPathHelper.new
  @tools.find_tool_path(binary: 'apkanalyzer', search_paths: @tools.cmdline_tools_search_paths)
end

.find_apkanalyzer_binary!String

The path where the ‘apkanalyzer` binary was found, after searching it:

- in priority in `$ANDROID_HOME` (or `$ANDROID_SDK_ROOT` for legacy setups), under `cmdline-tools/latest/bin/` or `cmdline-tools/tools/bin`
- and falling back by trying to find it in `$PATH`

Returns:

  • (String)

    The path to ‘apkanalyzer`

Raises:

  • (FastlaneCore::Interface::FastlaneError)

    if it wasn’t found in any of the above tested paths.



91
92
93
94
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/android/android_send_app_size_metrics.rb', line 91

def find_apkanalyzer_binary!
  @tools ||= Fastlane::Helper::Android::ToolsPathHelper.new
  @tools.find_tool_path!(binary: 'apkanalyzer', search_paths: @tools.cmdline_tools_search_paths)
end

.generate_split_apks(aab_path:) {|apk| ... } ⇒ Object

Note:

The split ‘.apk` files are generated in a temporary directory and are thus all deleted after each of them has been `yield`ed to the provided block.

Generates all the split ‘.apk` files (typically one per device architecture) from a given `.aab` file, then yield for each apk produced.

Parameters:

  • aab_path (String)

    The path to the ‘.aab` file to generate split `.apk` files for

Yields:

  • (apk)

    Calls the provided block once for each split ‘.apk` that was generated from the `.aab`

Yield Parameters:

  • apk (String)

    The path to one of the split ‘.apk` temporary file generated from the `.aab`



118
119
120
121
122
123
124
125
126
127
128
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/android/android_send_app_size_metrics.rb', line 118

def generate_split_apks(aab_path:, &block)
  check_bundletool_installed!
  UI.message("[App Size Metrics] Generating the various APK splits from #{aab_path}...")
  Dir.mktmpdir('release-toolkit-android-app-size-metrics') do |tmp_dir|
    Action.sh('bundletool', 'build-apks', '--bundle', aab_path, '--output-format', 'DIRECTORY', '--output', tmp_dir)
    apks = Dir.glob('splits/*.apk', base: tmp_dir).map { |f| File.join(tmp_dir, f) }
    UI.message("[App Size Metrics] Generated #{apks.length} APKs.")
    apks.each(&block)
    UI.message('[App Size Metrics] Done computing splits sizes.')
  end
end

.is_supported?(platform) ⇒ Boolean

Returns:

  • (Boolean)


269
270
271
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/android/android_send_app_size_metrics.rb', line 269

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

.return_typeObject



257
258
259
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/android/android_send_app_size_metrics.rb', line 257

def self.return_type
  :integer
end

.return_valueObject



261
262
263
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/android/android_send_app_size_metrics.rb', line 261

def self.return_value
  'The HTTP return code from the call. Expect a 201 when new metrics were received successfully and entries created in the database'
end

.run(params) ⇒ Object

value from ‘apkanalyzer apk download-size`



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
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/android/android_send_app_size_metrics.rb', line 13

def self.run(params)
  # Check input parameters
  api_url = URI(params[:api_url])
  api_token = params[:api_token]
  if (api_token.nil? || api_token.empty?) && !api_url.is_a?(URI::File)
    UI.user_error!('An API token is required when using an `api_url` with a scheme other than `file://`')
  end
  if params[:aab_path].nil? && params[:universal_apk_path].nil?
    UI.user_error!('You must provide at least an `aab_path` or an `universal_apk_path`, or both')
  end

  # Build the payload base
  metrics_helper = Fastlane::Helper::AppSizeMetricsHelper.new(
    Platform: 'Android',
    'App Name': params[:app_name],
    'App Version': params[:app_version_name],
    'Version Code': params[:app_version_code],
    'Product Flavor': params[:product_flavor],
    'Build Type': params[:build_type],
    Source: params[:source]
  )
  # Add AAB file size
  metrics_helper.add_metric(name: AAB_FILE_SIZE_KEY, value: File.size(params[:aab_path])) unless params[:aab_path].nil?
  # Add Universal APK file size
  metrics_helper.add_metric(name: UNIVERSAL_APK_FILE_SIZE_KEY, value: File.size(params[:universal_apk_path])) unless params[:universal_apk_path].nil?

  # Add optimized file and download sizes for each split `.apk` metrics to the payload if a `:include_split_sizes` is enabled
  if params[:include_split_sizes]
    apkanalyzer_bin = params[:apkanalyzer_binary] || find_apkanalyzer_binary!
    unless params[:aab_path].nil?
      generate_split_apks(aab_path: params[:aab_path]) do |apk|
        split_name = File.basename(apk, '.apk')
        add_apk_size_metrics(helper: metrics_helper, apkanalyzer_bin: apkanalyzer_bin, apk: apk, split_name: split_name)
      end
    end
    unless params[:universal_apk_path].nil?
      add_apk_size_metrics(helper: metrics_helper, apkanalyzer_bin: apkanalyzer_bin, apk: params[:universal_apk_path], split_name: UNIVERSAL_APK_SPLIT_NAME)
    end
  end

  # Send the payload
  metrics_helper.send_metrics(
    to: api_url,
    api_token: api_token,
    use_gzip: params[:use_gzip_content_encoding]
  )
end