# frozen_string_literal: true require "open-uri" require "fileutils" require "trellodon/formatters/base" module Trellodon module Formatters class Markdown < Base attr_reader :output_dir def initialize(output_dir:, **opts) super(**opts) @output_dir = output_dir end def card_added(card) card_mdfile = File.join(card_path(card), "index.md") raise "File #{card_mdfile} already exists" if File.exist?(card_mdfile) File.write(card_mdfile, format_card(card)) download_attachments(card) end def finish logger.info "Markdown dump is here: #{@output_dir}" end private def card_path(card) raise "Board is undefined" if @board.nil? raise "List id is undefined" if card.list_id.nil? || card.list_id.empty? list = @board.get_list(card.list_id) raise "List #{card.list_id} is not found" if list.nil? card_dir = File.join(@output_dir, "#{board.name} [#{board.short_id}]", "#{list.name} [#{list.short_id}]", "#{card.name} [#{card.short_id}]") FileUtils.mkdir_p(card_dir) unless File.directory?(card_dir) card_dir end def card_attachments_path(card) attachments_dir = File.join(card_path(card), "attachments") FileUtils.mkdir_p(attachments_dir) unless File.directory?(attachments_dir) attachments_dir end def download_attachments(card) return # FIXME: 401 Unauthorized ??? return if card.attachments.nil? || card.attachments.empty? # rubocop:disable Lint/UnreachableCode attachments_path = card_attachments_path(card) card.attachments.each do |att| IO.copy_stream(URI.parse(att.url).open, File.join(attachments_path, att.file_name)) end end def format_card(card) create_card_header(card) + create_card_title(card) + create_card_description(card) + create_card_comments(card) end def create_card_header(card) <<~EOS --- title: #{card.name} last_updated_at: #{card.last_activity_date} labels: #{create_card_labels(card)} --- EOS end def create_card_title(card) <<~EOS # #{card.name} EOS end def create_card_description(card) <<~EOS ## Description #{card.desc} EOS end def create_card_labels(card) return "" if card.labels.nil? || card.labels.empty? card.labels.map { |label| "\n - " + label }.reduce(:+) end def create_card_comments(card) return "" if card.comments.nil? || card.comments.empty? <<~EOS ## Comments #{card.comments.map { |comment| create_card_comment(comment) }.reduce(:+)} EOS end def create_card_comment(comment) <<~EOS **#{comment.creator_id} @ #{comment.date}** #{comment.text} EOS end end end end