SlideShare a Scribd company logo
1 of 38
Put Git to work
increase the quality of your Rails project, and let git do the boring
work for you
Happy Star
Wars Day!
Rodrigo
Urubatan
 rodrigo@urubatan.com.br
 http://twitter.com/urubatan
 http://github.com/urubatan
 http://linkedin.com/in/urubatan
 http://sobrecodigo.com
5 ways git can help deploy your rails
application
1 – check every commit follow company standards
2 – identify where each commit come from
3 – make sure at least the changed files tests run before pushing code
4 – start CI build after pushing the code
5 – 2 different approaches to git push your deploy after the ci build succeded
There is a lot of boring manual work to
do before each deploy!
Check code against
standards
Pretty format commit
messages
Run tests for the files
you changed to speed
up development
Start CI builds Start deployments Compile assets
Run migrations when
needed
Install npm modules
Reload application
servers
This is
my goal!
Git can help!
Commit Check
standards
Format
message
Push
code
Run tests
(locally)
Start CI
process
Pull
code
Bundle
install
Yarn
install
Start
deploy
Npm
install
Bundle
install
Db
migrate
Restart
service(s)
Putting it to
work!
Codding
standards
Git pre-commit hook
Formatting
commit
message
Git prepare-commit-msg hook
Running
tests
Git pre-push hook
Firing CI
build
Git post-receive hook
Automatic
deployment
Git post-receive hook
Or Git post-merge hook
I had one (more than one) evil coworker
that didn’t follow any company standards
This Photo by Unknown Author is licensed under CC BY
How to fight the
Evil Coworker
who does not
follow good
practices?
This Photo by Unknown Author is licensed under CC BY-SA
rubocode + .git/hooks/pre-commit
#!/bin/sh
echo "Checking commit"
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# If you want to allow non-ASCII filenames set this variable to true.
rubocop -R `git diff --cached --name-only $against`
if [ "$?" != "0" ]; then
cat <<EOF
pretty Failed!! message!!
EOF
exit 1
fi
I found a commit and did not know
where it came from
This Photo by Unknown Author is licensed under CC BY
Formatting commit messages
#!/bin/bash
BRANCH_NAME=$(git symbolic-ref --short HEAD)
BRANCH_NAME="${BRANCH_NAME##*/}"
BRANCH_IN_COMMIT=$(grep -c "[$BRANCH_NAME]" $1)
if [ -n "$BRANCH_NAME" ] && ! [[ $BRANCH_IN_COMMIT -ge 1 ]]; then
sed -i.bak -e "1s/^/[$BRANCH_NAME] /" $1
fi
Life is too short
to test before
sharing my code!
Run your tests before pushing the code!
#!/usr/bin/env ruby
branch_name=`git symbolic-ref -q HEAD`
branch_name = branch_name.gsub('refs/heads/', '').strip
changed_files = `git diff --name-only #{ARGV[0]}/#{branch_name}`.split("n").map(&:strip).select{|n| n
=~ /.rb$/}
#run the file specific test
test_files = changed_files.map do |name|
if name =~ /^app/
name.gsub('app/', 'test/').gsub(/.rb$/, '_test.rb')
elsif name =~ /^test/
name
else
nil
end
end.reject(&:nil?).uniq
#abort if there is a test missing
if !test_files.reject{|n| File.exists?(n)}.empty?
puts %Q{
Aborting push because there are missing test files: #{test_files.reject{|n| File.exists?(n)}}
}
exit 1
end
#if there are config files changes, run all tests
if !changed_files.select{|n| n =~ /^config/}.empty?
test_files = ''
end
system('git stash')
result = system("rails test #{test_files.join(' ')}")
system('git stash apply')
unless result
puts %Q{
Aborting push due to failed tests
}
exit 1
end
Trick’em into
using your
perfect hooks
This Photo by Unknown Author is licensed under CC BY-NC-ND
And the evil trick!
 npm i shared-git-hooks --save-dev or yarn add shared-git-hooks
 Add your git hooks (with or without extension) to the hooks
