~julienxx/atomini

atomini/atomini.rb -rw-r--r-- 2.0 KiB
53c408bd — Julien Blanchard Add LICENSE 1 year, 5 months ago
                                                                                
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/usr/bin/env ruby

require 'yaml'
require 'rss'

CONFIG_KEYS = %w[author title base_url feed_url].freeze
LINK_REGEXP = /^=>\s*(\S*)\s*(.*)?$/.freeze

def usage
  printf <<~USAGE_MESSAGE
    atomini - generate an atom feed from a gemini map in the current directory.

    Usage: atomini config_file gemini_map
  USAGE_MESSAGE

  exit(1)
end

def validate_args
  return usage unless ARGV[0] && ARGV[1]
end

def validate_config
  CONFIG_KEYS.each do |key|
    if config[key].nil?
      puts "Missing #{key} entry in your config file."
      exit(1)
    end
  end
end

def config_file
  ARGV[0]
end

def source_file
  ARGV[1]
end

def base_path
  File.expand_path(File.dirname(source_file))
end

def author
  config['author']
end

def title
  config['title']
end

def feed_url
  config['feed_url']
end

def base_url
  config['base_url']
end

def config
  YAML.load_file(config_file)
end

def links
  [].tap do |links|
    File.open(source_file, 'r') do |f|
      f.each_line do |line|
        match = line.match(LINK_REGEXP)
        next unless match
        next if match[1].include?('://')

        links << { link: match[1],
                   title: match[2],
                   timestamp: File.mtime(base_path + '/' + match[1]) }
      end
    end
  end
end

def generate_atom_feed
  atom_feed = RSS::Maker.make('atom') do |maker|
    maker.channel.author = config['author']
    maker.channel.updated = links.max_by { |link| link[:timestamp] }[:timestamp]
    maker.channel.about = config['feed_url']
    maker.channel.title = config['title']

    links.each do |link_line|
      maker.items.new_item do |item|
        item.link = base_url + '/' + link_line[:link]
        item.title = link_line[:title]
        item.updated = link_line[:timestamp]
      end
    end
  end

  atom_feed
end

def write_file(atom_feed)
  File.open('feed.xml', 'w') { |f| f.write atom_feed }
end

def run
  validate_args
  validate_config
  atom_feed = generate_atom_feed
  write_file(atom_feed)

  exit(0)
end

run