Module: Hx::CLI

Defined in:
lib/hx/cli.rb

Constant Summary collapse

DEFAULT_CONFIG_FILENAME =
"config.hx"

Class Method Summary collapse

Class Method Details

._parse_entry_spec(site, entry_spec) ⇒ Object

Raises:

  • (ArgumentError)


174
175
176
177
178
179
# File 'lib/hx/cli.rb', line 174

def self._parse_entry_spec(site, entry_spec)
  source_name, path = entry_spec.split(':', 2)
  source = site.sources[source_name]
  raise ArgumentError, "No such source #{source_name}" unless source
  return source, path
end

.cmd_dump(site, entry_spec) ⇒ Object



214
215
216
217
218
219
220
221
# File 'lib/hx/cli.rb', line 214

def self.cmd_dump(site, entry_spec)
  source, selector = parse_entry_pattern(site, entry_spec)
  items = []
  source.each_entry(selector) do |path, entry|
    items << {path => entry}
  end
  puts YAML.dump(items)
end

.cmd_edit(site, entry_spec) ⇒ Object



194
195
196
197
# File 'lib/hx/cli.rb', line 194

def self.cmd_edit(site, entry_spec)
  source, path = parse_entry_spec(site, entry_spec)
  do_edit(site, source, path, nil)
end

.cmd_editup(site, entry_spec) ⇒ Object



164
165
166
167
# File 'lib/hx/cli.rb', line 164

def self.cmd_editup(site, entry_spec)
  cmd_edit(site, entry_spec)
  cmd_upgen(site)
end

.cmd_list(site, entry_spec) ⇒ Object



209
210
211
212
# File 'lib/hx/cli.rb', line 209

def self.cmd_list(site, entry_spec)
  source, selector = parse_entry_pattern(site, entry_spec)
  source.each_entry_path(selector) { |path| puts path }
end

.cmd_post(site, entry_spec) ⇒ Object



199
200
201
202
203
204
205
206
207
# File 'lib/hx/cli.rb', line 199

def self.cmd_post(site, entry_spec)
  source, path = parse_entry_spec(site, entry_spec)
  prototype = {
    'title' => Hx.make_default_title(site.options, path),
    'author' => Hx.get_default_author(site.options),
    'content' => ""
  }
  do_edit(site, source, path, prototype)
end

.cmd_postup(site, entry_spec) ⇒ Object



169
170
171
172
# File 'lib/hx/cli.rb', line 169

def self.cmd_postup(site, entry_spec)
  cmd_post(site, entry_spec)
  cmd_upgen(site)
end

.cmd_regen(site) ⇒ Object



138
139
140
# File 'lib/hx/cli.rb', line 138

def self.cmd_regen(site)
  do_gen(site, false)
end

.cmd_serve(site, port = nil) ⇒ Object



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/hx/cli.rb', line 104

def self.cmd_serve(site, port=nil)
  Socket.do_not_reverse_lookup = true
  server = WEBrick::HTTPServer.new({:Port => port || 0})
  real_port = server.config[:Port]

  base_url = "http://localhost:#{real_port}/"
  server.logger.info "Serving on #{base_url}"

  config_file = site.options[:config_file]

  reload_lock = Mutex.new
  site_app = nil
  mtime = nil

  app = Proc.new { |env|
    reload_lock.synchronize {
      unless File.mtime(config_file) == mtime
        # reload the site/config, folding in the new base URL
        site = Hx::Site.load_file(config_file, :base_url => base_url)
        mtime = File.mtime(config_file)
        site_app = Hx::Rack::Application.new(site, site.options)
      end
      site_app
    }.call(env)
  }

  # force application load
  ::Rack::MockRequest.new(app).get("/")

  server.mount('/', ::Rack::Handler::WEBrick, app)
  %w(INT TERM).each { |s| trap(s) { server.shutdown } }
  server.start
end

.cmd_upgen(site) ⇒ Object



142
143
144
# File 'lib/hx/cli.rb', line 142

def self.cmd_upgen(site)
  do_gen(site, true)
end

.do_edit(site, source, path, prototype) ⇒ Object



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/hx/cli.rb', line 223

