summaryrefslogtreecommitdiff
path: root/bom/ann2bom.pl
blob: c53bd3e614c0a74913e9d4b91db9888823cc9125 (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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#!/usr/bin/perl
#
# bom/ann2bom.pl - Generate BOM from annotations
#
# Written 2014, 2016 by Werner Almesberger
# Copyright 2014, 2016 by Werner Almesberger
#
# 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.
#


$cache = ".cache";


sub usage
{
	print STDERR "usage: $0 [-e|-u] [file.ann ...]\n";
	exit(1);
}


sub flush
{
	return unless defined $curr;

	for my $id (keys %alt) {
		my $p = $alt{$id}[0];
		my $n = 1;

		for (keys %mult) {
			next if index((split(/\s/, $p))[1], $_) == -1;
			$n *= $mult{$_};
			delete $mult{$_};
		}
		$bom{$p} += $n;
		$group{$p} = $group;
	}
	for (keys %mult) {
		print STDRR "$curr: unused multiplier $mult{$_} x $_\n";
	}

	for (keys %alt) {
		my $p = $alt{$_}[0];
		$use{$p}{$curr} = 1;
	}

	undef $curr;
	undef $group;
	undef %mult;
	undef %alt;
}


sub ref
{
	local ($id, $vendor, $part) = @_;
	my $p = "$vendor $part";
	my $f = $alt{$id}[0];

	if (defined $f) {
		$eq{$f}{$p} = 1;
		$eq{$p}{$f} = 1;
	}
	push(@{ $alt{$id} }, $p);
}


sub collect
{
	local ($p) = @_;
	my @res = ($p);
	my @eq = keys %{ $eq{$p} };
	
	delete $eq{$p};
	for (@eq) {
		next unless exists $eq{$_};
		@res = (@res, &collect($_));
	}
	return @res;
}


if ($ARGV[0] eq "-e") {
	$equiv = 1;
	shift @ARGV;
} elsif ($ARGV[0] eq "-u") {
	$use = 1;
	shift @ARGV;
} else {
	$bom = 1;
}
&usage if $ARGV[0] =~ /^-/;

while (<>) {
	next if /^#/;
	if (/^\s*$/) {
		&flush;
		next;
	}
	if (/^(\S+):\s*$/) {
		&flush;
		$curr = $1;
		next;
	}
	die unless /^\s+/;

	my $tmp = $_;
	while ($tmp =~ /(\d+)\sx\s([A-Z][A-Z0-9]*)/) {
		$mult{$2} = $1;
		$tmp = $';
	}

	&ref($2, "DIGI-KEY", $3) if /\s+DK=(\((.*?)\)\s+)?(.*?)\s*$/;
	&ref($2, "NEWARK", $3) if /\s+NEWARK=(\((.*?)\)\s+)?(.*?)\s*$/;
	&ref($2, "ARROW", $3) if /\s+ARROW=(\((.*?)\)\s+)?(.*?)\s*$/;
	&ref($2, "FUTEL", $3) if /\s+FUTEL=(\((.*?)\)\s+)?(.*?)\s*$/;
	&ref(undef, "MANUAL", $1) if /\s+MANUAL=(.*?)\s*$/;
	$group = $1 if /\s+GROUP=(\S+)/;
}
&flush;

if ($bom) {
	for (sort keys %bom) {
		print "$bom{$_} $_ $group{$_}\n";
	}
}

if ($equiv) {
	for (keys %eq) {
		print join("\n\t", &collect($_)), "\n" if exists $eq{$_};
	}
}

if ($use) {
	for (sort keys %use) {
		print "$bom{$_} $_ ".join(",", sort keys %{ $use{$_} })."\n";
	}
}