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