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)
59 bool full_paths=false;
63 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG);
64 getopt.add_option('b', "build", build, GetOpt::NO_ARG);
65 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG);
66 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG);
67 getopt.add_option('h', "help", help, GetOpt::NO_ARG);
68 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG);
69 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG);
70 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG);
71 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG);
72 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG);
73 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG);
74 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG);
75 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG);
76 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG);
77 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG);
78 //getopt.add_option( "makefile", create_makefile, GetOpt::NO_ARG);
79 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG);
82 if(!analyze_mode.empty())
84 analyzer=new Analyzer(*this);
86 if(analyze_mode=="deps")
87 analyzer->set_mode(Analyzer::DEPS);
88 else if(analyze_mode=="alldeps")
89 analyzer->set_mode(Analyzer::ALLDEPS);
90 else if(analyze_mode=="rebuild")
91 analyzer->set_mode(Analyzer::REBUILD);
92 else if(analyze_mode=="rdeps")
93 analyzer->set_mode(Analyzer::RDEPS);
95 throw UsageError("Invalid analyze mode");
97 analyzer->set_max_depth(max_depth);
98 analyzer->set_full_paths(full_paths);
100 else if(!clean && !create_makefile)
103 const vector<string> &args=getopt.get_args();
104 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
106 unsigned equal=i->find('=');
107 if(equal!=string::npos)
108 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
110 cmdline_targets.push_back(*i);
113 if(cmdline_targets.empty())
114 cmdline_targets.push_back("default");
116 if(!work_dir.empty())
117 chdir(work_dir.c_str());
121 Architecture &native_arch=archs.insert(ArchMap::value_type("native", Architecture(*this, "native"))).first->second;
122 native_arch.set_tool("CC", "gcc");
123 native_arch.set_tool("CXX", "g++");
124 native_arch.set_tool("LD", "gcc");
125 native_arch.set_tool("LXX", "g++");
126 native_arch.set_tool("AR", "ar");
128 const char *home=getenv("HOME");
130 load_build_file((Path(home)/".builderrc").str());
134 Gets a package with the specified name, possibly creating it.
136 @param n Package name
138 @return Pointer to the package, or 0 if the package could not be located
140 Package *Builder::get_package(const string &n)
142 PackageMap::iterator i=packages.find(n);
143 if(i!=packages.end())
146 // Try to get source directory with pkgconfig
148 argv.push_back("pkg-config");
149 argv.push_back("--variable=source");
152 cout<<"Running "<<join(argv.begin(), argv.end())<<'\n';
153 string srcdir=strip(run_command(argv));
157 dirs.push_back(srcdir);
159 // Make some other guesses about the source directory
161 if(!dirname.compare(0, 3, "msp"))
163 dirs.push_back(cwd/dirname);
164 dirs.push_back(cwd/".."/dirname);
166 // Go through the candidate directories and look for a Build file
167 for(PathList::iterator j=dirs.begin(); j!=dirs.end(); ++j)
168 if(!load_build_file(*j/"Build"))
171 if(i!=packages.end())
176 // Package source not found - create a binary package
177 Package *pkg=BinaryPackage::from_pkgconfig(*this, n);
179 packages.insert(PackageMap::value_type(n, pkg));
182 problem(n, "not found");
188 Returns the target with the given name, or 0 if no such target exists.
190 Target *Builder::get_target(const string &n) const
192 TargetMap::const_iterator i=targets.find(n);
199 Tries to locate a header included from a given location and with a given include
200 path. Considers known targets as well as existing files. If a matching target
201 is not found but a file exists, a new SystemHeader target will be created and
204 Target *Builder::get_header(const string &include, const string &arch, const string &from, const list<string> &path)
207 update_hash(hash, from);
208 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
209 update_hash(hash, *i);
211 string id=hash+include;
212 TargetMap::iterator i=includes.find(id);
213 if(i!=includes.end())
216 static string cxx_ver;
220 argv.push_back(get_architecture(arch).get_tool("CXX"));
221 argv.push_back("--version");
222 cxx_ver=Regex("[0-9]\\.[0-9.]+").match(run_command(argv))[0].str;
223 while(!cxx_ver.empty() && !exists(Path("/usr/include/c++")/cxx_ver))
225 unsigned dot=cxx_ver.rfind('.');
226 if(dot==string::npos)
231 cout<<"C++ version is "<<cxx_ver<<'\n';
234 string fn=include.substr(1);
236 cout<<"Looking for include "<<fn<<" with path "<<join(path.begin(), path.end())<<'\n';
240 syspath.push_back("/usr/include");
242 syspath.push_back("/usr/"+get_architecture(arch).get_prefix()+"/include");
243 syspath.push_back((Path("/usr/include/c++/")/cxx_ver/fn).str());
247 tgt=get_header(Path(from)/fn);
248 for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
249 tgt=get_header(cwd/ *j/fn);
250 for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
251 tgt=get_header(Path(*j)/fn);
253 includes.insert(TargetMap::value_type(id, tgt));
259 Tries to locate a library with the given library path. Considers known targets
260 as well as existing files. If a matching target is not found but a file exists,
261 a new SystemLibrary target will be created and returned.
263 @param lib Name of the library to get (without "lib" prefix or extension)
264 @param path List of paths to search for the library
265 @param mode Shared / static mode
267 @return Some kind of library target, if a match was found
269 Target *Builder::get_library(const string &lib, const string &arch, const list<string> &path, LibMode mode)
272 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
273 update_hash(hash, *i);
275 //XXX Incorporate mode into id
277 TargetMap::iterator i=libraries.find(id);
278 if(i!=libraries.end())
284 syspath.push_back("/lib");
285 syspath.push_back("/usr/lib");
288 syspath.push_back("/usr/"+get_architecture(arch).get_prefix()+"/lib");
291 cout<<"Looking for library "<<lib<<" with path "<<join(path.begin(), path.end())<<'\n';
294 for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
295 tgt=get_library(lib, arch, cwd/ *j, mode);
296 for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
297 tgt=get_library(lib, arch, *j, mode);
299 libraries.insert(TargetMap::value_type(id, tgt));
304 const Architecture &Builder::get_architecture(const string &arch) const
306 ArchMap::const_iterator i=archs.find(arch);
308 throw InvalidParameterValue("Unknown architecture");
313 void Builder::apply_profile_template(Config &config, const string &pt) const
315 vector<string> parts=split(pt, '-');
317 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
319 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
320 if(j==profile_tmpl.end())
323 config.update(j->second);
327 void Builder::problem(const string &p, const string &d)
329 problems.push_back(Problem(p, d));
333 Adds a target to both the target map and the new target queue. Called from
336 void Builder::add_target(Target *t)
338 targets.insert(TargetMap::value_type(t->get_name(), t));
339 new_tgts.push_back(t);
344 if(load_build_file(cwd/build_file))
346 cerr<<"No build info here.\n";
350 main_pkg->configure(cmdline_options, conf_all?2:1);
354 usage(0, "builder", false);
360 if(!conf_only && create_targets())
363 PackageList all_reqs=main_pkg->collect_requires();
365 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
367 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
369 if(spkg && spkg->get_arch()!=main_pkg->get_arch())
370 problem(spkg->get_name(), format("wrong architecture (%s)", spkg->get_arch()));
376 cout<<all_reqs.size()<<" active packages, "<<targets.size()<<" targets\n";
379 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
381 cout<<' '<<(*i)->get_name();
382 if(dynamic_cast<SourcePackage *>(*i))
385 unsigned ood_count=0;
386 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
387 if(j->second->get_package()==*i)
390 if(j->second->get_rebuild())
395 cout<<" ("<<count<<" targets";
397 cout<<", "<<ood_count<<" out-of-date";
407 if(!problems.empty())
409 cerr<<"The following problems were detected:\n";
410 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
411 cerr<<" "<<i->package<<": "<<i->descr<<'\n';
412 cerr<<"Please fix them and try again.\n";
419 exit_code=do_clean();
421 exit_code=do_build();
428 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
430 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
435 void Builder::usage(const char *reason, const char *argv0, bool brief)
441 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> ...]";
445 "Usage: "<<argv0<<" [options] [<target> ...]\n"
448 " -a, --analyze MODE Perform analysis. MODE can be deps, alldeps or rebuild.\n"
449 " -b, --build Perform build even if doing analysis.\n"
450 " -c, --clean Clean buildable targets.\n"
451 " -f, --file FILE Read info from FILE instead of Build.\n"
452 " -h, --help Print this message.\n"
453 " -j, --jobs NUM Run NUM commands at once, whenever possible.\n"
454 " -n, --dry-run Don't actually do anything, only show what would be done.\n"
455 " -v, --verbose Print more information about what's going on.\n"
456 " -A, --conf-all Apply configuration to all packages.\n"
457 " -B, --build-all Build all targets unconditionally.\n"
458 " -C, --chdir DIR Change to DIR before doing anything else.\n"
459 " -P, --progress Display progress while building.\n"
460 " -W, --what-if FILE Pretend that FILE has changed.\n"
461 " --conf-only Stop after configuring packages.\n"
462 " --full-paths Output full paths in analysis.\n"
463 //" --makefile Create a makefile for this package.\n"
464 " --max-depth NUM Maximum depth to show in analysis.\n";
469 Loads the given build file.
471 @param fn Path to the file
473 @return 0 on success, -1 if the file could not be opened
475 int Builder::load_build_file(const Path &fn)
479 IO::File inf(fn.str());
480 IO::Buffered in(inf);
483 cout<<"Reading "<<fn<<'\n';
485 DataFile::Parser parser(in, fn.str());
486 Loader loader(*this, fn.subpath(0, fn.size()-1));
489 catch(const IO::FileNotFound &)
498 Creates targets for all packages and prepares them for building.
500 @return 0 if everything went ok, -1 if something bad happened and a build
501 shouldn't be attempted
503 int Builder::create_targets()
505 Target *world=new VirtualTarget(*this, "world");
507 Target *def_tgt=new VirtualTarget(*this, "default");
508 world->add_depend(def_tgt);
510 Target *install=new VirtualTarget(*this, "install");
511 world->add_depend(install);
513 Target *tarballs=new VirtualTarget(*this, "tarballs");
514 world->add_depend(tarballs);
516 PackageList all_reqs=main_pkg->collect_requires();
517 for(PackageList::iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
519 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
523 const ComponentList &components=spkg->get_components();
524 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
527 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
529 PkgConfig *pc=new PkgConfig(*this, *spkg);
530 install->add_depend(new Install(*this, *spkg, *pc));
533 tarballs->add_depend(new TarBall(*this, *spkg));
536 // Find dependencies until no new targets are created
537 while(!new_tgts.empty())
539 Target *tgt=new_tgts.front();
540 new_tgts.erase(new_tgts.begin());
542 if(!tgt->get_depends_ready())
543 new_tgts.push_back(tgt);
547 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
549 Target *tgt=get_target((cwd/ *i).str());
552 cerr<<"Unknown what-if target "<<*i<<'\n';
558 // Make the cmdline target depend on all targets mentioned on the command line
559 Target *cmdline=new VirtualTarget(*this, "cmdline");
560 bool build_world=false;
561 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
563 Target *tgt=get_target(*i);
565 tgt=get_target((cwd/ *i).str());
568 cerr<<"I don't know anything about "<<*i<<'\n';
573 cmdline->add_depend(tgt);
576 /* If world is to be built, prepare cmdline. If not, add cmdline to world
577 and prepare world. I don't really like this, but it keeps the graph
583 world->add_depend(cmdline);
587 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
588 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
589 spkg->get_deps_cache().save();
595 Check if a header exists, either as a target or a file. Either an existing
596 target or a new SystemHeader target will be returned.
598 Target *Builder::get_header(const Msp::Path &fn)
600 Target *tgt=get_target(fn.str());
605 tgt=new SystemHeader(*this, fn.str());
611 Target *Builder::get_library(const string &lib, const string &arch, const Path &path, LibMode mode)
613 // Populate a list of candidate filenames
614 StringList candidates;
620 candidates.push_back("lib"+lib+".dll");
621 candidates.push_back(lib+".dll");
624 candidates.push_back("lib"+lib+".so");
627 /* Static libraries are always considered, since sometimes shared versions
628 may not be available */
629 candidates.push_back("lib"+lib+".a");
631 candidates.push_back("lib"+lib+".dll.a");
633 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
635 string full=(path/ *i).str();
636 Target *tgt=get_target(full);
640 Target *real_tgt=tgt;
641 if(dynamic_cast<Install *>(tgt))
642 real_tgt=real_tgt->get_depends().front();
644 /* Ignore dynamic libraries from local packages unless library mode is
646 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
651 else if(exists(full))
653 tgt=new SystemLibrary(*this, full);
662 Updates a hash with a string. This is used from get_header and get_library.
664 void Builder::update_hash(string &hash, const string &value)
666 for(unsigned i=0; i<value.size(); ++i)
667 hash[i%hash.size()]^=value[i];
671 This function supervises the build process, starting new actions when slots
674 int Builder::do_build()
676 Target *cmdline=get_target("cmdline");
678 unsigned total=cmdline->count_rebuild();
681 cout<<"Already up to date\n";
684 cout<<"Will build "<<total<<" target(s)\n";
686 vector<Action *> actions;
695 if(actions.size()<jobs && !fail)
697 Target *tgt=cmdline->get_buildable_target();
700 Action *action=tgt->build();
702 actions.push_back(action);
706 cout<<count<<" of "<<total<<" targets built\033[1G";
710 else if(actions.empty())
714 Time::sleep(10*Time::msec);
716 for(unsigned i=0; i<actions.size();)
718 int status=actions[i]->check();
724 actions.erase(actions.begin()+i);
727 if(actions.empty() && fail)
738 cout<<"Build failed\n";
739 else if(show_progress)
740 cout<<"Build complete\n";
746 Cleans buildable targets. If clean is 1, cleans only this package. If
747 clean is 2 or greater, cleans all buildable packages.
749 int Builder::do_clean()
751 // Cleaning doesn't care about ordering, so a simpler method can be used
753 set<Target *> clean_tgts;
755 queue.push_back(get_target("cmdline"));
757 while(!queue.empty())
759 Target *tgt=queue.front();
760 queue.erase(queue.begin());
762 if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
763 clean_tgts.insert(tgt);
765 const TargetList &deps=tgt->get_depends();
766 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
767 if(!clean_tgts.count(*i))
771 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
773 Action *action=new Unlink(*this, **i);
774 while(action->check()<0);
782 Prints out information about the default package.
784 void Builder::package_help()
786 const Config &config=main_pkg->get_config();
787 const Config::OptionMap &options=config.get_options();
789 cout<<"Required packages:\n ";
790 const PackageList &requires=main_pkg->get_requires();
791 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
793 if(i!=requires.begin())
795 cout<<(*i)->get_name();
798 cout<<"Package configuration:\n";
799 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
801 const Config::Option &opt=i->second;
802 cout<<" "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
806 Application::RegApp<Builder> Builder::reg;
809 Builder::Loader::Loader(Builder &b, const Path &s):
813 add("architecture", &Loader::architecture);
814 add("binary_package", &Loader::binpkg);
815 add("profile", &Loader::profile);
816 add("package", &Loader::package);
819 void Builder::Loader::architecture(const string &n)
821 Architecture arch(bld, n);
823 bld.archs.insert(ArchMap::value_type(n, arch));
826 void Builder::Loader::binpkg(const string &n)
828 BinaryPackage *pkg=new BinaryPackage(bld, n);
830 bld.packages.insert(PackageMap::value_type(n, pkg));
833 void Builder::Loader::profile(const string &n)
836 load_sub<ProfileLoader>(prf);
837 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
840 void Builder::Loader::package(const string &n)
842 SourcePackage *pkg=new SourcePackage(bld, n, src);
847 bld.packages.insert(PackageMap::value_type(n, pkg));
851 Builder::ProfileLoader::ProfileLoader(StringMap &p):
854 add("option", &ProfileLoader::option);
857 void Builder::ProfileLoader::option(const string &o, const string &v)
859 profile.insert(StringMap::value_type(o, v));