Module: Utils::Analytics Private

Extended by:
Cacheable, Context, T::Generic, Output::Mixin
Defined in:
utils/analytics.rb,
utils/analytics/api.rb,
utils/analytics/influx.rb,
utils/analytics/releases.rb,
utils/analytics/repository.rb,
utils/analytics/package_feeds.rb,
utils/analytics/formula_history.rb,
utils/analytics/vulnerabilities.rb

Overview

This module is part of a private API. This module may only be used in the Homebrew/brew repository. Third parties should avoid using this module if possible, as it may be removed or changed without warning.

Helper module for fetching and reporting analytics data.

Defined Under Namespace

Modules: Vulnerabilities Classes: API, FormulaHistory, Influx, PackageFeeds, Releases, Repository

Constant Summary collapse

INFLUX_BUCKET =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

"analytics"
INFLUX_HOST =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

"https://analytics.brew.sh"
INFLUX_ORG =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

"d81a3e6d582d485f"
WSL_SUFFIX =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

" [WSL]"
ENV_CONFIG_COMMANDS =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

%w[config fetch install reinstall update update-report upgrade].freeze
INFLUX_MAX_BATCH_BYTES =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

Linux limits a single curl argument (the request body) to 128KiB so stay well under it.

65_536
Cache =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

type_template { { fixed: T::Hash[Symbol, T.untyped] } }

Class Method Summary collapse

Methods included from Context

current, current=, debug?, deferred_environment_expansion?, quiet?, verbose?, with_context

Methods included from Output::Mixin

issue_reporting_message, odebug, odeprecated, odie, odisabled, ofail, oh1, oh1_title, ohai, ohai_title, onoe, opoo, opoo_once, opoo_outside_github_actions, opoo_without_github_actions_annotation, pretty_cannot_install, pretty_deprecated, pretty_disabled, pretty_duration, pretty_incompatible, pretty_install_status, pretty_installed, pretty_removed, pretty_uninstalled, pretty_unmarked, pretty_upgradable, pretty_warning

Methods included from Cacheable

cache, clear_cache

Class Method Details

.cask_output(cask, args:) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:



417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# File 'utils/analytics.rb', line 417

def cask_output(cask, args:)
  return if Homebrew::EnvConfig.no_analytics? || Homebrew::EnvConfig.no_github_api?

  require "api"

  return unless Homebrew::API.cask_token?(cask.token)

  analytics = Homebrew::API::Analytics.cask_analytics cask.token
  return if analytics.blank?

  output_analytics(analytics, args:)
rescue ArgumentError
  # Ignore failed API requests
  nil
end

.config_true?(key) ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:

  • (Boolean)


582
583
584
# File 'utils/analytics.rb', line 582

def config_true?(key)
  Homebrew::Settings.read(key) == "true"
end

.default_package_fields ⇒ Hash{Symbol => String}

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

remove os_version starting with " or number remove macOS patch release

Returns:



462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
# File 'utils/analytics.rb', line 462

def default_package_fields
  cache[:default_package_fields] ||= begin
    version = if (numeric_version = HOMEBREW_VERSION[/^[\d.]+/])
      suffix = "-dev" if HOMEBREW_VERSION.include?("-")
      numeric_version + suffix.to_s
    else
      ">=4.1.22"
    end

    # Only include OS versions with an actual name.
    os_name_and_version = if (os_version = OS_VERSION.presence) && os_version.downcase.match?(/^[a-z]/)
      with_wsl_suffix_if_needed(os_version)
    end

    {
      version:,
      os_name_and_version:,
    }
  end
end

.default_package_tags ⇒ Hash{Symbol => Boolean, String}

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
# File 'utils/analytics.rb', line 441

def default_package_tags
  cache[:default_package_tags] ||= begin
    # Only display default prefixes to reduce cardinality and improve privacy
    prefix = Homebrew.default_prefix? ? HOMEBREW_PREFIX.to_s : "custom-prefix"

    # Tags are always strings and must have low cardinality.
    {
      ci:             ENV["CI"].present?,
      prefix:,
      default_prefix: Homebrew.default_prefix?,
      developer:      Homebrew::EnvConfig.developer?,
      devcmdrun:      Homebrew::EnvConfig.devcmdrun?,
      arch:           HOMEBREW_PHYSICAL_PROCESSOR,
      os:             with_wsl_suffix_if_needed(HOMEBREW_SYSTEM),
    }
  end
end

.deferred_curl(url, args) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'utils/analytics.rb', line 95

