構成可能なビルド属性

問題を報告 ソースを表示

構成可能な属性(一般に select())は、ユーザーがコマンドラインでビルドルール属性の値を切り替えることができる Bazel の機能です。

たとえば、アーキテクチャに適した実装を自動的に選択するマルチプラットフォーム ライブラリや、ビルド時にカスタマイズできる機能構成可能なバイナリに使用できます。

# myapp/BUILD

cc_binary(
    name = "mybinary",
    srcs = ["main.cc"],
    deps = select({
        ":arm_build": [":arm_lib"],
        ":x86_debug_build": [":x86_dev_lib"],
        "//conditions:default": [":generic_lib"],
    }),
)

config_setting(
    name = "arm_build",
    values = {"cpu": "arm"},
)

config_setting(
    name = "x86_debug_build",
    values = {
        "cpu": "x86",
        "compilation_mode": "dbg",
    },
)

これにより、コマンドラインのフラグに基づいて依存関係を選択する cc_binary を宣言します。具体的には、deps は次のようになります。

コマンド deps =
bazel build //myapp:mybinary --cpu=arm [":arm_lib"]
bazel build //myapp:mybinary -c dbg --cpu=x86 [":x86_dev_lib"]
bazel build //myapp:mybinary --cpu=ppc [":generic_lib"]
bazel build //myapp:mybinary -c dbg --cpu=ppc [":generic_lib"]

select() は、構成条件config_setting ターゲットを参照するラベル)に基づいて選択される値のプレースホルダとして機能します。構成可能な属性で select() を使用すると、さまざまな条件が当てはまる場合に、属性に異なる値を効果的に採用できます。

一致は明確でなければなりません。複数の条件が一致する場合、いずれか * すべて同じ値に解決されます。たとえば、Linux x86 で実行する場合、どちらのブランチも「hello」に解決されるため、{"@platforms//os:linux": "Hello", "@platforms//cpu:x86_64": "Hello"} はあいまいではありません。* 一方の values は他すべての厳格なスーパーセットです。たとえば、values = {"cpu": "x86", "compilation_mode": "dbg"}values = {"cpu": "x86"} の明確なスペシャライゼーションです。

組み込み条件 //conditions:default は、他に何もなければ自動的に一致します。

この例では deps を使用していますが、select()srcsresourcescmd など、多くの属性でも同じように機能します。構成不可能な属性はごく一部であり、それらには明確にアノテーションが付けられています。たとえば、config_setting 自身の values 属性は構成できません。

select() と依存関係

特定の属性の場合、ターゲットにおけるすべての推移的依存関係のビルド パラメータが変更されます。たとえば、genruletools は、--cpu を Bazel を実行しているマシンの CPU に変更します(クロスコンパイルにより、ターゲットがビルドされている CPU とは異なる場合があります)。これは構成の移行と呼ばれます。

与えられた

#myapp/BUILD

config_setting(
    name = "arm_cpu",
    values = {"cpu": "arm"},
)

config_setting(
    name = "x86_cpu",
    values = {"cpu": "x86"},
)

genrule(
    name = "my_genrule",
    srcs = select({
        ":arm_cpu": ["g_arm.src"],
        ":x86_cpu": ["g_x86.src"],
    }),
    tools = select({
        ":arm_cpu": [":tool1"],
        ":x86_cpu": [":tool2"],
    }),
)

cc_binary(
    name = "tool1",
    srcs = select({
        ":arm_cpu": ["armtool.cc"],
        ":x86_cpu": ["x86tool.cc"],
    }),
)

ランニング

$ bazel build //myapp:my_genrule --cpu=arm

x86 デベロッパー マシンの場合は、ビルドを g_arm.srctool1x86tool.cc にバインドします。my_genrule にアタッチされている select はどちらも my_genrule のビルド パラメータ(--cpu=arm を含む)を使用します。tools 属性は、tool1 とその推移的依存関係について --cpux86 に変更します。tool1select は、--cpu=x86 を含む tool1 のビルド パラメータを使用します。

構成条件

構成可能な属性の各キーは、config_setting または constraint_value へのラベル参照です。

config_setting は、想定されるコマンドライン フラグ設定の集合です。これらをターゲットにカプセル化することで、ユーザーが複数の場所から参照できる「標準」条件を簡単に維持できます。