directory in your project
Too much automation?
This Photo by Unknown Author is licensed under CC BY-NC-SA
Found out you
need another gem
or npm module
when you decide
to do some work
in the airplane?
This Photo by Unknown Author is licensed under CC BY-NC-SA
.git/hooks/post-merge
#!/bin/bash
bundle install
yarn install
Continuous Integration
This Photo by Unknown Author is licensed under CC BY-SA
Continuous
integration
pooling?
Firing CI
Build
.git/hooks/post-receive with a
curl to your CI server
Github integrated CI servers
(github version of the above)
Jenkins
curl -X POST http://username:user_api_token@your-
jenkins.com/job/JobName/build?token=build_trigger_api_token
TravisCI
body='{
"request": {
"branch":"master"
}}'
curl -s -X POST 
-H "Content-Type: application/json" 
-H "Accept: application/json" 
-H "Travis-API-Version: 3" 
-H "Authorization: token xxxxxx" 
-d "$body" 
https://api.travis-ci.com/repo/mycompany%2Fmyrepo/requests
TeamCity
curl -X POST -u apiuser:apipassword -d '<build><buildType
id="SpringPetclinic_Build"/></build>'
http://localhost:8111/httpAuth/app/rest/buildQueue --header "Content-Type:
application/xml" -H "Accept: application/json"
Bamboo
export BAMBOO_USER=foo
export BAMBOO_PASS=bar
export PROJECT_NAME=TST
export PLAN_NAME=DMY
export STAGE_NAME=JOB1
curl --user $BAMBOO_USER:$BAMBOO_PASS -X POST -d
"$STAGE_NAME&ExecuteAllStages"
http://mybamboohost:8085/rest/api/latest/queue/$PROJECT_NAME-
$PLAN_NAME
Automatic
Deployment
– Heroku
Recipe
1 server
1 bare repository
1 simple script
1 deployment
repository/path
My goal with this approach is to do this
 git remote add production user@server:myapp.git
 Git push production master
This Just Deployed my code to production!
Git Bare Repository
 mkdir myapp.git
 cd myapp.git && git init --bare
 vi hooks/post-receive
myapp.git/hooks/post-receive
#!/bin/bash
while read oldrev newrev ref
do
branch_received=`echo $ref | cut -d/ -f3`
echo "Deploying branch $branch_received"
/bin/bash --login -- <<__EOF__
cd /home/urubatan/projects/deployedapp
git fetch
git checkout -f $branch_received
git pull
yarn install
bundle install
rails db:migrate
rails assets:precompile
touch tmp/restart.txt
__EOF__
done
Automatic Deployment – git pull style
(post-merge hook)
#!/bin/bash
bundle install
yarn install
rails db:migrate
rails assets:precompile
touch tmp/restart.txt
Do you feel you need to track all that
deploys?
This Photo by Unknown Author is licensed under CC BY-SA
git-deploy
 https://github.com/git-deploy/git-deploy
 git deploy start (you can git deploy abort if needed)
 Merge all feature branches that need deployment
 git deploy sync
 Push that to all your servers (maybe using our Heroku strategy?)
 git deploy finish
 Now you can use the git-deploy script to list all deployments, or go back to
any one of them!
Questions?
Rodrigo Urubatan
 I help ruby developers to use the
best tools for each job so they can
solve hard problems, with less bugs
and have more free time.
 rodrigo@urubatan.com.br
 http://twitter.com/urubatan
 http://bit.ly/weekly_rails_tips
 http://github.com/urubatan
 http://linkedin.com/in/urubatan
 http://sobrecodigo.com
Whats next? A git ebook!
http://bit.ly/weekly_rails_tips

More Related Content

What's hot

How to develop Jenkins plugin using to ruby and Jenkins.rb
How to develop Jenkins plugin using to ruby and Jenkins.rbHow to develop Jenkins plugin using to ruby and Jenkins.rb
How to develop Jenkins plugin using to ruby and Jenkins.rb
Hiroshi SHIBATA
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
som_nangia
 
