logbot-util 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/perl
  2. use local::lib;
  3. use v5.10;
  4. use strict;
  5. use warnings;
  6. use FindBin qw( $RealBin );
  7. use lib "$RealBin/lib";
  8. BEGIN {
  9. $ENV{TZ} = 'UTC';
  10. }
  11. $| = 1;
  12. use List::Util qw( first );
  13. use LogBot::Config qw( find_config load_all_configs load_config );
  14. use Module::Load qw( load );
  15. use Mojo::Util qw( trim );
  16. use Try::Tiny qw( catch try );
  17. my @configs;
  18. if (@ARGV && $ARGV[0] eq '--all') {
  19. shift;
  20. @configs = values %{ load_all_configs(all => !!$ENV{DEBUG}) };
  21. } else {
  22. push @configs, load_config(find_config(shift));
  23. }
  24. my @commands;
  25. foreach my $file (glob("$RealBin/lib/LogBot/CLI/*.pm")) {
  26. (my $class = substr($file, length("$RealBin/lib/"), -3)) =~ s{/}{::}g;
  27. load($file);
  28. push @commands, $class->manifest();
  29. $commands[-1]->{class} = $class;
  30. }
  31. @commands = sort { $a->{command} cmp $b->{command} } @commands;
  32. my ($command, @args) = (lc(shift // ''), @ARGV);
  33. $command = first { $_->{command} eq $command } @commands;
  34. unless (@configs && $command) {
  35. my $usage = "syntax: logbot-util <config>|--all <command> [command args]\ncommands:\n";
  36. foreach my $c (@commands) {
  37. $usage .= sprintf(" %-16s %s\n", $c->{command}, $c->{help});
  38. }
  39. die $usage;
  40. }
  41. try {
  42. $command->{class}->execute(\@configs, @args);
  43. }
  44. catch {
  45. my $error = trim($_);
  46. die $error eq 'syntax' ? 'syntax: logbot-util <config>|--all ' . $command->{usage} . "\n" : "$error\n";
  47. };