]> git.tdb.fi Git - builder.git/blob - source/buildercli.cpp
Remove most container typedefs and refactor others
[builder.git] / source / buildercli.cpp
1 #include <msp/core/getopt.h>
2 #include <msp/fs/dir.h>
3 #include <msp/fs/stat.h>
4 #include <msp/io/print.h>
5 #include <msp/strings/format.h>
6 #include <msp/strings/utils.h>
7 #include "analyzer.h"
8 #include "buildercli.h"
9 #include "filetarget.h"
10 #include "sourcepackage.h"
11 #include "tool.h"
12 #include "toolchain.h"
13
14 using namespace std;
15 using namespace Msp;
16
17 BuilderCLI::BuilderCLI(int argc, char **argv):
18         RegisteredApplication<BuilderCLI>("builder"),
19         analyzer(0),
20         build(false),
21         clean(0),
22         dry_run(false),
23         help(false),
24         show_progress(false),
25         build_file("Build"),
26         jobs(1),
27         conf_all(false),
28         conf_only(false),
29         build_all(false),
30         create_makefile(false)
31 {
32         string analyze_mode;
33         string work_dir;
34         bool full_paths = false;
35         unsigned max_depth = 4;
36         string prefix;
37         string tempdir;
38         string arch;
39         bool no_externals = false;
40         unsigned verbose = 1;
41         bool silent = false;
42         list<string> log_channels;
43         string build_type;
44
45         GetOpt getopt;
46         getopt.add_option('a', "analyze",    analyze_mode,  GetOpt::REQUIRED_ARG).set_help("Perform dependency analysis.", "MODE");
47         getopt.add_option('b', "build",      build,         GetOpt::NO_ARG).set_help("Perform build even if also doing something else.");
48         getopt.add_option('c', "clean",      clean,         GetOpt::NO_ARG).set_help("Clean buildable targets.");
49         getopt.add_option('f', "file",       build_file,    GetOpt::REQUIRED_ARG).set_help("Read build instructions from FILE.", "FILE");
50         getopt.add_option('h', "help",       help,          GetOpt::NO_ARG).set_help("Print this message.");
51         getopt.add_option('j', "jobs",       jobs,          GetOpt::REQUIRED_ARG).set_help("Run up to NUM tasks in parallel.", "NUM");
52         getopt.add_option('l', "log",        log_channels,  GetOpt::REQUIRED_ARG).set_help("Enable listed log channels.", "LIST");
53         getopt.add_option('n', "dry-run",    dry_run,       GetOpt::NO_ARG).set_help("Show what would be done without actually doing it.");
54         getopt.add_option('s', "silent",     silent,        GetOpt::NO_ARG).set_help("Don't print any messages other than errors.");
55         getopt.add_option('t', "build-type", build_type,    GetOpt::REQUIRED_ARG).set_help("Set build type.", "TYPE");
56         getopt.add_option('v', "verbose",    verbose,       GetOpt::NO_ARG).set_help("Print more information about what's going on.");
57         getopt.add_option('x', "no-externals",no_externals, GetOpt::NO_ARG).set_help("Do not load external source packages.");
58         getopt.add_option('A', "conf-all",   conf_all,      GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
59         getopt.add_option('B', "build-all",  build_all,     GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
60         getopt.add_option('C', "chdir",      work_dir,      GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
61         getopt.add_option('P', "progress",   show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
62         getopt.add_option('W', "what-if",    what_if,       GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
63         getopt.add_option(     "arch",       arch,          GetOpt::REQUIRED_ARG).set_help("Build for architecture ARCH.", "ARCH");
64         getopt.add_option(     "conf-only",  conf_only,     GetOpt::NO_ARG).set_help("Stop after configuring packages.");
65         getopt.add_option(     "full-paths", full_paths,    GetOpt::NO_ARG).set_help("Output full paths in analysis.");
66         getopt.add_option(     "max-depth",  max_depth,     GetOpt::REQUIRED_ARG).set_help("Show up to NUM levels in analysis.", "NUM");
67         getopt.add_option(     "prefix",     prefix,        GetOpt::REQUIRED_ARG).set_help("Install things to DIR.", "DIR");
68         getopt.add_option(     "tempdir",    tempdir,       GetOpt::REQUIRED_ARG).set_help("Store temporary files in DIR.", "DIR");
69         getopt.add_argument("target", cmdline_targets, GetOpt::OPTIONAL_ARG).set_help("Target(s) to build");
70         getopt(argc, argv);
71
72         if(help)
73         {
74                 helpmsg = "Usage:\n  ";
75                 helpmsg += getopt.generate_usage(argv[0], true);
76                 helpmsg += "\n\n";
77                 helpmsg += getopt.generate_help();
78         }
79
80         if(silent)
81                 --verbose;
82         if(verbose>=1)
83         {
84                 logger.enable_channel("summary");
85                 logger.enable_channel("tasks");
86         }
87         if(verbose>=2)
88         {
89                 logger.enable_channel("environment");
90                 logger.enable_channel("packages");
91                 logger.enable_channel("commands");
92         }
93         if(verbose>=3)
94         {
95                 logger.enable_channel("files");
96                 logger.enable_channel("auxcommands");
97         }
98         for(const string &c: log_channels)
99                 for(const string &p: split(c, ','))
100                         logger.enable_channel(p);
101         builder.set_logger(&logger);
102
103         if(!analyze_mode.empty())
104         {
105                 analyzer = new Analyzer(builder);
106
107                 if(analyze_mode=="deps")
108                         analyzer->set_mode(Analyzer::DEPS);
109                 else if(analyze_mode=="alldeps")
110                         analyzer->set_mode(Analyzer::ALLDEPS);
111                 else if(analyze_mode=="rebuild")
112                         analyzer->set_mode(Analyzer::REBUILD);
113                 else if(analyze_mode=="rdeps")
114                         analyzer->set_mode(Analyzer::RDEPS);
115                 else
116                         throw usage_error("Invalid analyze mode");
117
118                 analyzer->set_max_depth(max_depth);
119                 analyzer->set_full_paths(full_paths);
120         }
121         else if(!clean && !create_makefile)
122                 build = true;
123
124         for(auto i=cmdline_targets.begin(); i!=cmdline_targets.end(); )
125         {
126                 string::size_type equal = i->find('=');
127                 if(equal!=string::npos)
128                 {
129                         cmdline_options.insert({ i->substr(0, equal), i->substr(equal+1) });
130                         cmdline_targets.erase(i++);
131                 }
132                 else
133                         ++i;
134         }
135
136         if(!work_dir.empty())
137                 FS::chdir(work_dir);
138
139         cwd = FS::getcwd();
140
141         PackageManager &package_manager = builder.get_package_manager();
142
143         package_manager.append_package_path(cwd);
144         package_manager.append_package_path(cwd/"..");
145         package_manager.append_binary_package_path(FS::get_sys_data_dir()/"packages");
146
147         package_manager.set_no_externals(no_externals);
148
149         builder.set_architecture(tolower(arch));
150
151         list<FS::Path> start_files;
152         start_files.push_back(FS::get_sys_data_dir()/"builderrc");
153         start_files.push_back(FS::get_user_data_dir()/"rc");
154         for(const FS::Path &f: start_files)
155                 if(FS::exists(f))
156                         builder.load_build_file(f);
157
158         if(!prefix.empty())
159                 builder.set_prefix(cwd/prefix);
160
161         if(!tempdir.empty())
162                 builder.set_temp_directory(tempdir);
163
164         if(!build_type.empty())
165                 builder.set_build_type(build_type);
166
167         builder.add_default_tools();
168
169         const Toolchain &toolchain = builder.get_toolchain();
170         for(auto i=cmdline_options.begin(); i!=cmdline_options.end(); )
171         {
172                 if(toolchain.has_tool(i->first))
173                 {
174                         toolchain.get_tool(i->first).set_command(i->second);
175                         cmdline_options.erase(i++);
176                 }
177                 else
178                         ++i;
179         }
180 }
181
182 BuilderCLI::~BuilderCLI()
183 {
184         delete analyzer;
185 }
186
187 int BuilderCLI::main()
188 {
189         FS::Path main_file = cwd/build_file;
190         if(FS::exists(main_file))
191         {
192                 builder.load_build_file(main_file, &cmdline_options, conf_all);
193                 if(!dry_run && !cmdline_options.empty())
194                         builder.save_caches();
195         }
196         else if(!help)
197         {
198                 IO::print(IO::cerr, "The file %s does not exist.\n", main_file);
199                 return 1;
200         }
201
202         if(help)
203         {
204                 IO::print("Builder 1.0\n"
205                         "Copyright © 2006-2013  Mikkosoft Productions, Mikko Rasa\n"
206                         "Licensed under the GPL\n\n"
207                         "%s", helpmsg);
208                 package_help();
209                 return 0;
210         }
211
212         if(!prepare_build())
213                 return 1;
214
215         if(conf_only)
216                 return 0;
217
218         const Architecture &native_arch = builder.get_native_arch();
219         const Architecture &current_arch = builder.get_current_arch();
220         logger.log("environment", format("Building on %s, for %s%s", native_arch.get_name(),
221                 current_arch.get_name(), (current_arch.is_native() ? " (native)" : "")));
222         logger.log("environment", format("Prefix is %s", builder.get_prefix()));
223         const FS::Path &tempdir = builder.get_temp_directory();
224         if(tempdir.is_absolute())
225                 logger.log("environment", format("Temporary directory is %s", tempdir));
226         else
227                 logger.log("environment", format("Using per-package temporary directory %s", tempdir));
228         const BuildType &build_type = builder.get_build_type();
229         logger.log("environment", format("Build type is %s", build_type.get_name()));
230
231         BuildGraph &build_graph = builder.get_build_graph();
232         PackageManager &package_manager = builder.get_package_manager();
233         list<string> package_details;
234         for(const auto &kvp: package_manager.get_packages())
235         {
236                 if(!kvp.second->is_prepared())
237                         continue;
238
239                 string line = kvp.second->get_name();
240                 if(dynamic_cast<SourcePackage *>(kvp.second))
241                 {
242                         line += '*';
243
244                         unsigned count = 0;
245                         unsigned to_be_built = 0;
246                         for(const auto &kvp2: build_graph.get_targets())
247                                 if(kvp2.second->get_package()==kvp.second)
248                                 {
249                                         ++count;
250                                         if(kvp2.second->needs_rebuild())
251                                                 ++to_be_built;
252                                 }
253                         if(count)
254                         {
255                                 line += format(" (%d targets", count);
256                                 if(to_be_built)
257                                         line += format(", %d to be built", to_be_built);
258                                 line += ')';
259                         }
260                 }
261
262                 package_details.push_back(line);
263         }
264
265         logger.log("summary", format("%d active packages, %d targets", package_details.size(), build_graph.get_targets().size()));
266         for(const string &d: package_details)
267                 logger.log("packages", d);
268
269         if(analyzer)
270                 analyzer->analyze();
271
272         if(build_graph.get_goals().is_broken())
273         {
274                 list<string> problems = builder.collect_problems();
275                 IO::print(IO::cerr, "The following problems were detected:\n");
276                 for(const string &p: problems)
277                         IO::print(IO::cerr, "  %s\n", p);
278                 if(!analyzer)
279                         IO::print(IO::cerr, "Please fix them and try again.\n");
280                 return 1;
281         }
282
283         if(clean)
284                 exit_code = builder.clean(clean>=2, dry_run);
285         if(build)
286                 exit_code = builder.build(jobs, dry_run, show_progress);
287
288         if(!dry_run)
289                 builder.save_caches();
290
291         return exit_code;
292 }
293
294 bool BuilderCLI::prepare_build()
295 {
296         /* XXX This is ugly; using the Builder class should not be this convoluted.
297         But the command line targets and what ifs need to be set at certain points
298         during preparation. */
299         BuildGraph &build_graph = builder.get_build_graph();
300         PackageManager &package_manager = builder.get_package_manager();
301
302         package_manager.get_main_package().prepare();
303
304         // Add targets from command line as goals
305         for(const string &t: cmdline_targets)
306         {
307                 Target *tgt = resolve_target(t);
308                 if(!tgt)
309                 {
310                         IO::print("I don't know anything about %s\n", t);
311                         return false;
312                 }
313
314                 build_graph.add_goal(*tgt);
315         }
316
317         build_graph.prepare();
318
319         // Apply what-ifs
320         for(const string &w: what_if)
321         {
322                 FileTarget *tgt = dynamic_cast<FileTarget *>(resolve_target(w));
323                 if(!tgt)
324                 {
325                         IO::print(IO::cerr, "Unknown what-if target %s\n", w);
326                         return false;
327                 }
328                 tgt->touch();
329         }
330
331         if(build_all)
332                 build_graph.force_full_rebuild();
333
334         if(!dry_run)
335                 package_manager.save_all_caches();
336
337         return true;
338 }
339
340 Target *BuilderCLI::resolve_target(const string &name)
341 {
342         Target *tgt = builder.get_build_graph().get_target(name);
343         if(!tgt)
344                 tgt = builder.get_vfs().get_target(cwd/name);
345         return tgt;
346 }
347
348 void BuilderCLI::package_help()
349 {
350         PackageManager &package_manager = builder.get_package_manager();
351         if(package_manager.get_packages().empty())
352                 return;
353
354         SourcePackage &main_pkg = dynamic_cast<SourcePackage &>(package_manager.get_main_package());
355         const Config &config = main_pkg.get_config();
356         const auto &options = config.get_options();
357         const Package::Requirements &requires = main_pkg.get_required_packages();
358
359         if(!requires.empty() || !options.empty())
360                 IO::print("\nHelp for package %s:\n", main_pkg.get_name());
361
362         if(!requires.empty())
363         {
364                 IO::print("\nRequired packages:\n  ");
365                 for(auto i=requires.begin(); i!=requires.end(); ++i)
366                 {
367                         if(i!=requires.begin())
368                                 IO::print(", ");
369                         IO::print((*i)->get_name());
370                 }
371                 IO::print("\n");
372         }
373
374         if(!options.empty())
375         {
376                 IO::print("\nPackage configuration:\n");
377                 for(const auto &kvp: options)
378                 {
379                         const Config::Option &opt = kvp.second;
380                         string line = format("  %s: %s (%s)", opt.name, opt.description, opt.value);
381                         if(!opt.choices.empty())
382                         {
383                                 line += " {";
384                                 line += join(opt.choices.begin(), opt.choices.end(), " ");
385                                 line += '}';
386                         }
387                         else if(opt.value!=opt.default_value)
388                                 line += format(" [%s]", opt.default_value);
389                         IO::print("%s\n", line);
390                 }
391         }
392 }