-
Notifications
You must be signed in to change notification settings - Fork 8
/
build.sbt
873 lines (764 loc) · 24.4 KB
/
build.sbt
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
import scala.scalanative.build
import sbt.internal.bsp.BuildTarget
import scala.collection.immutable
import _root_.bindgen.plugin.BindgenMode
import scala.scalanative.build.GC
import coursierapi.ResolutionParams
import coursierapi.Repository
import sbt.io.Using
import java.util.stream.Collectors
import java.nio.file.Files
import scala.scalanative.build.Mode
import scala.scalanative.build.NativeConfig
import scala.scalanative.build.LTO
import commandmatrix.extra.*
import com.indoorvivants.detective.Platform
import Platform.*
import _root_.bindgen.interface.*
import ArtifactNames.*
import java.nio.file.Paths
lazy val Versions = new {
val decline = "2.4.1"
val scribe = "3.13.2"
val scalaNative = nativeVersion
val junit = "0.13.3"
val scalameta = "4.5.13"
val b2s = "0.3.17"
val pluginTargetSN = "0.4.17"
val pluginTargetSBT = "1.6.1"
val detective = "0.0.2"
val opaqueNewtypes = "0.0.2"
val Scala3 = "3.3.4"
val Scala212 = "2.12.20"
val Scala213 = "2.13.15"
val Scala2 = List(Scala212, Scala213)
}
inThisBuild(
Seq(
semanticdbEnabled := true,
semanticdbVersion := scalafixSemanticdb.revision,
semanticdbIncludeInJar := false,
organization := "com.indoorvivants",
organizationName := "Anton Sviridov",
homepage := Some(url("https://github.com/indoorvivants/sn-bindgen")),
startYear := Some(2022),
licenses := List(
"Apache-2.0" -> url("http://www.apache.org/licenses/LICENSE-2.0")
),
developers := List(
Developer(
"keynmol",
"Anton Sviridov",
url("https://blog.indoorvivants.com")
)
)
)
)
// --------------MODULES-------------------------
lazy val root = project
.in(file("."))
.aggregate(bindgen, libclang)
.aggregate(iface.projectRefs*)
.aggregate(plugin.projectRefs*)
.aggregate(tests.projectRefs*)
.settings(remoteCacheSettings, noPublish)
lazy val iface = projectMatrix
.in(file("modules/interface"))
.settings(remoteCacheMatrixSettings)
.someVariations(
Versions.Scala2 :+ Versions.Scala3,
List(
VirtualAxis.jvm,
VirtualAxis.native
)
)(
MatrixAction.ForScala(_.isScala2).Settings(scalacOptions += "-Xsource:3"),
MatrixAction
.ForPlatform(VirtualAxis.native)
.Configure(_.enablePlugins(ScalaNativeJUnitPlugin)),
MatrixAction
.ForPlatform(VirtualAxis.jvm)
.Settings(
Seq(
Test / fork := true,
libraryDependencies += "com.github.sbt" % "junit-interface" % Versions.junit % Test
)
)
)
.settings(
moduleName := "bindgen-interface",
libraryDependencies += "com.indoorvivants.detective" %%% "platform" % Versions.detective,
scalacOptions += "-deprecation"
)
.enablePlugins(BuildInfoPlugin)
.settings(
buildInfoPackage := "bindgen.interface",
buildInfoKeys := Seq[BuildInfoKey](
version,
scalaVersion,
scalaBinaryVersion
)
)
.settings(noTests)
lazy val bindgen = project
.in(file("modules/bindgen"))
.dependsOn(libclang)
.enablePlugins(ScalaNativePlugin, ScalaNativeJUnitPlugin, BuildInfoPlugin)
.settings(nativeCommon)
.settings(Compile / nativeConfig ~= environmentConfiguration)
.settings(nativeConfig ~= usesLibClang)
.settings(nativeConfig ~= (_.withIncrementalCompilation(true)))
.settings(remoteCacheSettings)
.settings(
buildInfoPackage := "bindgen",
buildInfoKeys := Seq[BuildInfoKey](
version,
scalaVersion,
scalaBinaryVersion,
BuildInfoKey("nativeVersion" -> nativeVersion)
),
moduleName := "bindgen",
libraryDependencies += "com.indoorvivants.detective" %%% "platform" % Versions.detective,
libraryDependencies += "com.monovore" %%% "decline" % Versions.decline,
libraryDependencies += "com.outr" %%% "scribe" % Versions.scribe,
libraryDependencies += "com.indoorvivants" %%% "opaque-newtypes" % Versions.opaqueNewtypes,
libraryDependencies += compilerPlugin(
"org.polyvariant" % "better-tostring" % Versions.b2s cross CrossVersion.full
),
testOptions += Tests.Argument(TestFrameworks.JUnit, "-a", "-s", "-v")
)
.settings {
detectBinaryArtifacts
.map { case (_, (artifact, file)) =>
addArtifact(Def.setting(artifact), Def.task(file))
}
.toSeq
.flatten
}
.settings(
checkDetectedArtifacts := {
import Platform.*, Target.*, OS.*, Arch.*, Bits.*
val expected = Seq(
Target(Windows, Intel, x64),
Target(MacOS, Intel, x64),
Target(Linux, Intel, x64)
).map(jarString)
val packaged = packagedArtifacts.value
expected.foreach { classifier =>
assert(
packaged.exists(_._1.classifier.contains(classifier)),
s"Artifact with $classifier was not found"
)
}
}
)
val checkDetectedArtifacts = taskKey[Unit]("")
lazy val binaryArtifacts = project
.in(file("build/binary-artifacts"))
.enablePlugins(ScalaNativePlugin)
.settings(nativeCommon)
.settings(noTests)
.settings(
packageBin / publishArtifact := false,
packageDoc / publishArtifact := false,
packageSrc / publishArtifact := false,
moduleName := "bindgen"
)
.settings {
val detected = detectBinaryArtifacts
detected
.map { case (_, (artifact, file)) =>
addArtifact(Def.setting(artifact), Def.task(file))
}
.toSeq
.flatten
}
lazy val localBindgenArtifact = project
.in(file("local-bindgen"))
.enablePlugins(ScalaNativePlugin)
.dependsOn(bindgen, libclang)
.settings(nativeCommon)
.settings(
packageBin / publishArtifact := false,
packageDoc / publishArtifact := false,
packageSrc / publishArtifact := false,
moduleName := "bindgen"
)
.settings {
def build(classifier: String) =
Artifact("bindgen", classifier)
.withExtension("jar")
.withType("jar")
.withConfigurations(Vector(Compile))
addArtifact(
Def.setting(build(jarString(Platform.target))),
Def.task { (bindgen / Compile / nativeLink).value }
)
}
lazy val plugin = projectMatrix
.in(file("modules/sbt-plugin"))
.dependsOn(iface)
.defaultAxes(VirtualAxis.scalaABIVersion(Versions.Scala212), VirtualAxis.jvm)
.allVariations(List(Versions.Scala212), List(VirtualAxis.jvm))
.settings(remoteCacheMatrixSettings)
.settings(
sbtPlugin := true,
addSbtPlugin(
"org.scala-native" % "sbt-scala-native" % Versions.pluginTargetSN
),
pluginCrossBuild / sbtVersion := Versions.pluginTargetSBT,
moduleName := "bindgen-sbt-plugin",
scriptedLaunchOpts := {
scriptedLaunchOpts.value ++
Seq("-Xmx1024M", "-Dplugin.version=" + version.value)
},
scriptedBufferLog := false,
publishLocal := publishLocal
.dependsOn(
localBindgenArtifact / publishLocal
)
.value
)
.enablePlugins(ScriptedPlugin, SbtPlugin)
lazy val libclang = project
.in(file("modules/libclang"))
.enablePlugins(ScalaNativePlugin, BindgenPlugin)
.settings(nativeCommon)
.settings(nativeConfig ~= usesLibClang)
.settings(remoteCacheSettings)
.settings(
moduleName := "bindgen-libclang",
bindgenMode := BindgenMode.Manual(
scalaDir = ((Compile / sourceDirectory).value / "scala" / "generated"),
cDir = (Compile / resourceDirectory).value / "scala-native" / "generated"
),
bindgenBinary := (LocalProject("bindgen") / Compile / nativeLink).value,
bindgenBindings := {
val detected =
llvmFolder(nativeConfig.value.clang.toAbsolutePath()).llvmInclude
detected match {
case head :: tl =>
val include = new File(head)
Seq(
Binding(include / "clang-c" / "Index.h", "libclang")
.withClangFlags(List(s"-I$head"))
.addCImport("clang-c/Index.h")
.withMultiFile(true)
)
case immutable.Nil =>
sLog.value.error(
"Failed to detect LLVM installation - you won't be able to link the binary and regenerate libclang bindings. " +
"Please use LLVM_BIN environment variable to point at the `bin/` folder of your LLVM installation"
)
Seq.empty
}
}
)
val runExportTests = taskKey[Unit]("")
lazy val exportTestsLibrary: Project = project
.in(file("modules/export-tests/library"))
.enablePlugins(ScalaNativePlugin, BindgenPlugin)
.settings(
scalaVersion := Versions.Scala3,
bindgenBinary := (bindgen / Compile / nativeLink).value,
bindgenBindings := {
val dir = (Compile / sourceDirectory).value / "c"
collectBindings(dir)
},
nativeConfig ~= (_.withBuildTarget(build.BuildTarget.libraryDynamic)),
noPublish,
runExportTests := {
if (Platform.os != Platform.OS.Windows) {
val library = (Compile / nativeLink).value
val clang = (Compile / nativeClang).value
val sourcesDir = (Compile / sourceDirectory).value / "c"
val workDir = library.getParentFile()
import scala.sys.process.*
val destination = workDir / "a.out"
val cmd = Seq(
clang,
sourcesDir / "run_tests.c",
"-o",
destination,
"-lexporttestslibrary-out",
s"-L${workDir}"
).map(_.toString())
val stderr = List.newBuilder[String]
val stdout = List.newBuilder[String]
val logger = ProcessLogger.apply(
(o: String) => stdout += o,
(e: String) => stderr += e
)
val errPrintln: String => Unit = s => System.err.println(s)
val process = new java.lang.ProcessBuilder(cmd*)
.directory(workDir)
.start()
scala.io.Source
.fromInputStream(process.getErrorStream())
.getLines()
.foreach(errPrintln(_))
assert(
process.waitFor() == 0,
"Building export tests binary (with clang) failed"
)
val testsProcessB = (new java.lang.ProcessBuilder(destination.toString))
.directory(workDir)
testsProcessB.environment().put("LD_LIBRARY_PATH", workDir.toString)
testsProcessB.environment().put("DYLD_LIBRARY_PATH", workDir.toString)
val testsProcess = testsProcessB.start()
scala.io.Source
.fromInputStream(testsProcess.getErrorStream())
.getLines()
.foreach(errPrintln(_))
assert(
testsProcess.waitFor() == 0,
"Running export tests failed"
)
} else
System.err.println("Skipping export tests on windows")
}
)
lazy val tests = projectMatrix
.in(file("modules/tests"))
.dependsOn(iface)
.settings(remoteCacheMatrixSettings)
.someVariations(
Versions.Scala2 :+ Versions.Scala3,
List(
VirtualAxis.jvm,
VirtualAxis.native
)
)(
MatrixAction((sv, axes) =>
sv.isScala2 && axes.contains(VirtualAxis.native)
).Skip,
MatrixAction.ForScala(_.isScala2).Settings(scalacOptions += "-Xsource:3"),
MatrixAction
.ForPlatform(VirtualAxis.native)
.Configure(
_.enablePlugins(ScalaNativeJUnitPlugin, BindgenPlugin)
.settings(nativeCommon)
.settings(Compile / nativeConfig ~= environmentConfiguration)
.settings(
Compile / bindgenBinary := (bindgen / Compile / nativeLink).value,
Test / bindgenBinary := (bindgen / Compile / nativeLink).value,
bindgenBindings := Seq.empty,
bindgenBinary := (bindgen / Compile / nativeLink).value,
Test / bindgenBindings := {
collectBindings((Test / resourceDirectory).value / "scala-native")
}
)
),
MatrixAction
.ForPlatform(VirtualAxis.jvm)
.Settings(
Seq(
Test / fork := true,
Test / envVars += "BINARY" -> (bindgen / Compile / nativeLink).value.toString,
Test / envVars += "BINDGEN_CLANG_PATH" -> (bindgen / Compile / nativeClang).value.toString,
libraryDependencies += "com.github.sbt" % "junit-interface" % Versions.junit % Test
)
)
)
.settings(
publish / skip := true,
publishLocal / skip := true,
testOptions += Tests.Argument(TestFrameworks.JUnit, "-a", "-s", "-v"),
Test / sources := {
val defaults = (Test / sources).value
if (Platform.os == Platform.OS.Windows)
defaults.filterNot(_.toString.toLowerCase.contains("no-windows"))
else defaults
}
)
lazy val scalaNativeLibParser = project
.in(file("modules/scalaNativeLib"))
.settings(scalaVersion := Versions.Scala213)
.settings(
libraryDependencies += "org.scalameta" %% "scalameta" % Versions.scalameta,
scalacOptions += "-Xsource:3"
)
lazy val docs =
project
.in(file("docs"))
.enablePlugins(SubatomicPlugin)
.settings(
scalaVersion := Versions.Scala3,
fork := true,
publish / skip := true,
Compile / run / envVars := Map(
"BINDGEN_BINARY" -> (bindgen / Compile / nativeLink).value.toString()
),
subatomicMdocVariables ++= previousStableVersion.value
.map("STABLE_VERSION" -> _)
.toMap,
libraryDependencies += "com.lihaoyi" %% "scalatags" % "0.12.0"
)
// --------------HELPERS-------------------------
def artifactFileNames: Map[Target, String] = {
import Platform.OS
import Platform.Arch
import Platform.Bits
val artifacts = for {
os <- Seq(OS.Windows, OS.Linux, OS.MacOS)
arch <- Seq(Arch.Intel, Arch.Arm)
bits <- Seq(Bits.x32, Bits.x64)
target = Platform.Target(os, arch, bits)
ext = os match {
case OS.Windows => ".exe"
case _ => ""
}
fileName = s"sn-bindgen-${coursierString(target)}$ext"
} yield target -> fileName
artifacts.toMap
}
def detectBinaryArtifacts: Map[String, (Artifact, File)] = if (
sys.env.contains("BINARIES")
) {
val folder = new File(sys.env("BINARIES"))
def build(classifier: String, file: File): (String, (Artifact, File)) = {
val artif = Artifact("bindgen", classifier)
.withExtension("jar")
.withType("jar")
.withConfigurations(Vector(Compile))
classifier -> (artif, file)
}
import scala.collection.JavaConverters.*
val allFiles = Files
.walk(folder.toPath)
.filter(path => path.toFile().isFile())
.collect(Collectors.toList())
.asScala
.map { path =>
path.getFileName().toString -> path.toFile
}
.toMap
artifactFileNames.flatMap { case (target, fileName) =>
allFiles.get(fileName).map { file =>
build(jarString(target), file)
}
}.toMap
} else Map.empty
def environmentConfiguration(conf: NativeConfig): NativeConfig = {
var modified = conf
if (sys.env.contains("SN_RELEASE"))
modified = modified.withMode(Mode.releaseFast)
if (sys.env.contains("SN_SANITIZE")) {
val opts =
"-fsanitize=address -fno-omit-frame-pointer -fsanitize-address-use-after-return=always"
.split(' ')
.toList
modified = modified
.withLinkingOptions(modified.linkingOptions ++ opts)
.withCompileOptions(modified.compileOptions ++ opts)
.withOptimize(false)
.withMode(Mode.debug)
.withLTO(LTO.none)
}
if (sys.env.contains("SN_GC"))
modified = modified.withGC(GC.apply(sys.env("SN_GC")))
modified
}
def usesLibClang(conf: NativeConfig) = {
val libraryName =
if (Platform.os == Platform.OS.Windows) "libclang" else "clang"
val detected = llvmFolder(conf.clang.toAbsolutePath())
val arm64 =
if (Platform.arch == Platform.Arch.Arm) Seq("-arch", "arm64") else Seq.empty
conf
.withLinkingOptions(
conf.linkingOptions ++
Seq("-l" + libraryName) ++
detected.llvmLib.map("-L" + _) ++ arm64
)
.withCompileOptions(
conf.compileOptions ++ detected.llvmInclude.map("-I" + _) ++ arm64
)
}
// --------------SETTINGS-------------------------
ThisBuild / resolvers ++= Resolver.sonatypeOssRepos("snapshots")
lazy val markdownDocuments = taskKey[Seq[java.nio.file.Path]]("")
markdownDocuments := {
markdownDocuments.inputFiles
}
markdownDocuments / fileInputs ++=
Seq(
(docs / baseDirectory).value.toGlob / "**" / "*.md",
(docs / baseDirectory).value.toGlob / "**" / "*.css",
(
docs / baseDirectory
).value.toGlob / "**" / "*.js"
)
lazy val buildBinary = inputKey[File]("")
buildBinary := {
import complete.DefaultParsers.*
val args: Seq[String] = spaceDelimited("<arg>").parsed
val built = (bindgen / Compile / nativeLink).value
val name =
args.headOption.getOrElse {
if (Platform.os == Platform.OS.Windows) "bindgen.exe" else "bindgen"
}
val dest = (ThisBuild / baseDirectory).value / "bin" / name
IO.copyFile(built, dest)
dest
}
lazy val buildPlatformBinary = taskKey[File]("")
buildPlatformBinary := {
val target = Platform.target
val name = artifactFileNames(target)
val built = (bindgen / Compile / nativeLink).value
val dest = (ThisBuild / baseDirectory).value / "bin" / name
IO.copyFile(built, dest)
sLog.value.info(s"Platform binary built in ${dest}")
dest
}
lazy val nativeCommon = Seq(
scalaVersion := Versions.Scala3
)
lazy val noTests = Seq(
test := {}
)
lazy val noPublish = Seq(
publish / skip := true,
publishLocal / skip := true
)
Global / onChangedBuildSource := ReloadOnSourceChanges
lazy val versionDump =
taskKey[Unit]("Dumps the version in a file named version")
versionDump := {
val file = (ThisBuild / baseDirectory).value / "version"
IO.write(file, (Compile / version).value)
}
def collectBindings(headersPath: File) = {
val files = headersPath.toGlob / "**" / "*.h"
import scala.collection.JavaConverters.*
val headerSpec = Files
.walk(headersPath.toPath, 1)
.collect(Collectors.toList())
.asScala
.filter(_.toFile().isFile())
.filter(_.toFile.ext == "h")
.map(h =>
h.toFile -> headersPath.toPath
.relativize(h)
.toString
.dropRight(2)
)
.toMap
def directives(pref: String, lines: List[String]): List[String] =
lines
.map(_.trim)
.filter(_.startsWith(pref))
.map(_.stripPrefix(pref).trim)
.flatMap(_.split(" "))
.map(_.trim)
headerSpec.toSeq.map { case (header, name) =>
val lines = IO.readLines(header)
val contents = directives("//!bindgen:", lines)
val pkg = directives("//!bindgen-package:", lines).headOption
val multiFileFlag = "--multi-file"
val isMultiFile = contents.contains(multiFileFlag)
Binding(header, pkg.getOrElse(s"lib_test_$name"))
.addCImport(s"$name.h")
.withBindgenArguments(contents.filterNot(_ == multiFileFlag))
.withMultiFile(isMultiFile)
}
}
def llvmFolder(clangPath: java.nio.file.Path): LLVMInfo = {
import Platform.OS.*
val LLVM_MAJOR_VERSION = "17"
Platform.os match {
case MacOS =>
val detected =
sys.env
.get("LLVM_BIN")
.map(Paths.get(_))
.map(_.getParent)
.filter(_.toFile.exists)
.toList
val speculative =
if (detected.isEmpty)
List(
Paths.get(s"/usr/local/opt/llvm@$LLVM_MAJOR_VERSION"),
Paths.get("/usr/local/opt/llvm"),
Paths.get(s"/opt/homebrew/opt/llvm@$LLVM_MAJOR_VERSION"),
Paths.get("/opt/homebrew/opt/llvm")
)
else Nil
val all = (detected ++ speculative).dropWhile(!_.toFile.exists())
val includes = all
.map(_.resolve("include"))
.map(_.toAbsolutePath().toString)
val lib = all
.map(_.resolve("lib"))
.map(_.toAbsolutePath().toString)
LLVMInfo(
llvmInclude = includes,
llvmLib = lib
)
case Linux | Windows =>
// <llvm-path>/bin/clang
val realPath = clangPath.toRealPath()
val binFolder = realPath.getParent()
val llvmFolder = binFolder.getParent()
if (llvmFolder.toFile.exists())
LLVMInfo(
llvmInclude = List(llvmFolder.resolve("include").toString),
llvmLib = List(llvmFolder.resolve("lib").toString)
)
else LLVMInfo(Nil, Nil)
case _ => LLVMInfo(Nil, Nil)
}
}
import sbtwelcome.*
logo :=
s"""
| C Binding generator for Scala 3 Native
|
| ######
| # # # # # ##### #### ###### # #
| # # # ## # # # # # # ## #
| ###### # # # # # # # ##### # # #
| # # # # # # # # # ### # # # #
| # # # # ## # # # # # # ##
| ###### # # # ##### #### ###### # #
|
|Version: ${version.value}
|Scala Native: ${nativeVersion}
|
|${scala.Console.YELLOW}Scala ${(bindgen / scalaVersion).value}${scala.Console.RESET}
|
|""".stripMargin
usefulTasks := Seq(
UsefulTask("buildBinary", "Build bindgen binary and copy it into bin/ folder")
.alias("bb"),
UsefulTask(
"interfaceTests",
"Run tests for JVM artifacts that interact with CLI (Scala 2.12, 2.13, 3)"
).alias("itt"),
UsefulTask("cliTests", "Run tests for just the CLI flags parsing").alias(
"ctt"
),
UsefulTask(
"generatorTests",
"Tests for generated code and its runtime correctness"
).alias("gtt"),
UsefulTask(
"pluginTests",
"Run SBT plugin tests"
).alias("ptt"),
UsefulTask(
"exportTests",
"Tests for generated exported definitions"
).alias("ett"),
UsefulTask(
"buildWebsite",
"Build the website"
).alias("bw"),
UsefulTask(
"buildWebsiteQuick",
"Build the website (quick, no mdoc)"
).alias("bwq"),
UsefulTask(
"devPublish",
"Build and publish everything sn-bindgen needs to your local cache"
).alias("dp"),
UsefulTask(
"ci",
"Run exactly what CI runs"
),
UsefulTask(
"preCI",
"Run formatting/scalafix"
)
)
addCommandAlias("generatorTests", "testsNative3/clean; testsNative3/test")
addCommandAlias("cliTests", "bindgen/test")
addCommandAlias("pluginTests", "plugin/scripted")
addCommandAlias(
"exportTests",
"exportTestsLibrary/runExportTests"
)
addCommandAlias("interfaceTests", "tests/test; tests3/test; tests2_12/test")
addCommandAlias(
"ci",
"scalafmtCheckAll; scalafmtSbtCheck; cliTests; interfaceTests; pluginTests; generatorTests; exportTests"
)
addCommandAlias(
"devPublish",
"publishLocal; localBindgenArtifact/publishLocal; show bindgen/version"
)
addCommandAlias("preCI", "scalafmtAll; scalafmtSbt")
logoColor := scala.Console.MAGENTA
lazy val buildWebsite = taskKey[Unit]("Build website in _site folder")
buildWebsite := Def.taskDyn {
val root = (ThisBuild / baseDirectory).value / "_site"
(docs / Compile / run).toTask(
s" build --destination ${root.toString} --force"
)
}.value
lazy val buildWebsiteQuick =
taskKey[Unit]("Build website in _site folder (without Mdoc)")
buildWebsiteQuick := Def.taskDyn {
val root = (ThisBuild / baseDirectory).value / "_site"
(docs / Compile / run).toTask(
s" build --destination ${root.toString} --force --disable-mdoc"
)
}.value
def artifactName(nm: String, axes: Seq[VirtualAxis]) = {
nm + axes
.sortBy[Int] {
case _: VirtualAxis.ScalaVersionAxis => 0
case _: VirtualAxis.PlatformAxis => 1
case _: VirtualAxis.StrongAxis => 2
case _: VirtualAxis.WeakAxis => 3
}
.map(_.idSuffix)
.mkString("-", "-", "")
}
lazy val remoteCacheMatrixSettings = Seq(
pushRemoteCacheTo := Some(
MavenCache(
"local-cache",
(ThisBuild / baseDirectory).value / "target" / "remote-cache"
)
),
Compile / packageCache / moduleName := artifactName(
moduleName.value,
virtualAxes.value
)
)
lazy val remoteCacheSettings = Seq(
pushRemoteCacheTo := Some(
MavenCache(
"local-cache",
(ThisBuild / baseDirectory).value / "target" / "remote-cache"
)
)
)
lazy val generateScalaNativeDefinitions = taskKey[Unit]("")
generateScalaNativeDefinitions := Def.taskDyn {
val tg = (scalaNativeLibParser / Keys.target).value / "github"
val destination = tg / "scala-native"
IO.createDirectory(destination)
import sys.process.*
def fetchTags =
Process(s"git fetch --tags", destination).!
def checkout =
Process(s"git checkout v${nativeVersion}", destination).!
def clone =
Process(
s"git clone https://github.com/scala-native/scala-native.git $destination",
tg
).!!
if ((destination / "build.sbt").isFile()) {
fetchTags; checkout
} else {
println(clone); fetchTags; checkout
}
val targetFile =
(bindgen / sourceDirectory).value / "main" / "scala" / "BuiltinType.scala"
assert(targetFile.isFile(), s"$targetFile must exist (or was it renamed?)")
(scalaNativeLibParser / Compile / run).toTask(s" $destination $targetFile")
}.value