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"
26 #include "pkgconfiggenerator.h"
27 #include "sharedlibrary.h"
28 #include "sourcepackage.h"
31 #include "virtualtarget.h"
36 Builder::Builder(int argc, char **argv):
37 package_manager(*this),
39 native_arch(*this, string()),
52 create_makefile(false)
56 bool full_paths = false;
57 unsigned max_depth = 5;
58 StringList cmdline_warn;
61 bool no_externals = false;
64 list<string> log_channels;
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('l', "log", log_channels, GetOpt::REQUIRED_ARG).set_help("Set log channels to be displayed.", "LIST");
74 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG).set_help("Don't actually do anything, only show what would be done.");
75 getopt.add_option('s', "silent", silent, GetOpt::NO_ARG).set_help("Don't print any messages other than errors.");
76 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG).set_help("Print more information about what's going on.");
77 getopt.add_option('x', "no-externals", no_externals, GetOpt::NO_ARG).set_help("Do not load external source packages.");
78 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
79 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
80 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
81 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
82 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
83 getopt.add_option( "arch", arch, GetOpt::REQUIRED_ARG).set_help("Architecture to build for.", "ARCH");
84 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG).set_help("Stop after configuring packages.");
85 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG).set_help("Output full paths in analysis.");
86 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG).set_help("Maximum depth to show in analysis.", "NUM");
87 getopt.add_option( "prefix", prfx, GetOpt::REQUIRED_ARG).set_help("Directory to install things to.", "DIR");
88 getopt.add_option( "warnings", cmdline_warn, GetOpt::REQUIRED_ARG).set_help("Compiler warnings to use.", "LIST");
89 usagemsg = getopt.generate_usage(argv[0])+" [<target> ...]";
90 helpmsg = getopt.generate_help();
97 logger.enable_channel("summary");
98 logger.enable_channel("tasks");
102 logger.enable_channel("environment");
103 logger.enable_channel("packages");
104 logger.enable_channel("commands");
108 logger.enable_channel("packagemgr");
109 logger.enable_channel("configure");
113 logger.enable_channel("files");
114 logger.enable_channel("auxcommands");
118 logger.enable_channel("tools");
119 logger.enable_channel("vfs");
121 for(list<string>::const_iterator i=log_channels.begin(); i!=log_channels.end(); ++i)
123 vector<string> parts = split(*i, ',');
124 for(vector<string>::const_iterator j=parts.begin(); j!=parts.end(); ++j)
125 logger.enable_channel(*j);
128 if(!analyze_mode.empty())
130 analyzer = new Analyzer(*this);
132 if(analyze_mode=="deps")
133 analyzer->set_mode(Analyzer::DEPS);
134 else if(analyze_mode=="alldeps")
135 analyzer->set_mode(Analyzer::ALLDEPS);
136 else if(analyze_mode=="rebuild")
137 analyzer->set_mode(Analyzer::REBUILD);
138 else if(analyze_mode=="rdeps")
139 analyzer->set_mode(Analyzer::RDEPS);
141 throw usage_error("Invalid analyze mode");
143 analyzer->set_max_depth(max_depth);
144 analyzer->set_full_paths(full_paths);
146 else if(!clean && !create_makefile)
149 const vector<string> &args = getopt.get_args();
150 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
152 string::size_type equal = i->find('=');
153 if(equal!=string::npos)
154 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
156 cmdline_targets.push_back(*i);
159 if(cmdline_targets.empty())
160 cmdline_targets.push_back("default");
162 if(!work_dir.empty())
167 package_manager.set_no_externals(no_externals);
170 current_arch = &native_arch;
172 current_arch = new Architecture(*this, arch);
174 load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
175 load_build_file((FS::get_user_data_dir("builder")/"rc").str());
179 if(current_arch->is_native())
180 prefix = (FS::get_home_dir()/"local").str();
182 prefix = (FS::get_home_dir()/"local"/current_arch->get_name()).str();
185 prefix = FS::getcwd()/prfx;
187 warnings.push_back("all");
188 warnings.push_back("extra");
189 warnings.push_back("shadow");
190 warnings.push_back("pointer-arith");
191 warnings.push_back("error");
192 for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
194 vector<string> warns = split(*i, ',');
195 warnings.insert(warnings.end(), warns.begin(), warns.end());
198 toolchain.add_tool(new GnuCCompiler(*this, *current_arch));
199 toolchain.add_tool(new GnuCxxCompiler(*this, *current_arch));
200 toolchain.add_tool(new GnuLinker(*this, *current_arch));
201 toolchain.add_tool(new GnuArchiver(*this, *current_arch));
202 toolchain.add_tool(new Copy(*this));
203 toolchain.add_tool(new Tar(*this));
204 toolchain.add_tool(new PkgConfigGenerator(*this));
209 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
216 if(prefix.str()!="/usr")
218 FS::Path pcdir = prefix/"lib"/"pkgconfig";
219 if(const char *pcp = getenv("PKG_CONFIG_PATH"))
221 vector<string> path = split(pcp, ':');
223 for(vector<string>::const_iterator i=path.begin(); (!found && i!=path.end()); ++i)
224 found = (*i==pcdir.str());
227 path.push_back(pcdir.str());
228 setenv("PKG_CONFIG_PATH", join(path.begin(), path.end(), ":").c_str(), true);
232 setenv("PKG_CONFIG_PATH", pcdir.str().c_str(), true);
235 if(load_build_file(cwd/build_file))
239 usage(0, "builder", false);
244 IO::print(IO::cerr, "No build info here.\n");
249 main_pkg->configure(cmdline_options, conf_all?2:1);
253 usage(0, "builder", false);
265 logger.log("environment", format("Building on %s, for %s%s", native_arch.get_name(),
266 current_arch->get_name(), (current_arch->is_native() ? " (native)" : "")));
267 logger.log("environment", format("Prefix is %s", prefix));
269 const PackageManager::PackageMap &packages = package_manager.get_packages();
270 list<string> package_details;
271 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
273 if(!i->second || !i->second->is_configured())
276 string line = i->second->get_name();
277 if(dynamic_cast<SourcePackage *>(i->second))
282 unsigned to_be_built = 0;
283 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
284 if(j->second->get_package()==i->second)
287 if(j->second->needs_rebuild())
292 line += format(" (%d targets", count);
294 line += format(", %d to be built", to_be_built);
299 package_details.push_back(line);
302 logger.log("summary", format("%d active packages, %d targets", package_details.size(), targets.size()));
303 for(list<string>::const_iterator i=package_details.begin(); i!=package_details.end(); ++i)
304 logger.log("packages", *i);
309 if(!problems.empty())
311 IO::print(IO::cerr, "The following problems were detected:\n");
312 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
313 IO::print(IO::cerr, " %s: %s\n", i->package, i->descr);
315 IO::print(IO::cerr, "Please fix them and try again.\n");
320 exit_code = do_clean();
322 exit_code = do_build();
327 Target *Builder::get_target(const string &n) const
329 TargetMap::const_iterator i = targets.find(n);
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));
354 void Builder::add_target(Target *t)
356 targets.insert(TargetMap::value_type(t->get_name(), t));
359 void Builder::usage(const char *reason, const char *argv0, bool brief)
362 IO::print(IO::cerr, "%s\n", reason);
365 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
368 IO::print(IO::cerr, "Builder 1.0\n\n");
369 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
370 IO::print(IO::cerr, "Options:\n");
371 IO::print(IO::cerr, helpmsg);
375 int Builder::load_build_file(const FS::Path &fn)
380 IO::BufferedFile in(fn.str());
382 logger.log("files", format("Reading %s", fn));
384 DataFile::Parser parser(in, fn.str());
385 Loader loader(*this, fn.subpath(0, fn.size()-1));
391 int Builder::create_targets()
393 Target *world = new VirtualTarget(*this, "world");
395 Target *def_tgt = new VirtualTarget(*this, "default");
396 world->add_depend(*def_tgt);
398 Target *install = new VirtualTarget(*this, "install");
399 world->add_depend(*install);
401 Target *tarballs = new VirtualTarget(*this, "tarballs");
402 world->add_depend(*tarballs);
404 const PackageManager::PackageMap &packages = package_manager.get_packages();
405 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
406 if(i->second && i->second->is_configured())
407 i->second->create_targets();
409 // Make the cmdline target depend on all targets mentioned on the command line
410 Target *cmdline = new VirtualTarget(*this, "cmdline");
411 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
413 Target *tgt = get_target(*i);
415 tgt = vfs.get_target(*i);
417 tgt = vfs.get_target(cwd/ *i);
420 IO::print("I don't know anything about %s\n", *i);
424 cmdline->add_depend(*tgt);
430 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
432 FileTarget *tgt = vfs.get_target(cwd/ *i);
435 IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
443 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
444 if(i->second->is_buildable() && !i->second->needs_rebuild())
445 i->second->force_rebuild();
450 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
451 i->second->save_caches();
457 int Builder::do_build()
459 Target *cmdline = get_target("cmdline");
462 for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
463 if(i->second->is_buildable() && i->second->needs_rebuild())
468 logger.log("summary", "Already up to date");
471 logger.log("summary", format("Will build %d target%s", total, (total!=1 ? "s" : "")));
473 vector<Task *> tasks;
482 if(tasks.size()<jobs && !fail)
484 Target *tgt = cmdline->get_buildable_target();
488 logger.log("tasks", format("%-4s %s", tgt->get_tool()->get_tag(), tgt->get_name()));
489 Task *task = tgt->build();
492 logger.log("commands", format("%s", task->get_command()));
495 task->signal_finished.emit(true);
501 tasks.push_back(task);
506 IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
508 else if(tasks.empty())
512 Time::sleep(10*Time::msec);
514 for(unsigned i=0; i<tasks.size();)
516 Task::Status status = tasks[i]->check();
517 if(status!=Task::RUNNING)
522 tasks.erase(tasks.begin()+i);
523 if(status==Task::ERROR)
525 if(tasks.empty() && fail)
536 logger.log("summary", "Build failed");
537 else if(show_progress)
538 logger.log("summary", "Build complete");
543 int Builder::do_clean()
545 // Cleaning doesn't care about ordering, so a simpler method can be used
547 set<Target *> clean_tgts;
548 list<Target *> queue;
549 queue.push_back(get_target("cmdline"));
551 while(!queue.empty())
553 Target *tgt = queue.front();
554 queue.erase(queue.begin());
556 if(tgt->is_buildable() && (tgt->get_package()==main_pkg || clean>=2))
557 clean_tgts.insert(tgt);
559 const Target::Dependencies &deps = tgt->get_depends();
560 for(list<Target *>::const_iterator i=deps.begin(); i!=deps.end(); ++i)
561 if(!clean_tgts.count(*i))
565 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
566 if(FileTarget *ft = dynamic_cast<FileTarget *>(*i))
568 FS::unlink(ft->get_path());
573 void Builder::package_help()
575 const Config &config = main_pkg->get_config();
576 const Config::OptionMap &options = config.get_options();
578 IO::print("Required packages:\n ");
579 const PackageList &requires = main_pkg->get_requires();
580 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
582 if(i!=requires.begin())
584 IO::print((*i)->get_name());
586 IO::print("\n\nPackage configuration:\n");
587 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
589 const Config::Option &opt = i->second;
590 IO::print(" %s: %s (%s)", opt.name, opt.descr, opt.value);
591 if(opt.value!=opt.defv)
592 IO::print(" [%s]", opt.defv);
597 string Builder::usagemsg;
598 string Builder::helpmsg;
601 Builder::Loader::Loader(Builder &b, const FS::Path &s):
602 DataFile::ObjectLoader<Builder>(b),
605 add("architecture", &Loader::architecture);
606 add("binary_package", &Loader::binpkg);
607 add("profile", &Loader::profile);
608 add("package", &Loader::package);
611 void Builder::Loader::architecture(const string &n)
613 if(obj.current_arch->match_name(n))
614 load_sub(*obj.current_arch);
617 void Builder::Loader::binpkg(const string &n)
619 BinaryPackage *pkg = new BinaryPackage(obj, n);
623 void Builder::Loader::profile(const string &n)
626 ProfileLoader ldr(prf);
628 obj.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
631 void Builder::Loader::package(const string &n)
633 SourcePackage *pkg = new SourcePackage(obj, n, src);
641 Builder::ProfileLoader::ProfileLoader(StringMap &p):
644 add("option", &ProfileLoader::option);
647 void Builder::ProfileLoader::option(const string &o, const string &v)
649 profile.insert(StringMap::value_type(o, v));