def deferred_curl(url, args)
  require "utils/curl"

  curl = Utils::Curl.curl_executable
  if ENV["HOMEBREW_ANALYTICS_DEBUG"]
    # Keep the response and curl's error message so a failure shows why.
    failure_args = if Utils::Curl.curl_supports_fail_with_body?
      Utils::Curl.curl_fail_with_body_args
    else
      # Older curls drop the response with `--fail`, so turn off a curlrc `--fail` and print the status
      # after the response instead.
      ["--no-fail", *Utils::Curl.curl_http_code_write_out_args(prefix: "\nHTTP status: ", suffix: "\n")]
    end
    args = Utils::Curl.curl_args(*args, "--silent", *failure_args, show_output: true)
    puts "#{curl} #{args.join(" ")} \"#{url}\""
    puts Utils.safe_popen_read(curl, *args, url, err: :out)
  else
    args = Utils::Curl.curl_args(*args, "--silent", "--output", File::NULL, show_error: false)
    pid = spawn curl, *args, url, out: File::NULL, err: File::NULL
    Process.detach(pid)
  end
rescue => e
  odebug "Failed to send analytics: #{e}", always_display: ENV["HOMEBREW_ANALYTICS_DEBUG"].present?
end

.delete_uuid! ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



304
305
306
# File 'utils/analytics.rb', line 304

def delete_uuid!
  Homebrew::Settings.delete :analyticsuuid
end

.disable! ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



298
299
300
301
# File 'utils/analytics.rb', line 298

def disable!
  Homebrew::Settings.write :analyticsdisabled, true
  delete_uuid!
end

.disabled? ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (Boolean)


266
267
268
269
270
# File 'utils/analytics.rb', line 266

def disabled?
  return true if Homebrew::EnvConfig.no_analytics?

  config_true?(:analyticsdisabled)
end

.enable! ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



291
292
293
294
295
# File 'utils/analytics.rb', line 291

def enable!
  Homebrew::Settings.write :analyticsdisabled, false
  delete_uuid!
  messages_displayed!
end

.format_count(count) ⇒ String

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



587
588
589
# File 'utils/analytics.rb', line 587

def format_count(count)
  count.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse
end

.format_percent(percent) ⇒ String

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



592
593
594
# File 'utils/analytics.rb', line 592

def format_percent(percent)
  format("%<percent>.2f", percent:)
end

.formula_output(formula, args:) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:



399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'utils/analytics.rb', line 399

def formula_output(formula, args:)
  return if Homebrew::EnvConfig.no_analytics? || Homebrew::EnvConfig.no_github_api?

  require "api"

  return unless Homebrew::API.formula_name? formula.name

  analytics = Homebrew::API::Analytics.formula_analytics formula.name
  return if analytics.blank?

  output_analytics(analytics, args:)
  output_github_packages_downloads(formula, analytics, args:)
rescue ArgumentError
  # Ignore failed API requests
  nil
end

.influx_message_displayed? ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (Boolean)


253
254
255
# File 'utils/analytics.rb', line 253

def influx_message_displayed?
  config_true?(:influxanalyticsmessage)
end

.messages_displayed! ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



284
285
286
287
288
# File 'utils/analytics.rb', line 284

def messages_displayed!
  Homebrew::Settings.write :analyticsmessage, true
  Homebrew::Settings.write :caskanalyticsmessage, true
  Homebrew::Settings.write :influxanalyticsmessage, true
end

.messages_displayed? ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (Boolean)


258
259
260
261
262
263
# File 'utils/analytics.rb', line 258

def messages_displayed?
  return false unless config_true?(:analyticsmessage)
  return false unless config_true?(:caskanalyticsmessage)

  influx_message_displayed?
end

.no_message_output? ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (Boolean)


278
279
280
281
# File 'utils/analytics.rb', line 278

def no_message_output?
  # Used by Homebrew/install
  ENV["HOMEBREW_NO_ANALYTICS_MESSAGE_OUTPUT"].present?
end

.not_this_run? ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (Boolean)


273
274
275
# File 'utils/analytics.rb', line 273

def not_this_run?
  ENV["HOMEBREW_NO_ANALYTICS_THIS_RUN"].present?
end

.output(args:, filter: nil) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:



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
# File 'utils/analytics.rb', line 309

