summaryrefslogtreecommitdiff
path: root/scripts/sortmethods.pl
blob: 29800bd21689dfe5bf9686481b055dbd094ce0ff (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
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
111
112
113
114
115
116
117
#!/usr/bin/perl

# Automatically sorts the functions of a java class alphanumerical
# (C) 2008 by Paul C. Buetow

use strict;
use warnings;

use File::Find;

my @files;

sub usage () {
	return "Usage: perl $0 <sourcedir>\n";
}

sub process (@) {
	my ($file, @input) = @_;

	my $package;
	my @imports;
	my $classOrInterface;
	my @variables;
	my @constructors;
	my @methods;

	my $isMethod = 0;
	my $isInnerClass = 0;
	my $methodparant = 0;

	for (@input) {
		if (/^package/) {
			$package = $_;

		} elsif (/^import/) {
			push @imports, $_;

		} elsif (/^[^ ].*class/) {
			$classOrInterface = $_;

		} elsif (/^[^ ].*interface/) {
			$classOrInterface = $_;

		} elsif (!$isMethod && /;/ && !/{/) {
			push @variables, $_;

		} elsif (!$isMethod && !/;/ && /{/) {
			$methodparant = 0;
			++$methodparant while /{/g;
			--$methodparant while /}/g;
			my ($name) = /(\w*?\(.*) {/i;
			next unless defined $name;
			$isMethod = 1;
			my %method = (
					name => $name,
					prototype => $_,
					code => [],
					);
			push @methods, \%method;

		} elsif ($isMethod) {
			++$methodparant while /{/g;
			--$methodparant while /}/g;

			$isMethod = 0 if $methodparant == 0;
			push @{$methods[-1]->{code}}, $_;
		}
	}

	die "undef package in $file\n" unless defined $package;
	die "undef classOrInterface in $file\n" unless defined $classOrInterface;

	my @output = ();

	push @output, $package;
	push @output, "\n";

	if (@imports) {
		push @output, sort @imports;
		push @output, "\n";
	}

	push @output, $classOrInterface;

	if (@variables) {
		push @output, sort @variables;
		push @output, "\n";
	}

	if (@methods) {
		push @output, 
			 map { "@" .$_->{name} . "=>". $_->{prototype}, @{$_->{code}}, "\n" }
			 sort { $a->{name} cmp $b->{name} } @methods;
	}

	push @output, "}\n";

	return @output;
}

my $startDir = shift || die usage();
find(sub { push @files, $File::Find::name if /\.java$/ }, $startDir);

for (@files) {
	open my $file, $_ or die "$!: $_\n";
	my @input = <$file>;
	close $file;

	my @output = process($_, @input);
	print @output;

	print "=================== END $_\n";
}


=cut