Plack perl superglue for web frameworks and servers
Plack perl superglue for web frameworks and serversPlack perl superglue for web frameworks and servers
Plack perl superglue for web frameworks and servers
Tatsuhiko Miyagawa
 

What's hot (20)

Distributed Developer Workflows using Git
Distributed Developer Workflows using GitDistributed Developer Workflows using Git
Distributed Developer Workflows using Git
 
Ruby Isn't Just About Rails
Ruby Isn't Just About RailsRuby Isn't Just About Rails
Ruby Isn't Just About Rails
 
Crafting Beautiful CLI Applications in Ruby
Crafting Beautiful CLI Applications in RubyCrafting Beautiful CLI Applications in Ruby
Crafting Beautiful CLI Applications in Ruby
 
Becoming a Git Master
Becoming a Git MasterBecoming a Git Master
Becoming a Git Master
 
XebiCon'16 : Fastlane : Automatisez votre vie (de développeur iOS) Par Jean-...
XebiCon'16 : Fastlane : Automatisez votre vie (de développeur iOS)  Par Jean-...XebiCon'16 : Fastlane : Automatisez votre vie (de développeur iOS)  Par Jean-...
XebiCon'16 : Fastlane : Automatisez votre vie (de développeur iOS) Par Jean-...
 
Repoinit: a mini-language for content repository initialization
Repoinit: a mini-language for content repository initializationRepoinit: a mini-language for content repository initialization
Repoinit: a mini-language for content repository initialization
 
Puppet at GitHub / ChatOps
Puppet at GitHub / ChatOpsPuppet at GitHub / ChatOps
Puppet at GitHub / ChatOps
 
Mojolicious and REST
Mojolicious and RESTMojolicious and REST
Mojolicious and REST
 
Puppet at Pinterest
Puppet at PinterestPuppet at Pinterest
Puppet at Pinterest
 
以 Laravel 經驗開發 Hyperf 應用
以 Laravel 經驗開發 Hyperf 應用以 Laravel 經驗開發 Hyperf 應用
以 Laravel 經驗開發 Hyperf 應用
 
How to develop Jenkins plugin using to ruby and Jenkins.rb
How to develop Jenkins plugin using to ruby and Jenkins.rbHow to develop Jenkins plugin using to ruby and Jenkins.rb
How to develop Jenkins plugin using to ruby and Jenkins.rb
 
Using Ansible as Makefiles to unite your developers
Using Ansible as Makefiles to unite your developersUsing Ansible as Makefiles to unite your developers
Using Ansible as Makefiles to unite your developers
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby Team
 
Plack perl superglue for web frameworks and servers
Plack perl superglue for web frameworks and serversPlack perl superglue for web frameworks and servers
Plack perl superglue for web frameworks and servers
 
Serverless - introduction et perspectives concrètes
Serverless - introduction et perspectives concrètesServerless - introduction et perspectives concrètes
Serverless - introduction et perspectives concrètes
 
Grand Rapids PHP Meetup: Behavioral Driven Development with Behat
Grand Rapids PHP Meetup: Behavioral Driven Development with BehatGrand Rapids PHP Meetup: Behavioral Driven Development with Behat
Grand Rapids PHP Meetup: Behavioral Driven Development with Behat
 
Jedi Mind Tricks for Git
Jedi Mind Tricks for GitJedi Mind Tricks for Git
Jedi Mind Tricks for Git
 
Running node.js as a service behind nginx/varnish
Running node.js as a service behind nginx/varnishRunning node.js as a service behind nginx/varnish
Running node.js as a service behind nginx/varnish
 
Deploying distributed software services to the cloud without breaking a sweat
Deploying distributed software services to the cloud without breaking a sweatDeploying distributed software services to the cloud without breaking a sweat
Deploying distributed software services to the cloud without breaking a sweat
 

Similar to 2018 RubyHACK: put git to work - increase the quality of your rails project and let git do the boring work for you

Web development automatisation for fun and profit (Artem Daniliants)
Web development automatisation for fun and profit (Artem Daniliants)Web development automatisation for fun and profit (Artem Daniliants)
Web development automatisation for fun and profit (Artem Daniliants)
LumoSpark
 

