Class: Neocities::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/neocities/cli.rb

Constant Summary collapse

SUBCOMMANDS =
%w{upload delete list info push logout pizza pull}
HELP_SUBCOMMANDS =
['-h', '--help', 'help']
PENELOPE_MOUTHS =
%w{^ o ~ - v U}
PENELOPE_EYES =
%w{o ~ O}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv) ⇒ CLI

Returns a new instance of CLI.



18
19
20
21
22
23
24
25
26
# File 'lib/neocities/cli.rb', line 18

def initialize(argv)
  @argv = argv.dup
  @pastel = Pastel.new eachline: "\n"
  @subcmd = @argv.first
  @subargs = @argv[1..@argv.length]
  @prompt = TTY::Prompt.new
  @api_key = ENV['NEOCITIES_API_KEY'] || nil
  @app_config_path = File.join self.class.app_config_path('neocities'), 'config.json' # added json extension
end

Class Method Details

.app_config_path(name) ⇒ Object



503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
# File 'lib/neocities/cli.rb', line 503

def self.app_config_path(name)
  platform = if RUBY_PLATFORM =~ /win32/
    :win32
  elsif RUBY_PLATFORM =~ /darwin/
    :darwin
  elsif RUBY_PLATFORM =~ /linux/
    :linux
  else
    :unknown
  end

  case platform
  when :linux
    if ENV['XDG_CONFIG_HOME']
      return File.join(ENV['XDG_CONFIG_HOME'], name)
    end

    if ENV['HOME']
      return File.join(ENV['HOME'], '.config', name)
    end
  when :darwin
    return File.join(ENV['HOME'], 'Library', 'Application Support', name)
  else
    # Windows platform detection is weird, just look for the env variables
    if ENV['LOCALAPPDATA']
      return File.join(ENV['LOCALAPPDATA'], name)
    end

    if ENV['USERPROFILE']
      return File.join(ENV['USERPROFILE'], 'Local Settings', 'Application Data', name)
    end

    # Should work for the BSDs
    if ENV['HOME']
      return File.join(ENV['HOME'], '.'+name)
    end
  end
end

Instance Method Details

#deleteObject



103
104
105
106
107
108
109
110
111
# File 'lib/neocities/cli.rb', line 103

def delete
  display_delete_help_and_exit if @subargs.empty?
  @subargs.each do |file|
    puts @pastel.bold("Deleting #{file} ...")
    resp = @client.delete file

    display_response resp
  end
end

#display_bannerObject



475
476
477
478
479
480
481
482
483
# File 'lib/neocities/cli.rb', line 475

def display_banner
  puts <<HERE

  |\\---/|
  | #{PENELOPE_EYES.sample}_#{PENELOPE_EYES.sample} |  #{@pastel.on_cyan.bold ' Neocities '}
   \\_#{PENELOPE_MOUTHS.sample}_/

HERE
end

#display_delete_help_and_exitObject



381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
# File 'lib/neocities/cli.rb', line 381

def display_delete_help_and_exit
  display_banner

  puts <<HERE
  #{@pastel.green.bold 'delete'} - Delete files on your Neocities site

  #{@pastel.dim 'Examples:'}

  #{@pastel.green '$ neocities delete myfile.jpg'}               Delete myfile.jpg

  #{@pastel.green '$ neocities delete myfile.jpg myfile2.jpg'}   Delete myfile.jpg and myfile2.jpg

  #{@pastel.green '$ neocities delete mydir'}                    Deletes mydir and everything inside it (be careful!)

HERE
  exit
end

#display_help_and_exitObject



485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
# File 'lib/neocities/cli.rb', line 485

def display_help_and_exit
  display_banner
  puts <<HERE
  #{@pastel.dim 'Subcommands:'}
push        Recursively upload a local directory to your site
upload      Upload individual files to your Neocities site
delete      Delete files from your Neocities site
list        List files from your Neocities site
info        Information and stats for your site
logout      Remove the site api key from the config
version     Unceremoniously display version and self destruct
pull        Get the most recent version of files from your site
pizza       Order a free pizza

HERE
  exit
end

#display_info_help_and_exitObject



447
448
449
450
451
452
453
454
455
456
457
458
459
# File 'lib/neocities/cli.rb', line 447

