Class: DiscourseTheme::Uploader

Inherits:
Object
  • Object
show all
Defined in:
lib/discourse_theme/uploader.rb

Constant Summary collapse

THEME_CREATOR_REGEX =
/^https:\/\/theme-creator.discourse.org$/i

Instance Method Summary collapse

Constructor Details

#initialize(dir:, client:, theme_id: nil, components: nil) ⇒ Uploader

Returns a new instance of Uploader.



6
7
8
9
10
11
# File 'lib/discourse_theme/uploader.rb', line 6

def initialize(dir:, client:, theme_id: nil, components: nil)
  @dir = dir
  @client = client
  @theme_id = theme_id
  @components = components
end

Instance Method Details

#compress_dir(gzip, dir) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/discourse_theme/uploader.rb', line 13

def compress_dir(gzip, dir)
  sgz = Zlib::GzipWriter.new(File.open(gzip, 'wb'))
  tar = Archive::Tar::Minitar::Output.new(sgz)

  Dir.chdir(dir + "/../") do
    Find.find(File.basename(dir)) do |x|
      bn = File.basename(x)
      Find.prune if bn == "node_modules" || bn == "src" || bn[0] == ?.
      next if File.directory?(x)

      Minitar.pack_file(x, tar)
    end
  end
ensure
  tar.close
  sgz.close
end

#diagnose_errors(json) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/discourse_theme/uploader.rb', line 31

def diagnose_errors(json)
  count = 0
  json["theme"]["theme_fields"].each do |row|
    if (error = row["error"]) && error.length > 0
      count += 1
      Cli.error ""
      Cli.error "Error in #{row["target"]} #{row["name"]}: #{row["error"]}"
      Cli.error ""
    end
  end
  count
end

#upload_full_themeObject



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/discourse_theme/uploader.rb', line 65

def upload_full_theme
  filename = "#{Pathname.new(Dir.tmpdir).realpath}/bundle_#{SecureRandom.hex}.tar.gz"
  compress_dir(filename, @dir)

  File.open(filename) do |tgz|
    response = @client.upload_full_theme(tgz, theme_id: @theme_id, components: @components)

    json = JSON.parse(response.body)
    @theme_id = json["theme"]["id"]
    if diagnose_errors(json) != 0
      Cli.error "(end of errors)"
    end
    @theme_id
  end
ensure
  FileUtils.rm_f filename
end

#upload_theme_field(target:, name:, type_id:, value:) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/discourse_theme/uploader.rb', line 44

def upload_theme_field(target: , name: , type_id: , value:)
  raise "expecting theme_id to be set!" unless @theme_id

  args = {
    theme: {
      theme_fields: [{
        name: name,
        target: target,
        type_id: type_id,
        value: value
      }]
    }
  }

  response = @client.update_theme(@theme_id, args)
  json = JSON.parse(response.body)
    if diagnose_errors(json) != 0
      Cli.error "(end of errors)"
    end
end