Functions.pm 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package Dpkg::Source::Functions;
  2. use strict;
  3. use warnings;
  4. use Exporter;
  5. our @ISA = qw(Exporter);
  6. our @EXPORT_OK = qw(erasedir fixperms is_binary);
  7. use Dpkg::ErrorHandling qw(syserr subprocerr failure);
  8. use Dpkg::Gettext;
  9. use Dpkg::IPC;
  10. use POSIX;
  11. sub erasedir {
  12. my ($dir) = @_;
  13. if (not lstat($dir)) {
  14. return if $! == ENOENT;
  15. syserr(_g("cannot stat directory %s (before removal)"), $dir);
  16. }
  17. system 'rm','-rf','--',$dir;
  18. subprocerr("rm -rf $dir") if $?;
  19. if (not stat($dir)) {
  20. return if $! == ENOENT;
  21. syserr(_g("unable to check for removal of dir `%s'"), $dir);
  22. }
  23. failure(_g("rm -rf failed to remove `%s'"), $dir);
  24. }
  25. sub fixperms {
  26. my ($dir) = @_;
  27. my ($mode, $modes_set, $i, $j);
  28. # Unfortunately tar insists on applying our umask _to the original
  29. # permissions_ rather than mostly-ignoring the original
  30. # permissions. We fix it up with chmod -R (which saves us some
  31. # work) but we have to construct a u+/- string which is a bit
  32. # of a palaver. (Numeric doesn't work because we need [ugo]+X
  33. # and [ugo]=<stuff> doesn't work because that unsets sgid on dirs.)
  34. $mode = 0777 & ~umask;
  35. for ($i = 0; $i < 9; $i += 3) {
  36. $modes_set .= ',' if $i;
  37. $modes_set .= qw(u g o)[$i/3];
  38. for ($j = 0; $j < 3; $j++) {
  39. $modes_set .= $mode & (0400 >> ($i+$j)) ? '+' : '-';
  40. $modes_set .= qw(r w X)[$j];
  41. }
  42. }
  43. system('chmod', '-R', $modes_set, '--', $dir);
  44. subprocerr("chmod -R $modes_set $dir") if $?;
  45. }
  46. sub is_binary($) {
  47. my ($file) = @_;
  48. # Use diff to check if it's a binary file
  49. my $diffgen;
  50. my $diff_pid = fork_and_exec(
  51. 'exec' => [ 'diff', '-u', '--', '/dev/null', $file ],
  52. 'env' => { LC_ALL => 'C', LANG => 'C', TZ => 'UTC0' },
  53. 'to_pipe' => \$diffgen
  54. );
  55. my $result = 0;
  56. while (<$diffgen>) {
  57. if (m/^binary/i) {
  58. $result = 1;
  59. last;
  60. } elsif (m/^[-+\@ ]/) {
  61. $result = 0;
  62. last;
  63. }
  64. }
  65. close($diffgen) or syserr("close on diff pipe");
  66. wait_child($diff_pid, nocheck => 1, cmdline => "diff -u -- /dev/null $file");
  67. return $result;
  68. }
  69. # vim: set et sw=4 ts=8
  70. 1;