nopen.c - noice - small file browser (mirror / fork from 2f30.org)
HTML git clone git://git.codemadness.org/noice
DIR Log
DIR Files
DIR Refs
DIR README
DIR LICENSE
---
nopen.c (1618B)
---
1 /* See LICENSE file for copyright and license details. */
2 #include <sys/types.h>
3 #include <sys/wait.h>
4
5 #include <regex.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <unistd.h>
10
11 #include "arg.h"
12 #include "util.h"
13
14 struct rule {
15 char *regex; /* Regex to match on filename */
16 char *file;
17 char *argv[NR_ARGS];
18 regex_t regcomp;
19 };
20
21 #include "nopenconf.h"
22
23 char *argv0;
24
25 int
26 run(struct rule *rule, char *arg)
27 {
28 char *argv[NR_ARGS];
29 int i;
30
31 for (i = 0; rule->argv[i]; i++) {
32 if (strcmp(rule->argv[i], "{}") == 0) {
33 argv[i] = arg;
34 continue;
35 }
36 argv[i] = rule->argv[i];
37 }
38 argv[i] = NULL;
39 return spawnvp(NULL, rule->file, argv);
40 }
41
42 struct rule *
43 matchrule(char *file)
44 {
45 int i;
46
47 for (i = 0; i < LEN(rules); i++) {
48 if (regexec(&rules[i].regcomp, file, 0, NULL, 0) == 0)
49 return &rules[i];
50 }
51 return NULL;
52 }
53
54 void
55 parserules(void)
56 {
57 char errbuf[256];
58 int i, r;
59
60 for (i = 0; i < LEN(rules); i++) {
61 r = regcomp(&rules[i].regcomp, rules[i].regex,
62 REG_NOSUB | REG_EXTENDED | REG_ICASE);
63 if (r != 0) {
64 regerror(r, &rules[i].regcomp, errbuf, sizeof(errbuf));
65 fprintf(stderr, "invalid regex rules[%d]: %s: %s\n",
66 i, rules[i].regex, errbuf);
67 exit(1);
68 }
69 }
70 }
71
72 void
73 usage(void)
74 {
75 fprintf(stderr, "usage: %s file...\n", argv0);
76 exit(1);
77 }
78
79 int
80 main(int argc, char *argv[])
81 {
82 int r;
83
84 ARGBEGIN {
85 default:
86 usage();
87 } ARGEND
88
89 if (argc == 0)
90 usage();
91
92 r = 0;
93 parserules();
94 for (; argv[0] != NULL; argv++) {
95 struct rule *rule;
96
97 if ((rule = matchrule(argv[0])) == NULL)
98 continue;
99 if (run(rule, argv[0]) == -1)
100 r = 1;
101 }
102 return r;
103 }