constraint_value は、マルチプラットフォーム動作をサポートします。

組み込みフラグ

--cpu などのフラグは Bazel に組み込まれています。ビルドツールは、すべてのプロジェクトのすべてのビルドで、これらのフラグをネイティブに認識します。これらは config_settingvalues 属性で指定します。

config_setting(
    name = "meaningful_condition_name",
    values = {
        "flag1": "value1",
        "flag2": "value2",
        ...
    },
)

flagN はフラグ名です(-- なしのため、"--cpu" ではなく "cpu")。そのフラグの期待値は valueN です。:meaningful_condition_name は、values 内のすべてのエントリが一致する場合に一致します。順序は重要でない。

valueN は、コマンドラインで設定されているものとして解析されます。これは次のことを意味します。

  • bazel build -c opt に一致する values = { "compilation_mode": "opt" }
  • bazel build --force_pic=1 に一致する values = { "force_pic": "true" }
  • bazel build --noforce_pic に一致する values = { "force_pic": "0" }

config_setting は、ターゲットの動作に影響するフラグのみをサポートします。たとえば、--show_progress は、Bazel がユーザーに進行状況を報告する方法にのみ影響するため、許可されません。ターゲットは、このフラグを使用して結果を作成することはできません。サポートされているフラグの正確なセットは文書化されていません。実際には、「意味がある」フラグのほとんどは機能します。

カスタムフラグ

Starlark ビルド設定を使用して、独自のプロジェクト固有のフラグをモデル化できます。組み込みフラグとは異なり、これらはビルド ターゲットとして定義されるため、Bazel はターゲット ラベルを使用してこれらを参照します。

これらは config_settingflag_values 属性でトリガーされます。

config_setting(
    name = "meaningful_condition_name",
    flag_values = {
        "//myflags:flag1": "value1",
        "//myflags:flag2": "value2",
        ...
    },
)

動作は組み込みフラグと同じです。実際の例については、こちらをご覧ください。

--define は、カスタムフラグの代替レガシー構文(--define foo=bar など)です。これは、values 属性(values = {"define": "foo=bar"})または define_values 属性(define_values = {"foo": "bar"})で表現できます。--define は下位互換性のためにのみサポートされています。可能な限り Starlark ビルド設定を優先します。

valuesflag_valuesdefine_values は個別に評価されます。config_setting は、すべての値が一致する場合に一致します。

デフォルトの条件

他の条件が一致しない場合、組み込み条件 //conditions:default は一致します。

「完全に 1 つの一致」ルールにより、一致がなく、デフォルト条件のない構成可能な属性の場合、"no matching conditions" エラーが出力されます。これにより、予期しない設定によるサイレント エラーから保護できます。

# myapp/BUILD

config_setting(
    name = "x86_cpu",
    values = {"cpu": "x86"},
)

cc_library(
    name = "x86_only_lib",
    srcs = select({
        ":x86_cpu": ["lib.cc"],
    }),
)
$ bazel build //myapp:x86_only_lib --cpu=arm
ERROR: Configurable attribute "srcs" doesn't match this configuration (would
a default condition help?).
Conditions checked:
  //myapp:x86_cpu

エラーをさらに明確にするには、select()no_match_error 属性を使用してカスタム メッセージを設定します。

プラットフォーム

コマンドラインで複数のフラグを指定できるため、柔軟性が得られますが、ターゲットをビルドするたびにフラグを個別に設定する負担が大きくなる場合があります。プラットフォームを使用すると、これらをシンプルなバンドルに統合できます。

# myapp/BUILD

sh_binary(
    name = "my_rocks",
    srcs = select({
        ":basalt": ["pyroxene.sh"],
        ":marble": ["calcite.sh"],
        "//conditions:default": ["feldspar.sh"],
    }),
)

config_setting(
    name = "basalt",
    constraint_values = [
        ":black",
        ":igneous",
    ],
)

config_setting(
    name = "marble",
    constraint_values = [
        ":white",
        ":metamorphic",
    ],
)

