Skip to content

Instantly share code, notes, and snippets.

@zealot128
Created September 29, 2020 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zealot128/6c41df1d33a810856a557971a04989f6 to your computer and use it in GitHub Desktop.
Save zealot128/6c41df1d33a810856a557971a04989f6 to your computer and use it in GitHub Desktop.
Automatically convert vue sfc with default html into pug using an API
#!/usr/bin/env ruby
require 'bundler/inline'
# Usage: just ruby with a recentish ruby (2.4+) and bundler inline should download necessary gems
# The conversion is done by https://html2pug.now.sh/convert
# - This script is a wrapper that walks a tree of *.vue files and converts the inner <template>
# - The script is interactive and ask before saving each file
#
# - Note: <UpperCase> custom components become upper-case() in pug
# - Note: the remote api seems to have problems with ternary inline code in html attributes
gemfile do
source 'https://rubygems.org'
gem 'tty-prompt'
gem 'pry'
gem 'diffy'
gem 'activesupport'
end
OPTIONS = {
"bodyless" => true,
"donotencode" => true,
"double" => true,
"inlineCSS" => false,
"noattrcomma" => true,
"nspaces" => 2,
"tabs" => false
}.freeze
require 'net/http'
require 'active_support/json'
require 'active_support/core_ext'
require 'json'
if ARGV.length == 0
puts "USAGE: #{__FILE__} *PATH_TO_VUE/DIR"
exit 1
end
files = []
ARGV.each do |elem|
if File.directory?(elem)
files += Dir["#{elem}/**/*.vue"]
else
files << elem
end
end
class ConvertingFile
def initialize(file)
@content = File.read(file)
@file = file
end
def convert!
if @content["<template>"]
convert_file
end
end
# convert all custom EmailEditor to email-editor
def preprocess_camelcase_names(template)
template.gsub(%r{(<|</)([a-zA-Z]*[A-Z][a-zA-Z]*)}) do |_pattern|
"#{Regexp.last_match(1)}#{Regexp.last_match(2).underscore.dasherize}"
end
end
def convert_file
final = @content.sub(%r{<template>(.*)</template>}m) do |_pattern|
template = Regexp.last_match[1]
"<template>\n#{html_to_pug(template)}</template>"
end
final.sub!('<template>', '<template lang="pug">')
ask_and_compare(final)
end
def ask_and_compare(final)
puts Diffy::Diff.new(@content, final, context: 1).to_s(:color)
if TTY::Prompt.new.yes?("Save to #{@file}?")
File.write(@file, final)
end
end
def html_to_pug(template)
url = URI.parse('https://html2pug.now.sh/convert')
params = {
"html" => preprocess_camelcase_names(template),
"options" => OPTIONS
}
response = Net::HTTP.post(url, params.to_json, { 'Content-Type' => 'application/json; charset=utf-8' })
unless response.code_type == Net::HTTPOK
puts "Error while accessing remote api #{url} #{response.code}"
puts response.body
exit 1
end
JSON.parse(response.body)['pug']
end
end
files.each do |file|
ConvertingFile.new(file).convert!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment