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/io/print.h>
21 #include <msp/strings/formatter.h>
22 #include <msp/strings/regex.h>
23 #include <msp/strings/utils.h>
24 #include <msp/time/units.h>
25 #include <msp/time/utils.h>
28 #include "binarypackage.h"
34 #include "pkgconfig.h"
35 #include "sharedlibrary.h"
36 #include "sourcepackage.h"
37 #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).set_help("Perform analysis. MODE can be deps, alldeps or rebuild.", "MODE");
81 getopt.add_option('b', "build", build, GetOpt::NO_ARG).set_help("Perform build even if doing analysis.");
82 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG).set_help("Clean buildable targets.");
83 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG).set_help("Read info from FILE instead of Build.", "FILE");
84 getopt.add_option('h', "help", help, GetOpt::NO_ARG).set_help("Print this message.");
85 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG).set_help("Run NUM commands at once, whenever possible.", "NUM");
86 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG).set_help("Don't actually do anything, only show what would be done.");
87 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG).set_help("Print more information about what's going on.");
88 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
89 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
90 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
91 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
92 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
93 getopt.add_option( "arch", arch, GetOpt::REQUIRED_ARG).set_help("Architecture to build for.", "ARCH");
94 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG).set_help("Stop after configuring packages.");
95 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG).set_help("Output full paths in analysis.");
96 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG).set_help("Maximum depth to show in analysis.", "NUM");
97 getopt.add_option( "prefix", prfx, GetOpt::REQUIRED_ARG).set_help("Directory to install things to.", "DIR");
98 getopt.add_option( "warnings", cmdline_warn, GetOpt::REQUIRED_ARG).set_help("Compiler warnings to use.", "LIST");
99 usagemsg=getopt.generate_usage(argv[0])+" [<target> ...]";
100 helpmsg=getopt.generate_help();
103 if(!analyze_mode.empty())
105 analyzer=new Analyzer(*this);
107 if(analyze_mode=="deps")
108 analyzer->set_mode(Analyzer::DEPS);
109 else if(analyze_mode=="alldeps")
110 analyzer->set_mode(Analyzer::ALLDEPS);
111 else if(analyze_mode=="rebuild")
112 analyzer->set_mode(Analyzer::REBUILD);
113 else if(analyze_mode=="rdeps")
114 analyzer->set_mode(Analyzer::RDEPS);
116 throw UsageError("Invalid analyze mode");
118 analyzer->set_max_depth(max_depth);
119 analyzer->set_full_paths(full_paths);
121 else if(!clean && !create_makefile)
124 const vector<string> &args=getopt.get_args();
125 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
127 string::size_type equal=i->find('=');
128 if(equal!=string::npos)
129 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
131 cmdline_targets.push_back(*i);
134 if(cmdline_targets.empty())
135 cmdline_targets.push_back("default");
137 if(!work_dir.empty())
143 string sysname="native";
145 sysname=tolower(un.sysname);
147 native_arch=&archs.insert(ArchMap::value_type(sysname, Architecture(*this, sysname, true))).first->second;
148 native_arch->set_tool("CC", "gcc");
149 native_arch->set_tool("CXX", "g++");
150 native_arch->set_tool("LD", "gcc");
151 native_arch->set_tool("LXX", "g++");
152 native_arch->set_tool("AR", "ar");
154 load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
155 load_build_file((FS::get_user_data_dir("builder")/"rc").str());
158 current_arch=native_arch;
160 current_arch=&get_architecture(arch);
164 if(current_arch->is_native())
165 prefix=(FS::get_home_dir()/"local").str();
167 prefix=(FS::get_home_dir()/"local"/current_arch->get_name()).str();
170 prefix=FS::getcwd()/prfx;
172 warnings.push_back("all");
173 warnings.push_back("extra");
174 warnings.push_back("shadow");
175 warnings.push_back("pointer-arith");
176 warnings.push_back("error");
177 for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
179 vector<string> warns=split(*i, ',');
180 warnings.insert(warnings.end(), warns.begin(), warns.end());
183 pkg_path.push_back(cwd/".");
184 pkg_path.push_back(cwd/"..");
189 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
191 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
198 if(prefix.str()!="/usr")
200 FS::Path pcdir=prefix/"lib"/"pkgconfig";
201 if(const char *pcp=getenv("PKG_CONFIG_PATH"))
203 vector<string> path=split(pcp, ':');
205 for(vector<string>::const_iterator i=path.begin(); (!found && i!=path.end()); ++i)
206 found=(*i==pcdir.str());
209 path.push_back(pcdir.str());
210 setenv("PKG_CONFIG_PATH", join(path.begin(), path.end(), ":").c_str(), true);
214 setenv("PKG_CONFIG_PATH", pcdir.str().c_str(), true);
217 if(load_build_file(cwd/build_file))
221 usage(0, "builder", false);
226 IO::print(IO::cerr, "No build info here.\n");
231 main_pkg->configure(cmdline_options, conf_all?2:1);
235 usage(0, "builder", false);
241 if(!conf_only && create_targets())
244 PackageList all_reqs=main_pkg->collect_requires();
250 IO::print("Building on %s, for %s\n", native_arch->get_name(), current_arch->get_name());
252 IO::print("%d active packages, %d targets\n", all_reqs.size(), targets.size());
255 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
257 IO::print(" %s", (*i)->get_name());
258 if(dynamic_cast<SourcePackage *>(*i))
261 unsigned to_be_built=0;
262 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
263 if(j->second->get_package()==*i)
266 if(j->second->get_rebuild())
271 IO::print(" (%d targets", count);
273 IO::print(", %d to be built", to_be_built);
283 if(!problems.empty())
285 IO::print(IO::cerr, "The following problems were detected:\n");
286 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
287 IO::print(IO::cerr, " %s: %s\n", i->package, i->descr);
289 IO::print(IO::cerr, "Please fix them and try again.\n");
294 exit_code=do_clean();
296 exit_code=do_build();
301 string Builder::run_pkgconfig(const string &pkg, const string &what)
304 argv.push_back("pkg-config");
305 if(what=="cflags" || what=="libs")
306 argv.push_back("--"+what);
307 else if(what=="flags")
309 argv.push_back("--cflags");
310 argv.push_back("--libs");
313 argv.push_back("--variable="+what);
317 IO::print("Running %s\n", join(argv.begin(), argv.end()));
320 string res=run_command(argv, &status);
322 throw Exception(format("pkg-config for package %s failed", pkg));
327 Package *Builder::get_package(const string &name)
329 PackageMap::iterator i=packages.find(format("%s/%s", name, current_arch->get_name()));
330 if(i==packages.end())
331 i=packages.find(name);
332 if(i!=packages.end())
335 FS::Path path=get_package_location(name);
336 if(!path.empty() && !load_build_file(path/"Build"))
338 i=packages.find(name);
339 if(i!=packages.end())
346 // Package source not found - create a binary package
347 pkg=BinaryPackage::from_pkgconfig(*this, name);
351 problem(name, "not found");
354 packages.insert(PackageMap::value_type(name, pkg));
359 Target *Builder::get_target(const string &n) const
361 // XXX Used for getting targets by path. get_target(const FS::Path &)?
362 TargetMap::const_iterator i=targets.find(n);
368 Target *Builder::get_header(const string &include, const FS::Path &from, const list<string> &path)
372 update_hash(hash, from.str());
373 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
374 update_hash(hash, *i);
376 string id=hash+include;
377 TargetMap::iterator i=includes.find(id);
378 if(i!=includes.end())
381 static string cxx_ver;
385 argv.push_back(current_arch->get_tool("CXX"));
386 argv.push_back("--version");
387 cxx_ver=Regex("[0-9]\\.[0-9.]+").match(run_command(argv))[0].str;
388 while(!cxx_ver.empty() && !FS::is_dir(FS::Path("/usr/include/c++")/cxx_ver))
390 string::size_type dot=cxx_ver.rfind('.');
391 if(dot==string::npos)
396 IO::print("C++ version is %s\n", cxx_ver);
399 string fn=include.substr(1);
401 IO::print("Looking for include %s from %s with path %s\n", fn, from, join(path.begin(), path.end()));
404 if(current_arch->is_native())
405 syspath.push_back("/usr/include");
407 syspath.push_back("/usr/"+current_arch->get_prefix()+"/include");
408 syspath.push_back((FS::Path("/usr/include/c++/")/cxx_ver).str());
412 tgt=get_header(FS::Path(from)/fn);
413 for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
414 tgt=get_header(cwd/ *j/fn);
415 for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
416 tgt=get_header(FS::Path(*j)/fn);
418 includes.insert(TargetMap::value_type(id, tgt));
423 Target *Builder::get_library(const string &lib, const list<string> &path, LibMode mode)
426 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
427 update_hash(hash, *i);
429 string id=hash+string(1, mode)+lib;
430 TargetMap::iterator i=libraries.find(id);
431 if(i!=libraries.end())
435 if(current_arch->is_native())
437 syspath.push_back("/lib");
438 syspath.push_back("/usr/lib");
441 syspath.push_back("/usr/"+current_arch->get_prefix()+"/lib");
444 IO::print("Looking for library %s with path %s\n", lib, join(path.begin(), path.end()));
447 for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
448 tgt=get_library(lib, cwd/ *j, mode);
449 for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
450 tgt=get_library(lib, *j, mode);
452 libraries.insert(TargetMap::value_type(id, tgt));
457 const Architecture &Builder::get_architecture(const string &arch) const
459 ArchMap::const_iterator i=archs.find(arch);
461 throw KeyError("Unknown architecture", arch);
466 void Builder::apply_profile_template(Config &config, const string &pt) const
468 vector<string> parts=split(pt, '-');
470 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
472 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
473 if(j==profile_tmpl.end())
476 config.update(j->second);
480 void Builder::problem(const string &p, const string &d)
482 problems.push_back(Problem(p, d));
485 void Builder::add_target(Target *t)
487 targets.insert(TargetMap::value_type(t->get_name(), t));
488 new_tgts.push_back(t);
491 void Builder::usage(const char *reason, const char *argv0, bool brief)
494 IO::print(IO::cerr, "%s\n", reason);
497 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
500 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
501 IO::print(IO::cerr, "Options:\n");
502 IO::print(IO::cerr, helpmsg);
506 FS::Path Builder::get_package_location(const string &name)
509 IO::print("Looking for package %s\n", name);
513 // Try to get source directory with pkgconfig
514 string srcdir=strip(run_pkgconfig(name, "source"));
523 for(list<FS::Path>::const_iterator i=pkg_path.begin(); i!=pkg_path.end(); ++i)
525 list<string> files=list_files(*i);
526 for(list<string>::const_iterator j=files.begin(); j!=files.end(); ++j)
528 FS::Path full=*i / *j;
529 if(FS::exists(full/"Build"))
530 pkg_dirs.push_back(full);
534 IO::print("%d packages found in path\n", pkg_dirs.size());
537 bool msp=!name.compare(0, 3, "msp");
538 for(list<FS::Path>::const_iterator i=pkg_dirs.begin(); i!=pkg_dirs.end(); ++i)
540 string base=basename(*i);
541 unsigned dash=base.rfind('-');
543 if(!base.compare(0, dash, name))
545 else if(msp && !base.compare(0, dash-3, name, 3, string::npos))
552 int Builder::load_build_file(const FS::Path &fn)
556 IO::BufferedFile in(fn.str());
559 IO::print("Reading %s\n", fn);
561 DataFile::Parser parser(in, fn.str());
562 Loader loader(*this, fn.subpath(0, fn.size()-1));
565 catch(const IO::FileNotFound &)
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));
604 // Find dependencies until no new targets are created
605 while(!new_tgts.empty())
607 Target *tgt=new_tgts.front();
608 new_tgts.erase(new_tgts.begin());
610 if(!tgt->get_depends_ready())
611 new_tgts.push_back(tgt);
615 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
617 Target *tgt=get_target((cwd/ *i).str());
620 IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
626 // Make the cmdline target depend on all targets mentioned on the command line
627 Target *cmdline=new VirtualTarget(*this, "cmdline");
628 bool build_world=false;
629 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
631 Target *tgt=get_target(*i);
633 tgt=get_target((cwd/ *i).str());
636 IO::print("I don't know anything about %s\n", *i);
641 cmdline->add_depend(tgt);
646 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
647 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
648 spkg->get_deps_cache().save();
653 Target *Builder::get_header(const FS::Path &fn)
655 Target *tgt=get_target(fn.str());
660 tgt=new SystemHeader(*this, fn.str());
666 Target *Builder::get_library(const string &lib, const FS::Path &path, LibMode mode)
668 // Populate a list of candidate filenames
669 StringList candidates;
673 if(current_arch->get_name()=="win32")
675 candidates.push_back("lib"+lib+".dll");
676 candidates.push_back(lib+".dll");
679 candidates.push_back("lib"+lib+".so");
682 /* Static libraries are always considered, since sometimes shared versions
683 may not be available */
684 candidates.push_back("lib"+lib+".a");
685 if(current_arch->get_name()=="win32")
686 candidates.push_back("lib"+lib+".dll.a");
688 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
690 string full=(path/ *i).str();
691 Target *tgt=get_target(full);
695 Target *real_tgt=tgt;
696 if(Install *inst=dynamic_cast<Install *>(tgt))
697 real_tgt=&inst->get_source();
699 /* Ignore dynamic libraries from local packages unless library mode is
701 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
706 else if(FS::is_reg(full))
708 tgt=new SystemLibrary(*this, full);
716 int Builder::do_build()
718 Target *cmdline=get_target("cmdline");
721 for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
722 if(i->second->is_buildable() && i->second->get_rebuild())
727 IO::print("Already up to date\n");
731 IO::print("Will build %d target%s\n", total, (total!=1 ? "s" : ""));
733 vector<Action *> actions;
742 if(actions.size()<jobs && !fail)
744 Target *tgt=cmdline->get_buildable_target();
747 Action *action=tgt->build();
749 actions.push_back(action);
752 IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
754 else if(actions.empty())
758 Time::sleep(10*Time::msec);
760 for(unsigned i=0; i<actions.size();)
762 int status=actions[i]->check();
768 actions.erase(actions.begin()+i);
771 if(actions.empty() && fail)
782 IO::print("Build failed\n");
783 else if(show_progress)
784 IO::print("Build complete\n");
789 int Builder::do_clean()
791 // Cleaning doesn't care about ordering, so a simpler method can be used
793 set<Target *> clean_tgts;
795 queue.push_back(get_target("cmdline"));
797 while(!queue.empty())
799 Target *tgt=queue.front();
800 queue.erase(queue.begin());
802 if(tgt->is_buildable() && (tgt->get_package()==main_pkg || clean>=2))
803 clean_tgts.insert(tgt);
805 const TargetList &deps=tgt->get_depends();
806 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
807 if(!clean_tgts.count(*i))
811 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
812 if(FileTarget *ft=dynamic_cast<FileTarget *>(*i))
814 Action *action=new Unlink(*this, *ft);
815 while(action->check()<0) ;
822 void Builder::package_help()
824 const Config &config=main_pkg->get_config();
825 const Config::OptionMap &options=config.get_options();
827 IO::print("Required packages:\n ");
828 const PackageList &requires=main_pkg->get_requires();
829 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
831 if(i!=requires.begin())
833 IO::print((*i)->get_name());
835 IO::print("\n\nPackage configuration:\n");
836 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
838 const Config::Option &opt=i->second;
839 IO::print(" %s: %s (%s)", opt.name, opt.descr, opt.value);
840 if(opt.value!=opt.defv)
841 IO::print(" [%s]", opt.defv);
846 Application::RegApp<Builder> Builder::reg;
847 string Builder::usagemsg;
848 string Builder::helpmsg;
851 Builder::Loader::Loader(Builder &b, const FS::Path &s):
855 add("architecture", &Loader::architecture);
856 add("binary_package", &Loader::binpkg);
857 add("profile", &Loader::profile);
858 add("package", &Loader::package);
861 void Builder::Loader::architecture(const string &n)
863 Architecture arch(bld, n);
865 bld.archs.insert(ArchMap::value_type(n, arch));
868 void Builder::Loader::binpkg(const string &n)
870 BinaryPackage *pkg=new BinaryPackage(bld, n);
872 bld.packages.insert(PackageMap::value_type(n, pkg));
875 void Builder::Loader::profile(const string &n)
878 ProfileLoader ldr(prf);
880 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
883 void Builder::Loader::package(const string &n)
885 SourcePackage *pkg=new SourcePackage(bld, n, src);
890 bld.packages.insert(PackageMap::value_type(n, pkg));
894 Builder::ProfileLoader::ProfileLoader(StringMap &p):
897 add("option", &ProfileLoader::option);
900 void Builder::ProfileLoader::option(const string &o, const string &v)
902 profile.insert(StringMap::value_type(o, v));