diff --git a/CMakeLists.txt b/CMakeLists.txt index 5af80d9..27c5642 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,108 +1,107 @@ cmake_minimum_required(VERSION 3.0) project(kdesrc-build) # Needed for the docs, but optional. If not found, we will simply # defer to native CMake handling. find_package(ECM 5.10.0 NO_MODULE QUIET) if (ECM_FOUND) set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH} ${ECM_KDE_MODULE_DIR}) include(KDEInstallDirs) include(KDECMakeSettings) include(FeatureSummary) include(ECMOptionalAddSubdirectory) find_package(KF5 5.10.0 COMPONENTS DocTools) if(KF5_DocTools_FOUND) ecm_optional_add_subdirectory(doc) else() message(WARNING "Found ECM, but not KF5::DocTools; documentation will not be built") endif() else() message(WARNING "Did not find extra-cmake-modules; documentation will not be built and install paths will be guessed based on CMake settings.") # ECM now sets KDE_INSTALL_DATADIR to PREFIX/share, try to match set(KDE_INSTALL_DATADIR "${CMAKE_INSTALL_PREFIX}/share" CACHE PATH "The parent directory where applications can install their data") set(KDE_INSTALL_BINDIR "${CMAKE_INSTALL_PREFIX}/bin" CACHE PATH "The install dir for executables") endif() set(KDESRC_BUILD_INSTALL_MODULES TRUE CACHE BOOL "Controls whether to install the modules that make up the script. Leave enabled unless running straight from source") set(KDESRC_BUILD_MODULE_INSTALL_PREFIX "${KDE_INSTALL_DATADIR}/kdesrc-build/modules" CACHE PATH "Prefix to install the component Perl modules to. (This is only an option to allow for installing to vendor_perl or similar)") if (KDESRC_BUILD_INSTALL_MODULES) message(STATUS "Installing component modules to ${KDESRC_BUILD_MODULE_INSTALL_PREFIX}") install(FILES modules/ksb/Application.pm modules/ksb/BuildContext.pm modules/ksb/BuildException.pm modules/ksb/BuildSystem.pm modules/ksb/Debug.pm modules/ksb/DependencyResolver.pm modules/ksb/FirstRun.pm modules/ksb/IPC.pm modules/ksb/KDEProjectsReader.pm modules/ksb/Module.pm modules/ksb/ModuleResolver.pm modules/ksb/ModuleSet.pm modules/ksb/OptionsBase.pm modules/ksb/OSSupport.pm modules/ksb/PhaseList.pm modules/ksb/RecursiveFH.pm modules/ksb/StatusView.pm modules/ksb/Updater.pm modules/ksb/Util.pm modules/ksb/Version.pm - modules/ksb/l10nSystem.pm DESTINATION ${KDESRC_BUILD_MODULE_INSTALL_PREFIX}/ksb) install(FILES modules/ksb/BuildSystem/Autotools.pm modules/ksb/BuildSystem/CMakeBootstrap.pm modules/ksb/BuildSystem/KDE4.pm modules/ksb/BuildSystem/QMake.pm modules/ksb/BuildSystem/Qt4.pm DESTINATION ${KDESRC_BUILD_MODULE_INSTALL_PREFIX}/ksb/BuildSystem) install(FILES modules/ksb/Module/BranchGroupResolver.pm modules/ksb/Module/KDE.pm DESTINATION ${KDESRC_BUILD_MODULE_INSTALL_PREFIX}/ksb/Module) install(FILES modules/ksb/ModuleSet/KDEProjects.pm modules/ksb/ModuleSet/Null.pm DESTINATION ${KDESRC_BUILD_MODULE_INSTALL_PREFIX}/ksb/ModuleSet) install(FILES modules/ksb/IPC/Null.pm modules/ksb/IPC/Pipe.pm DESTINATION ${KDESRC_BUILD_MODULE_INSTALL_PREFIX}/ksb/IPC) install(FILES modules/ksb/Updater/Bzr.pm modules/ksb/Updater/Git.pm modules/ksb/Updater/KDEProject.pm modules/ksb/Updater/KDEProjectMetadata.pm modules/ksb/Updater/Svn.pm DESTINATION ${KDESRC_BUILD_MODULE_INSTALL_PREFIX}/ksb/Updater) endif() install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/kdesrc-build DESTINATION ${KDE_INSTALL_BINDIR}) install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/kdesrc-build-setup DESTINATION ${KDE_INSTALL_BINDIR}) install(PROGRAMS ${CMAKE_SOURCE_DIR}/sample-kde-env-master.sh ${CMAKE_SOURCE_DIR}/sample-xsession.sh ${CMAKE_SOURCE_DIR}/kf5-applications-build-include ${CMAKE_SOURCE_DIR}/kf5-extragear-build-include ${CMAKE_SOURCE_DIR}/kf5-frameworks-build-include ${CMAKE_SOURCE_DIR}/kf5-kdepim-build-include ${CMAKE_SOURCE_DIR}/kf5-qt5-build-include ${CMAKE_SOURCE_DIR}/kf5-workspace-build-include ${CMAKE_SOURCE_DIR}/dependencies_local_distro.yaml DESTINATION ${KDE_INSTALL_DATADIR}/kdesrc-build) if (ECM_FOUND) feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) endif() diff --git a/doc/index.docbook b/doc/index.docbook index 4fbfe1b..8eabbd9 100644 --- a/doc/index.docbook +++ b/doc/index.docbook @@ -1,4836 +1,4825 @@ Copyright (c) 2005 Carlos Leonhard Woelz Copyright (c) 2009 Burkhard Lück Copyright (c) 2007, 2011 Federico Zenith Copyright (c) 2009-2011 Yuri Chornoivan ... and possibly others. Check the git source repository for specifics. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in COPYING.DOC. The license will be included in the generated documentation as well. --> kdesrc-build"> BSD'> Git'> CMake'> Make'> SSH'> Cron'> Subversion'> Sudo'> URL'> configure-flags'> kdedir'> qtdir'> build-dir'> module-base-path'> override-url'> source-dir'> email-address'> email-on-compile-error'> colorful-output'> tag'> branch'> do-not-compile'> checkout-only'> svn-server'> make-install-prefix'> niceness'> set-env'> libpath'> binpath'> --nice'> --ignore-modules'> --resume-from'> --resume-after'> --reconfigure'> --refresh-build'> ]> &kdesrc-build; Script Manual &Michael.Pyne; &Michael.Pyne.mail; CarlosWoelz carloswoelz@imap-mail.com 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 Michael Pyne 2005 Carlos Woelz &FDLNotice; 2018-01-20 &kdesrc-build; 17.12 &kdesrc-build; is a script which builds and installs &kde; software directly from the &kde; project's source code repositories. KDE kdesdk SVN Subversion git KDE development kdesvn-build kdecvs-build Introduction A brief introduction to &kdesrc-build; What is &kdesrc-build;? &kdesrc-build; is a script to help the &kde; community install &kde; software from its &git; and &subversion; source repositories, and continue to update that software afterwards. It is particularly intended to support those who need to supporting testing and development of &kde; software, including users testing bugfixes and developers working on new features. The &kdesrc-build; script can be configured to maintain a single individual module, a full &plasma; desktop with &kde; application set, or somewhere in between. To get started, see , or continue reading for more detail on how &kdesrc-build; works and what is covered in this documentation. &kdesrc-build; operation <quote>in a nutshell</quote> &kdesrc-build; works by using the tools available to the user at the command-line, using the same interfaces available to the user. When &kdesrc-build; is run, the following sequence is followed: &kdesrc-build; reads in the command line and configuration file, to determine what to build, compile options to use, where to install, &etc; &kdesrc-build; performs a source update for each module. The update continues until all modules have been updated. Modules that fail to update normally do not stop the build – you will be notified at the end which modules did not update. Modules that were successfully updated are built, have their test suite run, and are then installed. To reduce the overall time spent, &kdesrc-build; will by default start building the code as soon as the first module has completed updating, and allow the remaining updates to continue behind the scenes. A very good overview of how &kde; modules are built, including informative diagrams, is provided on an online article discussing &kde;'s &krita; application. This workflow is what &kdesrc-build; automates for all &kde; modules. Documentation Overview This guide is an overview to describe the following aspects of &kdesrc-build; operation: An overview of the steps required to get started. Notable features. The configuration file syntax and options. The command line options. Also documented are the steps which you should perform using other tools (&ie; steps that are not automatically performed by &kdesrc-build;). Getting Started In this chapter, we show how to use the &kdesrc-build; to checkout modules from the &kde; repository and build them. We also provide a basic explanation of the &kde; source code structure and the steps you have to perform before running the script. All topics present in this chapter are covered with even more detail in the Build from Source article, at the &kde; Community Wiki. If you are compiling &kde; for the first time, it is a good idea to read it, or consult it as a reference source. You will find detailed information about packaging tools and requirements, common compilation pitfalls and strategies and information about running your new &kde; installation. Preparing the System to Build &kde; Setup a new user account It is recommended that you use a different user account to build, install, and run your &kde; software from, since less permissions are required, and to avoid interfering with your distribution's packages. If you already have &kde; packages installed, the best choice would be to create a different (dedicated) user to build and run the new &kde;. Leaving your system &kde; untouched also allows you to have an emergency fallback in case a coding mistake causes your latest software build to be unusable. You can do also setup to install to a system-wide directory (⪚ /usr/src/local) if you wish. This document does not cover this installation type, since we assume you know what you are doing. Ensure your system is ready to build &kde; software Before using the &kdesrc-build; script (or any other building strategy) you must install the development tools and libraries needed for &kde;. The nearly complete list of required tools can be found from the &kde; Community Wiki Build Requirements page. Here is a list of some of the things you will need: You will need &cmake;, this software is what &kde; uses to handle build-time configuration of the source code and generation of the specific build commands for your system. The required version will vary depending on what versions of &kde; software you are building (see TechBase for specifics), but with modern distributions the &cmake; included with your distribution should be quite sufficient. You must also install the source control clients needed to checkout the &kde; source code. This means you need at least the following: The Git source control manager, which is used for all &kde; source code Although it is not required, the Bazaar source control manager is used for a single module (libdbusmenu-qt) that is required for the &kde; libraries. Most users can install this library through their distribution packages but &kdesrc-build; supports building it as well if you desire. But to build libdbusmenu-qt, you must have Bazaar installed. The Perl scripting language is required for &kdesrc-build;, some &kde; repositories, and &Qt; (if you build that from source). The Perl that comes with your distribution should be suitable (it needs to be at least Perl 5.14), but you will also need some additional modules (&kdesrc-build; will warn if they are not present): IO::Socket::SSL JSON::PP or JSON::XS YAML::PP, YAML::XS, or YAML::Syck You will need a full C++ development environment (compiler, standard library, runtime, and any required development packages). The minimum required versions vary based on the &kde; module: the &kde; Frameworks 5 collection supports the oldest compilers, while &kde; Plasma 5 and &kde; Applications tend to require more recent compilers. The GCC 4.8 or Clang 4 compilers are the minimum recommended. Many distributions support easily installing these tools using a build-essentials package, an option to install "build dependencies" with &Qt;, or similar features. The KDE Community Wiki has a page tracking recommended packages for major distributions. You will need a build tool that actually performs the compilation steps (as generated by &cmake;). GNU Make is recommended and should be available through your package manager. &cmake; does support others options, such as the "ninja" build tool, which can be used by &kdesrc-build; using the custom-build-command configuration file option. Finally, you will need the appropriate &Qt; libraries (including development packages) for the version of &kde; software you are building. &kdesrc-build; does not officially support building &Qt; 5 (the current major version), so it is recommended to use your distribution's development packages or to see the KDE Community wiki page on self-building Qt 5. Most operating system distributions include a method of easily installing required development tools. Consult the Community Wiki page Required devel packages to see if these instructions are already available. Some of these packages are divided into libraries (or programs or utilities), and development packages. You will need at least the program or library and its development package. Setup &kdesrc-build; Install &kdesrc-build; The &kde; developers make frequent changes to &kdesrc-build; to keep it in sync with advances in &kde; development, including improvements to the recommended &kdesrc-build; configuration, added modules, improving &cmake; flags, &etc; Because of this, we recommend obtaining &kdesrc-build; directly from its source repository and then periodically updating it. You can obtain &kdesrc-build; from its source repository by running: $ git Replace with the directory you would like to install to. You can update &kdesrc-build; later by running: $ cd $ git We recommend adding the &kdesrc-build; installation directory to your PATH environment variable, so that you can run &kdesrc-build; without having to fully specify its path every time. Prepare the configuration file &kdesrc-build; uses a configuration file (located at ~/.kdesrc-buildrc) to control which modules are built, where they are installed to, etc. You can use a program included with &kdesrc-build;, called kdesrc-build-setup in order to prepare a simple kdesrc-build configuration. You can then edit the ~/.kdesrc-buildrc from there to make any changes you see fit. kdesrc-build-setup itself runs from a terminal (instead of using a graphical interface), just like &kdesrc-build;, so you can use it even if you have no graphical interface available yet. Manual setup of configuration file You can also setup your configuration file manually, by copying the included sample configuration file kdesrc-buildrc-kf5-sample to ~/.kdesrc-buildrc and then editing the file. will be a useful reference for this, especially its table of configuration options. &kdesrc-build; contains many recommended configuration files to support &kde; Frameworks 5, &plasma; 5, and other &kde; applications. The kdesrc-build-setup refers to these files in the configuration file it generates, but you can also use them yourself. See for information on how to use other configuration files from your own ~/.kdesrc-buildrc. You can find more information about the syntax of the configuration file in and in . Setting the Configuration Data To use &kdesrc-build;, you should have a file in your home directory called .kdesrc-buildrc, which sets the general options and sets the modules you would like to download and build. It is possible to use different configuration files for &kdesrc-build;, which is described in . If you need to use multiple configurations, please see that section. Here, we will assume the configuration is stored in ~/.kdesrc-buildrc. The easiest way to proceed is to use the kdesrc-buildrc-kf5-sample file as a template, changing global options to match your wants, and also change the list of modules you want to build. The default settings should be appropriate to perform a &kde; build. Some settings that you may wish to alter include: kdedir, which changes the destination directory that your &kde; software is installed to. This defaults to ~/kde, which is a single-user installation. branch-group, which can be used to choose the appropriate branch of development for the &kde; modules as a whole. There are many supported build configurations but you will likely want to choose so that &kdesrc-build; downloads the latest code based on &Qt; 5 and &kde; Frameworks 5. &kdesrc-build; will use a default branch group if you do not choose one, but this default will change over time, so it's better to choose one so that the branch group does not change unexpectedly. source-dir, to control the directory &kdesrc-build; uses for downloading the source code, running the build process, and saving logs. This defaults to ~/kdesrc. cmake-options, which sets the options to pass to the &cmake; command when building each module. Typically this is used to set between debug or release builds, to enable (or disable) optional features, or to pass information to the build process about the location of required libraries. make-options, which sets the options used when actually running the make command to build each module (once &cmake; has established the build system). The most typical option is , where N should be replaced with the maximum number of compile jobs you wish to allow. A higher number (up to the number of logical CPUs your system has available) leads to quicker builds, but requires more system resources. Configuring Make for 4 compiles at once, with exceptions global make-options -j4 … end global … module-set big-module-set repository kde-projects use-modules calligra make-options -j2 # Reduced number of build jobs for just these modules end module-set Some very large Git repositories may swamp your system if you try to compile with a too many build jobs at one time, especially repositories like the &Qt; WebKit and &Qt; WebEngine repositories. To maintain system interactivity you may have to reduce the number of build jobs for specific modules. gives an example of how to do this. You may want to select different modules to build, which is described in . Using the &kdesrc-build; script With the configuration data established, now you are ready to run the script. Even if you still have some tweaking or other reading you wish to do, it is a good idea to at least load the &kde; project metadata. Loading project metadata From a terminal window, log in to the user you are using to compile &kde; software and execute the script: % kdesrc-build This command will setup the source directory and connect to the KDE &git; repositories to download the database of &kde; git repositories, and the database of dependency metadata, without making any further changes. It is useful to run this separately as this metadata is useful for other &kdesrc-build; commands. Previewing what will happen when kdesrc-build runs With the project metadata installed, it is possible to preview what &kdesrc-build; will do when launched. This can be done with the command line option. % ./kdesrc-build You should see a message saying that some packages were successfully built (although nothing was actually built). If there were no significant problems shown, you can proceed to actually running the script. % kdesrc-build This command will download the appropriate source code, and build and install each module in order, but will stop if a module fails to build (due to the option). Afterwards, you should see output similar to that in : Example output of a kdesrc-build run % kdesrc-build Updating kde-build-metadata (to branch master) Updating sysadmin-repo-metadata (to branch master) Building libdbusmenu-qt (1/200) No changes to libdbusmenu-qt source, proceeding to build. Compiling... succeeded (after 0 seconds) Installing.. succeeded (after 0 seconds) Building taglib (2/200) Updating taglib (to branch master) Source update complete for taglib: 68 files affected. Compiling... succeeded (after 0 seconds) Installing.. succeeded (after 0 seconds) Building extra-cmake-modules from <module-set at line 32> (3/200) Updating extra-cmake-modules (to branch master) Source update complete for extra-cmake-modules: 2 files affected. Compiling... succeeded (after 0 seconds) Installing.. succeeded (after 0 seconds) ... Building kdevelop from kdev (200/200) Updating kdevelop (to branch master) Source update complete for kdevelop: 29 files affected. Compiling... succeeded (after 1 minute, and 34 seconds) Installing.. succeeded (after 2 seconds) <<< PACKAGES SUCCESSFULLY BUILT >>> Built 200 modules Your logs are saved in /home/kde-src/kdesrc/log/2018-01-20-07 Resolving build failures Depending on how many modules you are downloading, it is possible that &kdesrc-build; will not succeed the first time you compile &kde; software. Do not despair! &kdesrc-build; logs the output of every command it runs. By default, the log files are kept in ~/kdesrc/log. To see what the caused an error for a module in the last &kdesrc-build; command, usually it is sufficient to look at ~/kdesrc/log/latest/module-name/error.log. Perhaps the easiest way to find out what error caused a module to fail to build is to search backward with a case-insensitive search, starting from the end of the file looking for the word error. Once that is found, scroll up to make sure there are no other error messages nearby. The first error message in a group is usually the underlying problem. In that file, you will see the error that caused the build to fail for that module. If the file says (at the bottom) that you are missing some packages, try installing the package (including any appropriate -dev packages) before trying to build that module again. Make sure that when you run &kdesrc-build; again to pass the --reconfigure option so that &kdesrc-build; forces the module to check for the missing packages again. Or, if the error appears to be a build error (such as a syntax error, incorrect prototype, unknown type, or similar) then it is probably an error with the &kde; source, which will hopefully be resolved within a few days. If it is not resolved within that time, feel free to mail the kde-devel@kde.org mailing list (subscription may be required first) in order to report the build failure. You can find more common examples of things that can go wrong and their solutions, as well as general tips and strategies to build &kde; software in the Build from Source. On the other hand, assuming everything went well, you should have a new &kde; install on your computer, and now it is simply a matter of running it, described next in . For more information about &kdesrc-build;'s logging features, please see . Building specific modules Rather than building every module all the time, you may only want to build a single module, or other small subset. Rather than editing your configuration file, you can simply pass the names of modules or module sets to build to the command line. Example output of a kdesrc-build specific module build % kdesrc-build dolphin Updating kde-build-metadata (to branch master) Updating sysadmin-repo-metadata (to branch master) Building extra-cmake-modules from frameworks-set (1/79) Updating extra-cmake-modules (to branch master) No changes to extra-cmake-modules source, proceeding to build. Running cmake... Compiling... succeeded (after 0 seconds) Installing.. succeeded (after 0 seconds) Building phonon from phonon (2/79) Updating phonon (to branch master) No changes to phonon source, proceeding to build. Compiling... succeeded (after 0 seconds) Installing.. succeeded (after 0 seconds) Building attica from frameworks-set (3/79) Updating attica (to branch master) No changes to attica source, proceeding to build. Compiling... succeeded (after 0 seconds) Installing.. succeeded (after 0 seconds) ... Building dolphin from base-apps (79/79) Updating dolphin (to branch master) No changes to dolphin source, proceeding to build. Compiling... succeeded (after 0 seconds) Installing.. succeeded (after 0 seconds) <<< PACKAGES SUCCESSFULLY BUILT >>> Built 79 modules Your logs are saved in /home/kde-src/kdesrc/log/2018-01-20-07 In this case, although only the dolphin application was specified, the flag caused &kdesrc-build; to include the dependencies listed for dolphin (by setting the include-dependencies option). The dependency resolution worked in this case only because dolphin happened to be specified in a kde-projects-based module set (in this example, named base-apps). See . Setting the Environment to Run Your &kde; &plasma; Desktop Assuming you are using a dedicated user to build &kde; &plasma;, and you already have an installed &plasma; version, running your new &plasma; may be a bit tricky, as the new &plasma; has to take precedence over the old. You must change the environment variables of your login scripts to make sure the newly-built desktop is used. Automatically installing a login driver Starting from version 1.16, &kdesrc-build; will try to install an appropriate login driver, that will allow you to login to your &kdesrc-build;-built &kde; desktop from your login manager. This can be disabled by using the configuration file option. Session setup does not occur while &kdesrc-build; is running in pretend mode. This driver works by setting up a custom xsession session type. This type of session should work by default with the &kdm; login manager (where it appears as a Custom session), but other login managers (such as LightDM and gdm) may require additional files installed to enable xsession support. Adding xsession support for distributions The default login managers for some distributions may require additional packages to be installed in order to support xsession logins. The Fedora &Linux; distribution requires the xorg-x11-xinit-session package to be installed for custom xsession login support. Debian and Debian-derived &Linux; distributions should support custom xsession logins, but require the option to be set in /etc/X11/Xsession.options. See also the Debian documentation on customizing the X session. For other distributions, go to . Manually adding support for xsession If there were no distribution-specific directions for your distribution in , you can manually add a Custom xsession login entry to your distribution's list of session types as follows: Adding an .xsession login session type. This procedure will likely require administrative privileges to complete. Create the file /usr/share/xsessions/kdesrc-build.desktop. Ensure the file just created has the following text: Type=XSession Exec=$HOME/.xsession Name=KDE Plasma Desktop (unstable; kdesrc-build) The $HOME entry must be replaced by the full path to your home directory (example, /home/user). The desktop entry specification does not allow for user-generic files. When the login manager is restarted, it should show a new session type, KDE Plasma Desktop (unstable; kdesrc-build) in its list of sessions, which should try to run the .xsession file installed by &kdesrc-build; if it is selected when you login. It may be easiest to restart the computer to restart the login manager, if the login manager does not track updates to the /usr/share/xsessions directory. Setting up the environment manually This documentation used to include instruction on which environment variables to set in order to load up the newly-built desktop. These instructions have been moved to an appendix (). If you intend to setup your own login support you can consult that appendix or view the sample-kde-env-master.sh file included with the &kdesrc-build; source. Module Organization and selection KDE Software Organization &kde; software is split into different components, many of which can be built by &kdesrc-build;. Understanding this organization will help you properly select the software modules that you want built. At the lowest level comes the &Qt; library, which is a very powerful, cross-platform toolkit library. &kde; is based on &Qt;, and some of the non-&kde; libraries required by &kde; are also based on &Qt;. &kdesrc-build; can build &Qt;, or use the one already installed on your system if it is a recent enough version. On top of &Qt; are required libraries that are necessary for &kde; software to work. Some of these libraries are not considered part of &kde; itself due to their generic nature, but are still essential to the &kde; Platform. These libraries are collected under a kdesupport module grouping but are not considered part of the Frameworks libraries. On top of these essential libraries come the &kde; Frameworks, sometimes abbreviated as KF5, which are essential libraries for the &kde; Plasma desktop, &kde; Applications, and other third-party software. On top of the Frameworks, come several different things: Third-party applications. These are applications that use the &kde; Frameworks or are designed to run under &kde; Plasma but are not authored by or in association with the &kde; project. Plasma, which is a full workspace desktop environment. This is what users normally see when they log-in to &kde;. The &kde; Application suite. This is a collection of useful software included with the Platform and &plasma; Desktop, grouped into individual modules, including utilities like &dolphin;, games like KSudoku, and productivity software released by &kde; such as &kontact;. Finally, there is a collection of software (also collected in modules) whose development is supported by &kde; resources (such as translation, source control, bug tracking, &etc;) but is not released by &kde; as part of Plasma or the Application suite. These modules are known as Extragear. Selecting modules to build Selecting which of the possible modules to build is controlled by the configuration file. After the global section is a list of modules to build, bracketed by module ... end module lines. An example entry for a module is shown in . Example module entry in the configuration file module kdesrc-build-git # Options for this module go here, example: repository kde:kdesrc-build make-options -j4 # Run 4 compiles at a time end module In practice, this module construct is not usually used directly. Instead most modules are specified via module-sets as described below. When using only module entries, &kdesrc-build; builds them in the order you list, and does not attempt to download any other repositories other than what you specify directly. Module Sets The &kde; source code is decomposed into a great number of relatively small Git-based repositories. To make it easier to manage the large number of repositories involved in any useful &kde;-based install, &kdesrc-build; supports grouping multiple modules and treating the group as a module set. The basic module set concept By using a module set, you can quickly declare many Git modules to be downloaded and built, as if you'd typed out a separate module declaration for each one. The repository option is handled specially to setup where each module is downloaded from, and every other option contained in the module set is copied to every module generated in this fashion. Using module sets global kde-git kde: end global module qt # Options removed for brevity end module module-set kde-support-libs kde-git automoc attica akonadi end module-set # Other modules as necessary... module kdesupport end module In a brief module set is shown. When &kdesrc-build; encounters this module set, it acts as if, for every module given in , that an individual module has been declared, with its equal to the module-set's followed immediately by the given module name. In addition, other options can be passed in a module set, which are copied to every new module that is created this way. By using module-set it is possible to quickly declare many Git modules that are all based on the same repository URL. In addition, it is possible to give module-sets a name (as shown in the example), which allows you to quickly refer to the entire group of modules from the command line. Special Support for KDE module sets The module set support described so far is general to any Git-based modules. For the &kde; Git repositories, &kdesrc-build; includes additional features to make things easier for users and developers. This support is enabled by specifying kde-projects as the for the module set. &kdesrc-build; normally only builds the modules you have listed in your configuration file, in the order you list them. But with a kde-projects module set, &kdesrc-build; can do dependency resolution of &kde;-specific modules, and in addition automatically include modules into the build even if only indirectly specified. Using kde-projects module sets # Only adds a module for juk (the kde/kdemultimedia/juk repo) module-set juk-set kde-projects juk end module-set # Adds all modules that are in kde/multimedia/*, including juk, # but no other dependencies module-set multimedia-set kde-projects kde/multimedia end module-set # Adds all modules that are in kde/multimedia/*, and all kde-projects # dependencies from outside of kde/kdemultimedia module-set multimedia-deps-set kde-projects kde/multimedia true end module-set # All modules created out of these three module sets are automatically put in # proper dependency order, regardless of the setting for include-dependencies This kde-projects module set construct is the main method of declaring which modules you want to build. All module sets use the repository and use-modules options. kde-projects module sets have a predefined value, but other types of module sets also will use the git-repository-base option. The official &kde; module database &kde;'s Git repositories allow for grouping related Git modules into collections of related modules (e.g. kdegraphics). Git doesn't recognize these groupings, but &kdesrc-build; can understand these groups, using module sets with a option set to kde-projects. &kdesrc-build; will recognize that the kde-projects repository requires special handling, and adjust the build process appropriately. Among other things, &kdesrc-build; will: Download the latest module database from the &kde; git archive. Try to find a module with the name given in the module set's setting in that database. For every module that is found, &kdesrc-build; will lookup the appropriate repository in the database, based upon the branch-group setting in effect. If a repository exists and is active for the branch group, &kdesrc-build; will automatically use that to download or update the source code. In the current database, some module groups not only have a collection of modules, but they also declare their own &git; repository. In these situations &kdesrc-build; will currently prefer the group's &git; repository instead of including the childrens' repositories. The following example shows how to use the &kde; module database to install the Phonon multimedia library. module-set media-support # This option must be kde-projects to use the module database. kde-projects # This option chooses what modules to look for in the database. phonon/phonon phonon-gstreamer phonon-vlc end module-set phonon/phonon is used since (with the current project database) &kdesrc-build; would otherwise have to decide between the group of projects called phonon or the individual project named phonon. Currently &kdesrc-build; would pick the former, which would build many more backends than needed. The following example is perhaps more realistic, and shows a feature only available with the &kde; module database: Building all of the &kde; graphics applications with only a single declaration. module-set kdegraphics # This option must be kde-projects to use the module database. kde-projects # This option chooses what modules to look for in the database. kdegraphics/libs kdegraphics/* end module-set There are two important abilities demonstrated here: &kdesrc-build; allows you to specify modules that are descendents of a given module, without building the parent module, by using the syntax module-name/*. It is actually required in this case since the base module, kdegraphics, is marked as inactive so that it is not accidentally built along with its children modules. Specifying the descendent modules allows &kdesrc-build; to skip around the disabled module. &kdesrc-build; will also not add a given module to the build list more than once. This allows us to manually set kdegraphics/libs to build first, before the rest of kdegraphics, without trying to build kdegraphics/libs twice. This used to be required for proper dependency handling, and today remains a fallback option in case the &kde; project database is missing dependency metadata. Filtering out &kde; project modules You might decide that you'd like to build all programs within a &kde; module grouping except for a given program. For instance, the kdeutils group includes a program named kremotecontrol. If your computer does not have the proper hardware to receive the signals sent by remote controls then you may decide that you'd rather not download, build, and install kremotecontrol every time you update kdeutils. You can achieve this by using the ignore-modules configuration option. Example for ignoring a kde-project module in a group module-set utils kde-projects # This option chooses what modules to look for in the database. kdeutils # This option "subtracts out" modules from the modules chosen by use-modules, above. kremotecontrol end module-set module-set graphics kde-projects # This option chooses what modules to look for in the database. extragear/graphics # This option "subtracts out" modules from the modules chosen by use-modules, above. # In this case, *both* extragear/graphics/kipi-plugins and # extragear/graphics/kipi-plugins/kipi-plugins-docs are ignored extragear/graphics/kipi-plugins end module-set Getting Started Conclusion These are the major features and concepts needed to get started with &kdesrc-build; For additional information, you could keep reading through this documentation. In particular, the list of command-line options and the table of configuration file options are useful references. The &kde; Community also maintains an online Wiki reference for how to build the source code, which refers to &kdesrc-build; and includes tips and other guidelines on how to use the tool. Script Features Feature Overview &kdesrc-build; features include: You can pretend to do the operations. If you pass or on the command line, the script will give a verbose description of the commands it is about to execute, without actually executing it. However if you've never run &kdesrc-build;, you would want to run the kdesrc-build command first in order for to work. For an even more verbose description of what &kdesrc-build; is doing, try using the option. &kdesrc-build; can (with the assistance of the &kde; FTP server) allow for speedy checkouts of some Subversion modules. If the module you are checking out has already been packaged at the website, then &kdesrc-build; will download the snapshot and prepare it for use on your computer. There is generally no need for any special preparation to perform the initial checkout of a Git module, as the entire Git repository must be downloaded anyways, so it is easy for the server to determine what to send. This is faster for you, and helps to ease the load on the kde.org anonymous &subversion; servers. Another speedup is provided by starting the build process for a module as soon as the source code for that module has been downloaded. (Available since version 1.6) Excellent support for building the &Qt; library (in case the &kde; software you are trying to build depends on a recent &Qt; not available in your distribution). &kdesrc-build; does not require a GUI present to operate. So, you can build &kde; software without needing a graphical environment. Supports setting default options for all modules (such as the compilation settings or the configuration options). Such options can normally be changed for specific modules as well. Also, &kdesrc-build; will add standard flags as appropriate to save you the trouble and possible errors from typing them yourself. &kdesrc-build; can checkout a specific branch or tag of a module. You can also ensure that a specific revision is checked out of a module. &kdesrc-build; can automatically switch a source directory to checkout from a different repository, branch, or tag. This happens automatically when you change an option that changes what the repository &url; should be, but you must use the --src-only option to let &kdesrc-build; know that it is acceptable to perform the switch. &kdesrc-build; can checkout only portions of a module, for those situations where you only need one program from a large module. For developers: &kdesrc-build; will remind you if you use svn+ssh:// but ssh-agent is not running, as this will lead to repeated password requests from &ssh;. Can delete the build directory of a module after its installation to save space at the expense of future compilation time. The locations for the directories used by &kdesrc-build; are configurable (even per module). Can use &sudo;, or a different user-specified command to install modules so that &kdesrc-build; does not need to be run as the super user. &kdesrc-build; runs with reduced priority by default to allow you to still use your computer while &kdesrc-build; is working. Has support for using &kde;'s tags and branches. There is support for resuming a build from a given module. You can even ignore some modules temporarily for a given build. &kdesrc-build; will show the progress of your build when using &cmake;, and will always time the build process so you know after the fact how long it took. Comes built-in with a sane set of default options appropriate for building a base &kde; single-user installation from the anonymous source repositories. Tilde-expansion for your configuration options. For example, you can specify: qtdir ~/kdesrc/build/qt Automatically sets up a build system, with the source directory not the same as the build directory, in order to keep the source directory pristine. You can specify global options to apply to every module to check out, and you can specify options to apply to individual modules as well. Forced full rebuilds, by running &kdesrc-build; with the option. You can specify various environment values to be used during the build, including KDEDIR, QTDIR, DO_NOT_COMPILE, and CXXFLAGS. Command logging. Logs are dated and numbered so that you always have a log of a script run. Also, a special symlink called latest is created to always point to the most recent log entry in the log directory. You can check out only a portion of a &kde; &subversion; module. For example, you could check out only the taglib from kdesupport. &kdesrc-build;'s build logging Logging overview Logging is a &kdesrc-build; feature whereby the output from every command that &kdesrc-build; runs is saved to a file for examination later, if necessary. This is done because it is often necessary to have the output of these programs when there is a build failure, because there are so many reasons why a build can fail in the first place. Logging directory layout The logs are always stored under the log directory. The destination of the log directory is controlled by the log-dir option, which defaults to ${source-dir}/log (where ${source-dir} is the value of the source-dir option. The in rest of this section, this value will be referred to as ${log-dir}). Under ${log-dir}, is a set of directories, one for every time that &kdesrc-build; was run. Each directory is named with the date, and the run number. For instance, the second time that &kdesrc-build; is run on May 26, 2004, it would create a directory called 2004-05-26-02, where the 2004-05-26 is for the date, and the -02 is the run number. For your convenience, &kdesrc-build; will also create a link to the logs for your latest run, called latest. So the logs for the most recent &kdesrc-build; run should always be under ${log-dir}/latest. Now, each directory for a &kdesrc-build; run will itself contain a set of directories, one for every &kde; module that &kdesrc-build; tries to build. Also, a file called build-status will be contained in the directory, which will allow you to determine which modules built and which failed. If a module itself has a submodule (such as extragear/multimedia, playground/utils, or KDE/kdelibs), then there would actually be a matching layout in the log directory. For example, the logs for KDE/kdelibs after the last &kdesrc-build; run would be found in ${log-dir}/latest/KDE/kdelibs, and not under ${log-dir}/latest/kdelibs. In each module log directory, you will find a set of files for each operation that &kdesrc-build; performs. If &kdesrc-build; updates a module, you may see filenames such as svn-co.log (for a module checkout) or svn-up.log (when updating a module that has already been checked out). If the configure command was run, then you would expect to see a configure.log in that directory. If an error occurred, you should be able to see an explanation of why in one of the files. To help you determine which file contains the error, &kdesrc-build; will create a link from the file containing the error (such as build-1.log to a file called error.log). The upshot to all of this is that to see why a module failed to build after your last &kdesrc-build;, the file you should look at first is ${log-dir}/latest/module-name/error.log. If the file error.log is empty (especially after an installation), then perhaps there was no error. Some of the tools used by the &kde; build system will sometimes mistakenly report an error when there was none. Also, some commands will evade &kdesrc-build;'s output redirection and bypass the log file in certain circumstances (normally when performing the first &subversion; checkout), and the error output in that case is not in the log file but is instead at the &konsole; or terminal where you ran &kdesrc-build;. Configuring &kdesrc-build; Overview of &kdesrc-build; configuration To use the script, you must have a file in your home directory called .kdesrc-buildrc, which describes the modules you would like to download and build, and any options or configuration parameters to use for these modules. Layout of the configuration file Global configuration The configuration file starts with the global options, specified like the following: global option-name option-value [...] end global Module configuration It is then followed by one or more module sections, specified in one of the following two forms: module module-name option-name option-value [...] end module module-set module-set-name repository kde-projects or git://host.org/path/to/repo.git use-modules module-names # Other options may also be set option-name option-value [...] end module-set Note that the second form, module sets, only works for Git-based modules. For Subversion modules, module-name must be a module from the &kde; &subversion; repository (for example, kdeartwork or kde-wallpapers), although it is possible to get around this if you manually specify the &subversion; URL. For Git modules, the module name can be essentially whatever you'd like, as long as it does not duplicate any other module name in the configuration. Keep in mind the source and build directory layout will be based on the module name if you do not use the dest-dir option. However, for Git module sets the module-names must correspond with actual git modules in the chosen . See git-repository-base or use-modules for more information. <quote>options</quote> modules There is a final type of configuration file entry, options groups, which may be given wherever a module or module-set may be used. options module-name option-name option-value [...] end options An options group may have options set for it just like a module declaration, and is associated with an existing module. Any options set these way will be used to override options set for the associated module. The associated module name must match the name given in the options declaration. Be careful of mis-typing the name. This is useful to allow for declaring an entire module-set worth of modules, all using the same options, and then using options groups to make individual changes. options groups can also apply to named module sets. This allows expert users to use a common configuration file (which includes module-set declarations) as a baseline, and then make changes to the options used by those module-sets in configuration files that use the include command to reference the base configuration. Example of using options In this example we choose to build all modules from the &kde; multimedia software grouping. However we want to use a different version of the &kmix; application (perhaps for testing a bug fix). It works as follows: module-set kde-multimedia-set repository kde-projects use-modules kde/kdemultimedia branch master end module-set # kmix is a part of kde/kdemultimedia group, even though we never named # kmix earlier in this file, &kdesrc-build; will figure out the change. options kmix branch KDE/4.12 end options Now when you run &kdesrc-build;, all of the &kde; multimedia programs will be built from the master branch of the source repository, but &kmix; will be built from the older KDE/4.12 branch. By using options you didn't have to individually list all the other &kde; multimedia programs to give them the right branch option. Note that this feature is only available in &kdesrc-build; from version 1.16, or using the development version of &kdesrc-build; after 2014-01-12. Including other configuration files Within the configuration file, you may reference other files by using the include keyword with a file, which will act as if the file referenced had been inserted into the configuration file at that point. For example, you could have something like this: global include ~/common-kdesrc-build-options # Insert specific options here. end global If you don't specify the full path to the file to include, then the file will be searched for starting from the directory containing the source file. This works recursively as well. Commonly used configuration options The following is a list of commonly-used options. Click on the option to find out more about it. To see the full list of options, see . cmake-options to define what flags to configure a module with using &cmake;. branch, to checkout from a branch instead of /trunk (for &subversion;) or master (for Git). configure-flags to define what flags to configure &Qt; with. kdedir, to set the directory to install &kde; to. make-options, to pass options to the &make; program (such as number of CPUs to use). qtdir, to set the path to &Qt;. source-dir, to change where to download the source code to. Table of available configuration options Here is a table of the various options, containing the following information: The option name A description of how &kdesrc-build; responds if the option is set in both the global section, and the module section of the configuration file while building a module. Special comments on the purpose and usage of the option. Table of Options Option-name Module -> Global Behavior Notes apidox This option was used to allow for building KDE module API documentation. It was removed in &kdesrc-build; 1.6.3 due to lack of support. Online API documentation is available from kde.org. In addition it is possible to build KDE API documentation using the kdedoxygen.sh script included in the kde-dev-scripts module. See KDE TechBase for more details. apply-qt-patches This option was removed in kdesrc-build 1.10. To get the same effect, see and the repository option. async Cannot be overridden This option enables the asynchronous mode of operation, where the source code update and the build process will be performed in parallel, instead of waiting for all of the source code updates before starting the build process. This option defaults to enabling asynchronous mode. To disable, set this option to false This option is available since the 1.6 release. binpath Module setting overrides global Set this option to set the environment variable PATH while building. You cannot override this setting in a module option. The default value is the $PATH that is set when the script starts. This environment variable should include the colon-separated paths of your development toolchain. The paths $KDEDIR/bin and $QTDIR/bin are automatically added. You may use the tilde (~) for any paths you add using this option. branch Module setting overrides global Set this option to checkout from a branch of &kde; instead of the default of master (for &git; modules) or trunk (for &subversion;), where &kde; development occurs. For instance, to checkout &kde; 4.6 branch, you would set this option to 4.6. If &kdesrc-build; fails to properly download a branch with this option, you may have to manually specify the &url; to download from using the module-base-path or override-url options. For most &kde; modules you probably wish to use the branch-group option instead and use this option for case-by-case exceptions. branch-group Module setting overrides global Set this option to a general group from which you want modules to be chosen. For supported &git; module types, &kdesrc-build; will determine the actual branch to use automatically based on rules encoded by the &kde; developers (these rules may be viewed in the kde-build-metadata source repository in your source directory). After a branch is determined that branch is used as if you had specified it yourself using the branch option. This is useful if you're just trying to maintain up-to-date on some normal development track without having to pay attention to all the branch name changes. The current branch groups (as of 2013-08-11) are: stable-qt4, for tracking bugfixes to the &Qt; 4-based &kde; libraries and applications. latest-qt4, for tracking development and new features for the &Qt; 4-based &kde; libraries and applications. kf5-qt5, for tracking bleeding-edge development for the upcoming &Qt; 5-based &kde; Frameworks 5, &plasma; Workspace 2, &etc; Note that if you do choose a branch yourself, that it will override this setting. The same is true of other specific branch selection options such as tag. This option was added in &kdesrc-build; 1.16-pre2. This option only applies to kde-projects &git; modules (the common case). See also . build-dir Module setting overrides global Use this option to change the directory to contain the built sources. There are three different ways to use it: Relative to the &kde; &subversion; source directory (see the source-dir option). This is the default, and is selected if you type a directory name that does not start with a tilde (~) or a slash (/). The default value is build. Absolute path. If you specify a path that begins with a /, then that path is used directly. For example, /tmp/kde-obj-dir/. Relative to your home directory. If you specify a path that begins with a ~, then the path is used relative to your home directory, analogous to the shell's tilde-expansion. For example, ~/builddir would set the build directory to /home/user-name/builddir. Perhaps surprisingly, this option can be changed per module. build-when-unchanged Module setting overrides global Use this option in order to control whether &kdesrc-build; always tries to build a module that has not had any source code updates. By setting to true, &kdesrc-build; always attempts the build phase for a module, even if the module did not have any source code updates. This is the default setting since it is more likely to lead to a correct build. By setting to false, &kdesrc-build; will only attempt to run the build phase for a module if the module has a source code update, or in other situations where it is likely that a rebuild is actually required. This can save time, especially if you run &kdesrc-build; daily, or more frequently. This feature is provided as an optimization only. Like many other optimizations, there are trade-offs for the correctness of your installation. For instance, changes to the qt or kdelibs modules may cause a rebuild of other modules to be necessary, even if the source code doesn't change at all. checkout-only Module setting overrides global Set this option to checkout &subversion; sources piece by piece. The value for this option should be a space-separated list of directories to checkout. Although this option overrides the global option, be aware that setting this as a global option makes no sense. Note that this setting has no effect on &git; modules due to the operation of the &git; source control system. See for an example. cmake-options Appends to global options for the default buildsystem, overrides global for other buildsystems. Use this option to specify what flags to pass to &cmake; when creating the build system for the module. When this is used as a global option, it is applied to all modules that this script builds. When used as a module option, it is added to the end of the global options. This allows you to specify common &cmake; options in the global section. This option does not apply to qt (which does not use &cmake;). Use configure-flags instead. Since these options are passed directly to the &cmake; command line, they should be given as they would be typed into &cmake;. For example: cmake-options -DCMAKE_BUILD_TYPE=RelWithDebInfo Since this is a hassle, &kdesrc-build; takes pains to ensure that as long as the rest of the options are set correctly, you should be able to leave this option blank. (In other words, required &cmake; parameters are set for you automatically) colorful-output Cannot be overridden Set this option to false to disable the colorful output of &kdesrc-build;. This option defaults to true. Note that &kdesrc-build; will not output the color codes to anything but a terminal (such as xterm, &konsole;, or the normal &Linux; console). configure-flags Appends to global options for the default buildsystem, overrides global for other buildsystems. Use this option to specify what flags to pass to ./configure when creating the build system for the module. When this is used as a global-option, it is applied to all modules that this script builds. This option only works for qt. To change configuration settings for KDE modules, see cmake-options. custom-build-command Module setting overrides global (build system option) This option can be set to run a different command (other than make, for example) in order to perform the build process. &kdesrc-build; should in general do the right thing, so you should not need to set this option. However it can be useful to use alternate build systems. The value of this option is used as the command line to run, modified by the make-options option as normal. cxxflags Appends to global options for the default buildsystem, overrides global for other buildsystems. Use this option to specify what flags to use for building the module. This option is specified here instead of with configure-flags or cmake-options because this option will also set the environment variable CXXFLAGS during the build process. Note that for &kde; 4 and any other modules that use &cmake;, it is necessary to set the CMAKE_BUILD_TYPE option to none when configuring the module. This can be done using the cmake-options option. dest-dir Module setting overrides global Use this option to change the name a module is given on disk. For example, if your module was extragear/network, you could rename it to extragear-network using this option. Note that although this changes the name of the module on disk, it is not a good idea to include directories or directory separators in the name as this will interfere with any build-dir or source-dir options. disable-agent-check Cannot be overridden Normally if you are using &ssh; to download the &subversion; sources (such as if you are using the svn+ssh protocol), &kdesrc-build; will try and make sure that if you are using ssh-agent, it is actually managing some &ssh; identities. This is to try and prevent &ssh; from asking for your pass phrase for every module. You can disable this check by setting to true. do-not-compile Module setting overrides global Use this option to select a specific set of directories not to be built in a module (instead of all of them). The directories not to build should be space-separated. Note that the sources to the programs will still be downloaded. You can use the checkout-only directive to choose directories that you want to check out. For example, to hold &juk; and &kscd; in the kdemultimedia module from compiling, you would add "do-not-compile juk kscd" to your kdemultimedia settings. See for an example. email-address Cannot be overridden This option was removed in &kdesrc-build; 1.14. email-on-compile-error Cannot be overridden This option was removed in &kdesrc-build; 1.14. inst-apps This option was removed in version 1.10 git-desired-protocol Cannot be overridden This option only applies to modules from a &kde; project repository. What this option actually does is configure which network protocol to prefer when updating source code for these modules. Normally the very-efficient git protocol is used, but this may be blocked in some networks (e.g. corporate intranets, public Wi-Fi). An alternative protocol which is much better supported is the HTTP protocol used for Internet web sites. If you are using one of these constrained networks you can set this option to http to prefer HTTP communications instead. You may also need the http-proxy option if an HTTP proxy is also needed for network traffic. In any other situation you should not set this option as the default protocol is most efficient. This option was added in &kdesrc-build; 1.16. git-repository-base Cannot be overridden This option, added in version 1.12.1, is used to create a short name to reference a specific Git repository base URL in later module set declarations, which is useful for quickly declaring many Git modules to build. You must specify two things (separated by a space): The name to assign to the base URL, and the actual base URL itself. For example: global # other options # This is the common path to all anonymous Git server modules. git-repository-base kde-git kde: end global # Module declarations module-set # Now you can use the alias you defined earlier, but only # in a module-set. repository kde-git use-modules module1.git module2.git end module-set The module-set's use-modules option created two modules internally, with &kdesrc-build; behaving as if it had read: module module1 repository kde:module1.git end module module module2 repository kde:module2.git end module The kde: &git; repository prefix used above is a shortcut which will be setup by &kdesrc-build; automatically. See the TechBase URL Renaming article for more information. Note that unlike most other options, this option can be specified multiple times in order to create as many aliases as necessary. It is not required to use this option to take advantage of module-set, this option exists to make it easy to use the same repository across many different module sets. git-user Module setting overrides global This option is intended for &kde; developers. If set, it will be used to automatically setup identity information for the &git; source control software for newly downloaded &git; modules (including the vast majority of &kde; modules). Specifically, the user's name and email fields for each new &git; repository are filled in to the values set by this option. The value must be specified in the form . For instance, a developer named Foo Barbaz with the email address foo@abc.xyz would use: git-user Foo Barbaz <foo@abc.xyz> This option was introduced in &kdesrc-build; 15.09. http-proxy Module setting overrides global This option, if set, uses the specified URL as a proxy server to use for any HTTP network communications (for example, when downloading snapshots for new modules, or the KDE project database). In addition, &kdesrc-build; will try to ensure that the tools it depends on also use that proxy server, if possible, by setting the http_proxy environment variable to the indicated server, if that environment variable is not already set. This option was introduced with &kdesrc-build; 1.16. ignore-kde-structure Module setting overrides global This option is used to store the source and the build files directly in the name of the module. For example, source/extragear/network/telepathy/ktp-text-ui becomes source/ktp-text-ui. This option is disabled by default. If you want to enable this option you need to set it to true. This option was introduced with &kdesrc-build; 1.16. ignore-modules Can't be overridden Modules named by this option, which would be chosen by &kdesrc-build; due to a use-modules option, are instead skipped entirely. Use this option when you want to build an entire kde-projects project grouping except for some specific modules. The option value does not necessarily have to name the module directly. Any module that has full consecutive parts of its &kde; projects module path match one of the option values will be ignored, so you can ignore multiple modules this way. For example, an option value of libs would result in both kde/kdegraphics/libs and playground/libs being excluded (though not kde/kdelibs since the full part kdelibs is what is compared). See also . This option was introduced with &kdesrc-build; 1.16. include-dependencies Module setting overrides global This option, when set to true requests that &kdesrc-build; also include known dependencies of this module in its build, without requiring you to mention those dependencies (even indirectly). This option only works for kde-project-based modules, and requires that the metadata maintained by the &kde; developers is accurate for your selected branch-group. This option is disabled by default, to avoid inadvertently selecting a bunch of modules that were not desired. It was added with &kdesrc-build; 1.16 in 2015. install-after-build Module setting overrides global This option is used to install the package after it successfully builds. This option is enabled by default. If you want to disable this, you need to set this option to false in the configuration file. You can also use the command line flag. install-environment-driver Cannot be overridden By default, &kdesrc-build; will install a shell script that can be sourced in a user's profile setup scripts to easily establish needed environment variables to run the Plasma desktop built by &kdesrc-build;. This driver will alter the following files: $XDG_CONFIG_HOME/kde-env-master.sh (normally found at ~/.config/kde-env-master.sh). $XDG_CONFIG_HOME/kde-env-user.sh (normally found at ~/.config/kde-env-user.sh). The kde-env-user.sh is optional. It is intended for user customizations (see the Troubleshooting and Debugging section of the &kde; UserBase for examples of customizable settings), but these settings can be set elsewhere by the user in their existing profile setup scripts. You can disable this feature by setting this option to false, and ensuring that the install-session-driver option is also disabled. This option was introduced with &kdesrc-build; 17.08. &kdesrc-build; will not overwrite your existing files (if present) unless you also pass the command-line option. install-session-driver Cannot be overridden If enabled, &kdesrc-build; will try to install a driver for the graphical login manager that allows you to login to your &kdesrc-build;-built &kde; desktop. This driver will alter the following files: ~/.xsession $XDG_CONFIG_HOME/kde-env-master.sh (normally found at ~/.config/kde-env-master.sh). $XDG_CONFIG_HOME/kde-env-user.sh (normally found at ~/.config/kde-env-user.sh). If you maintain your own login driver then you can disable this feature by setting this option to false. If enabled, this feature also enables the install-environment-driver feature. This option was introduced with &kdesrc-build; 1.16. &kdesrc-build; will not overwrite your existing files (if present) unless you also pass the command-line option. kdedir Module setting overrides global This option sets the directory that &kde; will be installed to after it is built. It defaults to ~/kde. If you change this to a directory needing root access, you may want to read about the make-install-prefix option as well. kde-languages Cannot be overridden -This option allows you to choose to download and install -localization packages along with &kde;. You might do this if you do not live in -the United States and would like to use &kde; translated into your native -language. - -To use this option, set it to a space-separated list of languages to -install. Each language has a language code associated with it, which you -can look up at this page: http://l10n.kde.org/teams-list.php. +This option was intended to allow for building language packs from +the &kde; repository but has been removed due to brokenness. Interested users +should follow the normal translation build +instructions instead. -It is alright to choose only one language. By default, none are -downloaded, which means &kde; will display in American English. - -For instance, to choose to install French, you would set the option to -something like: -fr. You would still need to use -&systemsettings; in order to choose the French language, however. libpath Module setting overrides global Set this option to set the environment variable LD_LIBRARY_PATH while building. You cannot override this setting in a module option. The default value is blank, but the paths $KDEDIR/lib and $QTDIR/lib are automatically added. You may use the tilde (~) for any paths you add using this option. log-dir Module setting overrides global Use this option to change the directory used to hold the log files generated by the script. make-install-prefix Module setting overrides global Set this variable to a space-separated list, which is interpreted as a command and its options to precede the make command used to install modules. This is useful for installing packages with &sudo; for example, but please be careful while dealing with root privileges. make-options Module setting overrides global (build system option) Set this variable in order to pass command line options to the make command. This is useful for programs such as distcc or systems with more than one processor core. manual-build Module setting overrides global Set the option value to true to keep the build process from attempting to build this module. It will still be kept up-to-date when updating from &subversion;. This option is exactly equivalent to the command line option. manual-update Module setting overrides global Set the option value to true to keep the build process from attempting to update (and by extension, build or install) this module. If you set this option for a module, then you have essentially commented it out. module-base-path Module setting overrides global Set this option to override &kdesrc-build;'s default directory path to the module in question. This can be used, for example, to pull specific branches or tagged versions of libraries. The &kde; Source Viewer is invaluable in helping to pick the right path. Note that &kdesrc-build; constructs the final path according to the following template: $svn-server/home/kde/$module-base-path. The default value is either trunk/$module or trunk/KDE/$module, depending on the module name. Use the branch or tag options instead whenever they are applicable. niceness Cannot be overridden Set this option to a number between 20 and 0. The higher the number, the lower a priority &kdesrc-build; will set for itself, i.e. the higher the number, the "nicer" the program is. The default is 10. no-svn Module setting overrides global If this option is set to true then &kdesrc-build; will not update the source code for the module automatically. It will still try to build the module if it normally would have tried anyways. no-rebuild-on-fail This option was removed in version 1.10, since this behavior no longer helps due to fixes in the underlying build system. override-build-system Module setting overrides global This is an advanced option, added in &kdesrc-build; 1.16. Normally &kdesrc-build; will detect the appropriate build system to use for a module after it is downloaded. This is done by checking for the existence of specific files in the module's source directory. Some modules may include more than one required set of files, which could confuse the auto-detection. In this case you can manually specify the correct build type. Currently supported build types that can be set are: KDE Used to build &kde; modules. In reality it can be used to build almost any module that uses &cmake; but it is best not to rely on this. Qt Used to build the &Qt; library itself. qmake Used to build &Qt; modules that use qmake-style .pro files. generic Used to build modules that use plain Makefiles and that do not require any special configuration. autotools This is the standard configuration tool used for most Free and open-source software not in any of the other categories. override-url Module setting overrides global If you set this option, &kdesrc-build; will use its value as the &url; to pass to &subversion; completely unchanged. You should generally use this if you want to download a specific release but &kdesrc-build; cannot figure out what you mean using branch. persistent-data-file Cannot be overridden Use this option to change where &kdesrc-build; stores its persistent data. The default is to store this data in a file called .kdesrc-build-data placed in the same directory as the configuration file in use. If you have multiple available configurations in the same directory you may want to manually set this option so that the different configurations do not end up with conflicting persistent data. This option was added with &kdesrc-build; 1.15. prefix Module setting overrides global This option controls where to install the module (normally the setting is used). Using this option allows you to install a module to a different directory than where the KDE Platform libraries are installed, such as if you were using &kdesrc-build; only to build applications. You can use ${MODULE} or $MODULE in the path to have them expanded to the module's name. purge-old-logs Module setting overrides global This option controls whether old log directories are automatically deleted or not. The default value is true. qmake-options Module setting overrides global Any options specified here are passed to the qmake command, for modules that use the qmake build system. For instance, you can use the PREFIX=/path/to/qt option to qmake to override where it installs the module. This option was added to &kdesrc-build; 1.16. qtdir Module setting overrides global Set this option to set the environment variable QTDIR while building. If you do not specify this option, &kdesrc-build; will assume that &Qt; is provided by the operating system. remove-after-install Module setting overrides global If you are low on hard disk space, you may want to use this option in order to automatically delete the build directory (or both the source and build directories for one-time installs) after the module is successfully installed. Possible values for this option are: none - Do not delete anything (This is the default). builddir - Delete the build directory, but not the source. all - Delete both the source code and build directory. Note that using this option can have a significant detrimental impact on both your bandwidth usage (if you use all) and the time taken to compile &kde; software, since &kdesrc-build; will be unable to perform incremental builds. repository Module setting overrides global This option was introduced with version 1.10, and is used to specify the &git; repository to download the source code for the module. &Qt; (and therefore qt) would need this option, as well as various &kde; modules that are in the process of conversion to use &git;. revision Module setting overrides global If this option is set to a value other than 0 (zero), &kdesrc-build; will force the source update to bring the module to the exact revision given, even if options like branch are in effect. If the module is already at the given revision then it will not be updated further unless this option is changed or removed from the configuration. This option did not work for git-based modules (including kde-projects modules) until &kdesrc-build; version 1.16. run-tests Module setting overrides global (build system option) If set to true, then the module will be built with support for running its test suite, and the test suite will be executed as part of the build process. &kdesrc-build; will show a simple report of the test results. This is useful for developers or those who want to ensure their system is setup correctly. set-env Module setting overrides global This option accepts a space-separated set of values, where the first value is the environment variable to set, and the rest of the values is what you want the variable set to. For example, to set the variable RONALD to McDonald, you would put in the appropriate section this command: set-env RONALD McDonald This option is special in that it can be repeated without overriding earlier set-env settings in the same section of the configuration file. This way you can set more than one environment variable per module (or globally). source-dir Module setting overrides global This option is used to set the directory on your computer to store the &kde; &subversion; sources at. If you do not specify this value, the default is ~/kdesrc. You may use the tilde (~) to represent the home directory if using this option. ssh-identity-file Cannot be overridden Set this option to control which private SSH key file is passed to the ssh-add command when &kdesrc-build; is downloading source code from repositories that require authentication. See also: . This option was added in version 1.14.2. stop-on-failure Module setting overrides global Set this option value to true to cause the script to stop execution after an error occurs during the build or install process. This option is off by default. svn-server Module setting overrides global This option is used to set the server used to check out from &subversion;. The default is the anonymous &subversion; repository, svn://anonsvn.kde.org/ If you are developing for KDE, use the &subversion; repository that was provided to you when you received your developer account, instead of the anonymous repository. tag Module setting overrides global Use this option to download a specific release of a module. Note: The odds are very good that you do not want to use this option. &kde; releases are available in tarball form from the &kde; download site. This option has only been supported for git-based modules since &kdesrc-build; 1.16. use-clean-install Module setting overrides global (build system option) Set this option to true in order to have &kdesrc-build; run make uninstall directly before running make install. This can be useful in ensuring that there are not stray old library files, &cmake; metadata, etc. that can cause issues in long-lived &kde; installations. However this only works on build systems that support make uninstall. This option was added with &kdesrc-build; 1.12, but was not documented until &kdesrc-build; 1.16. use-cmake This option was removed in &kdesrc-build; 1.4 as all &kde; 4 modules require &cmake;, and &cmake; use is not permitted on any other modules. use-idle-io-priority Cannot be overridden This option, added in &kdesrc-build; 1.12, will cause a lower priority to be used for disk and other I/O usage, which can significantly improve the responsiveness of the rest of the system at the expense of slightly longer running times for &kdesrc-build;. The default is to be disabled, to enable the lower disk priority set this to true. use-modules Can only use in module-set This option, added in &kdesrc-build; 1.12.1, allows you to easily specify many different modules to build at the same point in the configuration file. This option must be used within a module-set. Every identifier passed to this option is internally converted to a &kdesrc-build; module, with a option set to the module-set's repository combined with the identifier name in order to setup the final repository to download from. All other options that are assigned in the module-set are also copied to the generated modules unaltered. The order that modules are defined in this option is important, because that is also the order that &kdesrc-build; will process the generated modules when updating, building, and installing. All modules defined in the given module-set will be handled before &kdesrc-build; moves to the next module after the module-set. If you need to change the options for a generated module, simply declare the module again after it is defined in the module-set, and set your options as needed. Although you will change the options set for the module this way, the module will still be updated and built in the order set by the module-set (i.e. you can't reorder the build sequence doing this). The name to use for the module if you do this is simply the name that you passed to , with the exception that any .git is removed. See and git-repository-base for a description of its use and an example. use-qt-builddir-hack Module setting overrides global This option has been removed due to improvements in the &Qt; build system. use-stable-kde Can't be overridden This option is deprecated and will be removed (again) in a future release. Please use the instead, which offers more selectivity.
Command Line Options and Environment Variables Command Line Usage &kdesrc-build; is designed to be run as follows: kdesrc-build --options modules to build If no modules to build are specified on the command line, then kdesrc-build will build all modules defined in its configuration file, in the order listed in that file (although this can be modified by various configuration file options). Commonly used command line options The full list of command line options is given in . The most-commonly used options include: (or ) This option causes &kdesrc-build; to indicate what actions it would take, without actually really implementing them. This can be useful to make sure that the modules you think you are building will actually get built. This option forces &kdesrc-build; to build the given modules from an absolutely fresh start point. Any existing build directory for that module is removed and it is rebuilt. This option is useful if you have errors building a module, and sometimes is required when &Qt; or &kde; libraries change. This option skips the source update process. You might use it if you have very recently updated the source code (perhaps you did it manually or recently ran &kdesrc-build;) but still want to rebuild some modules. This option is similar to above, but this time the build process is skipped. Specifying modules to build In general, specifying modules to build is as simple as passing their module name as you defined it in the configuration file. You can also pass modules that are part of a module set, either as named on use-modules, or the name of the entire module set itself, if you have given it a name. In the specific case of module sets based against the KDE project database, &kdesrc-build; will expand module name components to determine the exact module you want. For example, &kdesrc-build;'s KDE project entry locates the project in extragear/utils/kdesrc-build. You could specify any of the following to build &kdesrc-build;: % kdesrc-build % kdesrc-build % kdesrc-build The commands in the previous example preceded the module-name with a +. This forces the module name to be interpreted as a module from the KDE project database, even if that module hasn't been defined in your configuration file. Be careful about specifying very generic projects (e.g. extragear/utils by itself), as this can lead to a large amount of modules being built. You should use the option before building a new module set to ensure it is only building the modules you want. Supported Environment Variables &kdesrc-build; does not use environment variables. If you need to set environment variables for the build or install process, please see the set-env option. Supported command-line parameters The script accepts the following command-line options: --async Enables the asynchronous mode, which can perform the source code updates and module builds at the same time. This is the default, this option only needs specified if you have disabled it in the configuration. --help Only display simple help on this script. --version (or -v) Display the program version. --show-info Displays information about &kdesrc-build; and the operating system, that may prove useful in bug reports or when asking for help in forums or mailing lists. Available since version 18.11. --initial-setup Has &kdesrc-build; perform the one-time initial setup necessary to prepare the system for &kdesrc-build; to operate, and for the newly-installed &kde; software to run. This includes: Installing known dependencies (on supported &Linux; distributions) Adding required environment variables to ~/.bashrc Setting up a configuration file Available since version 18.11. --author Display contact information for the author. --color Enable colorful output. (This is the default for interactive terminals). --nice=value This value adjusts the computer CPU priority requested by &kdesrc-build;, and should be in the range of 0-20. 0 is highest priority (because it is the least nice), 20 is lowest priority. &kdesrc-build; defaults to 10. --no-async Disables the asynchronous mode of updating. Instead the update will be performed in its entirety before the build starts. This option will slow down the overall process, but if you encounter IPC errors while running &kdesrc-build; try using this option, and submitting a bug report. --no-color Disable colorful output. --pretend (or -p) &kdesrc-build; will run through the update and build process, but instead of performing any actions to update or build, will instead output what the script would have done (e.g. what commands to run, general steps being taken, etc.). Simple read-only commands (such as reading file information) may still be run to make the output more relevant (such as correctly simulating whether source code would be checked out or updated). This option requires that some needed metadata is available, which is normally automatically downloaded, but downloads are disabled in pretend mode. If you've never run &kdesrc-build; (and therefore, don't have this metadata), you should run kdesrc-build to download the required metadata first. --quiet (or -q) Do not be as noisy with the output. With this switch only the basics are output. --really-quiet Only output warnings and errors. --verbose Be very descriptive about what is going on, and what &kdesrc-build; is doing. --src-only (or --svn-only) Only perform the source update. (The --svn-only is only supported for compatibility with older scripts). --build-only Only perform the build process. --install-only Only perform the install process. --metadata-only Only perform the metadata download process. &kdesrc-build; normally handles this automatically, but you might manually use this to allow the command line option to work. --rebuild-failures Use this option to build only those modules which failed to build on a previous &kdesrc-build; run. This is useful if a significant number of failures occurred mixed with successful builds. After fixing the issue causing the build failures you can then easily build only the modules that failed previously. Note that the list of previously-failed modules is reset every time a &kdesrc-build; run finishes with some module failures. However it is not reset by a completely successful build, so you can successfully rebuild a module or two and this flag will still work. This option was added for &kdesrc-build; 15.09. --ignore-modules Do not include the modules passed on the rest of the command line in the update/build process (this is useful if you want to build most of the modules in your configuration file and just skip a few). --no-src (or --no-svn) Skip contacting the &subversion; server. (The --no-svn parameter is only supported for compatibility with older versions of the script). --no-build Skip the build process. --no-metadata Do not automatically download the extra metadata needed for &kde; git modules. The source updates for the modules themselves will still occur unless you pass --no-src as well. This can be useful if you are frequently re-running &kdesrc-build; since the metadata does not change very often. But note that many other features require the metadata to be available. You might want to consider running &kdesrc-build; with the --metadata-only option one time and then using this option for subsequent runs. --no-install Do not automatically install packages after they are built. --no-build-when-unchanged --force-build This option explicitly disables skipping the build process (an optimization controlled by the build-when-unchanged option). This is useful for making &kdesrc-build; run the build when you have changed something that &kdesrc-build; cannot check. --force-build performs the exact same function, and is perhaps easier to remember. --debug Enables debug mode for the script. Currently this means that all output will be dumped to the standard output in addition to being logged in the log directory like normal. Also, many functions are much more verbose about what they are doing in debugging mode. --query=mode This command causes &kdesrc-build; to query a parameter of the modules in the build list (either passed on the command line or read in from the configuration file), outputting the result to screen (one module per line). This option must be provided with a query mode, which should be one of the following: , which causes &kdesrc-build; to output the full path to where the module's source code is stored. , which causes &kdesrc-build; to output the full path to where the module build process occurs. , which causes &kdesrc-build; to output the full path to where the module will be installed. , which causes &kdesrc-build; to output the location of the module within the hierarchy of KDE source code repositories. See for more information on this hierarchy. , which causes &kdesrc-build; to output the resolved git branch that will be used for each module, based on the tag, branch and branch-group settings in effect. Otherwise, option names that are valid for modules in the configuration file can be used, the resolved value of which will be listed for each module. If a single module is passed on the command line, then the output is simply the value of the parameter being queried. If multiple (or no) modules are passed on the command line, then each line is prefixed by the name of the module. Either way, &kdesrc-build; stops running once each value is output. This option was added with &kdesrc-build; 16.05. For example, the command kdesrc-build --query branch kactivities kdepim might end up with output like: kactivities: master kdepim: master --no-rebuild-on-fail Do not try to rebuild modules that have failed building from scratch. &kdesrc-build; will never try to do this to a module that already was tried to be built from scratch. --refresh-build Recreate the build system and make from scratch. --reconfigure Run cmake (for &kde; modules) or configure (for &Qt;) again, without cleaning the build directory. You should not normally have to specify this, as &kdesrc-build; will detect when you change the relevant options and automatically re-run the build setup. This option is implied if --refresh-build is used. --resume-from This option is used to resume the build starting from the given module, which should be the next option on the command line. You should not specify other module names on the command line. This option formerly added --no-src, but does not any longer (since &kdesrc-build; 1.13). If you want to avoid source updates when resuming, simply pass in addition to the other options. See also: and . You would prefer to use this command line option if you have fixed the build error and want &kdesrc-build; to complete the build. --resume-after This option is used to resume the build starting after the given module, which should be the next option on the command line. You should not specify other module names on the command line. This option formerly added --no-src, but does not any longer (since &kdesrc-build; 1.13). If you want to avoid source updates when resuming, simply pass in addition to the other options. See also: and . You would prefer to use this command line option if you have fixed the build error and have also built and installed the module yourself, and want &kdesrc-build; to start again with the next module. --resume This option can be used to run &kdesrc-build; after it has had a build failure. It resumes the build from the module that failed, using the list of modules that were waiting to be built before, and disables source and metadata updates as well. The use case is when a simple mistake or missing dependency causes the build failure. Once you correct the error you can quickly get back into building the modules you were building before, without fiddling with and . This is even handier with the command line argument, especially if you're initially setting up your development environment. This option was added with &kdesrc-build; 1.16. --stop-before This command line option is used to stop the normal build process just before a module would ordinarily be built. For example, if the normal build list was moduleAmoduleBmoduleC, then would cause &kdesrc-build; to only build moduleA. This command line option was added with &kdesrc-build; 1.16. --stop-after This command line option is used to stop the normal build process just after a module would ordinarily be built. For example, if the normal build list was moduleAmoduleBmoduleC, then would cause &kdesrc-build; to build moduleA and moduleB. This command line option was added with &kdesrc-build; 1.16. --stop-on-failure This option causes the build to abort as soon as a failure occurs. Useful when you're setting up your initial development environment. Without this flag, &kdesrc-build; will try to press on with the rest of the modules in the build to avoid wasting time in case the problem is with a single module. This option was added with &kdesrc-build; 1.16. See also the stop-on-failure option. --rc-file This interprets the next command line parameter as the file to read the configuration options from. The default value for this parameter is kdesrc-buildrc (checked in the current directory) if it is present, or ~/.kdesrc-buildrc otherwise. See also . --print-modules Takes all actions up to and including dependency reordering of the modules specified on the command line (or configuration file), prints the modules that would be processed one per line, and then exits without further action. The kde-project metadata is downloaded first (though, see or ). The output is not fully compatible with usage by scripts as other output messages may be generated until the module list is shown. This is mostly just useful for quickly determining what &kdesrc-build; understands a module's dependencies to be, which means it's only useful for kde-projects modules. This option is also compatible with , , , . --run This option interprets the next item on the command line as a program to run, and &kdesrc-build; will then finish reading the configuration file, update the environment as normal, and then execute the given program. This will not work to start a shell with the &kdesrc-build; environment in most cases however, since interactive shells typically reset at least part of the environment variables (such as PATH and KDEDIRS) in the startup sequence. If you want to see the environment used by &kdesrc-build;, you can run the printenv command: $ kdesrc-build --run printenv KDE_SESSION_VERSION=4 SDL_AUDIODRIVER=alsa LANGUAGE= XCURSOR_THEME=Oxygen_Blue LESS=-R -M --shift 5 QMAIL_CONTROLDIR=/var/qmail/control ... etc. --prefix=</path/to/kde> This allows you to change the directory that &kde; will be installed to from the command line. This option implies --reconfigure, but using --refresh-build may still be required. --revision This option causes &kdesrc-build; to checkout a specific numbered revision for each &subversion; module, overriding any branch, tag, or revision options already set for these modules. This option is likely not a good idea, and is only supported for compatibility with older scripts. --build-system-only This option causes &kdesrc-build; to abort building a module just before the make command would have been run. This is supported for compatibility with older versions only, this effect is not helpful for the current &kde; build system. --install If this is the only command-line option, it tries to install all of the modules contained in log/latest/build-status. If command-line options are specified after --install, they are all assumed to be modules to install (even if they did not successfully build on the last run). --no-snapshots Supplying this option causes &kdesrc-build; to always perform a normal initial checkout of a module instead of using a quick-start snapshot (only available for Git modules from the kde-projects repository). Note that this option should only be used if there is a failure using snapshots, as the quick-start snapshot reduces load on the KDE source repositories. Module snapshots are real checkouts. You should not need to specify this option, it is only a troubleshooting aid. --delete-my-patches This option is used to let &kdesrc-build; delete source directories that may contain user data, so that the module can be re-downloaded. This would normally only be useful for &kde; developers (who might have local changes that would be deleted). This is currently only used to checkout modules that have been converted from &subversion; to &git;. You should not use this option normally, &kdesrc-build; will prompt to be re-run with it if it is needed. --delete-my-settings This option is used to let &kdesrc-build; overwrite existing files which may contain user data. This is currently only used for xsession setup for the login manager. You should not use this option normally, &kdesrc-build; will prompt to be re-run with it if it is needed. --<option-name>= You can use this option to override an option in your configuration file for every module. For instance, to override the log-dir option, you would do: --log-dir=/path/to/dir. This feature can only be used for option names already recognized by &kdesrc-build;, that are not already supported by relevant command line options. For example the async configuration file option has specific --async and --no-async command line options that are preferred by &kdesrc-build;. --set-module-option-value=<module-name>,<option-name>,<option-value> You can use this option to override an option in your configuration file for a specific module. Any other command-line options are assumed to be modules to update and build. Please, do not mix building with installing. Using &kdesrc-build; Preface Normally using &kdesrc-build; after you have gone through is as easy as doing the following from a terminal prompt: % kdesrc-build &kdesrc-build; will then download the sources for &kde;, try to configure and build them, and then install them. Read on to discover how &kdesrc-build; does this, and what else you can do with this tool. Basic &kdesrc-build; features qt support &kdesrc-build; supports building the &Qt; toolkit used by &kde; software as a convenience to users. This support is handled by a special module named qt. &Qt; is developed under a separate repository from &kde; software located at http://code.qt.io/cgit/qt/. In order to build &Qt;, you should make sure that the qtdir setting is set to the directory you'd like to install &Qt; to, as described in . You should then ensure that the qt module is added to your .kdesrc-buildrc, before any other modules in the file. If you are using the sample configuration file, you can simply uncomment the existing qt module entry. Now you should verify the repository option and branch options are set appropriately: The first option is to build &Qt; using a mirror maintained on the &kde; source repositories (no other changes are applied, it is simply a clone of the official source). This is highly recommended due to occasional issues with cloning the full &Qt; module from its official repository. You can set the option for the qt module to kde:qt to use this option. Otherwise, to build the standard &Qt;, set your option to git://gitorious.org/qt/qt.git. Note that you may experience problems performing the initial clone of &Qt; from this repository. In both cases, the branch option should be set to master (unless you'd like to build a different branch). Standard flags added by &kdesrc-build; To save you time, &kdesrc-build; adds some standard paths to your environment for you: The path to the &kde; and &Qt; libraries is added to the LD_LIBRARY_PATH variable automatically. This means that you do not need to edit &libpath; to include them. The path to the &kde; and &Qt; development support programs are added to the PATH variable automatically. This means that you do not need to edit &binpath; to include them. The path to the &kde;-provided pkg-config is added automatically to PKG_CONFIG_PATH. This means that you do not need to use &set-env; to add these. The setting for &kdedir; is automatically propagated to the KDEDIR environment variable while building. (KDEDIRS is not affected). The setting for &qtdir; is automatically propagated to the QTDIR environment variable while building. Changing &kdesrc-build;'s build priority Programs can run with different priority levels on Operating Systems, including &Linux; and &BSD;. This allows the system to allocate time for the different programs in accordance with how important they are. &kdesrc-build; will normally allocate itself a low priority so that the rest of the programs on your system are unaffected and can run normally. Using this technique, &kdesrc-build; will use extra CPU when it is available. &kdesrc-build; will still maintain a high enough priority level so that it runs before routine batch processes and before CPU donation programs such as Seti@Home. To alter &kdesrc-build; so that it uses a higher (or lower) priority level permanently, then you need to adjust the &niceness; setting in the configuration file. The &niceness; setting controls how nice &kdesrc-build; is to other programs. In other words, having a higher &niceness; gives &kdesrc-build; a lower priority. So to give &kdesrc-build; a higher priority, reduce the &niceness; (and vice versa). The &niceness; can go from 0 (not nice at all, highest priority) to 20 (super nice, lowest priority). You can also temporarily change the priority for &kdesrc-build; by using the &cmd-nice; command line option. The value to the option is used exactly the same as for &niceness;. It is possible for some programs run by the super user to have a negative nice value, with a correspondingly even higher priority for such programs. Setting a negative (or even 0) &niceness; for &kdesrc-build; is not a great idea, as it will not help run time significantly, but will make your computer seem very sluggish should you still need to use it. To run &kdesrc-build; with a niceness of 15 (a lower priority than normal): % kdesrc-build Or, you can edit the configuration file to make the change permanent: &niceness; 15 The niceness option only affects the usage of the computer's processor(s). One other major affect on computer performance relates to how much data input or output (I/O) a program uses. In order to control how much I/O a program can use, modern &Linux; operating systems support a similar tool called ionice. &kdesrc-build; supports ionice, (but only to enable or disable it completely) using the use-idle-io-priority option, since &kdesrc-build; version 1.12. Installation as the superuser You may wish to have &kdesrc-build; run the installation with super user privileges. This may be for the unrecommended system-wide installation. This is also useful when using a recommended single user &kde; build, however. This is because some modules (especially kdebase) install programs that will briefly need elevated permissions when run. They are not able to achieve these permission levels unless they are installed with the elevated permissions. You could simply run &kdesrc-build; as the super user directly, but this is not recommended, since the program has not been audited for that kind of use. Although it should be safe to run the program in this fashion, it is better to avoid running as the super user when possible. To take care of this, &kdesrc-build; provides the &make-install-prefix; option. You can use this option to specify a command to use to perform the installation as another user. The recommended way to use this command is with the &sudo; program, which will run the install command as the super user. For example, to install all modules using &sudo;, you could do something like this: global &make-install-prefix; sudo # Other options end global To use &make-install-prefix; for only a single module, this would work: module svn-module-name &make-install-prefix; sudo end module Showing the progress of a module build This feature is always available, and is automatically enabled when possible. What this does is display an estimated build progress while building a module; that way you know about how much longer it will take to build a module. Advanced features Partially building a module It is possible to build only pieces from a single &kde; module. For example, you may want to compile only one program from a module. &kdesrc-build; has features to make this easy. There are several complementing ways to do this. Checking out portions of a module This is perhaps the best way to do this. When it works, it will save you download time and disk space. What happens is that &kdesrc-build; will download only the parts of a module that you specify. This is done using the &checkout-only; option for a module, which will specify a list of directories to download. If you do not already know what to download from a module, it may be a good idea to browse the &subversion; layout for a module first, using WebSVN. To only grab &kuser; and KSystemLog from kdeadmin, you could use &checkout-only; like this: module kdeadmin &checkout-only; kuser ksystemlog end module The directories will be built in the order they are listed in the option. If one of the directories needs something else from the module to compile, then you need to make sure they are both in the &checkout-only; line, and that the required dependency goes before the directory that needs it. Also, sometimes an application may need other directories and it is hard to figure out what they are, which may require some trial and error of constantly adding directories to the option to figure out. This option depends on support from the build system of the module, so it is only useful for modules that are collections of individual applications. One final note to make about this option: If you change the value of this option, you should use kdesrc-build in order to ensure that the module is reconfigured properly. In addition, &kdesrc-build; will never remove existing files if you take away the number of directories from your &checkout-only; option, or add the option to a module that has already been checked out. Removing directories from a build Instead of restricting what is downloaded, it is possible to download everything but have the build system leave out a few directories when it does the build. This may be useful if one directory always breaks and is unnecessary to the rest of the module. This is controlled with the &do-not-compile; option. It works similar to the &checkout-only; option just described, in that it is simply a list of directories that should not be compiled. Also like &checkout-only;, this option requires at least that the build system for the module is reconfigured after changing it. This is done using the kdesrc-build command. To remove the python directory from the kdebindings build process: module kdebindings &do-not-compile; python end module This function depends on some standard conventions used in most &kde; modules. Therefore it may not work for all programs. Branching and tagging support for &kdesrc-build; What are branches and tags? &subversion; supports managing the history of the &kde; source code. &kde; uses this support to create branches for development, and to tag the repository every so often with a new version release. For example, the &kmail; developers may be working on a new feature in a different branch in order to avoid breaking the version being used by most developers. This branch has development ongoing inside it, even while the main branch (called /trunk) may have development going on inside of it. A tag, on the other hand, is a snapshot of the source code repository at a position in time. This is used by the &kde; administration team to mark off a version of code suitable for release and still allow the developers to work on the code. In &subversion;, there is no difference between branches, tags, or trunk within the code. It is only a convention used by the developers. This makes it difficult to properly support branches and tags within &kdesrc-build;. However, there are some things that can be done. How to use branches and tags Support for branches and tags is handled by a set of options, which range from a generic request for a version, to a specific &url; to download for advanced users. The easiest method is to use the &branch; and &tag; options. You simply use the option along with the name of the desired branch or tag for a module, and &kdesrc-build; will try to determine the appropriate location within the &kde; repository to download from. For most &kde; modules this works very well. To download kdelibs from &kde; 4.6 (which is simply known as the 4.6 branch): module kdelibs branch 4.6 # other options... end module Or, to download kdemultimedia as it was released with &kde; 4.6.1: module kdemultimedia tag 4.6.1 # other options... end module You can specify a global branch value. But if you do so, do not forget to specify a different branch for modules that should not use the global branch! Advanced branch support options &kdesrc-build; supports two options for situations where &branch; and &tag; guess the correct path improperly: &module-base-path; and &override-url;. &module-base-path; is used to help &kdesrc-build; fill in the missing part of a module's path. In the &kde; repository, all of the paths are of the form svnRoot/module-base-path/module-name. Normally &kdesrc-build; can figure out the appropriate middle part by itself. When it cannot, you can use &module-base-path;, like this: module kdesupport # kdesupport supports various tags to easily organize the required # software for a given KDE Platform release. module-base-path tags/kdesupport-for-4.5 end module This would cause &kdesrc-build; to download kdesupport from (in this example), svn://anonsvn.kde.org/home/kde/tags/kdesupport-for-4.5. In previous versions of &kdesrc-build;, the &module-base-path; was handled differently. If you encounter trouble using an old module-base-path definition perhaps you should verify that the actual path is as &kdesrc-build; expects by using the --pretend option. The &override-url; option, on the other hand, requires you to specify the exact path to download from. However, this allows you to pull from paths that previous versions of &kdesrc-build; would have no hope of downloading from. Currently, the &module-base-path; option should be sufficient for any Subversion source URL. &kdesrc-build; will not touch or correct the value you specify for &override-url; at all, so if you change your &svn-server; setting, you may need to update this as well. How &kdesrc-build; tries to ensure a successful build Automatic rebuilds &kdesrc-build; used to include features to automatically attempt to rebuild the module after a failure (as sometimes this re-attempt would work, due to bugs in the build system at that time). Thanks to switching to &cmake; the build system no longer suffers from these bugs, and so &kdesrc-build; will not try to build a module more than once. There are situations where &kdesrc-build; will automatically take action though: If you change configure-flags or cmake-options for a module, then &kdesrc-build; will detect that and automatically re-run configure or cmake for that module. If the buildsystem does not exist (even if &kdesrc-build; did not delete it) then &kdesrc-build; will automatically re-create it. This is useful to allow for performing a full --refresh-build for a specific module without having that performed on other modules. Manually rebuilding a module If you make a change to a module's option settings, or the module's source code changes in a way &kdesrc-build; does not recognize, you may need to manually rebuild the module. You can do this by simply running kdesrc-build . If you would like to have &kdesrc-build; automatically rebuild the module during the next normal build update instead, you can create a special file. Every module has a build directory. If you create a file called .refresh-me in the build directory for a module, &kdesrc-build; will rebuild the module next time the build process occurs, even if it would normally perform the faster incremental build. By default, the build directory is ~/kdesrc/build/module/. If you change the setting of the &build-dir; option, then use that instead of ~/kdesrc/build. Rebuild using .refresh-me for module kdelibs: % touch ~/kdesrc/build/kdelibs/.refresh-me % kdesrc-build Changing environment variable settings Normally &kdesrc-build; uses the environment that is present when starting up when running programs to perform updates and builds. This is useful for when you are running &kdesrc-build; from the command line. However, you may want to change the setting for environment variables that &kdesrc-build; does not provide an option for directly. (For instance, to setup any required environment variables when running &kdesrc-build; on a timer such as &cron;) This is possible with the &set-env; option. Unlike most options, it can be set more than once, and it accepts two entries, separated by a space. The first one is the name of the environment variable to set, and the remainder of the line is the value. Set DISTRO=BSD for all modules: global set-env DISTRO BSD end global Resuming builds Resuming a failed or canceled build You can tell &kdesrc-build; to start building from a different module than it normally would. This can be useful when a set of modules failed, or if you canceled a build run in the middle. You can control this using the &cmd-resume-from; option and the &cmd-resume-after; option. Older versions of &kdesrc-build; would skip the source update when resuming a build. This is no longer done by default, but you can always use the command line option to skip the source update. Resuming the build starting from kdebase: % kdesrc-build Resuming the build starting after kdebase (in case you manually fixed the issue and installed the module yourself): % kdesrc-build If the last &kdesrc-build; build ended with a build failure, you can also use the --resume command line option, which resumes the last build starting at the module that failed. The source and metadata updates are skipped as well (but if you need these, it's generally better to use --resume-from instead). Ignoring modules in a build Similar to the way you can resume the build from a module, you can instead choose to update and build everything normally, but ignore a set of modules. You can do this using the &cmd-ignore-modules; option. This option tells &kdesrc-build; to ignore all the modules on the command line when performing the update and build. Ignoring extragear/multimedia and kdereview during a full run: % kdesrc-build extragear/multimedia kdereview Changing options from the command line Changing global options You can change the setting of options read from the configuration file directly from the command line. This change will override the configuration file setting, but is only temporary. It only takes effect as long as it is still present on the command line. &kdesrc-build; allows you to change options named like option-name by passing an argument on the command line in the form . &kdesrc-build; will recognize whether it does not know what the option is, and search for the name in its list of option names. If it does not recognize the name, it will warn you, otherwise it will remember the value you set it to and override any setting from the configuration file. Setting the &source-dir; option to /dev/null for testing: % kdesrc-build Changing module options It is also possible to change options only for a specific module. The syntax is similar: --module,option-name=value. This change overrides any duplicate setting for the module found in the configuration file, and applies only while the option is passed on the command line. Using a different build directory for the kdeedu module: % kdesrc-build Features for &kde; developers &ssh; Agent checks &kdesrc-build; can ensure that &kde; developers that use &ssh; to access the &kde; source repository do not accidentally forget to leave the &ssh; Agent tool enabled. This can cause &kdesrc-build; to hang indefinitely waiting for the developer to type in their &ssh; password, so by default &kdesrc-build; will check if the Agent is running before performing source updates. This is only done for &kde; developers using &ssh;. This is because no password is required for the default anonymous checkout. &subversion; will handle passwords for the second possible protocol for &kde; developers, https. You may wish to disable the &ssh; Agent check, in case of situations where &kdesrc-build; is mis-detecting the presence of an agent. To disable the agent check, set the option to true. Disabling the &ssh; agent check: global disable-agent-check true end global Other &kdesrc-build; features Changing the amount of output from &kdesrc-build; &kdesrc-build; has several options to control the amount of output the script generates. In any case, errors will always be output. The option (short form is ) causes &kdesrc-build; to be mostly silent. Only important messages, warnings, or errors will be shown. When available, build progress information is still shown. The option (no short form) causes &kdesrc-build; to only display important warnings or errors while it is running. The option (short form is ) causes &kdesrc-build; to be very detailed in its output. The option is for debugging purposes only, it causes &kdesrc-build; to act as if was turned on, causes commands to also output to the terminal, and will display debugging information for many functions. Color output When being run from &konsole; or a different terminal, &kdesrc-build; will normally display with colorized text. You can disable this by using the on the command line, or by setting the &colorful-output; option in the configuration file to false. Disabling color output in the configuration file: global colorful-output false end global Removing unneeded directories after a build Are you short on disk space but still want to run a bleeding-edge &kde; checkout? &kdesrc-build; can help reduce your disk usage when building &kde; from &subversion;. Be aware that building &kde; does take a lot of space. There are several major space-using pieces when using &kdesrc-build;: The actual source checkout can take up a fair amount of space. The default modules take up about 1.6 gigabytes of on-disk space. You can reduce this amount by making sure that you are only building as many modules as you actually want. &kdesrc-build; will not delete source code from disk even if you delete the entry from the configuration file, so make sure that you go and delete unused source checkouts from the source directory. Note that the source files are downloaded from the Internet, you should not delete them if you are actually using them, at least until you are done using &kdesrc-build;. Also, if you already have a &Qt; installed by your distribution (and the odds are good that you do), you probably do not need to install the qt module. That will shave about 200 megabytes off of the on-disk source size. One thing to note is that due to the way &subversion; works: there are actually two files on disk for every file checked-out from the repository. &kdesrc-build; does not have code at this point to try and minimize the source size when the source is not being used. &kdesrc-build; will create a separate build directory to build the source code in. Sometimes &kdesrc-build; will have to copy a source directory to create a fake build directory. When this happens, space-saving symlinks are used, so this should not be a hassle on disk space. The build directory will typically be much larger than the source directory for a module. For example, the build directory for kdebase is about 1050 megabytes, whereas kdebase's source is only around 550 megabytes. Luckily, the build directory is not required after a module has successfully been built and installed. &kdesrc-build; can automatically remove the build directory after installing a module, see the examples below for more information. Note that taking this step will make it impossible for &kdesrc-build; to perform the time-saving incremental builds. Finally, there is disk space required for the actual installation of &kde;, which does not run from the build directory. This typically takes less space than the build directory. It is harder to get exact figures however. How do you reduce the space requirements of &kde;? One way is to use the proper compiler flags, to optimize for space reduction instead of for speed. Another way, which can have a large effect, is to remove debugging information from your &kde; build. You should be very sure you know what you are doing before deciding to remove debugging information. Running bleeding-edge software means you are running software which is potentially much more likely to crash than a stable release. If you are running software without debugging information, it can be very hard to create a good bug report to get your bug resolved, and you will likely have to re-enable debugging information for the affected application and rebuild to help a developer fix the crash. So, remove debugging information at your own risk! Removing the build directory after installation of a module. The source directory is still kept, and debugging is enabled: global configure-flags --enable-debug remove-after-install builddir # Remove build directory after install end global Removing the build directory after installation, without debugging information, with size optimization. global cxxflags -Os # Optimize for size configure-flags --disable-debug remove-after-install builddir # Remove build directory after install end global &cmake;, the &kde; build system Introduction to &cmake; In March 2006, the &cmake; program beat out several competitors and was selected to be the build system for &kde; 4, replacing the autotools-based system that &kde; had used from the beginning. A introduction to &cmake; page is available on the &kde; Community Wiki. Basically, instead of running make Makefile.cvs, then configure, then &make;, we simply run &cmake; and then &make;. &kdesrc-build; has support for &cmake;. A few features of &kdesrc-build; were really features of the underlying buildsystem, including configure-flags and do-not-compile. When equivalent features are available, they are provided. For instance, the equivalent to the configure-flags option is cmake-options, and the do-not-compile option is also supported for &cmake; as of &kdesrc-build; version 1.6.3. Credits And License &underFDL; &kde; modules and source code organization The <quote>Module</quote> &kde; groups its software into modules of various size. This was initially a loose grouping of a few large modules, but with the introduction of the Git-based source code repositories, these large modules were further split into many smaller modules. &kdesrc-build; uses this module concept as well. In essence, a module is a grouping of code that can be downloaded, built, tested, and installed. Individual modules It is easy to set &kdesrc-build; to build a single module. The following listing is an example of what a declaration for a Subversion-based module would look like in the configuration file. module kdefoo end module This is a Subversion-based module since it doesn't use a repository option. Also, the option is listed as an example only, it is not required. Groups of related modules Now most &kde; source modules are Git-based &kde;, and are normally combined into groups of modules. &kdesrc-build; therefore supports groups of modules as well, using module sets. An example: module-set base-modules kde-projects kde-runtime kde-workspace kde-baseapps end module-set You can leave the module set name (base-modules in this case) empty if you like. This setting tells &kdesrc-build; where to download the source from, but you can also use a git:// URL. One special feature of the kde-projects is that &kdesrc-build; will automatically include any Git modules that are grouped under the modules you list (in the KDE Project database). Module <quote>branch groups</quote> Taking the concept of a group of modules further, the &kde; developers eventually found that synchronizing the names of the Git branches across a large number of repositories was getting difficult, especially during the development push for the new &kde; Frameworks for &Qt; 5. So the concept of branch groups was developed, to allow users and developers to select one of only a few groups, and allow the script to automatically select the appropriate Git branch. &kdesrc-build; supports this feature as of version 1.16-pre2, via the branch-group option. Example of using branch-group branch-group can be used in the configuration file as follows: global # Select KDE Frameworks 5 and other Qt5-based apps kf5-qt5 # Other global options here ... end global module-set # branch-group only works for kde-projects kde-projects # branch-group is inherited from the one set globally, but could # specified here. kdelibs kde-workspace end module-set # kdelibs's branch will be "frameworks" # kde-workspace's branch will be "master" (as of August 2013) In this case the same branch-group gives different branch names for each Git module. This feature requires some data maintained by the &kde; developers in a Git repository named kde-build-metadata, however this module will be included automatically by &kdesrc-build; (though you may see it appear in the script output). &kde; modules that do not have a set branch name for the branch group you choose will default to an appropriate branch name, as if you had not specified branch-group at all. Superseded profile setup procedures Setting up a &kde; login profile These instructions cover how to setup the profile required to ensure your computer can login to your newly-built &kde; &plasma; desktop. &kdesrc-build; will normally try to do this automatically (see ). This appendix section can be useful for those who cannot use &kdesrc-build;'s support for login profile setup. However the instructions may not always be up-to-date, it can also be useful to consult the kde-env-master.sh file included with the &kdesrc-build; source. Changing your startup profile settings The .bash_profile is the login settings file for the popular bash shell used by many &Linux; distributions. If you use a different shell, then you may need to adjust the samples given in this section for your particular shell. Open or create the .bash_profile file in the home directory with your favorite editor, and add to the end of the file: If you are building the qt module (you are by default), add instead: QTDIR=(path to qtdir) # Such as ~/kdesrc/build/qt by default. KDEDIR=(path to kdedir) # Such as ~/kde by default. KDEDIRS=$KDEDIR PATH=$KDEDIR/bin:$QTDIR/bin:$PATH MANPATH=$QTDIR/doc/man:$MANPATH # Act appropriately if LD_LIBRARY_PATH is not already set. if [ -z $LD_LIBRARY_PATH ]; then LD_LIBRARY_PATH=$KDEDIR/lib:$QTDIR/lib else LD_LIBRARY_PATH=$KDEDIR/lib:$QTDIR/lib:$LD_LIBRARY_PATH fi export QTDIR KDEDIRS PATH MANPATH LD_LIBRARY_PATH or, if you are not building qt (and are using your system &Qt; instead), add this instead: KDEDIR=(path to kdedir) # Such as ~/kde by default. KDEDIRS=$KDEDIR PATH=$KDEDIR/bin:$QTDIR/bin:$PATH # Act appropriately if LD_LIBRARY_PATH is not already set. if [ -z $LD_LIBRARY_PATH ]; then LD_LIBRARY_PATH=$KDEDIR/lib else LD_LIBRARY_PATH=$KDEDIR/lib:$LD_LIBRARY_PATH fi export KDEDIRS PATH LD_LIBRARY_PATH If you are not using a dedicated user, set a different $KDEHOME for your new environment in your .bash_profile: export KDEHOME="${HOME}/.kde-svn" # Create it if needed [ ! -e ~/.kde-svn ] && mkdir ~/.kde-svn If later your K Menu is empty or too crowded with applications from your distribution, you may have to set the XDG environment variables in your .bash_profile: XDG_CONFIG_DIRS="/etc/xdg" XDG_DATA_DIRS="${KDEDIR}/share:/usr/share" export XDG_CONFIG_DIRS XDG_DATA_DIRS Starting &kde; Now that you have adjusted your environment settings to use the correct &kde;, it is important to ensure that the correct startkde script is used as well. Open the .xinitrc text file from the home directory, or create it if necessary. Add the line: exec On some distributions, it may be necessary to perform the same steps with the .xsession file, also in the home directory. This is especially true when using graphical login managers such as &kdm;, gdm, or xdm. Now start your fresh &kde;: in &BSD; and &Linux; systems with virtual terminal support, &Ctrl;&Alt;F1 ... &Ctrl;&Alt;F12 keystroke combinations are used to switch to Virtual Console 1 through 12. This allows you to run more than one desktop environment at the same time. The fist six are text terminals and the following six are graphical displays. If when you start your computer you are presented to the graphical display manager instead, you can use the new &kde; environment, even if it is not listed as an option. Most display managers, including &kdm;, have an option to use a Custom Session when you login. With this option, your session settings are loaded from the .xsession file in your home directory. If you have already modified this file as described above, this option should load you into your new &kde; installation. If it does not, there is something else you can try that should normally work: Press &Ctrl;&Alt;F2, and you will be presented to a text terminal. Log in using the dedicated user and type: startx You can run the &kde; from sources and the old &kde; at the same time! Log in using your regular user, start the stable &kde; desktop. Press &Ctrl;&Alt;F2 (or F1, F3, etc..), and you will be presented with a text terminal. Log in using the dedicated &kde; &subversion; user and type: startx You can go back to the &kde; desktop of your regular user by pressing the shortcut key for the already running desktop. This is normally &Ctrl;&Alt;F7, you may need to use F6 or F8 instead. To return to your &kdesrc-build;-compiled &kde;, you would use the same sequence, except with the next function key. For example, if you needed to enter &Ctrl;&Alt;F7 to switch to your regular &kde;, you would need to enter &Ctrl;&Alt;F8 to go back to your &kdesrc-build; &kde;.
diff --git a/kdesrc-build b/kdesrc-build index ab3f99a..badcea7 100755 --- a/kdesrc-build +++ b/kdesrc-build @@ -1,408 +1,316 @@ #!/usr/bin/env perl # Script to handle building KDE from source code. All of the configuration is # stored in the file ./kdesrc-buildrc (or ~/.kdesrc-buildrc, if that's not # present). # # Please also see the documentation that should be included with this program, # in the doc/ directory. # # Copyright © 2003 - 2018 Michael Pyne. # Home page: https://kdesrc-build.kde.org/ # # Copyright © 2005, 2006, 2008 - 2011 David Faure # Copyright © 2005 Thiago Macieira # Copyright © 2006 Stephan Kulow # Copyright © 2006, 2008 Dirk Mueller # ... and possibly others. Check the git source repository for specifics. # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # Adding an option? Grep for 'defaultGlobalOptions' in ksb::BuildContext --mpyne use 5.014; # Require Perl 5.14 use strict; use warnings; # "our" makes this a package-shared variable accessible outside of this package # by referring to $main::baseDataDir. our $baseDataDir; # where to find support files like modules and dependencies my $baseBinDir; # where to find kdesrc-build itself this run my $modPath; # Find our base directory to find modules and data under. On many # container-based distros, even FindBin is missing to conserve space. But we # can use File::Spec to do nearly the same. # These calls have to run when parsing (i.e. in BEGIN) to make the 'use lib' # below work (which itself implicitly uses BEGIN { }) BEGIN { use File::Spec; # resolve symlinks my $scriptPath = $0; for (1..16) { last unless -l $scriptPath; $scriptPath = readlink $scriptPath; } die "Too many symlinks followed looking for script" if -l $scriptPath; my ($volume, $directories, $script) = File::Spec->splitpath($scriptPath); my $baseDir = File::Spec->catpath($volume, $directories, ''); die "Couldn't find base directory!" unless $baseDir; $baseBinDir = File::Spec->rel2abs('.', $baseDir); # Use modules in git repo if running from git dir, otherwise assume # system install. if (-d "$baseDir/modules" && -e "$baseDir/kdesrc-build") { $baseDataDir = $baseBinDir; } elsif (-d "$baseDir/../share/kdesrc-build/modules") { $baseDataDir = File::Spec->rel2abs("../share/kdesrc-build", $baseDir); } $modPath = "$baseDataDir/modules"; die "Couldn't find modules for kdesrc-build from $baseDir!" unless -d $modPath; } use lib "$modPath"; # Make ksb:: modules available sub dumpError { my $err = $@; open my $fh, '>>', "error-$$.log" or return; my $time = localtime; say $fh $time; say $fh $@; } # When running in a limited environment, we might not be able to load # our modules although we can find them. In this case we should help user # by setting up system dependencies. eval { if (grep { $_ eq '--initial-setup' } @ARGV) { require ksb::FirstRun; require ksb::Debug; ksb::Debug::setColorfulOutput(1); exit ksb::FirstRun::setupUserSystem($baseDataDir); } }; if ($@) { dumpError(); say STDERR <import(); ksb::Util->import(); ksb::BuildException->import(); ksb::Version->import(qw(scriptVersion)); ksb::Application->import(); # Make Perl 'plain die' exceptions use Carp::confess instead of their core # support. This is not supported by the Perl 5 authors but assuming it works # will be better than the alternative backtrace we get (which is to say, none) $SIG{__DIE__} = \&Carp::confess; ksb::Version->path($baseBinDir); ### Script-global functions. # These functions might be called at runtime via log_command, using # log_command's support for symbolic execution of a named subroutine. Because # of that, they have been left in the top-level script. # # Everything else should be in an appropriate class. -# Subroutine to recursively symlink a directory into another location, in a -# similar fashion to how the XFree/X.org lndir() program does it. This is -# reimplemented here since some systems lndir doesn't seem to work right. -# -# Used from ksb::l10nSystem -# -# As a special exception to the GNU GPL, you may use and redistribute this -# function however you would like (i.e. consider it public domain). -# -# The first parameter is the directory to symlink from. -# The second parameter is the destination directory name. -# -# e.g. if you have $from/foo and $from/bar, lndir would create $to/foo and -# $to/bar. -# -# All intervening directories will be created as needed. In addition, you -# may safely run this function again if you only want to catch additional files -# in the source directory. -# -# Note that this function will unconditionally output the files/directories -# created, as it is meant to be a close match to lndir. -# -# RETURN VALUE: Boolean true (non-zero) if successful, Boolean false (0, "") -# if unsuccessful. -sub safe_lndir -{ - my ($from, $to) = @_; - - # Create destination directory. - if (not -e $to) - { - print "$to\n"; - if (not pretending() and not super_mkdir($to)) - { - error ("Couldn't create directory r[$to]: b[r[$!]"); - return 0; - } - } - - # Create closure callback subroutine. - my $wanted = sub { - my $dir = $File::Find::dir; - my $file = $File::Find::fullname; - $dir =~ s/$from/$to/; - - # Ignore the .svn directory and files. - return if $dir =~ m,/\.svn,; - - # Create the directory. - if (not -e $dir) - { - print "$dir\n"; - - if (not pretending()) - { - super_mkdir ($dir) or croak_runtime("Couldn't create directory $dir: $!"); - } - } - - # Symlink the file. Check if it's a regular file because File::Find - # has no qualms about telling you you have a file called "foo/bar" - # before pointing out that it was really a directory. - if (-f $file and not -e "$dir/$_") - { - print "$dir/$_\n"; - - if (not pretending()) - { - symlink $File::Find::fullname, "$dir/$_" or - croak_runtime("Couldn't create file $dir/$_: $!"); - } - } - }; - - # Recursively descend from source dir using File::Find - eval { - find ({ 'wanted' => $wanted, - 'follow_fast' => 1, - 'follow_skip' => 2}, - $from); - }; - - if ($@) - { - error ("Unable to symlink $from to $to: $@"); - return 0; - } - - return 1; -} - # Subroutine to delete recursively, everything under the given directory, # unless we're in pretend mode. # # Used from ksb::BuildSystem to handle cleaning a build directory. # # i.e. the effect is similar to "rm -r $arg/* $arg/.*". # # This assumes we're called from a separate child process. Therefore the # normal logging routines are /not used/, since our output will be logged # by the parent kdesrc-build. # # The first parameter should be the absolute path to the directory to delete. # # Returns boolean true on success, boolean false on failure. sub prune_under_directory { my $dir = shift; my $errorRef; print "starting delete of $dir\n"; eval { remove_tree($dir, { keep_root => 1, error => \$errorRef }); }; if ($@ || @$errorRef) { error ("\tUnable to clean r[$dir]:\n\ty[b[$@]"); return 0; } return 1; } sub findMissingModules { # should be either strings of module names to be found or a listref containing # a list of modules where any one of which will work. my @requiredModules = ( 'HTTP::Tiny', 'IO::Socket::SSL', [qw(JSON::XS JSON::PP)], [qw(YAML::XS YAML::PP YAML::Syck)] ); my @missingModules; my $validateMod = sub { return eval "require $_[0]; 1;"; }; my $description; foreach my $neededModule (@requiredModules) { if (ref $neededModule) { # listref of options my @moduleOptions = @$neededModule; next if (ksb::Util::any (sub { $validateMod->($_); }, $neededModule)); $description = 'one of (' . join(', ', @moduleOptions) . ')'; } else { next if $validateMod->($neededModule); $description = $neededModule; } push @missingModules, $description; } return @missingModules; } # Script starts. # Ensure some critical Perl modules are available so that the user isn't surprised # later with a Perl exception if(my @missingModuleDescriptions = findMissingModules()) { say <new(@ARGV); push @atexit_subs, sub { $app->finish(99) }; my $result = $app->runAllModulePhases(); @atexit_subs = (); # Clear exit handlers $app->finish($result); }; if (my $err = $@) { if (had_an_exception()) { print "kdesrc-build encountered an exceptional error condition:\n"; print " ========\n"; print " $err\n"; print " ========\n"; print "\tCan't continue, so stopping now.\n"; if ($err->{'exception_type'} eq 'Internal') { print "\nPlease submit a bug against kdesrc-build on https://bugs.kde.org/\n" } } else { # We encountered an error. print "Encountered an error in the execution of the script.\n"; print "The error reported was $err\n"; print "Please submit a bug against kdesrc-build on https://bugs.kde.org/\n"; } exit 99; } # vim: set et sw=4 ts=4 fdm=marker: diff --git a/modules/ksb/Application.pm b/modules/ksb/Application.pm index 0513c52..0cd260c 100644 --- a/modules/ksb/Application.pm +++ b/modules/ksb/Application.pm @@ -1,2609 +1,2559 @@ package ksb::Application 0.20; # Class: Application # # Contains the application-layer logic (i.e. creating a build context, reading # options, parsing command-line, etc.) use strict; use warnings; use 5.014; no if $] >= 5.018, 'warnings', 'experimental::smartmatch'; use ksb::Debug; use ksb::Util 0.35; use ksb::BuildContext 0.35; use ksb::BuildSystem::QMake; use ksb::BuildException 0.20; use ksb::FirstRun; use ksb::Module; use ksb::ModuleResolver 0.20; use ksb::ModuleSet 0.20; use ksb::ModuleSet::KDEProjects; use ksb::OSSupport; use ksb::RecursiveFH; use ksb::DependencyResolver 0.20; use ksb::IPC::Pipe 0.20; use ksb::IPC::Null; use ksb::Updater::Git; use ksb::Version qw(scriptVersion); use List::Util qw(first min); use File::Basename; # basename, dirname use File::Glob ':glob'; use POSIX qw(:sys_wait_h _exit :errno_h); use Getopt::Long qw(GetOptionsFromArray :config gnu_getopt nobundling); use IO::Handle; use IO::Select; ### Package-specific variables (not shared outside this file). use constant { # We use a named remote to make some git commands work that don't accept the # full path. KDE_PROJECT_ID => 'kde-projects', # git-repository-base for kde_projects.xml }; ### Package methods sub new { my ($class, @options) = @_; my $self = bless { context => ksb::BuildContext->new(), metadata_module => undef, run_mode => 'build', modules => undef, module_factory => undef, # ref to sub that makes a new Module. # See generateModuleList _base_pid => $$, # See finish() }, $class; # Default to colorized output if sending to TTY ksb::Debug::setColorfulOutput(-t STDOUT); my @moduleList = $self->generateModuleList(@options); $self->{modules} = \@moduleList; if (!@moduleList) { print "No modules to build, exiting.\n"; exit 0; } $self->context()->setupOperatingEnvironment(); # i.e. niceness, ulimits, etc. # After this call, we must run the finish() method # to cleanly complete process execution. if (!pretending() && !$self->context()->takeLock()) { print "$0 is already running!\n"; exit 1; # Don't finish(), it's not our lockfile!! } # Install signal handlers to ensure that the lockfile gets closed. _installSignalHandlers(sub { note ("Signal received, terminating."); @main::atexit_subs = (); # Remove their finish, doin' it manually $self->finish(5); }); return $self; } # Method: _readCommandLineOptionsAndSelectors # # Returns a list of module/module-set selectors, selected module/module-set # options, and global options, based on the command-line arguments passed to # this function. # # This is a package method, should be called as # $app->_readCommandLineOptionsAndSelectors # # Phase: # initialization - Do not call from this function. # # Parameters: # cmdlineOptions - hashref to hold parsed modules options to be applied later. # *Note* this must be done separately, it is not handled by this subroutine. # Global options will be stored in a hashref at $cmdlineOptions->{global}. # Module or module-set options will be stored in a hashref at # $cmdlineOptions->{$moduleName} (it will be necessary to disambiguate # later in the run whether it is a module set or a single module). # # If the global option 'start-program' is set, then the program to start and # its options will be found in a listref pointed to under the # 'start-program' option. # # selectors - listref to hold the list of module or module-set selectors to # build, in the order desired by the user. These will just be strings, the # caller will have to figure out whether the selector is a module or # module-set, and create any needed objects, and then set the recommended # options as listed in cmdlineOptions. # # ctx - to hold the global build state. # # @options - The remainder of the arguments are treated as command line # arguments to process. # # Returns: # Nothing. An exception will be raised on failure, or this function may quit # the program directly (e.g. to handle --help, --usage). sub _readCommandLineOptionsAndSelectors { my $self = shift; my ($cmdlineOptionsRef, $selectorsRef, $ctx, @options) = @_; my $phases = $ctx->phases(); my @savedOptions = @options; # Copied for use in debugging. my $os = ksb::OSSupport->new; my $version = "kdesrc-build " . scriptVersion(); my $author = < Many people have contributed code, bugfixes, and documentation. Please report bugs using the KDE Bugzilla, at https://bugs.kde.org/ DONE # Getopt::Long will store options in %foundOptions, since that is what we # pass in. To allow for custom subroutines to handle an option it is # required that the sub *also* be in %foundOptions... whereupon it will # promptly be overwritten if we're not careful. Instead we let the custom # subs save to %auxOptions, and read those in back over it later. my (%foundOptions, %auxOptions); %foundOptions = ( 'show-info' => sub { say $version; say "OS: ", $os->vendorID(); exit }, version => sub { say $version; exit }, author => sub { say $author; exit }, help => sub { _showHelpMessage(); exit 0 }, install => sub { $self->{run_mode} = 'install'; $phases->phases('install'); }, uninstall => sub { $self->{run_mode} = 'uninstall'; $phases->phases('uninstall'); }, 'no-src' => sub { $phases->filterOutPhase('update'); }, 'no-install' => sub { $phases->filterOutPhase('install'); }, 'no-snapshots' => sub { # The documented form of disable-snapshots $auxOptions{'disable-snapshots'} = 1; }, 'no-tests' => sub { # The "right thing" to do $phases->filterOutPhase('test'); # What actually works at this point. $foundOptions{'run-tests'} = 0; }, 'no-build' => sub { $phases->filterOutPhase('build'); }, # Mostly equivalent to the above 'src-only' => sub { $phases->phases('update'); # We have an auto-switching function that we only want to run # if --src-only was passed to the command line, so we still # need to set a flag for it. $foundOptions{'allow-auto-repo-move'} = 1; }, 'build-only' => sub { $phases->phases('build'); }, 'install-only' => sub { $self->{run_mode} = 'install'; $phases->phases('install'); }, prefix => sub { my ($optName, $arg) = @_; $auxOptions{prefix} = $arg; $foundOptions{kdedir} = $arg; #TODO: Still needed for compat? $foundOptions{reconfigure} = 1; }, query => sub { my (undef, $arg) = @_; my $validMode = qr/^[a-zA-Z0-9_][a-zA-Z0-9_-]*$/; die("Invalid query mode $arg") unless $arg =~ $validMode; # Add useful aliases $arg = 'source-dir' if $arg =~ /^src-?dir$/; $arg = 'build-dir' if $arg =~ /^build-?dir$/; $arg = 'install-dir' if $arg eq 'prefix'; $self->{run_mode} = 'query'; $auxOptions{query} = $arg; $auxOptions{pretend} = 1; # Implied pretend mode }, pretend => sub { # Set pretend mode but also force the build process to run. $auxOptions{pretend} = 1; $foundOptions{'build-when-unchanged'} = 1; }, resume => sub { $auxOptions{resume} = 1; $phases->filterOutPhase('update'); # Implied --no-src $foundOptions{'no-metadata'} = 1; # Implied --no-metadata }, verbose => sub { $foundOptions{'debug-level'} = ksb::Debug::WHISPER }, quiet => sub { $foundOptions{'debug-level'} = ksb::Debug::NOTE }, 'really-quiet' => sub { $foundOptions{'debug-level'} = ksb::Debug::WARNING }, debug => sub { $foundOptions{'debug-level'} = ksb::Debug::DEBUG; debug ("Commandline was: ", join(', ', @savedOptions)); }, # Hack to set module options 'set-module-option-value' => sub { my ($optName, $arg) = @_; my ($module, $option, $value) = split (',', $arg, 3); if ($module && $option) { $cmdlineOptionsRef->{$module} //= { }; $cmdlineOptionsRef->{$module}->{$option} = $value; } }, # Getopt::Long doesn't set these up for us even though we specify an # array. Set them up ourselves. 'start-program' => [ ], 'ignore-modules' => [ ], # Module selectors, the <> is Getopt::Long shortcut for an # unrecognized non-option value (i.e. an actual argument) '<>' => sub { my $arg = shift; push @{$selectorsRef}, $arg; }, ); # Handle any "cmdline-eligible" options not already covered. my $flagHandler = sub { my ($optName, $optValue) = @_; # Assume to set if nothing provided. $optValue = 1 if (!defined $optValue or $optValue eq ''); $optValue = 0 if lc($optValue) eq 'false'; $optValue = 0 if !$optValue; $auxOptions{$optName} = $optValue; }; foreach my $option (keys %ksb::BuildContext::defaultGlobalFlags) { if (!exists $foundOptions{$option}) { $foundOptions{$option} = $flagHandler; # A ref to a sub here! } } # Actually read the options. my $optsSuccess = GetOptionsFromArray(\@options, \%foundOptions, # Options here should not duplicate the flags and options defined below # from ksb::BuildContext! 'version|v', 'author', 'help', 'show-info', 'install', 'uninstall', 'no-src|no-svn', 'no-install', 'no-build', 'no-tests', 'build-when-unchanged|force-build', 'no-metadata', 'verbose', 'quiet|quite|q', 'really-quiet', 'debug', 'reconfigure', 'colorful-output|color!', 'async!', 'src-only|svn-only', 'build-only', 'install-only', 'build-system-only', 'rc-file=s', 'prefix=s', 'niceness|nice:10', 'ignore-modules=s{,}', 'print-modules', 'pretend|dry-run|p', 'refresh-build', 'query=s', 'start-program|run=s{,}', 'revision=i', 'resume-from=s', 'resume-after=s', 'rebuild-failures', 'resume', 'stop-after=s', 'stop-before=s', 'set-module-option-value=s', 'metadata-only', 'include-dependencies', # Special sub used (see above), but have to tell Getopt::Long to look # for negatable boolean flags (map { "$_!" } (keys %ksb::BuildContext::defaultGlobalFlags)), # Default handling fine, still have to ask for strings. (map { "$_:s" } (keys %ksb::BuildContext::defaultGlobalOptions)), '<>', # Required to read non-option args ); if (!$optsSuccess) { croak_runtime("Error reading command-line options."); } # To store the values we found, need to strip out the values that are # subroutines, as those are the ones we created. Alternately, place the # subs inline as an argument to the appropriate option in the # GetOptionsFromArray call above, but that's ugly too. my @readOptionNames = grep { ref($foundOptions{$_}) ne 'CODE' } (keys %foundOptions); # Slice assignment: $left{$key} = $right{$key} foreach $key (@keys), but # with hashref syntax everywhere. @{ $cmdlineOptionsRef->{'global'} }{@readOptionNames} = @foundOptions{@readOptionNames}; @{ $cmdlineOptionsRef->{'global'} }{keys %auxOptions} = values %auxOptions; } # Generates the build context and module list based on the command line options # and module selectors provided, resolves dependencies on those modules if needed, # filters out ignored or skipped modules, and sets up the module factory. # # After this function is called all module set selectors will have been # expanded, and we will have downloaded kde-projects metadata. # # Returns: List of Modules to build. sub generateModuleList { my $self = shift; my @argv = @_; # Note: Don't change the order around unless you're sure of what you're # doing. my $ctx = $self->context(); my $cmdlineOptions = { global => { }, }; my $cmdlineGlobalOptions = $cmdlineOptions->{global}; my $deferredOptions = { }; # 'options' blocks # Process --help, --install, etc. first. my @selectors; $self->_readCommandLineOptionsAndSelectors($cmdlineOptions, \@selectors, $ctx, @argv); # Convert list to hash for lookup my %ignoredSelectors = map { $_, 1 } @{$cmdlineGlobalOptions->{'ignore-modules'}}; my @startProgramAndArgs = @{$cmdlineGlobalOptions->{'start-program'}}; delete @{$cmdlineGlobalOptions}{qw/ignore-modules start-program/}; # rc-file needs special handling. if (exists $cmdlineGlobalOptions->{'rc-file'} && $cmdlineGlobalOptions->{'rc-file'}) { $ctx->setRcFile($cmdlineGlobalOptions->{'rc-file'}); } # disable async if only running a single phase. $cmdlineGlobalOptions->{async} = 0 if (scalar $ctx->phases()->phases() == 1); my $fh = $ctx->loadRcFile(); $ctx->loadPersistentOptions(); if (exists $cmdlineGlobalOptions->{'resume'}) { my $moduleList = $ctx->getPersistentOption('global', 'resume-list'); if (!$moduleList) { error ("b[--resume] specified, but unable to find resume point!"); error ("Perhaps try b[--resume-from] or b[--resume-after]?"); croak_runtime("Invalid --resume flag"); } unshift @selectors, split(/,\s*/, $moduleList); } if (exists $cmdlineGlobalOptions->{'rebuild-failures'}) { my $moduleList = $ctx->getPersistentOption('global', 'last-failed-module-list'); if (!$moduleList) { error ("b[y[--rebuild-failures] was specified, but unable to determine"); error ("which modules have previously failed to build."); croak_runtime("Invalid --rebuild-failures flag"); } unshift @selectors, split(/,\s*/, $moduleList); } # _readConfigurationOptions will add pending global opts to ctx while ensuring # returned modules/sets have any such options stripped out. It will also add # module-specific options to any returned modules/sets. my @optionModulesAndSets = _readConfigurationOptions($ctx, $fh, $deferredOptions); close $fh; # Check if we're supposed to drop into an interactive shell instead. If so, # here's the stop off point. if (@startProgramAndArgs) { $ctx->setupEnvironment(); # Read options from set-env $ctx->commitEnvironmentChanges(); # Apply env options to environment _executeCommandLineProgram(@startProgramAndArgs); # noreturn } # Everything else in cmdlineOptions should be OK to apply directly as a module # or context option. $ctx->setOption(%{$cmdlineGlobalOptions}); # Selecting modules or module sets would requires having the KDE # build metadata (kde-build-metadata and sysadmin/repo-metadata) # available. $ctx->setKDEDependenciesMetadataModuleNeeded(); $ctx->setKDEProjectsMetadataModuleNeeded(); if (!exists $ENV{HARNESS_ACTIVE}) { # Running in a test harness, avoid downloading metadata which will be # ignored in the test or making changes to git config ksb::Updater::Git::verifyGitConfig(); $self->_downloadKDEProjectMetadata(); } # The user might only want metadata to update to allow for a later # --pretend run, check for that here. if (exists $cmdlineGlobalOptions->{'metadata-only'}) { return; } # At this point we have our list of candidate modules / module-sets (as read in # from rc-file). The module sets have not been expanded into modules. # We also might have cmdline "selectors" to determine which modules or # module-sets to choose. First let's select module sets, and expand them. my @globalCmdlineArgs = keys %{$cmdlineGlobalOptions}; my $commandLineModules = scalar @selectors; my $moduleResolver = ksb::ModuleResolver->new($ctx); $moduleResolver->setCmdlineOptions($cmdlineOptions); $moduleResolver->setDeferredOptions($deferredOptions); $moduleResolver->setInputModulesAndOptions(\@optionModulesAndSets); $moduleResolver->setIgnoredSelectors([keys %ignoredSelectors]); $self->_defineNewModuleFactory($moduleResolver); my @modules; if ($commandLineModules) { @modules = $moduleResolver->resolveSelectorsIntoModules(@selectors); } else { # Build everything in the rc-file, in the order specified. @modules = $moduleResolver->expandModuleSets(@optionModulesAndSets); - - if ($ctx->getOption('kde-languages')) { - @modules = _expandl10nModules($ctx, @modules); - } } # If modules were on the command line then they are effectively forced to # process unless overridden by command line options as well. If phases # *were* overridden on the command line, then no update pass is required # (all modules already have correct phases) @modules = _updateModulePhases(@modules) unless $commandLineModules; # TODO: Verify this does anything still my $metadataModule = $ctx->getKDEDependenciesMetadataModule(); $ctx->addToIgnoreList($metadataModule->scm()->ignoredModules()); # Remove modules that are explicitly blanked out in their branch-group # i.e. those modules where they *have* a branch-group, and it's set to # be empty (""). my $resolver = $ctx->moduleBranchGroupResolver(); my $branchGroup = $ctx->effectiveBranchGroup(); @modules = grep { my $branch = $_->isKDEProject() ? $resolver->findModuleBranch($_->fullProjectPath(), $branchGroup) : 1; # Just a placeholder truthy value whisper ("Removing ", $_->fullProjectPath(), " due to branch-group") if (defined $branch and !$branch); (!defined $branch or $branch); # This is the actual test } (@modules); @modules = $self->_resolveModuleDependencies(@modules); # Filter --resume-foo options. This might be a second pass, but that should # be OK since there's nothing different going on from the first pass (in # resolveSelectorsIntoModules) in that event. @modules = _applyModuleFilters($ctx, @modules); # Check for ignored modules (post-expansion) @modules = grep { ! exists $ignoredSelectors{$_->name()} } @modules; return @modules; } # Causes kde-projects metadata to be downloaded (unless --pretend, --no-src, or # --no-metadata is in effect, although we'll download even in --pretend if # nothing is available). # # No return value. sub _downloadKDEProjectMetadata { my $self = shift; my $ctx = $self->context(); my $updateStillNeeded = 0; my $wasPretending = pretending(); eval { for my $metadataModule ( $ctx->getKDEDependenciesMetadataModule(), $ctx->getKDEProjectsMetadataModule()) { my $sourceDir = $metadataModule->getSourceDir(); super_mkdir($sourceDir); my $moduleSource = $metadataModule->fullpath('source'); my $updateDesired = !$ctx->getOption('no-metadata') && $ctx->phases()->has('update'); my $updateNeeded = (! -e $moduleSource) || is_dir_empty($moduleSource); my $lastUpdate = $ctx->getPersistentOption('global', 'last-metadata-update') // 0; $updateStillNeeded ||= $updateNeeded; if (!$updateDesired && $updateNeeded && (time - ($lastUpdate)) >= 7200) { warning (" r[b[*] Skipping build metadata update, but it hasn't been updated recently!"); } if ($updateNeeded && pretending()) { warning (" y[b[*] Ignoring y[b[--pretend] option to download required metadata\n" . " y[b[*] --pretend mode will resume after metadata is available."); ksb::Debug::setPretending(0); } if ($updateDesired && (!pretending() || $updateNeeded)) { $metadataModule->scm()->updateInternal(); $ctx->setPersistentOption('global', 'last-metadata-update', time); } ksb::Debug::setPretending($wasPretending); } }; my $err = $@; ksb::Debug::setPretending($wasPretending); if ($err) { die $err if $updateStillNeeded; # Assume previously-updated metadata will work if not updating warning (" b[r[*] Unable to download required metadata for build process"); warning (" b[r[*] Will attempt to press onward..."); warning (" b[r[*] Exception message: $@"); } } # Returns a list of Modules in the proper build order according to the # kde-build-metadata dependency information. # # The kde-build-metadata repository must have already been updated, and the # module factory must be setup. The Modules to reorder must be passed as # arguments. sub _resolveModuleDependencies { my $self = shift; my $ctx = $self->context(); my $metadataModule = $ctx->getKDEDependenciesMetadataModule(); my @modules = @_; @modules = eval { my $dependencyResolver = ksb::DependencyResolver->new($self->{module_factory}); my $branchGroup = $ctx->effectiveBranchGroup(); for my $file ('dependency-data-common', "dependency-data-$branchGroup") { my $dependencyFile = $metadataModule->fullpath('source') . "/$file"; my $dependencies = pretend_open($dependencyFile) or die "Unable to open $dependencyFile: $!"; debug (" -- Reading dependencies from $dependencyFile"); $dependencyResolver->readDependencyData($dependencies); close $dependencies; } my @reorderedModules = $dependencyResolver->resolveDependencies(@modules); return @reorderedModules; }; if ($@) { warning (" r[b[*] Problems encountered trying to sort modules into correct order:"); warning (" r[b[*] $@"); warning (" r[b[*] Will attempt to continue."); } return @modules; } # Runs all update, build, install, etc. phases. Basically this *is* the # script. # The metadata module must already have performed its update by this point. sub runAllModulePhases { my $self = shift; my $ctx = $self->context(); my @modules = $self->modules(); if ($ctx->getOption('print-modules')) { for my $m (@modules) { say ((" " x ($m->getOption('#dependency-level', 'module') // 0)), "$m"); } return 0; # Abort execution early! } # Add to global module list now that we've filtered everything. $ctx->addModule($_) foreach @modules; my $runMode = $self->runMode(); if ($runMode eq 'query') { my $queryMode = $ctx->getOption('query', 'module'); # Default to ->getOption as query method. # $_[0] is short name for first param. my $query = sub { $_[0]->getOption($queryMode) }; $query = sub { $_[0]->fullpath('source') } if $queryMode eq 'source-dir'; $query = sub { $_[0]->fullpath('build') } if $queryMode eq 'build-dir'; $query = sub { $_[0]->installationPath() } if $queryMode eq 'install-dir'; $query = sub { $_[0]->fullProjectPath() } if $queryMode eq 'project-path'; $query = sub { ($_[0]->scm()->_determinePreferredCheckoutSource())[0] // '' } if $queryMode eq 'branch'; if (@modules == 1) { # No leading module name, just the value say $query->($modules[0]); } else { for my $m (@modules) { say "$m: ", $query->($m); } } return 0; } my $result; if ($runMode eq 'build') { # No packages to install, we're in build mode # What we're going to do is fork another child to perform the source # updates while we build. Setup for this first by initializing some # shared memory. my $ipc = 0; my $updateOptsSub = sub { my ($k, $v) = @_; $ctx->setPersistentOption($k, $v); }; if ($ctx->getOption('async')) { $ipc = ksb::IPC::Pipe->new(); $ipc->setPersistentOptionHandler($updateOptsSub); } if (!$ipc) { $ipc = ksb::IPC::Null->new(); $ipc->setPersistentOptionHandler($updateOptsSub); whisper ("Using no IPC mechanism\n"); note ("\n b[<<< Update Process >>>]\n"); $result = _handle_updates ($ipc, $ctx); note (" b[<<< Build Process >>>]\n"); $result = _handle_build ($ipc, $ctx) || $result; } else { $result = _handle_async_build ($ipc, $ctx); $ipc->outputPendingLoggedMessages() if debugging(); } } elsif ($runMode eq 'install') { $result = _handle_install ($ctx); } elsif ($runMode eq 'uninstall') { $result = _handle_uninstall ($ctx); } _cleanup_log_directory($ctx) if $ctx->getOption('purge-old-logs'); _output_failed_module_lists($ctx); # Record all failed modules. Unlike the 'resume-list' option this doesn't # include any successfully-built modules in between failures. my $failedModules = join(',', map { "$_" } $ctx->listFailedModules()); if ($failedModules) { # We don't clear the list of failed modules on success so that # someone can build one or two modules and still use # --rebuild-failures $ctx->setPersistentOption('global', 'last-failed-module-list', $failedModules); } # env driver is just the ~/.config/kde-env-*.sh, session driver is that + ~/.xsession if ($ctx->getOption('install-environment-driver') || $ctx->getOption('install-session-driver')) { _installCustomSessionDriver($ctx); } my $color = 'g[b['; $color = 'r[b[' if $result; info ("${color}", $result ? ":-(" : ":-)") unless pretending(); return $result; } # Method: finish # # Exits the script cleanly, including removing any lock files created. # # Parameters: # ctx - Required; BuildContext to use. # [exit] - Optional; if passed, is used as the exit code, otherwise 0 is used. sub finish { my $self = shift; my $ctx = $self->context(); my $exitcode = shift // 0; if (pretending() || $self->{_base_pid} != $$) { # Abort early if pretending or if we're not the same process # that was started by the user (e.g. async mode, forked pipe-opens exit $exitcode; } $ctx->closeLock(); $ctx->storePersistentOptions(); my $logdir = $ctx->getLogDir(); note ("Your logs are saved in y[$logdir]"); exit $exitcode; } ### Package-internal helper functions. # Reads a "line" from a file. This line is stripped of comments and extraneous # whitespace. Also, backslash-continued multiple lines are merged into a single # line. # # First parameter is the reference to the filehandle to read from. # Returns the text of the line. sub _readNextLogicalLine { my $fileReader = shift; while($_ = $fileReader->readLine()) { # Remove trailing newline chomp; # Replace \ followed by optional space at EOL and try again. if(s/\\\s*$//) { $_ .= $fileReader->readLine(); redo; } s/#.*$//; # Remove comments next if /^\s*$/; # Skip blank lines return $_; } return undef; } # Takes an input line, and extracts it into an option name, and simplified # value. The value has "false" converted to 0, white space simplified (like in # Qt), and tildes (~) in what appear to be path-like entries are converted to # the home directory path. # # First parameter is the build context (used for translating option values). # Second parameter is the line to split. # Return value is (option-name, option-value) sub _splitOptionAndValue { my $ctx = assert_isa(shift, 'ksb::BuildContext'); my $input = shift; my $optionRE = qr/\$\{([a-zA-Z0-9-]+)\}/; # The option is the first word, followed by the # flags on the rest of the line. The interpretation # of the flags is dependent on the option. my ($option, $value) = ($input =~ /^\s* # Find all spaces ([-\w]+) # First match, alphanumeric, -, and _ # (?: ) means non-capturing group, so (.*) is $value # So, skip spaces and pick up the rest of the line. (?:\s+(.*))?$/x); $value //= ''; # Simplify whitespace. $value =~ s/\s+$//; $value =~ s/^\s+//; $value =~ s/\s+/ /g; # Check for false keyword and convert it to Perl false. $value = 0 if lc($value) eq 'false'; # Replace reference to global option with their value. # The regex basically just matches ${option-name}. my ($sub_var_name) = ($value =~ $optionRE); while ($sub_var_name) { my $sub_var_value = $ctx->getOption($sub_var_name) || ''; if(!$ctx->hasOption($sub_var_name)) { warning (" *\n * WARNING: $sub_var_name is not set at line y[$.]\n *"); ## TODO: filename is missing } debug ("Substituting \${$sub_var_name} with $sub_var_value"); $value =~ s/\$\{$sub_var_name\}/$sub_var_value/g; # Replace other references as well. Keep this RE up to date with # the other one. ($sub_var_name) = ($value =~ $optionRE); } # Replace tildes with home directory. 1 while ($value =~ s"(^|:|=)~/"$1$ENV{'HOME'}/"); return ($option, $value); } # Ensures that the given ModuleSet has at least a valid repository and # use-modules setting based on the given BuildContext. sub _validateModuleSet { my ($ctx, $moduleSet) = @_; my $name = $moduleSet->name() || 'unnamed'; my $rcSources = _getModuleSources($moduleSet); # re-read option from module set since it may be pre-set my $selectedRepo = $moduleSet->getOption('repository'); if (!$selectedRepo) { error (<getOption('git-repository-base'); if ($selectedRepo ne KDE_PROJECT_ID && not exists $repoSet->{$selectedRepo}) { my $projectID = KDE_PROJECT_ID; my $moduleSetName = $moduleSet->name(); my $moduleSetId = $moduleSetName ? "module-set ($moduleSetName)" : "module-set"; error (<isa('ksb::BuildContext') ? 'global' : $module->isa('ksb::ModuleSet') ? 'module-set' : $module->isa('ksb::Module') ? 'module' : 'options'; # Just look for an end marker if terminator not provided. $endRE //= qr/^end[\w\s]*$/; _markModuleSource($module, $fileReader->currentFilename() . ":$."); # Read in each option while (($_ = _readNextLogicalLine($fileReader)) && ($_ !~ $endRE)) { my $current_file = $fileReader->currentFilename(); # Sanity check, make sure the section is correctly terminated if(/^(module\b|options\b)/) { error ("Invalid configuration file $current_file at line $.\nAdd an 'end $endWord' before " . "starting a new module.\n"); die make_exception('Config', "Invalid file $current_file"); } my ($option, $value) = _splitOptionAndValue($ctx, $_); eval { $module->setOption($option, $value); }; if (my $err = $@) { if (blessed($err) && $err->isa('ksb::BuildException::Config')) { my $msg = "$current_file:$.: " . $err->message(); my $explanation = $err->optionUsageExplanation(); $msg = $msg . "\n" . $explanation if $explanation; $err->setMessage($msg); } die; # re-throw } } return $module; } # Marks the given OptionsBase subclass (i.e. Module or ModuleSet) as being # read in from the given string (filename:line). An OptionsBase can be # tagged under multiple files. sub _markModuleSource { my ($optionsBase, $configSource) = @_; my $key = '#defined-at'; my $sourcesRef = $optionsBase->hasOption($key) ? $optionsBase->getOption($key) : []; push @$sourcesRef, $configSource; $optionsBase->setOption($key, $sourcesRef); } # Returns rcfile sources for given OptionsBase (comma-separated). sub _getModuleSources { my $optionsBase = shift; my $key = '#defined-at'; my $sourcesRef = $optionsBase->getOption($key) || []; return join(', ', @$sourcesRef); } # Reads in a "moduleset". # # First parameter is the build context. # Second parameter is the filehandle to the config file to read from. # Third parameter is the ksb::ModuleSet to use. # # Returns the ksb::ModuleSet passed in with read-in options set, which may need # to be further expanded (see ksb::ModuleSet::convertToModules). sub _parseModuleSetOptions { my ($ctx, $fileReader, $moduleSet) = @_; $moduleSet = _parseModuleOptions($ctx, $fileReader, $moduleSet, qr/^end\s+module(-?set)?$/); if ($moduleSet->getOption('repository') eq KDE_PROJECT_ID && !$moduleSet->isa('ksb::ModuleSet::KDEProjects')) { # Perl-specific note! re-blessing the module set into the right 'class' # You'd probably have to construct an entirely new object and copy the # members over in other languages. bless $moduleSet, 'ksb::ModuleSet::KDEProjects'; } return $moduleSet; } # Function: _readConfigurationOptions # # Reads in the settings from the configuration, passed in as an open # filehandle. # # Phase: # initialization - Do not call from this function. # # Parameters: # ctx - The to update based on the configuration read and # any pending command-line options (see cmdlineGlobalOptions). # # filehandle - The I/O object to read from. Must handle _eof_ and _readline_ # methods (e.g. subclass). # # deferredOptions - An out parameter: a hashref holding the options set by any # 'options' blocks read in by this function. Each key (identified by the name # of the 'options' block) will point to a hashref value holding the options to # apply. # # Returns: # @module - Heterogeneous list of and defined in the # configuration file. No module sets will have been expanded out (either # kde-projects or standard sets). # # Throws: # - Config exceptions. sub _readConfigurationOptions { my $ctx = assert_isa(shift, 'ksb::BuildContext'); my $fh = shift; my $deferredOptionsRef = shift; my @module_list; my $rcfile = $ctx->rcFile(); my ($option, %readModules); my $fileReader = ksb::RecursiveFH->new($rcfile); $fileReader->addFile($fh, $rcfile); # Read in global settings while ($_ = $fileReader->readLine()) { s/#.*$//; # Remove comments s/^\s*//; # Remove leading whitespace next if (/^\s*$/); # Skip blank lines # First command in .kdesrc-buildrc should be a global # options declaration, even if none are defined. if (not /^global\s*$/) { error ("Invalid configuration file: $rcfile."); error ("Expecting global settings section at b[r[line $.]!"); die make_exception('Config', 'Missing global section'); } # Now read in each global option. _parseModuleOptions($ctx, $fileReader, $ctx); last; } my $using_default = 1; my %seenModules; # NOTE! *not* module-sets, *just* modules. my %seenModuleSets; # and vice versa -- named sets only though! my %seenModuleSetItems; # To track option override modules. # Now read in module settings while ($_ = $fileReader->readLine()) { s/#.*$//; # Remove comments s/^\s*//; # Remove leading whitespace next if (/^\s*$/); # Skip blank lines # Get modulename (has dash, dots, slashes, or letters/numbers) my ($type, $modulename) = /^(options|module)\s+([-\/\.\w]+)\s*$/; my $newModule; # 'include' directives can change the current file, so check where we're at $rcfile = $fileReader->currentFilename(); # Module-set? if (not $modulename) { my $moduleSetRE = qr/^module-set\s*([-\/\.\w]+)?\s*$/; ($modulename) = m/$moduleSetRE/; # modulename may be blank -- use the regex directly to match if (not /$moduleSetRE/) { error ("Invalid configuration file $rcfile!"); error ("Expecting a start of module section at r[b[line $.]."); die make_exception('Config', 'Ungrouped/Unknown option'); } if ($modulename && exists $seenModuleSets{$modulename}) { error ("Duplicate module-set $modulename at $rcfile:$."); die make_exception('Config', "Duplicate module-set $modulename defined at $rcfile:$."); } if ($modulename && exists $seenModules{$modulename}) { error ("Name $modulename for module-set at $rcfile:$. is already in use on a module"); die make_exception('Config', "Can't re-use name $modulename for module-set defined at $rcfile:$."); } # A moduleset can give us more than one module to add. $newModule = _parseModuleSetOptions($ctx, $fileReader, ksb::ModuleSet->new($ctx, $modulename || "")); # Save 'use-modules' entries so we can see if later module decls # are overriding/overlaying their options. my @moduleSetItems = $newModule->moduleNamesToFind(); @seenModuleSetItems{@moduleSetItems} = ($newModule) x scalar @moduleSetItems; $seenModuleSets{$modulename} = $newModule if $modulename; } # Duplicate module entry? (Note, this must be checked before the check # below for 'options' sets) elsif (exists $seenModules{$modulename} && $type ne 'options') { error ("Duplicate module declaration b[r[$modulename] on line $. of $rcfile"); die make_exception('Config', "Duplicate module $modulename declared at $rcfile:$."); } # Module/module-set options overrides elsif ($type eq 'options') { my $options = _parseModuleOptions($ctx, $fileReader, ksb::OptionsBase->new()); $deferredOptionsRef->{$modulename} = $options->{options}; next; # Don't add to module list } # Must follow 'options' handling elsif (exists $seenModuleSets{$modulename}) { error ("Name $modulename for module at $rcfile:$. is already in use on a module-set"); die make_exception('Config', "Can't re-use name $modulename for module defined at $rcfile:$."); } else { $newModule = _parseModuleOptions($ctx, $fileReader, ksb::Module->new($ctx, $modulename)); $seenModules{$modulename} = $newModule; } push @module_list, $newModule; $using_default = 0; } while (my ($name, $moduleSet) = each %seenModuleSets) { _validateModuleSet($ctx, $moduleSet); } # If the user doesn't ask to build any modules, build a default set. # The good question is what exactly should be built, but oh well. if ($using_default) { warning (" b[y[*] There do not seem to be any modules to build in your configuration."); return (); } return @module_list; } # Exits out of kdesrc-build, executing the user's preferred shell instead. The # difference is that the environment variables should be as set in kdesrc-build # instead of as read from .bashrc and friends. # # You should pass in the options to run the program with as a list. # # Meant to implement the --run command line option. sub _executeCommandLineProgram { my ($program, @args) = @_; if (!$program) { error ("You need to specify a program with the --run option."); exit 1; # Can't use finish here. } if (($< != $>) && ($> == 0)) { error ("kdesrc-build will not run a program as root unless you really are root."); exit 1; } debug ("Executing b[r[$program] ", join(' ', @args)); exit 0 if pretending(); exec $program, @args or do { # If we get to here, that sucks, but don't continue. error ("Error executing $program: $!"); exit 1; }; } # Function: _split_url # # Subroutine to split a url into a protocol and host sub _split_url { my $url = shift; my ($proto, $host) = ($url =~ m|([^:]*)://([^/]*)/|); return ($proto, $host); } # Function: _check_for_ssh_agent # # Checks if we are supposed to use ssh agent by examining the environment, and # if so checks if ssh-agent has a list of identities. If it doesn't, we run # ssh-add (with no arguments) and inform the user. This can be controlled with # the disable-agent-check parameter. # # Parameters: # 1. Build context sub _check_for_ssh_agent { my $ctx = assert_isa(shift, 'ksb::BuildContext'); # Don't bother with all this if the user isn't even using SSH. return 1 if pretending(); my @svnServers = grep { $_->scmType() eq 'svn' } ($ctx->modulesInPhase('update')); my @gitServers = grep { $_->scmType() eq 'git' } ($ctx->modulesInPhase('update')); my @sshServers = grep { my ($proto, $host) = _split_url($_->getOption('svn-server')); # Check if ssh is explicitly used in the proto, or if the host is the # developer main svn. (defined $proto && $proto =~ /ssh/) || (defined $host && $host =~ /^svn\.kde\.org/); } @svnServers; push @sshServers, grep { # Check for git+ssh:// or git@git.kde.org:/path/etc. my $repo = $_->getOption('repository'); ($repo =~ /^git\+ssh:\/\//) || ($repo =~ /^[a-zA-Z0-9_.]+@.*:\//); } @gitServers; return 1 if (not @sshServers) or $ctx->getOption('disable-agent-check'); whisper ("\tChecking for SSH Agent") if (scalar @sshServers); # We're using ssh to download, see if ssh-agent is running. return 1 unless exists $ENV{'SSH_AGENT_PID'}; my $pid = $ENV{'SSH_AGENT_PID'}; # It's supposed to be running, let's see if there exists the program with # that pid (this check is linux-specific at the moment). if (-d "/proc" and not -e "/proc/$pid") { warning ("r[ *] SSH Agent is enabled, but y[doesn't seem to be running]."); warning ("Since SSH is used to download from Subversion you may want to see why"); warning ("SSH Agent is not working, or correct the environment variable settings."); return 0; } # The agent is running, but does it have any keys? We can't be more specific # with this check because we don't know what key is required. my $noKeys = 0; filter_program_output(sub { $noKeys ||= /no identities/ }, 'ssh-add', '-l'); if ($noKeys) { # Use print so user can't inadvertently keep us quiet about this. print ksb::Debug::colorize (<getOption('ssh-identity-file'); push (@commandLine, $identFile) if $identFile; my $result = system (@commandLine); if ($result) # Run this code for both death-by-signal and nonzero return { my $rcfile = $ctx->rcFile(); print "\nUnable to add SSH identity, aborting.\n"; print "If you don't want kdesrc-build to check in the future,\n"; print ksb::Debug::colorize ("Set the g[disable-agent-check] option to g[true] in your $rcfile.\n\n"); return 0; } } return 1; } # Function: _handle_updates # # Subroutine to update a list of modules. # # Parameters: # 1. IPC module to pass results to. # 2. Build Context, which will be used to determine the module update list. # # The ipc parameter contains an object that is responsible for communicating # the status of building the modules. This function must account for every # module in $ctx's update phase to the ipc object before returning. # # Returns 0 on success, non-zero on error. sub _handle_updates { my ($ipc, $ctx) = @_; my $kdesrc = $ctx->getSourceDir(); my @update_list = $ctx->modulesInPhase('update'); # No reason to print out the text if we're not doing anything. if (!@update_list) { $ipc->sendIPCMessage(ksb::IPC::ALL_UPDATING, "update-list-empty"); $ipc->sendIPCMessage(ksb::IPC::ALL_DONE, "update-list-empty"); return 0; } if (not _check_for_ssh_agent($ctx)) { $ipc->sendIPCMessage(ksb::IPC::ALL_FAILURE, "ssh-failure"); return 1; } if (not -e $kdesrc) { whisper ("KDE source download directory doesn't exist, creating.\n"); if (not super_mkdir ($kdesrc)) { error ("Unable to make directory r[$kdesrc]!"); $ipc->sendIPCMessage(ksb::IPC::ALL_FAILURE, "no-source-dir"); return 1; } } # Once at this point, any errors we get should be limited to a module, # which means we can tell the build thread to start. $ipc->sendIPCMessage(ksb::IPC::ALL_UPDATING, "starting-updates"); my $hadError = 0; foreach my $module (@update_list) { $ipc->setLoggedModule($module->name()); # Note that this must be in this order to avoid accidentally not # running ->update() from short-circuiting if an error is noted. $hadError = !$module->update($ipc, $ctx) || $hadError; } $ipc->sendIPCMessage(ksb::IPC::ALL_DONE, "had_errors: $hadError"); return $hadError; } # Builds the given module. # # Return value is the failure phase, or 0 on success. sub _buildSingleModule { my ($ipc, $ctx, $module, $startTimeRef) = @_; $ctx->resetEnvironment(); $module->setupEnvironment(); my $fail_count = $module->getPersistentOption('failure-count') // 0; my ($resultStatus, $message) = $ipc->waitForModule($module); $ipc->forgetModule($module); if ($resultStatus eq 'failed') { error ("\tUnable to update r[$module], build canceled."); $module->setPersistentOption('failure-count', ++$fail_count); return 'update'; } elsif ($resultStatus eq 'success') { note ("\tSource update complete for g[$module]: $message"); } # Skip actually building a module if the user has selected to skip # builds when the source code was not actually updated. But, don't skip # if we didn't successfully build last time. elsif ($resultStatus eq 'skipped' && !$module->getOption('build-when-unchanged') && $fail_count == 0) { note ("\tSkipping g[$module], its source code has not changed."); return 0; } elsif ($resultStatus eq 'skipped') { note ("\tNo changes to g[$module] source, proceeding to build."); } $$startTimeRef = time; $fail_count = $module->build() ? 0 : $fail_count + 1; $module->setPersistentOption('failure-count', $fail_count); return $fail_count > 0 ? 'build' : 0; } # Function: _handle_build # # Subroutine to handle the build process. # # Parameters: # 1. IPC object to receive results from. # 2. Build Context, which is used to determine list of modules to build. # # If the packages are not already checked-out and/or updated, this # subroutine WILL NOT do so for you. # # This subroutine assumes that the source directory has already been set up. # It will create the build directory if it doesn't already exist. # # If $builddir/$module/.refresh-me exists, the subroutine will # completely rebuild the module (as if --refresh-build were passed for that # module). # # Returns 0 for success, non-zero for failure. sub _handle_build { my ($ipc, $ctx) = @_; my @build_done; my @modules = $ctx->modulesInPhase('build'); my $result = 0; # No reason to print building messages if we're not building. return 0 if scalar @modules == 0; # Check for absolutely essential programs now. if (!_checkForEssentialBuildPrograms($ctx) && !exists $ENV{KDESRC_BUILD_IGNORE_MISSING_PROGRAMS}) { error (" r[b[*] Aborting now to save a lot of wasted time."); error (" y[b[*] export KDESRC_BUILD_IGNORE_MISSING_PROGRAMS=1 and re-run (perhaps with --no-src)"); error (" r[b[*] to continue anyways. If this check was in error please report a bug against"); error (" y[b[*] kdesrc-build at https://bugs.kde.org/"); return 1; } # IPC queue should have a message saying whether or not to bother with the # build. $ipc->waitForStreamStart(); $ctx->unsetPersistentOption('global', 'resume-list'); my $outfile = pretending() ? '/dev/null' : $ctx->getLogDir() . '/build-status'; open (STATUS_FILE, '>', $outfile) or do { error (<statusViewer(); my $i = 1; $statusViewer->numberModulesTotal(scalar @modules); while (my $module = shift @modules) { my $moduleName = $module->name(); my $moduleSet = $module->moduleSet()->name(); my $modOutput = $moduleName; if (debugging(ksb::Debug::WHISPER)) { $modOutput .= " (build system " . $module->buildSystemType() . ")" } $moduleSet = " from g[$moduleSet]" if $moduleSet; note ("Building g[$modOutput]$moduleSet ($i/$num_modules)"); my $start_time = time; my $failedPhase = _buildSingleModule($ipc, $ctx, $module, \$start_time); my $elapsed = prettify_seconds(time - $start_time); if ($failedPhase) { # FAILURE $ctx->markModulePhaseFailed($failedPhase, $module); print STATUS_FILE "$module: Failed on $failedPhase after $elapsed.\n"; if ($result == 0) { # No failures yet, mark this as resume point my $moduleList = join(', ', map { "$_" } ($module, @modules)); $ctx->setPersistentOption('global', 'resume-list', $moduleList); } $result = 1; if ($module->getOption('stop-on-failure')) { note ("\n$module didn't build, stopping here."); return 1; # Error } $statusViewer->numberModulesFailed(1 + $statusViewer->numberModulesFailed); } else { # Success print STATUS_FILE "$module: Succeeded after $elapsed.\n"; push @build_done, $moduleName; # Make it show up as a success $statusViewer->numberModulesSucceeded(1 + $statusViewer->numberModulesSucceeded); } $i++; } continue # Happens at the end of each loop and on next { print "\n"; # Space things out } if ($outfile) { close STATUS_FILE; # Update the symlink in latest to point to this file. my $logdir = $ctx->getSubdirPath('log-dir'); if (-l "$logdir/latest/build-status") { safe_unlink("$logdir/latest/build-status"); } symlink($outfile, "$logdir/latest/build-status"); } info ("<<< g[PACKAGES SUCCESSFULLY BUILT] >>>") if scalar @build_done > 0; my $successes = scalar @build_done; # TODO: l10n my $mods = $successes == 1 ? 'module' : 'modules'; if (not pretending()) { # Print out results, and output to a file my $kdesrc = $ctx->getSourceDir(); open BUILT_LIST, ">$kdesrc/successfully-built"; foreach my $module (@build_done) { info ("$module") if $successes <= 10; print BUILT_LIST "$module\n"; } close BUILT_LIST; info ("Built g[$successes] $mods") if $successes > 10; } else { # Just print out the results if ($successes <= 10) { info ('g[', join ("]\ng[", @build_done), ']'); } else { info ("Built g[$successes] $mods") if $successes > 10; } } info (' '); # Space out nicely return $result; } # Function: _handle_async_build # # This subroutine special-cases the handling of the update and build phases, by # performing them concurrently (where possible), using forked processes. # # Only one thread or process of execution will return from this procedure. Any # other processes will be forced to exit after running their assigned module # phase(s). # # We also redirect ksb::Debug output messages to be sent to a single process # for display on the terminal instead of allowing them all to interrupt each # other. # # Parameters: # 1. IPC Object to use for sending/receiving update/build status. It must be # an object type that supports IPC concurrency (e.g. IPC::Pipe). # 2. Build Context to use, from which the module lists will be determined. # # Returns 0 on success, non-zero on failure. sub _handle_async_build { # The exact method for async is that two children are forked. One child # is a source update process. The other child is a monitor process which will # hold status updates from the update process so that the updates may # happen without waiting for us to be ready to read. my ($ipc, $ctx) = @_; print "\n"; # Space out from metadata messages. my $result = 0; my $monitorPid = fork; if ($monitorPid == 0) { # child my $updaterToMonitorIPC = ksb::IPC::Pipe->new(); my $updaterPid = fork; $SIG{INT} = sub { POSIX::_exit(EINTR); }; if ($updaterPid) { $0 = 'kdesrc-build-updater'; $updaterToMonitorIPC->setSender(); ksb::Debug::setIPC($updaterToMonitorIPC); POSIX::_exit (_handle_updates ($updaterToMonitorIPC, $ctx)); } else { $0 = 'kdesrc-build-monitor'; $ipc->setSender(); $updaterToMonitorIPC->setReceiver(); $ipc->setLoggedModule('#monitor#'); # This /should/ never be used... ksb::Debug::setIPC($ipc); POSIX::_exit (_handle_monitoring ($ipc, $updaterToMonitorIPC)); } } else { # Still the parent, let's do the build. $ipc->setReceiver(); $result = _handle_build ($ipc, $ctx); } $ipc->waitForEnd(); $ipc->close(); # Display a message for updated modules not listed because they were not # built. my $unseenModulesRef = $ipc->unacknowledgedModules(); if (%$unseenModulesRef) { note ("The following modules were updated but not built:"); foreach my $modulename (keys %$unseenModulesRef) { note ("\t$modulename"); } } # It's possible if build fails on first module that git or svn is still # running. Make them stop too. if (waitpid ($monitorPid, WNOHANG) == 0) { kill 'INT', $monitorPid; # Exit code is in $?. waitpid ($monitorPid, 0); $result = 1 if $? != 0; } return $result; } # Function: _handle_install # # Handles the installation process. Simply calls 'make install' in the build # directory, though there is also provision for cleaning the build directory # afterwards, or stopping immediately if there is a build failure (normally # every built module is attempted to be installed). # # Parameters: # 1. Build Context, from which the install list is generated. # # Return value is a shell-style success code (0 == success) sub _handle_install { my $ctx = assert_isa(shift, 'ksb::BuildContext'); my @modules = $ctx->modulesInPhase('install'); @modules = grep { $_->buildSystem()->needsInstalled() } (@modules); my $result = 0; for my $module (@modules) { $ctx->resetEnvironment(); $result = $module->install() || $result; if ($result && $module->getOption('stop-on-failure')) { note ("y[Stopping here]."); return 1; # Error } } return $result; } # Function: _handle_uninstall # # Handles the uninstal process. Simply calls 'make uninstall' in the build # directory, while assuming that Qt or CMake actually handles it. # # The order of the modules is often significant, and it may work better to # uninstall modules in reverse order from how they were installed. However this # code does not automatically reverse the order; modules are uninstalled in the # order determined by the build context. # # This function obeys the 'stop-on-failure' option supported by _handle_install. # # Parameters: # 1. Build Context, from which the uninstall list is generated. # # Return value is a shell-style success code (0 == success) sub _handle_uninstall { my $ctx = assert_isa(shift, 'ksb::BuildContext'); my @modules = $ctx->modulesInPhase('uninstall'); @modules = grep { $_->buildSystem()->needsInstalled() } (@modules); my $result = 0; for my $module (@modules) { $ctx->resetEnvironment(); $result = $module->uninstall() || $result; if ($result && $module->getOption('stop-on-failure')) { note ("y[Stopping here]."); return 1; # Error } } return $result; } # Function: _handle_monitoring # # This is the main subroutine for the monitoring process when using IPC::Pipe. # It reads in all status reports from the source update process and then holds # on to them. When the build process is ready to read information we send what # we have. Otherwise we're waiting on the update process to send us something. # # This convoluted arrangement is required to allow the source update # process to go from start to finish without undue interruption on it waiting # to write out its status to the build process (which is usually busy). # # Parameters: # 1. the IPC object to use to send to build process. # 2. the IPC object to use to receive from update process. # # Returns 0 on success, non-zero on failure. sub _handle_monitoring { my ($ipcToBuild, $ipcFromUpdater) = @_; my @msgs; # Message queue. # We will write to the build process and read from the update process. my $sendFH = $ipcToBuild->{fh} || croak_runtime('??? missing pipe to build proc'); my $recvFH = $ipcFromUpdater->{fh} || croak_runtime('??? missing pipe from monitor'); my $readSelector = IO::Select->new($recvFH); my $writeSelector = IO::Select->new($sendFH); # Start the loop. We will be waiting on either read or write ends. # Whenever select() returns we must check both sets. while ( my ($readReadyRef, $writeReadyRef) = IO::Select->select($readSelector, $writeSelector, undef)) { if (!$readReadyRef && !$writeReadyRef) { # Some kind of error occurred. return 1; } # Check for source updates first. if (@{$readReadyRef}) { undef $@; my $msg = eval { $ipcFromUpdater->receiveMessage(); }; # undef msg indicates EOF, so check for exception obj specifically die $@ if $@; # undef can be returned on EOF as well as error. EOF means the # other side is presumably done. if (! defined $msg) { $readSelector->remove($recvFH); last; # Select no longer needed, just output to build. } else { push @msgs, $msg; # We may not have been waiting for write handle to be ready if # we were blocking on an update from updater thread. $writeSelector->add($sendFH) unless $writeSelector->exists($sendFH); } } # Now check for build updates. if (@{$writeReadyRef}) { # If we're here the update is still going. If we have no messages # to send wait for that first. if (not @msgs) { $writeSelector->remove($sendFH); } else { # Send the message (if we got one). if (!$ipcToBuild->sendMessage(shift @msgs)) { error ("r[mon]: Build process stopped too soon! r[$!]"); return 1; } } } } # Send all remaining messages. while (@msgs) { if (!$ipcToBuild->sendMessage(shift @msgs)) { error ("r[mon]: Build process stopped too soon! r[$!]"); return 1; } } $ipcToBuild->close(); return 0; } # Function: _applyModuleFilters # # Applies any module-specific filtering that is necessary after reading command # line and rc-file options. (This is as opposed to phase filters, which leave # each module as-is but change the phases they operate as part of, this # function could remove a module entirely from the build). # # Used for --resume-{from,after} and --stop-{before,after}, but more could be # added in theory. # This subroutine supports --{resume,stop}-* for both modules and module-sets. # # Parameters: # ctx - in use. # @modules - List of or to apply filters on. # # Returns: # list of or with any inclusion/exclusion filters # applied. Do not assume this list will be a strict subset of the input list, # however the order will not change amongst the input modules. sub _applyModuleFilters { my $ctx = assert_isa(shift, 'ksb::BuildContext'); my @moduleList = @_; if (!$ctx->getOption('resume-from') && !$ctx->getOption('resume-after') && !$ctx->getOption('stop-before') && !$ctx->getOption('stop-after')) { debug ("No command-line filter seems to be present."); return @moduleList; } if ($ctx->getOption('resume-from') && $ctx->getOption('resume-after')) { # This one's an error. error (<getOption('stop-before') && $ctx->getOption('stop-after')) { # This one's an error. error (<getOption('resume-from') || $ctx->getOption('resume-after'); my $startIndex = scalar @moduleList; if ($resumePoint) { debug ("Looking for $resumePoint for --resume-* option"); # || 0 is a hack to force Boolean context. my $filterInclusive = $ctx->getOption('resume-from') || 0; my $found = 0; for (my $i = 0; $i < scalar @moduleList; $i++) { my $module = $moduleList[$i]; $found = $module->name() eq $resumePoint; if ($found) { $startIndex = $filterInclusive ? $i : $i + 1; $startIndex = min($startIndex, scalar @moduleList - 1); last; } } } else { $startIndex = 0; } my $stopPoint = $ctx->getOption('stop-before') || $ctx->getOption('stop-after'); my $stopIndex = 0; if ($stopPoint) { debug ("Looking for $stopPoint for --stop-* option"); # || 0 is a hack to force Boolean context. my $filterInclusive = $ctx->getOption('stop-before') || 0; my $found = 0; for (my $i = $startIndex; $i < scalar @moduleList; $i++) { my $module = $moduleList[$i]; $found = $module->name() eq $stopPoint; if ($found) { $stopIndex = $i - ($filterInclusive ? 1 : 0); last; } } } else { $stopIndex = scalar @moduleList - 1; } if ($startIndex > $stopIndex || scalar @moduleList == 0) { # Lost all modules somehow. croak_runtime("Unknown resume -> stop point $resumePoint -> $stopPoint."); } return @moduleList[$startIndex .. $stopIndex]; } # This defines the factory function needed for lower-level code to properly be # able to create ksb::Module objects from just the module name, while still # having the options be properly set and having the module properly tied into a # context. sub _defineNewModuleFactory { my ($self, $resolver) = @_; my $ctx = $self->context(); $self->{module_factory} = sub { # We used to need a special module-set to ignore virtual deps (they # would throw errors if the name did not exist). But, the resolver # handles that fine as well. return $resolver->resolveModuleIfPresent(shift); }; } -# This function converts any 'l10n' references on the command line to return a l10n -# module with the proper build system, scm type, etc. -# -# The languages are selected using global/kde-languages (which should be used -# exclusively from the configuration file). -sub _expandl10nModules -{ - my ($ctx, @modules) = @_; - my $l10n = 'l10n-kde4'; - - assert_isa($ctx, 'ksb::BuildContext'); - - # Only filter if 'l10n' is actually present in list. - my @matches = grep {$_->name() =~ /^(?:$l10n|l10n)$/} @modules; - my @langs = split(' ', $ctx->getOption('kde-languages')); - - return @modules if (!@matches || !@langs); - - my $l10nModule; - for my $match (@matches) - { - # Remove all instances of l10n. - @modules = grep {$_->name() ne $match->name()} @modules; - - # Save l10n module if user had it in config. We only save the first - # one encountered though. - $l10nModule //= $match; - } - - # No l10n module? Just create one. - $l10nModule //= ksb::Module->new($ctx, $l10n); - - whisper ("\tAdding languages ", join(';', @langs), " to build."); - - $l10nModule->setScmType('l10n'); - my $scm = $l10nModule->scm(); - - # Add all required directories to the l10n module. Its buildsystem should - # know to skip scripts and templates. - $scm->setLanguageDirs(qw/scripts templates/, @langs); - $l10nModule->setBuildSystem($scm); - - push @modules, $l10nModule; - return @modules; -} - # Updates the built-in phase list for all Modules passed into this function in # accordance with the options set by the user. sub _updateModulePhases { whisper ("Filtering out module phases."); for my $module (@_) { if ($module->getOption('manual-update') || $module->getOption('no-svn') || $module->getOption('no-src')) { $module->phases()->clear(); next; } if ($module->getOption('manual-build')) { $module->phases()->filterOutPhase('build'); $module->phases()->filterOutPhase('test'); $module->phases()->filterOutPhase('install'); } $module->phases()->filterOutPhase('install') unless $module->getOption('install-after-build'); $module->phases()->addPhase('test') if $module->getOption('run-tests'); } return @_; } # This subroutine extract the value from options of the form --option=value, # which can also be expressed as --option value. # # The first parameter is the option that the user passed to the cmd line (e.g. # --prefix=/opt/foo). # The second parameter is a reference to the list of command line options. # # The return value is the value of the option (the list of options might be # shorter by 1, copy it if you don't want it to change), or undef if no value # was provided. sub _extractOptionValue { my ($option, $options_ref) = @_; if ($option =~ /=/) { my @value = split(/=/, $option); shift @value; # We don't need the first one, that the --option part. return if (scalar @value == 0); # If we have more than one element left in @value it's because the # option itself has an = in it, make sure it goes back in the answer. return join('=', @value); } return if scalar @{$options_ref} == 0; return shift @{$options_ref}; } # Like _extractOptionValue, but throws an exception if the value is not # actually present, so you don't have to check for it yourself. If you do get a # return value, it will be defined to something. sub _extractOptionValueRequired { my ($option, $options_ref) = @_; my $returnValue = _extractOptionValue($option, $options_ref); if (not defined $returnValue) { croak_runtime("Option $option needs to be set to some value instead of left blank"); } return $returnValue; } # Function: _cleanup_log_directory # # This function removes log directories from old kdesrc-build runs. All log # directories not referenced by $log_dir/latest somehow are made to go away. # # Parameters: # 1. Build context. # # No return value. sub _cleanup_log_directory { my $ctx = assert_isa(shift, 'ksb::BuildContext'); my $logdir = $ctx->getSubdirPath('log-dir'); return 0 if ! -e "$logdir/latest"; # Could happen for error on first run... # This glob relies on the date being in the specific format YYYY-MM-DD-ID my @dirs = bsd_glob("$logdir/????-??-??-??/", GLOB_NOSORT); my @needed = _reachableModuleLogs("$logdir/latest"); # Convert a list to a hash lookup since Perl lacks a "list-has" my %needed_table; @needed_table{@needed} = (1) x @needed; my $length = scalar @dirs - scalar @needed; if ($length > 15) { # Arbitrary man is arbitrary note ("Removing y[b[$length] out of g[b[$#dirs] old log directories (this may take some time)..."); } elsif ($length > 0) { info ("Removing g[b[$length] out of g[b[$#dirs] old log directories..."); } for my $dir (@dirs) { my ($id) = ($dir =~ m/(\d\d\d\d-\d\d-\d\d-\d\d)/); safe_rmtree($dir) unless $needed_table{$id}; } } # Function: _output_failed_module_list # # Print out an error message, and a list of modules that match that error # message. It will also display the log file name if one can be determined. # The message will be displayed all in uppercase, with PACKAGES prepended, so # all you have to do is give a descriptive message of what this list of # packages failed at doing. # # No message is printed out if the list of failed modules is empty, so this # function can be called unconditionally. # # Parameters: # 1. Build Context # 2. Message to print (e.g. 'failed to foo') # 3. List of ksb::Modules that had failed to foo # # No return value. sub _output_failed_module_list { my ($ctx, $message, @fail_list) = @_; assert_isa($ctx, 'ksb::BuildContext'); $message = uc $message; # Be annoying if (@fail_list) { debug ("Message is $message"); debug ("\tfor ", join(', ', @fail_list)); } if (scalar @fail_list > 0) { my $homedir = $ENV{'HOME'}; my $logfile; warning ("\nr[b[<<< PACKAGES $message >>>]"); for my $module (@fail_list) { $logfile = $module->getOption('#error-log-file'); # async updates may cause us not to have a error log file stored. There's only # one place it should be though, take advantage of side-effect of log_command() # to find it. if (not $logfile) { my $logdir = $module->getLogDir() . "/error.log"; $logfile = $logdir if -e $logdir; } $logfile = "No log file" unless $logfile; $logfile =~ s|$homedir|~|; warning ("r[$module]") if pretending(); warning ("r[$module] - g[$logfile]") if not pretending(); } } } # Function: _output_failed_module_lists # # This subroutine reads the list of failed modules for each phase in the build # context and calls _output_failed_module_list for all the module failures. # # Parameters: # 1. Build context # # Return value: # None sub _output_failed_module_lists { my $ctx = assert_isa(shift, 'ksb::BuildContext'); # This list should correspond to the possible phase names (although # it doesn't yet since the old code didn't, TODO) for my $phase ($ctx->phases()->phases()) { my @failures = $ctx->failedModulesInPhase($phase); _output_failed_module_list($ctx, "failed to $phase", @failures); } # See if any modules fail continuously and warn specifically for them. my @super_fail = grep { ($_->getPersistentOption('failure-count') // 0) > 3 } (@{$ctx->moduleList()}); if (@super_fail) { warning ("\nThe following modules have failed to build 3 or more times in a row:"); warning ("\tr[b[$_]") foreach @super_fail; warning ("\nThere is probably a local error causing this kind of consistent failure, it"); warning ("is recommended to verify no issues on the system.\n"); } } # Function: _installTemplatedFile # # This function takes a given file and a build context, and installs it to a # given location while expanding out template entries within the source file. # # The template language is *extremely* simple: <% foo %> is replaced entirely # with the result of $ctx->getOption(foo, 'no-inherit'). If the result # evaluates false for any reason than an exception is thrown. No quoting of # any sort is used in the result, and there is no way to prevent expansion of # something that resembles the template format. # # Multiple template entries on a line will be replaced. # # The destination file will be created if it does not exist. If the file # already exists then an exception will be thrown. # # Error handling: Any errors will result in an exception being thrown. # # Parameters: # 1. Pathname to the source file (use absolute paths) # 2. Pathname to the destination file (use absolute paths) # 3. Build context to use for looking up template values # # Return value: There is no return value. sub _installTemplatedFile { my ($sourcePath, $destinationPath, $ctx) = @_; assert_isa($ctx, 'ksb::BuildContext'); open (my $input, '<', $sourcePath) or croak_runtime("Unable to open template source $sourcePath: $!"); open (my $output, '>', $destinationPath) or croak_runtime("Unable to open template output $destinationPath: $!"); while (!eof ($input)) { my $line = readline($input); if (!defined ($line)) { croak_runtime("Failed to read from $sourcePath at line $.: $!"); unlink($destinationPath); } # Some lines should only be present in the source as they aid with testing. next if $line =~ /kdesrc-build: filter/; $line =~ s { <% \s* # Template bracket and whitespace ([^\s%]+) # Capture variable name \s*%> # remaining whitespace and closing bracket } { $ctx->getOption($1, 'module') // croak_runtime("Invalid variable $1") }gxe; # Replace all matching expressions, use extended regexp w/ # comments, and replacement is Perl code to execute. (print $output $line) or croak_runtime("Unable to write line to $destinationPath at line $.: $!"); } } # Function: _installCustomFile # # This function installs a source file to a destination path, assuming the # source file is a "templated" source file (see also _installTemplatedFile), and # records a digest of the file actually installed. This function will overwrite # a destination if the destination is identical to the last-installed file. # # Error handling: Any errors will result in an exception being thrown. # # Parameters: # 1. Build context to use for looking up template values, # 2. The full path to the source file. # 3. The full path to the destination file (incl. name) # 4. The key name to use for searching/recording installed MD5 digest. # # Return value: There is no return value. sub _installCustomFile { use File::Copy qw(copy); my $ctx = assert_isa(shift, 'ksb::BuildContext'); my ($sourceFilePath, $destFilePath, $md5KeyName) = @_; my $baseName = basename($sourceFilePath); if (-e $destFilePath) { my $existingMD5 = $ctx->getPersistentOption('/digests', $md5KeyName) // ''; if (fileDigestMD5($destFilePath) ne $existingMD5) { if (!$ctx->getOption('#delete-my-settings')) { error ("\tr[*] Installing \"b[$baseName]\" would overwrite an existing file:"); error ("\tr[*] y[b[$destFilePath]"); error ("\tr[*] If this is acceptable, please delete the existing file and re-run,"); error ("\tr[*] or pass b[--delete-my-settings] and re-run."); return; } elsif (!pretending()) { copy ($destFilePath, "$destFilePath.kdesrc-build-backup"); } } } if (!pretending()) { _installTemplatedFile($sourceFilePath, $destFilePath, $ctx); $ctx->setPersistentOption('/digests', $md5KeyName, fileDigestMD5($destFilePath)); } } # Function: _installCustomSessionDriver # # This function installs the included sample .xsession and environment variable # setup files, and records the md5sum of the installed results. # # If a file already exists, then its md5sum is taken and if the same as what # was previously installed, is overwritten. If not the same, the original file # is left in place and the .xsession is instead installed to # .xsession-kdesrc-build # # Error handling: Any errors will result in an exception being thrown. # # Parameters: # 1. Build context to use for looking up template values, # # Return value: There is no return value. sub _installCustomSessionDriver { use File::Copy qw(copy); my $ctx = assert_isa(shift, 'ksb::BuildContext'); my $envScript = findDataResource('sample-kde-env-master.sh'); my $sessionScript = findDataResource('sample-xsession.sh'); if (!$envScript || !$sessionScript) { warning ("b[*] Unable to find helper files to setup a login session."); warning ("b[*] You will have to setup login yourself, or install kdesrc-build properly."); return; } my $destDir = $ENV{XDG_CONFIG_HOME} || "$ENV{HOME}/.config"; super_mkdir($destDir) unless -d $destDir; _installCustomFile($ctx, $envScript, "$destDir/kde-env-master.sh", 'kde-env-master-digest'); _installCustomFile($ctx, $sessionScript, "$ENV{HOME}/.xsession", 'xsession-digest') if $ctx->getOption('install-session-driver'); if (!pretending()) { if ($ctx->getOption('install-session-driver') && !chmod (0744, "$ENV{HOME}/.xsession")) { error ("\tb[r[*] Error making b[~/.xsession] executable: $!"); error ("\tb[r[*] If this file is not executable you may not be able to login!"); }; } } # Function: _checkForEssentialBuildPrograms # # This subroutine checks for programs which are absolutely essential to the # *build* process and returns false if they are not all present. Right now this # just means qmake and cmake (although this depends on what modules are # actually present in the build context). # # Parameters: # 1. Build context # # Return value: # None sub _checkForEssentialBuildPrograms { my $ctx = assert_isa(shift, 'ksb::BuildContext'); return 1 if pretending(); my @buildModules = $ctx->modulesInPhase('build'); my %requiredPrograms; my %modulesRequiringProgram; foreach my $module ($ctx->modulesInPhase('build')) { my @progs = $module->buildSystem()->requiredPrograms(); # Deliberately used @, since requiredPrograms can return a list. @requiredPrograms{@progs} = 1; foreach my $prog (@progs) { $modulesRequiringProgram{$prog} //= { }; $modulesRequiringProgram{$prog}->{$module->name()} = 1; } } my $wasError = 0; for my $prog (keys %requiredPrograms) { my %requiredPackages = ( qmake => 'Qt', cmake => 'CMake', ); my $programPath = absPathToExecutable($prog); # qmake is not necessarily named 'qmake' if (!$programPath && $prog eq 'qmake') { $programPath = ksb::BuildSystem::QMake::absPathToQMake(); } if (!$programPath) { # Don't complain about Qt if we're building it... if ($prog eq 'qmake' && ( grep { $_->buildSystemType() eq 'Qt' } (@buildModules)) || pretending() ) { next; } $wasError = 1; my $reqPackage = $requiredPackages{$prog} || $prog; my @modulesNeeding = keys %{$modulesRequiringProgram{$prog}}; local $, = ', '; # List separator in output error (<<"EOF"); Unable to find r[b[$prog]. This program is absolutely essential for building the modules: y[@modulesNeeding]. Please ensure the development packages for $reqPackage are installed by using your distribution's package manager. You can also see the https://techbase.kde.org/Getting_Started/Build/Distributions page for information specific to your distribution (although watch for outdated information :( ). EOF } } return !$wasError; } # Function: _reachableModuleLogs # # Returns a list of module directory IDs that must be kept due to being # referenced from the "latest" symlink. # # This function may call itself recursively if needed. # # Parameters: # 1. The log directory under which to search for symlinks, including the "/latest" # part of the path. sub _reachableModuleLogs { my $logdir = shift; my @dirs; # A lexicalized var (my $foo) is required in face of recursiveness. opendir(my $fh, $logdir) or croak_runtime("Can't opendir $logdir: $!"); my $dir = readdir($fh); while(defined $dir) { if (-l "$logdir/$dir") { my $link = readlink("$logdir/$dir"); push @dirs, $link; } elsif ($dir !~ /^\.{1,2}$/) { # Skip . and .. directories (this is a great idea, trust me) push @dirs, _reachableModuleLogs("$logdir/$dir"); } $dir = readdir $fh; } closedir $fh; # Extract numeric IDs from directory names. @dirs = map { m/(\d{4}-\d\d-\d\d-\d\d)/ } (@dirs); # Convert to unique list by abusing hash keys. my %tempHash; @tempHash{@dirs} = (); return keys %tempHash; } # Installs the given subroutine as a signal handler for a set of signals which # could kill the program. # # First parameter is a reference to the sub to act as the handler. sub _installSignalHandlers { my $handlerRef = shift; my @signals = qw/HUP INT QUIT ABRT TERM PIPE/; @SIG{@signals} = ($handlerRef) x scalar @signals; } # Ensures that basic one-time setup to actually *use* installed software is # performed, including .kdesrc-buildrc setup if necessary. # # Returns the appropriate exitcode to pass to the exit function sub performInitialUserSetup { my $self = shift; return ksb::FirstRun::setupUserSystem(); } # Shows a help message and version. Does not exit. sub _showHelpMessage { my $scriptVersion = scriptVersion(); say < and others, and is distributed under the terms of the GNU GPL v2. This script automates the download, build, and install process for KDE software using the latest available source code. Configuration is controlled from "\$PWD/kdesrc-buildrc" or "~/.kdesrc-buildrc". See kdesrc-buildrc-sample for an example. Usage: \$ $0 [--options] [module names] All configured modules are built if none are listed. Important Options: --pretend Don't actually take major actions, instead describe what would be done. --no-src Don't update source code, just build/install. --src-only Only update the source code --refresh-build Start the build from scratch. --rc-file= Read configuration from filename instead of default. --initial-setup Installs Plasma env vars (~/.bashrc), required system pkgs, and a base kdesrc-buildrc. --resume-from= Skips modules until just before or after the given --resume-after= package, then operates as normal. --stop-before= Stops just before or after the given package is --stop-after= reached. --include-dependencies Also builds KDE-based dependencies of given modules. --stop-on-failure Stops the build as soon as a package fails to build. More docs at https://docs.kde.org/trunk5/en/extragear-utils/kdesrc-build/ Supported configuration options: https://go.kde.org/u/ksboptions Supported cmdline options: https://go.kde.org/u/ksbcmdline DONE # Look for indications this is the first run. if (! -e "./kdesrc-buildrc" && ! -e "$ENV{HOME}/.kdesrc-buildrc") { say <{context}; } sub metadataModule { my $self = shift; return $self->{metadata_module}; } sub runMode { my $self = shift; return $self->{run_mode}; } sub modules { my $self = shift; return @{$self->{modules}}; } 1; diff --git a/modules/ksb/BuildSystem.pm b/modules/ksb/BuildSystem.pm index 2053f3b..08bb1a7 100644 --- a/modules/ksb/BuildSystem.pm +++ b/modules/ksb/BuildSystem.pm @@ -1,501 +1,494 @@ package ksb::BuildSystem 0.30; # Base module for the various build systems, includes built-in implementations of # generic functions and supports hooks for subclasses to provide needed detailed # functionality. use strict; use warnings; use 5.014; use ksb::BuildException; use ksb::Debug; use ksb::Util; use ksb::StatusView; use List::Util qw(first); sub new { my ($class, $module) = @_; my $self = bless { module => $module }, $class; # This is simply the 'default' build system at this point, also used for # KF5. if ($class ne 'ksb::BuildSystem::KDE4') { _maskGlobalBuildSystemOptions($self); } return $self; } # Removes or masks global build system-related options, so that they aren't # accidentally picked up for use with our non-default build system. # Module-specific options are left intact. sub _maskGlobalBuildSystemOptions { my $self = shift; my $module = $self->module(); my $ctx = $module->buildContext(); my @buildSystemOptions = qw( cmake-options configure-flags custom-build-command cxxflags make-options run-tests use-clean-install ); for my $opt (@buildSystemOptions) { # If an option is present, and not set at module-level, it must be # global. Can't use getOption() method due to recursion. if ($ctx->{options}->{$opt} && !$module->{options}->{$opt}) { $module->{options}->{$opt} = ''; } } } sub module { my $self = shift; return $self->{module}; } # Subroutine to determine if a given module needs to have the build system # recreated from scratch. # If so, it returns a non empty string sub needsRefreshed { my $self = assert_isa(shift, 'ksb::BuildSystem'); my $module = $self->module(); my $builddir = $module->fullpath('build'); my $confFileKey = $self->configuredModuleFileName(); if (not -e "$builddir") { return "the build directory doesn't exist"; } if (-e "$builddir/.refresh-me") { return "the last configure failed"; # see Module.pm } if ($module->getOption("refresh-build")) { return "the option refresh-build was set"; } if (($module->getPersistentOption('failure-count') // 0) > 1) { return "the module has failed to build " . $module->getPersistentOption('failure-count') . " times in a row"; } if (not -e "$builddir/$confFileKey") { return "$builddir/$confFileKey is missing"; } return ""; } # Returns true if the given subdirectory (reference from the module's root source directory) # can be built or not. Should be reimplemented by subclasses as appropriate. sub isSubdirBuildable { return 1; } # Called by the module being built before it runs its build/install process. Should # setup any needed environment variables, build context settings, etc., in preparation # for the build and install phases. sub prepareModuleBuildEnvironment { my ($self, $ctx, $module, $prefix) = @_; } # Returns true if the module should have make install run in order to be # used, or false if installation is not required or possible. sub needsInstalled { return 1; } # This should return a list of executable names that must be present to # even bother attempting to use this build system. An empty list should be # returned if there's no required programs. sub requiredPrograms { return; } sub name { return 'generic'; } # Returns a list of possible build commands to run, any one of which should # be supported by the build system. sub buildCommands { # Non Linux systems can sometimes fail to build when GNU Make would work, # so prefer GNU Make if present, otherwise try regular make. return 'gmake', 'make'; } # Return value style: boolean sub buildInternal { my $self = shift; return $self->safe_make({ target => undef, message => 'Compiling...', 'make-options' => [ split(' ', $self->module()->getOption('make-options')), ], logbase => 'build', subdirs => [ split(' ', $self->module()->getOption("checkout-only")) ], })->{was_successful}; } # Return value style: boolean sub configureInternal { # It is possible to make it here if there's no source dir and if we're # pretending. If we're not actually pretending then this should be a # bug... return 1 if pretending(); croak_internal('We were not supposed to get to this point...'); } # Returns name of file that should exist (relative to the module's build directory) # if the module has been configured. sub configuredModuleFileName { my $self = shift; return 'Makefile'; } # Runs the testsuite for the given module. # Returns true if a testsuite is present and all tests passed, false otherwise. sub runTestsuite { my $self = shift; my $module = $self->module(); info ("\ty[$module] does not support the b[run-tests] option"); return 0; } # Used to install a module (that has already been built, tested, etc.) # All options passed are prefixed to the eventual command to be run. # Returns boolean false if unable to install, true otherwise. sub installInternal { my $self = shift; my $module = $self->module(); my @cmdPrefix = @_; return $self->safe_make ({ target => 'install', message => 'Installing..', 'prefix-options' => [@cmdPrefix], subdirs => [ split(' ', $module->getOption("checkout-only")) ], })->{was_successful}; } # Used to uninstall a previously installed module. # All options passed are prefixed to the eventual command to be run. # Returns boolean false if unable to uninstall, true otherwise. sub uninstallInternal { my $self = shift; my $module = $self->module(); my @cmdPrefix = @_; return $self->safe_make ({ target => 'uninstall', message => "Uninstalling g[$module]", 'prefix-options' => [@cmdPrefix], subdirs => [ split(' ', $module->getOption("checkout-only")) ], })->{was_successful}; } # Subroutine to clean the build system for the given module. Works by # recursively deleting the directory and then recreating it. # Returns 0 for failure, non-zero for success. sub cleanBuildSystem { my $self = assert_isa(shift, 'ksb::BuildSystem'); my $module = $self->module(); my $srcdir = $module->fullpath('source'); my $builddir = $module->fullpath('build'); if (pretending()) { pretend ("\tWould have cleaned build system for g[$module]"); return 1; } # Use an existing directory if (-e $builddir && $builddir ne $srcdir) { info ("\tRemoving files in build directory for g[$module]"); # This variant of log_command runs the sub prune_under_directory($builddir) # in a forked child, so that we can log its output. if (log_command($module, 'clean-builddir', [ 'kdesrc-build', 'main::prune_under_directory', $builddir ])) { error (" r[b[*]\tFailed to clean build directory. Verify the permissions are correct."); return 0; # False for this function. } # Let users know we're done so they don't wonder why rm -rf is taking so # long and oh yeah, why's my HD so active?... info ("\tOld build system cleaned, starting new build system."); } # or create the directory elsif (!super_mkdir ($builddir)) { error ("\tUnable to create directory r[$builddir]."); return 0; } return 1; } sub needsBuilddirHack { return 0; # By default all build systems are assumed to be sane } # Return convention: boolean sub createBuildSystem { my $self = assert_isa(shift, 'ksb::BuildSystem'); my $module = $self->module(); my $builddir = $module->fullpath('build'); my $srcdir = $module->fullpath('source'); if (! -e "$builddir" && !super_mkdir("$builddir")) { error ("\tUnable to create build directory for r[$module]!!"); return 0; } - if ($builddir ne $srcdir && $self->needsBuilddirHack() && 0 != log_command($module, 'lndir', - ['kdesrc-build', 'main::safe_lndir', $srcdir, $builddir])) - { - error ("\tUnable to setup symlinked build directory for r[$module]!!"); - return 0; - } - return 1; } # Subroutine to run the build command with the arguments given by the # passed hash. # # In addition to finding the proper executable, this function handles the # step of running the build command for individual subdirectories (as # specified by the checkout-only option to the module). Due to the various # ways the build command is called by this script, it is required to pass # customization options in a hash: # { # target => undef, or a valid build target e.g. 'install', # message => 'Compiling.../Installing.../etc.' # make-options => [ list of command line arguments to pass to make. See # make-options ], # prefix-options => [ list of command line arguments to prefix *before* the # make command, used for make-install-prefix support for # e.g. sudo ], # logbase => 'base-log-filename', # subdirs => [ list of subdirectories of the module to build, # relative to the module's own build directory. ] # } # # target and message are required. logbase is required if target is left # undefined, but otherwise defaults to the same value as target. # # Note that the make command is based on the results of the 'buildCommands' # subroutine which should be overridden if necessary by subclasses. Each # command should be the command name (i.e. no path). The user may override # the command used (for build only) by using the 'custom-build-command' # option. # # The first command name found which resolves to an executable on the # system will be used, if no command this function will fail. # # The first argument should be the ksb::Module object to be made. # The second argument should be the reference to the hash described above. # # Returns a hashref: # { # was_successful => $bool, (if successful) # } sub safe_make (@) { my ($self, $optsRef) = @_; assert_isa($self, 'ksb::BuildSystem'); my $module = $self->module(); # Convert the path to an absolute path since I've encountered a sudo # that is apparently unable to guess. Maybe it's better that it # doesn't guess anyways from a security point-of-view. my $buildCommand = first { absPathToExecutable($_) } $self->buildCommands(); my @buildCommandLine = $buildCommand; # Check for custom user command. We support command line options being # passed to the command as well. my $userCommand = $module->getOption('custom-build-command'); if ($userCommand) { @buildCommandLine = split_quoted_on_whitespace($userCommand); $buildCommand = absPathToExecutable($buildCommandLine[0]); } if (!$buildCommand) { $buildCommand = $userCommand || $self->buildCommands(); error (" r[b[*] Unable to find the g[$buildCommand] executable!"); return { was_successful => 0 }; } # Make it prettier if pretending (Remove leading directories). $buildCommand =~ s{^/.*/}{} if pretending(); shift @buildCommandLine; # $buildCommand is already the first entry. # Simplify code by forcing lists to exist. $optsRef->{'prefix-options'} //= [ ]; $optsRef->{'make-options'} //= [ ]; $optsRef->{'subdirs'} //= [ ]; my @prefixOpts = @{$optsRef->{'prefix-options'}}; # If using sudo ensure that it doesn't wait on tty, but tries to read from # stdin (which should fail as we redirect that from /dev/null) if (@prefixOpts && $prefixOpts[0] eq 'sudo' && !grep { /^-S$/ } @prefixOpts) { splice (@prefixOpts, 1, 0, '-S'); # Add -S right after 'sudo' } # Assemble arguments my @args = (@prefixOpts, $buildCommand, @buildCommandLine); push @args, $optsRef->{target} if $optsRef->{target}; push @args, @{$optsRef->{'make-options'}}; # Will be output by _runBuildCommand my $buildMessage = $optsRef->{message}; # Here we're attempting to ensure that we either run the build command # in each subdirectory, *or* for the whole module, but not both. my @dirs = @{$optsRef->{subdirs}}; push (@dirs, "") if scalar @dirs == 0; for my $subdir (@dirs) { # Some subdirectories shouldn't have the build command run within # them. next unless $self->isSubdirBuildable($subdir); my $logname = $optsRef->{logbase} // $optsRef->{logfile} // $optsRef->{target}; if ($subdir ne '') { $logname = $logname . "-$subdir"; # Remove slashes in favor of something else. $logname =~ tr{/}{-}; # Mention subdirectory that we're working on, move ellipsis # if present. if ($buildMessage =~ /\.\.\.$/) { $buildMessage =~ s/(\.\.\.)?$/ subdirectory g[$subdir]$1/; } } my $builddir = $module->fullpath('build') . "/$subdir"; $builddir =~ s/\/*$//; # Remove trailing / p_chdir ($builddir); return $self->_runBuildCommand($buildMessage, $logname, \@args); }; return { was_successful => 1 }; } # Subroutine to run make and process the build process output in order to # provide completion updates. This procedure takes the same arguments as # log_command() (described here as well), except that the callback argument # is not used. # # First parameter is the message to display to the user while the build # happens. # Second parameter is the name of the log file to use (relative to the log # directory). # Third parameter is a reference to an array with the command and its # arguments. i.e. ['command', 'arg1', 'arg2'] # # The return value is a hashref as defined by safe_make sub _runBuildCommand { my ($self, $message, $filename, $argRef) = @_; my $module = $self->module(); my $resultRef = { was_successful => 0 }; my $ctx = $module->buildContext(); # There are situations when we don't want progress output: # 1. If we're not printing to a terminal. # 2. When we're debugging (we'd interfere with debugging output). if (! -t STDERR || debugging()) { note("\t$message"); $resultRef->{was_successful} = (0 == log_command($module, $filename, $argRef)); return $resultRef; } my $time = time; my $statusViewer = $ctx->statusViewer(); $statusViewer->setStatus("\t$message"); $statusViewer->update(); # TODO More details my $warnings = 0; # w00t. Check out the closure! Maks would be so proud. my $log_command_callback = sub { my $input = shift; return if not defined $input; my ($percentage) = ($input =~ /^\[\s*([0-9]+)%]/); if ($percentage) { $statusViewer->setProgressTotal(100); $statusViewer->setProgress($percentage); } else { my ($x, $y) = ($input =~ /^\[([0-9]+)\/([0-9]+)] /); if ($x && $y) { # ninja-syntax $statusViewer->setProgressTotal($y); $statusViewer->setProgress($x); } } $warnings++ if ($input =~ /warning: /); }; $resultRef->{was_successful} = (0 == log_command($module, $filename, $argRef, { callback => $log_command_callback })); $resultRef->{warnings} = $warnings; # Cleanup TTY output. $time = prettify_seconds(time - $time); my $status = $resultRef->{was_successful} ? "g[b[succeeded]" : "r[b[failed]"; $statusViewer->releaseTTY("\t$message $status (after $time)\n"); if ($warnings) { my $count = ($warnings < 3 ) ? 1 : ($warnings < 10 ) ? 2 : ($warnings < 30 ) ? 3 : 4; my $msg = sprintf("%s b[y[$warnings] %s", '-' x $count, '-' x $count); note ("\tNote: $msg compile warnings"); $self->{module}->setPersistentOption('last-compile-warnings', $warnings); } return $resultRef; } 1; diff --git a/modules/ksb/Module.pm b/modules/ksb/Module.pm index bf4f77d..721d816 100644 --- a/modules/ksb/Module.pm +++ b/modules/ksb/Module.pm @@ -1,970 +1,967 @@ package ksb::Module 0.20; # Class: Module # # Represents a source code module of some sort, which can be updated, built, # and installed. Includes a stringifying overload and can be sorted amongst # other ksb::Modules. use 5.014; use warnings; no if $] >= 5.018, 'warnings', 'experimental::smartmatch'; use parent qw(ksb::OptionsBase); use ksb::IPC; use ksb::Debug; use ksb::Util; -use ksb::l10nSystem; - use ksb::Updater::Svn; use ksb::Updater::Git; use ksb::Updater::Bzr; use ksb::Updater::KDEProject; use ksb::Updater::KDEProjectMetadata; use ksb::BuildException 0.20; use ksb::BuildSystem 0.30; use ksb::BuildSystem::Autotools; use ksb::BuildSystem::QMake; use ksb::BuildSystem::Qt4; use ksb::BuildSystem::KDE4; use ksb::BuildSystem::CMakeBootstrap; use ksb::ModuleSet::Null; use Storable 'dclone'; use Carp 'confess'; use Scalar::Util 'blessed'; use overload '""' => 'toString', # Add stringify operator. '<=>' => 'compare', ; sub new { my ($class, $ctx, $name) = @_; croak_internal ("Empty ksb::Module constructed") unless $name; my $self = ksb::OptionsBase::new($class); # If building a BuildContext instead of a ksb::Module, then the context # can't have been setup yet... my $contextClass = 'ksb::BuildContext'; if ($class ne $contextClass && (!blessed($ctx) || !$ctx->isa($contextClass))) { croak_internal ("Invalid context $ctx"); } # Clone the passed-in phases so we can be different. my $phases = dclone($ctx->phases()) if $ctx; my %newOptions = ( name => $name, scm_obj => undef, build_obj => undef, phases => $phases, context => $ctx, 'module-set' => undef, ); @{$self}{keys %newOptions} = values %newOptions; return $self; } sub phases { my $self = shift; return $self->{phases}; } sub moduleSet { my ($self) = @_; $self->{'module-set'} //= ksb::ModuleSet::Null->new(); return $self->{'module-set'}; } sub setModuleSet { my ($self, $moduleSet) = @_; assert_isa($moduleSet, 'ksb::ModuleSet'); $self->{'module-set'} = $moduleSet; } # Subroutine to retrieve a subdirectory path with tilde-expansion and # relative path handling. # The parameter is the option key (e.g. build-dir or log-dir) to read and # interpret. sub getSubdirPath { my ($self, $subdirOption) = @_; my $dir = $self->getOption($subdirOption); # If build-dir starts with a slash, it is an absolute path. return $dir if $dir =~ /^\//; # Make sure we got a valid option result. if (!$dir) { confess ("Reading option for $subdirOption gave empty \$dir!"); } # If it starts with a tilde, expand it out. if ($dir =~ /^~/) { $dir =~ s/^~/$ENV{'HOME'}/; } else { # Relative directory, tack it on to the end of $kdesrcdir. my $kdesrcdir = $self->getOption('source-dir'); $dir = "$kdesrcdir/$dir"; } return $dir; } # Method: getInstallPathComponents # # Returns the directory that a module should be installed in. # # NOTE: The return value is a hash. The key 'module' will return the final # module name, the key 'path' will return the full path to the module. The # key 'fullpath' will return their concatenation. # # For example, with $module == 'KDE/kdelibs', and no change in the dest-dir # option, you'd get something like: # # > { # > 'path' => '/home/user/kdesrc/KDE', # > 'module' => 'kdelibs', # > 'fullpath' => '/home/user/kdesrc/KDE/kdelibs' # > } # # If dest-dir were changed to e.g. extragear-multimedia, you'd get: # # > { # > 'path' => '/home/user/kdesrc', # > 'module' => 'extragear-multimedia', # > 'fullpath' => '/home/user/kdesrc/extragear-multimedia' # > } # # Parameters: # pathType - Either 'source' or 'build'. # # Returns: # hash (Not a hashref; See description). sub getInstallPathComponents { my $module = assert_isa(shift, 'ksb::Module'); my $type = shift; my $destdir = $module->destDir(); my $srcbase = $module->getSourceDir(); $srcbase = $module->getSubdirPath('build-dir') if $type eq 'build'; my $combined = "$srcbase/$destdir"; # Remove dup // $combined =~ s/\/+/\//; my @parts = split(/\//, $combined); my %result = (); $result{'module'} = pop @parts; $result{'path'} = join('/', @parts); $result{'fullpath'} = "$result{path}/$result{module}"; my $compatDestDir = $module->destDir($module->name()); my $fullCompatPath = "$srcbase/$compatDestDir"; # We used to have code here to migrate very old directory layouts. It was # removed as of about 2013-09-29. return %result; } # Do note that this returns the *base* path to the source directory, # without the module name or kde_projects stuff appended. If you want that # use subroutine fullpath(). sub getSourceDir { my $self = shift; return $self->getSubdirPath('source-dir'); } sub name { my $self = shift; return $self->{name}; } sub scm { my $self = shift; return $self->{scm_obj} if $self->{scm_obj}; # Look for specific setting of repository and svn-server. If both is # set it's a bug, if one is set, that's the type (because the user says # so...). Don't use getOption($key) as it will try to fallback to # global options. my $svn_status = $self->getOption('svn-server', 'module'); my $repository = $self->getOption('repository', 'module') // ''; my $rcfile = $self->buildContext()->rcFile(); if ($svn_status && $repository) { error (<{scm_obj} = ksb::Updater::Bzr->new($self); } # If it needs a repo it's git. Everything else is svn for now. $self->{scm_obj} //= $repository ? ksb::Updater::Git->new($self) : ksb::Updater::Svn->new($self); return $self->{scm_obj}; } sub setScmType { my ($self, $scmType) = @_; my $newType; given($scmType) { when('git') { $newType = ksb::Updater::Git->new($self); } when('proj') { $newType = ksb::Updater::KDEProject->new($self); } when('metadata') { $newType = ksb::Updater::KDEProjectMetadata->new($self); } - when('l10n') { $newType = ksb::l10nSystem->new($self); } when('svn') { $newType = ksb::Updater::Svn->new($self); } when('bzr') { $newType = ksb::Updater::Bzr->new($self); } default { $newType = undef; } } $self->{scm_obj} = $newType; } # Returns a string describing the scm platform of the given module. # Return value: 'git' or 'svn' at this point, as appropriate. sub scmType { my $self = shift; return $self->scm()->name(); } sub currentScmRevision { my $self = shift; return $self->scm()->currentRevisionInternal(); } # Returns a new build system object, given the appropriate name. # This is a sub-optimal way to fix the problem of allowing users to override # the detected build system (we could instead use introspection to figure out # available build systems at runtime). However, KISS... sub buildSystemFromName { my ($self, $name) = @_; my %buildSystemClasses = ( 'generic' => 'ksb::BuildSystem', 'qmake' => 'ksb::BuildSystem::QMake', 'cmake-bootstrap' => 'ksb::BuildSystem::CMakeBootstrap', 'kde' => 'ksb::BuildSystem::KDE4', 'qt' => 'ksb::BuildSystem::Qt4', 'autotools' => 'ksb::BuildSystem::Autotools', ); my $class = $buildSystemClasses{lc $name} // undef; return $class->new($self) if ($class); # Past here, no class found croak_runtime("Invalid build system $name requested"); } sub buildSystem { my $self = shift; if ($self->{build_obj} && $self->{build_obj}->name() ne 'generic') { return $self->{build_obj}; } if (my $userBuildSystem = $self->getOption('override-build-system')) { $self->{build_obj} = $self->buildSystemFromName($userBuildSystem); return $self->{build_obj}; } # If not set, let's guess. my $buildType; my $sourceDir = $self->fullpath('source'); if (($self->getOption('repository') =~ /gitorious\.org\/qt\//) || ($self->getOption('repository') =~ /^kde:qt$/) || (-e "$sourceDir/bin/syncqt")) { $buildType = ksb::BuildSystem::Qt4->new($self); } # This test must come before the KDE buildsystem's as cmake's own # bootstrap system also has CMakeLists.txt if (!$buildType && (-e "$sourceDir/CMakeLists.txt") && (-e "$sourceDir/bootstrap")) { $buildType = ksb::BuildSystem::CMakeBootstrap->new($self); } if (!$buildType && (-e "$sourceDir/CMakeLists.txt" || $self->isKDEProject())) { $buildType = ksb::BuildSystem::KDE4->new($self); } # We have to assign to an array to force glob to return all results, # otherwise it acts like a non-reentrant generator whose output depends on # how many times it's been called... if (!$buildType && (my @files = glob ("$sourceDir/*.pro"))) { $buildType = ksb::BuildSystem::QMake->new($self); } # 'configure' is a popular fall-back option even for other build # systems so ensure we check last for autotools. if (!$buildType && (-e "$sourceDir/configure" || -e "$sourceDir/autogen.sh")) { $buildType = ksb::BuildSystem::Autotools->new($self); } # Don't just assume the build system is KDE-based... $buildType //= ksb::BuildSystem->new($self); $self->{build_obj} = $buildType; return $self->{build_obj}; } # Sets the build system **object**, although you can find the build system # type afterwards (see buildSystemType). sub setBuildSystem { my ($self, $obj) = @_; assert_isa($obj, 'ksb::BuildSystem'); $self->{build_obj} = $obj; } # Current possible build system types: -# KDE (i.e. cmake), Qt, l10n (KDE language buildsystem), autotools (either +# KDE (i.e. cmake), Qt, autotools (either # configure or autogen.sh). A final possibility is 'pendingSource' which # simply means that we don't know yet. # # If the build system type is not set ('pendingSource' counts as being # set!) when this function is called then it will be autodetected if # possible, but note that not all possible types will be detected this way. # If in doubt use setBuildSystemType sub buildSystemType { my $self = shift; return $self->buildSystem()->name(); } # Subroutine to build this module. # Returns boolean false on failure, boolean true on success. sub build { my $self = assert_isa(shift, 'ksb::Module'); my $moduleName = $self->name(); my %pathinfo = $self->getInstallPathComponents('build'); my $builddir = $pathinfo{'fullpath'}; my $buildSystem = $self->buildSystem(); if ($buildSystem->name() eq 'generic' && !pretending()) { error ("\tr[b[$self] does not seem to have a build system to use."); return 0; } # Ensure we're in a known directory before we start; some options remove # the old build directory that a previous module might have been using. super_mkdir($pathinfo{'path'}); p_chdir($pathinfo{'path'}); return 0 if !$self->setupBuildSystem(); return 1 if $self->getOption('build-system-only'); if (!$buildSystem->buildInternal()) { return 0; } $self->setPersistentOption('last-build-rev', $self->currentScmRevision()); # TODO: This should be a simple phase to run. if ($self->getOption('run-tests')) { $self->buildSystem()->runTestsuite(); } # TODO: Likewise this should be a phase to run. if ($self->getOption('install-after-build')) { return 0 if !$self->install(); } else { info ("\tSkipping install for y[$self]"); } return 1; } # Subroutine to setup the build system in a directory. # Returns boolean true on success, boolean false (0) on failure. sub setupBuildSystem { my $self = assert_isa(shift, 'ksb::Module'); my $moduleName = $self->name(); my $buildSystem = $self->buildSystem(); if ($buildSystem->name() eq 'generic' && !pretending()) { croak_internal('Build system determination still pending when build attempted.'); } my $refreshReason = $buildSystem->needsRefreshed(); if ($refreshReason ne "") { # The build system needs created, either because it doesn't exist, or # because the user has asked that it be completely rebuilt. info ("\tPreparing build system for y[$self]."); # Check to see if we're actually supposed to go through the # cleaning process. if (!$self->getOption('#cancel-clean') && !$buildSystem->cleanBuildSystem()) { warning ("\tUnable to clean r[$self]!"); return 0; } } if (!$buildSystem->createBuildSystem()) { error ("\tError creating r[$self]'s build system!"); return 0; } # Now we're in the checkout directory # So, switch to the build dir. # builddir is automatically set to the right value for qt p_chdir ($self->fullpath('build')); if (!$buildSystem->configureInternal()) { error ("\tUnable to configure r[$self] with " . $self->buildSystemType()); # Add undocumented ".refresh-me" file to build directory to flag # for --refresh-build for this module on next run. See also the # "needsRefreshed" subroutine. if (open my $fh, '>', '.refresh-me') { say $fh "# Build directory will be re-generated next kdesrc-build run"; say $fh "# due to failing to complete configuration on the last run"; close $fh; }; return 0; } return 1; } # Responsible for installing the module (no update, build, etc.) # Return value: Boolean flag indicating whether module installed successfully or # not. # Exceptions may be thrown for abnormal conditions (e.g. no build dir exists) sub install { my $self = assert_isa(shift, 'ksb::Module'); my $builddir = $self->fullpath('build'); my $buildSysFile = $self->buildSystem()->configuredModuleFileName(); if (!pretending() && ! -e "$builddir/$buildSysFile") { warning ("\tThe build system doesn't exist for r[$self]."); warning ("\tTherefore, we can't install it. y[:-(]."); return 0; } $self->setupEnvironment(); my @makeInstallOpts = split(' ', $self->getOption('make-install-prefix')); # We can optionally uninstall prior to installing # to weed out old unused files. if ($self->getOption('use-clean-install') && $self->getPersistentOption('last-install-rev')) { if (!$self->buildSystem()->uninstallInternal(@makeInstallOpts)) { warning ("\tUnable to uninstall r[$self] before installing the new build."); warning ("\tContinuing anyways..."); } else { $self->unsetPersistentOption('last-install-rev'); } } if (!$self->buildSystem()->installInternal(@makeInstallOpts)) { error ("\tUnable to install r[$self]!"); $self->buildContext()->markModulePhaseFailed('install', $self); return 0; } if (pretending()) { pretend ("\tWould have installed g[$self]"); return 1; } # Past this point we know we've successfully installed, for real. $self->setPersistentOption('last-install-rev', $self->currentScmRevision()); my $remove_setting = $self->getOption('remove-after-install'); # Possibly remove the srcdir and builddir after install for users with # a little bit of HD space. if($remove_setting eq 'all') { # Remove srcdir my $srcdir = $self->fullpath('source'); note ("\tRemoving b[r[$self source]."); safe_rmtree($srcdir); } if($remove_setting eq 'builddir' || $remove_setting eq 'all') { # Remove builddir note ("\tRemoving b[r[$self build directory]."); safe_rmtree($builddir); # We're likely already in the builddir, so chdir back to the root p_chdir('/'); } return 1; } # Handles uninstalling this module (or its sub-directories as given by the checkout-only # option). # # Returns boolean false on failure, boolean true otherwise. sub uninstall { my $self = assert_isa(shift, 'ksb::Module'); my $builddir = $self->fullpath('build'); my $buildSysFile = $self->buildSystem()->configuredModuleFileName(); if (!pretending() && ! -e "$builddir/$buildSysFile") { warning ("\tThe build system doesn't exist for r[$self]."); warning ("\tTherefore, we can't uninstall it."); return 0; } $self->setupEnvironment(); my @makeInstallOpts = split(' ', $self->getOption('make-install-prefix')); if (!$self->buildSystem()->uninstallInternal(@makeInstallOpts)) { error ("\tUnable to uninstall r[$self]!"); $self->buildContext()->markModulePhaseFailed('install', $self); return 0; } if (pretending()) { pretend ("\tWould have uninstalled g[$self]"); return 1; } $self->unsetPersistentOption('last-install-rev'); return 1; } sub buildContext { my $self = shift; return $self->{context}; } # Integrates 'set-env' option to the build context environment sub applyUserEnvironment { my $self = assert_isa(shift, 'ksb::Module'); my $ctx = $self->buildContext(); # Let's see if the user has set env vars to be set. # Note the global set-env must be checked separately anyways, so # we limit inheritance when searching. my $env_hash_ref = $self->getOption('set-env', 'module'); while (my ($key, $value) = each %{$env_hash_ref}) { $ctx->queueEnvironmentVariable($key, $value); } } # Establishes proper build environment in the build context. Should be run # before forking off commands for e.g. updates, builds, installs, etc. sub setupEnvironment { my $self = assert_isa(shift, 'ksb::Module'); my $ctx = $self->buildContext(); my $kdedir = $self->getOption('kdedir'); my $prefix = $self->installationPath(); # Add global set-envs and context $self->buildContext()->applyUserEnvironment(); # Avoid moving /usr up in env vars if ($kdedir ne '/usr') { my @pkg_config_dirs = ("$kdedir/lib/pkgconfig"); $ctx->prependEnvironmentValue('PKG_CONFIG_PATH', @pkg_config_dirs); my @ld_dirs = ("$kdedir/lib", $self->getOption('libpath')); $ctx->prependEnvironmentValue('LD_LIBRARY_PATH', @ld_dirs); my @path = ("$kdedir/bin", $self->getOption('binpath')); $ctx->prependEnvironmentValue('PATH', @path); } # Build system's environment injection my $buildSystem = $self->buildSystem(); $buildSystem->prepareModuleBuildEnvironment($ctx, $self, $prefix); # Read in user environment defines $self->applyUserEnvironment() unless $self == $ctx; } # Returns the path to the log directory used during this run for this # ksb::Module, based on an autogenerated unique id. The id doesn't change # once generated within a single run of the script. sub getLogDir { my ($self) = @_; return $self->buildContext()->getLogDirFor($self); } # Returns a full path that can be open()'d to write a log # file, based on the given basename (with extension). # Updates the 'latest' symlink as well, unlike getLogDir # Use when you know you're going to create a new log sub getLogPath { my ($self, $path) = @_; return $self->buildContext()->getLogPathFor($self, $path); } sub toString { my $self = shift; return $self->name(); } sub compare { my ($self, $other) = @_; return $self->name() cmp $other->name(); } # Runs just before update phase, can be used to ensure that things like local # dependencies are setup. Meant to be subclassed. # # Returns non-zero on success or throws an exception if an error occurs. sub preUpdate { my $self = assert_isa(shift, 'ksb::Module'); return 1; } sub update { my ($self, $ipc, $ctx) = @_; my $moduleName = $self->name(); my $module_src_dir = $self->getSourceDir(); my $kdesrc = $ctx->getSourceDir(); if ($kdesrc ne $module_src_dir) { # This module has a different source directory, ensure it exists. if (!super_mkdir($module_src_dir)) { error ("Unable to create separate source directory for r[$self]: $module_src_dir"); $ipc->sendIPCMessage(ksb::IPC::MODULE_FAILURE, $moduleName); next; } } $self->preUpdate(); my $fullpath = $self->fullpath('source'); my $count; my $returnValue; eval { $count = $self->scm()->updateInternal($ipc) }; if ($@) { my $reason = ksb::IPC::MODULE_FAILURE; if (had_an_exception()) { if ($@->{'exception_type'} eq 'ConflictPresent') { $reason = ksb::IPC::MODULE_CONFLICT; } else { $ctx->markModulePhaseFailed('build', $self); } $@ = $@->{'message'}; } error ("Error updating r[$self], removing from list of packages to build."); error (" > y[$@]"); $ipc->sendIPCMessage($reason, $moduleName); $self->phases()->filterOutPhase('build'); $returnValue = 0; } else { my $message; if (not defined $count) { $message = ksb::Debug::colorize ("b[y[Unknown changes]."); $ipc->notifyUpdateSuccess($moduleName, $message); } elsif ($count) { $message = "1 file affected." if $count == 1; $message = "$count files affected." if $count != 1; $ipc->notifyUpdateSuccess($moduleName, $message); } else { $message = "0 files affected."; my $refreshReason = $self->buildSystem()->needsRefreshed(); $ipc->sendIPCMessage(ksb::IPC::MODULE_UPTODATE, "$moduleName,$refreshReason"); } # We doing e.g. --src-only, the build phase that normally outputs # number of files updated doesn't get run, so manually mention it # here. if (!$ipc->supportsConcurrency()) { info ("\t$self update complete, $message"); } $returnValue = 1; } info (""); # Print empty line. return $returnValue; } # OVERRIDE # # This calls OptionsBase::setOption and performs any Module-specific # handling. sub setOption { my ($self, %options) = @_; # Ensure we don't accidentally get fed module-set options for (qw(git-repository-base use-modules ignore-modules)) { if (exists $options{$_}) { error (" r[b[*] module b[$self] should be declared as module-set to use b[$_]"); die ksb::BuildException::Config->new($_, "Option $_ can only be used in module-set"); }; } # Special case handling. if (exists $options{'filter-out-phases'}) { for my $phase (split(' ', $options{'filter-out-phases'})) { $self->phases()->filterOutPhase($phase); } delete $options{'filter-out-phases'}; } $self->SUPER::setOption(%options); } # OVERRIDE # # This subroutine returns an option value for a given module. Some globals # can't be overridden by a module's choice (but see 2nd parameter below). # If so, the module's choice will be ignored, and a warning will be issued. # # Option names are case-sensitive! # # Some options (e.g. cmake-options, configure-flags) have the global value # and then the module's own value appended together. To get the actual # module setting you must use the level limit parameter set to 'module'. # # Likewise, some qt module options do not obey the previous proviso since # Qt options are not likely to agree nicely with generic KDE buildsystem # options. # # 1st parameter: Name of option # 2nd parameter: Level limit (optional). If not present, then the value # 'allow-inherit' is used. Options: # - allow-inherit: Module value is used if present (with exceptions), # otherwise global is used. # - module: Only module value is used (if you want only global then use the # buildContext) NOTE: This overrides global "sticky" options as well! sub getOption { my ($self, $key, $levelLimit) = @_; my $ctx = $self->buildContext(); $levelLimit //= 'allow-inherit'; # Some global options would probably make no sense applied to Qt. my @qtCopyOverrides = qw(branch configure-flags tag cxxflags); if (list_has(\@qtCopyOverrides, $key) && $self->buildSystemType() eq 'Qt') { $levelLimit = 'module'; } assert_in($levelLimit, [qw(allow-inherit module)]); # If module-only, check that first. return $self->{options}{$key} if $levelLimit eq 'module'; # Some global options always override module options. return $ctx->getOption($key) if $ctx->hasStickyOption($key); # Some options append to the global (e.g. conf flags) my @confFlags = qw(cmake-options configure-flags cxxflags); if (list_has(\@confFlags, $key) && $ctx->hasOption($key)) { return $ctx->getOption($key) . " " . ($self->{options}{$key} || ''); } # Everything else overrides the global option, unless it's simply not # set at all. return $self->{options}{$key} // $ctx->getOption($key); } # Gets persistent options set for this module. First parameter is the name # of the option to lookup. Undef is returned if the option is not set, # although even if the option is set, the value returned might be empty. # Note that ksb::BuildContext also has this function, with a slightly # different signature, which OVERRIDEs this function since Perl does not # have parameter-based method overloading. sub getPersistentOption { my ($self, $key) = @_; return $self->buildContext()->getPersistentOption($self->name(), $key); } # Sets a persistent option (i.e. survives between processes) for this module. # First parameter is the name of the persistent option. # Second parameter is its actual value. # See the warning for getPersistentOption above, it also applies for this # method vs. ksb::BuildContext::setPersistentOption sub setPersistentOption { my ($self, $key, $value) = @_; return $self->buildContext()->setPersistentOption($self->name(), $key, $value); } # Unsets a persistent option for this module. # Only parameter is the name of the option to unset. sub unsetPersistentOption { my ($self, $key) = @_; $self->buildContext()->unsetPersistentOption($self->name(), $key); } # Returns the path to the desired directory type (source or build), # including the module destination directory itself. sub fullpath { my ($self, $type) = @_; assert_in($type, [qw/build source/]); my %pathinfo = $self->getInstallPathComponents($type); return $pathinfo{'fullpath'}; } # Returns the "full kde-projects path" for the module. sub fullProjectPath { my $self = shift; # meant to be overridden croak_internal("Tried to ask for full path of a module $self that doesn't have one!"); } # Returns true if this module is (or was derived from) a kde-projects module. sub isKDEProject { return 0; # overridden in subclasses } # Subroutine to return the name of the destination directory for the # checkout and build routines. Based on the dest-dir option. The return # value will be relative to the src/build dir. The user may use the # '$MODULE' or '${MODULE}' sequences, which will be replaced by the name of # the module in question. # # The first parameter is optional, but if provided will be used as the base # path to replace $MODULE entries in dest-dir. sub destDir { my ($self, $basePath) = @_; my $destDir = $self->getOption('dest-dir'); $basePath ||= $self->name(); $destDir =~ s/(\$\{MODULE})|(\$MODULE\b)/$basePath/g; return $destDir; } # Subroutine to return the installation path of a given module (the value # that is passed to the CMAKE_INSTALL_PREFIX CMake option). # It is based on the "prefix" and, if it is not set, the "kdedir" option. # The user may use '$MODULE' or '${MODULE}' in the "prefix" option to have # them replaced by the name of the module in question. sub installationPath { my $self = assert_isa(shift, 'ksb::Module'); my $path = $self->getOption('prefix'); if (!$path) { return $self->getOption('kdedir'); } my $moduleName = $self->name(); $path =~ s/(\$\{MODULE})|(\$MODULE\b)/$moduleName/g; return $path; } 1; diff --git a/modules/ksb/ModuleResolver.pm b/modules/ksb/ModuleResolver.pm index b6b36b2..6a765ad 100644 --- a/modules/ksb/ModuleResolver.pm +++ b/modules/ksb/ModuleResolver.pm @@ -1,617 +1,613 @@ package ksb::ModuleResolver 0.20; # Handle proper resolution of module selectors, including option # handling. See POD docs below for more details. use warnings; use 5.014; use ksb::BuildException; use ksb::Debug; use ksb::Util; use ksb::ModuleSet::KDEProjects; use ksb::Module; use List::Util qw(first); # Public API sub new { my ($class, $ctx) = @_; my $self = { context => $ctx, ignoredSelectors => [ ], # Read in from rc-file inputModulesAndOptions => [ ], cmdlineOptions => { }, deferredOptions => { }, # Holds Modules defined in course of expanding module-sets definedModules => { }, # Holds use-module mentions with their source module-set referencedModules => { }, }; return bless $self, $class; } sub setCmdlineOptions { my ($self, $cmdlineOptionsRef) = @_; $self->{cmdlineOptions} = $cmdlineOptionsRef; return; } sub setDeferredOptions { my ($self, $deferredOptionsRef) = @_; $self->{deferredOptions} = $deferredOptionsRef; return; } sub setIgnoredSelectors { my ($self, $ignoredSelectorsRef) = @_; $self->{ignoredSelectors} = $ignoredSelectorsRef // [ ]; return; } sub setInputModulesAndOptions { my ($self, $modOptsRef) = @_; $self->{inputModulesAndOptions} = $modOptsRef; # Build lookup tables $self->{definedModules} = { map { $_->name() => $_ } (@$modOptsRef) }; $self->{referencedModules} = { _listReferencedModules(@{$modOptsRef}) }; return; } # Applies cmdline and deferred options to the given modules or module-sets. sub _applyOptions { my ($self, @modules) = @_; my $cmdlineOptionsRef = $self->{cmdlineOptions}; my $deferredOptionsRef = $self->{deferredOptions}; foreach my $m (@modules) { my $name = $m->name(); # Apply deferred options first $m->setOption(%{$deferredOptionsRef->{$name} // {}}); $m->getLogDir() if $m->isa('ksb::Module'); # Most of time cmdline options will be empty if (%$cmdlineOptionsRef) { my %moduleCmdlineArgs = ( # order is important here %{$cmdlineOptionsRef->{global} // {}}, %{$cmdlineOptionsRef->{$name} // {}}, ); # Remove any options that would interfere with cmdline args # to avoid any override behaviors in setOption() delete @{$m->{options}}{keys %moduleCmdlineArgs}; # Reapply module-specific cmdline options $m->setOption(%moduleCmdlineArgs); } } return; } # Returns a hash table of all module names referenced in use-module # declarations for any ModuleSets included within the input list. Each entry # in the hash table will map the referenced module name to the source # ModuleSet. sub _listReferencedModules { my %setEntryLookupTable; my @results; for my $moduleSet (grep { $_->isa('ksb::ModuleSet') } (@_)) { @results = $moduleSet->moduleNamesToFind(); # The parens in front of 'x' are semantically required for repetition! @setEntryLookupTable{@results} = ($moduleSet) x scalar @results; } return %setEntryLookupTable; } # Expands out a single module-set listed in referencedModules and places any # ksb::Modules created as a result within the lookup table of Modules. # Returns the list of created ksb::Modules sub _expandSingleModuleSet { my $self = shift; my $neededModuleSet = shift; my $selectedReason = 'partial-expansion:' . $neededModuleSet->name(); my $lookupTableRef = $self->{definedModules}; my $setEntryLookupTableRef = $self->{referencedModules}; # expandModuleSets applies pending/cmdline options already. my @moduleResults = $self->expandModuleSets($neededModuleSet); if (!@moduleResults) { croak_runtime ("$neededModuleSet->name() expanded to an empty list of modules!"); } $_->setOption('#selected-by', $selectedReason) foreach @moduleResults; # Copy entries into the lookup table, especially in case they're # from case 3 @{$lookupTableRef}{map { $_->name() } @moduleResults} = @moduleResults; # Ensure Case 2 and Case 1 stays disjoint (our selectors should now be # in the lookup table if it uniquely matches a module at all). my @moduleSetReferents = grep { $setEntryLookupTableRef->{$_} == $neededModuleSet } (keys %$setEntryLookupTableRef); delete @{$setEntryLookupTableRef}{@moduleSetReferents}; return @moduleResults; } # Determines the most appropriate module to return for a given selector. # The selector may refer to a module or module-set, which means that the # return value may be a list of modules. sub _resolveSingleSelector { my $self = shift; my $selector = shift; my $ctx = $self->{context}; my $selectorName = $selector; my @results; # Will default to '$selector' if unset by end of sub # In the remainder of this code, lookupTableRef is basically handling # case 1, while setEntryLookupTableRef handles case 2. No ksb::Modules # are *both* case 1 and 2 at the same time, and a module-set can only # be case 1. We clean up and handle any case 3s (if any) at the end. my $lookupTableRef = $self->{definedModules}; my $setEntryLookupTableRef = $self->{referencedModules}; # Module selectors beginning with '+' force treatment as a kde-projects # module, which means they won't be matched here (we're only looking for # sets). my $forcedToKDEProject = substr($selectorName, 0, 1) eq '+'; substr($selectorName, 0, 1, '') if $forcedToKDEProject; # Checks cmdline options only my $includingDeps = exists $self->{cmdlineOptions}->{$selectorName}->{'include-dependencies'} || exists $self->{cmdlineOptions}->{'global'}->{'include-dependencies'}; # See resolveSelectorsIntoModules for what the 3 "cases" mentioned below are. # Case 2. We make these checks first since they may update %lookupTable if (exists $setEntryLookupTableRef->{$selectorName} && !exists $lookupTableRef->{$selectorName}) { my $neededModuleSet = $setEntryLookupTableRef->{$selectorName}; my @moduleResults = $self->_expandSingleModuleSet($neededModuleSet); if (!$includingDeps) { $_->setOption('include-dependencies', 0) foreach @moduleResults; } # Now lookupTable should be updated with expanded modules. $selector = $lookupTableRef->{$selectorName} // undef; # If the selector doesn't match a name exactly it probably matches # a wildcard prefix. e.g. 'kdeedu' as a selector would pull in all kdeedu/* # modules, but kdeedu is not a module-name itself anymore. In this # case just return all the modules in the expanded list. if (!$selector) { push @results, @moduleResults; } else { $selector->setOption('#selected-by', 'name'); } } # Case 1 elsif (exists $lookupTableRef->{$selectorName}) { $selector = $lookupTableRef->{$selectorName}; $selector->setOption('#selected-by', 'name') unless $selector->isa('ksb::ModuleSet'); if (!$selector->isa('ksb::ModuleSet') && !$includingDeps) { # modules were manually selected on cmdline, so ignore # module-based include-dependencies, unless # include-dependencies also set on cmdline. $selector->setOption('#include-dependencies', 0); } } elsif (ref $selector && $selector->isa('ksb::Module')) { # We couldn't find anything better than what we were provided, # just use it. $selector->setOption('#selected-by', 'best-guess-after-full-search'); } elsif ($forcedToKDEProject) { # Just assume it's a kde-projects module and expand away... $selector = ksb::ModuleSet::KDEProjects->new($ctx, '_cmdline'); $selector->setModulesToFind($selectorName); $selector->setOption('#include-dependencies', $includingDeps); } else { # Case 3? $selector = ksb::Module->new($ctx, $selectorName); $selector->phases()->phases($ctx->phases()->phases()); - if ($selectorName eq 'l10n') { - $_->setScmType('l10n') - } - $selector->setScmType('proj'); $selector->setOption('#guessed-kde-project', 1); $selector->setOption('#selected-by', 'initial-guess'); $selector->setOption('#include-dependencies', $includingDeps); } push @results, $selector unless @results; return @results; } sub _expandAllUnexpandedModuleSets { my $self = shift; my @unexpandedModuleSets = unique_items(values %{$self->{referencedModules}}); $self->_expandSingleModuleSet($_) foreach @unexpandedModuleSets; return; } sub _resolveGuessedModules { my $self = shift; my $ctx = $self->{context}; my @modules = @_; # We didn't necessarily fully expand all module-sets available in the # inputModulesAndOptions when we were resolving selectors. # Because of this we may need to go a step further and expand out all # remaining module-sets in rcFileModulesAndModuleSets if we have 'guess' # modules still left over (since they might be Case 3), and see if we can # then successfully match. if (!first { $_->getOption('#guessed-kde-project', 'module') } @modules) { return @modules; } my $lookupTableRef = $self->{definedModules}; $self->_expandAllUnexpandedModuleSets(); my @results; # We use foreach since we *want* to be able to replace the iterated variable # if we find an existing module. for my $guessedModule (@modules) { if (!$guessedModule->getOption('#guessed-kde-project', 'module')) { push @results, $guessedModule; next; } # If the module we want could be found from within our rc-file # module-sets (even implicitly), use it. Otherwise assume # kde-projects and evaluate now. if (exists $lookupTableRef->{$guessedModule->name()}) { $guessedModule = $lookupTableRef->{$guessedModule->name()}; push @results, $guessedModule; } else { my $set = ksb::ModuleSet::KDEProjects->new($ctx, "guessed_from_cmdline"); $set->setModulesToFind($guessedModule->name()); my @setResults = $self->expandModuleSets($set); my $searchItem = $guessedModule->name(); if (!@setResults) { croak_runtime ("$searchItem doesn't match any modules."); } my $foundModule = first { $_->name() eq $searchItem } @setResults; $guessedModule = $foundModule if $foundModule; push @results, @setResults; } } return @results; } # Resolves already-stored module selectors into ksb::Modules, based on # the options, modules, and module-sets set. # # Returns a list of ksb::Modules in build order, with any module-sets fully # expanded. The desired options will be set for each ksb::Module returned. sub resolveSelectorsIntoModules { my ($self, @selectors) = @_; my $ctx = $self->{context}; # Basically there are 3 types of selectors at this point: # 1. Directly named and defined modules or module-sets. # 2. Referenced (but undefined) modules. These are mentioned in a # use-modules in a module set but not actually available as ksb::Module # objects yet. But we know they will exist. # 3. Indirect modules. These are modules that do exist in the KDE project # metadata, and will be pulled in once all module-sets are expanded # (whether that's due to implicit wildcarding with use-modules, or due # to dependency following). However we don't even know the names for # these yet. # We have to be careful to maintain order of selectors throughout. my @outputList; for my $selector (@selectors) { next if list_has ($self->{ignoredSelectors}, $selector); push @outputList, $self->_resolveSingleSelector($selector); } my @modules = $self->expandModuleSets(@outputList); # If we have any 'guessed' modules then they had no obvious source in the # rc-file. But they might still be implicitly from one of our module-sets # (Case 3). # We want them to use ksb::Modules from the rc-file modules/module-sets # instead of our shell Modules, if possible. @modules = $self->_resolveGuessedModules(@modules); return @modules; } # Similar to resolveSelectorsIntoModules, except that in this case no # 'guessing' for Modules is allowed; the requested module is returned if # present, or undef otherwise. Also unlike resolveSelectorsIntoModules, no # exceptions are thrown if the module is not present. # # The only major side-effect is that all known module-sets are expanded if # necessary before resorting to returning undef. sub resolveModuleIfPresent { my ($self, $moduleName) = @_; if (%{$self->{referencedModules}}) { $self->_expandAllUnexpandedModuleSets(); } # We may not already know about modules that can be found in kde-projects, # so double-check by resolving module name into a kde-projects module-set # selector (the + syntax) and then expanding out the module-set so generated. if (!defined $self->{definedModules}->{$moduleName}) { eval { $self->_expandSingleModuleSet( $self->_resolveSingleSelector("+$moduleName")); }; } return $self->{definedModules}->{$moduleName} // undef; } # Replaces ModuleSets in the given list with their component Modules, and # returns the new list. sub expandModuleSets { my $self = shift; my $ctx = $self->{context}; my @buildModuleList = @_; my @returnList; foreach my $set (@buildModuleList) { my @results = $set; # If a module-set, need to update first so it can then apply its # settings to modules it creates, otherwise update Module directly. $self->_applyOptions($set); if ($set->isa('ksb::ModuleSet')) { @results = $set->convertToModules($ctx); $self->_applyOptions(@results); } push @returnList, @results; } return @returnList; } # Internal API 1; __END__ =head1 ModuleResolver A class that handles general management tasks associated with the module build list, including option handling and resolution of module selectors into actual modules. =head2 METHODS =over =item new Creates a new C. You must pass the appropriate C Don't forget to call setPendingOptions(), setIgnoredSelectors() and setInputModulesAndOptions(). my $resolver = ModuleResolver->new($ctx); =item setPendingOptions Sets the options that should be applied to modules when they are created. No special handling for global options is performed here (but see ksb::OptionsBase::getOption and its friends). You should pass in a hashref, where module-names are keys to values which are themselves hashrefs of option-name => value pairs: $resolver->setPendingOptions( { mod1 => { 'cmake-options' => 'foo', ... }, mod2 => { } }) =item setIgnoredSelectors Declares all selectors that should be ignored by default in the process of expanding module sets. Any modules matching these selectors would be elided from any expanded module sets by default. You should pass a listref of selectors. =item setInputModulesAndOptions Declares the list of all modules and module-sets known to the program, along with their base options. Modules should be ksb::Module objects, module-sets should be ksb::ModuleSet objects, no other types should be present in the list. You should pass a listref of Modules or ModuleSets (as appropriate). =item resolveSelectorsIntoModules Resolves the given list of module selectors into ksb::Module objects, using the pending command-line options, ignore-selectors and available modules/module-sets. Selectors always choose an available ksb::Module or ksb::ModuleSet if present (based on the name() of each Module or ModuleSet, including any use-modules entries for ModuleSet objects). If a selector cannot be directly found then ModuleSet objects may be expanded into their constituent Module objects and the search performed again. If a selector still cannot be found an exception is thrown. Any embedded ModuleSets are expanded to Modules in the return value. The list of selected Modules is returned, in the approximate order of the input list (selectors for module-sets are expanded in arbitrary order). If you are just looking for a Module that should already be present, see resolveModuleIfPresent(). my @modules = eval { $resolver->resolveSelectorsIntoModules('kdelibs', 'juk'); } =item resolveModuleIfPresent Similar to resolveSelectorsIntoModules(), except that no exceptions are thrown if the module doesn't exist. Only a single module name is supported. =item expandModuleSets Converts any ksb::ModuleSet objects in the given list of Modules and ModuleSets into their component ksb::Module objects (with proper options set, and ignored modules not present). These component objects are spliced into the list of module-type objects, replacing the ModuleSet they came from. The list of ksb::Module objects is then returned. The list passed in is not actually modified in this process. =back =head2 IMPLEMENTATION This module uses a multi-pass option resolving system, in accordance with the way kdesrc-build handles options. Consider a simple kdesrc-buildrc: global cmake-options -DCMAKE_BUILD_TYPE=Debug ... end global module-set ms-foo cmake-options -DCMAKE_BUILD_TYPE=RelWithDebInfo repository kde-projects use-modules kde/kdemultimedia include-dependencies true end module-set options framework1 set-env BUILD_DEBUG 1 end options module taglib repository git://... branch 1.6 end module options juk cxxflags -g3 -Og custom-build-command ninja end options In this case we'd expect that a module like taglib ends up with its C derived from the global section directly, while all modules included from module set C use the C defined in the module-set. At the same time we'd expect that juk has all the options listed in ms-foo, but also the specific C and C options shown, I the juk module had been referenced during the build. There are many ways to convince kdesrc-build to add a module into its build list: =over =item 1. Mention it directly on the command line. =item 2. Include it in the kdesrc-buildrc file, either as a new C block or in a C of a C. =item 3. For KDE modules, mention a component of its project path in a C declaration within a C-based module set. E.g. the "kde/kdemultimedia" entry above, which will pull in the juk module even though "juk" is not named directly. =item 4. For KDE modules, by being a dependency of a module included from a C where the C option is set to C. This wouldn't apply to juk, but might apply to modules such as phonon. Note that "taglib" in this example would B be a dependency of juk according to kdesrc-build (although it is in reality), since taglib is not a KDE module. =back This mission of this class is to ensure that, no matter I a module ended up being selected by the user for the build list, that the same options are registered into the module, the module uses the same build and scm types, is defaulted to the right build phases, etc. To do this, this class takes the read-in options, modules, and module sets from the rc-file, the list of "selectors" requested by the user (via cmdline), any changes to the options from the cmdline, and then takes pains to ensure that any requested modules are returned via the appropriate module-set (and if no module-set can source the module, via default options). In doing so, the class must keep track of module sets, the modules included into each module set, and modules that were mentioned somehow but not already present in the known list of modules (or module sets). Since module sets can cause modules to be defined that are not mentioned anywhere within an rc-file, it may be required to completely expand all module sets in order to verify that a referenced C is B already known. =head2 OUTPUTS From the perspective of calling code, the 'outputs' of this module are lists of C objects, in the order they were selected (or mentioned in the rc-file). See expandModuleSets() and resolveSelectorsIntoModules(). Each object so returned should already have the appropriate options included (based on the cmdlineOptions member, which should be constructed as the union of rc-file and cmdline options). Note that dependency resolution is B handled by this module, see C for that. =cut diff --git a/modules/ksb/Updater/Svn.pm b/modules/ksb/Updater/Svn.pm index 383f470..969d914 100644 --- a/modules/ksb/Updater/Svn.pm +++ b/modules/ksb/Updater/Svn.pm @@ -1,673 +1,672 @@ package ksb::Updater::Svn 0.10; -# Module responsible for source code updates on Subversion modules. Used as a -# superclass for our l10n update/build system as well. +# Module responsible for source code updates on Subversion modules. use strict; use warnings; use 5.014; use parent qw(ksb::Updater); use ksb::BuildException; use ksb::Debug; use ksb::Util; use IPC::Open3 qw(open3); # Returns true if a module has a base component to their name (e.g. KDE/, # extragear/, or playground). Note that modules that aren't in trunk/KDE # don't necessary meet this criteria (e.g. kdereview is a module itself). sub _has_base_module { my $moduleName = shift; return $moduleName =~ /^(extragear|playground|KDE)(\/[^\/]+)?$/; } # Subroutine to return the branch prefix. i.e. the part before the branch # name and module name. # # The first parameter is the module name in question. # The second parameter should be 'branches' if we're dealing with a branch # or 'tags' if we're dealing with a tag. # # Ex: 'kdelibs' => 'branches/KDE' # 'kdevelop' => 'branches/kdevelop' sub _branch_prefix { my $moduleName = shift; my $type = shift; # These modules seem to have their own subdir in /tags. my @tag_components = qw/arts koffice amarok kst qt taglib/; # The map call adds the kde prefix to the module names because I don't feel # like typing them all in. my @kde_module_list = ((map {'kde' . $_} qw/-base-artwork -wallpapers accessibility addons admin artwork base bindings edu games graphics libs network pim pimlibs plasma-addons sdk toys utils webdev/)); # If the user already has the module in the form KDE/foo, it's already # done. return "$type/KDE" if $moduleName =~ /^KDE\//; # KDE proper modules seem to use this pattern. return "$type/KDE" if list_has(\@kde_module_list, $moduleName); # KDE extragear / playground modules use this pattern return "$type" if _has_base_module($moduleName); # If we doing a tag just return 'tags' because the next part is the actual # tag name, which is added by the caller, unless the module has its own # subdirectory in /tags. return "$type" if $type eq 'tags' and not list_has(\@tag_components, $moduleName); # Everything else. return "$type/$moduleName"; } # This subroutine is responsible for stripping the KDE/ part from the # beginning of modules that were entered by the user like "KDE/kdelibs" # instead of the normal "kdelibs". That way you can search for kdelibs # without having to strip KDE/ everywhere. sub _moduleBaseName { my $moduleName = shift; $moduleName =~ s/^KDE\///; return $moduleName; } # Subroutine to return a module URL for a module using the 'branch' option. # First parameter is the module in question. # Second parameter is the type ('tags' or 'branches') sub _handle_branch_tag_option { my $module = assert_isa(shift, 'ksb::Module'); my $type = shift; my $branch = _branch_prefix($module->name(), $type); my $svn_server = $module->getOption('svn-server'); my $branchname = $module->getOption($type eq 'branches' ? 'branch' : 'tag'); # Remove trailing slashes. $svn_server =~ s/\/*$//; # Remove KDE/ prefix for module name. my $moduleName = _moduleBaseName($module->name()); # KDE modules have a different module naming scheme than the rest it seems. return "$svn_server/$branch/$branchname/$moduleName" if $branch =~ /\/KDE\/?$/; # Non-trunk translations happen in a single branch. Assume all non-trunk # global branches are intended for the stable translations. if ($moduleName =~ /^l10n-kde4\/?/ && $branch ne 'trunk') { return "$svn_server/branches/stable/$moduleName"; } # Otherwise don't append the module name by default since it makes more # sense to branch this way in many situations (i.e. kdesupport tags, phonon) return "$svn_server/$branch/$branchname"; } # Subroutine to return the appropriate SVN URL for a given module, based on # the user settings. For example, 'kdelibs' -> # https://svn.kde.org/home/kde/trunk/KDE/kdelibs # # This operates under a double hierarchy: # 1. If any module-specific option is present, it wins. # 2. If only global options are present, the order override-url, tag, # branch, module-base-path, is preferred. sub svn_module_url { my $self = assert_isa(shift, 'ksb::Updater::Svn'); my $module = $self->module(); my $svn_server = $module->getOption('svn-server'); my $modulePath; foreach my $levelLimit ('module', 'allow-inherit') { $modulePath = $module->getOption('module-base-path', $levelLimit); # Allow user to override normal processing of the module in a few ways, # to make it easier to still be able to use kdesrc-build even when I # can't be there to manually update every little special case. if($module->getOption('override-url', $levelLimit)) { return $module->getOption('override-url', $levelLimit); } if($module->getOption('tag', $levelLimit)) { return _handle_branch_tag_option($module, 'tags'); } my $branch = $module->getOption('branch', $levelLimit); if($branch and $branch ne 'trunk') { return _handle_branch_tag_option($module, 'branches'); } my $moduleName = _moduleBaseName($module->name()); # The following modules are in /trunk, not /trunk/KDE. There are others, # but these are the important ones. my @non_trunk_modules = qw(extragear kdesupport koffice icecream kde-common playground KDE kdereview www l10n-kde4); my $module_root = $moduleName; $module_root =~ s/\/.*//; # Remove everything after the first slash if (not $modulePath and $levelLimit eq 'allow-inherit') { $modulePath = "trunk/KDE/$moduleName"; $modulePath = "trunk/$moduleName" if list_has(\@non_trunk_modules, $module_root); $modulePath =~ s/^\/*//; # Eliminate / at beginning of string. $modulePath =~ s/\/*$//; # Likewise at the end. } last if $modulePath; } # Remove trailing slashes. $svn_server =~ s/\/*$//; # Note that the module name is no longer appended if module-base-path is used (i.e. # $branch variable was set. This is a change as of version 1.8. return "$svn_server/$modulePath"; } # Subroutine to determine whether or not the given module has the correct # URL. If not, a warning is printed out. # First parameter: module to check. # Return: Nothing. sub _verifyCorrectServerURL { my $self = assert_isa(shift, 'ksb::Updater::Svn'); my $module = $self->module(); my $module_expected_url = $self->svn_module_url(); my $module_actual_url = $self->svnInfo('URL'); if (!$module_actual_url) { croak_runtime ("Unable to determine working copy's svn URL for $module"); } $module_expected_url =~ s{/+$}{}; # Remove trailing slashes $module_actual_url =~ s{/+$}{}; # Remove trailing slashes if ($module_actual_url ne $module_expected_url) { # Check if the --src-only flag was passed. my $module = $self->module(); if ($module->buildContext()->getOption('#allow-auto-repo-move')) { note ("g[$module] is checked out from a different location than expected."); note ("Attempting to correct to $module_expected_url"); my ($expected_host, $expected_path) = ($module_expected_url =~ m{://([^/]+)/(.*)$}); my ($actual_host, $actual_path) = ($module_actual_url =~ m{://([^/]+)/(.*)$}); # If the path didn't change but the host info did try --relocate # otherwise try regular svn switch. if (($expected_path eq $actual_path) && ($expected_host ne $actual_host)) { log_command($module, 'svn-switch', [ 'svn', 'switch', '--relocate', $module_actual_url, $module_expected_url]); } else { log_command($module, 'svn-switch', [ 'svn', 'switch', $module_expected_url]); } return; } warning (<module(); # svn 1.7 has a different working copy format that must be manually # converted. This will mess up everything else so make this our first # check. p_chdir($module->fullpath('source')); # gensym makes a symbol that can be made a filehandle by open3 use Symbol qw(gensym); # Can't use filter_program_output as that doesn't capture STDERR on # purpose. We, on the other hand, just want STDERR. my $stderrReader = gensym(); my $pid = open3(undef, undef, $stderrReader, 'svn', '--non-interactive', 'status'); my @errorLines = grep { /:\s*E155036:/ } (<$stderrReader>); waitpid ($pid, 0); if (@errorLines) { warning (<_verifyCorrectServerURL(); } # Subroutine used to handle the checkout-only option. It handles updating # subdirectories of an already-checked-out module. # # This function can throw an exception in the event of a update failure. # # First parameter is the module. # All remaining parameters are subdirectories to check out. # # Returns the number of files changed by the update, or undef if unable to # be determined. sub update_module_subdirectories { my $self = assert_isa(shift, 'ksb::Updater::Svn'); my $module = $self->module(); my $numChanged = 0; # If we have elements in @path, download them now for my $dir (@_) { info ("\tUpdating g[$dir]"); my $logname = $dir; $logname =~ tr{/}{-}; my $count = $self->run_svn("svn-up-$logname", [ 'svn', 'up', $dir ]); $numChanged = undef unless defined $count; $numChanged += $count if defined $numChanged; } return $numChanged; } # Checkout a module that has not been checked out before, along with any # subdirectories the user desires. # # This function will throw an exception in the event of a failure to update. # # The first parameter is the module to checkout (including extragear and # playground modules). # All remaining parameters are subdirectories of the module to checkout. # # Returns number of files affected, or undef. sub checkout_module_path { my $self = assert_isa(shift, 'ksb::Updater::Svn'); my $module = $self->module(); my @path = @_; my %pathinfo = $module->getInstallPathComponents('source'); my @args; if (not -e $pathinfo{'path'} and not super_mkdir($pathinfo{'path'})) { croak_runtime ("Unable to create path r[$pathinfo{path}]!"); } p_chdir ($pathinfo{'path'}); my $svn_url = $self->svn_module_url(); my $modulename = $pathinfo{'module'}; # i.e. kdelibs for KDE/kdelibs as $module push @args, ('svn', 'co', '--non-interactive'); push @args, '-N' if scalar @path; # Tells svn to only update the base dir push @args, $svn_url; push @args, $modulename; note ("Checking out g[$module]"); my $count = $self->run_svn('svn-co', \@args); p_chdir ($pathinfo{'module'}) if scalar @path; my $count2 = $self->update_module_subdirectories(@path); return $count + $count2 if defined $count and defined $count2; return undef; } # Update a module that has already been checked out, along with any # subdirectories the user desires. # # This function will throw an exception in the event of an update failure. # # The first parameter is the module to checkout (including extragear and # playground modules). # All remaining parameters are subdirectories of the module to checkout. sub update_module_path { my ($self, @path) = @_; assert_isa($self, 'ksb::Updater::Svn'); my $module = $self->module(); my $fullpath = $module->fullpath('source'); my @args; p_chdir ($fullpath); push @args, ('svn', 'up', '--non-interactive'); push @args, '-N' if scalar @path; note ("Updating g[$module]"); my $count = eval { $self->run_svn('svn-up', \@args); }; # Update failed, try svn cleanup. if (had_an_exception() && $@->{exception_type} ne 'ConflictPresent') { info ("\tUpdate failed, trying a cleanup."); my $result = safe_system('svn', 'cleanup'); $result == 0 or croak_runtime ("Unable to update $module, " . "svn cleanup failed with exit code $result"); info ("\tCleanup complete."); # Now try again (allow exception to bubble up this time). $count = $self->run_svn('svn-up-2', \@args); } my $count2 = $self->update_module_subdirectories(@path); return $count + $count2 if defined $count and defined $count2; return undef; } # Run the svn command. This is a special subroutine so that we can munge # the generated output to see what files have been added, and adjust the # build according. # # This function will throw an exception in the event of a build failure. # # First parameter is the ksb::Module object we're building. # Second parameter is the filename to use for the log file. # Third parameter is a reference to a list, which is the command ('svn') # and all of its arguments. # Return value is the number of files update (may be undef if unable to tell) sub run_svn { my ($self, $logfilename, $arg_ref) = @_; assert_isa($self, 'ksb::Updater::Svn'); my $module = $self->module(); my $revision = $module->getOption('revision'); if ($revision && $revision ne '0') { my @tmp = @{$arg_ref}; # Insert after first two entries, deleting 0 entries from the # list. splice @tmp, 2, 0, '-r', $revision; $arg_ref = \@tmp; } my $count = 0; my $conflict = 0; my $callback = sub { return unless $_; # The check for capitalized letters in the second column is because # svn can use the first six columns for updates (the characters will # all be uppercase), which makes it hard to tell apart from normal # sentences (like "At Revision foo" $count++ if /^[UPDARGMC][ A-Z]/; $conflict = 1 if /^C[ A-Z]/; }; # Do svn update. my $result = log_command($module, $logfilename, $arg_ref, { callback => $callback }); return 0 if pretending(); croak_runtime("Error updating $module!") unless $result == 0; if ($conflict) { warning ("Source code conflict exists in r[$module], this module will not"); warning ("build until it is resolved."); die make_exception('ConflictPresent', "Source conflicts exist in $module"); } return $count; } # Subroutine to check for subversion conflicts in a module. Basically just # runs svn st and looks for "^C". # # First parameter is the module to check for conflicts on. # Returns 0 if a conflict exists, non-zero otherwise. sub module_has_conflict { my $module = assert_isa(shift, 'ksb::Module'); my $srcdir = $module->fullpath('source'); if ($module->getOption('no-svn')) { whisper ("\tSource code conflict check skipped."); return 1; } else { info ("\tChecking for source conflicts... "); } my $pid = open my $svnProcess, "-|"; if (!$pid) { error ("\tUnable to open check source conflict status: b[r[$!]"); return 0; # false allows the build to proceed anyways. }; if (0 == $pid) { close STDERR; # No broken pipe warnings disable_locale_message_translation(); exec {'svn'} (qw/svn --non-interactive st/, $srcdir) or croak_runtime("Cannot execute 'svn' program: $!"); # Not reached } while (<$svnProcess>) { if (/^C/) { error (<isa('ksb::Module') should be true. sub updateInternal { my $self = assert_isa(shift, 'ksb::Updater::Svn'); my $module = $self->module(); my $fullpath = $module->fullpath('source'); my @options = split(' ', $module->getOption('checkout-only')); if (-e "$fullpath/.svn") { $self->check_module_validity(); my $updateCount = $self->update_module_path(@options); my $log_filter = sub { return unless defined $_; print $_ if /^C/; print $_ if /Checking for/; return; }; # Use log_command as the check so that an error file gets created. if (0 != log_command($module, 'conflict-check', ['kdesrc-build', 'ksb::Updater::Svn::module_has_conflict', $module], { callback => $log_filter, no_translate => 1 }) ) { croak_runtime (" * Conflicts present in module $module"); } return $updateCount; } else { return $self->checkout_module_path(@options); } } sub name { return 'svn'; } sub currentRevisionInternal { my $self = assert_isa(shift, 'ksb::Updater::Svn'); return $self->svnInfo('Revision'); } # Returns a requested parameter from 'svn info'. # # First parameter is a string with the name of the parameter to retrieve (e.g. URL). # Each line of output from svn info is searched for the requested string. # Returns the string value of the parameter or undef if an error occurred. sub svnInfo { my $self = assert_isa(shift, 'ksb::Updater::Svn'); my $module = $self->module(); my $param = shift; my $srcdir = $module->fullpath('source'); my $result; # Predeclare to outscope upcoming eval if (pretending() && ! -e $srcdir) { return 'Unknown'; } # Search each line of output, ignore stderr. # eval since filter_program_output uses exceptions. eval { # Need to chdir into the srcdir, in case srcdir is a symlink. # svn info /path/to/symlink barfs otherwise. p_chdir ($srcdir); my @lines = filter_program_output( sub { /^$param:/ }, 'svn', 'info', '--non-interactive', '.' ); croak_runtime ("No svn info output!") unless @lines; chomp ($result = $lines[0]); $result =~ s/^$param:\s*//; }; if($@) { error ("Unable to run r[b[svn], is the Subversion program installed?"); error (" -- Error was: r[$@]"); return undef; } return $result; } 1; diff --git a/modules/ksb/l10nSystem.pm b/modules/ksb/l10nSystem.pm deleted file mode 100644 index f2a0ea1..0000000 --- a/modules/ksb/l10nSystem.pm +++ /dev/null @@ -1,221 +0,0 @@ -package ksb::l10nSystem 0.10; - -# This class is an implementation of both the source and build interfaces needed to -# support building KDE l10n modules. - -use strict; -use warnings; -use 5.014; - -use parent qw(ksb::Updater::Svn ksb::BuildSystem); - -use ksb::Debug; -use ksb::Util; - -sub new -{ - my ($class, $module) = @_; - - # Ensure associated module updates from the proper svn path. - # TODO: Support different localization branches? - - $module->setOption('module-base-path', 'trunk/l10n-kde4'); - my $refreshMessage = "an update happened"; - return bless { module => $module, needsRefreshed => $refreshMessage }, $class; -} - -sub module -{ - my $self = shift; - return $self->{module}; -} - -sub configuredModuleFileName -{ - # Not quite correct (we should be looking at each individual language - # but it at least keeps the process going. - return 'teamnames'; -} - -# Sets the directories that are to be checked out/built/etc. -# There should be one l10nSystem for the entire l10n build (i.e. add -# all required support dirs and languages). -sub setLanguageDirs -{ - my ($self, @languageDirs) = @_; - $self->{l10n_dirs} = \@languageDirs; -} - -# Returns true if the given subdirectory (reference from the module's root source directory) -# can be built or not. Should be reimplemented by subclasses as appropriate. -sub isSubdirBuildable -{ - my ($self, $subdir) = @_; - return ($subdir ne 'scripts' && $subdir ne 'templates'); -} - -sub prepareModuleBuildEnvironment -{ - my ($ctx, $module, $prefix) = @_; - - $ctx->prependEnvironmentValue('CMAKE_PREFIX_PATH', $prefix); -} - -# scm-specific update procedure. -# May change the current directory as necessary. -sub updateInternal -{ - my $self = assert_isa(shift, 'ksb::Updater'); - my $module = $self->module(); - my $fullpath = $module->fullpath('source'); - my @dirs = @{$self->{l10n_dirs}}; - - if (-e "$fullpath/.svn") { - $self->check_module_validity(); - my $count = $self->update_module_path(@dirs); - - $self->{needsRefreshed} = '' if $count == 0; - return $count; - } - else { - return $self->checkout_module_path(@dirs); - } -} - -sub name -{ - return 'l10n'; -} - -# Returns a list of just the languages to install. -sub languages -{ - my $self = assert_isa(shift, 'ksb::l10nSystem'); - my @langs = @{$self->{l10n_dirs}}; - - return grep { $self->isSubdirBuildable($_); } (@langs); -} - -# Buildsystem support section - -sub needsRefreshed -{ - my $self = shift; - - # Should be a 'reason' string except if no update happened. - return $self->{needsRefreshed}; -} - -sub buildInternal -{ - my $self = assert_isa(shift, 'ksb::l10nSystem'); - my $builddir = $self->module()->fullpath('build'); - my @langs = $self->languages(); - my $result = ($self->safe_make({ - target => undef, - message => "Building localization for language...", - logbase => "build", - subdirs => \@langs, - }))->{was_successful}; - - return $result; -} - -sub configureInternal -{ - my $self = assert_isa(shift, 'ksb::l10nSystem'); - - my $builddir = $self->module()->fullpath('build'); - my @langs = $self->languages(); - my $result = 0; - - for my $lang (@langs) { - my $prefix = $self->module()->installationPath(); - p_chdir("$builddir/$lang"); - - info ("\tConfiguring to build language $lang"); - $result = (log_command($self->module(), "cmake-$lang", - ['cmake', '-DCMAKE_INSTALL_PREFIX=' . $prefix]) == 0) || $result; - } - - return $result; -} - -sub installInternal -{ - my $self = assert_isa(shift, 'ksb::l10nSystem'); - my $builddir = $self->module()->fullpath('build'); - my @langs = $self->languages(); - - return ($self->safe_make({ - target => 'install', - message => "Installing language...", - logbase => "install", - subdirs => \@langs, - }) == 0); -} - -# Subroutine to link a source directory into an alternate directory in -# order to fake srcdir != builddir for modules that don't natively support -# it. The first parameter is the module to prepare. -# -# The return value is true (non-zero) if it succeeded, and 0 (false) if it -# failed. -# -# On return from the subroutine the current directory will be in the build -# directory, since that's the only directory you should touch from then on. -sub prepareFakeBuilddir -{ - my $self = assert_isa(shift, 'ksb::l10nSystem'); - my $module = $self->module(); - my $builddir = $module->fullpath('build'); - my $srcdir = $module->fullpath('source'); - - # List reference, not a real list. The initial kdesrc-build does *NOT* - # fork another kdesrc-build using exec, see sub log_command() for more - # info. - my $args = [ 'kdesrc-build', 'main::safe_lndir', $srcdir, $builddir ]; - - info ("\tSetting up alternate build directory for l10n"); - return (0 == log_command ($module, 'create-builddir', $args)); -} - -# Subroutine to create the build system for a module. This involves making -# sure the directory exists and then running any preparatory steps (like -# for l10n modules). This subroutine assumes that the module is already -# downloaded. -# -# Return convention: boolean (inherited) -sub createBuildSystem -{ - my $self = assert_isa(shift, 'ksb::l10nSystem'); - my $module = $self->module(); - my $builddir = $module->fullpath('build'); - - # l10n doesn't support srcdir != builddir, fake it. - whisper ("\tFaking builddir for g[$module]"); - if (!$self->prepareFakeBuilddir()) - { - error ("Error creating r[$module] build system!"); - return 0; - } - - p_chdir ($builddir); - - my @langs = @{$self->{l10n_dirs}}; - @langs = grep { $self->isSubdirBuildable($_) } (@langs); - - foreach my $lang (@langs) { - my $cmd_ref = [ './scripts/autogen.sh', $lang ]; - if (log_command ($module, "build-system-$lang", $cmd_ref)) - { - error ("\tUnable to create build system for r[$module]"); - } - } - - $module->setOption('#reconfigure', 1); # Force reconfigure of the module - - return 1; -} - -1; diff --git a/vim/syntax/kdesrc-buildrc.vim b/vim/syntax/kdesrc-buildrc.vim index 6cd4808..bc1495f 100644 --- a/vim/syntax/kdesrc-buildrc.vim +++ b/vim/syntax/kdesrc-buildrc.vim @@ -1,153 +1,153 @@ " Vim syntax file " Language: kdesrc-build configuration file " Maintainer: Michael Pyne -" Latest Revision: 23 July 2017 +" Latest Revision: 6 January 2019 -" Copyright (c) 2014-2017 Michael Pyne +" Copyright (c) 2014-2019 Michael Pyne " Redistribution and use in source and binary forms, with or without " modification, are permitted provided that the following conditions " are met: " " 1. Redistributions of source code must retain the above copyright " notice, this list of conditions and the following disclaimer. " 2. Redistributions in binary form must reproduce the above copyright " notice, this list of conditions and the following disclaimer in the " documentation and/or other materials provided with the distribution. " " THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR " IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES " OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. " IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, " INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT " NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, " DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY " THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT " (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF " THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. if exists("b:current_syntax") finish endif syn case match " We use Lisp-style keywords setlocal iskeyword+=- " Keywords syn keyword ksbrcOption contained skipwhite nextgroup=ksbrcStringValue \ binpath branch build-dir checkout-only cmake-options configure-flags \ custom-build-command cxxflags dest-dir do-not-compile kdedir \ libpath log-dir make-install-prefix make-options module-base-path \ override-build-system override-url prefix qtdir repository \ revision source-dir svn-server tag remove-after-install \ qmake-options git-user syn keyword ksbrcGlobalOption contained skipwhite nextgroup=ksbrcStringValue \ branch-group git-desired-protocol git-repository-base http-proxy - \ kde-languages niceness debug-level persistent-data-file set-env + \ niceness debug-level persistent-data-file set-env " MUST BE CONSISTENT WITH ABOVE. Used when a module-set option is used in the " wrong spot to highlight the error. syn keyword ksbrcErrorGlobalOption contained skipwhite nextgroup=ksbrcStringValue \ branch-group git-desired-protocol git-repository-base http-proxy - \ kde-languages niceness debug-level persistent-data-file set-env + \ niceness debug-level persistent-data-file set-env syn keyword ksbrcModuleSetOption contained skipwhite nextgroup=ksbrcStringValue \ use-modules ignore-modules " MUST BE CONSISTENT WITH ABOVE. Used when a module-set option is used in the " wrong spot to highlight the error. syn keyword ksbrcErrorModuleSetOption contained skipwhite nextgroup=ksbrcStringValue \ use-modules ignore-modules syn keyword ksbrcBoolOption contained skipwhite nextgroup=ksbrcBoolValue \ build-system-only build-when-unchanged ignore-kde-structure \ include-dependencies install-after-build manual-build manual-update \ no-src reconfigure recreate-configure refresh-build run-tests \ use-clean-install syn keyword ksbrcGlobalBoolOption contained skipwhite nextgroup=ksbrcBoolValue \ async colorful-output disable-agent-check disable-snapshots pretend \ purge-old-logs stop-on-failure use-idle-io-priority install-session-driver \ install-environment-driver " MUST BE CONSISTENT WITH ABOVE. Used when a global option is used in the " wrong spot to highlight the error. syn keyword ksbrcErrorBoolOption contained skipwhite nextgroup=ksbrcBoolValue \ async colorful-output disable-agent-check disable-snapshots pretend \ purge-old-logs stop-on-failure use-idle-io-priority install-session-driver \ install-environment-driver " Matches syn match ksbrcKeyword "\" syn match ksbrcKeyword "\" syn match ksbrcKeyword "\" syn match ksbrcKeyword "\" syn match ksbrcPath "\S*$" contained syn match ksbrcKeyword "^\s*include\>" skipwhite nextgroup=ksbrcPath " This is a 'region' instead of a match to allow line continuations to work (a " match will never break across lines). 100% accuracy would demand that all " possible values/lines can be broken, but it makes no sense other than option " values so that's where I'll leave it for now. " " Since we're using a region we need to stop before comments manually, or stop " at EOL if there are no comments (which is why there's multiple end=). The " me=s-1 part to the 'end before comment' clause ensures that the comment and " any preceding whitespace isn't 'eaten up' by this match. syn region ksbrcStringValue start="\S" end="$" end="\s*#"me=s-1 contained contains=ksbrcLineContinue syn match ksbrcBoolValue "\c\" contained syn match ksbrcComment "#.*$" " Regions syn region ksbrcModuleSetRegion fold matchgroup=ksbrcKeyword \ start="module-set\>" end="end module-set" \ contains=ksbrcComment,ksbrcOption,ksbrcModuleSetOption,ksbrcBoolOption,ksbrcErrorBoolOption,ksbrcErrorGlobalOption syn region ksbrcGlobalRegion fold matchgroup=ksbrcKeyword \ start="global\>" end="end global" \ contains=ksbrcComment,ksbrcOption,ksbrcGlobalOption,ksbrcGlobalBoolOption,ksbrcBoolOption,ksbrcErrorModuleSetOption " These two regions should be about equivalent. Probably could just duplicate " the start= and end=, which vim supports, except that the end might not match " the corresponding start= syn region ksbrcModuleRegion fold matchgroup=ksbrcKeyword \ start='module\>\(-set\)\@!' end='end module' \ contains=ksbrcComment,ksbrcOption,ksbrcBoolOption,ksbrcErrorBoolOption,ksbrcErrorModuleSetOption,ksbrcErrorGlobalOption syn region ksbrcOptionsRegion fold matchgroup=ksbrcKeyword \ start="options\>" end="end options" \ contains=ksbrcComment,ksbrcOption,ksbrcBoolOption,ksbrcErrorBoolOption,ksbrcErrorModuleSetOption,ksbrcErrorGlobalOption " Handle continuation lines syn match ksbrcLineContinue "\\$" contained " Footer boilerplate let b:current_syntax = "kdesrc-buildrc" " Help vim find where to start highlighting (I think...) syn sync match SyncRegionEnd grouphere NONE "^\s*end\s\+\(module\|module-set\|options\)\s*$" " Link our styles to standard styles hi def link ksbrcKeyword Keyword hi def link ksbrcComment Comment hi def link ksbrcPath Include hi def link ksbrcStringValue String hi def link ksbrcBoolValue Boolean hi def link ksbrcOption Identifier hi def link ksbrcGlobalOption Identifier hi def link ksbrcBoolOption Identifier hi def link ksbrcGlobalBoolOption Identifier hi def link ksbrcModuleSetOption Identifier hi def link ksbrcLineContinue Special hi def link ksbrcErrorBoolOption Error hi def link ksbrcErrorModuleSetOption Error hi def link ksbrcErrorGlobalOption Error " vim: set ft=vim: