Initial commit

This commit is contained in:
Olivier 2023-11-12 11:51:39 +01:00
parent dfeb535db1
commit 5445a8a8f7
14 changed files with 629 additions and 7 deletions

74
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,74 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at [jekyll@sverrirs.com](mailto:jekyll@sverrirs.com). All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

12
Gemfile Normal file
View File

@ -0,0 +1,12 @@
# 2023-11-11
source 'https://rubygems.org'
gem 'rake'
# Specify your gem's dependencies in jekyll-webp.gemspec
gemspec
if ENV["JEKYLL_VERSION"]
gem "jekyll", "~> #{ENV["JEKYLL_VERSION"]}"
end

23
LICENSE
View File

@ -1,9 +1,22 @@
MIT License
The MIT License (MIT)
Copyright (c) 2023 kraoc
Copyright (c) 2016 Sverrir Sigmundarson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

130
README.md
View File

@ -1,3 +1,129 @@
# jekyll-webp
# WebP Generator for Jekyll (Extended)
WebP Image Generator for Jekyll Sites can automatically generate WebP images for all images on your static site and serve them when possible. View on [rubygems.org](https://rubygems.org/gems/jekyll-webp).
**This repo is an extended version of it's fork [jekyll-webp](https://github.com/sverrirs/jekyll-webp)**
## Additional Features
- Generate thumbnails in webp format
- Generate small images (.5x) in webp format
- Specifiy output sub directory for webp images
## Additional Dependencies
- fastimage
## Installation instructions
```
group :jekyll_plugins do
gem 'jekyll-webp', git: 'https://github.com/Rohithzr/jekyll-webp-ext', branch: 'extend'
end
```
## Original installation instructions
```
gem install jekyll-webp
```
The release includes all necessary files to run, including the WebP redistributable executable files.
> Currently the release includes the v0.6.1 version of the WebP utilities for Windows, Linux and Mac OS X 10.9 (Mountain Lion). Other versions and releases can be downloaded directly from <a href="https://developers.google.com/speed/webp/docs/precompiled" target="_blank">the Google page</a>.
Add the gem to your `Gemfile` and to Jekyll's `_config.yml` then run `jekyll serve` again and you should see the generator run during site generation.
## Configuration
The plugin can be configured in the site's `_config.yml` file by including the `webp` configuration element
``` yml
############################################################
# Site configuration for the WebP Generator Plugin
# The values here represent the defaults if nothing is set
webp:
enabled: true
# The quality of the webp conversion 0 to 100 (where 100 is least lossy)
quality: 75
# List of directories containing images to optimize, nested directories will only be checked if `nested` is true
# By default the generator will search for a folder called `/img` under the site root and process all jpg, png and tiff image files found there.
img_dir: ["/img"]
# Whether to search in nested directories or not
nested: false
# add ".gif" to the format list to generate webp for animated gifs as well
formats: [".jpeg", ".jpg", ".png", ".tiff"]
# File extensions for animated gif files
gifs: [".gif"]
# Set to true to always regenerate existing webp files
regenerate: false
# Local path to the WebP utilities to use (relative or absolute)
# Omit or leave as nil to use the utilities shipped with the gem, override only to use your local install
# Eg : "/usr/local/bin/cwebp"
webp_path: nil
# List of files or directories to exclude
# e.g. custom or hand generated webp conversion files
exclude: []
# append '.webp' to filename after original extension rather than replacing it.
# Default transforms `image.png` to `image.webp`, while changing to true transforms `image.png` to `image.png.webp`
append_ext: false
##### Extended Features start
# Use a different output subdirectory
# e.g. value of "/optimized" will create files at "/source/optimized" instead of "/source"
output_img_sub_dir: "/optimized" # default ""
# Generate thumbnails
thumbs: true
# Thumbnails sub directory
thumbs_dir: "/thumbs"
# generate .5x images
generate_50p: true
##### Extended Features end
############################################################
```
## Simplest use: HTML
In case you don't have control over your webserver then using the `<picture>` element and specifying all image formats available is the best option. This way the browser will decide which format to use based on its own capabilities.
``` html
<picture>
<source srcset="/path/to/image.webp" type="image/webp">
<img src="/path/to/image.jpg" alt="">
</picture>
```
## Advanced use: Webserver Configuration
If you can, then configuring your webserver to serve your new _.webp_ files to clients that support the format is probably the least problematic approach. This way you don't need to make any changes to your HTML files as your webserver will automatically serve WebP images when the client supports them.
Below is an example for a .htaccess configuration section in an Apache web-server. It will redirect users to webp images whenever possible.
```
####################
# Attempt to redirect images to WebP if one exists
# and the client supports the file format
####################
# check if browser accepts webp
RewriteCond %{HTTP_ACCEPT} image/webp
# check if file is jpg or png
RewriteCond %{REQUEST_FILENAME} (.*)\.(jpe?g|png)$
# check if corresponding webp file exists image.png -> image.webp
RewriteCond %1\.webp -f
# serve up webp instead
RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]
AddType image/webp .webp
```
> Depending on other configurations in your `.htaccess` file you might have to update your `ExpiresByType`, `ExpiresDefault` and `Header set Cache-Control` directives to include the webp format as well.
WebP Generator for Jekyll

15
Rakefile Normal file
View File

@ -0,0 +1,15 @@
# 2023-11-11
require 'rake'
require 'rake/testtask'
Rake::TestTask.new do |t|
t.libs.push 'lib'
t.libs.push 'specs'
t.verbose = true
t.pattern = "spec/*_spec.rb"
t.test_files = FileList['spec/*_spec.rb']
end
desc "Run tests"
task :default => [:test]

BIN
exe/linux-x64-cwebp Normal file

Binary file not shown.

BIN
exe/osx-cwebp Normal file

Binary file not shown.

BIN
exe/win-x64-cwebp.exe Normal file

Binary file not shown.

35
jekyll-webp.gemspec Normal file
View File

@ -0,0 +1,35 @@
# 2023-11-11
# coding: utf-8
require_relative 'lib/jekyll-webp/version'
require "date"
Gem::Specification.new do |spec|
spec.name = "jekyll-webp"
spec.version = Jekyll::Webp::VERSION
spec.platform = Gem::Platform::RUBY
spec.date = DateTime.now.strftime('%Y-%m-%d')
spec.authors = ["Sverrir Sigmundarson"]
spec.email = ["jekyll@sverrirs.com"]
spec.homepage = "https://github.com/sverrirs/jekyll-webp"
spec.license = "MIT"
spec.summary = %q{WebP image generator for Jekyll 3 websites}
spec.description = %q{WebP Image Generator for Jekyll 3 Sites that automatically generate WebP images for all images on your static site and serves them when possible. Includes the v0.6.1 version of the WebP utilities for Windows, Linux and Mac OS X 10.9 (Mountain Lion)}
spec.files = Dir['CODE_OF_CONDUCT.md', 'README.md', 'LICENSE', 'Rakefile', '*.gemspec', 'Gemfile', 'lib/**/*', 'spec/**/*', 'bin/**/*']
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^spec/})
spec.require_paths = ["lib"]
#spec.add_dependency "fastimage", '>= 2.0.0'
#spec.add_development_dependency "jekyll", ">= 3.0"
#spec.add_development_dependency "bundler", ">= 1.5"
#spec.add_development_dependency "rake", ">= 1.5"
spec.add_development_dependency "minitest", '~> 5.4', '>= 5.4.3'
spec.add_runtime_dependency 'fastimage', '~> 2.0', '>= 2.0.0'
spec.add_development_dependency 'jekyll', '~> 3.0'
spec.add_development_dependency 'bundler', '~> 1.5'
spec.add_development_dependency 'rake', '~> 1.5'
end

9
lib/jekyll-webp.rb Normal file
View File

@ -0,0 +1,9 @@
require "jekyll-webp/version"
require "jekyll-webp/defaults"
require "jekyll-webp/webpExec"
require "jekyll-webp/webpGenerator"
module Jekyll
module Webp
end # module Webp
end # module Jekyll

View File

@ -0,0 +1,63 @@
module Jekyll
module Webp
# The default configuration for the Webp generator
# The values here represent the defaults if nothing is set
DEFAULT = {
'enabled' => false,
# The quality of the webp conversion 0 to 100 (where 100 is least lossy)
'quality' => 75,
# Other flags to pass to the webp binary. For a list of valid parameters check here:
# https://developers.google.com/speed/webp/docs/cwebp#options
'flags' => "-m 4 -pass 4 -af",
# List of directories containing images to optimize, Nested directories only be checked if `nested` is true
'img_dir' => ["/img"],
# Whether to search in nested directories or not
'nested' => false,
# add ".gif" to the format list to generate webp for animated gifs as well
'formats' => [".jpeg", ".jpg", ".png", ".tiff"],
# append .webp to existing extension instead of replacing it
# (Enables more efficient nginx rules.
# See http://www.lazutkin.com/blog/2014/02/23/serve-files-with-nginx-conditionally/)
'append_ext' => false,
# File extensions for animated gif files
'gifs' => [".gif"],
# Set to true to always regenerate existing webp files
'regenerate'=> false,
# Local path to the WebP utilities to use (relative or absolute)
# Leave as nil to use the cmd line utilities shipped with the gem, override to use your local install
'webp_path' => nil,
# List of files or directories to exclude
# e.g. custom or hand generated webp conversion files
'exclude' => [],
# List of files or directories to explicitly include
# e.g. single files outside of the main image directories
'include' => [],
# Use a different output subdirectory
# e.g. value of "/optimized" will create files at "/source/optimized" instead of "/source"
'output_img_sub_dir' => "",
# Generate thumbnails
'thumbs' => false,
# Thumbnails sub directory
'thumbs_dir' => "/thumbs",
# generate .5x images
'generate_50p' => false
}
end # module Webp
end # module Jekyll

