File regex_replace of Package obs-service-regex_replace
#!/usr/bin/perl
# (C) 2010 by Adrian Schröter <adrian@suse.de>
# (C) 2014 martin.koegler@chello.at
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# See http://www.gnu.org/licenses/gpl-2.0.html for full license text.
my $regex;
my $replace;
my $outdir;
my @files;
use strict;
use warnings;
sub usage()
{
print<<END
Open Build Service source service "regex_replace"
Used to update build files using regular expressions.
Required:
--outdir: output directory for modified sources
--regex: regular expression
--replace: replacement expression
--file: modify this build description. maybe used multiple times.
END
;
exit;
}
while (@ARGV) {
usage() if $ARGV[0] eq '--help';
if ($ARGV[0] eq '--outdir') {
shift @ARGV;
$outdir = shift @ARGV;
next;
} elsif ($ARGV[0] eq '--regex') {
shift @ARGV;
$regex = shift @ARGV;
next;
} elsif ($ARGV[0] eq '--replace') {
shift @ARGV;
$replace = shift @ARGV;
next;
} elsif ($ARGV[0] eq '--file') {
shift @ARGV;
my $file = shift @ARGV;
# avoid jailbreak with ..
$file =~ s#.*/(.*)$#$1#;
push @files, $file;
next;
} else {
die("Unknown argument $ARGV[0]!");
}
last;
}
usage() unless $outdir;
usage() unless $regex;
usage() unless $replace;
usage() unless @files;
# to replace tags in .spec and .dsc files
sub replace_file {
my ($filename, $regex, $replace) = @_;
local *R;
local *W;
if (!open(R, '<', $filename)) {
die("unable to read $filename: $!\n");
return undef;
}
if (!open(W, '>', "$outdir/.$filename")) {
die("unable to write .$filename: $!\n");
return undef;
}
my $line;
while (defined($line = <R>)) {
$line =~ s/\n$//;
$line =~ s/$regex/$replace/g;
print W "$line\n";
}
close R;
close W;
rename("$outdir/.$filename", "$outdir/$filename") || die("rename failed");
}
for my $pattern (@files) {
my @files = glob $pattern;
for my $file (@files) {
replace_file($file, $regex, $replace);
}
}