]> git.tdb.fi Git - builder.git/blobdiff - source/builder.cpp
Change arch and prefix to global options
[builder.git] / source / builder.cpp
index 05ecf877c7f47265131491fa50f0e00189015c1d..aabfc00f3908213795ad2fd2a73fb67e6b4dbbb1 100644 (file)
-#include <fstream>
-#include <msp/strutils.h>
-#include <msp/parser/parser.h>
+/* $Id$
+
+This file is part of builder
+Copyright © 2006-2007 Mikko Rasa, Mikkosoft Productions
+Distributed under the LGPL
+*/
+
+#include <iostream>
+#include <set>
+#include <msp/core/except.h>
+#include <msp/core/getopt.h>
+#include <msp/datafile/parser.h>
+#include <msp/io/buffered.h>
+#include <msp/io/except.h>
+#include <msp/io/file.h>
 #include <msp/path/utils.h>
+#include <msp/strings/formatter.h>
+#include <msp/strings/regex.h>
+#include <msp/strings/utils.h>
 #include <msp/time/units.h>
+#include <msp/time/utils.h>
 #include "action.h"
+#include "analyzer.h"
+#include "binarypackage.h"
 #include "builder.h"
-#include "executable.h"
 #include "header.h"
+#include "install.h"
 #include "misc.h"
-#include "objectfile.h"
 #include "package.h"
+#include "pkgconfig.h"
+#include "sharedlibrary.h"
+#include "sourcepackage.h"
+#include "systemlibrary.h"
+#include "tarball.h"
+#include "unlink.h"
 #include "virtualtarget.h"
 
 using namespace std;
 using namespace Msp;
 
 Builder::Builder(int argc, char **argv):
+       main_pkg(0),
+       analyzer(0),
+       build(false),
+       clean(0),
+       dry_run(false),
+       help(false),
        verbose(1),