Similar to 2018 RubyHACK: put git to work - increase the quality of your rails project and let git do the boring work for you (20)

Scaling up development of a modular code base
Scaling up development of a modular code baseScaling up development of a modular code base
Scaling up development of a modular code base
 
Capistrano Overview
Capistrano OverviewCapistrano Overview
Capistrano Overview
 
DevFest 2022 - GitHub Actions를 활용한 Flutter 배포 자동화하기
DevFest 2022 - GitHub Actions를 활용한 Flutter 배포 자동화하기DevFest 2022 - GitHub Actions를 활용한 Flutter 배포 자동화하기
DevFest 2022 - GitHub Actions를 활용한 Flutter 배포 자동화하기
 
Mojolicious - A new hope
Mojolicious - A new hopeMojolicious - A new hope
Mojolicious - A new hope
 
Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)
 
Optimizing Spring Boot apps for Docker
Optimizing Spring Boot apps for DockerOptimizing Spring Boot apps for Docker
Optimizing Spring Boot apps for Docker
 
Deployment Tactics
Deployment TacticsDeployment Tactics
Deployment Tactics
 
[EXTENDED] Ceph, Docker, Heroku Slugs, CoreOS and Deis Overview
[EXTENDED] Ceph, Docker, Heroku Slugs, CoreOS and Deis Overview[EXTENDED] Ceph, Docker, Heroku Slugs, CoreOS and Deis Overview
[EXTENDED] Ceph, Docker, Heroku Slugs, CoreOS and Deis Overview
 
Web development automatisation for fun and profit (Artem Daniliants)
Web development automatisation for fun and profit (Artem Daniliants)Web development automatisation for fun and profit (Artem Daniliants)
Web development automatisation for fun and profit (Artem Daniliants)
 
Women Who Code - RSpec JSON API Workshop
Women Who Code - RSpec JSON API WorkshopWomen Who Code - RSpec JSON API Workshop
Women Who Code - RSpec JSON API Workshop
 
Deploying Symfony | symfony.cat
Deploying Symfony | symfony.catDeploying Symfony | symfony.cat
Deploying Symfony | symfony.cat
 
Sprockets
SprocketsSprockets
Sprockets
 
Write php deploy everywhere tek11
Write php deploy everywhere   tek11Write php deploy everywhere   tek11
Write php deploy everywhere tek11
 
Very Early Review - Rocket(CoreOS)
Very Early Review - Rocket(CoreOS)Very Early Review - Rocket(CoreOS)
Very Early Review - Rocket(CoreOS)
 
Instrumentación de entrega continua con Gitlab
Instrumentación de entrega continua con GitlabInstrumentación de entrega continua con Gitlab
Instrumentación de entrega continua con Gitlab
 
Mojolicious
MojoliciousMojolicious
Mojolicious
 
2019 11-bgphp
2019 11-bgphp2019 11-bgphp
2019 11-bgphp
 
Deploying configurable frontend web application containers
Deploying configurable frontend web application containersDeploying configurable frontend web application containers
Deploying configurable frontend web application containers
 
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
 
Scaling up development of a modular code base
Scaling up development of a modular code baseScaling up development of a modular code base
Scaling up development of a modular code base
 

More from Rodrigo Urubatan

Ruby on rails impressione a você mesmo, seu chefe e seu cliente
Ruby on rails  impressione a você mesmo, seu chefe e seu clienteRuby on rails  impressione a você mesmo, seu chefe e seu cliente
Ruby on rails impressione a você mesmo, seu chefe e seu cliente
Rodrigo Urubatan
 

More from Rodrigo Urubatan (20)

Ruby code smells
Ruby code smellsRuby code smells
Ruby code smells
 
Data science in ruby is it possible? is it fast? should we use it?
Data science in ruby is it possible? is it fast? should we use it?Data science in ruby is it possible? is it fast? should we use it?
Data science in ruby is it possible? is it fast? should we use it?
 