# constraint_setting acts as an enum type, and constraint_value as an enum value.
constraint_setting(name = "color")
constraint_value(name = "black", constraint_setting = "color")
constraint_value(name = "white", constraint_setting = "color")
constraint_setting(name = "texture")
constraint_value(name = "smooth", constraint_setting = "texture")
constraint_setting(name = "type")
constraint_value(name = "igneous", constraint_setting = "type")
constraint_value(name = "metamorphic", constraint_setting = "type")

platform(
    name = "basalt_platform",
    constraint_values = [
        ":black",
        ":igneous",
    ],
)

platform(
    name = "marble_platform",
    constraint_values = [
        ":white",
        ":smooth",
        ":metamorphic",
    ],
)

コマンドラインでプラットフォームを指定できます。これにより、プラットフォームの constraint_values のサブセットを含む config_setting が有効になり、それらの config_settingselect() 式で一致できるようになります。

たとえば、my_rockssrcs 属性を calcite.sh に設定するには、次のコマンドを実行します。

bazel build //my_app:my_rocks --platforms=//myapp:marble_platform

プラットフォームを使用しない場合は、

bazel build //my_app:my_rocks --define color=white --define texture=smooth --define type=metamorphic

select()constraint_value を直接読み取ることもできます。

constraint_setting(name = "type")
constraint_value(name = "igneous", constraint_setting = "type")
constraint_value(name = "metamorphic", constraint_setting = "type")
sh_binary(
    name = "my_rocks",
    srcs = select({
        ":igneous": ["igneous.sh"],
        ":metamorphic" ["metamorphic.sh"],
    }),
)

これにより、1 つの値のみをチェックする必要がある場合に、ボイラープレート config_setting が不要になります。

プラットフォームはまだ開発中です。詳しくは、こちらのドキュメントをご覧ください。

select() を組み合わせる

select は、同じ属性に複数回指定できます。

sh_binary(
    name = "my_target",
    srcs = ["always_include.sh"] +
           select({
               ":armeabi_mode": ["armeabi_src.sh"],
               ":x86_mode": ["x86_src.sh"],
           }) +
           select({
               ":opt_mode": ["opt_extras.sh"],
               ":dbg_mode": ["dbg_extras.sh"],
           }),
)

select を別の select 内に表示することはできません。selects をネストする必要があり、属性が他のターゲットを値として受け取る場合は、中間ターゲットを使用します。

sh_binary(
    name = "my_target",
    srcs = ["always_include.sh"],
    deps = select({
        ":armeabi_mode": [":armeabi_lib"],
        ...
    }),
)

sh_library(
    name = "armeabi_lib",
    srcs = select({
        ":opt_mode": ["armeabi_with_opt.sh"],
        ...
    }),
)

複数の条件が一致した場合に select を一致させる必要がある場合は、AND チェーンの使用を検討してください。

OR チェーン

次の点にご注意ください。

sh_binary(
    name = "my_target",
    srcs = ["always_include.sh"],
    deps = select({
        ":config1": [":standard_lib"],
        ":config2": [":standard_lib"],
        ":config3": [":standard_lib"],
        ":config4": [":special_lib"],
    }),
)

ほとんどの条件は同じ依存関係で評価されますが、この構文を読み取って維持するのは困難です。[":standard_lib"] を複数回繰り返す必要がない場合は便利です。

選択肢の一つとして、値を BUILD 変数として事前に定義する方法があります。

STANDARD_DEP = [":standard_lib"]

sh_binary(
    name = "my_target",
    srcs = ["always_include.sh"],
    deps = select({
        ":config1": STANDARD_DEP,
        ":config2": STANDARD_DEP,
        ":config3": STANDARD_DEP,
        ":config4": [":special_lib"],
    }),
)

これにより、依存関係の管理が容易になります。ただし、それでも不要な重複は発生します。

より直接的なサポートをご希望の場合は、次のいずれかをご利用ください。

selects.with_or

Skylibselects モジュールの with_or マクロは、select 内で直接 OR 条件をサポートしています。

load("@bazel_skylib//lib:selects.bzl", "selects")
sh_binary(
    name = "my_target",
    srcs = ["always_include.sh"],
    deps = selects.with_or({
        (":config1", ":config2", ":config3"): [":standard_lib"],
        ":config4": [":special_lib"],
    }),
)

selects.config_setting_group

