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 "externaltask.h"
21 #include "gnuarchiver.h"
22 #include "gnuccompiler.h"
23 #include "gnucxxcompiler.h"
24 #include "gnulinker.h"
25 #include "installedfile.h"
27 #include "pkgconfigfile.h"
28 #include "pkgconfiggenerator.h"
29 #include "sharedlibrary.h"
30 #include "sourcepackage.h"
33 #include "virtualtarget.h"
38 Builder::Builder(int argc, char **argv):
40 native_arch(*this, string()),
54 create_makefile(false)
58 bool full_paths = false;
59 unsigned max_depth = 5;
60 StringList cmdline_warn;
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 toolchain.add_tool(new GnuCCompiler(*this));
129 toolchain.add_tool(new GnuCxxCompiler(*this));
130 toolchain.add_tool(new GnuLinker(*this));
131 toolchain.add_tool(new GnuArchiver(*this));
132 toolchain.add_tool(new Copy(*this));
133 toolchain.add_tool(new Tar(*this));
134 toolchain.add_tool(new PkgConfigGenerator(*this));
136 load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
137 load_build_file((FS::get_user_data_dir("builder")/"rc").str());
140 current_arch = &native_arch;
142 current_arch = new Architecture(*this, arch);
144 if(!current_arch->is_native())
146 for(StringMap::const_iterator i=cross_prefixes.begin(); i!=cross_prefixes.end(); ++i)
147 if(current_arch->match_name(i->first))
149 current_arch->set_cross_prefix(i->second);
156 if(current_arch->is_native())
157 prefix = (FS::get_home_dir()/"local").str();
159 prefix = (FS::get_home_dir()/"local"/current_arch->get_name()).str();
162 prefix = FS::getcwd()/prfx;
164 warnings.push_back("all");
165 warnings.push_back("extra");
166 warnings.push_back("shadow");
167 warnings.push_back("pointer-arith");
168 warnings.push_back("error");
169 for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
171 vector<string> warns = split(*i, ',');
172 warnings.insert(warnings.end(), warns.begin(), warns.end());
175 pkg_path.push_back(cwd/".");
176 pkg_path.push_back(cwd/"..");
181 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
183 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
190 if(prefix.str()!="/usr")
192 FS::Path pcdir = prefix/"lib"/"pkgconfig";
193 if(const char *pcp = getenv("PKG_CONFIG_PATH"))
195 vector<string> path = split(pcp, ':');
197 for(vector<string>::const_iterator i=path.begin(); (!found && i!=path.end()); ++i)
198 found = (*i==pcdir.str());
201 path.push_back(pcdir.str());
202 setenv("PKG_CONFIG_PATH", join(path.begin(), path.end(), ":").c_str(), true);
206 setenv("PKG_CONFIG_PATH", pcdir.str().c_str(), true);
209 if(load_build_file(cwd/build_file))
213 usage(0, "builder", false);
218 IO::print(IO::cerr, "No build info here.\n");
223 main_pkg->configure(cmdline_options, conf_all?2:1);
227 usage(0, "builder", false);
241 IO::print("Building on %s, for %s%s\n", native_arch.get_name(),
242 current_arch->get_name(), (current_arch->is_native() ? " (native)" : ""));
243 IO::print("Prefix is %s\n", prefix);
248 unsigned n_packages = 0;
249 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
250 if(i->second && i->second->is_configured())
252 IO::print("%d active packages, %d targets\n", n_packages, targets.size());
257 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
259 if(!i->second->is_configured())
262 IO::print(" %s", i->second->get_name());
263 if(dynamic_cast<SourcePackage *>(i->second))
266 unsigned to_be_built = 0;
267 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
268 if(j->second->get_package()==i->second)
271 if(j->second->needs_rebuild())
276 IO::print(" (%d targets", count);
278 IO::print(", %d to be built", to_be_built);
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 string Builder::run_pkgconfig(const string &pkg, const string &what)
309 argv.push_back("pkg-config");
310 if(what=="cflags" || what=="libs")
311 argv.push_back("--"+what);
312 else if(what=="flags")
314 argv.push_back("--cflags");
315 argv.push_back("--libs");
318 argv.push_back("--variable="+what);
322 IO::print("Running %s\n", join(argv.begin(), argv.end()));
324 ExternalTask task(argv, FS::Path());
325 task.set_stdout(ExternalTask::CAPTURE);
326 task.set_stderr(ExternalTask::IGNORE);
329 while((status=task.check())==Task::RUNNING)
330 Time::sleep(10*Time::msec);
331 if(status==Task::ERROR)
332 throw runtime_error(format("pkg-config for package %s failed", pkg));
334 return task.get_output();
337 Package *Builder::get_package(const string &name)
339 PackageMap::iterator i = packages.find(format("%s/%s", name, current_arch->get_system()));
340 if(i==packages.end())
341 i = packages.find(name);
342 if(i!=packages.end())
347 FS::Path path = get_package_location(name);
348 if(!path.empty() && !load_build_file(path/"Build"))
350 i = packages.find(name);
351 if(i!=packages.end())
359 // Package source not found - create a binary package
360 pkg = BinaryPackage::from_pkgconfig(*this, name);
364 problem(name, "not found");
367 packages.insert(PackageMap::value_type(name, pkg));
372 Target *Builder::get_target(const string &n) const
374 TargetMap::const_iterator i = targets.find(n);
380 void Builder::apply_profile_template(Config &config, const string &pt) const
382 vector<string> parts = split(pt, '-');
384 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
386 ProfileTemplateMap::const_iterator j = profile_tmpl.find(*i);
387 if(j==profile_tmpl.end())
390 config.update(j->second);
394 void Builder::problem(const string &p, const string &d)
396 problems.push_back(Problem(p, d));
399 void Builder::add_target(Target *t)
401 targets.insert(TargetMap::value_type(t->get_name(), t));
402 new_tgts.push_back(t);
405 void Builder::usage(const char *reason, const char *argv0, bool brief)
408 IO::print(IO::cerr, "%s\n", reason);
411 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
414 IO::print(IO::cerr, "Builder 1.0\n\n");
415 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
416 IO::print(IO::cerr, "Options:\n");
417 IO::print(IO::cerr, helpmsg);
421 FS::Path Builder::get_package_location(const string &name)
424 IO::print("Looking for package %s\n", name);
428 // Try to get source directory with pkgconfig
429 string srcdir = strip(run_pkgconfig(name, "source"));
438 for(list<FS::Path>::const_iterator i=pkg_path.begin(); i!=pkg_path.end(); ++i)
440 list<string> files = list_files(*i);
441 for(list<string>::const_iterator j=files.begin(); j!=files.end(); ++j)
443 FS::Path full = *i / *j;
444 if(FS::exists(full/"Build"))
445 pkg_dirs.push_back(full);
449 IO::print("%d packages found in path\n", pkg_dirs.size());
452 bool msp = !name.compare(0, 3, "msp");
453 for(list<FS::Path>::const_iterator i=pkg_dirs.begin(); i!=pkg_dirs.end(); ++i)
455 string base = basename(*i);
456 unsigned dash = base.rfind('-');
458 if(!base.compare(0, dash, name))
460 else if(msp && !base.compare(0, dash-3, name, 3, string::npos))
467 int Builder::load_build_file(const FS::Path &fn)
472 IO::BufferedFile in(fn.str());
475 IO::print("Reading %s\n", fn);
477 DataFile::Parser parser(in, fn.str());
478 Loader loader(*this, fn.subpath(0, fn.size()-1));
484 int Builder::create_targets()
486 Target *world = new VirtualTarget(*this, "world");
488 Target *def_tgt = new VirtualTarget(*this, "default");
489 world->add_depend(def_tgt);
491 Target *install = new VirtualTarget(*this, "install");
492 world->add_depend(install);
494 Target *tarballs = new VirtualTarget(*this, "tarballs");
495 world->add_depend(tarballs);
497 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
499 if(!i->second || !i->second->is_configured())
502 SourcePackage *spkg = dynamic_cast<SourcePackage *>(i->second);
506 const ComponentList &components = spkg->get_components();
507 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
510 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
512 PkgConfigFile *pc = new PkgConfigFile(*this, *spkg);
513 install->add_depend(toolchain.get_tool("CP").create_target(*pc));
518 // XXX This does not currently work with targets found during dependency discovery
519 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
521 FileTarget *tgt = vfs.get_target(cwd/ *i);
524 IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
530 // Make the cmdline target depend on all targets mentioned on the command line
531 Target *cmdline = new VirtualTarget(*this, "cmdline");
532 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
534 Target *tgt = get_target(*i);
536 tgt = vfs.get_target(*i);
538 tgt = vfs.get_target(cwd/ *i);
541 IO::print("I don't know anything about %s\n", *i);
545 cmdline->add_depend(tgt);
550 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
551 if(SourcePackage *spkg = dynamic_cast<SourcePackage *>(i->second))
552 spkg->get_deps_cache().save();
557 int Builder::do_build()
559 Target *cmdline = get_target("cmdline");
562 for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
563 if(i->second->is_buildable() && i->second->needs_rebuild())
568 IO::print("Already up to date\n");
572 IO::print("Will build %d target%s\n", total, (total!=1 ? "s" : ""));
574 vector<Task *> tasks;
583 if(tasks.size()<jobs && !fail)
585 Target *tgt = cmdline->get_buildable_target();
589 IO::print("%-4s %s\n", tgt->get_tool()->get_tag(), tgt->get_name());
590 Task *task = tgt->build();
594 IO::print("%s\n", task->get_command());
597 task->signal_finished.emit(true);
603 tasks.push_back(task);
608 IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
610 else if(tasks.empty())
614 Time::sleep(10*Time::msec);
616 for(unsigned i=0; i<tasks.size();)
618 Task::Status status = tasks[i]->check();
619 if(status!=Task::RUNNING)
624 tasks.erase(tasks.begin()+i);
625 if(status==Task::ERROR)
627 if(tasks.empty() && fail)
638 IO::print("Build failed\n");
639 else if(show_progress)
640 IO::print("Build complete\n");
645 int Builder::do_clean()
647 // Cleaning doesn't care about ordering, so a simpler method can be used
649 set<Target *> clean_tgts;
650 list<Target *> queue;
651 queue.push_back(get_target("cmdline"));
653 while(!queue.empty())
655 Target *tgt = queue.front();
656 queue.erase(queue.begin());
658 if(tgt->is_buildable() && (tgt->get_package()==main_pkg || clean>=2))
659 clean_tgts.insert(tgt);
661 const Target::Dependencies &deps = tgt->get_depends();
662 for(list<Target *>::const_iterator i=deps.begin(); i!=deps.end(); ++i)
663 if(!clean_tgts.count(*i))
667 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
668 if(FileTarget *ft = dynamic_cast<FileTarget *>(*i))
670 FS::unlink(ft->get_path());
675 void Builder::package_help()
677 const Config &config = main_pkg->get_config();
678 const Config::OptionMap &options = config.get_options();
680 IO::print("Required packages:\n ");
681 const PackageList &requires = main_pkg->get_requires();
682 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
684 if(i!=requires.begin())
686 IO::print((*i)->get_name());
688 IO::print("\n\nPackage configuration:\n");
689 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
691 const Config::Option &opt = i->second;
692 IO::print(" %s: %s (%s)", opt.name, opt.descr, opt.value);
693 if(opt.value!=opt.defv)
694 IO::print(" [%s]", opt.defv);
699 string Builder::usagemsg;
700 string Builder::helpmsg;
703 Builder::Loader::Loader(Builder &b, const FS::Path &s):
707 add("binary_package", &Loader::binpkg);
708 add("cross_prefix", &Loader::cross_prefix);
709 add("profile", &Loader::profile);
710 add("package", &Loader::package);
713 void Builder::Loader::binpkg(const string &n)
715 BinaryPackage *pkg = new BinaryPackage(bld, n);
717 bld.packages.insert(PackageMap::value_type(n, pkg));
720 void Builder::Loader::cross_prefix(const string &a, const string &p)
722 bld.cross_prefixes[a] = p;
725 void Builder::Loader::profile(const string &n)
728 ProfileLoader ldr(prf);
730 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
733 void Builder::Loader::package(const string &n)
735 SourcePackage *pkg = new SourcePackage(bld, n, src);
740 bld.packages.insert(PackageMap::value_type(n, pkg));
744 Builder::ProfileLoader::ProfileLoader(StringMap &p):
747 add("option", &ProfileLoader::option);
750 void Builder::ProfileLoader::option(const string &o, const string &v)
752 profile.insert(StringMap::value_type(o, v));