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()),
53 create_makefile(false)
57 bool full_paths = false;
58 unsigned max_depth = 5;
59 StringList cmdline_warn;
62 bool no_externals = false;
65 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG).set_help("Perform analysis. MODE can be deps, alldeps or rebuild.", "MODE");
66 getopt.add_option('b', "build", build, GetOpt::NO_ARG).set_help("Perform build even if doing analysis.");
67 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG).set_help("Clean buildable targets.");
68 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG).set_help("Read info from FILE instead of Build.", "FILE");
69 getopt.add_option('h', "help", help, GetOpt::NO_ARG).set_help("Print this message.");
70 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG).set_help("Run NUM commands at once, whenever possible.", "NUM");
71 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG).set_help("Don't actually do anything, only show what would be done.");
72 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG).set_help("Print more information about what's going on.");
73 getopt.add_option('x', "no-externals", no_externals, GetOpt::NO_ARG).set_help("Do not load external source packages.");
74 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
75 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
76 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
77 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
78 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
79 getopt.add_option( "arch", arch, GetOpt::REQUIRED_ARG).set_help("Architecture to build for.", "ARCH");
80 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG).set_help("Stop after configuring packages.");
81 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG).set_help("Output full paths in analysis.");
82 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG).set_help("Maximum depth to show in analysis.", "NUM");
83 getopt.add_option( "prefix", prfx, GetOpt::REQUIRED_ARG).set_help("Directory to install things to.", "DIR");
84 getopt.add_option( "warnings", cmdline_warn, GetOpt::REQUIRED_ARG).set_help("Compiler warnings to use.", "LIST");
85 usagemsg = getopt.generate_usage(argv[0])+" [<target> ...]";
86 helpmsg = getopt.generate_help();
89 if(!analyze_mode.empty())
91 analyzer = new Analyzer(*this);
93 if(analyze_mode=="deps")
94 analyzer->set_mode(Analyzer::DEPS);
95 else if(analyze_mode=="alldeps")
96 analyzer->set_mode(Analyzer::ALLDEPS);
97 else if(analyze_mode=="rebuild")
98 analyzer->set_mode(Analyzer::REBUILD);
99 else if(analyze_mode=="rdeps")
100 analyzer->set_mode(Analyzer::RDEPS);
102 throw usage_error("Invalid analyze mode");
104 analyzer->set_max_depth(max_depth);
105 analyzer->set_full_paths(full_paths);
107 else if(!clean && !create_makefile)
110 const vector<string> &args = getopt.get_args();
111 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
113 string::size_type equal = i->find('=');
114 if(equal!=string::npos)
115 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
117 cmdline_targets.push_back(*i);
120 if(cmdline_targets.empty())
121 cmdline_targets.push_back("default");
123 if(!work_dir.empty())
128 package_manager.set_no_externals(no_externals);
130 load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
131 load_build_file((FS::get_user_data_dir("builder")/"rc").str());
134 current_arch = &native_arch;
136 current_arch = new Architecture(*this, arch);
138 if(!current_arch->is_native())
140 for(StringMap::const_iterator i=cross_prefixes.begin(); i!=cross_prefixes.end(); ++i)
141 if(current_arch->match_name(i->first))
143 current_arch->set_cross_prefix(i->second);
148 toolchain.add_tool(new GnuCCompiler(*this));
149 toolchain.add_tool(new GnuCxxCompiler(*this));
150 toolchain.add_tool(new GnuLinker(*this));
151 toolchain.add_tool(new GnuArchiver(*this));
152 toolchain.add_tool(new Copy(*this));
153 toolchain.add_tool(new Tar(*this));
154 toolchain.add_tool(new PkgConfigGenerator(*this));
158 if(current_arch->is_native())
159 prefix = (FS::get_home_dir()/"local").str();
161 prefix = (FS::get_home_dir()/"local"/current_arch->get_name()).str();
164 prefix = FS::getcwd()/prfx;
166 warnings.push_back("all");
167 warnings.push_back("extra");
168 warnings.push_back("shadow");
169 warnings.push_back("pointer-arith");
170 warnings.push_back("error");
171 for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
173 vector<string> warns = split(*i, ',');
174 warnings.insert(warnings.end(), warns.begin(), warns.end());
180 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
187 if(prefix.str()!="/usr")
189 FS::Path pcdir = prefix/"lib"/"pkgconfig";
190 if(const char *pcp = getenv("PKG_CONFIG_PATH"))
192 vector<string> path = split(pcp, ':');
194 for(vector<string>::const_iterator i=path.begin(); (!found && i!=path.end()); ++i)
195 found = (*i==pcdir.str());
198 path.push_back(pcdir.str());
199 setenv("PKG_CONFIG_PATH", join(path.begin(), path.end(), ":").c_str(), true);
203 setenv("PKG_CONFIG_PATH", pcdir.str().c_str(), true);
206 if(load_build_file(cwd/build_file))
210 usage(0, "builder", false);
215 IO::print(IO::cerr, "No build info here.\n");
220 main_pkg->configure(cmdline_options, conf_all?2:1);
224 usage(0, "builder", false);
238 IO::print("Building on %s, for %s%s\n", native_arch.get_name(),
239 current_arch->get_name(), (current_arch->is_native() ? " (native)" : ""));
240 IO::print("Prefix is %s\n", prefix);
245 const PackageManager::PackageMap &packages = package_manager.get_packages();
246 unsigned n_packages = 0;
247 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
248 if(i->second && i->second->is_configured())
250 IO::print("%d active packages, %d targets\n", n_packages, targets.size());
255 const PackageManager::PackageMap &packages = package_manager.get_packages();
256 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
258 if(!i->second->is_configured())
261 IO::print(" %s", i->second->get_name());
262 if(dynamic_cast<SourcePackage *>(i->second))
265 unsigned to_be_built = 0;
266 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
267 if(j->second->get_package()==i->second)
270 if(j->second->needs_rebuild())
275 IO::print(" (%d targets", count);
277 IO::print(", %d to be built", to_be_built);
287 if(!problems.empty())
289 IO::print(IO::cerr, "The following problems were detected:\n");
290 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
291 IO::print(IO::cerr, " %s: %s\n", i->package, i->descr);
293 IO::print(IO::cerr, "Please fix them and try again.\n");
298 exit_code = do_clean();
300 exit_code = do_build();
305 Target *Builder::get_target(const string &n) const
307 TargetMap::const_iterator i = targets.find(n);
313 void Builder::apply_profile_template(Config &config, const string &pt) const
315 vector<string> parts = split(pt, '-');
317 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
319 ProfileTemplateMap::const_iterator j = profile_tmpl.find(*i);
320 if(j==profile_tmpl.end())
323 config.update(j->second);
327 void Builder::problem(const string &p, const string &d)
329 problems.push_back(Problem(p, d));
332 void Builder::add_target(Target *t)
334 targets.insert(TargetMap::value_type(t->get_name(), t));
337 void Builder::usage(const char *reason, const char *argv0, bool brief)
340 IO::print(IO::cerr, "%s\n", reason);
343 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
346 IO::print(IO::cerr, "Builder 1.0\n\n");
347 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
348 IO::print(IO::cerr, "Options:\n");
349 IO::print(IO::cerr, helpmsg);
353 int Builder::load_build_file(const FS::Path &fn)
358 IO::BufferedFile in(fn.str());
361 IO::print("Reading %s\n", fn);
363 DataFile::Parser parser(in, fn.str());
364 Loader loader(*this, fn.subpath(0, fn.size()-1));
370 int Builder::create_targets()
372 Target *world = new VirtualTarget(*this, "world");
374 Target *def_tgt = new VirtualTarget(*this, "default");
375 world->add_depend(def_tgt);
377 Target *install = new VirtualTarget(*this, "install");
378 world->add_depend(install);
380 Target *tarballs = new VirtualTarget(*this, "tarballs");
381 world->add_depend(tarballs);
383 const PackageManager::PackageMap &packages = package_manager.get_packages();
384 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
385 if(i->second && i->second->is_configured())
386 i->second->create_targets();
388 // Make the cmdline target depend on all targets mentioned on the command line
389 Target *cmdline = new VirtualTarget(*this, "cmdline");
390 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
392 Target *tgt = get_target(*i);
394 tgt = vfs.get_target(*i);
396 tgt = vfs.get_target(cwd/ *i);
399 IO::print("I don't know anything about %s\n", *i);
403 cmdline->add_depend(tgt);
409 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
411 FileTarget *tgt = vfs.get_target(cwd/ *i);
414 IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
422 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
423 if(i->second->is_buildable() && !i->second->needs_rebuild())
424 i->second->force_rebuild();
427 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
428 if(SourcePackage *spkg = dynamic_cast<SourcePackage *>(i->second))
429 spkg->get_deps_cache().save();
434 int Builder::do_build()
436 Target *cmdline = get_target("cmdline");
439 for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
440 if(i->second->is_buildable() && i->second->needs_rebuild())
445 IO::print("Already up to date\n");
449 IO::print("Will build %d target%s\n", total, (total!=1 ? "s" : ""));
451 vector<Task *> tasks;
460 if(tasks.size()<jobs && !fail)
462 Target *tgt = cmdline->get_buildable_target();
466 IO::print("%-4s %s\n", tgt->get_tool()->get_tag(), tgt->get_name());
467 Task *task = tgt->build();
471 IO::print("%s\n", task->get_command());
474 task->signal_finished.emit(true);
480 tasks.push_back(task);
485 IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
487 else if(tasks.empty())
491 Time::sleep(10*Time::msec);
493 for(unsigned i=0; i<tasks.size();)
495 Task::Status 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)
515 IO::print("Build failed\n");
516 else if(show_progress)
517 IO::print("Build complete\n");
522 int Builder::do_clean()
524 // Cleaning doesn't care about ordering, so a simpler method can be used
526 set<Target *> clean_tgts;
527 list<Target *> queue;
528 queue.push_back(get_target("cmdline"));
530 while(!queue.empty())
532 Target *tgt = queue.front();
533 queue.erase(queue.begin());
535 if(tgt->is_buildable() && (tgt->get_package()==main_pkg || clean>=2))
536 clean_tgts.insert(tgt);
538 const Target::Dependencies &deps = tgt->get_depends();
539 for(list<Target *>::const_iterator i=deps.begin(); i!=deps.end(); ++i)
540 if(!clean_tgts.count(*i))
544 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
545 if(FileTarget *ft = dynamic_cast<FileTarget *>(*i))
547 FS::unlink(ft->get_path());
552 void Builder::package_help()
554 const Config &config = main_pkg->get_config();
555 const Config::OptionMap &options = config.get_options();
557 IO::print("Required packages:\n ");
558 const PackageList &requires = main_pkg->get_requires();
559 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
561 if(i!=requires.begin())
563 IO::print((*i)->get_name());
565 IO::print("\n\nPackage configuration:\n");
566 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
568 const Config::Option &opt = i->second;
569 IO::print(" %s: %s (%s)", opt.name, opt.descr, opt.value);
570 if(opt.value!=opt.defv)
571 IO::print(" [%s]", opt.defv);
576 string Builder::usagemsg;
577 string Builder::helpmsg;
580 Builder::Loader::Loader(Builder &b, const FS::Path &s):
584 add("binary_package", &Loader::binpkg);
585 add("cross_prefix", &Loader::cross_prefix);
586 add("profile", &Loader::profile);
587 add("package", &Loader::package);
590 void Builder::Loader::binpkg(const string &n)
592 BinaryPackage *pkg = new BinaryPackage(bld, n);
596 void Builder::Loader::cross_prefix(const string &a, const string &p)
598 bld.cross_prefixes[a] = p;
601 void Builder::Loader::profile(const string &n)
604 ProfileLoader ldr(prf);
606 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
609 void Builder::Loader::package(const string &n)
611 SourcePackage *pkg = new SourcePackage(bld, n, src);
619 Builder::ProfileLoader::ProfileLoader(StringMap &p):
622 add("option", &ProfileLoader::option);
625 void Builder::ProfileLoader::option(const string &o, const string &v)
627 profile.insert(StringMap::value_type(o, v));