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('P', "progress", show_progress, GetOpt::NO_ARG);
72 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_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 vector<string> &args=getopt.get_args();
101 for(vector<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 Architecture &native_arch=archs.insert(ArchMap::value_type("native", Architecture(*this, "native"))).first->second;
119 native_arch.set_tool("CC", "gcc");
120 native_arch.set_tool("CXX", "g++");
121 native_arch.set_tool("LD", "gcc");
122 native_arch.set_tool("LXX", "g++");
123 native_arch.set_tool("AR", "ar");
125 const char *home=getenv("HOME");
127 load_build_file((Path(home)/".builderrc").str());
131 Gets a package with the specified name, possibly creating it.
133 @param n Package name
135 @return Pointer to the package, or 0 if the package could not be located
137 Package *Builder::get_package(const string &n)
139 PackageMap::iterator i=packages.find(n);
140 if(i!=packages.end())
143 // Try to get source directory with pkgconfig
145 argv.push_back("pkg-config");
146 argv.push_back("--variable=source");
149 cout<<"Running "<<join(argv.begin(), argv.end())<<'\n';
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(from)/fn)))
217 else if((tgt=get_header(Path("/usr/include")/fn)))
219 //XXX Determine the C++ header location dynamically
220 else if((tgt=get_header(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_architecture(arch).get_prefix()+"/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 Architecture &Builder::get_architecture(const string &arch) const
278 ArchMap::const_iterator i=archs.find(arch);
280 throw InvalidParameterValue("Unknown architecture");
285 void Builder::apply_profile_template(Config &config, const string &pt) const
287 vector<string> parts=split(pt, '-');
289 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
291 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
292 if(j==profile_tmpl.end())
295 config.update(j->second);
299 void Builder::problem(const string &p, const string &d)
301 problems.push_back(Problem(p, d));
305 Adds a target to both the target map and the new target queue. Called from
308 void Builder::add_target(Target *t)
310 targets.insert(TargetMap::value_type(t->get_name(), t));
311 new_tgts.push_back(t);
316 if(load_build_file(cwd/build_file))
318 cerr<<"No build info here.\n";
322 main_pkg->configure(cmdline_options, conf_all?2:1);
326 usage(0, "builder", false);
332 if(!conf_only && create_targets())
335 PackageList all_reqs=main_pkg->collect_requires();
337 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
339 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
341 if(spkg && spkg->get_arch()!=main_pkg->get_arch())
342 problem(spkg->get_name(), format("wrong architecture (%s)", spkg->get_arch()));
345 if(!problems.empty())
347 cerr<<"The following problems were detected:\n";
348 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
349 cerr<<" "<<i->package<<": "<<i->descr<<'\n';
350 cerr<<"Please fix them and try again.\n";
357 cout<<all_reqs.size()<<" active packages, "<<targets.size()<<" targets\n";
360 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
362 cout<<' '<<(*i)->get_name();
363 if(dynamic_cast<SourcePackage *>(*i))
366 unsigned ood_count=0;
367 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
368 if(j->second->get_package()==*i)
371 if(j->second->get_rebuild())
376 cout<<" ("<<count<<" targets";
378 cout<<", "<<ood_count<<" out-of-date";
391 exit_code=do_clean();
393 exit_code=do_build();
400 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
402 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
407 void Builder::usage(const char *reason, const char *argv0, bool brief)
413 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> ...]";
417 "Usage: "<<argv0<<" [options] [<target> ...]\n"
420 " -a, --analyze MODE Perform analysis. MODE can be deps, alldeps or rebuild.\n"
421 " -b, --build Perform build even if doing analysis.\n"
422 " -c, --clean Clean buildable targets.\n"
423 " -f, --file FILE Read info from FILE instead of Build.\n"
424 " -h, --help Print this message.\n"
425 " -j, --jobs NUM Run NUM commands at once, whenever possible.\n"
426 " -n, --dry-run Don't actually do anything, only show what would be done.\n"
427 " -v, --verbose Print more information about what's going on.\n"
428 " -A, --conf-all Apply configuration to all packages.\n"
429 " -B, --build-all Build all targets unconditionally.\n"
430 " -C, --chdir DIR Change to DIR before doing anything else.\n"
431 " -P, --progress Display progress while building.\n"
432 " -W, --what-if FILE Pretend that FILE has changed.\n"
433 " --conf-only Stop after configuring packages.\n"
434 " --full-paths Output full paths in analysis.\n"
435 //" --makefile Create a makefile for this package.\n"
436 " --max-depth NUM Maximum depth to show in analysis.\n";
441 Loads the given build file.
443 @param fn Path to the file
445 @return 0 on success, -1 if the file could not be opened
447 int Builder::load_build_file(const Path &fn)
449 ifstream in(fn.str().c_str());
454 cout<<"Reading "<<fn<<'\n';
456 DataFile::Parser parser(in, fn.str());
457 Loader loader(*this, fn.subpath(0, fn.size()-1));
464 Creates targets for all packages and prepares them for building.
466 @return 0 if everything went ok, -1 if something bad happened and a build
467 shouldn't be attempted
469 int Builder::create_targets()
471 Target *world=new VirtualTarget(*this, "world");
473 Target *def_tgt=new VirtualTarget(*this, "default");
474 world->add_depend(def_tgt);
476 Target *install=new VirtualTarget(*this, "install");
477 world->add_depend(install);
479 Target *tarballs=new VirtualTarget(*this, "tarballs");
480 world->add_depend(tarballs);
482 PackageList all_reqs=main_pkg->collect_requires();
483 for(PackageList::iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
485 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
489 const ComponentList &components=spkg->get_components();
490 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
493 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
495 PkgConfig *pc=new PkgConfig(*this, *spkg);
496 install->add_depend(new Install(*this, *spkg, *pc));
499 tarballs->add_depend(new TarBall(*this, *spkg));
502 // Find dependencies until no new targets are created
503 while(!new_tgts.empty())
505 Target *tgt=new_tgts.front();
506 new_tgts.erase(new_tgts.begin());
508 if(!tgt->get_depends_ready())
509 new_tgts.push_back(tgt);
513 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
515 Target *tgt=get_target((cwd/ *i).str());
518 cerr<<"Unknown what-if target "<<*i<<'\n';
524 // Make the cmdline target depend on all targets mentioned on the command line
525 Target *cmdline=new VirtualTarget(*this, "cmdline");
526 bool build_world=false;
527 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
529 Target *tgt=get_target(*i);
531 tgt=get_target((cwd/ *i).str());
534 cerr<<"I don't know anything about "<<*i<<'\n';
539 cmdline->add_depend(tgt);
542 /* If world is to be built, prepare cmdline. If not, add cmdline to world
543 and prepare world. I don't really like this, but it keeps the graph
549 world->add_depend(cmdline);
553 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
554 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
555 spkg->get_deps_cache().save();
561 Check if a header exists, either as a target or a file. Either an existing
562 target or a new SystemHeader target will be returned.
564 Target *Builder::get_header(const Msp::Path &fn)
566 Target *tgt=get_target(fn.str());
571 tgt=new SystemHeader(*this, fn.str());
577 Target *Builder::get_library(const string &lib, const string &arch, const Path &path, LibMode mode)
579 // Populate a list of candidate filenames
580 StringList candidates;
585 candidates.push_back("lib"+lib+".dll");
587 candidates.push_back("lib"+lib+".so");
590 /* Static libraries are always considered, since sometimes shared versions
591 may not be available */
592 candidates.push_back("lib"+lib+".a");
594 candidates.push_back("lib"+lib+".dll.a");
596 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
598 string full=(path/ *i).str();
599 Target *tgt=get_target(full);
603 Target *real_tgt=tgt;
604 if(dynamic_cast<Install *>(tgt))
605 real_tgt=real_tgt->get_depends().front();
607 /* Ignore dynamic libraries from local packages unless library mode is
609 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
614 else if(exists(full))
616 tgt=new SystemLibrary(*this, full);
625 Updates a hash with a string. This is used from get_header and get_library.
627 void Builder::update_hash(string &hash, const string &value)
629 for(unsigned i=0; i<value.size(); ++i)
630 hash[i%hash.size()]^=value[i];
634 This function supervises the build process, starting new actions when slots
637 int Builder::do_build()
639 Target *cmdline=get_target("cmdline");
641 unsigned total=cmdline->count_rebuild();
644 cout<<"Already up to date\n";
647 cout<<"Will build "<<total<<" target(s)\n";
649 vector<Action *> actions;
658 if(actions.size()<jobs && !fail)
660 Target *tgt=cmdline->get_buildable_target();
663 Action *action=tgt->build();
665 actions.push_back(action);
669 cout<<count<<" of "<<total<<" targets built\033[1G";
673 else if(actions.empty())
677 Time::sleep(10*Time::msec);
679 for(unsigned i=0; i<actions.size();)
681 int status=actions[i]->check();
687 actions.erase(actions.begin()+i);
690 if(actions.empty() && fail)
701 cout<<"Build failed\n";
702 else if(show_progress)
703 cout<<"Build complete\n";
709 Cleans buildable targets. If clean is 1, cleans only this package. If
710 clean is 2 or greater, cleans all buildable packages.
712 int Builder::do_clean()
714 // Cleaning doesn't care about ordering, so a simpler method can be used
716 set<Target *> clean_tgts;
718 queue.push_back(get_target("cmdline"));
720 while(!queue.empty())
722 Target *tgt=queue.front();
723 queue.erase(queue.begin());
725 if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
726 clean_tgts.insert(tgt);
728 const TargetList &deps=tgt->get_depends();
729 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
730 if(!clean_tgts.count(*i))
734 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
736 Action *action=new Unlink(*this, **i);
737 while(action->check()<0);
745 Prints out information about the default package.
747 void Builder::package_help()
749 const Config &config=main_pkg->get_config();
750 const Config::OptionMap &options=config.get_options();
752 cout<<"Required packages:\n ";
753 const PackageList &requires=main_pkg->get_requires();
754 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
756 if(i!=requires.begin())
758 cout<<(*i)->get_name();
761 cout<<"Package configuration:\n";
762 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
764 const Config::Option &opt=i->second;
765 cout<<" "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
769 Application::RegApp<Builder> Builder::reg;
772 Builder::Loader::Loader(Builder &b, const Path &s):
776 add("architecture", &Loader::architecture);
777 add("binary_package", &Loader::binpkg);
778 add("profile", &Loader::profile);
779 add("package", &Loader::package);
782 void Builder::Loader::architecture(const string &n)
784 Architecture arch(bld, n);
786 bld.archs.insert(ArchMap::value_type(n, arch));
789 void Builder::Loader::binpkg(const string &n)
791 BinaryPackage *pkg=new BinaryPackage(bld, n);
793 bld.packages.insert(PackageMap::value_type(n, pkg));
796 void Builder::Loader::profile(const string &n)
799 load_sub<ProfileLoader>(prf);
800 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
803 void Builder::Loader::package(const string &n)
805 SourcePackage *pkg=new SourcePackage(bld, n, src);
810 bld.packages.insert(PackageMap::value_type(n, pkg));
814 Builder::ProfileLoader::ProfileLoader(StringMap &p):
817 add("option", &ProfileLoader::option);
820 void Builder::ProfileLoader::option(const string &o, const string &v)
822 profile.insert(StringMap::value_type(o, v));