def output(args:, filter: nil)
  require "api"

  days = args.days || "30"
  category = args.category || "install"
  begin
    json = Homebrew::API::Analytics.fetch category, days
  rescue ArgumentError
    # Ignore failed API requests
    return
  end
  return if json.blank? || json["items"].blank?

  os_version = category == "os-version"
  cask_install = category == "cask-install"
  results = {}
  json["items"].each do |item|
    key = if os_version
      item["os_version"]
    elsif cask_install
      item["cask"]
    else
      item["formula"]
    end
    next if filter.present? && key != filter && !key.start_with?("#{filter} ")

    results[key] = item["count"].tr(",", "").to_i
  end

  if filter.present? && results.blank?
    onoe "No results matching `#{filter}` found!"
    return
  end

  table_output(category, days, results, os_version:, cask_install:)
end

.output_analytics(analytics, args:) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:



347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'utils/analytics.rb', line 347

def output_analytics(analytics, args:)
  full_analytics = args.analytics? || verbose?

  ohai "Analytics"
  analytics.each do |category, value|
    category = category.tr("_", "-")
    summaries = []

    value.each do |days, results|
      days = days.to_i
      if full_analytics
        next if args.days.present? && args.days&.to_i != days
        next if args.category.present? && args.category != category

        table_output(category, days.to_s, results)
      else
        total_count = results.values.sum
        summaries << "#{Formatter.number_readable(total_count)} (#{days} days)"
      end
    end

    puts "#{category}: #{summaries.join(", ")}" unless full_analytics
  end
end

.output_github_packages_downloads(formula, analytics, args:) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

This flag is hidden because it is not intended for general use. It relies on screen scraping some GitHub HTML that's not available as an API. This seems very likely to break in the future. That said, it's the only way to get the data we want right now.

Parameters:



377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
# File 'utils/analytics.rb', line 377

def output_github_packages_downloads(formula, analytics, args:)
  return unless args.github_packages_downloads?
  return unless formula.core_formula?

  downloads = GitHubPackages.downloads(formula.name)
  unless downloads
    opoo "Failed to fetch GitHub Packages downloads for: #{formula.name}"
    return
  end

  puts "GitHub Packages downloads (since Bintray migration): #{format_count(downloads.all_time)}"
  puts "GitHub Packages downloads (30 days): #{format_count(downloads.last_30_days)}"
  puts "Download dates: #{downloads.start_date} to #{downloads.end_date}; fetched #{downloads.fetched_at}"

  install_count = analytics.dig("install", "30d")&.values&.sum
  return unless install_count&.positive?

  ratio = format("%.2f", downloads.last_30_days.to_f / install_count)
  puts "Downloads / analytics install events (30 days): #{ratio}x (#{format_count(install_count)} events)"
end

.report_build_error(exception) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:



172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'utils/analytics.rb', line 172

def report_build_error(exception)
  return if not_this_run? || disabled?

  formula = exception.formula
  return unless formula

  tap = formula.tap
  return unless tap
  return unless tap.should_report_analytics?

  options = exception.options.to_a.compact.map(&:to_s).sort.uniq.join(" ")
  report_package_event(:build_error, package_name: formula.name, tap_name: tap.name, options:)
end

.report_command_run(command_instance) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:



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
# File 'utils/analytics.rb', line 187

def report_command_run(command_instance)
  return if not_this_run? || disabled?

  command = command_instance.class.command_name

  options_array = command_instance.args.options_only.to_a.compact

  # Strip out any flag values to reduce cardinality and preserve privacy.
  options_array.map! { |option| option.sub(/=.*/m, "=") }

  # Strip out --with-* and --without-* options
  options_array.reject! { |option| option.match(/^--with(?:out)?-/) }

  options = options_array.sort.uniq.join(" ")

  # Tags must have low cardinality.
  tags = {
    command:,
    ci:        ENV["CI"].present?,
    devcmdrun: Homebrew::EnvConfig.devcmdrun?,
    developer: Homebrew::EnvConfig.developer?,
  }
  if ENV_CONFIG_COMMANDS.include?(command)
    variables = Homebrew::EnvConfig::ANALYTICS_VARIABLES
    env_config = variables.fetch(Random.rand(variables.length))
    tags[:env_config] = env_config.to_s
    tags[:env_config_state] = if Homebrew::EnvConfig.user_set_variable?(env_config)
      Homebrew::EnvConfig.non_default_variable?(env_config) ? "non_default" : "default"
    else
      "unset"
    end
  end

  # Fields can have high cardinality.
  fields = { options: }

  report_influx(:command_run, tags, fields)
end

.report_influx(measurement, tags, fields, batches: nil) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:



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
# File 'utils/analytics.rb', line 53

