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_sys_data_dir(argv[0], "builder")/"builderrc").str());
143 load_build_file((FS::get_home_dir()/".builderrc").str());
146 current_arch=native_arch;
148 current_arch=&get_architecture(arch);
152 if(current_arch->is_native())
153 prefix=(FS::get_home_dir()/"local").str();
155 prefix=(FS::get_home_dir()/"local"/current_arch->get_name()).str();
158 prefix=FS::getcwd()/prfx;
160 warnings.push_back("all");
161 warnings.push_back("extra");
162 warnings.push_back("shadow");
163 warnings.push_back("pointer-arith");
164 warnings.push_back("error");
165 for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
167 vector<string> warns=split(*i, ',');
168 warnings.insert(warnings.end(), warns.begin(), warns.end());
171 pkg_path.push_back(cwd/".");
172 pkg_path.push_back(cwd/"..");
176 Gets a package by name, possibly creating it.
178 @param name Package name
180 @return Pointer to the package, or 0 if the package could not be located
182 Package *Builder::get_package(const string &name)
184 PackageMap::iterator i=packages.find(format("%s/%s", name, current_arch->get_name()));
185 if(i==packages.end())
186 i=packages.find(name);
187 if(i!=packages.end())
190 FS::Path path=get_package_location(name);
191 if(!path.empty() && !load_build_file(path/"Build"))
193 i=packages.find(name);
194 if(i!=packages.end())
198 // Package source not found - create a binary package
199 Package *pkg=BinaryPackage::from_pkgconfig(*this, name);
201 packages.insert(PackageMap::value_type(name, pkg));
204 problem(name, "not found");
210 Returns the target with the given name, or 0 if no such target exists.
212 Target *Builder::get_target(const string &n) const
214 TargetMap::const_iterator i=targets.find(n);
221 Tries to locate a header included from a given location and with a given include
222 path. Considers known targets as well as existing files. If a matching target
223 is not found but a file exists, a new SystemHeader target will be created and
226 Target *Builder::get_header(const string &include, const string &from, const list<string> &path)
230 update_hash(hash, from);
231 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
232 update_hash(hash, *i);
234 string id=hash+include;
235 TargetMap::iterator i=includes.find(id);
236 if(i!=includes.end())
239 static string cxx_ver;
243 argv.push_back(current_arch->get_tool("CXX"));
244 argv.push_back("--version");
245 cxx_ver=Regex("[0-9]\\.[0-9.]+").match(run_command(argv))[0].str;
246 while(!cxx_ver.empty() && !FS::is_dir(FS::Path("/usr/include/c++")/cxx_ver))
248 unsigned dot=cxx_ver.rfind('.');
249 if(dot==string::npos)
254 cout<<"C++ version is "<<cxx_ver<<'\n';
257 string fn=include.substr(1);
259 cout<<"Looking for include "<<fn<<" with path "<<join(path.begin(), path.end())<<'\n';
262 if(current_arch->is_native())
263 syspath.push_back("/usr/include");
265 syspath.push_back("/usr/"+current_arch->get_prefix()+"/include");
266 syspath.push_back((FS::Path("/usr/include/c++/")/cxx_ver).str());
270 tgt=get_header(FS::Path(from)/fn);
271 for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
272 tgt=get_header(cwd/ *j/fn);
273 for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
274 tgt=get_header(FS::Path(*j)/fn);
276 includes.insert(TargetMap::value_type(id, tgt));
282 Tries to locate a library with the given library path. Considers known targets
283 as well as existing files. If a matching target is not found but a file exists,
284 a new SystemLibrary target will be created and returned.
286 @param lib Name of the library to get (without "lib" prefix or extension)
287 @param path List of paths to search for the library
288 @param mode Shared / static mode
290 @return Some kind of library target, if a match was found
292 Target *Builder::get_library(const string &lib, const list<string> &path, LibMode mode)
295 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
296 update_hash(hash, *i);
298 string id=hash+string(1, mode)+lib;
299 TargetMap::iterator i=libraries.find(id);
300 if(i!=libraries.end())
304 if(current_arch->is_native())
306 syspath.push_back("/lib");
307 syspath.push_back("/usr/lib");
310 syspath.push_back("/usr/"+current_arch->get_prefix()+"/lib");
313 cout<<"Looking for library "<<lib<<" with path "<<join(path.begin(), path.end())<<'\n';
316 for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
317 tgt=get_library(lib, cwd/ *j, mode);
318 for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
319 tgt=get_library(lib, *j, mode);
321 libraries.insert(TargetMap::value_type(id, tgt));
326 const Architecture &Builder::get_architecture(const string &arch) const
328 ArchMap::const_iterator i=archs.find(arch);
330 throw KeyError("Unknown architecture", arch);
335 void Builder::apply_profile_template(Config &config, const string &pt) const
337 vector<string> parts=split(pt, '-');
339 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
341 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
342 if(j==profile_tmpl.end())
345 config.update(j->second);
349 void Builder::problem(const string &p, const string &d)
351 problems.push_back(Problem(p, d));
355 Adds a target to both the target map and the new target queue. Called from
358 void Builder::add_target(Target *t)
360 targets.insert(TargetMap::value_type(t->get_name(), t));
361 new_tgts.push_back(t);
366 if(load_build_file(cwd/build_file))
368 cerr<<"No build info here.\n";
372 main_pkg->configure(cmdline_options, conf_all?2:1);
376 usage(0, "builder", false);
382 if(!conf_only && create_targets())
385 PackageList all_reqs=main_pkg->collect_requires();
391 cout<<"Building on "<<native_arch->get_name()<<", for "<<current_arch->get_name()<<'\n';
393 cout<<all_reqs.size()<<" active packages, "<<targets.size()<<" targets\n";
396 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
398 cout<<' '<<(*i)->get_name();
399 if(dynamic_cast<SourcePackage *>(*i))
402 unsigned ood_count=0;
403 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
404 if(j->second->get_package()==*i)
407 if(j->second->get_rebuild())
412 cout<<" ("<<count<<" targets";
414 cout<<", "<<ood_count<<" out-of-date";
424 if(!problems.empty())
426 cerr<<"The following problems were detected:\n";
427 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
428 cerr<<" "<<i->package<<": "<<i->descr<<'\n';
429 cerr<<"Please fix them and try again.\n";
436 exit_code=do_clean();
438 exit_code=do_build();
445 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
447 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
452 void Builder::usage(const char *reason, const char *argv0, bool brief)
458 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";
462 "Usage: "<<argv0<<" [options] [<target> ...]\n"
465 " -a, --analyze MODE Perform analysis. MODE can be deps, alldeps or rebuild.\n"
466 " -b, --build Perform build even if doing analysis.\n"
467 " -c, --clean Clean buildable targets.\n"
468 " -f, --file FILE Read info from FILE instead of Build.\n"
469 " -h, --help Print this message.\n"
470 " -j, --jobs NUM Run NUM commands at once, whenever possible.\n"
471 " -n, --dry-run Don't actually do anything, only show what would be done.\n"
472 " -v, --verbose Print more information about what's going on.\n"
473 " -A, --conf-all Apply configuration to all packages.\n"
474 " -B, --build-all Build all targets unconditionally.\n"
475 " -C, --chdir DIR Change to DIR before doing anything else.\n"
476 " -P, --progress Display progress while building.\n"
477 " -W, --what-if FILE Pretend that FILE has changed.\n"
478 " --arch ARCH Architecture to build for.\n"
479 " --conf-only Stop after configuring packages.\n"
480 " --full-paths Output full paths in analysis.\n"
481 //" --makefile Create a makefile for this package.\n"
482 " --max-depth NUM Maximum depth to show in analysis.\n"
483 " --prefix DIR Directory to install things to.\n"
484 " --warnings LIST Compiler warnings to use.\n";
489 Determines the source directory of a package. pkg-config is consulted first,
490 and if it fails, the package path is searched for matches.
492 FS::Path Builder::get_package_location(const string &name)
495 cout<<"Looking for package "<<name<<'\n';
497 // Try to get source directory with pkgconfig
499 argv.push_back("pkg-config");
500 argv.push_back("--variable=source");
501 argv.push_back(name);
503 cout<<"Running "<<join(argv.begin(), argv.end())<<'\n';
504 string srcdir=strip(run_command(argv));
510 for(list<FS::Path>::const_iterator i=pkg_path.begin(); i!=pkg_path.end(); ++i)
512 list<string> files=list_files(*i);
513 for(list<string>::const_iterator j=files.begin(); j!=files.end(); ++j)
515 FS::Path full=*i / *j;
516 if(FS::exists(full/"Build"))
517 pkg_dirs.push_back(full);
521 cout<<pkg_dirs.size()<<" packages found in path\n";
524 bool msp=!name.compare(0, 3, "msp");
525 for(list<FS::Path>::const_iterator i=pkg_dirs.begin(); i!=pkg_dirs.end(); ++i)
527 string base=basename(*i);
528 unsigned dash=base.rfind('-');
530 if(!base.compare(0, dash, name))
532 else if(msp && !base.compare(0, dash-3, name, 3, string::npos))
540 Loads the given build file.
542 @param fn Path to the file
544 @return 0 on success, -1 if the file could not be opened
546 int Builder::load_build_file(const FS::Path &fn)
550 IO::BufferedFile in(fn.str());
553 cout<<"Reading "<<fn<<'\n';
555 DataFile::Parser parser(in, fn.str());
556 Loader loader(*this, fn.subpath(0, fn.size()-1));
559 catch(const IO::FileNotFound &)
568 Creates targets for all packages and prepares them for building.
570 @return 0 if everything went ok, -1 if something bad happened and a build
571 shouldn't be attempted
573 int Builder::create_targets()
575 Target *world=new VirtualTarget(*this, "world");
577 Target *def_tgt=new VirtualTarget(*this, "default");
578 world->add_depend(def_tgt);
580 Target *install=new VirtualTarget(*this, "install");
581 world->add_depend(install);
583 Target *tarballs=new VirtualTarget(*this, "tarballs");
584 world->add_depend(tarballs);
586 PackageList all_reqs=main_pkg->collect_requires();
587 for(PackageList::iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
589 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
593 const ComponentList &components=spkg->get_components();
594 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
597 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
599 PkgConfig *pc=new PkgConfig(*this, *spkg);
600 install->add_depend(new Install(*this, *spkg, *pc));
603 tarballs->add_depend(new TarBall(*this, *spkg));
606 // Find dependencies until no new targets are created
607 while(!new_tgts.empty())
609 Target *tgt=new_tgts.front();
610 new_tgts.erase(new_tgts.begin());
612 if(!tgt->get_depends_ready())
613 new_tgts.push_back(tgt);
617 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
619 Target *tgt=get_target((cwd/ *i).str());
622 cerr<<"Unknown what-if target "<<*i<<'\n';
628 // Make the cmdline target depend on all targets mentioned on the command line
629 Target *cmdline=new VirtualTarget(*this, "cmdline");
630 bool build_world=false;
631 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
633 Target *tgt=get_target(*i);
635 tgt=get_target((cwd/ *i).str());
638 cerr<<"I don't know anything about "<<*i<<'\n';
643 cmdline->add_depend(tgt);
646 /* If world is to be built, prepare cmdline. If not, add cmdline to world
647 and prepare world. I don't really like this, but it keeps the graph
653 world->add_depend(cmdline);
657 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
658 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
659 spkg->get_deps_cache().save();
665 Check if a header exists, either as a target or a file. Either an existing
666 target or a new SystemHeader target will be returned.
668 Target *Builder::get_header(const Msp::FS::Path &fn)
670 Target *tgt=get_target(fn.str());
675 tgt=new SystemHeader(*this, fn.str());
681 Target *Builder::get_library(const string &lib, const FS::Path &path, LibMode mode)
683 // Populate a list of candidate filenames
684 StringList candidates;
688 if(current_arch->get_name()=="win32")
690 candidates.push_back("lib"+lib+".dll");
691 candidates.push_back(lib+".dll");
694 candidates.push_back("lib"+lib+".so");
697 /* Static libraries are always considered, since sometimes shared versions
698 may not be available */
699 candidates.push_back("lib"+lib+".a");
700 if(current_arch->get_name()=="win32")
701 candidates.push_back("lib"+lib+".dll.a");
703 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
705 string full=(path/ *i).str();
706 Target *tgt=get_target(full);
710 Target *real_tgt=tgt;
711 if(dynamic_cast<Install *>(tgt))
712 real_tgt=real_tgt->get_depends().front();
714 /* Ignore dynamic libraries from local packages unless library mode is
716 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
721 else if(FS::is_reg(full))
723 tgt=new SystemLibrary(*this, full);
732 Updates a hash with a string. This is used from get_header and get_library.
734 void Builder::update_hash(string &hash, const string &value)
736 for(unsigned i=0; i<value.size(); ++i)
737 hash[i%hash.size()]^=value[i];
741 This function supervises the build process, starting new actions when slots
744 int Builder::do_build()
746 Target *cmdline=get_target("cmdline");
748 unsigned total=cmdline->count_rebuild();
751 cout<<"Already up to date\n";
755 cout<<"Will build "<<total<<" target(s)\n";
757 vector<Action *> actions;
766 if(actions.size()<jobs && !fail)
768 Target *tgt=cmdline->get_buildable_target();
771 Action *action=tgt->build();
773 actions.push_back(action);
777 cout<<count<<" of "<<total<<" targets built\033[1G";
781 else if(actions.empty())
785 Time::sleep(10*Time::msec);
787 for(unsigned i=0; i<actions.size();)
789 int status=actions[i]->check();
795 actions.erase(actions.begin()+i);
798 if(actions.empty() && fail)
809 cout<<"Build failed\n";
810 else if(show_progress)
811 cout<<"Build complete\n";
817 Cleans buildable targets. If clean is 1, cleans only this package. If
818 clean is 2 or greater, cleans all buildable packages.
820 int Builder::do_clean()
822 // Cleaning doesn't care about ordering, so a simpler method can be used
824 set<Target *> clean_tgts;
826 queue.push_back(get_target("cmdline"));
828 while(!queue.empty())
830 Target *tgt=queue.front();
831 queue.erase(queue.begin());
833 if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
834 clean_tgts.insert(tgt);
836 const TargetList &deps=tgt->get_depends();
837 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
838 if(!clean_tgts.count(*i))
842 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
844 Action *action=new Unlink(*this, **i);
845 while(action->check()<0) ;
853 Prints out information about the default package.
855 void Builder::package_help()
857 const Config &config=main_pkg->get_config();
858 const Config::OptionMap &options=config.get_options();
860 cout<<"Required packages:\n ";
861 const PackageList &requires=main_pkg->get_requires();
862 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
864 if(i!=requires.begin())
866 cout<<(*i)->get_name();
869 cout<<"Package configuration:\n";
870 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
872 const Config::Option &opt=i->second;
873 cout<<" "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
877 Application::RegApp<Builder> Builder::reg;
880 Builder::Loader::Loader(Builder &b, const FS::Path &s):
884 add("architecture", &Loader::architecture);
885 add("binary_package", &Loader::binpkg);
886 add("profile", &Loader::profile);
887 add("package", &Loader::package);
890 void Builder::Loader::architecture(const string &n)
892 Architecture arch(bld, n);
894 bld.archs.insert(ArchMap::value_type(n, arch));
897 void Builder::Loader::binpkg(const string &n)
899 BinaryPackage *pkg=new BinaryPackage(bld, n);
901 bld.packages.insert(PackageMap::value_type(n, pkg));
904 void Builder::Loader::profile(const string &n)
907 ProfileLoader ldr(prf);
909 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
912 void Builder::Loader::package(const string &n)
914 SourcePackage *pkg=new SourcePackage(bld, n, src);
919 bld.packages.insert(PackageMap::value_type(n, pkg));
923 Builder::ProfileLoader::ProfileLoader(StringMap &p):
926 add("option", &ProfileLoader::option);
929 void Builder::ProfileLoader::option(const string &o, const string &v)
931 profile.insert(StringMap::value_type(o, v));