Debian Codegraph @

bcftools/vcfplugin.c.pysam.c

raw symbols SCIP
1 #include "bcftools.pysam.h"
2
3 /* vcfplugin.c -- plugin modules for operating on VCF/BCF files.
4
5 Copyright (C) 2013-2023 Genome Research Ltd.
6
7 Author: Petr Danecek <[email protected]>
8
9 Permission is hereby granted, free of charge, to any person obtaining a copy
10 of this software and associated documentation files (the "Software"), to deal
11 in the Software without restriction, including without limitation the rights
12 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 copies of the Software, and to permit persons to whom the Software is
14 furnished to do so, subject to the following conditions:
15
16 The above copyright notice and this permission notice shall be included in
17 all copies or substantial portions of the Software.
18
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 THE SOFTWARE. */
26
27 #include "config.h"
28 #include <stdio.h>
29 #include <strings.h>
30 #include <unistd.h>
31 #include <getopt.h>
32 #include <ctype.h>
33 #include <string.h>
34 #include <errno.h>
35 #include <sys/stat.h>
36 #include <sys/types.h>
37 #include <dirent.h>
38 #include <math.h>
39 #include <htslib/vcf.h>
40 #include <htslib/synced_bcf_reader.h>
41 #include <htslib/kseq.h>
42 #include <htslib/khash_str2int.h>
43 #ifdef _WIN32
44 #include <windows.h>
45 #else
46 #include <dlfcn.h>
47 #endif
48 #include "bcftools.h"
49 #include "vcmp.h"
50 #include "filter.h"
51
52 #ifdef ENABLE_BCF_PLUGINS
53
54 typedef struct _plugin_t plugin_t;
55
56 /**
57 * Plugin API:
58 * ----------
59 * const char *about(void)
60 * - short description used by 'bcftools plugin -lv'
61 *
62 * const char *usage(void)
63 * - longer description used by 'bcftools +name -h'
64 *
65 * int run(int argc, char **argv)
66 * - if implemented, the control is immediately handed over to the plugin,
67 * none of the init/process/destroy functions is called. Return 0 on
68 * success or non-zero value on error.
69 *
70 * int init(int argc, char **argv, bcf_hdr_t *in_hdr, bcf_hdr_t *out_hdr)
71 * - called once at startup, it initializes local variables.
72 * Return 1 to suppress normal VCF/BCF header output, -1 on critical
73 * errors, 0 otherwise.
74 *
75 * bcf1_t *process(bcf1_t *rec)
76 * - called for each VCF record, return NULL for no output
77 *
78 * void destroy(void)
79 * - called after all lines have been processed to clean up
80 */
81 typedef void (*dl_version_f) (const char **, const char **);
82 typedef int (*dl_run_f) (int, char **);
83 typedef int (*dl_init_f) (int, char **, bcf_hdr_t *, bcf_hdr_t *);
84 typedef char* (*dl_about_f) (void);
85 typedef char* (*dl_usage_f) (void);
86 typedef bcf1_t* (*dl_process_f) (bcf1_t *);
87 typedef void (*dl_destroy_f) (void);
88
89 struct _plugin_t
90 {
91 int argc;
92 char *name, **argv;
93 dl_version_f version;
94 dl_run_f run;
95 dl_init_f init;
96 dl_about_f about;
97 dl_usage_f usage;
98 dl_process_f process;
99 dl_destroy_f destroy;
100 void *handle;
101 };
102
103
104 struct _args_t;
105
106 typedef struct _rm_tag_t
107 {
108 char *key;
109 int hdr_id;
110 void (*handler)(struct _args_t *, bcf1_t *, struct _rm_tag_t *);
111 }
112 rm_tag_t;
113
114 typedef struct
115 {
116 char **cols;
117 int ncols, mcols;
118 char **als;
119 int nals, mals;
120 kstring_t line;
121 int rid, start, end;
122 }
123 annot_line_t;
124
125 typedef struct _annot_col_t
126 {
127 int icol, replace;
128 char *hdr_key;
129 int (*setter)(struct _args_t *, bcf1_t *, struct _annot_col_t *, void*);
130 }
131 annot_col_t;
132
133 // Logic of the filters: include or exclude sites which match the filters?
134 #define FLT_INCLUDE 1
135 #define FLT_EXCLUDE 2
136
137 typedef struct _args_t
138 {
139 bcf_srs_t *files;
140 bcf_hdr_t *hdr, *hdr_out;
141 htsFile *out_fh;
142 int output_type, n_threads, clevel;
143
144 filter_t *filter;
145 char *filter_str;
146 int filter_logic; // include or exclude sites which match the filters? One of FLT_INCLUDE/FLT_EXCLUDE
147
148 plugin_t plugin;
149 int nplugin_paths;
150 char **plugin_paths;
151
152 char **argv, *output_fname, *regions_list, *targets_list;
153 int argc, drop_header, verbose, record_cmd_line, plist_only;
154 char *index_fn;
155 int write_index;
156 }
157 args_t;
158
159 char *msprintf(const char *fmt, ...);
160
161 static void add_plugin_paths(args_t *args, const char *path)
162 {
163 while (1)
164 {
165 size_t len = strcspn(path, HTS_PATH_SEPARATOR_STR);
166
167 if ( len == 0 )
168 {
169 #ifdef PLUGINPATH
170 add_plugin_paths(args, PLUGINPATH);
171 #endif
172 }
173 else
174 {
175 char *dir = (char *) malloc(len + 1);
176 strncpy(dir, path, len);
177 dir[len] = '\0';
178
179 struct stat st;
180 if ( stat(dir, &st) == 0 )
181 {
182 args->plugin_paths = (char**) realloc(args->plugin_paths,sizeof(char*)*(args->nplugin_paths+1));
183 args->plugin_paths[args->nplugin_paths] = dir;
184 args->nplugin_paths++;
185 if ( args->verbose > 1 && strcmp(".",dir) ) fprintf(bcftools_stderr, "plugin directory %s .. ok\n", dir);
186 }
187 else
188 {
189 if ( args->verbose > 1 ) fprintf(bcftools_stderr, "plugin directory %s .. %s\n", dir, strerror(errno));
190 free(dir);
191 }
192
193 }
194
195 path += len;
196 if ( *path == HTS_PATH_SEPARATOR_CHAR ) path++;
197 else break;
198 }
199 }
200
201 static void init_plugin_paths(args_t *args)
202 {
203 if ( args->nplugin_paths!=-1 ) return;
204
205 args->nplugin_paths = 0;
206 args->plugin_paths = NULL;
207
208 char *path = getenv("BCFTOOLS_PLUGINS");
209 add_plugin_paths(args, path ? path : "");
210 }
211
212 static void *dlopen_plugin(args_t *args, const char *fname)
213 {
214 init_plugin_paths(args);
215
216 void *handle;
217 char *tmp;
218 int is_absolute_path = 0;
219 #ifdef _WIN32
220 // Windows accepts both forward slash (/) and backslash (\) as folder separator
221 // and can have any path prefixed by the drive letter and a colon (:).
222 if ( fname[0]=='/' || fname[0]=='\\') is_absolute_path = 1;
223 else if ( fname[0] && fname[1]==':' && (fname[2]=='/' || fname[2]=='\\') ) is_absolute_path = 1;
224 #else
225 if ( fname[0]=='/' ) is_absolute_path = 1;
226 #endif
227
228 kstring_t err = {0,0,0};
229 if ( !is_absolute_path )
230 {
231 int i;
232 for (i=0; i<args->nplugin_paths; i++)
233 {
234 tmp = msprintf("%s/%s%s", args->plugin_paths[i], fname, PLUGIN_EXT);
235 #ifdef _WIN32
236 handle = LoadLibraryA(tmp);
237 #else
238 handle = dlopen(tmp, RTLD_NOW); // valgrind complains about unfreed memory, not our problem though
239 #endif
240 if ( !handle )
241 #ifdef _WIN32
242 ksprintf(&err,"LoadLibraryA .. %lu\n", GetLastError());
243 #else
244 ksprintf(&err,"%s:\n\tdlopen .. %s\n", tmp,dlerror());
245 #endif
246 else if ( args->verbose > 1 )
247 fprintf(bcftools_stderr,"%s:\n\tplugin open .. ok\n", tmp);
248 free(tmp);
249 if ( handle ) return handle;
250 }
251 }
252
253 #ifdef _WIN32
254 handle = LoadLibraryA(fname);
255 #else
256 handle = dlopen(fname, RTLD_NOW);
257 #endif
258 if ( !handle )
259 #ifdef _WIN32
260 ksprintf(&err,"LoadLibraryA .. %lu\n", GetLastError());
261 #else
262 ksprintf(&err,"%s:\n\tdlopen .. %s\n", fname,dlerror());
263 #endif
264 else if ( args->verbose > 1 )
265 fprintf(bcftools_stderr,"%s:\n\tplugin open .. ok\n", fname);
266
267 if ( !handle && (!args->plist_only || args->verbose>1) )
268 fprintf(bcftools_stderr,"%s",err.s);
269 free(err.s);
270
271 return handle;
272 }
273
274 static void print_plugin_usage_hint(const char *name)
275 {
276 if ( name )
277 fprintf(bcftools_stderr, "\nThe bcftools plugin \"%s\" was not found or is not functional", name);
278 else
279 fprintf(bcftools_stderr, "\nNo functional bcftools plugins were found");
280 if ( !getenv("BCFTOOLS_PLUGINS") )
281 {
282 fprintf(bcftools_stderr,". The environment variable BCFTOOLS_PLUGINS is not set");
283 #ifdef PLUGINPATH
284 fprintf(bcftools_stderr,"\nand no usable plugins were found in %s", PLUGINPATH);
285 #endif
286 fprintf(bcftools_stderr,".\n\n");
287 }
288 else
289 {
290 fprintf(bcftools_stderr,
291 " in\n\tBCFTOOLS_PLUGINS=\"%s\".\n\n"
292 "- Is the plugin path correct?\n\n"
293 "- Run \"bcftools plugin -l\" or \"bcftools plugin -lvv\" for a list of available plugins.\n"
294 "\n",
295 getenv("BCFTOOLS_PLUGINS")
296 );
297 }
298 }
299
300 static int load_plugin(args_t *args, const char *fname, int exit_on_error, plugin_t *plugin)
301 {
302 plugin->name = strdup(fname);
303
304 plugin->handle = dlopen_plugin(args, fname);
305 if ( !plugin->handle )
306 {
307 if ( exit_on_error )
308 {
309 print_plugin_usage_hint(fname);
310 error("Could not load \"%s\".\n\n", fname);
311 }
312 return -1;
313 }
314
315 #ifdef _WIN32
316 plugin->init = (dl_init_f) GetProcAddress(plugin->handle, "init");
317 if ( plugin->init && args->verbose > 1 ) fprintf(bcftools_stderr,"\tinit .. ok\n");
318
319 plugin->run = (dl_run_f) GetProcAddress(plugin->handle, "run");
320 if ( plugin->run && args->verbose > 1 ) fprintf(bcftools_stderr,"\trun .. ok\n");
321
322 if ( !plugin->init && !plugin->run )
323 {
324 if ( exit_on_error ) error("Could not initialize %s, neither run or init found \n", plugin->name);
325 else if ( args->verbose > 1 ) fprintf(bcftools_stderr,"\tinit/run .. not found\n");
326 return -1;
327 }
328
329 plugin->version = (dl_version_f) GetProcAddress(plugin->handle, "version");
330 if ( !plugin->version )
331 {
332 if ( exit_on_error ) error("Could not initialize %s: version string not found\n", plugin->name);
333 else if ( args->verbose > 1 ) fprintf(bcftools_stderr,"\tversion .. not found\n");
334 return -1;
335 }
336
337 plugin->about = (dl_about_f) GetProcAddress(plugin->handle, "about");
338 if ( !plugin->about )
339 {
340 if ( exit_on_error ) error("Could not initialize %s: about string not found\n", plugin->name);
341 return -1;
342 }
343
344 plugin->usage = (dl_about_f) GetProcAddress(plugin->handle, "usage");
345 if ( !plugin->usage )
346 plugin->usage = plugin->about;
347
348 if ( plugin->run ) return 0;
349
350 plugin->process = (dl_process_f) GetProcAddress(plugin->handle, "process");
351 if ( !plugin->process )
352 {
353 if ( exit_on_error ) error("Could not initialize %s: process method not found\n", plugin->name);
354 return -1;
355 }
356
357 plugin->destroy = (dl_destroy_f) GetProcAddress(plugin->handle, "destroy");
358 if ( !plugin->destroy )
359 {
360 if ( exit_on_error ) error("Could not initialize %s: destroy method not found\n", plugin->name);
361 return -1;
362 }
363 #else
364 dlerror();
365 plugin->init = (dl_init_f) dlsym(plugin->handle, "init");
366 char *ret = dlerror();
367 if ( ret )
368 plugin->init = NULL;
369 else
370 if ( args->verbose > 1 ) fprintf(bcftools_stderr,"\tinit .. ok\n");
371
372 plugin->run = (dl_run_f) dlsym(plugin->handle, "run");
373 ret = dlerror();
374 if ( ret )
375 plugin->run = NULL;
376 else
377 if ( args->verbose > 1 ) fprintf(bcftools_stderr,"\trun .. ok\n");
378
379 if ( !plugin->init && !plugin->run )
380 {
381 if ( exit_on_error ) error("Could not initialize %s, neither run or init found \n", plugin->name);
382 else if ( args->verbose > 1 ) fprintf(bcftools_stderr,"\tinit/run .. not found\n");
383 return -1;
384 }
385
386 plugin->version = (dl_version_f) dlsym(plugin->handle, "version");
387 ret = dlerror();
388 if ( ret )
389 {
390 if ( exit_on_error ) error("Could not initialize %s, version string not found\n", plugin->name);
391 else if ( args->verbose > 1 ) fprintf(bcftools_stderr,"\tversion .. not found\n");
392 return -1;
393 }
394
395 plugin->about = (dl_about_f) dlsym(plugin->handle, "about");
396 ret = dlerror();
397 if ( ret )
398 {
399 if ( exit_on_error ) error("Could not initialize %s: %s\n", plugin->name, ret);
400 return -1;
401 }
402
403 plugin->usage = (dl_about_f) dlsym(plugin->handle, "usage");
404 ret = dlerror();
405 if ( ret )
406 plugin->usage = plugin->about;
407
408 if ( plugin->run ) return 0;
409
410 plugin->process = (dl_process_f) dlsym(plugin->handle, "process");
411 ret = dlerror();
412 if ( ret )
413 {
414 if ( exit_on_error ) error("Could not initialize %s: %s\n", plugin->name, ret);
415 return -1;
416 }
417
418 plugin->destroy = (dl_destroy_f) dlsym(plugin->handle, "destroy");
419 ret = dlerror();
420 if ( ret )
421 {
422 if ( exit_on_error ) error("Could not initialize %s: %s\n", plugin->name, ret);
423 return -1;
424 }
425 #endif
426
427 return 0;
428 }
429
430 static void check_version(args_t *args)
431 {
432 static int warned_bcftools = 0, warned_htslib = 0;
433 const char *bver, *hver;
434 args->plugin.version(&bver, &hver);
435 if ( strcmp(bver,bcftools_version()) && !warned_bcftools )
436 {
437 fprintf(bcftools_stderr,"WARNING: bcftools version mismatch .. bcftools at %s, the plugin \"%s\" at %s\n", bcftools_version(),args->plugin.name,bver);
438 warned_bcftools = 1;
439 }
440 if ( strcmp(hver,hts_version()) && !warned_htslib )
441 {
442 fprintf(bcftools_stderr,"WARNING: htslib version mismatch .. bcftools at %s, the plugin \"%s\" at %s\n", hts_version(),args->plugin.name,hver);
443 warned_htslib = 1;
444 }
445 }
446
447 static void init_plugin(args_t *args)
448 {
449 int ret = args->plugin.init(args->plugin.argc,args->plugin.argv,args->hdr,args->hdr_out);
450 if ( ret<0 ) error("The plugin exited with an error.\n");
451 check_version(args);
452 args->drop_header += ret;
453 }
454
455 static int cmp_plugin_name(const void *p1, const void *p2)
456 {
457 plugin_t *a = (plugin_t*) p1;
458 plugin_t *b = (plugin_t*) p2;
459 return strcmp(a->name,b->name);
460 }
461
462 // If args=NULL then returns the number of plugins available. Otherwise prints the
463 // plugins on bcftools_stdout and returns 0 on success.
464 static int list_plugins(args_t *args)
465 {
466 plugin_t *plugins = NULL;
467 int nplugins = 0, mplugins = 0;
468
469 int count_only = 0;
470 args_t _args;
471 if ( !args )
472 {
473 memset(&_args,0,sizeof(_args));
474 args = &_args;
475 args->nplugin_paths = -1;
476 count_only = 1;
477 }
478 init_plugin_paths(args);
479
480 kstring_t str = {0,0,0};
481 int plugin_ext_len = strlen(PLUGIN_EXT);
482 int i;
483 for (i=0; i<args->nplugin_paths; i++)
484 {
485 DIR *dp = opendir(args->plugin_paths[i]);
486 if ( dp==NULL ) continue;
487
488 struct dirent *ep;
489 while ( (ep=readdir(dp)) )
490 {
491 int len = strlen(ep->d_name);
492 if ( strcasecmp(PLUGIN_EXT,ep->d_name+len-plugin_ext_len) ) continue;
493 str.l = 0;
494 ksprintf(&str,"%s/%s", args->plugin_paths[i],ep->d_name);
495 hts_expand(plugin_t, nplugins+1, mplugins, plugins);
496 if ( load_plugin(args, str.s, 0, &plugins[nplugins]) < 0 ) continue;
497 nplugins++;
498 str.l = 0;
499 kputs(ep->d_name, &str);
500 int l = str.l - 1;
501 while ( l>=0 && str.s[l]!='.' ) l--;
502 if ( l>=0 ) str.s[l] = 0;
503 free(plugins[nplugins-1].name);
504 plugins[nplugins-1].name = strdup(str.s); // use a short name
505 }
506 closedir(dp);
507 }
508 if ( count_only )
509 {
510 free(str.s);
511 return nplugins;
512 }
513 if ( nplugins )
514 {
515 qsort(plugins, nplugins, sizeof(plugins[0]), cmp_plugin_name);
516
517 for (i=0; i<nplugins; i++)
518 {
519 if ( args->verbose )
520 fprintf(bcftools_stdout, "\n-- %s --\n%s", plugins[i].name, plugins[i].about());
521 else
522 fprintf(bcftools_stdout, "%s\n", plugins[i].name);
523 }
524 if ( args->verbose ) fprintf(bcftools_stdout, "\n");
525 }
526 else
527 print_plugin_usage_hint(NULL);
528 free(str.s);
529 return nplugins ? 0 : 1;
530 }
531 int count_plugins(void)
532 {
533 return list_plugins(NULL);
534 }
535
536 static void init_data(args_t *args)
537 {
538 args->hdr = args->files->readers[0].header;
539 args->hdr_out = bcf_hdr_dup(args->hdr);
540
541 init_plugin(args);
542
543 if ( args->filter_str )
544 args->filter = filter_init(args->hdr, args->filter_str);
545
546 if (args->record_cmd_line) bcf_hdr_append_version(args->hdr_out, args->argc, args->argv, "bcftools_plugin");
547 if ( !args->drop_header )
548 {
549 char wmode[8];
550 set_wmode(wmode,args->output_type,args->output_fname,args->clevel);
551 args->out_fh = hts_open(args->output_fname ? args->output_fname : "-", wmode);
552 if ( args->out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->output_fname, strerror(errno));
553 if ( args->n_threads ) hts_set_threads(args->out_fh, args->n_threads);
554 if ( bcf_hdr_write(args->out_fh, args->hdr_out)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
555 if ( init_index2(args->out_fh,args->hdr_out,args->output_fname,
556 &args->index_fn, args->write_index)<0 )
557 error("Error: failed to initialise index for %s\n",args->output_fname);
558 }
559 }
560
561 static void destroy_data(args_t *args)
562 {
563 free(args->plugin.name);
564 if ( args->plugin.destroy ) args->plugin.destroy();
565 #ifdef _WIN32
566 FreeLibrary(args->plugin.handle);
567 #else
568 dlclose(args->plugin.handle);
569 #endif
570 if ( args->hdr_out ) bcf_hdr_destroy(args->hdr_out);
571 if ( args->nplugin_paths>0 )
572 {
573 int i;
574 for (i=0; i<args->nplugin_paths; i++) free(args->plugin_paths[i]);
575 free(args->plugin_paths);
576 }
577 if ( args->filter )
578 filter_destroy(args->filter);
579 if (args->out_fh )
580 {
581 if ( args->write_index )
582 {
583 if ( bcf_idx_save(args->out_fh)<0 )
584 {
585 if ( hts_close(args->out_fh)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"bcftools_stdout");
586 error("Error: cannot write to index %s\n", args->index_fn);
587 }
588 free(args->index_fn);
589 }
590 if ( hts_close(args->out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->output_fname);
591 }
592 }
593
594 static void usage(args_t *args)
595 {
596 fprintf(bcftools_stderr, "\n");
597 fprintf(bcftools_stderr, "About: Run user defined plugin\n");
598 fprintf(bcftools_stderr, "Usage: bcftools plugin <name> [OPTIONS] <file> [-- PLUGIN_OPTIONS]\n");
599 fprintf(bcftools_stderr, " bcftools +name [OPTIONS] <file> [-- PLUGIN_OPTIONS]\n");
600 fprintf(bcftools_stderr, "\n");
601 fprintf(bcftools_stderr, "VCF input options:\n");
602 fprintf(bcftools_stderr, " -e, --exclude EXPR Exclude sites for which the expression is true\n");
603 fprintf(bcftools_stderr, " -i, --include EXPR Select sites for which the expression is true\n");
604 fprintf(bcftools_stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n");
605 fprintf(bcftools_stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n");
606 fprintf(bcftools_stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
607 fprintf(bcftools_stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n");
608 fprintf(bcftools_stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n");
609 fprintf(bcftools_stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n");
610 fprintf(bcftools_stderr, "VCF output options:\n");
611 fprintf(bcftools_stderr, " --no-version Do not append version and command line to the header\n");
612 fprintf(bcftools_stderr, " -o, --output FILE Write output to a file [standard output]\n");
613 fprintf(bcftools_stderr, " -O, --output-type u|b|v|z[0-9] u/b: un/compressed BCF, v/z: un/compressed VCF, 0-9: compression level [v]\n");
614 fprintf(bcftools_stderr, " --threads INTT Use multithreading with <int> worker threads [0]\n");
615 fprintf(bcftools_stderr, "Plugin options:\n");
616 fprintf(bcftools_stderr, " -h, --help List plugin's options\n");
617 fprintf(bcftools_stderr, " -l, --list-plugins List available plugins. See BCFTOOLS_PLUGINS environment variable and man page for details\n");
618 fprintf(bcftools_stderr, " -v, --verbose Print verbose information, -vv increases verbosity\n");
619 fprintf(bcftools_stderr, " -V, --version Print version string and exit\n");
620 fprintf(bcftools_stderr, " -W, --write-index[=FMT] Automatically index the output files [off]\n");
621 fprintf(bcftools_stderr, "\n");
622 bcftools_exit(1);
623 }
624
625 static int is_verbose(int argc, char *argv[])
626 {
627 int c, verbose = 0, opterr_ori = opterr;
628 static struct option loptions[] =
629 {
630 {"verbose",no_argument,NULL,'v'},
631 {NULL,0,NULL,0}
632 };
633 opterr = 0;
634 while ((c = getopt_long(argc, argv, "-v",loptions,NULL)) >= 0)
635 {
636 switch (c) {
637 case 'v': verbose++; break;
638 case 1:
639 default: break;
640 }
641 }
642 opterr = opterr_ori;
643 optind = 0;
644 return verbose;
645 }
646 int main_plugin(int argc, char *argv[])
647 {
648 int c;
649 args_t *args = (args_t*) calloc(1,sizeof(args_t));
650 args->argc = argc; args->argv = argv;
651 args->output_fname = "-";
652 args->output_type = FT_VCF;
653 args->n_threads = 0;
654 args->record_cmd_line = 1;
655 args->nplugin_paths = -1;
656 args->clevel = -1;
657 int regions_is_file = 0, targets_is_file = 0, usage_only = 0, version_only = 0;
658 int regions_overlap = 1;
659 int targets_overlap = 0;
660
661 if ( argc==1 ) usage(args);
662 char *plugin_name = NULL;
663 if ( argv[1][0]!='-' )
664 {
665 args->verbose = is_verbose(argc, argv);
666 plugin_name = argv[1];
667 argc--;
668 argv++;
669 load_plugin(args, plugin_name, 1, &args->plugin);
670 if ( args->plugin.run )
671 {
672 check_version(args);
673 int ret = args->plugin.run(argc, argv);
674 destroy_data(args);
675 free(args);
676 return ret;
677 }
678 }
679
680 static struct option loptions[] =
681 {
682 {"version",no_argument,NULL,'V'},
683 {"verbose",no_argument,NULL,'v'},
684 {"help",no_argument,NULL,'h'},
685 {"list-plugins",no_argument,NULL,'l'},
686 {"output",required_argument,NULL,'o'},
687 {"output-type",required_argument,NULL,'O'},
688 {"threads",required_argument,NULL,9},
689 {"include",required_argument,NULL,'i'},
690 {"exclude",required_argument,NULL,'e'},
691 {"regions",required_argument,NULL,'r'},
692 {"regions-file",required_argument,NULL,'R'},
693 {"regions-overlap",required_argument,NULL,1},
694 {"targets",required_argument,NULL,'t'},
695 {"targets-file",required_argument,NULL,'T'},
696 {"targets-overlap",required_argument,NULL,2},
697 {"no-version",no_argument,NULL,8},
698 {"write-index",optional_argument,NULL,'W'},
699 {NULL,0,NULL,0}
700 };
701 char *tmp;
702 while ((c = getopt_long(argc, argv, "h?o:O:r:R:t:T:li:e:vVW::",loptions,NULL)) >= 0)
703 {
704 switch (c) {
705 case 'V': version_only = 1; break;
706 case 'v': args->verbose++; break;
707 case 'o': args->output_fname = optarg; break;
708 case 'O':
709 switch (optarg[0]) {
710 case 'b': args->output_type = FT_BCF_GZ; break;
711 case 'u': args->output_type = FT_BCF; break;
712 case 'z': args->output_type = FT_VCF_GZ; break;
713 case 'v': args->output_type = FT_VCF; break;
714 default:
715 {
716 args->clevel = strtol(optarg,&tmp,10);
717 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg);
718 }
719 };
720 if ( optarg[1] )
721 {
722 args->clevel = strtol(optarg+1,&tmp,10);
723 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1);
724 }
725 break;
726 case 'e':
727 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
728 args->filter_str = optarg; args->filter_logic |= FLT_EXCLUDE; break;
729 case 'i':
730 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
731 args->filter_str = optarg; args->filter_logic |= FLT_INCLUDE; break;
732 case 'r': args->regions_list = optarg; break;
733 case 'R': args->regions_list = optarg; regions_is_file = 1; break;
734 case 't': args->targets_list = optarg; break;
735 case 'T': args->targets_list = optarg; targets_is_file = 1; break;
736 case 'l': args->plist_only = 1; break;
737 case 1 :
738 regions_overlap = parse_overlap_option(optarg);
739 if ( regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
740 break;
741 case 2 :
742 targets_overlap = parse_overlap_option(optarg);
743 if ( targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg);
744 break;
745 case 9 : args->n_threads = strtol(optarg, 0, 0); break;
746 case 8 : args->record_cmd_line = 0; break;
747 case 'W':
748 if (!(args->write_index = write_index_parse(optarg)))
749 error("Unsupported index format '%s'\n", optarg);
750 break;
751 case '?':
752 case 'h': usage_only = 1; break;
753 default: error("Unknown argument: %s\n", optarg);
754 }
755 }
756 if ( args->plist_only ) return list_plugins(args);
757 if ( !plugin_name ) usage(args);
758
759 if ( version_only )
760 {
761 const char *bver, *hver;
762 args->plugin.version(&bver, &hver);
763 fprintf(bcftools_stdout, "bcftools %s using htslib %s\n", bcftools_version(), hts_version());
764 fprintf(bcftools_stdout, "plugin at %s using htslib %s\n\n", bver, hver);
765 return 0;
766 }
767
768 if ( usage_only )
769 {
770 if ( args->plugin.usage )
771 fprintf(bcftools_stderr,"%s",args->plugin.usage());
772 else
773 fprintf(bcftools_stderr,"Usage: bcftools +%s [General Options] -- [Plugin Options]\n",plugin_name);
774 return 0;
775 }
776
777 char *fname = NULL;
778 if ( optind>=argc || (argv[optind][0]=='-' && argv[optind][1]) )
779 {
780 args->plugin.argc = argc - optind + 1;
781 args->plugin.argv = argv + optind - 1;
782
783 if ( !isatty(fileno((FILE *)stdin)) ) fname = "-"; // reading from stdin
784 else if ( optind>=argc ) usage(args);
785 else
786 {
787 optind = 1;
788 init_plugin(args);
789 }
790 }
791 else
792 {
793 fname = argv[optind];
794 args->plugin.argc = argc - optind;
795 args->plugin.argv = argv + optind;
796 }
797 optind = 0;
798
799 args->files = bcf_sr_init();
800 if ( args->regions_list )
801 {
802 bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,regions_overlap);
803 if ( bcf_sr_set_regions(args->files, args->regions_list, regions_is_file)<0 )
804 error("Failed to read the regions: %s\n", args->regions_list);
805 }
806 if ( args->targets_list )
807 {
808 bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,targets_overlap);
809 if ( bcf_sr_set_targets(args->files, args->targets_list, targets_is_file, 0)<0 )
810 error("Failed to read the targets: %s\n", args->targets_list);
811 args->files->collapse |= COLLAPSE_SOME;
812 }
813 if ( !bcf_sr_add_reader(args->files, fname) ) error("Failed to read from %s: %s\n", !strcmp("-",fname)?"standard input":fname,bcf_sr_strerror(args->files->errnum));
814
815 init_data(args);
816 while ( bcf_sr_next_line(args->files) )
817 {
818 bcf1_t *line = bcf_sr_get_line(args->files,0);
819 if ( args->filter )
820 {
821 int pass = filter_test(args->filter, line, NULL);
822 if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1;
823 if ( !pass ) continue;
824 }
825 line = args->plugin.process(line);
826 if ( line )
827 {
828 if ( line->errcode ) error("[E::main_plugin] Unchecked error (%d), exiting\n",line->errcode);
829 if ( bcf_write1(args->out_fh, args->hdr_out, line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
830 }
831 }
832 destroy_data(args);
833 bcf_sr_destroy(args->files);
834 free(args);
835 return 0;
836 }
837
838 #else /* ENABLE_BCF_PLUGINS */
839
840 int main_plugin(int argc, char *argv[])
841 {
842 fprintf(bcftools_stderr, "bcftools plugins are disabled. To use them, you will need to rebuild\n"
843 "bcftools from the source distribution with plugins enabled.\n");
844 return 1;
845 }
846
847 #endif /* ENABLE_BCF_PLUGINS */