Functions.pm 2.2 KB

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