3 #include <msp/progress.h>
4 #include <msp/strconv.h>
5 #include <msp/strutils.h>
6 #include <msp/core/error.h>
7 #include <msp/getopt++/getopt++.h>
8 #include <msp/parser/parser.h>
9 #include <msp/path/utils.h>
10 #include <msp/time/units.h>
11 #include <msp/time/utils.h>
15 #include "executable.h"
19 #include "objectfile.h"
21 #include "sharedlibrary.h"
22 #include "staticlibrary.h"
23 #include "systemlibrary.h"
24 #include "virtualtarget.h"
29 Builder::Builder(int argc, char **argv):
38 getopt.add_option(GetOpt::Option('a', "analyze", GetOpt::REQUIRED));
39 getopt.add_option(GetOpt::Option('b', "build", GetOpt::NONE));
40 getopt.add_option(GetOpt::Option('c', "clean", GetOpt::NONE));
41 getopt.add_option(GetOpt::Option('f', "file", GetOpt::REQUIRED, "Build"));
42 getopt.add_option(GetOpt::Option('h', "help", GetOpt::NONE));
43 getopt.add_option(GetOpt::Option('j', "jobs", GetOpt::REQUIRED, "1"));
44 getopt.add_option(GetOpt::Option('n', "dry-run", GetOpt::NONE));
45 getopt.add_option(GetOpt::Option('v', "verbose", GetOpt::NONE));
46 getopt.add_option(GetOpt::Option('A', "conf-all", GetOpt::NONE));
47 getopt.add_option(GetOpt::Option('B', "build-all", GetOpt::NONE));
48 getopt.add_option(GetOpt::Option('C', "chdir", GetOpt::REQUIRED));
49 getopt.add_option(GetOpt::Option('W', "what-if", GetOpt::REQUIRED));
50 getopt.add_option(GetOpt::Option("chrome", GetOpt::NONE));
51 getopt.add_option(GetOpt::Option("full-paths", GetOpt::NONE));
52 getopt.add_option(GetOpt::Option("max-depth", GetOpt::REQUIRED));
53 int index=getopt(argc, argv);
55 verbose+=getopt['v'].count();
59 analyzer=new Analyzer(*this);
61 string mode=getopt['a'].arg();
63 analyzer->set_mode(Analyzer::DEPS);
64 else if(mode=="alldeps")
65 analyzer->set_mode(Analyzer::ALLDEPS);
66 else if(mode=="rebuild")
67 analyzer->set_mode(Analyzer::REBUILD);
68 else if(mode=="rdeps")
69 analyzer->set_mode(Analyzer::RDEPS);
71 throw UsageError("Invalid analysis mode");
73 if(getopt["max-depth"])
74 analyzer->set_max_depth(strtol(getopt["max-depth"].arg()));
75 analyzer->set_full_paths(getopt["full-paths"]);
82 jobs=max(strtol(getopt['j'].arg()), 1L);
83 chrome=getopt["chrome"];
85 build_file=getopt['f'].arg();
86 build_all=getopt['B'];
90 chdir(getopt['C'].arg().c_str());
92 for(int i=index; i<argc; ++i)
95 unsigned equal=v.find('=');
96 if(equal!=string::npos)
97 cmdline_options.insert(RawOptionMap::value_type(v.substr(0, equal), v.substr(equal+1)));
99 cmdline_targets.push_back(argv[i]);
102 if(cmdline_targets.empty())
103 cmdline_targets.push_back("default");
106 what_if.push_back(getopt['W'].arg());
112 Gets a package with the specified name, possibly creating it.
114 @param n Package name
116 @return Pointer to the package, or 0 if the package could not be located
118 Package *Builder::get_package(const string &n)
120 PackageMap::iterator i=packages.find(n);
121 if(i!=packages.end())
124 // Try to get source directory with pkgconfig
126 argv.push_back("pkg-config");
127 argv.push_back("--variable=source");
129 string srcdir=strip(run_command(argv));
133 dirs.push_back(srcdir);
135 // Make some other guesses about the source directory
137 if(!dirname.compare(0, 3, "msp"))
139 dirs.push_back(cwd/dirname);
140 dirs.push_back(cwd/".."/dirname);
142 // Go through the candidate directories and look for a Build file
143 for(PathList::iterator j=dirs.begin(); j!=dirs.end(); ++j)
144 if(!load_build_file(*j/"Build"))
147 if(i!=packages.end())
152 // Package source not found - create a binary package
153 Package *pkg=Package::create(*this, n);
154 packages.insert(PackageMap::value_type(n, pkg));
156 new_pkgs.push_back(pkg);
162 Returns the target with the given name, or 0 if no such target exists.
164 Target *Builder::get_target(const string &n)
166 TargetMap::iterator i=targets.find(n);
173 Tries to locate a header included from a given location and with a given include
174 path. Considers known targets as well as existing files.
176 Target *Builder::get_header(const string &include, const string &from, const list<string> &path)
179 update_hash(hash, from);
180 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
181 update_hash(hash, *i);
183 string id=hash+include;
184 TargetMap::iterator i=includes.find(id);
185 if(i!=includes.end())
188 string fn=include.substr(1);
190 if(include[0]=='"' && (tgt=check_header(Path::Path(from)/fn)))
192 if((tgt=check_header(Path::Path("/usr/include")/fn)))
194 //XXX Determine the C++ header location dynamically
195 if((tgt=check_header(Path::Path("/usr/include/c++/4.1.2")/fn)))
197 for(list<string>::const_iterator j=path.begin(); j!=path.end(); ++j)
198 if((tgt=check_header(cwd/ *j/fn)))
204 Target *Builder::get_library(const string &lib, const list<string> &path)
207 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
208 update_hash(hash, *i);
211 TargetMap::iterator i=libraries.find(id);
212 if(i!=libraries.end())
215 string basename="lib"+lib+".so";
216 for(list<string>::const_iterator j=path.begin(); j!=path.end(); ++j)
218 string full=(cwd/ *j/basename).str();
219 Target *tgt=get_target(full);
222 if(Path::exists(full))
224 add_target(tgt=new SystemLibrary(*this, full));
234 if(load_build_file(cwd/build_file))
236 cerr<<"No build info here.\n";
240 default_pkg=packages.begin()->second;
242 while(!new_pkgs.empty())
244 Package *pkg=new_pkgs.front();
245 if(pkg==default_pkg || conf_all)
246 pkg->process_options(cmdline_options);
247 new_pkgs.erase(new_pkgs.begin());
253 usage("builder", false);
260 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
262 missing.push_back(i->first);
267 cerr<<"The following packages were not found on the system:\n";
268 for(list<string>::iterator i=missing.begin(); i!=missing.end(); ++i)
270 cerr<<"Please install them and try again.\n";
274 default_pkg->create_build_info();
279 cout<<packages.size()<<" packages, "<<targets.size()<<" targets\n";
282 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
284 cout<<' '<<i->second->get_name();
285 if(i->second->get_buildable())
288 unsigned ood_count=0;
289 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
290 if(j->second->get_package()==i->second)
293 if(j->second->get_rebuild())
298 cout<<" ("<<count<<" targets";
300 cout<<", "<<ood_count<<" out-of-date";
318 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
320 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
325 void Builder::usage(const char *argv0, bool brief)
328 cerr<<"Usage: "<<argv0<<" [-a|--analyze MODE] [-b|--build] [-c|--clean] [-f|--file FILE] [-h|--help] [-j|--jobs NUM] [-n||--dry-run] [-v|--verbose] [-A|--conf-all] [-B|--build-all] [-C|--chdir DIRECTORY] [-W|--what-if FILE] [--chrome] [--full-paths] [--max-depth NUM] [<target> ...]";
332 "Usage: "<<argv0<<" [options] [<target> ...]\n"
335 " -a, --analyze MODE Perform analysis. MODE can be deps, alldeps or rebuild.\n"
336 " -b, --build Perform build even if doing analysis.\n"
337 " -c, --clean Clean buildable targets.\n"
338 " -f, --file FILE Read info from FILE instead of Build.\n"
339 " -h, --help Print this message.\n"
340 " -j, --jobs NUM Run NUM commands at once, whenever possible.\n"
341 " -n, --dry-run Don't actually do anything, only show what would be done.\n"
342 " -v, --verbose Print more information about what's going on.\n"
343 " -A, --conf-all Apply configuration to all packages.\n"
344 " -B, --build-all Build all targets unconditionally.\n"
345 " -C, --chdir DIR Change to DIR before doing anything else.\n"
346 " -W, --what-if FILE Pretend that FILE has changed.\n"
347 " --chrome Use extra chrome to print status.\n"
348 " --full-paths Output full paths in analysis.\n"
349 " --max-depth NUM Maximum depth to show in analysis.\n";
353 int Builder::load_build_file(const Path::Path &fn)
355 ifstream in(fn.str().c_str());
359 Parser::Parser parser(in, fn.str());
360 Loader loader(*this, fn.subpath(0, fn.size()-1));
366 int Builder::create_targets()
368 Target *world=new VirtualTarget(*this, "world");
371 Target *def_tgt=new VirtualTarget(*this, "default");
373 world->add_depend(def_tgt);
375 Target *install=new VirtualTarget(*this, "install");
377 world->add_depend(install);
379 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
383 if(!i->second->get_buildable())
386 Path::Path inst_base;
387 if(i->second->get_config().is_option("prefix"))
388 inst_base=i->second->get_config().get_option("prefix").value;
390 const ComponentList &components=i->second->get_components();
391 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
394 const PathList &sources=j->get_sources();
395 for(PathList::const_iterator k=sources.begin(); k!=sources.end(); ++k)
399 if(S_ISDIR(st.st_mode))
401 list<string> sfiles=list_files(*k);
402 for(list<string>::iterator l=sfiles.begin(); l!=sfiles.end(); ++l)
403 files.push_back(*k / *l);
409 bool build_exe=j->get_type()!=Component::HEADERS;
411 list<ObjectFile *> objs;
412 for(PathList::iterator k=files.begin(); k!=files.end(); ++k)
414 string basename=(*k)[-1];
415 string ext=Path::splitext(basename).ext;
416 if(ext==".cpp" || ext==".c")
420 SourceFile *src=new SourceFile(*this, &*j, k->str());
423 ObjectFile *obj=new ObjectFile(*this, *j, *src);
430 Target *hdr=get_target(k->str());
433 hdr=new Header(*this, &*j, k->str());
436 if(!j->get_install_headers().empty())
438 Path::Path inst_path=inst_base/"include"/j->get_install_headers()/basename;
439 Install *inst=new Install(*this, *i->second, *hdr, inst_path.str());
441 install->add_depend(inst);
449 StaticLibrary *slib=0;
450 if(j->get_type()==Component::LIBRARY)
452 exe=new SharedLibrary(*this, *j, objs);
453 slib=new StaticLibrary(*this, *j, objs);
457 exe=new Executable(*this, *j, objs);
460 if(i->second==default_pkg)
462 def_tgt->add_depend(exe);
463 if(slib) def_tgt->add_depend(slib);
467 world->add_depend(exe);
468 if(slib) world->add_depend(slib);
474 if(j->get_type()==Component::PROGRAM)
476 else if(j->get_type()==Component::LIBRARY)
478 if(!inst_dir.empty())
480 Install *inst=new Install(*this, *i->second, *exe, (inst_base/inst_dir/Path::basename(exe->get_name())).str());
482 install->add_depend(inst);
486 inst=new Install(*this, *i->second, *slib, (inst_base/inst_dir/Path::basename(slib->get_name())).str());
488 install->add_depend(inst);
496 while(!new_tgts.empty())
498 Target *tgt=new_tgts.front();
499 new_tgts.erase(new_tgts.begin());
501 if(!tgt->get_depends_ready())
502 new_tgts.push_back(tgt);
505 for(list<string>::iterator i=what_if.begin(); i!=what_if.end(); ++i)
507 Target *tgt=get_target((cwd/ *i).str());
510 cerr<<"Unknown what-if target "<<*i<<'\n';
516 Target *cmdline=new VirtualTarget(*this, "cmdline");
518 world->add_depend(cmdline);
519 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
521 Target *tgt=get_target(*i);
523 tgt=get_target((cwd/ *i).str());
526 cerr<<"I don't know anything about "<<*i<<'\n';
529 cmdline->add_depend(tgt);
537 Target *Builder::check_header(const Msp::Path::Path &fn)
539 Target *tgt=get_target(fn.str());
544 add_target(tgt=new SystemHeader(*this, fn.str()));
550 void Builder::add_target(Target *t)
552 targets.insert(TargetMap::value_type(t->get_name(), t));
553 new_tgts.push_back(t);
556 void Builder::update_hash(string &hash, const string &value)
558 for(unsigned i=0; i<value.size(); ++i)
559 hash[i%hash.size()]^=value[i];
563 This function supervises the build process, starting new actions when slots
568 Target *cmdline=get_target("cmdline");
570 unsigned total=cmdline->count_rebuild();
573 cout<<"Already up to date\n";
576 cout<<"Will build "<<total<<" target(s)\n";
578 vector<Action *> actions;
581 cout<<"0 targets built\n";
589 if(actions.size()<jobs && !fail)
591 Target *tgt=cmdline->get_buildable_target();
594 Action *action=tgt->build();
596 actions.push_back(action);
598 else if(actions.empty())
602 Time::sleep(10*Time::msec);
604 for(unsigned i=0; i<actions.size();)
606 int status=actions[i]->check();
612 cout<<"\e["<<actions.size()+1<<'A';
613 cout<<count<<" targets built\n";
617 if(i<actions.size()-1)
618 cout<<"\e["<<actions.size()-i-1<<"B";
622 actions.erase(actions.begin()+i);
625 if(actions.empty() && fail)
636 void Builder::package_help()
638 const Config &config=default_pkg->get_config();
639 const Config::OptionMap &options=config.get_options();
641 cout<<"Required packages:\n ";
642 const PkgRefList &requires=default_pkg->get_requires();
643 for(PkgRefList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
645 if(i!=requires.begin())
650 cout<<"Package configuration:\n";
651 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
653 const Config::Option &opt=i->second;
654 cout<<" "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
658 Application::RegApp<Builder> Builder::reg;
660 Builder::Loader::Loader(Builder &b, const Path::Path &s):
664 add("package", &Loader::package);
667 void Builder::Loader::package(const string &n)
669 Package *pkg=new Package(bld, n, src);
671 bld.packages.insert(PackageMap::value_type(n, pkg));
672 bld.new_pkgs.push_back(pkg);