Skip to content

Commit

Permalink
dynamically get $PATH for package manager scan
Browse files Browse the repository at this point in the history
  • Loading branch information
an-prata committed Jun 22, 2023
1 parent 543666c commit d1e609d
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 18 deletions.
20 changes: 2 additions & 18 deletions src/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@

#define MAX(a, b) ((a) > (b) ? (a) : (b))

static const char* pac_mans[] = PAC_MANS;

/// Gets the size of the current terminal window.
///
/// @param width
Expand Down Expand Up @@ -115,22 +113,8 @@ int main(int argc, char** argv) {

mem_unit = unit_from_power(e, base_1024);

DIR* dir = opendir("/bin");

if (dir) {
struct dirent* dirent;
unsigned int prev_pac = 0 - 1;

while ((dirent = readdir(dir))) {
for (unsigned int i = 0; i < sizeof(pac_mans) / sizeof(*pac_mans); i++) {
if (!strcmp(dirent->d_name, pac_mans[i]) && i < prev_pac) {
pac_man = pac_mans[i];
prev_pac = i;
}
}
}
}

pac_man = get_pac_man();

// Currently excludes memory and storage
longest_entry_len = MAX(
MAX(
Expand Down
60 changes: 60 additions & 0 deletions src/pac_man.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Copyright (c) 2023 Evan Overman (https://an-prata.it). Licensed under the MIT License.
// See LICENSE file in repository root for complete license text.

#include <dirent.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "pac_man.h"

static const char* pac_mans[] = PAC_MANS;

static char* get_sub_str(char* str, char delim, size_t len) {
for (unsigned int i = 0; i < len; i++) {
if (!str[i]) {
if (i + 1 < len) {
str = &str[i + 1];
len -= i;
i = 0;
}

continue;
}

if (str[i] == delim) {
str[i] = '\0';
puts(str);
return str;
}
}

puts(str);
return NULL;
}

const char* get_pac_man() {
const char* pac_man, * current_dir;
char* path = getenv("PATH");
size_t path_len = strlen(path);

while ((current_dir = get_sub_str(path, ':', path_len))) {
DIR* dir = opendir(current_dir);

if (dir) {
struct dirent* dirent;
unsigned int prev_pac = 0 - 1;

while ((dirent = readdir(dir))) {
for (unsigned int i = 0; i < sizeof(pac_mans) / sizeof(*pac_mans); i++) {
if (!strcmp(dirent->d_name, pac_mans[i]) && i < prev_pac) {
pac_man = pac_mans[i];
prev_pac = i;
}
}
}
}
}

return pac_man;
}
2 changes: 2 additions & 0 deletions src/pac_man.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@
"apt" \
}

const char* get_pac_man();

#endif // PAC_MAN_H

0 comments on commit d1e609d

Please sign in to comment.