3 This file is part of builder
4 Copyright © 2006-2009 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"
46 void update_hash(string &hash, const string &value)
48 for(unsigned i=0; i<value.size(); ++i)
49 hash[i%hash.size()]^=value[i];
55 Builder::Builder(int argc, char **argv):
69 create_makefile(false)
73 bool full_paths=false;
75 StringList cmdline_warn;
80 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG);
81 getopt.add_option('b', "build", build, GetOpt::NO_ARG);
82 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG);
83 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG);
84 getopt.add_option('h', "help", help, GetOpt::NO_ARG);
85 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG);
86 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG);
87 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG);
88 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG);
89 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG);
90 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG);
91 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG);
92 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG);
93 getopt.add_option( "arch", arch, GetOpt::REQUIRED_ARG);
94 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG);
95 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG);
96 //getopt.add_option( "makefile", create_makefile, GetOpt::NO_ARG);
97 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG);
98 getopt.add_option( "prefix", prfx, GetOpt::REQUIRED_ARG);
99 getopt.add_option( "warnings", cmdline_warn, GetOpt::REQUIRED_ARG);
102 if(!analyze_mode.empty())
104 analyzer=new Analyzer(*this);
106 if(analyze_mode=="deps")
107 analyzer->set_mode(Analyzer::DEPS);
108 else if(analyze_mode=="alldeps")
109 analyzer->set_mode(Analyzer::ALLDEPS);
110 else if(analyze_mode=="rebuild")
111 analyzer->set_mode(Analyzer::REBUILD);
112 else if(analyze_mode=="rdeps")
113 analyzer->set_mode(Analyzer::RDEPS);
115 throw UsageError("Invalid analyze mode");
117 analyzer->set_max_depth(max_depth);
118 analyzer->set_full_paths(full_paths);
120 else if(!clean && !create_makefile)
123 const vector<string> &args=getopt.get_args();
124 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
126 unsigned equal=i->find('=');
127 if(equal!=string::npos)
128 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
130 cmdline_targets.push_back(*i);
133 if(cmdline_targets.empty())
134 cmdline_targets.push_back("default");
136 if(!work_dir.empty())
137 chdir(work_dir.c_str());
142 string sysname="native";
144 sysname=tolower(un.sysname);
146 native_arch=&archs.insert(ArchMap::value_type(sysname, Architecture(*this, sysname, true))).first->second;
147 native_arch->set_tool("CC", "gcc");
148 native_arch->set_tool("CXX", "g++");
149 native_arch->set_tool("LD", "gcc");
150 native_arch->set_tool("LXX", "g++");
151 native_arch->set_tool("AR", "ar");
153 load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
154 load_build_file((FS::get_home_dir()/".builderrc").str());
157 current_arch=native_arch;
159 current_arch=&get_architecture(arch);
163 if(current_arch->is_native())
164 prefix=(FS::get_home_dir()/"local").str();
166 prefix=(FS::get_home_dir()/"local"/current_arch->get_name()).str();
169 prefix=FS::getcwd()/prfx;
171 warnings.push_back("all");
172 warnings.push_back("extra");
173 warnings.push_back("shadow");
174 warnings.push_back("pointer-arith");
175 warnings.push_back("error");
176 for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
178 vector<string> warns=split(*i, ',');
179 warnings.insert(warnings.end(), warns.begin(), warns.end());
182 pkg_path.push_back(cwd/".");
183 pkg_path.push_back(cwd/"..");
188 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
190 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
197 if(load_build_file(cwd/build_file))
199 cerr<<"No build info here.\n";
203 main_pkg->configure(cmdline_options, conf_all?2:1);
207 usage(0, "builder", false);
213 if(!conf_only && create_targets())
216 PackageList all_reqs=main_pkg->collect_requires();
222 cout<<"Building on "<<native_arch->get_name()<<", for "<<current_arch->get_name()<<'\n';
224 cout<<all_reqs.size()<<" active packages, "<<targets.size()<<" targets\n";
227 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
229 cout<<' '<<(*i)->get_name();
230 if(dynamic_cast<SourcePackage *>(*i))
233 unsigned ood_count=0;
234 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
235 if(j->second->get_package()==*i)
238 if(j->second->get_rebuild())
243 cout<<" ("<<count<<" targets";
245 cout<<", "<<ood_count<<" out-of-date";
255 if(!problems.empty())
257 cerr<<"The following problems were detected:\n";
258 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
259 cerr<<" "<<i->package<<": "<<i->descr<<'\n';
260 cerr<<"Please fix them and try again.\n";
267 exit_code=do_clean();
269 exit_code=do_build();
274 Package *Builder::get_package(const string &name)
276 PackageMap::iterator i=packages.find(format("%s/%s", name, current_arch->get_name()));
277 if(i==packages.end())
278 i=packages.find(name);
279 if(i!=packages.end())
282 FS::Path path=get_package_location(name);
283 if(!path.empty() && !load_build_file(path/"Build"))
285 i=packages.find(name);
286 if(i!=packages.end())
290 // Package source not found - create a binary package
291 Package *pkg=BinaryPackage::from_pkgconfig(*this, name);
293 packages.insert(PackageMap::value_type(name, pkg));
296 problem(name, "not found");
301 Target *Builder::get_target(const string &n) const
303 TargetMap::const_iterator i=targets.find(n);
309 Target *Builder::get_header(const string &include, const string &from, const list<string> &path)
313 update_hash(hash, from);
314 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
315 update_hash(hash, *i);
317 string id=hash+include;
318 TargetMap::iterator i=includes.find(id);
319 if(i!=includes.end())
322 static string cxx_ver;
326 argv.push_back(current_arch->get_tool("CXX"));
327 argv.push_back("--version");
328 cxx_ver=Regex("[0-9]\\.[0-9.]+").match(run_command(argv))[0].str;
329 while(!cxx_ver.empty() && !FS::is_dir(FS::Path("/usr/include/c++")/cxx_ver))
331 unsigned dot=cxx_ver.rfind('.');
332 if(dot==string::npos)
337 cout<<"C++ version is "<<cxx_ver<<'\n';
340 string fn=include.substr(1);
342 cout<<"Looking for include "<<fn<<" with path "<<join(path.begin(), path.end())<<'\n';
345 if(current_arch->is_native())
346 syspath.push_back("/usr/include");
348 syspath.push_back("/usr/"+current_arch->get_prefix()+"/include");
349 syspath.push_back((FS::Path("/usr/include/c++/")/cxx_ver).str());
353 tgt=get_header(FS::Path(from)/fn);
354 for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
355 tgt=get_header(cwd/ *j/fn);
356 for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
357 tgt=get_header(FS::Path(*j)/fn);
359 includes.insert(TargetMap::value_type(id, tgt));
364 Target *Builder::get_library(const string &lib, const list<string> &path, LibMode mode)
367 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
368 update_hash(hash, *i);
370 string id=hash+string(1, mode)+lib;
371 TargetMap::iterator i=libraries.find(id);
372 if(i!=libraries.end())
376 if(current_arch->is_native())
378 syspath.push_back("/lib");
379 syspath.push_back("/usr/lib");
382 syspath.push_back("/usr/"+current_arch->get_prefix()+"/lib");
385 cout<<"Looking for library "<<lib<<" with path "<<join(path.begin(), path.end())<<'\n';
388 for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
389 tgt=get_library(lib, cwd/ *j, mode);
390 for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
391 tgt=get_library(lib, *j, mode);
393 libraries.insert(TargetMap::value_type(id, tgt));
398 const Architecture &Builder::get_architecture(const string &arch) const
400 ArchMap::const_iterator i=archs.find(arch);
402 throw KeyError("Unknown architecture", arch);
407 void Builder::apply_profile_template(Config &config, const string &pt) const
409 vector<string> parts=split(pt, '-');
411 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
413 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
414 if(j==profile_tmpl.end())
417 config.update(j->second);
421 void Builder::problem(const string &p, const string &d)
423 problems.push_back(Problem(p, d));
426 void Builder::add_target(Target *t)
428 targets.insert(TargetMap::value_type(t->get_name(), t));
429 new_tgts.push_back(t);
432 void Builder::usage(const char *reason, const char *argv0, bool brief)
438 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";
442 "Usage: "<<argv0<<" [options] [<target> ...]\n"
445 " -a, --analyze MODE Perform analysis. MODE can be deps, alldeps or rebuild.\n"
446 " -b, --build Perform build even if doing analysis.\n"
447 " -c, --clean Clean buildable targets.\n"
448 " -f, --file FILE Read info from FILE instead of Build.\n"
449 " -h, --help Print this message.\n"
450 " -j, --jobs NUM Run NUM commands at once, whenever possible.\n"
451 " -n, --dry-run Don't actually do anything, only show what would be done.\n"
452 " -v, --verbose Print more information about what's going on.\n"
453 " -A, --conf-all Apply configuration to all packages.\n"
454 " -B, --build-all Build all targets unconditionally.\n"
455 " -C, --chdir DIR Change to DIR before doing anything else.\n"
456 " -P, --progress Display progress while building.\n"
457 " -W, --what-if FILE Pretend that FILE has changed.\n"
458 " --arch ARCH Architecture to build for.\n"
459 " --conf-only Stop after configuring packages.\n"
460 " --full-paths Output full paths in analysis.\n"
461 //" --makefile Create a makefile for this package.\n"
462 " --max-depth NUM Maximum depth to show in analysis.\n"
463 " --prefix DIR Directory to install things to.\n"
464 " --warnings LIST Compiler warnings to use.\n";
468 FS::Path Builder::get_package_location(const string &name)
471 cout<<"Looking for package "<<name<<'\n';
473 // Try to get source directory with pkgconfig
475 argv.push_back("pkg-config");
476 argv.push_back("--variable=source");
477 argv.push_back(name);
479 cout<<"Running "<<join(argv.begin(), argv.end())<<'\n';
480 string srcdir=strip(run_command(argv));
486 for(list<FS::Path>::const_iterator i=pkg_path.begin(); i!=pkg_path.end(); ++i)
488 list<string> files=list_files(*i);
489 for(list<string>::const_iterator j=files.begin(); j!=files.end(); ++j)
491 FS::Path full=*i / *j;
492 if(FS::exists(full/"Build"))
493 pkg_dirs.push_back(full);
497 cout<<pkg_dirs.size()<<" packages found in path\n";
500 bool msp=!name.compare(0, 3, "msp");
501 for(list<FS::Path>::const_iterator i=pkg_dirs.begin(); i!=pkg_dirs.end(); ++i)
503 string base=basename(*i);
504 unsigned dash=base.rfind('-');
506 if(!base.compare(0, dash, name))
508 else if(msp && !base.compare(0, dash-3, name, 3, string::npos))
515 int Builder::load_build_file(const FS::Path &fn)
519 IO::BufferedFile in(fn.str());
522 cout<<"Reading "<<fn<<'\n';
524 DataFile::Parser parser(in, fn.str());
525 Loader loader(*this, fn.subpath(0, fn.size()-1));
528 catch(const IO::FileNotFound &)
536 int Builder::create_targets()
538 Target *world=new VirtualTarget(*this, "world");
540 Target *def_tgt=new VirtualTarget(*this, "default");
541 world->add_depend(def_tgt);
543 Target *install=new VirtualTarget(*this, "install");
544 world->add_depend(install);
546 Target *tarballs=new VirtualTarget(*this, "tarballs");
547 world->add_depend(tarballs);
549 PackageList all_reqs=main_pkg->collect_requires();
550 for(PackageList::iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
552 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
556 const ComponentList &components=spkg->get_components();
557 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
560 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
562 PkgConfig *pc=new PkgConfig(*this, *spkg);
563 install->add_depend(new Install(*this, *spkg, *pc));
566 tarballs->add_depend(new TarBall(*this, *spkg));
569 // Find dependencies until no new targets are created
570 while(!new_tgts.empty())
572 Target *tgt=new_tgts.front();
573 new_tgts.erase(new_tgts.begin());
575 if(!tgt->get_depends_ready())
576 new_tgts.push_back(tgt);
580 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
582 Target *tgt=get_target((cwd/ *i).str());
585 cerr<<"Unknown what-if target "<<*i<<'\n';
591 // Make the cmdline target depend on all targets mentioned on the command line
592 Target *cmdline=new VirtualTarget(*this, "cmdline");
593 bool build_world=false;
594 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
596 Target *tgt=get_target(*i);
598 tgt=get_target((cwd/ *i).str());
601 cerr<<"I don't know anything about "<<*i<<'\n';
606 cmdline->add_depend(tgt);
609 /* If world is to be built, prepare cmdline. If not, add cmdline to world
610 and prepare world. I don't really like this, but it keeps the graph
613 XXX Could we skip preparing targets we are not interested in? */
618 world->add_depend(cmdline);
622 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
623 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
624 spkg->get_deps_cache().save();
629 Target *Builder::get_header(const Msp::FS::Path &fn)
631 Target *tgt=get_target(fn.str());
636 tgt=new SystemHeader(*this, fn.str());
642 Target *Builder::get_library(const string &lib, const FS::Path &path, LibMode mode)
644 // Populate a list of candidate filenames
645 StringList candidates;
649 if(current_arch->get_name()=="win32")
651 candidates.push_back("lib"+lib+".dll");
652 candidates.push_back(lib+".dll");
655 candidates.push_back("lib"+lib+".so");
658 /* Static libraries are always considered, since sometimes shared versions
659 may not be available */
660 candidates.push_back("lib"+lib+".a");
661 if(current_arch->get_name()=="win32")
662 candidates.push_back("lib"+lib+".dll.a");
664 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
666 string full=(path/ *i).str();
667 Target *tgt=get_target(full);
671 Target *real_tgt=tgt;
672 if(dynamic_cast<Install *>(tgt))
673 real_tgt=real_tgt->get_depends().front();
675 /* Ignore dynamic libraries from local packages unless library mode is
677 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
682 else if(FS::is_reg(full))
684 tgt=new SystemLibrary(*this, full);
692 int Builder::do_build()
694 Target *cmdline=get_target("cmdline");
696 unsigned total=cmdline->count_rebuild();
699 cout<<"Already up to date\n";
703 cout<<"Will build "<<total<<" target(s)\n";
705 vector<Action *> actions;
714 if(actions.size()<jobs && !fail)
716 Target *tgt=cmdline->get_buildable_target();
719 Action *action=tgt->build();
721 actions.push_back(action);
725 cout<<count<<" of "<<total<<" targets built\033[1G";
729 else if(actions.empty())
733 Time::sleep(10*Time::msec);
735 for(unsigned i=0; i<actions.size();)
737 int status=actions[i]->check();
743 actions.erase(actions.begin()+i);
746 if(actions.empty() && fail)
757 cout<<"Build failed\n";
758 else if(show_progress)
759 cout<<"Build complete\n";
764 int Builder::do_clean()
766 // Cleaning doesn't care about ordering, so a simpler method can be used
768 set<Target *> clean_tgts;
770 queue.push_back(get_target("cmdline"));
772 while(!queue.empty())
774 Target *tgt=queue.front();
775 queue.erase(queue.begin());
777 if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
778 clean_tgts.insert(tgt);
780 const TargetList &deps=tgt->get_depends();
781 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
782 if(!clean_tgts.count(*i))
786 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
788 Action *action=new Unlink(*this, **i);
789 while(action->check()<0) ;
796 void Builder::package_help()
798 const Config &config=main_pkg->get_config();
799 const Config::OptionMap &options=config.get_options();
801 cout<<"Required packages:\n ";
802 const PackageList &requires=main_pkg->get_requires();
803 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
805 if(i!=requires.begin())
807 cout<<(*i)->get_name();
810 cout<<"Package configuration:\n";
811 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
813 const Config::Option &opt=i->second;
814 cout<<" "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
818 Application::RegApp<Builder> Builder::reg;
821 Builder::Loader::Loader(Builder &b, const FS::Path &s):
825 add("architecture", &Loader::architecture);
826 add("binary_package", &Loader::binpkg);
827 add("profile", &Loader::profile);
828 add("package", &Loader::package);
831 void Builder::Loader::architecture(const string &n)
833 Architecture arch(bld, n);
835 bld.archs.insert(ArchMap::value_type(n, arch));
838 void Builder::Loader::binpkg(const string &n)
840 BinaryPackage *pkg=new BinaryPackage(bld, n);
842 bld.packages.insert(PackageMap::value_type(n, pkg));
845 void Builder::Loader::profile(const string &n)
848 ProfileLoader ldr(prf);
850 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
853 void Builder::Loader::package(const string &n)
855 SourcePackage *pkg=new SourcePackage(bld, n, src);
860 bld.packages.insert(PackageMap::value_type(n, pkg));
864 Builder::ProfileLoader::ProfileLoader(StringMap &p):
867 add("option", &ProfileLoader::option);
870 void Builder::ProfileLoader::option(const string &o, const string &v)
872 profile.insert(StringMap::value_type(o, v));