-
Notifications
You must be signed in to change notification settings - Fork 3
/
Helpers.pm
88 lines (77 loc) · 1.73 KB
/
Helpers.pm
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/env perl
# -*- mode: cperl; indent-tabs-mode: nil; tab-width: 3; cperl-indent-level: 3; -*-
package Helpers;
use strict;
use warnings;
use utf8;
use Carp::Always;
use autodie qw(:all);
use Exporter qw(import);
our @EXPORT = qw( trim ltrim_lines file_get_contents file_put_contents replace_in_file run_fail read_control load_packages );
sub trim {
my ($s) = @_;
$s =~ s/^\s+//g;
$s =~ s/\s+$//g;
return $s;
}
sub ltrim_lines {
my ($s) = @_;
$s =~ s/[ \t]+\n/\n/g;
return $s;
}
sub file_get_contents {
my ($fname) = @_;
local $/ = undef;
open FILE, '<:encoding(UTF-8)', $fname;
my $data = <FILE>;
close FILE;
return $data;
}
sub file_put_contents {
my ($fname,$data) = @_;
open FILE, '>:encoding(UTF-8)', $fname;
print FILE $data;
close FILE;
}
sub replace_in_file {
my ($file, $what, $with) = @_;
open my $in, '<', $file;
open my $out, '>', $file.".$$.new";
while (<$in>) {
if (/$what/) {
$_ = $with."\n";
}
print $out $_;
}
close $in;
close $out;
rename $file.".$$.new", $file;
}
sub run_fail {
my ($cmd) = @_;
my $out = `$cmd`;
if ($?) {
print STDERR "Failed to execute: $cmd\n";
exit($?);
}
return $out;
}
sub read_control {
my ($fname) = @_;
my $control = file_get_contents($fname);
$control =~ s@,\s*\n\s*@, @gs;
return $control;
}
sub load_packages {
use FindBin qw($Bin);
use JSON;
my %ps = ('order' => [], 'packages' => {});
my $pkgs = JSON->new->relaxed->decode(file_get_contents("$Bin/packages.json5"));
for my $pkg (@{$pkgs}) {
my ($pkname) = ($pkg->[0] =~ m@([-\w]+)$@);
push(@{$ps{'order'}}, $pkname);
$ps{'packages'}{$pkname} = $pkg;
}
return %ps;
}
1;