3 This file is part of builder
4 Copyright © 2006-2007 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
10 #include <msp/core/except.h>
11 #include <msp/core/getopt.h>
12 #include <msp/datafile/parser.h>
13 #include <msp/io/buffered.h>
14 #include <msp/io/except.h>
15 #include <msp/io/file.h>
16 #include <msp/path/utils.h>
17 #include <msp/strings/formatter.h>
18 #include <msp/strings/regex.h>
19 #include <msp/strings/utils.h>
20 #include <msp/time/units.h>
21 #include <msp/time/utils.h>
24 #include "binarypackage.h"
30 #include "pkgconfig.h"
31 #include "sharedlibrary.h"
32 #include "sourcepackage.h"
33 #include "systemlibrary.h"
36 #include "virtualtarget.h"
41 Builder::Builder(int argc, char **argv):
55 create_makefile(false),
56 current_arch("native")
60 bool full_paths=false;
64 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG);
65 getopt.add_option('b', "build", build, GetOpt::NO_ARG);
66 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG);
67 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG);
68 getopt.add_option('h', "help", help, GetOpt::NO_ARG);
69 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG);
70 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG);
71 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG);
72 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG);
73 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG);
74 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG);
75 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG);
76 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG);
77 getopt.add_option( "arch", current_arch, GetOpt::REQUIRED_ARG);
78 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG);
79 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG);
80 //getopt.add_option( "makefile", create_makefile, GetOpt::NO_ARG);
81 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG);
82 getopt.add_option( "prefix", prefix, GetOpt::REQUIRED_ARG);
85 if(!analyze_mode.empty())
87 analyzer=new Analyzer(*this);
89 if(analyze_mode=="deps")
90 analyzer->set_mode(Analyzer::DEPS);
91 else if(analyze_mode=="alldeps")
92 analyzer->set_mode(Analyzer::ALLDEPS);
93 else if(analyze_mode=="rebuild")
94 analyzer->set_mode(Analyzer::REBUILD);
95 else if(analyze_mode=="rdeps")
96 analyzer->set_mode(Analyzer::RDEPS);
98 throw UsageError("Invalid analyze mode");
100 analyzer->set_max_depth(max_depth);
101 analyzer->set_full_paths(full_paths);
103 else if(!clean && !create_makefile)
106 const vector<string> &args=getopt.get_args();
107 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
109 unsigned equal=i->find('=');
110 if(equal!=string::npos)
111 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
113 cmdline_targets.push_back(*i);
116 if(cmdline_targets.empty())
117 cmdline_targets.push_back("default");
119 if(!work_dir.empty())
120 chdir(work_dir.c_str());
124 Architecture &native_arch=archs.insert(ArchMap::value_type("native", Architecture(*this, "native"))).first->second;
125 native_arch.set_tool("CC", "gcc");
126 native_arch.set_tool("CXX", "g++");
127 native_arch.set_tool("LD", "gcc");
128 native_arch.set_tool("LXX", "g++");
129 native_arch.set_tool("AR", "ar");
131 load_build_file((get_home_dir()/".builderrc").str());
135 if(current_arch=="native")
136 prefix=(get_home_dir()/"local").str();
138 prefix=(get_home_dir()/"local"/current_arch).str();
143 Gets a package by name, possibly creating it.
145 @param name Package name
147 @return Pointer to the package, or 0 if the package could not be located
149 Package *Builder::get_package(const string &name)
151 PackageMap::iterator i=packages.find(format("%s/%s", name, current_arch));
152 if(i==packages.end())
153 i=packages.find(name);
154 if(i!=packages.end())
157 // Try to get source directory with pkgconfig
159 argv.push_back("pkg-config");
160 argv.push_back("--variable=source");
161 argv.push_back(name);
163 cout<<"Running "<<join(argv.begin(), argv.end())<<'\n';
164 string srcdir=strip(run_command(argv));
168 dirs.push_back(srcdir);
170 // Make some other guesses about the source directory
171 dirs.push_back(cwd/name);
172 dirs.push_back(cwd/".."/name);
173 if(!name.compare(0, 3, "msp"))
175 dirs.push_back(cwd/name.substr(3));
176 dirs.push_back(cwd/".."/name.substr(3));
179 // Go through the candidate directories and look for a Build file
180 for(PathList::iterator j=dirs.begin(); j!=dirs.end(); ++j)
181 if(!load_build_file(*j/"Build"))
183 i=packages.find(name);
184 if(i!=packages.end())
189 // Package source not found - create a binary package
190 Package *pkg=BinaryPackage::from_pkgconfig(*this, name);
192 packages.insert(PackageMap::value_type(name, pkg));
195 problem(name, "not found");
201 Returns the target with the given name, or 0 if no such target exists.
203 Target *Builder::get_target(const string &n) const
205 TargetMap::const_iterator i=targets.find(n);
212 Tries to locate a header included from a given location and with a given include
213 path. Considers known targets as well as existing files. If a matching target
214 is not found but a file exists, a new SystemHeader target will be created and
217 Target *Builder::get_header(const string &include, const string &from, const list<string> &path)
220 update_hash(hash, from);
221 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
222 update_hash(hash, *i);
224 string id=hash+include;
225 TargetMap::iterator i=includes.find(id);
226 if(i!=includes.end())
229 static string cxx_ver;
233 argv.push_back(get_current_arch().get_tool("CXX"));
234 argv.push_back("--version");
235 cxx_ver=Regex("[0-9]\\.[0-9.]+").match(run_command(argv))[0].str;
236 while(!cxx_ver.empty() && !exists(Path("/usr/include/c++")/cxx_ver))
238 unsigned dot=cxx_ver.rfind('.');
239 if(dot==string::npos)
244 cout<<"C++ version is "<<cxx_ver<<'\n';
247 string fn=include.substr(1);
249 cout<<"Looking for include "<<fn<<" with path "<<join(path.begin(), path.end())<<'\n';
252 if(current_arch=="native")
253 syspath.push_back("/usr/include");
255 syspath.push_back("/usr/"+get_architecture(current_arch).get_prefix()+"/include");
256 syspath.push_back((Path("/usr/include/c++/")/cxx_ver/fn).str());
260 tgt=get_header(Path(from)/fn);
261 for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
262 tgt=get_header(cwd/ *j/fn);
263 for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
264 tgt=get_header(Path(*j)/fn);
266 includes.insert(TargetMap::value_type(id, tgt));
272 Tries to locate a library with the given library path. Considers known targets
273 as well as existing files. If a matching target is not found but a file exists,
274 a new SystemLibrary target will be created and returned.
276 @param lib Name of the library to get (without "lib" prefix or extension)
277 @param path List of paths to search for the library
278 @param mode Shared / static mode
280 @return Some kind of library target, if a match was found
282 Target *Builder::get_library(const string &lib, const list<string> &path, LibMode mode)
285 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
286 update_hash(hash, *i);
288 //XXX Incorporate mode into id
290 TargetMap::iterator i=libraries.find(id);
291 if(i!=libraries.end())
295 if(current_arch=="native")
297 syspath.push_back("/lib");
298 syspath.push_back("/usr/lib");
301 syspath.push_back("/usr/"+get_current_arch().get_prefix()+"/lib");
304 cout<<"Looking for library "<<lib<<" with path "<<join(path.begin(), path.end())<<'\n';
307 for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
308 tgt=get_library(lib, cwd/ *j, mode);
309 for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
310 tgt=get_library(lib, *j, mode);
312 libraries.insert(TargetMap::value_type(id, tgt));
317 const Architecture &Builder::get_architecture(const string &arch) const
319 ArchMap::const_iterator i=archs.find(arch);
321 throw KeyError("Unknown architecture", arch);
326 const Architecture &Builder::get_current_arch() const
328 return get_architecture(current_arch);
331 void Builder::apply_profile_template(Config &config, const string &pt) const
333 vector<string> parts=split(pt, '-');
335 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
337 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
338 if(j==profile_tmpl.end())
341 config.update(j->second);
345 void Builder::problem(const string &p, const string &d)
347 problems.push_back(Problem(p, d));
351 Adds a target to both the target map and the new target queue. Called from
354 void Builder::add_target(Target *t)
356 targets.insert(TargetMap::value_type(t->get_name(), t));
357 new_tgts.push_back(t);
362 if(load_build_file(cwd/build_file))
364 cerr<<"No build info here.\n";
368 main_pkg->configure(cmdline_options, conf_all?2:1);
372 usage(0, "builder", false);
378 if(!conf_only && create_targets())
381 PackageList all_reqs=main_pkg->collect_requires();
386 cout<<all_reqs.size()<<" active packages, "<<targets.size()<<" targets\n";
389 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
391 cout<<' '<<(*i)->get_name();
392 if(dynamic_cast<SourcePackage *>(*i))
395 unsigned ood_count=0;
396 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
397 if(j->second->get_package()==*i)
400 if(j->second->get_rebuild())
405 cout<<" ("<<count<<" targets";
407 cout<<", "<<ood_count<<" out-of-date";
417 if(!problems.empty())
419 cerr<<"The following problems were detected:\n";
420 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
421 cerr<<" "<<i->package<<": "<<i->descr<<'\n';
422 cerr<<"Please fix them and try again.\n";
429 exit_code=do_clean();
431 exit_code=do_build();
438 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
440 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
445 void Builder::usage(const char *reason, const char *argv0, bool brief)
451 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> ...]";
455 "Usage: "<<argv0<<" [options] [<target> ...]\n"
458 " -a, --analyze MODE Perform analysis. MODE can be deps, alldeps or rebuild.\n"
459 " -b, --build Perform build even if doing analysis.\n"
460 " -c, --clean Clean buildable targets.\n"
461 " -f, --file FILE Read info from FILE instead of Build.\n"
462 " -h, --help Print this message.\n"
463 " -j, --jobs NUM Run NUM commands at once, whenever possible.\n"
464 " -n, --dry-run Don't actually do anything, only show what would be done.\n"
465 " -v, --verbose Print more information about what's going on.\n"
466 " -A, --conf-all Apply configuration to all packages.\n"
467 " -B, --build-all Build all targets unconditionally.\n"
468 " -C, --chdir DIR Change to DIR before doing anything else.\n"
469 " -P, --progress Display progress while building.\n"
470 " -W, --what-if FILE Pretend that FILE has changed.\n"
471 " --conf-only Stop after configuring packages.\n"
472 " --full-paths Output full paths in analysis.\n"
473 //" --makefile Create a makefile for this package.\n"
474 " --max-depth NUM Maximum depth to show in analysis.\n";
479 Loads the given build file.
481 @param fn Path to the file
483 @return 0 on success, -1 if the file could not be opened
485 int Builder::load_build_file(const Path &fn)
489 IO::File inf(fn.str());
490 IO::Buffered in(inf);
493 cout<<"Reading "<<fn<<'\n';
495 DataFile::Parser parser(in, fn.str());
496 Loader loader(*this, fn.subpath(0, fn.size()-1));
499 catch(const IO::FileNotFound &)
508 Creates targets for all packages and prepares them for building.
510 @return 0 if everything went ok, -1 if something bad happened and a build
511 shouldn't be attempted
513 int Builder::create_targets()
515 Target *world=new VirtualTarget(*this, "world");
517 Target *def_tgt=new VirtualTarget(*this, "default");
518 world->add_depend(def_tgt);
520 Target *install=new VirtualTarget(*this, "install");
521 world->add_depend(install);
523 Target *tarballs=new VirtualTarget(*this, "tarballs");
524 world->add_depend(tarballs);
526 PackageList all_reqs=main_pkg->collect_requires();
527 for(PackageList::iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
529 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
533 const ComponentList &components=spkg->get_components();
534 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
537 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
539 PkgConfig *pc=new PkgConfig(*this, *spkg);
540 install->add_depend(new Install(*this, *spkg, *pc));
543 tarballs->add_depend(new TarBall(*this, *spkg));
546 // Find dependencies until no new targets are created
547 while(!new_tgts.empty())
549 Target *tgt=new_tgts.front();
550 new_tgts.erase(new_tgts.begin());
552 if(!tgt->get_depends_ready())
553 new_tgts.push_back(tgt);
557 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
559 Target *tgt=get_target((cwd/ *i).str());
562 cerr<<"Unknown what-if target "<<*i<<'\n';
568 // Make the cmdline target depend on all targets mentioned on the command line
569 Target *cmdline=new VirtualTarget(*this, "cmdline");
570 bool build_world=false;
571 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
573 Target *tgt=get_target(*i);
575 tgt=get_target((cwd/ *i).str());
578 cerr<<"I don't know anything about "<<*i<<'\n';
583 cmdline->add_depend(tgt);
586 /* If world is to be built, prepare cmdline. If not, add cmdline to world
587 and prepare world. I don't really like this, but it keeps the graph
593 world->add_depend(cmdline);
597 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
598 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
599 spkg->get_deps_cache().save();
605 Check if a header exists, either as a target or a file. Either an existing
606 target or a new SystemHeader target will be returned.
608 Target *Builder::get_header(const Msp::Path &fn)
610 Target *tgt=get_target(fn.str());
615 tgt=new SystemHeader(*this, fn.str());
621 Target *Builder::get_library(const string &lib, const Path &path, LibMode mode)
623 // Populate a list of candidate filenames
624 StringList candidates;
628 if(current_arch=="win32")
630 candidates.push_back("lib"+lib+".dll");
631 candidates.push_back(lib+".dll");
634 candidates.push_back("lib"+lib+".so");
637 /* Static libraries are always considered, since sometimes shared versions
638 may not be available */
639 candidates.push_back("lib"+lib+".a");
640 if(current_arch=="win32")
641 candidates.push_back("lib"+lib+".dll.a");
643 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
645 string full=(path/ *i).str();
646 Target *tgt=get_target(full);
650 Target *real_tgt=tgt;
651 if(dynamic_cast<Install *>(tgt))
652 real_tgt=real_tgt->get_depends().front();
654 /* Ignore dynamic libraries from local packages unless library mode is
656 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
661 else if(exists(full))
663 tgt=new SystemLibrary(*this, full);
672 Updates a hash with a string. This is used from get_header and get_library.
674 void Builder::update_hash(string &hash, const string &value)
676 for(unsigned i=0; i<value.size(); ++i)
677 hash[i%hash.size()]^=value[i];
681 This function supervises the build process, starting new actions when slots
684 int Builder::do_build()
686 Target *cmdline=get_target("cmdline");
688 unsigned total=cmdline->count_rebuild();
691 cout<<"Already up to date\n";
694 cout<<"Will build "<<total<<" target(s)\n";
696 vector<Action *> actions;
705 if(actions.size()<jobs && !fail)
707 Target *tgt=cmdline->get_buildable_target();
710 Action *action=tgt->build();
712 actions.push_back(action);
716 cout<<count<<" of "<<total<<" targets built\033[1G";
720 else if(actions.empty())
724 Time::sleep(10*Time::msec);
726 for(unsigned i=0; i<actions.size();)
728 int status=actions[i]->check();
734 actions.erase(actions.begin()+i);
737 if(actions.empty() && fail)
748 cout<<"Build failed\n";
749 else if(show_progress)
750 cout<<"Build complete\n";
756 Cleans buildable targets. If clean is 1, cleans only this package. If
757 clean is 2 or greater, cleans all buildable packages.
759 int Builder::do_clean()
761 // Cleaning doesn't care about ordering, so a simpler method can be used
763 set<Target *> clean_tgts;
765 queue.push_back(get_target("cmdline"));
767 while(!queue.empty())
769 Target *tgt=queue.front();
770 queue.erase(queue.begin());
772 if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
773 clean_tgts.insert(tgt);
775 const TargetList &deps=tgt->get_depends();
776 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
777 if(!clean_tgts.count(*i))
781 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
783 Action *action=new Unlink(*this, **i);
784 while(action->check()<0);
792 Prints out information about the default package.
794 void Builder::package_help()
796 const Config &config=main_pkg->get_config();
797 const Config::OptionMap &options=config.get_options();
799 cout<<"Required packages:\n ";
800 const PackageList &requires=main_pkg->get_requires();
801 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
803 if(i!=requires.begin())
805 cout<<(*i)->get_name();
808 cout<<"Package configuration:\n";
809 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
811 const Config::Option &opt=i->second;
812 cout<<" "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
816 Application::RegApp<Builder> Builder::reg;
819 Builder::Loader::Loader(Builder &b, const Path &s):
823 add("architecture", &Loader::architecture);
824 add("binary_package", &Loader::binpkg);
825 add("profile", &Loader::profile);
826 add("package", &Loader::package);
829 void Builder::Loader::architecture(const string &n)
831 Architecture arch(bld, n);
833 bld.archs.insert(ArchMap::value_type(n, arch));
836 void Builder::Loader::binpkg(const string &n)
838 BinaryPackage *pkg=new BinaryPackage(bld, n);
840 bld.packages.insert(PackageMap::value_type(n, pkg));
843 void Builder::Loader::profile(const string &n)
846 load_sub<ProfileLoader>(prf);
847 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
850 void Builder::Loader::package(const string &n)
852 SourcePackage *pkg=new SourcePackage(bld, n, src);
857 bld.packages.insert(PackageMap::value_type(n, pkg));
861 Builder::ProfileLoader::ProfileLoader(StringMap &p):
864 add("option", &ProfileLoader::option);
867 void Builder::ProfileLoader::option(const string &o, const string &v)
869 profile.insert(StringMap::value_type(o, v));