Skylibselects モジュールの config_setting_group マクロは複数の config_setting に対する OR をサポートしています。

load("@bazel_skylib//lib:selects.bzl", "selects")
config_setting(
    name = "config1",
    values = {"cpu": "arm"},
)
config_setting(
    name = "config2",
    values = {"compilation_mode": "dbg"},
)
selects.config_setting_group(
    name = "config1_or_2",
    match_any = [":config1", ":config2"],
)
sh_binary(
    name = "my_target",
    srcs = ["always_include.sh"],
    deps = select({
        ":config1_or_2": [":standard_lib"],
        "//conditions:default": [":other_lib"],
    }),
)

selects.with_or とは異なり、異なるターゲットが複数の属性間で :config1_or_2 を共有できます。

複数の条件が一致すると、エラーになります。ただし、1 つの条件が他の条件を明確に「特殊化」していない場合や、すべて同じ値に解決される場合は除きます。詳しくはこちらをご覧ください。

AND チェーン

複数の条件が一致した場合に select 分岐を一致させる必要がある場合は、Skylib マクロ config_setting_group を使用します。

config_setting(
    name = "config1",
    values = {"cpu": "arm"},
)
config_setting(
    name = "config2",
    values = {"compilation_mode": "dbg"},
)
selects.config_setting_group(
    name = "config1_and_2",
    match_all = [":config1", ":config2"],
)
sh_binary(
    name = "my_target",
    srcs = ["always_include.sh"],
    deps = select({
        ":config1_and_2": [":standard_lib"],
        "//conditions:default": [":other_lib"],
    }),
)

OR チェーンとは異なり、既存の config_settingselect 内で直接 AND することはできません。明示的に config_setting_group でラップする必要があります。

カスタム エラー メッセージ

デフォルトでは、条件が一致しない場合、select() がアタッチされているターゲットはエラーで失敗します。

ERROR: Configurable attribute "deps" doesn't match this configuration (would
a default condition help?).
Conditions checked:
  //tools/cc_target_os:darwin
  //tools/cc_target_os:android

これは no_match_error 属性でカスタマイズできます。

cc_library(
    name = "my_lib",
    deps = select(
        {
            "//tools/cc_target_os:android": [":android_deps"],
            "//tools/cc_target_os:windows": [":windows_deps"],
        },
        no_match_error = "Please build with an Android or Windows toolchain",
    ),
)
$ bazel build //myapp:my_lib
ERROR: Configurable attribute "deps" doesn't match this configuration: Please
build with an Android or Windows toolchain

ルールの互換性

ルールの実装では、構成可能な属性の解決値を受け取ります。たとえば、次のようになります。

# myapp/BUILD

some_rule(
    name = "my_target",
    some_attr = select({
        ":foo_mode": [":foo"],
        ":bar_mode": [":bar"],
    }),
)
$ bazel build //myapp/my_target --define mode=foo

ルール実装コードでは ctx.attr.some_attr[":foo"] と見なされます。

マクロは select() 句を受け入れ、ネイティブ ルールに渡すことができます。ただし、データを直接操作することはできません。たとえば、マクロで文字列を変換することはできないので、

select({"foo": "val"}, ...)

たとえば

select({"foo": "val_with_suffix"}, ...)

これには 2 つの理由があります。

まず、select が選択するパスを認識する必要があるマクロは動作しません。マクロは Bazel の読み込みフェーズで評価され、このフェーズはフラグの値が判明する前になります。これは Bazel の設計上の制限であり、近いうちに変更される見込みはありません。

次に、すべての select パスを反復処理する必要があるマクロは技術的には可能ですが、一貫した UI がありません。これを変更するには、さらなる設計が必要です。

Bazel クエリと cquery

Bazel query は、Bazel の読み込みフェーズで動作します。つまり、ターゲットが使用するコマンドライン フラグは、ビルド後半(分析フェーズ)まで評価されないため、ターゲットは認識できません。そのため、どの select() ブランチが選択されるかを判別することはできません。

Bazel cquery は、Bazel の分析フェーズの後に動作するので、この情報がすべて含まれており、select() を正確に解決できます。

重要ポイント:

load("@bazel_skylib//rules:common_settings.bzl", "string_flag")
# myapp/BUILD

