2 Commits

10 changed files with 256 additions and 244 deletions

3
.gitignore vendored
View File

@@ -1,4 +1 @@
.rbenv-version
.bundle
/bin
Gemfile.lock

View File

@@ -1,3 +1,9 @@
source "https://rubygems.org"
gemspec
group :test do
gem 'rake'
gem 'rspec'
gem 'capistrano'
gem 'capistrano-ext'
gem 'capistrano-spec', :git => 'git://github.com/mydrive/capistrano-spec.git'
end

45
Gemfile.lock Normal file
View File

@@ -0,0 +1,45 @@
GIT
remote: git://github.com/mydrive/capistrano-spec.git
revision: dcc0908dc00872272b1d495bcce70e82240fa8f7
specs:
capistrano-spec (0.1.0)
GEM
remote: https://rubygems.org/
specs:
capistrano (2.11.2)
highline
net-scp (>= 1.0.0)
net-sftp (>= 2.0.0)
net-ssh (>= 2.0.14)
net-ssh-gateway (>= 1.1.0)
capistrano-ext (1.2.1)
capistrano (>= 1.0.0)
diff-lcs (1.1.3)
highline (1.6.11)
net-scp (1.0.4)
net-ssh (>= 1.99.1)
net-sftp (2.0.5)
net-ssh (>= 2.0.9)
net-ssh (2.3.0)
net-ssh-gateway (1.1.0)
net-ssh (>= 1.99.1)
rake (0.9.2.2)
rspec (2.8.0)
rspec-core (~> 2.8.0)
rspec-expectations (~> 2.8.0)
rspec-mocks (~> 2.8.0)
rspec-core (2.8.0)
rspec-expectations (2.8.0)
diff-lcs (~> 1.1.2)
rspec-mocks (2.8.0)
PLATFORMS
ruby
DEPENDENCIES
capistrano
capistrano-ext
capistrano-spec!
rake
rspec

183
README.md
View File

