-
Notifications
You must be signed in to change notification settings - Fork 51
/
SjsonnetMain.scala
266 lines (242 loc) · 9.86 KB
/
SjsonnetMain.scala
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
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
185
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
package sjsonnet
import java.io.{BufferedOutputStream, InputStream, OutputStreamWriter, PrintStream, StringWriter, Writer}
import java.nio.charset.StandardCharsets
import java.nio.file.NoSuchFileException
import scala.util.Try
import scala.util.control.NonFatal
object SjsonnetMain {
def resolveImport(searchRoots0: Seq[Path], allowedInputs: Option[Set[os.Path]] = None) = new Importer {
def resolve(docBase: Path, importName: String): Option[Path] =
(docBase +: searchRoots0)
.flatMap(base => os.FilePath(importName) match {
case r: os.SubPath => Some(base.asInstanceOf[OsPath].p / r)
case r: os.RelPath =>
if (r.ups > base.segmentCount()) None
else Some(base.asInstanceOf[OsPath].p / r)
case a: os.Path => Some(a)
})
.filter(p => allowedInputs.fold(true)(_(p)))
.find(os.exists)
.flatMap(p => try Some(OsPath(p)) catch{case NonFatal(_) => None})
def read(path: Path): Option[String] =
try Some(os.read(path.asInstanceOf[OsPath].p)) catch { case NonFatal(_) => None }
}
def main(args: Array[String]): Unit = {
var exitCode = main0(
args match {
case Array(s, _*) if s == "-i" || s == "--interactive" => args.tail
case _ => args
},
new DefaultParseCache,
System.in,
System.out,
System.err,
os.pwd,
None
)
System.exit(exitCode)
}
def main0(args: Array[String],
parseCache: ParseCache,
stdin: InputStream,
stdout: PrintStream,
stderr: PrintStream,
wd: os.Path,
allowedInputs: Option[Set[os.Path]] = None,
importer: Option[(Path, String) => Option[os.Path]] = None): Int = {
var hasWarnings = false
def warn(msg: String): Unit = {
hasWarnings = true
stderr.println("[warning] "+msg)
}
val parser = mainargs.ParserForClass[Config]
val name = s"Sjsonnet ${sjsonnet.Version.version}"
val doc = "usage: sjsonnet [sjsonnet-options] script-file"
val result = for{
config <- parser.constructEither(
args,
customName = name, customDoc = doc,
autoPrintHelpAndExit = None
)
file <- {
if (config.interactive.value) {
Left("error: -i/--interactive must be passed in as the first argument")
}else Right(config.file)
}
outputStr <- mainConfigured(file, config, parseCache, wd, allowedInputs, importer, warn)
res <- {
if(hasWarnings && config.fatalWarnings.value) Left("")
else Right(outputStr)
}
} yield res
result match{
case Left(err) =>
if (!err.isEmpty) stderr.println(err)
1
case Right(str) =>
if (!str.isEmpty) stdout.println(str)
0
}
}
def rendererForConfig(wr: Writer, config: Config, getCurrentPosition: () => Position) =
if (config.yamlOut.value) new PrettyYamlRenderer(
wr,
indent = config.indent,
getCurrentPosition = getCurrentPosition
)
else new Renderer(wr, indent = config.indent)
def handleWriteFile[T](f: => T): Either[String, T] =
Try(f).toEither.left.map{
case e: NoSuchFileException => s"open $f: no such file or directory"
case e => e.toString
}
def writeFile(config: Config, f: os.Path, contents: String): Either[String, Unit] =
handleWriteFile(os.write.over(f, contents, createFolders = config.createDirs.value))
def writeToFile[U](config: Config, wd: os.Path)(materialize: Writer => Either[String, U]): Either[String, String] = {
config.outputFile match{
case None => materialize(new StringWriter).map(_.toString)
case Some(f) =>
handleWriteFile(os.write.over.outputStream(os.Path(f, wd), createFolders = config.createDirs.value)).flatMap { out =>
try {
val buf = new BufferedOutputStream(out)
val wr = new OutputStreamWriter(buf, StandardCharsets.UTF_8)
val u = materialize(wr)
wr.flush()
u.map(_ => "")
} finally out.close()
}
}
}
def renderNormal(config: Config, interp: Interpreter, path: os.Path, wd: os.Path,
getCurrentPosition: () => Position) = {
writeToFile(config, wd){ writer =>
val renderer = rendererForConfig(writer, config, getCurrentPosition)
val res = interp.interpret0(os.read(path), OsPath(path), renderer)
if (config.yamlOut.value) writer.write('\n')
res
}
}
def isScalar(v: ujson.Value) = !v.isInstanceOf[ujson.Arr] && !v.isInstanceOf[ujson.Obj]
def mainConfigured(file: String,
config: Config,
parseCache: ParseCache,
wd: os.Path,
allowedInputs: Option[Set[os.Path]] = None,
importer: Option[(Path, String) => Option[os.Path]] = None,
warnLogger: String => Unit = null): Either[String, String] = {
val path = os.Path(file, wd)
var varBinding = Map.empty[String, String]
config.extStr.map(_.split("=", 2)).foreach{
case Array(x) => varBinding = varBinding ++ Seq(x -> ujson.write(System.getenv(x)))
case Array(x, v) => varBinding = varBinding ++ Seq(x -> ujson.write(v))
}
config.extStrFile.map(_.split("=", 2)).foreach {
case Array(x, v) =>
varBinding = varBinding ++ Seq(x -> ujson.write(os.read(os.Path(v, wd))))
}
config.extCode.map(_.split("=", 2)).foreach {
case Array(x) => varBinding = varBinding ++ Seq(x -> System.getenv(x))
case Array(x, v) => varBinding = varBinding ++ Seq(x -> v)
}
config.extCodeFile.map(_.split("=", 2)).foreach {
case Array(x, v) =>
varBinding = varBinding ++ Seq(x -> os.read(os.Path(v, wd)))
}
var tlaBinding = Map.empty[String, ujson.Value]
config.tlaStr.map(_.split("=", 2)).foreach{
case Array(x) => tlaBinding = tlaBinding ++ Seq(x -> ujson.Str(System.getenv(x)))
case Array(x, v) => tlaBinding = tlaBinding ++ Seq(x -> ujson.Str(v))
}
config.tlaStrFile.map(_.split("=", 2)).foreach {
case Array(x, v) =>
tlaBinding = tlaBinding ++ Seq(x -> ujson.Str(os.read(os.Path(v, wd))))
}
config.tlaCode.map(_.split("=", 2)).foreach {
case Array(x) => tlaBinding = tlaBinding ++ Seq(x -> ujson.read(System.getenv(x)))
case Array(x, v) => tlaBinding = tlaBinding ++ Seq(x -> ujson.read(v))
}
config.tlaCodeFile.map(_.split("=", 2)).foreach {
case Array(x, v) =>
tlaBinding = tlaBinding ++ Seq(x -> ujson.read(os.read(os.Path(v, wd))))
}
var currentPos: Position = null
val interp = new Interpreter(
varBinding,
tlaBinding,
OsPath(wd),
importer = importer match{
case Some(i) => new Importer {
def resolve(docBase: Path, importName: String): Option[Path] =
i(docBase, importName).map(OsPath)
def read(path: Path): Option[String] =
try Some(os.read(path.asInstanceOf[OsPath].p)) catch { case NonFatal(_) => None }
}
case None => resolveImport(config.jpaths.map(os.Path(_, wd)).map(OsPath(_)), allowedInputs)
},
parseCache,
settings = new Settings(
preserveOrder = config.preserveOrder.value,
strict = config.strict.value,
noStaticErrors = config.noStaticErrors.value,
),
storePos = if (config.yamlDebug.value) currentPos = _ else null,
warnLogger
)
(config.multi, config.yamlStream.value) match {
case (Some(multiPath), _) =>
interp.interpret(os.read(path), OsPath(path)).flatMap{
case obj: ujson.Obj =>
val renderedFiles: Seq[Either[String, os.RelPath]] =
obj.value.toSeq.map{case (f, v) =>
for{
rendered <- {
if (config.expectString.value) {
v match {
case ujson.Str(s) => Right(s)
case _ => Left("expected string result, got: " + v.getClass)
}
} else Right(ujson.transform(v, new Renderer(indent = config.indent)).toString)
}
relPath = os.RelPath(multiPath) / os.RelPath(f)
_ <- writeFile(config, wd / relPath, rendered)
} yield relPath
}
renderedFiles.collect{case Left(err) => err} match{
case Nil =>
Right[String, String](renderedFiles.collect{case Right(path) => path}.mkString("\n"))
case errs =>
Left[String, String]("rendering errors:\n" + errs.mkString("\n"))
}
case _ =>
Left("error: multi mode: top-level should be an object " +
"whose keys are filenames and values hold the JSON for that file.")
}
case (None, true) =>
// YAML stream
interp.interpret(os.read(path), OsPath(path)).flatMap {
case arr: ujson.Arr =>
writeToFile(config, wd){ writer =>
arr.value.toSeq match {
case Nil => //donothing
case Seq(single) =>
val renderer = rendererForConfig(writer, config, () => currentPos)
single.transform(renderer)
writer.write(if (isScalar(single)) "\n..." else "")
case multiple =>
for((v, i) <- multiple.zipWithIndex){
if (i > 0) writer.write('\n')
if (isScalar(v)) writer.write("--- ")
else if (i != 0) writer.write("---\n")
val renderer = rendererForConfig(writer, config, () => currentPos)
v.transform(renderer)
}
}
writer.write('\n')
Right("")
}
case _ => renderNormal(config, interp, path, wd, () => currentPos)
}
case _ => renderNormal(config, interp, path, wd, () => currentPos)
}
}
}