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"
25 #include "pkgconfiggenerator.h"
26 #include "sharedlibrary.h"
27 #include "sourcepackage.h"
30 #include "virtualtarget.h"
35 Builder::Builder(int argc, char **argv):
36 package_manager(*this),
38 native_arch(*this, string()),
52 create_makefile(false),
57 bool full_paths = false;
58 unsigned max_depth = 4;
59 StringList cmdline_warn;
63 bool no_externals = false;
66 list<string> log_channels;
67 string build_type_name;
70 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG).set_help("Perform dependency analysis.", "MODE");
71 getopt.add_option('b', "build", build, GetOpt::NO_ARG).set_help("Perform build even if also doing something else.");
72 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG).set_help("Clean buildable targets.");
73 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG).set_help("Read build instructions from FILE.", "FILE");
74 getopt.add_option('h', "help", help, GetOpt::NO_ARG).set_help("Print this message.");
75 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG).set_help("Run up to NUM tasks in parallel.", "NUM");
76 getopt.add_option('l', "log", log_channels, GetOpt::REQUIRED_ARG).set_help("Enable listed log channels.", "LIST");
77 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG).set_help("Show what would be done without actually doing it.");
78 getopt.add_option('s', "silent", silent, GetOpt::NO_ARG).set_help("Don't print any messages other than errors.");
79 getopt.add_option('t', "build-type", build_type_name, GetOpt::REQUIRED_ARG).set_help("Set build type.", "TYPE");
80 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG).set_help("Print more information about what's going on.");
81 getopt.add_option('x', "no-externals", no_externals, GetOpt::NO_ARG).set_help("Do not load external source packages.");
82 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
83 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
84 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
85 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
86 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
87 getopt.add_option( "arch", arch, GetOpt::REQUIRED_ARG).set_help("Build for architecture ARCH.", "ARCH");
88 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG).set_help("Stop after configuring packages.");
89 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG).set_help("Output full paths in analysis.");
90 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG).set_help("Show up to NUM levels in analysis.", "NUM");
91 getopt.add_option( "prefix", prfx, GetOpt::REQUIRED_ARG).set_help("Install things to DIR.", "DIR");
92 getopt.add_option( "tempdir", temp_str, GetOpt::REQUIRED_ARG).set_help("Store temporary files in DIR.", "DIR");
93 usagemsg = getopt.generate_usage(argv[0])+" [<target> ...]";
94 helpmsg = getopt.generate_help();
101 logger.enable_channel("summary");
102 logger.enable_channel("tasks");
106 logger.enable_channel("environment");
107 logger.enable_channel("packages");
108 logger.enable_channel("commands");
112 logger.enable_channel("files");
113 logger.enable_channel("auxcommands");
115 for(list<string>::const_iterator i=log_channels.begin(); i!=log_channels.end(); ++i)
117 vector<string> parts = split(*i, ',');
118 for(vector<string>::const_iterator j=parts.begin(); j!=parts.end(); ++j)
119 logger.enable_channel(*j);
122 if(!analyze_mode.empty())
124 analyzer = new Analyzer(*this);
126 if(analyze_mode=="deps")
127 analyzer->set_mode(Analyzer::DEPS);
128 else if(analyze_mode=="alldeps")
129 analyzer->set_mode(Analyzer::ALLDEPS);
130 else if(analyze_mode=="rebuild")
131 analyzer->set_mode(Analyzer::REBUILD);
132 else if(analyze_mode=="rdeps")
133 analyzer->set_mode(Analyzer::RDEPS);
135 throw usage_error("Invalid analyze mode");
137 analyzer->set_max_depth(max_depth);
138 analyzer->set_full_paths(full_paths);
140 else if(!clean && !create_makefile)
143 const vector<string> &args = getopt.get_args();
144 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
146 string::size_type equal = i->find('=');
147 if(equal!=string::npos)
148 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
150 cmdline_targets.push_back(*i);
153 if(cmdline_targets.empty())
154 cmdline_targets.push_back("default");
156 if(!work_dir.empty())
161 package_manager.set_no_externals(no_externals);
164 current_arch = &native_arch;
166 current_arch = new Architecture(*this, arch);
168 load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
169 load_build_file((FS::get_user_data_dir("builder")/"rc").str());
173 if(current_arch->is_native())
174 prefix = (FS::get_home_dir()/"local").str();
176 prefix = (FS::get_home_dir()/"local"/current_arch->get_name()).str();
181 if(!temp_str.empty())
184 if(!build_type_name.empty())
186 BuildTypeMap::iterator i = build_types.find(build_type_name);
187 if(i==build_types.end())
188 throw usage_error("Unknown build type");
189 build_type = &i->second;
192 toolchain.add_tool(new GnuCCompiler(*this, *current_arch));
193 toolchain.add_tool(new GnuCxxCompiler(*this, *current_arch));
194 toolchain.add_tool(new GnuLinker(*this, *current_arch));
195 toolchain.add_tool(new GnuArchiver(*this, *current_arch));
196 toolchain.add_tool(new Copy(*this));
197 toolchain.add_tool(new Tar(*this));
198 toolchain.add_tool(new PkgConfigGenerator(*this));
203 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
210 if(load_build_file(cwd/build_file))
214 usage(0, "builder", false);
219 IO::print(IO::cerr, "No build info here.\n");
226 usage(0, "builder", false);
238 logger.log("environment", format("Building on %s, for %s%s", native_arch.get_name(),
239 current_arch->get_name(), (current_arch->is_native() ? " (native)" : "")));
240 logger.log("environment", format("Prefix is %s", prefix));
241 if(tempdir.is_absolute())
242 logger.log("environment", format("Temporary directory is %s", tempdir));
244 logger.log("environment", format("Using per-package temporary directory %s", tempdir));
246 logger.log("environment", format("Build type is %s", build_type->get_name()));
248 const PackageManager::PackageMap &packages = package_manager.get_packages();
249 list<string> package_details;
250 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
252 if(!i->second || !i->second->is_prepared())
255 string line = i->second->get_name();
256 if(dynamic_cast<SourcePackage *>(i->second))
261 unsigned to_be_built = 0;
262 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
263 if(j->second->get_package()==i->second)
266 if(j->second->needs_rebuild())
271 line += format(" (%d targets", count);
273 line += format(", %d to be built", to_be_built);
278 package_details.push_back(line);
281 logger.log("summary", format("%d active packages, %d targets", package_details.size(), targets.size()));
282 for(list<string>::const_iterator i=package_details.begin(); i!=package_details.end(); ++i)
283 logger.log("packages", *i);
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 Target *Builder::get_target(const string &n) const
308 TargetMap::const_iterator i = targets.find(n);
314 void Builder::problem(const string &p, const string &d)
316 problems.push_back(Problem(p, d));
319 void Builder::add_target(Target *t)
321 targets.insert(TargetMap::value_type(t->get_name(), t));
324 void Builder::add_primary_target(Target &t)
326 get_target("world")->add_dependency(t);
328 if(t.get_package()==main_pkg && t.get_component() && t.get_component()->is_default())
329 get_target("default")->add_dependency(t);
332 void Builder::usage(const char *reason, const char *argv0, bool brief)
335 IO::print(IO::cerr, "%s\n", reason);
338 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
341 IO::print(IO::cerr, "Builder 1.0\n\n");
342 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
343 IO::print(IO::cerr, "Options:\n");
344 IO::print(IO::cerr, helpmsg);
348 int Builder::load_build_file(const FS::Path &fn)
353 IO::BufferedFile in(fn.str());
355 logger.log("files", format("Reading %s", fn));
357 DataFile::Parser parser(in, fn.str());
358 Loader loader(*this);
364 bool Builder::prepare_build()
366 Target *world = new VirtualTarget(*this, "world");
368 Target *def_tgt = new VirtualTarget(*this, "default");
369 world->add_dependency(*def_tgt);
371 Target *install = new VirtualTarget(*this, "install");
372 world->add_dependency(*install);
374 Target *tarballs = new VirtualTarget(*this, "tarballs");
375 world->add_dependency(*tarballs);
379 // Make the cmdline target depend on all targets mentioned on the command line
380 Target *cmdline = new VirtualTarget(*this, "cmdline");
381 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
383 Target *tgt = get_target(*i);
385 tgt = vfs.get_target(*i);
387 tgt = vfs.get_target(cwd/ *i);
390 IO::print("I don't know anything about %s\n", *i);
394 cmdline->add_dependency(*tgt);
400 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
402 FileTarget *tgt = vfs.get_target(cwd/ *i);
405 IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
413 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
414 if(i->second->is_buildable() && !i->second->needs_rebuild())
415 i->second->force_rebuild();
420 const PackageManager::PackageMap &packages = package_manager.get_packages();
421 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
422 i->second->save_caches();
428 int Builder::do_build()
430 Target *cmdline = get_target("cmdline");
433 for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
434 if(i->second->is_buildable() && i->second->needs_rebuild())
439 logger.log("summary", "Already up to date");
442 logger.log("summary", format("Will build %d target%s", total, (total!=1 ? "s" : "")));
444 vector<Task *> tasks;
450 bool starved = false;
454 if(tasks.size()<jobs && !fail && !starved)
456 Target *tgt = cmdline->get_buildable_target();
460 logger.log("tasks", format("%-4s %s", tgt->get_tool()->get_tag(), tgt->get_name()));
461 Task *task = tgt->build();
464 logger.log("commands", format("%s", task->get_command()));
467 task->signal_finished.emit(true);
473 tasks.push_back(task);
478 IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
480 else if(tasks.empty())
486 Time::sleep(10*Time::msec);
488 for(unsigned i=0; i<tasks.size();)
491 if(jobs==1 || (tasks.size()==1 && starved))
492 status = tasks[i]->wait();
494 status = tasks[i]->check();
496 if(status!=Task::RUNNING)
501 tasks.erase(tasks.begin()+i);
502 if(status==Task::ERROR)
504 if(tasks.empty() && fail)
516 logger.log("summary", "Build failed");
517 else if(show_progress)
518 logger.log("summary", "Build complete");
522 const PackageManager::PackageMap &packages = package_manager.get_packages();
523 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
524 i->second->save_caches();
530 int Builder::do_clean()
532 // Cleaning doesn't care about ordering, so a simpler method can be used
534 set<Target *> clean_tgts;
535 list<Target *> queue;
536 queue.push_back(get_target("cmdline"));
538 while(!queue.empty())
540 Target *tgt = queue.front();
541 queue.erase(queue.begin());
543 if(tgt->is_buildable() && (tgt->get_package()==main_pkg || clean>=2))
544 clean_tgts.insert(tgt);
546 const Target::Dependencies &deps = tgt->get_dependencies();
547 for(list<Target *>::const_iterator i=deps.begin(); i!=deps.end(); ++i)
548 if(!clean_tgts.count(*i))
552 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
554 logger.log("tasks", format("RM %s", (*i)->get_name()));
562 void Builder::package_help()
564 const Config &config = main_pkg->get_config();
565 const Config::OptionMap &options = config.get_options();
567 IO::print("Required packages:\n ");
568 const PackageList &requires = main_pkg->get_required_packages();
569 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
571 if(i!=requires.begin())
573 IO::print((*i)->get_name());
575 IO::print("\n\nPackage configuration:\n");
576 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
578 const Config::Option &opt = i->second;
579 IO::print(" %s: %s (%s)", opt.name, opt.description, opt.value);
580 if(opt.value!=opt.default_value)
581 IO::print(" [%s]", opt.default_value);
586 string Builder::usagemsg;
587 string Builder::helpmsg;
590 Builder::Loader::Loader(Builder &b):
591 DataFile::ObjectLoader<Builder>(b)
593 add("architecture", &Loader::architecture);
594 add("binary_package", &Loader::binpkg);
595 add("build_type", &Loader::build_type);
596 add("profile", &Loader::profile);
597 add("package", &Loader::package);
600 void Builder::Loader::architecture(const string &n)
602 if(obj.current_arch->match_name(n))
603 load_sub(*obj.current_arch);
606 void Builder::Loader::binpkg(const string &n)
608 BinaryPackage *pkg = new BinaryPackage(obj, n);
612 void Builder::Loader::build_type(const string &n)
616 BuildTypeMap::iterator i = obj.build_types.insert(BuildTypeMap::value_type(n, btype)).first;
618 obj.build_type = &i->second;
621 void Builder::Loader::profile(const string &)
623 IO::print("Profiles are deprecated\n");
626 void Builder::Loader::package(const string &n)
628 SourcePackage *pkg = new SourcePackage(obj, n, get_source());
632 if(obj.conf_all || pkg==obj.main_pkg)
633 load_sub(*pkg, obj.cmdline_options);
638 pkg->set_build_type(*obj.build_type);