Module: RuneBlog::REPL

Defined in:
lib/helpers-repl.rb,
lib/repl.rb

Constant Summary collapse

Patterns =
{"help"              => :cmd_help, 
  "h"                 => :cmd_help,
  "version"           => :cmd_version,
  "v"                 => :cmd_version,
  "list views"        => :cmd_list_views, 
  "lsv"               => :cmd_list_views, 
  "clear"             => :cmd_clear,

  "new view $name"    => :cmd_new_view,

  "tags"              => :cmd_tags,
  "import"            => :cmd_import,

  "new post"          => :cmd_new_post,
  "p"                 => :cmd_new_post,
  "post"              => :cmd_new_post,

  "change view $name" => :cmd_change_view,
  "cv $name"          => :cmd_change_view,
  "cv"                => :cmd_change_view,  # 0-arity must come second

  "config"            => :cmd_config,
  "manage $widget"    => :cmd_manage,

  "legacy"            => :cmd_legacy,

  "list posts"        => :cmd_list_posts,
  "lsp"               => :cmd_list_posts,

  "list drafts"       => :cmd_list_drafts,
  "lsd"               => :cmd_list_drafts,

  "list assets"       => :cmd_list_assets,
  "lsa"               => :cmd_list_assets,

  "pages"             => :cmd_pages,

  "delete >postid"    => :cmd_remove_post,
  "undel $postid"     => :cmd_undelete_post,

  "edit $postid"      => :cmd_edit_post,
  "ed $postid"        => :cmd_edit_post,
  "e $postid"         => :cmd_edit_post,

  "preview"           => :cmd_preview,

  "browse"            => :cmd_browse,

  "rebuild"           => :cmd_rebuild,

  "publish"           => :cmd_publish,

  "ssh"               => :cmd_ssh,

  "q"                 => :cmd_quit,
  "quit"              => :cmd_quit
}
Abbr =
{
"h"                 => :cmd_help,
"v"                 => :cmd_version,
"lsv"               => :cmd_list_views, 
"p"                 => :cmd_new_post,
"cv $name"          => :cmd_change_view,
"cv"                => :cmd_change_view,  # 0-arity must come second
"lsp"               => :cmd_list_posts,
"lsd"               => :cmd_list_drafts,
"list assets"       => :cmd_list_assets,
"lsa"               => :cmd_list_assets,
"rm $postid"        => :cmd_remove_post,
"ed $postid"        => :cmd_edit_post,
"e $postid"         => :cmd_edit_post,
"q"                 => :cmd_quit
}
Regexes =
{}
Help =
<<-EOS

{Basics:}                                         {Views:}
-------------------------------------------       -------------------------------------------
{h, help}           This message                  {change view VIEW}  Change current view
{q, quit}           Exit the program              {cv VIEW}           Change current view
{v, version}        Print version information     {new view}          Create a new view
{clear}             Clear screen                  {list views}        List all views available
                                                  {lsv}               Same as: list views
                 

{Posts:}                                          {Advanced:}
-------------------------------------------       -------------------------------------------
{p, post}           Create a new post             {config}            Edit various system files
{new post}          Same as p, post                
{lsp, list posts}   List posts in current view    {preview}           Look at current (local) view in browser
{lsd, list drafts}  List all drafts (all views)   {browse}            Look at current (published) view in browser
{delete ID [ID...]} Remove multiple posts         {rebuild}           Regenerate all posts and relink
{undelete ID}       Undelete a post               {publish}           Publish (current view)
{edit ID}           Edit a post                   {ssh}               Login to remote server
{import ASSETS}     Import assets (images, etc.)  {manage WIDGET}     Manage content/layout of a widget
EOS

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.choose_method(cmd) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/helpers-repl.rb', line 99

def self.choose_method(cmd)
  cmd = cmd.strip
  found = nil
  params = nil
  Regexes.each_pair do |rx, meth|
    m = cmd.match(rx)
    result = m ? m.to_a : nil
    next unless result
    found = meth
    params = m[1]
  end
  meth = found || :cmd_INVALID
  params = cmd if meth == :cmd_INVALID
  result = [meth]
  result << params unless params.nil?
  result
end

Instance Method Details



118
119
120
121
122
# File 'lib/repl.rb', line 118

def _manage_links
  dir = @blog.view.dir/"themes/standard/widgets/links"
  data = dir/"list.data"
  edit_file(data)
end

#_manage_navbarObject

cloned from manage_pages



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/repl.rb', line 89

