]> git.tdb.fi Git - builder.git/blob - source/builder.cpp
Move class PackageRef to its own files
[builder.git] / source / builder.cpp
1 #include <fstream>
2 #include <msp/progress.h>
3 #include <msp/strconv.h>
4 #include <msp/strutils.h>
5 #include <msp/core/error.h>
6 #include <msp/getopt++/getopt++.h>
7 #include <msp/parser/parser.h>
8 #include <msp/path/utils.h>
9 #include <msp/time/units.h>
10 #include <msp/time/utils.h>
11 #include "action.h"
12 #include "analyzer.h"
13 #include "builder.h"
14 #include "executable.h"
15 #include "header.h"
16 #include "install.h"
17 #include "misc.h"
18 #include "objectfile.h"
19 #include "package.h"
20 #include "systemlibrary.h"
21 #include "virtualtarget.h"
22
23 using namespace std;
24 using namespace Msp;
25
26 Builder::Builder(int argc, char **argv):
27         verbose(1),
28         cwd(Path::getcwd()),
29         build_file("Build"),
30         do_build(true),
31         analyzer(0),
32         jobs(1),
33         chrome(false)
34 {
35         GetOpt getopt;
36         getopt.add_option(GetOpt::Option('v', "verbose", GetOpt::NONE));
37         getopt.add_option(GetOpt::Option('a', "analyze", GetOpt::REQUIRED));
38         getopt.add_option(GetOpt::Option('b', "build", GetOpt::NONE));
39         getopt.add_option(GetOpt::Option("max-depth", GetOpt::REQUIRED));
40         getopt.add_option(GetOpt::Option('n', "dry-run", GetOpt::NONE));
41         getopt.add_option(GetOpt::Option('W', "what-if", GetOpt::REQUIRED));
42         getopt.add_option(GetOpt::Option('B', "build-all", GetOpt::NONE));
43         getopt.add_option(GetOpt::Option('C', "chdir", GetOpt::REQUIRED));
44         getopt.add_option(GetOpt::Option('j', "jobs", GetOpt::REQUIRED, "1"));
45         getopt.add_option(GetOpt::Option('h', "help", GetOpt::NONE));
46         getopt.add_option(GetOpt::Option('c', "clean", GetOpt::NONE));
47         getopt.add_option(GetOpt::Option('f', "file", GetOpt::REQUIRED, "Build"));
48         getopt.add_option(GetOpt::Option("chrome", GetOpt::NONE));
49         getopt.add_option(GetOpt::Option("full-paths", GetOpt::NONE));
50         int index=getopt(argc, argv);
51
52         verbose+=getopt['v'].count();
53
54         if(getopt['a'])
55         {
56                 analyzer=new Analyzer(*this);
57
58                 string mode=getopt['a'].arg();
59                 if(mode=="deps")
60                         analyzer->set_mode(Analyzer::DEPS);
61                 else if(mode=="alldeps")
62                         analyzer->set_mode(Analyzer::ALLDEPS);
63                 else if(mode=="rebuild")
64                         analyzer->set_mode(Analyzer::REBUILD);
65                 else if(mode=="rdeps")
66                         analyzer->set_mode(Analyzer::RDEPS);
67                 else
68                         throw UsageError("Invalid analysis mode");
69
70                 if(getopt["max-depth"])
71                         analyzer->set_max_depth(strtol(getopt["max-depth"].arg()));
72                 analyzer->set_full_paths(getopt["full-paths"]);
73
74                 if(!getopt['b'])
75                         do_build=false;
76         }
77
78         dry_run=getopt['n'];
79
80         jobs=max(strtol(getopt['j'].arg()), 1L);
81
82         chrome=getopt["chrome"];
83
84         if(getopt['C'])
85                 chdir(getopt['C'].arg().c_str());
86
87         build_file=getopt['f'].arg();
88
89         for(int i=index; i<argc; ++i)
90         {
91                 string v(argv[i]);
92                 unsigned equal=v.find('=');
93                 if(equal!=string::npos)
94                         cmdline_options.insert(RawOptionMap::value_type(v.substr(0, equal), v.substr(equal+1)));
95                 else
96                         cmdline_targets.push_back(argv[i]);
97         }
98
99         if(cmdline_targets.empty())
100                 cmdline_targets.push_back("default");
101
102         if(getopt['W'])
103                 what_if.push_back(getopt['W'].arg());
104 }
105
106 /**
107 Gets a package with the specified name, possibly creating it.
108
109 @param   n  Package name
110
111 @return  Pointer to the package, or 0 if the package could not be located
112 */
113 Package *Builder::get_package(const string &n)
114 {
115         PackageMap::iterator i=packages.find(n);
116         if(i!=packages.end())
117                 return i->second;
118
119         // Try to get source directory with pkgconfig
120         list<string> argv;
121         argv.push_back("pkg-config");
122         argv.push_back("--variable=source");
123         argv.push_back(n);
124         string srcdir=strip(run_command(argv));
125         
126         PathList dirs;
127         if(!srcdir.empty())
128                 dirs.push_back(srcdir);
129
130         // Make some other guesses about the source directory
131         string dirname=n;
132         if(!dirname.compare(0, 3, "msp"))
133                 dirname.erase(0, 3);
134         dirs.push_back(cwd/dirname);
135         dirs.push_back(cwd/".."/dirname);
136
137         // Go through the candidate directories and look for a Build file
138         for(PathList::iterator j=dirs.begin(); j!=dirs.end(); ++j)
139                 if(!load_build_file(*j/"Build"))
140                 {
141                         i=packages.find(n);
142                         if(i!=packages.end())
143                                 return i->second;
144                         break;
145                 }
146
147         // Package source not found - create a binary package
148         Package *pkg=Package::create(*this, n);
149         packages.insert(PackageMap::value_type(n, pkg));
150         if(pkg)
151                 new_pkgs.push_back(pkg);
152
153         return pkg;
154 }
155
156 /**
157 Returns the target with the given name, or 0 if no such target exists.
158 */
159 Target *Builder::get_target(const string &n)
160 {
161         TargetMap::iterator i=targets.find(n);
162         if(i!=targets.end())
163                 return i->second;
164         return 0;
165 }
166
167 /**
168 Tries to locate a header included from a given location and with a given include
169 path.  Considers known targets as well as existing files.
170 */
171 Target *Builder::get_header(const string &include, const string &from, const list<string> &path)
172 {
173         string hash(8, 0);
174         update_hash(hash, from);
175         for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
176                 update_hash(hash, *i);
177
178         string id=hash+include;
179         TargetMap::iterator i=includes.find(id);
180         if(i!=includes.end())
181                 return i->second;
182
183         string fn=include.substr(1);
184         Target *tgt=0;
185         if(include[0]=='"' && (tgt=check_header(Path::Path(from)/fn)))
186                 return tgt;
187         if((tgt=check_header(Path::Path("/usr/include")/fn)))
188                 return tgt;
189         //XXX Determine the C++ header location dynamically
190         if((tgt=check_header(Path::Path("/usr/include/c++/4.1.2")/fn)))
191                 return tgt;
192         for(list<string>::const_iterator j=path.begin(); j!=path.end(); ++j)
193                 if((tgt=check_header(Path::Path(*j)/fn)))
194                         return tgt;
195         
196         return 0;
197 }
198
199 Target *Builder::get_library(const string &lib, const list<string> &path)
200 {
201         string hash(8, 0);
202         for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
203                 update_hash(hash, *i);
204
205         string id=hash+lib;
206         TargetMap::iterator i=libraries.find(id);
207         if(i!=libraries.end())
208                 return i->second;
209
210         string basename="lib"+lib+".so";
211         for(list<string>::const_iterator j=path.begin(); j!=path.end(); ++j)
212         {
213                 string full=(Path::Path(*j)/basename).str();
214                 Target *tgt=get_target(full);
215                 if(tgt) return tgt;
216                 
217                 if(Path::exists(full))
218                 {
219                         add_target(tgt=new SystemLibrary(*this, full));
220                         return tgt;
221                 }
222         }
223
224         return 0;
225 }
226
227 int Builder::main()
228 {
229         if(load_build_file(cwd/build_file))
230         {
231                 cerr<<"No build info here.\n";
232                 return 1;
233         }
234
235         default_pkg=packages.begin()->second;
236
237         bool conf_all=cmdline_options.count("conf_all");
238         while(!new_pkgs.empty())
239         {
240                 Package *pkg=new_pkgs.front();
241                 if(pkg==default_pkg || conf_all)
242                         pkg->process_options(cmdline_options);
243                 new_pkgs.erase(new_pkgs.begin());
244                 pkg->resolve_refs();
245         }
246
247         std::list<std::string> missing;
248         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
249                 if(!i->second)
250                         missing.push_back(i->first);
251
252         if(!missing.empty())
253         {
254                 missing.sort();
255                 cerr<<"The following packages were not found on the system:\n";
256                 for(list<string>::iterator i=missing.begin(); i!=missing.end(); ++i)
257                         cerr<<"  "<<*i<<'\n';
258                 cerr<<"Please install them and try again.\n";
259                 return 1;
260         }
261
262         default_pkg->create_build_info();
263
264         if(create_targets())
265                 return 1;
266
267         cout<<packages.size()<<" packages, "<<targets.size()<<" targets\n";
268         if(verbose>=2)
269         {
270                 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
271                 {
272                         cout<<' '<<i->second->get_name();
273                         if(i->second->get_buildable())
274                                 cout<<'*';
275                         unsigned count=0;
276                         for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
277                                 if(j->second->get_package()==i->second)
278                                         ++count;
279                         cout<<" ("<<count<<" targets)\n";
280                 }
281         }
282
283         if(analyzer)
284                 analyzer->analyze();
285
286         if(do_build)
287                 build();
288
289         return exit_code;
290 }
291
292 Builder::~Builder()
293 {
294         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
295                 delete i->second;
296         for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
297                 delete i->second;
298         delete analyzer;
299 }
300
301 int Builder::load_build_file(const Path::Path &fn)
302 {
303         ifstream in(fn.str().c_str());
304         if(!in)
305                 return -1;
306
307         Parser::Parser parser(in, fn.str());
308         Loader loader(*this, fn.subpath(0, fn.size()-1));
309         loader.load(parser);
310
311         return 0;
312 }
313
314 int Builder::create_targets()
315 {
316         Target *world=new VirtualTarget(*this, "world");
317         add_target(world);
318
319         Target *def_tgt=new VirtualTarget(*this, "default");
320         add_target(def_tgt);
321         world->add_depend(def_tgt);
322
323         Target *install=new VirtualTarget(*this, "install");
324         add_target(install);
325         world->add_depend(install);
326
327         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
328         {
329                 if(!i->second)
330                         continue;
331                 if(!i->second->get_buildable())
332                         continue;
333
334                 Path::Path inst_base;
335                 if(i->second->get_config().is_option("prefix"))
336                         inst_base=i->second->get_config().get_option("prefix").value;
337
338                 const ComponentList &components=i->second->get_components();
339                 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
340                 {
341                         PathList files;
342                         const PathList &sources=j->get_sources();
343                         for(PathList::const_iterator k=sources.begin(); k!=sources.end(); ++k)
344                         {
345                                 struct stat st;
346                                 stat(*k, st);
347                                 if(S_ISDIR(st.st_mode))
348                                 {
349                                         list<string> sfiles=list_files(*k);
350                                         for(list<string>::iterator l=sfiles.begin(); l!=sfiles.end(); ++l)
351                                                 files.push_back(*k / *l);
352                                 }
353                                 else
354                                         files.push_back(*k);
355                         }
356
357                         bool build_exe=j->get_type()!=Component::HEADERS;
358                         
359                         list<ObjectFile *> objs;
360                         for(PathList::iterator k=files.begin(); k!=files.end(); ++k)
361                         {
362                                 string basename=(*k)[-1];
363                                 string ext=Path::splitext(basename).ext;
364                                 if(ext==".cpp" || ext==".c")
365                                 {
366                                         if(build_exe)
367                                         {
368                                                 SourceFile *src=new SourceFile(*this, &*j, k->str());
369                                                 add_target(src);
370                                                 
371                                                 ObjectFile *obj=new ObjectFile(*this, *j, *src);
372                                                 add_target(obj);
373                                                 objs.push_back(obj);
374                                         }
375                                 }
376                                 else if(ext==".h")
377                                 {
378                                         Target *hdr=get_target(k->str());
379                                         if(!hdr)
380                                         {
381                                                 hdr=new Header(*this, &*j, k->str());
382                                                 add_target(hdr);
383                                         }
384                                         if(!j->get_install_headers().empty())
385                                         {
386                                                 Path::Path inst_path=inst_base/"include"/j->get_install_headers()/basename;
387                                                 Install *inst=new Install(*this, *i->second, *hdr, inst_path.str());
388                                                 add_target(inst);
389                                                 install->add_depend(inst);
390                                         }
391                                 }
392                         }
393
394                         if(build_exe)
395                         {
396                                 Executable *exe=new Executable(*this, *j, objs);
397                                 add_target(exe);
398                                 if(i->second==default_pkg)
399                                         def_tgt->add_depend(exe);
400                                 else
401                                         world->add_depend(exe);
402
403                                 if(j->get_install())
404                                 {
405                                         string inst_dir;
406                                         if(j->get_type()==Component::PROGRAM)
407                                                 inst_dir="bin";
408                                         else if(j->get_type()==Component::LIBRARY)
409                                                 inst_dir="lib";
410                                         if(!inst_dir.empty())
411                                         {
412                                                 Install *inst=new Install(*this, *i->second, *exe, (inst_base/inst_dir/Path::basename(exe->get_name())).str());
413                                                 add_target(inst);
414                                                 install->add_depend(inst);
415                                         }
416                                 }
417                         }
418                 }
419         }
420
421         while(!new_tgts.empty())
422         {
423                 Target *tgt=new_tgts.front();
424                 new_tgts.erase(new_tgts.begin());
425                 tgt->find_depends();
426                 if(!tgt->get_depends_ready())
427                         new_tgts.push_back(tgt);
428         }
429
430         for(list<string>::iterator i=what_if.begin(); i!=what_if.end(); ++i)
431         {
432                 Target *tgt=get_target((cwd/ *i).str());
433                 if(!tgt)
434                 {
435                         cerr<<"Unknown what-if target "<<*i<<'\n';
436                         return -1;
437                 }
438                 tgt->touch();
439         }
440
441         Target *cmdline=new VirtualTarget(*this, "cmdline");
442         add_target(cmdline);
443         world->add_depend(cmdline);
444         for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
445         {
446                 Target *tgt=get_target(*i);
447                 if(!tgt)
448                         tgt=get_target((cwd/ *i).str());
449                 if(!tgt)
450                 {
451                         cerr<<"I don't know anything about "<<*i<<'\n';
452                         return -1;
453                 }
454                 cmdline->add_depend(tgt);
455         }
456
457         world->prepare();
458
459         return 0;
460 }
461
462 Target *Builder::check_header(const Msp::Path::Path &fn)
463 {
464         Target *tgt=get_target(fn.str());
465         if(tgt) return tgt;
466
467         if(Path::exists(fn))
468         {
469                 add_target(tgt=new SystemHeader(*this, fn.str()));
470                 return tgt;
471         }
472         return 0;
473 }
474
475 void Builder::add_target(Target *t)
476 {
477         targets.insert(TargetMap::value_type(t->get_name(), t));
478         new_tgts.push_back(t);
479 }
480
481 void Builder::update_hash(string &hash, const string &value)
482 {
483         for(unsigned i=0; i<value.size(); ++i)
484                 hash[i%hash.size()]^=value[i];
485 }
486
487 /**
488 This function supervises the build process, starting new actions when slots
489 become available.
490 */
491 int Builder::build()
492 {
493         Target *cmdline=get_target("cmdline");
494
495         unsigned total=cmdline->count_rebuild();
496         if(!total)
497         {
498                 cout<<"Already up to date\n";
499                 return 0;
500         }
501         cout<<"Will build "<<total<<" target(s)\n";
502
503         vector<Action *> actions;
504
505         if(chrome)
506                 cout<<"0 targets built\n";
507         unsigned count=0;
508
509         bool fail=false;
510         bool finish=false;
511
512         while(!finish)
513         {
514                 if(actions.size()<jobs && !fail)
515                 {
516                         Target *tgt=cmdline->get_buildable_target();
517                         if(tgt)
518                         {
519                                 Action *action=tgt->build();
520                                 if(action)
521                                         actions.push_back(action);
522                         }
523                         else if(actions.empty())
524                                 finish=true;
525                 }
526                 else
527                         Time::sleep(10*Time::msec);
528
529                 for(unsigned i=0; i<actions.size();)
530                 {
531                         int status=actions[i]->check();
532                         if(status>=0)
533                         {
534                                 ++count;
535                                 if(chrome)
536                                 {
537                                         cout<<"\e["<<actions.size()+1<<'A';
538                                         cout<<count<<" targets built\n";
539                                         if(i)
540                                                 cout<<"\e["<<i<<"B";
541                                         cout<<"\e[M";
542                                         if(i<actions.size()-1)
543                                                 cout<<"\e["<<actions.size()-i-1<<"B";
544                                         cout.flush();
545                                 }
546                                 delete actions[i];
547                                 actions.erase(actions.begin()+i);
548                                 if(status>0)
549                                         fail=true;
550                                 if(actions.empty() && fail)
551                                         finish=true;
552                         }
553                         else
554                                 ++i;
555                 }
556         }
557
558         return fail?-1:0;
559 }
560
561 Application::RegApp<Builder> Builder::reg;
562
563 Builder::Loader::Loader(Builder &b, const Path::Path &s):
564         bld(b),
565         src(s)
566 {
567         add("package", &Loader::package);
568 }
569
570 void Builder::Loader::package(const string &n)
571 {
572         Package *pkg=new Package(bld, n, src);
573         load_sub(*pkg);
574         bld.packages.insert(PackageMap::value_type(n, pkg));
575         bld.new_pkgs.push_back(pkg);
576 }
577