Very old versions for history.
[opsoft_archive.git] / silentbob / silent_bob-1.2 / src / plugins / plugin_grep.cpp
blob19337178152bc6cc867dee0f778d221aaa771373
1 /*
2 * (c) Oleg Puchinin 2006
3 * graycardinalster@gmail.com
5 */
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include <fcntl.h>
11 #include <gclib/gclib.h>
12 #include <gclib/gclib_c.h>
13 #include "../mod.h"
14 #include "../head.h"
15 #include "../dbg.h"
17 extern "C" DArray * plugin_init (struct env_t *env);
19 struct grep_env_t {
20 bool ignore_case;
21 char * f_name;
23 struct grep_env_t ENV_grep;
25 void grep_one (char * buf, int size, char * search, int s_len)
27 int nlines;
28 int i;
29 char *s_line;
30 char *ptr;
31 char *end;
32 char *end2;
33 char * line_ptr;
34 bool b_text = true;
36 if (size < s_len)
37 return;
39 nlines = 1;
40 ptr = buf;
41 end = &buf[size - s_len - 1];
42 end2 = &buf[size - 1];
43 line_ptr = ptr;
45 while (ptr <= end) {
46 if (*ptr == '\n') {
47 line_ptr = ptr+1;
48 ++nlines;
51 if (! memcmp (ptr, search, s_len)) {
52 s_line = Dmid_getstr (line_ptr, end2);
53 if (! s_line)
54 break;
55 chomp (s_line);
56 if (SB_FLGET (SB_FLTAGSTYLE))
57 printf ("%s\t%s\t%i\n", search, ENV_grep.f_name, nlines);
58 else
59 printf ("%s:%i: %s\n", ENV_grep.f_name, nlines, s_line);
60 free (s_line);
61 ptr += s_len;
62 continue;
64 ++ptr;
68 void grep_loop (DArray * files, char * search)
70 char * ptr;
71 int s_len;
72 int nfiles;
73 int size;
74 int i;
76 if (! files || ! search)
77 return;
79 s_len = strlen (search);
80 nfiles = files->get_size ();
81 for (i = 0; i < nfiles; ++i) {
82 size = 0;
83 ptr = DFILE (files->get (i), &size);
84 if (! ptr) {
85 perror ("DFILE");
86 continue;
88 ENV_grep.f_name = files->get (i);
89 grep_one (ptr, size, search, s_len);
90 DROP (ptr);
94 char grep_opt (DArray * d_opts, int * pos)
96 int count;
97 char * S;
99 if (! d_opts || ! pos)
100 return 0;
102 count = d_opts->get_size ();
103 S = d_opts->get (*pos);
104 if (EQ (S, "--grep")) {
105 ++(*pos);
106 return 1;
109 return 0;
112 char grep_opt2 (DArray * d_opts, int * pos)
114 char * S;
116 if (! d_opts || ! pos)
117 return 0;
119 S = d_opts->get (*pos);
120 if (EQ (S, "--grep")) {
121 ++(*pos);
122 S = d_opts->get (*pos);
123 if (! S) {
124 printf ("SilentBob grep require parameter.\n");
125 exit (1);
127 grep_loop (ENV->d_files, S);
128 exit (0);
131 return 0;
134 void grep_info ()
136 printf ("Search of text.\n");
137 printf ("Version: 1.0\n");
138 printf ("options: --grep\n");
141 DArray * plugin_init (struct env_t *env)
143 DArray * Ret;
144 struct mod_feature * pm;
146 ENV = env;
147 Ret = new DArray (1);
148 pm = CNEW (mod_feature, 1);
149 memset (pm, 0, sizeof (mod_feature));
150 pm->mod.Type = TYPE_FEATURE;
151 pm->mod.Version = strdup ("1.0");
152 pm->mod.info = grep_info;
153 pm->opt = grep_opt;
154 pm->opt2 = grep_opt2;
156 Ret->add (LPCHAR (pm));
157 return Ret;