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/utils.h>
17 #include <msp/time/units.h>
18 #include <msp/time/utils.h>
21 #include "binarypackage.h"
27 #include "pkgconfig.h"
28 #include "sharedlibrary.h"
29 #include "sourcepackage.h"
30 #include "systemlibrary.h"
33 #include "virtualtarget.h"
38 Builder::Builder(int argc, char **argv):
52 create_makefile(false)
56 bool full_paths=false;
60 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG);
61 getopt.add_option('b', "build", build, GetOpt::NO_ARG);
62 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG);
63 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG);
64 getopt.add_option('h', "help", help, GetOpt::NO_ARG);
65 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG);
66 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG);
67 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG);
68 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG);
69 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG);
70 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG);
71 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG);
72 getopt.add_option( "chrome", chrome, GetOpt::NO_ARG);
73 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG);
74 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG);
75 //getopt.add_option( "makefile", create_makefile, GetOpt::NO_ARG);
76 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG);
79 if(!analyze_mode.empty())
81 analyzer=new Analyzer(*this);
83 if(analyze_mode=="deps")
84 analyzer->set_mode(Analyzer::DEPS);
85 else if(analyze_mode=="alldeps")
86 analyzer->set_mode(Analyzer::ALLDEPS);
87 else if(analyze_mode=="rebuild")
88 analyzer->set_mode(Analyzer::REBUILD);
89 else if(analyze_mode=="rdeps")
90 analyzer->set_mode(Analyzer::RDEPS);
92 throw UsageError("Invalid analyze mode");
94 analyzer->set_max_depth(max_depth);
95 analyzer->set_full_paths(full_paths);
97 else if(!clean && !create_makefile)
100 const list<string> &args=getopt.get_args();
101 for(list<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
103 unsigned equal=i->find('=');
104 if(equal!=string::npos)
105 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
107 cmdline_targets.push_back(*i);
110 if(cmdline_targets.empty())
111 cmdline_targets.push_back("default");
113 if(!work_dir.empty())
114 chdir(work_dir.c_str());
118 archs.insert(StringMap::value_type("native", ""));
120 StringMap &native_tools=tools.insert(ToolMap::value_type("native", StringMap())).first->second;
121 native_tools.insert(StringMap::value_type("CC", "gcc"));
122 native_tools.insert(StringMap::value_type("CXX", "g++"));
123 native_tools.insert(StringMap::value_type("LD", "gcc"));
124 native_tools.insert(StringMap::value_type("LDXX", "g++"));
125 native_tools.insert(StringMap::value_type("AR", "ar"));
127 const char *home=getenv("HOME");
129 load_build_file((Path::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");
150 string srcdir=strip(run_command(argv));
154 dirs.push_back(srcdir);
156 // Make some other guesses about the source directory
158 if(!dirname.compare(0, 3, "msp"))
160 dirs.push_back(cwd/dirname);
161 dirs.push_back(cwd/".."/dirname);
163 // Go through the candidate directories and look for a Build file
164 for(PathList::iterator j=dirs.begin(); j!=dirs.end(); ++j)
165 if(!load_build_file(*j/"Build"))
168 if(i!=packages.end())
173 // Package source not found - create a binary package
174 Package *pkg=BinaryPackage::from_pkgconfig(*this, n);
176 packages.insert(PackageMap::value_type(n, pkg));
179 problem(n, "not found");
185 Returns the target with the given name, or 0 if no such target exists.
187 Target *Builder::get_target(const string &n) const
189 TargetMap::const_iterator i=targets.find(n);
196 Tries to locate a header included from a given location and with a given include
197 path. Considers known targets as well as existing files. If a matching target
198 is not found but a file exists, a new SystemHeader target will be created and
201 Target *Builder::get_header(const string &include, const string &, const string &from, const list<string> &path)
204 update_hash(hash, from);
205 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
206 update_hash(hash, *i);
208 string id=hash+include;
209 TargetMap::iterator i=includes.find(id);
210 if(i!=includes.end())
213 string fn=include.substr(1);
215 if(include[0]=='"' && (tgt=get_header(Path::Path(from)/fn)))
217 else if((tgt=get_header(Path::Path("/usr/include")/fn)))
219 //XXX Determine the C++ header location dynamically
220 else if((tgt=get_header(Path::Path("/usr/include/c++/4.1.2")/fn)))
224 for(list<string>::const_iterator j=path.begin(); (j!=path.end() && !tgt); ++j)
225 tgt=get_header(cwd/ *j/fn);
228 includes.insert(TargetMap::value_type(id, tgt));
234 Tries to locate a library with the given library path. Considers known targets
235 as well as existing files. If a matching target is not found but a file exists,
236 a new SystemLibrary target will be created and returned.
238 @param lib Name of the library to get (without "lib" prefix or extension)
239 @param path List of paths to search for the library
240 @param mode Shared / static mode
242 @return Some kind of library target, if a match was found
244 Target *Builder::get_library(const string &lib, const string &arch, const list<string> &path, LibMode mode)
247 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
248 update_hash(hash, *i);
250 //XXX Incorporate mode into id
252 TargetMap::iterator i=libraries.find(id);
253 if(i!=libraries.end())
259 syspath.push_back("/lib");
260 syspath.push_back("/usr/lib");
263 syspath.push_back("/usr/"+get_arch_prefix(arch)+"/lib");
266 for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
267 tgt=get_library(lib, arch, *j, mode);
268 for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
269 tgt=get_library(lib, arch, cwd/ *j, mode);
271 libraries.insert(TargetMap::value_type(id, tgt));
276 const string &Builder::get_arch_prefix(const string &arch) const
278 StringMap::const_iterator i=archs.find(arch);
280 throw InvalidParameterValue("Unknown architecture");
285 string Builder::get_tool(const std::string &tool, const std::string &arch)
287 ToolMap::iterator i=tools.find(arch);
290 StringMap::iterator j=i->second.find(tool);
291 if(j!=i->second.end())
295 // Either the arch, or the tool within the arch was not found
296 i=tools.find("native");
297 StringMap::iterator j=i->second.find(tool);
298 if(j==i->second.end())
299 throw InvalidParameterValue("Unknown tool");
301 return get_arch_prefix(arch)+"-"+j->second;
304 void Builder::apply_profile_template(Config &config, const string &pt) const
306 vector<string> parts=split(pt, '-');
308 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
310 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
311 if(j==profile_tmpl.end())
314 config.update(j->second);
318 void Builder::problem(const string &p, const string &d)
320 problems.push_back(Problem(p, d));
324 Adds a target to both the target map and the new target queue. Called from
327 void Builder::add_target(Target *t)
329 targets.insert(TargetMap::value_type(t->get_name(), t));
330 new_tgts.push_back(t);
335 if(load_build_file(cwd/build_file))
337 cerr<<"No build info here.\n";
341 main_pkg->configure(cmdline_options, conf_all?2:1);
345 usage(0, "builder", false);
351 if(!conf_only && create_targets())
354 PackageList all_reqs=main_pkg->collect_requires();
356 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
358 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
360 if(spkg && spkg->get_arch()!=main_pkg->get_arch())
361 problem(spkg->get_name(), format("wrong architecture (%s)", spkg->get_arch()));
364 if(!problems.empty())
366 cerr<<"The following problems were detected:\n";
367 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
368 cerr<<" "<<i->package<<": "<<i->descr<<'\n';
369 cerr<<"Please fix them and try again.\n";
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";
410 exit_code=do_clean();
412 exit_code=do_build();
419 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
421 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
426 void Builder::usage(const char *reason, const char *argv0, bool brief)
432 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> ...]";
436 "Usage: "<<argv0<<" [options] [<target> ...]\n"
439 " -a, --analyze MODE Perform analysis. MODE can be deps, alldeps or rebuild.\n"
440 " -b, --build Perform build even if doing analysis.\n"
441 " -c, --clean Clean buildable targets.\n"
442 " -f, --file FILE Read info from FILE instead of Build.\n"
443 " -h, --help Print this message.\n"
444 " -j, --jobs NUM Run NUM commands at once, whenever possible.\n"
445 " -n, --dry-run Don't actually do anything, only show what would be done.\n"
446 " -v, --verbose Print more information about what's going on.\n"
447 " -A, --conf-all Apply configuration to all packages.\n"
448 " -B, --build-all Build all targets unconditionally.\n"
449 " -C, --chdir DIR Change to DIR before doing anything else.\n"
450 " -W, --what-if FILE Pretend that FILE has changed.\n"
451 " --chrome Use extra chrome to print status.\n"
452 " --conf-only Stop after configuring packages.\n"
453 " --full-paths Output full paths in analysis.\n"
454 //" --makefile Create a makefile for this package.\n"
455 " --max-depth NUM Maximum depth to show in analysis.\n";
460 Loads the given build file.
462 @param fn Path to the file
464 @return 0 on success, -1 if the file could not be opened
466 int Builder::load_build_file(const Path::Path &fn)
468 ifstream in(fn.str().c_str());
473 cout<<"Reading "<<fn<<'\n';
475 DataFile::Parser parser(in, fn.str());
476 Loader loader(*this, fn.subpath(0, fn.size()-1));
483 Creates targets for all packages and prepares them for building.
485 @return 0 if everything went ok, -1 if something bad happened and a build
486 shouldn't be attempted
488 int Builder::create_targets()
490 Target *world=new VirtualTarget(*this, "world");
492 Target *def_tgt=new VirtualTarget(*this, "default");
493 world->add_depend(def_tgt);
495 Target *install=new VirtualTarget(*this, "install");
496 world->add_depend(install);
498 Target *tarballs=new VirtualTarget(*this, "tarballs");
499 world->add_depend(tarballs);
501 PackageList all_reqs=main_pkg->collect_requires();
502 for(PackageList::iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
504 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
508 const ComponentList &components=spkg->get_components();
509 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
512 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
514 PkgConfig *pc=new PkgConfig(*this, *spkg);
515 install->add_depend(new Install(*this, *spkg, *pc));
518 tarballs->add_depend(new TarBall(*this, *spkg));
521 // Find dependencies until no new targets are created
522 while(!new_tgts.empty())
524 Target *tgt=new_tgts.front();
525 new_tgts.erase(new_tgts.begin());
527 if(!tgt->get_depends_ready())
528 new_tgts.push_back(tgt);
532 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
534 Target *tgt=get_target((cwd/ *i).str());
537 cerr<<"Unknown what-if target "<<*i<<'\n';
543 // Make the cmdline target depend on all targets mentioned on the command line
544 Target *cmdline=new VirtualTarget(*this, "cmdline");
545 bool build_world=false;
546 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
548 Target *tgt=get_target(*i);
550 tgt=get_target((cwd/ *i).str());
553 cerr<<"I don't know anything about "<<*i<<'\n';
558 cmdline->add_depend(tgt);
561 /* If world is to be built, prepare cmdline. If not, add cmdline to world
562 and prepare world. I don't really like this, but it keeps the graph
568 world->add_depend(cmdline);
572 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
573 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
574 spkg->get_deps_cache().save();
580 Check if a header exists, either as a target or a file. Either an existing
581 target or a new SystemHeader target will be returned.
583 Target *Builder::get_header(const Msp::Path::Path &fn)
585 Target *tgt=get_target(fn.str());
590 tgt=new SystemHeader(*this, fn.str());
596 Target *Builder::get_library(const string &lib, const string &arch, const Path::Path &path, LibMode mode)
598 // Populate a list of candidate filenames
599 StringList candidates;
604 candidates.push_back("lib"+lib+".dll");
606 candidates.push_back("lib"+lib+".so");
609 /* Static libraries are always considered, since sometimes shared versions
610 may not be available */
611 candidates.push_back("lib"+lib+".a");
613 candidates.push_back("lib"+lib+".dll.a");
615 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
617 string full=(path/ *i).str();
618 Target *tgt=get_target(full);
622 Target *real_tgt=tgt;
623 if(dynamic_cast<Install *>(tgt))
624 real_tgt=real_tgt->get_depends().front();
626 /* Ignore dynamic libraries from local packages unless library mode is
628 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
633 else if(Path::exists(full))
635 tgt=new SystemLibrary(*this, full);
644 Updates a hash with a string. This is used from get_header and get_library.
646 void Builder::update_hash(string &hash, const string &value)
648 for(unsigned i=0; i<value.size(); ++i)
649 hash[i%hash.size()]^=value[i];
653 This function supervises the build process, starting new actions when slots
656 int Builder::do_build()
658 Target *cmdline=get_target("cmdline");
660 unsigned total=cmdline->count_rebuild();
663 cout<<"Already up to date\n";
666 cout<<"Will build "<<total<<" target(s)\n";
668 vector<Action *> actions;
671 cout<<"0 targets built\n";
679 if(actions.size()<jobs && !fail)
681 Target *tgt=cmdline->get_buildable_target();
684 Action *action=tgt->build();
686 actions.push_back(action);
688 else if(actions.empty())
692 Time::sleep(10*Time::msec);
694 for(unsigned i=0; i<actions.size();)
696 int status=actions[i]->check();
702 cout<<"\e["<<actions.size()+1<<'A';
703 cout<<count<<" targets built\n";
707 if(i<actions.size()-1)
708 cout<<"\e["<<actions.size()-i-1<<"B";
712 actions.erase(actions.begin()+i);
715 if(actions.empty() && fail)
724 cout<<"Build failed\n";
730 Cleans buildable targets. If clean is 1, cleans only this package. If
731 clean is 2 or greater, cleans all buildable packages.
733 int Builder::do_clean()
735 // Cleaning doesn't care about ordering, so a simpler method can be used
737 set<Target *> clean_tgts;
739 queue.push_back(get_target("cmdline"));
741 while(!queue.empty())
743 Target *tgt=queue.front();
744 queue.erase(queue.begin());
746 if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
747 clean_tgts.insert(tgt);
749 const TargetList &deps=tgt->get_depends();
750 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
751 if(!clean_tgts.count(*i))
755 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
757 Action *action=new Unlink(*this, **i);
758 while(action->check()<0);
766 Prints out information about the default package.
768 void Builder::package_help()
770 const Config &config=main_pkg->get_config();
771 const Config::OptionMap &options=config.get_options();
773 cout<<"Required packages:\n ";
774 const PackageList &requires=main_pkg->get_requires();
775 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
777 if(i!=requires.begin())
779 cout<<(*i)->get_name();
782 cout<<"Package configuration:\n";
783 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
785 const Config::Option &opt=i->second;
786 cout<<" "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
790 Application::RegApp<Builder> Builder::reg;
793 Builder::Loader::Loader(Builder &b, const Path::Path &s):
797 add("architecture", &Loader::architecture);
798 add("binary_package", &Loader::binpkg);
799 add("profile", &Loader::profile);
800 add("package", &Loader::package);
803 void Builder::Loader::architecture(const string &a, const string &p)
805 bld.archs.insert(StringMap::value_type(a, p));
808 void Builder::Loader::binpkg(const string &n)
810 BinaryPackage *pkg=new BinaryPackage(bld, n);
812 bld.packages.insert(PackageMap::value_type(n, pkg));
815 void Builder::Loader::profile(const string &n)
818 load_sub<ProfileLoader>(prf);
819 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
822 void Builder::Loader::package(const string &n)
824 SourcePackage *pkg=new SourcePackage(bld, n, src);
829 bld.packages.insert(PackageMap::value_type(n, pkg));
833 Builder::ProfileLoader::ProfileLoader(StringMap &p):
836 add("option", &ProfileLoader::option);
839 void Builder::ProfileLoader::option(const string &o, const string &v)
841 profile.insert(StringMap::value_type(o, v));