Skip to content

Instantly share code, notes, and snippets.

@kazuph kazuph/esa2esa.rb
Last active Mar 23, 2017

Embed
What would you like to do?
esaを一度解約したが、再度使い始めたときに使うスクリプト(ExportデータをそのままImport)
#!/usr/bin/env ruby
# coding : utf-8
require 'esa'
require 'yaml'
class Importer
attr_accessor :client, :files
def initialize(client, dir_path)
@client = client
@files = Dir.glob File.expand_path(File.join(dir_path, '**/*'))
end
def import(dry_run: true, start_index: 0)
files.sort.each.with_index do |file, index|
next unless File::ftype(file) == "file"
next unless index >= start_index
md = File.read(file)
# 先頭の記事情報をパースして本文と分離する
md =~ /\A---(.+?)---(.+?)\z/m
md_info = YAML.load $1
md_body = $2.gsub(/\/<OLD_ORGANIZATION_ID>/, '/<NEW_ORGANIZATION_ID>') # 画像のファイル名が変わるはずなので置換
params = {
name: md_info["title"],
category: md_info["category"],
tags: md_info["tags"],
body_md: md_body,
wip: !md_info["published"], # wipと対応(論理反転)
message: '[skip notice] Imported from API',
user: 'esa_bot', # 記事作成者上書き: owner権限が必要
}
if dry_run
puts "***** index: #{index} *****"
pp params
puts
next
end
print "[#{Time.now}] index[#{index}] #{params['name']} => "
response = client.create_post(params)
case response.status
when 201
puts "created: #{response.body["full_name"]}"
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}"
exit 1
end
end
end
private
def wait_for(seconds)
(seconds / 10).times do
print '.'
sleep 10
end
puts
end
end
client = Esa::Client.new(
access_token: '<YOUR_API_KEY>',
current_team: '<YOUR_DOMAIN>', # 移行先のチーム名(サブドメイン)
)
importer = Importer.new(client, '<DIR>')
# dry_run: trueで確認後に dry_run: falseで実際にimportを実行
importer.import(dry_run: true, start_index: 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.