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 "pkgconfig.h"
22 #include "sharedlibrary.h"
23 #include "staticlibrary.h"
24 #include "systemlibrary.h"
25 #include "virtualtarget.h"
30 Builder::Builder(int argc, char **argv):
40 bool full_paths=false;
44 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG);
45 getopt.add_option('b', "build", do_build, GetOpt::NO_ARG);
46 // getopt.add_option('c', "clean", clean, GetOpt::NO_ARG);
47 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG);
48 getopt.add_option('h', "help", help, GetOpt::NO_ARG);
49 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG);
50 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG);
51 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG);
52 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG);
53 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG);
54 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG);
55 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG);
56 getopt.add_option( "chrome", chrome, GetOpt::NO_ARG);
57 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG);
58 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG);
59 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG);
62 if(!analyze_mode.empty())
64 analyzer=new Analyzer(*this);
66 if(analyze_mode=="deps")
67 analyzer->set_mode(Analyzer::DEPS);
68 else if(analyze_mode=="alldeps")
69 analyzer->set_mode(Analyzer::ALLDEPS);
70 else if(analyze_mode=="rebuild")
71 analyzer->set_mode(Analyzer::REBUILD);
72 else if(analyze_mode=="rdeps")
73 analyzer->set_mode(Analyzer::RDEPS);
75 throw UsageError("Invalid analyze mode");
77 analyzer->set_max_depth(max_depth);
78 analyzer->set_full_paths(full_paths);
83 const list<string> &args=getopt.get_args();
84 for(list<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
86 unsigned equal=i->find('=');
87 if(equal!=string::npos)
88 cmdline_options.insert(RawOptionMap::value_type(i->substr(0, equal), i->substr(equal+1)));
90 cmdline_targets.push_back(*i);
93 if(cmdline_targets.empty())
94 cmdline_targets.push_back("default");
97 chdir(work_dir.c_str());
103 Gets a package with the specified name, possibly creating it.
105 @param n Package name
107 @return Pointer to the package, or 0 if the package could not be located
109 Package *Builder::get_package(const string &n)
111 PackageMap::iterator i=packages.find(n);
112 if(i!=packages.end())
115 // Try to get source directory with pkgconfig
117 argv.push_back("pkg-config");
118 argv.push_back("--variable=source");
120 string srcdir=strip(run_command(argv));
124 dirs.push_back(srcdir);
126 // Make some other guesses about the source directory
128 if(!dirname.compare(0, 3, "msp"))
130 dirs.push_back(cwd/dirname);
131 dirs.push_back(cwd/".."/dirname);
133 // Go through the candidate directories and look for a Build file
134 for(PathList::iterator j=dirs.begin(); j!=dirs.end(); ++j)
135 if(!load_build_file(*j/"Build"))
138 if(i!=packages.end())
143 // Package source not found - create a binary package
144 Package *pkg=Package::create(*this, n);
145 packages.insert(PackageMap::value_type(n, pkg));
147 new_pkgs.push_back(pkg);
153 Returns the target with the given name, or 0 if no such target exists.
155 Target *Builder::get_target(const string &n)
157 TargetMap::iterator i=targets.find(n);
164 Tries to locate a header included from a given location and with a given include
165 path. Considers known targets as well as existing files. If a matching target
166 is not found but a file exists, a new SystemHeader target will be created and
169 Target *Builder::get_header(const string &include, const string &from, const list<string> &path)
172 update_hash(hash, from);
173 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
174 update_hash(hash, *i);
176 string id=hash+include;
177 TargetMap::iterator i=includes.find(id);
178 if(i!=includes.end())
181 string fn=include.substr(1);
183 if(include[0]=='"' && (tgt=get_header(Path::Path(from)/fn)))
185 else if((tgt=get_header(Path::Path("/usr/include")/fn)))
187 //XXX Determine the C++ header location dynamically
188 else if((tgt=get_header(Path::Path("/usr/include/c++/4.1.2")/fn)))
192 for(list<string>::const_iterator j=path.begin(); (j!=path.end() && !tgt); ++j)
193 tgt=get_header(cwd/ *j/fn);
196 includes.insert(TargetMap::value_type(id, tgt));
202 Tries to locate a library with the given library path. Considers known targets
203 as well as existing files. If a matching target is not found but a file exists,
204 a new SystemLibrary target will be created and returned.
206 @param lib Name of the library to get (without "lib" prefix or extension)
207 @param path List of paths to search for the library
208 @param mode Shared / shared mode - 0: always shared, 1: static for buildable
209 packages, otherwise shared, 2: always static
211 @return Some kind of library target, if a match was found
213 Target *Builder::get_library(const string &lib, const list<string> &path, unsigned mode)
216 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
217 update_hash(hash, *i);
219 //XXX Incorporate mode into id
221 TargetMap::iterator i=libraries.find(id);
222 if(i!=libraries.end())
226 if((tgt=get_library(lib, "/lib", mode)))
228 else if((tgt=get_library(lib, "/usr/lib", mode)))
232 for(list<string>::const_iterator j=path.begin(); (j!=path.end() && !tgt); ++j)
233 tgt=get_library(lib, cwd/ *j, mode);
236 libraries.insert(TargetMap::value_type(id, tgt));
243 if(load_build_file(cwd/build_file))
245 cerr<<"No build info here.\n";
249 default_pkg=packages.begin()->second;
251 while(!new_pkgs.empty())
253 Package *pkg=new_pkgs.front();
254 new_pkgs.erase(new_pkgs.begin());
258 default_pkg->configure(cmdline_options, conf_all?2:1);
262 usage(0, "builder", false);
269 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
271 missing.push_back(i->first);
276 cerr<<"The following packages were not found on the system:\n";
277 for(list<string>::iterator i=missing.begin(); i!=missing.end(); ++i)
279 cerr<<"Please install them and try again.\n";
289 cout<<packages.size()<<" packages, "<<targets.size()<<" targets\n";
292 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
294 cout<<' '<<i->second->get_name();
295 if(i->second->get_buildable())
298 unsigned ood_count=0;
299 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
300 if(j->second->get_package()==i->second)
303 if(j->second->get_rebuild())
308 cout<<" ("<<count<<" targets";
310 cout<<", "<<ood_count<<" out-of-date";
328 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
330 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
335 void Builder::usage(const char *reason, const char *argv0, bool brief)
341 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] [--conf-only] [--full-paths] [--max-depth NUM] [<target> ...]";
345 "Usage: "<<argv0<<" [options] [<target> ...]\n"
348 " -a, --analyze MODE Perform analysis. MODE can be deps, alldeps or rebuild.\n"
349 " -b, --build Perform build even if doing analysis.\n"
350 " -c, --clean Clean buildable targets.\n"
351 " -f, --file FILE Read info from FILE instead of Build.\n"
352 " -h, --help Print this message.\n"
353 " -j, --jobs NUM Run NUM commands at once, whenever possible.\n"
354 " -n, --dry-run Don't actually do anything, only show what would be done.\n"
355 " -v, --verbose Print more information about what's going on.\n"
356 " -A, --conf-all Apply configuration to all packages.\n"
357 " -B, --build-all Build all targets unconditionally.\n"
358 " -C, --chdir DIR Change to DIR before doing anything else.\n"
359 " -W, --what-if FILE Pretend that FILE has changed.\n"
360 " --chrome Use extra chrome to print status.\n"
361 " --conf-only Stop after configuring packages.\n"
362 " --full-paths Output full paths in analysis.\n"
363 " --max-depth NUM Maximum depth to show in analysis.\n";
368 Loads the given build file.
370 @param fn Path to the file
372 @return 0 on success, -1 if the file could not be opened
374 int Builder::load_build_file(const Path::Path &fn)
376 ifstream in(fn.str().c_str());
380 Parser::Parser parser(in, fn.str());
381 Loader loader(*this, fn.subpath(0, fn.size()-1));
388 Creates targets for all packages and prepares them for building.
390 @return 0 if everything went ok, -1 if something bad happened and a build
391 shouldn't be attempted
393 int Builder::create_targets()
395 Target *world=new VirtualTarget(*this, "world");
398 Target *def_tgt=new VirtualTarget(*this, "default");
400 world->add_depend(def_tgt);
402 Target *install=new VirtualTarget(*this, "install");
404 world->add_depend(install);
406 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
410 if(!i->second->get_buildable())
413 Path::Path inst_base;
414 if(i->second->get_config().is_option("prefix"))
415 inst_base=i->second->get_config().get_option("prefix").value;
417 const ComponentList &components=i->second->get_components();
418 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
420 // Collect all files belonging to the component
422 const PathList &sources=j->get_sources();
423 for(PathList::const_iterator k=sources.begin(); k!=sources.end(); ++k)
427 if(S_ISDIR(st.st_mode))
429 list<string> sfiles=list_files(*k);
430 for(list<string>::iterator l=sfiles.begin(); l!=sfiles.end(); ++l)
431 files.push_back(*k / *l);
437 bool build_exe=j->get_type()!=Component::HEADERS;
439 list<ObjectFile *> objs;
440 for(PathList::iterator k=files.begin(); k!=files.end(); ++k)
442 string basename=(*k)[-1];
443 string ext=Path::splitext(basename).ext;
444 if((ext==".cpp" || ext==".c") && build_exe)
446 SourceFile *src=new SourceFile(*this, &*j, k->str());
450 ObjectFile *obj=new ObjectFile(*this, *j, *src);
456 Target *hdr=get_target(k->str());
459 hdr=new Header(*this, &*j, k->str());
463 // Install headers if requested
464 if(!j->get_install_headers().empty())
466 Path::Path inst_path=inst_base/"include"/j->get_install_headers()/basename;
467 Install *inst=new Install(*this, *i->second, *hdr, inst_path.str());
469 install->add_depend(inst);
477 StaticLibrary *slib=0;
478 if(j->get_type()==Component::LIBRARY)
480 exe=new SharedLibrary(*this, *j, objs);
481 slib=new StaticLibrary(*this, *j, objs);
485 exe=new Executable(*this, *j, objs);
488 if(i->second==default_pkg)
490 def_tgt->add_depend(exe);
491 if(slib) def_tgt->add_depend(slib);
495 world->add_depend(exe);
496 if(slib) world->add_depend(slib);
502 if(j->get_type()==Component::PROGRAM)
504 else if(j->get_type()==Component::LIBRARY)
506 if(!inst_dir.empty())
508 Install *inst=new Install(*this, *i->second, *exe, (inst_base/inst_dir/Path::basename(exe->get_name())).str());
510 install->add_depend(inst);
514 inst=new Install(*this, *i->second, *slib, (inst_base/inst_dir/Path::basename(slib->get_name())).str());
516 install->add_depend(inst);
523 if(i->second->get_install_flags()&(Package::LIB|Package::INCLUDE))
525 PkgConfig *pc=new PkgConfig(*this, *i->second);
527 Install *inst=new Install(*this, *i->second, *pc, (inst_base/"lib"/"pkgconfig"/Path::basename(pc->get_name())).str());
529 install->add_depend(inst);
533 // Find dependencies until no new targets are created
534 while(!new_tgts.empty())
536 Target *tgt=new_tgts.front();
537 new_tgts.erase(new_tgts.begin());
539 if(!tgt->get_depends_ready())
540 new_tgts.push_back(tgt);
544 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
546 Target *tgt=get_target((cwd/ *i).str());
549 cerr<<"Unknown what-if target "<<*i<<'\n';
555 // Make the cmdline target depend on all targets mentioned on the command line
556 Target *cmdline=new VirtualTarget(*this, "cmdline");
558 world->add_depend(cmdline);
559 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
561 Target *tgt=get_target(*i);
563 tgt=get_target((cwd/ *i).str());
566 cerr<<"I don't know anything about "<<*i<<'\n';
569 cmdline->add_depend(tgt);
578 Check if a header exists, either as a target or a file. Either an existing
579 target or a new SystemHeader target will be returned.
581 Target *Builder::get_header(const Msp::Path::Path &fn)
583 Target *tgt=get_target(fn.str());
588 add_target(tgt=new SystemHeader(*this, fn.str()));
594 Target *Builder::get_library(const string &lib, const Path::Path &path, unsigned mode)
599 full=(path/("lib"+lib+".a")).str();
600 Target *tgt=get_target(full);
601 // Targets can only be associated with buildable packages (or no package at all)
602 if(tgt && (tgt->get_package() || mode==2)) return tgt;
606 full=(path/("lib"+lib+".so")).str();
607 Target *tgt=get_target(full);
611 if(Path::exists(full))
613 Target *tgt=new SystemLibrary(*this, full);
622 Adds a target to both the target map and the new target queue.
624 void Builder::add_target(Target *t)
626 targets.insert(TargetMap::value_type(t->get_name(), t));
627 new_tgts.push_back(t);
631 Updates a hash with a string. This is used from get_header and get_library.
633 void Builder::update_hash(string &hash, const string &value)
635 for(unsigned i=0; i<value.size(); ++i)
636 hash[i%hash.size()]^=value[i];
640 This function supervises the build process, starting new actions when slots
645 Target *cmdline=get_target("cmdline");
647 unsigned total=cmdline->count_rebuild();
650 cout<<"Already up to date\n";
653 cout<<"Will build "<<total<<" target(s)\n";
655 vector<Action *> actions;
658 cout<<"0 targets built\n";
666 if(actions.size()<jobs && !fail)
668 Target *tgt=cmdline->get_buildable_target();
671 Action *action=tgt->build();
673 actions.push_back(action);
675 else if(actions.empty())
679 Time::sleep(10*Time::msec);
681 for(unsigned i=0; i<actions.size();)
683 int status=actions[i]->check();
689 cout<<"\e["<<actions.size()+1<<'A';
690 cout<<count<<" targets built\n";
694 if(i<actions.size()-1)
695 cout<<"\e["<<actions.size()-i-1<<"B";
699 actions.erase(actions.begin()+i);
702 if(actions.empty() && fail)
714 Prints out information about the default package.
716 void Builder::package_help()
718 const Config &config=default_pkg->get_config();
719 const Config::OptionMap &options=config.get_options();
721 cout<<"Required packages:\n ";
722 const PkgRefList &requires=default_pkg->get_requires();
723 for(PkgRefList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
725 if(i!=requires.begin())
730 cout<<"Package configuration:\n";
731 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
733 const Config::Option &opt=i->second;
734 cout<<" "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
738 Application::RegApp<Builder> Builder::reg;
740 Builder::Loader::Loader(Builder &b, const Path::Path &s):
744 add("package", &Loader::package);
747 void Builder::Loader::package(const string &n)
749 Package *pkg=new Package(bld, n, src);
751 bld.packages.insert(PackageMap::value_type(n, pkg));
752 bld.new_pkgs.push_back(pkg);