-       cwd(Path::getcwd())
+       show_progress(false),
+       build_file("Build"),
+       jobs(1),
+       conf_all(false),
+       conf_only(false),
+       build_all(false),
+       create_makefile(false),
+       current_arch("native")
 {
-       for(int i=1; i<argc; ++i)
+       string   analyze_mode;
+       string   work_dir;
+       bool     full_paths=false;
+       unsigned max_depth=5;
+
+       GetOpt getopt;
+       getopt.add_option('a', "analyze",    analyze_mode, GetOpt::REQUIRED_ARG);
+       getopt.add_option('b', "build",      build,        GetOpt::NO_ARG);
+       getopt.add_option('c', "clean",      clean,        GetOpt::NO_ARG);
+       getopt.add_option('f', "file",       build_file,   GetOpt::REQUIRED_ARG);
+       getopt.add_option('h', "help",       help,         GetOpt::NO_ARG);
+       getopt.add_option('j', "jobs",       jobs,         GetOpt::REQUIRED_ARG);
+       getopt.add_option('n', "dry-run",    dry_run,      GetOpt::NO_ARG);
+       getopt.add_option('v', "verbose",    verbose,      GetOpt::NO_ARG);
+       getopt.add_option('A', "conf-all",   conf_all,     GetOpt::NO_ARG);
+       getopt.add_option('B', "build-all",  build_all,    GetOpt::NO_ARG);
+       getopt.add_option('C', "chdir",      work_dir,     GetOpt::REQUIRED_ARG);
+       getopt.add_option('P', "progress",   show_progress, GetOpt::NO_ARG);
+       getopt.add_option('W', "what-if",    what_if,      GetOpt::REQUIRED_ARG);
+       getopt.add_option(     "arch",       current_arch, GetOpt::REQUIRED_ARG);
+       getopt.add_option(     "conf-only",  conf_only,    GetOpt::NO_ARG);
+       getopt.add_option(     "full-paths", full_paths,   GetOpt::NO_ARG);
+       //getopt.add_option(     "makefile",   create_makefile, GetOpt::NO_ARG);
+       getopt.add_option(     "max-depth",  max_depth,    GetOpt::REQUIRED_ARG);
+       getopt.add_option(     "prefix",     prefix,       GetOpt::REQUIRED_ARG);
+       getopt(argc, argv);
+
+       if(!analyze_mode.empty())
        {
-               string v(argv[i]);
-               unsigned equal=v.find('=');
+               analyzer=new Analyzer(*this);
+
+               if(analyze_mode=="deps")
+                       analyzer->set_mode(Analyzer::DEPS);
+               else if(analyze_mode=="alldeps")
+                       analyzer->set_mode(Analyzer::ALLDEPS);
+               else if(analyze_mode=="rebuild")
+                       analyzer->set_mode(Analyzer::REBUILD);
+               else if(analyze_mode=="rdeps")
+                       analyzer->set_mode(Analyzer::RDEPS);
+               else
+                       throw UsageError("Invalid analyze mode");
+
+               analyzer->set_max_depth(max_depth);
+               analyzer->set_full_paths(full_paths);
+       }
+       else if(!clean && !create_makefile)
+               build=true;
+
+       const vector<string> &args=getopt.get_args();
+       for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
+       {
+               unsigned equal=i->find('=');
                if(equal!=string::npos)
-                       cmdline_options.insert(RawOptionMap::value_type(v.substr(0, equal), v.substr(equal+1)));
+                       cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
                else
-                       cmdline_targets.push_back(argv[i]);
+                       cmdline_targets.push_back(*i);
        }
 
        if(cmdline_targets.empty())
                cmdline_targets.push_back("default");
+
+       if(!work_dir.empty())
+               chdir(work_dir.c_str());
+
+       cwd=getcwd();
+
+       Architecture &native_arch=archs.insert(ArchMap::value_type("native", Architecture(*this, "native"))).first->second;
+       native_arch.set_tool("CC",  "gcc");
+       native_arch.set_tool("CXX", "g++");
+       native_arch.set_tool("LD",  "gcc");
+       native_arch.set_tool("LXX", "g++");
+       native_arch.set_tool("AR",  "ar");
+
+       load_build_file((get_home_dir()/".builderrc").str());
+
+       if(prefix.empty())
+       {
+               if(current_arch=="native")
+                       prefix=(get_home_dir()/"local").str();
+               else
+                       prefix=(get_home_dir()/"local"/current_arch).str();
+       }
 }
 
-Package *Builder::get_package(const string &n)
+/**
+Gets a package by name, possibly creating it.
+
+@param   name  Package name
+
+@return  Pointer to the package, or 0 if the package could not be located
+*/
+Package *Builder::get_package(const string &name)
 {
-       PackageMap::iterator i=packages.find(n);
+       PackageMap::iterator i=packages.find(format("%s/%s", name, current_arch));
+       if(i==packages.end())
+               i=packages.find(name);
        if(i!=packages.end())
                return i->second;
 
+       // Try to get source directory with pkgconfig
        list<string> argv;
        argv.push_back("pkg-config");
        argv.push_back("--variable=source");
-       argv.push_back(n);
+       argv.push_back(name);
+       if(verbose>=4)
+               cout<<"Running "<<join(argv.begin(), argv.end())<<'\n';
        string srcdir=strip(run_command(argv));
-       cout<<srcdir;
-       
-       list<Path::Path> dirs;
+
+       PathList dirs;
        if(!srcdir.empty())
                dirs.push_back(srcdir);
 
-       string dirname=n;
-       if(dirname.compare(0, 3, "msp"))
-               dirname.erase(0, 3);
-       dirs.push_back(cwd/dirname);
-       dirs.push_back(cwd/".."/dirname);
+       // Make some other guesses about the source directory
+       dirs.push_back(cwd/name);
+       dirs.push_back(cwd/".."/name);
+       if(!name.compare(0, 3, "msp"))
+       {
+               dirs.push_back(cwd/name.substr(3));
+               dirs.push_back(cwd/".."/name.substr(3));
+       }
 
-       for(list<Path::Path>::iterator j=dirs.begin(); j!=dirs.end(); ++j)
+       // Go through the candidate directories and look for a Build file
+       for(PathList::iterator j=dirs.begin(); j!=dirs.end(); ++j)
                if(!load_build_file(*j/"Build"))
                {
-                       i=packages.find(n);
+                       i=packages.find(name);
                        if(i!=packages.end())
                                return i->second;
-                       return 0;
+                       break;
                }
-       
-       Package *pkg=Package::create(*this, n);
-       packages.insert(PackageMap::value_type(n, pkg));
-       new_pkgs.push_back(pkg);
+
+       // Package source not found - create a binary package
+       Package *pkg=BinaryPackage::from_pkgconfig(*this, name);
+
+       packages.insert(PackageMap::value_type(name, pkg));
+
+       if(!pkg)
+               problem(name, "not found");
 
        return pkg;
 }
 
