aboutsummaryrefslogtreecommitdiffstats
path: root/src/search.c
blob: 126a944888aa5aa0fa2296907acee31052d15ffa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* search.c - the search action ----------------------------------------*- C -*-
 *
 * This file is part of ck, the config keeper
 *
 * -----------------------------------------------------------------------------
 *
 * Copyright (C) 2019  Anastasis Grammenos
 * GPLv3 (see LICENCE for the full notice)
 *
 * -------------------------------------------------------------------------- */
#include "dblayer.h"
#include "ckerrlog.h"

ERRLOG(search);

int run_SEARCH(UserOpt *opt, Conf *conf) {
  if (system("which grep > /dev/null 2>&1") != 0) {
    ERR("No grep avaliable. Please make sure you have grep installed.");
    return -1;
  }
  DB db;
  if (open_DB(&db, opt)) {
    return -1;
  }

  cklist *paths = list_make_new();
  list_get_paths(&db, paths, 0 /*basename*/, 0/*attributes*/, conf->home_dir);
  close_DB(&db);
  if (list_size(paths) && list_size(opt->args)) {
    do {
      FILE *cmd;
      char result[STR_L] = "";
      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;
}

void print_SEARCH_help() {
  HELP("ck search SEARCH_TERM");
}