GN元构建中仅当文件存在时添加可选Action输入的实现方法咨询
Let's start by grounding this in GN's official guidance for action inputs, since that helps frame the best practices here:
For
actionandaction_foreachtargets,inputsshould specify non-variable inputs for the script. These include all.pyfiles the script uses via imports (the main script itself is an implicit dependency and doesn't need to be listed). Foractiontargets,inputsandsourcesare handled the same way, but stylistically it's best to follow the same rule asaction_foreach: put helper files ininputsand any data the script uses insources.Another way to declare action input dependencies is to have the action generate a
depfile(seegn help depfile). This lets the script dynamically write input dependencies that might only be determined when the script actually runs. This is more efficient than handling fixed inputs during GN runtime and easier to keep in sync than hardcoded lists.
Now, to your specific question: you want to add an optional input file to your list only if it exists, but GN doesn't have a built-in way to check for file existence during the configure phase.
The depfile approach you're already considering is indeed the most robust solution here—and it's not just a workaround, it's aligned with GN's recommended pattern for dynamic dependencies. Here's how it works for your case:
- When your action script runs, it can check if the optional file exists on disk.
- If it does, the script adds that file path to the generated
depfile. GN will then track it as a dependency, so any changes to the file will trigger a rebuild. - If the file doesn't exist, you just omit it from the depfile, and GN will never try to process it.
Are there other options? You could use exec_script to run a tiny helper during gn gen that checks for the file and returns an input list. But this has significant drawbacks:
- It only runs once during the initial configure. If you add or remove the optional file later, you'll have to re-run
gn genmanually for GN to pick up the change. - It adds extra configuration complexity, whereas the
depfileapproach keeps all the logic within your existing action script.
So all things considered, sticking with the depfile method is the way to go—it's dynamic, low-maintenance, and fits how GN is designed to handle variable dependencies.
内容的提问来源于stack exchange,提问作者Alexey Romanov