-Target *Builder::get_target(const string &n)
+/**
+Returns the target with the given name, or 0 if no such target exists.
+*/
+Target *Builder::get_target(const string &n) const
 {
-       TargetMap::iterator i=targets.find(n);
+       TargetMap::const_iterator i=targets.find(n);
        if(i!=targets.end())
                return i->second;
        return 0;
 }
 
+/**
+Tries to locate a header included from a given location and with a given include
+path.  Considers known targets as well as existing files.  If a matching target
+is not found but a file exists, a new SystemHeader target will be created and
+returned.
+*/
 Target *Builder::get_header(const string &include, const string &from, const list<string> &path)
 {
-       string id=from+":"+include;
+       string hash(8, 0);
+       update_hash(hash, from);
+       for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
+               update_hash(hash, *i);
+
+       string id=hash+include;
        TargetMap::iterator i=includes.find(id);
        if(i!=includes.end())
                return i->second;
 
+       static string cxx_ver;
+       if(cxx_ver.empty())
+       {
+               StringList argv;
+               argv.push_back(get_current_arch().get_tool("CXX"));
+               argv.push_back("--version");
+               cxx_ver=Regex("[0-9]\\.[0-9.]+").match(run_command(argv))[0].str;
+               while(!cxx_ver.empty() && !exists(Path("/usr/include/c++")/cxx_ver))
+               {
+                       unsigned dot=cxx_ver.rfind('.');
+                       if(dot==string::npos)
+                               break;
+                       cxx_ver.erase(dot);
+               }
+               if(verbose>=5)
+                       cout<<"C++ version is "<<cxx_ver<<'\n';
+       }
+
        string fn=include.substr(1);
-       Target *tgt;
-       if(include[0]=='"' && (tgt=check_header(Path::Path(from)/fn)))
-               return tgt;
-       if((tgt=check_header(Path::Path("/usr/include")/fn)))
-               return tgt;
-       if((tgt=check_header(Path::Path("/usr/include/c++/4.1.2")/fn)))
-               return tgt;
-       for(list<string>::const_iterator j=path.begin(); j!=path.end(); ++j)
-               if((tgt=check_header(Path::Path(*j)/fn)))
-                       return tgt;
-       
-       return 0;
+       if(verbose>=5)
+               cout<<"Looking for include "<<fn<<" with path "<<join(path.begin(), path.end())<<'\n';
+
+       StringList syspath;
+       if(current_arch=="native")
+               syspath.push_back("/usr/include");
+       else
+               syspath.push_back("/usr/"+get_architecture(current_arch).get_prefix()+"/include");
+       syspath.push_back((Path("/usr/include/c++/")/cxx_ver/fn).str());
+
+       Target *tgt=0;
+       if(include[0]=='\"')
+               tgt=get_header(Path(from)/fn);
+       for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
+               tgt=get_header(cwd/ *j/fn);
+       for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
+               tgt=get_header(Path(*j)/fn);
+
+       includes.insert(TargetMap::value_type(id, tgt));
+
+       return tgt;
+}
+
+/**
+Tries to locate a library with the given library path.  Considers known targets
+as well as existing files.  If a matching target is not found but a file exists,
+a new SystemLibrary target will be created and returned.
+
+@param   lib   Name of the library to get (without "lib" prefix or extension)
+@param   path  List of paths to search for the library
+@param   mode  Shared / static mode
+
+@return  Some kind of library target, if a match was found
+*/
+Target *Builder::get_library(const string &lib, const list<string> &path, LibMode mode)
+{
+       string hash(8, 0);
+       for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
+               update_hash(hash, *i);
+
+       //XXX Incorporate mode into id
+       string id=hash+lib;
+       TargetMap::iterator i=libraries.find(id);
+       if(i!=libraries.end())
+               return i->second;
+
+       StringList syspath;
+       if(current_arch=="native")
+       {
+               syspath.push_back("/lib");
+               syspath.push_back("/usr/lib");
+       }
+       else
+               syspath.push_back("/usr/"+get_current_arch().get_prefix()+"/lib");
+
+       if(verbose>=5)
+               cout<<"Looking for library "<<lib<<" with path "<<join(path.begin(), path.end())<<'\n';
+
+       Target *tgt=0;
+       for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
+               tgt=get_library(lib, cwd/ *j, mode);
+       for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
+               tgt=get_library(lib, *j, mode);
+
+       libraries.insert(TargetMap::value_type(id, tgt));
+
+       return tgt;
+}
+
+const Architecture &Builder::get_architecture(const string &arch) const
+{
+       ArchMap::const_iterator i=archs.find(arch);
+       if(i==archs.end())
+               throw KeyError("Unknown architecture", arch);
+
+       return i->second;
+}
+
+const Architecture &Builder::get_current_arch() const
+{
+       return get_architecture(current_arch);
+}
+
+void Builder::apply_profile_template(Config &config, const string &pt) const
+{
+       vector<string> parts=split(pt, '-');
+
+       for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
+       {
+               ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
+               if(j==profile_tmpl.end())
+                       continue;
+
+               config.update(j->second);
+       }
+}
+
+void Builder::problem(const string &p, const string &d)
+{
+       problems.push_back(Problem(p, d));
+}
+
+/**
+Adds a target to both the target map and the new target queue.  Called from
+Target constructor.
+*/
+void Builder::add_target(Target *t)
+{
+       targets.insert(TargetMap::value_type(t->get_name(), t));
+       new_tgts.push_back(t);
 }
 
 int Builder::main()
 {
-       if(load_build_file("Build"))
+       if(load_build_file(cwd/build_file))
        {
                cerr<<"No build info here.\n";
                return 1;
        }
 
-       default_pkg=packages.begin()->second;
+       main_pkg->configure(cmdline_options, conf_all?2:1);
 
-       while(!new_pkgs.empty())
+       if(help)
        {
-               Package *pkg=new_pkgs.front();
-               new_pkgs.erase(new_pkgs.begin());
-               pkg->resolve_refs();
+               usage(0, "builder", false);
+               cout<<'\n';
+               package_help();
+               return 0;
        }
 
-       std::list<std::string> missing;
-       for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
+       if(!conf_only && create_targets())
+               return 1;
+
+       PackageList all_reqs=main_pkg->collect_requires();
+
+       if(conf_only)
+               return 0;
+
+       cout<<all_reqs.size()<<" active packages, "<<targets.size()<<" targets\n";
+       if(verbose>=2)
        {
-               const list<PackageRef> &requires=i->second->get_requires();
-               for(list<PackageRef>::const_iterator j=requires.begin(); j!=requires.end(); ++j)
-                       if(!j->get_package())
-                               missing.push_back(j->get_name());
+               for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
+               {
+                       cout<<' '<<(*i)->get_name();
+                       if(dynamic_cast<SourcePackage *>(*i))
+                               cout<<'*';
+                       unsigned count=0;
+                       unsigned ood_count=0;
+                       for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
+                               if(j->second->get_package()==*i)
+                               {
+                                       ++count;
+                                       if(j->second->get_rebuild())
+                                               ++ood_count;
+                               }
+                       if(count)
+                       {
+                               cout<<" ("<<count<<" targets";
+                               if(ood_count)
+                                       cout<<", "<<ood_count<<" out-of-date";
+                               cout<<')';
+                       }
+                       cout<<'\n';
+               }
        }
 
-       if(!missing.empty())
+       if(analyzer)
+               analyzer->analyze();
+
+       if(!problems.empty())
        {
-               missing.sort();
-               missing.unique();
-               cerr<<"The following packages were not found on the system:\n";
-               for(list<string>::iterator i=missing.begin(); i!=missing.end(); ++i)
-                       cerr<<"  "<<*i<<'\n';
-               cerr<<"Please install them and try again.\n";
+               cerr<<"The following problems were detected:\n";
+               for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
+                       cerr<<"  "<<i->package<<": "<<i->descr<<'\n';
+               cerr<<"Please fix them and try again.\n";
+               return 1;
        }
 
-       default_pkg->create_build_info();
+       //if(create_makefile
+
+       if(clean)
+               exit_code=do_clean();
+       else if(build)
+               exit_code=do_build();
 
-       cout<<"Active packages:";
+       return exit_code;
+}
+
+Builder::~Builder()
+{
        for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
+               delete i->second;
+       for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
+               delete i->second;
+       delete analyzer;
+}
+
+void Builder::usage(const char *reason, const char *argv0, bool brief)
+{
+       if(reason)
+               cerr<<reason<<'\n';
+
+       if(brief)
+               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> ...]";
+       else
        {
-               cout<<' '<<i->second->get_name();
-               if(i->second->get_buildable())
-                       cout<<'*';
+               cerr<<
+                       "Usage: "<<argv0<<" [options] [<target> ...]\n"
+                       "\n"
+                       "Options:\n"
+                       "  -a, --analyze MODE  Perform analysis.  MODE can be deps, alldeps or rebuild.\n"
+                       "  -b, --build         Perform build even if doing analysis.\n"
+                       "  -c, --clean         Clean buildable targets.\n"
+                       "  -f, --file FILE     Read info from FILE instead of Build.\n"
+                       "  -h, --help          Print this message.\n"
+                       "  -j, --jobs NUM      Run NUM commands at once, whenever possible.\n"
+                       "  -n, --dry-run       Don't actually do anything, only show what would be done.\n"
+                       "  -v, --verbose       Print more information about what's going on.\n"
+                       "  -A, --conf-all      Apply configuration to all packages.\n"
+                       "  -B, --build-all     Build all targets unconditionally.\n"
+                       "  -C, --chdir DIR     Change to DIR before doing anything else.\n"
+                       "  -P, --progress      Display progress while building.\n"
+                       "  -W, --what-if FILE  Pretend that FILE has changed.\n"
+                       "  --conf-only         Stop after configuring packages.\n"
+                       "  --full-paths        Output full paths in analysis.\n"
+                       //"  --makefile          Create a makefile for this package.\n"
+                       "  --max-depth NUM     Maximum depth to show in analysis.\n";
        }
