2 #include <msp/core/getopt.h>
3 #include <msp/datafile/parser.h>
4 #include <msp/fs/dir.h>
5 #include <msp/fs/stat.h>
6 #include <msp/fs/utils.h>
7 #include <msp/io/buffered.h>
8 #include <msp/io/file.h>
9 #include <msp/io/print.h>
10 #include <msp/strings/format.h>
11 #include <msp/strings/regex.h>
12 #include <msp/strings/utils.h>
13 #include <msp/time/units.h>
14 #include <msp/time/utils.h>
16 #include "binarypackage.h"
19 #include "gnuarchiver.h"
20 #include "gnuccompiler.h"
21 #include "gnucxxcompiler.h"
22 #include "gnulinker.h"
23 #include "installedfile.h"
24 #include "mingwdlltool.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),
38 native_arch(*this, string()),
52 create_makefile(false),
57 bool full_paths = false;
58 unsigned max_depth = 4;
62 bool no_externals = false;
65 list<string> log_channels;
66 string build_type_name;
69 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG).set_help("Perform dependency analysis.", "MODE");
70 getopt.add_option('b', "build", build, GetOpt::NO_ARG).set_help("Perform build even if also doing something else.");
71 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG).set_help("Clean buildable targets.");
72 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG).set_help("Read build instructions from FILE.", "FILE");
73 getopt.add_option('h', "help", help, GetOpt::NO_ARG).set_help("Print this message.");
74 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG).set_help("Run up to NUM tasks in parallel.", "NUM");
75 getopt.add_option('l', "log", log_channels, GetOpt::REQUIRED_ARG).set_help("Enable listed log channels.", "LIST");
76 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG).set_help("Show what would be done without actually doing it.");
77 getopt.add_option('s', "silent", silent, GetOpt::NO_ARG).set_help("Don't print any messages other than errors.");
78 getopt.add_option('t', "build-type", build_type_name, GetOpt::REQUIRED_ARG).set_help("Set build type.", "TYPE");
79 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG).set_help("Print more information about what's going on.");
80 getopt.add_option('x', "no-externals", no_externals, GetOpt::NO_ARG).set_help("Do not load external source packages.");
81 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
82 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
83 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
84 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
85 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
86 getopt.add_option( "arch", arch, GetOpt::REQUIRED_ARG).set_help("Build for architecture ARCH.", "ARCH");
87 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG).set_help("Stop after configuring packages.");
88 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG).set_help("Output full paths in analysis.");
89 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG).set_help("Show up to NUM levels in analysis.", "NUM");
90 getopt.add_option( "prefix", prfx, GetOpt::REQUIRED_ARG).set_help("Install things to DIR.", "DIR");
91 getopt.add_option( "tempdir", temp_str, GetOpt::REQUIRED_ARG).set_help("Store temporary files in DIR.", "DIR");
92 usagemsg = getopt.generate_usage(argv[0])+" [<target> ...]";
93 helpmsg = getopt.generate_help();
100 logger.enable_channel("summary");
101 logger.enable_channel("tasks");
105 logger.enable_channel("environment");
106 logger.enable_channel("packages");
107 logger.enable_channel("commands");
111 logger.enable_channel("files");
112 logger.enable_channel("auxcommands");
114 for(list<string>::const_iterator i=log_channels.begin(); i!=log_channels.end(); ++i)
116 vector<string> parts = split(*i, ',');
117 for(vector<string>::const_iterator j=parts.begin(); j!=parts.end(); ++j)
118 logger.enable_channel(*j);
121 if(!analyze_mode.empty())
123 analyzer = new Analyzer(*this);
125 if(analyze_mode=="deps")
126 analyzer->set_mode(Analyzer::DEPS);
127 else if(analyze_mode=="alldeps")
128 analyzer->set_mode(Analyzer::ALLDEPS);
129 else if(analyze_mode=="rebuild")
130 analyzer->set_mode(Analyzer::REBUILD);
131 else if(analyze_mode=="rdeps")
132 analyzer->set_mode(Analyzer::RDEPS);
134 throw usage_error("Invalid analyze mode");
136 analyzer->set_max_depth(max_depth);
137 analyzer->set_full_paths(full_paths);
139 else if(!clean && !create_makefile)
142 const vector<string> &args = getopt.get_args();
143 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
145 string::size_type equal = i->find('=');
146 if(equal!=string::npos)
147 cmdline_options.insert(Config::InputOptions::value_type(i->substr(0, equal), i->substr(equal+1)));
149 cmdline_targets.push_back(*i);
152 if(cmdline_targets.empty())
153 cmdline_targets.push_back("default");
155 if(!work_dir.empty())
160 package_manager.append_package_path(cwd);
161 package_manager.append_package_path(cwd/"..");
162 package_manager.append_binary_package_path(FS::get_sys_data_dir(argv[0], "builder"));
164 package_manager.set_no_externals(no_externals);
167 current_arch = &native_arch;
169 current_arch = new Architecture(*this, arch);
171 list<FS::Path> start_files;
172 start_files.push_back(FS::get_sys_data_dir(argv[0], "builder")/"builderrc");
173 start_files.push_back(FS::get_user_data_dir("builder")/"rc");
174 for(list<FS::Path>::const_iterator i=start_files.begin(); i!=start_files.end(); ++i)
180 if(current_arch->is_native())
181 prefix = (FS::get_home_dir()/"local").str();
183 prefix = (FS::get_home_dir()/"local"/current_arch->get_name()).str();
188 if(!temp_str.empty())
191 if(!build_type_name.empty())
193 BuildTypeMap::iterator i = build_types.find(build_type_name);
194 if(i==build_types.end())
195 throw usage_error("Unknown build type");
196 build_type = &i->second;
199 toolchain.add_tool(new GnuCCompiler(*this, *current_arch));
200 toolchain.add_tool(new GnuCxxCompiler(*this, *current_arch));
201 toolchain.add_tool(new GnuLinker(*this, *current_arch));
202 toolchain.add_tool(new GnuArchiver(*this, *current_arch));
203 toolchain.add_tool(new Copy(*this));
204 toolchain.add_tool(new Tar(*this));
205 toolchain.add_tool(new PkgConfigGenerator(*this));
206 if(current_arch->get_system()=="windows")
207 toolchain.add_tool(new MingwDllTool(*this, *current_arch));
212 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
219 FS::Path main_file = cwd/build_file;
220 if(!FS::exists(main_file))
224 usage(0, "builder", false);
229 IO::print(IO::cerr, "The file %s does not exist.\n", main_file);
234 load_build_file(main_file);
238 usage(0, "builder", false);
250 logger.log("environment", format("Building on %s, for %s%s", native_arch.get_name(),
251 current_arch->get_name(), (current_arch->is_native() ? " (native)" : "")));
252 logger.log("environment", format("Prefix is %s", prefix));
253 if(tempdir.is_absolute())
254 logger.log("environment", format("Temporary directory is %s", tempdir));
256 logger.log("environment", format("Using per-package temporary directory %s", tempdir));
258 logger.log("environment", format("Build type is %s", build_type->get_name()));
260 const PackageManager::PackageMap &packages = package_manager.get_packages();
261 list<string> package_details;
262 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
264 if(!i->second->is_prepared())
267 string line = i->second->get_name();
268 if(dynamic_cast<SourcePackage *>(i->second))
273 unsigned to_be_built = 0;
274 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
275 if(j->second->get_package()==i->second)
278 if(j->second->needs_rebuild())
283 line += format(" (%d targets", count);
285 line += format(", %d to be built", to_be_built);
290 package_details.push_back(line);
293 logger.log("summary", format("%d active packages, %d targets", package_details.size(), targets.size()));
294 for(list<string>::const_iterator i=package_details.begin(); i!=package_details.end(); ++i)
295 logger.log("packages", *i);
300 if(!problems.empty())
302 IO::print(IO::cerr, "The following problems were detected:\n");
303 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
304 IO::print(IO::cerr, " %s: %s\n", i->package, i->descr);
306 IO::print(IO::cerr, "Please fix them and try again.\n");
311 exit_code = do_clean();
313 exit_code = do_build();
318 Target *Builder::get_target(const string &n) const
320 TargetMap::const_iterator i = targets.find(n);
326 void Builder::problem(const string &p, const string &d)
328 problems.push_back(Problem(p, d));
331 void Builder::add_target(Target *t)
333 targets.insert(TargetMap::value_type(t->get_name(), t));
336 void Builder::add_primary_target(Target &t)
338 get_target("world")->add_dependency(t);
340 if(t.get_package()==main_pkg && t.get_component() && t.get_component()->is_default())
341 get_target("default")->add_dependency(t);
344 void Builder::add_installed_target(Target &t)
346 Target *inst_tgt = 0;
347 if(const Tool *tool = t.get_tool())
348 inst_tgt = tool->create_install(t);
350 inst_tgt = toolchain.get_tool("CP").create_target(t);
351 get_target("install")->add_dependency(*inst_tgt);
354 void Builder::usage(const char *reason, const char *argv0, bool brief)
357 IO::print(IO::cerr, "%s\n", reason);
360 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
363 IO::print(IO::cerr, "Builder 1.0\n\n");
364 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
365 IO::print(IO::cerr, "Options:\n");
366 IO::print(IO::cerr, helpmsg);
370 void Builder::load_build_file(const FS::Path &fn)
372 IO::BufferedFile in(fn.str());
374 logger.log("files", format("Reading %s", fn));
376 DataFile::Parser parser(in, fn.str());
377 Loader loader(*this);
381 bool Builder::prepare_build()
383 Target *world = new VirtualTarget(*this, "world");
385 Target *def_tgt = new VirtualTarget(*this, "default");
386 world->add_dependency(*def_tgt);
388 Target *install = new VirtualTarget(*this, "install");
389 world->add_dependency(*install);
391 Target *tarballs = new VirtualTarget(*this, "tarballs");
392 world->add_dependency(*tarballs);
394 package_manager.get_main_package().prepare();
396 // Make the cmdline target depend on all targets mentioned on the command line
397 Target *cmdline = new VirtualTarget(*this, "cmdline");
398 for(NameList::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
400 Target *tgt = get_target(*i);
402 tgt = vfs.get_target(*i);
404 tgt = vfs.get_target(cwd/ *i);
407 IO::print("I don't know anything about %s\n", *i);
411 cmdline->add_dependency(*tgt);
417 for(NameList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
419 FileTarget *tgt = vfs.get_target(cwd/ *i);
422 IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
430 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
431 if(i->second->is_buildable() && !i->second->needs_rebuild())
432 i->second->force_rebuild();
437 const PackageManager::PackageMap &packages = package_manager.get_packages();
438 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
439 i->second->save_caches();
445 int Builder::do_build()
447 Target *cmdline = get_target("cmdline");
450 for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
451 if(i->second->is_buildable() && i->second->needs_rebuild())
456 logger.log("summary", "Already up to date");
459 logger.log("summary", format("Will build %d target%s", total, (total!=1 ? "s" : "")));
461 vector<Task *> tasks;
467 bool starved = false;
471 if(tasks.size()<jobs && !fail && !starved)
473 Target *tgt = cmdline->get_buildable_target();
477 logger.log("tasks", format("%-4s %s", tgt->get_tool()->get_tag(), tgt->get_name()));
478 Task *task = tgt->build();
481 logger.log("commands", format("%s", task->get_command()));
484 task->signal_finished.emit(true);
490 tasks.push_back(task);
495 IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
497 else if(tasks.empty())
503 Time::sleep(10*Time::msec);
505 for(unsigned i=0; i<tasks.size();)
508 if(jobs==1 || (tasks.size()==1 && starved))
509 status = tasks[i]->wait();
511 status = tasks[i]->check();
513 if(status!=Task::RUNNING)
518 tasks.erase(tasks.begin()+i);
519 if(status==Task::ERROR)
521 if(tasks.empty() && fail)
533 logger.log("summary", "Build failed");
534 else if(show_progress)
535 logger.log("summary", "Build complete");
539 const PackageManager::PackageMap &packages = package_manager.get_packages();
540 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
541 i->second->save_caches();
547 int Builder::do_clean()
549 // Cleaning doesn't care about ordering, so a simpler method can be used
551 set<Target *> clean_tgts;
552 list<Target *> queue;
553 queue.push_back(get_target("cmdline"));
555 while(!queue.empty())
557 Target *tgt = queue.front();
558 queue.erase(queue.begin());
560 if(tgt->is_buildable() && (tgt->get_package()==&package_manager.get_main_package() || clean>=2))
561 clean_tgts.insert(tgt);
563 const Target::Dependencies &deps = tgt->get_dependencies();
564 for(list<Target *>::const_iterator i=deps.begin(); i!=deps.end(); ++i)
565 if(!clean_tgts.count(*i))
569 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
571 logger.log("tasks", format("RM %s", (*i)->get_name()));
579 void Builder::package_help()
581 SourcePackage &main_pkg = dynamic_cast<SourcePackage &>(package_manager.get_main_package());
582 const Config &config = main_pkg.get_config();
583 const Config::OptionMap &options = config.get_options();
585 IO::print("Required packages:\n ");
586 const Package::Requirements &requires = main_pkg.get_required_packages();
587 for(Package::Requirements::const_iterator i=requires.begin(); i!=requires.end(); ++i)
589 if(i!=requires.begin())
591 IO::print((*i)->get_name());
593 IO::print("\n\nPackage configuration:\n");
594 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
596 const Config::Option &opt = i->second;
597 IO::print(" %s: %s (%s)", opt.name, opt.description, opt.value);
598 if(opt.value!=opt.default_value)
599 IO::print(" [%s]", opt.default_value);
604 string Builder::usagemsg;
605 string Builder::helpmsg;
608 Builder::Loader::Loader(Builder &b):
609 DataFile::ObjectLoader<Builder>(b)
611 add("architecture", &Loader::architecture);
612 add("binary_package", &Loader::binpkg);
613 add("build_type", &Loader::build_type);
614 add("profile", &Loader::profile);
615 add("package", &Loader::package);
618 void Builder::Loader::architecture(const string &n)
620 if(obj.current_arch->match_name(n))
621 load_sub(*obj.current_arch);
624 void Builder::Loader::binpkg(const string &n)
626 BinaryPackage *pkg = new BinaryPackage(obj, n);
630 void Builder::Loader::build_type(const string &n)
634 BuildTypeMap::iterator i = obj.build_types.insert(BuildTypeMap::value_type(n, btype)).first;
636 obj.build_type = &i->second;
639 void Builder::Loader::profile(const string &)
641 IO::print("Profiles are deprecated\n");
644 void Builder::Loader::package(const string &n)
646 SourcePackage *pkg = new SourcePackage(obj, n, get_source());
648 if(obj.conf_all || pkg==&obj.package_manager.get_main_package())
649 load_sub(*pkg, obj.cmdline_options);
654 pkg->set_build_type(*obj.build_type);