]> pd.if.org Git - zpackage/blob - zpm-findpkg.c
cleanup foreach-path
[zpackage] / zpm-findpkg.c
1 #define _POSIX_C_SOURCE 2 
2
3 #include <stdlib.h>
4 #include <stdio.h>
5 #include <ctype.h>
6 #include <unistd.h>
7
8 #include "zpm.h"
9
10 void usage(void) {
11         fprintf(stderr, "zpm-findpkg [-I] [-s <status> ...] [-S <status>] [package]\n");
12 }
13
14 int main(int ac, char **av){
15         int opt, argn;
16         struct zpm zpm;
17         char *dbfile = 0, *pkgstr = 0, *pkgid = 0;
18
19         char *sql;
20         sqlite3_str *include;
21         sqlite3_str *exclude;
22         sqlite3_str *query;
23
24         dbfile = getenv("ZPMDB");
25
26         include = sqlite3_str_new(NULL);
27         exclude = sqlite3_str_new(NULL);
28
29         while ((opt = getopt(ac, av, "f:s:S:I")) != -1) {
30                 switch (opt) {
31                         case 'f': dbfile = optarg; break;
32                         case 's': sqlite3_str_appendf(include,",%Q", optarg);
33                                   break;
34                         case 'S': sqlite3_str_appendf(exclude,",%Q", optarg);
35                                   break;
36                         case 'I': sqlite3_str_appendall(include,",'installed'");
37                                   break;
38                         default:
39                                   usage();
40                                   exit(EXIT_FAILURE);
41                                   break;
42                 }
43         }
44         argn = optind;
45
46         if (!dbfile) {
47                 fprintf(stderr, "must specify db\n");
48                 return 1;
49         }
50
51         query = sqlite3_str_new(NULL);
52
53         if (zpm_open(&zpm, dbfile)) {
54                 char *excludes, *includes;
55
56                 excludes = sqlite3_str_value(exclude);
57                 includes = sqlite3_str_value(include);
58
59                 if (includes) {
60                         sqlite3_str_appendf(query, "status in (%s)", includes+1);
61                 }
62                 if (excludes) {
63                         sqlite3_str_appendf(query, "%sstatus not in (%s)",
64                                        includes ? " and " : "",
65                                        excludes+1);
66                 }
67
68                 if (ac >= argn) {
69                         pkgstr = av[argn];
70                 }
71
72                 sql = sqlite3_str_value(query);
73
74                 pkgid = zpm_findpkg(&zpm, pkgstr, sql);
75
76                 sqlite3_free(sql);
77                 if (pkgid) {
78                         printf("%s\n", pkgid);
79                 }
80                 zpm_close(&zpm);
81         }
82         return pkgid ? 0 : 1;
83 }