From ff04205b2d794ae9157f9c423295da97bcebd90e Mon Sep 17 00:00:00 2001 From: Anastasis Grammenos Date: Sat, 22 Sep 2018 23:25:35 +0300 Subject: Add search action --- src/actions.c | 46 ++++++++++++++++++++++++++++++++++++---------- 1 file changed, 36 insertions(+), 10 deletions(-) (limited to 'src/actions.c') diff --git a/src/actions.c b/src/actions.c index e75c885..efffc1b 100644 --- a/src/actions.c +++ b/src/actions.c @@ -41,7 +41,7 @@ int run_ADD(UserOpt * opt, Conf *conf) { if (db.error == SQL_ERR_NO_TABLES) { PRINT_ERR("The database file is currupted. Run ck init anew."); } - return 1; + goto error; } AddOpt addOpt = add_make_options(opt->args); switch (addOpt.err) { @@ -49,26 +49,25 @@ int run_ADD(UserOpt * opt, Conf *conf) { break; case ADD_ERR_WRONG_CONFIG: PRINT_ERR("The config file specified doesn't exist."); - close_DB(&db); - return 1; + goto error; case ADD_ERR_WRONG_FLAGS: PRINT_ERR("Flags are: -s for secret and -p for primary."); - close_DB(&db); - return 1; + goto error; } add_print_opts(&addOpt); /* Try adding the new config to the DB */ if (add_transaction_try(&db, &addOpt)) { - close_DB(&db); - return 1; + goto error; } - close_DB(&db); add_make_link(&addOpt, conf); char err[STR_M]; if (add_err_message(err)) { PRINT_ERR(err); + error: + close_DB(&db); return 1; } + close_DB(&db); return 0; } @@ -175,11 +174,38 @@ int run_LIST(UserOpt *opt, Conf *conf) { return 0; } +FILE *popen(const char *command, const char *mode); +int pclose(FILE *stream); + int run_SEARCH(UserOpt *opt, Conf *conf) { - printf("Running %s\n", "search"); + if (system("which grep > /dev/null") != 0) { + return 2; + } DB db = open_DB(opt); + cklist *paths = list_make_new(); + list_get_paths(&db, paths); close_DB(&db); - return 1; + if (list_size(paths)) { + do { + FILE *cmd; + char result[4096] = ""; + char command[STR_L] = "grep -H -n "; + strcat(command, list_get(opt->args)); + strcat(command, " "); + strcat(command, list_get(paths)); + cmd = popen(command, "r"); + if (cmd == NULL) { + list_free(paths); + return 1; + } + while (fgets(result, sizeof(result), cmd)) { + printf("%s", result); + } + pclose(cmd); + } while(list_next(paths)); + } + list_free(paths); + return 0; } int run_HELP(UserOpt *opt, Conf *conf) { -- cgit v1.2.3