summaryrefslogtreecommitdiff
path: root/lib/jive/issue.rb
blob: 4796a47b5406cf67fa94c5b9c72f09feb4db1b7a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# frozen_string_literal: true

module Jive
  class Issue
    class << self
      def what_type?
        Jive.prompt?(
          Jive.root
            .join("lib/jive/templates")
            .glob("*.md")
            .map { |x| x.basename.to_s.gsub(".md", "") }
        )
      end

      def create!(name:, type:, repo: Repo.current)
        new(repo: repo, name: name, type: type)
      end

      def for(type, repo: Repo.current)
        dir_for(type, repo: repo).glob("*.md").map do |x|
          name = x.basename.to_s.gsub(".md", "")
          new(repo: repo, name: name, type: type)
        end
      end

      def dir_for(type, repo: Repo.current)
        Jive.home
            .join(repo.uri.host)
            .join(repo.nwo)
            .join(type)
      end
    end

    def initialize(name:, type:, repo: Repo.current)
      @repo = repo
      @type = type
      @name = name
    end

    def file_name
      "#{name.gsub(/[^a-z0-9\-_]+/i, "-").downcase}.md"
    end

    def edit(editor: ENV["EDITOR"])
      Jive.shell.execute([editor, issue.to_s])
    end

    private

    attr_reader :repo, :name, :type

    def issue
      @issue ||=
        begin
          dir = self.class.dir_for(type, repo: repo)
          Jive.shell.execute([:mkdir, "-p", dir])
          dir.join(file_name).tap do |file|
            file.write(template_for(type).read) unless file.exist?
          end
        end
    end

    def template_for(type)
      Jive.root.join("lib/jive/templates/#{type}.md")
    end
  end
end