]> git.tdb.fi Git - builder.git/blob - source/builder.cpp
0b1d1bf55163b3a8c44d2a767bcb4e790a0b7b7a
[builder.git] / source / builder.cpp
1 #include <fstream>
2 #include <iostream>
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>
12 #include "action.h"
13 #include "analyzer.h"
14 #include "builder.h"
15 #include "executable.h"
16 #include "header.h"
17 #include "install.h"
18 #include "misc.h"
19 #include "objectfile.h"
20 #include "package.h"
21 #include "systemlibrary.h"
22 #include "virtualtarget.h"
23
24 using namespace std;
25 using namespace Msp;
26
27 Builder::Builder(int argc, char **argv):
28         verbose(1),
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('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);
52
53         verbose+=getopt['v'].count();
54
55         if(getopt['a'])
56         {
57                 analyzer=new Analyzer(*this);
58
59                 string mode=getopt['a'].arg();
60                 if(mode=="deps")
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);
68                 else
69                         throw UsageError("Invalid analysis mode");
70
71                 if(getopt["max-depth"])
72                         analyzer->set_max_depth(strtol(getopt["max-depth"].arg()));
73                 analyzer->set_full_paths(getopt["full-paths"]);
74
75                 if(!getopt['b'])
76                         do_build=false;
77         }
78
79         dry_run=getopt['n'];
80         jobs=max(strtol(getopt['j'].arg()), 1L);
81         chrome=getopt["chrome"];
82         conf_all=getopt['A'];
83         build_file=getopt['f'].arg();
84         build_all=getopt['B'];
85         help=getopt['h'];
86
87         if(getopt['C'])
88                 chdir(getopt['C'].arg().c_str());
89
90         for(int i=index; i<argc; ++i)
91         {
92                 string v(argv[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)));
96                 else
97                         cmdline_targets.push_back(argv[i]);
98         }
99
100         if(cmdline_targets.empty())
101                 cmdline_targets.push_back("default");
102
103         if(getopt['W'])
104                 what_if.push_back(getopt['W'].arg());
105
106         cwd=Path::getcwd();
107 }
108
109 /**
110 Gets a package with the specified name, possibly creating it.
111
112 @param   n  Package name
113
114 @return  Pointer to the package, or 0 if the package could not be located
115 */
116 Package *Builder::get_package(const string &n)
117 {
118         PackageMap::iterator i=packages.find(n);
119         if(i!=packages.end())
120                 return i->second;
121
122         // Try to get source directory with pkgconfig
123         list<string> argv;
124         argv.push_back("pkg-config");
125         argv.push_back("--variable=source");
126         argv.push_back(n);
127         string srcdir=strip(run_command(argv));
128         
129         PathList dirs;
130         if(!srcdir.empty())
131                 dirs.push_back(srcdir);
132
133         // Make some other guesses about the source directory
134         string dirname=n;
135         if(!dirname.compare(0, 3, "msp"))
136                 dirname.erase(0, 3);
137         dirs.push_back(cwd/dirname);
138         dirs.push_back(cwd/".."/dirname);
139
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"))
143                 {
144                         i=packages.find(n);
145                         if(i!=packages.end())
146                                 return i->second;
147                         break;
148                 }
149
150         // Package source not found - create a binary package
151         Package *pkg=Package::create(*this, n);
152         packages.insert(PackageMap::value_type(n, pkg));
153         if(pkg)
154                 new_pkgs.push_back(pkg);
155
156         return pkg;
157 }
158
159 /**
160 Returns the target with the given name, or 0 if no such target exists.
161 */
162 Target *Builder::get_target(const string &n)
163 {
164         TargetMap::iterator i=targets.find(n);
165         if(i!=targets.end())
166                 return i->second;
167         return 0;
168 }
169
170 /**
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.
173 */
174 Target *Builder::get_header(const string &include, const string &from, const list<string> &path)
175 {
176         string hash(8, 0);
177         update_hash(hash, from);
178         for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
179                 update_hash(hash, *i);
180
181         string id=hash+include;
182         TargetMap::iterator i=includes.find(id);
183         if(i!=includes.end())
184                 return i->second;
185
186         string fn=include.substr(1);
187         Target *tgt=0;
188         if(include[0]=='"' && (tgt=check_header(Path::Path(from)/fn)))
189                 return tgt;
190         if((tgt=check_header(Path::Path("/usr/include")/fn)))
191                 return tgt;
192         //XXX Determine the C++ header location dynamically
193         if((tgt=check_header(Path::Path("/usr/include/c++/4.1.2")/fn)))
194                 return tgt;
195         for(list<string>::const_iterator j=path.begin(); j!=path.end(); ++j)
196                 if((tgt=check_header(cwd/ *j/fn)))
197                         return tgt;
198         
199         return 0;
200 }
201
202 Target *Builder::get_library(const string &lib, const list<string> &path)
203 {
204         string hash(8, 0);
205         for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
206                 update_hash(hash, *i);
207
208         string id=hash+lib;
209         TargetMap::iterator i=libraries.find(id);
210         if(i!=libraries.end())
211                 return i->second;
212
213         string basename="lib"+lib+".so";
214         for(list<string>::const_iterator j=path.begin(); j!=path.end(); ++j)
215         {
216                 string full=(cwd/ *j/basename).str();
217                 Target *tgt=get_target(full);
218                 if(tgt) return tgt;
219                 
220                 if(Path::exists(full))
221                 {
222                         add_target(tgt=new SystemLibrary(*this, full));
223                         return tgt;
224                 }
225         }
226
227         return 0;
228 }
229
230 int Builder::main()
231 {
232         if(load_build_file(cwd/build_file))
233         {
234                 cerr<<"No build info here.\n";
235                 return 1;
236         }
237
238         default_pkg=packages.begin()->second;
239
240         while(!new_pkgs.empty())
241         {
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());
246                 pkg->resolve_refs();
247         }
248
249         if(help)
250         {
251                 usage("builder", false);
252                 cout<<'\n';
253                 package_help();
254                 return 0;
255         }
256
257         std::list<std::string> missing;
258         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
259                 if(!i->second)
260                         missing.push_back(i->first);
261
262         if(!missing.empty())
263         {
264                 missing.sort();
265                 cerr<<"The following packages were not found on the system:\n";
266                 for(list<string>::iterator i=missing.begin(); i!=missing.end(); ++i)
267                         cerr<<"  "<<*i<<'\n';
268                 cerr<<"Please install them and try again.\n";
269                 return 1;
270         }
271
272         default_pkg->create_build_info();
273
274         if(create_targets())
275                 return 1;
276
277         cout<<packages.size()<<" packages, "<<targets.size()<<" targets\n";
278         if(verbose>=2)
279         {
280                 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
281                 {
282                         cout<<' '<<i->second->get_name();
283                         if(i->second->get_buildable())
284                                 cout<<'*';
285                         unsigned count=0;
286                         unsigned ood_count=0;
287                         for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
288                                 if(j->second->get_package()==i->second)
289                                 {
290                                         ++count;
291                                         if(j->second->get_rebuild())
292                                                 ++ood_count;
293                                 }
294                         if(count)
295                         {
296                                 cout<<" ("<<count<<" targets";
297                                 if(ood_count)
298                                         cout<<", "<<ood_count<<" out-of-date";
299                                 cout<<')';
300                         }
301                         cout<<'\n';
302                 }
303         }
304
305         if(analyzer)
306                 analyzer->analyze();
307
308         if(do_build)
309                 build();
310
311         return exit_code;
312 }
313
314 Builder::~Builder()
315 {
316         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
317                 delete i->second;
318         for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
319                 delete i->second;
320         delete analyzer;
321 }
322
323 void Builder::usage(const char *argv0, bool brief)
324 {
325         if(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> ...]";
327         else
328         {
329                 cerr<<
330                         "Usage: "<<argv0<<" [options] [<target> ...]\n"
331                         "\n"
332                         "Options:\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";
348         }
349 }
350
351 int Builder::load_build_file(const Path::Path &fn)
352 {
353         ifstream in(fn.str().c_str());
354         if(!in)
355                 return -1;
356
357         Parser::Parser parser(in, fn.str());
358         Loader loader(*this, fn.subpath(0, fn.size()-1));
359         loader.load(parser);
360
361         return 0;
362 }
363
364 int Builder::create_targets()
365 {
366         Target *world=new VirtualTarget(*this, "world");
367         add_target(world);
368
369         Target *def_tgt=new VirtualTarget(*this, "default");
370         add_target(def_tgt);
371         world->add_depend(def_tgt);
372
373         Target *install=new VirtualTarget(*this, "install");
374         add_target(install);
375         world->add_depend(install);
376
377         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
378         {
379                 if(!i->second)
380                         continue;
381                 if(!i->second->get_buildable())
382                         continue;
383
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;
387
388                 const ComponentList &components=i->second->get_components();
389                 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
390                 {
391                         PathList files;
392                         const PathList &sources=j->get_sources();
393                         for(PathList::const_iterator k=sources.begin(); k!=sources.end(); ++k)
394                         {
395                                 struct stat st;
396                                 stat(*k, st);
397                                 if(S_ISDIR(st.st_mode))
398                                 {
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);
402                                 }
403                                 else
404                                         files.push_back(*k);
405                         }
406
407                         bool build_exe=j->get_type()!=Component::HEADERS;
408                         
409                         list<ObjectFile *> objs;
410                         for(PathList::iterator k=files.begin(); k!=files.end(); ++k)
411                         {
412                                 string basename=(*k)[-1];
413                                 string ext=Path::splitext(basename).ext;
414                                 if(ext==".cpp" || ext==".c")
415                                 {
416                                         if(build_exe)
417                                         {
418                                                 SourceFile *src=new SourceFile(*this, &*j, k->str());
419                                                 add_target(src);
420                                                 
421                                                 ObjectFile *obj=new ObjectFile(*this, *j, *src);
422                                                 add_target(obj);
423                                                 objs.push_back(obj);
424                                         }
425                                 }
426                                 else if(ext==".h")
427                                 {
428                                         Target *hdr=get_target(k->str());
429                                         if(!hdr)
430                                         {
431                                                 hdr=new Header(*this, &*j, k->str());
432                                                 add_target(hdr);
433                                         }
434                                         if(!j->get_install_headers().empty())
435                                         {
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());
438                                                 add_target(inst);
439                                                 install->add_depend(inst);
440                                         }
441                                 }
442                         }
443
444                         if(build_exe)
445                         {
446                                 Executable *exe=new Executable(*this, *j, objs);
447                                 add_target(exe);
448                                 if(i->second==default_pkg)
449                                         def_tgt->add_depend(exe);
450                                 else
451                                         world->add_depend(exe);
452
453                                 if(j->get_install())
454                                 {
455                                         string inst_dir;
456                                         if(j->get_type()==Component::PROGRAM)
457                                                 inst_dir="bin";
458                                         else if(j->get_type()==Component::LIBRARY)
459                                                 inst_dir="lib";
460                                         if(!inst_dir.empty())
461                                         {
462                                                 Install *inst=new Install(*this, *i->second, *exe, (inst_base/inst_dir/Path::basename(exe->get_name())).str());
463                                                 add_target(inst);
464                                                 install->add_depend(inst);
465                                         }
466                                 }
467                         }
468                 }
469         }
470
471         while(!new_tgts.empty())
472         {
473                 Target *tgt=new_tgts.front();
474                 new_tgts.erase(new_tgts.begin());
475                 tgt->find_depends();
476                 if(!tgt->get_depends_ready())
477                         new_tgts.push_back(tgt);
478         }
479
480         for(list<string>::iterator i=what_if.begin(); i!=what_if.end(); ++i)
481         {
482                 Target *tgt=get_target((cwd/ *i).str());
483                 if(!tgt)
484                 {
485                         cerr<<"Unknown what-if target "<<*i<<'\n';
486                         return -1;
487                 }
488                 tgt->touch();
489         }
490
491         Target *cmdline=new VirtualTarget(*this, "cmdline");
492         add_target(cmdline);
493         world->add_depend(cmdline);
494         for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
495         {
496                 Target *tgt=get_target(*i);
497                 if(!tgt)
498                         tgt=get_target((cwd/ *i).str());
499                 if(!tgt)
500                 {
501                         cerr<<"I don't know anything about "<<*i<<'\n';
502                         return -1;
503                 }
504                 cmdline->add_depend(tgt);
505         }
506
507         world->prepare();
508
509         return 0;
510 }
511
512 Target *Builder::check_header(const Msp::Path::Path &fn)
513 {
514         Target *tgt=get_target(fn.str());
515         if(tgt) return tgt;
516
517         if(Path::exists(fn))
518         {
519                 add_target(tgt=new SystemHeader(*this, fn.str()));
520                 return tgt;
521         }
522         return 0;
523 }
524
525 void Builder::add_target(Target *t)
526 {
527         targets.insert(TargetMap::value_type(t->get_name(), t));
528         new_tgts.push_back(t);
529 }
530
531 void Builder::update_hash(string &hash, const string &value)
532 {
533         for(unsigned i=0; i<value.size(); ++i)
534                 hash[i%hash.size()]^=value[i];
535 }
536
537 /**
538 This function supervises the build process, starting new actions when slots
539 become available.
540 */
541 int Builder::build()
542 {
543         Target *cmdline=get_target("cmdline");
544
545         unsigned total=cmdline->count_rebuild();
546         if(!total)
547         {
548                 cout<<"Already up to date\n";
549                 return 0;
550         }
551         cout<<"Will build "<<total<<" target(s)\n";
552
553         vector<Action *> actions;
554
555         if(chrome)
556                 cout<<"0 targets built\n";
557         unsigned count=0;
558
559         bool fail=false;
560         bool finish=false;
561
562         while(!finish)
563         {
564                 if(actions.size()<jobs && !fail)
565                 {
566                         Target *tgt=cmdline->get_buildable_target();
567                         if(tgt)
568                         {
569                                 Action *action=tgt->build();
570                                 if(action)
571                                         actions.push_back(action);
572                         }
573                         else if(actions.empty())
574                                 finish=true;
575                 }
576                 else
577                         Time::sleep(10*Time::msec);
578
579                 for(unsigned i=0; i<actions.size();)
580                 {
581                         int status=actions[i]->check();
582                         if(status>=0)
583                         {
584                                 ++count;
585                                 if(chrome)
586                                 {
587                                         cout<<"\e["<<actions.size()+1<<'A';
588                                         cout<<count<<" targets built\n";
589                                         if(i)
590                                                 cout<<"\e["<<i<<"B";
591                                         cout<<"\e[M";
592                                         if(i<actions.size()-1)
593                                                 cout<<"\e["<<actions.size()-i-1<<"B";
594                                         cout.flush();
595                                 }
596                                 delete actions[i];
597                                 actions.erase(actions.begin()+i);
598                                 if(status>0)
599                                         fail=true;
600                                 if(actions.empty() && fail)
601                                         finish=true;
602                         }
603                         else
604                                 ++i;
605                 }
606         }
607
608         return fail?-1:0;
609 }
610
611 void Builder::package_help()
612 {
613         const Config &config=default_pkg->get_config();
614         const Config::OptionMap &options=config.get_options();
615
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)
619         {
620                 if(i!=requires.begin())
621                         cout<<", ";
622                 cout<<i->get_name();
623         }
624         cout<<"\n\n";
625         cout<<"Package configuration:\n";
626         for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
627         {
628                 const Config::Option &opt=i->second;
629                 cout<<"  "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
630         }
631 }
632
633 Application::RegApp<Builder> Builder::reg;
634
635 Builder::Loader::Loader(Builder &b, const Path::Path &s):
636         bld(b),
637         src(s)
638 {
639         add("package", &Loader::package);
640 }
641
642 void Builder::Loader::package(const string &n)
643 {
644         Package *pkg=new Package(bld, n, src);
645         load_sub(*pkg);
646         bld.packages.insert(PackageMap::value_type(n, pkg));
647         bld.new_pkgs.push_back(pkg);
648 }
649