summaryrefslogtreecommitdiffstats
path: root/lib/MDV/Draklive/Utils.pm
blob: 3fae6a9ee1c462a901d427eec48e172869264013 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package MDV::Draklive::Utils;

use MDK::Common;
use run_program;
use IPC::Open3;
use IO::Select;

use Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(directory_usage run_ run_foreach);

sub directory_usage { first(split /\s/, `du -sb $_[0]`) }

#- expand only if the pattern contains '*'
#- and matches dot characters (like shell dotglob)
sub glob__ {
    my ($pattern) = @_;
    $pattern =~ /\*/ ? glob_($pattern) : $pattern;
}

sub run_ {
    my $options = ref $_[0] eq 'HASH' ? shift @_ : {};
    my @cmd = @_;
    $options->{timeout} ||= 'never';
    my $setarch = delete $options->{setarch};
    unshift @cmd, 'setarch', $setarch if $setarch;
    print STDERR "running " . (exists $options->{root} && "(in chroot) ") . join(' ', @cmd) . "\n";
    run_program::raw($options, @cmd);
}

sub run_foreach {
    my ($foreach, @command) = @_;
    print STDERR "running " . join(' ', @command) . "\n";
    my $pid = open3(my $cmd_in, my $cmd_out, undef, @command);
    my $selector = IO::Select->new($cmd_out);
    while (my @ready = $selector->can_read) {
        foreach my $fh (@ready) {
            local $_ = scalar<$fh>;
            return if /^open3:/;
            $foreach->();
            $selector->remove($fh) if eof($fh);
        }
    }
    close($cmd_out);
    close($cmd_in);
    return waitpid($pid, 0) > 0 && !($? >> 8);
}

sub mtools_run_ {
    local $ENV{MTOOLS_SKIP_CHECK} = 1;
    &run_;
}

sub device_allocate_file {
    my ($device, $size) = @_;
    run_('dd', "of=$device", 'count=0', 'bs=1', "seek=" . removeXiBSuffix($size));
}

#- format $device as type $type
sub device_mkfs {
    my ($device, $type) = @_;
    if ($type eq 'vfat') {
        run_('mkfs.vfat', $device);
    } elsif (member($type, 'ext2', 'ext3')) {
        run_("mkfs.$type", "-m", 0, if_(!-b $device, '-F'), $device);
    } else {
        die "unable to mkfs for unsupported media type $type\n";
    }
}

1;