Class: StarlarkCompiler::BuildFile

Inherits:
Object
  • Object
show all
Defined in:
lib/starlark_compiler/build_file.rb

Instance Method Summary collapse

Constructor Details

#initialize(package:, workspace: Dir.pwd) ⇒ BuildFile

Returns a new instance of BuildFile.



8
9
10
11
12
13
14
15
# File 'lib/starlark_compiler/build_file.rb', line 8

def initialize(package:, workspace: Dir.pwd)
  @loads = Hash.new { |h, k| h[k] = Set.new }
  @targets = {}
  @variable_assignments = {}
  @package = package
  @workspace = workspace
  @path = File.join(@workspace, @package, 'BUILD.bazel')
end

Instance Method Details

#add_load(from:, of:) ⇒ Object

rubocop:disable Naming/MethodParameterName



17
18
19
# File 'lib/starlark_compiler/build_file.rb', line 17

def add_load(from:, of:) # rubocop:disable Naming/MethodParameterName
  @loads[from] |= Array(of)
end

#add_target(function_call) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/starlark_compiler/build_file.rb', line 21

def add_target(function_call)
  name = function_call.kwargs.fetch(:name)
  if @targets[name]
    raise Error, "Target named #{name.inspect} already exists in #{package}"
  end

  @targets[name] = function_call
end

#add_variable_assignment(name:, var:) ⇒ Object



30
31
32
# File 'lib/starlark_compiler/build_file.rb', line 30

def add_variable_assignment(name:, var:)
  @variable_assignments[name] = var
end

#save!Object



34
35
36
37
38
# File 'lib/starlark_compiler/build_file.rb', line 34

def save!
  File.open(@path, 'w') do |f|
    Writer.write(ast: to_starlark, io: f)
  end
end

#to_starlarkObject



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/starlark_compiler/build_file.rb', line 40

def to_starlark
  loads = @loads
          .sort_by { |k, _| k }
          .map { |f, fn| AST.build { function_call('load', f, *fn.sort) } }
  variable_assignments = @variable_assignments
                         .map do |name, var|
                           AST.build { variable_assignment(name, var) }
                         end
  targets = @targets
            .sort_by { |k, _| k }
            .map { |_f, fn| normalize_function_call_kwargs(fn) }
  AST.new(toplevel: loads + variable_assignments + targets)
end