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;
62 StringList cmdline_warn;
65 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG);
66 getopt.add_option('b', "build", build, GetOpt::NO_ARG);
67 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG);
68 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG);
69 getopt.add_option('h', "help", help, GetOpt::NO_ARG);
70 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG);
71 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG);
72 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG);
73 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG);
74 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG);
75 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG);
76 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG);
77 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG);
78 getopt.add_option( "arch", current_arch, GetOpt::REQUIRED_ARG);
79 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG);
80 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG);
81 //getopt.add_option( "makefile", create_makefile, GetOpt::NO_ARG);
82 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG);
83 getopt.add_option( "prefix", prefix, GetOpt::REQUIRED_ARG);
84 getopt.add_option( "warnings", cmdline_warn, GetOpt::REQUIRED_ARG);
87 if(!analyze_mode.empty())
89 analyzer=new Analyzer(*this);
91 if(analyze_mode=="deps")
92 analyzer->set_mode(Analyzer::DEPS);
93 else if(analyze_mode=="alldeps")
94 analyzer->set_mode(Analyzer::ALLDEPS);
95 else if(analyze_mode=="rebuild")
96 analyzer->set_mode(Analyzer::REBUILD);
97 else if(analyze_mode=="rdeps")
98 analyzer->set_mode(Analyzer::RDEPS);
100 throw UsageError("Invalid analyze mode");
102 analyzer->set_max_depth(max_depth);
103 analyzer->set_full_paths(full_paths);
105 else if(!clean && !create_makefile)
108 const vector<string> &args=getopt.get_args();
109 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
111 unsigned equal=i->find('=');
112 if(equal!=string::npos)
113 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
115 cmdline_targets.push_back(*i);
118 if(cmdline_targets.empty())
119 cmdline_targets.push_back("default");
121 if(!work_dir.empty())
122 chdir(work_dir.c_str());
126 Architecture &native_arch=archs.insert(ArchMap::value_type("native", Architecture(*this, "native"))).first->second;
127 native_arch.set_tool("CC", "gcc");
128 native_arch.set_tool("CXX", "g++");
129 native_arch.set_tool("LD", "gcc");
130 native_arch.set_tool("LXX", "g++");
131 native_arch.set_tool("AR", "ar");
133 load_build_file((get_home_dir()/".builderrc").str());
137 if(current_arch=="native")
138 prefix=(get_home_dir()/"local").str();
140 prefix=(get_home_dir()/"local"/current_arch).str();
143 warnings.push_back("all");
144 warnings.push_back("extra");
145 warnings.push_back("shadow");
146 warnings.push_back("pointer-arith");
147 warnings.push_back("error");
148 for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
150 vector<string> warns=split(*i, ',');
151 warnings.insert(warnings.end(), warns.begin(), warns.end());
156 Gets a package by name, possibly creating it.
158 @param name Package name
160 @return Pointer to the package, or 0 if the package could not be located
162 Package *Builder::get_package(const string &name)
164 PackageMap::iterator i=packages.find(format("%s/%s", name, current_arch));
165 if(i==packages.end())
166 i=packages.find(name);
167 if(i!=packages.end())
170 // Try to get source directory with pkgconfig
172 argv.push_back("pkg-config");
173 argv.push_back("--variable=source");
174 argv.push_back(name);
176 cout<<"Running "<<join(argv.begin(), argv.end())<<'\n';
177 string srcdir=strip(run_command(argv));
181 dirs.push_back(srcdir);
183 // Make some other guesses about the source directory
184 dirs.push_back(cwd/name);
185 dirs.push_back(cwd/".."/name);
186 if(!name.compare(0, 3, "msp"))
188 dirs.push_back(cwd/name.substr(3));
189 dirs.push_back(cwd/".."/name.substr(3));
192 // Go through the candidate directories and look for a Build file
193 for(PathList::iterator j=dirs.begin(); j!=dirs.end(); ++j)
194 if(!load_build_file(*j/"Build"))
196 i=packages.find(name);
197 if(i!=packages.end())
202 // Package source not found - create a binary package
203 Package *pkg=BinaryPackage::from_pkgconfig(*this, name);
205 packages.insert(PackageMap::value_type(name, pkg));
208 problem(name, "not found");
214 Returns the target with the given name, or 0 if no such target exists.
216 Target *Builder::get_target(const string &n) const
218 TargetMap::const_iterator i=targets.find(n);
225 Tries to locate a header included from a given location and with a given include
226 path. Considers known targets as well as existing files. If a matching target
227 is not found but a file exists, a new SystemHeader target will be created and
230 Target *Builder::get_header(const string &include, const string &from, const list<string> &path)
233 update_hash(hash, from);
234 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
235 update_hash(hash, *i);
237 string id=hash+include;
238 TargetMap::iterator i=includes.find(id);
239 if(i!=includes.end())
242 static string cxx_ver;
246 argv.push_back(get_current_arch().get_tool("CXX"));
247 argv.push_back("--version");
248 cxx_ver=Regex("[0-9]\\.[0-9.]+").match(run_command(argv))[0].str;
249 while(!cxx_ver.empty() && !exists(Path("/usr/include/c++")/cxx_ver))
251 unsigned dot=cxx_ver.rfind('.');
252 if(dot==string::npos)
257 cout<<"C++ version is "<<cxx_ver<<'\n';
260 string fn=include.substr(1);
262 cout<<"Looking for include "<<fn<<" with path "<<join(path.begin(), path.end())<<'\n';
265 if(current_arch=="native")
266 syspath.push_back("/usr/include");
268 syspath.push_back("/usr/"+get_architecture(current_arch).get_prefix()+"/include");
269 syspath.push_back((Path("/usr/include/c++/")/cxx_ver/fn).str());
273 tgt=get_header(Path(from)/fn);
274 for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
275 tgt=get_header(cwd/ *j/fn);
276 for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
277 tgt=get_header(Path(*j)/fn);
279 includes.insert(TargetMap::value_type(id, tgt));
285 Tries to locate a library with the given library path. Considers known targets
286 as well as existing files. If a matching target is not found but a file exists,
287 a new SystemLibrary target will be created and returned.
289 @param lib Name of the library to get (without "lib" prefix or extension)
290 @param path List of paths to search for the library
291 @param mode Shared / static mode
293 @return Some kind of library target, if a match was found
295 Target *Builder::get_library(const string &lib, const list<string> &path, LibMode mode)
298 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
299 update_hash(hash, *i);
301 string id=hash+string(1, mode)+lib;
302 TargetMap::iterator i=libraries.find(id);
303 if(i!=libraries.end())
307 if(current_arch=="native")
309 syspath.push_back("/lib");
310 syspath.push_back("/usr/lib");
313 syspath.push_back("/usr/"+get_current_arch().get_prefix()+"/lib");
316 cout<<"Looking for library "<<lib<<" with path "<<join(path.begin(), path.end())<<'\n';
319 for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
320 tgt=get_library(lib, cwd/ *j, mode);
321 for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
322 tgt=get_library(lib, *j, mode);
324 libraries.insert(TargetMap::value_type(id, tgt));
329 const Architecture &Builder::get_architecture(const string &arch) const
331 ArchMap::const_iterator i=archs.find(arch);
333 throw KeyError("Unknown architecture", arch);
338 const Architecture &Builder::get_current_arch() const
340 return get_architecture(current_arch);
343 void Builder::apply_profile_template(Config &config, const string &pt) const
345 vector<string> parts=split(pt, '-');
347 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
349 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
350 if(j==profile_tmpl.end())
353 config.update(j->second);
357 void Builder::problem(const string &p, const string &d)
359 problems.push_back(Problem(p, d));
363 Adds a target to both the target map and the new target queue. Called from
366 void Builder::add_target(Target *t)
368 targets.insert(TargetMap::value_type(t->get_name(), t));
369 new_tgts.push_back(t);
374 if(load_build_file(cwd/build_file))
376 cerr<<"No build info here.\n";
380 main_pkg->configure(cmdline_options, conf_all?2:1);
384 usage(0, "builder", false);
390 if(!conf_only && create_targets())
393 PackageList all_reqs=main_pkg->collect_requires();
398 cout<<all_reqs.size()<<" active packages, "<<targets.size()<<" targets\n";
401 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
403 cout<<' '<<(*i)->get_name();
404 if(dynamic_cast<SourcePackage *>(*i))
407 unsigned ood_count=0;
408 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
409 if(j->second->get_package()==*i)
412 if(j->second->get_rebuild())
417 cout<<" ("<<count<<" targets";
419 cout<<", "<<ood_count<<" out-of-date";
429 if(!problems.empty())
431 cerr<<"The following problems were detected:\n";
432 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
433 cerr<<" "<<i->package<<": "<<i->descr<<'\n';
434 cerr<<"Please fix them and try again.\n";
441 exit_code=do_clean();
443 exit_code=do_build();
450 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
452 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
457 void Builder::usage(const char *reason, const char *argv0, bool brief)
463 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> ...]\n";
467 "Usage: "<<argv0<<" [options] [<target> ...]\n"
470 " -a, --analyze MODE Perform analysis. MODE can be deps, alldeps or rebuild.\n"
471 " -b, --build Perform build even if doing analysis.\n"
472 " -c, --clean Clean buildable targets.\n"
473 " -f, --file FILE Read info from FILE instead of Build.\n"
474 " -h, --help Print this message.\n"
475 " -j, --jobs NUM Run NUM commands at once, whenever possible.\n"
476 " -n, --dry-run Don't actually do anything, only show what would be done.\n"
477 " -v, --verbose Print more information about what's going on.\n"
478 " -A, --conf-all Apply configuration to all packages.\n"
479 " -B, --build-all Build all targets unconditionally.\n"
480 " -C, --chdir DIR Change to DIR before doing anything else.\n"
481 " -P, --progress Display progress while building.\n"
482 " -W, --what-if FILE Pretend that FILE has changed.\n"
483 " --arch ARCH Architecture to build for.\n"
484 " --conf-only Stop after configuring packages.\n"
485 " --full-paths Output full paths in analysis.\n"
486 //" --makefile Create a makefile for this package.\n"
487 " --max-depth NUM Maximum depth to show in analysis.\n"
488 " --prefix DIR Directory to install things to.\n"
489 " --warnings LIST Compiler warnings to use.\n";
494 Loads the given build file.
496 @param fn Path to the file
498 @return 0 on success, -1 if the file could not be opened
500 int Builder::load_build_file(const Path &fn)
504 IO::File inf(fn.str());
505 IO::Buffered in(inf);
508 cout<<"Reading "<<fn<<'\n';
510 DataFile::Parser parser(in, fn.str());
511 Loader loader(*this, fn.subpath(0, fn.size()-1));
514 catch(const IO::FileNotFound &)
523 Creates targets for all packages and prepares them for building.
525 @return 0 if everything went ok, -1 if something bad happened and a build
526 shouldn't be attempted
528 int Builder::create_targets()
530 Target *world=new VirtualTarget(*this, "world");
532 Target *def_tgt=new VirtualTarget(*this, "default");
533 world->add_depend(def_tgt);
535 Target *install=new VirtualTarget(*this, "install");
536 world->add_depend(install);
538 Target *tarballs=new VirtualTarget(*this, "tarballs");
539 world->add_depend(tarballs);
541 PackageList all_reqs=main_pkg->collect_requires();
542 for(PackageList::iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
544 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
548 const ComponentList &components=spkg->get_components();
549 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
552 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
554 PkgConfig *pc=new PkgConfig(*this, *spkg);
555 install->add_depend(new Install(*this, *spkg, *pc));
558 tarballs->add_depend(new TarBall(*this, *spkg));
561 // Find dependencies until no new targets are created
562 while(!new_tgts.empty())
564 Target *tgt=new_tgts.front();
565 new_tgts.erase(new_tgts.begin());
567 if(!tgt->get_depends_ready())
568 new_tgts.push_back(tgt);
572 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
574 Target *tgt=get_target((cwd/ *i).str());
577 cerr<<"Unknown what-if target "<<*i<<'\n';
583 // Make the cmdline target depend on all targets mentioned on the command line
584 Target *cmdline=new VirtualTarget(*this, "cmdline");
585 bool build_world=false;
586 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
588 Target *tgt=get_target(*i);
590 tgt=get_target((cwd/ *i).str());
593 cerr<<"I don't know anything about "<<*i<<'\n';
598 cmdline->add_depend(tgt);
601 /* If world is to be built, prepare cmdline. If not, add cmdline to world
602 and prepare world. I don't really like this, but it keeps the graph
608 world->add_depend(cmdline);
612 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
613 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
614 spkg->get_deps_cache().save();
620 Check if a header exists, either as a target or a file. Either an existing
621 target or a new SystemHeader target will be returned.
623 Target *Builder::get_header(const Msp::Path &fn)
625 Target *tgt=get_target(fn.str());
630 tgt=new SystemHeader(*this, fn.str());
636 Target *Builder::get_library(const string &lib, const Path &path, LibMode mode)
638 // Populate a list of candidate filenames
639 StringList candidates;
643 if(current_arch=="win32")
645 candidates.push_back("lib"+lib+".dll");
646 candidates.push_back(lib+".dll");
649 candidates.push_back("lib"+lib+".so");
652 /* Static libraries are always considered, since sometimes shared versions
653 may not be available */
654 candidates.push_back("lib"+lib+".a");
655 if(current_arch=="win32")
656 candidates.push_back("lib"+lib+".dll.a");
658 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
660 string full=(path/ *i).str();
661 Target *tgt=get_target(full);
665 Target *real_tgt=tgt;
666 if(dynamic_cast<Install *>(tgt))
667 real_tgt=real_tgt->get_depends().front();
669 /* Ignore dynamic libraries from local packages unless library mode is
671 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
676 else if(exists(full))
678 tgt=new SystemLibrary(*this, full);
687 Updates a hash with a string. This is used from get_header and get_library.
689 void Builder::update_hash(string &hash, const string &value)
691 for(unsigned i=0; i<value.size(); ++i)
692 hash[i%hash.size()]^=value[i];
696 This function supervises the build process, starting new actions when slots
699 int Builder::do_build()
701 Target *cmdline=get_target("cmdline");
703 unsigned total=cmdline->count_rebuild();
706 cout<<"Already up to date\n";
709 cout<<"Will build "<<total<<" target(s)\n";
711 vector<Action *> actions;
720 if(actions.size()<jobs && !fail)
722 Target *tgt=cmdline->get_buildable_target();
725 Action *action=tgt->build();
727 actions.push_back(action);
731 cout<<count<<" of "<<total<<" targets built\033[1G";
735 else if(actions.empty())
739 Time::sleep(10*Time::msec);
741 for(unsigned i=0; i<actions.size();)
743 int status=actions[i]->check();
749 actions.erase(actions.begin()+i);
752 if(actions.empty() && fail)
763 cout<<"Build failed\n";
764 else if(show_progress)
765 cout<<"Build complete\n";
771 Cleans buildable targets. If clean is 1, cleans only this package. If
772 clean is 2 or greater, cleans all buildable packages.
774 int Builder::do_clean()
776 // Cleaning doesn't care about ordering, so a simpler method can be used
778 set<Target *> clean_tgts;
780 queue.push_back(get_target("cmdline"));
782 while(!queue.empty())
784 Target *tgt=queue.front();
785 queue.erase(queue.begin());
787 if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
788 clean_tgts.insert(tgt);
790 const TargetList &deps=tgt->get_depends();
791 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
792 if(!clean_tgts.count(*i))
796 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
798 Action *action=new Unlink(*this, **i);
799 while(action->check()<0) ;
807 Prints out information about the default package.
809 void Builder::package_help()
811 const Config &config=main_pkg->get_config();
812 const Config::OptionMap &options=config.get_options();
814 cout<<"Required packages:\n ";
815 const PackageList &requires=main_pkg->get_requires();
816 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
818 if(i!=requires.begin())
820 cout<<(*i)->get_name();
823 cout<<"Package configuration:\n";
824 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
826 const Config::Option &opt=i->second;
827 cout<<" "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
831 Application::RegApp<Builder> Builder::reg;
834 Builder::Loader::Loader(Builder &b, const Path &s):
838 add("architecture", &Loader::architecture);
839 add("binary_package", &Loader::binpkg);
840 add("profile", &Loader::profile);
841 add("package", &Loader::package);
844 void Builder::Loader::architecture(const string &n)
846 Architecture arch(bld, n);
848 bld.archs.insert(ArchMap::value_type(n, arch));
851 void Builder::Loader::binpkg(const string &n)
853 BinaryPackage *pkg=new BinaryPackage(bld, n);
855 bld.packages.insert(PackageMap::value_type(n, pkg));
858 void Builder::Loader::profile(const string &n)
861 load_sub<ProfileLoader>(prf);
862 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
865 void Builder::Loader::package(const string &n)
867 SourcePackage *pkg=new SourcePackage(bld, n, src);
872 bld.packages.insert(PackageMap::value_type(n, pkg));
876 Builder::ProfileLoader::ProfileLoader(StringMap &p):
879 add("option", &ProfileLoader::option);
882 void Builder::ProfileLoader::option(const string &o, const string &v)
884 profile.insert(StringMap::value_type(o, v));