def display_info_help_and_exit
  display_banner

  puts <<HERE
  #{@pastel.green.bold 'info'} - Get site info

  #{@pastel.dim 'Examples:'}

  #{@pastel.green '$ neocities info fauux'}   Gets info for 'fauux' site

HERE
  exit
end

#display_list_help_and_exitObject



363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/neocities/cli.rb', line 363

def display_list_help_and_exit
  display_banner

  puts <<HERE
  #{@pastel.green.bold 'list'} - List files on your Neocities site

  #{@pastel.dim 'Examples:'}

  #{@pastel.green '$ neocities list /'}           List files in your root directory

  #{@pastel.green '$ neocities list -a'}          Recursively display all files and directories

  #{@pastel.green '$ neocities list -d /mydir'}   Show detailed information on /mydir

HERE
  exit
end

#display_logout_help_and_exitObject



461
462
463
464
465
466
467
468
469
470
471
472
473
# File 'lib/neocities/cli.rb', line 461

def display_logout_help_and_exit
  display_banner

  puts <<HERE
  #{@pastel.green.bold 'logout'} - Remove the site api key from the config

  #{@pastel.dim 'Examples:'}

  #{@pastel.green '$ neocities logout -y'}

HERE
  exit
end

#display_pizza_help_and_exitObject



358
359
360
361
# File 'lib/neocities/cli.rb', line 358

def display_pizza_help_and_exit
  puts "Sorry, we're fresh out of dough today. Try again tomorrow."
  exit
end

#display_pull_help_and_exitObject



415
416
417
418
419
420
421
422
423
# File 'lib/neocities/cli.rb', line 415

def display_pull_help_and_exit
  display_banner

  puts <<HERE
  #{@pastel.magenta.bold 'pull'} - Get the most recent version of files from your site

HERE
  exit
end

#display_push_help_and_exitObject



425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
# File 'lib/neocities/cli.rb', line 425

def display_push_help_and_exit
  display_banner

  puts <<HERE
  #{@pastel.green.bold 'push'} - Recursively upload a local directory to your Neocities site

  #{@pastel.dim 'Examples:'}

  #{@pastel.green '$ neocities push .'}                                 Recursively upload current directory.

  #{@pastel.green '$ neocities push -e node_modules -e secret.txt .'}   Exclude certain files from push

  #{@pastel.green '$ neocities push --no-gitignore .'}                  Don't use .gitignore to exclude files

  #{@pastel.green '$ neocities push --dry-run .'}                       Just show what would be uploaded

  #{@pastel.green '$ neocities push --prune .'}                         Delete site files not in dir (be careful!)

HERE
  exit
end

#display_response(resp) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/neocities/cli.rb', line 28

def display_response(resp)
  if resp[:result] == 'success'
    puts "#{@pastel.green.bold 'SUCCESS:'} #{resp[:message]}"
  elsif resp[:result] == 'error' && resp[:error_type] == 'file_exists'
    out = "#{@pastel.yellow.bold 'EXISTS:'} #{resp[:message]}"
    out += " (#{resp[:error_type]})" if resp[:error_type]
    puts out
  else
    out = "#{@pastel.red.bold 'ERROR:'} #{resp[:message]}"
    out += " (#{resp[:error_type]})" if resp[:error_type]
    puts out
  end
end

#display_upload_help_and_exitObject



399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/neocities/cli.rb', line 399

def display_upload_help_and_exit
  display_banner

  puts <<HERE
  #{@pastel.green.bold 'upload'} - Upload individual files to your Neocities site

  #{@pastel.dim 'Examples:'}

  #{@pastel.green '$ neocities upload img.jpg img2.jpg'}    Upload images to the root of your site

  #{@pastel.green '$ neocities upload -d images img.jpg'}   Upload img.jpg to the 'images' directory on your site

HERE
  exit
end

#infoObject



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/neocities/cli.rb', line 130

def info
  resp = @client.info(@subargs[0] || @sitename)

  if resp[:result] == 'error'
    display_response resp
    exit
  end

  out = []

  resp[:info].each do |k, v|
    v = Time.parse(v).localtime if v && (k == :created_at || k == :last_updated)
    out.push [@pastel.bold(k), v]
  end

  puts TTY::Table.new(out).to_s
  exit
end

#listObject



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/neocities/cli.rb', line 149

