Debian Codegraph @

bcftools/vcfplugin.c

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