diff --git a/include/utilities.h b/include/utilities.h index c1b959e..a96ba22 100644 --- a/include/utilities.h +++ b/include/utilities.h @@ -64,5 +64,7 @@ void combine_path(char*, char*); PathType get_path_type(const char*); char* get_file_content(char*); char* get_file_content_with_size(char*, size_t*); +int create_default_config_file(char*); + #endif // UTILITIES_H diff --git a/src/utilities.c b/src/utilities.c index 7717aea..ad65027 100644 --- a/src/utilities.c +++ b/src/utilities.c @@ -532,3 +532,61 @@ char* get_file_content_with_size(char* path, size_t* size) { *size = got; return buf; } + +// Create directory recursively +static int mkdir_recursive(const char *path, mode_t mode) { + char *path_copy = strdup(path); + if (!path_copy) return -1; + + char *p = path_copy; + + if (*p == '/') p++; + + while (*p) { + while (*p && *p != '/') p++; + + char saved = *p; + *p = '\0'; + + if (mkdir(path_copy, mode) == -1 && errno != EEXIST) { + free(path_copy); + return -1; + } + + *p = saved; + if (*p) p++; + } + + free(path_copy); + return 0; +} + +// Create default config file +int create_default_config_file(char* config_path) { + char *dir_path = strdup(config_path); + if (!dir_path) return -1; + + char *last_slash = strrchr(dir_path, '/'); + if (last_slash) { + *last_slash = '\0'; + if (mkdir_recursive(dir_path, 0755) < 0) { + perror("mkdir_recursive"); + free(dir_path); + return -1; + } + } + free(dir_path); + + FILE *fp = fopen(config_path, "w"); + if (!fp) { + perror("fopen"); + return -1; + } + + fprintf(fp, "[user]\n"); + fprintf(fp, "name = \"Your Name\"\n"); + fprintf(fp, "email = \"your.email@example.com\"\n"); + + fclose(fp); + return 0; +}