Userland: Use ArgParser in stat and support multiple files + links

The '-L' option can be used for calling stat instead of lstat
This commit is contained in:
Shannon Booth 2020-03-09 20:40:41 +13:00 committed by Andreas Kling
parent 0f45a1b5e7
commit 28731179b1
Notes: sideshowbarker 2024-07-19 08:49:03 +09:00

View file

@ -1,5 +1,6 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2020, Shannon Booth <shannon.ml.booth@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@ -25,6 +26,7 @@
*/
#include <AK/String.h>
#include <LibCore/ArgsParser.h>
#include <LibCore/DateTime.h>
#include <grp.h>
#include <pwd.h>
@ -33,24 +35,15 @@
#include <time.h>
#include <unistd.h>
int main(int argc, char** argv)
static int stat(const char* file, bool should_follow_links)
{
if (pledge("stdio rpath", nullptr) < 0) {
perror("pledge");
return 1;
}
if (argc == 1) {
printf("stat <file>\n");
return 1;
}
struct stat st;
int rc = lstat(argv[1], &st);
int rc = should_follow_links ? stat(file, &st) : lstat(file, &st);
if (rc < 0) {
perror("lstat");
return 1;
}
printf(" File: %s\n", argv[1]);
printf(" File: %s\n", file);
printf(" Inode: %u\n", st.st_ino);
if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))
printf(" Device: %u,%u\n", major(st.st_rdev), minor(st.st_rdev));
@ -117,3 +110,25 @@ int main(int argc, char** argv)
return 0;
}
int main(int argc, char** argv)
{
if (pledge("stdio rpath", nullptr) < 0) {
perror("pledge");
return 1;
}
bool should_follow_links = false;
Vector<const char*> files;
auto args_parser = Core::ArgsParser();
args_parser.add_option(should_follow_links, "Follow links to files", nullptr, 'L');
args_parser.add_positional_argument(files, "File(s) to stat", "file", Core::ArgsParser::Required::Yes);
args_parser.parse(argc, argv);
int ret = 0;
for (auto& file : files)
ret |= stat(file, should_follow_links);
return ret;
}