class DotEnviOS::Generator

Public Class Methods

new(options) click to toggle source
# File lib/dotenv-ios/generator.rb, line 13
def initialize(options)
  @options = options

  @ui = DotEnviOS::UI.new(@options.verbose, @options.debug)
end

Public Instance Methods

generate_output(env_variables) click to toggle source
# File lib/dotenv-ios/generator.rb, line 78
def generate_output(env_variables)
  @ui.verbose("Outputting environment variables to #{@options.out}")

  file_contents = "class Env {\n\n"
  env_variables.each do |key, value|
    file_contents += "  static var #{DotEnviOS::Util.snake_to_camel(key)}: String = \"#{value}\"\n"
  end

  file_contents += "\n}"

  @ui.debug("Output file: #{file_contents}")

  File.open(@options.out, 'w') { |file| file.write(file_contents) }

  @ui.success('Environment variables file generated!')
  @ui.success("Add file, #{@options.out}, to your XCode project")
end
get_env_requests(file) click to toggle source
# File lib/dotenv-ios/generator.rb, line 43
def get_env_requests(file)
  requests = []

  File.readlines(file).each do |line|
    # Regex matcher: https://regexr.com/4rf2s
    matches = line.match(/Env\.[a-z]\w*/)
    next if matches.nil?

    matches.to_a.each do |word|
      word = word.gsub('_', '') # \w in regex pattern above allows underscores. We want to remove those.

      requested_variable = word.split('.')[1]
      requested_variable = DotEnviOS::Util.to_snakecase(requested_variable).upcase

      requests.push(requested_variable)
    end
  end

  requests
end
get_values(requests) click to toggle source
# File lib/dotenv-ios/generator.rb, line 64
def get_values(requests)
  variables = Dotenv.parse('.env')
  values = {}

  requests.each do |request|
    @ui.fail("Environment variable #{request} not found in .env") unless variables[request]

    values[request] = variables[request]
  end

  @ui.debug("Values: #{values}")
  values
end
iterate_source() click to toggle source
# File lib/dotenv-ios/generator.rb, line 25
def iterate_source
  source_pattern = File.expand_path("#{@options.source}/**/*.swift")
  @ui.verbose("Searching for environment vars in source: #{source_pattern}")

  requests = Set[]

  Dir.glob(source_pattern) do |swift_file|
    next if File.directory? swift_file

    @ui.verbose("Looking for Env usage in: #{swift_file}")
    requests.merge(get_env_requests(swift_file))
    @ui.verbose("Found #{requests.count} requests")
    @ui.debug("Requests found for file: #{requests.to_a}")
  end

  requests.to_a
end
start() click to toggle source
# File lib/dotenv-ios/generator.rb, line 19
def start
  requests = iterate_source
  env_variables = get_values(requests)
  generate_output(env_variables)
end