~singpolyma/dhall-ruby

ref: 47e514eb3cacf441a67fcdc94c9572efaccb74cf dhall-ruby/bin/dhall-compile -rwxr-xr-x 2.0 KiB View raw
47e514ebStephen Paul Weber dhall-compile support generating cache folder 8 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
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
#!/usr/bin/ruby
# frozen_string_literal: true

require "dhall"
require "optparse"

@extension = ".dhallb"

def compile(source)
	Dhall.load(
		source,
		timeout:  Float::INFINITY,
		resolver: Dhall::Resolvers::Default.new(
			max_depth: Float::INFINITY
		)
	)
end

def compile_file(file_path, relative_to: Pathname.new("."))
	out = file_path.sub_ext(@extension)
	if @output_directory
		out = @output_directory + out.relative_path_from(relative_to)
	end
	$stderr.print "#{file_path} => "
	warn out unless @cache
	compile(file_path.expand_path).then { |dhall|
		if @cache
			base = "1220#{dhall.digest.hexdigest}"
			out = file_path.dirname + base
			if @output_directory
				out = @output_directory + base
				out.dirname.mkpath
			end
			warn out
			out.write(dhall.to_cbor)
		else
			out.dirname.mkpath
			out.write(dhall.to_binary)
		end
	}
end

opt_parser = OptionParser.new do |opts|
	opts.banner = "Usage: dhall-compile [options] [-] [files_and_dirs]"

	opts.on(
		"-oDIRECTORY",
		"--output-directory DIRECTORY",
		"Write output to this directory"
	) do |dir|
		@output_directory = Pathname.new(dir)
	end

	opts.on(
		"-e [EXTENSION]",
		"--extension [EXTENSION]",
		"Use this extension for files (default .dhallb)"
	) do |ext|
		@extension = ext ? ".#{ext}" : ""
	end

	opts.on(
		"-c",
		"--cache",
		"Write output in standard dhall file cache format"
	) do
		@extension = ""
		@cache = true
	end

	opts.on("-h", "--help", "Show this usage information") do
		warn opts
		exit
	end
end

opt_parser.parse!

if ARGV.empty?
	warn opt_parser
	exit 0
end

ARGV.map(&Pathname.method(:new)).each do |path|
	if !path.exist? && path.to_s == "-"
		warn "Compiling STDIN to STDOUT"
		compile(STDIN.read).then(&STDOUT.method(:write)).sync
	elsif path.file?
		compile_file(path, relative_to: path.dirname).sync
	elsif path.directory?
		warn "Recursively compiling #{path}"
		path.find.flat_map do |child|
			next if !child.file? || child.extname == ".dhallb"
			compile_file(child, relative_to: path).sync
		end
	else
		warn "#{path} may not exist"
		exit 1
	end
end