Skip to content

Commit

Permalink
add scr_print binary
Browse files Browse the repository at this point in the history
This adds an scr_print binary, which is essentially a duplicate of the
kvtree_print command. This separate binary abstracts the fact from
users that SCR files are really stored as kvtree files.
  • Loading branch information
adammoody committed May 27, 2020
1 parent 97c2e69 commit d0777f8
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ LIST(APPEND cliscr_c_bins
scr_index
scr_rebuild_xor
scr_rebuild_partner
scr_print
)

# CLI binaries that require full SCR library
Expand Down
102 changes: 102 additions & 0 deletions src/scr_print.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
#include "kvtree.h"

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>

static void print_usage(void)
{
printf("\n");
printf("Usage: scr_print [options] <file>\n");
printf("\n");
printf(" Options:\n");
printf(" -m, --mode <mode> Specify print format: \"tree\" or \"keyval\" (default tree)\n");
printf(" -h, --help Print usage\n");
printf("\n");
}

int main(int argc, char* argv[])
{
int rc = 0;

static const char *opt_string = "m:h";
static struct option long_options[] = {
{"mode", required_argument, NULL, 'm'},
{"help", no_argument, NULL, 'h'},
{NULL, no_argument, NULL, 0}
};

int usage = 0;
char* mode = NULL;

int long_index = 0;
while (1) {
char c = getopt_long(argc, argv, opt_string, long_options, &long_index);
if (c == -1) {
break;
}

switch(c) {
case 'm':
mode = strdup(optarg);
break;
case 'h':
usage = 1;
break;
default:
printf("ERROR: Unknown option: `%s'\n", argv[optind]);
usage = 1;
rc = 1;
break;
}
}

/* check that we were given exactly one filename argument */
int numargs = argc - optind;
if (!usage && numargs != 1) {
printf("ERROR: Missing file name or too many files\n");
usage = 1;
rc = 1;
}

/* parse the print mode option, if one is given */
int print_mode = KVTREE_PRINT_TREE;
if (mode != NULL) {
if (strcmp(mode, "tree") == 0) {
print_mode = KVTREE_PRINT_TREE;
} else if (strcmp(mode, "keyval") == 0) {
print_mode = KVTREE_PRINT_KEYVAL;
} else {
printf("ERROR: Invalid mode name: `%s'\n", mode);
usage = 1;
rc = 1;
}
free(mode);
}

if (usage) {
print_usage();
return rc;
}

/* get the file name */
char* filename = argv[optind];

/* read in the file */
kvtree* hash = kvtree_new();
if (kvtree_read_file(filename, hash) == KVTREE_SUCCESS) {
/* we read the file, now print it out */
kvtree_print_mode(hash, 0, print_mode);
} else {
printf("ERROR: Failed to read file: `%s'\n", filename);
rc = 1;
}
kvtree_delete(&hash);

return rc;
}

0 comments on commit d0777f8

Please sign in to comment.