3 This file is part of builder
4 Copyright © 2006-2009 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
9 #include <sys/utsname.h>
10 #include <msp/core/except.h>
11 #include <msp/core/getopt.h>
12 #include <msp/datafile/parser.h>
13 #include <msp/fs/dir.h>
14 #include <msp/fs/stat.h>
15 #include <msp/fs/utils.h>
16 #include <msp/io/buffered.h>
17 #include <msp/io/except.h>
18 #include <msp/io/file.h>
19 #include <msp/io/print.h>
20 #include <msp/strings/formatter.h>
21 #include <msp/strings/regex.h>
22 #include <msp/strings/utils.h>
23 #include <msp/time/units.h>
24 #include <msp/time/utils.h>
27 #include "binarypackage.h"
33 #include "pkgconfig.h"
34 #include "sharedlibrary.h"
35 #include "sourcepackage.h"
36 #include "systemlibrary.h"
38 #include "virtualtarget.h"
45 void update_hash(string &hash, const string &value)
47 for(unsigned i=0; i<value.size(); ++i)
48 hash[i%hash.size()]^=value[i];
54 Builder::Builder(int argc, char **argv):
68 create_makefile(false)
72 bool full_paths=false;
74 StringList cmdline_warn;
79 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG).set_help("Perform analysis. MODE can be deps, alldeps or rebuild.", "MODE");
80 getopt.add_option('b', "build", build, GetOpt::NO_ARG).set_help("Perform build even if doing analysis.");
81 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG).set_help("Clean buildable targets.");
82 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG).set_help("Read info from FILE instead of Build.", "FILE");
83 getopt.add_option('h', "help", help, GetOpt::NO_ARG).set_help("Print this message.");
84 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG).set_help("Run NUM commands at once, whenever possible.", "NUM");
85 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG).set_help("Don't actually do anything, only show what would be done.");
86 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG).set_help("Print more information about what's going on.");
87 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
88 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
89 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
90 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
91 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
92 getopt.add_option( "arch", arch, GetOpt::REQUIRED_ARG).set_help("Architecture to build for.", "ARCH");
93 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG).set_help("Stop after configuring packages.");
94 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG).set_help("Output full paths in analysis.");
95 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG).set_help("Maximum depth to show in analysis.", "NUM");
96 getopt.add_option( "prefix", prfx, GetOpt::REQUIRED_ARG).set_help("Directory to install things to.", "DIR");
97 getopt.add_option( "warnings", cmdline_warn, GetOpt::REQUIRED_ARG).set_help("Compiler warnings to use.", "LIST");
98 usagemsg=getopt.generate_usage(argv[0])+" [<target> ...]";
99 helpmsg=getopt.generate_help();
102 if(!analyze_mode.empty())
104 analyzer=new Analyzer(*this);
106 if(analyze_mode=="deps")
107 analyzer->set_mode(Analyzer::DEPS);
108 else if(analyze_mode=="alldeps")
109 analyzer->set_mode(Analyzer::ALLDEPS);
110 else if(analyze_mode=="rebuild")
111 analyzer->set_mode(Analyzer::REBUILD);
112 else if(analyze_mode=="rdeps")
113 analyzer->set_mode(Analyzer::RDEPS);
115 throw UsageError("Invalid analyze mode");
117 analyzer->set_max_depth(max_depth);
118 analyzer->set_full_paths(full_paths);
120 else if(!clean && !create_makefile)
123 const vector<string> &args=getopt.get_args();
124 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
126 unsigned equal=i->find('=');
127 if(equal!=string::npos)
128 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
130 cmdline_targets.push_back(*i);
133 if(cmdline_targets.empty())
134 cmdline_targets.push_back("default");
136 if(!work_dir.empty())
142 string sysname="native";
144 sysname=tolower(un.sysname);
146 native_arch=&archs.insert(ArchMap::value_type(sysname, Architecture(*this, sysname, true))).first->second;
147 native_arch->set_tool("CC", "gcc");
148 native_arch->set_tool("CXX", "g++");
149 native_arch->set_tool("LD", "gcc");
150 native_arch->set_tool("LXX", "g++");
151 native_arch->set_tool("AR", "ar");
153 load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
154 load_build_file((FS::get_home_dir()/".builderrc").str());
157 current_arch=native_arch;
159 current_arch=&get_architecture(arch);
163 if(current_arch->is_native())
164 prefix=(FS::get_home_dir()/"local").str();
166 prefix=(FS::get_home_dir()/"local"/current_arch->get_name()).str();
169 prefix=FS::getcwd()/prfx;
171 warnings.push_back("all");
172 warnings.push_back("extra");
173 warnings.push_back("shadow");
174 warnings.push_back("pointer-arith");
175 warnings.push_back("error");
176 for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
178 vector<string> warns=split(*i, ',');
179 warnings.insert(warnings.end(), warns.begin(), warns.end());
182 pkg_path.push_back(cwd/".");
183 pkg_path.push_back(cwd/"..");
188 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
190 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
197 if(load_build_file(cwd/build_file))
201 usage(0, "builder", false);
206 IO::print(IO::cerr, "No build info here.\n");
211 main_pkg->configure(cmdline_options, conf_all?2:1);
215 usage(0, "builder", false);
221 if(!conf_only && create_targets())
224 PackageList all_reqs=main_pkg->collect_requires();
230 IO::print("Building on %s, for %s\n", native_arch->get_name(), current_arch->get_name());
232 IO::print("%d active packages, %d targets\n", all_reqs.size(), targets.size());
235 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
237 IO::print(" %s", (*i)->get_name());
238 if(dynamic_cast<SourcePackage *>(*i))
241 unsigned ood_count=0;
242 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
243 if(j->second->get_package()==*i)
246 if(j->second->get_rebuild())
251 IO::print(" (%d targets", count);
253 IO::print(", %d out-of-date", ood_count);
263 if(!problems.empty())
265 IO::print(IO::cerr, "The following problems were detected:\n");
266 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
267 IO::print(IO::cerr, " %s: %s\n", i->package, i->descr);
268 IO::print(IO::cerr, "Please fix them and try again.\n");
275 exit_code=do_clean();
277 exit_code=do_build();
282 Package *Builder::get_package(const string &name)
284 PackageMap::iterator i=packages.find(format("%s/%s", name, current_arch->get_name()));
285 if(i==packages.end())
286 i=packages.find(name);
287 if(i!=packages.end())
290 FS::Path path=get_package_location(name);
291 if(!path.empty() && !load_build_file(path/"Build"))
293 i=packages.find(name);
294 if(i!=packages.end())
298 // Package source not found - create a binary package
299 Package *pkg=BinaryPackage::from_pkgconfig(*this, name);
301 packages.insert(PackageMap::value_type(name, pkg));
304 problem(name, "not found");
309 Target *Builder::get_target(const string &n) const
311 // XXX Used for getting targets by path. get_target(const FS::Path &)?
312 TargetMap::const_iterator i=targets.find(n);
318 Target *Builder::get_header(const string &include, const FS::Path &from, const list<string> &path)
322 update_hash(hash, from.str());
323 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
324 update_hash(hash, *i);
326 string id=hash+include;
327 TargetMap::iterator i=includes.find(id);
328 if(i!=includes.end())
331 static string cxx_ver;
335 argv.push_back(current_arch->get_tool("CXX"));
336 argv.push_back("--version");
337 cxx_ver=Regex("[0-9]\\.[0-9.]+").match(run_command(argv))[0].str;
338 while(!cxx_ver.empty() && !FS::is_dir(FS::Path("/usr/include/c++")/cxx_ver))
340 unsigned dot=cxx_ver.rfind('.');
341 if(dot==string::npos)
346 IO::print("C++ version is %s\n", cxx_ver);
349 string fn=include.substr(1);
351 IO::print("Looking for include %s from %s with path %s\n", fn, from, join(path.begin(), path.end()));
354 if(current_arch->is_native())
355 syspath.push_back("/usr/include");
357 syspath.push_back("/usr/"+current_arch->get_prefix()+"/include");
358 syspath.push_back((FS::Path("/usr/include/c++/")/cxx_ver).str());
362 tgt=get_header(FS::Path(from)/fn);
363 for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
364 tgt=get_header(cwd/ *j/fn);
365 for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
366 tgt=get_header(FS::Path(*j)/fn);
368 includes.insert(TargetMap::value_type(id, tgt));
373 Target *Builder::get_library(const string &lib, const list<string> &path, LibMode mode)
376 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
377 update_hash(hash, *i);
379 string id=hash+string(1, mode)+lib;
380 TargetMap::iterator i=libraries.find(id);
381 if(i!=libraries.end())
385 if(current_arch->is_native())
387 syspath.push_back("/lib");
388 syspath.push_back("/usr/lib");
391 syspath.push_back("/usr/"+current_arch->get_prefix()+"/lib");
394 IO::print("Looking for library %s with path %s\n", lib, join(path.begin(), path.end()));
397 for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
398 tgt=get_library(lib, cwd/ *j, mode);
399 for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
400 tgt=get_library(lib, *j, mode);
402 libraries.insert(TargetMap::value_type(id, tgt));
407 const Architecture &Builder::get_architecture(const string &arch) const
409 ArchMap::const_iterator i=archs.find(arch);
411 throw KeyError("Unknown architecture", arch);
416 void Builder::apply_profile_template(Config &config, const string &pt) const
418 vector<string> parts=split(pt, '-');
420 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
422 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
423 if(j==profile_tmpl.end())
426 config.update(j->second);
430 void Builder::problem(const string &p, const string &d)
432 problems.push_back(Problem(p, d));
435 void Builder::add_target(Target *t)
437 targets.insert(TargetMap::value_type(t->get_name(), t));
438 new_tgts.push_back(t);
441 void Builder::usage(const char *reason, const char *argv0, bool brief)
444 IO::print(IO::cerr, "%s\n", reason);
447 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
450 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
451 IO::print(IO::cerr, "Options:\n");
452 IO::print(IO::cerr, helpmsg);
456 FS::Path Builder::get_package_location(const string &name)
459 IO::print("Looking for package %s\n", name);
461 // Try to get source directory with pkgconfig
463 argv.push_back("pkg-config");
464 argv.push_back("--variable=source");
465 argv.push_back(name);
467 IO::print("Running %s\n", join(argv.begin(), argv.end()));
468 string srcdir=strip(run_command(argv));
474 for(list<FS::Path>::const_iterator i=pkg_path.begin(); i!=pkg_path.end(); ++i)
476 list<string> files=list_files(*i);
477 for(list<string>::const_iterator j=files.begin(); j!=files.end(); ++j)
479 FS::Path full=*i / *j;
480 if(FS::exists(full/"Build"))
481 pkg_dirs.push_back(full);
485 IO::print("%d packages found in path\n", pkg_dirs.size());
488 bool msp=!name.compare(0, 3, "msp");
489 for(list<FS::Path>::const_iterator i=pkg_dirs.begin(); i!=pkg_dirs.end(); ++i)
491 string base=basename(*i);
492 unsigned dash=base.rfind('-');
494 if(!base.compare(0, dash, name))
496 else if(msp && !base.compare(0, dash-3, name, 3, string::npos))
503 int Builder::load_build_file(const FS::Path &fn)
507 IO::BufferedFile in(fn.str());
510 IO::print("Reading %s\n", fn);
512 DataFile::Parser parser(in, fn.str());
513 Loader loader(*this, fn.subpath(0, fn.size()-1));
516 catch(const IO::FileNotFound &)
524 int Builder::create_targets()
526 Target *world=new VirtualTarget(*this, "world");
528 Target *def_tgt=new VirtualTarget(*this, "default");
529 world->add_depend(def_tgt);
531 Target *install=new VirtualTarget(*this, "install");
532 world->add_depend(install);
534 Target *tarballs=new VirtualTarget(*this, "tarballs");
535 world->add_depend(tarballs);
537 PackageList all_reqs=main_pkg->collect_requires();
538 for(PackageList::iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
540 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
544 const ComponentList &components=spkg->get_components();
545 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
548 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
550 PkgConfig *pc=new PkgConfig(*this, *spkg);
551 install->add_depend(new Install(*this, *spkg, *pc));
555 // Find dependencies until no new targets are created
556 while(!new_tgts.empty())
558 Target *tgt=new_tgts.front();
559 new_tgts.erase(new_tgts.begin());
561 if(!tgt->get_depends_ready())
562 new_tgts.push_back(tgt);
566 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
568 Target *tgt=get_target((cwd/ *i).str());
571 IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
577 // Make the cmdline target depend on all targets mentioned on the command line
578 Target *cmdline=new VirtualTarget(*this, "cmdline");
579 bool build_world=false;
580 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
582 Target *tgt=get_target(*i);
584 tgt=get_target((cwd/ *i).str());
587 IO::print("I don't know anything about %s\n", *i);
592 cmdline->add_depend(tgt);
595 /* If world is to be built, prepare cmdline. If not, add cmdline to world
596 and prepare world. I don't really like this, but it keeps the graph
599 XXX Could we skip preparing targets we are not interested in? */
604 world->add_depend(cmdline);
608 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
609 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
610 spkg->get_deps_cache().save();
615 Target *Builder::get_header(const Msp::FS::Path &fn)
617 Target *tgt=get_target(fn.str());
622 tgt=new SystemHeader(*this, fn.str());
628 Target *Builder::get_library(const string &lib, const FS::Path &path, LibMode mode)
630 // Populate a list of candidate filenames
631 StringList candidates;
635 if(current_arch->get_name()=="win32")
637 candidates.push_back("lib"+lib+".dll");
638 candidates.push_back(lib+".dll");
641 candidates.push_back("lib"+lib+".so");
644 /* Static libraries are always considered, since sometimes shared versions
645 may not be available */
646 candidates.push_back("lib"+lib+".a");
647 if(current_arch->get_name()=="win32")
648 candidates.push_back("lib"+lib+".dll.a");
650 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
652 string full=(path/ *i).str();
653 Target *tgt=get_target(full);
657 Target *real_tgt=tgt;
658 if(Install *inst=dynamic_cast<Install *>(tgt))
659 real_tgt=&inst->get_source();
661 /* Ignore dynamic libraries from local packages unless library mode is
663 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
668 else if(FS::is_reg(full))
670 tgt=new SystemLibrary(*this, full);
678 int Builder::do_build()
680 Target *cmdline=get_target("cmdline");
682 unsigned total=cmdline->count_rebuild();
685 IO::print("Already up to date\n");
689 IO::print("Will build %d target%s\n", total, (total!=1 ? "s" : ""));
691 vector<Action *> actions;
700 if(actions.size()<jobs && !fail)
702 Target *tgt=cmdline->get_buildable_target();
705 Action *action=tgt->build();
707 actions.push_back(action);
710 IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
712 else if(actions.empty())
716 Time::sleep(10*Time::msec);
718 for(unsigned i=0; i<actions.size();)
720 int status=actions[i]->check();
726 actions.erase(actions.begin()+i);
729 if(actions.empty() && fail)
740 IO::print("Build failed\n");
741 else if(show_progress)
742 IO::print("Build complete\n");
747 int Builder::do_clean()
749 // Cleaning doesn't care about ordering, so a simpler method can be used
751 set<Target *> clean_tgts;
753 queue.push_back(get_target("cmdline"));
755 while(!queue.empty())
757 Target *tgt=queue.front();
758 queue.erase(queue.begin());
760 if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
761 clean_tgts.insert(tgt);
763 const TargetList &deps=tgt->get_depends();
764 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
765 if(!clean_tgts.count(*i))
769 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
770 if(FileTarget *ft=dynamic_cast<FileTarget *>(*i))
772 Action *action=new Unlink(*this, *ft);
773 while(action->check()<0) ;
780 void Builder::package_help()
782 const Config &config=main_pkg->get_config();
783 const Config::OptionMap &options=config.get_options();
785 IO::print("Required packages:\n ");
786 const PackageList &requires=main_pkg->get_requires();
787 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
789 if(i!=requires.begin())
791 IO::print((*i)->get_name());
793 IO::print("\n\nPackage configuration:\n");
794 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
796 const Config::Option &opt=i->second;
797 IO::print(" %s: %s (%s)", opt.name, opt.descr, opt.value);
798 if(opt.value!=opt.defv)
799 IO::print(" [%s]", opt.defv);
804 Application::RegApp<Builder> Builder::reg;
805 string Builder::usagemsg;
806 string Builder::helpmsg;
809 Builder::Loader::Loader(Builder &b, const FS::Path &s):
813 add("architecture", &Loader::architecture);
814 add("binary_package", &Loader::binpkg);
815 add("profile", &Loader::profile);
816 add("package", &Loader::package);
819 void Builder::Loader::architecture(const string &n)
821 Architecture arch(bld, n);
823 bld.archs.insert(ArchMap::value_type(n, arch));
826 void Builder::Loader::binpkg(const string &n)
828 BinaryPackage *pkg=new BinaryPackage(bld, n);
830 bld.packages.insert(PackageMap::value_type(n, pkg));
833 void Builder::Loader::profile(const string &n)
836 ProfileLoader ldr(prf);
838 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
841 void Builder::Loader::package(const string &n)
843 SourcePackage *pkg=new SourcePackage(bld, n, src);
848 bld.packages.insert(PackageMap::value_type(n, pkg));
852 Builder::ProfileLoader::ProfileLoader(StringMap &p):
855 add("option", &ProfileLoader::option);
858 void Builder::ProfileLoader::option(const string &o, const string &v)
860 profile.insert(StringMap::value_type(o, v));