apps: Add mktemp
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
apio 2023-06-03 12:15:57 +02:00
parent fd62de6474
commit d2334a67dd
Signed by: apio
GPG Key ID: B8A7D06E42258954
4 changed files with 47 additions and 1 deletions

View File

@ -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)

40
apps/mktemp.cpp Normal file
View File

@ -0,0 +1,40 @@
#include <errno.h>
#include <luna/String.h>
#include <os/ArgumentParser.h>
#include <os/File.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
Result<int> 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;
}

View File

@ -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)

View File

@ -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;