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/fs/dir.h>
14 #include <msp/fs/stat.h>
15 #include <msp/fs/utils.h>
16 #include <msp/io/buffered.h>
17 #include <msp/io/except.h>
18 #include <msp/io/file.h>
19 #include <msp/strings/formatter.h>
20 #include <msp/strings/regex.h>
21 #include <msp/strings/utils.h>
22 #include <msp/time/units.h>
23 #include <msp/time/utils.h>
26 #include "binarypackage.h"
32 #include "pkgconfig.h"
33 #include "sharedlibrary.h"
34 #include "sourcepackage.h"
35 #include "systemlibrary.h"
38 #include "virtualtarget.h"
43 Builder::Builder(int argc, char **argv):
57 create_makefile(false),
58 current_arch("native")
62 bool full_paths=false;
64 StringList cmdline_warn;
68 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG);
69 getopt.add_option('b', "build", build, GetOpt::NO_ARG);
70 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG);
71 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG);
72 getopt.add_option('h', "help", help, GetOpt::NO_ARG);
73 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG);
74 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG);
75 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG);
76 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG);
77 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG);
78 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG);
79 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG);
80 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG);
81 getopt.add_option( "arch", current_arch, GetOpt::REQUIRED_ARG);
82 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG);
83 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG);
84 //getopt.add_option( "makefile", create_makefile, GetOpt::NO_ARG);
85 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG);
86 getopt.add_option( "prefix", prfx, GetOpt::REQUIRED_ARG);
87 getopt.add_option( "warnings", cmdline_warn, GetOpt::REQUIRED_ARG);
90 if(!analyze_mode.empty())
92 analyzer=new Analyzer(*this);
94 if(analyze_mode=="deps")
95 analyzer->set_mode(Analyzer::DEPS);
96 else if(analyze_mode=="alldeps")
97 analyzer->set_mode(Analyzer::ALLDEPS);
98 else if(analyze_mode=="rebuild")
99 analyzer->set_mode(Analyzer::REBUILD);
100 else if(analyze_mode=="rdeps")
101 analyzer->set_mode(Analyzer::RDEPS);
103 throw UsageError("Invalid analyze mode");
105 analyzer->set_max_depth(max_depth);
106 analyzer->set_full_paths(full_paths);
108 else if(!clean && !create_makefile)
111 const vector<string> &args=getopt.get_args();
112 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
114 unsigned equal=i->find('=');
115 if(equal!=string::npos)
116 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
118 cmdline_targets.push_back(*i);
121 if(cmdline_targets.empty())
122 cmdline_targets.push_back("default");
124 if(!work_dir.empty())
125 chdir(work_dir.c_str());
129 Architecture &native_arch=archs.insert(ArchMap::value_type("native", Architecture(*this, "native"))).first->second;
130 native_arch.set_tool("CC", "gcc");
131 native_arch.set_tool("CXX", "g++");
132 native_arch.set_tool("LD", "gcc");
133 native_arch.set_tool("LXX", "g++");
134 native_arch.set_tool("AR", "ar");
136 load_build_file((FS::get_home_dir()/".builderrc").str());
140 if(current_arch=="native")
141 prefix=(FS::get_home_dir()/"local").str();
143 prefix=(FS::get_home_dir()/"local"/current_arch).str();
148 warnings.push_back("all");
149 warnings.push_back("extra");
150 warnings.push_back("shadow");
151 warnings.push_back("pointer-arith");
152 warnings.push_back("error");
153 for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
155 vector<string> warns=split(*i, ',');
156 warnings.insert(warnings.end(), warns.begin(), warns.end());
161 Gets a package by name, possibly creating it.
163 @param name Package name
165 @return Pointer to the package, or 0 if the package could not be located
167 Package *Builder::get_package(const string &name)
169 PackageMap::iterator i=packages.find(format("%s/%s", name, current_arch));
170 if(i==packages.end())
171 i=packages.find(name);
172 if(i!=packages.end())
175 // Try to get source directory with pkgconfig
177 argv.push_back("pkg-config");
178 argv.push_back("--variable=source");
179 argv.push_back(name);
181 cout<<"Running "<<join(argv.begin(), argv.end())<<'\n';
182 string srcdir=strip(run_command(argv));
186 dirs.push_back(srcdir);
188 // Make some other guesses about the source directory
189 dirs.push_back(cwd/name);
190 dirs.push_back(cwd/".."/name);
191 if(!name.compare(0, 3, "msp"))
193 dirs.push_back(cwd/name.substr(3));
194 dirs.push_back(cwd/".."/name.substr(3));
197 // Go through the candidate directories and look for a Build file
198 for(PathList::iterator j=dirs.begin(); j!=dirs.end(); ++j)
199 if(!load_build_file(*j/"Build"))
201 i=packages.find(name);
202 if(i!=packages.end())
207 // Package source not found - create a binary package
208 Package *pkg=BinaryPackage::from_pkgconfig(*this, name);
210 packages.insert(PackageMap::value_type(name, pkg));
213 problem(name, "not found");
219 Returns the target with the given name, or 0 if no such target exists.
221 Target *Builder::get_target(const string &n) const
223 TargetMap::const_iterator i=targets.find(n);
230 Tries to locate a header included from a given location and with a given include
231 path. Considers known targets as well as existing files. If a matching target
232 is not found but a file exists, a new SystemHeader target will be created and
235 Target *Builder::get_header(const string &include, const string &from, const list<string> &path)
238 update_hash(hash, from);
239 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
240 update_hash(hash, *i);
242 string id=hash+include;
243 TargetMap::iterator i=includes.find(id);
244 if(i!=includes.end())
247 static string cxx_ver;
251 argv.push_back(get_current_arch().get_tool("CXX"));
252 argv.push_back("--version");
253 cxx_ver=Regex("[0-9]\\.[0-9.]+").match(run_command(argv))[0].str;
254 while(!cxx_ver.empty() && !FS::is_dir(FS::Path("/usr/include/c++")/cxx_ver))
256 unsigned dot=cxx_ver.rfind('.');
257 if(dot==string::npos)
262 cout<<"C++ version is "<<cxx_ver<<'\n';
265 string fn=include.substr(1);
267 cout<<"Looking for include "<<fn<<" with path "<<join(path.begin(), path.end())<<'\n';
270 if(current_arch=="native")
271 syspath.push_back("/usr/include");
273 syspath.push_back("/usr/"+get_architecture(current_arch).get_prefix()+"/include");
274 syspath.push_back((FS::Path("/usr/include/c++/")/cxx_ver/fn).str());
278 tgt=get_header(FS::Path(from)/fn);
279 for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
280 tgt=get_header(cwd/ *j/fn);
281 for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
282 tgt=get_header(FS::Path(*j)/fn);
284 includes.insert(TargetMap::value_type(id, tgt));
290 Tries to locate a library with the given library path. Considers known targets
291 as well as existing files. If a matching target is not found but a file exists,
292 a new SystemLibrary target will be created and returned.
294 @param lib Name of the library to get (without "lib" prefix or extension)
295 @param path List of paths to search for the library
296 @param mode Shared / static mode
298 @return Some kind of library target, if a match was found
300 Target *Builder::get_library(const string &lib, const list<string> &path, LibMode mode)
303 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
304 update_hash(hash, *i);
306 string id=hash+string(1, mode)+lib;
307 TargetMap::iterator i=libraries.find(id);
308 if(i!=libraries.end())
312 if(current_arch=="native")
314 syspath.push_back("/lib");
315 syspath.push_back("/usr/lib");
318 syspath.push_back("/usr/"+get_current_arch().get_prefix()+"/lib");
321 cout<<"Looking for library "<<lib<<" with path "<<join(path.begin(), path.end())<<'\n';
324 for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
325 tgt=get_library(lib, cwd/ *j, mode);
326 for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
327 tgt=get_library(lib, *j, mode);
329 libraries.insert(TargetMap::value_type(id, tgt));
334 const Architecture &Builder::get_architecture(const string &arch) const
336 ArchMap::const_iterator i=archs.find(arch);
338 throw KeyError("Unknown architecture", arch);
343 const Architecture &Builder::get_current_arch() const
345 return get_architecture(current_arch);
348 void Builder::apply_profile_template(Config &config, const string &pt) const
350 vector<string> parts=split(pt, '-');
352 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
354 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
355 if(j==profile_tmpl.end())
358 config.update(j->second);
362 void Builder::problem(const string &p, const string &d)
364 problems.push_back(Problem(p, d));
368 Adds a target to both the target map and the new target queue. Called from
371 void Builder::add_target(Target *t)
373 targets.insert(TargetMap::value_type(t->get_name(), t));
374 new_tgts.push_back(t);
379 if(load_build_file(cwd/build_file))
381 cerr<<"No build info here.\n";
385 main_pkg->configure(cmdline_options, conf_all?2:1);
389 usage(0, "builder", false);
395 if(!conf_only && create_targets())
398 PackageList all_reqs=main_pkg->collect_requires();
403 cout<<all_reqs.size()<<" active packages, "<<targets.size()<<" targets\n";
406 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
408 cout<<' '<<(*i)->get_name();
409 if(dynamic_cast<SourcePackage *>(*i))
412 unsigned ood_count=0;
413 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
414 if(j->second->get_package()==*i)
417 if(j->second->get_rebuild())
422 cout<<" ("<<count<<" targets";
424 cout<<", "<<ood_count<<" out-of-date";
434 if(!problems.empty())
436 cerr<<"The following problems were detected:\n";
437 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
438 cerr<<" "<<i->package<<": "<<i->descr<<'\n';
439 cerr<<"Please fix them and try again.\n";
446 exit_code=do_clean();
448 exit_code=do_build();
455 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
457 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
462 void Builder::usage(const char *reason, const char *argv0, bool brief)
468 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";
472 "Usage: "<<argv0<<" [options] [<target> ...]\n"
475 " -a, --analyze MODE Perform analysis. MODE can be deps, alldeps or rebuild.\n"
476 " -b, --build Perform build even if doing analysis.\n"
477 " -c, --clean Clean buildable targets.\n"
478 " -f, --file FILE Read info from FILE instead of Build.\n"
479 " -h, --help Print this message.\n"
480 " -j, --jobs NUM Run NUM commands at once, whenever possible.\n"
481 " -n, --dry-run Don't actually do anything, only show what would be done.\n"
482 " -v, --verbose Print more information about what's going on.\n"
483 " -A, --conf-all Apply configuration to all packages.\n"
484 " -B, --build-all Build all targets unconditionally.\n"
485 " -C, --chdir DIR Change to DIR before doing anything else.\n"
486 " -P, --progress Display progress while building.\n"
487 " -W, --what-if FILE Pretend that FILE has changed.\n"
488 " --arch ARCH Architecture to build for.\n"
489 " --conf-only Stop after configuring packages.\n"
490 " --full-paths Output full paths in analysis.\n"
491 //" --makefile Create a makefile for this package.\n"
492 " --max-depth NUM Maximum depth to show in analysis.\n"
493 " --prefix DIR Directory to install things to.\n"
494 " --warnings LIST Compiler warnings to use.\n";
499 Loads the given build file.
501 @param fn Path to the file
503 @return 0 on success, -1 if the file could not be opened
505 int Builder::load_build_file(const FS::Path &fn)
509 IO::File inf(fn.str());
510 IO::Buffered in(inf);
513 cout<<"Reading "<<fn<<'\n';
515 DataFile::Parser parser(in, fn.str());
516 Loader loader(*this, fn.subpath(0, fn.size()-1));
519 catch(const IO::FileNotFound &)
528 Creates targets for all packages and prepares them for building.
530 @return 0 if everything went ok, -1 if something bad happened and a build
531 shouldn't be attempted
533 int Builder::create_targets()
535 Target *world=new VirtualTarget(*this, "world");
537 Target *def_tgt=new VirtualTarget(*this, "default");
538 world->add_depend(def_tgt);
540 Target *install=new VirtualTarget(*this, "install");
541 world->add_depend(install);
543 Target *tarballs=new VirtualTarget(*this, "tarballs");
544 world->add_depend(tarballs);
546 PackageList all_reqs=main_pkg->collect_requires();
547 for(PackageList::iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
549 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
553 const ComponentList &components=spkg->get_components();
554 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
557 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
559 PkgConfig *pc=new PkgConfig(*this, *spkg);
560 install->add_depend(new Install(*this, *spkg, *pc));
563 tarballs->add_depend(new TarBall(*this, *spkg));
566 // Find dependencies until no new targets are created
567 while(!new_tgts.empty())
569 Target *tgt=new_tgts.front();
570 new_tgts.erase(new_tgts.begin());
572 if(!tgt->get_depends_ready())
573 new_tgts.push_back(tgt);
577 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
579 Target *tgt=get_target((cwd/ *i).str());
582 cerr<<"Unknown what-if target "<<*i<<'\n';
588 // Make the cmdline target depend on all targets mentioned on the command line
589 Target *cmdline=new VirtualTarget(*this, "cmdline");
590 bool build_world=false;
591 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
593 Target *tgt=get_target(*i);
595 tgt=get_target((cwd/ *i).str());
598 cerr<<"I don't know anything about "<<*i<<'\n';
603 cmdline->add_depend(tgt);
606 /* If world is to be built, prepare cmdline. If not, add cmdline to world
607 and prepare world. I don't really like this, but it keeps the graph
613 world->add_depend(cmdline);
617 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
618 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
619 spkg->get_deps_cache().save();
625 Check if a header exists, either as a target or a file. Either an existing
626 target or a new SystemHeader target will be returned.
628 Target *Builder::get_header(const Msp::FS::Path &fn)
630 Target *tgt=get_target(fn.str());
635 tgt=new SystemHeader(*this, fn.str());
641 Target *Builder::get_library(const string &lib, const FS::Path &path, LibMode mode)
643 // Populate a list of candidate filenames
644 StringList candidates;
648 if(current_arch=="win32")
650 candidates.push_back("lib"+lib+".dll");
651 candidates.push_back(lib+".dll");
654 candidates.push_back("lib"+lib+".so");
657 /* Static libraries are always considered, since sometimes shared versions
658 may not be available */
659 candidates.push_back("lib"+lib+".a");
660 if(current_arch=="win32")
661 candidates.push_back("lib"+lib+".dll.a");
663 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
665 string full=(path/ *i).str();
666 Target *tgt=get_target(full);
670 Target *real_tgt=tgt;
671 if(dynamic_cast<Install *>(tgt))
672 real_tgt=real_tgt->get_depends().front();
674 /* Ignore dynamic libraries from local packages unless library mode is
676 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
681 else if(FS::is_reg(full))
683 tgt=new SystemLibrary(*this, full);
692 Updates a hash with a string. This is used from get_header and get_library.
694 void Builder::update_hash(string &hash, const string &value)
696 for(unsigned i=0; i<value.size(); ++i)
697 hash[i%hash.size()]^=value[i];
701 This function supervises the build process, starting new actions when slots
704 int Builder::do_build()
706 Target *cmdline=get_target("cmdline");
708 unsigned total=cmdline->count_rebuild();
711 cout<<"Already up to date\n";
714 cout<<"Will build "<<total<<" target(s)\n";
716 vector<Action *> actions;
725 if(actions.size()<jobs && !fail)
727 Target *tgt=cmdline->get_buildable_target();
730 Action *action=tgt->build();
732 actions.push_back(action);
736 cout<<count<<" of "<<total<<" targets built\033[1G";
740 else if(actions.empty())
744 Time::sleep(10*Time::msec);
746 for(unsigned i=0; i<actions.size();)
748 int status=actions[i]->check();
754 actions.erase(actions.begin()+i);
757 if(actions.empty() && fail)
768 cout<<"Build failed\n";
769 else if(show_progress)
770 cout<<"Build complete\n";
776 Cleans buildable targets. If clean is 1, cleans only this package. If
777 clean is 2 or greater, cleans all buildable packages.
779 int Builder::do_clean()
781 // Cleaning doesn't care about ordering, so a simpler method can be used
783 set<Target *> clean_tgts;
785 queue.push_back(get_target("cmdline"));
787 while(!queue.empty())
789 Target *tgt=queue.front();
790 queue.erase(queue.begin());
792 if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
793 clean_tgts.insert(tgt);
795 const TargetList &deps=tgt->get_depends();
796 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
797 if(!clean_tgts.count(*i))
801 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
803 Action *action=new Unlink(*this, **i);
804 while(action->check()<0) ;
812 Prints out information about the default package.
814 void Builder::package_help()
816 const Config &config=main_pkg->get_config();
817 const Config::OptionMap &options=config.get_options();
819 cout<<"Required packages:\n ";
820 const PackageList &requires=main_pkg->get_requires();
821 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
823 if(i!=requires.begin())
825 cout<<(*i)->get_name();
828 cout<<"Package configuration:\n";
829 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
831 const Config::Option &opt=i->second;
832 cout<<" "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
836 Application::RegApp<Builder> Builder::reg;
839 Builder::Loader::Loader(Builder &b, const FS::Path &s):
843 add("architecture", &Loader::architecture);
844 add("binary_package", &Loader::binpkg);
845 add("profile", &Loader::profile);
846 add("package", &Loader::package);
849 void Builder::Loader::architecture(const string &n)
851 Architecture arch(bld, n);
853 bld.archs.insert(ArchMap::value_type(n, arch));
856 void Builder::Loader::binpkg(const string &n)
858 BinaryPackage *pkg=new BinaryPackage(bld, n);
860 bld.packages.insert(PackageMap::value_type(n, pkg));
863 void Builder::Loader::profile(const string &n)
866 ProfileLoader ldr(prf);
868 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
871 void Builder::Loader::package(const string &n)
873 SourcePackage *pkg=new SourcePackage(bld, n, src);
878 bld.packages.insert(PackageMap::value_type(n, pkg));
882 Builder::ProfileLoader::ProfileLoader(StringMap &p):
885 add("option", &ProfileLoader::option);
888 void Builder::ProfileLoader::option(const string &o, const string &v)
890 profile.insert(StringMap::value_type(o, v));