@@ -1,20 +1,13 @@
[![Gem Version](https://badge.fury.io/rb/capistrano-deploytags.svg)](http://badge.fury.io/rb/capistrano-deploytags)
## Capistrano Deployment Tags
This plugin for Capistrano 3 will add a timestamped Git tag
at each deployment, automatically. It requires :branch and :stage to be set,
but as Capistrano 3 is multistage by default (unlike Cap 2) :stage should
already be set, but you can override the variable if you want to change the
name of the tag.
### Requires Capistrano 3
As of version 1.0.0, this plugin requires Cap 3. If you need a Capistrano
2 compatible version, then use `gem 'capistrano-deploytags', '~> 0.9.2'`
### What It Does
Capistrano Deployment Tags
==========================
This plugin to Capistrano will add a timestamped Git tag
at each deployment, automatically. It is intended to be used with
the multistage recipe and will tag each release by environment.
You can, however, use it without multistage simply by setting :branch
and :stage in your recipe.
What It Does
------------
Simply: it makes it so you can track your deployments from Git.
If I were to issue the command:
@@ -23,124 +16,42 @@ If I were to issue the command:
This would result in one new git tag with the environment and
timestamp:
`production-2012.04.02-203155-utc`
`production-2012.04.02-203155`
These tags can be used for any number of useful things including
generating statistics about deployments per day/week/year, tracking
code size over a period of time, detecting Rails migrations, and
probably a thousand other things I haven't thought of.
### Usage
Usage
-----
capistrano-deploytags is available on
[rubygems.org](https://rubygems.org/gems/capistrano-deploytags).
In keeping with the pattern used by Capistrano itself and other plugins, add it
to the `development` group of your Gemfile with `require: false`:
You can install it from there with:
```ruby
# Gemfile
group :deployment do
gem 'capistrano-deploytags', '~> 1.0.0', require: false
end
```
`gem install capistrano-deploytags`
Then require `capistrano/deploytags` in your Capfile
If you use Bundler, be sure to add the gem to your Gemfile.
In your Capistrano `config/deploy.rb` you should add:
```
# Capfile
require 'capistrano/deploytags'
```
`require 'capistrano-deploytags'`
This will create two tasks, one that runs before the `deploy` task, and one
that runs after the `cleanup` task.
This will create two tasks, one that runs before deployment and one
that runs after.
*NOTE:* You will be creating and pushing tags from the version of the code in the
current checkout. This plugin needs to be run from a clean checkout of your
codebase. You should be deploying from a clean checkout anyway, so in most
cases this is not a restriction on how you already do things. The plugin will
check if your code is clean and complain if it is not.
*ALSO:* The plugin will do a pull to make sure you have the code on your local
system that will actually be deployed before checking the tree for changes.
Know this ahead of time as this may affect how you deal with your deployment
branches.
### Setting the Remote
By default, Capistrano Deploytags will use the remote names `origin`. If you
use a different remote name, then you may change the `:git_remote` setting
from your `deploy.rb` or the stage.
### Working on Your Deployment Scripts
Because you must have a clean tree to deploy, working on your deployment
scripts themselves can be a bit frustrating unless you know how to make it
work. The easiest way around this problem is to simply commit your changes
before you deploy. You do not have to push them. The plugin will then
happily carry on deploying without complaint.
Alternatively, you could disable the plugin temporarily with one of the
methods described below.
### Disabling Tagging for a Stage
Sometimes you do not want to enable deployment tagging for a particular
stage. In that event, you can simply disable tagging by setting `no_deploytags`
like so:
```ruby
set :no_deploytags, true
```
You can also set this from the command line at any time with an environment
variable `cap stage deploy NO_DEPLOYTAGS=true`.
*NOTE:* this will disable the use of the plugin's functionality entirely for
that stage. The tasks will run, but will do nothing. This means that tasks that
are hooked to the Capistrano Deploytags tasks will also still run, but they may
find their expectations are not met with regards to the cleanliness of the git
tree.
### Customizing the Tag Format
You may override the time format in `deploy.rb` or your stage:
```ruby
set :deploytag_time_format, "%Y.%m.%d-%H%M%S-utc"
```
### Customizing the Tag Commit Message
By default, Capistrano Deploytags will create a tag with a message that indicates
the local user name on the box where the deployment is done, and the hash of the
tagged commit. If you prefer to have a more detailed commit message you may override
the `:deploytag_commit_message` setting from your `deploy.rb`, e.g.
`set :deploytag_commit_message, 'This is my commit message for the deployed tag'`
### Viewing Deployment History
It's trivial to view the deployment history for a repo. From a checkout
of the repo, type `git tag -l -n1`. The output looks something like:
```
dev-2013.07.22-105130 baz deployed a4d522d9d to dev
dev-2013.07.22-113207 karl deployed 4c43f8464 to dev
dev-2013.07.22-114437 gavin deployed 776e15414 to dev
dev-2013.07.22-115103 karl deployed 619ff5724 to dev
dev-2013.07.22-144121 josh deployed cf1ed1a02 to dev
```
A little use of `grep` and you can easily get the history for a
particular (e.g. `git tag -l -n1 | grep dev`).
It should be noted that the names used when tags are created are the
local user name on the box where the deployment is done.
### Helpful Git Config
NOTE: You will be creating and pushing tags from the version of the
code in the current checkout. This plugin needs to be run from a
clean checkout of your codebase. You should be deploying from a
clean checkout anyway, so in most cases this is not a restriction
on how you already do things. The plugin will check if your code
is clean and complain if it is not.
Helpful Git Config
------------------
You might find it useful to add this to your ~/.gitconfig in order
to get a nice history view of the commits and tags.
```ini
```
[alias]
lol = log --pretty=oneline --abbrev-commit --graph --decorate
```
@@ -148,43 +59,13 @@ to get a nice history view of the commits and tags.
You can then view the list by typing `git lol` from the checked out
code path.
### Deploying a Previous Commit
Because you have to actually be on the head of the branch you are
deploying in order for tagging to work properly, deploying a previous
commit doesn't work as you might expect.
One simple solution is to configure your `config.rb` to accept an ENV var
override. Then if you need to deploy a previous commit you can check out that
commit (SHA or branch), and supply the var on the command line. e.g. with this
in your `config.rb`:
```ruby
set :branch, ENV["REVISION"] || ENV["BRANCH_NAME"] || "master"
```
you can deploy a previous commit with
```shell
git checkout <previous-commit>
cap <stage> deploy REVISION=<previous-commit>
```
### Running from Jenkins
Because Jenkins will check out the code with the current revision
number you will be in a detached state. This causes the plugin to be
unhappy about the git tree. The solution is to add `-S branch=$GIT_COMMIT`
to the cap deploy line called from your Jenkins build. This will cause
the diffs and comparisons done by the deploytags gem to be correct.
### Credits
Credits
-------
This software was written by [Karl Matthias](https://github.com/relistan)
with help from [Gavin Heavyside](https://github.com/gavinheavyside) and the
support of [MyDrive Solutions Limited](http://mydrivesolutions.com).
### License
License
-------
This plugin is released under the BSD two clause license which is
available in both the Ruby Gem and the source repository.

View File

@@ -1,18 +1,16 @@
Gem::Specification.new do |s|
s.name = 'capistrano-deploytags'
s.version = '1.0.0'
s.date = '2014-06-14'
s.summary = 'Add dated, environment-specific tags to your git repo at each deployment.'
s.version = '0.7.0'
s.date = '2012-10-02'
s.summary = "Add dated, environment-specific tags to your git repo at each deployment."
s.description = <<-EOS
Capistrano Deploytags is a simple plugin to Capistrano 3 that works with your deployment framework to track your code releases. All you have to do is require capistrano-deploytags/capistrano and each deployment will add a new tag for that deployment, pointing to the latest commit. This lets you easily see which code is deployed on each environment, and allows you to figure out which code was running in an environment at any time in the past.
Capistrano Deploytags is a simple plugin to Capistrano that works with your deployment framework to track your code releases. All you have to do is require capistrano-deploytags and each deployment will add a new tag for that deployment, pointing to the latest commit. This lets you easily see which code is deployed on each environment, and allows you to figure out which code was running in an environment at any time in the past.
EOS
s.authors = ['Karl Matthias', 'Gavin Heavyside']
s.email = ['relistan@gmail.com', 'gavin.heavyside@mydrivesolutions.com']
s.files = `git ls-files lib`.split(/\n/) + %w{ README.md LICENSE }
s.authors = ["Karl Matthias"]
s.email = 'relistan@gmail.com'
s.files = Dir.glob("lib/**/*") + %w{ README.md LICENSE }
s.homepage = 'http://github.com/mydrive/capistrano-deploytags'
s.add_dependency 'capistrano', '>= 3.2.0'
# s.add_development_dependency 'capistrano-spec'
s.add_development_dependency 'rake'
s.add_development_dependency 'rspec', '~> 3.0.0'
s.add_dependency 'capistrano'
s.add_dependency 'capistrano-ext'
s.require_path = 'lib'
end

View File

@@ -0,0 +1,3 @@
Dir[File.join(File.dirname(__FILE__), 'capistrano', '*')].each do |file|
require file
end

View File

@@ -0,0 +1,89 @@
module Capistrano
module DeployTags
def uncommitted_git_changes?
# Is the working directory clean?
!( `git status --porcelain`.strip.empty? )
end
def git_tag_for(stage)
"#{stage}-#{Time.now.strftime("%Y.%m.%d-%H%M%S")}"
end
def safe_run(*args)
raise "#{args.join(" ")} failed!" unless system(*args)
end
def validate_git_vars
unless exists?(:branch) && exists?(:stage)
logger.log Capistrano::Logger::IMPORTANT, "Capistrano Deploytags requires that :branch and :stage be defined."
raise 'define :branch and :stage'
end
end
def git_tag?(tag)
!`git tag -l #{tag}`.strip.empty?
end
def has_remote?
!`git remote`.strip.empty?
end
def self.load_into(configuration)
configuration.load do
before "deploy", 'git:prepare_tree'
before "deploy:migrations", 'git:prepare_tree'
after "deploy", 'git:tagdeploy'
after "deploy:migrations", 'git:tagdeploy'
desc 'prepare git tree so we can tag on successful deployment'
namespace :git do
task :prepare_tree, :except => { :no_release => true } do
cdt.validate_git_vars
if cdt.uncommitted_git_changes?
logger.log Capistrano::Logger::IMPORTANT, "Sorry, you have uncommitted changes. Please commit or stash them."
end
cdt.safe_run "git", "fetch"
ref = fetch(:revision, branch)
if exists?(:revision)
logger.log Capistrano::Logger::IMPORTANT, "Preparing to deploy '#{ref}' to '#{stage}'"
else
logger.log Capistrano::Logger::IMPORTANT, "Preparing to deploy HEAD from '#{ref}' to '#{stage}'"
end
cdt.safe_run "git", "checkout", ref
# It doesn't make sense to pull a SHA, only a branch.
if cdt.has_remote? && ! exists?(:revision)
cdt.safe_run "git", "pull", "origin", ref
end
end
desc 'add git tags for each successful deployment'
task :tagdeploy, :except => { :no_release => true } do
cdt.validate_git_vars
current_sha = `git rev-parse #{branch} HEAD`.strip[0..8]
logger.log Capistrano::Logger::INFO, "Tagging #{current_sha} for deployment"
tag_user = (ENV['USER'] || ENV['USERNAME']).strip
cdt.safe_run "git", "tag", "-a", cdt.git_tag_for(stage), "-m", "#{tag_user} deployed #{current_sha} to #{stage}"
cdt.safe_run "git", "push", "--tags" if cdt.has_remote?
end
end
end
end
end
end
Capistrano.plugin :cdt, Capistrano::DeployTags
if Capistrano::Configuration.instance
Capistrano::DeployTags.load_into(Capistrano::Configuration.instance(:must_exist))
end

View File

@@ -1,26 +0,0 @@
# Ensure deploy tasks are loaded before we run
require 'capistrano/deploy'
# Load extra tasks into the deploy namespace
load File.expand_path("../tasks/deploytags.rake", __FILE__)
module CapistranoDeploytags
class Helper
def self.git_tag_for(stage)
"#{stage}-#{formatted_time}"
end
def self.formatted_time
Time.new.utc.strftime(fetch(:deploytag_time_format, "%Y.%m.%d-%H%M%S-utc"))
end
def self.commit_message(current_sha, stage)
if fetch(:deploytag_commit_message, false)
deploytag_commit_message
else
tag_user = (ENV['USER'] || ENV['USERNAME'] || 'deployer').strip
"#{tag_user} deployed #{current_sha} to #{stage}"
end
end
end
end

View File

@@ -1,49 +0,0 @@
namespace :deploy do
desc 'prepare git tree so we can tag on successful deployment'
before :deploy, :prepare_tree do
run_locally do
if ENV['NO_DEPLOYTAGS'] || fetch(:no_deploytags, false)
info "[deploytags] Skipping deploytags"
else
branch = fetch(:branch, false)
stage = fetch(:stage, false)
unless branch && stage
error 'capistrano-deploytags requires that :branch and :stage be defined'
raise 'define :branch and :stage'
end
strategy.git "fetch #{fetch(:git_remote, 'origin')}"
diff_output = capture :git, "diff #{branch} --shortstat"
unless diff_output.empty?
error "Whoa there, partner. Dirty trees can't deploy. Git yerself clean first"
raise 'Dirty git tree'
end
strategy.git "checkout #{branch}"
info "Pulling from #{branch}"
strategy.git "pull #{fetch(:git_remote, 'origin')} #{branch}"
end
end
end
desc 'add git tags for each successful deployment'
after :cleanup, :tagdeploy do
run_locally do
if ENV['NO_DEPLOYTAGS'] || fetch(:no_deploytags, false)
info "[deploytags] Skipping deploytags"
else
tag_name = CapistranoDeploytags::Helper.git_tag_for(fetch(:stage))
latest_revision = fetch(:current_revision)
commit_message = CapistranoDeploytags::Helper.commit_message(latest_revision, fetch(:stage))
strategy.git "tag -a #{tag_name} -m \"#{commit_message}\" #{latest_revision}"
strategy.git "push #{fetch(:git_remote, 'origin')} #{tag_name}"
info "[cap-deploy-tagger] Tagged #{latest_revision} with #{tag_name}"
end
end
end
end

View File

@@ -1,5 +1,73 @@
require 'rspec'
require 'capistrano'
require 'capistrano-spec'
require 'fileutils'
mypath = File.expand_path(File.dirname(__FILE__))
require File.expand_path(File.join(mypath, '..', 'lib', 'capistrano', 'deploy_tags'))
describe 'Capistrano::Deploytags' do
pending "capistrano-spec doesn't support Capistrano 3"
describe Capistrano::DeployTags do
let(:configuration) { Capistrano::Configuration.new }
let(:tmpdir) { "/tmp/#{$$}" }
let(:mypath) { mypath }
before :each do
Capistrano::DeployTags.load_into(configuration)
end
def with_clean_repo(&block)
FileUtils.rm_rf tmpdir
FileUtils.mkdir tmpdir
FileUtils.chdir tmpdir
raise unless system("/usr/bin/tar xzf #{File.join(mypath, 'fixtures', 'git-fixture.tar.gz')}")
FileUtils.chdir "#{tmpdir}/git-fixture"
yield
FileUtils.rm_rf tmpdir
end
context "prepare_tree" do
it "raises an error when not in a git tree" do
FileUtils.chdir '/tmp'
configuration.set(:branch, 'master')
configuration.set(:stage, 'test')
expect { configuration.find_and_execute_task('git:prepare_tree') }.to raise_error('git checkout master failed!')
end
context "with a clean git tree" do
it "raises an error if :stage or :branch are undefined" do
with_clean_repo do
expect { configuration.find_and_execute_task('git:prepare_tree') }.to raise_error('define :branch and :stage')
end
end
it "does not raise an error when run from a clean tree" do
with_clean_repo do
configuration.set(:branch, 'master')
configuration.set(:stage, 'test')
expect { configuration.find_and_execute_task('git:prepare_tree') }.to_not raise_error
end
end
end
end
context "tagdeploy" do
before :each do
configuration.set(:branch, 'master')
configuration.set(:stage, 'test')
end
it "does not raise an error when run from a clean tree" do
with_clean_repo do
expect { configuration.find_and_execute_task('git:tagdeploy') }.to_not raise_error
end
end
it "adds appropriate git tags" do
with_clean_repo do
configuration.find_and_execute_task('git:tagdeploy')
tags = `git tag -l`.split(/\n/)
tags.should have(1).items
tags.first.should =~ /^test-\d{4}\.\d{2}\.\d{2}/
end
end
end
end