Data science in ruby, is it possible? is it fast? should we use it?
Data science in ruby, is it possible? is it fast? should we use it?Data science in ruby, is it possible? is it fast? should we use it?
Data science in ruby, is it possible? is it fast? should we use it?
 
TDC2017 - POA - Aprendendo a usar Xamarin para desenvolver aplicações moveis ...
TDC2017 - POA - Aprendendo a usar Xamarin para desenvolver aplicações moveis ...TDC2017 - POA - Aprendendo a usar Xamarin para desenvolver aplicações moveis ...
TDC2017 - POA - Aprendendo a usar Xamarin para desenvolver aplicações moveis ...
 
Your first game with unity3d framework
Your first game with unity3d frameworkYour first game with unity3d framework
Your first game with unity3d framework
 
Tdc Floripa 2017 - 8 falácias da programação distribuída
Tdc Floripa 2017 -  8 falácias da programação distribuídaTdc Floripa 2017 -  8 falácias da programação distribuída
Tdc Floripa 2017 - 8 falácias da programação distribuída
 
Rubyconf2016 - Solving communication problems in distributed teams with BDD
Rubyconf2016 - Solving communication problems in distributed teams with BDDRubyconf2016 - Solving communication problems in distributed teams with BDD
Rubyconf2016 - Solving communication problems in distributed teams with BDD
 
resolvendo problemas de comunicação em equipes distribuídas com bdd
resolvendo problemas de comunicação em equipes distribuídas com bddresolvendo problemas de comunicação em equipes distribuídas com bdd
resolvendo problemas de comunicação em equipes distribuídas com bdd
 
vantagens e desvantagens de trabalhar remoto
vantagens e desvantagens de trabalhar remotovantagens e desvantagens de trabalhar remoto
vantagens e desvantagens de trabalhar remoto
 
Using BDD to Solve communication problems
Using BDD to Solve communication problemsUsing BDD to Solve communication problems
Using BDD to Solve communication problems
 
TDC2015 Porto Alegre - Interfaces ricas com Rails e React.JS
TDC2015  Porto Alegre - Interfaces ricas com Rails e React.JSTDC2015  Porto Alegre - Interfaces ricas com Rails e React.JS
TDC2015 Porto Alegre - Interfaces ricas com Rails e React.JS
 
Interfaces ricas com Rails e React.JS @ Rubyconf 2015
Interfaces ricas com Rails e React.JS @ Rubyconf 2015Interfaces ricas com Rails e React.JS @ Rubyconf 2015
Interfaces ricas com Rails e React.JS @ Rubyconf 2015
 
TDC São Paulo 2015 - Interfaces Ricas com Rails e React.JS
TDC São Paulo 2015  - Interfaces Ricas com Rails e React.JSTDC São Paulo 2015  - Interfaces Ricas com Rails e React.JS
TDC São Paulo 2015 - Interfaces Ricas com Rails e React.JS
 
Full Text Search com Solr, MySQL Full text e PostgreSQL Full Text
Full Text Search com Solr, MySQL Full text e PostgreSQL Full TextFull Text Search com Solr, MySQL Full text e PostgreSQL Full Text
Full Text Search com Solr, MySQL Full text e PostgreSQL Full Text
 
Ruby para programadores java
Ruby para programadores javaRuby para programadores java
Ruby para programadores java
 
Treinamento html5, css e java script apresentado na HP
Treinamento html5, css e java script apresentado na HPTreinamento html5, css e java script apresentado na HP
Treinamento html5, css e java script apresentado na HP
 
Ruby on rails impressione a você mesmo, seu chefe e seu cliente
Ruby on rails  impressione a você mesmo, seu chefe e seu clienteRuby on rails  impressione a você mesmo, seu chefe e seu cliente
Ruby on rails impressione a você mesmo, seu chefe e seu cliente
 
Mini curso rails 3
Mini curso rails 3Mini curso rails 3
Mini curso rails 3
 
Aplicações Hibridas com Phonegap e HTML5
Aplicações Hibridas com Phonegap e HTML5Aplicações Hibridas com Phonegap e HTML5
Aplicações Hibridas com Phonegap e HTML5
 
