[Ruby] post to Qiita patching version

1 minute read

Version to update the article already posted on qiita

There is a record of creating the version to be posted first. In addition, it is a version that updates the article already posted on qiita. Code below

ruby post_final.rb post_final.org 

You can do something. In the first post, create a new one, and then write the id of items in org. If it exists, it will patch its id.

In addition, you can select’open’,’ teams’. default is’private’.

ruby post_final.rb post_final.org teams

What?

key is

-I made a package to export Qiita compliant Markdown from Org-mode

code

require "net/https"
require "json"

def get_title_tags(src)
  $conts = File.read(src)
  title =  $conts.match(/\#\+(TITLE|title|Title): (.+)/)[2] || "test"
  m = []
  tags = if m =  $conts.match(/\#\+(TAG|tag|Tag|tags|TAGS|Tags): (.+)/)
	   m[2].split(',').inject([]) do |l, c|
      l << {name: c.strip} #, versions: []}
    end
	 else
	   [{ name: "hoge"}] #, versions: [] }]
	 end
  p tags
  return title,tags
end

src = ARGV[0] || 'README.org'
title, tags = get_title_tags(src)
p title
p tags

system "emacs #{src} --batch -l ~/.emacs.d/site_lisp/ox-qmd -f org-qmd-export-to-markdown --kill"

lines = File.readlines(src.gsub('org','md'))

m = []
patch = false
if m = $conts.match(/\#\+qiita_id: (.+)/)
  qiita_id = m[1]
  patch = true
else
  qiita_id = ''
end


case ARGV[1]
when 'teams'
  qiita = 'https://nishitani.qiita.com/'
  access_token = ENV['QIITA_TEAM_WRITE_TOKEN']
  private = false
when 'open'
  qiita = 'https://qiita.com/'
  access_token = ENV['QIITA_WRITE_TOKEN']
  private = false
else
  qiita = 'https://qiita.com/'
  access_token = ENV['QIITA_WRITE_TOKEN']
  private = true
end

params = {
  "body": lines.join, #"#test",
  "private": private,
  "title": title,
  "tags": tags
}

if patch
  path = "api/v2/items/#{qiita_id}"
else
  path = 'api/v2/items'
end
p qiita+path
uri = URI.parse(qiita+path)

http_req = Net::HTTP.new(uri.host, uri.port)
http_req.use_ssl = uri.scheme === "https"

headers = {"Authorization" => "Bearer #{access_token}",
  "Content-Type" => "application/json"}
if patch
  res = http_req.patch(uri.path, params.to_json, headers)
else
  res = http_req.post(uri.path, params.to_json, headers)
end

p res.message

res_body = JSON.parse(res.body)
res_body.each do |key, cont|
  if key == 'rendered_body' or key == 'body'
    puts "%20s brabrabra..." % key
    next
  end
  print "%20s %s\n" % [key, cont]
end
system "open #{res_body["url"]}"
qiita_id =res_body["id"]
unless patch
  File.write(src,"#+qiita_id: #{qiita_id}\n"+$conts)
end

Well, please refactor.

Task

If you want to put it in two places with open and teams, you will not know which is which. I wonder if it can be updated automatically around that point. .. ..