string_flag(
    name = "dog_type",
    build_setting_default = "cat"
)

cc_library(
    name = "my_lib",
    deps = select({
        ":long": [":foo_dep"],
        ":short": [":bar_dep"],
    }),
)

config_setting(
    name = "long",
    flag_values = {":dog_type": "dachshund"},
)

config_setting(
    name = "short",
    flag_values = {":dog_type": "pug"},
)

query:my_lib の依存関係を過剰近似します。

$ bazel query 'deps(//myapp:my_lib)'
//myapp:my_lib
//myapp:foo_dep
//myapp:bar_dep

cquery はその正確な依存関係を示します。

$ bazel cquery 'deps(//myapp:my_lib)' --//myapp:dog_type=pug
//myapp:my_lib
//myapp:bar_dep

よくある質問

マクロで select() が動作しないのはなぜですか?

select() はルールで機能します。詳しくは、ルールの互換性をご覧ください。

通常、この質問の重要な問題は select() がマクロで機能しないことです。これらはルールとは異なります。違いについては、ルールマクロのドキュメントをご覧ください。エンドツーエンドの例を次に示します。

ルールとマクロを定義します。

# myapp/defs.bzl

# Rule implementation: when an attribute is read, all select()s have already
# been resolved. So it looks like a plain old attribute just like any other.
def _impl(ctx):
    name = ctx.attr.name
    allcaps = ctx.attr.my_config_string.upper()  # This works fine on all values.
    print("My name is " + name + " with custom message: " + allcaps)

# Rule declaration:
my_custom_bazel_rule = rule(
    implementation = _impl,
    attrs = {"my_config_string": attr.string()},
)

# Macro declaration:
def my_custom_bazel_macro(name, my_config_string):
    allcaps = my_config_string.upper()  # This line won't work with select(s).
    print("My name is " + name + " with custom message: " + allcaps)

ルールとマクロをインスタンス化します。

# myapp/BUILD

load("//myapp:defs.bzl", "my_custom_bazel_rule")
load("//myapp:defs.bzl", "my_custom_bazel_macro")

my_custom_bazel_rule(
    name = "happy_rule",
    my_config_string = select({
        "//tools/target_cpu:x86": "first string",
        "//third_party/bazel_platforms/cpu:ppc": "second string",
    }),
)

my_custom_bazel_macro(
    name = "happy_macro",
    my_config_string = "fixed string",
)

my_custom_bazel_macro(
    name = "sad_macro",
    my_config_string = select({
        "//tools/target_cpu:x86": "first string",
        "//third_party/bazel_platforms/cpu:ppc": "other string",
    }),
)

sad_macroselect() を処理できないため、ビルドは失敗します。

$ bazel build //myapp:all
ERROR: /myworkspace/myapp/BUILD:17:1: Traceback
  (most recent call last):