Git presentation to some coworkers some time ago
Git presentation to some coworkers some time agoGit presentation to some coworkers some time ago
Git presentation to some coworkers some time ago
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 

2018 RubyHACK: put git to work - increase the quality of your rails project and let git do the boring work for you

  • 1. Put Git to work increase the quality of your Rails project, and let git do the boring work for you
  • 3. Rodrigo Urubatan  rodrigo@urubatan.com.br  http://twitter.com/urubatan  http://github.com/urubatan  http://linkedin.com/in/urubatan  http://sobrecodigo.com
  • 4. 5 ways git can help deploy your rails application 1 – check every commit follow company standards 2 – identify where each commit come from 3 – make sure at least the changed files tests run before pushing code 4 – start CI build after pushing the code 5 – 2 different approaches to git push your deploy after the ci build succeded
  • 5. There is a lot of boring manual work to do before each deploy! Check code against standards Pretty format commit messages Run tests for the files you changed to speed up development Start CI builds Start deployments Compile assets Run migrations when needed Install npm modules Reload application servers
  • 7. Git can help! Commit Check standards Format message Push code Run tests (locally) Start CI process Pull code Bundle install Yarn install Start deploy Npm install Bundle install Db migrate Restart service(s)
  • 8. Putting it to work! Codding standards Git pre-commit hook Formatting commit message Git prepare-commit-msg hook Running tests Git pre-push hook Firing CI build Git post-receive hook Automatic deployment Git post-receive hook Or Git post-merge hook
  • 9. I had one (more than one) evil coworker that didn’t follow any company standards This Photo by Unknown Author is licensed under CC BY
  • 10. How to fight the Evil Coworker who does not follow good practices? This Photo by Unknown Author is licensed under CC BY-SA
  • 11. rubocode + .git/hooks/pre-commit #!/bin/sh echo "Checking commit" if git rev-parse --verify HEAD >/dev/null 2>&1 then against=HEAD else # Initial commit: diff against an empty tree object against=4b825dc642cb6eb9a060e54bf8d69288fbee4904 fi # If you want to allow non-ASCII filenames set this variable to true. rubocop -R `git diff --cached --name-only $against` if [ "$?" != "0" ]; then cat <<EOF pretty Failed!! message!! EOF exit 1 fi
  • 12. I found a commit and did not know where it came from This Photo by Unknown Author is licensed under CC BY
  • 13. Formatting commit messages #!/bin/bash BRANCH_NAME=$(git symbolic-ref --short HEAD) BRANCH_NAME="${BRANCH_NAME##*/}" BRANCH_IN_COMMIT=$(grep -c "[$BRANCH_NAME]" $1) if [ -n "$BRANCH_NAME" ] && ! [[ $BRANCH_IN_COMMIT -ge 1 ]]; then sed -i.bak -e "1s/^/[$BRANCH_NAME] /" $1 fi
  • 14. Life is too short to test before sharing my code!
  • 15. Run your tests before pushing the code! #!/usr/bin/env ruby branch_name=`git symbolic-ref -q HEAD` branch_name = branch_name.gsub('refs/heads/', '').strip changed_files = `git diff --name-only #{ARGV[0]}/#{branch_name}`.split("n").map(&:strip).select{|n| n =~ /.rb$/} #run the file specific test test_files = changed_files.map do |name| if name =~ /^app/ name.gsub('app/', 'test/').gsub(/.rb$/, '_test.rb') elsif name =~ /^test/ name else nil end end.reject(&:nil?).uniq #abort if there is a test missing if !test_files.reject{|n| File.exists?(n)}.empty? puts %Q{ Aborting push because there are missing test files: #{test_files.reject{|n| File.exists?(n)}} } exit 1 end #if there are config files changes, run all tests if !changed_files.select{|n| n =~ /^config/}.empty? test_files = '' end system('git stash') result = system("rails test #{test_files.join(' ')}") system('git stash apply') unless result puts %Q{ Aborting push due to failed tests } exit 1 end
  • 16. Trick’em into using your perfect hooks This Photo by Unknown Author is licensed under CC BY-NC-ND
  • 17. And the evil trick!  npm i shared-git-hooks --save-dev or yarn add shared-git-hooks  Add your git hooks (with or without extension) to the hooks directory in your project
  • 18. Too much automation? This Photo by Unknown Author is licensed under CC BY-NC-SA
  • 19. Found out you need another gem or npm module when you decide to do some work in the airplane? This Photo by Unknown Author is licensed under CC BY-NC-SA
  • 21. Continuous Integration This Photo by Unknown Author is licensed under CC BY-SA
  • 23. Firing CI Build .git/hooks/post-receive with a curl to your CI server Github integrated CI servers (github version of the above)
  • 24. Jenkins curl -X POST http://username:user_api_token@your- jenkins.com/job/JobName/build?token=build_trigger_api_token
  • 25. TravisCI body='{ "request": { "branch":"master" }}' curl -s -X POST -H "Content-Type: application/json" -H "Accept: application/json" -H "Travis-API-Version: 3" -H "Authorization: token xxxxxx" -d "$body" https://api.travis-ci.com/repo/mycompany%2Fmyrepo/requests
  • 26. TeamCity curl -X POST -u apiuser:apipassword -d '<build><buildType id="SpringPetclinic_Build"/></build>' http://localhost:8111/httpAuth/app/rest/buildQueue --header "Content-Type: application/xml" -H "Accept: application/json"
  • 27. Bamboo export BAMBOO_USER=foo export BAMBOO_PASS=bar export PROJECT_NAME=TST export PLAN_NAME=DMY export STAGE_NAME=JOB1 curl --user $BAMBOO_USER:$BAMBOO_PASS -X POST -d "$STAGE_NAME&ExecuteAllStages" http://mybamboohost:8085/rest/api/latest/queue/$PROJECT_NAME- $PLAN_NAME
  • 28.
  • 29. Automatic Deployment – Heroku Recipe 1 server 1 bare repository 1 simple script 1 deployment repository/path
  • 30. My goal with this approach is to do this  git remote add production user@server:myapp.git  Git push production master This Just Deployed my code to production!
  • 31. Git Bare Repository  mkdir myapp.git  cd myapp.git && git init --bare  vi hooks/post-receive
  • 32. myapp.git/hooks/post-receive #!/bin/bash while read oldrev newrev ref do branch_received=`echo $ref | cut -d/ -f3` echo "Deploying branch $branch_received" /bin/bash --login -- <<__EOF__ cd /home/urubatan/projects/deployedapp git fetch git checkout -f $branch_received git pull yarn install bundle install rails db:migrate rails assets:precompile touch tmp/restart.txt __EOF__ done
  • 33. Automatic Deployment – git pull style (post-merge hook) #!/bin/bash bundle install yarn install rails db:migrate rails assets:precompile touch tmp/restart.txt
  • 34. Do you feel you need to track all that deploys? This Photo by Unknown Author is licensed under CC BY-SA
  • 35. git-deploy  https://github.com/git-deploy/git-deploy  git deploy start (you can git deploy abort if needed)  Merge all feature branches that need deployment  git deploy sync  Push that to all your servers (maybe using our Heroku strategy?)  git deploy finish  Now you can use the git-deploy script to list all deployments, or go back to any one of them!
  • 37. Rodrigo Urubatan  I help ruby developers to use the best tools for each job so they can solve hard problems, with less bugs and have more free time.  rodrigo@urubatan.com.br  http://twitter.com/urubatan  http://bit.ly/weekly_rails_tips  http://github.com/urubatan  http://linkedin.com/in/urubatan  http://sobrecodigo.com
  • 38. Whats next? A git ebook! http://bit.ly/weekly_rails_tips

Editor's Notes

  1. Ask audience, has anyone already caused a bug or a broken build just by forgetting one of these tasks? Is any of these tasks related to the business of your application? And the worse, is that rails should let you focus on your business logic instead of those boring repetitive tasks!
  2. Talk a little about past projects and alternative options Start talking about git hooks and the difference between client and server hooks