Class: Lamma::Code

Inherits:
Object
  • Object
show all
Defined in:
lib/lamma/code.rb

Constant Summary collapse

BUILD_FILE_NAME =
'build.zip'

Instance Method Summary collapse

Constructor Details

#initialize(function, yaml) ⇒ Code

Returns a new instance of Code.



10
11
12
13
14
15
# File 'lib/lamma/code.rb', line 10

def initialize(function, yaml)
  @function = function
  @source_path = yaml.fetch('source_path', '.')
  @prebuild = yaml.fetch('prebuild', nil)
  @build_path = yaml.fetch('build_path', nil)
end

Instance Method Details

#to_hObject



65
66
67
68
69
# File 'lib/lamma/code.rb', line 65

def to_h
  {
    zip_file: zip_io
  }
end

#zip_ioObject



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
# File 'lib/lamma/code.rb', line 17

def zip_io
  return @zip_io if @zip_io

  if h = cached_build_hash
    bp = File.join(build_path, h, BUILD_FILE_NAME)
    Lamma.logger.info "Using cached build: #{bp}"
    @zip_io = File.open(bp, 'rb')
  else
    unless File.directory?(@source_path)
      raise "Source path #{@source_path} doesn't exists"
    end

    # prebuild script
    if @prebuild
      Lamma.logger.info 'Running prebuild script...'
      raise unless system(@prebuild)
    elsif @function.runtime == Lamma::Runtime::PYTHON_27 \
      && File.exist?(File.join(@source_path, 'requirements.txt'))
      raise unless system("pip", "install", "-r", "requirements.txt", "-t", ".")
      # XXX: verbose?
    elsif [Lamma::Runtime::EDGE_NODE_43, Lamma::Runtime::NODE_43].include? @function.runtime \
      && File.exist?(File.join(@source_path, 'package.json'))
      raise unless system("npm", "install", "--production")
    end

    io = Zip::OutputStream.write_buffer do |zio|
      active_paths.each do |path|
        next unless File.file?(path)
        File.open(path) do |source_io|
          zio.put_next_entry(path)
          data = source_io.read
          zio.write(data)
        end
      end
    end

    io.rewind
    if true # XXX: option save_builds?
      File.open(File.join(zipfile_path, BUILD_FILE_NAME), 'w').write(io.read)
      Lamma.logger.info("Saved the build: #{zipfile_path}")
      io.rewind
    end
    @zip_io = io
  end

  @zip_io
end