From d2334a67dd349b801fa2a3cd629b52ea5ea1d37c Mon Sep 17 00:00:00 2001 From: apio Date: Sat, 3 Jun 2023 12:15:57 +0200 Subject: [PATCH] apps: Add mktemp --- apps/CMakeLists.txt | 1 + apps/mktemp.cpp | 40 +++++++++++++++++++++++++++++++++++ libc/src/stdlib.cpp | 2 +- libluna/include/luna/String.h | 5 +++++ 4 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 apps/mktemp.cpp diff --git a/apps/CMakeLists.txt b/apps/CMakeLists.txt index 0c49dfd8..7f933321 100644 --- a/apps/CMakeLists.txt +++ b/apps/CMakeLists.txt @@ -29,3 +29,4 @@ luna_app(umount.cpp umount) luna_app(ps.cpp ps) luna_app(time.cpp time) luna_app(ln.cpp ln) +luna_app(mktemp.cpp mktemp) diff --git a/apps/mktemp.cpp b/apps/mktemp.cpp new file mode 100644 index 00000000..4e53576b --- /dev/null +++ b/apps/mktemp.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +#include +#include +#include +#include + +Result luna_main(int argc, char** argv) +{ + srand((unsigned)time(NULL)); + + bool make_directory { false }; + StringView template_sv; + + os::ArgumentParser parser; + parser.add_description("Create a temporary file or directory safely and print its name."); + parser.add_system_program_info("mktemp"_sv); + parser.add_switch_argument(make_directory, 'd', "directory"_sv, "make a directory instead of a file"_sv); + parser.add_positional_argument(template_sv, "template"_sv, "/tmp/tmp.XXXXXX"_sv); + parser.parse(argc, argv); + + String str = TRY(String::from_string_view(template_sv)); + + if (make_directory) + { + if (mkdtemp(str.mutable_data()) == nullptr) return err(errno); + } + else + { + int fd = -1; + fd = mkstemp(str.mutable_data()); + if (fd < 0) return err(errno); + close(fd); + } + + os::println("%s"_sv, str.chars()); + + return 0; +} diff --git a/libc/src/stdlib.cpp b/libc/src/stdlib.cpp index 926a4582..19eac27b 100644 --- a/libc/src/stdlib.cpp +++ b/libc/src/stdlib.cpp @@ -228,7 +228,7 @@ extern "C" static void generate_random_character(char* ptr) { constexpr const char chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"; - *ptr = chars[rand() % sizeof(chars)]; + *ptr = chars[rand() % (sizeof(chars) - 1)]; } static int check_template(char* _template, size_t* len) diff --git a/libluna/include/luna/String.h b/libluna/include/luna/String.h index f477e883..dc330a46 100644 --- a/libluna/include/luna/String.h +++ b/libluna/include/luna/String.h @@ -75,6 +75,11 @@ class String return m_inline ? m_inline_storage : m_string; } + char* mutable_data() + { + return m_inline ? m_inline_storage : m_string; + } + usize length() const { return m_length;