modfetch/util.c

80 lines
1.8 KiB
C

#include "util.h"
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
char *remove_whitespaces(const char *str) {
char tmp[strlen(str)];
size_t i = 0;
size_t j = 0;
while (str[i] != '\0') {
if (isspace(str[i])) {
i += 1;
continue;
}
tmp[j] = str[i];
i += 1;
j += 1;
}
char *ret = malloc(j * sizeof(char));
strncpy(ret, tmp, j);
ret[j] = '\0';
return ret;
}
char *resolve_env_vars(const char *str) {
size_t len = strlen(str);
char *ret = malloc(MAX_PATH_LENGTH * sizeof(char));
size_t ret_offset = 0;
bool in_env_var = false;
char env_var[MAX_PATH_LENGTH];
memset(env_var, 0, sizeof(env_var));
size_t env_var_offset = 0;
for (size_t i = 0; i < len; ++i) {
if (str[i] == '~') {
char *home = getenv("HOME");
strcat(ret, home);
ret_offset += strlen(home);
continue;
}
if (str[i] == '$') {
in_env_var = true;
continue;
}
// end of current env var
if (in_env_var && !(isalpha(str[i]) || isdigit(str[i]) || str[i] == '_')) {
in_env_var = false;
char *env = getenv(env_var);
strcat(ret, env);
ret_offset += strlen(env);
memset(env_var, 0, sizeof(env_var));
env_var_offset = 0;
}
if (in_env_var) {
env_var[env_var_offset] = str[i];
env_var_offset += 1;
continue;
}
ret[ret_offset] = str[i];
ret_offset += 1;
}
ret[ret_offset] = '\0';
return ret;
}
char *process_str(const char *str) {
char *whitespaceless = remove_whitespaces(str);
char *ret = resolve_env_vars(whitespaceless);
free(whitespaceless);
return ret;
}