Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions core/main.gd
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
extends Node

var args := OS.get_cmdline_args()
var feature_flags := load("res://core/systems/features/feature_flags.tres") as FeatureFlags


# Called when the node enters the scene tree for the first time.
func _ready() -> void:
# Resolve feature flags from launch arguments and the environment
feature_flags.load_from_os()

# Display a custom help if 'help' in args
if "help" in args:
_show_help()
Expand Down Expand Up @@ -51,4 +55,13 @@ func _show_help() -> void:
print("Environment Variables:")
print(" LOG_LEVEL Set the global log level (debug,info,warn,error)")
print(" LOG_LEVEL_<NAME> Set the log level for one logger (debug,info,warn,error)")
print(" OGUI_FEATURES Comma-separated list of features to enable")
print(" OGUI_DISABLED_FEATURES Comma-separated list of features to disable")
print("")
print("Features (--feature-<id> / --feature-no-<id>):")
for feature in feature_flags.get_features():
var description := feature.description
if description == "":
description = "Feature flag"
print(" ", feature.id, " ", description)
print("")
30 changes: 30 additions & 0 deletions core/systems/features/feature.gd
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
extends Resource
class_name Feature

## Definition of a single feature flag
##
## A Feature describes one toggleable behavior: its id, description, and default
## state. Feature objects hold no logic and are registered with [FeatureFlags].

## The normalized identifier of this feature (lowercase, hyphen-separated).
@export var id: String = ""

## Human-readable description, used by help output and settings UI.
@export var description: String = ""

## The state this feature has when no source overrides it.
@export var default: bool = false


## Creates a new feature with a normalized id.
static func create(feature_id: String, feature_default: bool = false, feature_description: String = "") -> Feature:
var feature := Feature.new()
feature.id = normalize(feature_id)
feature.description = feature_description
feature.default = feature_default
return feature


## Normalizes a feature id: lowercase, with underscores and spaces replaced by hyphens.
static func normalize(feature_id: String) -> String:
return feature_id.to_lower().replace("_", "-").replace(" ", "-")
1 change: 1 addition & 0 deletions core/systems/features/feature.gd.uid
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
uid://bpubgh1iqco41
268 changes: 268 additions & 0 deletions core/systems/features/feature_flags.gd
Original file line number Diff line number Diff line change
@@ -0,0 +1,268 @@
extends Resource
class_name FeatureFlags

## Registry of feature flags
##
## FeatureFlags parses command-line arguments and environment variables to turn
## features on or off, and allows features to be toggled at runtime by plugins and
## platform classes. Signals are emitted when a feature changes so the UI can react.

signal feature_registered(feature: Feature)
signal feature_changed(feature: Feature, enabled: bool)
signal feature_enabled(feature: Feature)
signal feature_disabled(feature: Feature)

## Where the current value of a feature came from.
enum Source { DEFAULT, ENV, ARG, RUNTIME }

## Environment variable prefix for a single feature, e.g. OGUI_FEATURE_UPDATER=0.
const ENV_PREFIX := "OGUI_FEATURE_"

## Environment variable containing a list of features to enable.
const ENV_LIST := "OGUI_FEATURES"

## Environment variable containing a list of features to disable.
const ENV_DISABLED_LIST := "OGUI_DISABLED_FEATURES"

## Command-line argument prefix for a single feature, e.g. --feature-no-updater.
const ARG_PREFIX := "--feature-"

const TRUTHY := ["1", "true", "yes", "on", "enable", "enabled"]
const FALSY := ["0", "false", "no", "off", "disable", "disabled"]

## The registered features.
@export var features: Array[Feature] = []

var _env: Dictionary = {}
var _env_overrides: Dictionary[String, bool] = {}
var _arg_overrides: Dictionary[String, bool] = {}
var _runtime_overrides: Dictionary[String, bool] = {}
var logger: CustomLogger = Log.get_logger("FeatureFlags")


func _init() -> void:
load_from_os()


## Registers a feature. Returns OK if the feature was newly registered.
func register_feature(feature: Feature) -> Error:
if not feature or feature.id == "":
logger.warn("Cannot register a feature without an id")
return Error.ERR_INVALID_PARAMETER
feature.id = Feature.normalize(feature.id)
Comment thread
pastaq marked this conversation as resolved.
Resolved
if get_feature(feature.id):
return Error.ERR_ALREADY_EXISTS
features.append(feature)
feature_registered.emit(feature)
var value := _resolve(feature.id)
if value != feature.default:
_emit_change(feature, value)
return Error.OK


## Returns the registered feature with the given id, or null if it is not registered.
func get_feature(id: String) -> Feature:
var normalized := Feature.normalize(id)
for feature in features:
if feature and Feature.normalize(feature.id) == normalized:
return feature
return null


## Returns all registered features.
func get_features() -> Array[Feature]:
return features


## Returns whether the given feature is enabled. Unknown features return false.
func is_enabled(id: String) -> bool:
var normalized := Feature.normalize(id)
var feature := get_feature(normalized)
if not feature:
logger.warn("Unknown feature: " + normalized)
return false
return _resolve(normalized)


## Sets a feature at runtime. The runtime value takes precedence over all sources.
func set_feature(id: String, enabled: bool) -> void:
var normalized := Feature.normalize(id)
if not get_feature(normalized):
logger.warn("Cannot set unknown feature: " + normalized)
return
_apply(normalized, enabled, Source.RUNTIME)


## Turns the given feature on at runtime. Shortcut for set_feature(id, true).
func enable(id: String) -> void:
set_feature(id, true)


## Turns the given feature off at runtime. Shortcut for set_feature(id, false).
func disable(id: String) -> void:
set_feature(id, false)


