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/utils.h>
16 #include <msp/time/units.h>
17 #include <msp/time/utils.h>
20 #include "binarypackage.h"
26 #include "pkgconfig.h"
27 #include "sharedlibrary.h"
28 #include "sourcepackage.h"
29 #include "systemlibrary.h"
32 #include "virtualtarget.h"
37 Builder::Builder(int argc, char **argv):
51 create_makefile(false)
55 bool full_paths=false;
59 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG);
60 getopt.add_option('b', "build", build, GetOpt::NO_ARG);
61 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG);
62 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG);
63 getopt.add_option('h', "help", help, GetOpt::NO_ARG);
64 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG);
65 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG);
66 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG);
67 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG);
68 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG);
69 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG);
70 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG);
71 getopt.add_option( "chrome", chrome, GetOpt::NO_ARG);
72 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG);
73 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG);
74 //getopt.add_option( "makefile", create_makefile, GetOpt::NO_ARG);
75 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG);
78 if(!analyze_mode.empty())
80 analyzer=new Analyzer(*this);
82 if(analyze_mode=="deps")
83 analyzer->set_mode(Analyzer::DEPS);
84 else if(analyze_mode=="alldeps")
85 analyzer->set_mode(Analyzer::ALLDEPS);
86 else if(analyze_mode=="rebuild")
87 analyzer->set_mode(Analyzer::REBUILD);
88 else if(analyze_mode=="rdeps")
89 analyzer->set_mode(Analyzer::RDEPS);
91 throw UsageError("Invalid analyze mode");
93 analyzer->set_max_depth(max_depth);
94 analyzer->set_full_paths(full_paths);
96 else if(!clean && !create_makefile)
99 const list<string> &args=getopt.get_args();
100 for(list<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
102 unsigned equal=i->find('=');
103 if(equal!=string::npos)
104 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
106 cmdline_targets.push_back(*i);
109 if(cmdline_targets.empty())
110 cmdline_targets.push_back("default");
112 if(!work_dir.empty())
113 chdir(work_dir.c_str());
117 archs.insert(StringMap::value_type("native", ""));
119 StringMap &native_tools=tools.insert(ToolMap::value_type("native", StringMap())).first->second;
120 native_tools.insert(StringMap::value_type("CC", "gcc"));
121 native_tools.insert(StringMap::value_type("CXX", "g++"));
122 native_tools.insert(StringMap::value_type("LD", "gcc"));
123 native_tools.insert(StringMap::value_type("LDXX", "g++"));
124 native_tools.insert(StringMap::value_type("AR", "ar"));
126 const char *home=getenv("HOME");
128 load_build_file((Path::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");
149 string srcdir=strip(run_command(argv));
153 dirs.push_back(srcdir);
155 // Make some other guesses about the source directory
157 if(!dirname.compare(0, 3, "msp"))
159 dirs.push_back(cwd/dirname);
160 dirs.push_back(cwd/".."/dirname);
162 // Go through the candidate directories and look for a Build file
163 for(PathList::iterator j=dirs.begin(); j!=dirs.end(); ++j)
164 if(!load_build_file(*j/"Build"))
167 if(i!=packages.end())
172 // Package source not found - create a binary package
173 Package *pkg=BinaryPackage::from_pkgconfig(*this, n);
175 packages.insert(PackageMap::value_type(n, pkg));
177 new_pkgs.push_back(pkg);
183 Returns the target with the given name, or 0 if no such target exists.
185 Target *Builder::get_target(const string &n) const
187 TargetMap::const_iterator i=targets.find(n);
194 Tries to locate a header included from a given location and with a given include
195 path. Considers known targets as well as existing files. If a matching target
196 is not found but a file exists, a new SystemHeader target will be created and
199 Target *Builder::get_header(const string &include, const string &, const string &from, const list<string> &path)
202 update_hash(hash, from);
203 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
204 update_hash(hash, *i);
206 string id=hash+include;
207 TargetMap::iterator i=includes.find(id);
208 if(i!=includes.end())
211 string fn=include.substr(1);
213 if(include[0]=='"' && (tgt=get_header(Path::Path(from)/fn)))
215 else if((tgt=get_header(Path::Path("/usr/include")/fn)))
217 //XXX Determine the C++ header location dynamically
218 else if((tgt=get_header(Path::Path("/usr/include/c++/4.1.2")/fn)))
222 for(list<string>::const_iterator j=path.begin(); (j!=path.end() && !tgt); ++j)
223 tgt=get_header(cwd/ *j/fn);
226 includes.insert(TargetMap::value_type(id, tgt));
232 Tries to locate a library with the given library path. Considers known targets
233 as well as existing files. If a matching target is not found but a file exists,
234 a new SystemLibrary target will be created and returned.
236 @param lib Name of the library to get (without "lib" prefix or extension)
237 @param path List of paths to search for the library
238 @param mode Shared / static mode
240 @return Some kind of library target, if a match was found
242 Target *Builder::get_library(const string &lib, const string &arch, const list<string> &path, LibMode mode)
245 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
246 update_hash(hash, *i);
248 //XXX Incorporate mode into id
250 TargetMap::iterator i=libraries.find(id);
251 if(i!=libraries.end())
257 syspath.push_back("/lib");
258 syspath.push_back("/usr/lib");
261 syspath.push_back("/usr/"+get_arch_prefix(arch)+"/lib");
264 for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
265 tgt=get_library(lib, arch, *j, mode);
266 for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
267 tgt=get_library(lib, arch, cwd/ *j, mode);
269 libraries.insert(TargetMap::value_type(id, tgt));
274 const string &Builder::get_arch_prefix(const string &arch) const
276 StringMap::const_iterator i=archs.find(arch);
278 throw InvalidParameterValue("Unknown architecture");
283 string Builder::get_tool(const std::string &tool, const std::string &arch)
285 ToolMap::iterator i=tools.find(arch);
288 StringMap::iterator j=i->second.find(tool);
289 if(j!=i->second.end())
293 // Either the arch, or the tool within the arch was not found
294 i=tools.find("native");
295 StringMap::iterator j=i->second.find(tool);
296 if(j==i->second.end())
297 throw InvalidParameterValue("Unknown tool");
299 return get_arch_prefix(arch)+"-"+j->second;
302 void Builder::apply_profile_template(Config &config, const string &pt) const
304 vector<string> parts=split(pt, '-');
306 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
308 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
309 if(j==profile_tmpl.end())
312 config.update(j->second);
317 Adds a target to both the target map and the new target queue. Called from
320 void Builder::add_target(Target *t)
322 targets.insert(TargetMap::value_type(t->get_name(), t));
323 new_tgts.push_back(t);
328 if(load_build_file(cwd/build_file))
330 cerr<<"No build info here.\n";
334 while(!new_pkgs.empty())
336 Package *pkg=new_pkgs.front();
337 new_pkgs.erase(new_pkgs.begin());
341 default_pkg->configure(cmdline_options, conf_all?2:1);
345 usage(0, "builder", false);
352 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
354 SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second);
358 else if(spkg && spkg->get_arch()!=default_pkg->get_arch())
359 prob="wrong architecture ("+spkg->get_arch()+")";
361 problems.insert(StringMap::value_type(i->first, prob));
364 if(!problems.empty())
366 cerr<<"The following problems were detected:\n";
367 for(StringMap::iterator i=problems.begin(); i!=problems.end(); ++i)
368 cerr<<" "<<i->first<<": "<<i->second<<'\n';
369 cerr<<"Please fix them and try again.\n";
379 cout<<packages.size()<<" packages, "<<targets.size()<<" targets\n";
382 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
384 cout<<' '<<i->second->get_name();
385 if(dynamic_cast<SourcePackage *>(i->second))
388 unsigned ood_count=0;
389 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
390 if(j->second->get_package()==i->second)
393 if(j->second->get_rebuild())
398 cout<<" ("<<count<<" targets";
400 cout<<", "<<ood_count<<" out-of-date";
413 exit_code=do_clean();
415 exit_code=do_build();
422 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
424 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
429 void Builder::usage(const char *reason, const char *argv0, bool brief)
435 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> ...]";
439 "Usage: "<<argv0<<" [options] [<target> ...]\n"
442 " -a, --analyze MODE Perform analysis. MODE can be deps, alldeps or rebuild.\n"
443 " -b, --build Perform build even if doing analysis.\n"
444 " -c, --clean Clean buildable targets.\n"
445 " -f, --file FILE Read info from FILE instead of Build.\n"
446 " -h, --help Print this message.\n"
447 " -j, --jobs NUM Run NUM commands at once, whenever possible.\n"
448 " -n, --dry-run Don't actually do anything, only show what would be done.\n"
449 " -v, --verbose Print more information about what's going on.\n"
450 " -A, --conf-all Apply configuration to all packages.\n"
451 " -B, --build-all Build all targets unconditionally.\n"
452 " -C, --chdir DIR Change to DIR before doing anything else.\n"
453 " -W, --what-if FILE Pretend that FILE has changed.\n"
454 " --chrome Use extra chrome to print status.\n"
455 " --conf-only Stop after configuring packages.\n"
456 " --full-paths Output full paths in analysis.\n"
457 //" --makefile Create a makefile for this package.\n"
458 " --max-depth NUM Maximum depth to show in analysis.\n";
463 Loads the given build file.
465 @param fn Path to the file
467 @return 0 on success, -1 if the file could not be opened
469 int Builder::load_build_file(const Path::Path &fn)
471 ifstream in(fn.str().c_str());
476 cout<<"Reading "<<fn<<'\n';
478 DataFile::Parser parser(in, fn.str());
479 Loader loader(*this, fn.subpath(0, fn.size()-1));
486 Creates targets for all packages and prepares them for building.
488 @return 0 if everything went ok, -1 if something bad happened and a build
489 shouldn't be attempted
491 int Builder::create_targets()
493 Target *world=new VirtualTarget(*this, "world");
495 Target *def_tgt=new VirtualTarget(*this, "default");
496 world->add_depend(def_tgt);
498 Target *install=new VirtualTarget(*this, "install");
499 world->add_depend(install);
501 Target *tarballs=new VirtualTarget(*this, "tarballs");
502 world->add_depend(tarballs);
504 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
506 SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second);
510 const ComponentList &components=spkg->get_components();
511 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
514 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
516 PkgConfig *pc=new PkgConfig(*this, *spkg);
517 install->add_depend(new Install(*this, *spkg, *pc));
520 tarballs->add_depend(new TarBall(*this, *spkg));
523 // Find dependencies until no new targets are created
524 while(!new_tgts.empty())
526 Target *tgt=new_tgts.front();
527 new_tgts.erase(new_tgts.begin());
529 if(!tgt->get_depends_ready())
530 new_tgts.push_back(tgt);
534 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
536 Target *tgt=get_target((cwd/ *i).str());
539 cerr<<"Unknown what-if target "<<*i<<'\n';
545 // Make the cmdline target depend on all targets mentioned on the command line
546 Target *cmdline=new VirtualTarget(*this, "cmdline");
547 bool build_world=false;
548 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
550 Target *tgt=get_target(*i);
552 tgt=get_target((cwd/ *i).str());
555 cerr<<"I don't know anything about "<<*i<<'\n';
560 cmdline->add_depend(tgt);
563 /* If world is to be built, prepare cmdline. If not, add cmdline to world
564 and prepare world. I don't really like this, but it keeps the graph
570 world->add_depend(cmdline);
574 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
575 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
576 spkg->get_deps_cache().save();
582 Check if a header exists, either as a target or a file. Either an existing
583 target or a new SystemHeader target will be returned.
585 Target *Builder::get_header(const Msp::Path::Path &fn)
587 Target *tgt=get_target(fn.str());
592 tgt=new SystemHeader(*this, fn.str());
598 Target *Builder::get_library(const string &lib, const string &arch, const Path::Path &path, LibMode mode)
600 // Populate a list of candidate filenames
601 StringList candidates;
606 candidates.push_back("lib"+lib+".dll");
608 candidates.push_back("lib"+lib+".so");
611 /* Static libraries are always considered, since sometimes shared versions
612 may not be available */
613 candidates.push_back("lib"+lib+".a");
615 candidates.push_back("lib"+lib+".dll.a");
617 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
619 string full=(path/ *i).str();
620 Target *tgt=get_target(full);
624 Target *real_tgt=tgt;
625 if(dynamic_cast<Install *>(tgt))
626 real_tgt=real_tgt->get_depends().front();
628 /* Ignore dynamic libraries from local packages unless library mode is
630 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
635 else if(Path::exists(full))
637 tgt=new SystemLibrary(*this, full);
646 Updates a hash with a string. This is used from get_header and get_library.
648 void Builder::update_hash(string &hash, const string &value)
650 for(unsigned i=0; i<value.size(); ++i)
651 hash[i%hash.size()]^=value[i];
655 This function supervises the build process, starting new actions when slots
658 int Builder::do_build()
660 Target *cmdline=get_target("cmdline");
662 unsigned total=cmdline->count_rebuild();
665 cout<<"Already up to date\n";
668 cout<<"Will build "<<total<<" target(s)\n";
670 vector<Action *> actions;
673 cout<<"0 targets built\n";
681 if(actions.size()<jobs && !fail)
683 Target *tgt=cmdline->get_buildable_target();
686 Action *action=tgt->build();
688 actions.push_back(action);
690 else if(actions.empty())
694 Time::sleep(10*Time::msec);
696 for(unsigned i=0; i<actions.size();)
698 int status=actions[i]->check();
704 cout<<"\e["<<actions.size()+1<<'A';
705 cout<<count<<" targets built\n";
709 if(i<actions.size()-1)
710 cout<<"\e["<<actions.size()-i-1<<"B";
714 actions.erase(actions.begin()+i);
717 if(actions.empty() && fail)
726 cout<<"Build failed\n";
732 Cleans buildable targets. If clean is 1, cleans only this package. If
733 clean is 2 or greater, cleans all buildable packages.
735 int Builder::do_clean()
737 // Cleaning doesn't care about ordering, so a simpler method can be used
739 set<Target *> clean_tgts;
741 queue.push_back(get_target("cmdline"));
743 while(!queue.empty())
745 Target *tgt=queue.front();
746 queue.erase(queue.begin());
748 if(tgt->get_buildable() && (tgt->get_package()==default_pkg || clean>=2))
749 clean_tgts.insert(tgt);
751 const TargetList &deps=tgt->get_depends();
752 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
753 if(!clean_tgts.count(*i))
757 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
759 Action *action=new Unlink(*this, **i);
760 while(action->check()<0);
768 Prints out information about the default package.
770 void Builder::package_help()
772 const Config &config=default_pkg->get_config();
773 const Config::OptionMap &options=config.get_options();
775 cout<<"Required packages:\n ";
776 const PkgRefList &requires=default_pkg->get_requires();
777 for(PkgRefList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
779 if(i!=requires.begin())
784 cout<<"Package configuration:\n";
785 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
787 const Config::Option &opt=i->second;
788 cout<<" "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
792 Application::RegApp<Builder> Builder::reg;
795 Builder::Loader::Loader(Builder &b, const Path::Path &s):
799 add("architecture", &Loader::architecture);
800 add("binary_package", &Loader::binpkg);
801 add("profile", &Loader::profile);
802 add("package", &Loader::package);
805 void Builder::Loader::architecture(const string &a, const string &p)
807 bld.archs.insert(StringMap::value_type(a, p));
810 void Builder::Loader::binpkg(const string &n)
812 BinaryPackage *pkg=new BinaryPackage(bld, n);
814 bld.packages.insert(PackageMap::value_type(n, pkg));
815 bld.new_pkgs.push_back(pkg);
818 void Builder::Loader::profile(const string &n)
821 load_sub<ProfileLoader>(prf);
822 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
825 void Builder::Loader::package(const string &n)
827 SourcePackage *pkg=new SourcePackage(bld, n, src);
829 bld.packages.insert(PackageMap::value_type(n, pkg));
830 bld.new_pkgs.push_back(pkg);
836 Builder::ProfileLoader::ProfileLoader(StringMap &p):
839 add("option", &ProfileLoader::option);
842 void Builder::ProfileLoader::option(const string &o, const string &v)
844 profile.insert(StringMap::value_type(o, v));