def _manage_navbar   # cloned from manage_pages
  dir = @blog.view.dir/"themes/standard/banner/navbar"
  files = Dir.entries(dir) - %w[. .. navbar.lt3]
  main_file = "[ navbar.lt3 ]"
  new_item  = "  [New item]  "
  files = [main_file] + files + [new_item]
  num, fname = STDSCR.menu(title: "Edit navbar:", items: files)
  return if fname.nil?
  case fname
    when new_item
      print "Page title:  "
      title = RubyText.gets
      title.chomp!
      print "File name (.lt3): "
      fname = RubyText.gets
      fname << ".lt3" unless fname.end_with?(".lt3")
      new_file = dir/fname
      File.open(new_file, "w") do |f|
        f.puts "<h1>#{title}</h1>\n\n\n "
        f.puts ".backlink"
      end
      edit_file(new_file)
    when main_file
      edit_file(main_file[2..-3])
  else
    edit_file(dir/fname)
  end
end

#_manage_pagesObject



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/repl.rb', line 124

def _manage_pages
  dir = @blog.view.dir/"themes/standard/widgets/pages"
  # Assume child files already generated (and list.data??)
  data = dir/"list.data"
  lines = _get_data?(data)
  hash = {}
  lines.each do |line|
    url, name = line.chomp.split(",")
    source = url.sub(/.html$/, ".lt3")
    hash[name] = source
  end
  new_item = "[New page]"
  num, fname = STDSCR.menu(title: "Edit page:", items: hash.keys + [new_item])
  return if fname.nil?
  if fname == new_item
    print "Page title:  "
    title = RubyText.gets
    title.chomp!
    print "File name (.lt3): "
    fname = RubyText.gets
    fname << ".lt3" unless fname.end_with?(".lt3")
    fhtml = fname.sub(/.lt3$/, ".html")
    File.open(data, "a") {|f| f.puts "#{fhtml},#{title}" }
    new_file = dir/fname
    File.open(new_file, "w") do |f|
      f.puts "<h1>#{title}</h1>\n\n\n "
      f.puts ".backlink"
    end
    edit_file(new_file)
  else
    target = hash[fname]
    edit_file(dir/target)
  end
end

#_manage_pinnedObject

cloned from manage_links



83
84
85
86
87
# File 'lib/repl.rb', line 83

def _manage_pinned   # cloned from manage_links
  dir = @blog.view.dir/"themes/standard/widgets/pinned"
  data = dir/"list.data"
  edit_file(data)
end

#_remove_post(arg, testing = false) ⇒ Object



293
294
295
296
297
# File 'lib/repl.rb', line 293

def _remove_post(arg, testing=false)
  id = get_integer(arg)
  result = @blog.remove_post(id)
  puts "Post #{id} not found" if result.nil?
end

#all_tagsObject



157
158
159
160
161
# File 'lib/helpers-repl.rb', line 157

def all_tags
  all = []
  @blog.views.each {|view| all.append(*tags_for_view(view)) }
  all.sort + ["NEW TAG"]
end

#ask(prompt, meth = :to_s) ⇒ Object



117
118
119
120
# File 'lib/helpers-repl.rb', line 117

def ask(prompt, meth = :to_s)
  print prompt
  gets.chomp.send(meth)
end

#ask!(prompt, meth = :to_s) ⇒ Object



122
123
124
# File 'lib/helpers-repl.rb', line 122

def ask!(prompt, meth = :to_s)
  ask(fx(prompt, :bold), meth)
end

#check_file_exists(file) ⇒ Object



132
133
134
# File 'lib/helpers-repl.rb', line 132

def check_file_exists(file)
  raise FileNotFound(file) unless File.exist?(file)
end

#cmd_browseObject



164
165
166
167
168
169
170
171
172
173
# File 'lib/repl.rb', line 164

def cmd_browse
  url = @blog.view.publisher.url
  if url.nil?   
    puts "\n  Publish first."
    return
  end
  result = system!("open '#{url}'")
  raise CantOpen(url) unless result
  return
end

#cmd_change_view(arg = nil) ⇒ Object



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/repl.rb', line 244

def cmd_change_view(arg = nil)
  if arg.nil?
    viewnames = @blog.views.map {|x| x.name }
    n = viewnames.find_index(@blog.view.name)
    name = @blog.view.name
    # TODO: Add view description 
    k, name = STDSCR.menu(title: "Views", items: viewnames, curr: n)
    return if name.nil?
    @blog.view = name
    puts "\n  ", fx(name, :bold), "\n"
    return
  else
    if @blog.view?(arg)
      @blog.view = arg
      puts "\n  ", fx(arg, :bold), "\n"
    end
  end
end

