ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
options/config.c
Go to the documentation of this file.
1
6
7/* Storage capacities in elements; text buffers include the terminating NUL. */
8#define OPTIONS_CONFIG_QUESTION_BUFFER_SIZE 4096
9
11
12#include <options/config.h>
13#include <options/enums.h>
15#include <options/options.h>
16#include <options/validation.h>
18#include <options/rcu.h>
20#include <util/string.h>
22#include <ascii-chat/common.h>
23#include <libplatform/terminal.h>
24#include <libplatform/system.h>
25#include <libplatform/question.h>
26#include <sys/stat.h>
27#include <libplatform/filesystem.h>
28#include <libflags/builder.h>
29#include <libflags/config.h>
30#include <libflags/explicit.h>
32#include <ascii-chat/log/log.h>
35#include <ascii-chat/version.h>
36#include <defer.h>
37
38#include <string.h>
39#include <stdlib.h>
40#include <stdio.h>
41#include <errno.h>
42#include <sys/stat.h>
43
51 flags_schema_builder_t *builder = flags_schema_builder_create();
52 if (!builder)
53 return NULL;
54 if (registry_add_all_to_flags_builder(builder, mode_mask) != ASCIICHAT_OK) {
55 flags_schema_builder_destroy(builder);
56 return NULL;
57 }
58
59 return builder;
60}
61
68#define CONFIG_WARN(fmt, ...) \
69 do { \
70 log_warn("Config file: " fmt, ##__VA_ARGS__); \
71 } while (0)
72
79#define CONFIG_DEBUG(fmt, ...) \
80 do { \
81 /* Debug messages are only shown in debug builds after logging is initialized */ \
82 /* Use log_dev which safely checks initialization itself */ \
83 log_dev(fmt, ##__VA_ARGS__); \
84 } while (0)
85
87
88asciichat_error_t config_create_default(const char *config_path) {
89 /*
90 * The schema and serializer belong to libflags. ascii-chat only owns the
91 * application-specific destination policy and overwrite confirmation.
92 */
93 char *expanded_path = NULL;
94 defer(SAFE_FREE(expanded_path));
95
96 const char *output_path = "-";
97 if (config_path && config_path[0] != '\0') {
98 expanded_path = expand_path(config_path);
99 if (!expanded_path)
100 expanded_path = platform_strdup(config_path);
101 if (!expanded_path)
102 return SET_ERRNO(ERROR_MEMORY, "Failed to resolve config file path");
103
104 char *validated_path = NULL;
105 asciichat_error_t validation = path_validate_user_path(expanded_path, PATH_ROLE_CONFIG_FILE, &validated_path);
106 if (validation != ASCIICHAT_OK) {
107 SAFE_FREE(validated_path);
108 return validation;
109 }
110 SAFE_FREE(expanded_path);
111 expanded_path = validated_path;
112 output_path = expanded_path;
113
114 struct stat st;
115 if (stat(output_path, &st) == 0) {
116 log_plain("Config file already exists: %s", output_path);
118 safe_snprintf(question, sizeof(question), "File already exists: %s\n\nOverwrite", output_path);
119 if (!ui_notice_confirm_kind(UI_PROMPT_CONFIG_OVERWRITE, UI_NOTICE_WARNING, question, 30))
120 return SET_ERRNO(ERROR_CONFIG, "User cancelled overwrite");
121 }
122
123 char *directory = platform_strdup(output_path);
124 if (!directory)
125 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate memory for config directory");
126 char *separator = strrchr(directory, PATH_DELIM);
127 if (separator) {
128 *separator = '\0';
129 asciichat_error_t mkdir_result = platform_mkdir_recursive(directory, DIR_PERM_PRIVATE);
130 SAFE_FREE(directory);
131 if (mkdir_result != ASCIICHAT_OK)
132 return mkdir_result;
133 } else {
134 SAFE_FREE(directory);
135 }
136 }
137
138 options_t defaults = options_t_new();
140 if (!builder)
141 return SET_ERRNO(ERROR_CONFIG, "Failed to build configuration schema");
142 flags_context_t *context = flags_create(flags_schema_builder_schema(builder), &defaults, sizeof(defaults));
143 if (!context) {
144 flags_schema_builder_destroy(builder);
145 return SET_ERRNO(ERROR_CONFIG, "Failed to create configuration context");
146 }
147
148 const bool written = flags_config_write_toml(context, output_path);
149 flags_destroy(context);
150 flags_schema_builder_destroy(builder);
151 if (!written)
152 return SET_ERRNO(ERROR_CONFIG, "Failed to write configuration to '%s'", output_path);
153 return ASCIICHAT_OK;
154}
155
156asciichat_error_t config_load_and_apply(asciichat_mode_t detected_mode, const char *config_path, bool strict, options_t *opts) {
157 if (!opts)
158 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing configuration path or destination");
159 if (!config_path)
160 return strict ? SET_ERRNO(ERROR_CONFIG, "Missing configuration path") : ASCIICHAT_OK;
161
162 struct stat file_info;
163 if (strcmp(config_path, "-") != 0 && stat(config_path, &file_info) != 0) {
164 if (!strict && (errno == ENOENT || errno == ENOTDIR))
165 return ASCIICHAT_OK;
166 return SET_ERRNO(ERROR_CONFIG, "Unable to access configuration file '%s': %s", config_path, platform_strerror(errno));
167 }
168
169 const option_mode_bitmask_t mode_mask = detected_mode == MODE_DISCOVERY ? OPTION_MODE_ALL : (option_mode_bitmask_t)(OPTION_MODE_BINARY | (1U << detected_mode));
171 if (!builder)
172 return SET_ERRNO(ERROR_CONFIG, "Failed to build configuration schema");
173 flags_context_t *context = flags_create(flags_schema_builder_schema(builder), opts, sizeof(*opts));
174 if (!context) {
175 flags_schema_builder_destroy(builder);
176 return SET_ERRNO(ERROR_MEMORY, "Failed to create configuration context");
177 }
178
179 const bool loaded = flags_config_load_toml(context, config_path);
180 if (loaded && !flags_explicit_state_merge(context)) {
181 flags_destroy_preserving_storage(context);
182 flags_schema_builder_destroy(builder);
183 return SET_ERRNO(ERROR_MEMORY, "Failed to record explicit option state");
184 }
185 if (loaded)
186 options_resolve_flip_x(opts, flags_was_explicitly_set(context, "flip-x"));
187 flags_destroy_preserving_storage(context);
188 flags_schema_builder_destroy(builder);
189 if (!loaded && !strict)
190 return ASCIICHAT_OK;
191 if (!loaded)
192 return SET_ERRNO(ERROR_CONFIG, "Failed to load configuration file '%s'", config_path);
193 return ASCIICHAT_OK;
194}
195
197 // Use platform abstraction to find all config.toml files across standard locations
198 config_file_list_t config_files = {0};
199 asciichat_error_t search_result = platform_find_config_file("config.toml", &config_files);
200 defer(config_file_list_destroy(&config_files));
201
202 // Keep the application config authoritative even when an older platform
203 // runtime is present. The explicit config path and generated config both
204 // use this directory, so discovery must not silently fall back to the
205 // generic "application" directory.
206 if (search_result == ASCIICHAT_OK && config_files.count == 0) {
207 char *config_dir = get_config_dir();
208 if (config_dir) {
209 size_t dir_len = strlen(config_dir);
210 bool has_separator = dir_len > 0 && (config_dir[dir_len - 1] == '/' || config_dir[dir_len - 1] == '\\');
211 size_t path_len = dir_len + (has_separator ? 0 : 1) + strlen("config.toml") + 1;
212 char *path = SAFE_MALLOC(path_len, char *);
213 if (path) {
214 safe_snprintf(path, path_len, "%s%sconfig.toml", config_dir, has_separator ? "" : "\\");
215 if (config_files.capacity > config_files.count) {
216 config_file_result_t *file = &config_files.files[config_files.count++];
217 file->path = path;
218 file->priority = 0;
219 file->exists = true;
220 file->is_system_config = false;
221 path = NULL;
222 }
223 SAFE_FREE(path);
224 }
225 SAFE_FREE(config_dir);
226 }
227 }
228
229 if (search_result != ASCIICHAT_OK) {
230 CONFIG_DEBUG("Failed to search for config files: %d", search_result);
231 return search_result;
232 }
233
234 // Cascade load: Load all found configs in reverse order (lowest priority first)
235 // This allows higher-priority configs to override lower-priority values.
236 // Example: System configs load first, then user configs override them.
237
239 for (size_t i = config_files.count; i > 0; i--) {
240 const config_file_result_t *file = &config_files.files[i - 1];
241
242 // Determine strictness based on whether this is a system or user config
243 // System configs are non-strict (values can be missing, errors are non-fatal)
244 // User config is strict or non-strict based on parameter
245 bool is_user_config = !file->is_system_config;
246 bool file_strict = is_user_config ? strict : false;
247
248 CONFIG_DEBUG("Loading config from %s (system=%s, strict=%s)", file->path, file->is_system_config ? "yes" : "no", file_strict ? OPT_VALUE_TRUE : OPT_VALUE_FALSE);
249
251 asciichat_error_t load_result = config_load_and_apply(detected_mode, file->path, file_strict, opts);
252
253 if (load_result != ASCIICHAT_OK) {
254 if (file_strict) {
255 // Strict mode: errors are fatal
256 CONFIG_DEBUG("Strict config loading failed for %s", file->path);
257 result = load_result;
258 } else {
259 // Non-strict mode: errors are non-fatal, just log and continue
260 CONFIG_DEBUG("Non-strict config loading warning for %s: %d (continuing)", file->path, load_result);
262 ASSERT_NO_ERRNO_SINCE(load_scope);
263 }
264 } else {
265 ASSERT_NO_ERRNO_SINCE(load_scope);
267 }
268 }
269
270 return result;
271}
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
asciichat_errno_scope_t errno_scope_begin(void)
#define SET_ERRNO(code,...)
#define ASSERT_NO_ERRNO_SINCE(scope)
@ ASCIICHAT_ERRNO_HANDLED
@ ASCIICHAT_ERRNO_DISMISSED
Option enum value definitions - single source of truth.
#define OPT_VALUE_FALSE
Definition enums.h:79
#define OPT_VALUE_TRUE
Definition enums.h:78
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
Error and exit codes - unified status values (0-255).
int platform_mkdir_recursive(const char *path, int mode)
Definition filesystem.c:36
int platform_find_config_file(const char *filename, config_file_list_t *list_out)
Definition filesystem.c:42
void config_file_list_destroy(config_file_list_t *list)
Definition filesystem.c:52
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
asciichat_error_t config_load_system_and_user(asciichat_mode_t detected_mode, bool strict, options_t *opts)
Load system config first, then user config (user config overrides system).
flags_schema_builder_t * options_config_build_flags_schema(option_mode_bitmask_t mode_mask)
asciichat_error_t config_create_default(const char *config_path)
Create default configuration file with all default values.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_INVALID_PARAM
#define log_plain(...)
Plain logging - writes to both log file and stderr without timestamps or log levels.
Definition log/log.h:659
asciichat_mode_t
Mode type for options parsing.
Definition options.h:916
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
option_mode_bitmask_t
Option mode bitmask.
Definition options.h:933
options_t options_t_new(void)
Initialize options by parsing command-line arguments.
Definition options.c:643
@ MODE_DISCOVERY
Discovery mode - participant that can dynamically become host.
Definition options.h:921
@ OPTION_MODE_ALL
All modes + binary.
Definition options.h:943
@ OPTION_MODE_BINARY
Binary-level options (parsed before mode detection).
Definition options.h:942
asciichat_error_t path_validate_user_path(const char *input, path_role_t role, char **normalized_out)
Validate and canonicalize a user-supplied filesystem path.
Definition path.c:705
char * expand_path(const char *path)
Expand path with tilde (~) support.
Definition path.c:257
char * get_config_dir(void)
Get configuration directory path with XDG_CONFIG_HOME support.
Definition path.c:279
@ PATH_ROLE_CONFIG_FILE
Definition path.h:323
⚙️ Common definitions, error codes, macros, and types shared throughout the application
Central registry of all command-line options with mode applicability.
struct flags_schema_builder flags_schema_builder_t
📝 Logging API with multiple log levels and terminal output control
bool ui_notice_confirm_kind(ui_prompt_kind_t kind, ui_notice_severity_t severity, const char *text, unsigned timeout_seconds)
Definition notice.c:479
@ UI_NOTICE_WARNING
Definition notice.h:13
#define OPTIONS_CONFIG_QUESTION_BUFFER_SIZE
#define CONFIG_DEBUG(fmt,...)
Print configuration debug message.
asciichat_error_t config_load_and_apply(asciichat_mode_t detected_mode, const char *config_path, bool strict, options_t *opts)
Load configuration from TOML file and apply to global options.
TOML configuration file support for ascii-chat.
Validation functions for options parsing.
void options_resolve_flip_x(options_t *opts, bool explicitly_set)
Definition options.c:2435
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
ASCII Palette Management for Video-to-ASCII Conversion.
📂 Path Manipulation Utilities
asciichat_error_t registry_add_all_to_flags_builder(flags_schema_builder_t *builder, option_mode_bitmask_t mode_mask)
Definition public_api.c:84
char * platform_strdup(const char *s)
🔤 String Manipulation and Shell Escaping Utilities
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
const char * platform_strerror(int errnum)
Definition system.c:52
🔤 UTF-8 Encoding and Decoding Utilities