Class: Mail2FrontMatter::Committer

Inherits:
Object
  • Object
show all
Defined in:
lib/mail2frontmatter/committer.rb

Class Method Summary collapse

Class Method Details

.available?Boolean

Returns:

  • (Boolean)


14
15
16
# File 'lib/mail2frontmatter/committer.rb', line 14

def self.available?
  @@available
end

.commit(metadata, _body) ⇒ Object



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
# File 'lib/mail2frontmatter/committer.rb', line 18

def self.commit(, _body)
  repo = Rugged::Repository.new(Mail2FrontMatter.config[:git][:path])
  index = repo.index

  # stage frontmatter/erb
  relative_path = [:filepath].gsub(Mail2FrontMatter.config[:git][:path] + '/', '')

  index.add(path: relative_path,
            oid: (Rugged::Blob.from_workdir repo, relative_path),
            mode: 0100644)

  # stage attachments
  [:attachments].each_pair do |_k, filemeta|
    relative_path = filemeta[:filepath].gsub(Mail2FrontMatter.config[:git][:path] + '/', '')

    index.add(path: relative_path,
              oid: (Rugged::Blob.from_workdir repo, relative_path),
              mode: 0100644)
  end

  # commit
  tree = index.write_tree(repo)
  index.write

  author = {
    email: Mail2FrontMatter.config[:git][:email] || [:from].match(/\<(.*)\>/)[1],
    name:  Mail2FrontMatter.config[:git][:name]  || [:from].match(/(.*) \<.*\>/)[1],
    time:  Time.now
  }

  Rugged::Commit.create(repo, author:     author,
                              committer:  author,
                              message:    "post via email, #{[:subject]}",
                              parents:    [repo.head.target],
                              tree:       tree,
                              update_ref: 'HEAD')

  # push
  begin
    credentials = Rugged::Credentials::SshKeyFromAgent.new(username: 'git')
    repo.push 'origin', ['refs/heads/master'], { credentials: credentials }
  rescue StandardError => e
    Mail2FrontMatter.logger.info("Could not push!")
    Mail2FrontMatter.logger.error(e)
  end

  # return sha
  repo.references['refs/heads/master'].target_id
end