commit 7347981dbdea21211c391303279972d6b5899058
parent eea8a4b1a56ea6eea5466d208e376740b2898024
Author: torter <koubbamohamedrayan@gmail.com>
Date: Sat, 28 Nov 2026 14:34:36 +0000
which, rev, strings, clear, free, cal and tree; 0.3
Diffstat:
| M | rifle.c | | | 287 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- |
1 file changed, 286 insertions(+), 1 deletion(-)
diff --git a/rifle.c b/rifle.c
@@ -2,7 +2,7 @@
* whichever name it was called by. build.sh makes them in bin/, "rifle --install DIR" anywhere else. */
#include "c.h"
-#define VERSION "0.2"
+#define VERSION "0.3"
/* ---- messages ---- */
@@ -12230,6 +12230,284 @@ static int t_diff(int argc, char **argv)
return r;
}
+/* ---- which ---- */
+static int t_which(int argc, char **argv)
+{
+ static const struct opt lo[] = { { "all", 0, 'a' }, { NULL, 0, 0 } };
+ int c, all = 0, i, bad = 0;
+ const char *path;
+ char buf[PATH_MAX];
+ opts_reset();
+ while ((c = getopts(argc, argv, "a", lo))) if (c == 'a') all = 1;
+ if (!nops) return 1;
+ path = getenv("PATH");
+ if (!path || !*path) path = "/usr/bin:/bin";
+ for (i = 0; i < nops; i++) {
+ int found = 0;
+ if (strchr(ops[i], '/')) {
+ if (!access(ops[i], X_OK)) { puts(ops[i]); found = 1; }
+ } else {
+ char *ps = xstrdup(path), *dir, *nx;
+ for (dir = ps; dir; dir = nx) {
+ nx = strchr(dir, ':');
+ if (nx) *nx++ = 0;
+ snprintf(buf, sizeof buf, "%s/%s", *dir ? dir : ".", ops[i]);
+ if (!access(buf, X_OK)) { puts(buf); found = 1; if (!all) break; }
+ }
+ free(ps);
+ }
+ if (!found) bad = 1;
+ }
+ return finish_stdout() ? 2 : bad;
+}
+
+/* ---- rev ---- */
+static int rev_file(FILE *f, const char *name)
+{
+ char *line = NULL;
+ size_t cap = 0;
+ ssize_t n;
+ while ((n = getline(&line, &cap, f)) > 0) {
+ ssize_t j;
+ int nl = line[n - 1] == '\n';
+ if (nl) n--;
+ for (j = n - 1; j >= 0; j--) putchar(line[j]);
+ if (nl) putchar('\n');
+ }
+ free(line);
+ if (ferror(f)) { perr("%s: read error", name); return 1; }
+ return 0;
+}
+static int t_rev(int argc, char **argv)
+{
+ int i, rc = 0;
+ opts_reset();
+ while (getopts(argc, argv, "", NULL)) ;
+ if (!nops) rc = rev_file(stdin, "standard input");
+ else for (i = 0; i < nops; i++) {
+ FILE *f = strcmp(ops[i], "-") ? fopen(ops[i], "r") : stdin;
+ if (!f) { perr("%s: %s", ops[i], strerror(errno)); rc = 1; continue; }
+ if (rev_file(f, ops[i])) rc = 1;
+ if (f != stdin) fclose(f);
+ }
+ return finish_stdout() ? 1 : rc;
+}
+
+/* ---- strings ---- */
+static void strings_file(FILE *f, int min, const char *name, int pfn)
+{
+ int c, n = 0;
+ size_t cap = 256;
+ char *b = xmalloc(cap);
+ for (;;) {
+ c = getc(f);
+ if (c == '\t' || (c >= 0x20 && c < 0x7f)) {
+ if ((size_t)n + 1 >= cap) b = xrealloc(b, cap *= 2);
+ b[n++] = c;
+ continue;
+ }
+ if (n >= min) { b[n] = 0; if (pfn) printf("%s: ", name); puts(b); }
+ n = 0;
+ if (c == EOF) break;
+ }
+ free(b);
+}
+static int t_strings(int argc, char **argv)
+{
+ static const struct opt lo[] = { { "bytes", 1, 'n' }, { "print-file-name", 0, 'f' }, { NULL, 0, 0 } };
+ int c, min = 4, pfn = 0, i, rc = 0;
+ opts_reset();
+ while ((c = getopts(argc, argv, "n:f", lo)))
+ switch (c) {
+ case 'n': min = atoi(optarg); if (min < 1) die(1, "invalid minimum string length '%s'", optarg); break;
+ case 'f': pfn = 1; break;
+ }
+ if (!nops) strings_file(stdin, min, "{standard input}", pfn);
+ else for (i = 0; i < nops; i++) {
+ FILE *f = strcmp(ops[i], "-") ? fopen(ops[i], "rb") : stdin;
+ if (!f) { perr("'%s': %s", ops[i], strerror(errno)); rc = 1; continue; }
+ strings_file(f, min, ops[i], pfn);
+ if (f != stdin) fclose(f);
+ }
+ return finish_stdout() ? 1 : rc;
+}
+
+/* ---- clear ---- */
+static int t_clear(int argc, char **argv)
+{
+ opts_reset();
+ while (getopts(argc, argv, "", NULL)) ;
+ fputs("\033[3J\033[H\033[2J", stdout);
+ return finish_stdout() ? 1 : 0;
+}
+
+/* ---- free ---- */
+static long meminfo_kb(const char *buf, const char *key)
+{
+ const char *p = strstr(buf, key);
+ return p ? atol(p + strlen(key)) : 0;
+}
+static int t_free(int argc, char **argv)
+{
+ static const struct opt lo[] = { { "human", 0, 'h' }, { "kibi", 0, 'k' }, { "mebi", 0, 'm' }, { "gibi", 0, 'g' }, { "total", 0, 't' }, { NULL, 0, 0 } };
+ static const char *const u[] = { "B", "K", "M", "G", "T" };
+ int c, human = 0, want_t = 0, fd, i;
+ long div = 1024; /* meminfo is in kB; mebibytes by default, the number people read */
+ char buf[8192];
+ long total, mfree, avail, buffers, cached, srecl, shmem, used, bc, stotal, sfree;
+ struct row { const char *name; long v[6]; int n; } rows[2];
+ long mv[6], sv[6];
+ int r;
+ opts_reset();
+ while ((c = getopts(argc, argv, "hkmgt", lo)))
+ switch (c) {
+ case 'h': human = 1; break;
+ case 'k': div = 1; break;
+ case 'm': div = 1024; break;
+ case 'g': div = 1024L * 1024; break;
+ case 't': want_t = 1; break;
+ }
+ if ((fd = open("/proc/meminfo", O_RDONLY)) < 0) die(1, "/proc/meminfo: %s", strerror(errno));
+ i = read(fd, buf, sizeof buf - 1);
+ close(fd);
+ if (i <= 0) die(1, "cannot read /proc/meminfo");
+ buf[i] = 0;
+ total = meminfo_kb(buf, "MemTotal:");
+ mfree = meminfo_kb(buf, "MemFree:");
+ avail = meminfo_kb(buf, "MemAvailable:");
+ buffers = meminfo_kb(buf, "Buffers:");
+ cached = meminfo_kb(buf, "Cached:");
+ srecl = meminfo_kb(buf, "SReclaimable:");
+ shmem = meminfo_kb(buf, "Shmem:");
+ stotal = meminfo_kb(buf, "SwapTotal:");
+ sfree = meminfo_kb(buf, "SwapFree:");
+ bc = buffers + cached + srecl;
+ used = total - mfree - bc;
+ if (used < 0) used = total - mfree;
+ printf("%15s%12s%12s%12s%12s%12s\n", "total", "used", "free", "shared", "buff/cache", "available");
+ mv[0] = total; mv[1] = used; mv[2] = mfree; mv[3] = shmem; mv[4] = bc; mv[5] = avail;
+ sv[0] = stotal; sv[1] = stotal - sfree; sv[2] = sfree; sv[3] = sv[4] = sv[5] = 0;
+ rows[0].name = "Mem:"; memcpy(rows[0].v, mv, sizeof mv); rows[0].n = 6;
+ rows[1].name = "Swap:"; memcpy(rows[1].v, sv, sizeof sv); rows[1].n = 3;
+ for (r = 0; r < 2; r++) {
+ printf("%-7s", rows[r].name);
+ for (i = 0; i < rows[r].n; i++) {
+ long kb = rows[r].v[i];
+ if (human) {
+ double d = kb * 1024.0;
+ int k = 0;
+ while (d >= 1024 && k < 4) { d /= 1024; k++; }
+ printf("%11.1f%s", d, u[k]);
+ } else
+ printf("%12ld", kb / div);
+ }
+ putchar('\n');
+ }
+ if (want_t)
+ printf("%-7s%12ld%12ld%12ld\n", "Total:", (total + stotal) / div, (used + stotal - sfree) / div, (mfree + sfree) / div);
+ return finish_stdout() ? 1 : 0;
+}
+
+/* ---- cal ---- */
+static int cal_dow(int y, int m, int d) /* Sakamoto: 0 is Sunday */
+{
+ static const int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
+ if (m < 3) y--;
+ return (y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7;
+}
+static int t_cal(int argc, char **argv)
+{
+ static const char *const mon[] = { "January", "February", "March", "April", "May", "June",
+ "July", "August", "September", "October", "November", "December" };
+ int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
+ int c, y, m, d, first, len, col, pad;
+ time_t now;
+ struct tm *tm;
+ char head[32];
+ opts_reset();
+ while ((c = getopts(argc, argv, "", NULL))) ;
+ now = time(NULL);
+ tm = localtime(&now);
+ y = tm->tm_year + 1900;
+ m = tm->tm_mon + 1;
+ d = tm->tm_mday;
+ if (nops >= 2) { m = atoi(ops[0]); y = atoi(ops[1]); d = 0; }
+ else if (nops == 1) { y = atoi(ops[0]); d = 0; }
+ if (m < 1 || m > 12) m = tm->tm_mon + 1;
+ if (!(y % 4) && (y % 100 || !(y % 400))) days[1] = 29;
+ len = days[m - 1];
+ first = cal_dow(y, m, 1);
+ snprintf(head, sizeof head, "%s %d", mon[m - 1], y);
+ pad = (20 - (int)strlen(head)) / 2;
+ printf("%*s%s\n", pad, "", head);
+ fputs("Su Mo Tu We Th Fr Sa\n", stdout);
+ for (col = 0; col < first; col++) fputs(" ", stdout);
+ for (c = 1; c <= len; c++) {
+ if (c == d) printf("\033[7m%2d\033[0m ", c); else printf("%2d ", c);
+ if (++col == 7 && c != len) { putchar('\n'); col = 0; }
+ }
+ putchar('\n');
+ return finish_stdout() ? 1 : 0;
+}
+
+/* ---- tree ---- */
+static long tree_dirs, tree_files;
+static int tree_all, tree_donly, tree_max;
+static int tree_cmp(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
+static void tree_walk(const char *path, const char *prefix, int depth)
+{
+ DIR *dp = opendir(path);
+ struct dirent *e;
+ char **names = NULL;
+ int n = 0, i;
+ if (!dp) { printf("%s [error opening dir]\n", path); return; }
+ while ((e = readdir(dp))) {
+ if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
+ if (!tree_all && e->d_name[0] == '.') continue;
+ names = xrealloc(names, (n + 1) * sizeof *names);
+ names[n++] = xstrdup(e->d_name);
+ }
+ closedir(dp);
+ qsort(names, n, sizeof *names, tree_cmp);
+ for (i = 0; i < n; i++) {
+ char *full = xmalloc(strlen(path) + strlen(names[i]) + 2);
+ struct stat st;
+ int isdir, last = i == n - 1;
+ sprintf(full, "%s/%s", path, names[i]);
+ isdir = lstat(full, &st) == 0 && S_ISDIR(st.st_mode);
+ if (!tree_donly || isdir) {
+ printf("%s%s%s\n", prefix, last ? "\\-- " : "|-- ", names[i]);
+ if (isdir) tree_dirs++; else tree_files++;
+ }
+ if (isdir && (!tree_max || depth < tree_max)) {
+ char *np = xmalloc(strlen(prefix) + 5);
+ sprintf(np, "%s%s", prefix, last ? " " : "| ");
+ tree_walk(full, np, depth + 1);
+ free(np);
+ }
+ free(full); free(names[i]);
+ }
+ free(names);
+}
+static int t_tree(int argc, char **argv)
+{
+ static const struct opt lo[] = { { "all", 0, 'a' }, { NULL, 0, 0 } };
+ int c, i;
+ opts_reset();
+ tree_all = tree_donly = tree_max = 0;
+ tree_dirs = tree_files = 0;
+ while ((c = getopts(argc, argv, "adL:", lo)))
+ switch (c) {
+ case 'a': tree_all = 1; break;
+ case 'd': tree_donly = 1; break;
+ case 'L': tree_max = atoi(optarg); if (tree_max < 1) die(1, "invalid level, must be greater than 0"); break;
+ }
+ if (!nops) { puts("."); tree_walk(".", "", 1); }
+ else for (i = 0; i < nops; i++) { puts(ops[i]); tree_walk(ops[i], "", 1); }
+ printf("\n%ld director%s, %ld file%s\n", tree_dirs, tree_dirs == 1 ? "y" : "ies", tree_files, tree_files == 1 ? "" : "s");
+ return finish_stdout() ? 1 : 0;
+}
+
/* ---- the table and main ---- */
struct applet { const char *name; int (*fn)(int, char **); const char *usage; const char *about; };
@@ -12241,6 +12519,7 @@ static const struct applet applets[] = {
{ "basenc", t_basenc, "[OPTION]... [FILE]", "Encode or decode FILE with one of several encodings." },
{ "base64", t_base, "[OPTION]... [FILE]", "Base64 encode or decode FILE." },
{ "basename", t_basename, "NAME [SUFFIX] | OPTION... NAME...", "Print NAME without any leading directory components, and SUFFIX if it ends the name." },
+ { "cal", t_cal, "[[MONTH] YEAR]", "Print a calendar for the month." },
{ "cat", t_cat, "[OPTION]... [FILE]...", "Concatenate FILE(s) to standard output." },
{ "chcon", t_chcon, "[OPTION]... CONTEXT FILE...", "Change the SELinux security context of each FILE to CONTEXT." },
{ "chgrp", t_chown, "[OPTION]... GROUP FILE...", "Change the group of each FILE to GROUP." },
@@ -12248,6 +12527,7 @@ static const struct applet applets[] = {
{ "chown", t_chown, "[OPTION]... [OWNER][:[GROUP]] FILE...", "Change the owner and/or group of each FILE." },
{ "chroot", t_chroot, "[OPTION] NEWROOT [COMMAND [ARG]...]", "Run COMMAND with root directory set to NEWROOT." },
{ "cksum", t_cksum, "[OPTION]... [FILE]...", "Print CRC checksum and byte counts of each FILE." },
+ { "clear", t_clear, "", "Clear the terminal screen." },
{ "comm", t_comm, "[OPTION]... FILE1 FILE2", "Compare sorted files FILE1 and FILE2 line by line." },
{ "cp", t_cp, "[OPTION]... SOURCE... DEST", "Copy SOURCE to DEST, or several SOURCEs to a DIRECTORY." },
{ "cut", t_cut, "OPTION... [FILE]...", "Print selected parts of lines from each FILE." },
@@ -12276,6 +12556,7 @@ static const struct applet applets[] = {
{ "fgrep", t_grep, "[OPTION]... PATTERNS [FILE]...", "Search for PATTERNS in each FILE." },
{ "find", t_find, "[-H] [-L] [-P] [PATH...] [EXPRESSION]", "Search for files in a directory hierarchy." },
{ "fold", t_fold, "[OPTION]... [FILE]...", "Wrap each input line to fit in a given width." },
+ { "free", t_free, "[-hkmgt]", "Show how much memory and swap is used and free." },
{ "grep", t_grep, "[OPTION]... PATTERNS [FILE]...", "Search for PATTERNS in each FILE." },
{ "groups", t_id, "[OPTION]... [USERNAME]...", "Print the groups a user is in." },
{ "head", t_head, "[OPTION]... [FILE]...", "Print the first 10 lines of each FILE." },
@@ -12309,6 +12590,7 @@ static const struct applet applets[] = {
{ "pwd", t_pwd, "[OPTION]...", "Print the name of the current working directory." },
{ "readlink", t_readlink, "[OPTION]... FILE...", "Print the value of a symbolic link, or a file's canonical name." },
{ "realpath", t_realpath, "[OPTION]... FILE...", "Print the resolved absolute file name." },
+ { "rev", t_rev, "[FILE]...", "Reverse the characters of each line." },
{ "rm", t_rm, "[OPTION]... [FILE]...", "Remove (unlink) the FILE(s)." },
{ "rmdir", t_rmdir, "[OPTION]... DIRECTORY...", "Remove the DIRECTORY(ies), if they are empty." },
{ "runcon", t_runcon, "CONTEXT COMMAND [ARG]...", "Run COMMAND with a SELinux security context." },
@@ -12325,6 +12607,7 @@ static const struct applet applets[] = {
{ "split", t_split, "[OPTION]... [FILE [PREFIX]]", "Output pieces of FILE to PREFIXaa, PREFIXab, ..." },
{ "stat", t_stat, "[OPTION]... FILE...", "Display file or file system status." },
{ "stdbuf", t_stdbuf, "OPTION... COMMAND", "Run COMMAND with modified buffering for its standard streams." },
+ { "strings", t_strings, "[-f] [-n MIN] [FILE]...", "Print the printable strings in FILE(s)." },
{ "sum", t_cksum, "[OPTION]... [FILE]...", "Print checksum and block counts for each FILE." },
{ "sync", t_sync, "[OPTION] [FILE]...", "Flush file system buffers." },
{ "tac", t_tac, "[OPTION]... [FILE]...", "Print each FILE last line first." },
@@ -12334,6 +12617,7 @@ static const struct applet applets[] = {
{ "timeout", t_timeout, "[OPTION] DURATION COMMAND [ARG]...", "Start COMMAND, and kill it if still running after DURATION." },
{ "touch", t_touch, "[OPTION]... FILE...", "Update the access and modification times of each FILE." },
{ "tr", t_tr, "[OPTION]... SET1 [SET2]", "Translate, squeeze, and/or delete characters from standard input." },
+ { "tree", t_tree, "[-ad] [-L LEVEL] [DIR]...", "List the contents of a directory as a tree." },
{ "true", t_true, "", "Do nothing, successfully." },
{ "truncate", t_truncate, "OPTION... FILE...", "Shrink or extend the size of each FILE to the specified size." },
{ "tsort", t_tsort, "[OPTION] [FILE]", "Write totally ordered list consistent with the partial ordering in FILE." },
@@ -12346,6 +12630,7 @@ static const struct applet applets[] = {
{ "users", t_users, "[FILE]", "Print the user names of users currently logged in." },
{ "vdir", t_dir, "[OPTION]... [FILE]...", "List directory contents in long format, with C-style escapes." },
{ "wc", t_wc, "[OPTION]... [FILE]...", "Print newline, word, and byte counts for each FILE." },
+ { "which", t_which, "[-a] NAME...", "Show the full path of a command, the way the shell would find it." },
{ "who", t_who, "[OPTION]... [FILE] [am i]", "Print information about users who are currently logged in." },
{ "whoami", t_whoami, "", "Print the user name for the current effective user ID." },
{ "xargs", t_xargs, "[OPTION]... COMMAND [INITIAL-ARGS]...", "Build and execute command lines from standard input." },