def self.do_edit(site, source, path, prototype)
  catch(:unchanged) do
    begin
      tempfile = Tempfile.new('hx-entry')
      original_text = nil
      loop do
        begin
          source.edit_entry(path, prototype) do |text|
            unless original_text
              File.open(tempfile.path, 'w') { |s| s << text }
              original_text = text
            end
            # TODO: deal with conflict if text != original_text
            editor = ENV['EDITOR'] || 'vi'
            system(editor, tempfile.path)
            new_text = File.open(tempfile.path, 'r') { |s| s.read }
            throw(:unchanged) if new_text == text
            new_text
          end
          break
        rescue Exception => e
          $stderr.puts e
          $stderr.print "Edit failed; retry? [Yn] "
          $stderr.flush
          response = $stdin.gets.strip
          raise unless response =~ /^y/i
        end
      end
    ensure
      tempfile.unlink
    end
  end
end

.do_gen(site, update_only) ⇒ Object



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/hx/cli.rb', line 146

def self.do_gen(site, update_only)
  output_dir = Hx.get_pathname(site.options, :output_dir)
  Hx.cache_scope do
    site.each_entry(Path::ALL) do |path, entry|
      pathname = output_dir + path
      content = entry['content']
      if update_only
        update_time = entry['updated']
      else
        update_time = nil
      end
      written = Hx.refresh_file(pathname, content, update_time,
                                entry['executable'])
      puts "===> #{path}" if written
    end
  end
end

.main(*args) ⇒ Object



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
# File 'lib/hx/cli.rb', line 41

def self.main(*args)
  options = OpenStruct.new
  options.config_file = nil

  OptionParser.new do |opts|
    opts.banner = <<EOS
Usage: hx [--config CONFIG_FILE] [upgen]
       hx [--config CONFIG_FILE] regen
       hx [--config CONFIG_FILE] post[up] SOURCE:PATH
       hx [--config CONFIG_FILE] edit[up] SOURCE:PATH
       hx [--config CONFIG_FILE] list SOURCE[:PATTERN]
       hx [--config CONFIG_FILE] dump SOURCE[:PATTERN]
       hx [--config CONFIG_FILE] serve [PORT]

EOS

    opts.on("-c", "--config CONFIG_FILE",
            "Use CONFIG_FILE instead of searching for " +
            DEFAULT_CONFIG_FILENAME) \
    do |config_file|
      options.config_file = Pathname.new(config_file)
    end

    opts.on_tail("-h", "--help", "Show this usage information") do
      puts opts
      return
    end

    opts.on_tail("-v", "--version", "Output the version (#{Hx::VERSION})") do
      puts Hx::VERSION
      return
    end

    opts.parse!(args)
  end

  options.config_file ||= ENV['HX_CONFIG']

  unless options.config_file
    Pathname.getwd.ascend do |ancestor|
      filename = ancestor + DEFAULT_CONFIG_FILENAME
      if filename.exist?
        options.config_file = filename
        break
      end
    end
    unless options.config_file
      raise RuntimeError, "No #{DEFAULT_CONFIG_FILENAME} found"
    end
  end

  site = Hx::Site.load_file(options.config_file)

  subcommand = args.shift || "upgen"
  method_name = "cmd_#{subcommand}".intern
  begin
    m = method(method_name)
  rescue NameError
    raise ArgumentError, "Unrecognized subcommand: #{subcommand}"
  end
  m.call(site, *args)
end

.parse_entry_pattern(site, entry_pattern) ⇒ Object



187
188
189
190
191
192
# File 'lib/hx/cli.rb', line 187

def self.parse_entry_pattern(site, entry_pattern)
  source, pattern = _parse_entry_spec(site, entry_pattern)
  pattern = "**" unless pattern
  selector = Hx::Path.parse_pattern(pattern)
  return source, selector
end

.parse_entry_spec(site, entry_spec) ⇒ Object



181
182
183
184
185
# File 'lib/hx/cli.rb', line 181

def self.parse_entry_spec(site, entry_spec)
  source, path = _parse_entry_spec(site, entry_spec)
  raise "Invalid entry specification #{entry_spec}" unless path
  return source, path
end