3 #include <msp/core/getopt.h>
4 #include <msp/datafile/parser.h>
5 #include <msp/fs/dir.h>
6 #include <msp/fs/stat.h>
7 #include <msp/fs/utils.h>
8 #include <msp/io/buffered.h>
9 #include <msp/io/file.h>
10 #include <msp/io/print.h>
11 #include <msp/strings/format.h>
12 #include <msp/strings/regex.h>
13 #include <msp/strings/utils.h>
14 #include <msp/time/units.h>
15 #include <msp/time/utils.h>
17 #include "binarypackage.h"
20 #include "gnuarchiver.h"
21 #include "gnuccompiler.h"
22 #include "gnucxxcompiler.h"
23 #include "gnulinker.h"
28 #include "pkgconfig.h"
29 #include "pkgconfiggenerator.h"
30 #include "sharedlibrary.h"
31 #include "sourcepackage.h"
32 #include "systemlibrary.h"
35 #include "virtualtarget.h"
40 Builder::Builder(int argc, char **argv):
42 native_arch(*this, string()),
56 create_makefile(false)
60 bool full_paths = false;
61 unsigned max_depth = 5;
62 StringList cmdline_warn;
67 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG).set_help("Perform analysis. MODE can be deps, alldeps or rebuild.", "MODE");
68 getopt.add_option('b', "build", build, GetOpt::NO_ARG).set_help("Perform build even if doing analysis.");
69 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG).set_help("Clean buildable targets.");
70 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG).set_help("Read info from FILE instead of Build.", "FILE");
71 getopt.add_option('h', "help", help, GetOpt::NO_ARG).set_help("Print this message.");
72 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG).set_help("Run NUM commands at once, whenever possible.", "NUM");
73 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG).set_help("Don't actually do anything, only show what would be done.");
74 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG).set_help("Print more information about what's going on.");
75 getopt.add_option('x', "no-externals", no_externals, GetOpt::NO_ARG).set_help("Do not load external source packages.");
76 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
77 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
78 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
79 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
80 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
81 getopt.add_option( "arch", arch, GetOpt::REQUIRED_ARG).set_help("Architecture to build for.", "ARCH");
82 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG).set_help("Stop after configuring packages.");
83 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG).set_help("Output full paths in analysis.");
84 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG).set_help("Maximum depth to show in analysis.", "NUM");
85 getopt.add_option( "prefix", prfx, GetOpt::REQUIRED_ARG).set_help("Directory to install things to.", "DIR");
86 getopt.add_option( "warnings", cmdline_warn, GetOpt::REQUIRED_ARG).set_help("Compiler warnings to use.", "LIST");
87 usagemsg = getopt.generate_usage(argv[0])+" [<target> ...]";
88 helpmsg = getopt.generate_help();
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 usage_error("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 string::size_type 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())
130 toolchain.add_tool(new GnuCCompiler(*this));
131 toolchain.add_tool(new GnuCxxCompiler(*this));
132 toolchain.add_tool(new GnuLinker(*this));
133 toolchain.add_tool(new GnuArchiver(*this));
134 toolchain.add_tool(new Copy(*this));
135 toolchain.add_tool(new Tar(*this));
136 toolchain.add_tool(new PkgConfigGenerator(*this));
138 load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
139 load_build_file((FS::get_user_data_dir("builder")/"rc").str());
142 current_arch = &native_arch;
144 current_arch = new Architecture(*this, arch);
146 if(!current_arch->is_native())
148 for(StringMap::const_iterator i=cross_prefixes.begin(); i!=cross_prefixes.end(); ++i)
149 if(current_arch->match_name(i->first))
151 current_arch->set_cross_prefix(i->second);
158 if(current_arch->is_native())
159 prefix = (FS::get_home_dir()/"local").str();
161 prefix = (FS::get_home_dir()/"local"/current_arch->get_name()).str();
164 prefix = FS::getcwd()/prfx;
166 warnings.push_back("all");
167 warnings.push_back("extra");
168 warnings.push_back("shadow");
169 warnings.push_back("pointer-arith");
170 warnings.push_back("error");
171 for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
173 vector<string> warns = split(*i, ',');
174 warnings.insert(warnings.end(), warns.begin(), warns.end());
177 pkg_path.push_back(cwd/".");
178 pkg_path.push_back(cwd/"..");
183 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
185 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
192 if(prefix.str()!="/usr")
194 FS::Path pcdir = prefix/"lib"/"pkgconfig";
195 if(const char *pcp = getenv("PKG_CONFIG_PATH"))
197 vector<string> path = split(pcp, ':');
199 for(vector<string>::const_iterator i=path.begin(); (!found && i!=path.end()); ++i)
200 found = (*i==pcdir.str());
203 path.push_back(pcdir.str());
204 setenv("PKG_CONFIG_PATH", join(path.begin(), path.end(), ":").c_str(), true);
208 setenv("PKG_CONFIG_PATH", pcdir.str().c_str(), true);
211 if(load_build_file(cwd/build_file))
215 usage(0, "builder", false);
220 IO::print(IO::cerr, "No build info here.\n");
225 main_pkg->configure(cmdline_options, conf_all?2:1);
229 usage(0, "builder", false);
243 IO::print("Building on %s, for %s%s\n", native_arch.get_name(),
244 current_arch->get_name(), (current_arch->is_native() ? " (native)" : ""));
245 IO::print("Prefix is %s\n", prefix);
250 unsigned n_packages = 0;
251 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
252 if(i->second && i->second->is_configured())
254 IO::print("%d active packages, %d targets\n", n_packages, targets.size());
259 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
261 if(!i->second->is_configured())
264 IO::print(" %s", i->second->get_name());
265 if(dynamic_cast<SourcePackage *>(i->second))
268 unsigned to_be_built = 0;
269 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
270 if(j->second->get_package()==i->second)
273 if(j->second->get_rebuild())
278 IO::print(" (%d targets", count);
280 IO::print(", %d to be built", to_be_built);
290 if(!problems.empty())
292 IO::print(IO::cerr, "The following problems were detected:\n");
293 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
294 IO::print(IO::cerr, " %s: %s\n", i->package, i->descr);
296 IO::print(IO::cerr, "Please fix them and try again.\n");
301 exit_code = do_clean();
303 exit_code = do_build();
308 string Builder::run_pkgconfig(const string &pkg, const string &what)
311 argv.push_back("pkg-config");
312 if(what=="cflags" || what=="libs")
313 argv.push_back("--"+what);
314 else if(what=="flags")
316 argv.push_back("--cflags");
317 argv.push_back("--libs");
320 argv.push_back("--variable="+what);
324 IO::print("Running %s\n", join(argv.begin(), argv.end()));
327 string res = run_command(argv, &status);
329 throw runtime_error(format("pkg-config for package %s failed", pkg));
334 Package *Builder::get_package(const string &name)
336 PackageMap::iterator i = packages.find(format("%s/%s", name, current_arch->get_system()));
337 if(i==packages.end())
338 i = packages.find(name);
339 if(i!=packages.end())
344 FS::Path path = get_package_location(name);
345 if(!path.empty() && !load_build_file(path/"Build"))
347 i = packages.find(name);
348 if(i!=packages.end())
356 // Package source not found - create a binary package
357 pkg = BinaryPackage::from_pkgconfig(*this, name);
361 problem(name, "not found");
364 packages.insert(PackageMap::value_type(name, pkg));
369 Target *Builder::get_target(const string &n) const
371 TargetMap::const_iterator i = targets.find(n);
377 void Builder::apply_profile_template(Config &config, const string &pt) const
379 vector<string> parts = split(pt, '-');
381 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
383 ProfileTemplateMap::const_iterator j = profile_tmpl.find(*i);
384 if(j==profile_tmpl.end())
387 config.update(j->second);
391 void Builder::problem(const string &p, const string &d)
393 problems.push_back(Problem(p, d));
396 void Builder::add_target(Target *t)
398 targets.insert(TargetMap::value_type(t->get_name(), t));
399 new_tgts.push_back(t);
402 void Builder::usage(const char *reason, const char *argv0, bool brief)
405 IO::print(IO::cerr, "%s\n", reason);
408 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
411 IO::print(IO::cerr, "Builder 1.0\n\n");
412 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
413 IO::print(IO::cerr, "Options:\n");
414 IO::print(IO::cerr, helpmsg);
418 FS::Path Builder::get_package_location(const string &name)
421 IO::print("Looking for package %s\n", name);
425 // Try to get source directory with pkgconfig
426 string srcdir = strip(run_pkgconfig(name, "source"));
435 for(list<FS::Path>::const_iterator i=pkg_path.begin(); i!=pkg_path.end(); ++i)
437 list<string> files = list_files(*i);
438 for(list<string>::const_iterator j=files.begin(); j!=files.end(); ++j)
440 FS::Path full = *i / *j;
441 if(FS::exists(full/"Build"))
442 pkg_dirs.push_back(full);
446 IO::print("%d packages found in path\n", pkg_dirs.size());
449 bool msp = !name.compare(0, 3, "msp");
450 for(list<FS::Path>::const_iterator i=pkg_dirs.begin(); i!=pkg_dirs.end(); ++i)
452 string base = basename(*i);
453 unsigned dash = base.rfind('-');
455 if(!base.compare(0, dash, name))
457 else if(msp && !base.compare(0, dash-3, name, 3, string::npos))
464 int Builder::load_build_file(const FS::Path &fn)
469 IO::BufferedFile in(fn.str());
472 IO::print("Reading %s\n", fn);
474 DataFile::Parser parser(in, fn.str());
475 Loader loader(*this, fn.subpath(0, fn.size()-1));
481 int Builder::create_targets()
483 Target *world = new VirtualTarget(*this, "world");
485 Target *def_tgt = new VirtualTarget(*this, "default");
486 world->add_depend(def_tgt);
488 Target *install = new VirtualTarget(*this, "install");
489 world->add_depend(install);
491 Target *tarballs = new VirtualTarget(*this, "tarballs");
492 world->add_depend(tarballs);
494 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
496 if(!i->second || !i->second->is_configured())
499 SourcePackage *spkg = dynamic_cast<SourcePackage *>(i->second);
503 const ComponentList &components = spkg->get_components();
504 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
507 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
509 PkgConfig *pc = new PkgConfig(*this, *spkg);
510 install->add_depend(new Install(*this, *spkg, *pc));
514 // Find dependencies until no new targets are created
515 while(!new_tgts.empty())
517 Target *tgt = new_tgts.front();
518 new_tgts.erase(new_tgts.begin());
520 if(!tgt->get_depends_ready())
521 new_tgts.push_back(tgt);
525 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
527 FileTarget *tgt = vfs.get_target(cwd/ *i);
530 IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
536 // Make the cmdline target depend on all targets mentioned on the command line
537 Target *cmdline = new VirtualTarget(*this, "cmdline");
538 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
540 Target *tgt = get_target(*i);
542 tgt = vfs.get_target(*i);
544 tgt = vfs.get_target(cwd/ *i);
547 IO::print("I don't know anything about %s\n", *i);
551 cmdline->add_depend(tgt);
556 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
557 if(SourcePackage *spkg = dynamic_cast<SourcePackage *>(i->second))
558 spkg->get_deps_cache().save();
563 int Builder::do_build()
565 Target *cmdline = get_target("cmdline");
568 for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
569 if(i->second->is_buildable() && i->second->get_rebuild())
574 IO::print("Already up to date\n");
578 IO::print("Will build %d target%s\n", total, (total!=1 ? "s" : ""));
580 vector<Task *> tasks;
589 if(tasks.size()<jobs && !fail)
591 Target *tgt = cmdline->get_buildable_target();
595 IO::print("[%-10s] [%-4s] %s\n", tgt->get_package()->get_name(), tgt->get_tool()->get_tag(), tgt->get_name());
596 Task *task = tgt->build();
598 tasks.push_back(task);
601 IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
603 else if(tasks.empty())
607 Time::sleep(10*Time::msec);
609 for(unsigned i=0; i<tasks.size();)
611 Task::Status status = tasks[i]->check();
612 if(status!=Task::RUNNING)
617 tasks.erase(tasks.begin()+i);
618 if(status==Task::ERROR)
620 if(tasks.empty() && fail)
631 IO::print("Build failed\n");
632 else if(show_progress)
633 IO::print("Build complete\n");
638 int Builder::do_clean()
640 // Cleaning doesn't care about ordering, so a simpler method can be used
642 set<Target *> clean_tgts;
644 queue.push_back(get_target("cmdline"));
646 while(!queue.empty())
648 Target *tgt = queue.front();
649 queue.erase(queue.begin());
651 if(tgt->is_buildable() && (tgt->get_package()==main_pkg || clean>=2))
652 clean_tgts.insert(tgt);
654 const TargetList &deps = tgt->get_depends();
655 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
656 if(!clean_tgts.count(*i))
660 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
661 if(FileTarget *ft = dynamic_cast<FileTarget *>(*i))
662 unlink(ft->get_path());
667 void Builder::package_help()
669 const Config &config = main_pkg->get_config();
670 const Config::OptionMap &options = config.get_options();
672 IO::print("Required packages:\n ");
673 const PackageList &requires = main_pkg->get_requires();
674 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
676 if(i!=requires.begin())
678 IO::print((*i)->get_name());
680 IO::print("\n\nPackage configuration:\n");
681 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
683 const Config::Option &opt = i->second;
684 IO::print(" %s: %s (%s)", opt.name, opt.descr, opt.value);
685 if(opt.value!=opt.defv)
686 IO::print(" [%s]", opt.defv);
691 string Builder::usagemsg;
692 string Builder::helpmsg;
695 Builder::Loader::Loader(Builder &b, const FS::Path &s):
699 add("binary_package", &Loader::binpkg);
700 add("cross_prefix", &Loader::cross_prefix);
701 add("profile", &Loader::profile);
702 add("package", &Loader::package);
705 void Builder::Loader::binpkg(const string &n)
707 BinaryPackage *pkg = new BinaryPackage(bld, n);
709 bld.packages.insert(PackageMap::value_type(n, pkg));
712 void Builder::Loader::cross_prefix(const string &a, const string &p)
714 bld.cross_prefixes[a] = p;
717 void Builder::Loader::profile(const string &n)
720 ProfileLoader ldr(prf);
722 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
725 void Builder::Loader::package(const string &n)
727 SourcePackage *pkg = new SourcePackage(bld, n, src);
732 bld.packages.insert(PackageMap::value_type(n, pkg));
736 Builder::ProfileLoader::ProfileLoader(StringMap &p):
739 add("option", &ProfileLoader::option);
742 void Builder::ProfileLoader::option(const string &o, const string &v)
744 profile.insert(StringMap::value_type(o, v));