deployer/recipe/deploy/update_code.php

82 lines
2.2 KiB
PHP
Raw Normal View History

2016-11-19 15:13:32 +07:00
<?php
namespace Deployer;
2020-04-25 23:00:08 +03:00
use Deployer\Exception\RunException;
/**
2020-10-02 00:11:13 +02:00
* Determines which branch to deploy. Can be overridden with cli option `--branch`.
* If not specified, will get current git HEAD branch as default branch to deploy.
*/
set('branch', function () {
if (input()->hasOption('branch') && !empty(input()->getOption('branch'))) {
return input()->getOption('branch');
}
return null;
});
2020-10-02 00:11:13 +02:00
/**
* Update code at {{release_path}} on host.
*/
2016-11-19 15:13:32 +07:00
desc('Update code');
task('deploy:update_code', function () {
2019-08-12 20:59:59 +03:00
$repository = get('repository');
2016-11-19 15:13:32 +07:00
$branch = get('branch');
$git = get('bin/git');
$at = 'HEAD';
2016-11-19 15:13:32 +07:00
if (!empty($branch)) {
2021-03-15 01:35:06 +03:00
$at = $branch;
2016-11-19 15:13:32 +07:00
}
2021-03-15 01:35:06 +03:00
// If option `tag` is set.
2016-11-19 15:13:32 +07:00
if (input()->hasOption('tag')) {
$tag = input()->getOption('tag');
if (!empty($tag)) {
2021-03-15 01:35:06 +03:00
$at = $tag;
2016-11-19 15:13:32 +07:00
}
}
2021-03-15 01:35:06 +03:00
// If option `tag` is not set and option `revision` is set.
if (empty($tag)) {
2016-11-19 15:13:32 +07:00
$revision = input()->getOption('revision');
if (!empty($revision)) {
2021-03-15 01:35:06 +03:00
$at = $revision;
2016-11-19 15:13:32 +07:00
}
}
2017-11-27 11:18:22 +01:00
2021-03-15 01:35:06 +03:00
// Populate known hosts.
2020-04-25 23:00:08 +03:00
preg_match('/.*(@|\/\/)([^\/:]+).*/', $repository, $match);
if (isset($match[2])) {
$repositoryHostname = $match[2];
try {
run("ssh-keygen -F $repositoryHostname");
2021-03-15 01:35:06 +03:00
} catch (RunException $e) {
2020-04-25 23:00:08 +03:00
run("ssh-keyscan -H $repositoryHostname >> ~/.ssh/known_hosts");
}
}
2021-03-15 01:35:06 +03:00
$bare = parse('{{deploy_path}}/.dep/repo');
start:
// Clone the repository to a bare repo.
2021-03-15 01:35:06 +03:00
run("[ -d $bare ] || mkdir -p $bare");
run("[ -f $bare/HEAD ] || $git clone --mirror $repository $bare 2>&1");
2016-11-19 15:13:32 +07:00
2021-03-15 01:35:06 +03:00
cd($bare);
// If remote url changed, drop `.git/repo` and reinstall.
if (run("$git config --get remote.origin.url") !== $repository) {
cd('{{deploy_path}}');
run("rm -rf $bare");
goto start;
}
2021-03-15 01:35:06 +03:00
// Copy to release_path.
run("$git remote update 2>&1");
run("$git archive $at | tar -x -f - -C {{release_path}} 2>&1");
// Save revision in releases log.
$rev = run("$git rev-list $at -1");
2021-03-15 21:53:46 +01:00
run("sed -ibak 's/revision/$rev/' {{deploy_path}}/.dep/releases");
2016-11-19 15:13:32 +07:00
});