def report_influx(measurement, tags, fields, batches: nil)
  return if not_this_run? || disabled?

  # Tags are always implicitly strings and must have low cardinality.
  tags_string = tags.map do |k, v|
    escaped_value = v.to_s.gsub(/[ ,=]/) { |char| "\\#{char}" }
    "#{k}=#{escaped_value}"
  end.join(",")

  # Fields need explicitly wrapped with quotes and can have high cardinality.
  fields_string = fields.compact
                        .map { |k, v| %Q(#{k}="#{v}") }
                        .join(",")

  # InfluxDB merges points with the same tags and timestamp, so give each event its own second,
  # even across separate reports. analytics.brew.sh only accepts second precision.
  timestamp = [Time.now.to_i, cache.fetch(:last_influx_timestamp, -1) + 1].max
  cache[:last_influx_timestamp] = timestamp
  line = "#{measurement},#{tags_string} #{fields_string} #{timestamp}"
  if batches.nil?
    write_influx(line)
  elsif (body = batches.last) && body.bytesize + 1 + line.bytesize <= INFLUX_MAX_BATCH_BYTES
    body << "\n" << line
  else
    batches << line
  end
end

.report_installs(formulae: [], casks: []) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Report one batch per completed fetch, giving explicitly requested formulae precedence over dependencies.

Parameters:



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
# File 'utils/analytics.rb', line 142

def report_installs(formulae: [], casks: [])
  return if not_this_run? || disabled?

  batches = T.let([], T::Array[String])
  requested = formulae.reject(&:only_deps?)
  dependencies = formulae.flat_map(&:verified_dependency_installers)
  (requested + dependencies).uniq { |fi| fi.formula.full_name }.each do |fi|
    formula = fi.formula
    next unless (tap = formula.tap)&.should_report_analytics?

    report_package_event(:formula_install, package_name: formula.name, tap_name: tap.name,
                         on_request: fi.installed_on_request?, options: fi.display_options(formula).join(" "),
                         batches:)
  rescue
    # An unreadable receipt should only affect the package that owns it.
    next
  end
  casks.each do |installer|
    next if installer.download_failed?

    cask = installer.cask
    next unless (tap = cask.tap)&.should_report_analytics?

    report_package_event(:cask_install, package_name: cask.token, tap_name: tap.name, on_request: true,
                         batches:)
  end
  batches.each { |body| write_influx(body) }
end

.report_package_event(measurement, package_name:, tap_name:, on_request: false, options: "", batches: nil) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:

  • measurement (Symbol)
  • package_name (String)
  • tap_name (String)
  • on_request (Boolean) (defaults to: false)
  • options (String) (defaults to: "")
  • batches (Array<String>, nil) (defaults to: nil)


124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'utils/analytics.rb', line 124

def report_package_event(measurement, package_name:, tap_name:, on_request: false, options: "", batches: nil)
  return if not_this_run? || disabled?

  # ensure options are removed (by `.compact` below) if empty
  options = nil if options.blank?

  # Tags must have low cardinality.
  tags = default_package_tags.merge(on_request:)

  # Fields can have high cardinality.
  fields = default_package_fields.merge(package: package_name, tap_name:, options:)
                                 .compact

  report_influx(measurement, tags, fields, batches:)
end

.report_test_bot_test(step_command_short, passed) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:

  • step_command_short (String)
  • passed (Boolean)


227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'utils/analytics.rb', line 227

def report_test_bot_test(step_command_short, passed)
  return if not_this_run? || disabled?
  return if ENV["HOMEBREW_TEST_BOT_ANALYTICS"].blank?

  # Tags must have low cardinality.
  tags = {
    passed:,
    arch:   HOMEBREW_PHYSICAL_PROCESSOR,
    os:     HOMEBREW_SYSTEM,
  }

  # Strip out any flag values to reduce cardinality and preserve privacy.
  # Sort options to ensure consistent ordering and improve readability.
  command_and_package, options =
    step_command_short.split
                      .map { |arg| arg.sub(/=.*/, "=") }
                      .partition { |arg| !arg.start_with?("-") }
  command = (command_and_package + options.sort).join(" ")

  # Fields can have high cardinality.
  fields = { command: }

  report_influx(:test_bot_test, tags, fields)
end

.table_output(category, days, results, os_version: false, cask_install: false, name_header: nil) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:

  • category (String)
  • days (String)
  • results (Hash{String => Integer})
  • os_version (Boolean) (defaults to: false)
  • cask_install (Boolean) (defaults to: false)
  • name_header (String, nil) (defaults to: nil)


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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
# File 'utils/analytics.rb', line 489

def table_output(category, days, results, os_version: false, cask_install: false, name_header: nil)
  oh1 "#{category} (#{days} days)"
  total_count = results.values.sum
  formatted_total_count = format_count(total_count)
  formatted_total_percent = format_percent(100)

  index_header = "Index"
  count_header = "Count"
  percent_header = "Percent"
  name_with_options_header = if name_header
    name_header
  elsif os_version
    "macOS Version"
  elsif cask_install
    "Token"
  else
    "Name (with options)"
  end

  total_index_footer = "Total"
  max_index_width = results.length.to_s.length
  index_width = [
    index_header.length,
    total_index_footer.length,
    max_index_width,
  ].max
  count_width = [
    count_header.length,
    formatted_total_count.length,
  ].max
  percent_width = [
    percent_header.length,
    formatted_total_percent.length,
  ].max
  name_with_options_width = Tty.width -
                            index_width -
                            count_width -
                            percent_width -
                            10 # spacing and lines

  formatted_index_header =
    format "%#{index_width}s", index_header
  formatted_name_with_options_header =
    format "%-#{name_with_options_width}s",
           name_with_options_header[0..(name_with_options_width-1)]
  formatted_count_header =
    format "%#{count_width}s", count_header
  formatted_percent_header =
    format "%#{percent_width}s", percent_header
  puts "#{formatted_index_header} | #{formatted_name_with_options_header} | " \
       "#{formatted_count_header} |  #{formatted_percent_header}"

  index_rule = "-"*index_width
  name_rule = "-"*name_with_options_width
  count_rule = "-"*count_width
  percent_rule = "-"*percent_width
  columns_line = "#{index_rule}:|-#{name_rule}-|-#{count_rule}:|-#{percent_rule}:"
  puts columns_line

  index = 0
  results.each do |name_with_options, count|
    index += 1
    formatted_index = format "%0#{max_index_width}d", index
    formatted_index = format "%-#{index_width}s", formatted_index
    formatted_name_with_options =
      format "%-#{name_with_options_width}s",
             name_with_options[0..(name_with_options_width-1)]
    formatted_count = format "%#{count_width}s", format_count(count)
    formatted_percent = if total_count.zero?
      format "%#{percent_width}s", format_percent(0)
    else
      format "%#{percent_width}s",
             format_percent((count.to_i * 100) / total_count.to_f)
    end
    puts "#{formatted_index} | #{formatted_name_with_options} | " \
         "#{formatted_count} | #{formatted_percent}%"
    next if index > 10
  end
  return if results.length <= 1

  formatted_total_footer =
    format "%-#{index_width}s", total_index_footer
  formatted_blank_footer =
    format "%-#{name_with_options_width}s", ""
  formatted_total_count_footer =
    format "%#{count_width}s", formatted_total_count
  formatted_total_percent_footer =
    format "%#{percent_width}s", formatted_total_percent
  puts "#{formatted_total_footer} | #{formatted_blank_footer} | " \
       "#{formatted_total_count_footer} | #{formatted_total_percent_footer}%"
end

.with_wsl_suffix_if_needed(value, wsl: OS.wsl?) ⇒ String

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • value (String)
  • wsl (Boolean) (defaults to: OS.wsl?)

Returns:



434
435
436
437
438
# File 'utils/analytics.rb', line 434

def with_wsl_suffix_if_needed(value, wsl: OS.wsl?)
  return value if !wsl || value.end_with?(WSL_SUFFIX)

  "#{value}#{WSL_SUFFIX}"
end

.write_api(category, name, data, data_source: nil) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:

  • category (String)
  • name (String)
  • data (T.anything)
  • data_source (String, nil) (defaults to: nil)


31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'utils/analytics.rb', line 31

def write_api(category, name, data, data_source: nil)
  suffix = File.join(category, data_source || "")
  Pathname("_data/analytics/#{suffix}").mkpath
  Pathname("api/analytics/#{suffix}").mkpath
  Pathname("_data/analytics/#{suffix}/#{name}.json").write(JSON.pretty_generate(data))
  data_source_line = data_source ? "#{data_source}: true" : ""
  Pathname("api/analytics/#{suffix}/#{name}.json").write(<<~EOS)
    ---
    layout: analytics_json
    category: #{category}
    #{data_source_line}
    ---
    {{ content }}
  EOS
end

.write_influx(body) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:



82
83
84
85
86
87
88
89
90
91
92
# File 'utils/analytics.rb', line 82

def write_influx(body)
  args = [
    "--max-time", "3",
    "--header", "Content-Type: text/plain; charset=utf-8",
    "--header", "Accept: application/json",
    "--data-binary", body
  ]

  url = "#{INFLUX_HOST}/api/v2/write?bucket=#{INFLUX_BUCKET}&precision=s"
  deferred_curl(url, args)
end