## Flips the given feature to the opposite of its current state at runtime.
func toggle(id: String) -> void:
set_feature(id, not is_enabled(id))


## Clears the runtime override so the feature resolves from its sources again.
func reset(id: String) -> void:
var normalized := Feature.normalize(id)
if not _runtime_overrides.has(normalized):
return
var before := _resolve(normalized)
_runtime_overrides.erase(normalized)
var feature := get_feature(normalized)
if not feature or before == _resolve(normalized):
return
_emit_change(feature, _resolve(normalized))


## Returns which source produced the current value of the given feature.
func get_source(id: String) -> int:
var normalized := Feature.normalize(id)
if _runtime_overrides.has(normalized):
return Source.RUNTIME
if _arg_overrides.has(normalized):
return Source.ARG
if _has_env_value(normalized):
return Source.ENV
return Source.DEFAULT


## Clears all parsed values so the sources can be applied again.
func clear_sources() -> void:
_env = {}
_env_overrides.clear()
_arg_overrides.clear()
_runtime_overrides.clear()


## Applies the given command-line arguments. Testable entrypoint.
func parse_args(args: Array[String]) -> void:
for arg in args:
if not arg.begins_with(ARG_PREFIX):
continue
var id := arg.trim_prefix(ARG_PREFIX)
var enabled := true
if id.begins_with("no-"):
enabled = false
id = id.trim_prefix("no-")
if id == "":
continue
_apply(Feature.normalize(id), enabled, Source.ARG)


## Applies the given environment variables. Testable entrypoint.
func parse_env(env: Dictionary) -> void:
_env = env
# Bulk lists are applied first so per-feature variables take precedence.
for id in _parse_list(str(env.get(ENV_LIST, ""))):
_apply(id, true, Source.ENV)
for id in _parse_list(str(env.get(ENV_DISABLED_LIST, ""))):
_apply(id, false, Source.ENV)
for key in env:
var name := str(key)
if not name.begins_with(ENV_PREFIX):
continue
var raw := str(env[key])
if not _is_bool_string(raw):
logger.warn("Unable to parse value for " + name + ", using default")
continue
_apply(Feature.normalize(name.trim_prefix(ENV_PREFIX)), _to_bool(raw), Source.ENV)


## Parses the process command-line arguments and environment.
func load_from_os() -> void:
parse_args(OS.get_cmdline_args())
parse_env(_collect_env())


func _resolve(id: String) -> bool:
if _runtime_overrides.has(id):
return _runtime_overrides[id]
if _arg_overrides.has(id):
return _arg_overrides[id]
if _has_env_value(id):
return _env_value(id)
var feature := get_feature(id)
if not feature:
return false
return feature.default


func _has_env_value(id: String) -> bool:
return _env_overrides.has(id) or _is_bool_string(_read_env(ENV_PREFIX + _env_key(id)))


func _env_value(id: String) -> bool:
if _env_overrides.has(id):
return _env_overrides[id]
return _to_bool(_read_env(ENV_PREFIX + _env_key(id)))


func _apply(id: String, value: bool, source: int) -> void:
var before := _resolve(id)
if source == Source.RUNTIME:
_runtime_overrides[id] = value
elif source == Source.ARG:
_arg_overrides[id] = value
elif source == Source.ENV:
_env_overrides[id] = value
if before == value:
return
var feature := get_feature(id)
if not feature:
return
_emit_change(feature, value)


func _emit_change(feature: Feature, value: bool) -> void:
feature_changed.emit(feature, value)
if value:
feature_enabled.emit(feature)
else:
feature_disabled.emit(feature)


func _read_env(name: String) -> String:
if _env.has(name):
return str(_env[name])
return OS.get_environment(name)


func _collect_env() -> Dictionary:
var env := {}
env[ENV_LIST] = OS.get_environment(ENV_LIST)
env[ENV_DISABLED_LIST] = OS.get_environment(ENV_DISABLED_LIST)
for feature in features:
if not feature:
continue
var name := ENV_PREFIX + _env_key(feature.id)
env[name] = OS.get_environment(name)
return env


func _env_key(id: String) -> String:
return id.replace("-", "_").to_upper()


func _is_bool_string(raw: String) -> bool:
var value := raw.to_lower()
return value in TRUTHY or value in FALSY


func _to_bool(raw: String) -> bool:
return raw.to_lower() in TRUTHY


func _parse_list(raw: String) -> Array[String]:
var ids: Array[String] = []
for part in raw.replace(",", " ").split(" "):
if part == "":
continue
ids.append(Feature.normalize(part))
return ids
1 change: 1 addition & 0 deletions core/systems/features/feature_flags.gd.uid
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
uid://b6lv3knr8wjqx
20 changes: 20 additions & 0 deletions core/systems/features/feature_flags.tres
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[gd_resource type="Resource" script_class="FeatureFlags" format=3 uid="uid://cfb4ht3s2u5ox"]

[ext_resource type="Script" uid="uid://bpubgh1iqco41" path="res://core/systems/features/feature.gd" id="1_feature"]
[ext_resource type="Script" uid="uid://b6lv3knr8wjqx" path="res://core/systems/features/feature_flags.gd" id="2_feature_flags"]

[sub_resource type="Resource" id="Feature_updater"]
script = ExtResource("1_feature")
id = "updater"
description = "Allow checking for and installing app updates"
default = true

[sub_resource type="Resource" id="Feature_tdp"]
script = ExtResource("1_feature")
id = "tdp"
description = "Allow managing TDP settings"
default = true

[resource]
script = ExtResource("2_feature_flags")
features = Array[ExtResource("1_feature")]([SubResource("Feature_updater"), SubResource("Feature_tdp")])
Loading
Loading