-       cout<<'\n';
-       
-       if(create_targets())
-               return 1;
+}
 
-       for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
-               cout<<i->second->get_name()<<' '<<i->second->get_type()<<' '<<i->second->get_rebuild()<<' '<<i->second->get_rebuild_reason()<<'\n';
+/**
+Loads the given build file.
 
-       cout<<"Active targets: "<<targets.size()<<'\n';
+@param   fn  Path to the file
 
-       build();
+@return  0 on success, -1 if the file could not be opened
+*/
+int Builder::load_build_file(const Path &fn)
+{
+       try
+       {
+               IO::File inf(fn.str());
+               IO::Buffered in(inf);
 
-       return exit_code;
-}
+               if(verbose>=3)
+                       cout<<"Reading "<<fn<<'\n';
 
-int Builder::load_build_file(const Path::Path &fn)
-{
-       ifstream in(fn.str().c_str());
-       if(!in)
+               DataFile::Parser parser(in, fn.str());
+               Loader loader(*this, fn.subpath(0, fn.size()-1));
+               loader.load(parser);
+       }
+       catch(const IO::FileNotFound &)
+       {
                return -1;
-
-       Parser::Parser parser(in, fn.str());
-       Loader loader(*this, cwd/fn.subpath(0, fn.size()-1));
-       loader.load(parser);
+       }
 
        return 0;
 }
 
