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"
24 #include "installedfile.h"
27 #include "pkgconfig.h"
28 #include "pkgconfiggenerator.h"
29 #include "sharedlibrary.h"
30 #include "sourcepackage.h"
33 #include "virtualtarget.h"
38 Builder::Builder(int argc, char **argv):
40 native_arch(*this, string()),
54 create_makefile(false)
58 bool full_paths = false;
59 unsigned max_depth = 5;
60 StringList cmdline_warn;
65 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG).set_help("Perform analysis. MODE can be deps, alldeps or rebuild.", "MODE");
66 getopt.add_option('b', "build", build, GetOpt::NO_ARG).set_help("Perform build even if doing analysis.");
67 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG).set_help("Clean buildable targets.");
68 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG).set_help("Read info from FILE instead of Build.", "FILE");
69 getopt.add_option('h', "help", help, GetOpt::NO_ARG).set_help("Print this message.");
70 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG).set_help("Run NUM commands at once, whenever possible.", "NUM");
71 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG).set_help("Don't actually do anything, only show what would be done.");
72 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG).set_help("Print more information about what's going on.");
73 getopt.add_option('x', "no-externals", no_externals, GetOpt::NO_ARG).set_help("Do not load external source packages.");
74 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
75 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
76 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
77 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
78 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
79 getopt.add_option( "arch", arch, GetOpt::REQUIRED_ARG).set_help("Architecture to build for.", "ARCH");
80 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG).set_help("Stop after configuring packages.");
81 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG).set_help("Output full paths in analysis.");
82 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG).set_help("Maximum depth to show in analysis.", "NUM");
83 getopt.add_option( "prefix", prfx, GetOpt::REQUIRED_ARG).set_help("Directory to install things to.", "DIR");
84 getopt.add_option( "warnings", cmdline_warn, GetOpt::REQUIRED_ARG).set_help("Compiler warnings to use.", "LIST");
85 usagemsg = getopt.generate_usage(argv[0])+" [<target> ...]";
86 helpmsg = getopt.generate_help();
89 if(!analyze_mode.empty())
91 analyzer = new Analyzer(*this);
93 if(analyze_mode=="deps")
94 analyzer->set_mode(Analyzer::DEPS);
95 else if(analyze_mode=="alldeps")
96 analyzer->set_mode(Analyzer::ALLDEPS);
97 else if(analyze_mode=="rebuild")
98 analyzer->set_mode(Analyzer::REBUILD);
99 else if(analyze_mode=="rdeps")
100 analyzer->set_mode(Analyzer::RDEPS);
102 throw usage_error("Invalid analyze mode");
104 analyzer->set_max_depth(max_depth);
105 analyzer->set_full_paths(full_paths);
107 else if(!clean && !create_makefile)
110 const vector<string> &args = getopt.get_args();
111 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
113 string::size_type equal = i->find('=');
114 if(equal!=string::npos)
115 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
117 cmdline_targets.push_back(*i);
120 if(cmdline_targets.empty())
121 cmdline_targets.push_back("default");
123 if(!work_dir.empty())
128 toolchain.add_tool(new GnuCCompiler(*this));
129 toolchain.add_tool(new GnuCxxCompiler(*this));
130 toolchain.add_tool(new GnuLinker(*this));
131 toolchain.add_tool(new GnuArchiver(*this));
132 toolchain.add_tool(new Copy(*this));
133 toolchain.add_tool(new Tar(*this));
134 toolchain.add_tool(new PkgConfigGenerator(*this));
136 load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
137 load_build_file((FS::get_user_data_dir("builder")/"rc").str());
140 current_arch = &native_arch;
142 current_arch = new Architecture(*this, arch);
144 if(!current_arch->is_native())
146 for(StringMap::const_iterator i=cross_prefixes.begin(); i!=cross_prefixes.end(); ++i)
147 if(current_arch->match_name(i->first))
149 current_arch->set_cross_prefix(i->second);
156 if(current_arch->is_native())
157 prefix = (FS::get_home_dir()/"local").str();
159 prefix = (FS::get_home_dir()/"local"/current_arch->get_name()).str();
162 prefix = FS::getcwd()/prfx;
164 warnings.push_back("all");
165 warnings.push_back("extra");
166 warnings.push_back("shadow");
167 warnings.push_back("pointer-arith");
168 warnings.push_back("error");
169 for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
171 vector<string> warns = split(*i, ',');
172 warnings.insert(warnings.end(), warns.begin(), warns.end());
175 pkg_path.push_back(cwd/".");
176 pkg_path.push_back(cwd/"..");
181 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
183 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
190 if(prefix.str()!="/usr")
192 FS::Path pcdir = prefix/"lib"/"pkgconfig";
193 if(const char *pcp = getenv("PKG_CONFIG_PATH"))
195 vector<string> path = split(pcp, ':');
197 for(vector<string>::const_iterator i=path.begin(); (!found && i!=path.end()); ++i)
198 found = (*i==pcdir.str());
201 path.push_back(pcdir.str());
202 setenv("PKG_CONFIG_PATH", join(path.begin(), path.end(), ":").c_str(), true);
206 setenv("PKG_CONFIG_PATH", pcdir.str().c_str(), true);
209 if(load_build_file(cwd/build_file))
213 usage(0, "builder", false);
218 IO::print(IO::cerr, "No build info here.\n");
223 main_pkg->configure(cmdline_options, conf_all?2:1);
227 usage(0, "builder", false);
241 IO::print("Building on %s, for %s%s\n", native_arch.get_name(),
242 current_arch->get_name(), (current_arch->is_native() ? " (native)" : ""));
243 IO::print("Prefix is %s\n", prefix);
248 unsigned n_packages = 0;
249 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
250 if(i->second && i->second->is_configured())
252 IO::print("%d active packages, %d targets\n", n_packages, targets.size());
257 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
259 if(!i->second->is_configured())
262 IO::print(" %s", i->second->get_name());
263 if(dynamic_cast<SourcePackage *>(i->second))
266 unsigned to_be_built = 0;
267 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
268 if(j->second->get_package()==i->second)
271 if(j->second->needs_rebuild())
276 IO::print(" (%d targets", count);
278 IO::print(", %d to be built", to_be_built);
288 if(!problems.empty())
290 IO::print(IO::cerr, "The following problems were detected:\n");
291 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
292 IO::print(IO::cerr, " %s: %s\n", i->package, i->descr);
294 IO::print(IO::cerr, "Please fix them and try again.\n");
299 exit_code = do_clean();
301 exit_code = do_build();
306 string Builder::run_pkgconfig(const string &pkg, const string &what)
309 argv.push_back("pkg-config");
310 if(what=="cflags" || what=="libs")
311 argv.push_back("--"+what);
312 else if(what=="flags")
314 argv.push_back("--cflags");
315 argv.push_back("--libs");
318 argv.push_back("--variable="+what);
322 IO::print("Running %s\n", join(argv.begin(), argv.end()));
325 string res = run_command(argv, &status);
327 throw runtime_error(format("pkg-config for package %s failed", pkg));
332 Package *Builder::get_package(const string &name)
334 PackageMap::iterator i = packages.find(format("%s/%s", name, current_arch->get_system()));
335 if(i==packages.end())
336 i = packages.find(name);
337 if(i!=packages.end())
342 FS::Path path = get_package_location(name);
343 if(!path.empty() && !load_build_file(path/"Build"))
345 i = packages.find(name);
346 if(i!=packages.end())
354 // Package source not found - create a binary package
355 pkg = BinaryPackage::from_pkgconfig(*this, name);
359 problem(name, "not found");
362 packages.insert(PackageMap::value_type(name, pkg));
367 Target *Builder::get_target(const string &n) const
369 TargetMap::const_iterator i = targets.find(n);
375 void Builder::apply_profile_template(Config &config, const string &pt) const
377 vector<string> parts = split(pt, '-');
379 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
381 ProfileTemplateMap::const_iterator j = profile_tmpl.find(*i);
382 if(j==profile_tmpl.end())
385 config.update(j->second);
389 void Builder::problem(const string &p, const string &d)
391 problems.push_back(Problem(p, d));
394 void Builder::add_target(Target *t)
396 targets.insert(TargetMap::value_type(t->get_name(), t));
397 new_tgts.push_back(t);
400 void Builder::usage(const char *reason, const char *argv0, bool brief)
403 IO::print(IO::cerr, "%s\n", reason);
406 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
409 IO::print(IO::cerr, "Builder 1.0\n\n");
410 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
411 IO::print(IO::cerr, "Options:\n");
412 IO::print(IO::cerr, helpmsg);
416 FS::Path Builder::get_package_location(const string &name)
419 IO::print("Looking for package %s\n", name);
423 // Try to get source directory with pkgconfig
424 string srcdir = strip(run_pkgconfig(name, "source"));
433 for(list<FS::Path>::const_iterator i=pkg_path.begin(); i!=pkg_path.end(); ++i)
435 list<string> files = list_files(*i);
436 for(list<string>::const_iterator j=files.begin(); j!=files.end(); ++j)
438 FS::Path full = *i / *j;
439 if(FS::exists(full/"Build"))
440 pkg_dirs.push_back(full);
444 IO::print("%d packages found in path\n", pkg_dirs.size());
447 bool msp = !name.compare(0, 3, "msp");
448 for(list<FS::Path>::const_iterator i=pkg_dirs.begin(); i!=pkg_dirs.end(); ++i)
450 string base = basename(*i);
451 unsigned dash = base.rfind('-');
453 if(!base.compare(0, dash, name))
455 else if(msp && !base.compare(0, dash-3, name, 3, string::npos))
462 int Builder::load_build_file(const FS::Path &fn)
467 IO::BufferedFile in(fn.str());
470 IO::print("Reading %s\n", fn);
472 DataFile::Parser parser(in, fn.str());
473 Loader loader(*this, fn.subpath(0, fn.size()-1));
479 int Builder::create_targets()
481 Target *world = new VirtualTarget(*this, "world");
483 Target *def_tgt = new VirtualTarget(*this, "default");
484 world->add_depend(def_tgt);
486 Target *install = new VirtualTarget(*this, "install");
487 world->add_depend(install);
489 Target *tarballs = new VirtualTarget(*this, "tarballs");
490 world->add_depend(tarballs);
492 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
494 if(!i->second || !i->second->is_configured())
497 SourcePackage *spkg = dynamic_cast<SourcePackage *>(i->second);
501 const ComponentList &components = spkg->get_components();
502 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
505 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
507 PkgConfig *pc = new PkgConfig(*this, *spkg);
508 install->add_depend(new InstalledFile(*this, *spkg, *pc));
513 // XXX This does not currently work with targets found during dependency discovery
514 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
516 FileTarget *tgt = vfs.get_target(cwd/ *i);
519 IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
525 // Make the cmdline target depend on all targets mentioned on the command line
526 Target *cmdline = new VirtualTarget(*this, "cmdline");
527 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
529 Target *tgt = get_target(*i);
531 tgt = vfs.get_target(*i);
533 tgt = vfs.get_target(cwd/ *i);
536 IO::print("I don't know anything about %s\n", *i);
540 cmdline->add_depend(tgt);
545 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
546 if(SourcePackage *spkg = dynamic_cast<SourcePackage *>(i->second))
547 spkg->get_deps_cache().save();
552 int Builder::do_build()
554 Target *cmdline = get_target("cmdline");
557 for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
558 if(i->second->is_buildable() && i->second->needs_rebuild())
563 IO::print("Already up to date\n");
567 IO::print("Will build %d target%s\n", total, (total!=1 ? "s" : ""));
569 vector<Task *> tasks;
578 if(tasks.size()<jobs && !fail)
580 Target *tgt = cmdline->get_buildable_target();
584 IO::print("[%-10s] [%-4s] %s\n", tgt->get_package()->get_name(), tgt->get_tool()->get_tag(), tgt->get_name());
585 Task *task = tgt->build();
587 tasks.push_back(task);
590 IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
592 else if(tasks.empty())
596 Time::sleep(10*Time::msec);
598 for(unsigned i=0; i<tasks.size();)
600 Task::Status status = tasks[i]->check();
601 if(status!=Task::RUNNING)
606 tasks.erase(tasks.begin()+i);
607 if(status==Task::ERROR)
609 if(tasks.empty() && fail)
620 IO::print("Build failed\n");
621 else if(show_progress)
622 IO::print("Build complete\n");
627 int Builder::do_clean()
629 // Cleaning doesn't care about ordering, so a simpler method can be used
631 set<Target *> clean_tgts;
632 list<Target *> queue;
633 queue.push_back(get_target("cmdline"));
635 while(!queue.empty())
637 Target *tgt = queue.front();
638 queue.erase(queue.begin());
640 if(tgt->is_buildable() && (tgt->get_package()==main_pkg || clean>=2))
641 clean_tgts.insert(tgt);
643 const Target::Dependencies &deps = tgt->get_depends();
644 for(list<Target *>::const_iterator i=deps.begin(); i!=deps.end(); ++i)
645 if(!clean_tgts.count(*i))
649 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
650 if(FileTarget *ft = dynamic_cast<FileTarget *>(*i))
651 unlink(ft->get_path());
656 void Builder::package_help()
658 const Config &config = main_pkg->get_config();
659 const Config::OptionMap &options = config.get_options();
661 IO::print("Required packages:\n ");
662 const PackageList &requires = main_pkg->get_requires();
663 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
665 if(i!=requires.begin())
667 IO::print((*i)->get_name());
669 IO::print("\n\nPackage configuration:\n");
670 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
672 const Config::Option &opt = i->second;
673 IO::print(" %s: %s (%s)", opt.name, opt.descr, opt.value);
674 if(opt.value!=opt.defv)
675 IO::print(" [%s]", opt.defv);
680 string Builder::usagemsg;
681 string Builder::helpmsg;
684 Builder::Loader::Loader(Builder &b, const FS::Path &s):
688 add("binary_package", &Loader::binpkg);
689 add("cross_prefix", &Loader::cross_prefix);
690 add("profile", &Loader::profile);
691 add("package", &Loader::package);
694 void Builder::Loader::binpkg(const string &n)
696 BinaryPackage *pkg = new BinaryPackage(bld, n);
698 bld.packages.insert(PackageMap::value_type(n, pkg));
701 void Builder::Loader::cross_prefix(const string &a, const string &p)
703 bld.cross_prefixes[a] = p;
706 void Builder::Loader::profile(const string &n)
709 ProfileLoader ldr(prf);
711 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
714 void Builder::Loader::package(const string &n)
716 SourcePackage *pkg = new SourcePackage(bld, n, src);
721 bld.packages.insert(PackageMap::value_type(n, pkg));
725 Builder::ProfileLoader::ProfileLoader(StringMap &p):
728 add("option", &ProfileLoader::option);
731 void Builder::ProfileLoader::option(const string &o, const string &v)
733 profile.insert(StringMap::value_type(o, v));