]> git.tdb.fi Git - builder.git/blob - source/builder.cpp
Set PKG_CONFIG_PATH to include prefix
[builder.git] / source / builder.cpp
1 /* $Id$
2
3 This file is part of builder
4 Copyright © 2006-2009  Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #include <set>
9 #include <cstdlib>
10 #include <sys/utsname.h>
11 #include <msp/core/except.h>
12 #include <msp/core/getopt.h>
13 #include <msp/datafile/parser.h>
14 #include <msp/fs/dir.h>
15 #include <msp/fs/stat.h>
16 #include <msp/fs/utils.h>
17 #include <msp/io/buffered.h>
18 #include <msp/io/except.h>
19 #include <msp/io/file.h>
20 #include <msp/io/print.h>
21 #include <msp/strings/formatter.h>
22 #include <msp/strings/regex.h>
23 #include <msp/strings/utils.h>
24 #include <msp/time/units.h>
25 #include <msp/time/utils.h>
26 #include "action.h"
27 #include "analyzer.h"
28 #include "binarypackage.h"
29 #include "builder.h"
30 #include "header.h"
31 #include "install.h"
32 #include "misc.h"
33 #include "package.h"
34 #include "pkgconfig.h"
35 #include "sharedlibrary.h"
36 #include "sourcepackage.h"
37 #include "systemlibrary.h"
38 #include "unlink.h"
39 #include "virtualtarget.h"
40
41 using namespace std;
42 using namespace Msp;
43
44 namespace {
45
46 void update_hash(string &hash, const string &value)
47 {
48         for(unsigned i=0; i<value.size(); ++i)
49                 hash[i%hash.size()]^=value[i];
50 }
51
52 }
53
54
55 Builder::Builder(int argc, char **argv):
56         main_pkg(0),
57         analyzer(0),
58         build(false),
59         clean(0),
60         dry_run(false),
61         help(false),
62         verbose(1),
63         show_progress(false),
64         build_file("Build"),
65         jobs(1),
66         conf_all(false),
67         conf_only(false),
68         build_all(false),
69         create_makefile(false)
70 {
71         string analyze_mode;
72         string work_dir;
73         bool full_paths=false;
74         unsigned max_depth=5;
75         StringList cmdline_warn;
76         string prfx;
77         string arch;
78
79         GetOpt getopt;
80         getopt.add_option('a', "analyze",    analyze_mode,  GetOpt::REQUIRED_ARG).set_help("Perform analysis.  MODE can be deps, alldeps or rebuild.", "MODE");
81         getopt.add_option('b', "build",      build,         GetOpt::NO_ARG).set_help("Perform build even if doing analysis.");
82         getopt.add_option('c', "clean",      clean,         GetOpt::NO_ARG).set_help("Clean buildable targets.");
83         getopt.add_option('f', "file",       build_file,    GetOpt::REQUIRED_ARG).set_help("Read info from FILE instead of Build.", "FILE");
84         getopt.add_option('h', "help",       help,          GetOpt::NO_ARG).set_help("Print this message.");
85         getopt.add_option('j', "jobs",       jobs,          GetOpt::REQUIRED_ARG).set_help("Run NUM commands at once, whenever possible.", "NUM");
86         getopt.add_option('n', "dry-run",    dry_run,       GetOpt::NO_ARG).set_help("Don't actually do anything, only show what would be done.");
87         getopt.add_option('v', "verbose",    verbose,       GetOpt::NO_ARG).set_help("Print more information about what's going on.");
88         getopt.add_option('A', "conf-all",   conf_all,      GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
89         getopt.add_option('B', "build-all",  build_all,     GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
90         getopt.add_option('C', "chdir",      work_dir,      GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
91         getopt.add_option('P', "progress",   show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
92         getopt.add_option('W', "what-if",    what_if,       GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
93         getopt.add_option(     "arch",       arch,          GetOpt::REQUIRED_ARG).set_help("Architecture to build for.", "ARCH");
94         getopt.add_option(     "conf-only",  conf_only,     GetOpt::NO_ARG).set_help("Stop after configuring packages.");
95         getopt.add_option(     "full-paths", full_paths,    GetOpt::NO_ARG).set_help("Output full paths in analysis.");
96         getopt.add_option(     "max-depth",  max_depth,     GetOpt::REQUIRED_ARG).set_help("Maximum depth to show in analysis.", "NUM");
97         getopt.add_option(     "prefix",     prfx,          GetOpt::REQUIRED_ARG).set_help("Directory to install things to.", "DIR");
98         getopt.add_option(     "warnings",   cmdline_warn,  GetOpt::REQUIRED_ARG).set_help("Compiler warnings to use.", "LIST");
99         usagemsg=getopt.generate_usage(argv[0])+" [<target> ...]";
100         helpmsg=getopt.generate_help();
101         getopt(argc, argv);
102
103         if(!analyze_mode.empty())
104         {
105                 analyzer=new Analyzer(*this);
106
107                 if(analyze_mode=="deps")
108                         analyzer->set_mode(Analyzer::DEPS);
109                 else if(analyze_mode=="alldeps")
110                         analyzer->set_mode(Analyzer::ALLDEPS);
111                 else if(analyze_mode=="rebuild")
112                         analyzer->set_mode(Analyzer::REBUILD);
113                 else if(analyze_mode=="rdeps")
114                         analyzer->set_mode(Analyzer::RDEPS);
115                 else
116                         throw UsageError("Invalid analyze mode");
117
118                 analyzer->set_max_depth(max_depth);
119                 analyzer->set_full_paths(full_paths);
120         }
121         else if(!clean && !create_makefile)
122                 build=true;
123
124         const vector<string> &args=getopt.get_args();
125         for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
126         {
127                 unsigned equal=i->find('=');
128                 if(equal!=string::npos)
129                         cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
130                 else
131                         cmdline_targets.push_back(*i);
132         }
133
134         if(cmdline_targets.empty())
135                 cmdline_targets.push_back("default");
136
137         if(!work_dir.empty())
138                 FS::chdir(work_dir);
139
140         cwd=FS::getcwd();
141
142         utsname un;
143         string sysname="native";
144         if(uname(&un)==0)
145                 sysname=tolower(un.sysname);
146
147         native_arch=&archs.insert(ArchMap::value_type(sysname, Architecture(*this, sysname, true))).first->second;
148         native_arch->set_tool("CC",  "gcc");
149         native_arch->set_tool("CXX", "g++");
150         native_arch->set_tool("LD",  "gcc");
151         native_arch->set_tool("LXX", "g++");
152         native_arch->set_tool("AR",  "ar");
153
154         load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
155         load_build_file((FS::get_home_dir()/".builderrc").str());
156
157         if(arch.empty())
158                 current_arch=native_arch;
159         else
160                 current_arch=&get_architecture(arch);
161
162         if(prfx.empty())
163         {
164                 if(current_arch->is_native())
165                         prefix=(FS::get_home_dir()/"local").str();
166                 else
167                         prefix=(FS::get_home_dir()/"local"/current_arch->get_name()).str();
168         }
169         else
170                 prefix=FS::getcwd()/prfx;
171
172         warnings.push_back("all");
173         warnings.push_back("extra");
174         warnings.push_back("shadow");
175         warnings.push_back("pointer-arith");
176         warnings.push_back("error");
177         for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
178         {
179                 vector<string> warns=split(*i, ',');
180                 warnings.insert(warnings.end(), warns.begin(), warns.end());
181         }
182
183         pkg_path.push_back(cwd/".");
184         pkg_path.push_back(cwd/"..");
185 }
186
187 Builder::~Builder()
188 {
189         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
190                 delete i->second;
191         for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
192                 delete i->second;
193         delete analyzer;
194 }
195
196 int Builder::main()
197 {
198         if(prefix.str()!="/usr")
199         {
200                 FS::Path pcdir=prefix/"lib"/"pkgconfig";
201                 if(const char *pcp=getenv("PKG_CONFIG_PATH"))
202                 {
203                         vector<string> path=split(pcp, ':');
204                         bool found=false;
205                         for(vector<string>::const_iterator i=path.begin(); (!found && i!=path.end()); ++i)
206                                 found=(*i==pcdir.str());
207                         if(!found)
208                         {
209                                 path.push_back(pcdir.str());
210                                 setenv("PKG_CONFIG_PATH", join(path.begin(), path.end(), ":").c_str(), true);
211                         }
212                 }
213                 else
214                         setenv("PKG_CONFIG_PATH", pcdir.str().c_str(), true);
215         }
216
217         if(load_build_file(cwd/build_file))
218         {
219                 if(help)
220                 {
221                         usage(0, "builder", false);
222                         return 0;
223                 }
224                 else
225                 {
226                         IO::print(IO::cerr, "No build info here.\n");
227                         return 1;
228                 }
229         }
230
231         main_pkg->configure(cmdline_options, conf_all?2:1);
232
233         if(help)
234         {
235                 usage(0, "builder", false);
236                 IO::print("\n");
237                 package_help();
238                 return 0;
239         }
240
241         if(!conf_only && create_targets())
242                 return 1;
243
244         PackageList all_reqs=main_pkg->collect_requires();
245
246         if(conf_only)
247                 return 0;
248
249         if(verbose>=2)
250                 IO::print("Building on %s, for %s\n", native_arch->get_name(), current_arch->get_name());
251         if(verbose>=1)
252                 IO::print("%d active packages, %d targets\n", all_reqs.size(), targets.size());
253         if(verbose>=2)
254         {
255                 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
256                 {
257                         IO::print(" %s", (*i)->get_name());
258                         if(dynamic_cast<SourcePackage *>(*i))
259                                 IO::print("*");
260                         unsigned count=0;
261                         unsigned ood_count=0;
262                         for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
263                                 if(j->second->get_package()==*i)
264                                 {
265                                         ++count;
266                                         if(j->second->get_rebuild())
267                                                 ++ood_count;
268                                 }
269                         if(count)
270                         {
271                                 IO::print(" (%d targets", count);
272                                 if(ood_count)
273                                         IO::print(", %d out-of-date", ood_count);
274                                 IO::print(")");
275                         }
276                         IO::print("\n");
277                 }
278         }
279
280         if(analyzer)
281                 analyzer->analyze();
282
283         if(!problems.empty())
284         {
285                 IO::print(IO::cerr, "The following problems were detected:\n");
286                 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
287                         IO::print(IO::cerr, "  %s: %s\n", i->package, i->descr);
288                 IO::print(IO::cerr, "Please fix them and try again.\n");
289                 return 1;
290         }
291
292         if(clean)
293                 exit_code=do_clean();
294         else if(build)
295                 exit_code=do_build();
296
297         return exit_code;
298 }
299
300 string Builder::run_pkgconfig(const string &pkg, const string &what)
301 {
302         list<string> argv;
303         argv.push_back("pkg-config");
304         if(what=="cflags" || what=="libs")
305                 argv.push_back("--"+what);
306         else if(what=="flags")
307         {
308                 argv.push_back("--cflags");
309                 argv.push_back("--libs");
310         }
311         else
312                 argv.push_back("--variable="+what);
313         argv.push_back(pkg);
314
315         if(verbose>=4)
316                 IO::print("Running %s\n", join(argv.begin(), argv.end()));
317
318         int status;
319         string res=run_command(argv, &status);
320         if(status)
321                 throw Exception(format("pkg-config for package %s failed", pkg));
322
323         return res;
324 }
325
326 Package *Builder::get_package(const string &name)
327 {
328         PackageMap::iterator i=packages.find(format("%s/%s", name, current_arch->get_name()));
329         if(i==packages.end())
330                 i=packages.find(name);
331         if(i!=packages.end())
332                 return i->second;
333
334         FS::Path path=get_package_location(name);
335         if(!path.empty() && !load_build_file(path/"Build"))
336         {
337                 i=packages.find(name);
338                 if(i!=packages.end())
339                         return i->second;
340         }
341
342         Package *pkg=0;
343         try
344         {
345                 // Package source not found - create a binary package
346                 pkg=BinaryPackage::from_pkgconfig(*this, name);
347         }
348         catch(...)
349         {
350                 problem(name, "not found");
351         }
352
353         packages.insert(PackageMap::value_type(name, pkg));
354
355         return pkg;
356 }
357
358 Target *Builder::get_target(const string &n) const
359 {
360         // XXX Used for getting targets by path.  get_target(const FS::Path &)?
361         TargetMap::const_iterator i=targets.find(n);
362         if(i!=targets.end())
363                 return i->second;
364         return 0;
365 }
366
367 Target *Builder::get_header(const string &include, const FS::Path &from, const list<string> &path)
368 {
369         string hash(8, 0);
370         if(include[0]=='\"')
371                 update_hash(hash, from.str());
372         for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
373                 update_hash(hash, *i);
374
375         string id=hash+include;
376         TargetMap::iterator i=includes.find(id);
377         if(i!=includes.end())
378                 return i->second;
379
380         static string cxx_ver;
381         if(cxx_ver.empty())
382         {
383                 StringList argv;
384                 argv.push_back(current_arch->get_tool("CXX"));
385                 argv.push_back("--version");
386                 cxx_ver=Regex("[0-9]\\.[0-9.]+").match(run_command(argv))[0].str;
387                 while(!cxx_ver.empty() && !FS::is_dir(FS::Path("/usr/include/c++")/cxx_ver))
388                 {
389                         unsigned dot=cxx_ver.rfind('.');
390                         if(dot==string::npos)
391                                 break;
392                         cxx_ver.erase(dot);
393                 }
394                 if(verbose>=5)
395                         IO::print("C++ version is %s\n", cxx_ver);
396         }
397
398         string fn=include.substr(1);
399         if(verbose>=5)
400                 IO::print("Looking for include %s from %s with path %s\n", fn, from, join(path.begin(), path.end()));
401
402         StringList syspath;
403         if(current_arch->is_native())
404                 syspath.push_back("/usr/include");
405         else
406                 syspath.push_back("/usr/"+current_arch->get_prefix()+"/include");
407         syspath.push_back((FS::Path("/usr/include/c++/")/cxx_ver).str());
408
409         Target *tgt=0;
410         if(include[0]=='\"')
411                 tgt=get_header(FS::Path(from)/fn);
412         for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
413                 tgt=get_header(cwd/ *j/fn);
414         for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
415                 tgt=get_header(FS::Path(*j)/fn);
416
417         includes.insert(TargetMap::value_type(id, tgt));
418
419         return tgt;
420 }
421
422 Target *Builder::get_library(const string &lib, const list<string> &path, LibMode mode)
423 {
424         string hash(8, 0);
425         for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
426                 update_hash(hash, *i);
427
428         string id=hash+string(1, mode)+lib;
429         TargetMap::iterator i=libraries.find(id);
430         if(i!=libraries.end())
431                 return i->second;
432
433         StringList syspath;
434         if(current_arch->is_native())
435         {
436                 syspath.push_back("/lib");
437                 syspath.push_back("/usr/lib");
438         }
439         else
440                 syspath.push_back("/usr/"+current_arch->get_prefix()+"/lib");
441
442         if(verbose>=5)
443                 IO::print("Looking for library %s with path %s\n", lib, join(path.begin(), path.end()));
444
445         Target *tgt=0;
446         for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
447                 tgt=get_library(lib, cwd/ *j, mode);
448         for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
449                 tgt=get_library(lib, *j, mode);
450
451         libraries.insert(TargetMap::value_type(id, tgt));
452
453         return tgt;
454 }
455
456 const Architecture &Builder::get_architecture(const string &arch) const
457 {
458         ArchMap::const_iterator i=archs.find(arch);
459         if(i==archs.end())
460                 throw KeyError("Unknown architecture", arch);
461
462         return i->second;
463 }
464
465 void Builder::apply_profile_template(Config &config, const string &pt) const
466 {
467         vector<string> parts=split(pt, '-');
468
469         for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
470         {
471                 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
472                 if(j==profile_tmpl.end())
473                         continue;
474
475                 config.update(j->second);
476         }
477 }
478
479 void Builder::problem(const string &p, const string &d)
480 {
481         problems.push_back(Problem(p, d));
482 }
483
484 void Builder::add_target(Target *t)
485 {
486         targets.insert(TargetMap::value_type(t->get_name(), t));
487         new_tgts.push_back(t);
488 }
489
490 void Builder::usage(const char *reason, const char *argv0, bool brief)
491 {
492         if(reason)
493                 IO::print(IO::cerr, "%s\n", reason);
494
495         if(brief)
496                 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
497         else
498         {
499                 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
500                 IO::print(IO::cerr, "Options:\n");
501                 IO::print(IO::cerr, helpmsg);
502         }
503 }
504
505 FS::Path Builder::get_package_location(const string &name)
506 {
507         if(verbose>=3)
508                 IO::print("Looking for package %s\n", name);
509
510         try
511         {
512                 // Try to get source directory with pkgconfig
513                 string srcdir=strip(run_pkgconfig(name, "source"));
514                 if(!srcdir.empty())
515                         return srcdir;
516         }
517         catch(...)
518         { }
519
520         if(pkg_dirs.empty())
521         {
522                 for(list<FS::Path>::const_iterator i=pkg_path.begin(); i!=pkg_path.end(); ++i)
523                 {
524                         list<string> files=list_files(*i);
525                         for(list<string>::const_iterator j=files.begin(); j!=files.end(); ++j)
526                         {
527                                 FS::Path full=*i / *j;
528                                 if(FS::exists(full/"Build"))
529                                         pkg_dirs.push_back(full);
530                         }
531                 }
532                 if(verbose>=3)
533                         IO::print("%d packages found in path\n", pkg_dirs.size());
534         }
535
536         bool msp=!name.compare(0, 3, "msp");
537         for(list<FS::Path>::const_iterator i=pkg_dirs.begin(); i!=pkg_dirs.end(); ++i)
538         {
539                 string base=basename(*i);
540                 unsigned dash=base.rfind('-');
541
542                 if(!base.compare(0, dash, name))
543                         return *i;
544                 else if(msp && !base.compare(0, dash-3, name, 3, string::npos))
545                         return *i;
546         }
547
548         return FS::Path();
549 }
550
551 int Builder::load_build_file(const FS::Path &fn)
552 {
553         try
554         {
555                 IO::BufferedFile in(fn.str());
556
557                 if(verbose>=3)
558                         IO::print("Reading %s\n", fn);
559
560                 DataFile::Parser parser(in, fn.str());
561                 Loader loader(*this, fn.subpath(0, fn.size()-1));
562                 loader.load(parser);
563         }
564         catch(const IO::FileNotFound &)
565         {
566                 return -1;
567         }
568
569         return 0;
570 }
571
572 int Builder::create_targets()
573 {
574         Target *world=new VirtualTarget(*this, "world");
575
576         Target *def_tgt=new VirtualTarget(*this, "default");
577         world->add_depend(def_tgt);
578
579         Target *install=new VirtualTarget(*this, "install");
580         world->add_depend(install);
581
582         Target *tarballs=new VirtualTarget(*this, "tarballs");
583         world->add_depend(tarballs);
584
585         PackageList all_reqs=main_pkg->collect_requires();
586         for(PackageList::iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
587         {
588                 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
589                 if(!spkg)
590                         continue;
591
592                 const ComponentList &components=spkg->get_components();
593                 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
594                         j->create_targets();
595
596                 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
597                 {
598                         PkgConfig *pc=new PkgConfig(*this, *spkg);
599                         install->add_depend(new Install(*this, *spkg, *pc));
600                 }
601         }
602
603         // Find dependencies until no new targets are created
604         while(!new_tgts.empty())
605         {
606                 Target *tgt=new_tgts.front();
607                 new_tgts.erase(new_tgts.begin());
608                 tgt->find_depends();
609                 if(!tgt->get_depends_ready())
610                         new_tgts.push_back(tgt);
611         }
612
613         // Apply what-ifs
614         for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
615         {
616                 Target *tgt=get_target((cwd/ *i).str());
617                 if(!tgt)
618                 {
619                         IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
620                         return -1;
621                 }
622                 tgt->touch();
623         }
624
625         // Make the cmdline target depend on all targets mentioned on the command line
626         Target *cmdline=new VirtualTarget(*this, "cmdline");
627         bool build_world=false;
628         for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
629         {
630                 Target *tgt=get_target(*i);
631                 if(!tgt)
632                         tgt=get_target((cwd/ *i).str());
633                 if(!tgt)
634                 {
635                         IO::print("I don't know anything about %s\n", *i);
636                         return -1;
637                 }
638                 if(tgt==world)
639                         build_world=true;
640                 cmdline->add_depend(tgt);
641         }
642
643         /* If world is to be built, prepare cmdline.  If not, add cmdline to world
644         and prepare world.  I don't really like this, but it keeps the graph
645         acyclic.
646         
647         XXX Could we skip preparing targets we are not interested in? */
648         if(build_world)
649                 cmdline->prepare();
650         else
651         {
652                 world->add_depend(cmdline);
653                 world->prepare();
654         }
655
656         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
657                 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
658                         spkg->get_deps_cache().save();
659
660         return 0;
661 }
662
663 Target *Builder::get_header(const Msp::FS::Path &fn)
664 {
665         Target *tgt=get_target(fn.str());
666         if(tgt) return tgt;
667
668         if(FS::is_reg(fn))
669         {
670                 tgt=new SystemHeader(*this, fn.str());
671                 return tgt;
672         }
673         return 0;
674 }
675
676 Target *Builder::get_library(const string &lib, const FS::Path &path, LibMode mode)
677 {
678         // Populate a list of candidate filenames
679         StringList candidates;
680
681         if(mode!=ALL_STATIC)
682         {
683                 if(current_arch->get_name()=="win32")
684                 {
685                         candidates.push_back("lib"+lib+".dll");
686                         candidates.push_back(lib+".dll");
687                 }
688                 else
689                         candidates.push_back("lib"+lib+".so");
690         }
691
692         /* Static libraries are always considered, since sometimes shared versions
693         may not be available */
694         candidates.push_back("lib"+lib+".a");
695         if(current_arch->get_name()=="win32")
696                 candidates.push_back("lib"+lib+".dll.a");
697
698         for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
699         {
700                 string full=(path/ *i).str();
701                 Target *tgt=get_target(full);
702
703                 if(tgt)
704                 {
705                         Target *real_tgt=tgt;
706                         if(Install *inst=dynamic_cast<Install *>(tgt))
707                                 real_tgt=&inst->get_source();
708
709                         /* Ignore dynamic libraries from local packages unless library mode is
710                         DYNAMIC */
711                         if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
712                                 continue;
713                         else if(tgt)
714                                 return tgt;
715                 }
716                 else if(FS::is_reg(full))
717                 {
718                         tgt=new SystemLibrary(*this, full);
719                         return tgt;
720                 }
721         }
722
723         return 0;
724 }
725
726 int Builder::do_build()
727 {
728         Target *cmdline=get_target("cmdline");
729
730         unsigned total=cmdline->count_rebuild();
731         if(!total)
732         {
733                 IO::print("Already up to date\n");
734                 return 0;
735         }
736         if(verbose>=1)
737                 IO::print("Will build %d target%s\n", total, (total!=1 ? "s" : ""));
738
739         vector<Action *> actions;
740
741         unsigned count=0;
742
743         bool fail=false;
744         bool finish=false;
745
746         while(!finish)
747         {
748                 if(actions.size()<jobs && !fail)
749                 {
750                         Target *tgt=cmdline->get_buildable_target();
751                         if(tgt)
752                         {
753                                 Action *action=tgt->build();
754                                 if(action)
755                                         actions.push_back(action);
756
757                                 if(show_progress)
758                                         IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
759                         }
760                         else if(actions.empty())
761                                 finish=true;
762                 }
763                 else
764                         Time::sleep(10*Time::msec);
765
766                 for(unsigned i=0; i<actions.size();)
767                 {
768                         int status=actions[i]->check();
769                         if(status>=0)
770                         {
771                                 ++count;
772
773                                 delete actions[i];
774                                 actions.erase(actions.begin()+i);
775                                 if(status>0)
776                                         fail=true;
777                                 if(actions.empty() && fail)
778                                         finish=true;
779                         }
780                         else
781                                 ++i;
782                 }
783         }
784
785         if(show_progress)
786                 IO::print("\033[K");
787         if(fail)
788                 IO::print("Build failed\n");
789         else if(show_progress)
790                 IO::print("Build complete\n");
791
792         return fail;
793 }
794
795 int Builder::do_clean()
796 {
797         // Cleaning doesn't care about ordering, so a simpler method can be used
798
799         set<Target *> clean_tgts;
800         TargetList queue;
801         queue.push_back(get_target("cmdline"));
802
803         while(!queue.empty())
804         {
805                 Target *tgt=queue.front();
806                 queue.erase(queue.begin());
807
808                 if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
809                         clean_tgts.insert(tgt);
810
811                 const TargetList &deps=tgt->get_depends();
812                 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
813                         if(!clean_tgts.count(*i))
814                                 queue.push_back(*i);
815         }
816
817         for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
818                 if(FileTarget *ft=dynamic_cast<FileTarget *>(*i))
819                 {
820                         Action *action=new Unlink(*this, *ft);
821                         while(action->check()<0) ;
822                         delete action;
823                 }
824
825         return 0;
826 }
827
828 void Builder::package_help()
829 {
830         const Config &config=main_pkg->get_config();
831         const Config::OptionMap &options=config.get_options();
832
833         IO::print("Required packages:\n  ");
834         const PackageList &requires=main_pkg->get_requires();
835         for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
836         {
837                 if(i!=requires.begin())
838                         IO::print(", ");
839                 IO::print((*i)->get_name());
840         }
841         IO::print("\n\nPackage configuration:\n");
842         for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
843         {
844                 const Config::Option &opt=i->second;
845                 IO::print("  %s: %s (%s)", opt.name, opt.descr, opt.value);
846                 if(opt.value!=opt.defv)
847                         IO::print(" [%s]", opt.defv);
848                 IO::print("\n");
849         }
850 }
851
852 Application::RegApp<Builder> Builder::reg;
853 string Builder::usagemsg;
854 string Builder::helpmsg;
855
856
857 Builder::Loader::Loader(Builder &b, const FS::Path &s):
858         bld(b),
859         src(s)
860 {
861         add("architecture", &Loader::architecture);
862         add("binary_package", &Loader::binpkg);
863         add("profile", &Loader::profile);
864         add("package", &Loader::package);
865 }
866
867 void Builder::Loader::architecture(const string &n)
868 {
869         Architecture arch(bld, n);
870         load_sub(arch);
871         bld.archs.insert(ArchMap::value_type(n, arch));
872 }
873
874 void Builder::Loader::binpkg(const string &n)
875 {
876         BinaryPackage *pkg=new BinaryPackage(bld, n);
877         load_sub(*pkg);
878         bld.packages.insert(PackageMap::value_type(n, pkg));
879 }
880
881 void Builder::Loader::profile(const string &n)
882 {
883         StringMap prf;
884         ProfileLoader ldr(prf);
885         load_sub_with(ldr);
886         bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
887 }
888
889 void Builder::Loader::package(const string &n)
890 {
891         SourcePackage *pkg=new SourcePackage(bld, n, src);
892         if(!bld.main_pkg)
893                 bld.main_pkg=pkg;
894
895         load_sub(*pkg);
896         bld.packages.insert(PackageMap::value_type(n, pkg));
897 }
898
899
900 Builder::ProfileLoader::ProfileLoader(StringMap &p):
901         profile(p)
902 {
903         add("option", &ProfileLoader::option);
904 }
905
906 void Builder::ProfileLoader::option(const string &o, const string &v)
907 {
908         profile.insert(StringMap::value_type(o, v));
909 }