View File

@ -0,0 +1,8 @@
module Jekyll
module Webp
VERSION = "1.1.1"
# When modifying remember to issue a new tag command in git before committing, then push the new tag
# git tag -a v1.0.0 -m "Gem v1.0.0"
# git push origin --tags
end #module Webp
end #module Jekyll

110
lib/jekyll-webp/webpExec.rb Normal file
View File

@ -0,0 +1,110 @@
require 'open3'
require 'fastimage'
module Jekyll
module Webp
class WebpExec
#
# Runs the WebP executable for the given input parameters
# the function detects the OS platform and architecture automatically
#
def self.run(quality, flags, input_file, output_file, webp_bin_fullpath)
if webp_bin_fullpath
full_path = webp_bin_fullpath
else
# What is the path to the execs inside the gem? perhaps just bin/?
bin_path = "bin/"
# What is the OS and architecture specific executable name?
exe_name = WebpExec.exe_name
# We need to locate the Gems bin path as we're currently running inside the
# jekyll site working directory
# http://stackoverflow.com/a/10083594/779521
gem_spec = Gem::Specification.find_by_name("jekyll-webp")
gem_root = gem_spec.gem_dir
# Construct the full path to the executable
full_path = File.join(gem_root, bin_path, exe_name)
end
# Construct the full program call
cmd = "\"#{full_path}\" -quiet -mt -q #{quality.to_s} #{flags} \"#{input_file}\" -o \"#{output_file}\""
# Execute the command
exit_code = 0
error = ""
output = ""
Open3.popen3(cmd) do |stdin, stdout, stderr, wait_thr|
stdin.close # we don't pass any input to the process
output = stdout.gets
error = stderr.gets
exit_code = wait_thr.value
end
if exit_code != 0
# Jekyll.logger.error("WebP:","Conversion for image #{input_file} failed, no webp version could be created for this image")
Jekyll.logger.error("WebP:","cwebp returned #{exit_code} with error #{error}")
end
# Return any captured return value
return [output, error]
end #function run
#
# Returns the correct executable name depending on the OS platform and OS architecture
#
def self.exe_name
if OS.mac?
return "osx-cwebp"
elsif OS.windows?
if OS.x32?
return "win-x86-cwebp.exe"
else
return "win-x64-cwebp.exe"
end
elsif OS.unix? || OS.linux?
if OS.x32?
return "linux-x86-cwebp"
else
return "linux-x64-cwebp"
end
else
raise ArgumentError.new("OS platform could not be identified (gem can only be run on linux,osx or windows)")
end
end #function exe_name
end #class WebpExec
end #module Webp
module OS
def OS.windows?
(/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM) != nil
end
def OS.mac?
(/darwin/ =~ RUBY_PLATFORM) != nil
end
def OS.unix?
!OS.windows?
end
def OS.linux?
OS.unix? and not OS.mac?
end
def OS.x32?
return 1.size != 8
end
def OS.x64?
return 1.size == 8
end
end #module OS
end #module Jekyll

View File

