diff options
author | Joseph Hunkeler <jhunkeler@users.noreply.github.com> | 2024-11-06 08:55:52 -0500 |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-11-06 08:55:52 -0500 |
commit | 52e6d0f495023c0aa939bf6b2170ca5ea853202b (patch) | |
tree | 897a87316c280b6824892368662afcb848de1cf6 | |
parent | 6db1b15b5c62d6fb52825c1d833ac8dfa9a49fbb (diff) | |
parent | 46ae10e55603b8852612ebe12c7636c2b358bdd6 (diff) | |
download | stasis-52e6d0f495023c0aa939bf6b2170ca5ea853202b.tar.gz |
Merge pull request #67 from jhunkeler/safety-and-convenience
Safety and convenience
41 files changed, 343 insertions, 335 deletions
diff --git a/include/core.h b/include/core.h index b0a1a11..b8b047f 100644 --- a/include/core.h +++ b/include/core.h @@ -12,7 +12,7 @@ #include <sys/statvfs.h> #define SYSERROR(MSG, ...) do { \ - fprintf(stderr, "%s:%s:%d:%s - ", path_basename(__FILE__), __FUNCTION__, __LINE__, strerror(errno) ? "info" : strerror(errno)); \ + fprintf(stderr, "%s:%s:%d:%s - ", path_basename(__FILE__), __FUNCTION__, __LINE__, (errno > 0) ? strerror(errno) : "info"); \ fprintf(stderr, MSG LINE_SEP, __VA_ARGS__); \ } while (0) #define STASIS_BUFSIZ 8192 diff --git a/include/delivery.h b/include/delivery.h index 345cd13..2ab25d1 100644 --- a/include/delivery.h +++ b/include/delivery.h @@ -277,6 +277,8 @@ char *delivery_get_release_header(struct Delivery *ctx); * Finalizes a delivery artifact for distribution * @param ctx poitner to Delivery context * @param filename path to delivery artifact (Conda YAML file) + * @param stage DELIVERY_REWRITE_SPEC_STAGE_1 - Replacements for build + * @param stage DELIVERY_REWRITE_SPEC_STAGE_2 - Replacements for export */ void delivery_rewrite_spec(struct Delivery *ctx, char *filename, unsigned stage); @@ -298,6 +300,7 @@ int delivery_copy_conda_artifacts(struct Delivery *ctx); /** * Retrieve Conda installer + * @param ctx pointer to Delivery context * @param installer_url URL to installation script */ int delivery_get_conda_installer(struct Delivery *ctx, char *installer_url); diff --git a/src/cli/stasis/stasis_main.c b/src/cli/stasis/stasis_main.c index 0c02796..e188b2e 100644 --- a/src/cli/stasis/stasis_main.c +++ b/src/cli/stasis/stasis_main.c @@ -133,6 +133,8 @@ int main(int argc, char *argv[]) { printf(BANNER, VERSION, AUTHOR); + check_system_path(); + msg(STASIS_MSG_L1, "Setup\n"); tpl_setup_vars(&ctx); @@ -241,7 +243,6 @@ int main(int argc, char *argv[]) { msg(STASIS_MSG_L2, "Installing: %s\n", ctx.conda.installer_name); delivery_install_conda(ctx.conda.installer_path, ctx.storage.conda_install_prefix); - check_pathvar(&ctx); msg(STASIS_MSG_L2, "Configuring: %s\n", ctx.storage.conda_install_prefix); delivery_conda_enable(&ctx, ctx.storage.conda_install_prefix); @@ -395,7 +396,7 @@ int main(int argc, char *argv[]) { } if (strlist_count(ctx.conda.pip_packages_defer)) { - if (!(ctx.conda.wheels_packages = delivery_build_wheels(&ctx))) { + if (!((ctx.conda.wheels_packages = delivery_build_wheels(&ctx)))) { exit(1); } if (delivery_index_wheel_artifacts(&ctx)) { diff --git a/src/cli/stasis/system_requirements.c b/src/cli/stasis/system_requirements.c index 53ebbf7..d8d7df3 100644 --- a/src/cli/stasis/system_requirements.c +++ b/src/cli/stasis/system_requirements.c @@ -67,16 +67,11 @@ void check_requirements(struct Delivery *ctx) { check_system_env_requirements(); } -void check_pathvar(struct Delivery *ctx) { +void check_system_path() { char *pathvar = NULL; pathvar = getenv("PATH"); if (!pathvar) { msg(STASIS_MSG_ERROR | STASIS_MSG_L2, "PATH variable is not set. Cannot continue.\n"); exit(1); - } else { - char pathvar_tmp[STASIS_BUFSIZ]; - sprintf(pathvar_tmp, "%s/bin:%s", ctx->storage.conda_install_prefix, pathvar); - setenv("PATH", pathvar_tmp, 1); - pathvar = NULL; } }
\ No newline at end of file diff --git a/src/cli/stasis/system_requirements.h b/src/cli/stasis/system_requirements.h index 3a6fa25..ddc2705 100644 --- a/src/cli/stasis/system_requirements.h +++ b/src/cli/stasis/system_requirements.h @@ -5,9 +5,9 @@ #include "callbacks.h" #include "envctl.h" +void check_system_path(); void check_system_env_requirements(); void check_system_requirements(struct Delivery *ctx); void check_requirements(struct Delivery *ctx); -void check_pathvar(struct Delivery *ctx); #endif //STASIS_SYSTEM_REQUIREMENTS_H diff --git a/src/cli/stasis_indexer/stasis_indexer.c b/src/cli/stasis_indexer/stasis_indexer.c index bd59920..fddf18c 100644 --- a/src/cli/stasis_indexer/stasis_indexer.c +++ b/src/cli/stasis_indexer/stasis_indexer.c @@ -23,15 +23,15 @@ const char *long_options_help[] = { static void usage(char *name) { int maxopts = sizeof(long_options) / sizeof(long_options[0]); - unsigned char *opts = calloc(maxopts + 1, sizeof(char)); + char *opts = calloc(maxopts + 1, sizeof(char)); for (int i = 0; i < maxopts; i++) { - opts[i] = long_options[i].val; + opts[i] = (char) long_options[i].val; } printf("usage: %s [-%s] {{STASIS_ROOT}...}\n", name, opts); guard_free(opts); for (int i = 0; i < maxopts - 1; i++) { - char line[255]; + char line[255] = {0}; sprintf(line, " --%s -%c %-20s", long_options[i].name, long_options[i].val, long_options_help[i]); puts(line); } @@ -93,9 +93,8 @@ int indexer_wheels(struct Delivery *ctx) { int indexer_load_metadata(struct Delivery *ctx, const char *filename) { char line[STASIS_NAME_MAX] = {0}; - FILE *fp; - fp = fopen(filename, "r"); + FILE *fp = fopen(filename, "r"); if (!fp) { return -1; } @@ -179,9 +178,8 @@ int indexer_get_files(struct StrList **out, const char *path, const char *patter char *item = strlist_item(list, i); if (fnmatch(userpattern, item, 0)) { no_match++; - continue; } else { - strlist_append(&(*out), item); + strlist_append((out), item); } } if (no_match >= strlist_count(list)) { @@ -254,7 +252,7 @@ int get_pandoc_version(size_t *result) { } size_t parts_total; - for (parts_total = 0; parts[parts_total] != NULL; parts_total++); + for (parts_total = 0; parts[parts_total] != NULL; parts_total++) {} // generate the version as an integer // note: pandoc version scheme never exceeds four elements (or bytes in this case) @@ -276,7 +274,6 @@ int get_pandoc_version(size_t *result) { } int indexer_make_website(struct Delivery *ctx) { - char cmd[PATH_MAX]; const char *pattern = "*.md"; if (!find_program("pandoc")) { @@ -334,6 +331,7 @@ int indexer_make_website(struct Delivery *ctx) { } char *root = strlist_item(dirs, i); for (size_t x = 0; x < strlist_count(inputs); x++) { + char cmd[PATH_MAX] = {0}; char *filename = strlist_item(inputs, x); char fullpath_src[PATH_MAX] = {0}; char fullpath_dest[PATH_MAX] = {0}; @@ -524,8 +522,7 @@ int indexer_readmes(struct Delivery ctx[], size_t nelem) { sprintf(indexfile, "%s/README.md", ctx->storage.delivery_dir); if (!pushd(ctx->storage.delivery_dir)) { - FILE *indexfp; - indexfp = fopen(indexfile, "w+"); + FILE *indexfp = fopen(indexfile, "w+"); if (!indexfp) { fprintf(stderr, "Unable to open %s for writing\n", indexfile); return -1; @@ -604,8 +601,7 @@ int indexer_junitxml_report(struct Delivery ctx[], size_t nelem) { } if (!pushd(ctx->storage.results_dir)) { - FILE *indexfp; - indexfp = fopen(indexfile, "w+"); + FILE *indexfp = fopen(indexfile, "w+"); if (!indexfp) { fprintf(stderr, "Unable to open %s for writing\n", indexfile); return -1; @@ -814,7 +810,6 @@ int main(int argc, char *argv[]) { exit(1); } - char *workdir; char workdir_template[PATH_MAX] = {0}; char *system_tmp = getenv("TMPDIR"); if (system_tmp) { @@ -823,7 +818,7 @@ int main(int argc, char *argv[]) { strcat(workdir_template, "/tmp"); } strcat(workdir_template, "/stasis-combine.XXXXXX"); - workdir = mkdtemp(workdir_template); + char *workdir = mkdtemp(workdir_template); if (!workdir) { SYSERROR("Unable to create temporary directory: %s", workdir_template); exit(1); @@ -832,8 +827,7 @@ int main(int argc, char *argv[]) { exit(1); } - struct Delivery ctx; - memset(&ctx, 0, sizeof(ctx)); + struct Delivery ctx = {0}; printf(BANNER, VERSION, AUTHOR); @@ -919,8 +913,7 @@ int main(int argc, char *argv[]) { } msg(STASIS_MSG_L1, "Copying indexed delivery to '%s'\n", destdir); - char cmd[PATH_MAX]; - memset(cmd, 0, sizeof(cmd)); + char cmd[PATH_MAX] = {0}; sprintf(cmd, "rsync -ah%s --delete --exclude 'tmp/' --exclude 'tools/' '%s/' '%s/'", globals.verbose ? "v" : "q", workdir, destdir); guard_free(destdir); diff --git a/src/lib/core/artifactory.c b/src/lib/core/artifactory.c index 6b9635d..0cd3b18 100644 --- a/src/lib/core/artifactory.c +++ b/src/lib/core/artifactory.c @@ -1,7 +1,5 @@ #include "artifactory.h" -extern struct STASIS_GLOBAL globals; - int artifactory_download_cli(char *dest, char *jfrog_artifactory_base_url, char *jfrog_artifactory_product, @@ -73,8 +71,7 @@ int artifactory_download_cli(char *dest, } void jfrt_register_opt_str(char *jfrt_val, const char *opt_name, struct StrList **opt_map) { - char data[STASIS_BUFSIZ]; - memset(data, 0, sizeof(data)); + char data[STASIS_BUFSIZ] = {0}; if (jfrt_val == NULL) { // no data @@ -85,8 +82,7 @@ void jfrt_register_opt_str(char *jfrt_val, const char *opt_name, struct StrList } void jfrt_register_opt_bool(bool jfrt_val, const char *opt_name, struct StrList **opt_map) { - char data[STASIS_BUFSIZ]; - memset(data, 0, sizeof(data)); + char data[STASIS_BUFSIZ] = {0}; if (jfrt_val == false) { // option will not be used @@ -97,8 +93,7 @@ void jfrt_register_opt_bool(bool jfrt_val, const char *opt_name, struct StrList } void jfrt_register_opt_int(int jfrt_val, const char *opt_name, struct StrList **opt_map) { - char data[STASIS_BUFSIZ]; - memset(data, 0, sizeof(data)); + char data[STASIS_BUFSIZ] = {0}; if (jfrt_val == 0) { // option will not be used @@ -109,8 +104,7 @@ void jfrt_register_opt_int(int jfrt_val, const char *opt_name, struct StrList ** } void jfrt_register_opt_long(long jfrt_val, const char *opt_name, struct StrList **opt_map) { - char data[STASIS_BUFSIZ]; - memset(data, 0, sizeof(data)); + char data[STASIS_BUFSIZ] = {0}; if (jfrt_val == 0) { // option will not be used @@ -197,7 +191,6 @@ int jfrog_cli(struct JFRT_Auth *auth, const char *subsystem, const char *task, c struct Process proc; char cmd[STASIS_BUFSIZ]; char cmd_redacted[STASIS_BUFSIZ]; - int status; memset(&proc, 0, sizeof(proc)); memset(cmd, 0, sizeof(cmd)); @@ -251,8 +244,7 @@ int jfrog_cli(struct JFRT_Auth *auth, const char *subsystem, const char *task, c strcpy(proc.f_stdout, "/dev/null"); strcpy(proc.f_stderr, "/dev/null"); } - status = shell(&proc, cmd); - return status; + return shell(&proc, cmd); } static int jfrog_cli_rt(struct JFRT_Auth *auth, char *task, char *args) { @@ -260,15 +252,13 @@ static int jfrog_cli_rt(struct JFRT_Auth *auth, char *task, char *args) { } int jfrog_cli_rt_build_collect_env(struct JFRT_Auth *auth, char *build_name, char *build_number) { - char cmd[STASIS_BUFSIZ]; - memset(cmd, 0, sizeof(cmd)); + char cmd[STASIS_BUFSIZ] = {0}; snprintf(cmd, sizeof(cmd) - 1, "\"%s\" \"%s\"", build_name, build_number); return jfrog_cli(auth, "rt", "build-collect-env", cmd); } int jfrog_cli_rt_build_publish(struct JFRT_Auth *auth, char *build_name, char *build_number) { - char cmd[STASIS_BUFSIZ]; - memset(cmd, 0, sizeof(cmd)); + char cmd[STASIS_BUFSIZ] = {0}; snprintf(cmd, sizeof(cmd) - 1, "\"%s\" \"%s\"", build_name, build_number); return jfrog_cli(auth, "rt", "build-publish", cmd); } @@ -278,8 +268,7 @@ int jfrog_cli_rt_ping(struct JFRT_Auth *auth) { } int jfrog_cli_rt_download(struct JFRT_Auth *auth, struct JFRT_Download *ctx, char *repo_path, char *dest) { - char cmd[STASIS_BUFSIZ]; - memset(cmd, 0, sizeof(cmd)); + char cmd[STASIS_BUFSIZ] = {0}; if (isempty(repo_path)) { fprintf(stderr, "repo_path argument must be a valid artifactory repository path\n"); @@ -345,8 +334,7 @@ int jfrog_cli_rt_download(struct JFRT_Auth *auth, struct JFRT_Download *ctx, cha } int jfrog_cli_rt_upload(struct JFRT_Auth *auth, struct JFRT_Upload *ctx, char *src, char *repo_path) { - char cmd[STASIS_BUFSIZ]; - memset(cmd, 0, sizeof(cmd)); + char cmd[STASIS_BUFSIZ] = {0}; if (isempty(src)) { fprintf(stderr, "src argument must be a valid file system path\n"); @@ -444,8 +432,7 @@ int jfrog_cli_rt_upload(struct JFRT_Auth *auth, struct JFRT_Upload *ctx, char *s } int jfrog_cli_rt_search(struct JFRT_Auth *auth, struct JFRT_Search *ctx, char *repo_path, char *pattern) { - char cmd[STASIS_BUFSIZ]; - memset(cmd, 0, sizeof(cmd)); + char cmd[STASIS_BUFSIZ] = {0}; if (isempty(repo_path)) { fprintf(stderr, "repo_path argument must be a valid artifactory repository path\n"); diff --git a/src/lib/core/conda.c b/src/lib/core/conda.c index 5954f20..435af35 100644 --- a/src/lib/core/conda.c +++ b/src/lib/core/conda.c @@ -40,8 +40,7 @@ int micromamba(struct MicromambaInfo *info, char *command, ...) { } } - char cmd[STASIS_BUFSIZ]; - memset(cmd, 0, sizeof(cmd)); + char cmd[STASIS_BUFSIZ] = {0}; sprintf(cmd, "%s -r %s -p %s ", mmbin, info->conda_prefix, info->conda_prefix); va_list args; va_start(args, command); @@ -63,16 +62,14 @@ int micromamba(struct MicromambaInfo *info, char *command, ...) { } int python_exec(const char *args) { - char command[PATH_MAX]; - memset(command, 0, sizeof(command)); + char command[PATH_MAX] = {0}; snprintf(command, sizeof(command) - 1, "python %s", args); msg(STASIS_MSG_L3, "Executing: %s\n", command); return system(command); } int pip_exec(const char *args) { - char command[PATH_MAX]; - memset(command, 0, sizeof(command)); + char command[PATH_MAX] = {0}; snprintf(command, sizeof(command) - 1, "python -m pip %s", args); msg(STASIS_MSG_L3, "Executing: %s\n", command); return system(command); @@ -116,8 +113,7 @@ int pkg_index_provides(int mode, const char *index, const char *spec) { } int status = 0; - struct Process proc; - memset(&proc, 0, sizeof(proc)); + struct Process proc = {0}; proc.redirect_stderr = 1; strcpy(proc.f_stdout, logfile); @@ -196,8 +192,7 @@ int conda_exec(const char *args) { "deactivate", NULL }; - char conda_as[6]; - memset(conda_as, 0, sizeof(conda_as)); + char conda_as[6] = {0}; strcpy(conda_as, "conda"); for (size_t i = 0; mamba_commands[i] != NULL; i++) { @@ -212,6 +207,24 @@ int conda_exec(const char *args) { return system(command); } +static int conda_prepend_bin(const char *root) { + const char *system_path_old = getenv("PATH"); + char conda_bin[PATH_MAX] = {0}; + + snprintf(conda_bin, sizeof(conda_bin) - 1, "%s/bin:%s/condabin", root, root); + + if (!strstr(system_path_old, conda_bin)) { + // conda_bin is not present in PATH. Add it to the head. + char system_path_new[STASIS_BUFSIZ]; + sprintf(system_path_new, "%s:%s", conda_bin, system_path_old); + if (setenv("PATH", system_path_new, 1) < 0) { + SYSERROR("Unable to prepend to PATH: %s", conda_bin); + return -1; + } + } + return 0; +} + int conda_activate(const char *root, const char *env_name) { FILE *fp = NULL; const char *init_script_conda = "/etc/profile.d/conda.sh"; @@ -219,8 +232,7 @@ int conda_activate(const char *root, const char *env_name) { char path_conda[PATH_MAX] = {0}; char path_mamba[PATH_MAX] = {0}; char logfile[PATH_MAX] = {0}; - struct Process proc; - memset(&proc, 0, sizeof(proc)); + struct Process proc = {0}; // Where to find conda's init scripts sprintf(path_conda, "%s%s", root, init_script_conda); @@ -254,9 +266,24 @@ int conda_activate(const char *root, const char *env_name) { return -1; } + if (conda_prepend_bin(root)) { + remove(logfile); + return -1; + } + // Fully activate conda and record its effect on the runtime environment char command[PATH_MAX * 3]; - snprintf(command, sizeof(command) - 1, "set -a; source %s; source %s; conda activate %s &>/dev/null; env -0", path_conda, path_mamba, env_name); + const char *conda_shlvl = getenv("CONDA_SHLVL"); + if (conda_shlvl == NULL || strcmp(conda_shlvl, "0") == 0) { + // First-run initialization + snprintf(command, sizeof(command) - 1, "source %s; source %s; conda activate %s &>/dev/null; env -0", path_conda, path_mamba, env_name); + } else { + // Conda is already available and configured. + // Make calls directly to conda using conda's base interpreter. + // The shell functions generated by sourcing path_conda and path_mamba are extremely inconsistent + // in this environment. DO NOT USE THEM. + snprintf(command, sizeof(command) - 1, "$CONDA_PYTHON_EXE $CONDA_EXE activate %s &>/dev/null; env -0", env_name); + } int retval = shell(&proc, command); if (retval) { // it didn't work; drop out for cleanup diff --git a/src/lib/core/copy.c b/src/lib/core/copy.c index f69a756..928bc40 100644 --- a/src/lib/core/copy.c +++ b/src/lib/core/copy.c @@ -1,11 +1,7 @@ #include "copy.h" int copy2(const char *src, const char *dest, unsigned int op) { - size_t bytes_read; - size_t bytes_written; - char buf[STASIS_BUFSIZ]; struct stat src_stat, dnamest; - FILE *fp1, *fp2; if (lstat(src, &src_stat) < 0) { perror(src); @@ -18,9 +14,8 @@ int copy2(const char *src, const char *dest, unsigned int op) { char dname[1024] = {0}; strcpy(dname, dest); - char *dname_endptr; - dname_endptr = strrchr(dname, '/'); + char *dname_endptr = strrchr(dname, '/'); if (dname_endptr != NULL) { *dname_endptr = '\0'; } @@ -47,19 +42,21 @@ int copy2(const char *src, const char *dest, unsigned int op) { return -1; } } else if (S_ISREG(src_stat.st_mode)) { - fp1 = fopen(src, "rb"); + char buf[STASIS_BUFSIZ] = {0}; + size_t bytes_read; + FILE *fp1 = fopen(src, "rb"); if (!fp1) { perror(src); return -1; } - fp2 = fopen(dest, "w+b"); + FILE *fp2 = fopen(dest, "w+b"); if (!fp2) { perror(dest); return -1; } - bytes_written = 0; + size_t bytes_written = 0; while ((bytes_read = fread(buf, sizeof(char), sizeof(buf), fp1)) != 0) { bytes_written += fwrite(buf, sizeof(char), bytes_read, fp2); } diff --git a/src/lib/core/delivery.c b/src/lib/core/delivery.c index ada708d..1ceb8b7 100644 --- a/src/lib/core/delivery.c +++ b/src/lib/core/delivery.c @@ -165,9 +165,6 @@ void delivery_defer_packages(struct Delivery *ctx, int type) { struct StrList *dataptr = NULL; struct StrList *deferred = NULL; char *name = NULL; - char cmd[PATH_MAX]; - - memset(cmd, 0, sizeof(cmd)); char mode[10]; if (DEFER_CONDA == type) { diff --git a/src/lib/core/delivery_artifactory.c b/src/lib/core/delivery_artifactory.c index 27f4823..b69615e 100644 --- a/src/lib/core/delivery_artifactory.c +++ b/src/lib/core/delivery_artifactory.c @@ -75,9 +75,6 @@ int delivery_artifact_upload(struct Delivery *ctx) { ctx->deploy.jfrog[i].upload_ctx.build_name = ctx->info.build_name; ctx->deploy.jfrog[i].upload_ctx.build_number = ctx->info.build_number; - char files[PATH_MAX]; - char dest[PATH_MAX]; // repo + remote dir - if (jfrog_cli_rt_ping(&ctx->deploy.jfrog_auth)) { msg(STASIS_MSG_ERROR | STASIS_MSG_L2, "Unable to contact artifactory server: %s\n", ctx->deploy.jfrog_auth.url); return -1; @@ -85,8 +82,8 @@ int delivery_artifact_upload(struct Delivery *ctx) { if (strlist_count(ctx->deploy.jfrog[i].files)) { for (size_t f = 0; f < strlist_count(ctx->deploy.jfrog[i].files); f++) { - memset(dest, 0, sizeof(dest)); - memset(files, 0, sizeof(files)); + char dest[PATH_MAX] = {0}; + char files[PATH_MAX] = {0}; snprintf(dest, sizeof(dest) - 1, "%s/%s", ctx->deploy.jfrog[i].repo, ctx->deploy.jfrog[i].dest); snprintf(files, sizeof(files) - 1, "%s", strlist_item(ctx->deploy.jfrog[i].files, f)); status += jfrog_cli_rt_upload(&ctx->deploy.jfrog_auth, &ctx->deploy.jfrog[i].upload_ctx, files, dest); @@ -118,7 +115,6 @@ int delivery_mission_render_files(struct Delivery *ctx) { char *dest; } data; struct INIFILE *cfg = ctx->_stasis_ini_fp.mission; - union INIVal val; memset(&data, 0, sizeof(data)); data.src = calloc(PATH_MAX, sizeof(*data.src)); @@ -128,6 +124,7 @@ int delivery_mission_render_files(struct Delivery *ctx) { } for (size_t i = 0; i < cfg->section_count; i++) { + union INIVal val; char *section_name = cfg->section[i]->key; if (!startswith(section_name, "template:")) { continue; @@ -143,7 +140,6 @@ int delivery_mission_render_files(struct Delivery *ctx) { int err = 0; data.dest = ini_getval_str(cfg, section_name, "destination", INI_READ_RENDER, &err); - char *contents; struct stat st; if (lstat(data.src, &st)) { perror(data.src); @@ -151,15 +147,14 @@ int delivery_mission_render_files(struct Delivery *ctx) { continue; } - contents = calloc(st.st_size + 1, sizeof(*contents)); + char *contents = calloc(st.st_size + 1, sizeof(*contents)); if (!contents) { perror("template file contents"); guard_free(data.dest); continue; } - FILE *fp; - fp = fopen(data.src, "rb"); + FILE *fp = fopen(data.src, "rb"); if (!fp) { perror(data.src); guard_free(contents); diff --git a/src/lib/core/delivery_build.c b/src/lib/core/delivery_build.c index 615fa76..fa19f95 100644 --- a/src/lib/core/delivery_build.c +++ b/src/lib/core/delivery_build.c @@ -4,8 +4,6 @@ int delivery_build_recipes(struct Delivery *ctx) { for (size_t i = 0; i < sizeof(ctx->tests) / sizeof(ctx->tests[0]); i++) { char *recipe_dir = NULL; if (ctx->tests[i].build_recipe) { // build a conda recipe - int recipe_type; - int status; if (recipe_clone(ctx->storage.build_recipes_dir, ctx->tests[i].build_recipe, NULL, &recipe_dir)) { fprintf(stderr, "Encountered an issue while cloning recipe for: %s\n", ctx->tests[i].name); return -1; @@ -14,7 +12,7 @@ int delivery_build_recipes(struct Delivery *ctx) { fprintf(stderr, "BUG: recipe_clone() succeeded but recipe_dir is NULL: %s\n", strerror(errno)); return -1; } - recipe_type = recipe_get_type(recipe_dir); + int recipe_type = recipe_get_type(recipe_dir); if(!pushd(recipe_dir)) { if (RECIPE_TYPE_ASTROCONDA == recipe_type) { pushd(path_basename(ctx->tests[i].repository)); @@ -77,7 +75,7 @@ int delivery_build_recipes(struct Delivery *ctx) { } else { sprintf(command, "mambabuild --python=%s .", ctx->meta.python); } - status = conda_exec(command); + int status = conda_exec(command); if (status) { guard_free(recipe_dir); return -1; @@ -131,8 +129,7 @@ int filter_repo_tags(char *repo, struct StrList *patterns) { struct StrList *delivery_build_wheels(struct Delivery *ctx) { struct StrList *result = NULL; - struct Process proc; - memset(&proc, 0, sizeof(proc)); + struct Process proc = {0}; result = strlist_init(); if (!result) { diff --git a/src/lib/core/delivery_conda.c b/src/lib/core/delivery_conda.c index 93a06fc..8974ae8 100644 --- a/src/lib/core/delivery_conda.c +++ b/src/lib/core/delivery_conda.c @@ -45,8 +45,7 @@ int delivery_get_conda_installer(struct Delivery *ctx, char *installer_url) { } void delivery_install_conda(char *install_script, char *conda_install_dir) { - struct Process proc; - memset(&proc, 0, sizeof(proc)); + struct Process proc = {0}; if (globals.conda_fresh_start) { if (!access(conda_install_dir, F_OK)) { diff --git a/src/lib/core/delivery_docker.c b/src/lib/core/delivery_docker.c index e1d7f60..c170082 100644 --- a/src/lib/core/delivery_docker.c +++ b/src/lib/core/delivery_docker.c @@ -11,7 +11,7 @@ int delivery_docker(struct Delivery *ctx) { size_t total_build_args = strlist_count(ctx->deploy.docker.build_args); if (!has_registry) { - msg(STASIS_MSG_WARN | STASIS_MSG_L2, "No docker registry defined. You will need to manually retag the resulting image.\n"); + msg(STASIS_MSG_WARN | STASIS_MSG_L2, "No docker registry defined. You will need to manually re-tag the resulting image.\n"); } if (!total_tags) { @@ -59,9 +59,9 @@ int delivery_docker(struct Delivery *ctx) { } // Build the image - char delivery_file[PATH_MAX]; - char dest[PATH_MAX]; - char rsync_cmd[PATH_MAX * 2]; + char delivery_file[PATH_MAX] = {0}; + char dest[PATH_MAX] = {0}; + char rsync_cmd[PATH_MAX * 2] = {0}; memset(delivery_file, 0, sizeof(delivery_file)); memset(dest, 0, sizeof(dest)); diff --git a/src/lib/core/delivery_init.c b/src/lib/core/delivery_init.c index 2333628..356a8ce 100644 --- a/src/lib/core/delivery_init.c +++ b/src/lib/core/delivery_init.c @@ -286,8 +286,7 @@ int delivery_init(struct Delivery *ctx, int render_mode) { } int bootstrap_build_info(struct Delivery *ctx) { - struct Delivery local; - memset(&local, 0, sizeof(local)); + struct Delivery local = {0}; local._stasis_ini_fp.cfg = ini_open(ctx->_stasis_ini_fp.cfg_path); local._stasis_ini_fp.delivery = ini_open(ctx->_stasis_ini_fp.delivery_path); delivery_init_platform(&local); diff --git a/src/lib/core/delivery_install.c b/src/lib/core/delivery_install.c index 098e6f4..a348346 100644 --- a/src/lib/core/delivery_install.c +++ b/src/lib/core/delivery_install.c @@ -23,7 +23,7 @@ static struct Test *requirement_from_test(struct Delivery *ctx, const char *name return result; } -static char *have_spec_in_config(struct Delivery *ctx, const char *name) { +static char *have_spec_in_config(const struct Delivery *ctx, const char *name) { for (size_t x = 0; x < strlist_count(ctx->conda.pip_packages); x++) { char *config_spec = strlist_item(ctx->conda.pip_packages, x); char *op = find_version_spec(config_spec); @@ -125,7 +125,7 @@ int delivery_overlay_packages_from_env(struct Delivery *ctx, const char *env_nam int delivery_install_packages(struct Delivery *ctx, char *conda_install_dir, char *env_name, int type, struct StrList **manifest) { char cmd[PATH_MAX]; char pkgs[STASIS_BUFSIZ]; - char *env_current = getenv("CONDA_DEFAULT_ENV"); + const char *env_current = getenv("CONDA_DEFAULT_ENV"); if (env_current) { // The requested environment is not the current environment diff --git a/src/lib/core/delivery_populate.c b/src/lib/core/delivery_populate.c index b37f677..c699545 100644 --- a/src/lib/core/delivery_populate.c +++ b/src/lib/core/delivery_populate.c @@ -75,15 +75,13 @@ int populate_delivery_cfg(struct Delivery *ctx, int render_mode) { } int populate_delivery_ini(struct Delivery *ctx, int render_mode) { - union INIVal val; struct INIFILE *ini = ctx->_stasis_ini_fp.delivery; struct INIData *rtdata; - RuntimeEnv *rt; validate_delivery_ini(ini); // Populate runtime variables first they may be interpreted by other // keys in the configuration - rt = runtime_copy(__environ); + RuntimeEnv *rt = runtime_copy(__environ); while ((rtdata = ini_getall(ini, "runtime")) != NULL) { char rec[STASIS_BUFSIZ]; sprintf(rec, "%s=%s", lstrip(strip(rtdata->key)), lstrip(strip(rtdata->value))); @@ -191,6 +189,7 @@ int populate_delivery_ini(struct Delivery *ctx, int render_mode) { for (size_t z = 0, i = 0; i < ini->section_count; i++) { char *section_name = ini->section[i]->key; if (startswith(section_name, "test:")) { + union INIVal val; struct Test *test = &ctx->tests[z]; val.as_char_p = strchr(ini->section[i]->key, ':') + 1; if (val.as_char_p && isempty(val.as_char_p)) { @@ -257,7 +256,6 @@ int populate_delivery_ini(struct Delivery *ctx, int render_mode) { int populate_mission_ini(struct Delivery **ctx, int render_mode) { int err = 0; - struct INIFILE *ini; if ((*ctx)->_stasis_ini_fp.mission) { return 0; @@ -275,7 +273,7 @@ int populate_mission_ini(struct Delivery **ctx, int render_mode) { msg(STASIS_MSG_L2, "Reading mission configuration: %s\n", missionfile); (*ctx)->_stasis_ini_fp.mission = ini_open(missionfile); - ini = (*ctx)->_stasis_ini_fp.mission; + struct INIFILE *ini = (*ctx)->_stasis_ini_fp.mission; if (!ini) { msg(STASIS_MSG_ERROR | STASIS_MSG_L2, "Failed to read mission configuration: %s, %s\n", missionfile, strerror(errno)); exit(1); diff --git a/src/lib/core/delivery_postprocess.c b/src/lib/core/delivery_postprocess.c index 1a902e3..40ac43f 100644 --- a/src/lib/core/delivery_postprocess.c +++ b/src/lib/core/delivery_postprocess.c @@ -21,10 +21,9 @@ char *delivery_get_release_header(struct Delivery *ctx) { } int delivery_dump_metadata(struct Delivery *ctx) { - FILE *fp; char filename[PATH_MAX]; sprintf(filename, "%s/meta-%s.stasis", ctx->storage.meta_dir, ctx->info.release_name); - fp = fopen(filename, "w+"); + FILE *fp = fopen(filename, "w+"); if (!fp) { return -1; } @@ -62,7 +61,6 @@ int delivery_dump_metadata(struct Delivery *ctx) { } void delivery_rewrite_spec(struct Delivery *ctx, char *filename, unsigned stage) { - char output[PATH_MAX]; char *header = NULL; char *tempfile = NULL; FILE *tp = NULL; @@ -129,6 +127,7 @@ void delivery_rewrite_spec(struct Delivery *ctx, char *filename, unsigned stage) remove(tempfile); guard_free(tempfile); } else if (globals.enable_rewrite_spec_stage_2 && stage == DELIVERY_REWRITE_SPEC_STAGE_2) { + char output[PATH_MAX] = {0}; // Replace "local" channel with the staging URL if (ctx->storage.conda_staging_url) { file_replace_text(filename, "@CONDA_CHANNEL@", ctx->storage.conda_staging_url, 0); @@ -183,8 +182,7 @@ int delivery_index_conda_artifacts(struct Delivery *ctx) { } int delivery_copy_wheel_artifacts(struct Delivery *ctx) { - char cmd[PATH_MAX]; - memset(cmd, 0, sizeof(cmd)); + char cmd[PATH_MAX] = {0}; snprintf(cmd, sizeof(cmd) - 1, "rsync -avi --progress %s/*/dist/*.whl %s", ctx->storage.build_sources_dir, ctx->storage.wheel_artifact_dir); @@ -193,20 +191,17 @@ int delivery_copy_wheel_artifacts(struct Delivery *ctx) { int delivery_index_wheel_artifacts(struct Delivery *ctx) { struct dirent *rec; - DIR *dp; - FILE *top_fp; - dp = opendir(ctx->storage.wheel_artifact_dir); + DIR *dp = opendir(ctx->storage.wheel_artifact_dir); if (!dp) { return -1; } // Generate a "dumb" local pypi index that is compatible with: // pip install --extra-index-url - char top_index[PATH_MAX]; - memset(top_index, 0, sizeof(top_index)); + char top_index[PATH_MAX] = {0}; sprintf(top_index, "%s/index.html", ctx->storage.wheel_artifact_dir); - top_fp = fopen(top_index, "w+"); + FILE *top_fp = fopen(top_index, "w+"); if (!top_fp) { closedir(dp); return -2; @@ -218,11 +213,9 @@ int delivery_index_wheel_artifacts(struct Delivery *ctx) { continue; } - FILE *bottom_fp; - char bottom_index[PATH_MAX * 2]; - memset(bottom_index, 0, sizeof(bottom_index)); + char bottom_index[PATH_MAX * 2] = {0}; sprintf(bottom_index, "%s/%s/index.html", ctx->storage.wheel_artifact_dir, rec->d_name); - bottom_fp = fopen(bottom_index, "w+"); + FILE *bottom_fp = fopen(bottom_index, "w+"); if (!bottom_fp) { closedir(dp); return -3; @@ -234,8 +227,7 @@ int delivery_index_wheel_artifacts(struct Delivery *ctx) { // Add record to top level index fprintf(top_fp, "<a href=\"%s/\">%s</a><br/>\n", rec->d_name, rec->d_name); - char dpath[PATH_MAX * 2]; - memset(dpath, 0, sizeof(dpath)); + char dpath[PATH_MAX * 2] = {0}; sprintf(dpath, "%s/%s", ctx->storage.wheel_artifact_dir, rec->d_name); struct StrList *packages = listdir(dpath); if (!packages) { diff --git a/src/lib/core/delivery_test.c b/src/lib/core/delivery_test.c index cb78f64..0bcf04d 100644 --- a/src/lib/core/delivery_test.c +++ b/src/lib/core/delivery_test.c @@ -5,8 +5,7 @@ void delivery_tests_run(struct Delivery *ctx) { static const int PARALLEL = 1; static const int SERIAL = 2; struct MultiProcessingPool *pool[3]; - struct Process proc; - memset(&proc, 0, sizeof(proc)); + struct Process proc = {0}; if (!globals.workaround.conda_reactivate) { globals.workaround.conda_reactivate = calloc(PATH_MAX, sizeof(*globals.workaround.conda_reactivate)); @@ -227,7 +226,6 @@ void delivery_tests_run(struct Delivery *ctx) { // Execute all queued tasks for (size_t p = 0; p < sizeof(pool) / sizeof(*pool); p++) { - int pool_status; long jobs = globals.cpu_limit; if (!pool[p]->num_used) { @@ -244,7 +242,7 @@ void delivery_tests_run(struct Delivery *ctx) { // 1. Setup (builds) // 2. Parallel (fast jobs) // 3. Serial (long jobs) - pool_status = mp_pool_join(pool[p], jobs, opt_flags); + int pool_status = mp_pool_join(pool[p], jobs, opt_flags); // On error show a summary of the current pool, and die if (pool_status != 0) { @@ -266,17 +264,15 @@ void delivery_tests_run(struct Delivery *ctx) { int delivery_fixup_test_results(struct Delivery *ctx) { struct dirent *rec; - DIR *dp; - dp = opendir(ctx->storage.results_dir); + DIR *dp = opendir(ctx->storage.results_dir); if (!dp) { perror(ctx->storage.results_dir); return -1; } while ((rec = readdir(dp)) != NULL) { - char path[PATH_MAX]; - memset(path, 0, sizeof(path)); + char path[PATH_MAX] = {0}; if (!strcmp(rec->d_name, ".") || !strcmp(rec->d_name, "..") || !endswith(rec->d_name, ".xml")) { continue; diff --git a/src/lib/core/docker.c b/src/lib/core/docker.c index 5834ef9..4dd5163 100644 --- a/src/lib/core/docker.c +++ b/src/lib/core/docker.c @@ -21,28 +21,24 @@ int docker_exec(const char *args, unsigned flags) { int docker_script(const char *image, char *data, unsigned flags) { (void)flags; // TODO: placeholder - FILE *infile; - FILE *outfile; - char cmd[PATH_MAX]; - char buffer[STASIS_BUFSIZ]; + char cmd[PATH_MAX] = {0}; - memset(cmd, 0, sizeof(cmd)); snprintf(cmd, sizeof(cmd) - 1, "docker run --rm -i %s /bin/sh -", image); - outfile = popen(cmd, "w"); + FILE *outfile = popen(cmd, "w"); if (!outfile) { // opening command pipe for writing failed return -1; } - infile = fmemopen(data, strlen(data), "r"); + FILE *infile = fmemopen(data, strlen(data), "r"); if (!infile) { // opening memory file for reading failed return -1; } do { - memset(buffer, 0, sizeof(buffer)); + char buffer[STASIS_BUFSIZ] = {0}; if (fgets(buffer, sizeof(buffer) - 1, infile) != NULL) { fputs(buffer, outfile); } @@ -54,9 +50,8 @@ int docker_script(const char *image, char *data, unsigned flags) { int docker_build(const char *dirpath, const char *args, int engine) { char cmd[PATH_MAX]; - char build[15]; + char build[15] = {0}; - memset(build, 0, sizeof(build)); memset(cmd, 0, sizeof(cmd)); if (engine & STASIS_DOCKER_BUILD) { @@ -70,13 +65,10 @@ int docker_build(const char *dirpath, const char *args, int engine) { } int docker_save(const char *image, const char *destdir, const char *compression_program) { - char cmd[PATH_MAX]; - - memset(cmd, 0, sizeof(cmd)); + char cmd[PATH_MAX] = {0}; if (compression_program && strlen(compression_program)) { - char ext[255]; - memset(ext, 0, sizeof(ext)); + char ext[255] = {0}; if (startswith(compression_program, "zstd")) { strcpy(ext, "zst"); } else if (startswith(compression_program, "xz")) { diff --git a/src/lib/core/download.c b/src/lib/core/download.c index bfb323e..f07a850 100644 --- a/src/lib/core/download.c +++ b/src/lib/core/download.c @@ -11,20 +11,17 @@ size_t download_writer(void *fp, size_t size, size_t nmemb, void *stream) { long download(char *url, const char *filename, char **errmsg) { extern char *VERSION; - CURL *c; - CURLcode curl_code; long http_code = -1; - FILE *fp; char user_agent[20]; sprintf(user_agent, "stasis/%s", VERSION); long timeout = 30L; char *timeout_str = getenv("STASIS_DOWNLOAD_TIMEOUT"); curl_global_init(CURL_GLOBAL_ALL); - c = curl_easy_init(); + CURL *c = curl_easy_init(); curl_easy_setopt(c, CURLOPT_URL, url); curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, download_writer); - fp = fopen(filename, "wb"); + FILE *fp = fopen(filename, "wb"); if (!fp) { return -1; } @@ -40,7 +37,7 @@ long download(char *url, const char *filename, char **errmsg) { } curl_easy_setopt(c, CURLOPT_CONNECTTIMEOUT, timeout); - curl_code = curl_easy_perform(c); + CURLcode curl_code = curl_easy_perform(c); if (curl_code != CURLE_OK) { if (errmsg) { strcpy(*errmsg, curl_easy_strerror(curl_code)); diff --git a/src/lib/core/envctl.c b/src/lib/core/envctl.c index 9037d9d..0be3f89 100644 --- a/src/lib/core/envctl.c +++ b/src/lib/core/envctl.c @@ -1,9 +1,7 @@ #include "envctl.h" struct EnvCtl *envctl_init() { - struct EnvCtl *result; - - result = calloc(1, sizeof(*result)); + struct EnvCtl *result = calloc(1, sizeof(*result)); if (!result) { return NULL; } @@ -102,13 +100,13 @@ void envctl_do_required(const struct EnvCtl *envctl, int verbose) { int code = callback((const void *) item, (const void *) name); if (code == STASIS_ENVCTL_RET_IGNORE || code == STASIS_ENVCTL_RET_SUCCESS) { continue; - } else if (code == STASIS_ENVCTL_RET_FAIL) { + } + if (code == STASIS_ENVCTL_RET_FAIL) { fprintf(stderr, "\n%s must be set. Exiting.\n", name); exit(1); - } else { - fprintf(stderr, "\nan unknown envctl callback code occurred: %d\n", code); - exit(1); } + fprintf(stderr, "\nan unknown envctl callback code occurred: %d\n", code); + exit(1); } } diff --git a/src/lib/core/environment.c b/src/lib/core/environment.c index 580062c..cc72b8d 100644 --- a/src/lib/core/environment.c +++ b/src/lib/core/environment.c @@ -70,7 +70,6 @@ void runtime_export(RuntimeEnv *env, char **keys) { NULL, }; - char output[STASIS_BUFSIZ]; char export_command[7]; // export=6 and setenv=6... convenient char *_sh = getenv("SHELL"); char *sh = path_basename(_sh); @@ -93,6 +92,7 @@ void runtime_export(RuntimeEnv *env, char **keys) { } for (size_t i = 0; i < strlist_count(env); i++) { + char output[STASIS_BUFSIZ] = {0}; char **pair = split(strlist_item(env, i), "=", 0); char *key = pair[0]; char *value = NULL; @@ -145,7 +145,7 @@ void runtime_export(RuntimeEnv *env, char **keys) { RuntimeEnv *runtime_copy(char **env) { RuntimeEnv *rt = NULL; size_t env_count; - for (env_count = 0; env[env_count] != NULL; env_count++); + for (env_count = 0; env[env_count] != NULL; env_count++) {}; rt = strlist_init(); for (size_t i = 0; i < env_count; i++) { @@ -276,7 +276,6 @@ char *runtime_get(RuntimeEnv *env, const char *key) { */ char *runtime_expand_var(RuntimeEnv *env, char *input) { const char delim = '$'; - const char *delim_literal = "$$"; char *expanded = NULL; // Input is invalid @@ -297,10 +296,9 @@ char *runtime_expand_var(RuntimeEnv *env, char *input) { } // Parse the input string - size_t i; - for (i = 0; i < strlen(input); i++) { - char var[MAXNAMLEN]; // environment variable name - memset(var, '\0', MAXNAMLEN); // zero out name + for (size_t i = 0; i < strlen(input); i++) { + const char *delim_literal = "$$"; + char var[MAXNAMLEN] = {0}; // environment variable name // Handle literal statement "$$var" // Value becomes "$var" (unexpanded) diff --git a/src/lib/core/github.c b/src/lib/core/github.c index c5e4534..c195a28 100644 --- a/src/lib/core/github.c +++ b/src/lib/core/github.c @@ -9,7 +9,7 @@ struct GHContent { size_t len; }; -static size_t writer(void *contents, size_t size, size_t nmemb, void *result) { +static size_t writer(const void *contents, size_t size, size_t nmemb, void *result) { const size_t newlen = size * nmemb; struct GHContent *content = (struct GHContent *) result; @@ -42,8 +42,6 @@ static char *unescape_lf(char *value) { } int get_github_release_notes(const char *api_token, const char *repo, const char *tag, const char *target_commitish, char **output) { - const char *field_body = "\"body\":\""; - const char *field_message = "\"message\":\""; const char *endpoint_header_auth_fmt = "Authorization: Bearer %s"; const char *endpoint_header_api_version = "X-GitHub-Api-Version: " STASIS_GITHUB_API_VERSION; const char *endpoint_post_fields_fmt = "{\"tag_name\":\"%s\", \"target_commitish\":\"%s\"}"; @@ -84,8 +82,7 @@ int get_github_release_notes(const char *api_token, const char *repo, const char // Execute curl request memset(&content, 0, sizeof(content)); - CURLcode res; - res = curl_easy_perform(curl); + CURLcode res = curl_easy_perform(curl); // Clean up curl_slist_free_all(list); @@ -100,6 +97,8 @@ int get_github_release_notes(const char *api_token, const char *repo, const char // Replace all "\\n" literals with new line characters char *line = unescape_lf(content.data); if (line) { + const char *field_message = "\"message\":\""; + const char *field_body = "\"body\":\""; char *data_offset = NULL; if ((data_offset = strstr(line, field_body))) { // Skip past the body field diff --git a/src/lib/core/ini.c b/src/lib/core/ini.c index d44e1cc..14f337d 100644 --- a/src/lib/core/ini.c +++ b/src/lib/core/ini.c @@ -6,8 +6,7 @@ #include "ini.h" struct INIFILE *ini_init() { - struct INIFILE *ini; - ini = calloc(1, sizeof(*ini)); + struct INIFILE *ini = calloc(1, sizeof(*ini)); ini->section_count = 0; return ini; } @@ -116,8 +115,7 @@ int ini_getval(struct INIFILE *ini, char *section_name, char *key, int type, int char *token = NULL; char tbuf[STASIS_BUFSIZ]; char *tbufp = tbuf; - struct INIData *data; - data = ini_data_get(ini, section_name, key); + struct INIData *data = ini_data_get(ini, section_name, key); if (!data) { result->as_char_p = NULL; return -1; @@ -305,8 +303,7 @@ char *ini_getval_str_array(struct INIFILE *ini, char *section_name, char *key, i struct StrList *ini_getval_strlist(struct INIFILE *ini, char *section_name, char *key, char *tok, int flags, int *state) { getval_setup(INIVAL_TYPE_STR_ARRAY, flags) - struct StrList *list; - list = strlist_init(); + struct StrList *list = strlist_init(); strlist_append_tokenize(list, result.as_char_p, tok); guard_free(result.as_char_p); return list; @@ -441,8 +438,6 @@ int ini_write(struct INIFILE *ini, FILE **stream, unsigned mode) { value = xvalue; } char **parts = split(value, LINE_SEP, 0); - size_t parts_total = 0; - for (; parts && parts[parts_total] != NULL; parts_total++); for (size_t p = 0; parts && parts[p] != NULL; p++) { char *render = NULL; if (mode == INI_WRITE_PRESERVE) { @@ -520,7 +515,6 @@ void ini_free(struct INIFILE **ini) { } struct INIFILE *ini_open(const char *filename) { - FILE *fp; char line[STASIS_BUFSIZ] = {0}; char current_section[STASIS_BUFSIZ] = {0}; char reading_value = 0; @@ -537,7 +531,7 @@ struct INIFILE *ini_open(const char *filename) { strcpy(current_section, "default"); // Open the configuration file for reading - fp = fopen(filename, "r"); + FILE *fp = fopen(filename, "r"); if (!fp) { ini_free(&ini); ini = NULL; @@ -550,9 +544,8 @@ struct INIFILE *ini_open(const char *filename) { char inikey[2][255]; char *key = inikey[0]; char *key_last = inikey[1]; - char value[STASIS_BUFSIZ]; + char value[STASIS_BUFSIZ] = {0}; - memset(value, 0, sizeof(value)); memset(inikey, 0, sizeof(inikey)); // Read file diff --git a/src/lib/core/junitxml.c b/src/lib/core/junitxml.c index c7d0834..8ab231b 100644 --- a/src/lib/core/junitxml.c +++ b/src/lib/core/junitxml.c @@ -49,9 +49,7 @@ static int testsuite_append_testcase(struct JUNIT_Testsuite **testsuite, struct } static struct JUNIT_Failure *testcase_failure_from_attributes(struct StrList *attrs) { - struct JUNIT_Failure *result; - - result = calloc(1, sizeof(*result)); + struct JUNIT_Failure *result = calloc(1, sizeof(*result)); if(!result) { return NULL; } @@ -66,9 +64,7 @@ static struct JUNIT_Failure *testcase_failure_from_attributes(struct StrList *at } static struct JUNIT_Error *testcase_error_from_attributes(struct StrList *attrs) { - struct JUNIT_Error *result; - - result = calloc(1, sizeof(*result)); + struct JUNIT_Error *result = calloc(1, sizeof(*result)); if(!result) { return NULL; } @@ -83,9 +79,7 @@ static struct JUNIT_Error *testcase_error_from_attributes(struct StrList *attrs) } static struct JUNIT_Skipped *testcase_skipped_from_attributes(struct StrList *attrs) { - struct JUNIT_Skipped *result; - - result = calloc(1, sizeof(*result)); + struct JUNIT_Skipped *result = calloc(1, sizeof(*result)); if(!result) { return NULL; } @@ -100,9 +94,7 @@ static struct JUNIT_Skipped *testcase_skipped_from_attributes(struct StrList *at } static struct JUNIT_Testcase *testcase_from_attributes(struct StrList *attrs) { - struct JUNIT_Testcase *result; - - result = calloc(1, sizeof(*result)); + struct JUNIT_Testcase *result = calloc(1, sizeof(*result)); if(!result) { return NULL; } @@ -145,10 +137,9 @@ static struct StrList *attributes_to_strlist(xmlTextReaderPtr reader) { } static int read_xml_data(xmlTextReaderPtr reader, struct JUNIT_Testsuite **testsuite) { - const xmlChar *name; //const xmlChar *value; - name = xmlTextReaderConstName(reader); + const xmlChar *name = xmlTextReaderConstName(reader); if (!name) { // name could not be converted to string name = BAD_CAST "--"; @@ -206,15 +197,12 @@ static int read_xml_data(xmlTextReaderPtr reader, struct JUNIT_Testsuite **tests } static int read_xml_file(const char *filename, struct JUNIT_Testsuite **testsuite) { - xmlTextReaderPtr reader; - int result; - - reader = xmlReaderForFile(filename, NULL, 0); + xmlTextReaderPtr reader = xmlReaderForFile(filename, NULL, 0); if (!reader) { return -1; } - result = xmlTextReaderRead(reader); + int result = xmlTextReaderRead(reader); while (result == 1) { read_xml_data(reader, testsuite); result = xmlTextReaderRead(reader); diff --git a/src/lib/core/recipe.c b/src/lib/core/recipe.c index 833908c..99d3fe1 100644 --- a/src/lib/core/recipe.c +++ b/src/lib/core/recipe.c @@ -36,8 +36,6 @@ int recipe_clone(char *recipe_dir, char *url, char *gitref, char **result) { int recipe_get_type(char *repopath) { - int result; - char path[PATH_MAX]; // conda-forge is a collection of repositories // "conda-forge.yml" is guaranteed to exist const char *marker[] = { @@ -53,8 +51,9 @@ int recipe_get_type(char *repopath) { }; for (size_t i = 0; marker[i] != NULL; i++) { + char path[PATH_MAX] = {0}; sprintf(path, "%s/%s", repopath, marker[i]); - result = access(path, F_OK); + int result = access(path, F_OK); if (!result) { return type[i]; } diff --git a/src/lib/core/relocation.c b/src/lib/core/relocation.c index 852aca4..58b829d 100644 --- a/src/lib/core/relocation.c +++ b/src/lib/core/relocation.c @@ -21,10 +21,11 @@ * @param original string to modify * @param target string value to replace * @param replacement string value + * @param flags REPLACE_TRUNCATE_AFTER_MATCH * @return 0 on success, -1 on error */ int replace_text(char *original, const char *target, const char *replacement, unsigned flags) { - char buffer[STASIS_BUFSIZ]; + char buffer[STASIS_BUFSIZ] = {0}; char *pos = original; char *match = NULL; size_t original_len = strlen(original); @@ -65,7 +66,7 @@ int replace_text(char *original, const char *target, const char *replacement, un break; } // find more matches - if (!(match = strstr(pos, target))) { + if (!((match = strstr(pos, target)))) { // no more matches // append whatever remains to the buffer strcat(buffer, pos); @@ -100,22 +101,20 @@ int replace_text(char *original, const char *target, const char *replacement, un * @param filename path to file * @param target string value to replace * @param replacement string + * @param flags REPLACE_TRUNCATE_AFTER_MATCH * @return 0 on success, -1 on error */ int file_replace_text(const char* filename, const char* target, const char* replacement, unsigned flags) { - int result; char buffer[STASIS_BUFSIZ]; char tempfilename[] = "tempfileXXXXXX"; - FILE *fp; - FILE *tfp; - fp = fopen(filename, "r"); + FILE *fp = fopen(filename, "r"); if (!fp) { fprintf(stderr, "unable to open for reading: %s\n", filename); return -1; } - tfp = fopen(tempfilename, "w+"); + FILE *tfp = fopen(tempfilename, "w+"); if (!tfp) { SYSERROR("unable to open temporary fp for writing: %s", tempfilename); fclose(fp); @@ -123,7 +122,7 @@ int file_replace_text(const char* filename, const char* target, const char* repl } // Write modified strings to temporary file - result = 0; + int result = 0; while (fgets(buffer, sizeof(buffer), fp) != NULL) { if (strstr(buffer, target)) { if (replace_text(buffer, target, replacement, flags)) { diff --git a/src/lib/core/str.c b/src/lib/core/str.c index 868a6c7..a7dbab1 100644 --- a/src/lib/core/str.c +++ b/src/lib/core/str.c @@ -1,5 +1,5 @@ /** - * @file strings.c + * @file str.c */ #include <unistd.h> #include "str.h" @@ -196,11 +196,10 @@ char *join_ex(char *separator, ...) { char **tmp = realloc(argv, (argc + 1) * sizeof(char *)); if (tmp == NULL) { perror("join_ex realloc failed"); - guard_free(argv); + GENERIC_ARRAY_FREE(argv); return NULL; - } else { - argv = tmp; } + argv = tmp; size += strlen(current) + separator_len; argv[argc] = strdup(current); } @@ -280,14 +279,14 @@ char *substring_between(char *sptr, const char *delims) { /* * Comparison functions for `strsort` */ -static int _strsort_alpha_compare(const void *a, const void *b) { +static int strsort_alpha_compare(const void *a, const void *b) { const char *aa = *(const char **)a; const char *bb = *(const char **)b; int result = strcmp(aa, bb); return result; } -static int _strsort_numeric_compare(const void *a, const void *b) { +static int strsort_numeric_compare(const void *a, const void *b) { const char *aa = *(const char **)a; const char *bb = *(const char **)b; @@ -306,7 +305,7 @@ static int _strsort_numeric_compare(const void *a, const void *b) { return 0; } -static int _strsort_asc_compare(const void *a, const void *b) { +static int strsort_asc_compare(const void *a, const void *b) { const char *aa = *(const char**)a; const char *bb = *(const char**)b; size_t len_a = strlen(aa); @@ -317,7 +316,7 @@ static int _strsort_asc_compare(const void *a, const void *b) { /* * Helper function for `strsortlen` */ -static int _strsort_dsc_compare(const void *a, const void *b) { +static int strsort_dsc_compare(const void *a, const void *b) { const char *aa = *(const char**)a; const char *bb = *(const char**)b; size_t len_a = strlen(aa); @@ -332,16 +331,16 @@ void strsort(char **arr, unsigned int sort_mode) { typedef int (*compar)(const void *, const void *); // Default mode is alphabetic sort - compar fn = _strsort_alpha_compare; + compar fn = strsort_alpha_compare; if (sort_mode == STASIS_SORT_LEN_DESCENDING) { - fn = _strsort_dsc_compare; + fn = strsort_dsc_compare; } else if (sort_mode == STASIS_SORT_LEN_ASCENDING) { - fn = _strsort_asc_compare; + fn = strsort_asc_compare; } else if (sort_mode == STASIS_SORT_ALPHA) { - fn = _strsort_alpha_compare; // ^ still selectable though ^ + fn = strsort_alpha_compare; // ^ still selectable though ^ } else if (sort_mode == STASIS_SORT_NUMERIC) { - fn = _strsort_numeric_compare; + fn = strsort_numeric_compare; } size_t arr_size = 0; @@ -377,7 +376,7 @@ char **strdeldup(char **arr) { size_t records; // Determine the length of the array - for (records = 0; arr[records] != NULL; records++); + for (records = 0; arr[records] != NULL; records++) {} // Allocate enough memory to store the original array contents // (It might not have duplicate values, for example) @@ -520,7 +519,6 @@ void print_banner(const char *s, int len) { * @return pointer to `s` */ char *normalize_space(char *s) { - size_t len; size_t trim_pos; int add_whitespace = 0; char *result = s; @@ -537,11 +535,11 @@ char *normalize_space(char *s) { char *tmp_orig = tmp; // count whitespace, if any - for (trim_pos = 0; isblank(s[trim_pos]); trim_pos++); + for (trim_pos = 0; isblank(s[trim_pos]); trim_pos++) {} // trim whitespace from the left, if any memmove(s, &s[trim_pos], strlen(&s[trim_pos])); // cull bytes not part of the string after moving - len = strlen(s); + size_t len = strlen(s); s[len - trim_pos] = '\0'; // Generate a new string with extra whitespace stripped out @@ -581,7 +579,7 @@ char **strdup_array(char **array) { } // Count elements in `array` - for (elems = 0; array[elems] != NULL; elems++); + for (elems = 0; array[elems] != NULL; elems++) {} // Create new array result = calloc(elems + 1, sizeof(*result)); @@ -606,8 +604,8 @@ int strcmp_array(const char **a, const char **b) { } // Get length of arrays - for (a_len = 0; a[a_len] != NULL; a_len++); - for (b_len = 0; b[b_len] != NULL; b_len++); + for (a_len = 0; a[a_len] != NULL; a_len++) {} + for (b_len = 0; b[b_len] != NULL; b_len++) {} // Check lengths are equal if (a_len < b_len) return (int)(b_len - a_len); @@ -644,8 +642,7 @@ char *tolower_s(char *s) { } char *to_short_version(const char *s) { - char *result; - result = strdup(s); + char *result = strdup(s); if (!result) { return NULL; } diff --git a/src/lib/core/strlist.c b/src/lib/core/strlist.c index f0bffa8..ec7b3f4 100644 --- a/src/lib/core/strlist.c +++ b/src/lib/core/strlist.c @@ -43,9 +43,8 @@ void strlist_append(struct StrList **pStrList, char *str) { guard_strlist_free(pStrList); perror("failed to append to array"); exit(1); - } else if (tmp != (*pStrList)->data) { - (*pStrList)->data = tmp; } + (*pStrList)->data = tmp; (*pStrList)->data[(*pStrList)->num_inuse] = strdup(str); (*pStrList)->data[(*pStrList)->num_alloc] = NULL; strcpy((*pStrList)->data[(*pStrList)->num_inuse], str); @@ -62,7 +61,7 @@ static int reader_strlist_append_file(size_t lineno, char **line) { /** * Append lines from a local file or remote URL (HTTP/s only) * @param pStrList - * @param path file path or HTTP/s address + * @param _path file path or HTTP/s address * @param readerFn pointer to a reader function (use NULL to retrieve all data) * @return 0=success 1=no data, -1=error (spmerrno set) */ @@ -170,13 +169,12 @@ void strlist_append_strlist(struct StrList *pStrList1, struct StrList *pStrList2 * @param delim */ void strlist_append_tokenize(struct StrList *pStrList, char *str, char *delim) { - char **token; if (!str || !delim) { return; } char *tmp = strdup(str); - token = split(tmp, delim, 0); + char **token = split(tmp, delim, 0); if (token) { for (size_t i = 0; token[i] != NULL; i++) { lstrip(token[i]); @@ -310,6 +308,7 @@ size_t strlist_count(struct StrList *pStrList) { /** * Set value at index * @param pStrList + * @param index pStrlist->data[index] to set * @param value string * @return */ @@ -390,10 +389,9 @@ char *strlist_item_as_str(struct StrList *pStrList, size_t index) { */ char strlist_item_as_char(struct StrList *pStrList, size_t index) { char *error_p; - char result; strlist_clear_error(); - result = (char) strtol(strlist_item(pStrList, index), &error_p, 10); + char result = (char) strtol(strlist_item(pStrList, index), &error_p, 10); if (!result && error_p && *error_p != 0) { strlist_set_error(STRLIST_E_INVALID_VALUE); return 0; @@ -410,10 +408,9 @@ char strlist_item_as_char(struct StrList *pStrList, size_t index) { */ unsigned char strlist_item_as_uchar(struct StrList *pStrList, size_t index) { char *error_p; - unsigned char result; strlist_clear_error(); - result = (unsigned char) strtoul(strlist_item(pStrList, index), &error_p, 10); + unsigned char result = (unsigned char) strtoul(strlist_item(pStrList, index), &error_p, 10); if (!result && error_p && *error_p != 0) { strlist_set_error(STRLIST_E_INVALID_VALUE); return 0; @@ -430,10 +427,9 @@ unsigned char strlist_item_as_uchar(struct StrList *pStrList, size_t index) { */ short strlist_item_as_short(struct StrList *pStrList, size_t index) { char *error_p; - short result; strlist_clear_error(); - result = (short) strtol(strlist_item(pStrList, index), &error_p, 10); + short result = (short) strtol(strlist_item(pStrList, index), &error_p, 10); if (!result && error_p && *error_p != 0) { strlist_set_error(STRLIST_E_INVALID_VALUE); return 0; @@ -450,10 +446,9 @@ short strlist_item_as_short(struct StrList *pStrList, size_t index) { */ unsigned short strlist_item_as_ushort(struct StrList *pStrList, size_t index) { char *error_p; - unsigned short result; strlist_clear_error(); - result = (unsigned short) strtoul(strlist_item(pStrList, index), &error_p, 10); + unsigned short result = (unsigned short) strtoul(strlist_item(pStrList, index), &error_p, 10); if (!result && error_p && *error_p != 0) { strlist_set_error(STRLIST_E_INVALID_VALUE); return 0; @@ -470,10 +465,9 @@ unsigned short strlist_item_as_ushort(struct StrList *pStrList, size_t index) { */ int strlist_item_as_int(struct StrList *pStrList, size_t index) { char *error_p; - int result; strlist_clear_error(); - result = (int) strtol(strlist_item(pStrList, index), &error_p, 10); + int result = (int) strtol(strlist_item(pStrList, index), &error_p, 10); if (!result && error_p && *error_p != 0) { strlist_set_error(STRLIST_E_INVALID_VALUE); return 0; @@ -490,10 +484,9 @@ int strlist_item_as_int(struct StrList *pStrList, size_t index) { */ unsigned int strlist_item_as_uint(struct StrList *pStrList, size_t index) { char *error_p; - unsigned int result; strlist_clear_error(); - result = (unsigned int) strtoul(strlist_item(pStrList, index), &error_p, 10); + unsigned int result = (unsigned int) strtoul(strlist_item(pStrList, index), &error_p, 10); if (!result && error_p && *error_p != 0) { strlist_set_error(STRLIST_E_INVALID_VALUE); return 0; @@ -510,10 +503,9 @@ unsigned int strlist_item_as_uint(struct StrList *pStrList, size_t index) { */ long strlist_item_as_long(struct StrList *pStrList, size_t index) { char *error_p; - long result; strlist_clear_error(); - result = (long) strtol(strlist_item(pStrList, index), &error_p, 10); + long result = (long) strtol(strlist_item(pStrList, index), &error_p, 10); if (!result && error_p && *error_p != 0) { strlist_set_error(STRLIST_E_INVALID_VALUE); return 0; @@ -530,10 +522,9 @@ long strlist_item_as_long(struct StrList *pStrList, size_t index) { */ unsigned long strlist_item_as_ulong(struct StrList *pStrList, size_t index) { char *error_p; - unsigned long result; strlist_clear_error(); - result = (unsigned long) strtoul(strlist_item(pStrList, index), &error_p, 10); + unsigned long result = (unsigned long) strtoul(strlist_item(pStrList, index), &error_p, 10); if (!result && error_p && *error_p != 0) { strlist_set_error(STRLIST_E_INVALID_VALUE); return 0; @@ -550,10 +541,9 @@ unsigned long strlist_item_as_ulong(struct StrList *pStrList, size_t index) { */ long long strlist_item_as_long_long(struct StrList *pStrList, size_t index) { char *error_p; - long long result; strlist_clear_error(); - result = (long long) strtoll(strlist_item(pStrList, index), &error_p, 10); + long long result = (long long) strtoll(strlist_item(pStrList, index), &error_p, 10); if (!result && error_p && *error_p != 0) { strlist_set_error(STRLIST_E_INVALID_VALUE); return 0; @@ -570,10 +560,9 @@ long long strlist_item_as_long_long(struct StrList *pStrList, size_t index) { */ unsigned long long strlist_item_as_ulong_long(struct StrList *pStrList, size_t index) { char *error_p; - unsigned long long result; strlist_clear_error(); - result = (unsigned long long) strtol(strlist_item(pStrList, index), &error_p, 10); + unsigned long long result = (unsigned long long) strtol(strlist_item(pStrList, index), &error_p, 10); if (!result && error_p && *error_p != 0) { strlist_set_error(STRLIST_E_INVALID_VALUE); return 0; @@ -590,10 +579,9 @@ unsigned long long strlist_item_as_ulong_long(struct StrList *pStrList, size_t i */ float strlist_item_as_float(struct StrList *pStrList, size_t index) { char *error_p; - float result; strlist_clear_error(); - result = (float) strtof(strlist_item(pStrList, index), &error_p); + float result = (float) strtof(strlist_item(pStrList, index), &error_p); if (!result && error_p && *error_p != 0) { strlist_set_error(STRLIST_E_INVALID_VALUE); return 0; @@ -610,10 +598,9 @@ float strlist_item_as_float(struct StrList *pStrList, size_t index) { */ double strlist_item_as_double(struct StrList *pStrList, size_t index) { char *error_p; - double result; strlist_clear_error(); - result = (double) strtod(strlist_item(pStrList, index), &error_p); + double result = (double) strtod(strlist_item(pStrList, index), &error_p); if (!result && error_p && *error_p != 0) { strlist_set_error(STRLIST_E_INVALID_VALUE); return 0; @@ -630,10 +617,9 @@ double strlist_item_as_double(struct StrList *pStrList, size_t index) { */ long double strlist_item_as_long_double(struct StrList *pStrList, size_t index) { char *error_p; - long double result; strlist_clear_error(); - result = (long double) strtold(strlist_item(pStrList, index), &error_p); + long double result = (long double) strtold(strlist_item(pStrList, index), &error_p); if (!result && error_p && *error_p != 0) { strlist_set_error(STRLIST_E_INVALID_VALUE); return 0; diff --git a/src/lib/core/system.c b/src/lib/core/system.c index 4e605ec..9eff64a 100644 --- a/src/lib/core/system.c +++ b/src/lib/core/system.c @@ -3,7 +3,6 @@ int shell(struct Process *proc, char *args) { struct Process selfproc; - pid_t pid; pid_t status; status = 0; errno = 0; @@ -21,8 +20,7 @@ int shell(struct Process *proc, char *args) { } FILE *tp = NULL; - char *t_name; - t_name = xmkstemp(&tp, "w"); + char *t_name = xmkstemp(&tp, "w"); if (!t_name || !tp) { return -1; } @@ -36,7 +34,7 @@ int shell(struct Process *proc, char *args) { // somewhere. chmod(t_name, 0700); - pid = fork(); + pid_t pid = fork(); if (pid == -1) { fprintf(stderr, "fork failed\n"); exit(1); @@ -100,14 +98,13 @@ int shell(struct Process *proc, char *args) { int shell_safe(struct Process *proc, char *args) { FILE *fp; char buf[1024] = {0}; - int result; char *invalid_ch = strpbrk(args, STASIS_SHELL_SAFE_RESTRICT); if (invalid_ch) { args = NULL; } - result = shell(proc, args); + int result = shell(proc, args); if (strlen(proc->f_stdout)) { fp = fopen(proc->f_stdout, "r"); if (fp) { @@ -138,11 +135,10 @@ char *shell_output(const char *command, int *status) { size_t current_size = initial_size; char *result = NULL; char line[STASIS_BUFSIZ]; - FILE *pp; errno = 0; *status = 0; - pp = popen(command, "r"); + FILE *pp = popen(command, "r"); if (!pp) { *status = -1; return NULL; diff --git a/src/lib/core/template.c b/src/lib/core/template.c index a412fa8..60ed91e 100644 --- a/src/lib/core/template.c +++ b/src/lib/core/template.c @@ -241,7 +241,7 @@ char *tpl_render(char *str) { char *k = func_name_temp; char **params = split(param_begin, ",", 0); int params_count; - for (params_count = 0; params[params_count] != NULL; params_count++); + for (params_count = 0; params[params_count] != NULL; params_count++) {} struct tplfunc_frame *frame = tpl_getfunc(k); if (params_count > frame->argc || params_count < frame->argc) { @@ -293,17 +293,14 @@ char *tpl_render(char *str) { } int tpl_render_to_file(char *str, const char *filename) { - char *result; - FILE *fp; - // Render the input string - result = tpl_render(str); + char *result = tpl_render(str); if (!result) { return -1; } // Open the destination file for writing - fp = fopen(filename, "w+"); + FILE *fp = fopen(filename, "w+"); if (!fp) { guard_free(result); return -1; diff --git a/src/lib/core/template_func_proto.c b/src/lib/core/template_func_proto.c index 3305b4d..8324389 100644 --- a/src/lib/core/template_func_proto.c +++ b/src/lib/core/template_func_proto.c @@ -3,18 +3,17 @@ #include "github.h" int get_github_release_notes_tplfunc_entrypoint(void *frame, void *data_out) { - int result; char **output = (char **) data_out; struct tplfunc_frame *f = (struct tplfunc_frame *) frame; char *api_token = getenv("STASIS_GH_TOKEN"); if (!api_token) { api_token = getenv("GITHUB_TOKEN"); } - result = get_github_release_notes(api_token ? api_token : "anonymous", - (const char *) f->argv[0].t_char_ptr, - (const char *) f->argv[1].t_char_ptr, - (const char *) f->argv[2].t_char_ptr, - output); + int result = get_github_release_notes(api_token ? api_token : "anonymous", + (const char *) f->argv[0].t_char_ptr, + (const char *) f->argv[1].t_char_ptr, + (const char *) f->argv[2].t_char_ptr, + output); return result; } diff --git a/src/lib/core/utils.c b/src/lib/core/utils.c index 89950df..5f0807c 100644 --- a/src/lib/core/utils.c +++ b/src/lib/core/utils.c @@ -36,10 +36,9 @@ int rmtree(char *_path) { int status = 0; char path[PATH_MAX] = {0}; strncpy(path, _path, sizeof(path) - 1); - DIR *dir; struct dirent *d_entity; - dir = opendir(path); + DIR *dir = opendir(path); if (!dir) { return 1; } @@ -166,7 +165,6 @@ char *path_dirname(char *path) { char **file_readlines(const char *filename, size_t start, size_t limit, ReaderFn *readerFn) { FILE *fp = NULL; char **result = NULL; - char *buffer = NULL; size_t lines = 0; int use_stdin = 0; @@ -187,7 +185,8 @@ char **file_readlines(const char *filename, size_t start, size_t limit, ReaderFn } // Allocate buffer - if ((buffer = calloc(STASIS_BUFSIZ, sizeof(char))) == NULL) { + char *buffer = calloc(STASIS_BUFSIZ, sizeof(char)); + if (buffer == NULL) { SYSERROR("unable to allocate %d bytes for buffer", STASIS_BUFSIZ); if (!use_stdin) { fclose(fp); @@ -346,15 +345,13 @@ int git_clone(struct Process *proc, char *url, char *destdir, char *gitref) { char *git_describe(const char *path) { - static char version[NAME_MAX]; - FILE *pp; + static char version[NAME_MAX] = {0}; - memset(version, 0, sizeof(version)); if (pushd(path)) { return NULL; } - pp = popen("git describe --first-parent --always --tags", "r"); + FILE *pp = popen("git describe --first-parent --always --tags", "r"); if (!pp) { return NULL; } @@ -368,7 +365,6 @@ char *git_describe(const char *path) { char *git_rev_parse(const char *path, char *args) { static char version[NAME_MAX]; char cmd[PATH_MAX]; - FILE *pp; memset(version, 0, sizeof(version)); if (isempty(args)) { @@ -381,7 +377,7 @@ char *git_rev_parse(const char *path, char *args) { } sprintf(cmd, "git rev-parse %s", args); - pp = popen(cmd, "r"); + FILE *pp = popen(cmd, "r"); if (!pp) { return NULL; } @@ -490,11 +486,10 @@ char *xmkstemp(FILE **fp, const char *mode) { } int isempty_dir(const char *path) { - DIR *dp; struct dirent *rec; size_t count = 0; - dp = opendir(path); + DIR *dp = opendir(path); if (!dp) { return -1; } @@ -509,7 +504,6 @@ int isempty_dir(const char *path) { } int path_store(char **destptr, size_t maxlen, const char *base, const char *path) { - char *path_tmp; size_t base_len = 0; size_t path_len = 0; @@ -519,7 +513,7 @@ int path_store(char **destptr, size_t maxlen, const char *base, const char *path } // Initialize destination pointer to length of maxlen - path_tmp = calloc(maxlen, sizeof(*path_tmp)); + char *path_tmp = calloc(maxlen, sizeof(*path_tmp)); if (!path_tmp) { return -1; } @@ -541,7 +535,7 @@ int path_store(char **destptr, size_t maxlen, const char *base, const char *path guard_free(*destptr); } - if (!(*destptr = realpath(path_tmp, NULL))) { + if (!((*destptr = realpath(path_tmp, NULL)))) { goto l_path_setup_error; } @@ -620,11 +614,9 @@ int xml_pretty_print_in_place(const char *filename, const char *pretty_print_pro int fix_tox_conf(const char *filename, char **result) { struct INIFILE *toxini; FILE *fptemp; - char *tempfile; - const char *with_posargs = " \\\n {posargs}\n"; // Create new temporary tox configuration file - tempfile = xmkstemp(&fptemp, "w+"); + char *tempfile = xmkstemp(&fptemp, "w+"); if (!tempfile) { return -1; } @@ -663,17 +655,16 @@ int fix_tox_conf(const char *filename, char **result) { char *value = ini_getval_str(toxini, section->key, data->key, INI_READ_RENDER, &err); if (key && value) { if (startswith(value, "pytest") && !strstr(value, "{posargs}")) { + const char *with_posargs = " \\\n {posargs}\n"; strip(value); - char *tmp; - tmp = realloc(value, strlen(value) + strlen(with_posargs) + 1); + char *tmp = realloc(value, strlen(value) + strlen(with_posargs) + 1); if (!tmp) { SYSERROR("failed to increase size to +%zu bytes", strlen(value) + strlen(with_posargs) + 1); guard_free(*result); return -1; - } else if (tmp != value) { - value = tmp; } + value = tmp; strcat(value, with_posargs); ini_setval(&toxini, INI_SETVAL_REPLACE, section_name, key, value); } @@ -725,6 +716,7 @@ char *collapse_whitespace(char **s) { /** * Replace sensitive text in strings with ***REDACTED*** * @param to_redact a list of tokens to redact + * @param to_redact_size limit to n tokens in list * @param src to read * @param dest to write modified string * @param maxlen maximum length of dest string @@ -762,10 +754,9 @@ int redact_sensitive(const char **to_redact, size_t to_redact_size, char *src, c */ struct StrList *listdir(const char *path) { struct StrList *node; - DIR *dp; struct dirent *rec; - dp = opendir(path); + DIR *dp = opendir(path); if (!dp) { return NULL; } @@ -790,7 +781,6 @@ long get_cpu_count() { } int mkdirs(const char *_path, mode_t mode) { - int status; char *token; char pathbuf[PATH_MAX] = {0}; char *path; @@ -799,7 +789,7 @@ int mkdirs(const char *_path, mode_t mode) { errno = 0; char result[PATH_MAX] = {0}; - status = 0; + int status = 0; while ((token = strsep(&path, "/")) != NULL && !status) { if (token[0] == '.') continue; diff --git a/src/lib/core/wheel.c b/src/lib/core/wheel.c index 4692d0a..d5d5ff0 100644 --- a/src/lib/core/wheel.c +++ b/src/lib/core/wheel.c @@ -1,7 +1,6 @@ #include "wheel.h" struct Wheel *get_wheel_info(const char *basepath, const char *name, char *to_match[], unsigned match_mode) { - DIR *dp; struct dirent *rec; struct Wheel *result = NULL; char package_path[PATH_MAX]; @@ -11,7 +10,7 @@ struct Wheel *get_wheel_info(const char *basepath, const char *name, char *to_ma tolower_s(package_name); sprintf(package_path, "%s/%s", basepath, package_name); - dp = opendir(package_path); + DIR *dp = opendir(package_path); if (!dp) { return NULL; } @@ -80,7 +79,7 @@ struct Wheel *get_wheel_info(const char *basepath, const char *name, char *to_ma return NULL; } - for (parts_total = 0; parts[parts_total] != NULL; parts_total++); + for (parts_total = 0; parts[parts_total] != NULL; parts_total++) {} if (parts_total == 5) { // no build tag result->distribution = strdup(parts[0]); diff --git a/tests/data/generic_based_on.ini b/tests/data/generic_based_on.ini index 1c993ea..1287933 100644 --- a/tests/data/generic_based_on.ini +++ b/tests/data/generic_based_on.ini @@ -1,6 +1,6 @@ [meta] mission = generic -name = GENERIC +name = GENERIC_BASED_ON version = 1.2.3 rc = 1 final = false diff --git a/tests/setup.sh b/tests/setup.sh index 0875cac..50209ae 100644 --- a/tests/setup.sh +++ b/tests/setup.sh @@ -24,7 +24,15 @@ setup_script_dir="$(dirname ${BASH_SOURCE[0]})" export TOPDIR=$(pwd) export TEST_DATA="$TOPDIR"/data -WS_DEFAULT=rt_workspace_ +pushd() { + command pushd "$@" 1>/dev/null +} + +popd() { + command popd 1>/dev/null +} + +WS_DEFAULT="workspaces/rt_workspace_" setup_workspace() { if [ -z "$1" ]; then echo "setup_workspace requires a name argument" >&2 @@ -253,8 +261,18 @@ assert_file_contains() { fi } +clean_up_docker() { + CONTAINERS_DIR="$WORKSPACE/.local/share/containers" + # HOME points to the WORKSPACE. The only reason we'd have this directory is if docker/podman was executed + # Fair to assume if the directory exists, docker/podman is functional. + if [ -d "$CONTAINERS_DIR" ]; then + docker run --rm -it -v $CONTAINERS_DIR:/data alpine sh -c '/bin/rm -r -f /data/*' + fi +} + clean_up() { - if [ -z "$RT_KEEP_WORKSPACE" ] && [ -d "$WORKSPACE" ]; then + if ([ -z "$RT_KEEP_WORKSPACE" ] || [ -z "$KEEP_WORKSPACE" ]) && [ -d "$WORKSPACE" ]; then + clean_up_docker rm -rf "$WORKSPACE" fi diff --git a/tests/test_conda.c b/tests/test_conda.c index 84f98bc..63a2781 100644 --- a/tests/test_conda.c +++ b/tests/test_conda.c @@ -202,7 +202,11 @@ int main(int argc, char *argv[]) { test_delivery_gather_tool_versions, }; - const char *ws = "workspace"; + char ws[] = "workspace_XXXXXX"; + if (!mkdtemp(ws)) { + perror("mkdtemp"); + exit(1); + } getcwd(cwd_start, sizeof(cwd_start) - 1); mkdir(ws, 0755); chdir(ws); diff --git a/tests/test_junitxml.c b/tests/test_junitxml.c index e222b56..362cb32 100644 --- a/tests/test_junitxml.c +++ b/tests/test_junitxml.c @@ -3,7 +3,10 @@ void test_junitxml_testsuite_read() { struct JUNIT_Testsuite *testsuite; - STASIS_ASSERT_FATAL((testsuite = junitxml_testsuite_read("data/result.xml")) != NULL, "failed to load testsuite data"); + char datafile[PATH_MAX] = {0}; + snprintf(datafile, sizeof(datafile) - 1, "%s/result.xml", TEST_DATA_DIR); + + STASIS_ASSERT_FATAL((testsuite = junitxml_testsuite_read(datafile)) != NULL, "failed to load testsuite data"); STASIS_ASSERT(testsuite->name != NULL, "Test suite must be named"); STASIS_ASSERT(testsuite->skipped > 0, "missed skipped tests"); STASIS_ASSERT(testsuite->failures > 0, "missed failed tests"); @@ -44,7 +47,9 @@ void test_junitxml_testsuite_read() { void test_junitxml_testsuite_read_error() { struct JUNIT_Testsuite *testsuite; - STASIS_ASSERT_FATAL((testsuite = junitxml_testsuite_read("data/result_error.xml")) != NULL, "failed to load testsuite data"); + char datafile[PATH_MAX] = {0}; + snprintf(datafile, sizeof(datafile) - 1, "%s/result_error.xml", TEST_DATA_DIR); + STASIS_ASSERT_FATAL((testsuite = junitxml_testsuite_read(datafile)) != NULL, "failed to load testsuite data"); STASIS_ASSERT(testsuite->name != NULL, "test suite must be named"); STASIS_ASSERT(testsuite->skipped == 0, "should not have any skipped tests"); diff --git a/tests/test_str.c b/tests/test_str.c index 4991c1c..3aea50b 100644 --- a/tests/test_str.c +++ b/tests/test_str.c @@ -204,8 +204,7 @@ void test_split() { {.data = NULL, .delim = NULL, NULL}, }; for (size_t i = 0; i < sizeof(tc) / sizeof(*tc); i++) { - char **result; - result = split(tc[i].data, tc[i].delim, tc[i].max_split); + char **result = split((char *) tc[i].data, tc[i].delim, tc[i].max_split); STASIS_ASSERT(strcmp_array((const char **) result, tc[i].expected) == 0, "Split failed"); GENERIC_ARRAY_FREE(result); } @@ -243,8 +242,7 @@ void test_join_ex() { {.delim = "\n\n", .expected = "a\n\nb\n\nc\n\nd\n\ne"}, }; for (size_t i = 0; i < sizeof(tc) / sizeof(*tc); i++) { - char *result; - result = join_ex((char *) tc[i].delim, "a", "b", "c", "d", "e", NULL); + char *result = join_ex((char *) tc[i].delim, "a", "b", "c", "d", "e", NULL); STASIS_ASSERT(strcmp(result ? result : "", tc[i].expected) == 0, "failed to join array"); guard_free(result); } @@ -270,7 +268,7 @@ void test_substring_between() { {.data = "nothing () here", .delim = "()", .expected = ""}, // nothing exists between delimiters }; for (size_t i = 0; i < sizeof(tc) / sizeof(*tc); i++) { - char *result = substring_between(tc[i].data, tc[i].delim); + char *result = substring_between((char *) tc[i].data, tc[i].delim); STASIS_ASSERT(strcmp(result ? result : "", tc[i].expected) == 0, "unable to extract substring"); guard_free(result); } diff --git a/tests/testing.h b/tests/testing.h index 15bd208..4c97bf2 100644 --- a/tests/testing.h +++ b/tests/testing.h @@ -21,14 +21,21 @@ struct stasis_test_result_t { } stasis_test_results[STASIS_TEST_RUN_MAX]; size_t stasis_test_results_i = 0; -void stasis_testing_record_result(struct stasis_test_result_t result); - -void stasis_testing_record_result(struct stasis_test_result_t result) { +extern inline void stasis_testing_setup_workspace(); +extern inline void stasis_testing_clean_up_docker(); +extern inline void stasis_testing_teardown_workspace(); +extern inline void stasis_testing_record_result(struct stasis_test_result_t result); +extern inline int stasis_testing_has_failed(); +extern inline void stasis_testing_record_result_summary(); +extern inline char *stasis_testing_read_ascii(const char *filename); +extern inline int stasis_testing_write_ascii(const char *filename, const char *data); + +inline void stasis_testing_record_result(struct stasis_test_result_t result) { memcpy(&stasis_test_results[stasis_test_results_i], &result, sizeof(result)); stasis_test_results_i++; } -int stasis_testing_has_failed() { +inline int stasis_testing_has_failed() { for (size_t i = 0; i < stasis_test_results_i; i++) { if (stasis_test_results[i].status == false) { return 1; @@ -36,7 +43,8 @@ int stasis_testing_has_failed() { } return 0; } -void stasis_testing_record_result_summary() { + +inline void stasis_testing_record_result_summary() { size_t failed = 0; size_t skipped = 0; size_t passed = 0; @@ -70,7 +78,7 @@ void stasis_testing_record_result_summary() { fprintf(stdout, "\n[UNIT] %zu tests passed, %zu tests failed, %zu tests skipped out of %zu\n", passed, failed, skipped, stasis_test_results_i); } -char *stasis_testing_read_ascii(const char *filename) { +inline char *stasis_testing_read_ascii(const char *filename) { struct stat st; if (stat(filename, &st)) { perror(filename); @@ -96,7 +104,7 @@ char *stasis_testing_read_ascii(const char *filename) { return result; } -int stasis_testing_write_ascii(const char *filename, const char *data) { +inline int stasis_testing_write_ascii(const char *filename, const char *data) { FILE *fp; fp = fopen(filename, "w+"); if (!fp) { @@ -114,13 +122,85 @@ int stasis_testing_write_ascii(const char *filename, const char *data) { return 0; } +char TEST_DATA_DIR[PATH_MAX] = {0}; +char TEST_START_DIR[PATH_MAX] = {0}; +char TEST_WORKSPACE_DIR[PATH_MAX] = {0}; +inline void stasis_testing_setup_workspace() { + if (!realpath("data", TEST_DATA_DIR)) { + SYSERROR("%s", "Data directory is missing"); + exit(1); + } + + if (mkdir("workspaces", 0755) < 0) { + if (errno != EEXIST) { + SYSERROR("%s", "Unable to create workspaces directory"); + exit(1); + } + } + char ws[] = "workspaces/workspace_XXXXXX"; + if (mkdtemp(ws) == NULL) { + SYSERROR("Unable to create testing workspace: %s", ws); + exit(1); + } + if (!realpath(ws, TEST_WORKSPACE_DIR)) { + SYSERROR("%s", "Unable to determine absolute path to temporary workspace"); + exit(1); + } + if (chdir(TEST_WORKSPACE_DIR) < 0) { + SYSERROR("Unable to enter workspace directory: '%s'", TEST_WORKSPACE_DIR); + exit(1); + } + if (setenv("HOME", TEST_WORKSPACE_DIR, 1) < 0) { + SYSERROR("Unable to reset HOME to '%s'", TEST_WORKSPACE_DIR); + } +} + +inline void stasis_testing_clean_up_docker() { + char containers_dir[PATH_MAX] = {0}; + snprintf(containers_dir, sizeof(containers_dir) - 1, "%s/.local/share/containers", TEST_WORKSPACE_DIR); + + if (access(containers_dir, F_OK) == 0) { + char cmd[PATH_MAX] = {0}; + snprintf(cmd, sizeof(cmd) - 1, "docker run --rm -it -v %s:/data alpine sh -c '/bin/rm -r -f /data/*' &>/dev/null", containers_dir); + // This command will "fail" due to podman's internal protection(s). However, this gets us close enough. + system(cmd); + + // Podman seems to defer the rollback operation on-error for a short period. + // This buys time, so we can delete it. + sleep(1); + sync(); + if (rmtree(containers_dir)) { + SYSERROR("WARNING: Unable to fully remove container directory: '%s'", containers_dir); + } + } +} + +inline void stasis_testing_teardown_workspace() { + if (chdir(TEST_START_DIR) < 0) { + SYSERROR("Unable to re-enter test start directory from workspace directory: %s", TEST_START_DIR); + exit(1); + } + if (!getenv("KEEP_WORKSPACE")) { + if (strlen(TEST_WORKSPACE_DIR) > 1) { + stasis_testing_clean_up_docker(); + rmtree(TEST_WORKSPACE_DIR); + } + } +} + #define STASIS_TEST_BEGIN_MAIN() do { \ setenv("PYTHONUNBUFFERED", "1", 1); \ fflush(stdout); \ fflush(stderr); \ setvbuf(stdout, NULL, _IONBF, 0); \ setvbuf(stderr, NULL, _IONBF, 0); \ + if (!getcwd(TEST_START_DIR, sizeof(TEST_START_DIR) - 1)) { \ + SYSERROR("%s", "Unable to determine current working directory"); \ + exit(1); \ + } \ atexit(stasis_testing_record_result_summary); \ + atexit(stasis_testing_teardown_workspace); \ + stasis_testing_setup_workspace(); \ } while (0) #define STASIS_TEST_END_MAIN() do { return stasis_testing_has_failed(); } while (0) |