3 This file is part of builder
4 Copyright © 2006-2007 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
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/strings/formatter.h>
20 #include <msp/strings/regex.h>
21 #include <msp/strings/utils.h>
22 #include <msp/time/units.h>
23 #include <msp/time/utils.h>
26 #include "binarypackage.h"
32 #include "pkgconfig.h"
33 #include "sharedlibrary.h"
34 #include "sourcepackage.h"
35 #include "systemlibrary.h"
38 #include "virtualtarget.h"
43 Builder::Builder(int argc, char **argv):
57 create_makefile(false),
58 current_arch("native")
62 bool full_paths=false;
64 StringList cmdline_warn;
68 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG);
69 getopt.add_option('b', "build", build, GetOpt::NO_ARG);
70 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG);
71 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG);
72 getopt.add_option('h', "help", help, GetOpt::NO_ARG);
73 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG);
74 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG);
75 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG);
76 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG);
77 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG);
78 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG);
79 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG);
80 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG);
81 getopt.add_option( "arch", current_arch, GetOpt::REQUIRED_ARG);
82 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG);
83 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG);
84 //getopt.add_option( "makefile", create_makefile, GetOpt::NO_ARG);
85 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG);
86 getopt.add_option( "prefix", prfx, GetOpt::REQUIRED_ARG);
87 getopt.add_option( "warnings", cmdline_warn, GetOpt::REQUIRED_ARG);
90 if(!analyze_mode.empty())
92 analyzer=new Analyzer(*this);
94 if(analyze_mode=="deps")
95 analyzer->set_mode(Analyzer::DEPS);
96 else if(analyze_mode=="alldeps")
97 analyzer->set_mode(Analyzer::ALLDEPS);
98 else if(analyze_mode=="rebuild")
99 analyzer->set_mode(Analyzer::REBUILD);
100 else if(analyze_mode=="rdeps")
101 analyzer->set_mode(Analyzer::RDEPS);
103 throw UsageError("Invalid analyze mode");
105 analyzer->set_max_depth(max_depth);
106 analyzer->set_full_paths(full_paths);
108 else if(!clean && !create_makefile)
111 const vector<string> &args=getopt.get_args();
112 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
114 unsigned equal=i->find('=');
115 if(equal!=string::npos)
116 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
118 cmdline_targets.push_back(*i);
121 if(cmdline_targets.empty())
122 cmdline_targets.push_back("default");
124 if(!work_dir.empty())
125 chdir(work_dir.c_str());
129 Architecture &native_arch=archs.insert(ArchMap::value_type("native", Architecture(*this, "native"))).first->second;
130 native_arch.set_tool("CC", "gcc");
131 native_arch.set_tool("CXX", "g++");
132 native_arch.set_tool("LD", "gcc");
133 native_arch.set_tool("LXX", "g++");
134 native_arch.set_tool("AR", "ar");
136 load_build_file((FS::get_home_dir()/".builderrc").str());
140 if(current_arch=="native")
141 prefix=(FS::get_home_dir()/"local").str();
143 prefix=(FS::get_home_dir()/"local"/current_arch).str();
146 prefix=FS::getcwd()/prfx;
148 warnings.push_back("all");
149 warnings.push_back("extra");
150 warnings.push_back("shadow");
151 warnings.push_back("pointer-arith");
152 warnings.push_back("error");
153 for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
155 vector<string> warns=split(*i, ',');
156 warnings.insert(warnings.end(), warns.begin(), warns.end());
159 pkg_path.push_back(cwd/".");
160 pkg_path.push_back(cwd/"..");
164 Gets a package by name, possibly creating it.
166 @param name Package name
168 @return Pointer to the package, or 0 if the package could not be located
170 Package *Builder::get_package(const string &name)
172 PackageMap::iterator i=packages.find(format("%s/%s", name, current_arch));
173 if(i==packages.end())
174 i=packages.find(name);
175 if(i!=packages.end())
178 FS::Path path=get_package_location(name);
179 if(!path.empty() && !load_build_file(path/"Build"))
181 i=packages.find(name);
182 if(i!=packages.end())
186 // Package source not found - create a binary package
187 Package *pkg=BinaryPackage::from_pkgconfig(*this, name);
189 packages.insert(PackageMap::value_type(name, pkg));
192 problem(name, "not found");
198 Returns the target with the given name, or 0 if no such target exists.
200 Target *Builder::get_target(const string &n) const
202 TargetMap::const_iterator i=targets.find(n);
209 Tries to locate a header included from a given location and with a given include
210 path. Considers known targets as well as existing files. If a matching target
211 is not found but a file exists, a new SystemHeader target will be created and
214 Target *Builder::get_header(const string &include, const string &from, const list<string> &path)
217 update_hash(hash, from);
218 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
219 update_hash(hash, *i);
221 string id=hash+include;
222 TargetMap::iterator i=includes.find(id);
223 if(i!=includes.end())
226 static string cxx_ver;
230 argv.push_back(get_current_arch().get_tool("CXX"));
231 argv.push_back("--version");
232 cxx_ver=Regex("[0-9]\\.[0-9.]+").match(run_command(argv))[0].str;
233 while(!cxx_ver.empty() && !FS::is_dir(FS::Path("/usr/include/c++")/cxx_ver))
235 unsigned dot=cxx_ver.rfind('.');
236 if(dot==string::npos)
241 cout<<"C++ version is "<<cxx_ver<<'\n';
244 string fn=include.substr(1);
246 cout<<"Looking for include "<<fn<<" with path "<<join(path.begin(), path.end())<<'\n';
249 if(current_arch=="native")
250 syspath.push_back("/usr/include");
252 syspath.push_back("/usr/"+get_architecture(current_arch).get_prefix()+"/include");
253 syspath.push_back((FS::Path("/usr/include/c++/")/cxx_ver/fn).str());
257 tgt=get_header(FS::Path(from)/fn);
258 for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
259 tgt=get_header(cwd/ *j/fn);
260 for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
261 tgt=get_header(FS::Path(*j)/fn);
263 includes.insert(TargetMap::value_type(id, tgt));
269 Tries to locate a library with the given library path. Considers known targets
270 as well as existing files. If a matching target is not found but a file exists,
271 a new SystemLibrary target will be created and returned.
273 @param lib Name of the library to get (without "lib" prefix or extension)
274 @param path List of paths to search for the library
275 @param mode Shared / static mode
277 @return Some kind of library target, if a match was found
279 Target *Builder::get_library(const string &lib, const list<string> &path, LibMode mode)
282 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
283 update_hash(hash, *i);
285 string id=hash+string(1, mode)+lib;
286 TargetMap::iterator i=libraries.find(id);
287 if(i!=libraries.end())
291 if(current_arch=="native")
293 syspath.push_back("/lib");
294 syspath.push_back("/usr/lib");
297 syspath.push_back("/usr/"+get_current_arch().get_prefix()+"/lib");
300 cout<<"Looking for library "<<lib<<" with path "<<join(path.begin(), path.end())<<'\n';
303 for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
304 tgt=get_library(lib, cwd/ *j, mode);
305 for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
306 tgt=get_library(lib, *j, mode);
308 libraries.insert(TargetMap::value_type(id, tgt));
313 const Architecture &Builder::get_architecture(const string &arch) const
315 ArchMap::const_iterator i=archs.find(arch);
317 throw KeyError("Unknown architecture", arch);
322 const Architecture &Builder::get_current_arch() const
324 return get_architecture(current_arch);
327 void Builder::apply_profile_template(Config &config, const string &pt) const
329 vector<string> parts=split(pt, '-');
331 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
333 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
334 if(j==profile_tmpl.end())
337 config.update(j->second);
341 void Builder::problem(const string &p, const string &d)
343 problems.push_back(Problem(p, d));
347 Adds a target to both the target map and the new target queue. Called from
350 void Builder::add_target(Target *t)
352 targets.insert(TargetMap::value_type(t->get_name(), t));
353 new_tgts.push_back(t);
358 if(load_build_file(cwd/build_file))
360 cerr<<"No build info here.\n";
364 main_pkg->configure(cmdline_options, conf_all?2:1);
368 usage(0, "builder", false);
374 if(!conf_only && create_targets())
377 PackageList all_reqs=main_pkg->collect_requires();
383 cout<<all_reqs.size()<<" active packages, "<<targets.size()<<" targets\n";
386 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
388 cout<<' '<<(*i)->get_name();
389 if(dynamic_cast<SourcePackage *>(*i))
392 unsigned ood_count=0;
393 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
394 if(j->second->get_package()==*i)
397 if(j->second->get_rebuild())
402 cout<<" ("<<count<<" targets";
404 cout<<", "<<ood_count<<" out-of-date";
414 if(!problems.empty())
416 cerr<<"The following problems were detected:\n";
417 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
418 cerr<<" "<<i->package<<": "<<i->descr<<'\n';
419 cerr<<"Please fix them and try again.\n";
426 exit_code=do_clean();
428 exit_code=do_build();
435 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
437 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
442 void Builder::usage(const char *reason, const char *argv0, bool brief)
448 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> ...]\n";
452 "Usage: "<<argv0<<" [options] [<target> ...]\n"
455 " -a, --analyze MODE Perform analysis. MODE can be deps, alldeps or rebuild.\n"
456 " -b, --build Perform build even if doing analysis.\n"
457 " -c, --clean Clean buildable targets.\n"
458 " -f, --file FILE Read info from FILE instead of Build.\n"
459 " -h, --help Print this message.\n"
460 " -j, --jobs NUM Run NUM commands at once, whenever possible.\n"
461 " -n, --dry-run Don't actually do anything, only show what would be done.\n"
462 " -v, --verbose Print more information about what's going on.\n"
463 " -A, --conf-all Apply configuration to all packages.\n"
464 " -B, --build-all Build all targets unconditionally.\n"
465 " -C, --chdir DIR Change to DIR before doing anything else.\n"
466 " -P, --progress Display progress while building.\n"
467 " -W, --what-if FILE Pretend that FILE has changed.\n"
468 " --arch ARCH Architecture to build for.\n"
469 " --conf-only Stop after configuring packages.\n"
470 " --full-paths Output full paths in analysis.\n"
471 //" --makefile Create a makefile for this package.\n"
472 " --max-depth NUM Maximum depth to show in analysis.\n"
473 " --prefix DIR Directory to install things to.\n"
474 " --warnings LIST Compiler warnings to use.\n";
479 Determines the source directory of a package. pkg-config is consulted first,
480 and if it fails, the package path is searched for matches.
482 FS::Path Builder::get_package_location(const string &name)
484 // Try to get source directory with pkgconfig
486 argv.push_back("pkg-config");
487 argv.push_back("--variable=source");
488 argv.push_back(name);
490 cout<<"Running "<<join(argv.begin(), argv.end())<<'\n';
491 string srcdir=strip(run_command(argv));
497 for(list<FS::Path>::const_iterator i=pkg_path.begin(); i!=pkg_path.end(); ++i)
499 list<string> files=list_files(*i);
500 for(list<string>::const_iterator j=files.begin(); j!=files.end(); ++j)
502 FS::Path full=*i / *j;
503 if(FS::exists(full/"Build"))
504 pkg_dirs.push_back(full);
509 bool msp=!name.compare(0, 3, "msp");
510 for(list<FS::Path>::const_iterator i=pkg_dirs.begin(); i!=pkg_dirs.end(); ++i)
512 string base=basename(*i);
513 unsigned dash=base.rfind('-');
515 if(!base.compare(0, dash, name))
517 else if(msp && !base.compare(0, dash-3, name, 3, string::npos))
525 Loads the given build file.
527 @param fn Path to the file
529 @return 0 on success, -1 if the file could not be opened
531 int Builder::load_build_file(const FS::Path &fn)
535 IO::File inf(fn.str());
536 IO::Buffered in(inf);
539 cout<<"Reading "<<fn<<'\n';
541 DataFile::Parser parser(in, fn.str());
542 Loader loader(*this, fn.subpath(0, fn.size()-1));
545 catch(const IO::FileNotFound &)
554 Creates targets for all packages and prepares them for building.
556 @return 0 if everything went ok, -1 if something bad happened and a build
557 shouldn't be attempted
559 int Builder::create_targets()
561 Target *world=new VirtualTarget(*this, "world");
563 Target *def_tgt=new VirtualTarget(*this, "default");
564 world->add_depend(def_tgt);
566 Target *install=new VirtualTarget(*this, "install");
567 world->add_depend(install);
569 Target *tarballs=new VirtualTarget(*this, "tarballs");
570 world->add_depend(tarballs);
572 PackageList all_reqs=main_pkg->collect_requires();
573 for(PackageList::iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
575 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
579 const ComponentList &components=spkg->get_components();
580 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
583 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
585 PkgConfig *pc=new PkgConfig(*this, *spkg);
586 install->add_depend(new Install(*this, *spkg, *pc));
589 tarballs->add_depend(new TarBall(*this, *spkg));
592 // Find dependencies until no new targets are created
593 while(!new_tgts.empty())
595 Target *tgt=new_tgts.front();
596 new_tgts.erase(new_tgts.begin());
598 if(!tgt->get_depends_ready())
599 new_tgts.push_back(tgt);
603 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
605 Target *tgt=get_target((cwd/ *i).str());
608 cerr<<"Unknown what-if target "<<*i<<'\n';
614 // Make the cmdline target depend on all targets mentioned on the command line
615 Target *cmdline=new VirtualTarget(*this, "cmdline");
616 bool build_world=false;
617 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
619 Target *tgt=get_target(*i);
621 tgt=get_target((cwd/ *i).str());
624 cerr<<"I don't know anything about "<<*i<<'\n';
629 cmdline->add_depend(tgt);
632 /* If world is to be built, prepare cmdline. If not, add cmdline to world
633 and prepare world. I don't really like this, but it keeps the graph
639 world->add_depend(cmdline);
643 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
644 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
645 spkg->get_deps_cache().save();
651 Check if a header exists, either as a target or a file. Either an existing
652 target or a new SystemHeader target will be returned.
654 Target *Builder::get_header(const Msp::FS::Path &fn)
656 Target *tgt=get_target(fn.str());
661 tgt=new SystemHeader(*this, fn.str());
667 Target *Builder::get_library(const string &lib, const FS::Path &path, LibMode mode)
669 // Populate a list of candidate filenames
670 StringList candidates;
674 if(current_arch=="win32")
676 candidates.push_back("lib"+lib+".dll");
677 candidates.push_back(lib+".dll");
680 candidates.push_back("lib"+lib+".so");
683 /* Static libraries are always considered, since sometimes shared versions
684 may not be available */
685 candidates.push_back("lib"+lib+".a");
686 if(current_arch=="win32")
687 candidates.push_back("lib"+lib+".dll.a");
689 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
691 string full=(path/ *i).str();
692 Target *tgt=get_target(full);
696 Target *real_tgt=tgt;
697 if(dynamic_cast<Install *>(tgt))
698 real_tgt=real_tgt->get_depends().front();
700 /* Ignore dynamic libraries from local packages unless library mode is
702 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
707 else if(FS::is_reg(full))
709 tgt=new SystemLibrary(*this, full);
718 Updates a hash with a string. This is used from get_header and get_library.
720 void Builder::update_hash(string &hash, const string &value)
722 for(unsigned i=0; i<value.size(); ++i)
723 hash[i%hash.size()]^=value[i];
727 This function supervises the build process, starting new actions when slots
730 int Builder::do_build()
732 Target *cmdline=get_target("cmdline");
734 unsigned total=cmdline->count_rebuild();
737 cout<<"Already up to date\n";
741 cout<<"Will build "<<total<<" target(s)\n";
743 vector<Action *> actions;
752 if(actions.size()<jobs && !fail)
754 Target *tgt=cmdline->get_buildable_target();
757 Action *action=tgt->build();
759 actions.push_back(action);
763 cout<<count<<" of "<<total<<" targets built\033[1G";
767 else if(actions.empty())
771 Time::sleep(10*Time::msec);
773 for(unsigned i=0; i<actions.size();)
775 int status=actions[i]->check();
781 actions.erase(actions.begin()+i);
784 if(actions.empty() && fail)
795 cout<<"Build failed\n";
796 else if(show_progress)
797 cout<<"Build complete\n";
803 Cleans buildable targets. If clean is 1, cleans only this package. If
804 clean is 2 or greater, cleans all buildable packages.
806 int Builder::do_clean()
808 // Cleaning doesn't care about ordering, so a simpler method can be used
810 set<Target *> clean_tgts;
812 queue.push_back(get_target("cmdline"));
814 while(!queue.empty())
816 Target *tgt=queue.front();
817 queue.erase(queue.begin());
819 if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
820 clean_tgts.insert(tgt);
822 const TargetList &deps=tgt->get_depends();
823 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
824 if(!clean_tgts.count(*i))
828 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
830 Action *action=new Unlink(*this, **i);
831 while(action->check()<0) ;
839 Prints out information about the default package.
841 void Builder::package_help()
843 const Config &config=main_pkg->get_config();
844 const Config::OptionMap &options=config.get_options();
846 cout<<"Required packages:\n ";
847 const PackageList &requires=main_pkg->get_requires();
848 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
850 if(i!=requires.begin())
852 cout<<(*i)->get_name();
855 cout<<"Package configuration:\n";
856 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
858 const Config::Option &opt=i->second;
859 cout<<" "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
863 Application::RegApp<Builder> Builder::reg;
866 Builder::Loader::Loader(Builder &b, const FS::Path &s):
870 add("architecture", &Loader::architecture);
871 add("binary_package", &Loader::binpkg);
872 add("profile", &Loader::profile);
873 add("package", &Loader::package);
876 void Builder::Loader::architecture(const string &n)
878 Architecture arch(bld, n);
880 bld.archs.insert(ArchMap::value_type(n, arch));
883 void Builder::Loader::binpkg(const string &n)
885 BinaryPackage *pkg=new BinaryPackage(bld, n);
887 bld.packages.insert(PackageMap::value_type(n, pkg));
890 void Builder::Loader::profile(const string &n)
893 ProfileLoader ldr(prf);
895 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
898 void Builder::Loader::package(const string &n)
900 SourcePackage *pkg=new SourcePackage(bld, n, src);
905 bld.packages.insert(PackageMap::value_type(n, pkg));
909 Builder::ProfileLoader::ProfileLoader(StringMap &p):
912 add("option", &ProfileLoader::option);
915 void Builder::ProfileLoader::option(const string &o, const string &v)
917 profile.insert(StringMap::value_type(o, v));