/* * mkproj - dumb project generator. * * generates boilerplate for make, cmake, meson, premake or xmake so you can * stop writing the same fucking build files every time you start a project. * * Author: hachem * Version: 0.4.0 */ #include #include #include #include #include #include #include #include #include #include #include #define mkproj_program "mkproj" #define mkproj_version "0.4.0" #define mkproj_tagline "dumb project generator" enum Language { language_c, language_cpp, language_objc, language_nasm, language_swift, language_crust, language_count }; enum Build_System { build_make, build_cmake, build_meson, build_premake, build_xmake, build_system_count }; enum Kind { kind_exe, kind_lib, kind_shared }; enum License { license_none, license_mit, license_isc, license_bsd2, license_bsd3, license_unlicense, license_count }; struct Language_Info { const char* key; const char* name; const char* compiler; const char* extension; const char* const* standards; size_t standard_count; const char* default_standard; }; struct Build_Info { const char* key; const char* name; const char* default_bin; const char* default_bin_int; }; struct Config { const char* name; const char* dir; const char* src_dir; enum Language language; const char* standard; const char* compiler; enum Build_System build; enum Kind kind; enum License license; const char* bin_dir; const char* bin_int_dir; int use_git; int use_intermediate; int use_flat; int use_docker; int use_root; int use_style; int use_ci; int use_single; int use_validation; }; static const char* const c_standards[] = { "c89", "c99", "c11", "c17", "c23", "c2y" }; static const char* const cpp_standards[] = { "c++98", "c++03", "c++11", "c++14", "c++17", "c++20", "c++23", "c++26" }; static const struct Language_Info languages[language_count] = { [language_c] = { .key = "c", .name = "C", .compiler = "clang", .extension = "c", .standards = c_standards, .standard_count = sizeof c_standards / sizeof c_standards[0], .default_standard = "c2y", }, [language_cpp] = { .key = "cpp", .name = "C++", .compiler = "clang++", .extension = "cpp", .standards = cpp_standards, .standard_count = sizeof cpp_standards / sizeof cpp_standards[0], .default_standard = "c++26", }, [language_objc] = { .key = "objc", .name = "Objective-C", .compiler = "clang", .extension = "m", .standards = c_standards, .standard_count = sizeof c_standards / sizeof c_standards[0], .default_standard = "c2y", }, [language_nasm] = { .key = "nasm", .name = "NASM", .compiler = "nasm", .extension = "asm", .standards = NULL, .standard_count = 0, .default_standard = NULL, }, [language_swift] = { .key = "swift", .name = "Swift", .compiler = "swiftc", .extension = "swift", .standards = NULL, .standard_count = 0, .default_standard = NULL, }, [language_crust] = { .key = "crust", .name = "Rust", .compiler = "rustc", .extension = "rs", .standards = NULL, .standard_count = 0, .default_standard = NULL, }, }; /* the clang-driven languages: they share -std, the warning set, per-object * make rules and clang-format. nasm, swift and crust each build their own way * instead. */ static int is_c_family(enum Language language) { return language == language_c || language == language_cpp || language == language_objc; } static const struct Build_Info build_systems[build_system_count] = { [build_make] = { .key = "make", .name = "Make", .default_bin = "bin", .default_bin_int = "bin-int", }, [build_cmake] = { .key = "cmake", .name = "CMake", .default_bin = "build", .default_bin_int = "build", }, [build_meson] = { .key = "meson", .name = "Meson", .default_bin = "builddir", .default_bin_int = "builddir", }, [build_premake] = { .key = "premake", .name = "premake5", .default_bin = "bin", .default_bin_int = "bin-int", }, [build_xmake] = { .key = "xmake", .name = "xmake", .default_bin = "build", .default_bin_int = "build", }, }; struct License_Info { const char* key; const char* name; }; static const struct License_Info licenses[license_count] = { [license_none] = { .key = "none", .name = "none" }, [license_mit] = { .key = "mit", .name = "MIT" }, [license_isc] = { .key = "isc", .name = "ISC" }, [license_bsd2] = { .key = "bsd-2", .name = "BSD 2-Clause" }, [license_bsd3] = { .key = "bsd-3", .name = "BSD 3-Clause" }, [license_unlicense] = { .key = "unlicense", .name = "The Unlicense" }, }; static void print_version(void) { (void) printf("%s %s\n", mkproj_program, mkproj_version); } static void print_usage(FILE* stream) { (void) fprintf( stream, "%s %s - %s\n" "\n" "generates boilerplate for make, cmake, meson, premake or xmake so you can\n" "stop writing the same fucking build files every time you start a project.\n" "\n" "usage: %s [-l lang] [-s std] [-b system] [-k kind] [--cc cc] [--license name]\n" " [--git] [--no-root] [--single] [--no-validation] [--docker]\n" " [--style] [--ci] [--src dir] [--bin dir] [--bin-int dir] \n" " %s --completions bash|zsh|fish\n" " %s [-v | -h]\n" "\n" " is the project directory to create, or . to generate into the\n" "current directory (the project name is taken from its basename).\n" "\n" "defaults: a flat C project built with make, binary at the project root,\n" "the latest language standard, and objects under bin/.\n" "\n" "options:\n" " -l, --lang LANG language: c, cpp, objc, nasm, swift, crust (default c)\n" " -s, --std STD language standard (default: latest for the language)\n" " -b, --build SYSTEM build system: make, cmake, meson, premake, xmake (default make)\n" " -k, --kind KIND exe or lib (default exe)\n" " --cc CC compiler (default clang/clang++); make, premake, xmake\n" " --license NAME add a LICENSE: mit, isc, bsd-2, bsd-3, unlicense\n" " --git initialize a git repository and write a .gitignore\n" " --src DIR put sources in DIR/ instead of at the project root\n" " --no-root put the binary in the build dir, not the project root\n" " --single single-file project: compile directly, no object dir (make, c family)\n" " --no-validation drop the make check target and the sanitizer flags\n" " --docker add a Dockerfile to build in a container (c, cpp, nasm)\n" " --style add .clang-format + .editorconfig from the style guide\n" " --ci add a GitHub Actions workflow that builds the project\n" " --bin DIR build directory (default per build system)\n" " --bin-int DIR put objects in a separate dir (make/premake)\n" " -v, --version print version and bail\n" " -h, --help print this and bail\n" "\n" "by hachem \n", mkproj_program, mkproj_version, mkproj_tagline, mkproj_program, mkproj_program, mkproj_program); } /* space-separated language / build-system / license keys, straight from the * tables so the completions never drift from what the parser accepts. */ static void collect_langs(char* buf, size_t size) { size_t off = 0; for (enum Language l = 0; l < language_count; l++) off += (size_t) snprintf(buf + off, size - off, "%s%s", off != 0 ? " " : "", languages[l].key); } static void collect_builds(char* buf, size_t size) { size_t off = 0; for (enum Build_System b = 0; b < build_system_count; b++) off += (size_t) snprintf(buf + off, size - off, "%s%s", off != 0 ? " " : "", build_systems[b].key); } static void collect_licenses(char* buf, size_t size) { size_t off = 0; for (enum License l = license_mit; l < license_count; l++) off += (size_t) snprintf(buf + off, size - off, "%s%s", off != 0 ? " " : "", licenses[l].key); } /* the plain (no-argument) flags, shared by every shell's option list. */ #define mkproj_flags \ "-l --lang -s --std -b --build -k --kind --cc --license " \ "--git --src --no-root --single --no-validation --docker --style --ci " \ "--bin --bin-int -v --version -h --help" static void print_completions_bash(void) { char langs[128], builds[128], lics[128]; collect_langs(langs, sizeof langs); collect_builds(builds, sizeof builds); collect_licenses(lics, sizeof lics); (void) printf( "_mkproj()\n" "{\n" " local cur prev\n" " cur=\"${COMP_WORDS[COMP_CWORD]}\"\n" " prev=\"${COMP_WORDS[COMP_CWORD-1]}\"\n" "\n" " case \"$prev\" in\n" " -l|--lang) COMPREPLY=( $(compgen -W \"%s\" -- \"$cur\") ); return ;;\n" " -b|--build) COMPREPLY=( $(compgen -W \"%s\" -- \"$cur\") ); return ;;\n" " -k|--kind) COMPREPLY=( $(compgen -W \"exe lib\" -- \"$cur\") ); return ;;\n" " --license) COMPREPLY=( $(compgen -W \"%s\" -- \"$cur\") ); return ;;\n" " --completions) COMPREPLY=( $(compgen -W \"bash zsh fish\" -- \"$cur\") ); return ;;\n" " --cc|--bin|--bin-int|--src|-s|--std) return ;;\n" " esac\n" "\n" " if [[ \"$cur\" == -* ]]; then\n" " COMPREPLY=( $(compgen -W \"%s\" -- \"$cur\") )\n" " else\n" " COMPREPLY=( $(compgen -f -- \"$cur\") )\n" " fi\n" "}\n" "complete -F _mkproj mkproj\n", langs, builds, lics, mkproj_flags); } static void print_completions_zsh(void) { char langs[128], builds[128], lics[128]; collect_langs(langs, sizeof langs); collect_builds(builds, sizeof builds); collect_licenses(lics, sizeof lics); (void) printf( "#compdef mkproj\n" "\n" "_mkproj()\n" "{\n" " _arguments -s \\\n" " '(-l --lang)'{-l,--lang}'[source language]:language:(%s)' \\\n" " '(-s --std)'{-s,--std}'[language standard]:standard:' \\\n" " '(-b --build)'{-b,--build}'[build system]:system:(%s)' \\\n" " '(-k --kind)'{-k,--kind}'[exe or lib]:kind:(exe lib)' \\\n" " '--cc[compiler]:compiler:' \\\n" " '--license[add a LICENSE]:license:(%s)' \\\n" " '--src[source directory]:dir:_files -/' \\\n" " '--bin[build directory]:dir:_files -/' \\\n" " '--bin-int[object directory]:dir:_files -/' \\\n" " '--git[init a git repo and write .gitignore]' \\\n" " '--no-root[binary in the build dir]' \\\n" " '--single[single-file project, no object dir]' \\\n" " '--no-validation[no check target or sanitizers]' \\\n" " '--docker[add a Dockerfile]' \\\n" " '--style[add clang-format + editorconfig]' \\\n" " '--ci[add a GitHub Actions workflow]' \\\n" " '(-v --version)'{-v,--version}'[print version]' \\\n" " '(-h --help)'{-h,--help}'[print help]' \\\n" " '1:name:'\n" "}\n" "\n" "_mkproj \"$@\"\n", langs, builds, lics); } static void print_completions_fish(void) { char langs[128], builds[128], lics[128]; collect_langs(langs, sizeof langs); collect_builds(builds, sizeof builds); collect_licenses(lics, sizeof lics); (void) printf( "complete -c mkproj -s l -l lang -x -a '%s' -d 'source language'\n" "complete -c mkproj -s s -l std -x -d 'language standard'\n" "complete -c mkproj -s b -l build -x -a '%s' -d 'build system'\n" "complete -c mkproj -s k -l kind -x -a 'exe lib' -d 'exe or lib'\n" "complete -c mkproj -l cc -x -d 'compiler'\n" "complete -c mkproj -l license -x -a '%s' -d 'add a LICENSE'\n" "complete -c mkproj -l src -x -a '(__fish_complete_directories)' -d 'source directory'\n" "complete -c mkproj -l bin -x -a '(__fish_complete_directories)' -d 'build directory'\n" "complete -c mkproj -l bin-int -x -a '(__fish_complete_directories)' -d 'object directory'\n" "complete -c mkproj -l git -d 'init a git repo and write .gitignore'\n" "complete -c mkproj -l no-root -d 'binary in the build dir'\n" "complete -c mkproj -l single -d 'single-file project, no object dir'\n" "complete -c mkproj -l no-validation -d 'no check target or sanitizers'\n" "complete -c mkproj -l docker -d 'add a Dockerfile'\n" "complete -c mkproj -l style -d 'add clang-format + editorconfig'\n" "complete -c mkproj -l ci -d 'add a GitHub Actions workflow'\n" "complete -c mkproj -s v -l version -d 'print version'\n" "complete -c mkproj -s h -l help -d 'print help'\n", langs, builds, lics); } static int find_language(const char* key, enum Language* out) { for (enum Language language = 0; language < language_count; language++) if (strcmp(languages[language].key, key) == 0) { *out = language; return 1; } return 0; } static int find_build_system(const char* key, enum Build_System* out) { for (enum Build_System build = 0; build < build_system_count; build++) if (strcmp(build_systems[build].key, key) == 0) { *out = build; return 1; } return 0; } static int find_license(const char* key, enum License* out) { for (enum License license = 0; license < license_count; license++) if (strcmp(licenses[license].key, key) == 0) { *out = license; return 1; } return 0; } static int valid_standard(enum Language language, const char* standard) { const struct Language_Info* info = &languages[language]; for (size_t i = 0; i < info->standard_count; i++) if (strcmp(info->standards[i], standard) == 0) return 1; return 0; } static void error(const char* message, const char* detail) { if (detail != NULL) (void) fprintf(stderr, "%s: error: %s: %s\n", mkproj_program, message, detail); else (void) fprintf(stderr, "%s: error: %s\n", mkproj_program, message); } /* match a value-taking option. handles both "--opt val" and "--opt=val". * returns 1 and sets *value on a match, -1 if the value is missing, else 0. */ static int opt_value(const char* arg, const char* shortname, const char* longname, int argc, char** argv, int* i, const char** value) { if (strcmp(arg, shortname) == 0 || strcmp(arg, longname) == 0) { if (*i + 1 >= argc) return -1; *value = argv[++(*i)]; return 1; } size_t longlen = strlen(longname); if (strncmp(arg, longname, longlen) == 0 && arg[longlen] == '=') { *value = arg + longlen + 1; return 1; } return 0; } /* returns an error string if name is not usable as a directory and build * identifier, or NULL when it is fine. */ static const char* validate_name(const char* name) { if (name[0] == '\0') return "project name cannot be empty"; if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) return "project name cannot be . or .."; for (const char* c = name; *c != '\0'; c++) if (!isalnum((unsigned char) *c) && *c != '_' && *c != '-' && *c != '.' && *c != '+') return "project name may only contain letters, digits and _-.+"; return NULL; } /* derive a valid C identifier from name into buf: non-alnum becomes '_', and a * leading digit is prefixed with '_'. */ static void to_identifier(const char* name, char* buf, size_t size) { size_t j = 0; if (isdigit((unsigned char) name[0]) && j + 1 < size) buf[j++] = '_'; for (size_t i = 0; name[i] != '\0' && j + 1 < size; i++) buf[j++] = isalnum((unsigned char) name[i]) ? name[i] : '_'; buf[j] = '\0'; } /* map a compiler binary to a premake/xmake toolset name. */ static const char* toolset_of(const char* compiler) { if (strstr(compiler, "clang") != NULL) return "clang"; if (strstr(compiler, "gcc") != NULL || strstr(compiler, "g++") != NULL) return "gcc"; return "clang"; } /* the build dir ends up in a "rm -rf" clean rule, so it must stay inside the * project: reject empty, absolute and ~ paths, any .. component, and paths * that resolve to the project root itself (., ./, ./., ...). */ static int bin_dir_safe(const char* dir) { if (dir[0] == '\0' || dir[0] == '/' || dir[0] == '~') return 0; int has_real = 0; for (const char* p = dir; *p != '\0'; ) { const char* start = p; while (*p != '\0' && *p != '/') p++; size_t len = (size_t) (p - start); if (len == 2 && start[0] == '.' && start[1] == '.') return 0; if (len != 0 && !(len == 1 && start[0] == '.')) has_real = 1; if (*p == '/') p++; } return has_real; } /* * parse argv into config. returns 0 on success, a negative value when the * program should exit successfully (help/version), or a positive value on a * usage error. */ static int parse_args(int argc, char** argv, struct Config* config) { const char* lang_arg = getenv("MKPROJ_LANG"); const char* std_arg = getenv("MKPROJ_STD"); const char* build_arg = getenv("MKPROJ_BUILD"); const char* cc_arg = getenv("MKPROJ_CC"); const char* kind_arg = getenv("MKPROJ_KIND"); const char* license_arg = getenv("MKPROJ_LICENSE"); const char* bin_arg = NULL; const char* bin_int_arg = NULL; const char* src_arg = NULL; const char* name = NULL; for (int i = 1; i < argc; i++) { const char* arg = argv[i]; if (strcmp(arg, "-h") == 0 || strcmp(arg, "--help") == 0) { print_usage(stdout); return -1; } if (strcmp(arg, "-v") == 0 || strcmp(arg, "--version") == 0) { print_version(); return -1; } if (strcmp(arg, "--completions") == 0) { if (i + 1 >= argc) { error("missing argument for", arg); return 1; } const char* shell = argv[++i]; if (strcmp(shell, "bash") == 0) print_completions_bash(); else if (strcmp(shell, "zsh") == 0) print_completions_zsh(); else if (strcmp(shell, "fish") == 0) print_completions_fish(); else { error("unknown shell (want bash, zsh or fish)", shell); return 1; } return -1; } if (strcmp(arg, "--git") == 0) { config->use_git = 1; continue; } if (strcmp(arg, "--no-root") == 0) { config->use_root = 0; continue; } if (strcmp(arg, "--docker") == 0) { config->use_docker = 1; continue; } if (strcmp(arg, "--style") == 0) { config->use_style = 1; continue; } if (strcmp(arg, "--ci") == 0) { config->use_ci = 1; continue; } if (strcmp(arg, "--single") == 0) { config->use_single = 1; continue; } if (strcmp(arg, "--no-validation") == 0) { config->use_validation = 0; continue; } int matched = 0; matched = opt_value(arg, "-l", "--lang", argc, argv, &i, &lang_arg); if (matched != 0) { if (matched < 0) { error("missing argument for", arg); return 1; } continue; } matched = opt_value(arg, "-s", "--std", argc, argv, &i, &std_arg); if (matched != 0) { if (matched < 0) { error("missing argument for", arg); return 1; } continue; } matched = opt_value(arg, "-b", "--build", argc, argv, &i, &build_arg); if (matched != 0) { if (matched < 0) { error("missing argument for", arg); return 1; } continue; } matched = opt_value(arg, "--cc", "--cc", argc, argv, &i, &cc_arg); if (matched != 0) { if (matched < 0) { error("missing argument for", arg); return 1; } continue; } matched = opt_value(arg, "-k", "--kind", argc, argv, &i, &kind_arg); if (matched != 0) { if (matched < 0) { error("missing argument for", arg); return 1; } continue; } matched = opt_value(arg, "--license", "--license", argc, argv, &i, &license_arg); if (matched != 0) { if (matched < 0) { error("missing argument for", arg); return 1; } continue; } matched = opt_value(arg, "--bin", "--bin", argc, argv, &i, &bin_arg); if (matched != 0) { if (matched < 0) { error("missing argument for", arg); return 1; } continue; } matched = opt_value(arg, "--bin-int", "--bin-int", argc, argv, &i, &bin_int_arg); if (matched != 0) { if (matched < 0) { error("missing argument for", arg); return 1; } config->use_intermediate = 1; continue; } matched = opt_value(arg, "--src", "--src", argc, argv, &i, &src_arg); if (matched != 0) { if (matched < 0) { error("missing argument for", arg); return 1; } config->use_flat = 0; continue; } if (arg[0] == '-' && arg[1] != '\0') { error("unknown option", arg); return 1; } if (name != NULL) { error("unexpected extra argument", arg); return 1; } name = arg; } if (name == NULL) { error("missing project name", NULL); return 1; } /* "." means generate into the current directory, taking the project name * from its basename instead of creating a subdirectory. */ static char here_name[PATH_MAX]; if (strcmp(name, ".") == 0) { char cwd[PATH_MAX]; if (getcwd(cwd, sizeof cwd) == NULL) { error("cannot determine the current directory", NULL); return 1; } const char* base = strrchr(cwd, '/'); (void) snprintf(here_name, sizeof here_name, "%s", base != NULL ? base + 1 : cwd); name = here_name; config->dir = "."; } else { config->dir = name; } const char* name_error = validate_name(name); if (name_error != NULL) { error(name_error, name[0] != '\0' ? name : NULL); return 1; } config->name = name; config->src_dir = src_arg != NULL ? src_arg : "src"; if (lang_arg != NULL && !find_language(lang_arg, &config->language)) { error("unknown language", lang_arg); return 1; } if (build_arg != NULL && !find_build_system(build_arg, &config->build)) { error("unknown build system", build_arg); return 1; } if (!is_c_family(config->language)) { if (std_arg != NULL) { error("this language has no language standard", languages[config->language].name); return 1; } config->standard = NULL; } else if (std_arg != NULL) { if (!valid_standard(config->language, std_arg)) { error("invalid standard for language", std_arg); return 1; } config->standard = std_arg; } else { config->standard = languages[config->language].default_standard; } config->compiler = cc_arg != NULL ? cc_arg : languages[config->language].compiler; if (kind_arg != NULL) { if (strcmp(kind_arg, "exe") == 0) config->kind = kind_exe; else if (strcmp(kind_arg, "lib") == 0) config->kind = kind_lib; else if (strcmp(kind_arg, "shared") == 0) config->kind = kind_shared; else { error("unknown kind (want exe, lib or shared)", kind_arg); return 1; } } if (license_arg != NULL && !find_license(license_arg, &config->license)) { error("unknown license", license_arg); return 1; } if (config->use_intermediate && config->build != build_make && config->build != build_premake) { error("--bin-int only applies to make and premake", build_systems[config->build].key); return 1; } if (config->use_intermediate && (config->language == language_swift || config->language == language_crust)) { error("--bin-int does not apply to", languages[config->language].name); return 1; } if (!is_c_family(config->language) && config->build != build_make) { error("this language only supports make", languages[config->language].name); return 1; } if (!is_c_family(config->language) && config->kind != kind_exe) { error("this language only supports executables", languages[config->language].name); return 1; } if (config->use_docker && config->language != language_c && config->language != language_cpp && config->language != language_nasm) { error("--docker supports only c, cpp and nasm", languages[config->language].key); return 1; } if (config->use_docker && config->build != build_make && config->build != build_cmake && config->build != build_meson) { error("--docker supports only make, cmake and meson", build_systems[config->build].key); return 1; } if (config->use_docker && config->kind != kind_exe) { error("--docker needs an executable, not a library", NULL); return 1; } if (config->use_style && !is_c_family(config->language)) { error("--style (clang-format) supports only c, cpp and objc", languages[config->language].name); return 1; } if (config->use_single && config->build != build_make) { error("--single only applies to make", build_systems[config->build].key); return 1; } if (config->use_single && !is_c_family(config->language)) { error("--single supports only c, cpp and objc", languages[config->language].name); return 1; } if (config->use_single && config->kind != kind_exe) { error("--single needs an executable, not a library", NULL); return 1; } if (bin_arg != NULL && !bin_dir_safe(bin_arg)) { error("--bin must be a path inside the project, not '.', '..' or absolute", bin_arg); return 1; } if (bin_int_arg != NULL && !bin_dir_safe(bin_int_arg)) { error("--bin-int must be a path inside the project, not '.', '..' or absolute", bin_int_arg); return 1; } config->bin_dir = bin_arg != NULL ? bin_arg : build_systems[config->build].default_bin; config->bin_int_dir = bin_int_arg != NULL ? bin_int_arg : build_systems[config->build].default_bin_int; return 0; } /* run argv to completion. returns the exit code, 127 if it could not be * executed, or -1 on a fork/wait failure. */ static int run(char* const argv[], int quiet) { pid_t pid = fork(); if (pid < 0) return -1; if (pid == 0) { if (quiet) { int devnull = open("/dev/null", O_WRONLY); if (devnull >= 0) { (void) dup2(devnull, STDOUT_FILENO); (void) dup2(devnull, STDERR_FILENO); (void) close(devnull); } } (void) execvp(argv[0], argv); _exit(127); } int status = 0; if (waitpid(pid, &status, 0) < 0) return -1; if (WIFEXITED(status)) return WEXITSTATUS(status); return -1; } static int git_init(const char* root) { char* const argv[] = { "git", "-C", (char*) root, "init", NULL }; return run(argv, 1); } static const char* main_source(const struct Config* config) { if (config->language == language_nasm) { if (config->use_docker) return " global _start\n" "\n" " section .rodata\n" "msg: db \"type shi\", 10\n" "msg.len equ $ - msg\n" "\n" " section .text\n" "_start:\n" " mov rax, 1 ; write\n" " mov rdi, 1 ; stdout\n" " lea rsi, [rel msg]\n" " mov rdx, msg.len\n" " syscall\n" "\n" " mov rax, 60 ; exit\n" " xor edi, edi\n" " syscall\n"; return " default rel\n" "\n" " global _main\n" " extern _printf\n" "\n" " section .text\n" "_main:\n" " push rbp\n" " mov rbp, rsp\n" " lea rdi, [msg]\n" " xor eax, eax\n" " call _printf\n" " xor eax, eax\n" " pop rbp\n" " ret\n" "\n" " section .data\n" "msg: db \"type shi\", 10, 0\n"; } if (config->language == language_swift) return "print(\"type shi\")\n"; if (config->language == language_crust) return "fn main()\n" "{\n" " println!(\"type shi\");\n" "}\n"; if (config->language == language_objc) return "#import \n" "\n" "int main(void)\n" "{\n" " @autoreleasepool\n" " {\n" " (void)NSLog(@\"type shi\");\n" " }\n" "}\n"; if (config->language == language_cpp) { const char* std = config->standard; if (strcmp(std, "c++23") == 0 || strcmp(std, "c++26") == 0) return "#include \n" "\n" "auto main() -> int\n" "{\n" " std::println(\"type shi\");\n" "}\n"; if (strcmp(std, "c++98") == 0 || strcmp(std, "c++03") == 0) return "#include \n" "\n" "int main()\n" "{\n" " std::cout << \"type shi\\n\";\n" "}\n"; return "#include \n" "\n" "auto main() -> int\n" "{\n" " std::cout << \"type shi\\n\";\n" "}\n"; } return "#include \n" "\n" "int main(void)\n" "{\n" " (void)puts(\"type shi\");\n" "}\n"; } static void write_main(FILE* out, const struct Config* config) { (void) fputs(main_source(config), out); } static void write_lib_header(FILE* out, const struct Config* config) { char ident[256]; to_identifier(config->name, ident, sizeof ident); (void) fputs("#pragma once\n\n", out); if (config->language == language_cpp) (void) fprintf(out, "auto %s_answer() -> int;\n", ident); else (void) fprintf(out, "int %s_answer(void);\n", ident); } static void write_lib_source(FILE* out, const struct Config* config) { char ident[256]; to_identifier(config->name, ident, sizeof ident); const char* include = config->language == language_objc ? "#import" : "#include"; (void) fprintf(out, "%s \"%s.h\"\n\n", include, config->name); if (config->language == language_cpp) (void) fprintf(out, "auto %s_answer() -> int\n{\n return 42;\n}\n", ident); else (void) fprintf(out, "int %s_answer(void)\n{\n return 42;\n}\n", ident); } /* fill flags with the shared warning + debug flags and return the count. * every generator reuses these so all four build systems compile alike. */ static size_t base_warnings(const struct Config* config, const char* flags[]) { size_t count = 0; flags[count++] = "-Wall"; flags[count++] = "-Wextra"; flags[count++] = "-Wshadow"; flags[count++] = "-Wpedantic"; flags[count++] = "-Wconversion"; if (config->language != language_cpp) flags[count++] = "-Wstrict-prototypes"; flags[count++] = "-Wsign-conversion"; if (config->language != language_cpp) flags[count++] = "-Wmissing-prototypes"; return count; } static size_t base_flags(const struct Config* config, const char* flags[]) { size_t count = base_warnings(config, flags); flags[count++] = "-g"; flags[count++] = "-fno-omit-frame-pointer"; return count; } static const char* cmake_language(enum Language language) { if (language == language_cpp) return "CXX"; if (language == language_objc) return "OBJC"; return "C"; } /* nasm is its own thing: assemble each .asm with nasm, then link with cc. no * -std, no warning flags, no sanitizers. macho64 is the macOS object format. */ static void write_makefile_nasm(FILE* out, const struct Config* config) { const char* obj_dir = config->use_intermediate ? config->bin_int_dir : config->bin_dir; char clean[3 * PATH_MAX + 16]; if (config->use_intermediate) (void) snprintf(clean, sizeof clean, "rm -rf %s %s", config->bin_dir, config->bin_int_dir); else (void) snprintf(clean, sizeof clean, "rm -rf %s", config->bin_dir); if (config->use_root) { size_t n = strlen(clean); (void) snprintf(clean + n, sizeof clean - n, " %s", config->name); } char target[2 * PATH_MAX]; if (config->use_root) (void) snprintf(target, sizeof target, "%s", config->name); else (void) snprintf(target, sizeof target, "%s/%s", config->bin_dir, config->name); const char* format = config->use_docker ? "elf64" : "macho64"; const char* ld = config->use_docker ? "ld" : "cc"; const char* ldflags = config->use_docker ? "" : "-arch x86_64"; (void) fprintf( out, "AS := nasm\n" "LD := %s\n" "\n" "DEBUG ?= 1\n" "\n" "ASFLAGS := -f %s\n" "LDFLAGS := %s\n" "\n" "ifeq ($(DEBUG),1)\n" "ASFLAGS += -g -F dwarf\n" "endif\n" "\n" "TARGET := %s\n", ld, format, ldflags, target); if (config->use_flat) (void) fprintf(out, "SRC := $(wildcard *.asm)\nOBJ := $(SRC:%%=%s/%%.o)\n", obj_dir); else (void) fprintf(out, "SRC := $(shell find %s -name '*.asm')\nOBJ := $(SRC:%s/%%=%s/%%.o)\n", config->src_dir, config->src_dir, obj_dir); (void) fprintf( out, "\n" "all: $(TARGET)\n" "\n" "$(TARGET): $(OBJ)\n" "\t@mkdir -p $(@D)\n" "\t$(LD) $^ -o $@ $(LDFLAGS)\n" "\n"); if (config->use_flat) (void) fprintf(out, "%s/%%.asm.o: %%.asm\n", obj_dir); else (void) fprintf(out, "%s/%%.asm.o: %s/%%.asm\n", obj_dir, config->src_dir); (void) fprintf( out, "\t@mkdir -p $(@D)\n" "\t$(AS) $(ASFLAGS) $< -o $@\n" "\n" "run: $(TARGET)\n" "\t./$(TARGET)\n" "\n" "clean:\n" "\t%s\n" "\n" ".PHONY: all run clean\n", clean); } /* swift compiles the whole module in one shot: no per-file objects, no -std, * no warning flags. asan is available through swiftc's own -sanitize. */ static void write_makefile_swift(FILE* out, const struct Config* config) { char target[2 * PATH_MAX]; if (config->use_root) (void) snprintf(target, sizeof target, "%s", config->name); else (void) snprintf(target, sizeof target, "%s/%s", config->bin_dir, config->name); char clean[2 * PATH_MAX + 16]; if (config->use_root) (void) snprintf(clean, sizeof clean, "rm -rf %s %s", config->bin_dir, config->name); else (void) snprintf(clean, sizeof clean, "rm -rf %s", config->bin_dir); (void) fprintf(out, "SWIFTC := %s\n\nDEBUG ?= 1\n", config->compiler); if (config->use_validation) (void) fprintf(out, "SANITIZE ?= 1\n"); (void) fprintf( out, "\n" "SWIFTFLAGS :=\n" "\n" "ifeq ($(DEBUG),1)\n" "SWIFTFLAGS += -g -Onone\n" "else\n" "SWIFTFLAGS += -O\n" "endif\n"); if (config->use_validation) (void) fprintf( out, "\n" "ifeq ($(SANITIZE),1)\n" "SWIFTFLAGS += -sanitize=address\n" "endif\n"); (void) fprintf(out, "\nTARGET := %s\n", target); if (config->use_flat) (void) fprintf(out, "SRC := $(wildcard *.swift)\n"); else (void) fprintf(out, "SRC := $(shell find %s -name '*.swift')\n", config->src_dir); (void) fprintf( out, "\n" "all: $(TARGET)\n" "\n" "$(TARGET): $(SRC)\n" "\t@mkdir -p $(@D)\n" "\t$(SWIFTC) $(SWIFTFLAGS) $^ -o $@\n" "\n" "run: $(TARGET)\n" "\t./$(TARGET)\n" "\n" "clean:\n" "\t%s\n" "\n" ".PHONY: all run clean\n", clean); } /* crust is rust driven straight through rustc from the crate root, no cargo. * rustc pulls in the other modules itself, so only the crate root is compiled; * $(SRC) exists just to retrigger the build when any source changes. */ static void write_makefile_crust(FILE* out, const struct Config* config) { char target[2 * PATH_MAX]; if (config->use_root) (void) snprintf(target, sizeof target, "%s", config->name); else (void) snprintf(target, sizeof target, "%s/%s", config->bin_dir, config->name); char clean[2 * PATH_MAX + 16]; if (config->use_root) (void) snprintf(clean, sizeof clean, "rm -rf %s %s", config->bin_dir, config->name); else (void) snprintf(clean, sizeof clean, "rm -rf %s", config->bin_dir); char crate[PATH_MAX]; if (config->use_flat) (void) snprintf(crate, sizeof crate, "main.rs"); else (void) snprintf(crate, sizeof crate, "%s/main.rs", config->src_dir); (void) fprintf( out, "RUSTC := %s\n" "\n" "DEBUG ?= 1\n" "\n" "RUSTFLAGS :=\n" "\n" "ifeq ($(DEBUG),1)\n" "RUSTFLAGS += -g\n" "else\n" "RUSTFLAGS += -O\n" "endif\n" "\n" "TARGET := %s\n" "CRATE := %s\n", config->compiler, target, crate); if (config->use_flat) (void) fprintf(out, "SRC := $(wildcard *.rs)\n"); else (void) fprintf(out, "SRC := $(shell find %s -name '*.rs')\n", config->src_dir); (void) fprintf( out, "\n" "all: $(TARGET)\n" "\n" "$(TARGET): $(SRC)\n" "\t@mkdir -p $(@D)\n" "\t$(RUSTC) $(RUSTFLAGS) $(CRATE) -o $@\n" "\n" "run: $(TARGET)\n" "\t./$(TARGET)\n" "\n" "clean:\n" "\t%s\n" "\n" ".PHONY: all run clean\n", clean); } static void write_makefile(FILE* out, const struct Config* config) { if (config->language == language_nasm) { write_makefile_nasm(out, config); return; } if (config->language == language_swift) { write_makefile_swift(out, config); return; } if (config->language == language_crust) { write_makefile_crust(out, config); return; } const struct Language_Info* lang = &languages[config->language]; const char* ext = lang->extension; const char* obj_dir = config->use_intermediate ? config->bin_int_dir : config->bin_dir; char target_name[PATH_MAX]; if (config->kind == kind_lib) (void) snprintf(target_name, sizeof target_name, "lib%s.a", config->name); else if (config->kind == kind_shared) (void) snprintf(target_name, sizeof target_name, "lib%s.$(SOEXT)", config->name); else (void) snprintf(target_name, sizeof target_name, "%s", config->name); char target[2 * PATH_MAX]; if (config->use_single || config->use_root) (void) snprintf(target, sizeof target, "%s", target_name); else (void) snprintf(target, sizeof target, "%s/%s", config->bin_dir, target_name); char clean[3 * PATH_MAX + 16]; if (config->use_single) (void) snprintf(clean, sizeof clean, "rm -f %s", target_name); else if (config->use_intermediate) (void) snprintf(clean, sizeof clean, "rm -rf %s %s", config->bin_dir, config->bin_int_dir); else (void) snprintf(clean, sizeof clean, "rm -rf %s", config->bin_dir); if (!config->use_single && config->use_root) { size_t n = strlen(clean); (void) snprintf(clean + n, sizeof clean - n, " %s", target_name); } const char* flags[16]; size_t count = 0; char include[PATH_MAX + 2]; (void) snprintf(include, sizeof include, "-I%s", config->use_flat ? "." : config->src_dir); flags[count++] = "-std=$(STD)"; count += base_warnings(config, flags + count); flags[count++] = include; int width = 0; for (size_t i = 0; i < count; i++) if ((int) strlen(flags[i]) > width) width = (int) strlen(flags[i]); int sanitize = config->use_validation && config->kind == kind_exe; (void) fprintf(out, "CC := %s\nSTD := %s\n\nDEBUG ?= 1\n", config->compiler, config->standard); if (sanitize) (void) fprintf(out, "SANITIZE ?= 1\n"); (void) fprintf(out, "\nCFLAGS := "); for (size_t i = 0; i < count; i++) { if (i > 0) (void) fprintf(out, " "); if (i < count - 1) (void) fprintf(out, "%-*s \\\n", width, flags[i]); else (void) fprintf(out, "%s\n", flags[i]); } (void) fprintf( out, "\n" "ifeq ($(DEBUG),1)\n" "CFLAGS += -g -fno-omit-frame-pointer\n" "else\n" "CFLAGS += -O2\n" "endif\n"); if (sanitize) (void) fprintf( out, "\n" "ifeq ($(SANITIZE),1)\n" "CFLAGS += -fsanitize=address,undefined\n" "LDFLAGS += -fsanitize=address,undefined\n" "endif\n"); if (config->language == language_objc && config->kind == kind_exe) (void) fprintf(out, "\nLDFLAGS += -framework Foundation\n"); if (config->kind == kind_shared) (void) fprintf( out, "\n" "CFLAGS += -fPIC\n" "\n" "UNAME := $(shell uname)\n" "ifeq ($(UNAME),Darwin)\n" "SOEXT := dylib\n" "SOFLAGS := -dynamiclib\n" "else\n" "SOEXT := so\n" "SOFLAGS := -shared\n" "endif\n"); (void) fprintf(out, "\nTARGET := %s\n", target); if (config->use_single) { if (config->use_flat) (void) fprintf(out, "SRC := $(wildcard *.%s)\n", ext); else (void) fprintf(out, "SRC := $(shell find %s -name '*.%s')\n", config->src_dir, ext); (void) fprintf( out, "\n" "all: $(TARGET)\n" "\n" "$(TARGET): $(SRC)\n" "\t$(CC) $(CFLAGS) $(SRC) -o $@ $(LDFLAGS)\n" "\n"); } else { if (config->use_flat) (void) fprintf(out, "SRC := $(wildcard *.%s)\nOBJ := $(SRC:%%=%s/%%.o)\n", ext, obj_dir); else (void) fprintf(out, "SRC := $(shell find %s -name '*.%s')\nOBJ := $(SRC:%s/%%=%s/%%.o)\n", config->src_dir, ext, config->src_dir, obj_dir); (void) fprintf( out, "\n" "all: $(TARGET)\n" "\n" "$(TARGET): $(OBJ)\n" "\t@mkdir -p $(@D)\n"); if (config->kind == kind_lib) (void) fprintf(out, "\t$(AR) rcs $@ $^\n\n"); else if (config->kind == kind_shared) (void) fprintf(out, "\t$(CC) $(SOFLAGS) $^ -o $@ $(LDFLAGS)\n\n"); else (void) fprintf(out, "\t$(CC) $^ -o $@ $(LDFLAGS)\n\n"); if (config->use_flat) (void) fprintf(out, "%s/%%.%s.o: %%.%s\n", obj_dir, ext, ext); else (void) fprintf(out, "%s/%%.%s.o: %s/%%.%s\n", obj_dir, ext, config->src_dir, ext); (void) fprintf( out, "\t@mkdir -p $(@D)\n" "\t$(CC) $(CFLAGS) -c $< -o $@\n" "\n"); } if (config->use_validation) (void) fprintf( out, "check:\n" "\tbear -- make clean all\n" "\tcppcheck --enable=warning,style,performance,portability \\\n" "\t\t --project=compile_commands.json \\\n" "\t\t --error-exitcode=1\n" "\n"); if (config->kind == kind_exe) (void) fprintf(out, "run: $(TARGET)\n\t./$(TARGET)\n\n"); (void) fprintf( out, "clean:\n" "\t%s\n" "\n" ".PHONY: all%s clean%s\n", clean, config->use_validation ? " check" : "", config->kind == kind_exe ? " run" : ""); } static void write_cmake(FILE* out, const struct Config* config) { const char* name = config->name; const char* ext = languages[config->language].extension; const char* flags[10]; size_t count = base_flags(config, flags); int sanitize = config->kind == kind_exe; (void) fprintf( out, "cmake_minimum_required(VERSION 3.16)\n" "\n" "project(%s %s)\n" "\n", name, cmake_language(config->language)); if (sanitize) (void) fprintf(out, "option(SANITIZE \"build with asan + ubsan\" ON)\n\n"); if (config->use_flat) (void) fprintf(out, "file(GLOB SOURCES CONFIGURE_DEPENDS *.%s)\n", ext); else (void) fprintf(out, "file(GLOB_RECURSE SOURCES CONFIGURE_DEPENDS %s/*.%s)\n", config->src_dir, ext); if (config->kind == kind_lib) (void) fprintf(out, "\nadd_library(%s STATIC ${SOURCES})\n", name); else if (config->kind == kind_shared) (void) fprintf(out, "\nadd_library(%s SHARED ${SOURCES})\n", name); else (void) fprintf(out, "\nadd_executable(%s ${SOURCES})\n", name); (void) fprintf( out, "\n" "target_include_directories(%s PRIVATE %s)\n" "\n" "target_compile_options(%s PRIVATE\n", name, config->use_flat ? "." : config->src_dir, name); for (size_t i = 0; i < count; i++) (void) fprintf(out, " %s\n", flags[i]); (void) fprintf(out, " -std=%s)\n", config->standard); if (config->language == language_objc && config->kind == kind_exe) (void) fprintf( out, "\n" "target_link_libraries(%s PRIVATE \"-framework Foundation\")\n", name); if (sanitize) (void) fprintf( out, "\n" "if(SANITIZE)\n" " target_compile_options(%s PRIVATE -fsanitize=address,undefined)\n" " target_link_options(%s PRIVATE -fsanitize=address,undefined)\n" "endif()\n", name, name); } static const char* meson_language(enum Language language) { if (language == language_cpp) return "cpp"; if (language == language_objc) return "objc"; return "c"; } static void write_meson(FILE* out, const struct Config* config) { const char* name = config->name; const char* ext = languages[config->language].extension; const char* lang = meson_language(config->language); const char* flags[10]; size_t count = base_flags(config, flags); if (config->kind == kind_exe) (void) fprintf( out, "project('%s', '%s',\n" " default_options: [\n" " 'b_sanitize=address,undefined',\n" " 'b_lundef=false',\n" " ])\n" "\n", name, lang); else (void) fprintf(out, "project('%s', '%s')\n\n", name, lang); if (config->use_flat) (void) fprintf( out, "sources = run_command(\n" " 'find', '.', '-maxdepth', '1', '-name', '*.%s',\n" " check: true).stdout().strip().split('\\n')\n" "\n", ext); else (void) fprintf( out, "sources = run_command(\n" " 'find', '%s', '-name', '*.%s',\n" " check: true).stdout().strip().split('\\n')\n" "\n", config->src_dir, ext); (void) fprintf(out, "add_project_arguments(\n"); for (size_t i = 0; i < count; i++) (void) fprintf(out, " '%s',\n", flags[i]); (void) fprintf( out, " '-std=%s',\n" " language: '%s')\n" "\n", config->standard, lang); int link_foundation = config->language == language_objc && config->kind == kind_exe; if (!config->use_flat) (void) fprintf(out, "inc = include_directories('%s')\n\n", config->src_dir); if (link_foundation) (void) fprintf(out, "foundation = dependency('appleframeworks', modules: ['Foundation'])\n\n"); if (config->kind == kind_lib) (void) fprintf(out, "static_library('%s', sources", name); else if (config->kind == kind_shared) (void) fprintf(out, "shared_library('%s', sources", name); else (void) fprintf(out, "executable('%s', sources", name); if (!config->use_flat) (void) fprintf(out, ",\n include_directories: inc"); if (link_foundation) (void) fprintf(out, ",\n dependencies: foundation"); (void) fprintf(out, ")\n"); } static const char* premake_language(enum Language language) { if (language == language_cpp) return "C++"; return "C"; } static void write_premake(FILE* out, const struct Config* config) { const char* name = config->name; const char* ext = languages[config->language].extension; const char* obj_dir = config->use_intermediate ? config->bin_int_dir : config->bin_dir; const char* flags[10]; size_t count = base_flags(config, flags); const char* pkind = config->kind == kind_lib ? "StaticLib" : config->kind == kind_shared ? "SharedLib" : "ConsoleApp"; (void) fprintf( out, "workspace \"%s\"\n" " configurations { \"debug\" }\n" "\n" "project \"%s\"\n" " kind \"%s\"\n" " language \"%s\"\n" " toolset \"%s\"\n" "\n" " targetdir \"%s\"\n" " targetname \"%s\"\n" " objdir \"%s\"\n" "\n", name, name, pkind, premake_language(config->language), toolset_of(config->compiler), config->use_root ? "." : config->bin_dir, name, obj_dir); if (config->use_flat) (void) fprintf(out, " files { \"*.%s\" }\n includedirs { \".\" }\n", ext); else (void) fprintf(out, " files { \"%s/**.%s\" }\n includedirs { \"%s\" }\n", config->src_dir, ext, config->src_dir); (void) fprintf(out, "\n buildoptions {\n"); for (size_t i = 0; i < count; i++) (void) fprintf(out, " \"%s\",\n", flags[i]); (void) fprintf( out, " \"-std=%s\",\n" " \"-fsanitize=address,undefined\",\n" " }\n" "\n" " linkoptions { \"-fsanitize=address,undefined\" }\n", config->standard); if (config->language == language_objc && config->kind == kind_exe) (void) fputs( "\n" " links { \"Foundation.framework\" }\n", out); } static const char* xmake_flags(enum Language language) { if (language == language_cpp) return "add_cxxflags"; if (language == language_objc) return "add_mflags"; return "add_cflags"; } static void write_xmake(FILE* out, const struct Config* config) { const char* name = config->name; const char* ext = languages[config->language].extension; const char* flag_fn = xmake_flags(config->language); const char* flags[10]; size_t count = base_flags(config, flags); (void) fprintf( out, "set_config(\"builddir\", \"%s\")\n" "\n" "set_toolchains(\"%s\")\n" "\n" "target(\"%s\")\n" " set_kind(\"%s\")\n", config->bin_dir, toolset_of(config->compiler), name, config->kind == kind_lib ? "static" : config->kind == kind_shared ? "shared" : "binary"); if (config->use_flat) (void) fprintf(out, " add_files(\"*.%s\")\n add_includedirs(\".\")\n", ext); else (void) fprintf(out, " add_files(\"%s/**.%s\")\n add_includedirs(\"%s\")\n", config->src_dir, ext, config->src_dir); (void) fprintf(out, "\n %s(\n", flag_fn); for (size_t i = 0; i < count; i++) (void) fprintf(out, " \"%s\",\n", flags[i]); if (config->kind == kind_exe) (void) fprintf( out, " \"-std=%s\",\n" " \"-fsanitize=address,undefined\")\n" "\n" " add_ldflags(\"-fsanitize=address,undefined\")\n", config->standard); else (void) fprintf(out, " \"-std=%s\")\n", config->standard); if (config->language == language_objc && config->kind == kind_exe) (void) fputs("\n add_frameworks(\"Foundation\")\n", out); } /* best-effort copyright holder: git's configured name, else $USER. */ static void get_author(char* buf, size_t size) { buf[0] = '\0'; FILE* pipe = popen("git config user.name", "r"); if (pipe != NULL) { if (fgets(buf, (int) size, pipe) != NULL) { size_t len = strlen(buf); if (len > 0 && buf[len - 1] == '\n') buf[len - 1] = '\0'; } (void) pclose(pipe); } if (buf[0] == '\0') { const char* user = getenv("USER"); (void) snprintf(buf, size, "%s", user != NULL ? user : "unknown"); } } static int current_year(void) { time_t now = time(NULL); struct tm* local = localtime(&now); return local != NULL ? local->tm_year + 1900 : 1970; } static void write_license(FILE* out, const struct Config* config) { char author[256]; int year = current_year(); get_author(author, sizeof author); switch (config->license) { case license_mit: (void) fprintf(out, "MIT License\n\n" "Copyright (c) %d %s\n\n" "Permission is hereby granted, free of charge, to any person obtaining a copy\n" "of this software and associated documentation files (the \"Software\"), to deal\n" "in the Software without restriction, including without limitation the rights\n" "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n" "copies of the Software, and to permit persons to whom the Software is\n" "furnished to do so, subject to the following conditions:\n\n" "The above copyright notice and this permission notice shall be included in all\n" "copies or substantial portions of the Software.\n\n" "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n" "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n" "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n" "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n" "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n" "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n" "SOFTWARE.\n", year, author); break; case license_isc: (void) fprintf(out, "ISC License\n\n" "Copyright (c) %d %s\n\n" "Permission to use, copy, modify, and/or distribute this software for any\n" "purpose with or without fee is hereby granted, provided that the above\n" "copyright notice and this permission notice appear in all copies.\n\n" "THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n" "REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n" "AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n" "INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n" "LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n" "OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n" "PERFORMANCE OF THIS SOFTWARE.\n", year, author); break; case license_bsd2: case license_bsd3: (void) fprintf(out, "BSD %s License\n\n" "Copyright (c) %d %s\n\n" "Redistribution and use in source and binary forms, with or without\n" "modification, are permitted provided that the following conditions are met:\n\n" "1. Redistributions of source code must retain the above copyright notice, this\n" " list of conditions and the following disclaimer.\n\n" "2. Redistributions in binary form must reproduce the above copyright notice,\n" " this list of conditions and the following disclaimer in the documentation\n" " and/or other materials provided with the distribution.\n\n", config->license == license_bsd3 ? "3-Clause" : "2-Clause", year, author); if (config->license == license_bsd3) (void) fputs( "3. Neither the name of the copyright holder nor the names of its\n" " contributors may be used to endorse or promote products derived from\n" " this software without specific prior written permission.\n\n", out); (void) fputs( "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n" "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n" "DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n" "FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n" "DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n" "SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n" "CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n" "OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n" "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n", out); break; case license_unlicense: (void) fputs( "This is free and unencumbered software released into the public domain.\n\n" "Anyone is free to copy, modify, publish, use, compile, sell, or distribute\n" "this software, either in source code form or as a compiled binary, for any\n" "purpose, commercial or non-commercial, and by any means.\n\n" "In jurisdictions that recognize copyright laws, the author or authors of this\n" "software dedicate any and all copyright interest in the software to the public\n" "domain. We make this dedication for the benefit of the public at large and to\n" "the detriment of our heirs and successors. We intend this dedication to be an\n" "overt act of relinquishment in perpetuity of all present and future rights to\n" "this software under copyright law.\n\n" "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n" "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n" "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n" "AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n" "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n" "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n" "For more information, please refer to \n", out); break; default: break; } } /* a minimal GitHub Actions workflow that builds the project. objc, swift and * nasm run on macOS; everything else on Linux. build only: the C 'make check' * needs bear and cppcheck, which we do not drag into CI. */ static void write_ci(FILE* out, const struct Config* config) { int apple = config->language == language_objc || config->language == language_swift || config->language == language_nasm; const char* runner = apple ? "macos-latest" : "ubuntu-latest"; (void) fprintf( out, "name: ci\n" "\n" "on:\n" " push:\n" " pull_request:\n" "\n" "jobs:\n" " build:\n" " runs-on: %s\n" " steps:\n" " - uses: actions/checkout@v4\n", runner); /* extra toolchain the runner does not already ship. */ if (config->language == language_nasm) (void) fputs(" - run: brew install nasm\n", out); switch (config->build) { case build_meson: if (apple) (void) fputs(" - run: brew install meson ninja\n", out); else (void) fputs(" - run: sudo apt-get update && sudo apt-get install -y meson ninja-build\n", out); break; case build_premake: (void) fputs(" - uses: abel0b/setup-premake@v2.4\n", out); break; case build_xmake: (void) fputs(" - uses: xmake-io/github-action-setup-xmake@v1\n", out); break; default: break; } switch (config->build) { case build_cmake: (void) fprintf(out, " - run: cmake -B %s && cmake --build %s\n", config->bin_dir, config->bin_dir); break; case build_meson: (void) fprintf(out, " - run: meson setup %s && meson compile -C %s\n", config->bin_dir, config->bin_dir); break; case build_premake: (void) fputs(" - run: premake5 gmake2 && make\n", out); break; case build_xmake: (void) fputs(" - run: xmake -y\n", out); break; default: (void) fputs(" - run: make\n", out); break; } } /* a single-stage Dockerfile that installs the toolchain, builds a release * (no sanitizers), and runs the binary. c/cpp with make, cmake or meson. */ static void write_dockerfile(FILE* out, const struct Config* config) { /* make and premake honour --root and drop the binary at the project root; * cmake and meson always keep it inside their build directory. */ int at_root = config->use_root && (config->build == build_make || config->build == build_premake); char run_path[2 * PATH_MAX]; if (at_root) (void) snprintf(run_path, sizeof run_path, "./%s", config->name); else (void) snprintf(run_path, sizeof run_path, "./%s/%s", config->bin_dir, config->name); if (config->language == language_nasm) { (void) fprintf( out, "FROM --platform=linux/amd64 debian:stable-slim\n" "\n" "RUN apt-get update \\\n" " && apt-get install -y --no-install-recommends nasm binutils make \\\n" " && rm -rf /var/lib/apt/lists/*\n" "\n" "WORKDIR /app\n" "COPY . .\n" "\n" "RUN make\n" "\n" "CMD [\"%s\"]\n", run_path); return; } const char* tools; char build[2 * PATH_MAX]; switch (config->build) { case build_cmake: tools = "make cmake"; (void) snprintf(build, sizeof build, "cmake -B %s -DSANITIZE=OFF && cmake --build %s", config->bin_dir, config->bin_dir); break; case build_meson: tools = "meson ninja-build"; (void) snprintf(build, sizeof build, "meson setup %s -Db_sanitize=none && meson compile -C %s", config->bin_dir, config->bin_dir); break; default: tools = "make"; (void) snprintf(build, sizeof build, "make DEBUG=0 SANITIZE=0"); break; } char packages[128]; (void) snprintf(packages, sizeof packages, "clang %s%s", tools, config->language == language_cpp ? " libstdc++-dev" : ""); (void) fprintf( out, "FROM debian:stable-slim\n" "\n" "RUN apt-get update \\\n" " && apt-get install -y --no-install-recommends %s \\\n" " && rm -rf /var/lib/apt/lists/*\n" "\n" "ENV CC=clang CXX=clang++\n" "\n" "WORKDIR /app\n" "COPY . .\n" "\n" "RUN %s\n" "\n" "CMD [\"%s\"]\n", packages, build, run_path); } static void write_dockerignore(FILE* out, const struct Config* config) { (void) fprintf(out, ".git\n%s/\n", config->bin_dir); if (config->use_intermediate && strcmp(config->bin_int_dir, config->bin_dir) != 0) (void) fprintf(out, "%s/\n", config->bin_int_dir); } /* clang-format matching the house style guide (hachem.wtf/blabbing/style-guide). */ static void write_clang_format(FILE* out, const struct Config* config) { (void) fprintf(out, "Language: %s\n", config->language == language_objc ? "ObjC" : "Cpp"); (void) fputs( "BreakBeforeBraces: Allman\n" "PointerAlignment: Left\n" "AllowShortFunctionsOnASingleLine: None\n" "AllowShortIfStatementsOnASingleLine: Never\n" "AllowShortLoopsOnASingleLine: false\n" "AllowShortBlocksOnASingleLine: Never\n" "SpaceBeforeParens: ControlStatements\n" "IndentCaseLabels: false\n" "IndentWidth: 4\n" "ContinuationIndentWidth: 8\n" "ColumnLimit: 100\n" "UseTab: Never\n" "AlignConsecutiveDeclarations: false\n", out); } static void write_editorconfig(FILE* out, const struct Config* config) { (void) config; (void) fputs( "root = true\n" "\n" "[*]\n" "charset = utf-8\n" "end_of_line = lf\n" "insert_final_newline = true\n" "trim_trailing_whitespace = true\n" "\n" "[*.{c,h,cpp,hpp,cc,m}]\n" "indent_style = space\n" "indent_size = 4\n" "max_line_length = 100\n", out); } static void write_gitignore(FILE* out, const struct Config* config) { (void) fprintf(out, "%s/\n", config->bin_dir); if (config->use_root) { if (config->kind == kind_lib) (void) fprintf(out, "/lib%s.a\n", config->name); else if (config->kind == kind_shared) (void) fprintf(out, "/lib%s.so\n/lib%s.dylib\n", config->name, config->name); else (void) fprintf(out, "/%s\n", config->name); } if (config->use_intermediate && (config->build == build_make || config->build == build_premake) && strcmp(config->bin_int_dir, config->bin_dir) != 0) (void) fprintf(out, "%s/\n", config->bin_int_dir); if (config->build == build_premake) (void) fputs("Makefile\n*.make\n", out); if (config->build == build_xmake) (void) fputs(".xmake/\n", out); if (is_c_family(config->language)) (void) fputs("\ncompile_commands.json\n", out); } /* open path, hand the stream to writer, close. returns 0 on success. */ static int emit(const char* path, const struct Config* config, void (*writer)(FILE*, const struct Config*)) { FILE* file = fopen(path, "w"); if (file == NULL) { error("cannot create file", path); return -1; } writer(file, config); if (fclose(file) != 0) { error("cannot write file", path); return -1; } return 0; } static int make_dir(const char* path) { if (mkdir(path, 0755) == 0) return 0; if (errno == EEXIST) error("already exists", path); else error("cannot create directory", path); return -1; } /* like make_dir but fine with the directory already being there; for nested * output dirs such as .github/workflows that we do not own outright. */ static int ensure_dir(const char* path) { if (mkdir(path, 0755) == 0 || errno == EEXIST) return 0; error("cannot create directory", path); return -1; } static void print_next_steps(const struct Config* config) { if (config->standard != NULL) (void) printf("\ncreated %s (%s, %s, %s)\n\n", config->name, languages[config->language].name, config->standard, build_systems[config->build].name); else (void) printf("\ncreated %s (%s, %s)\n\n", config->name, languages[config->language].name, build_systems[config->build].name); if (strcmp(config->dir, ".") != 0) (void) printf(" cd %s\n", config->name); if (config->use_docker) { (void) printf(" docker build -t %s .\n", config->name); (void) printf(" docker run --rm %s\n", config->name); (void) printf("\n"); return; } switch (config->build) { case build_make: (void) printf(" make\n"); if (config->kind == kind_exe) (void) printf(" make run\n"); else if (is_c_family(config->language)) (void) printf(" make check\n"); break; case build_cmake: (void) printf(" cmake -B %s\n", config->bin_dir); (void) printf(" cmake --build %s\n", config->bin_dir); break; case build_meson: (void) printf(" meson setup %s\n", config->bin_dir); (void) printf(" meson compile -C %s\n", config->bin_dir); break; case build_premake: (void) printf(" premake5 gmake2\n"); (void) printf(" make\n"); break; case build_xmake: (void) printf(" xmake\n"); if (config->kind == kind_exe) (void) printf(" xmake run\n"); break; default: break; } (void) printf("\n"); } static int generate_project(const struct Config* config) { char path[PATH_MAX]; const char* build_file; void (*write_build)(FILE*, const struct Config*); switch (config->build) { case build_make: build_file = "Makefile"; write_build = write_makefile; break; case build_cmake: build_file = "CMakeLists.txt"; write_build = write_cmake; break; case build_meson: build_file = "meson.build"; write_build = write_meson; break; case build_premake: build_file = "premake5.lua"; write_build = write_premake; break; case build_xmake: build_file = "xmake.lua"; write_build = write_xmake; break; default: error("unknown build system", NULL); return -1; } const char* ext = languages[config->language].extension; const char* dir = config->dir; int in_place = strcmp(dir, ".") == 0; char srcdir[PATH_MAX]; /* generating in place: refuse to clobber an existing build file. */ if (in_place && access(build_file, F_OK) == 0) { error("refusing to overwrite existing", build_file); return -1; } if (!in_place && make_dir(dir) != 0) return -1; if (config->use_flat) { (void) snprintf(srcdir, sizeof srcdir, "%s", dir); } else { (void) snprintf(srcdir, sizeof srcdir, "%s/%s", dir, config->src_dir); if (make_dir(srcdir) != 0) return -1; } if (config->kind != kind_exe) { (void) snprintf(path, sizeof path, "%s/%s.h", srcdir, config->name); if (emit(path, config, write_lib_header) != 0) return -1; (void) snprintf(path, sizeof path, "%s/%s.%s", srcdir, config->name, ext); if (emit(path, config, write_lib_source) != 0) return -1; } else { (void) snprintf(path, sizeof path, "%s/main.%s", srcdir, ext); if (emit(path, config, write_main) != 0) return -1; } (void) snprintf(path, sizeof path, "%s/%s", dir, build_file); if (emit(path, config, write_build) != 0) return -1; if (config->use_git) { (void) snprintf(path, sizeof path, "%s/.gitignore", dir); if (emit(path, config, write_gitignore) != 0) return -1; } if (config->license != license_none) { (void) snprintf(path, sizeof path, "%s/LICENSE", dir); if (emit(path, config, write_license) != 0) return -1; } if (config->use_docker) { (void) snprintf(path, sizeof path, "%s/Dockerfile", dir); if (emit(path, config, write_dockerfile) != 0) return -1; (void) snprintf(path, sizeof path, "%s/.dockerignore", dir); if (emit(path, config, write_dockerignore) != 0) return -1; } if (config->use_style) { (void) snprintf(path, sizeof path, "%s/.clang-format", dir); if (emit(path, config, write_clang_format) != 0) return -1; (void) snprintf(path, sizeof path, "%s/.editorconfig", dir); if (emit(path, config, write_editorconfig) != 0) return -1; } if (config->use_ci) { (void) snprintf(path, sizeof path, "%s/.github", dir); if (ensure_dir(path) != 0) return -1; (void) snprintf(path, sizeof path, "%s/.github/workflows", dir); if (ensure_dir(path) != 0) return -1; (void) snprintf(path, sizeof path, "%s/.github/workflows/ci.yml", dir); if (emit(path, config, write_ci) != 0) return -1; } if (config->use_git && git_init(dir) != 0) (void) fprintf(stderr, "%s: warning: git is not installed\n", mkproj_program); print_next_steps(config); { char* const argv[] = { "tree", "-a", "--dirsfirst", "-I", ".git", (char*) dir, NULL }; if (run(argv, 0) == 127) (void) puts(" (tree is not installed)"); } return 0; } int main(int argc, char** argv) { struct Config config = { .name = NULL, .dir = NULL, .src_dir = NULL, .language = language_c, .standard = NULL, .compiler = NULL, .build = build_make, .kind = kind_exe, .license = license_none, .bin_dir = NULL, .bin_int_dir = NULL, .use_git = 0, .use_intermediate = 0, .use_flat = 1, .use_single = 0, .use_validation = 1, .use_docker = 0, .use_root = 1, .use_style = 0, .use_ci = 0, }; int status = parse_args(argc, argv, &config); if (status < 0) return EXIT_SUCCESS; if (status > 0) { print_usage(stderr); return EXIT_FAILURE; } if (generate_project(&config) != 0) return EXIT_FAILURE; return EXIT_SUCCESS; }