Created
March 11, 2018 10:04
-
-
Save kaibadash/c24235708c296db1589ee1ba2edf4563 to your computer and use it in GitHub Desktop.
Import exported esa markdowns to new esa team
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'esa' | |
require 'pp' | |
require 'find' | |
class EsaExportedMarkdown | |
attr_reader :title, :category, :tags, :created_at, :updated_at, :published, :number, :body | |
INDEX_DATA_START = 1 | |
INDEX_DATA_END = 7 | |
INDEX_BODY_START = 10 | |
def initialize(file_path) | |
File.open(file_path) do |file| | |
md = file.read | |
key_vals = md.split("\n")[INDEX_DATA_START..INDEX_DATA_END] | |
key_vals.each do |key_val| | |
if /^(?<key>.+): \"?(?<val>.+?)\"?$/ =~ key_val | |
instance_variable_set("@#{key}".to_sym, val) | |
end | |
end | |
@body = md.split("\n")[INDEX_BODY_START..-1].join("\n") | |
end | |
end | |
def to_params | |
{ | |
name: title, | |
category: category, | |
tags: tags, | |
body_md: body, | |
wip: false, | |
message: '[skip notice] Imported from other esa', | |
# user: 'hoge', # need owner rights to override user | |
} | |
end | |
end | |
class Importer | |
def initialize(client, dir, base_cat = '') | |
@client = client | |
@dir = dir | |
@base_cat = base_cat | |
end | |
attr_accessor :client, :dir, :base_cat | |
def wait_for(seconds) | |
(seconds / 10).times do | |
print '.' | |
sleep 10 | |
end | |
puts | |
end | |
def import(dry_run: true) | |
Find.find(dir) do |file_path| | |
next unless file_path.end_with?('.md') | |
params = EsaExportedMarkdown.new(file_path).to_params | |
params[:category] = "#{base_cat}/#{params[:category]}" if base_cat != '' | |
if dry_run | |
puts "***** #{file_path} *****" | |
pp params | |
puts | |
next | |
end | |
puts "start #{file_path}" | |
response = client.create_post(params) | |
case response.status | |
when 201 | |
puts "created: #{response.body['full_name']}" | |
sleep 5 | |
when 429 | |
retry_after = (response.headers['Retry-After'] || 20 * 60).to_i | |
puts "rate limit exceeded: will retry after #{retry_after} seconds." | |
wait_for(retry_after) | |
redo | |
else | |
puts "failure with status: #{response.status} #{response.inspect}" | |
exit 1 | |
end | |
end | |
end | |
end | |
client = Esa::Client.new( | |
access_token: 'your secret token', | |
current_team: 'dst_team' # destination of sub domain | |
) | |
importer = Importer.new(client, 'exported_dir', 'dest/product') | |
# remove dry_run after test | |
importer.import(dry_run: false) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment