Skip to content

Instantly share code, notes, and snippets.

@nonchip
Last active March 13, 2018 09:38
Show Gist options
  • Save nonchip/e6268f81f99172009994d8b3aad99f5a to your computer and use it in GitHub Desktop.
Save nonchip/e6268f81f99172009994d8b3aad99f5a to your computer and use it in GitHub Desktop.
a xbps virtual packages list parser for dxpb
#define _POSIX_C_SOURCE 200809L
#include <czmq.h>
#include <stdio.h>
// you'll need to `free` the living shit out of everything in this hash when destroying it!
zhash_t *bvirtpkg_read(const char * path) {
zhash_t *retVal = zhash_new();
// if argument is already a complete path to the file, set to `0` or remove `if` block.
#if 1
const char* innerpath = "/etc/defaults.virtual";
char *filepath = malloc(strlen(path)+strlen(innerpath)+1);
if(!filepath) return NULL;
strcpy(filepath,path);
strcat(filepath,innerpath);
FILE *handle = fopen(filepath,"r");
free(filepath);
#else
FILE *handle = fopen(path,"r");
#endif
if(!handle) return NULL;
char line[1025],vpkg[1025],resto[1025];
while (fgets(line, sizeof line, handle)) {
if (*line == '#') continue; /* ignore comment line */
if (sscanf(line, "%1024s %1024s", vpkg, resto) == 2) {
char *virtualpkg = malloc(strlen(vpkg)+1);
char *resolvesto = malloc(strlen(resto)+1);
strcpy(virtualpkg,vpkg);
strcpy(resolvesto,resto);
zhash_insert(retVal, virtualpkg, resolvesto);
}
}
return retVal;
}
#ifdef TEST_BUILD
int main(int argc, char *argv[]) {
if(argc<2) {
printf("usage: %s /path/to/void-packages name-of-virtual-package\n",argv[0]);
return 1;
}
zhash_t *hash = bvirtpkg_read(argv[1]);
if(!hash) {
printf("bvirtpkg_read(\"%s\") failed.\n",argv[1]);
return 2;
}
char *found = zhash_lookup(hash,argv[2]);
if(!found) {
printf("zhash_lookup(\"%s\") failed.\n",argv[2]);
return 3;
}
printf("\"%s\" => \"%s\"\n",argv[2],found);
return 0;
}
#endif
/* tested with:
$ gcc -DTEST_BUILD bvirtpkg_read.c -lczmq
$ ./a.out ~/void-packages ntp-daemon
"ntp-daemon" => "chrony"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment