├── logo_combawa.png ├── .gitignore ├── utils ├── colors.sh ├── prerequisites.sh └── functions.sh ├── templates ├── combawa-build │ ├── update.sh.twig │ ├── install.sh.twig │ ├── predeploy_actions.sh.twig │ └── postdeploy_actions.sh.twig └── combawa-env │ ├── settings.local.php.twig │ ├── env-install.twig │ └── env-update.twig ├── composer.json ├── load.environment.php ├── src └── Drush │ └── Commands │ ├── InitializeBuildScriptsDrushCommands.php │ ├── DrushCommandsGeneratorBase.php │ └── GenerateEnvironmentDrushCommands.php ├── README.md ├── bin └── combawa.sh └── LICENCE /logo_combawa.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Happyculture/combawa/HEAD/logo_combawa.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # When building a library, the version should not be locked. 2 | # If necessary, add constraints in the dependencies versions. 3 | composer.lock 4 | vendor/ 5 | .idea 6 | -------------------------------------------------------------------------------- /utils/colors.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | LIGHT_RED="\033[0;31m" 4 | RED="\033[1;31m" 5 | LIGHT_GREEN="\033[0;32m" 6 | GREEN="\033[1;32m" 7 | ORANGE="\033[0;33m" 8 | YELLOW="\033[1;33m" 9 | LIGHT_BLUE="\033[0;34m" 10 | BLUE="\033[1;34m" 11 | LIGHT_PURPLE="\033[0;35m" 12 | PURPLE="\033[1;35m" 13 | LIGHT_CYAN="\033[0;36m" 14 | CYAN="\033[1;36m" 15 | NC="\033[0m" 16 | -------------------------------------------------------------------------------- /templates/combawa-build/update.sh.twig: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Actions run when the script is in update mode. 3 | 4 | # Flush drush cache to identify new commands such as rr. 5 | $DRUSH cc drush 6 | 7 | # Run drush deploy. It runs: 8 | # - hook_update_N 9 | # - hook_post_update_NAME 10 | # - cache:rebuild 11 | # - config:import 12 | # - cache:rebuild 13 | # - hook_deploy_NAME 14 | $DRUSH deploy 15 | -------------------------------------------------------------------------------- /templates/combawa-env/settings.local.php.twig: -------------------------------------------------------------------------------- 1 | $_ENV['COMBAWA_DB_HOSTNAME'], 6 | 'port' => $_ENV['COMBAWA_DB_PORT'], 7 | 'database' => $_ENV['COMBAWA_DB_DATABASE'], 8 | 'password' => $_ENV['COMBAWA_DB_PASSWORD'], 9 | 'username' => $_ENV['COMBAWA_DB_USER'], 10 | 'prefix' => '', 11 | 'driver' => 'mysql', 12 | 'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql', 13 | ]; 14 | -------------------------------------------------------------------------------- /templates/combawa-build/install.sh.twig: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Actions run when the script is in install mode. 3 | 4 | # Install the site. 5 | $DRUSH site-install --sites-subdir=default --locale=fr --existing-config minimal 6 | 7 | # Ensure all configuration has been imported (even the splitted config). 8 | $DRUSH cr 9 | $DRUSH config:import 10 | 11 | # Add administrator role to the user #1. 12 | $DRUSH user:role:add administrator admin 13 | 14 | # Fix Drupal annoying need to change permissions. 15 | chmod u+w "$WEBROOT/sites/default" 16 | chmod u+w "$WEBROOT/sites/default/settings.php" 17 | -------------------------------------------------------------------------------- /templates/combawa-env/env-install.twig: -------------------------------------------------------------------------------- 1 | # Environment type (dev, testing, prod). 2 | COMBAWA_BUILD_ENV={{ environment }} 3 | 4 | # Backup base before build. 5 | COMBAWA_DB_BACKUP_FLAG={{ backup_db }} 6 | 7 | # Internal path from the repo root pointing to the public document root. 8 | COMBAWA_WEBROOT_PATH={{ webroot }} 9 | 10 | ##### Database access settings. 11 | COMBAWA_DB_HOSTNAME={{ db_host }} 12 | COMBAWA_DB_PORT={{ db_port }} 13 | COMBAWA_DB_DATABASE={{ db_name }} 14 | COMBAWA_DB_USER={{ db_user }} 15 | COMBAWA_DB_PASSWORD={{ db_password }} 16 | 17 | ##### Drush settings. 18 | # Drush reads .env files and use these settings by default. 19 | 20 | DRUSH_OPTIONS_URI={{ environment_url }} 21 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "happyculture/combawa", 3 | "description": "Projects builder", 4 | "bin": ["bin/combawa.sh"], 5 | "type": "library", 6 | "licence": "GPL-3.0-or-later", 7 | "autoload": { 8 | "files": ["load.environment.php"], 9 | "psr-4": {"Combawa\\": "src"} 10 | }, 11 | "require": { 12 | "drush/drush": "^13", 13 | "symfony/dotenv": "^6 || ^7" 14 | }, 15 | "suggest": { 16 | "happyculture/combawa-wrapper": "Lets you run combawa from anywhere without naming explicitely vendor/bin/combawa.sh." 17 | }, 18 | "config": { 19 | "allow-plugins": { 20 | "composer/installers": true 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /load.environment.php: -------------------------------------------------------------------------------- 1 | usePutenv(TRUE); 9 | try { 10 | // This file is located in our dependency (vendor/happyculture/combawa) so we have to climb up the arborescence 11 | // to load the environment files expected to be at the root level or our project repository. 12 | // Load .env, .env.local, and .env.$APP_ENV.local or .env.$APP_ENV if defined. 13 | $dotenv->loadEnv(__DIR__ . '/../../../.env'); 14 | } 15 | catch (PathException $exception) { 16 | // Do nothing. Production environments rarely use .env files. 17 | } 18 | -------------------------------------------------------------------------------- /templates/combawa-build/predeploy_actions.sh.twig: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Actions to run before the main and shared deployment actions. 3 | # It can be useful to backup, import databases or doing something similar. 4 | 5 | # Example to clean files to avoid keeping old stuff. 6 | {#if [[ $COMBAWA_BUILD_ENV != "prod" ]]; then#} 7 | {# # Catch errors if the removal of files breaks.#} 8 | {# {#} 9 | {# rm -rf $WEBROOT/sites/default/files/*#} 10 | {# } || {#} 11 | {# if [[ $? != 0 ]]; then#} 12 | {# # Send a notification to inform that the build is broken#} 13 | {# # due to permissions errors.#} 14 | {# if hash notify-send 2>/dev/null; then#} 15 | {# notify-send "Error purging files before reinstalling. Permissions may be incorrect."#} 16 | {# exit -1#} 17 | {# fi#} 18 | {# fi#} 19 | {# }#} 20 | {#fi#} 21 | 22 | # Enable the maintenance mode. 23 | if [[ $COMBAWA_BUILD_MODE == "update" ]]; then 24 | $DRUSH sset system.maintenance_mode 1 25 | fi 26 | 27 | case $COMBAWA_BUILD_ENV in 28 | dev) 29 | ;; 30 | testing) 31 | ;; 32 | prod) 33 | ;; 34 | *) 35 | notify_fatal "Unknown environment: $COMBAWA_BUILD_ENV. Please check your name." 36 | esac 37 | -------------------------------------------------------------------------------- /templates/combawa-env/env-update.twig: -------------------------------------------------------------------------------- 1 | # Environment type (dev, testing, prod). 2 | COMBAWA_BUILD_ENV={{ environment }} 3 | 4 | # Backup base before build. 5 | COMBAWA_DB_BACKUP_FLAG={{ backup_db }} 6 | 7 | {% if environment != 'prod' %} 8 | # Reinstall site before building. 9 | COMBAWA_REIMPORT_REF_DUMP_FLAG={{ reimport }} 10 | 11 | # Whether to retrieve the dump from a remote server or not. 12 | # Re-run the generate-environment script to change this value afterwards. 13 | COMBAWA_DB_FETCH_FLAG={{ dump_fetch_update }} 14 | 15 | # Command to update the reference dump. 16 | COMBAWA_DB_FETCH_METHOD={{ dump_fetch_method }} 17 | {% if dump_fetch_method == 'scp' %} 18 | {% if dump_fetch_scp_config_name is not empty %} 19 | COMBAWA_DB_FETCH_SCP_CONFIG_NAME="{{ dump_fetch_scp_config_name }}" 20 | {% else %} 21 | COMBAWA_DB_FETCH_SCP_USER={{ dump_fetch_scp_user }} 22 | COMBAWA_DB_FETCH_SCP_SERVER="{{ dump_fetch_scp_host }}" 23 | COMBAWA_DB_FETCH_SCP_PORT={{ dump_fetch_scp_port }} 24 | {% endif %} 25 | {% endif %} 26 | COMBAWA_DB_FETCH_PATH_SOURCE="{{ dump_fetch_source_path }}" 27 | {% endif %} 28 | 29 | # Internal path from the repo root pointing to the public document root. 30 | COMBAWA_WEBROOT_PATH={{ webroot }} 31 | 32 | ##### Database access settings. 33 | COMBAWA_DB_HOSTNAME={{ db_host }} 34 | COMBAWA_DB_PORT={{ db_port }} 35 | COMBAWA_DB_DATABASE={{ db_name }} 36 | COMBAWA_DB_USER={{ db_user }} 37 | COMBAWA_DB_PASSWORD={{ db_password }} 38 | 39 | ##### Drush settings. 40 | # Drush reads .env files and use these settings by default. 41 | 42 | DRUSH_OPTIONS_URI={{ environment_url }} 43 | -------------------------------------------------------------------------------- /templates/combawa-build/postdeploy_actions.sh.twig: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Action to run after the main and shared deployment actions. 3 | # It can be useful to enable specific modules for instance. 4 | 5 | case $COMBAWA_BUILD_ENV in 6 | dev) 7 | # Update translations. 8 | $DRUSH locale:check 9 | $DRUSH locale:update 10 | 11 | # Import deployment and test related content. 12 | # $DRUSH en MYPROJECT_NAME_content_deploy 13 | # $DRUSH en MYPROJECT_NAME_content_test 14 | 15 | # Use config import to disable modules that should not be enabled in this 16 | # environment. 17 | #$DRUSH config:import 18 | 19 | # Rebuild search indexes. 20 | # $DRUSH sapi-r 21 | # $DRUSH sapi-i 22 | 23 | # Rebuild permissions 24 | # $DRUSH php-eval 'node_access_rebuild();' 25 | 26 | # Enable development settings. 27 | $DRUSH sset twig_debug TRUE 28 | $DRUSH sset twig_autoreload TRUE 29 | $DRUSH sset twig_cache_disable TRUE 30 | $DRUSH sset disable_rendered_output_cache_bins TRUE 31 | 32 | # Connect. 33 | $DRUSH uli 34 | ;; 35 | testing) 36 | # Update translations. 37 | $DRUSH locale:check 38 | $DRUSH locale:update 39 | 40 | # Import deployment and test related content. 41 | # $DRUSH en MYPROJECT_NAME_content_deploy 42 | # $DRUSH en MYPROJECT_NAME_content_test 43 | 44 | # Use config import to disable modules that should not be enabled in this 45 | # environment. 46 | #$DRUSH config:import 47 | 48 | # Rebuild search indexes. 49 | # $DRUSH sapi-r 50 | # $DRUSH sapi-i 51 | 52 | # Rebuild permissions 53 | # $DRUSH php-eval 'node_access_rebuild();' 54 | ;; 55 | prod) 56 | # Update translations. 57 | $DRUSH locale:check 58 | $DRUSH locale:update 59 | 60 | # Import deployment related content. 61 | # $DRUSH en MYPROJECT_NAME_content_deploy 62 | 63 | # Use config import to disable modules that should not be enabled in this 64 | # environment. 65 | #$DRUSH config:import 66 | 67 | # Rebuild permissions 68 | # $DRUSH php-eval 'node_access_rebuild();' 69 | ;; 70 | *) 71 | notify_fatal "Unknown environment: $COMBAWA_BUILD_ENV. Please check your name." 72 | esac 73 | 74 | # Disable the maintenance mode. 75 | if [[ $COMBAWA_BUILD_MODE == "update" ]]; then 76 | $DRUSH sset system.maintenance_mode 0 77 | fi 78 | -------------------------------------------------------------------------------- /utils/prerequisites.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ################################# 4 | section_separator 5 | ################################# 6 | 7 | # Check predeploy action script. 8 | message_step "Verifying predeploy action script." 9 | if [ ! -f "$COMBAWA_SCRIPTS_DIR/predeploy_actions.sh" ]; then 10 | notify_fatal "There is no predeploy actions script at the moment or its not readable." "You should run the following command to initialize it: 'drupal combawa:generate-project'." 11 | fi 12 | message_confirm "Predeploy actions script... OK!" 13 | 14 | ################################# 15 | section_separator 16 | ################################# 17 | 18 | # Check postdeploy actions script. 19 | message_step "Verifying postdeploy action script." 20 | if [ ! -f "$COMBAWA_SCRIPTS_DIR/postdeploy_actions.sh" ]; then 21 | notify_fatal "There is no postdeploy actions script at the moment or its not readable." "You should run the following command to initialize it: 'drupal combawa:generate-project'." 22 | fi 23 | message_confirm "Postdeploy actions script... OK!" 24 | 25 | ################################# 26 | section_separator 27 | ################################# 28 | 29 | # Preliminary verification to avoid running actions 30 | # if the requiprements are not met. 31 | case $COMBAWA_BUILD_MODE in 32 | "install" ) 33 | message_step "Verifying install.sh action script." 34 | if [ ! -f "$COMBAWA_SCRIPTS_DIR/install.sh" ]; then 35 | notify_fatal "There is no /scripts/combawa/install.sh script at the moment or its not readable." "You should run the following command to initialize it: 'drupal combawa:generate-project'." 36 | fi 37 | message_confirm "Install.sh check... OK!" 38 | ;; 39 | "update" ) 40 | message_step "Verifying update.sh action script." 41 | if [ ! -f "$COMBAWA_SCRIPTS_DIR/update.sh" ]; then 42 | notify_fatal "There is no /scripts/combawa/update.sh script at the moment or its not readable." "You should run the following command to initialize it: 'drupal combawa:generate-project'." 43 | fi 44 | message_confirm "Update.sh check... OK!" 45 | ;; 46 | * ) 47 | notify_fatal "Build mode unknown." 48 | ;; 49 | esac 50 | 51 | ################################# 52 | section_separator 53 | ################################# 54 | 55 | # Test DB connection. 56 | message_step "Verifying database connectivity." 57 | { 58 | $DRUSH sql:query "SHOW TABLES;" 59 | } &> /dev/null || { # catch 60 | notify_fatal "The connection to the database is impossible." 61 | } 62 | message_confirm "DB connection... OK!" 63 | 64 | ################################# 65 | section_separator 66 | ################################# 67 | 68 | if [ $COMBAWA_DB_FETCH_FLAG == 1 ]; then 69 | # Test DB fetch method parameters. 70 | message_step "Verifying reference dump fetching method." 71 | 72 | # Verify that the fetch method is supported. 73 | case $COMBAWA_DB_FETCH_METHOD in 74 | "cp" ) 75 | message_action "Verifying 'cp' dump fetching parameters." 76 | # Are our variables defined? 77 | if [ -z ${COMBAWA_DB_FETCH_PATH_SOURCE+x} ] || [ -z ${COMBAWA_DB_DUMP_PATH+x} ]; then 78 | notify_fatal "The parameter COMBAWA_DB_FETCH_PATH_SOURCE or COMBAWA_DB_DUMP_PATH is empty. We will not be able to copy a reference dump." 79 | fi 80 | message_action "Verifying 'cp' files are accessible." 81 | # Is the source file accessible/readable? 82 | if [ ! -f $COMBAWA_DB_FETCH_PATH_SOURCE ]; then 83 | notify_fatal "There is no $COMBAWA_DB_FETCH_PATH_SOURCE source file at the moment or its not readable." "Is your path correct or accessible?." 84 | fi 85 | message_confirm "'cp' dump fetching parameters check... OK!" 86 | ;; 87 | "scp" ) 88 | message_action "Verifying 'scp' dump fetching parameters." 89 | set +e 90 | # Login with SSH config name or ssh info? 91 | if [ -z ${COMBAWA_DB_FETCH_SCP_CONFIG_NAME+x} ]; then 92 | # Are our variables defined? 93 | if [ -z ${COMBAWA_DB_FETCH_SCP_SERVER+x} ] || [ -z ${COMBAWA_DB_FETCH_SCP_PORT+x} ] || [ -z ${COMBAWA_DB_FETCH_PATH_SOURCE+x} ] ; then 94 | notify_fatal "One of the parameters COMBAWA_DB_FETCH_SCP_SERVER, COMBAWA_DB_FETCH_SCP_PORT or COMBAWA_DB_FETCH_PATH_SOURCE is empty. We will not be able to copy a reference dump." 95 | fi 96 | message_step "Testing connection with remote SSH server from which the dump will be retrieved:" 97 | # Determine if we have a username to use to login. 98 | if [ -z ${COMBAWA_DB_FETCH_SCP_USER} ]; then 99 | # SCP login via servername and current user. 100 | ssh -q -p $COMBAWA_DB_FETCH_SCP_PORT $COMBAWA_DB_FETCH_SCP_SERVER -o ConnectTimeout=5 echo > /dev/null 101 | else 102 | # Also determine if we have a password to use. 103 | if [ -z ${COMBAWA_DB_FETCH_SCP_PASSWORD} ]; then 104 | # SCP login via username. 105 | ssh -q -p $COMBAWA_DB_FETCH_SCP_PORT $COMBAWA_DB_FETCH_SCP_USER@$COMBAWA_DB_FETCH_SCP_SERVER -o ConnectTimeout=5 echo > /dev/null 106 | else 107 | # SCP login via username and password. 108 | ssh -q -p $COMBAWA_DB_FETCH_SCP_PORT $COMBAWA_DB_FETCH_SCP_USER:$COMBAWA_DB_FETCH_SCP_PASSWORD@$COMBAWA_DB_FETCH_SCP_SERVER -o ConnectTimeout=5 echo > /dev/null 109 | fi 110 | fi 111 | else 112 | ssh -q $COMBAWA_DB_FETCH_SCP_CONFIG_NAME -o ConnectTimeout=5 echo > /dev/null 113 | fi 114 | if [ "$?" != "0" ] ; then 115 | notify_fatal "Impossible to connect to the SSH server." "Check your SSH connection parameters. Should you connect through a VPN?" 116 | else 117 | message_confirm "'scp' dump fetching parameters check... OK!" 118 | fi 119 | set -e 120 | ;; 121 | * ) 122 | notify_fatal "Dump fetching '$COMBAWA_DB_FETCH_METHOD' method unsupported." 123 | ;; 124 | esac 125 | message_confirm "Reference dump fetching method... OK!" 126 | else 127 | message_action "Do not fetch the reference dump for this build." 128 | fi 129 | 130 | ################################# 131 | section_separator 132 | ################################# 133 | 134 | # Test incompatible parameters. 135 | if [[ $COMBAWA_BUILD_MODE == "install" ]] && [[ $COMBAWA_REIMPORT_REF_DUMP_FLAG == 1 ]]; then 136 | notify_error "Reimport DB is not available in install build mode.\nYou should either change your build mode (-m) to 'update' or disable the reimport mode (-r 0)." 137 | fi 138 | -------------------------------------------------------------------------------- /src/Drush/Commands/InitializeBuildScriptsDrushCommands.php: -------------------------------------------------------------------------------- 1 | install, update)', 28 | suggestedValues: ['install', 'update'])] 29 | #[CLI\Option( 30 | name: 'overwrite-scripts', 31 | description: 'Overwrite existing scripts files. (Accepted: boolean)', 32 | suggestedValues: [TRUE, FALSE])] 33 | #[CLI\Option( 34 | name: 'generate-env', 35 | description: 'Generate environment file. (Accepted: boolean)', 36 | suggestedValues: [TRUE, FALSE])] 37 | #[CLI\Option( 38 | name: 'dry-run', 39 | description: 'Output the generated code but do not save it to file system.')] 40 | #[CLI\Usage(name: 'drush combawa:initialize-build-scripts', description: 'Run with wizard')] 41 | public function initializeBuildScripts(array $options = [ 42 | 'build-mode' => self::REQ, 43 | 'overwrite-scripts' => self::OPT, 44 | 'generate-env' => self::OPT, 45 | 'dry-run' => FALSE, 46 | ]): int { 47 | return $this->generate($options); 48 | } 49 | 50 | /** 51 | * {@inheritdoc} 52 | */ 53 | protected function extractOptions(array $options): array { 54 | $vars = [ 55 | 'build_mode' => $options['build-mode'], 56 | 'overwrite_scripts' => $options['overwrite-scripts'], 57 | 'generate_env' => $options['generate-env'], 58 | ]; 59 | return array_filter($vars, fn ($value) => !\is_null($value)); 60 | } 61 | 62 | /** 63 | * {@inheritDoc} 64 | */ 65 | protected function interview(array &$vars): void { 66 | if (!isset($vars['build_mode'])) { 67 | $composerData = Json::decode(file_get_contents($this->drupalFinder()->getComposerRoot() . '/composer.json')); 68 | $defaultValue = $composerData['extra']['combawa']['build_mode'] ?? 'install'; 69 | $vars['build_mode'] = $this->io()->select( 70 | 'What is the build mode to use?', 71 | ['install', 'update'], 72 | $defaultValue, 73 | ); 74 | } 75 | 76 | $scriptsDir = $this->drupalFinder()->getComposerRoot() . '/scripts/combawa'; 77 | if ( 78 | $this->fileSystem->exists($scriptsDir . '/' . $vars['build_mode'] . '.sh') && 79 | !isset($vars['overwrite_scripts']) 80 | ) { 81 | $vars['overwrite_scripts'] = $this->io()->confirm( 82 | 'Do you want to overwrite your existing scripts located in the scripts/combawa directory?', 83 | FALSE, 84 | ); 85 | } 86 | } 87 | 88 | /** 89 | * {@inheritdoc} 90 | */ 91 | protected function validateVars(array $vars): void { 92 | $errors = []; 93 | if (isset($vars['build_mode'])) { 94 | $errors[] = $this->validateBuildMode($vars['build_mode']); 95 | } 96 | 97 | $errors = array_filter($errors); 98 | if (!empty($errors)) { 99 | throw new \InvalidArgumentException(implode("\n", $errors)); 100 | } 101 | } 102 | 103 | /** 104 | * {@inheritdoc} 105 | */ 106 | protected function getVarsSummary(array $vars): array { 107 | $summary = [ 108 | 'Build mode' => $vars['build_mode'], 109 | ]; 110 | $scriptsDir = $this->drupalFinder()->getComposerRoot() . '/scripts/combawa'; 111 | if ($this->fileSystem->exists($scriptsDir . '/' . $vars['build_mode'] . '.sh')) { 112 | $summary['Overwrite scripts files'] = $vars['overwrite_scripts'] ? 'Yes' : 'No'; 113 | } 114 | return $summary; 115 | } 116 | 117 | /** 118 | * {@inheritdoc} 119 | */ 120 | protected function preGenerate(array &$vars): void { 121 | $prevDir = getcwd(); 122 | chdir($this->drupalFinder()->getComposerRoot()); 123 | 124 | // Update the build mode. 125 | $process = $this->processManager() 126 | ->shell('/usr/bin/env composer config extra.combawa.build_mode ' . $vars['build_mode']); 127 | $process->mustRun(); 128 | 129 | // Update the lock file. 130 | $process = $this->processManager() 131 | ->shell('/usr/bin/env composer update --lock'); 132 | $process->mustRun(); 133 | 134 | chdir($prevDir); 135 | } 136 | 137 | /** 138 | * {@inheritdoc} 139 | */ 140 | protected function postGenerate(array $vars): void { 141 | if (!isset($vars['generate_env'])) { 142 | $defaultValue = FALSE; 143 | $vars['generate_env'] = $this->io()->confirm( 144 | 'Next, we will need you to generate the environment file (.env). Do you want to do it right after saving the previous settings?', 145 | $defaultValue, 146 | ); 147 | } 148 | if (empty($vars['generate_env'])) { 149 | return; 150 | } 151 | 152 | // Run generate-environment drush command on the same build_mode used in 153 | // this command. 154 | $process = $this->processManager()->drush( 155 | $this->siteAliasManager()->getSelf(), 156 | 'combawa:generate-environment', 157 | [], 158 | Drush::redispatchOptions() + ['build-mode' => $vars['build_mode']], 159 | ); 160 | // Enable TTY unless this command was already non interactive. 161 | $process->setTty($this->input()->isInteractive()); 162 | $process->mustRun(); 163 | } 164 | 165 | /** 166 | * {@inheritDoc} 167 | */ 168 | protected function collectAssets(AssetCollection $assets, array $vars): void { 169 | $scriptsDir = $this->drupalFinder()->getComposerRoot() . '/scripts/combawa'; 170 | if ( 171 | !empty($vars['overwrite_scripts']) || 172 | !$this->fileSystem->exists($scriptsDir . '/' . $vars['build_mode'] . '.sh') 173 | ) { 174 | $dir = opendir(static::TEMPLATES_PATH); 175 | while ($file = readdir($dir)) { 176 | if ($file[0] === '.') { 177 | continue; 178 | } 179 | 180 | $destination_file = substr($file, 0, -1 * strlen('.twig')); 181 | 182 | $assets->addFile( 183 | '../scripts/combawa/' . $destination_file, 184 | $file, 185 | ); 186 | } 187 | } 188 | } 189 | 190 | /** 191 | * {@inheritdoc} 192 | */ 193 | protected function outputGeneratedAssetsSummary(AssetCollection $assets): void { 194 | $assets->addFile('../composer.json'); 195 | $assets->addFile('../composer.lock'); 196 | parent::outputGeneratedAssetsSummary($assets); 197 | } 198 | 199 | } 200 | -------------------------------------------------------------------------------- /src/Drush/Commands/DrushCommandsGeneratorBase.php: -------------------------------------------------------------------------------- 1 | renderer->setLogger(new Logger($this->output())); 48 | $this->renderer->registerTemplatePath(static::TEMPLATES_PATH); 49 | } 50 | 51 | /** 52 | * Command creator called by Drush before bootstrapping Drupal. 53 | * 54 | * @see https://www.drush.org/12.x/dependency-injection/#createearly-method 55 | */ 56 | public static function createEarly(DrushContainer $drush_container): static { 57 | return new static( 58 | new Filesystem(), 59 | new TwigRenderer(new TwigEnvironment(new TemplateLoader())), 60 | ); 61 | } 62 | 63 | /** 64 | * DrupalFinder utility getter. 65 | * 66 | * @return \Drush\DrupalFinder\DrushDrupalFinder 67 | * The DrupalFinder utility. 68 | */ 69 | public function drupalFinder(): DrushDrupalFinder { 70 | if (!isset($this->drupalFinder)) { 71 | $this->drupalFinder = $this->processManager()->getDrupalFinder(); 72 | } 73 | return $this->drupalFinder; 74 | } 75 | 76 | /** 77 | * Run the generation process. 78 | * 79 | * @param array $options 80 | * The options array given to the command. 81 | */ 82 | protected function generate(array $options): int { 83 | // Extract generation data from options. 84 | $vars = $this->extractOptions($options); 85 | 86 | // Ensure all preset vars are correct. 87 | $this->validateVars($vars); 88 | 89 | // Ask questions to complete existing data. 90 | $this->interview($vars); 91 | 92 | // Process vars to get a clean extraction. 93 | $vars = Utils::processVars($vars); 94 | 95 | // Show collected data. 96 | $summary = $this->getVarsSummary($vars); 97 | if (!empty($summary)) { 98 | $this->io()->newLine(1); 99 | $this->io()->title('Settings summary'); 100 | $output = array_chunk($summary, 1, TRUE); 101 | $this->io()->definitionList(...$output); 102 | } 103 | 104 | $proceed = $this->io()->confirm('Are you sure you want to proceed?'); 105 | if (!$proceed) { 106 | $this->io()->info('Generation aborted.'); 107 | return self::EXIT_SUCCESS; 108 | } 109 | 110 | $this->preGenerate($vars); 111 | 112 | // Collect and generate assets. 113 | $assets = new AssetCollection(); 114 | $this->collectAssets($assets, $vars); 115 | $generatedAssets = $this->generateAssets($assets, $vars); 116 | $this->outputGeneratedAssetsSummary($generatedAssets); 117 | 118 | $this->postGenerate($vars); 119 | 120 | return self::EXIT_SUCCESS; 121 | } 122 | 123 | /** 124 | * Extract generator data from the command options. 125 | * 126 | * @param array $options 127 | * The array of the command options. 128 | * 129 | * @return array 130 | * The data used by the generator. 131 | */ 132 | protected function extractOptions(array $options): array { 133 | return $options; 134 | } 135 | 136 | /** 137 | * Ask needed questions to generate the files. 138 | * 139 | * @param array $vars 140 | * The preset vars to be amended. 141 | */ 142 | abstract protected function interview(array &$vars): void; 143 | 144 | /** 145 | * Validate generator data content. 146 | * 147 | * @param array $vars 148 | * The generator data. 149 | */ 150 | protected function validateVars(array $vars): void {} 151 | 152 | /** 153 | * Outputs the summary of vars used to generate the files. 154 | * 155 | * @param array $vars 156 | * The vars used to generate the files. 157 | * 158 | * @return array 159 | * The vars summary array keyed by human readable variable name. 160 | */ 161 | protected function getVarsSummary(array $vars): array { 162 | return $vars; 163 | } 164 | 165 | /** 166 | * Act before assets generation. 167 | * 168 | * @param array $vars 169 | * The generator data. 170 | */ 171 | protected function preGenerate(array &$vars): void {} 172 | 173 | /** 174 | * Act after assets generation. 175 | * 176 | * @param array $vars 177 | * The generator data. 178 | */ 179 | protected function postGenerate(array $vars): void {} 180 | 181 | /** 182 | * Collect assets to be generated. 183 | * 184 | * @param \DrupalCodeGenerator\Asset\AssetCollection $assets 185 | * The asset collection. 186 | * @param array $vars 187 | * The generator data. 188 | */ 189 | abstract protected function collectAssets(AssetCollection $assets, array $vars): void; 190 | 191 | /** 192 | * Generate assets. 193 | * 194 | * @param \DrupalCodeGenerator\Asset\AssetCollection $assets 195 | * The assets to be generated. 196 | * @param array $vars 197 | * The generator data. 198 | * 199 | * @return \DrupalCodeGenerator\Asset\AssetCollection 200 | * The assets that have been generated. 201 | */ 202 | protected function generateAssets(AssetCollection $assets, array $vars): AssetCollection { 203 | $resolver = new ReplaceResolver($this->dcgIo()); 204 | 205 | foreach ($assets as $asset) { 206 | $asset->resolver($resolver); 207 | $asset->vars(\array_merge($vars, Utils::processVars($asset->getVars()))); 208 | if ($asset instanceof RenderableInterface) { 209 | $asset->render($this->renderer); 210 | } 211 | } 212 | 213 | if ($this->input()->getOption('dry-run')) { 214 | $dumper = new DryDumper($this->fileSystem); 215 | $this->io()->newLine(); 216 | $this->io()->title('Files that would have been created or updated:'); 217 | } 218 | else { 219 | $dumper = new FileSystemDumper($this->fileSystem); 220 | } 221 | $dumper->io($this->dcgIo()); 222 | return $dumper->dump($assets, $this->drupalFinder()->getDrupalRoot()); 223 | } 224 | 225 | /** 226 | * Display files that have been generated. 227 | * 228 | * @param \DrupalCodeGenerator\Asset\AssetCollection $assets 229 | * The generated asset collection. 230 | */ 231 | protected function outputGeneratedAssetsSummary(AssetCollection $assets): void { 232 | if (\count($assets) === 0 || $this->input()->getOption('dry-run')) { 233 | return; 234 | } 235 | 236 | $this->io()->newLine(); 237 | $this->io()->title('The following directories and files have been created or updated:'); 238 | 239 | $items = []; 240 | foreach ($assets->getSorted() as $asset) { 241 | $items[] = $asset->getPath(); 242 | } 243 | 244 | $this->io()->listing($items); 245 | } 246 | 247 | /** 248 | * Get IO object for DrupalCodeGenerator services. 249 | * 250 | * @return \DrupalCodeGenerator\InputOutput\IO 251 | * The IO crafted for our use of DrupalCodeGenerator services. 252 | */ 253 | protected function dcgIo(): IO { 254 | if (!isset($this->dcgIo)) { 255 | $inputDefinition = new InputDefinition([ 256 | new InputOption('replace'), 257 | new InputOption('full-path'), 258 | new InputOption('dry-run'), 259 | ]); 260 | $input = new ArrayInput([], $inputDefinition); 261 | $input->setInteractive($this->input()->isInteractive()); 262 | $input->setOption('dry-run', $this->input()->getOption('dry-run')); 263 | $this->dcgIo = new IO($input, $this->output(), new QuestionHelper()); 264 | } 265 | return $this->dcgIo; 266 | } 267 | 268 | /** 269 | * Validates the build mode input. 270 | * 271 | * @param string $build_mode 272 | * The build mode. 273 | * 274 | * @return ?string 275 | * The error if there is one. 276 | */ 277 | public function validateBuildMode($build_mode): ?string { 278 | if (!in_array($build_mode, ['install', 'update'])) { 279 | return sprintf( 280 | 'Build mode "%s" is invalid, it must either be install or update.', 281 | $build_mode 282 | ); 283 | } 284 | return NULL; 285 | } 286 | 287 | } 288 | -------------------------------------------------------------------------------- /utils/functions.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ########## FUNCTION ############## 4 | 5 | # Display messages in specific colors. 6 | # Arg1: Message string. 7 | # Arg2: Message color (see colors.sh for available colors). 8 | message_color() 9 | { 10 | _MESSAGE="$1" 11 | _COLOR="$2" 12 | echo -e "${_COLOR}${_MESSAGE}${NC}" 13 | } 14 | 15 | # Displays a step message. 16 | message_step() 17 | { 18 | _MESSAGE="$1" 19 | message_color "${_MESSAGE}" "${BLUE}" 20 | } 21 | 22 | # Displays an action message. 23 | message_action() 24 | { 25 | _MESSAGE="$1" 26 | message_color "${_MESSAGE}" "${YELLOW}" 27 | } 28 | 29 | # Displays a confirmation message. 30 | message_confirm() 31 | { 32 | _MESSAGE="$1" 33 | message_color "${_MESSAGE}" "${GREEN}" 34 | echo -e "" 35 | } 36 | 37 | # Displays a warning message. 38 | message_warning() 39 | { 40 | _MESSAGE="$1" 41 | message_color "${_MESSAGE}" "${ORANGE}" 42 | } 43 | 44 | # Displays an error message. 45 | message_error() 46 | { 47 | _MESSAGE="$1" 48 | message_color "${_MESSAGE}" "${RED}" 49 | } 50 | 51 | # Displays an error message and exits. 52 | message_fatal() 53 | { 54 | message_error "$1" 55 | return -1 56 | } 57 | 58 | # Display a variable override. 59 | # Arg 1 is the source value. 60 | # Arg 2 is the new value. 61 | message_override() 62 | { 63 | _VAL_SOURCE="$1" 64 | _VAL_OVERRIDE="$2" 65 | echo -e "From ${LIGHT_RED}${_VAL_SOURCE}${NC} to ${LIGHT_GREEN}${_VAL_OVERRIDE}${NC}" 66 | } 67 | 68 | # Useful to separate build steps. 69 | section_separator() 70 | { 71 | echo -e "" 72 | echo -e "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" 73 | echo -e "" 74 | } 75 | 76 | # Help function. 77 | usage() 78 | { 79 | bold=$(tput bold) 80 | normal=$(tput sgr0) 81 | 82 | echo -e "${bold}Usage:${normal}" 83 | echo '' 84 | echo -e "${bold}Long version:${normal} ./build.sh --env dev --mode install --backup 1 --fetch-db-dump 1 --reimport 1 --yes" 85 | echo -e "${bold}Short version:${normal} ./build.sh -e dev -m install -b 1 -u http://hc.fun -f 1 -r 1 -y" 86 | echo '' 87 | echo -e "Some arguments can be omitted, the default value will be pulled from the generated .env file." 88 | echo '' 89 | echo -e "Available arguments are:" 90 | echo -e "${bold}\t--env, -e: Environment to build.${normal}" 91 | echo -e '\t\tAllowed values are: dev, testing, prod' 92 | echo '' 93 | echo -e "${bold}\t--mode, -m: Build mode${normal}" 94 | echo -e '\t\tAllowed values are: install, update' 95 | echo '' 96 | echo -e "${bold}\t--backup, -b: Generates a backup before building the project.${normal}" 97 | echo -e '\t\tAllowed values are: 0: does not generate a backup, 1: generates a backup.' 98 | echo '' 99 | echo -e "${bold}\t--fetch-db-dump, -f: Fetch a fresh DB dump from the production site.${normal}" 100 | echo -e '\t\tUsed when the reference dump should be updated.' 101 | echo -e '\t\tAllowed values are: 0: does not fetch a copy of the reference DB dump, 1: fetches the reference DB dump.' 102 | echo '' 103 | echo -e "${bold}\t--reimport, -r: Reimport the site from the reference dump.${normal}" 104 | echo -e '\t\tAllowed values are: 0: does not reimport the reference dump, 1: reimports the ref dump (drop and inject).' 105 | echo '' 106 | echo -e "${bold}\t--yes, -y: Bypass confirmation step.${normal}" 107 | echo '' 108 | echo -e '\t Additional arguments are available to control the steps to execute:' 109 | echo '' 110 | echo -e "${bold}\t--no-predeploy:${normal} Do not process predeploy actions." 111 | echo -e "${bold}\t--no-postdeploy:${normal} Do not process postdeploy actions." 112 | echo -e "${bold}\t--only-predeploy:${normal} Only process predeploy actions." 113 | echo -e "${bold}\t--only-postdeploy:${normal} Only process postdeploy actions." 114 | echo '' 115 | echo -e "${bold}\t--stop-after-reimport: Utilitary flag to stop building after reimporting the DB.${normal}" 116 | echo -e "\t\tThis option is useful if you want to fetch your remote DB, import it and version its config." 117 | echo '' 118 | exit 119 | } 120 | 121 | # Notify function. 122 | notify() 123 | { 124 | if hash notify-send 2>/dev/null; then 125 | notify-send "$1" 126 | fi 127 | 128 | message_confirm "$1" 129 | } 130 | 131 | # Notify error. 132 | notify_error() 133 | { 134 | _MESSAGE="$1" 135 | if hash notify-send 2>/dev/null; then 136 | notify-send "$1" 137 | fi 138 | message_error "$_MESSAGE" 139 | # Test if we have a suggestion message and display it if so. 140 | # Bash is weird, we must test if the second argument is empty (the opposite 141 | # test doesn't exist). It means that when we enter in the if, we don't want 142 | # to do anything. 143 | if [ -z ${2+x} ]; then 144 | # We need to use ":" to do nothing (an empty string generates a syntax 145 | # error) 146 | : 147 | else 148 | message_warning "$2" 149 | fi 150 | 151 | exit -1 152 | } 153 | 154 | # Notify fatal. 155 | notify_fatal() 156 | { 157 | 158 | _MESSAGE="$1" 159 | if hash notify-send 2>/dev/null; then 160 | notify-send "$1" 161 | fi 162 | message_error "$_MESSAGE" 163 | # Test if we have a suggestion message and display it if so. 164 | # Bash is weird, we must test if the second argument is empty (the opposite 165 | # test doesn't exist). It means that when we enter in the if, we don't want 166 | # to do anything. 167 | if [ -z ${2+x} ]; then 168 | # We need to use ":" to do nothing (an empty string generates a syntax 169 | # error) 170 | : 171 | else 172 | message_warning "$2" 173 | fi 174 | exit -10 175 | } 176 | 177 | # Generates a backup of the current DB 178 | backup_db() 179 | { 180 | message_step "Generating the backup DB dump:" 181 | # Store a security backup in case the update doesn't go right. 182 | DUMP_NAME="update-backup-script-$(date +%Y%m%d%H%M%S).sql"; 183 | DUMP_PATH="$WEBROOT/../dumps/$DUMP_NAME" 184 | mkdir -p "$WEBROOT/../dumps/" 185 | message_action "Dump generation in progress..." 186 | $DRUSH sql-dump --structure-tables-list=cache_* --result-file=$DUMP_PATH --gzip 187 | # Remove older backups but keep the 10 youngest ones. 188 | if [[ $(ls -l $WEBROOT/../dumps/*.sql.gz | wc -l) -gt 10 ]]; then 189 | message_action "Cleaning up oldest backup dumps..." 190 | ls -tp $WEBROOT/../dumps/*.sql.gz | grep -v '/$' | tail -n +10 | tr '\n' '\0' | xargs -0 rm -- 191 | message_confirm "Cleanup done!" 192 | fi 193 | message_confirm "Backup dump generated!" 194 | } 195 | 196 | # Download dump function. 197 | download_dump() 198 | { 199 | message_step "Updating the reference dump:" 200 | # Create the dumps dir if necessary. 201 | $(mkdir -p $(dirname -- "$COMBAWA_ROOT/$COMBAWA_DB_DUMP_PATH")) 202 | 203 | case $COMBAWA_DB_FETCH_METHOD in 204 | "cp" ) 205 | message_action "Copying reference dump with 'cp'." 206 | cp $COMBAWA_DB_FETCH_PATH_SOURCE $COMBAWA_ROOT/$COMBAWA_DB_DUMP_PATH 207 | message_confirm "Reference dump update... OK!" 208 | ;; 209 | "scp" ) 210 | message_action "Copying reference dump with 'scp'." 211 | # Login with SSH config name or ssh info? 212 | if [ -z ${COMBAWA_DB_FETCH_SCP_CONFIG_NAME+x} ]; then 213 | # Determine if we have a username to use to login. 214 | if [ -z ${COMBAWA_DB_FETCH_SCP_USER} ]; then 215 | # SCP login via servername and current user. 216 | scp -P $COMBAWA_DB_FETCH_SCP_PORT $COMBAWA_DB_FETCH_SCP_SERVER:$COMBAWA_DB_FETCH_PATH_SOURCE $COMBAWA_ROOT/$COMBAWA_DB_DUMP_PATH 217 | else 218 | # Also determine if we have a password to use. 219 | if [ -z ${COMBAWA_DB_FETCH_SCP_PASSWORD} ]; then 220 | # SCP login via username. 221 | scp -P $COMBAWA_DB_FETCH_SCP_PORT $COMBAWA_DB_FETCH_SCP_USER@$COMBAWA_DB_FETCH_SCP_SERVER:$COMBAWA_DB_FETCH_PATH_SOURCE $COMBAWA_ROOT/$COMBAWA_DB_DUMP_PATH 222 | else 223 | # SCP login via username and password. 224 | scp -P $COMBAWA_DB_FETCH_SCP_PORT $COMBAWA_DB_FETCH_SCP_USER:$COMBAWA_DB_FETCH_SCP_PASSWORD@$COMBAWA_DB_FETCH_SCP_SERVER:$COMBAWA_DB_FETCH_PATH_SOURCE $COMBAWA_ROOT/$COMBAWA_DB_DUMP_PATH 225 | fi 226 | fi 227 | else 228 | scp $COMBAWA_DB_FETCH_SCP_CONFIG_NAME:$COMBAWA_DB_FETCH_PATH_SOURCE $COMBAWA_ROOT/$COMBAWA_DB_DUMP_PATH 229 | fi 230 | message_confirm "Reference dump update... OK!" 231 | ;; 232 | esac 233 | if [[ $? != 0 ]]; then 234 | message_fatal "Error when retrieving the reference dump file. Are your paths valid? Access opened?" 235 | fi 236 | } 237 | 238 | # Load dump function. 239 | load_dump() 240 | { 241 | if [ -f "$COMBAWA_ROOT/$COMBAWA_DB_DUMP_PATH" ]; then 242 | message_step "Let's import the reference dump:" 243 | echo -e "" 244 | $DRUSH sql-drop -y; 245 | message_confirm "DB drop... OK!" 246 | echo -e "" 247 | 248 | message_step "Importing the new DB..." 249 | message_action "Decompressing file..." 250 | _DUMP_PATH_GZ="$COMBAWA_ROOT/$COMBAWA_DB_DUMP_PATH" 251 | _DUMP_PATH="${_DUMP_PATH_GZ%.*}" 252 | gzip -dkf $_DUMP_PATH_GZ 253 | message_confirm "Done!" 254 | message_action "DB Import in progress..." 255 | if hash pv 2>/dev/null; then 256 | pv --progress -tea "$_DUMP_PATH" | $($DRUSH sql:connect) 257 | else 258 | cat "$_DUMP_PATH" | $($DRUSH sql:connect) 259 | fi 260 | message_confirm "Done!" 261 | message_action "Removing temporary sql file..." 262 | rm -f $_DUMP_PATH 263 | message_confirm "Done!" 264 | message_confirm "Reimporting the reference dump... OK!" 265 | echo -e "" 266 | else 267 | message_fatal "Database reference dump $COMBAWA_ROOT/$COMBAWA_DB_DUMP_PATH not found." 268 | fi 269 | } 270 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Logo Combawa](logo_combawa.png) 2 | 3 | * **[Combawa](#combawa)** 4 | * **[Installation](#installation)** 5 | * **[Usage](#usage)** 6 | * **[Drush commands](#drush-commands)** 7 | * **[Advanced usages](#advanced)** 8 | * **[Troubleshooting](#troubleshooting)** 9 | 10 | # Combawa 11 | Combawa is a bash script that helps you **build** your Drupal projects. 12 | 13 | It's compatible with Drupal 10 and is meant to be used by developers and CI applications. (See other branches for lower Drupal versions). 14 | 15 | You are encouraged to use Combawa as a daily companion to reinstall/update your local installation or CI environment. 16 | 17 | Because Combawa is very cool, you can use a Drush command to setup the required environment variables. See below for details. 18 | 19 | ## Installation 20 | 21 | - `composer require happyculture/combawa` 22 | - Use `drush combawa:initialize-build-scripts` to initiate the project build files from a template (actions run when the Drupal site is (re)installed or updated). 23 | - If you are in `install` mode using an install profile different than `minimal`, you should update the `scripts/combawa/install.sh` file to replace the profile name in the `$DRUSH site-install` command. 24 | - Use `drush combawa:generate-environment` to setup your environment (configuring your site variables). 25 | 26 | If you don't want to use the generated `settings.local.php` file, you will have to add in your `settings.php` (or any other settings file) the following snippet: 27 | 28 | ``` 29 | $_ENV['COMBAWA_DB_HOSTNAME'], 34 | 'port' => $_ENV['COMBAWA_DB_PORT'], 35 | 'database' => $_ENV['COMBAWA_DB_DATABASE'], 36 | 'password' => $_ENV['COMBAWA_DB_PASSWORD'], 37 | 'username' => $_ENV['COMBAWA_DB_USER'], 38 | 'prefix' => '', 39 | 'driver' => 'mysql', 40 | 'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql', 41 | ]; 42 | ``` 43 | 44 | ### Recommended 45 | 46 | #### Combawa wrapper as a global command 47 | 48 | If you are lazy as we are (you should), it is possible to use a global command `combawa` instead of `vendor/bin/combawa` in your projects. 49 | In order to do that, you need to install the Combawa wrapper (https://github.com/Happyculture/combawa-wrapper). It works similarly as the Drush wrapper. 50 | 51 | `composer global require happyculture/combawa-wrapper` 52 | 53 | ## Usage 54 | 55 | ### Conception & philosophy 56 | 57 | **(Re)Build your project with Combawa** 58 | 59 | Combawa is the script that will ease your project reinstallation when you want to test your freshly baked feature. 60 | 61 | It's designed with an CI context in mind for the local station. 62 | When you will start using Combawa, you will initiate a build scenario (we suggest the production scenario) to set default values to the internal options (should my script backup the site before building? Retrieve a fresh reference dump from production...) 63 | You can build the project from an installation profile, from existing config or from a reference dump directly retrieved from your production server. 64 | 65 | ### How to use Combawa 66 | 67 | Running Combawa to (re)build your project mostly resumes to running this command: `./vendor/bin/combawa`. 68 | 69 | When you are building a site, the following steps are followed: 70 | * Preflight checkup (system requirement + setup verifications) 71 | * Predeployment actions (fetch a remote DB, save a backup of the current install, drop the DB) 72 | * Build actions (install or update mode (differences below)) 73 | * Postdeployment (rebuild caches, generate a connection link, setup env specific modules, reindex...) 74 | 75 | Combawa takes the default settings when you run it with no extra arguments. 76 | You can override them on the fly (see arguments section below). 77 | 78 | #### Environment specific 79 | 80 | Combawa is designed to build your site following an environment specific set of rules. 81 | 82 | Said otherwise, you have a solution to compile CSS files in prod and not in dev, drop the DB to each rebuild (but not on prod), enable/disable specific modules in development (Devel, Views UI...) or production (no DBLog or UI...) 83 | 84 | The valid environments (option `-e`) are the following: 85 | * Development (dev) 86 | * Testing (testing) 87 | * Production (prod) 88 | 89 | When you are targeting a specific environment, you can edit `predeploy_actions.sh` or `postdeploy_actions.sh`. Each file is composed of a switch/case per environment but you can specialize those files per project. 90 | 91 | #### Build mode 92 | 93 | When you build your projects, you are in two different scenarios: 94 | - Install mode: You are initiating the project and build from an installation profile. 95 | - Update mode: You are advanced in your project life cycle and may have it in production. You want to rebuild from the configuration that you exported or a reference SQL dump. 96 | 97 | Each mode (option `-m`) is using a different build file since you don't run the same commands whether you are installing or updating. 98 | 99 | Combawa ships with template files for each mode, you can update them when you need to adjust them to your constraints. 100 | 101 | #### Combawa options 102 | 103 | You can use more arguments such as : `./vendor/bin/combawa.sh --env dev --mode install --backup 1 --fetch-db-dump` 104 | 105 | Here is the list of available arguments: 106 | * `--yes`, `-y`: Do not ask for confirmation before running the build. Useful for CI integration. 107 | * `--env`, `-e`: Environment to build. Allowed values are: dev, testing, prod 108 | * `--mode`, `-m`: Build mode. Allowed values are: install, update 109 | * `--backup`, `-b`: Generates a backup before building the project. Allowed values are: 0: do not generate a backup, 1: generate a backup. 110 | * `--reimport`, `-r`: Reimports the site from the reference dump (DB drop and replace). Allowed values are: 0: do not reimport the reference database, 1: reimport the reference database. 111 | * `--fetch-db-dump`, `-f`: Fetches a fresh DB dump from the production site. Used when the reference dump should be updated. 112 | * `--only-predeploy`: Only execute the predeploy script. 113 | * `--only-postdeploy`: Only execute the postdeploy script. 114 | * `--no-predeploy`: Do not execute the predeploy script. 115 | * `--no-postdeploy`: Do not execute the postdeploy script. 116 | * `--stop-after-reimport`: Flag to stop building after reimporting the DB. Useful to version config from prod. 117 | 118 | ## Environment files 119 | 120 | You can generate or manually create environment files to inject Combawa required variables and extra environment infos. 121 | The `.env` file(s) are expected to be located at the repository root level. 122 | 123 | We leverage Symfony Dotenv component so the `.env` file may be overriden by `.env.local`, `.env.$APP_ENV.local` or `.env.$APP_ENV` if defined. 124 | 125 | ## Drush commands 126 | 127 | ### Environment generator 128 | 129 | Command `drush combawa:generate-environment`: 130 | 131 | Used once per environment, this command creates two files: 132 | - `.env`: Stores local values for the build script. 133 | - `settings.local.php`: Used to inject the local values into Drupal. 134 | 135 | By default the command is interactive. If you want to use it through CLI, you can pass all arguments with there value. If a required value is missing, the command will prompt to collect the missing values. 136 | Eg: 137 | 138 | ``` 139 | ./vendor/bin/drush combawa:generate-environment \ 140 | --build-mode update \ 141 | --environment dev \ 142 | --environment-url https://mydevsite.coop \ 143 | --backup-db \ 144 | --dump-fetch-update \ 145 | --dump-retrieval-tool scp \ 146 | --scp-connection-username=username \ 147 | --scp-connection-servername myserver.org \ 148 | --scp-connection-port 22 \ 149 | --fetch-source-path /home/dumps-source/my_dump.sql.gz \ 150 | --db-host localhost \ 151 | --db-port 3306 \ 152 | --db-name test_db \ 153 | --db-user db_username \ 154 | --no-interaction 155 | ``` 156 | 157 | See the integrated help using `drush combawa:generate-environment --help` for arguments values. 158 | 159 | Please note that the command will NOT generate the settings.local.php if it already exists to avoid data loss. If you any valid reason, you need to override the existing file (eg: in a Continous Integration context), you can do so by passing the extra argument `--force-settings-generation`. 160 | 161 | Please also be aware that the `.env` file content will be different if you are in `install` or `update` mode. It means that you should retrigger the command when you switch from `install` to `update` to fill the extra required information (to fetch the DB dumps mostly). 162 | 163 | ### Script templates generator 164 | 165 | Command `drush combawa:initialize-build-scripts`: 166 | 167 | This command generates the build scripts used by Combawa to install/update the project from templates. Once those files are generated, you can customize them to your needs and probably want to version them. 168 | 169 | ## Advanced usages 170 | 171 | ### Pulling changes from production 172 | 173 | If some of your users are able to change the configuration on the production environment, you might want to ensure your repository is up-to-date before shipping new features. Those settings being stored in the database, you need to retrieve them on your local environment then export the configuration to your repository. 174 | 175 | Run combawa to only replace your local database with your production dump as follow: \ 176 | `combawa -f 1 -r 1 --stop-after-reimport` 177 | 178 | You are now in the state where the database has been imported. Run `drush config:export -y` to export in code and version the config delta from prod. 179 | 180 | ## Troubleshooting 181 | 182 | This version is obviously bug free! If you identify an issue, please open an issue. 183 | -------------------------------------------------------------------------------- /bin/combawa.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Catch all errors. 4 | set -euo pipefail 5 | 6 | # Working directory. 7 | # Helper to let you run the install script from anywhere. 8 | currentscriptpath () { 9 | SOURCE="${BASH_SOURCE[0]}" 10 | # resolve $SOURCE until the file is no longer a symlink 11 | while [ -h "$SOURCE" ]; do 12 | 13 | DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" 14 | SOURCE="$(readlink "$SOURCE")" 15 | # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located 16 | [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" 17 | done 18 | DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" 19 | echo $DIR 20 | } 21 | 22 | # Binary variables. 23 | SCRIPTS_PATH=$(currentscriptpath) 24 | UTILS_DIR="$SCRIPTS_PATH/../utils" 25 | TEMPLATES_DIR="$SCRIPTS_PATH/../templates" 26 | 27 | # App variables. 28 | COMBAWA_ROOT="$SCRIPTS_PATH/../../../.." 29 | WEBROOT="$COMBAWA_ROOT/web" 30 | CONFIG_DIR="$COMBAWA_ROOT/config" 31 | COMBAWA_SCRIPTS_DIR="$COMBAWA_ROOT/scripts/combawa" 32 | COMBAWA_DB_DUMP_PATH=dumps/reference_dump.sql.gz 33 | 34 | # State variables. 35 | _COMBAWA_BYPASS_CONFIRMATION=0 36 | _COMBAWA_ONLY_PREDEPLOY=0 37 | _COMBAWA_ONLY_POSTDEPLOY=0 38 | _COMBAWA_NO_PREDEPLOY=0 39 | _COMBAWA_NO_POSTDEPLOY=0 40 | _COMBAWA_REIMPORT_FORCE_EXIT=0 41 | 42 | # Compute steps to run. By default, every steps are run. 43 | _COMBAWA_RUN_PREDEPLOY=1 44 | _COMBAWA_RUN_MAIN_BUILD_STEP=1 45 | _COMBAWA_RUN_POSTDEPLOY=1 46 | 47 | source $UTILS_DIR/colors.sh 48 | source $UTILS_DIR/functions.sh 49 | 50 | echo -e "" 51 | echo -e "${LIGHT_PURPLE}" 52 | echo -e " . " 53 | echo -e " /\ /l " 54 | echo -e " ((.Y(! " 55 | echo -e " \ |/ COMBAWA, PLEASED TO SERVE!" 56 | echo -e " / 6~6, Let's build this project." 57 | echo -e " \ _ +-. " 58 | echo -e " \`-=--^-' " 59 | echo -e " \ \ " 60 | echo -e " _/ \\" 61 | echo -e " ( . Y" 62 | echo -e " /\"\ \`--^--v--." 63 | echo -e " / _ \`--\"T~\/~\/" 64 | echo -e " / \" ~\. !" 65 | echo -e " _ Y Y./'" 66 | echo -e " Y^| | |~~7" 67 | echo -e " | l | / ./'" 68 | echo -e " | \`L | Y .^/~T" 69 | echo -e " | l ! | |/| | -Row" 70 | echo -e " | .\`\/' | Y | !" 71 | echo -e " l \"~ j l j_L______" 72 | echo -e " \,____{ __\"~ __ ,\_,\_" 73 | echo -e "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~${NC}" 74 | echo -e "" 75 | 76 | # Set default variables. 77 | COMBAWA_BUILD_MODE="update" 78 | COMBAWA_BUILD_ENV="prod" 79 | COMBAWA_DB_BACKUP_FLAG=1 80 | COMBAWA_REIMPORT_REF_DUMP_FLAG=0 81 | COMBAWA_DB_FETCH_FLAG=0 82 | 83 | # Load local overrides. 84 | # Load build mode override from Composer.json file if defined. 85 | _BUILD_MODE_OVERRIDE=`php -r "echo json_decode(file_get_contents('./composer.json'))->extra->combawa->build_mode;"` 86 | if [[ ! -z _BUILD_MODE_OVERRIDE ]]; then 87 | COMBAWA_BUILD_MODE=$_BUILD_MODE_OVERRIDE 88 | fi 89 | if [ -f "$COMBAWA_ROOT/.env" ]; then 90 | source $COMBAWA_ROOT/.env 91 | fi 92 | if [ -f "$COMBAWA_ROOT/.env.local" ]; then 93 | source $COMBAWA_ROOT/.env.local 94 | fi 95 | 96 | # Make drush a variable to use the one shipped with the repository. 97 | DRUSH="$COMBAWA_ROOT/vendor/bin/drush -y" 98 | 99 | # Set the arguments value. 100 | set +u 101 | while [[ $1 ]] 102 | do 103 | key="$1" 104 | if [ -z "$key" ]; then 105 | shift 106 | else 107 | case $key in 108 | -h|--help) 109 | usage 110 | shift 111 | ;; 112 | -y | --yes) 113 | _COMBAWA_BYPASS_CONFIRMATION=1 114 | ;; 115 | -e | --env) 116 | case $2 in 117 | dev|testing|prod) 118 | SOURCE_BUILD_ENV=$COMBAWA_BUILD_ENV 119 | COMBAWA_BUILD_ENV="$2" 120 | 121 | message_action "Environment overriden:" 122 | message_override "$SOURCE_BUILD_ENV" "$COMBAWA_BUILD_ENV" 123 | ;; 124 | *) 125 | notify_fatal "Unknown environment: $2. Please check your name." 126 | esac 127 | shift 128 | ;; 129 | -m|--mode) 130 | SOURCE_BUILD_MODE=$COMBAWA_BUILD_MODE 131 | COMBAWA_BUILD_MODE="$2" 132 | 133 | if [[ $2 != "install" ]] && [[ $2 != "update" ]]; then 134 | notify_fatal "Invalid build mode." "Only install or update is valid" 135 | fi; 136 | 137 | message_action "Build mode overriden:" 138 | message_override "$SOURCE_BUILD_MODE" "$COMBAWA_BUILD_MODE" 139 | shift 140 | ;; 141 | -b|--backup) 142 | SOURCE_DB_BACKUP_FLAG=$COMBAWA_DB_BACKUP_FLAG 143 | COMBAWA_DB_BACKUP_FLAG="$2" 144 | 145 | if [[ $2 != "0" ]] && [[ $2 != "1" ]]; then 146 | notify_fatal "Invalid backup flag." "Only 0 or 1 is valid." 147 | fi 148 | 149 | message_action "Backup base overriden:" 150 | message_override "$SOURCE_DB_BACKUP_FLAG" "$COMBAWA_DB_BACKUP_FLAG" 151 | shift 152 | ;; 153 | -r|--reimport) 154 | SOURCE_REIMPORT=$COMBAWA_REIMPORT_REF_DUMP_FLAG 155 | COMBAWA_REIMPORT_REF_DUMP_FLAG="$2" 156 | 157 | if [[ $2 != "0" ]] && [[ $2 != "1" ]]; then 158 | notify_fatal "Invalid reimport flag." "Only 0 or 1 is valid." 159 | fi 160 | 161 | message_action "Reimport reference dump flag overriden:" 162 | message_override "$SOURCE_REIMPORT" "$COMBAWA_REIMPORT_REF_DUMP_FLAG" 163 | shift 164 | ;; 165 | -f|--fetch-db-dump) 166 | SOURCE_DB_FETCH_FLAG=$COMBAWA_DB_FETCH_FLAG 167 | COMBAWA_DB_FETCH_FLAG="$2" 168 | 169 | if [[ $2 != "0" ]] && [[ $2 != "1" ]]; then 170 | notify_error "Invalid fetch-db-dump flag." "Only 0 or 1 is valid." 171 | fi 172 | 173 | message_action "Fetch DB dump from prod overriden:" 174 | message_override "$SOURCE_DB_FETCH_FLAG" "$COMBAWA_DB_FETCH_FLAG" 175 | echo -e "" 176 | 177 | if [[ $COMBAWA_DB_FETCH_FLAG == "1" ]]; then 178 | if [[ ! -z "$COMBAWA_DB_FETCH_CNX_STRING" ]]; then 179 | message_step "Testing connection with remote SSH server from which the dump will be retrieved:" 180 | ssh -q $COMBAWA_DB_FETCH_CNX_STRING echo > /dev/null 181 | if [[ $? != 0 ]]; then 182 | notify_fatal "Impossible to connect to the production server." "Check your SSH config file. Should you connect through a VPN?" 183 | else 184 | message_confirm "SSH connection OK." 185 | fi 186 | fi 187 | fi 188 | shift 189 | ;; 190 | --only-predeploy) 191 | _COMBAWA_ONLY_PREDEPLOY=1 192 | message_action "Only predeploy actions will be run." 193 | ;; 194 | --only-postdeploy) 195 | _COMBAWA_ONLY_POSTDEPLOY=1 196 | message_action "Only postdeploy actions will be run." 197 | ;; 198 | --no-predeploy) 199 | _COMBAWA_RUN_PREDEPLOY=0 200 | message_action "Predeploy actions will not be run." 201 | ;; 202 | --no-postdeploy) 203 | _COMBAWA_RUN_POSTDEPLOY=0 204 | message_action "Postdeploy actions will not be run." 205 | ;; 206 | --stop-after-reimport) 207 | _COMBAWA_REIMPORT_FORCE_EXIT=1 208 | message_action "Postdeploy actions will not be run." 209 | ;; 210 | --) # End of all options 211 | shift 212 | ;; 213 | *) # No more options 214 | notify_error "Argument $key does not exist." 215 | ;; 216 | esac 217 | shift 218 | fi 219 | done 220 | set -u 221 | 222 | # Compute steps to run. By default, every steps are run. 223 | if [[ $_COMBAWA_ONLY_PREDEPLOY == 1 ]]; then 224 | _COMBAWA_RUN_MAIN_BUILD_STEP=0 225 | _COMBAWA_RUN_POSTDEPLOY=0 226 | fi 227 | if [[ $_COMBAWA_ONLY_POSTDEPLOY == 1 ]]; then 228 | _COMBAWA_RUN_PREDEPLOY=0 229 | _COMBAWA_RUN_MAIN_BUILD_STEP=0 230 | fi 231 | 232 | source $UTILS_DIR/prerequisites.sh 233 | 234 | # Show the build config. 235 | USAGE=$(cat <<-END 236 | Environment built:\t${LIGHT_CYAN}$COMBAWA_BUILD_ENV${NC} 237 | Build mode:\t${LIGHT_CYAN}$COMBAWA_BUILD_MODE${NC} 238 | Generate a backup:\t${LIGHT_CYAN}$COMBAWA_DB_BACKUP_FLAG${NC} 239 | Environment URI:\t${LIGHT_CYAN}${DRUSH_OPTIONS_URI:-undefined}${NC} 240 | Retrieve DB from prod:\t${LIGHT_CYAN}$COMBAWA_DB_FETCH_FLAG${NC} 241 | Reimport site:\t${LIGHT_CYAN}$COMBAWA_REIMPORT_REF_DUMP_FLAG${NC} 242 | END 243 | ) 244 | 245 | message_step "Build options summary:" 246 | echo -e "" 247 | if hash column 2>/dev/null; then 248 | echo -e "$USAGE" | column -s $'\t' -t 249 | else 250 | echo -e "$USAGE" 251 | fi 252 | 253 | if [[ $_COMBAWA_BYPASS_CONFIRMATION == 0 ]]; then 254 | ################################# 255 | section_separator 256 | ################################# 257 | 258 | message_step "Confirmation:" 259 | read -p "Are you sure that you want to run this build [yN]? " -n 1 -r 260 | if [[ ! $REPLY =~ ^[Yy]$ ]]; then 261 | [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1 262 | fi 263 | fi 264 | 265 | ################################# 266 | section_separator 267 | ################################# 268 | if [[ $COMBAWA_DB_BACKUP_FLAG == "1" ]]; then 269 | backup_db 270 | fi 271 | 272 | # Download the reference dump file. 273 | if [[ $COMBAWA_DB_FETCH_FLAG == "1" ]]; then 274 | download_dump 275 | fi 276 | 277 | # Reimport the SQL reference dump. 278 | if [[ $COMBAWA_REIMPORT_REF_DUMP_FLAG == "1" ]]; then 279 | load_dump 280 | fi 281 | 282 | # Exit if the force exit flag has been raised. It's interesting to check if the prod dump doesn't have config to export. 283 | if [[ $_COMBAWA_REIMPORT_FORCE_EXIT == "1" ]]; then 284 | if [[ $COMBAWA_REIMPORT_REF_DUMP_FLAG == "1" ]]; then 285 | message_action "Exiting now that the reference dump has been reimported and the force exit flag has been raised!" 286 | else 287 | message_action "Build stopped as requested but no dump has been reimported. Didn't you forget to add the --reimport flag? ;-)." 288 | fi 289 | exit 290 | fi 291 | 292 | if [[ $_COMBAWA_RUN_PREDEPLOY == "1" ]]; then 293 | message_step "Running predeploy actions." 294 | # Return error codes if they happen. 295 | set -xe 296 | # Run the potential actions to do pre deployment. 297 | source $COMBAWA_SCRIPTS_DIR/predeploy_actions.sh 298 | set +xe 299 | 300 | message_confirm "Predeploy actions... Done!" 301 | 302 | if [[ $_COMBAWA_ONLY_PREDEPLOY == "1" ]]; then 303 | message_action "Exiting now that predeploy actions have been run!" 304 | fi 305 | fi 306 | 307 | if [[ $_COMBAWA_RUN_MAIN_BUILD_STEP == "1" ]]; then 308 | # Run the build content. 309 | if [[ $COMBAWA_BUILD_MODE == "install" ]]; then 310 | message_step "Running install." 311 | # Return error codes if they happen. 312 | set -xe 313 | source $COMBAWA_SCRIPTS_DIR/install.sh 314 | set +xe 315 | if [[ $? != 0 ]]; then 316 | message_error "The install.sh generated an error. Check the logs." 317 | exit $? 318 | fi 319 | message_confirm "Install... OK!" 320 | elif [[ $COMBAWA_BUILD_MODE == "update" ]]; then 321 | message_step "Running update." 322 | # Return error codes if they happen. 323 | set -xe 324 | source $COMBAWA_SCRIPTS_DIR/update.sh 325 | set +xe 326 | if [[ $? != 0 ]]; then 327 | message_error "The update.sh generated an error. Check the logs." 328 | exit $? 329 | fi 330 | message_confirm "Update... OK!" 331 | fi 332 | fi 333 | 334 | if [[ $_COMBAWA_RUN_POSTDEPLOY == 1 ]]; then 335 | message_step "Running postdeploy actions." 336 | # Run the potential actions to do post deployment. 337 | # Return error codes if they happen. 338 | set -xe 339 | source $COMBAWA_SCRIPTS_DIR/postdeploy_actions.sh 340 | set +xe 341 | 342 | message_confirm "Postdeploy actions... Done!" 343 | 344 | if [[ $_COMBAWA_ONLY_POSTDEPLOY == "1" ]]; then 345 | message_action "Exiting now that postdeploy actions have been run!" 346 | fi 347 | fi 348 | 349 | # Send a notification to inform that the build is done. 350 | notify "The build is completed." 351 | -------------------------------------------------------------------------------- /src/Drush/Commands/GenerateEnvironmentDrushCommands.php: -------------------------------------------------------------------------------- 1 | install, update)', 24 | suggestedValues: ['install', 'update'])] 25 | #[CLI\Option( 26 | name: 'environment', 27 | description: 'The build environment. (Accepted: dev, testing, prod)', 28 | suggestedValues: ['dev', 'testing', 'prod'])] 29 | #[CLI\Option( 30 | name: 'webroot', 31 | description: 'Override the discovered Drupal webroot location.')] 32 | #[CLI\Option( 33 | name: 'environment-url', 34 | description: 'The URL on which the project is reachable for this environment.')] 35 | #[CLI\Option( 36 | name: 'backup-db', 37 | description: 'Backup the database on each build. (Accepted: boolean)', 38 | suggestedValues: [TRUE, FALSE])] 39 | #[CLI\Option( 40 | name: 'dump-fetch-update', 41 | description: 'Always update the reference dump before building. (Accepted: boolean)', 42 | suggestedValues: [TRUE, FALSE])] 43 | #[CLI\Option( 44 | name: 'dump-retrieval-tool', 45 | description: 'Tool used to retrieve the reference dump. (Accepted: cp, scp)', 46 | suggestedValues: ['cp', 'scp'])] 47 | #[CLI\Option( 48 | name: 'scp-config-name', 49 | description: 'The remote server name where to find the dump.')] 50 | #[CLI\Option( 51 | name: 'scp-connection-username', 52 | description: 'SCP connection username.')] 53 | #[CLI\Option( 54 | name: 'scp-connection-servername', 55 | description: 'SCP connection server name.')] 56 | #[CLI\Option( 57 | name: 'scp-connection-port', 58 | description: 'SCP connection port.')] 59 | #[CLI\Option( 60 | name: 'fetch-source-path', 61 | description: 'Source path to copy the reference dump from. Must include the dump file name and use a .gz extension.')] 62 | #[CLI\Option( 63 | name: 'reimport', 64 | description: 'Reimport the website from the reference dump on each build? (Accepted: boolean)', 65 | suggestedValues: [TRUE, FALSE])] 66 | #[CLI\Option( 67 | name: 'db-host', 68 | description: 'The host of the database.')] 69 | #[CLI\Option( 70 | name: 'db-port', 71 | description: 'The port of the database.')] 72 | #[CLI\Option( 73 | name: 'db-name', 74 | description: 'The name of the database.')] 75 | #[CLI\Option( 76 | name: 'db-user', 77 | description: 'The user name of the database.')] 78 | #[CLI\Option( 79 | name: 'db-password', 80 | description: 'The password of the database.')] 81 | #[CLI\Option( 82 | name: 'write-db-settings', 83 | description: 'Write DB settings code in settings.local.php? (Accepted: boolean)', 84 | suggestedValues: [TRUE, FALSE])] 85 | #[CLI\Option( 86 | name: 'dry-run', 87 | description: 'Output the generated code but not save it to file system.')] 88 | #[CLI\Usage(name: 'drush combawa:generate-environment', description: 'Run with wizard')] 89 | public function generateEnvironment(array $options = [ 90 | 'build-mode' => self::REQ, 91 | 'environment' => self::REQ, 92 | 'webroot' => self::REQ, 93 | 'environment-url' => self::REQ, 94 | 'backup-db' => self::OPT, 95 | 'dump-fetch-update' => self::OPT, 96 | 'dump-retrieval-tool' => self::REQ, 97 | 'scp-config-name' => self::REQ, 98 | 'scp-connection-username' => self::REQ, 99 | 'scp-connection-servername' => self::REQ, 100 | 'scp-connection-port' => self::REQ, 101 | 'fetch-source-path' => self::REQ, 102 | 'reimport' => self::OPT, 103 | 'db-host' => self::REQ, 104 | 'db-port' => self::REQ, 105 | 'db-name' => self::REQ, 106 | 'db-user' => self::REQ, 107 | 'db-password' => self::REQ, 108 | 'write-db-settings' => self::OPT, 109 | 'dry-run' => FALSE, 110 | ]): int { 111 | return $this->generate($options); 112 | } 113 | 114 | /** 115 | * {@inheritdoc} 116 | */ 117 | protected function extractOptions(array $options): array { 118 | $vars = [ 119 | 'build_mode' => $options['build-mode'], 120 | 'environment' => $options['environment'], 121 | 'webroot' => $options['webroot'], 122 | 'environment_url' => $options['environment-url'], 123 | 'backup_db' => $options['backup-db'], 124 | 'dump_fetch_update' => $options['dump-fetch-update'], 125 | 'dump_fetch_method' => $options['dump-retrieval-tool'], 126 | 'dump_fetch_scp_config_name' => $options['scp-config-name'], 127 | 'dump_fetch_scp_user' => $options['scp-connection-username'], 128 | 'dump_fetch_scp_host' => $options['scp-connection-servername'], 129 | 'dump_fetch_scp_port' => $options['scp-connection-port'], 130 | 'dump_fetch_source_path' => $options['fetch-source-path'], 131 | 'reimport' => $options['reimport'], 132 | 'db_host' => $options['db-host'], 133 | 'db_port' => $options['db-port'], 134 | 'db_name' => $options['db-name'], 135 | 'db_user' => $options['db-user'], 136 | 'db_password' => $options['db-password'], 137 | 'write_db_settings' => $options['write-db-settings'], 138 | ]; 139 | return array_filter($vars, fn ($value) => !\is_null($value)); 140 | } 141 | 142 | /** 143 | * {@inheritdoc} 144 | */ 145 | protected function interview(array &$vars): void { 146 | if (!isset($vars['build_mode'])) { 147 | $composerData = Json::decode(file_get_contents($this->drupalFinder()->getComposerRoot() . '/composer.json')); 148 | $defaultValue = $composerData['extra']['combawa']['build_mode'] ?? 'install'; 149 | $vars['build_mode'] = $this->io()->select( 150 | 'What is your current build mode?', 151 | ['install', 'update'], 152 | $defaultValue, 153 | ); 154 | } 155 | 156 | if (!isset($vars['environment'])) { 157 | $defaultValue = $_ENV['COMBAWA_BUILD_ENV'] ?? 'prod'; 158 | $vars['environment'] = $this->io()->select( 159 | 'Which kind of environment is it?', 160 | ['dev', 'testing', 'prod'], 161 | $defaultValue, 162 | ); 163 | } 164 | 165 | if (!isset($vars['webroot'])) { 166 | $detectedDefaultValue = ltrim(substr($this->drupalFinder()->getDrupalRoot(), strlen($this->drupalFinder()->getComposerRoot())), DIRECTORY_SEPARATOR); 167 | $defaultValue = $_ENV['COMBAWA_WEBROOT_PATH'] ?? $detectedDefaultValue; 168 | $vars['webroot'] = $this->io()->ask( 169 | 'In which directory is your Drupal webroot located?', 170 | $defaultValue, 171 | ); 172 | } 173 | 174 | if (!isset($vars['environment_url'])) { 175 | $defaultValue = $_ENV['DRUSH_OPTIONS_URI'] ?? 'https://' . $vars['environment'] . '.happyculture.coop'; 176 | $vars['environment_url'] = $this->io()->ask( 177 | 'What is the URL of the project for the ' . $vars['environment'] . ' environment?', 178 | $defaultValue, 179 | required: TRUE, 180 | validate: $this->validateUrl(...), 181 | ); 182 | } 183 | 184 | // Database credentials. 185 | foreach (['host', 'port', 'name', 'user', 'password'] as $key) { 186 | $varName = 'db_' . $key; 187 | $defaultValueKey = match($key) { 188 | 'host' => 'COMBAWA_DB_HOSTNAME', 189 | 'port' => 'COMBAWA_DB_PORT', 190 | 'name' => 'COMBAWA_DB_DATABASE', 191 | 'user' => 'COMBAWA_DB_USER', 192 | 'password' => 'COMBAWA_DB_PASSWORD', 193 | }; 194 | $defaultValueValue = match($key) { 195 | 'host' => '127.0.0.1', 196 | 'port' => '3306', 197 | 'name' => 'drupal', 198 | 'user' => 'root', 199 | 'password' => '', 200 | }; 201 | $question = match($key) { 202 | 'host' => 'What is the hostname of your database server?', 203 | 'port' => 'What is the port of your database server?', 204 | 'name' => 'What is the name of your database?', 205 | 'user' => 'What is the name of your database user?', 206 | 'password' => 'What is the password of your database user?', 207 | }; 208 | $required = match($key) { 209 | 'host' => TRUE, 210 | 'port' => TRUE, 211 | 'name' => TRUE, 212 | 'user' => TRUE, 213 | 'password' => FALSE, 214 | }; 215 | $validator = match($key) { 216 | 'host' => $this->validateDomainOrIpFormat(...), 217 | 'port' => NULL, 218 | 'name' => NULL, 219 | 'user' => NULL, 220 | 'password' => NULL, 221 | }; 222 | if (!isset($vars[$varName])) { 223 | $defaultValue = $_ENV[$defaultValueKey] ?? $defaultValueValue; 224 | $vars[$varName] = $this->io()->ask( 225 | $question, 226 | $defaultValue, 227 | required: $required, 228 | validate: $validator, 229 | ); 230 | } 231 | } 232 | 233 | if (!isset($vars['backup_db'])) { 234 | $defaultValue = $_ENV['COMBAWA_DB_BACKUP_FLAG'] ?? TRUE; 235 | $vars['backup_db'] = $this->io()->confirm( 236 | 'Do you want the database to be backed up before each build?', 237 | $defaultValue, 238 | ); 239 | } 240 | 241 | if ($vars['environment'] !== 'prod' && $vars['build_mode'] === 'update') { 242 | if (!isset($vars['dump_fetch_update'])) { 243 | $defaultValue = $_ENV['COMBAWA_DB_FETCH_FLAG'] ?? TRUE; 244 | $vars['dump_fetch_update'] = $this->io()->confirm( 245 | 'Do you want to update the reference dump before each build?', 246 | $defaultValue, 247 | ); 248 | } 249 | 250 | if (!isset($vars['dump_fetch_method'])) { 251 | $defaultValue = $_ENV['COMBAWA_DB_RETRIEVAL_TOOL'] ?? 'scp'; 252 | $vars['dump_fetch_method'] = $this->io()->select( 253 | 'When updated, what is the tool used to retrieve the reference dump?', 254 | ['cp', 'scp'], 255 | $defaultValue, 256 | ); 257 | } 258 | 259 | if ($vars['dump_fetch_method'] === 'scp') { 260 | if (!isset($vars['dump_use_ssh_config_name'])) { 261 | $defaultValue = FALSE; 262 | $vars['dump_use_ssh_config_name'] = $this->io()->confirm( 263 | '[SCP] Do you have an SSH config name from your ~/.ssh/config to use to retrieve the dump?', 264 | $defaultValue, 265 | ); 266 | } 267 | 268 | if ($vars['dump_use_ssh_config_name'] === TRUE) { 269 | if (!isset($vars['dump_fetch_scp_config_name'])) { 270 | $defaultValue = $_ENV['COMBAWA_DB_FETCH_SCP_CONFIG_NAME'] ?? 'my_remote'; 271 | $vars['dump_fetch_scp_config_name'] = $this->io()->ask( 272 | '[SCP] What is the name of you config entry in your ~/.ssh/config file?', 273 | $defaultValue, 274 | required: TRUE, 275 | ); 276 | } 277 | } 278 | else { 279 | // SCP credentials. 280 | foreach (['host', 'port', 'user'] as $key) { 281 | $varName = 'dump_fetch_scp_' . $key; 282 | $defaultValueKey = match($key) { 283 | 'host' => 'COMBAWA_DB_FETCH_SCP_SERVER', 284 | 'port' => 'COMBAWA_DB_FETCH_SCP_SERVER', 285 | 'user' => 'COMBAWA_DB_FETCH_SCP_USER', 286 | }; 287 | $defaultValueValue = match($key) { 288 | 'host' => '', 289 | 'port' => 22, 290 | 'user' => '', 291 | }; 292 | $question = match($key) { 293 | 'host' => '[SCP] What is the connection server name or IP?', 294 | 'port' => '[SCP] What is the connection server port?', 295 | 'user' => '[SCP] What is the connection user name?', 296 | }; 297 | $validator = match($key) { 298 | 'host' => $this->validateDomainOrIpFormat(...), 299 | 'port' => NULL, 300 | 'user' => NULL, 301 | }; 302 | if (!isset($vars[$varName])) { 303 | $defaultValue = $_ENV[$defaultValueKey] ?? $defaultValueValue; 304 | $vars[$varName] = $this->io()->ask( 305 | $question, 306 | $defaultValue, 307 | required: TRUE, 308 | validate: $validator, 309 | ); 310 | } 311 | } 312 | } 313 | } 314 | 315 | if (!isset($vars['dump_fetch_source_path'])) { 316 | $defaultValue = $_ENV['COMBAWA_DB_FETCH_PATH_SOURCE'] ?? '/home/dumps-source/my_dump.sql.gz'; 317 | $vars['dump_fetch_source_path'] = $this->io()->ask( 318 | 'What is the source path of the reference dump to copy (only Gzipped file supported at the moment)?', 319 | $defaultValue, 320 | required: TRUE, 321 | validate: $this->validateDumpExtension(...), 322 | ); 323 | } 324 | 325 | if (!isset($vars['reimport'])) { 326 | $defaultValue = $_ENV['COMBAWA_REIMPORT_REF_DUMP_FLAG'] ?? FALSE; 327 | $vars['reimport'] = $this->io()->confirm( 328 | 'Do you want the site to be reimported from the reference dump on each build?', 329 | $defaultValue, 330 | ); 331 | } 332 | } 333 | 334 | if (!isset($vars['write_db_settings'])) { 335 | $defaultValue = FALSE; 336 | $vars['write_db_settings'] = $this->io()->confirm( 337 | 'Do you want Combawa to create a settings.local.php file that will ease your DB connection? You can do it yourself later on, the code to copy/paste will be prompted in the next step.', 338 | $defaultValue, 339 | ); 340 | } 341 | } 342 | 343 | /** 344 | * {@inheritdoc} 345 | */ 346 | protected function validateVars(array $vars): void { 347 | $errors = []; 348 | if (isset($vars['build_mode'])) { 349 | $errors[] = $this->validateBuildMode($vars['build_mode']); 350 | } 351 | 352 | if (isset($vars['environment']) && !in_array($vars['environment'], ['dev', 'testing', 'prod'])) { 353 | $errors[] = 'Environment must be either dev, testing or prod.'; 354 | } 355 | 356 | if (isset($vars['environment_url'])) { 357 | $errors[] = $this->validateUrl($vars['environment_url']); 358 | } 359 | 360 | if (isset($vars['db_host'])) { 361 | $errors[] = $this->validateDomainOrIpFormat($vars['db_host']); 362 | } 363 | 364 | if (isset($vars['dump_fetch_method']) && !in_array($vars['dump_fetch_method'], ['cp', 'scp'])) { 365 | $errors[] = 'Fetch method must be either cp or scp.'; 366 | } 367 | 368 | if (isset($vars['dump_fetch_scp_host'])) { 369 | $errors[] = $this->validateDomainOrIpFormat($vars['dump_fetch_scp_host']); 370 | } 371 | 372 | if (isset($vars['dump_fetch_source_path'])) { 373 | $errors[] = $this->validateDumpExtension($vars['dump_fetch_source_path']); 374 | } 375 | 376 | $errors = array_filter($errors); 377 | if (!empty($errors)) { 378 | throw new \InvalidArgumentException(implode("\n", $errors)); 379 | } 380 | } 381 | 382 | /** 383 | * {@inheritdoc} 384 | */ 385 | protected function getVarsSummary(array $vars): array { 386 | $summary = [ 387 | 'Build mode' => $vars['build_mode'], 388 | 'Environment' => $vars['environment'], 389 | 'App root' => $vars['webroot'], 390 | 'DB Host' => $vars['db_host'], 391 | 'DB Port' => $vars['db_port'], 392 | 'DB name' => $vars['db_user'], 393 | 'DB Username' => $vars['db_name'], 394 | 'DB password' => empty($vars['db_password']) ? 'No password' : 'Your secret password', 395 | 'Site URL' => $vars['environment_url'], 396 | 'Backup DB before build' => $vars['backup_db'] ? 'Yes' : 'No', 397 | 'Write code to connect to DB' => $vars['write_db_settings'] ? 'Yes' : 'No', 398 | ]; 399 | if ($vars['environment'] !== 'prod' && $vars['build_mode'] === 'update') { 400 | if ($vars['dump_fetch_method'] === 'scp') { 401 | if (!empty($vars['dump_fetch_scp_config_name'])) { 402 | // Expected: scp . 403 | $fetch_command = 'scp ' . $vars['dump_fetch_scp_config_name']; 404 | } 405 | else { 406 | // Expected: scp [-P PORT] [:PASS]@. 407 | $fetch_command = 'scp'; 408 | $fetch_command .= !empty($vars['dump_fetch_scp_port']) ? ' -P ' . $vars['dump_fetch_scp_port'] : ''; 409 | $fetch_command .= ' ' . $vars['dump_fetch_scp_user']; 410 | $fetch_command .= '@' . $vars['dump_fetch_scp_host']; 411 | } 412 | // Expected: scp : . 413 | $fetch_command .= ':' . $vars['dump_fetch_source_path']; 414 | $fetch_command .= ' ' . $this->drupalFinder()->getComposerRoot() . '/' . static::FETCH_DEST_PATH; 415 | } 416 | elseif ($vars['dump_fetch_method'] === 'cp') { 417 | // Expected: cp . 418 | $fetch_command = 'cp'; 419 | $fetch_command .= ' ' . $vars['dump_fetch_source_path']; 420 | $fetch_command .= ' ' . $this->drupalFinder()->getComposerRoot() . '/' . static::FETCH_DEST_PATH; 421 | } 422 | $summary['Fetch command'] = $fetch_command; 423 | $summary['Always reimport DB before building?'] = $vars['reimport'] ? 'Yes' : 'No'; 424 | $summary['Always update ref DB before building?'] = $vars['dump_fetch_update'] ? 'Yes' : 'No'; 425 | } 426 | return $summary; 427 | } 428 | 429 | /** 430 | * {@inheritdoc} 431 | */ 432 | protected function postGenerate(array $vars): void { 433 | if (empty($vars['write_db_settings'])) { 434 | $content = $this->renderer->render( 435 | 'settings.local.php.twig', 436 | $vars 437 | ); 438 | $this->io()->newLine(1); 439 | $this->io()->title('Additional informations:'); 440 | $this->io()->note('You can use the following code into your settings.local.php to use variables defined in the .env file.'); 441 | $this->io()->text($content); 442 | } 443 | 444 | // Uncomment settings.local.php inclusion in the settings.php file. 445 | $filename = 'sites/default/settings.php'; 446 | $filepath = $this->drupalFinder()->getDrupalRoot() . '/' . $filename; 447 | if ($this->fileSystem->exists($filepath)) { 448 | // Only uncomment the include line as we are sure to have a 449 | // settings.local.php file. 450 | $data = file_get_contents($filepath); 451 | $data = str_replace("# include \$app_root . '/' . \$site_path . '/settings.local.php';", " include \$app_root . '/' . \$site_path . '/settings.local.php';", $data); 452 | 453 | $this->fileSystem->chmod(dirname($filepath), 0775); 454 | $this->fileSystem->chmod($filepath, 0664); 455 | $this->fileSystem->dumpFile($filepath, $data); 456 | 457 | $this->io()->note('Your settings.php file has been updated to include settings.local.php if it exists.'); 458 | } 459 | } 460 | 461 | /** 462 | * {@inheritdoc} 463 | */ 464 | protected function collectAssets(AssetCollection $assets, array $vars): void { 465 | $assets->addFile( 466 | '../.env', 467 | 'env-' . $vars['build_mode'] . '.twig', 468 | ); 469 | 470 | if (!empty($vars['write_db_settings'])) { 471 | $assets->addFile( 472 | 'sites/default/settings.local.php', 473 | 'settings.local.php.twig', 474 | ); 475 | } 476 | } 477 | 478 | /** 479 | * Validates an url. 480 | * 481 | * @param string $url 482 | * The url to validate. 483 | * 484 | * @return ?string 485 | * The error if there is one. 486 | */ 487 | public function validateUrl($url): ?string { 488 | $parts = parse_url($url); 489 | if ($parts === FALSE) { 490 | return sprintf( 491 | '"%s" is a malformed url.', 492 | $url 493 | ); 494 | } 495 | elseif (empty($parts['scheme']) || empty($parts['host'])) { 496 | return sprintf( 497 | 'Please specify a full URL with scheme and host instead of "%s".', 498 | $url 499 | ); 500 | } 501 | return NULL; 502 | } 503 | 504 | /** 505 | * Validates a domain name format. 506 | * 507 | * @param string $connection_str 508 | * The domain or IP address to validate. 509 | * 510 | * @return ?string 511 | * The error if there is one. 512 | */ 513 | public function validateDomainOrIpFormat($connection_str): ?string { 514 | if ( 515 | // Format an IP address. 516 | !preg_match('/^[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}$/', $connection_str) && 517 | // Or a domain. 518 | !preg_match('/^[a-zA-Z0-9](?:[-\w]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-\w]*[a-zA-Z0-9])?)*$/', $connection_str) 519 | ) { 520 | return sprintf('The connection string "%s" does not look like a valid domain or IP address.', $connection_str); 521 | } 522 | return NULL; 523 | } 524 | 525 | /** 526 | * Helper to validate that the dump filetype is supported. 527 | * 528 | * @param string $path 529 | * The file path to validate. 530 | * 531 | * @return ?string 532 | * The error if there is one. 533 | */ 534 | public function validateDumpExtension(string $path): ?string { 535 | $supported = ['gz']; 536 | if (!in_array(pathinfo($path, PATHINFO_EXTENSION), $supported)) { 537 | return sprintf( 538 | 'The file extension "%s" is not supported (only Gzipped files).', 539 | $path 540 | ); 541 | } 542 | return NULL; 543 | } 544 | 545 | } 546 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------