mkexec.pl 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #!/usr/bin/perl
  2. # make an executeble file
  3. use strict;
  4. use warnings;
  5. sub usage; sub mkexec; sub guesstype; sub getcmd; sub launch_editor;
  6. my $DEFAULT_TYPE = 'pl';
  7. my $DEFAULT_MODE = 0755;
  8. my $name = shift or usage;
  9. my $type = ($ARGV[0] ? shift : guesstype $name);
  10. my $bang = {
  11. pl => `which perl`,
  12. sh => `which sh`,
  13. py => `which python`,
  14. bash => `which bash`,
  15. sed => `which sed`,
  16. bc => `which bc`
  17. };
  18. my $template = {
  19. pl => "use strict;\nuse warnings;\n",
  20. py => "if __name__ == '__main__':\n"
  21. };
  22. my $editors = [ qw/ vim editor / ];
  23. my $cmds;
  24. $cmds->{vim}->{test} = "vim --version 2>/dev/null";
  25. $cmds->{vim}->{run} = "vim +\"normal G\$\" '%s'";
  26. $cmds->{editor}->{test} = "editor --version 2>/dev/null";
  27. $cmds->{editor}->{run} = "editor '%s'";
  28. if (exists $bang->{$type}) {
  29. -e $name || mkexec $name, mkbody($type);
  30. chmod $DEFAULT_MODE, $name;
  31. launch_editor $name;
  32. } else {
  33. die "unknown type: $type\n";
  34. }
  35. sub usage {
  36. print STDERR "usage: $0 filename [type]\n";
  37. exit 0;
  38. }
  39. sub guesstype {
  40. my $name = shift;
  41. my ($ext) = $name =~ m|\.(\w+)$|;
  42. return ( $ext ? $ext : $DEFAULT_TYPE);
  43. }
  44. sub mkbody {
  45. my $type = shift;
  46. my $tmpl = "";
  47. $tmpl .= $template->{$type} if exists $template->{$type};
  48. return sprintf "#!%s\n%s\n", $bang->{$type}, $tmpl;
  49. }
  50. sub mkexec {
  51. my ($name, $body) = @_;
  52. open EXE, ">", $name || die "cannot open $name for writing: $!\n";
  53. -W EXE || die "file $name is not writable\n";
  54. print EXE $body;
  55. close EXE || die "cannot close $name: $!\n";
  56. }
  57. sub get_cmd {
  58. foreach (@$editors) {
  59. return $cmds->{$_}->{run} if `$cmds->{$_}->{test}`
  60. }
  61. warn "no supported editor available\n";
  62. return;
  63. }
  64. sub launch_editor {
  65. my $name = shift;
  66. my $form = get_cmd;
  67. if ($form) {
  68. my $command = sprintf get_cmd, $name;
  69. exec "$command";
  70. } else { return }
  71. warn "failed to launch editor: $form\n";
  72. }