def list
  display_list_help_and_exit if @subargs.empty?
  if @subargs.delete('-d') == '-d'
    @detail = true
  end

  if @subargs.delete('-a')
    @subargs[0] = nil
  end

  resp = @client.list @subargs[0]

  if resp[:result] == 'error'
    display_response resp
    exit
  end

  if @detail
    out = [
      [@pastel.bold('Path'), @pastel.bold('Size'), @pastel.bold('Updated')]
    ]
    resp[:files].each do |file|
      out.push([
        @pastel.send(file[:is_directory] ? :blue : :green).bold(file[:path]),
        file[:size] || '',
        Time.parse(file[:updated_at]).localtime
      ])
    end
    puts TTY::Table.new(out).to_s
    exit
  end

  resp[:files].each do |file|
    puts @pastel.send(file[:is_directory] ? :blue : :green).bold(file[:path])
  end
end

#logoutObject



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/neocities/cli.rb', line 113

def logout
  confirmed = false
  loop do
    case @subargs[0]
    when '-y' then @subargs.shift; confirmed = true
    when /^-/ then puts(@pastel.red.bold("Unknown option: #{@subargs[0].inspect}")); break
    else break
    end
  end
  if confirmed
    FileUtils.rm @app_config_path
    puts @pastel.bold("Your api key has been removed.")
  else
    display_logout_help_and_exit
  end
end

#pizzaObject



354
355
356
# File 'lib/neocities/cli.rb', line 354

def pizza
  display_pizza_help_and_exit
end

#pullObject



325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# File 'lib/neocities/cli.rb', line 325

def pull
  begin
    quiet = !(['--log', '-l'].include? @subargs[0])

    file = File.read @app_config_path
    data = JSON.load file

    last_pull_time = data["LAST_PULL"] ? data["LAST_PULL"]["time"] : nil
    last_pull_loc = data["LAST_PULL"] ? data["LAST_PULL"]["loc"] : nil

    Whirly.start spinner: ["😺", "😸", "😹", "😻", "😼", "😽", "🙀", "😿", "😾"], status: "Retrieving files for #{@pastel.bold @sitename}" if quiet
    resp = @client.pull @sitename, last_pull_time, last_pull_loc, quiet

    # write last pull data to file (not necessarily the best way to do this, but better than cloning every time)
    data["LAST_PULL"] = {
      "time": Time.now,
      "loc": Dir.pwd
    }

    File.write @app_config_path, data.to_json
  rescue StandardError => ex
    Whirly.stop if quiet
    puts @pastel.red.bold "\nA fatal error occurred :-("
    puts @pastel.red ex
  ensure
    exit
  end
end

#pushObject



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/neocities/cli.rb', line 186

def push
  display_push_help_and_exit if @subargs.empty?
  @no_gitignore = false
  @excluded_files = []
  @dry_run = false
  @prune = false
  loop do
    case @subargs[0]
    when '--no-gitignore' then @subargs.shift; @no_gitignore = true
    when '-e' then @subargs.shift; @excluded_files.push(@subargs.shift)
    when '--dry-run' then @subargs.shift; @dry_run = true
    when '--prune' then @subargs.shift; @prune = true
    when /^-/ then puts(@pastel.red.bold("Unknown option: #{@subargs[0].inspect}")); display_push_help_and_exit
    else break
    end
  end

  if @subargs[0].nil?
    display_response result: 'error', message: "no local path provided"
    display_push_help_and_exit
  end

  root_path = Pathname @subargs[0]

  if !root_path.exist?
    display_response result: 'error', message: "path #{root_path} does not exist"
    display_push_help_and_exit
  end

  if !root_path.directory?
    display_response result: 'error', message: 'provided path is not a directory'
    display_push_help_and_exit
  end

  if @dry_run
    puts @pastel.green.bold("Doing a dry run, not actually pushing anything")
  end

  if @prune
    pruned_dirs = []
    resp = @client.list
    resp[:files].each do |file|
      path = Pathname(File.join(@subargs[0], file[:path]))

      pruned_dirs << path if !path.exist? && (file[:is_directory])

      if !path.exist? && !pruned_dirs.include?(path.dirname)
        print @pastel.bold("Deleting #{file[:path]} ... ")
        resp = @client.delete_wrapper_with_dry_run file[:path], @dry_run

        if resp[:result] == 'success'
          print @pastel.green.bold("SUCCESS") + "\n"
        else
          print "\n"
          display_response resp
        end
      end
    end
  end

  Dir.chdir(root_path) do
    paths = Dir.glob(File.join('**', '*'), File::FNM_DOTMATCH)

    if @no_gitignore == false
      begin
        ignores = File.readlines('.gitignore').collect! do |ignore|
          ignore.strip!
          File.directory?(ignore) ? "#{ignore}**" : ignore
        end
        paths.select! do |path|
          res = true
          ignores.each do |ignore|
            if File.fnmatch?(ignore.strip, path)
              res = false
              break
            end
          end
        end
        puts "Not pushing .gitignore entries (--no-gitignore to disable)"
      rescue Errno::ENOENT
      end
    end

    paths.select! { |p| !@excluded_files.include?(p) }

    paths.select! { |p| !@excluded_files.include?(Pathname.new(p).dirname.to_s) }

    paths.collect! { |path| Pathname path }

    paths.each do |path|
      next if path.directory?
      print @pastel.bold("Uploading #{path} ... ")
      resp = @client.upload path, path, @dry_run

      if resp[:result] == 'error' && resp[:error_type] == 'file_exists'
        print @pastel.yellow.bold("EXISTS") + "\n"
      elsif resp[:result] == 'success'
        print @pastel.green.bold("SUCCESS") + "\n"
      else
        print "\n"
        display_response resp
      end
    end
  end