#cmd_clearObject



35
36
37
38
39
# File 'lib/repl.rb', line 35

def cmd_clear
  STDSCR.rows.times { puts " "*(STDSCR.cols-1) }
  # sleep 0.1
  STDSCR.clear
end

#cmd_configObject



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
# File 'lib/repl.rb', line 45

def cmd_config
  hash = {"Variables (general)"                 => "global.lt3",
          "   View-specific"                    => "../../settings/view.txt",
          "   Recent posts"                     => "../../settings/recent.txt",
          "   Publishing"                       => "../../settings/publish.txt",
          "Configuration: enable/disable"       => "../../settings/features.txt",
          "   Reddit"                           => "../../config/reddit/credentials.txt",
          "   Facebook"                         => "../../config/facebook/credentials.txt",
          "   Twitter"                          => "../../config/twitter/credentials.txt",
          "View: generator"                     => "blog/generate.lt3",
          "   HEAD info"                        => "blog/head.lt3",
          "   Layout "                          => "blog/index.lt3",
          "   Recent-posts entry"               => "blog/post_entry.lt3",
          "   Banner: Description"              => "blog/banner.lt3",
          "      Text portion"                  => "banner/top.lt3",
          "Generator for a post"                => "post/generate.lt3",
          "   HEAD info for post"               => "post/head.lt3",
          "   Content for post"                 => "post/index.lt3",
          "Global CSS"                          => "etc/blog.css.lt3",
          "External JS/CSS (Bootstrap, etc.)"   => "/etc/externals.lt3"
         }

  dir = @blog.view.dir/"themes/standard/"
  num, target = STDSCR.menu(title: "Edit file:", items: hash)
  edit_file(dir/target)
end

#cmd_edit_post(arg) ⇒ Object



308
309
310
311
312
313
314
315
316
317
318
319
# File 'lib/repl.rb', line 308

