util.rb 2.19 KB
Newer Older
1 2
# frozen_string_literal: true

3
module GitLab
4
  module Exporter
Pablo Carranza's avatar
Pablo Carranza committed
5
    # Simple time wrapper that provides a to_i and wraps the execution result
6 7 8 9 10 11
    TrackedResult = Struct.new(:result, :time) do
      def to_i
        time
      end
    end

Pablo Carranza's avatar
Pablo Carranza committed
12 13 14 15
    # Time tracking object
    #
    # Provides a simple time tracking, and returns back the result plus the tracked time
    # wraped in a TrackedResult struct
16 17 18
    class TimeTracker
      def track
        @start = Time.now.to_f
19 20
        result = yield
        TrackedResult.new(result, Time.now.to_f - @start)
21 22
      end
    end
23

Ahmad Sherif's avatar
Ahmad Sherif committed
24
    # Helper methods, some stuff was copied from ActiveSupport
25 26
    module Utils
      def camel_case_string(str)
27
        str.gsub(/(?:_|^)([a-z\d]*)/i) { $1.capitalize } # rubocop:disable Style/PerlBackrefs
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
      end
      module_function :camel_case_string

      def deep_symbolize_hash_keys(hash)
        deep_transform_keys_in_object(hash, &:to_sym)
      end
      module_function :deep_symbolize_hash_keys

      def deep_transform_keys_in_object(object, &block)
        case object
        when Hash
          object.keys.each do |key|
            value = object.delete(key)
            object[yield(key)] = deep_transform_keys_in_object(value, &block)
          end
          object
        when Array
          object.map! { |e| deep_transform_keys_in_object(e, &block) }
        else
          object
        end
      end
      module_function :deep_transform_keys_in_object
Ahmad Sherif's avatar
Ahmad Sherif committed
51 52

      def pgrep(pattern)
53 54 55 56 57
        # pgrep will include the PID of the shell, so strip that out
        exec_pgrep(pattern).split("\n").each_with_object([]) do |line, arr|
          pid, name = line.split(" ")
          arr << pid if name != "sh"
        end
Ahmad Sherif's avatar
Ahmad Sherif committed
58 59 60
      end
      module_function :pgrep

61 62 63 64 65
      def exec_pgrep(pattern)
        `pgrep -fl "#{pattern}"`
      end
      module_function :exec_pgrep

Ahmad Sherif's avatar
Ahmad Sherif committed
66 67 68 69
      def system_uptime
        File.read("/proc/uptime").split(" ")[0].to_f
      end
      module_function :system_uptime
70 71 72 73 74 75 76 77 78 79 80

      def wrap_in_array(object)
        if object.nil?
          []
        elsif object.respond_to?(:to_ary)
          object.to_ary || [object]
        else
          [object]
        end
      end
      module_function :wrap_in_array
81
    end
82 83
  end
end