end

#runObject



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

def run
  if @argv[0] == 'version'
    puts Neocities::VERSION
    exit
  end

  if HELP_SUBCOMMANDS.include?(@subcmd) && SUBCOMMANDS.include?(@subargs[0])
    send "display_#{@subargs[0]}_help_and_exit"
  elsif @subcmd.nil? || !SUBCOMMANDS.include?(@subcmd)
    display_help_and_exit
  elsif @subargs.join("").match(HELP_SUBCOMMANDS.join('|')) && @subcmd != "info"
    send "display_#{@subcmd}_help_and_exit"
  end

  if !@api_key
    begin
      file = File.read @app_config_path
      data = JSON.load file

      if data
        @api_key = data["API_KEY"].strip # Remove any trailing whitespace causing HTTP requests to fail
        @sitename = data["SITENAME"] # Store the sitename to be able to reference it later
        @last_pull = data["LAST_PULL"] # Store the last time a pull was performed so that we only fetch from updated files
      end
    rescue Errno::ENOENT
      @api_key = nil
    end
  end

  if @api_key.nil?
    puts "Please login to get your API key:"

    if !@sitename && !@password
      @sitename = @prompt.ask('sitename:', default: ENV['NEOCITIES_SITENAME'])
      @password = @prompt.mask('password:', default: ENV['NEOCITIES_PASSWORD'])
    end

    @client = Neocities::Client.new sitename: @sitename, password: @password

    resp = @client.key
    if resp[:api_key]
      conf = {
        "API_KEY": resp[:api_key],
        "SITENAME": @sitename,
      }

      FileUtils.mkdir_p Pathname(@app_config_path).dirname
      File.write @app_config_path, conf.to_json

      puts "The api key for #{@pastel.bold @sitename} has been stored in #{@pastel.bold @app_config_path}."
    else
      display_response resp
      exit
    end
  else
    @client = Neocities::Client.new api_key: @api_key
  end

  send @subcmd
end

#uploadObject



292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# File 'lib/neocities/cli.rb', line 292

def upload
  display_upload_help_and_exit if @subargs.empty?
  @dir = ''

  loop do
    case @subargs[0]
    when '-d' then @subargs.shift; @dir = @subargs.shift
    when /^-/ then puts(@pastel.red.bold("Unknown option: #{@subargs[0].inspect}")); display_upload_help_and_exit
    else break
    end
  end

  @subargs.each do |path|
    path = Pathname path

    if !path.exist?
      display_response result: 'error', message: "#{path} does not exist locally."
      next
    end

    if path.directory?
      puts "#{path} is a directory, skipping (see the push command)"
      next
    end

    remote_path = ['/', @dir, path.basename.to_s].join('/').gsub %r{/+}, '/'

    puts @pastel.bold("Uploading #{path} to #{remote_path} ...")
    resp = @client.upload path, remote_path
    display_response resp
  end
end