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 = 5;
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 analysis. MODE can be deps, alldeps or rebuild.", "MODE");
71 getopt.add_option('b', "build", build, GetOpt::NO_ARG).set_help("Perform build even if doing analysis.");
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 info from FILE instead of Build.", "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 NUM commands at once, whenever possible.", "NUM");
76 getopt.add_option('l', "log", log_channels, GetOpt::REQUIRED_ARG).set_help("Set log channels to be displayed.", "LIST");
77 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG).set_help("Don't actually do anything, only show what would be done.");
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 getopt.add_option( "warnings", cmdline_warn, GetOpt::REQUIRED_ARG).set_help("Compiler warnings to use.", "LIST");
94 usagemsg = getopt.generate_usage(argv[0])+" [<target> ...]";
95 helpmsg = getopt.generate_help();
102 logger.enable_channel("summary");
103 logger.enable_channel("tasks");
107 logger.enable_channel("environment");
108 logger.enable_channel("packages");
109 logger.enable_channel("commands");
113 logger.enable_channel("packagemgr");
114 logger.enable_channel("configure");
118 logger.enable_channel("files");
119 logger.enable_channel("auxcommands");
123 logger.enable_channel("tools");
124 logger.enable_channel("vfs");
126 for(list<string>::const_iterator i=log_channels.begin(); i!=log_channels.end(); ++i)
128 vector<string> parts = split(*i, ',');
129 for(vector<string>::const_iterator j=parts.begin(); j!=parts.end(); ++j)
130 logger.enable_channel(*j);
133 if(!analyze_mode.empty())
135 analyzer = new Analyzer(*this);
137 if(analyze_mode=="deps")
138 analyzer->set_mode(Analyzer::DEPS);
139 else if(analyze_mode=="alldeps")
140 analyzer->set_mode(Analyzer::ALLDEPS);
141 else if(analyze_mode=="rebuild")
142 analyzer->set_mode(Analyzer::REBUILD);
143 else if(analyze_mode=="rdeps")
144 analyzer->set_mode(Analyzer::RDEPS);
146 throw usage_error("Invalid analyze mode");
148 analyzer->set_max_depth(max_depth);
149 analyzer->set_full_paths(full_paths);
151 else if(!clean && !create_makefile)
154 const vector<string> &args = getopt.get_args();
155 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
157 string::size_type equal = i->find('=');
158 if(equal!=string::npos)
159 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
161 cmdline_targets.push_back(*i);
164 if(cmdline_targets.empty())
165 cmdline_targets.push_back("default");
167 if(!work_dir.empty())
172 package_manager.set_no_externals(no_externals);
175 current_arch = &native_arch;
177 current_arch = new Architecture(*this, arch);
179 load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
180 load_build_file((FS::get_user_data_dir("builder")/"rc").str());
184 if(current_arch->is_native())
185 prefix = (FS::get_home_dir()/"local").str();
187 prefix = (FS::get_home_dir()/"local"/current_arch->get_name()).str();
190 prefix = FS::getcwd()/prfx;
192 if(!temp_str.empty())
195 if(!build_type_name.empty())
197 BuildTypeMap::iterator i = build_types.find(build_type_name);
198 if(i==build_types.end())
199 throw usage_error("Unknown build type");
200 build_type = &i->second;
203 warnings.push_back("all");
204 warnings.push_back("extra");
205 warnings.push_back("shadow");
206 warnings.push_back("pointer-arith");
207 warnings.push_back("error");
208 for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
210 vector<string> warns = split(*i, ',');
211 warnings.insert(warnings.end(), warns.begin(), warns.end());
214 toolchain.add_tool(new GnuCCompiler(*this, *current_arch));
215 toolchain.add_tool(new GnuCxxCompiler(*this, *current_arch));
216 toolchain.add_tool(new GnuLinker(*this, *current_arch));
217 toolchain.add_tool(new GnuArchiver(*this, *current_arch));
218 toolchain.add_tool(new Copy(*this));
219 toolchain.add_tool(new Tar(*this));
220 toolchain.add_tool(new PkgConfigGenerator(*this));
225 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
232 if(load_build_file(cwd/build_file))
236 usage(0, "builder", false);
241 IO::print(IO::cerr, "No build info here.\n");
248 usage(0, "builder", false);
260 logger.log("environment", format("Building on %s, for %s%s", native_arch.get_name(),
261 current_arch->get_name(), (current_arch->is_native() ? " (native)" : "")));
262 logger.log("environment", format("Prefix is %s", prefix));
263 if(tempdir.is_absolute())
264 logger.log("environment", format("Temporary directory is %s", tempdir));
266 logger.log("environment", format("Using per-package temporary directory %s", tempdir));
268 logger.log("environment", format("Build type is %s", build_type->get_name()));
270 const PackageManager::PackageMap &packages = package_manager.get_packages();
271 list<string> package_details;
272 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
274 if(!i->second || !i->second->is_prepared())
277 string line = i->second->get_name();
278 if(dynamic_cast<SourcePackage *>(i->second))
283 unsigned to_be_built = 0;
284 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
285 if(j->second->get_package()==i->second)
288 if(j->second->needs_rebuild())
293 line += format(" (%d targets", count);
295 line += format(", %d to be built", to_be_built);
300 package_details.push_back(line);
303 logger.log("summary", format("%d active packages, %d targets", package_details.size(), targets.size()));
304 for(list<string>::const_iterator i=package_details.begin(); i!=package_details.end(); ++i)
305 logger.log("packages", *i);
310 if(!problems.empty())
312 IO::print(IO::cerr, "The following problems were detected:\n");
313 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
314 IO::print(IO::cerr, " %s: %s\n", i->package, i->descr);
316 IO::print(IO::cerr, "Please fix them and try again.\n");
321 exit_code = do_clean();
323 exit_code = do_build();
328 Target *Builder::get_target(const string &n) const
330 TargetMap::const_iterator i = targets.find(n);
336 void Builder::problem(const string &p, const string &d)
338 problems.push_back(Problem(p, d));
341 void Builder::add_target(Target *t)
343 targets.insert(TargetMap::value_type(t->get_name(), t));
346 void Builder::usage(const char *reason, const char *argv0, bool brief)
349 IO::print(IO::cerr, "%s\n", reason);
352 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
355 IO::print(IO::cerr, "Builder 1.0\n\n");
356 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
357 IO::print(IO::cerr, "Options:\n");
358 IO::print(IO::cerr, helpmsg);
362 int Builder::load_build_file(const FS::Path &fn)
367 IO::BufferedFile in(fn.str());
369 logger.log("files", format("Reading %s", fn));
371 DataFile::Parser parser(in, fn.str());
372 Loader loader(*this, fn.subpath(0, fn.size()-1));
378 bool Builder::prepare_build()
380 Target *world = new VirtualTarget(*this, "world");
382 Target *def_tgt = new VirtualTarget(*this, "default");
383 world->add_depend(*def_tgt);
385 Target *install = new VirtualTarget(*this, "install");
386 world->add_depend(*install);
388 Target *tarballs = new VirtualTarget(*this, "tarballs");
389 world->add_depend(*tarballs);
393 // Make the cmdline target depend on all targets mentioned on the command line
394 Target *cmdline = new VirtualTarget(*this, "cmdline");
395 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
397 Target *tgt = get_target(*i);
399 tgt = vfs.get_target(*i);
401 tgt = vfs.get_target(cwd/ *i);
404 IO::print("I don't know anything about %s\n", *i);
408 cmdline->add_depend(*tgt);
414 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
416 FileTarget *tgt = vfs.get_target(cwd/ *i);
419 IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
427 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
428 if(i->second->is_buildable() && !i->second->needs_rebuild())
429 i->second->force_rebuild();
434 const PackageManager::PackageMap &packages = package_manager.get_packages();
435 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
436 i->second->save_caches();
442 int Builder::do_build()
444 Target *cmdline = get_target("cmdline");
447 for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
448 if(i->second->is_buildable() && i->second->needs_rebuild())
453 logger.log("summary", "Already up to date");
456 logger.log("summary", format("Will build %d target%s", total, (total!=1 ? "s" : "")));
458 vector<Task *> tasks;
467 if(tasks.size()<jobs && !fail)
469 Target *tgt = cmdline->get_buildable_target();
473 logger.log("tasks", format("%-4s %s", tgt->get_tool()->get_tag(), tgt->get_name()));
474 Task *task = tgt->build();
477 logger.log("commands", format("%s", task->get_command()));
480 task->signal_finished.emit(true);
486 tasks.push_back(task);
491 IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
493 else if(tasks.empty())
497 Time::sleep(10*Time::msec);
499 for(unsigned i=0; i<tasks.size();)
501 Task::Status status = tasks[i]->check();
502 if(status!=Task::RUNNING)
507 tasks.erase(tasks.begin()+i);
508 if(status==Task::ERROR)
510 if(tasks.empty() && fail)
521 logger.log("summary", "Build failed");
522 else if(show_progress)
523 logger.log("summary", "Build complete");
528 int Builder::do_clean()
530 // Cleaning doesn't care about ordering, so a simpler method can be used
532 set<Target *> clean_tgts;
533 list<Target *> queue;
534 queue.push_back(get_target("cmdline"));
536 while(!queue.empty())
538 Target *tgt = queue.front();
539 queue.erase(queue.begin());
541 if(tgt->is_buildable() && (tgt->get_package()==main_pkg || clean>=2))
542 clean_tgts.insert(tgt);
544 const Target::Dependencies &deps = tgt->get_depends();
545 for(list<Target *>::const_iterator i=deps.begin(); i!=deps.end(); ++i)
546 if(!clean_tgts.count(*i))
550 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
551 if(FileTarget *ft = dynamic_cast<FileTarget *>(*i))
553 FS::unlink(ft->get_path());
558 void Builder::package_help()
560 const Config &config = main_pkg->get_config();
561 const Config::OptionMap &options = config.get_options();
563 IO::print("Required packages:\n ");
564 const PackageList &requires = main_pkg->get_requires();
565 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
567 if(i!=requires.begin())
569 IO::print((*i)->get_name());
571 IO::print("\n\nPackage configuration:\n");
572 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
574 const Config::Option &opt = i->second;
575 IO::print(" %s: %s (%s)", opt.name, opt.descr, opt.value);
576 if(opt.value!=opt.defv)
577 IO::print(" [%s]", opt.defv);
582 string Builder::usagemsg;
583 string Builder::helpmsg;
586 Builder::Loader::Loader(Builder &b, const FS::Path &s):
587 DataFile::ObjectLoader<Builder>(b),
590 add("architecture", &Loader::architecture);
591 add("binary_package", &Loader::binpkg);
592 add("build_type", &Loader::build_type);
593 add("profile", &Loader::profile);
594 add("package", &Loader::package);
597 void Builder::Loader::architecture(const string &n)
599 if(obj.current_arch->match_name(n))
600 load_sub(*obj.current_arch);
603 void Builder::Loader::binpkg(const string &n)
605 BinaryPackage *pkg = new BinaryPackage(obj, n);
609 void Builder::Loader::build_type(const string &n)
613 BuildTypeMap::iterator i = obj.build_types.insert(BuildTypeMap::value_type(n, btype)).first;
615 obj.build_type = &i->second;
618 void Builder::Loader::profile(const string &)
620 IO::print("Profiles are deprecated\n");
623 void Builder::Loader::package(const string &n)
625 SourcePackage *pkg = new SourcePackage(obj, n, src);
629 if(obj.conf_all || pkg==obj.main_pkg)
630 load_sub(*pkg, obj.cmdline_options);
635 pkg->set_build_type(*obj.build_type);