Class: DotEnviOS::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/dotenv-ios/generator.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Generator

Returns a new instance of Generator.



13
14
15
16
17
# File 'lib/dotenv-ios/generator.rb', line 13

def initialize(options)
  @options = options

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

Instance Method Details

#generate_output(env_variables) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/dotenv-ios/generator.rb', line 75

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) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/dotenv-ios/generator.rb', line 43

def get_env_requests(file)
  requests = []

  File.readlines(file).each do |line|
    line.split(' ').each do |word|
      # https://regexr.com/4pmp0
      next unless /Env\.[a-z]\w*/.match? word

      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) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/dotenv-ios/generator.rb', line 61

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_sourceObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# 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

#startObject



19
20
21
22
23
# File 'lib/dotenv-ios/generator.rb', line 19

def start
  requests = iterate_source
  env_variables = get_values(requests)
  generate_output(env_variables)
end