How to enable automatic code reloading in Rails - html

Is there a way to do 'hot code reloading' with a Rails application in the development environment?
For example: I'm working on a Rails application, I add a few lines of css in a stylesheet, I look at the browser to see the modified styling. As of right now I have to refresh the page with cmd-r or by clicking the refresh button.
Is there a way to get the page to reload automatically when changes are made?
This works nicely in the Phoenix web framework (and I'm sure Phoenix isn't the only framework in this feature). How could a feature like this be enabled in Ruby on Rails?

I am using this setup reloads all assets, js, css, ruby files
in Gemfile
group :development, :test do
gem 'guard-livereload', '~> 2.5', require: false
end
group :development do
gem 'listen'
gem 'guard'
gem 'guard-zeus'
gem 'rack-livereload'
end
insert this in your development.rb
config.middleware.insert_after ActionDispatch::Static, Rack::LiveReload
i have this in my guard file
# A sample Guardfile
# More info at https://github.com/guard/guard#readme
## Uncomment and set this to only include directories you want to watch
# directories %w(app lib config test spec features) \
# .select{|d| Dir.exists?(d) ? d : UI.warning("Directory #{d} does not exist")}
## Note: if you are using the `directories` clause above and you are not
## watching the project directory ('.'), then you will want to move
## the Guardfile to a watched dir and symlink it back, e.g.
#
# $ mkdir config
# $ mv Guardfile config/
# $ ln -s config/Guardfile .
#
# and, you'll have to watch "config/Guardfile" instead of "Guardfile"
guard 'livereload' do
extensions = {
css: :css,
scss: :css,
sass: :css,
js: :js,
coffee: :js,
html: :html,
png: :png,
gif: :gif,
jpg: :jpg,
jpeg: :jpeg,
# less: :less, # uncomment if you want LESS stylesheets done in browser
}
rails_view_exts = %w(erb haml slim)
# file types LiveReload may optimize refresh for
compiled_exts = extensions.values.uniq
watch(%r{public/.+\.(#{compiled_exts * '|'})})
extensions.each do |ext, type|
watch(%r{
(?:app|vendor)
(?:/assets/\w+/(?<path>[^.]+) # path+base without extension
(?<ext>\.#{ext})) # matching extension (must be first encountered)
(?:\.\w+|$) # other extensions
}x) do |m|
path = m[1]
"/assets/#{path}.#{type}"
end
end
# file needing a full reload of the page anyway
watch(%r{app/views/.+\.(#{rails_view_exts * '|'})$})
watch(%r{app/helpers/.+\.rb})
watch(%r{config/locales/.+\.yml})
end
guard 'zeus' do
require 'ostruct'
rspec = OpenStruct.new
# rspec.spec_dir = 'spec'
# rspec.spec = ->(m) { "#{rspec.spec_dir}/#{m}_spec.rb" }
# rspec.spec_helper = "#{rspec.spec_dir}/spec_helper.rb"
# matchers
# rspec.spec_files = /^#{rspec.spec_dir}\/.+_spec\.rb$/
# Ruby apps
ruby = OpenStruct.new
ruby.lib_files = /^(lib\/.+)\.rb$/
# watch(rspec.spec_files)
# watch(rspec.spec_helper) { rspec.spec_dir }
# watch(ruby.lib_files) { |m| rspec.spec.call(m[1]) }
# Rails example
rails = OpenStruct.new
rails.app_files = /^app\/(.+)\.rb$/
rails.views_n_layouts = /^app\/(.+(?:\.erb|\.haml|\.slim))$/
rails.controllers = %r{^app/controllers/(.+)_controller\.rb$}
# watch(rails.app_files) { |m| rspec.spec.call(m[1]) }
# watch(rails.views_n_layouts) { |m| rspec.spec.call(m[1]) }
# watch(rails.controllers) do |m|
# [
# rspec.spec.call("routing/#{m[1]}_routing"),
# rspec.spec.call("controllers/#{m[1]}_controller"),
# rspec.spec.call("acceptance/#{m[1]}")
# ]
# end
end
I am using zeus instead of spring on this setup.
Run guard
Open localhost:3000 and you are good to go.
This should resolve your question, and have blazing reload times better than browserify.
I commented out guard looking at test directories if you want you can uncomment those lines if your are doing TDD.

CSS hot swapping and auto-reload when HTML/JS changes can be achieved with guard in combination with livereload: https://github.com/guard/guard-livereload

This gem would auto reload when you make changes to js elements(Not css or ruby files).
https://github.com/rmosolgo/react-rails-hot-loader
Never seen css hot code reloading in rails platform.

Related

Can't read JSON file in Ruby on Rails

I am new in ruby on rails and I want to read data from a JSON file from a specified directory, but I constantly get an error in chap3(File name)
Errno::ENOENT in TopController#chap3. No such file or directory # rb_sysopen - links.json.
In the console, I get a message
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
How I can fix that?
Code:
require "json"
class TopController < ApplicationController
def index
#message = "おはようございます!"
end
def chap3
data = File.read('links.json')
datahash = JSON.parse(data)
puts datahash.keys
end
def getName
render plain: "名前は、#{params[:name]}"
end
def database
#members = Member.all
end
end
JSON file:
{ "data": [
{"link1": "http://localhost:3000/chap3/a.html"},
{"link2": "http://localhost:3000/chap3/b.html"},
{"link3": "http://localhost:3000/chap3/c.html"},
{"link4": "http://localhost:3000/chap3/d.html"},
{"link5": "http://localhost:3000/chap3/e.html"},
{"link6": "http://localhost:3000/chap3/f.html"},
{"link7": "http://localhost:3000/chap3/g.html"}]}
I would change these two lines
data = File.read('links.json')
datahash = JSON.parse(data)
in the controller to
datahash = Rails.root.join('app/controllers/links.json').read
Note: I would consider moving this kind of configuration file into the /config folder and creating a simple Ruby class to handle it. Additionally, you might want to consider paths instead of URLs with a host because localhost:3000 might work in the development environment but in production, you will need to return non-localhost URLs anyway.
Rails use the content of file in the controller
#data = File.read("#{Rails.root}/app/controllers/links.json")

Nanoc setup for URLs and links on a github deployed webpage [duplicate]

I have a simple static page app that i have built with nanoc and i want to deploy it as a github page.
Everything goes well except that the assets (like css, javascripts) and all the links in general point to the root of the repo:
like
/css/style.css
instead of being
/docs/css/style.css
Everything works well on localhost but fails when published.
i am using rake publish to push it to gh-pages.
Here is my Rakefile
require 'nanoc3/tasks'
BASE_URL = "http://darko1002001.github.com/docs/"
desc "Compile the site"
task :compile do
`nanoc compile`
end
desc "Publish to http://documentation.getchute.com"
task :publish => [:clean] do
FileUtils.rm_r('output') if File.exist?('output')
sh "nanoc compile"
ENV['GIT_DIR'] = File.expand_path(`git rev-parse --git-dir`.chomp)
old_sha = `git rev-parse refs/remotes/origin/gh-pages`.chomp
Dir.chdir('output') do
ENV['GIT_INDEX_FILE'] = gif = '/tmp/dev.gh.i'
ENV['GIT_WORK_TREE'] = Dir.pwd
File.unlink(gif) if File.file?(gif)
`git add -A`
tsha = `git write-tree`.strip
puts "Created tree #{tsha}"
if old_sha.size == 40
csha = `echo 'boom' | git commit-tree #{tsha} -p #{old_sha}`.strip
else
csha = `echo 'boom' | git commit-tree #{tsha}`.strip
end
puts "Created commit #{csha}"
puts `git show #{csha} --stat`
puts "Updating gh-pages from #{old_sha}"
`git update-ref refs/heads/gh-pages #{csha}`
`git push origin gh-pages`
end
end
Rules
compile '/static/*' do
end
compile '/CNAME/' do
end
compile '/feed/' do
filter :erb
filter :kramdown, :toc_levels => [2]
end
%w(v3 */).each do |version|
compile "/changes/#{version}" do
filter :erb
filter :kramdown, :toc_levels => [2]
filter :colorize_syntax,
:colorizers => {:javascript => :pygmentsrb}
layout 'changes' if version[0] == '*'
layout 'default'
end
end
compile '*' do
filter :erb
filter :kramdown, :toc_levels => [2]
filter :colorize_syntax,
:colorizers => {:javascript => :pygmentsrb}
layout 'default'
end
route '/static/*' do
item.identifier[7..-2]
end
route '/CNAME/' do
'/CNAME'
end
route '/feed' do
'/changes.atom'
end
route '*' do
item.identifier + 'index.html'
end
layout '*', :erb
nanoc generates absolute URLs by default, but you can use the relativize_paths filter to make all URLs relative. For HTML, use filter :relativize_paths, :type => :html. For CSS, use :css instead of :html.
Cheers
Denis

RoR Agile Web Dev 4 CSS not loading

I am new to RoR and I am following the Agile Web Development with Rails 4 book and I am to the point where we add CSS styling to the store front page (page 135 "8.1 Iteration C1: Creating the Catalog Listing").
However, I did exactly as the book stated but the CSS style is not being loaded when I load the page.
I did some research and from what I understand, everything is correct.
Does anyone see anything wrong or what I need to add?
I have tried everything here but nothing worked: Agile web development with rails” book: CSS not applied
UPDATE Looks like the application is using /assets/scaffold.css.scss for styling. If I go to this file a change colors, they reflect on the StoreControllers view!!?? What is wrong here??!!
I cannot figure out why the application is using the incorrect stylesheet...
BTW I also ran RAILS_ENV=production bundle exec rake assets:precompile and made sure the assets were included in public/assets/ folder
Here is my code:
Depot/app/assets/stylesheets/store.css.scss
.store {
h1 {
margin:0;
padding-bottom: 0.5em;
font: 150% san-serif;
color: #226;
border-bottom: 3px dotted #77d;
}
.entry {
overflow: auto;
margin-top: 1em;
border-bottom: 1px dotted #77d;
min-hieght:100px;
img {
width: 80px;
margin-right: 5px;
margin-bottom: 5px;
position: absolute;
}
h3 {
font-size: 120%;
font-family: sans-serif;
margin-left: 100px;
margin-top: 0;
margin-bottom: 2px;
color: #227;
}
p,div.price_line{
margin-left: 100px;
margin-top: 0.5em;
margin-bottom: 0.8em;
}
.price{
color: #44a;
font-weight: bold;
margin-right: 3em;
}
}
}
// Place all the styles related to the Store controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/
Depot/app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Application</title>
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
<%= csrf_meta_tags %>
</head>
<body class=​'<%= controller.controller_name%>'>
<%= yield %>
</body>
</html>
Depot/app/controllers/store/store_controller.rb
class StoreController < ApplicationController
def index
#products = Product.order(:title)
end
end
Depot/app/views/store/index.html.erb
<% if notice %>
<p id= "notice" ><%= notice %></p>
<% end %>
<h1>Your Pragmatic Catalog</h1>
<% #products.each do |product| %>
<div class= ".entry" >
<%= image_tag(product.image_url)%>
<h3><%= product.title %></h3>
<%= sanitize(product.description)%>
<div class= "price_line" >
<span class= "price" ><%= product.price %></span>
</div>
</div>
<% end %>
Depot/app/assets/stylesheets/application.css
/*
* This is a manifest file that'll be compiled into application.css, which will include all the files
* listed below.
*
* Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
* or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
*
* You're free to add application-wide styles to this file and they'll appear at the top of the
* compiled file, but it's generally better to create a new file per style scope.
*
*= require_self
*= require_tree .
*/
Depot/config/environments/production.rb
Depot::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = true
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = true
config.assets.precompile = ['*.js', '*.css', '*.css.erb']
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end
Depot::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = true
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = true
config.assets.precompile = ['*.js', '*.css', '*.css.erb']
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end
This solved it for me.
CSS is not loading in app
Be sure to test your CSS with something more obvious, like
color: red;
somewhere. The agile book is only aligning the text here. It could be easily missed.

How to create a rails 4 offline webapp?

I'm trying to create an app with Rails 4 that should be usable without internet connection.
I've heard about html5 application cache and the rack-offline gem which is the approach I took.
Now, it seems that it's not working properly on Rails 4 since the /application.manifest only shows:
CACHE MANIFEST
# dd1ba6bba9339ef83f9c1225c70289dd6326d3caae01b0d52b502381030dc78f
404.html
422.html
500.html
NETWORK:
*
Also, I'm using assets precompile so the application.js, application.css and the image files has a fingerprint in their names, something like application-e8cc2fba8275c884c.js.
I made my own solution in a generate_appcahe_manifest.rake file and put it in /lib/tasks folder.
task :generate_appcache_file => ['deploy:precompile_assets', 'html5_manifest']
desc "Create html5 manifest.appcache"
task :html5_manifest => :environment do
puts 'Creating appcache manifest file...'
File.open("public/manifest.appcache", "w") do |f|
f.write("CACHE MANIFEST\n")
f.write("# Version #{Time.now.to_i}\n\n")
f.write("CACHE:\n")
assets = Dir.glob(File.join(Rails.root, 'public/assets/**/*'))
assets.each do |asset|
if File.extname(asset) != '.gz' && File.extname(asset) != '' && File.extname(asset) != '.json'
filename_path = /#{Rails.root.to_s}\/public\/(assets\/.*)/.match(File.absolute_path(asset))[1].to_s
# f.write("assets/#{File.basename(asset)}\n")
f.write(filename_path.concat("\n"))
end
end
f.write("\nNETWORK:\n")
f.write("*\n")
f.write("http://*\n")
f.write("https://*\n")
end
puts 'Done.'
end
namespace :deploy do
task :precompile_assets do
require 'fileutils'
if File.directory?("#{Rails.root.to_s}/public/assets")
FileUtils.rm_r "#{Rails.root.to_s}/public/assets"
end
puts 'Precompiling assets...'
puts `RAILS_ENV=production bundle exec rake assets:precompile`
puts 'Done.'
end
end
So when I run rake generate_appcache_file on the terminal, I got a /public/manifest.appcache file with the compiled assets like this:
CACHE MANIFEST
# Version 1409045103
CACHE:
assets/app/backgrounds/strips-05561384267a3286ab382c852f1e8b0d.jpg
assets/app/backgrounds/team-12e0fc5f670794c4eba3db117fba6746.jpg
assets/app-a7de6b02d1d39b783fe4e7ab7906ec95.css
assets/app-ae958853aa13f9011e35121cbe5b3cfe.js
NETWORK:
*
http://*
https://*
Finally, I call that file on my /app/views/layouts/app.html.erb file:
<!DOCTYPE html>
<html lang="en" manifest="/manifest.appcache">
More info about offline application cache that helps me a lot can be found here.

How to get list of changed files since last build in Jenkins/Hudson

I have set up Jenkins, but I would like to find out what files were added/changed between the current build and the previous build. I'd like to run some long running tests depending on whether or not certain parts of the source tree were changed.
Having scoured the Internet I can find no mention of this ability within Hudson/Jenkins though suggestions were made to use SVN post-commit hooks. Maybe it's so simple that everyone (except me) knows how to do it!
Is this possible?
I have done it the following way. I am not sure if that is the right way, but it seems to be working. You need to get the Jenkins Groovy plugin installed and do the following script.
import hudson.model.*;
import hudson.util.*;
import hudson.scm.*;
import hudson.plugins.accurev.*
def thr = Thread.currentThread();
def build = thr?.executable;
def changeSet= build.getChangeSet();
changeSet.getItems();
ChangeSet.getItems() gives you the changes. Since I use accurev, I did List<AccurevTransaction> accurevTransList = changeSet.getItems();.
Here, the modified list contains duplicate files/names if it has been committed more than once during the current build window.
The CI server will show you the list of changes, if you are polling for changes and using SVN update. However, you seem to want to be changing the behaviour of the build depending on which files were modified. I don't think there is any out-of-the-box way to do that with Jenkins alone.
A post-commit hook is a reasonable idea. You could parameterize the job, and have your hook script launch the build with the parameter value set according to the changes committed. I'm not sure how difficult that might be for you.
However, you may want to consider splitting this into two separate jobs - one that runs on every commit, and a separate one for the long-running tests that you don't always need. Personally I prefer to keep job behaviour consistent between executions. Otherwise traceability suffers.
echo $SVN_REVISION
svn_last_successful_build_revision=`curl $JOB_URL'lastSuccessfulBuild/api/json' | python -c 'import json,sys;obj=json.loads(sys.stdin.read());print obj["'"changeSet"'"]["'"revisions"'"][0]["'"revision"'"]'`
diff=`svn di -r$SVN_REVISION:$svn_last_successful_build_revision --summarize`
You can use the Jenkins Remote Access API to get a machine-readable description of the current build, including its full change set. The subtlety here is that if you have a 'quiet period' configured, Jenkins may batch multiple commits to the same repository into a single build, so relying on a single revision number is a bit naive.
I like to keep my Subversion post-commit hooks relatively simple and hand things off to the CI server. To do this, I use wget to trigger the build, something like this...
/usr/bin/wget --output-document "-" --timeout=2 \
https://ci.example.com/jenkins/job/JOBID/build?token=MYTOKEN
The job is then configured on the Jenkins side to execute a Python script that leverages the BUILD_URL environment variable and constructs the URL for the API from that. The URL ends up looking like this:
https://ci.example.com/jenkins/job/JOBID/BUILDID/api/json/
Here's some sample Python code that could be run inside the shell script. I've left out any error handling or HTTP authentication stuff to keep things readable here.
import os
import json
import urllib2
# Make the URL
build_url = os.environ['BUILD_URL']
api = build_url + 'api/json/'
# Call the Jenkins server and figured out what changed
f = urllib2.urlopen(api)
build = json.loads(f.read())
change_set = build['changeSet']
items = change_set['items']
touched = []
for item in items:
touched += item['affectedPaths']
Using the Build Flow plugin and Git:
final changeSet = build.getChangeSet()
final changeSetIterator = changeSet.iterator()
while (changeSetIterator.hasNext()) {
final gitChangeSet = changeSetIterator.next()
for (final path : gitChangeSet.getPaths()) {
println path.getPath()
}
}
With Jenkins pipelines (pipeline supporting APIs plugin 2.2 or above), this solution is working for me:
def changeLogSets = currentBuild.changeSets
for (int i = 0; i < changeLogSets.size(); i++) {
def entries = changeLogSets[i].items
for (int j = 0; j < entries.length; j++) {
def entry = entries[j]
def files = new ArrayList(entry.affectedFiles)
for (int k = 0; k < files.size(); k++) {
def file = files[k]
println file.path
}
}
}
See How to access changelogs in a pipeline job.
Through Groovy:
<!-- CHANGE SET -->
<% changeSet = build.changeSet
if (changeSet != null) {
hadChanges = false %>
<h2>Changes</h2>
<ul>
<% changeSet.each { cs ->
hadChanges = true
aUser = cs.author %>
<li>Commit <b>${cs.revision}</b> by <b><%= aUser != null ? aUser.displayName : it.author.displayName %>:</b> (${cs.msg})
<ul>
<% cs.affectedFiles.each { %>
<li class="change-${it.editType.name}"><b>${it.editType.name}</b>: ${it.path} </li> <% } %> </ul> </li> <% }
if (!hadChanges) { %>
<li>No Changes !!</li>
<% } %> </ul> <% } %>
#!/bin/bash
set -e
job_name="whatever"
JOB_URL="http://myserver:8080/job/${job_name}/"
FILTER_PATH="path/to/folder/to/monitor"
python_func="import json, sys
obj = json.loads(sys.stdin.read())
ch_list = obj['changeSet']['items']
_list = [ j['affectedPaths'] for j in ch_list ]
for outer in _list:
for inner in outer:
print inner
"
_affected_files=`curl --silent ${JOB_URL}${BUILD_NUMBER}'/api/json' | python -c "$python_func"`
if [ -z "`echo \"$_affected_files\" | grep \"${FILTER_PATH}\"`" ]; then
echo "[INFO] no changes detected in ${FILTER_PATH}"
exit 0
else
echo "[INFO] changed files detected: "
for a_file in `echo "$_affected_files" | grep "${FILTER_PATH}"`; do
echo " $a_file"
done;
fi;
It is slightly different - I needed a script for Git on a particular folder...
So, I wrote a check based on jollychang.
It can be added directly to the job's exec shell script. If no files are detected it will exit 0, i.e. SUCCESS... this way you can always trigger on check-ins to the repository, but build when files in the folder of interest change.
But... If you wanted to build on-demand (i.e. clicking Build Now) with the changed from the last build.. you would change _affected_files to:
_affected_files=`curl --silent $JOB_URL'lastSuccessfulBuild/api/json' | python -c "$python_func"`
Note: You have to use Jenkins' own SVN client to get a change list. Doing it through a shell build step won't list the changes in the build.
It's simple, but this works for me:
$DirectoryA = "D:\Jenkins\jobs\projectName\builds" ####Jenkind directory
$firstfolder = Get-ChildItem -Path $DirectoryA | Where-Object {$_.PSIsContainer} | Sort-Object LastWriteTime -Descending | Select-Object -First 1
$DirectoryB = $DirectoryA + "\" + $firstfolder
$sVnLoGfIle = $DirectoryB + "\" + "changelog.xml"
write-host $sVnLoGfIle
I tried to add that to comments but code in comments is no way:
Just want to prettify code from heroin's answer:
def changedFiles = []
def changeLogSets = currentBuild.changeSets
for (entries in changeLogSets) {
for (entry in entries) {
for (file in entry.affectedFiles) {
echo "Found changed file: ${file.path}"
changedFiles += "${file.path}"
}
}
}
Keep in mind for some cases git plugin returns empty changeSet, like:
First run in newly created branch
'Build now' button build
Refer to https://issues.jenkins-ci.org/browse/JENKINS-26354 for more details.