3 This file is part of builder
4 Copyright © 2006-2007 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
11 #include <msp/core/error.h>
12 #include <msp/core/getopt.h>
13 #include <msp/datafile/parser.h>
14 #include <msp/path/utils.h>
15 #include <msp/strings/formatter.h>
16 #include <msp/strings/utils.h>
17 #include <msp/time/units.h>
18 #include <msp/time/utils.h>
21 #include "binarypackage.h"
27 #include "pkgconfig.h"
28 #include "sharedlibrary.h"
29 #include "sourcepackage.h"
30 #include "systemlibrary.h"
33 #include "virtualtarget.h"
38 Builder::Builder(int argc, char **argv):
52 create_makefile(false)
56 bool full_paths=false;
60 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG);
61 getopt.add_option('b', "build", build, GetOpt::NO_ARG);
62 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG);
63 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG);
64 getopt.add_option('h', "help", help, GetOpt::NO_ARG);
65 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG);
66 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG);
67 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG);
68 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG);
69 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG);
70 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG);
71 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG);
72 getopt.add_option( "chrome", chrome, GetOpt::NO_ARG);
73 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG);
74 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG);
75 //getopt.add_option( "makefile", create_makefile, GetOpt::NO_ARG);
76 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG);
79 if(!analyze_mode.empty())
81 analyzer=new Analyzer(*this);
83 if(analyze_mode=="deps")
84 analyzer->set_mode(Analyzer::DEPS);
85 else if(analyze_mode=="alldeps")
86 analyzer->set_mode(Analyzer::ALLDEPS);
87 else if(analyze_mode=="rebuild")
88 analyzer->set_mode(Analyzer::REBUILD);
89 else if(analyze_mode=="rdeps")
90 analyzer->set_mode(Analyzer::RDEPS);
92 throw UsageError("Invalid analyze mode");
94 analyzer->set_max_depth(max_depth);
95 analyzer->set_full_paths(full_paths);
97 else if(!clean && !create_makefile)
100 const list<string> &args=getopt.get_args();
101 for(list<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
103 unsigned equal=i->find('=');
104 if(equal!=string::npos)
105 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
107 cmdline_targets.push_back(*i);
110 if(cmdline_targets.empty())
111 cmdline_targets.push_back("default");
113 if(!work_dir.empty())
114 chdir(work_dir.c_str());
118 Architecture &native_arch=archs.insert(ArchMap::value_type("native", Architecture(*this, "native"))).first->second;
119 native_arch.set_tool("CC", "gcc");
120 native_arch.set_tool("CXX", "g++");
121 native_arch.set_tool("LD", "gcc");
122 native_arch.set_tool("LXX", "g++");
123 native_arch.set_tool("AR", "ar");
125 const char *home=getenv("HOME");
127 load_build_file((Path::Path(home)/".builderrc").str());
131 Gets a package with the specified name, possibly creating it.
133 @param n Package name
135 @return Pointer to the package, or 0 if the package could not be located
137 Package *Builder::get_package(const string &n)
139 PackageMap::iterator i=packages.find(n);
140 if(i!=packages.end())
143 // Try to get source directory with pkgconfig
145 argv.push_back("pkg-config");
146 argv.push_back("--variable=source");
148 string srcdir=strip(run_command(argv));
152 dirs.push_back(srcdir);
154 // Make some other guesses about the source directory
156 if(!dirname.compare(0, 3, "msp"))
158 dirs.push_back(cwd/dirname);
159 dirs.push_back(cwd/".."/dirname);
161 // Go through the candidate directories and look for a Build file
162 for(PathList::iterator j=dirs.begin(); j!=dirs.end(); ++j)
163 if(!load_build_file(*j/"Build"))
166 if(i!=packages.end())
171 // Package source not found - create a binary package
172 Package *pkg=BinaryPackage::from_pkgconfig(*this, n);
174 packages.insert(PackageMap::value_type(n, pkg));
177 problem(n, "not found");
183 Returns the target with the given name, or 0 if no such target exists.
185 Target *Builder::get_target(const string &n) const
187 TargetMap::const_iterator i=targets.find(n);
194 Tries to locate a header included from a given location and with a given include
195 path. Considers known targets as well as existing files. If a matching target
196 is not found but a file exists, a new SystemHeader target will be created and
199 Target *Builder::get_header(const string &include, const string &, const string &from, const list<string> &path)
202 update_hash(hash, from);
203 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
204 update_hash(hash, *i);
206 string id=hash+include;
207 TargetMap::iterator i=includes.find(id);
208 if(i!=includes.end())
211 string fn=include.substr(1);
213 if(include[0]=='"' && (tgt=get_header(Path::Path(from)/fn)))
215 else if((tgt=get_header(Path::Path("/usr/include")/fn)))
217 //XXX Determine the C++ header location dynamically
218 else if((tgt=get_header(Path::Path("/usr/include/c++/4.1.2")/fn)))
222 for(list<string>::const_iterator j=path.begin(); (j!=path.end() && !tgt); ++j)
223 tgt=get_header(cwd/ *j/fn);
226 includes.insert(TargetMap::value_type(id, tgt));
232 Tries to locate a library with the given library path. Considers known targets
233 as well as existing files. If a matching target is not found but a file exists,
234 a new SystemLibrary target will be created and returned.
236 @param lib Name of the library to get (without "lib" prefix or extension)
237 @param path List of paths to search for the library
238 @param mode Shared / static mode
240 @return Some kind of library target, if a match was found
242 Target *Builder::get_library(const string &lib, const string &arch, const list<string> &path, LibMode mode)
245 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
246 update_hash(hash, *i);
248 //XXX Incorporate mode into id
250 TargetMap::iterator i=libraries.find(id);
251 if(i!=libraries.end())
257 syspath.push_back("/lib");
258 syspath.push_back("/usr/lib");
261 syspath.push_back("/usr/"+get_architecture(arch).get_prefix()+"/lib");
264 for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
265 tgt=get_library(lib, arch, *j, mode);
266 for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
267 tgt=get_library(lib, arch, cwd/ *j, mode);
269 libraries.insert(TargetMap::value_type(id, tgt));
274 const Architecture &Builder::get_architecture(const string &arch) const
276 ArchMap::const_iterator i=archs.find(arch);
278 throw InvalidParameterValue("Unknown architecture");
283 void Builder::apply_profile_template(Config &config, const string &pt) const
285 vector<string> parts=split(pt, '-');
287 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
289 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
290 if(j==profile_tmpl.end())
293 config.update(j->second);
297 void Builder::problem(const string &p, const string &d)
299 problems.push_back(Problem(p, d));
303 Adds a target to both the target map and the new target queue. Called from
306 void Builder::add_target(Target *t)
308 targets.insert(TargetMap::value_type(t->get_name(), t));
309 new_tgts.push_back(t);
314 if(load_build_file(cwd/build_file))
316 cerr<<"No build info here.\n";
320 main_pkg->configure(cmdline_options, conf_all?2:1);
324 usage(0, "builder", false);
330 if(!conf_only && create_targets())
333 PackageList all_reqs=main_pkg->collect_requires();
335 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
337 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
339 if(spkg && spkg->get_arch()!=main_pkg->get_arch())
340 problem(spkg->get_name(), format("wrong architecture (%s)", spkg->get_arch()));
343 if(!problems.empty())
345 cerr<<"The following problems were detected:\n";
346 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
347 cerr<<" "<<i->package<<": "<<i->descr<<'\n';
348 cerr<<"Please fix them and try again.\n";
355 cout<<all_reqs.size()<<" active packages, "<<targets.size()<<" targets\n";
358 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
360 cout<<' '<<(*i)->get_name();
361 if(dynamic_cast<SourcePackage *>(*i))
364 unsigned ood_count=0;
365 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
366 if(j->second->get_package()==*i)
369 if(j->second->get_rebuild())
374 cout<<" ("<<count<<" targets";
376 cout<<", "<<ood_count<<" out-of-date";
389 exit_code=do_clean();
391 exit_code=do_build();
398 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
400 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
405 void Builder::usage(const char *reason, const char *argv0, bool brief)
411 cerr<<"Usage: "<<argv0<<" [-a|--analyze MODE] [-b|--build] [-c|--clean] [-f|--file FILE] [-h|--help] [-j|--jobs NUM] [-n||--dry-run] [-v|--verbose] [-A|--conf-all] [-B|--build-all] [-C|--chdir DIRECTORY] [-W|--what-if FILE] [--chrome] [--conf-only] [--full-paths] [--max-depth NUM] [<target> ...]";
415 "Usage: "<<argv0<<" [options] [<target> ...]\n"
418 " -a, --analyze MODE Perform analysis. MODE can be deps, alldeps or rebuild.\n"
419 " -b, --build Perform build even if doing analysis.\n"
420 " -c, --clean Clean buildable targets.\n"
421 " -f, --file FILE Read info from FILE instead of Build.\n"
422 " -h, --help Print this message.\n"
423 " -j, --jobs NUM Run NUM commands at once, whenever possible.\n"
424 " -n, --dry-run Don't actually do anything, only show what would be done.\n"
425 " -v, --verbose Print more information about what's going on.\n"
426 " -A, --conf-all Apply configuration to all packages.\n"
427 " -B, --build-all Build all targets unconditionally.\n"
428 " -C, --chdir DIR Change to DIR before doing anything else.\n"
429 " -W, --what-if FILE Pretend that FILE has changed.\n"
430 " --chrome Use extra chrome to print status.\n"
431 " --conf-only Stop after configuring packages.\n"
432 " --full-paths Output full paths in analysis.\n"
433 //" --makefile Create a makefile for this package.\n"
434 " --max-depth NUM Maximum depth to show in analysis.\n";
439 Loads the given build file.
441 @param fn Path to the file
443 @return 0 on success, -1 if the file could not be opened
445 int Builder::load_build_file(const Path::Path &fn)
447 ifstream in(fn.str().c_str());
452 cout<<"Reading "<<fn<<'\n';
454 DataFile::Parser parser(in, fn.str());
455 Loader loader(*this, fn.subpath(0, fn.size()-1));
462 Creates targets for all packages and prepares them for building.
464 @return 0 if everything went ok, -1 if something bad happened and a build
465 shouldn't be attempted
467 int Builder::create_targets()
469 Target *world=new VirtualTarget(*this, "world");
471 Target *def_tgt=new VirtualTarget(*this, "default");
472 world->add_depend(def_tgt);
474 Target *install=new VirtualTarget(*this, "install");
475 world->add_depend(install);
477 Target *tarballs=new VirtualTarget(*this, "tarballs");
478 world->add_depend(tarballs);
480 PackageList all_reqs=main_pkg->collect_requires();
481 for(PackageList::iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
483 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
487 const ComponentList &components=spkg->get_components();
488 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
491 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
493 PkgConfig *pc=new PkgConfig(*this, *spkg);
494 install->add_depend(new Install(*this, *spkg, *pc));
497 tarballs->add_depend(new TarBall(*this, *spkg));
500 // Find dependencies until no new targets are created
501 while(!new_tgts.empty())
503 Target *tgt=new_tgts.front();
504 new_tgts.erase(new_tgts.begin());
506 if(!tgt->get_depends_ready())
507 new_tgts.push_back(tgt);
511 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
513 Target *tgt=get_target((cwd/ *i).str());
516 cerr<<"Unknown what-if target "<<*i<<'\n';
522 // Make the cmdline target depend on all targets mentioned on the command line
523 Target *cmdline=new VirtualTarget(*this, "cmdline");
524 bool build_world=false;
525 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
527 Target *tgt=get_target(*i);
529 tgt=get_target((cwd/ *i).str());
532 cerr<<"I don't know anything about "<<*i<<'\n';
537 cmdline->add_depend(tgt);
540 /* If world is to be built, prepare cmdline. If not, add cmdline to world
541 and prepare world. I don't really like this, but it keeps the graph
547 world->add_depend(cmdline);
551 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
552 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
553 spkg->get_deps_cache().save();
559 Check if a header exists, either as a target or a file. Either an existing
560 target or a new SystemHeader target will be returned.
562 Target *Builder::get_header(const Msp::Path::Path &fn)
564 Target *tgt=get_target(fn.str());
569 tgt=new SystemHeader(*this, fn.str());
575 Target *Builder::get_library(const string &lib, const string &arch, const Path::Path &path, LibMode mode)
577 // Populate a list of candidate filenames
578 StringList candidates;
583 candidates.push_back("lib"+lib+".dll");
585 candidates.push_back("lib"+lib+".so");
588 /* Static libraries are always considered, since sometimes shared versions
589 may not be available */
590 candidates.push_back("lib"+lib+".a");
592 candidates.push_back("lib"+lib+".dll.a");
594 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
596 string full=(path/ *i).str();
597 Target *tgt=get_target(full);
601 Target *real_tgt=tgt;
602 if(dynamic_cast<Install *>(tgt))
603 real_tgt=real_tgt->get_depends().front();
605 /* Ignore dynamic libraries from local packages unless library mode is
607 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
612 else if(Path::exists(full))
614 tgt=new SystemLibrary(*this, full);
623 Updates a hash with a string. This is used from get_header and get_library.
625 void Builder::update_hash(string &hash, const string &value)
627 for(unsigned i=0; i<value.size(); ++i)
628 hash[i%hash.size()]^=value[i];
632 This function supervises the build process, starting new actions when slots
635 int Builder::do_build()
637 Target *cmdline=get_target("cmdline");
639 unsigned total=cmdline->count_rebuild();
642 cout<<"Already up to date\n";
645 cout<<"Will build "<<total<<" target(s)\n";
647 vector<Action *> actions;
650 cout<<"0 targets built\n";
658 if(actions.size()<jobs && !fail)
660 Target *tgt=cmdline->get_buildable_target();
663 Action *action=tgt->build();
665 actions.push_back(action);
667 else if(actions.empty())
671 Time::sleep(10*Time::msec);
673 for(unsigned i=0; i<actions.size();)
675 int status=actions[i]->check();
681 cout<<"\e["<<actions.size()+1<<'A';
682 cout<<count<<" targets built\n";
686 if(i<actions.size()-1)
687 cout<<"\e["<<actions.size()-i-1<<"B";
691 actions.erase(actions.begin()+i);
694 if(actions.empty() && fail)
703 cout<<"Build failed\n";
709 Cleans buildable targets. If clean is 1, cleans only this package. If
710 clean is 2 or greater, cleans all buildable packages.
712 int Builder::do_clean()
714 // Cleaning doesn't care about ordering, so a simpler method can be used
716 set<Target *> clean_tgts;
718 queue.push_back(get_target("cmdline"));
720 while(!queue.empty())
722 Target *tgt=queue.front();
723 queue.erase(queue.begin());
725 if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
726 clean_tgts.insert(tgt);
728 const TargetList &deps=tgt->get_depends();
729 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
730 if(!clean_tgts.count(*i))
734 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
736 Action *action=new Unlink(*this, **i);
737 while(action->check()<0);
745 Prints out information about the default package.
747 void Builder::package_help()
749 const Config &config=main_pkg->get_config();
750 const Config::OptionMap &options=config.get_options();
752 cout<<"Required packages:\n ";
753 const PackageList &requires=main_pkg->get_requires();
754 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
756 if(i!=requires.begin())
758 cout<<(*i)->get_name();
761 cout<<"Package configuration:\n";
762 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
764 const Config::Option &opt=i->second;
765 cout<<" "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
769 Application::RegApp<Builder> Builder::reg;
772 Builder::Loader::Loader(Builder &b, const Path::Path &s):
776 add("architecture", &Loader::architecture);
777 add("binary_package", &Loader::binpkg);
778 add("profile", &Loader::profile);
779 add("package", &Loader::package);
782 void Builder::Loader::architecture(const string &n)
784 Architecture arch(bld, n);
786 bld.archs.insert(ArchMap::value_type(n, arch));
789 void Builder::Loader::binpkg(const string &n)
791 BinaryPackage *pkg=new BinaryPackage(bld, n);
793 bld.packages.insert(PackageMap::value_type(n, pkg));
796 void Builder::Loader::profile(const string &n)
799 load_sub<ProfileLoader>(prf);
800 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
803 void Builder::Loader::package(const string &n)
805 SourcePackage *pkg=new SourcePackage(bld, n, src);
810 bld.packages.insert(PackageMap::value_type(n, pkg));
814 Builder::ProfileLoader::ProfileLoader(StringMap &p):
817 add("option", &ProfileLoader::option);
820 void Builder::ProfileLoader::option(const string &o, const string &v)
822 profile.insert(StringMap::value_type(o, v));