Fastlane:如何根据 --env 从父目录加载 .env 文件

Fastlane: How to load .env file from parent directory according to --env

  1. 我知道 Fastlane 会自动从 .env.env.default.env.{environment} 加载变量,其中 environment--env 中的标志 --env 提供=15=]命令。
  2. 在我的 Fastfile 中,我需要 fastlane 来加载我的环境文件,这些文件位于 父目录 .
  3. 我想保持加载 .env.{environment} 文件的行为,当 {environment} 根据我在 --env 标志中传递的内容变化时。

我最终在 platform 块中使用了 before_all

  before_all do |lane|
    Dotenv.overload '../../.env'
    environment = lane_context[SharedValues::ENVIRONMENT]
    unless environment.nil?
        puts "Load .env file of #{environment}"
        Dotenv.overload '../../.env.' + environment
    end
  end

并且还在 fastlane 目录中放置一个空白的 .env 文件。

创建空 .env 的原因记录在我的空 .env 文件中:

TL;DR: do NOT delete this empty file

This file is blank to make Fastlane define the SharedValue::ENVIRONMENT variable, which is part of our fastlane/Fastfile configurations.

As you can see in Fastlane's cli_tools, Fastlane removes the --env index from ARGV pretty early so we can't know what the user passed to the --env parameter.

Unfortunatly, Fastlane search the .env files only in the fastlane folder and in it's parent folder (the ios folder, in our case). It means that, in our project, fastlane won't find any .env files. (Source)

When Fastlane fails to find .env files, it does not call the function load_dot_envs_from, which is responsible to define the SharedValue::ENVIRONMENT variable, which we use inside our Fastfile (Source)

This file is a hack that will make Fastlane find an empty .env file. It will then set the SharedValue::ENVIRONMENT to the ARGV value. We then use SharedValue::ENVIRONMENT inside Fastlane to load the right file from the right place.