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/regex.h>
17 #include <msp/strings/utils.h>
18 #include <msp/time/units.h>
19 #include <msp/time/utils.h>
22 #include "binarypackage.h"
28 #include "pkgconfig.h"
29 #include "sharedlibrary.h"
30 #include "sourcepackage.h"
31 #include "systemlibrary.h"
34 #include "virtualtarget.h"
39 Builder::Builder(int argc, char **argv):
53 create_makefile(false)
57 bool full_paths=false;
61 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG);
62 getopt.add_option('b', "build", build, GetOpt::NO_ARG);
63 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG);
64 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG);
65 getopt.add_option('h', "help", help, GetOpt::NO_ARG);
66 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG);
67 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG);
68 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG);
69 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG);
70 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG);
71 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG);
72 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG);
73 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG);
74 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG);
75 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG);
76 //getopt.add_option( "makefile", create_makefile, GetOpt::NO_ARG);
77 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG);
80 if(!analyze_mode.empty())
82 analyzer=new Analyzer(*this);
84 if(analyze_mode=="deps")
85 analyzer->set_mode(Analyzer::DEPS);
86 else if(analyze_mode=="alldeps")
87 analyzer->set_mode(Analyzer::ALLDEPS);
88 else if(analyze_mode=="rebuild")
89 analyzer->set_mode(Analyzer::REBUILD);
90 else if(analyze_mode=="rdeps")
91 analyzer->set_mode(Analyzer::RDEPS);
93 throw UsageError("Invalid analyze mode");
95 analyzer->set_max_depth(max_depth);
96 analyzer->set_full_paths(full_paths);
98 else if(!clean && !create_makefile)
101 const vector<string> &args=getopt.get_args();
102 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
104 unsigned equal=i->find('=');
105 if(equal!=string::npos)
106 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
108 cmdline_targets.push_back(*i);
111 if(cmdline_targets.empty())
112 cmdline_targets.push_back("default");
114 if(!work_dir.empty())
115 chdir(work_dir.c_str());
119 Architecture &native_arch=archs.insert(ArchMap::value_type("native", Architecture(*this, "native"))).first->second;
120 native_arch.set_tool("CC", "gcc");
121 native_arch.set_tool("CXX", "g++");
122 native_arch.set_tool("LD", "gcc");
123 native_arch.set_tool("LXX", "g++");
124 native_arch.set_tool("AR", "ar");
126 const char *home=getenv("HOME");
128 load_build_file((Path(home)/".builderrc").str());
132 Gets a package with the specified name, possibly creating it.
134 @param n Package name
136 @return Pointer to the package, or 0 if the package could not be located
138 Package *Builder::get_package(const string &n)
140 PackageMap::iterator i=packages.find(n);
141 if(i!=packages.end())
144 // Try to get source directory with pkgconfig
146 argv.push_back("pkg-config");
147 argv.push_back("--variable=source");
150 cout<<"Running "<<join(argv.begin(), argv.end())<<'\n';
151 string srcdir=strip(run_command(argv));
155 dirs.push_back(srcdir);
157 // Make some other guesses about the source directory
159 if(!dirname.compare(0, 3, "msp"))
161 dirs.push_back(cwd/dirname);
162 dirs.push_back(cwd/".."/dirname);
164 // Go through the candidate directories and look for a Build file
165 for(PathList::iterator j=dirs.begin(); j!=dirs.end(); ++j)
166 if(!load_build_file(*j/"Build"))
169 if(i!=packages.end())
174 // Package source not found - create a binary package
175 Package *pkg=BinaryPackage::from_pkgconfig(*this, n);
177 packages.insert(PackageMap::value_type(n, pkg));
180 problem(n, "not found");
186 Returns the target with the given name, or 0 if no such target exists.
188 Target *Builder::get_target(const string &n) const
190 TargetMap::const_iterator i=targets.find(n);
197 Tries to locate a header included from a given location and with a given include
198 path. Considers known targets as well as existing files. If a matching target
199 is not found but a file exists, a new SystemHeader target will be created and
202 Target *Builder::get_header(const string &include, const string &arch, const string &from, const list<string> &path)
205 update_hash(hash, from);
206 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
207 update_hash(hash, *i);
209 string id=hash+include;
210 TargetMap::iterator i=includes.find(id);
211 if(i!=includes.end())
214 static string cxx_ver;
218 argv.push_back(get_architecture(arch).get_tool("CXX"));
219 argv.push_back("--version");
220 cxx_ver=Regex(" ([0-9.]+) ").match(run_command(argv))[1].str;
221 while(!cxx_ver.empty() && !exists(Path("/usr/include/c++")/cxx_ver))
223 unsigned dot=cxx_ver.rfind('.');
224 if(dot==string::npos)
229 cout<<"C++ version is "<<cxx_ver<<'\n';
232 string fn=include.substr(1);
234 cout<<"Looking for include "<<fn<<" with path "<<join(path.begin(), path.end())<<'\n';
238 syspath.push_back(from);
240 syspath.push_back("/usr/include");
242 syspath.push_back("/usr/"+get_architecture(arch).get_prefix()+"/lib");
243 syspath.push_back((Path("/usr/include/c++/")/cxx_ver/fn).str());
246 for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
247 tgt=get_header(Path(*j)/fn);
248 for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
249 tgt=get_header(cwd/ *j/fn);
251 includes.insert(TargetMap::value_type(id, tgt));
257 Tries to locate a library with the given library path. Considers known targets
258 as well as existing files. If a matching target is not found but a file exists,
259 a new SystemLibrary target will be created and returned.
261 @param lib Name of the library to get (without "lib" prefix or extension)
262 @param path List of paths to search for the library
263 @param mode Shared / static mode
265 @return Some kind of library target, if a match was found
267 Target *Builder::get_library(const string &lib, const string &arch, const list<string> &path, LibMode mode)
270 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
271 update_hash(hash, *i);
273 //XXX Incorporate mode into id
275 TargetMap::iterator i=libraries.find(id);
276 if(i!=libraries.end())
282 syspath.push_back("/lib");
283 syspath.push_back("/usr/lib");
286 syspath.push_back("/usr/"+get_architecture(arch).get_prefix()+"/lib");
289 cout<<"Looking for library "<<lib<<" with path "<<join(path.begin(), path.end())<<'\n';
292 for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
293 tgt=get_library(lib, arch, *j, mode);
294 for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
295 tgt=get_library(lib, arch, cwd/ *j, mode);
297 libraries.insert(TargetMap::value_type(id, tgt));
302 const Architecture &Builder::get_architecture(const string &arch) const
304 ArchMap::const_iterator i=archs.find(arch);
306 throw InvalidParameterValue("Unknown architecture");
311 void Builder::apply_profile_template(Config &config, const string &pt) const
313 vector<string> parts=split(pt, '-');
315 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
317 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
318 if(j==profile_tmpl.end())
321 config.update(j->second);
325 void Builder::problem(const string &p, const string &d)
327 problems.push_back(Problem(p, d));
331 Adds a target to both the target map and the new target queue. Called from
334 void Builder::add_target(Target *t)
336 targets.insert(TargetMap::value_type(t->get_name(), t));
337 new_tgts.push_back(t);
342 if(load_build_file(cwd/build_file))
344 cerr<<"No build info here.\n";
348 main_pkg->configure(cmdline_options, conf_all?2:1);
352 usage(0, "builder", false);
358 if(!conf_only && create_targets())
361 PackageList all_reqs=main_pkg->collect_requires();
363 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
365 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
367 if(spkg && spkg->get_arch()!=main_pkg->get_arch())
368 problem(spkg->get_name(), format("wrong architecture (%s)", spkg->get_arch()));
374 cout<<all_reqs.size()<<" active packages, "<<targets.size()<<" targets\n";
377 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
379 cout<<' '<<(*i)->get_name();
380 if(dynamic_cast<SourcePackage *>(*i))
383 unsigned ood_count=0;
384 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
385 if(j->second->get_package()==*i)
388 if(j->second->get_rebuild())
393 cout<<" ("<<count<<" targets";
395 cout<<", "<<ood_count<<" out-of-date";
405 if(!problems.empty())
407 cerr<<"The following problems were detected:\n";
408 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
409 cerr<<" "<<i->package<<": "<<i->descr<<'\n';
410 cerr<<"Please fix them and try again.\n";
417 exit_code=do_clean();
419 exit_code=do_build();
426 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
428 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
433 void Builder::usage(const char *reason, const char *argv0, bool brief)
439 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> ...]";
443 "Usage: "<<argv0<<" [options] [<target> ...]\n"
446 " -a, --analyze MODE Perform analysis. MODE can be deps, alldeps or rebuild.\n"
447 " -b, --build Perform build even if doing analysis.\n"
448 " -c, --clean Clean buildable targets.\n"
449 " -f, --file FILE Read info from FILE instead of Build.\n"
450 " -h, --help Print this message.\n"
451 " -j, --jobs NUM Run NUM commands at once, whenever possible.\n"
452 " -n, --dry-run Don't actually do anything, only show what would be done.\n"
453 " -v, --verbose Print more information about what's going on.\n"
454 " -A, --conf-all Apply configuration to all packages.\n"
455 " -B, --build-all Build all targets unconditionally.\n"
456 " -C, --chdir DIR Change to DIR before doing anything else.\n"
457 " -P, --progress Display progress while building.\n"
458 " -W, --what-if FILE Pretend that FILE has changed.\n"
459 " --conf-only Stop after configuring packages.\n"
460 " --full-paths Output full paths in analysis.\n"
461 //" --makefile Create a makefile for this package.\n"
462 " --max-depth NUM Maximum depth to show in analysis.\n";
467 Loads the given build file.
469 @param fn Path to the file
471 @return 0 on success, -1 if the file could not be opened
473 int Builder::load_build_file(const Path &fn)
475 ifstream in(fn.str().c_str());
480 cout<<"Reading "<<fn<<'\n';
482 DataFile::Parser parser(in, fn.str());
483 Loader loader(*this, fn.subpath(0, fn.size()-1));
490 Creates targets for all packages and prepares them for building.
492 @return 0 if everything went ok, -1 if something bad happened and a build
493 shouldn't be attempted
495 int Builder::create_targets()
497 Target *world=new VirtualTarget(*this, "world");
499 Target *def_tgt=new VirtualTarget(*this, "default");
500 world->add_depend(def_tgt);
502 Target *install=new VirtualTarget(*this, "install");
503 world->add_depend(install);
505 Target *tarballs=new VirtualTarget(*this, "tarballs");
506 world->add_depend(tarballs);
508 PackageList all_reqs=main_pkg->collect_requires();
509 for(PackageList::iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
511 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
515 const ComponentList &components=spkg->get_components();
516 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
519 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
521 PkgConfig *pc=new PkgConfig(*this, *spkg);
522 install->add_depend(new Install(*this, *spkg, *pc));
525 tarballs->add_depend(new TarBall(*this, *spkg));
528 // Find dependencies until no new targets are created
529 while(!new_tgts.empty())
531 Target *tgt=new_tgts.front();
532 new_tgts.erase(new_tgts.begin());
534 if(!tgt->get_depends_ready())
535 new_tgts.push_back(tgt);
539 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
541 Target *tgt=get_target((cwd/ *i).str());
544 cerr<<"Unknown what-if target "<<*i<<'\n';
550 // Make the cmdline target depend on all targets mentioned on the command line
551 Target *cmdline=new VirtualTarget(*this, "cmdline");
552 bool build_world=false;
553 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
555 Target *tgt=get_target(*i);
557 tgt=get_target((cwd/ *i).str());
560 cerr<<"I don't know anything about "<<*i<<'\n';
565 cmdline->add_depend(tgt);
568 /* If world is to be built, prepare cmdline. If not, add cmdline to world
569 and prepare world. I don't really like this, but it keeps the graph
575 world->add_depend(cmdline);
579 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
580 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
581 spkg->get_deps_cache().save();
587 Check if a header exists, either as a target or a file. Either an existing
588 target or a new SystemHeader target will be returned.
590 Target *Builder::get_header(const Msp::Path &fn)
592 Target *tgt=get_target(fn.str());
597 tgt=new SystemHeader(*this, fn.str());
603 Target *Builder::get_library(const string &lib, const string &arch, const Path &path, LibMode mode)
605 // Populate a list of candidate filenames
606 StringList candidates;
611 candidates.push_back("lib"+lib+".dll");
613 candidates.push_back("lib"+lib+".so");
616 /* Static libraries are always considered, since sometimes shared versions
617 may not be available */
618 candidates.push_back("lib"+lib+".a");
620 candidates.push_back("lib"+lib+".dll.a");
622 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
624 string full=(path/ *i).str();
625 Target *tgt=get_target(full);
629 Target *real_tgt=tgt;
630 if(dynamic_cast<Install *>(tgt))
631 real_tgt=real_tgt->get_depends().front();
633 /* Ignore dynamic libraries from local packages unless library mode is
635 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
640 else if(exists(full))
642 tgt=new SystemLibrary(*this, full);
651 Updates a hash with a string. This is used from get_header and get_library.
653 void Builder::update_hash(string &hash, const string &value)
655 for(unsigned i=0; i<value.size(); ++i)
656 hash[i%hash.size()]^=value[i];
660 This function supervises the build process, starting new actions when slots
663 int Builder::do_build()
665 Target *cmdline=get_target("cmdline");
667 unsigned total=cmdline->count_rebuild();
670 cout<<"Already up to date\n";
673 cout<<"Will build "<<total<<" target(s)\n";
675 vector<Action *> actions;
684 if(actions.size()<jobs && !fail)
686 Target *tgt=cmdline->get_buildable_target();
689 Action *action=tgt->build();
691 actions.push_back(action);
695 cout<<count<<" of "<<total<<" targets built\033[1G";
699 else if(actions.empty())
703 Time::sleep(10*Time::msec);
705 for(unsigned i=0; i<actions.size();)
707 int status=actions[i]->check();
713 actions.erase(actions.begin()+i);
716 if(actions.empty() && fail)
727 cout<<"Build failed\n";
728 else if(show_progress)
729 cout<<"Build complete\n";
735 Cleans buildable targets. If clean is 1, cleans only this package. If
736 clean is 2 or greater, cleans all buildable packages.
738 int Builder::do_clean()
740 // Cleaning doesn't care about ordering, so a simpler method can be used
742 set<Target *> clean_tgts;
744 queue.push_back(get_target("cmdline"));
746 while(!queue.empty())
748 Target *tgt=queue.front();
749 queue.erase(queue.begin());
751 if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
752 clean_tgts.insert(tgt);
754 const TargetList &deps=tgt->get_depends();
755 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
756 if(!clean_tgts.count(*i))
760 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
762 Action *action=new Unlink(*this, **i);
763 while(action->check()<0);
771 Prints out information about the default package.
773 void Builder::package_help()
775 const Config &config=main_pkg->get_config();
776 const Config::OptionMap &options=config.get_options();
778 cout<<"Required packages:\n ";
779 const PackageList &requires=main_pkg->get_requires();
780 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
782 if(i!=requires.begin())
784 cout<<(*i)->get_name();
787 cout<<"Package configuration:\n";
788 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
790 const Config::Option &opt=i->second;
791 cout<<" "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
795 Application::RegApp<Builder> Builder::reg;
798 Builder::Loader::Loader(Builder &b, const Path &s):
802 add("architecture", &Loader::architecture);
803 add("binary_package", &Loader::binpkg);
804 add("profile", &Loader::profile);
805 add("package", &Loader::package);
808 void Builder::Loader::architecture(const string &n)
810 Architecture arch(bld, n);
812 bld.archs.insert(ArchMap::value_type(n, arch));
815 void Builder::Loader::binpkg(const string &n)
817 BinaryPackage *pkg=new BinaryPackage(bld, n);
819 bld.packages.insert(PackageMap::value_type(n, pkg));
822 void Builder::Loader::profile(const string &n)
825 load_sub<ProfileLoader>(prf);
826 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
829 void Builder::Loader::package(const string &n)
831 SourcePackage *pkg=new SourcePackage(bld, n, src);
836 bld.packages.insert(PackageMap::value_type(n, pkg));
840 Builder::ProfileLoader::ProfileLoader(StringMap &p):
843 add("option", &ProfileLoader::option);
846 void Builder::ProfileLoader::option(const string &o, const string &v)
848 profile.insert(StringMap::value_type(o, v));