summaryrefslogtreecommitdiff
path: root/Tools/scripts/splitpatch.pl
blob: ddac4b33394c7d68c2b2620164b26c6a7cd1f785 (plain) (blame)
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#! /usr/bin/perl -w
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42)
# <tobez@FreeBSD.org> wrote this file.  As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return.   Anton Berezin
# ----------------------------------------------------------------------------
#
# $FreeBSD$
use strict;

# good tests:
# /usr/ports/archivers/zoo/files/patch-aa  (context diff)
# /usr/ports/astro/xplanet/files/patch-aa  (unified with paths)

my ($in,$fl,$abort,$state,$out);

if (!@ARGV || $ARGV[0] =~ /^-/) {
	print STDERR "Usage:
	$0 patchfile ...
"
}

while (@ARGV) {
	$in = shift;
	$state = \&nofile;
	if (open IN, "< $in") {
		$abort = 0;
		$out = "";
		$fl = "";
		while (<IN>) {
			$state->();
			last if $abort;
		}
		close IN;
		if ($out && !$abort) {
			print "Wrote $out\n";
		}
	} else {
		print STDERR "cannot open $in: $!\n";
	}
}

sub nofile
{
	if (/^\*\*\*\s+/ && !/^\*\*\*\s+\d+,\d+\s+/) {
		$state = \&cstart;
		$fl = $_;
	} elsif (/^---\s+/ && !/^---\s+\d+,\d+\s+/) {
		$state = \&ustart;
		$fl = $_;
	}
}

sub cstart
{
	if (!/^---\s+\d+,\d+\s+/ && /^---\s+(\S+)\s+/) {
		$state = \&body;
		$out = $1;
		$out =~ s|/|__|g;
		$out = "patch-$out";
		if (open OUT, "> $out") {
			print OUT $fl;
			print OUT $_;
		} else {
			print STDERR "Cannot create $out: $!, aborting\n";
			$abort = 1;
		}
	} else {
		print STDERR "Bad context diff in $in, aborting\n";
		$abort = 1;
	}
}

sub ustart
{
	if (/^\+\+\+\s+(\S+)\s+/) {
		$state = \&body;
		$out = $1;
		$out =~ s|/|__|g;
		$out = "patch-$out";
		if (open OUT, "> $out") {
			print OUT $fl;
			print OUT $_;
		} else {
			print STDERR "Cannot create $out: $!, aborting\n";
			$abort = 1;
		}
	} else {
		print STDERR "Bad unified diff in $in, aborting\n";
		$abort = 1;
	}
}

sub body
{
	if (/^\*\*\*\s+/ && !/^\*\*\*\s+\d+,\d+\s+/) {
		close OUT;
		print "Wrote $out\n";
		$state = \&cstart;
		$fl = $_;
	} elsif (/^---\s+/ && !/^---\s+\d+,\d+\s+/) {
		close OUT;
		print "Wrote $out\n";
		$state = \&ustart;
		$fl = $_;
	} else {
		print OUT $_;
	}
}