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"
20 #include "gnuarchiver.h"
21 #include "gnuccompiler.h"
22 #include "gnucxxcompiler.h"
23 #include "gnulinker.h"
24 #include "installedfile.h"
25 #include "mingwdlltool.h"
27 #include "pkgconfiggenerator.h"
28 #include "sharedlibrary.h"
29 #include "sourcepackage.h"
32 #include "virtualtarget.h"
37 Builder::Builder(int argc, char **argv):
38 package_manager(*this),
39 native_arch(*this, string()),
54 create_makefile(false),
60 bool full_paths = false;
61 unsigned max_depth = 4;
65 bool no_externals = false;
68 list<string> log_channels;
69 string build_type_name;
72 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG).set_help("Perform dependency analysis.", "MODE");
73 getopt.add_option('b', "build", build, GetOpt::NO_ARG).set_help("Perform build even if also doing something else.");
74 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG).set_help("Clean buildable targets.");
75 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG).set_help("Read build instructions from FILE.", "FILE");
76 getopt.add_option('h', "help", help, GetOpt::NO_ARG).set_help("Print this message.");
77 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG).set_help("Run up to NUM tasks in parallel.", "NUM");
78 getopt.add_option('l', "log", log_channels, GetOpt::REQUIRED_ARG).set_help("Enable listed log channels.", "LIST");
79 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG).set_help("Show what would be done without actually doing it.");
80 getopt.add_option('s', "silent", silent, GetOpt::NO_ARG).set_help("Don't print any messages other than errors.");
81 getopt.add_option('t', "build-type", build_type_name, GetOpt::REQUIRED_ARG).set_help("Set build type.", "TYPE");
82 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG).set_help("Print more information about what's going on.");
83 getopt.add_option('x', "no-externals", no_externals, GetOpt::NO_ARG).set_help("Do not load external source packages.");
84 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
85 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
86 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
87 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
88 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
89 getopt.add_option( "arch", arch, GetOpt::REQUIRED_ARG).set_help("Build for architecture ARCH.", "ARCH");
90 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG).set_help("Stop after configuring packages.");
91 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG).set_help("Output full paths in analysis.");
92 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG).set_help("Show up to NUM levels in analysis.", "NUM");
93 getopt.add_option( "prefix", prfx, GetOpt::REQUIRED_ARG).set_help("Install things to DIR.", "DIR");
94 getopt.add_option( "tempdir", temp_str, GetOpt::REQUIRED_ARG).set_help("Store temporary files in DIR.", "DIR");
95 usagemsg = getopt.generate_usage(argv[0])+" [<target> ...]";
96 helpmsg = getopt.generate_help();
103 logger.enable_channel("summary");
104 logger.enable_channel("tasks");
108 logger.enable_channel("environment");
109 logger.enable_channel("packages");
110 logger.enable_channel("commands");
114 logger.enable_channel("files");
115 logger.enable_channel("auxcommands");
117 for(list<string>::const_iterator i=log_channels.begin(); i!=log_channels.end(); ++i)
119 vector<string> parts = split(*i, ',');
120 for(vector<string>::const_iterator j=parts.begin(); j!=parts.end(); ++j)
121 logger.enable_channel(*j);
124 if(!analyze_mode.empty())
126 analyzer = new Analyzer(*this);
128 if(analyze_mode=="deps")
129 analyzer->set_mode(Analyzer::DEPS);
130 else if(analyze_mode=="alldeps")
131 analyzer->set_mode(Analyzer::ALLDEPS);
132 else if(analyze_mode=="rebuild")
133 analyzer->set_mode(Analyzer::REBUILD);
134 else if(analyze_mode=="rdeps")
135 analyzer->set_mode(Analyzer::RDEPS);
137 throw usage_error("Invalid analyze mode");
139 analyzer->set_max_depth(max_depth);
140 analyzer->set_full_paths(full_paths);
142 else if(!clean && !create_makefile)
145 const vector<string> &args = getopt.get_args();
146 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
148 string::size_type equal = i->find('=');
149 if(equal!=string::npos)
150 cmdline_options.insert(Config::InputOptions::value_type(i->substr(0, equal), i->substr(equal+1)));
152 cmdline_targets.push_back(*i);
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));
208 toolchain.add_tool(new DataTool(*this));
218 FS::Path main_file = cwd/build_file;
219 if(!FS::exists(main_file))
223 usage(0, "builder", false);
228 IO::print(IO::cerr, "The file %s does not exist.\n", main_file);
233 load_build_file(main_file, &cmdline_options, conf_all);
237 usage(0, "builder", false);
249 logger.log("environment", format("Building on %s, for %s%s", native_arch.get_name(),
250 current_arch->get_name(), (current_arch->is_native() ? " (native)" : "")));
251 logger.log("environment", format("Prefix is %s", prefix));
252 if(tempdir.is_absolute())
253 logger.log("environment", format("Temporary directory is %s", tempdir));
255 logger.log("environment", format("Using per-package temporary directory %s", tempdir));
257 logger.log("environment", format("Build type is %s", build_type->get_name()));
259 const PackageManager::PackageMap &packages = package_manager.get_packages();
260 list<string> package_details;
261 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
263 if(!i->second->is_prepared())
266 string line = i->second->get_name();
267 if(dynamic_cast<SourcePackage *>(i->second))
272 unsigned to_be_built = 0;
273 const BuildGraph::TargetMap &targets = build_graph.get_targets();
274 for(BuildGraph::TargetMap::const_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(), build_graph.get_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 void Builder::problem(const string &p, const string &d)
320 problems.push_back(Problem(p, d));
323 void Builder::usage(const char *reason, const char *argv0, bool brief)
326 IO::print(IO::cerr, "%s\n", reason);
329 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
332 IO::print(IO::cerr, "Builder 1.0\n\n");
333 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
334 IO::print(IO::cerr, "Options:\n");
335 IO::print(IO::cerr, helpmsg);
339 void Builder::load_build_file(const FS::Path &fn, const Config::InputOptions *opts, bool all)
341 IO::BufferedFile in(fn.str());
343 logger.log("files", format("Reading %s", fn));
345 DataFile::Parser parser(in, fn.str());
346 Loader loader(*this, opts, all);
350 bool Builder::prepare_build()
352 package_manager.get_main_package().prepare();
354 // Add targets from command line as goals
355 for(NameList::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
357 Target *tgt = build_graph.get_target(*i);
359 tgt = vfs.get_target(*i);
361 tgt = vfs.get_target(cwd/ *i);
364 IO::print("I don't know anything about %s\n", *i);
368 build_graph.add_goal(*tgt);
371 build_graph.prepare();
374 for(NameList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
376 FileTarget *tgt = vfs.get_target(cwd/ *i);
379 IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
386 build_graph.force_full_rebuild();
390 const PackageManager::PackageMap &packages = package_manager.get_packages();
391 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
392 i->second->save_caches();
398 int Builder::do_build()
400 unsigned total = build_graph.count_rebuild_targets();
404 logger.log("summary", "Already up to date");
407 logger.log("summary", format("Will build %d target%s", total, (total!=1 ? "s" : "")));
409 vector<Task *> tasks;
415 bool starved = false;
419 if(tasks.size()<jobs && !fail && !starved)
421 Target *tgt = build_graph.get_buildable_target();
425 logger.log("tasks", format("%-4s %s", tgt->get_tool()->get_tag(), tgt->get_name()));
426 Task *task = tgt->build();
429 logger.log("commands", format("%s", task->get_command()));
432 task->signal_finished.emit(true);
438 tasks.push_back(task);
443 IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
445 else if(tasks.empty())
451 Time::sleep(10*Time::msec);
453 for(unsigned i=0; i<tasks.size();)
456 if(jobs==1 || (tasks.size()==1 && starved))
457 status = tasks[i]->wait();
459 status = tasks[i]->check();
461 if(status!=Task::RUNNING)
466 tasks.erase(tasks.begin()+i);
467 if(status==Task::ERROR)
469 if(tasks.empty() && fail)
481 logger.log("summary", "Build failed");
482 else if(show_progress)
483 logger.log("summary", "Build complete");
487 const PackageManager::PackageMap &packages = package_manager.get_packages();
488 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
489 i->second->save_caches();
495 int Builder::do_clean()
497 // Cleaning doesn't care about ordering, so a simpler method can be used
499 set<Target *> clean_tgts;
500 list<Target *> queue;
501 queue.push_back(build_graph.get_target("cmdline"));
503 while(!queue.empty())
505 Target *tgt = queue.front();
506 queue.erase(queue.begin());
508 if(tgt->is_buildable() && (tgt->get_package()==&package_manager.get_main_package() || clean>=2))
509 clean_tgts.insert(tgt);
511 const Target::Dependencies &deps = tgt->get_dependencies();
512 for(list<Target *>::const_iterator i=deps.begin(); i!=deps.end(); ++i)
513 if(!clean_tgts.count(*i))
517 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
519 logger.log("tasks", format("RM %s", (*i)->get_name()));
527 void Builder::package_help()
529 SourcePackage &main_pkg = dynamic_cast<SourcePackage &>(package_manager.get_main_package());
530 const Config &config = main_pkg.get_config();
531 const Config::OptionMap &options = config.get_options();
533 IO::print("Required packages:\n ");
534 const Package::Requirements &requires = main_pkg.get_required_packages();
535 for(Package::Requirements::const_iterator i=requires.begin(); i!=requires.end(); ++i)
537 if(i!=requires.begin())
539 IO::print((*i)->get_name());
541 IO::print("\n\nPackage configuration:\n");
542 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
544 const Config::Option &opt = i->second;
545 IO::print(" %s: %s (%s)", opt.name, opt.description, opt.value);
546 if(opt.value!=opt.default_value)
547 IO::print(" [%s]", opt.default_value);
552 string Builder::usagemsg;
553 string Builder::helpmsg;
556 Builder::Loader::Loader(Builder &b, const Config::InputOptions *o, bool a):
557 DataFile::ObjectLoader<Builder>(b),
561 add("architecture", &Loader::architecture);
562 add("binary_package", &Loader::binpkg);
563 add("build_type", &Loader::build_type);
564 add("profile", &Loader::profile);
565 add("package", &Loader::package);
568 obj.top_loader = this;
569 else if(!options && obj.top_loader!=this && obj.top_loader->conf_all)
570 options = obj.top_loader->options;
573 Builder::Loader::~Loader()
575 if(obj.top_loader==this)
579 void Builder::Loader::architecture(const string &n)
581 if(obj.current_arch->match_name(n))
582 load_sub(*obj.current_arch);
585 void Builder::Loader::binpkg(const string &n)
587 BinaryPackage *pkg = new BinaryPackage(obj, n);
591 void Builder::Loader::build_type(const string &n)
595 BuildTypeMap::iterator i = obj.build_types.insert(BuildTypeMap::value_type(n, btype)).first;
597 obj.build_type = &i->second;
600 void Builder::Loader::profile(const string &)
602 IO::print("Profiles are deprecated\n");
605 void Builder::Loader::package(const string &n)
607 SourcePackage *pkg = new SourcePackage(obj, n, get_source());
610 load_sub(*pkg, *options);
615 pkg->set_build_type(*obj.build_type);