File "/myworkspace/myapp/BUILD", line 17
my_custom_bazel_macro(name = "sad_macro", my_config_stri..."}))
File "/myworkspace/myapp/defs.bzl", line 4, in
  my_custom_bazel_macro
my_config_string.upper()
type 'select' has no method upper().
ERROR: error loading package 'myapp': Package 'myapp' contains errors.

sad_macro をコメントアウトすると、ビルドが成功します。

# Comment out sad_macro so it doesn't mess up the build.
$ bazel build //myapp:all
DEBUG: /myworkspace/myapp/defs.bzl:5:3: My name is happy_macro with custom message: FIXED STRING.
DEBUG: /myworkspace/myapp/hi.bzl:15:3: My name is happy_rule with custom message: FIRST STRING.

Bazel がビルドのコマンドライン フラグを読み取る前に、定義上マクロが評価されるため、これは変更できません。つまり、select() を評価するための十分な情報がありません。

ただし、マクロは select() を不透明な blob としてルールに渡すことができます。

# myapp/defs.bzl

def my_custom_bazel_macro(name, my_config_string):
    print("Invoking macro " + name)
    my_custom_bazel_rule(
        name = name + "_as_target",
        my_config_string = my_config_string,
    )
$ bazel build //myapp:sad_macro_less_sad
DEBUG: /myworkspace/myapp/defs.bzl:23:3: Invoking macro sad_macro_less_sad.
DEBUG: /myworkspace/myapp/defs.bzl:15:3: My name is sad_macro_less_sad with custom message: FIRST STRING.

select() が常に true を返すのはなぜですか?

マクロ(ルールではない)は定義上、select() を評価できないため、通常、エラーが生成されます。

ERROR: /myworkspace/myapp/BUILD:17:1: Traceback
  (most recent call last):
File "/myworkspace/myapp/BUILD", line 17
my_custom_bazel_macro(name = "sad_macro", my_config_stri..."}))
File "/myworkspace/myapp/defs.bzl", line 4, in
  my_custom_bazel_macro
my_config_string.upper()
type 'select' has no method upper().

ブール値は、通知なく失敗する特殊なケースであるため、特に注意してください。

$ cat myapp/defs.bzl
def my_boolean_macro(boolval):
  print("TRUE" if boolval else "FALSE")

$ cat myapp/BUILD
load("//myapp:defs.bzl", "my_boolean_macro")
my_boolean_macro(
    boolval = select({
        "//tools/target_cpu:x86": True,
        "//third_party/bazel_platforms/cpu:ppc": False,
    }),
)

$ bazel build //myapp:all --cpu=x86
DEBUG: /myworkspace/myapp/defs.bzl:4:3: TRUE.
$ bazel build //mypro:all --cpu=ppc
DEBUG: /myworkspace/myapp/defs.bzl:4:3: TRUE.

これは、マクロが select() の内容を認識しないためです。そのため、実際に評価するのは select() オブジェクトそのものです。Pythonic 設計標準によると、少数の例外を除き、すべてのオブジェクトは自動的に true を返します。

select() を dict のように読み取ることはできますか?

マクロは Bazel がビルドのコマンドライン パラメータを認識する前に評価するため、SELECT を評価できません。少なくとも select() の辞書を読み取れる(たとえば、各値に接尾辞を追加するなど)できますか?

概念的には可能ですが、まだ Bazel の機能ではありません。 今すぐできることは、単純な辞書を準備し、それを select() にフィードすることです。

$ cat myapp/defs.bzl
def selecty_genrule(name, select_cmd):
  for key in select_cmd.keys():
    select_cmd[key] += " WITH SUFFIX"
  native.genrule(
      name = name,
      outs = [name + ".out"],
      srcs = [],
      cmd = "echo " + select(select_cmd + {"//conditions:default": "default"})
        + " > $@"
  )

$ cat myapp/BUILD
selecty_genrule(
    name = "selecty",
    select_cmd = {
        "//tools/target_cpu:x86": "x86 mode",
    },
)

$ bazel build //testapp:selecty --cpu=x86 && cat bazel-genfiles/testapp/selecty.out
x86 mode WITH SUFFIX

select() とネイティブ型の両方をサポートする場合は、次のようにします。

$ cat myapp/defs.bzl
def selecty_genrule(name, select_cmd):
    cmd_suffix = ""
    if type(select_cmd) == "string":
        cmd_suffix = select_cmd + " WITH SUFFIX"
    elif type(select_cmd) == "dict":
        for key in select_cmd.keys():
            select_cmd[key] += " WITH SUFFIX"
        cmd_suffix = select(select_cmd + {"//conditions:default": "default"})

    native.genrule(
        name = name,
        outs = [name + ".out"],
        srcs = [],
        cmd = "echo " + cmd_suffix + "> $@",
    )

select() が bind() と連携しないのはなぜですか?

まず、bind() は使用しないでください。非推奨になり、alias() に置き換えられました。

技術的な答えは、bind() は BUILD ルールではなく、リポジトリ ルールであるということです。

Repo ルールには特定の構成はなく、BUILD ルールと同じ方法で評価されません。したがって、bind() 内の select() が実際に特定のブランチを評価することはできません。

代わりに、actual 属性で select() を指定して alias() を使用し、この種の実行時の判定を行う必要があります。alias() は BUILD ルールであり、特定の構成で評価されるため、これは正しく機能します。

$ cat WORKSPACE
workspace(name = "myapp")
bind(name = "openssl", actual = "//:ssl")
http_archive(name = "alternative", ...)
http_archive(name = "boringssl", ...)

$ cat BUILD
config_setting(
    name = "alt_ssl",
    define_values = {
        "ssl_library": "alternative",
    },
)

alias(
    name = "ssl",
    actual = select({
        "//:alt_ssl": "@alternative//:ssl",
        "//conditions:default": "@boringssl//:ssl",
    }),
)

この設定で、--define ssl_library=alternative を渡すことができます。//:ssl または //external:ssl に依存するターゲットは、@alternative//:ssl にある代替パスを参照します。

ただし、bind() の使用はやめてください。

select() で想定どおりの結果が選択されないのはなぜですか?

//myapp:fooselect() が想定する条件を選択しない場合は、cquerybazel config を使用してデバッグします。

作成中のトップレベル ターゲットが //myapp:foo の場合は、次のコマンドを実行します。

$ bazel cquery //myapp:foo <desired build flags>
//myapp:foo (12e23b9a2b534a)

サブグラフのどこか //myapp:foo に依存している他のターゲット //bar をビルドする場合は、次のコマンドを実行します。

$ bazel cquery 'somepath(//bar, //myapp:foo)' <desired build flags>
//bar:bar   (3ag3193fee94a2)
//bar:intermediate_dep (12e23b9a2b534a)
//myapp:foo (12e23b9a2b534a)

//myapp:foo の横にある (12e23b9a2b534a) は、//myapp:fooselect() を解決する構成のハッシュです。この値は bazel config で確認できます。

$ bazel config 12e23b9a2b534a
BuildConfigurationValue 12e23b9a2b534a
Fragment com.google.devtools.build.lib.analysis.config.CoreOptions {
  cpu: darwin
  compilation_mode: fastbuild
  ...
}
Fragment com.google.devtools.build.lib.rules.cpp.CppOptions {
  linkopt: [-Dfoo=bar]
  ...
}
...

次に、この出力を、各 config_setting で想定される設定と比較します。

//myapp:foo は、同じビルド内に異なる構成に存在する場合があります。somepath を使用して適切なものを取得する方法については、cquery のドキュメントをご覧ください。

select() がプラットフォームで動作しないのはなぜですか?

Bazel では、セマンティクスが不明瞭なため、特定のプラットフォームがターゲット プラットフォームであるかどうかをチェックする構成可能な属性はサポートされていません。

例:

platform(
    name = "x86_linux_platform",
    constraint_values = [
        "@platforms//cpu:x86",
        "@platforms//os:linux",
    ],
)

cc_library(
    name = "lib",
    srcs = [...],
    linkopts = select({
        ":x86_linux_platform": ["--enable_x86_optimizations"],
        "//conditions:default": [],
    }),
)

ターゲット プラットフォームに @platforms//cpu:x86@platforms//os:linux の両方の制約があり、ここで定義された :x86_linux_platform ではない場合、この BUILD ファイルでは、どの select() を使用する必要がありますか?BUILD ファイルの作成者と別のプラットフォームを定義したユーザーは、考え方が異なる場合があります。

別の方法があれば教えてください。

代わりに、次の制約のある任意のプラットフォームに一致する config_setting を定義します。

config_setting(
    name = "is_x86_linux",
    constraint_values = [
        "@platforms//cpu:x86",
        "@platforms//os:linux",
    ],
)

cc_library(
    name = "lib",
    srcs = [...],
    linkopts = select({
        ":is_x86_linux": ["--enable_x86_optimizations"],
        "//conditions:default": [],
    }),
)

このプロセスでは特定のセマンティクスが定義され、どのプラットフォームが望ましい条件を満たすかがユーザーに明示されます。

YouTube で本当にselectをしたいときは、どうすればよいか?

ビルド要件で特にプラットフォームを確認する必要がある場合は、config_setting--platforms フラグの値を反転できます。

config_setting(
    name = "is_specific_x86_linux_platform",
    values = {
        "platforms": ["//package:x86_linux_platform"],
    },
)

cc_library(
    name = "lib",
    srcs = [...],
    linkopts = select({
        ":is_specific_x86_linux_platform": ["--enable_x86_optimizations"],
        "//conditions:default": [],
    }),
)

Bazel チームはこの方法を支持していません。ビルドに過剰な制約が生じ、予期される条件が一致しないとユーザーを混乱させます。