@ -0,0 +1,157 @@
require 'jekyll/document'
require 'fileutils'
module Jekyll
module Webp
#
# A static file to hold the generated webp image after generation
# so that Jekyll will copy it into the site output directory
class WebpFile < StaticFile
def write(dest)
true # Recover from strange exception when starting server without --auto
end
end #class WebpFile
class WebpGenerator < Generator
# This generator is safe from arbitrary code execution.
safe true
# This generator should be passive with regard to its execution
priority :lowest
# Generate paginated pages if necessary (Default entry point)
# site - The Site.
#
# Returns nothing.
def generate(site)
# Retrieve and merge the configuration from the site yml file
@config = DEFAULT.merge(site.config['webp'] || {})
# If disabled then simply quit
if !@config['enabled']
Jekyll.logger.info "WebP:","Disabled in site.config."
return
end
Jekyll.logger.debug "WebP:","Starting"
# If the site destination directory has not yet been created then create it now. Otherwise, we cannot write our file there.
Dir::mkdir(site.dest) if !File.directory? site.dest
# If nesting is enabled, get all the nested directories too
if @config['nested']
newdir = []
for imgdir in @config['img_dir']
# Get every directory below (and including) imgdir, recursively
newdir.concat(Dir.glob(imgdir + "/**/"))
end
@config['img_dir'] = newdir
end
# Counting the number of files generated
file_count = 0
thumb_count = 0
# Iterate through every image in each of the image folders and create a webp image
# if one has not been created already for that image.
for imgdir in @config['img_dir']
imgdir_source = File.join(site.source, imgdir)
imgdir_destination = File.join(site.dest, imgdir)
FileUtils::mkdir_p(imgdir_destination)
if @config['output_img_sub_dir'] != ""
FileUtils::mkdir_p(File.join(imgdir_destination, @config['output_img_sub_dir']))
end
if @config['thumbs']
FileUtils::mkdir_p(File.join(imgdir_destination, @config['thumbs_dir']))
end
Jekyll.logger.info "WebP:","Processing #{imgdir_source}"
# handle only jpg, jpeg, png and gif
for imgfile in Dir[imgdir_source + "**/*.*"]
imgfile_relative_path = File.dirname(imgfile.sub(imgdir_source, ""))
# Skip empty stuff
file_ext = File.extname(imgfile).downcase
# If the file is not one of the supported formats, exit early
next if !@config['formats'].include? file_ext
# TODO: Do an exclude check
# Create the output file path
outfile_filename = if @config['append_ext']
File.basename(imgfile) + '.webp'
else
file_noext = File.basename(imgfile, file_ext)
file_noext + ".webp"
end
small_outfile_filename = File.basename(imgfile, file_ext) + "-small" + ".webp"
FileUtils::mkdir_p(imgdir_destination + imgfile_relative_path)
outfile_fullpath_webp = File.join(imgdir_destination + imgfile_relative_path, @config['output_img_sub_dir'], outfile_filename)
small_outfile_fullpath_webp = File.join(imgdir_destination + imgfile_relative_path, @config['output_img_sub_dir'], small_outfile_filename)
thumb_outfile_fullpath_webp = File.join(imgdir_destination + imgfile_relative_path, @config['thumbs_dir'], outfile_filename)
# Check if the file already has a webp alternative?
# If we're force rebuilding all webp files then ignore the check
# also check the modified time on the files to ensure that the webp file
# is newer than the source file, if not then regenerate
if @config['regenerate'] || !File.file?(outfile_fullpath_webp) ||
File.mtime(outfile_fullpath_webp) <= File.mtime(imgfile)
Jekyll.logger.info "WebP:", "Change to source image file #{imgfile} detected, regenerating WebP"
# Generate the file
WebpExec.run(@config['quality'], @config['flags'], imgfile, outfile_fullpath_webp, @config['webp_path'])
file_count += 1
if @config['generate_50p']
# Get the image size
Jekyll.logger.info "WebP:", "Generating small image file #{outfile_filename}"
image_size = FastImage.size(imgfile, :raise_on_failure=>true, :timeout=>2.0)
h_width = image_size[0] / 2
size_flags = "-resize #{h_width} 0" + " " + @config['flags']
WebpExec.run(@config['quality'], size_flags, imgfile, small_outfile_fullpath_webp, @config['webp_path'])
end
# Generate the thumbnails
if @config['thumbs']
Jekyll.logger.info "WebP:", "Generating thumbnail for #{outfile_filename} in #{@config['thumbs_dir']}"
thumb_flags = "-resize 400 0" + " " + @config['flags']
WebpExec.run(@config['quality'], thumb_flags, imgfile, thumb_outfile_fullpath_webp, @config['webp_path'])
thumb_count += 1
end
end
if File.file?(outfile_fullpath_webp)
# Keep the webp file from being cleaned by Jekyll
site.static_files << WebpFile.new(site,
site.dest,
File.join(imgdir, imgfile_relative_path, @config['output_img_sub_dir']),
outfile_filename)
if @config['thumbs']
site.static_files << WebpFile.new(site,
site.dest,
File.join(imgdir, imgfile_relative_path, @config['thumbs_dir']),
outfile_filename)
end
if @config['generate_50p']
site.static_files << WebpFile.new(site,
site.dest,
File.join(imgdir, imgfile_relative_path, @config['output_img_sub_dir']),
small_outfile_filename)
end
end
end # dir.foreach
end # img_dir
Jekyll.logger.info "WebP:","Generator Complete: #{file_count} file(s) generated #{thumb_count} thumbnail(s) generated"
end #function generate
end #class WebPGenerator
end #module Webp
end #module Jekyll