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 "systemlibrary.h"
22 #include "virtualtarget.h"
27 Builder::Builder(int argc, char **argv):
36 getopt.add_option(GetOpt::Option('a', "analyze", GetOpt::REQUIRED));
37 getopt.add_option(GetOpt::Option('b', "build", GetOpt::NONE));
38 getopt.add_option(GetOpt::Option('c', "clean", GetOpt::NONE));
39 getopt.add_option(GetOpt::Option('f', "file", GetOpt::REQUIRED, "Build"));
40 getopt.add_option(GetOpt::Option('h', "help", GetOpt::NONE));
41 getopt.add_option(GetOpt::Option('j', "jobs", GetOpt::REQUIRED, "1"));
42 getopt.add_option(GetOpt::Option('n', "dry-run", GetOpt::NONE));
43 getopt.add_option(GetOpt::Option('v', "verbose", GetOpt::NONE));
44 getopt.add_option(GetOpt::Option('A', "conf-all", GetOpt::NONE));
45 getopt.add_option(GetOpt::Option('B', "build-all", GetOpt::NONE));
46 getopt.add_option(GetOpt::Option('C', "chdir", GetOpt::REQUIRED));
47 getopt.add_option(GetOpt::Option('W', "what-if", GetOpt::REQUIRED));
48 getopt.add_option(GetOpt::Option("chrome", GetOpt::NONE));
49 getopt.add_option(GetOpt::Option("full-paths", GetOpt::NONE));
50 getopt.add_option(GetOpt::Option("max-depth", GetOpt::REQUIRED));
51 int index=getopt(argc, argv);
53 verbose+=getopt['v'].count();
57 analyzer=new Analyzer(*this);
59 string mode=getopt['a'].arg();
61 analyzer->set_mode(Analyzer::DEPS);
62 else if(mode=="alldeps")
63 analyzer->set_mode(Analyzer::ALLDEPS);
64 else if(mode=="rebuild")
65 analyzer->set_mode(Analyzer::REBUILD);
66 else if(mode=="rdeps")
67 analyzer->set_mode(Analyzer::RDEPS);
69 throw UsageError("Invalid analysis mode");
71 if(getopt["max-depth"])
72 analyzer->set_max_depth(strtol(getopt["max-depth"].arg()));
73 analyzer->set_full_paths(getopt["full-paths"]);
80 jobs=max(strtol(getopt['j'].arg()), 1L);
81 chrome=getopt["chrome"];
83 build_file=getopt['f'].arg();
84 build_all=getopt['B'];
88 chdir(getopt['C'].arg().c_str());
90 for(int i=index; i<argc; ++i)
93 unsigned equal=v.find('=');
94 if(equal!=string::npos)
95 cmdline_options.insert(RawOptionMap::value_type(v.substr(0, equal), v.substr(equal+1)));
97 cmdline_targets.push_back(argv[i]);
100 if(cmdline_targets.empty())
101 cmdline_targets.push_back("default");
104 what_if.push_back(getopt['W'].arg());
110 Gets a package with the specified name, possibly creating it.
112 @param n Package name
114 @return Pointer to the package, or 0 if the package could not be located
116 Package *Builder::get_package(const string &n)
118 PackageMap::iterator i=packages.find(n);
119 if(i!=packages.end())
122 // Try to get source directory with pkgconfig
124 argv.push_back("pkg-config");
125 argv.push_back("--variable=source");
127 string srcdir=strip(run_command(argv));
131 dirs.push_back(srcdir);
133 // Make some other guesses about the source directory
135 if(!dirname.compare(0, 3, "msp"))
137 dirs.push_back(cwd/dirname);
138 dirs.push_back(cwd/".."/dirname);
140 // Go through the candidate directories and look for a Build file
141 for(PathList::iterator j=dirs.begin(); j!=dirs.end(); ++j)
142 if(!load_build_file(*j/"Build"))
145 if(i!=packages.end())
150 // Package source not found - create a binary package
151 Package *pkg=Package::create(*this, n);
152 packages.insert(PackageMap::value_type(n, pkg));
154 new_pkgs.push_back(pkg);
160 Returns the target with the given name, or 0 if no such target exists.
162 Target *Builder::get_target(const string &n)
164 TargetMap::iterator i=targets.find(n);
171 Tries to locate a header included from a given location and with a given include
172 path. Considers known targets as well as existing files.
174 Target *Builder::get_header(const string &include, const string &from, const list<string> &path)
177 update_hash(hash, from);
178 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
179 update_hash(hash, *i);
181 string id=hash+include;
182 TargetMap::iterator i=includes.find(id);
183 if(i!=includes.end())
186 string fn=include.substr(1);
188 if(include[0]=='"' && (tgt=check_header(Path::Path(from)/fn)))
190 if((tgt=check_header(Path::Path("/usr/include")/fn)))
192 //XXX Determine the C++ header location dynamically
193 if((tgt=check_header(Path::Path("/usr/include/c++/4.1.2")/fn)))
195 for(list<string>::const_iterator j=path.begin(); j!=path.end(); ++j)
196 if((tgt=check_header(cwd/ *j/fn)))
202 Target *Builder::get_library(const string &lib, const list<string> &path)
205 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
206 update_hash(hash, *i);
209 TargetMap::iterator i=libraries.find(id);
210 if(i!=libraries.end())
213 string basename="lib"+lib+".so";
214 for(list<string>::const_iterator j=path.begin(); j!=path.end(); ++j)
216 string full=(cwd/ *j/basename).str();
217 Target *tgt=get_target(full);
220 if(Path::exists(full))
222 add_target(tgt=new SystemLibrary(*this, full));
232 if(load_build_file(cwd/build_file))
234 cerr<<"No build info here.\n";
238 default_pkg=packages.begin()->second;
240 while(!new_pkgs.empty())
242 Package *pkg=new_pkgs.front();
243 if(pkg==default_pkg || conf_all)
244 pkg->process_options(cmdline_options);
245 new_pkgs.erase(new_pkgs.begin());
251 usage("builder", false);
257 std::list<std::string> missing;
258 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
260 missing.push_back(i->first);
265 cerr<<"The following packages were not found on the system:\n";
266 for(list<string>::iterator i=missing.begin(); i!=missing.end(); ++i)
268 cerr<<"Please install them and try again.\n";
272 default_pkg->create_build_info();
277 cout<<packages.size()<<" packages, "<<targets.size()<<" targets\n";
280 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
282 cout<<' '<<i->second->get_name();
283 if(i->second->get_buildable())
286 unsigned ood_count=0;
287 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
288 if(j->second->get_package()==i->second)
291 if(j->second->get_rebuild())
296 cout<<" ("<<count<<" targets";
298 cout<<", "<<ood_count<<" out-of-date";
316 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
318 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
323 void Builder::usage(const char *argv0, bool brief)
326 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> ...]";
330 "Usage: "<<argv0<<" [options] [<target> ...]\n"
333 " -a, --analyze MODE Perform analysis. MODE can be deps, alldeps or rebuild.\n"
334 " -b, --build Perform build even if doing analysis.\n"
335 " -c, --clean Clean buildable targets.\n"
336 " -f, --file FILE Read info from FILE instead of Build.\n"
337 " -h, --help Print this message.\n"
338 " -j, --jobs NUM Run NUM commands at once, whenever possible.\n"
339 " -n, --dry-run Don't actually do anything, only show what would be done.\n"
340 " -v, --verbose Print more information about what's going on.\n"
341 " -A, --conf-all Apply configuration to all packages.\n"
342 " -B, --build-all Build all targets unconditionally.\n"
343 " -C, --chdir DIR Change to DIR before doing anything else.\n"
344 " -W, --what-if FILE Pretend that FILE has changed.\n"
345 " --chrome Use extra chrome to print status.\n"
346 " --full-paths Output full paths in analysis.\n"
347 " --max-depth NUM Maximum depth to show in analysis.\n";
351 int Builder::load_build_file(const Path::Path &fn)
353 ifstream in(fn.str().c_str());
357 Parser::Parser parser(in, fn.str());
358 Loader loader(*this, fn.subpath(0, fn.size()-1));
364 int Builder::create_targets()
366 Target *world=new VirtualTarget(*this, "world");
369 Target *def_tgt=new VirtualTarget(*this, "default");
371 world->add_depend(def_tgt);
373 Target *install=new VirtualTarget(*this, "install");
375 world->add_depend(install);
377 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
381 if(!i->second->get_buildable())
384 Path::Path inst_base;
385 if(i->second->get_config().is_option("prefix"))
386 inst_base=i->second->get_config().get_option("prefix").value;
388 const ComponentList &components=i->second->get_components();
389 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
392 const PathList &sources=j->get_sources();
393 for(PathList::const_iterator k=sources.begin(); k!=sources.end(); ++k)
397 if(S_ISDIR(st.st_mode))
399 list<string> sfiles=list_files(*k);
400 for(list<string>::iterator l=sfiles.begin(); l!=sfiles.end(); ++l)
401 files.push_back(*k / *l);
407 bool build_exe=j->get_type()!=Component::HEADERS;
409 list<ObjectFile *> objs;
410 for(PathList::iterator k=files.begin(); k!=files.end(); ++k)
412 string basename=(*k)[-1];
413 string ext=Path::splitext(basename).ext;
414 if(ext==".cpp" || ext==".c")
418 SourceFile *src=new SourceFile(*this, &*j, k->str());
421 ObjectFile *obj=new ObjectFile(*this, *j, *src);
428 Target *hdr=get_target(k->str());
431 hdr=new Header(*this, &*j, k->str());
434 if(!j->get_install_headers().empty())
436 Path::Path inst_path=inst_base/"include"/j->get_install_headers()/basename;
437 Install *inst=new Install(*this, *i->second, *hdr, inst_path.str());
439 install->add_depend(inst);
446 Executable *exe=new Executable(*this, *j, objs);
448 if(i->second==default_pkg)
449 def_tgt->add_depend(exe);
451 world->add_depend(exe);
456 if(j->get_type()==Component::PROGRAM)
458 else if(j->get_type()==Component::LIBRARY)
460 if(!inst_dir.empty())
462 Install *inst=new Install(*this, *i->second, *exe, (inst_base/inst_dir/Path::basename(exe->get_name())).str());
464 install->add_depend(inst);
471 while(!new_tgts.empty())
473 Target *tgt=new_tgts.front();
474 new_tgts.erase(new_tgts.begin());
476 if(!tgt->get_depends_ready())
477 new_tgts.push_back(tgt);
480 for(list<string>::iterator i=what_if.begin(); i!=what_if.end(); ++i)
482 Target *tgt=get_target((cwd/ *i).str());
485 cerr<<"Unknown what-if target "<<*i<<'\n';
491 Target *cmdline=new VirtualTarget(*this, "cmdline");
493 world->add_depend(cmdline);
494 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
496 Target *tgt=get_target(*i);
498 tgt=get_target((cwd/ *i).str());
501 cerr<<"I don't know anything about "<<*i<<'\n';
504 cmdline->add_depend(tgt);
512 Target *Builder::check_header(const Msp::Path::Path &fn)
514 Target *tgt=get_target(fn.str());
519 add_target(tgt=new SystemHeader(*this, fn.str()));
525 void Builder::add_target(Target *t)
527 targets.insert(TargetMap::value_type(t->get_name(), t));
528 new_tgts.push_back(t);
531 void Builder::update_hash(string &hash, const string &value)
533 for(unsigned i=0; i<value.size(); ++i)
534 hash[i%hash.size()]^=value[i];
538 This function supervises the build process, starting new actions when slots
543 Target *cmdline=get_target("cmdline");
545 unsigned total=cmdline->count_rebuild();
548 cout<<"Already up to date\n";
551 cout<<"Will build "<<total<<" target(s)\n";
553 vector<Action *> actions;
556 cout<<"0 targets built\n";
564 if(actions.size()<jobs && !fail)
566 Target *tgt=cmdline->get_buildable_target();
569 Action *action=tgt->build();
571 actions.push_back(action);
573 else if(actions.empty())
577 Time::sleep(10*Time::msec);
579 for(unsigned i=0; i<actions.size();)
581 int status=actions[i]->check();
587 cout<<"\e["<<actions.size()+1<<'A';
588 cout<<count<<" targets built\n";
592 if(i<actions.size()-1)
593 cout<<"\e["<<actions.size()-i-1<<"B";
597 actions.erase(actions.begin()+i);
600 if(actions.empty() && fail)
611 void Builder::package_help()
613 const Config &config=default_pkg->get_config();
614 const Config::OptionMap &options=config.get_options();
616 cout<<"Required packages:\n ";
617 const list<PackageRef> &requires=default_pkg->get_requires();
618 for(list<PackageRef>::const_iterator i=requires.begin(); i!=requires.end(); ++i)
620 if(i!=requires.begin())
625 cout<<"Package configuration:\n";
626 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
628 const Config::Option &opt=i->second;
629 cout<<" "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
633 Application::RegApp<Builder> Builder::reg;
635 Builder::Loader::Loader(Builder &b, const Path::Path &s):
639 add("package", &Loader::package);
642 void Builder::Loader::package(const string &n)
644 Package *pkg=new Package(bld, n, src);
646 bld.packages.insert(PackageMap::value_type(n, pkg));
647 bld.new_pkgs.push_back(pkg);