mkexec.pl 2.1KB

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