3 This file is part of builder
4 Copyright © 2006-2007 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
10 #include <sys/utsname.h>
11 #include <msp/core/except.h>
12 #include <msp/core/getopt.h>
13 #include <msp/datafile/parser.h>
14 #include <msp/fs/dir.h>
15 #include <msp/fs/stat.h>
16 #include <msp/fs/utils.h>
17 #include <msp/io/buffered.h>
18 #include <msp/io/except.h>
19 #include <msp/io/file.h>
20 #include <msp/strings/formatter.h>
21 #include <msp/strings/regex.h>
22 #include <msp/strings/utils.h>
23 #include <msp/time/units.h>
24 #include <msp/time/utils.h>
27 #include "binarypackage.h"
33 #include "pkgconfig.h"
34 #include "sharedlibrary.h"
35 #include "sourcepackage.h"
36 #include "systemlibrary.h"
39 #include "virtualtarget.h"
44 Builder::Builder(int argc, char **argv):
58 create_makefile(false)
62 bool full_paths=false;
64 StringList cmdline_warn;
69 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG);
70 getopt.add_option('b', "build", build, GetOpt::NO_ARG);
71 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG);
72 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG);
73 getopt.add_option('h', "help", help, GetOpt::NO_ARG);
74 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG);
75 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG);
76 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG);
77 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG);
78 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG);
79 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG);
80 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG);
81 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG);
82 getopt.add_option( "arch", arch, GetOpt::REQUIRED_ARG);
83 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG);
84 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG);
85 //getopt.add_option( "makefile", create_makefile, GetOpt::NO_ARG);
86 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG);
87 getopt.add_option( "prefix", prfx, GetOpt::REQUIRED_ARG);
88 getopt.add_option( "warnings", cmdline_warn, GetOpt::REQUIRED_ARG);
91 if(!analyze_mode.empty())
93 analyzer=new Analyzer(*this);
95 if(analyze_mode=="deps")
96 analyzer->set_mode(Analyzer::DEPS);
97 else if(analyze_mode=="alldeps")
98 analyzer->set_mode(Analyzer::ALLDEPS);
99 else if(analyze_mode=="rebuild")
100 analyzer->set_mode(Analyzer::REBUILD);
101 else if(analyze_mode=="rdeps")
102 analyzer->set_mode(Analyzer::RDEPS);
104 throw UsageError("Invalid analyze mode");
106 analyzer->set_max_depth(max_depth);
107 analyzer->set_full_paths(full_paths);
109 else if(!clean && !create_makefile)
112 const vector<string> &args=getopt.get_args();
113 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
115 unsigned equal=i->find('=');
116 if(equal!=string::npos)
117 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
119 cmdline_targets.push_back(*i);
122 if(cmdline_targets.empty())
123 cmdline_targets.push_back("default");
125 if(!work_dir.empty())
126 chdir(work_dir.c_str());
131 string sysname="native";
133 sysname=tolower(un.sysname);
135 native_arch=&archs.insert(ArchMap::value_type(sysname, Architecture(*this, sysname, true))).first->second;
136 native_arch->set_tool("CC", "gcc");
137 native_arch->set_tool("CXX", "g++");
138 native_arch->set_tool("LD", "gcc");
139 native_arch->set_tool("LXX", "g++");
140 native_arch->set_tool("AR", "ar");
142 load_build_file((FS::get_home_dir()/".builderrc").str());
145 current_arch=native_arch;
147 current_arch=&get_architecture(arch);
151 if(current_arch->is_native())
152 prefix=(FS::get_home_dir()/"local").str();
154 prefix=(FS::get_home_dir()/"local"/current_arch->get_name()).str();
157 prefix=FS::getcwd()/prfx;
159 warnings.push_back("all");
160 warnings.push_back("extra");
161 warnings.push_back("shadow");
162 warnings.push_back("pointer-arith");
163 warnings.push_back("error");
164 for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
166 vector<string> warns=split(*i, ',');
167 warnings.insert(warnings.end(), warns.begin(), warns.end());
170 pkg_path.push_back(cwd/".");
171 pkg_path.push_back(cwd/"..");
175 Gets a package by name, possibly creating it.
177 @param name Package name
179 @return Pointer to the package, or 0 if the package could not be located
181 Package *Builder::get_package(const string &name)
183 PackageMap::iterator i=packages.find(format("%s/%s", name, current_arch));
184 if(i==packages.end())
185 i=packages.find(name);
186 if(i!=packages.end())
189 FS::Path path=get_package_location(name);
190 if(!path.empty() && !load_build_file(path/"Build"))
192 i=packages.find(name);
193 if(i!=packages.end())
197 // Package source not found - create a binary package
198 Package *pkg=BinaryPackage::from_pkgconfig(*this, name);
200 packages.insert(PackageMap::value_type(name, pkg));
203 problem(name, "not found");
209 Returns the target with the given name, or 0 if no such target exists.
211 Target *Builder::get_target(const string &n) const
213 TargetMap::const_iterator i=targets.find(n);
220 Tries to locate a header included from a given location and with a given include
221 path. Considers known targets as well as existing files. If a matching target
222 is not found but a file exists, a new SystemHeader target will be created and
225 Target *Builder::get_header(const string &include, const string &from, const list<string> &path)
228 update_hash(hash, from);
229 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
230 update_hash(hash, *i);
232 string id=hash+include;
233 TargetMap::iterator i=includes.find(id);
234 if(i!=includes.end())
237 static string cxx_ver;
241 argv.push_back(get_current_arch().get_tool("CXX"));
242 argv.push_back("--version");
243 cxx_ver=Regex("[0-9]\\.[0-9.]+").match(run_command(argv))[0].str;
244 while(!cxx_ver.empty() && !FS::is_dir(FS::Path("/usr/include/c++")/cxx_ver))
246 unsigned dot=cxx_ver.rfind('.');
247 if(dot==string::npos)
252 cout<<"C++ version is "<<cxx_ver<<'\n';
255 string fn=include.substr(1);
257 cout<<"Looking for include "<<fn<<" with path "<<join(path.begin(), path.end())<<'\n';
260 if(current_arch->is_native())
261 syspath.push_back("/usr/include");
263 syspath.push_back("/usr/"+current_arch->get_prefix()+"/include");
264 syspath.push_back((FS::Path("/usr/include/c++/")/cxx_ver/fn).str());
268 tgt=get_header(FS::Path(from)/fn);
269 for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
270 tgt=get_header(cwd/ *j/fn);
271 for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
272 tgt=get_header(FS::Path(*j)/fn);
274 includes.insert(TargetMap::value_type(id, tgt));
280 Tries to locate a library with the given library path. Considers known targets
281 as well as existing files. If a matching target is not found but a file exists,
282 a new SystemLibrary target will be created and returned.
284 @param lib Name of the library to get (without "lib" prefix or extension)
285 @param path List of paths to search for the library
286 @param mode Shared / static mode
288 @return Some kind of library target, if a match was found
290 Target *Builder::get_library(const string &lib, const list<string> &path, LibMode mode)
293 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
294 update_hash(hash, *i);
296 string id=hash+string(1, mode)+lib;
297 TargetMap::iterator i=libraries.find(id);
298 if(i!=libraries.end())
302 if(current_arch->is_native())
304 syspath.push_back("/lib");
305 syspath.push_back("/usr/lib");
308 syspath.push_back("/usr/"+get_current_arch().get_prefix()+"/lib");
311 cout<<"Looking for library "<<lib<<" with path "<<join(path.begin(), path.end())<<'\n';
314 for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
315 tgt=get_library(lib, cwd/ *j, mode);
316 for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
317 tgt=get_library(lib, *j, mode);
319 libraries.insert(TargetMap::value_type(id, tgt));
324 const Architecture &Builder::get_architecture(const string &arch) const
326 ArchMap::const_iterator i=archs.find(arch);
328 throw KeyError("Unknown architecture", arch);
333 void Builder::apply_profile_template(Config &config, const string &pt) const
335 vector<string> parts=split(pt, '-');
337 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
339 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
340 if(j==profile_tmpl.end())
343 config.update(j->second);
347 void Builder::problem(const string &p, const string &d)
349 problems.push_back(Problem(p, d));
353 Adds a target to both the target map and the new target queue. Called from
356 void Builder::add_target(Target *t)
358 targets.insert(TargetMap::value_type(t->get_name(), t));
359 new_tgts.push_back(t);
364 if(load_build_file(cwd/build_file))
366 cerr<<"No build info here.\n";
370 main_pkg->configure(cmdline_options, conf_all?2:1);
374 usage(0, "builder", false);
380 if(!conf_only && create_targets())
383 PackageList all_reqs=main_pkg->collect_requires();
389 cout<<"Building on "<<native_arch->get_name()<<", for "<<current_arch->get_name()<<'\n';
391 cout<<all_reqs.size()<<" active packages, "<<targets.size()<<" targets\n";
394 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
396 cout<<' '<<(*i)->get_name();
397 if(dynamic_cast<SourcePackage *>(*i))
400 unsigned ood_count=0;
401 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
402 if(j->second->get_package()==*i)
405 if(j->second->get_rebuild())
410 cout<<" ("<<count<<" targets";
412 cout<<", "<<ood_count<<" out-of-date";
422 if(!problems.empty())
424 cerr<<"The following problems were detected:\n";
425 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
426 cerr<<" "<<i->package<<": "<<i->descr<<'\n';
427 cerr<<"Please fix them and try again.\n";
434 exit_code=do_clean();
436 exit_code=do_build();
443 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
445 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
450 void Builder::usage(const char *reason, const char *argv0, bool brief)
456 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";
460 "Usage: "<<argv0<<" [options] [<target> ...]\n"
463 " -a, --analyze MODE Perform analysis. MODE can be deps, alldeps or rebuild.\n"
464 " -b, --build Perform build even if doing analysis.\n"
465 " -c, --clean Clean buildable targets.\n"
466 " -f, --file FILE Read info from FILE instead of Build.\n"
467 " -h, --help Print this message.\n"
468 " -j, --jobs NUM Run NUM commands at once, whenever possible.\n"
469 " -n, --dry-run Don't actually do anything, only show what would be done.\n"
470 " -v, --verbose Print more information about what's going on.\n"
471 " -A, --conf-all Apply configuration to all packages.\n"
472 " -B, --build-all Build all targets unconditionally.\n"
473 " -C, --chdir DIR Change to DIR before doing anything else.\n"
474 " -P, --progress Display progress while building.\n"
475 " -W, --what-if FILE Pretend that FILE has changed.\n"
476 " --arch ARCH Architecture to build for.\n"
477 " --conf-only Stop after configuring packages.\n"
478 " --full-paths Output full paths in analysis.\n"
479 //" --makefile Create a makefile for this package.\n"
480 " --max-depth NUM Maximum depth to show in analysis.\n"
481 " --prefix DIR Directory to install things to.\n"
482 " --warnings LIST Compiler warnings to use.\n";
487 Determines the source directory of a package. pkg-config is consulted first,
488 and if it fails, the package path is searched for matches.
490 FS::Path Builder::get_package_location(const string &name)
493 cout<<"Looking for package "<<name<<'\n';
495 // Try to get source directory with pkgconfig
497 argv.push_back("pkg-config");
498 argv.push_back("--variable=source");
499 argv.push_back(name);
501 cout<<"Running "<<join(argv.begin(), argv.end())<<'\n';
502 string srcdir=strip(run_command(argv));
508 for(list<FS::Path>::const_iterator i=pkg_path.begin(); i!=pkg_path.end(); ++i)
510 list<string> files=list_files(*i);
511 for(list<string>::const_iterator j=files.begin(); j!=files.end(); ++j)
513 FS::Path full=*i / *j;
514 if(FS::exists(full/"Build"))
515 pkg_dirs.push_back(full);
519 cout<<pkg_dirs.size()<<" packages found in path\n";
522 bool msp=!name.compare(0, 3, "msp");
523 for(list<FS::Path>::const_iterator i=pkg_dirs.begin(); i!=pkg_dirs.end(); ++i)
525 string base=basename(*i);
526 unsigned dash=base.rfind('-');
528 if(!base.compare(0, dash, name))
530 else if(msp && !base.compare(0, dash-3, name, 3, string::npos))
538 Loads the given build file.
540 @param fn Path to the file
542 @return 0 on success, -1 if the file could not be opened
544 int Builder::load_build_file(const FS::Path &fn)
548 IO::File inf(fn.str());
549 IO::Buffered in(inf);
552 cout<<"Reading "<<fn<<'\n';
554 DataFile::Parser parser(in, fn.str());
555 Loader loader(*this, fn.subpath(0, fn.size()-1));
558 catch(const IO::FileNotFound &)
567 Creates targets for all packages and prepares them for building.
569 @return 0 if everything went ok, -1 if something bad happened and a build
570 shouldn't be attempted
572 int Builder::create_targets()
574 Target *world=new VirtualTarget(*this, "world");
576 Target *def_tgt=new VirtualTarget(*this, "default");
577 world->add_depend(def_tgt);
579 Target *install=new VirtualTarget(*this, "install");
580 world->add_depend(install);
582 Target *tarballs=new VirtualTarget(*this, "tarballs");
583 world->add_depend(tarballs);
585 PackageList all_reqs=main_pkg->collect_requires();
586 for(PackageList::iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
588 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
592 const ComponentList &components=spkg->get_components();
593 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
596 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
598 PkgConfig *pc=new PkgConfig(*this, *spkg);
599 install->add_depend(new Install(*this, *spkg, *pc));
602 tarballs->add_depend(new TarBall(*this, *spkg));
605 // Find dependencies until no new targets are created
606 while(!new_tgts.empty())
608 Target *tgt=new_tgts.front();
609 new_tgts.erase(new_tgts.begin());
611 if(!tgt->get_depends_ready())
612 new_tgts.push_back(tgt);
616 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
618 Target *tgt=get_target((cwd/ *i).str());
621 cerr<<"Unknown what-if target "<<*i<<'\n';
627 // Make the cmdline target depend on all targets mentioned on the command line
628 Target *cmdline=new VirtualTarget(*this, "cmdline");
629 bool build_world=false;
630 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
632 Target *tgt=get_target(*i);
634 tgt=get_target((cwd/ *i).str());
637 cerr<<"I don't know anything about "<<*i<<'\n';
642 cmdline->add_depend(tgt);
645 /* If world is to be built, prepare cmdline. If not, add cmdline to world
646 and prepare world. I don't really like this, but it keeps the graph
652 world->add_depend(cmdline);
656 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
657 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
658 spkg->get_deps_cache().save();
664 Check if a header exists, either as a target or a file. Either an existing
665 target or a new SystemHeader target will be returned.
667 Target *Builder::get_header(const Msp::FS::Path &fn)
669 Target *tgt=get_target(fn.str());
674 tgt=new SystemHeader(*this, fn.str());
680 Target *Builder::get_library(const string &lib, const FS::Path &path, LibMode mode)
682 // Populate a list of candidate filenames
683 StringList candidates;
687 if(current_arch->get_name()=="win32")
689 candidates.push_back("lib"+lib+".dll");
690 candidates.push_back(lib+".dll");
693 candidates.push_back("lib"+lib+".so");
696 /* Static libraries are always considered, since sometimes shared versions
697 may not be available */
698 candidates.push_back("lib"+lib+".a");
699 if(current_arch->get_name()=="win32")
700 candidates.push_back("lib"+lib+".dll.a");
702 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
704 string full=(path/ *i).str();
705 Target *tgt=get_target(full);
709 Target *real_tgt=tgt;
710 if(dynamic_cast<Install *>(tgt))
711 real_tgt=real_tgt->get_depends().front();
713 /* Ignore dynamic libraries from local packages unless library mode is
715 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
720 else if(FS::is_reg(full))
722 tgt=new SystemLibrary(*this, full);
731 Updates a hash with a string. This is used from get_header and get_library.
733 void Builder::update_hash(string &hash, const string &value)
735 for(unsigned i=0; i<value.size(); ++i)
736 hash[i%hash.size()]^=value[i];
740 This function supervises the build process, starting new actions when slots
743 int Builder::do_build()
745 Target *cmdline=get_target("cmdline");
747 unsigned total=cmdline->count_rebuild();
750 cout<<"Already up to date\n";
754 cout<<"Will build "<<total<<" target(s)\n";
756 vector<Action *> actions;
765 if(actions.size()<jobs && !fail)
767 Target *tgt=cmdline->get_buildable_target();
770 Action *action=tgt->build();
772 actions.push_back(action);
776 cout<<count<<" of "<<total<<" targets built\033[1G";
780 else if(actions.empty())
784 Time::sleep(10*Time::msec);
786 for(unsigned i=0; i<actions.size();)
788 int status=actions[i]->check();
794 actions.erase(actions.begin()+i);
797 if(actions.empty() && fail)
808 cout<<"Build failed\n";
809 else if(show_progress)
810 cout<<"Build complete\n";
816 Cleans buildable targets. If clean is 1, cleans only this package. If
817 clean is 2 or greater, cleans all buildable packages.
819 int Builder::do_clean()
821 // Cleaning doesn't care about ordering, so a simpler method can be used
823 set<Target *> clean_tgts;
825 queue.push_back(get_target("cmdline"));
827 while(!queue.empty())
829 Target *tgt=queue.front();
830 queue.erase(queue.begin());
832 if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
833 clean_tgts.insert(tgt);
835 const TargetList &deps=tgt->get_depends();
836 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
837 if(!clean_tgts.count(*i))
841 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
843 Action *action=new Unlink(*this, **i);
844 while(action->check()<0) ;
852 Prints out information about the default package.
854 void Builder::package_help()
856 const Config &config=main_pkg->get_config();
857 const Config::OptionMap &options=config.get_options();
859 cout<<"Required packages:\n ";
860 const PackageList &requires=main_pkg->get_requires();
861 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
863 if(i!=requires.begin())
865 cout<<(*i)->get_name();
868 cout<<"Package configuration:\n";
869 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
871 const Config::Option &opt=i->second;
872 cout<<" "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
876 Application::RegApp<Builder> Builder::reg;
879 Builder::Loader::Loader(Builder &b, const FS::Path &s):
883 add("architecture", &Loader::architecture);
884 add("binary_package", &Loader::binpkg);
885 add("profile", &Loader::profile);
886 add("package", &Loader::package);
889 void Builder::Loader::architecture(const string &n)
891 Architecture arch(bld, n);
893 bld.archs.insert(ArchMap::value_type(n, arch));
896 void Builder::Loader::binpkg(const string &n)
898 BinaryPackage *pkg=new BinaryPackage(bld, n);
900 bld.packages.insert(PackageMap::value_type(n, pkg));
903 void Builder::Loader::profile(const string &n)
906 ProfileLoader ldr(prf);
908 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
911 void Builder::Loader::package(const string &n)
913 SourcePackage *pkg=new SourcePackage(bld, n, src);
918 bld.packages.insert(PackageMap::value_type(n, pkg));
922 Builder::ProfileLoader::ProfileLoader(StringMap &p):
925 add("option", &ProfileLoader::option);
928 void Builder::ProfileLoader::option(const string &o, const string &v)
930 profile.insert(StringMap::value_type(o, v));