|
| 1 | +require 'dry/cli' |
| 2 | + |
| 3 | +module EmergeCLI |
| 4 | + module Commands |
| 5 | + class DownloadOrderFiles < EmergeCLI::Commands::GlobalOptions |
| 6 | + desc 'Download order files from Emerge' |
| 7 | + |
| 8 | + option :bundle_id, type: :string, required: true, desc: 'Bundle identifier to download order files for' |
| 9 | + |
| 10 | + option :api_token, type: :string, required: false, |
| 11 | + desc: 'API token for authentication, defaults to ENV[EMERGE_API_TOKEN]' |
| 12 | + |
| 13 | + option :app_version, type: :string, required: true, |
| 14 | + desc: 'App version to download order files for' |
| 15 | + |
| 16 | + option :unzip, type: :boolean, required: false, |
| 17 | + desc: 'Unzip the order file after downloading' |
| 18 | + |
| 19 | + option :output, type: :string, required: false, |
| 20 | + desc: 'Output name for the order file, defaults to bundle_id-app_version.gz' |
| 21 | + |
| 22 | + EMERGE_ORDER_FILE_URL = 'order-files-prod.emergetools.com'.freeze |
| 23 | + |
| 24 | + def initialize(network: nil) |
| 25 | + @network = network |
| 26 | + end |
| 27 | + |
| 28 | + def call(**options) |
| 29 | + @options = options |
| 30 | + before(options) |
| 31 | + |
| 32 | + begin |
| 33 | + api_token = @options[:api_token] || ENV.fetch('EMERGE_API_TOKEN', nil) |
| 34 | + raise 'API token is required' unless api_token |
| 35 | + |
| 36 | + raise 'Bundle ID is required' unless @options[:bundle_id] |
| 37 | + raise 'App version is required' unless @options[:app_version] |
| 38 | + |
| 39 | + @network ||= EmergeCLI::Network.new(api_token:, base_url: EMERGE_ORDER_FILE_URL) |
| 40 | + output_name = @options[:output] || "#{@options[:bundle_id]}-#{@options[:app_version]}.gz" |
| 41 | + output_name = "#{output_name}.gz" unless output_name.end_with?('.gz') |
| 42 | + |
| 43 | + Sync do |
| 44 | + request = get_order_file(options[:bundle_id], options[:app_version]) |
| 45 | + response = request.read |
| 46 | + |
| 47 | + File.write(output_name, response) |
| 48 | + |
| 49 | + if @options[:unzip] |
| 50 | + Logger.info 'Unzipping order file...' |
| 51 | + Zlib::GzipReader.open(output_name) do |gz| |
| 52 | + File.write(output_name.gsub('.gz', ''), gz.read) |
| 53 | + end |
| 54 | + end |
| 55 | + |
| 56 | + Logger.info 'Order file downloaded successfully' |
| 57 | + end |
| 58 | + rescue StandardError => e |
| 59 | + Logger.error "Failed to download order file: #{e.message}" |
| 60 | + Logger.error 'Check your parameters and try again' |
| 61 | + raise e |
| 62 | + ensure |
| 63 | + @network&.close |
| 64 | + end |
| 65 | + end |
| 66 | + |
| 67 | + private |
| 68 | + |
| 69 | + def get_order_file(bundle_id, app_version) |
| 70 | + @network.get( |
| 71 | + path: "/#{bundle_id}/#{app_version}", |
| 72 | + max_retries: 0 |
| 73 | + ) |
| 74 | + end |
| 75 | + end |
| 76 | + end |
| 77 | +end |
0 commit comments