ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/SCRAM/src/BuildSystem/BuildDataStorage.pm
Revision: 1.4
Committed: Fri Mar 11 18:55:28 2005 UTC (20 years, 1 month ago) by sashby
Content type: text/plain
Branch: MAIN
CVS Tags: V1_0_1
Changes since 1.3: +11 -4 lines
Log Message:
Fix for problems with files being edited while cache-scanning.

File Contents

# User Rev Content
1 sashby 1.2 #____________________________________________________________________
2     # File: BuildDataStorage.pm
3     #____________________________________________________________________
4     #
5     # Author: Shaun Ashby <Shaun.Ashby@cern.ch>
6     # Update: 2004-06-22 15:16:01+0200
7 sashby 1.4 # Revision: $Id: BuildDataStorage.pm,v 1.3 2005/03/09 19:28:19 sashby Exp $
8 sashby 1.2 #
9     # Copyright: 2004 (C) Shaun Ashby
10     #
11     #--------------------------------------------------------------------
12     package BuildSystem::BuildDataStorage;
13     require 5.004;
14     use Exporter;
15     @ISA=qw(Exporter);
16     @EXPORT_OK=qw( );
17    
18     sub new()
19     ###############################################################
20     # new #
21     ###############################################################
22     # modified : Tue Jun 22 15:16:08 2004 / SFA #
23     # params : #
24     # : #
25     # function : #
26     # : #
27     ###############################################################
28     {
29     my $proto=shift;
30     my $class=ref($proto) || $proto;
31     my ($configdir) = @_;
32     my $self=
33     {
34     BUILDTREE => {}, # Path/data pairs;
35     STATUS => 0, # Status of cache
36     VERBOSE => 0 # Verbose mode (0/1);
37     };
38    
39     bless $self,$class;
40    
41     # The location of the top-level BuildFile:
42     $self->{CONFIGDIR} = $configdir;
43    
44     # Somewhere to store the dependencies:
45     $self->{DEPENDENCIES} = {}; # GLOBAL dependencies
46 sashby 1.3 $self->{SKIPPEDDIRS} = {}; # Global skipped dirs
47 sashby 1.2
48     # Initialize the Template Engine:
49     $self->init_engine();
50    
51     return $self;
52     }
53    
54     sub grapher()
55     {
56     my $self=shift;
57     my ($mode,$writeopt)=@_;
58    
59     if ($mode)
60     {
61     $mode =~ tr[A-Z][a-z];
62     # Check to see what the mode is:
63     if ($mode =~ /^g.*?/)
64     {
65     $self->{GRAPH_MODE} = 'GLOBAL';
66     # GLOBAL package graphing:
67     use BuildSystem::SCRAMGrapher;
68     $self->{SCRAMGRAPHER} = BuildSystem::SCRAMGrapher->new();
69     }
70     elsif ($mode =~ /^p.*?/)
71     {
72     # All other cases assume per package. This means that each package
73     # is responsible for creating/destroying grapher objects and writing
74     # out graphs, if required:
75     $self->{GRAPH_MODE} = 'PACKAGE';
76     }
77     else
78     {
79     print "SCRAM error: no mode (w=p,w=g) given for graphing utility!","\n";
80     exit(1);
81     }
82    
83     # Set write option:
84     $self->{GRAPH_WRITE} = $writeopt;
85     }
86     else
87     {
88     print "SCRAM error: no mode (w=p,w=g) given for graphing utility!","\n";
89     exit(1);
90     }
91     }
92    
93     sub global_graph_writer()
94     {
95     my $self=shift;
96     my $name='Project';
97     # Only produce graphs with DOT if enabled. This routine is
98     # only used at Project level:
99     if (defined($self->{SCRAMGRAPHER}) && $self->{GRAPH_WRITE})
100     {
101     my $data; # Fake data - there isn't a DataCollector object
102     $self->{SCRAMGRAPHER}->graph_write($data, $name);
103     delete $self->{SCRAMGRAPHER};
104     }
105     else
106     {
107     print "SCRAM error: can't write graph!","\n";
108     exit(1);
109     }
110    
111     return;
112     }
113    
114     #### The methods ####
115     sub datapath()
116     {
117     my $self=shift;
118     my ($path)=@_;
119     my $datapath;
120     # At project-level, the path is src so just return src. Also,
121     # if we received a BuildFile path that we need to determine the data path for,
122     # check first to see if the path matches config/BuildFile. If it does, we have the top-level
123     # datapath which should be src:
124     if ($path eq "$ENV{LOCALTOP}/$ENV{SCRAM_CONFIGDIR}/BuildFile" || $path eq $ENV{SCRAM_SOURCEDIR})
125     {
126     return $ENV{SCRAM_SOURCEDIR};
127     }
128    
129     # For other paths, strip off the src dir (part of LOCALTOP) and the final BuildFile to
130     # get a data position to be used as a key:
131     ($datapath = $path) =~ s|^\Q$ENV{SCRAM_SOURCEDIR}\L/||;
132    
133     if ($datapath =~ m|(.*)/BuildFile$|)
134     {
135     return $1;
136     }
137    
138     return $datapath;
139     }
140    
141     sub check_global_config()
142     {
143     my $self=shift;
144     my $topbuildfile = $self->{CONFIGDIR}."/BuildFile";
145    
146     if ( ! -f $topbuildfile )
147     {
148     print "SCRAM error: no BuildFile at top-level (config)! Invalid area!","\n";
149     exit(1);
150     }
151    
152     return $self;
153     }
154    
155     sub processtree()
156     {
157     my $self=shift;
158     my $parent = $ENV{SCRAM_SOURCEDIR};
159     $self->procrecursive($parent);
160     return $self;
161     }
162    
163     sub updatetree()
164     {
165     my $self=shift;
166     my ($startdir) = @_;
167     print "Updating metadata from $startdir","\n",if ($ENV{SCRAM_DEBUG});
168     $self->updaterecursive($startdir);
169     return $self;
170     }
171    
172     sub updatemkfrommeta()
173     {
174     my $self=shift;
175     my ($startdir)=$ENV{SCRAM_SOURCEDIR};
176     print "Updating Makefile from $startdir","\n",if ($ENV{SCRAM_DEBUG});
177     $self->updatefrommeta($startdir);
178     return $self;
179     }
180    
181     sub scanbranch()
182     {
183     my $self=shift;
184     my ($files,$datapath)=@_;
185 sashby 1.4 # Fix (or rather hack) so that only the current buildfile is parsed, not the parent.
186     # This is required becuase it's not desired to pick up dependencies from the level lower:
187     # one should always do it via a <use name=x> to get the package deps. We don't care about
188     # deps in subsystems (they're only used to define groups) and project-wide deps are added at
189     # template level:
190     my $nfiles = [ $files->[0] ];
191    
192 sashby 1.2 # Scan all buildfiles in a branch:
193     use BuildSystem::BuildFile;
194     my $bfbranch=BuildSystem::BuildFile->new();
195 sashby 1.4 $bfbranch->parsebranchfiles($nfiles);
196 sashby 1.3
197 sashby 1.2 # Store:
198     $self->storebranchmetadata($datapath,$bfbranch);
199     return $self;
200     }
201    
202     sub procrecursive()
203     {
204     my $self=shift;
205     my ($dir)=@_;
206     my $datacollector;
207    
208     # Data for current dir:
209     my $treedata = $self->buildtreeitem($dir);
210     # Data for the parent:
211     my $parent = $treedata->parent();
212     my $parenttree = $self->buildtreeitem($parent);
213     # Base classes. These are structural template classes which are fixed in SCRAM:
214     my $baseclasses = [ qw( SUBSYSTEM PACKAGE ) ];
215    
216     # If we have a parent dir, collect METABF. Skip inheriting from config/BuildFile:
217     if (defined ($parenttree) && $parenttree->metabf() && $parent ne 'src')
218     {
219     # Add the meta (BuildFile) location to the current locations meta:
220     $treedata->metabf(@{$parenttree->metabf()});
221     }
222    
223     # Perfect match to class:
224     if ($treedata->suffix() eq '')
225     {
226     # For directories where there's a full match to the classpath, check the class.
227     # Only process Buildfiles if the match occurs for a build product class. In either case,
228     # run the template engine.
229     # Don't process BuildFiles unless we happen to be in a product branch (i.e.,
230     # not a baseclass as defined above) except for Project which we do want:
231     if (! grep($treedata->class() eq $_, @$baseclasses))
232     {
233     # Scan all BuildFiles in this branch:
234     $self->scanbranch($treedata->metabf(),$self->datapath($dir));
235     # Process the build data:
236     $datacollector = $self->processbuildfile($dir, $treedata->path());
237     $treedata->clean(); # Get rid of BRANCHMETA
238     $treedata->branchdata($datacollector);
239     }
240    
241     # And run the engine:
242     $self->run_engine($treedata);
243    
244     foreach my $c ($treedata->children())
245     {
246     if ($c ne '')
247     {
248     $self->procrecursive($c);
249     }
250     }
251     }
252     else
253     {
254     # For directories where there isn't a full match, just run the template engine:
255     $self->run_engine($treedata);
256    
257     foreach my $c ($treedata->children())
258     {
259     if ($c ne '')
260     {
261     $self->procrecursive($c);
262     }
263     }
264     }
265    
266     return $self;
267     }
268    
269     sub updaterecursive()
270     {
271     my $self=shift;
272     my ($dir)=@_;
273     my $datacollector;
274     # updaterecursive() only SCANS and UPDATES METADATA. The Makefile is rebuilt in
275     # its entirety using updatefrommeta(), called after metadata is updated and stored:
276    
277     # Data for current dir:
278     my $treedata = $self->buildtreeitem($dir);
279     # Data for the parent:
280     my $parent = $treedata->parent();
281     my $parenttree = $self->buildtreeitem($parent);
282     # Base classes. These are structural template classes which are fixed in SCRAM:
283     my $baseclasses = [ qw( SUBSYSTEM PACKAGE ) ];
284    
285     # If we have a parent dir, collect METABF. Skip inheriting from config/BuildFile:
286     if (defined ($parenttree) && $parenttree->metabf() && $parent ne 'src')
287     {
288     # Add the meta (BuildFile) location to the current locations meta:
289     $treedata->metabf(@{$parenttree->metabf()});
290     }
291    
292     # Perfect match to class:
293     if ($treedata->suffix() eq '')
294     {
295     # For directories where there's a full match to the classpath, check the class.
296     # Only process Buildfiles if the match occurs for a build product class. In either case,
297     # run the template engine.
298     # Don't process BuildFiles unless we happen to be in a product branch (i.e.,
299     # not a baseclass as defined above):
300     if (! grep($treedata->class() eq $_, @$baseclasses))
301     {
302     # Scan all BuildFiles in this branch:
303     $self->scanbranch($treedata->metabf(),$self->datapath($dir));
304     # Process the build data:
305     $datacollector = $self->processbuildfile($dir, $treedata->path());
306     $treedata->clean();
307     $treedata->branchdata($datacollector);
308     }
309    
310     foreach my $c ($treedata->children())
311     {
312     if ($c ne '')
313     {
314     $self->updaterecursive($c);
315     }
316     }
317     }
318     else
319     {
320     foreach my $c ($treedata->children())
321     {
322     if ($c ne '')
323     {
324     $self->updaterecursive($c);
325     }
326     }
327     }
328    
329     return $self;
330     }
331    
332     sub updatefrommeta()
333     {
334     my $self=shift;
335     my $datacollector;
336     my ($startdir)=@_;
337     # Data for current dir:
338     my $treedata = $self->buildtreeitem($startdir);
339     # Run the engine:
340 sashby 1.3 $self->run_engine($treedata);
341 sashby 1.2
342     foreach my $c ($treedata->children())
343     {
344     if ($c ne '')
345     {
346     $self->updatefrommeta($c);
347     }
348     }
349    
350     return $self;
351     }
352    
353     sub buildtreeitem()
354     {
355     my $self=shift;
356     my ($datapath)=@_;
357     # This will return the TreeItem object for
358     # the corresponding data path:
359     return $self->{BUILDTREE}->{$datapath};
360     }
361    
362     sub bproductparse()
363     {
364     my $self=shift;
365     my ($dataposition, $path, $bcollector, $product, $localg)=@_;
366     my $packdir;
367    
368     if ($dataposition =~ m|(.*)/src|)
369     {
370     $packdir=$1;
371     }
372     elsif ($dataposition =~ m|(.*)/|)
373     {
374     $packdir=$dataposition;
375     }
376    
377     # Probably better to use the bin name/safename:
378     $packdir = $product->safename();
379     my $label = $product->name();
380    
381     # Look for architecture-specific tags:
382     if (my $archdata=$product->archspecific())
383     {
384     $bcollector->resolve_arch($archdata,$packdir);
385     }
386    
387     # Groups:
388     if (my @groups=$product->group())
389     {
390     $bcollector->resolve_groups(\@groups,$packdir);
391     }
392    
393     # Check for packages and external tools:
394     if (my @otheruses=$product->use())
395     {
396     $bcollector->localgraph()->vertex($packdir);
397    
398     # Add vertex and edges for current package and its dependencies:
399     foreach my $OU (@otheruses)
400     {
401     $bcollector->localgraph()->edge($packdir, $OU);
402     }
403    
404     $bcollector->resolve_use(\@otheruses);
405     }
406    
407     # For each tag type that has associated data in this buildfile
408     # data object, get the data and store it:
409     map { my $subname = lc($_); $bcollector->storedata($_, $product->$subname(),$packdir); }
410     $product->basic_tags();
411    
412     # Prepare the metadata for this location:
413     my $graphexists = $bcollector->prepare_meta($packdir);
414    
415     # Write out the graph if required:
416     if ($localg && $self->{GRAPH_WRITE} && $graphexists)
417     {
418     $bcollector->localgraph()->graph_write($bcollector->attribute_data(), $packdir);
419     }
420    
421     # Clean up:
422     $bcollector->clean4storage();
423     return $bcollector;
424     }
425    
426     sub processbuildfile()
427     {
428     my $self=shift;
429     my ($dataposition, $path)=@_;
430     my $collector;
431     my $packdir;
432     my $CURRENTBF = $self->metaobject($dataposition);
433     my $localgrapher=0;
434     my $scramgrapher;
435 sashby 1.4
436 sashby 1.2 if (defined($CURRENTBF))
437     {
438     use BuildSystem::DataCollector;
439    
440     # Graphing:
441     if (! defined($self->{SCRAMGRAPHER}))
442     {
443     # We don't have a grapher object so we must we working at package level.
444     $localgrapher=1;
445     # Create the object here:
446     use BuildSystem::SCRAMGrapher;
447     $scramgrapher = BuildSystem::SCRAMGrapher->new();
448     }
449     else
450     {
451     $scramgrapher = $self->{SCRAMGRAPHER};
452     }
453    
454     my %projects = %{$self->{SCRAM_PROJECTS}};
455     my %projectbases = %{$self->{SCRAM_PROJECT_BASES}};
456    
457     # Set up the collector object:
458     $collector = BuildSystem::DataCollector->new($self, $self->{TOOLMANAGER},
459     $path, \%projects, \%projectbases,
460     $scramgrapher);
461    
462     # Need the package name for our dep tracking:
463     if ($dataposition =~ m|(.*)/src|)
464     {
465     $packdir=$1;
466     }
467     elsif ($dataposition =~ m|(.*)/|)
468     {
469     $packdir=$dataposition;
470     }
471     elsif ($dataposition eq $ENV{SCRAM_SOURCEDIR})
472     {
473     $packdir = $ENV{SCRAM_SOURCEDIR};
474     }
475    
476     # Look for architecture-specific tags:
477     if (my $archdata=$CURRENTBF->archspecific())
478     {
479     $collector->resolve_arch($archdata,$packdir);
480     }
481    
482     # Groups:
483     if (my @groups=$CURRENTBF->group())
484     {
485     $collector->resolve_groups(\@groups,$packdir);
486     }
487    
488     # Check for packages and external tools:
489     if (my @otheruses=$CURRENTBF->use())
490     {
491     $scramgrapher->vertex($packdir);
492    
493     # Add vertex and edges for current package and its dependencies:
494     foreach my $OU (@otheruses)
495     {
496     $scramgrapher->edge($packdir, $OU);
497     }
498    
499     $collector->resolve_use(\@otheruses);
500     }
501    
502     # If we are at project-level, also resolve the 'self' tool. We ONLY do this
503     # at project-level:
504     if ($dataposition eq $ENV{SCRAM_SOURCEDIR})
505     {
506     $collector->resolve_use(['self']);
507     }
508    
509     # For each tag type that has associated data in this buildfile
510     # data object, get the data and store it:
511     map { my $subname = lc($_); $collector->storedata($_, $CURRENTBF->$subname(),$packdir); }
512     $CURRENTBF->basic_tags();
513    
514     # Check for build products and process them here:
515     my $buildproducts=$CURRENTBF->buildproducts();
516    
517     my $BUILDP = {};
518    
519     # If we have build products:
520     if ($buildproducts)
521     {
522     # Build a list of target types that should built at this location in
523     # addition to normal libraries:
524     foreach my $type (keys %$buildproducts)
525     {
526     my $typedata=$CURRENTBF->values($type);
527     while (my ($name,$product) = each %$typedata)
528     {
529     # We make a copy from existing collector object. This is basically a "new()"
530     # followed by some copying of relevant data elements:
531     $bcollector = $collector->copy($localgrapher);
532     # The Product object inherits from same core utility packages
533 sashby 1.4 # as BuildFile so all BuildFile methods can be used on the Product object:
534 sashby 1.2 $self->bproductparse($dataposition,$path,$bcollector,$product,$localgrapher);
535     $product->data($bcollector);
536     $BUILDP->{$product->safename()} = $product;
537     }
538     }
539    
540     # Return the hash of products (safe_name/Product object pairs):
541     return $BUILDP;
542     }
543     else
544     {
545     # Prepare the metadata for this location. Also needed for each build product:
546     my $graphexists = $collector->prepare_meta($packdir);
547    
548     # Write out the graph if required (also to be done for each product):
549     if ($localgrapher && $self->{GRAPH_WRITE} && $graphexists)
550     {
551     $scramgrapher->graph_write($collector->attribute_data(), $packdir);
552     }
553    
554     # At this point I think we can clean away the graph object:
555     $collector->clean4storage();
556    
557     # No products: return main collector:
558     return $collector;
559     }
560     }
561     else
562     {
563     # No build data, just return:
564     return $collector;
565     }
566     }
567    
568     sub create_productstores()
569     {
570     my $self=shift;
571     # This routine will only ever be run for top-level so
572     # datapath can be coded here:
573     my $datapath='src';
574     my $tldata=$self->buildtreeitem($datapath);
575     my $stores=$tldata->rawdata()->productstore();
576    
577     # Iterate over the stores:
578     foreach my $H (@$stores)
579     {
580     my $storename="";
581     # Probably want the store value to be set to <name/<arch> or <arch>/<name> with
582     # <path> only prepending to this value rather than replacing <name>: FIXME...
583     if ($$H{'type'} eq 'arch')
584     {
585     if ($$H{'swap'} eq 'true')
586     {
587     (exists $$H{'path'}) ? ($storename .= $$H{'path'}."/".$ENV{SCRAM_ARCH})
588     : ($storename .= $$H{'name'}."/".$ENV{SCRAM_ARCH});
589     }
590     else
591     {
592     (exists $$H{'path'}) ? ($storename .= $ENV{SCRAM_ARCH}."/".$$H{'path'})
593     : ($storename .= $ENV{SCRAM_ARCH}."/".$$H{'name'});
594     }
595     }
596     else
597     {
598     (exists $$H{'path'}) ? ($storename .= $$H{'path'})
599     : ($storename .= $$H{'name'});
600     }
601    
602     # Create the dir: FIXME: may need a more portable mkdir?
603     system("mkdir","-p",$ENV{LOCALTOP}."/".$storename);
604     }
605     }
606    
607     sub populate()
608     {
609     my $self=shift;
610     my ($paths,$filecache,$toolmanager)=@_;
611     my $datapath;
612     my $buildfile;
613     $|=1; # Flush
614    
615     # The tool manager:
616     $self->{TOOLMANAGER} = $toolmanager;
617    
618     # Get scram projects from toolbox. Each project cache is loaded at this point too:
619     $self->scramprojects();
620    
621     # Check that there's a global config. Exit if not:
622     $self->check_global_config();
623    
624     # Loop over all paths. Apply a sort so that src (shortest path) is first (FIXME!):
625     foreach my $path (sort(@$paths))
626     {
627     # Ignore config content here:
628     next if ($path !~ m|^\Q$ENV{SCRAM_SOURCEDIR}\L|);
629 sashby 1.3
630 sashby 1.2 # Set the data path:
631 sashby 1.3 $datapath = $self->datapath($path);
632    
633 sashby 1.2 # Create a TreeItem object:
634     use BuildSystem::TreeItem;
635     my $treeitem = BuildSystem::TreeItem->new();
636     $self->{BUILDTREE}->{$datapath} = $treeitem;
637    
638     # If we have the project root (i.e. src), we want to process the
639     # top-level (project config) BuildFile:
640     if ($path eq $ENV{SCRAM_SOURCEDIR})
641     {
642     $buildfile = $ENV{SCRAM_CONFIGDIR}."/BuildFile";
643     # Parse the top-level BuildFile. We must do this here
644     # because we need the ClassPaths. Store as RAWDATA:
645     $self->scan($buildfile, $datapath);
646     # At this point, we've scanned the top-level BuildFile so we can
647     # create the store dirs and setup "self":
648     $self->create_productstores();
649     # We need scram project base vars at project-level:
650     $treeitem->scramprojectbases($self->{SCRAM_PROJECT_BASES});
651     }
652     else
653     {
654     $buildfile = $path."/BuildFile";
655     }
656    
657     # If this BuildFile exists, store in METABF:
658     if ( -f $buildfile )
659     {
660     # This level has a buildfile so store this path:
661     $treeitem->metabf($buildfile);
662     # Scan to resolve groups. Store as RAWDATA:
663     $self->scan($buildfile, $datapath);
664     ($ENV{SCRAM_DEBUG}) ? print "Scanning ",$buildfile,"\n" : print "." ;
665     }
666    
667 sashby 1.3 if ($self->skipdir($datapath))
668     {
669     $treeitem->skip(1);
670     print $datapath," building skipped.\n", if ($ENV{SCRAM_DEBUG});
671     }
672    
673 sashby 1.2 # Now add the class and path info to the TreeItem:
674     my ($class, $classdir, $suffix) = @{$self->buildclass($path)};
675    
676     $treeitem->class($class);
677     $treeitem->classdir($classdir);
678     $treeitem->suffix($suffix);
679     $treeitem->path($path);
680     $treeitem->safepath($path);
681     $treeitem->parent($datapath);
682     $treeitem->children($filecache);
683     $treeitem->name();
684     }
685    
686     print "\n";
687    
688     # Check dependencies- look for cycles in the global dependency data:
689     $self->check_dependencies();
690 sashby 1.3 $self->skipdir() if ($ENV{SCRAM_DEBUG});
691 sashby 1.2 }
692    
693     sub check_dependencies()
694     {
695     my $self=shift;
696     # Use the SCRAMGrapher to process the deps and return a
697     # Graph object:
698     use BuildSystem::SCRAMGrapher;
699    
700     my $SG = BuildSystem::SCRAMGrapher->new($self->{DEPENDENCIES}); # GLOBAL dependencies
701     my $G = $SG->_graph_init();
702     my @classification = $G->edge_classify();
703     my @cycles;
704     my $status=0;
705    
706     # Dump the vertex classification if required:
707     if ($ENV{SCRAM_DEBUG})
708     {
709     print "\n";
710     print "Dumping vertex/path classifications:","\n";
711     print "\n";
712     printf("%-40s %-40s %-15s\n",'Vertex_i','Vertex_j','CLASS');
713     printf("%-95s\n",'-'x95);
714     }
715    
716     foreach my $element (@classification)
717     {
718     printf("%-40s %-40s %-15s\n",$element->[0],$element->[1],$element->[2]), if ($ENV{SCRAM_DEBUG});
719     # Save our cycles to list separately:
720     if ($element->[2] eq 'back')
721     {
722     push(@cycles,$element);
723     $status++;
724     }
725     }
726    
727     print "\n";
728     if ($status)
729     {
730     map
731     {
732     print $::fail."SCRAM buildsystem ERROR: Cyclic dependency ",$_->[0]," <--------> ",$_->[1].$::normal."\n";
733     } @cycles;
734     print "\n";
735    
736     # Exit:
737     exit(1);
738     }
739    
740     # Otherwise return:
741     return;
742     }
743    
744     sub update_toplevel()
745     {
746     my $self=shift;
747     my (@buildfiles) = @_;
748     my $treeitem;
749    
750     print "Re-scanning at top-level..\n";
751    
752     my $datapath = $self->datapath($ENV{LOCALTOP}."/".$ENV{SCRAM_CONFIGDIR}."/BuildFile");
753    
754     # This updates the raw data:
755     $self->scan($ENV{LOCALTOP}."/".$ENV{SCRAM_CONFIGDIR}."/BuildFile", $datapath);
756    
757     # Update everything else:
758     foreach my $B (@buildfiles)
759     {
760     next if ($B eq $ENV{LOCALTOP}."/config/BuildFile");
761     $datapath = $self->datapath($B);
762     # Check to see if we already have the raw data for this buildfile.
763     # Note that we won't if this scan was run from update mode. In this
764     # case, we set up the TreeItem object:
765     if (! exists($self->{BUILDTREE}->{$datapath}))
766     {
767     use BuildSystem::TreeItem;
768     $treeitem = BuildSystem::TreeItem->new();
769     my $path=$ENV{SCRAM_SOURCEDIR}."/".$datapath;
770     my ($class, $classdir, $suffix) = @{$self->buildclass($path)};
771    
772     $treeitem->class($class);
773     $treeitem->classdir($classdir);
774     $treeitem->suffix($suffix);
775     $treeitem->path($path);
776     $treeitem->safepath($path);
777     $treeitem->parent($datapath);
778     $treeitem->children($filecache);
779     $treeitem->name();
780    
781     $self->{BUILDTREE}->{$datapath} = $treeitem;
782    
783     print "Scanning ",$B,"\n";
784     $self->scan($B,$datapath); # This updates the raw data
785     }
786     else
787     {
788     print "Scanning ",$B,"\n";
789     $self->scan($B,$datapath); # This updates the raw data
790     }
791    
792     # Recursively update the tree from this data path:
793     $self->updatetree($datapath);
794     }
795     }
796    
797     sub update()
798     {
799     my $self=shift;
800     my ($changeddirs, $addeddirs, $bf, $removedpaths, $toolmanager, $filecache) = @_;
801     my $buildfiles = {};
802     # Copy the contents of the array of BuildFiles to a hash so that
803     # we can track which ones have been parsed:
804     map
805     {
806     $buildfiles->{$_} = 0;
807     } @$bf;
808    
809     # Tool manager:
810     $self->{TOOLMANAGER} = $toolmanager;
811     # Get scram projects from toolbox. Each project cache is
812     # loaded at this point too:
813     $self->scramprojects();
814    
815     # Remove build data for removed directories:
816     $self->removedata($removedpaths);
817    
818     # Now check to see if something changed at the top-level. If so we reparse everything:
819     my $toplevel = $ENV{LOCALTOP}."/".$ENV{SCRAM_CONFIGDIR}."/BuildFile";
820    
821     if (exists($buildfiles->{$toplevel}))
822     {
823     $buildfiles->{$toplevel} = 1; # Parsed
824     $self->update_toplevel(@$bf);
825     }
826     else
827     {
828     # Process all new directories first then changed ones. This means that everything will be in
829     # place once we start parsing any modified BuildFiles and once we run updatetree():
830    
831     $self->update_newdirs($addeddirs);
832    
833     $self->update_existingdirs($changeddirs);
834    
835     # Now check for any modified BuildFiles that have not yet been rescanned:
836     foreach my $bftoscan (keys %$buildfiles)
837     {
838     if ($buildfiles->{$bftoscan} == 0)
839     {
840     my $datapath = $self->datapath($bftoscan);
841     $self->scan($bftoscan,$datapath); # This updates the raw data
842     }
843     }
844     }
845    
846     # Also rebuild the project Makefile from scratch:
847     $self->updatemkfrommeta();
848     print "\n";
849     }
850    
851     sub update_newdirs()
852     {
853     my $self=shift;
854     my ($newdirs) = @_;
855     foreach my $path (@$newdirs)
856     {
857     print "Processing new directory \"",$path,"\"\n",if ($ENV{SCRAM_DEBUG});
858     $self->updateadir($path);
859     }
860     }
861    
862     sub update_existingdirs()
863     {
864     my $self=shift;
865     my ($changeddirs) = @_;
866     foreach my $path (@$changeddirs)
867     {
868     print "Processing modified directory \"",$path,"\"\n",if ($ENV{SCRAM_DEBUG});
869     $self->updateadir($path);
870     }
871     }
872    
873     sub updateadir()
874     {
875     my $self=shift;
876     my ($path) = @_;
877     my $datapath = $self->datapath($path);
878     my $possiblebf = $path."/BuildFile";
879     my $treeitem;
880    
881     if (! exists($self->{BUILDTREE}->{$datapath}))
882     {
883     use BuildSystem::TreeItem;
884     $treeitem = BuildSystem::TreeItem->new();
885    
886     # Get the class info:
887     my ($class, $classdir, $suffix) = @{$self->buildclass($path)};
888    
889     $treeitem->class($class);
890     $treeitem->classdir($classdir);
891     $treeitem->suffix($suffix);
892     $treeitem->path($path);
893     $treeitem->safepath($path);
894     $treeitem->parent($datapath);
895     $treeitem->children($filecache);
896     $treeitem->name();
897     # Store the TreeItem object:
898     $self->{BUILDTREE}->{$datapath} = $treeitem;
899     }
900    
901     # Update the status of the parent. Add the child and update
902     # the safe subdirs:
903     my $parent = $self->{BUILDTREE}->{$datapath}->parent();
904     $self->{BUILDTREE}->{$parent}->updateparentstatus($datapath);
905    
906     # Now check to see if there is a BuildFile here. If there is, parse it:
907     if ( -f $possiblebf)
908     {
909     # This level has a buildfile so store this path:
910     $self->{BUILDTREE}->{$datapath}->metabf($possiblebf);
911     # Scan to resolve groups. Store as RAWDATA:
912     print "Scanning ",$possiblebf,"\n";
913     $self->scan($possiblebf, $datapath);
914     # Check to see if this BuildFile is known to have needed scanning. If so,
915     # mark it as read:
916     if (exists($buildfiles->{$possiblebf}))
917     {
918     $buildfiles->{$possiblebf} = 1;
919     }
920     }
921    
922     # Recursively update the tree from this data path:
923     $self->updatetree($datapath);
924     }
925    
926     sub scan()
927     {
928     my $self=shift;
929     my ($buildfile, $datapath) = @_;
930    
931     use BuildSystem::BuildFile;
932     my $bfparse=BuildSystem::BuildFile->new();
933     $bfparse->parse($buildfile);
934 sashby 1.3
935 sashby 1.2 # Store group data:
936 sashby 1.3 $self->addgroup($bfparse->defined_group(), $datapath)
937     if ($bfparse->defined_group());
938    
939     # See if there were skipped dirs:
940     my $skipped = $bfparse->skippeddirs($datapath);
941     # Check to see if there was an info array for this location.
942     # If so, we extract the first element of the array (i.e. ->[1])
943     # and store it under the datapath entry. This is just so that useful
944     # messages explaining why the dir was skipped can be preserved.
945     if (ref($skipped) eq 'ARRAY')
946     {
947     $self->skipdir($datapath,$skipped->[1]);
948     }
949 sashby 1.2
950     $self->storedata($datapath, $bfparse);
951    
952 sashby 1.3 # Add the dependency list to our store:
953     $self->{DEPENDENCIES}->{$datapath} = $bfparse->dependencies();
954 sashby 1.2 return $self;
955     }
956    
957     sub init_engine()
958     {
959     my $self=shift;
960    
961     # Create the interface to the template engine:
962     use BuildSystem::TemplateInterface;
963     # Pass in the config dir as the location where templates live:
964     $self->{TEMPLATE_ENGINE} = BuildSystem::TemplateInterface->new();
965     }
966    
967     sub run_engine()
968     {
969     my $self=shift;
970     my ($templatedata)=@_;
971    
972     $self->{TEMPLATE_ENGINE}->template_data($templatedata);
973     $self->{TEMPLATE_ENGINE}->run();
974     return $self;
975     }
976    
977     sub buildclass
978     {
979     my $self=shift;
980     my ($path)=@_;
981     my $cache=[];
982     # Associate a path with ClassPath setting.
983     # For now, just assumes global data has been scanned and class settings
984     # are already known (in $self->{CONFIGDATA}->classpath()).
985     # Generate more optimal classpath data structure, only once.
986     # Split every cache definition into an array of pairs, directory
987     # name and class. So ClassPath of type "+foo/+bar/src+library"
988     # becomes [ [ "" "foo" ] [ "" "bar" ] [ "src" "library" ] ]
989     my @CLASSPATHS=@{$self->{BUILDTREE}->{$ENV{SCRAM_SOURCEDIR}}->rawdata()->classpath()};
990    
991     if (! scalar @$cache)
992     {
993     foreach my $classpath (@CLASSPATHS)
994     {
995     push (@$cache, [map { [ split(/\+/, $_) ] } split(/\//, $classpath)]);
996     }
997     }
998    
999     print "WARNING: No ClassPath definitions, nothing will be done!","\n",
1000     if (! scalar @$cache);
1001     # Now scan the class paths. All the classpaths are given a rank
1002     # to mark how relevant they are, and then the best match is chosen.
1003     #
1004     # The ranking logic is as follows. We scan each class path and
1005     # drop if it doesn't match at all. For paths that match, we
1006     # record how many components of the class was *not* used to match
1007     # on the class: for a short $path, many classes will match.
1008     # For each path component we record whether the match was exact
1009     # (if the class part is empty, i.e. "", it's a wildcard that
1010     # matches everything). Given these rankings, we pick
1011     # - the *first* class that
1012     # - has least *unmatched* components
1013     # - with *first* or *longest* exact match sequence in
1014     # left-to-right order.
1015     my @ranks = ();
1016     my @dirs = split(/\/+/, $path);
1017     CLASS: foreach my $class (@$cache)
1018     {
1019     # The first two members of $rank are fixed: how much of path
1020     # was and was not used in the match.
1021     my $rank = [[], [@dirs]];
1022     foreach my $component (@$class)
1023     {
1024     my $dir = $rank->[1][0];
1025     if (! defined $dir)
1026     {
1027     # Path exhausted. Leave used/unused as is.
1028     last;
1029     }
1030     elsif ($component->[0] eq "")
1031     {
1032     # Wildcard match, push class and use up path
1033     push(@$rank, [1, $component->[1]]);
1034     push(@{$rank->[0]}, shift(@{$rank->[1]}));
1035     }
1036     elsif ($component->[0] eq $dir)
1037     {
1038     # Exact match, push class and use up path
1039     push(@$rank, [0, $component->[1]]);
1040     push(@{$rank->[0]}, shift(@{$rank->[1]}));
1041     }
1042     else
1043     {
1044     # Unmatched, leave used/unused as is.
1045     last;
1046     }
1047     }
1048    
1049     push(@ranks, $rank);
1050     }
1051    
1052     # If no classes match, bail out:
1053     if (! scalar @ranks)
1054     {
1055     return "";
1056     }
1057    
1058     # Sort in ascending order by how much was of class was not used;
1059     # the first entry has least "extra" trailing match data. Then
1060     # truncate to only those equal to the best rank.
1061     my @sorted = sort { scalar(@{$a->[1]}) <=> scalar(@{$b->[1]}) } @ranks;
1062     my @best = grep(scalar(@{$_->[1]}) == scalar(@{$sorted[0][1]}), @sorted);
1063    
1064     # Now figure which of the best-ranking classes have the longest
1065     # exact match in left-to-right order (= which one is first, and
1066     # those with equal first exact match, longest exact match).
1067     my $n = 0;
1068     my $class = $best[$n][scalar @{$best[$n]}-1];
1069    
1070     # Return the class data:
1071     return [ $class->[1], join('/', @{$best[$n][0]}), join('/', @{$best[$n][1]}) ];
1072     }
1073    
1074     sub storedata
1075     {
1076     my $self=shift;
1077     my ($datapath, $data)=@_;
1078 sashby 1.3
1079 sashby 1.2 # Store the content of this BuildFile in cache:
1080     $self->{BUILDTREE}->{$datapath}->rawdata($data);
1081     return $self;
1082     }
1083    
1084     sub removedata
1085     {
1086     my $self=shift;
1087     my ($removedpaths) = @_;
1088    
1089     foreach my $rd (@$removedpaths)
1090     {
1091     my $datapath = $self->datapath($rd);
1092     # Remove all data, recursively, from $datapath:
1093     $self->recursive_remove_data($datapath);
1094     }
1095    
1096     return $self;
1097     }
1098    
1099     sub recursive_remove_data()
1100     {
1101     my $self=shift;
1102     my ($datapath)=@_;
1103    
1104     # Delete main entry in build data via TreeItem:
1105     if (exists($self->{BUILDTREE}->{$datapath}))
1106     {
1107     # We also must modify the parent TreeItem to remove the child
1108     # from SAFE_SUBDIRS as well as from CHILDREN array:
1109     my $parent = $self->{BUILDTREE}->{$datapath}->parent();
1110     $self->{BUILDTREE}->{$parent}->updatechildlist($datapath);
1111    
1112     # Get the children:
1113     my @children = $self->{BUILDTREE}->{$datapath}->children();
1114    
1115     foreach my $childpath (@children)
1116     {
1117     # The child path value is the datapath so can be used
1118     # directly when deleting data entries
1119     $self->recursive_remove_data($childpath);
1120     }
1121    
1122     # Finally, delete the parent data (a TreeItem):
1123     delete $self->{BUILDTREE}->{$datapath};
1124     }
1125    
1126     # return:
1127     return $self;
1128     }
1129    
1130     sub storebranchmetadata()
1131     {
1132     my $self=shift;
1133     my ($datapath,$data)=@_;
1134    
1135     # Store the content of this BuildFile in cache:
1136     $self->{BUILDTREE}->{$datapath}->branchmetadata($data);
1137     return $self;
1138     }
1139    
1140     sub buildobject
1141     {
1142     my $self=shift;
1143     my ($datapath)=@_;
1144    
1145     if (exists($self->{BUILDTREE}->{$datapath}) && defined($self->{BUILDTREE}->{$datapath}->rawdata()))
1146     {
1147     return $self->{BUILDTREE}->{$datapath}->rawdata();
1148     }
1149     else
1150     {
1151     return undef;
1152     }
1153     }
1154    
1155     sub metaobject
1156     {
1157     my $self=shift;
1158     my ($datapath)=@_;
1159    
1160     if (exists($self->{BUILDTREE}->{$datapath}) && defined($self->{BUILDTREE}->{$datapath}->branchmetadata()))
1161     {
1162     return $self->{BUILDTREE}->{$datapath}->branchmetadata();
1163     }
1164     else
1165     {
1166     return undef;
1167     }
1168     }
1169    
1170     sub addgroup
1171     {
1172     my $self=shift;
1173     my ($grouparray,$datapath)=@_;
1174    
1175     foreach my $group (@{$grouparray})
1176     {
1177     # Only give a warning if the group is defined already in a
1178     # BuildFile other than the one at $path (avoids errors because KNOWNGROUPS
1179     # is not reset before re-parsing a BuildFile in which a group is defined):
1180     if (exists $self->{KNOWNGROUPS}->{$group}
1181     && $self->{KNOWNGROUPS}->{$group} ne $datapath)
1182     {
1183 sashby 1.3 print "ERROR: Group \"",$group,"\", defined in ",$datapath,"/BuildFile, is already defined in ",
1184     $self->{KNOWNGROUPS}->{$group}."/BuildFile.","\n";
1185 sashby 1.2 exit(0); # For now, we exit.
1186     }
1187     else
1188     {
1189     $self->{KNOWNGROUPS}->{$group} = $datapath;
1190     }
1191     }
1192     }
1193    
1194     sub findgroup
1195     {
1196     my $self=shift;
1197     my ($groupname) = @_;
1198    
1199     if (exists $self->{KNOWNGROUPS}->{$groupname})
1200     {
1201     # If group exists, return data:
1202     return $self->{KNOWNGROUPS}->{$groupname};
1203     }
1204     else
1205     {
1206     # Not found so return:
1207     return(0);
1208     }
1209     }
1210    
1211     sub knowngroups
1212     {
1213     my $self=shift;
1214     @_ ? $self->{KNOWNGROUPS}=shift
1215     : $self->{KNOWNGROUPS}
1216     }
1217    
1218     sub scramprojects()
1219     {
1220     my $self=shift;
1221     # Need this to be able to read our project cache:
1222     use Cache::CacheUtilities;
1223    
1224     $self->{SCRAM_PROJECTS} = $self->{TOOLMANAGER}->scram_projects();
1225    
1226     # Also store the BASE of each project:
1227     $self->{SCRAM_PROJECT_BASES}={};
1228    
1229     # Load the project cache for every scram-managed project in our toolbox:
1230     while (my ($project, $info) = each %{$self->{SCRAM_PROJECTS}})
1231     {
1232     if ( -f $info."/.SCRAM/".$ENV{SCRAM_ARCH}."/ProjectCache.db")
1233     {
1234     print "Reading cache for ",uc($project),"\n", if ($ENV{SCRAM_DEBUG});
1235     $self->{SCRAM_PROJECTS}->{$project} =
1236     &Cache::CacheUtilities::read($info."/.SCRAM/".$ENV{SCRAM_ARCH}."/ProjectCache.db");
1237     $self->{SCRAM_PROJECT_BASES}->{uc($project)."_BASE"} = $info;
1238     }
1239     else
1240     {
1241     print "WARNING: Unable to read project cache for ",uc($project)," tool.\n", if ($ENV{SCRAM_DEBUG});
1242     print " It could be that the project has not been built for your current architecture.","\n",
1243     if ($ENV{SCRAM_DEBUG});
1244     delete $self->{SCRAM_PROJECTS}->{$project};
1245     }
1246     }
1247    
1248     # Also check to see if we're based on a release area. If so, store the cache as above. Don't store
1249     # the project name but instead just use 'RELEASE':
1250     if (my $releasearea=$::scram->releasearea() && exists $ENV{RELEASETOP})
1251     {
1252     if ( -f $ENV{RELEASETOP}."/.SCRAM/".$ENV{SCRAM_ARCH}."/ProjectCache.db")
1253     {
1254     # OK, so we found the cache. Now read it and store in the projects list:
1255     $self->{SCRAM_PROJECTS}->{RELEASE} =
1256     &Cache::CacheUtilities::read($ENV{RELEASETOP}."/.SCRAM/".$ENV{SCRAM_ARCH}."/ProjectCache.db");
1257     print "OK found release cache ",$self->{SCRAM_PROJECTS}->{RELEASE},"\n", if ($ENV{SCRAM_DEBUG});
1258     }
1259     else
1260     {
1261     print "WARNING: Current area is based on a release area but the project cache does not exist!","\n";
1262     }
1263     }
1264     }
1265    
1266     sub scramprojectbases()
1267     {
1268     my $self=shift;
1269     return $self->{SCRAM_PROJECT_BASES};
1270     }
1271    
1272     sub alldirs
1273     {
1274     my $self=shift;
1275     return @{$self->{ALLDIRS}};
1276     }
1277    
1278 sashby 1.3 sub skipdir
1279     {
1280     my $self=shift;
1281     my ($dir, $message) = @_;
1282    
1283     # Set the info if we have both args:
1284     if ($dir && $message)
1285     {
1286     $self->{SKIPPEDDIRS}->{$dir} = $message;
1287     }
1288     # If we have the dir name only, return true if
1289     # this dir is to be skipped:
1290     elsif ($dir)
1291     {
1292     (exists($self->{SKIPPEDDIRS}->{$dir})) ? return 1 : return 0;
1293     }
1294     else
1295     {
1296     # Dump the list of directories and the message for each:
1297     foreach my $directory (keys %{$self->{SKIPPEDDIRS}})
1298     {
1299     print "Directory \"",$directory,"\" skipped by the build system";
1300     if (length($self->{SKIPPEDDIRS}->{$directory}->[0]) > 10)
1301     {
1302     chomp($self->{SKIPPEDDIRS}->{$directory}->[0]);
1303     my @lines = split("\n",$self->{SKIPPEDDIRS}->{$directory}->[0]); print ":\n";
1304     foreach my $line (@lines)
1305     {
1306     next if ($line =~ /^\s*$/);
1307     print "\t-- ",$line,"\n";
1308     }
1309     print "\n";
1310     }
1311     else
1312     {
1313     print ".","\n";
1314     }
1315     }
1316     }
1317     }
1318    
1319 sashby 1.2 sub verbose
1320     {
1321     my $self=shift;
1322     # Turn on verbose mode:
1323     @_ ? $self->{VERBOSE} = shift
1324     : $self->{VERBOSE}
1325     }
1326    
1327     sub cachestatus()
1328     {
1329     my $self=shift;
1330     # Set/return the status of the cache:
1331     @_ ? $self->{STATUS} = shift
1332     : $self->{STATUS}
1333     }
1334    
1335     sub logmsg
1336     {
1337     my $self=shift;
1338     # Print a message to STDOUT if VERBOSE is true:
1339     print STDERR @_ if $self->verbose();
1340     }
1341    
1342     sub name()
1343     {
1344     my $self=shift;
1345     # Set/return the name of the cache to use:
1346     @_ ? $self->{CACHENAME} = shift
1347     : $self->{CACHENAME}
1348     }
1349    
1350     sub save()
1351     {
1352     my $self=shift;
1353     # Delete unwanted stuff:
1354     delete $self->{DEPENDENCIES};
1355     delete $self->{TOOLMANAGER};
1356     delete $self->{TEMPLATE_ENGINE};
1357     delete $self->{SCRAM_PROJECTS};
1358     delete $self->{SCRAM_PROJECT_BASES};
1359     return $self;
1360     }
1361    
1362     1;