def cmd_edit_post(arg)
  id = get_integer(arg)
  # Simplify this
  tag = "#{'%04d' % id}"
  files = ::Find.find(@blog.root/:drafts).to_a
  files = files.grep(/#{tag}-.*lt3/)
  draft = exactly_one(files)
  result = edit_file(draft, vim: '-c$')
  @blog.generate_post(draft)
rescue => err
  _tmp_error(err)
end

#cmd_helpObject



475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# File 'lib/repl.rb', line 475

def cmd_help
  msg = Help
  msg.each_line do |line|
    e = line.each_char
    first = true
    loop do
      s1 = ""
      c = e.next
      if c == "{"
        s2 = first ? "" : "  "
        first = false
        loop do 
          c = e.next
          break if c == "}"
          s2 << c
        end
        print fx(s2, :bold)
        s2 = ""
      else
        s1 << c
      end
      print s1
    end
  end
  puts
end

#cmd_importObject



159
160
161
162
# File 'lib/repl.rb', line 159

def cmd_import
  files = ask("\n  File(s) = ")
  system!("cp #{files} #{@blog.root}/views/#{@blog.view.name}/assets/")
end

#cmd_INVALID(arg) ⇒ Object



411
412
413
414
415
# File 'lib/repl.rb', line 411

def cmd_INVALID(arg)
  print fx("\n  Command ", :bold)
  print fx(arg, Red, :bold)
  puts fx(" was not understood.\n ", :bold)
end

#cmd_legacyObject



417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# File 'lib/repl.rb', line 417

def cmd_legacy
  dir = "sources/computing"
  puts "Importing from: #{dir}"
  files = Dir[dir/"**"]
  files.each do |fname|
    name = fname
    cmd = "grep ^.title #{name}"
    grep = `#{cmd}`   # find .title
    @title = grep.sub(/^.title /, "")
    num = `grep ^.post #{name}`.sub(/^.post /, "").to_i
    seq = @blog.get_sequence
    tnum = File.basename(fname).to_i

    raise "num != seq + 1" if num != seq + 1
    raise "num != tnum" if num != tnum
    seq = @blog.next_sequence
    raise "num != seq" if num != seq

    label = '%04d' % num
    slug0 = @title.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')
    @slug = "#{label}-#{slug0}"
    @fname = @slug + ".lt3"
    cmd = "cp #{name} #{@blog.root}/drafts/#@fname"
    result = system!(cmd)
    raise CantCopy(name, "#{@blog.root}/drafts/#@fname") unless result
    # post = Post.load(@slug)
    draft = "#{@blog.root}/drafts/#@fname"
    @meta = @blog.generate_post(draft)
    puts
    sleep 2
  end
rescue => err
  error(err)
end

#cmd_list_assetsObject



387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# File 'lib/repl.rb', line 387

def cmd_list_assets
  dir = @blog.view.dir + "/assets"
  assets = Dir[dir + "/*"]
  if assets.empty?
    puts "  No assets"
    return
  else
    puts
    assets.each do |name| 
      asset = File.basename(name)
      puts "  ", fx(asset, Blue)
    end
  end
  puts
end

#cmd_list_draftsObject



362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/repl.rb', line 362

def cmd_list_drafts
  curr_drafts = @blog.drafts  # current view
  if curr_drafts.empty?
    puts "\n  No drafts\n "
    return
  else
    puts
    curr_drafts.each do |draft| 
      base = draft.sub(/.lt3$/, "")
      dir = @blog.root/:posts/base
      meta = nil 
      Dir.chdir(dir) { meta = @blog. }
      num, title = meta.num, meta.title
      num = '%4d' % num.to_s
      puts "  ", fx(num, Red), "  ", fx(title, Black)
      other = @blog._get_views(@blog.root/:drafts/draft) - [@blog.view.to_s]
      unless other.empty?
        print fx(" "*9 + "also in: ", Bold) 
        puts other.join(", ") 
      end
    end
  end
  puts
end

#cmd_list_postsObject



336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/repl.rb', line 336

def cmd_list_posts
  posts = @blog.posts  # current view
  str = @blog.view.name + ":\n"
  puts
  if posts.empty?
    puts "  No posts"
  else
    posts.each do |post| 
      base = post.sub(/.lt3$/, "")
      dir = @blog.root/:posts/base
      meta = nil 
      Dir.chdir(dir) { meta = @blog. }
      num, title = meta.num, meta.title
      num = '%4d' % num.to_s
      puts "  ", fx(num, Red), "  ", fx(title, Black)
      draft = @blog.root/:drafts/post + ".lt3"
      other = meta.views - [@blog.view.to_s]
      unless other.empty?
        print fx(" "*9 + "also in: ", :bold) 
        puts other.join(", ") 
      end
    end
  end
  puts
end

#cmd_list_viewsObject



321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/repl.rb', line 321

def cmd_list_views
  puts
  @blog.views.each do |v| 
    v = v.to_s
    v = fx(v, :bold) if v == @blog.view.name
    # FIXME: next 3 lines are crufty as hell
    lines = File.readlines(@blog.root/"views/#{v}/settings/view.txt")
    lines = lines.select {|x| x =~ /^title / && x !~ /VIEW_/ }
    title = lines.first.split(" ", 2)[1]
    print "  ", ('%15s' % v)
    puts  "  ", fx(title, Black)
  end
  puts
end

#cmd_manage(arg) ⇒ Object



72
73
74
75
76
77
78
79
80
81
# File 'lib/repl.rb', line 72

def cmd_manage(arg)
  case arg
    when "pages";   _manage_pages
    when "links";   _manage_links
    when "navbar";  _manage_navbar
    when "pinned";  _manage_pinned  # ditch this??
  else
    puts "#{arg} is unknown"
  end
end

#cmd_new_postObject



281
282
283
284
285
286
287
288
289
290
291
# File 'lib/repl.rb', line 281

def cmd_new_post
  if @blog.views.empty?
    puts "\n  Create a view before creating the first post!\n "
    return
  end
  title = ask("\nTitle: ")
  puts
  @blog.create_new_post(title)
rescue => err
  _tmp_error(err)
end

#cmd_new_view(arg) ⇒ Object



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/repl.rb', line 263

def cmd_new_view(arg)
  if arg.nil?
    arg = ask(fx("\nFilename: ", :bold))
    puts
  end
  @blog.create_view(arg)
  text = File.read("#{@blog.root}/data/global.lt3")
  File.write("#{@blog.root}/views/#{@blog.view}/themes/standard/global.lt3", 
             text.gsub(/VIEW_NAME/, @blog.view.to_s))
  vim_params = '-c ":set hlsearch" -c ":hi Search ctermfg=2 ctermbg=6" +/"\(VIEW_.*\|SITE.*\)"'
  edit_file(@blog.view.dir/"themes/standard/global.lt3", vim: vim_params)
  @blog.change_view(arg)
rescue ViewAlreadyExists
  puts 'Blog already exists'
rescue => err
  _tmp_error(err)
end

#cmd_previewObject



175
176
177
178
179
180
181
182
183
184
185
# File 'lib/repl.rb', line 175

def cmd_preview
  local = @blog.view.local_index
  unless File.exist?(local)
    puts "\n  No index. Rebuilding..."
    cmd_rebuild
  end
  result = system!("open #{local}")
  raise CantOpen(local) unless result
rescue => err
  _tmp_error(err)
end

#cmd_publishObject



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/repl.rb', line 187

def cmd_publish
  puts
  unless @blog.view.can_publish?
    msg = "Can't publish... see global.lt3"
    puts msg
    return
  end

  ret = RubyText.spinner(label: " Publishing... ") do
    @blog.view.publisher.publish
  end
  return unless ret

  vdir = @blog.view.dir
  dump("fix this later", "#{vdir}/last_published")
  puts "  ...finished.\n " unless ret
rescue => err
  _tmp_error(err)
end

#cmd_quitObject



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/repl.rb', line 22

def cmd_quit
  STDSCR.rows.times { puts " "*(STDSCR.cols-1) }
  # FIXME please?
  # sleep 0.1
  STDSCR.clear
  sleep 0.1
  RubyText.stop
  sleep 0.1
  system("clear")
  # sleep 0.1
  exit
end

#cmd_rebuildObject



231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/repl.rb', line 231

def cmd_rebuild
  debug "Starting cmd_rebuild..."
  puts
  regen_posts
  puts "  Generating view"
  @blog.generate_view(@blog.view)
  puts "  Generating index"
  @blog.generate_index(@blog.view)
  puts "  ...finished!"
rescue => err
  _tmp_error(err)
end

#cmd_remove_post(arg) ⇒ Object



299
300
301
302
303
304
305
306
# File 'lib/repl.rb', line 299

def cmd_remove_post(arg)
  args = arg.split
  args.each do |x| 
    # FIXME
    ret = _remove_post(x.to_i, false)
    puts ret
  end
end

#cmd_sshObject



403
404
405
406
407
408
409
# File 'lib/repl.rb', line 403

def cmd_ssh
  pub = @blog.view.publisher
  puts
  system!("tputs clear; ssh #{pub.user}@#{pub.server}")
  sleep 0.1
  cmd_clear
end

#cmd_versionObject



41
42
43
# File 'lib/repl.rb', line 41

def cmd_version
  puts fx("\n  RuneBlog", :bold), fx(" v #{RuneBlog::VERSION}\n", Red)
end

#edit_file(file, vim: "") ⇒ Object



12
13
14
15
16
17
18
19
20
# File 'lib/repl.rb', line 12

def edit_file(file, vim: "")
#   STDSCR.saveback
  ed = @blog.editor
  params = vim if ed =~ /vim$/
  result = system!("#{@blog.editor} #{file} #{params}")
  raise EditorProblem(file) unless result
#   STDSCR.restback
  cmd_clear
end

#error_cant_delete(files) ⇒ Object



136
137
138
139
140
141
142
143
# File 'lib/helpers-repl.rb', line 136

def error_cant_delete(files)
  case files
    when String
      raise CantDelete(files)
    when Array
      raise CantDelete(files.join("\n"))
  end
end

#fresh?(src, dst) ⇒ Boolean

Returns:

  • (Boolean)


207
208
209
210
# File 'lib/repl.rb', line 207

def fresh?(src, dst)
  return false unless File.exist?(dst)
  File.mtime(src) <= File.mtime(dst)
end

#get_integer(arg) ⇒ Object



126
127
128
129
130
# File 'lib/helpers-repl.rb', line 126

def get_integer(arg)
  Integer(arg) 
rescue 
  raise ArgumentError, "'#{arg}' is not an integer"
end

#regen_postsObject



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/repl.rb', line 212

def regen_posts
  drafts = @blog.drafts  # current view
  puts "  Regenerating posts..." unless drafts.empty?
  drafts.each do |draft|
    orig = @blog.root/:drafts/draft
    postdir = @blog.root/:posts/draft.sub(/.lt3$/, "")
    content = postdir/"/guts.html"
    next if fresh?(orig, content)

    @blog.generate_post(orig)    # rebuild post
    Dir.chdir(postdir) do
      meta = @blog.
      num, title = meta.num, meta.title
      num = '%4d' % num.to_s
      puts "  ", fx(num, Red), "  ", fx(title, Black)
    end
  end
end

#tags_for_view(vname = @blog.view) ⇒ Object



145
146
147
148
149
150
151
152
153
154
155
# File 'lib/helpers-repl.rb', line 145

def tags_for_view(vname = @blog.view)
  Dir.chdir(vname) do
    fname = "tagpool"
    if File.exist?(fname)
      tags = File.readlines(fname).map(&:chomp)
    else
      tags = []
    end
  end
  tags.sort
end