+/**
+Creates targets for all packages and prepares them for building.
+
+@return  0 if everything went ok, -1 if something bad happened and a build
+         shouldn't be attempted
+*/
 int Builder::create_targets()
 {
        Target *world=new VirtualTarget(*this, "world");
-       add_target(world);
 
        Target *def_tgt=new VirtualTarget(*this, "default");
-       add_target(def_tgt);
        world->add_depend(def_tgt);
 
-       for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
+       Target *install=new VirtualTarget(*this, "install");
+       world->add_depend(install);
+
+       Target *tarballs=new VirtualTarget(*this, "tarballs");
+       world->add_depend(tarballs);
+
+       PackageList all_reqs=main_pkg->collect_requires();
+       for(PackageList::iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
        {
-               if(!i->second->get_buildable())
+               SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
+               if(!spkg)
                        continue;
 
-               const ComponentList &components=i->second->get_components();
+               const ComponentList &components=spkg->get_components();
                for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
-               {
-                       Path::Path base=i->second->get_source()/j->get_source();
-                       list<string> files=list_files(base);
+                       j->create_targets();
 
-                       list<ObjectFile *> objs;
-                       for(list<string>::iterator k=files.begin(); k!=files.end(); ++k)
-                       {
-                               Path::Path fn=base/ *k;
-                               string ext=Path::splitext(*k).ext;
-                               if(ext==".cpp" || ext==".c")
-                               {
-                                       SourceFile *src=new SourceFile(*this, &*j, fn.str());
-                                       add_target(src);
-                                       
-                                       ObjectFile *obj=new ObjectFile(*this, *j, *src);
-                                       add_target(obj);
-                                       objs.push_back(obj);
-                               }
-                               else if(ext==".h")
-                                       add_target(new Header(*this, &*j, fn.str()));
-                       }
-
-                       Executable *exe=new Executable(*this, *j, objs);
-                       add_target(exe);
-                       if(i->second==default_pkg)
-                               def_tgt->add_depend(exe);
-                       else
-                               world->add_depend(exe);
+               if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
+               {
+                       PkgConfig *pc=new PkgConfig(*this, *spkg);
+                       install->add_depend(new Install(*this, *spkg, *pc));
                }
+
+               tarballs->add_depend(new TarBall(*this, *spkg));
        }
 
+       // Find dependencies until no new targets are created
        while(!new_tgts.empty())
        {
                Target *tgt=new_tgts.front();
                new_tgts.erase(new_tgts.begin());
                tgt->find_depends();
+               if(!tgt->get_depends_ready())
+                       new_tgts.push_back(tgt);
        }
 
+       // Apply what-ifs
+       for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
+       {
+               Target *tgt=get_target((cwd/ *i).str());
+               if(!tgt)
+               {
+                       cerr<<"Unknown what-if target "<<*i<<'\n';
+                       return -1;
+               }
+               tgt->touch();
+       }
+
+       // Make the cmdline target depend on all targets mentioned on the command line
        Target *cmdline=new VirtualTarget(*this, "cmdline");
-       add_target(cmdline);
-       world->add_depend(cmdline);
+       bool build_world=false;
        for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
        {
                Target *tgt=get_target(*i);
@@ -240,88 +576,295 @@ int Builder::create_targets()
                if(!tgt)
                {
                        cerr<<"I don't know anything about "<<*i<<'\n';
-                       return 1;
+                       return -1;
                }
+               if(tgt==world)
+                       build_world=true;
                cmdline->add_depend(tgt);
        }
 
-       world->prepare();
+       /* If world is to be built, prepare cmdline.  If not, add cmdline to world
+          and prepare world.  I don't really like this, but it keeps the graph
+          acyclic. */
+       if(build_world)
+               cmdline->prepare();
+       else
+       {
+               world->add_depend(cmdline);
+               world->prepare();
+       }
+
+       for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
+               if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
+                       spkg->get_deps_cache().save();
 
        return 0;
 }
 
-Target *Builder::check_header(const Msp::Path::Path &fn)
+/**
+Check if a header exists, either as a target or a file.  Either an existing
+target or a new SystemHeader target will be returned.
+*/
+Target *Builder::get_header(const Msp::Path &fn)
 {
        Target *tgt=get_target(fn.str());
        if(tgt) return tgt;
 
-       if(Path::exists(fn))
+       if(exists(fn))
        {
-               add_target(tgt=new SystemHeader(*this, fn.str()));
+               tgt=new SystemHeader(*this, fn.str());
                return tgt;
        }
        return 0;
 }
 
-void Builder::add_target(Target *t)
+Target *Builder::get_library(const string &lib, const Path &path, LibMode mode)
 {
-       targets.insert(TargetMap::value_type(t->get_name(), t));
-       new_tgts.push_back(t);
+       // Populate a list of candidate filenames
+       StringList candidates;
+
+       if(mode!=ALL_STATIC)
+       {
+               if(current_arch=="win32")
+               {
+                       candidates.push_back("lib"+lib+".dll");
+                       candidates.push_back(lib+".dll");
+               }
+               else
+                       candidates.push_back("lib"+lib+".so");
+       }
+
+       /* Static libraries are always considered, since sometimes shared versions
+       may not be available */
+       candidates.push_back("lib"+lib+".a");
+       if(current_arch=="win32")
+               candidates.push_back("lib"+lib+".dll.a");
+
+       for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
+       {
+               string full=(path/ *i).str();
+               Target *tgt=get_target(full);
+
+               if(tgt)
+               {
+                       Target *real_tgt=tgt;
+                       if(dynamic_cast<Install *>(tgt))
+                               real_tgt=real_tgt->get_depends().front();
+
+                       /* Ignore dynamic libraries from local packages unless library mode is
+                       DYNAMIC */
+                       if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
+                               continue;
+                       else if(tgt)
+                               return tgt;
+               }
+               else if(exists(full))
+               {
+                       tgt=new SystemLibrary(*this, full);
+                       return tgt;
+               }
+       }
+
+       return 0;
+}
+
+/**
+Updates a hash with a string.  This is used from get_header and get_library.
+*/
+void Builder::update_hash(string &hash, const string &value)
+{
+       for(unsigned i=0; i<value.size(); ++i)
+               hash[i%hash.size()]^=value[i];
 }
 
-int Builder::build()
+/**
+This function supervises the build process, starting new actions when slots
+become available.
+*/
+int Builder::do_build()
 {
        Target *cmdline=get_target("cmdline");
-       list<Action *> actions;
+
+       unsigned total=cmdline->count_rebuild();
+       if(!total)
+       {
+               cout<<"Already up to date\n";
+               return 0;
+       }
+       cout<<"Will build "<<total<<" target(s)\n";
+
+       vector<Action *> actions;
+
+       unsigned count=0;
+
        bool fail=false;
+       bool finish=false;
 
-       while(cmdline->get_rebuild() && !fail)
+       while(!finish)
        {
-               if(actions.empty() && !fail)
+               if(actions.size()<jobs && !fail)
                {
                        Target *tgt=cmdline->get_buildable_target();
                        if(tgt)
                        {
-                               cout<<"Build "<<tgt->get_name()<<'\n';
                                Action *action=tgt->build();
                                if(action)
                                        actions.push_back(action);
+
+                               if(show_progress)
+                               {
+                                       cout<<count<<" of "<<total<<" targets built\033[1G";
+                                       cout.flush();
+                               }
                        }
+                       else if(actions.empty())
+                               finish=true;
                }
                else
-                       sleep(10*Time::msec);
+                       Time::sleep(10*Time::msec);
 
-               for(list<Action *>::iterator i=actions.begin(); i!=actions.end();)
+               for(unsigned i=0; i<actions.size();)
                {
-                       int status=(*i)->check();
+                       int status=actions[i]->check();
                        if(status>=0)
                        {
-                               delete *i;
-                               i=actions.erase(i);
+                               ++count;
+
+                               delete actions[i];
+                               actions.erase(actions.begin()+i);
                                if(status>0)
                                        fail=true;
+                               if(actions.empty() && fail)
+                                       finish=true;
                        }
+                       else
+                               ++i;
                }
        }
 
+       if(show_progress)
+               cout<<"\033[K";
+       if(fail)
+               cout<<"Build failed\n";
+       else if(show_progress)
+               cout<<"Build complete\n";
+
+       return fail?1:0;
+}
+
+/**
+Cleans buildable targets.  If clean is 1, cleans only this package.  If
+clean is 2 or greater, cleans all buildable packages.
+*/
+int Builder::do_clean()
+{
+       // Cleaning doesn't care about ordering, so a simpler method can be used
+
+       set<Target *> clean_tgts;
+       TargetList queue;
+       queue.push_back(get_target("cmdline"));
+
+       while(!queue.empty())
+       {
+               Target *tgt=queue.front();
+               queue.erase(queue.begin());
+
+               if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
+                       clean_tgts.insert(tgt);
+
+               const TargetList &deps=tgt->get_depends();
+               for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
+                       if(!clean_tgts.count(*i))
+                               queue.push_back(*i);
+       }
+
+       for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
+       {
+               Action *action=new Unlink(*this, **i);
+               while(action->check()<0);
+               delete action;
+       }
+
        return 0;
 }
 
+/**
+Prints out information about the default package.
+*/
+void Builder::package_help()
+{
+       const Config &config=main_pkg->get_config();
+       const Config::OptionMap &options=config.get_options();
+
+       cout<<"Required packages:\n  ";
+       const PackageList &requires=main_pkg->get_requires();
+       for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
+       {
+               if(i!=requires.begin())
+                       cout<<", ";
+               cout<<(*i)->get_name();
+       }
+       cout<<"\n\n";
+       cout<<"Package configuration:\n";
+       for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
+       {
+               const Config::Option &opt=i->second;
+               cout<<"  "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
+       }
+}
+
 Application::RegApp<Builder> Builder::reg;
 
-Builder::Loader::Loader(Builder &b, const Path::Path &s):
+
+Builder::Loader::Loader(Builder &b, const Path &s):
        bld(b),
        src(s)
 {
+       add("architecture", &Loader::architecture);
+       add("binary_package", &Loader::binpkg);
+       add("profile", &Loader::profile);
        add("package", &Loader::package);
 }
 
+void Builder::Loader::architecture(const string &n)
+{
+       Architecture arch(bld, n);
+       load_sub(arch);
+       bld.archs.insert(ArchMap::value_type(n, arch));
+}
+
+void Builder::Loader::binpkg(const string &n)
+{
+       BinaryPackage *pkg=new BinaryPackage(bld, n);
+       load_sub(*pkg);
+       bld.packages.insert(PackageMap::value_type(n, pkg));
+}
+
+void Builder::Loader::profile(const string &n)
+{
+       StringMap prf;
+       load_sub<ProfileLoader>(prf);
+       bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
+}
+
 void Builder::Loader::package(const string &n)
 {
-       Package *pkg=new Package(bld, n, src);
+       SourcePackage *pkg=new SourcePackage(bld, n, src);
+       if(!bld.main_pkg)
+               bld.main_pkg=pkg;
+
        load_sub(*pkg);
        bld.packages.insert(PackageMap::value_type(n, pkg));
-       bld.new_pkgs.push_back(pkg);
-       //cout<<"loaded "<<pkg->get_name()<<'\n';
 }
 
+
+Builder::ProfileLoader::ProfileLoader(StringMap &p):
+       profile(p)
+{
+       add("option", &ProfileLoader::option);
+}
+
+void Builder::ProfileLoader::option(const string &o, const string &v)
+{
+       profile.insert(StringMap::value_type(o, v));
+}