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/file.h>
15 #include <msp/path/utils.h>
16 #include <msp/strings/formatter.h>
17 #include <msp/strings/regex.h>
18 #include <msp/strings/utils.h>
19 #include <msp/time/units.h>
20 #include <msp/time/utils.h>
23 #include "binarypackage.h"
29 #include "pkgconfig.h"
30 #include "sharedlibrary.h"
31 #include "sourcepackage.h"
32 #include "systemlibrary.h"
35 #include "virtualtarget.h"
40 Builder::Builder(int argc, char **argv):
54 create_makefile(false)
58 bool full_paths=false;
62 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG);
63 getopt.add_option('b', "build", build, GetOpt::NO_ARG);
64 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG);
65 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG);
66 getopt.add_option('h', "help", help, GetOpt::NO_ARG);
67 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG);
68 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG);
69 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG);
70 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG);
71 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG);
72 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG);
73 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG);
74 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG);
75 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG);
76 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG);
77 //getopt.add_option( "makefile", create_makefile, GetOpt::NO_ARG);
78 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG);
81 if(!analyze_mode.empty())
83 analyzer=new Analyzer(*this);
85 if(analyze_mode=="deps")
86 analyzer->set_mode(Analyzer::DEPS);
87 else if(analyze_mode=="alldeps")
88 analyzer->set_mode(Analyzer::ALLDEPS);
89 else if(analyze_mode=="rebuild")
90 analyzer->set_mode(Analyzer::REBUILD);
91 else if(analyze_mode=="rdeps")
92 analyzer->set_mode(Analyzer::RDEPS);
94 throw UsageError("Invalid analyze mode");
96 analyzer->set_max_depth(max_depth);
97 analyzer->set_full_paths(full_paths);
99 else if(!clean && !create_makefile)
102 const vector<string> &args=getopt.get_args();
103 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
105 unsigned equal=i->find('=');
106 if(equal!=string::npos)
107 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
109 cmdline_targets.push_back(*i);
112 if(cmdline_targets.empty())
113 cmdline_targets.push_back("default");
115 if(!work_dir.empty())
116 chdir(work_dir.c_str());
120 Architecture &native_arch=archs.insert(ArchMap::value_type("native", Architecture(*this, "native"))).first->second;
121 native_arch.set_tool("CC", "gcc");
122 native_arch.set_tool("CXX", "g++");
123 native_arch.set_tool("LD", "gcc");
124 native_arch.set_tool("LXX", "g++");
125 native_arch.set_tool("AR", "ar");
127 const char *home=getenv("HOME");
129 load_build_file((Path(home)/".builderrc").str());
133 Gets a package with the specified name, possibly creating it.
135 @param n Package name
137 @return Pointer to the package, or 0 if the package could not be located
139 Package *Builder::get_package(const string &n)
141 PackageMap::iterator i=packages.find(n);
142 if(i!=packages.end())
145 // Try to get source directory with pkgconfig
147 argv.push_back("pkg-config");
148 argv.push_back("--variable=source");
151 cout<<"Running "<<join(argv.begin(), argv.end())<<'\n';
152 string srcdir=strip(run_command(argv));
156 dirs.push_back(srcdir);
158 // Make some other guesses about the source directory
160 if(!dirname.compare(0, 3, "msp"))
162 dirs.push_back(cwd/dirname);
163 dirs.push_back(cwd/".."/dirname);
165 // Go through the candidate directories and look for a Build file
166 for(PathList::iterator j=dirs.begin(); j!=dirs.end(); ++j)
167 if(!load_build_file(*j/"Build"))
170 if(i!=packages.end())
175 // Package source not found - create a binary package
176 Package *pkg=BinaryPackage::from_pkgconfig(*this, n);
178 packages.insert(PackageMap::value_type(n, pkg));
181 problem(n, "not found");
187 Returns the target with the given name, or 0 if no such target exists.
189 Target *Builder::get_target(const string &n) const
191 TargetMap::const_iterator i=targets.find(n);
198 Tries to locate a header included from a given location and with a given include
199 path. Considers known targets as well as existing files. If a matching target
200 is not found but a file exists, a new SystemHeader target will be created and
203 Target *Builder::get_header(const string &include, const string &arch, const string &from, const list<string> &path)
206 update_hash(hash, from);
207 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
208 update_hash(hash, *i);
210 string id=hash+include;
211 TargetMap::iterator i=includes.find(id);
212 if(i!=includes.end())
215 static string cxx_ver;
219 argv.push_back(get_architecture(arch).get_tool("CXX"));
220 argv.push_back("--version");
221 cxx_ver=Regex("[0-9]\\.[0-9.]+").match(run_command(argv))[0].str;
222 while(!cxx_ver.empty() && !exists(Path("/usr/include/c++")/cxx_ver))
224 unsigned dot=cxx_ver.rfind('.');
225 if(dot==string::npos)
230 cout<<"C++ version is "<<cxx_ver<<'\n';
233 string fn=include.substr(1);
235 cout<<"Looking for include "<<fn<<" with path "<<join(path.begin(), path.end())<<'\n';
239 syspath.push_back("/usr/include");
241 syspath.push_back("/usr/"+get_architecture(arch).get_prefix()+"/include");
242 syspath.push_back((Path("/usr/include/c++/")/cxx_ver/fn).str());
246 tgt=get_header(Path(from)/fn);
247 for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
248 tgt=get_header(cwd/ *j/fn);
249 for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
250 tgt=get_header(Path(*j)/fn);
252 includes.insert(TargetMap::value_type(id, tgt));
258 Tries to locate a library with the given library path. Considers known targets
259 as well as existing files. If a matching target is not found but a file exists,
260 a new SystemLibrary target will be created and returned.
262 @param lib Name of the library to get (without "lib" prefix or extension)
263 @param path List of paths to search for the library
264 @param mode Shared / static mode
266 @return Some kind of library target, if a match was found
268 Target *Builder::get_library(const string &lib, const string &arch, const list<string> &path, LibMode mode)
271 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
272 update_hash(hash, *i);
274 //XXX Incorporate mode into id
276 TargetMap::iterator i=libraries.find(id);
277 if(i!=libraries.end())
283 syspath.push_back("/lib");
284 syspath.push_back("/usr/lib");
287 syspath.push_back("/usr/"+get_architecture(arch).get_prefix()+"/lib");
290 cout<<"Looking for library "<<lib<<" with path "<<join(path.begin(), path.end())<<'\n';
293 for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
294 tgt=get_library(lib, arch, cwd/ *j, mode);
295 for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
296 tgt=get_library(lib, arch, *j, mode);
298 libraries.insert(TargetMap::value_type(id, tgt));
303 const Architecture &Builder::get_architecture(const string &arch) const
305 ArchMap::const_iterator i=archs.find(arch);
307 throw InvalidParameterValue("Unknown architecture");
312 void Builder::apply_profile_template(Config &config, const string &pt) const
314 vector<string> parts=split(pt, '-');
316 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
318 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
319 if(j==profile_tmpl.end())
322 config.update(j->second);
326 void Builder::problem(const string &p, const string &d)
328 problems.push_back(Problem(p, d));
332 Adds a target to both the target map and the new target queue. Called from
335 void Builder::add_target(Target *t)
337 targets.insert(TargetMap::value_type(t->get_name(), t));
338 new_tgts.push_back(t);
343 if(load_build_file(cwd/build_file))
345 cerr<<"No build info here.\n";
349 main_pkg->configure(cmdline_options, conf_all?2:1);
353 usage(0, "builder", false);
359 if(!conf_only && create_targets())
362 PackageList all_reqs=main_pkg->collect_requires();
364 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
366 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
368 if(spkg && spkg->get_arch()!=main_pkg->get_arch())
369 problem(spkg->get_name(), format("wrong architecture (%s)", spkg->get_arch()));
375 cout<<all_reqs.size()<<" active packages, "<<targets.size()<<" targets\n";
378 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
380 cout<<' '<<(*i)->get_name();
381 if(dynamic_cast<SourcePackage *>(*i))
384 unsigned ood_count=0;
385 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
386 if(j->second->get_package()==*i)
389 if(j->second->get_rebuild())
394 cout<<" ("<<count<<" targets";
396 cout<<", "<<ood_count<<" out-of-date";
406 if(!problems.empty())
408 cerr<<"The following problems were detected:\n";
409 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
410 cerr<<" "<<i->package<<": "<<i->descr<<'\n';
411 cerr<<"Please fix them and try again.\n";
418 exit_code=do_clean();
420 exit_code=do_build();
427 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
429 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
434 void Builder::usage(const char *reason, const char *argv0, bool brief)
440 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> ...]";
444 "Usage: "<<argv0<<" [options] [<target> ...]\n"
447 " -a, --analyze MODE Perform analysis. MODE can be deps, alldeps or rebuild.\n"
448 " -b, --build Perform build even if doing analysis.\n"
449 " -c, --clean Clean buildable targets.\n"
450 " -f, --file FILE Read info from FILE instead of Build.\n"
451 " -h, --help Print this message.\n"
452 " -j, --jobs NUM Run NUM commands at once, whenever possible.\n"
453 " -n, --dry-run Don't actually do anything, only show what would be done.\n"
454 " -v, --verbose Print more information about what's going on.\n"
455 " -A, --conf-all Apply configuration to all packages.\n"
456 " -B, --build-all Build all targets unconditionally.\n"
457 " -C, --chdir DIR Change to DIR before doing anything else.\n"
458 " -P, --progress Display progress while building.\n"
459 " -W, --what-if FILE Pretend that FILE has changed.\n"
460 " --conf-only Stop after configuring packages.\n"
461 " --full-paths Output full paths in analysis.\n"
462 //" --makefile Create a makefile for this package.\n"
463 " --max-depth NUM Maximum depth to show in analysis.\n";
468 Loads the given build file.
470 @param fn Path to the file
472 @return 0 on success, -1 if the file could not be opened
474 int Builder::load_build_file(const Path &fn)
476 IO::File inf(fn.str());
477 IO::Buffered in(inf);
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;
612 candidates.push_back("lib"+lib+".dll");
613 candidates.push_back(lib+".dll");
616 candidates.push_back("lib"+lib+".so");
619 /* Static libraries are always considered, since sometimes shared versions
620 may not be available */
621 candidates.push_back("lib"+lib+".a");
623 candidates.push_back("lib"+lib+".dll.a");
625 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
627 string full=(path/ *i).str();
628 Target *tgt=get_target(full);
632 Target *real_tgt=tgt;
633 if(dynamic_cast<Install *>(tgt))
634 real_tgt=real_tgt->get_depends().front();
636 /* Ignore dynamic libraries from local packages unless library mode is
638 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
643 else if(exists(full))
645 tgt=new SystemLibrary(*this, full);
654 Updates a hash with a string. This is used from get_header and get_library.
656 void Builder::update_hash(string &hash, const string &value)
658 for(unsigned i=0; i<value.size(); ++i)
659 hash[i%hash.size()]^=value[i];
663 This function supervises the build process, starting new actions when slots
666 int Builder::do_build()
668 Target *cmdline=get_target("cmdline");
670 unsigned total=cmdline->count_rebuild();
673 cout<<"Already up to date\n";
676 cout<<"Will build "<<total<<" target(s)\n";
678 vector<Action *> actions;
687 if(actions.size()<jobs && !fail)
689 Target *tgt=cmdline->get_buildable_target();
692 Action *action=tgt->build();
694 actions.push_back(action);
698 cout<<count<<" of "<<total<<" targets built\033[1G";
702 else if(actions.empty())
706 Time::sleep(10*Time::msec);
708 for(unsigned i=0; i<actions.size();)
710 int status=actions[i]->check();
716 actions.erase(actions.begin()+i);
719 if(actions.empty() && fail)
730 cout<<"Build failed\n";
731 else if(show_progress)
732 cout<<"Build complete\n";
738 Cleans buildable targets. If clean is 1, cleans only this package. If
739 clean is 2 or greater, cleans all buildable packages.
741 int Builder::do_clean()
743 // Cleaning doesn't care about ordering, so a simpler method can be used
745 set<Target *> clean_tgts;
747 queue.push_back(get_target("cmdline"));
749 while(!queue.empty())
751 Target *tgt=queue.front();
752 queue.erase(queue.begin());
754 if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
755 clean_tgts.insert(tgt);
757 const TargetList &deps=tgt->get_depends();
758 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
759 if(!clean_tgts.count(*i))
763 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
765 Action *action=new Unlink(*this, **i);
766 while(action->check()<0);
774 Prints out information about the default package.
776 void Builder::package_help()
778 const Config &config=main_pkg->get_config();
779 const Config::OptionMap &options=config.get_options();
781 cout<<"Required packages:\n ";
782 const PackageList &requires=main_pkg->get_requires();
783 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
785 if(i!=requires.begin())
787 cout<<(*i)->get_name();
790 cout<<"Package configuration:\n";
791 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
793 const Config::Option &opt=i->second;
794 cout<<" "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
798 Application::RegApp<Builder> Builder::reg;
801 Builder::Loader::Loader(Builder &b, const Path &s):
805 add("architecture", &Loader::architecture);
806 add("binary_package", &Loader::binpkg);
807 add("profile", &Loader::profile);
808 add("package", &Loader::package);
811 void Builder::Loader::architecture(const string &n)
813 Architecture arch(bld, n);
815 bld.archs.insert(ArchMap::value_type(n, arch));
818 void Builder::Loader::binpkg(const string &n)
820 BinaryPackage *pkg=new BinaryPackage(bld, n);
822 bld.packages.insert(PackageMap::value_type(n, pkg));
825 void Builder::Loader::profile(const string &n)
828 load_sub<ProfileLoader>(prf);
829 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
832 void Builder::Loader::package(const string &n)
834 SourcePackage *pkg=new SourcePackage(bld, n, src);
839 bld.packages.insert(PackageMap::value_type(n, pkg));
843 Builder::ProfileLoader::ProfileLoader(StringMap &p):
846 add("option", &ProfileLoader::option);
849 void Builder::ProfileLoader::option(const string &o, const string &v)
851 profile.insert(StringMap::value_type(o, v));