### Setup Static Library Targets Source: https://github.com/google/jsonnet/blob/master/CMakeLists.txt Configures and builds static libraries for Jsonnet, including both C and C++ interfaces, based on build options. Installs them if BUILD_STATIC_LIBS is enabled. ```cmake if(BUILD_STATIC_LIBS OR (BUILD_SOME_BINARIES AND NOT BUILD_SHARED_BINARIES)) add_library(jsonnet_obj_static OBJECT) configure_jsonnet_obj_target(jsonnet_obj_static) add_library(jsonnet_static STATIC) configure_jsonnet_lib_target(jsonnet_static jsonnet_obj_static) add_library(jsonnet_cpp_static STATIC) configure_jsonnet_cpp_lib_target(jsonnet_cpp_static jsonnet_obj_static) if(BUILD_STATIC_LIBS) install(TARGETS jsonnet_static jsonnet_cpp_static) endif() endif() ``` -------------------------------- ### Install Jsonnet with vcpkg Source: https://github.com/google/jsonnet/blob/master/README.md Install Jsonnet using the vcpkg dependency manager. This involves cloning the vcpkg repository, bootstrapping it, integrating it with your system, and then installing Jsonnet. ```bash git clone https://github.com/Microsoft/vcpkg.git cd vcpkg ./bootstrap-vcpkg.sh ./vcpkg integrate install vcpkg install jsonnet ``` -------------------------------- ### Installation Source: https://github.com/google/jsonnet/blob/master/doc/third_party/js-yaml/README.md Instructions for installing the js-yaml package for Node.js and as a global CLI executable. ```APIDOC ## Installation ### YAML module for node.js ```bash npm install js-yaml ``` ### CLI executable If you want to inspect your YAML files from CLI, install js-yaml globally: ```bash npm install -g js-yaml ``` ``` -------------------------------- ### Install Jsonnet with Homebrew Source: https://github.com/google/jsonnet/blob/master/README.md Use Homebrew to install Jsonnet on macOS. ```bash brew install jsonnet ``` -------------------------------- ### Setup Shared Library Targets Source: https://github.com/google/jsonnet/blob/master/CMakeLists.txt Configures and builds shared libraries for Jsonnet, including C and C++ interfaces, with position-independent code. Installs them if BUILD_SHARED_LIBS is enabled. ```cmake if(BUILD_SHARED_LIBS OR (BUILD_SOME_BINARIES AND BUILD_SHARED_BINARIES)) add_library(jsonnet_obj_shared OBJECT) set_property(TARGET jsonnet_obj_shared PROPERTY POSITION_INDEPENDENT_CODE ON) configure_jsonnet_obj_target(jsonnet_obj_shared) add_library(jsonnet_shared SHARED) configure_jsonnet_lib_target(jsonnet_shared jsonnet_obj_shared) set_target_properties(jsonnet_shared PROPERTIES VERSION "${JSONNET_HEADER_VERSION}" SOVERSION "0") add_library(jsonnet_cpp_shared SHARED) configure_jsonnet_cpp_lib_target(jsonnet_cpp_shared jsonnet_obj_shared) set_target_properties(jsonnet_cpp_shared PROPERTIES VERSION "${JSONNET_HEADER_VERSION}" SOVERSION "0") if(BUILD_SHARED_LIBS) install(TARGETS jsonnet_shared jsonnet_cpp_shared) endif() endif() ``` -------------------------------- ### Install Jsonnet with MSYS2 Source: https://github.com/google/jsonnet/blob/master/README.md Install Jsonnet using pacman on MSYS2 for different architectures. ```bash pacman -S mingw-w64-clang-i686-jsonnet ``` ```bash pacman -S mingw-w64-clang-x86_64-jsonnet ``` ```bash pacman -S mingw-w64-i686-jsonnet ``` ```bash pacman -S mingw-w64-x86_64-jsonnet ``` ```bash pacman -S mingw-w64-ucrt-x86_64-jsonnet ``` -------------------------------- ### Install JS-YAML for Node.js Source: https://github.com/google/jsonnet/blob/master/doc/third_party/js-yaml/README.md Install the JS-YAML module for use in Node.js projects using npm. ```bash npm install js-yaml ``` -------------------------------- ### Install Jsonnet Python Binding Source: https://github.com/google/jsonnet/blob/master/README.md Install the Python binding for Jsonnet using pip. ```bash pip install jsonnet ``` -------------------------------- ### Object-Orientation Example in Jsonnet Source: https://github.com/google/jsonnet/blob/master/doc/learning/tutorial.html Demonstrates object-orientation in Jsonnet using hidden fields, the 'super' keyword, and deep field overrides. This example is contrived but illustrates core concepts. ```jsonnet local templates = import 'templates.libsonnet'; templates.Sour { // Override the spirit of the Sour. spirit: 'Pisco', } ``` -------------------------------- ### Install JS-YAML CLI Globally Source: https://github.com/google/jsonnet/blob/master/doc/third_party/js-yaml/README.md Install the js-yaml package globally to use its command-line interface for inspecting YAML files. ```bash npm install -g js-yaml ``` -------------------------------- ### Custom Import Callback Example Source: https://github.com/google/jsonnet/blob/master/PYTHON_README.md Demonstrates how to use a custom `import_callback` to load file content from memory. The callback should return a tuple of the file path and its content as bytes. ```python import _jsonnet FILES = { "the_message.txt": b"hello, world", } def import_callback_memfile(dir, rel): """Custom import function which only returns files from some in-memory storage. Args: dir: The directory part of the file in which the `import` occurred. rel: The path string passed to the `import` expression. """ if rel in FILES: # Note that the returned file _content_ should be a bytes value, not a string. return rel, FILES[rel] raise RuntimeError('File not found') result = _jsonnet.evaluate_snippet( 'example', 'local the_message = importstr "the_message.txt"; ' + '{ msg: the_message }', import_callback=import_callback_memfile) assert result == '{\n "msg": "hello, world"\n}\n'; ``` -------------------------------- ### Jsonnet Formatter Output Example Source: https://github.com/google/jsonnet/blob/master/doc/learning/tools.html Example of Jsonnet code after formatting. This shows the canonical form applied by jsonnetfmt, including consistent spacing, quoting, and structure. ```jsonnet // Edit me! local a = import 'a.libsonnet'; local b = import 'b.libsonnet'; // comment local f(x, y) = x + y; local Template = { z: 'foo', }; Template { f: (3), 'g g': f(4, 2), arr: [ [1, 2], 3, ], } ``` -------------------------------- ### Build Jsonnet with Bazel (GCC) Source: https://github.com/google/jsonnet/blob/master/README.md Build the Jsonnet project using Bazel with GCC. Ensure Bazel is installed and use the specified command to build all targets. ```bash bazel build -c opt //cmd:all ``` -------------------------------- ### newcommand Errors Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/localization.html Examples of incorrect usage of \newcommand and \def. ```jsonnet \( \newcommand{_INVALID_}{} \) ``` ```jsonnet \( \newcommand{mycommand}[INVALID]{} \) ``` ```jsonnet \( \let INVALID \) ``` ```jsonnet \( \def\mycommand#A \) ``` ```jsonnet \( \def\mycommand#2#1 \) ``` ```jsonnet \( \def\mycommand \) ``` ```jsonnet \( \def\mycommand[#1]#2[#3]{#1+#2+#3} \mycommand{a}{b}[c] \) ``` ```jsonnet \( \def\mycommand[#1][#2]#3{#1+#2+#3} \mycommand[a]{b} \) ``` -------------------------------- ### Extpfeil Errors Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/localization.html Examples of incorrect usage of \Newextarrow. ```jsonnet \( \Newextarrow{}{}{} \) ``` ```jsonnet \( \Newextarrow{\myarrow}{}{} \) ``` ```jsonnet \( \Newextarrow{\myarrow}{0,0}{} \) ``` -------------------------------- ### Display Bold Text Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/index-images.html Example of displaying bold text using TeX commands. ```tex \\bf MathJax\\ Image\\ Fonts\\ Appear\\ to\\ be\\ Working! ``` -------------------------------- ### Jsonnet Formatter Input Example Source: https://github.com/google/jsonnet/blob/master/doc/learning/tools.html Example of Jsonnet code before formatting. This snippet demonstrates various Jsonnet constructs including imports, function definitions, local variables, and object manipulation. ```jsonnet # Edit me! local b = import "b.libsonnet"; # comment local a = import "a.libsonnet"; local f(x,y)=x+y; local Template = {z: "foo"}; Template + { "f": ((3)) , "g g": f(4,2), arr: [[ 1, 2, ], 3, ] } ``` -------------------------------- ### Jsonnet Closure Example Source: https://github.com/google/jsonnet/blob/master/doc/ref/language.html.md Illustrates the creation and usage of closures in Jsonnet, where functions capture their surrounding environment. ```jsonnet local addNumber(number) = function(x) number + x; local add2 = addNumber(2); local add3 = addNumber(3); [ add2(2), add3(5) ] ``` -------------------------------- ### Jsonnet Sours Function Example Source: https://github.com/google/jsonnet/blob/master/doc/learning/tutorial.html A practical example demonstrating Jsonnet functions by defining a 'sours' function that calculates cocktail ingredients. This showcases parameter usage and object construction within functions. ```jsonnet local sours(spirit, citrus, sweetener) = { "spirit": spirit, "citrus": citrus, "sweetener": sweetener, "ice": "cubed", "garnish": "none" }; { "Whiskey Sour": sours("bourbon", "lemon juice", "simple syrup"), "Daiquiri": sours("rum", "lime juice", "simple syrup") } ``` -------------------------------- ### Call a Jsonnet program with Top-Level Arguments Source: https://github.com/google/jsonnet/blob/master/doc/ref/language.html.md Demonstrates how to execute a Jsonnet program using the `jsonnet` CLI, passing arguments directly on the command line with `--tla-code`. The example shows passing numeric arguments. ```bash jsonnet add.jsonnet --tla-code a=1 --tla-code b=2 ``` -------------------------------- ### Lexical Scoping Example in Jsonnet Source: https://github.com/google/jsonnet/blob/master/doc/ref/language.html.md Demonstrates lexical scoping in Jsonnet, showing how variable bindings are determined statically. ```jsonnet local a = local x = 'a'; x; local foo = local x = 'b'; a; foo ``` -------------------------------- ### Jsonnet Syntax Example Source: https://github.com/google/jsonnet/blob/master/doc/learning/tutorial.html Demonstrates basic Jsonnet syntax including unquoted fields, trailing commas, comments, string literals, text blocks, verbatim strings, and numeric literals with underscores. Use the interactive demo to experiment with modifications. ```jsonnet { "Martini": { "gin": "100ml", "vermouth": "5ml", "olive": true }, "Manhattan": { "whiskey": "60ml", "sweet Vermouth": "30ml", "bitters": "2 dashes", "cherry": true }, // A new cocktail "Dry Manhattan": { whiskey: "60ml", "dry vermouth": "30ml", bitters: "2 dashes", cherry: true } } ``` -------------------------------- ### Setup Object Library Properties Source: https://github.com/google/jsonnet/blob/master/CMakeLists.txt A utility function designed to set up all necessary properties for an OBJECT library used for the Jsonnet core. It handles differences in compilation flags, such as `-fPIC` for shared libraries. ```cmake # Utility function to set up all the properties for an OBJECT library for the jsonnet core. # # This is done as a function because there separate object libraries for shared vs. static. # Shared has slightly different compilation flags (it needs -fPIC). ``` -------------------------------- ### Jsonnet Comprehensions Example Source: https://github.com/google/jsonnet/blob/master/doc/learning/tutorial.html Demonstrates nested for and if constructs in Jsonnet comprehensions, behaving like loop nests. ```jsonnet { local drinks = [ { name: "Old Fashioned", ingredients: ["whiskey", "sugar", "bitters"] }, { name: "Daiquiri", ingredients: ["rum", "lime juice", "sugar"] }, { name: "Screwdriver", ingredients: ["vodka", "orange juice"] }, { name: "Red Screwdriver", ingredients: ["vodka", "cranberry juice"] }, ]; cocktails: [ drink.name for drink in drinks if std.length(drink.ingredients) > 2 ] } ``` -------------------------------- ### Serve Jsonnet Website Locally with Jekyll Source: https://github.com/google/jsonnet/blob/master/README.md Generate and serve the Jsonnet website locally using Jekyll. This command assumes you have Jekyll installed and the necessary wasm file downloaded. ```bash jekyll serve -s doc/ ``` -------------------------------- ### Jsonnet Error Handling Examples Source: https://github.com/google/jsonnet/blob/master/doc/learning/tutorial.html Illustrates how to raise errors and assert conditions in Jsonnet. Demonstrates lazy evaluation where code is not executed until needed. ```jsonnet { // This assertion will fail because the condition is false. fail_assertion: assert false : "This is a custom error message.", // This assertion will fail because the condition is false. fail_assertion_no_message: assert false, // This will throw an error because division by zero is not allowed. divide_by_zero: 1 / 0, // This will not throw an error because Jsonnet is lazy and this code is never evaluated. equal_parts: { local ingredients = [1, 2, 3]; local num_ingredients = std.length(ingredients); local equal_part = 1 / 0; // This would normally cause a division by zero error local result = [ ingredient * equal_part for ingredient in ingredients ]; }, } ``` -------------------------------- ### Jsonnetfmt CLI Executable Source: https://github.com/google/jsonnet/blob/master/CMakeLists.txt Defines the jsonnetfmt command-line executable, linking against the jsonnet library. Installation is conditional on BUILD_JSONNETFMT. ```cmake if(BUILD_JSONNETFMT OR BUILD_TESTS) add_executable(jsonnetfmt cmd/jsonnetfmt.cpp $ ) target_link_libraries(jsonnetfmt PRIVATE jsonnet_lib_for_binaries) if(BUILD_JSONNETFMT) install(TARGETS jsonnetfmt) endif() endif() ``` -------------------------------- ### Recursive function example Source: https://github.com/google/jsonnet/blob/master/doc/ref/language.html.md Illustrates referential transparency by showing a recursive function definition and its call. The call can be replaced by its definition. ```jsonnet local pow2(n) = if n == 0 then 1 else 2 * pow2(n - 1); pow2(17) ``` -------------------------------- ### Bug Report Template Example Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/CONTRIBUTING.md Use this template when creating a bug report on GitHub. Include a clear title, summary, steps to reproduce, and technical details about your environment. ```markdown Short and descriptive example bug report title ### Issue Summary A summary of the issue and the browser/OS environment in which it occurs. If suitable, include the steps required to reproduce the bug. ``` -------------------------------- ### Configure MathJax Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/sample-signals.html Configures MathJax extensions, input/output formats, and TeX options. This setup is essential before MathJax can process mathematical content. ```javascript // // Configure MathJax // MathJax.Hub.Config({ extensions: ["tex2jax.js","TeX/noUndefined.js"], jax: ["input/TeX","output/HTML-CSS"], tex2jax: { inlineMath: [["$","$"],["\\(","\\)"]] }, TeX: { extensions: ["AMSmath.js","AMSsymbols.js"] } }); ``` -------------------------------- ### Extract Substring with std.substr Source: https://github.com/google/jsonnet/blob/master/doc/ref/stdlib.html Use std.substr to get a portion of a string starting at a specific index for a given length. If the string is too short, it returns the available suffix. ```jsonnet std.substr("example string", 8, 6) ``` -------------------------------- ### Initialize and Configure Jsonnet C++ VM Source: https://context7.com/google/jsonnet/llms.txt Demonstrates initializing the Jsonnet C++ VM and setting various configuration options like stack limits, garbage collection parameters, and output format. Use this to set up the environment before evaluating Jsonnet code. ```cpp #include #include #include #include int main() { jsonnet::Jsonnet jsonnet; // Initialize the VM if (!jsonnet.init()) { std::cerr << "Failed to initialize Jsonnet VM" << std::endl; return 1; } // Configure the VM jsonnet.setMaxStack(500); jsonnet.setGcMinObjects(1000); jsonnet.setGcGrowthTrigger(2.0); jsonnet.setMaxTrace(20); jsonnet.setStringOutput(false); // JSON output // Add library search paths jsonnet.addImportPath("/path/to/libs"); jsonnet.addImportPath("./local/libs"); // Set external variables jsonnet.bindExtVar("prefix", "Production "); jsonnet.bindExtCodeVar("debug", "false"); // Set top-level arguments jsonnet.bindTlaVar("name", "MyApp"); jsonnet.bindTlaCodeVar("replicas", "3"); // Evaluate a file std::string output; if (!jsonnet.evaluateFile("config.jsonnet", &output)) { std::cerr << "Error: " << jsonnet.lastError() << std::endl; return 1; } std::cout << output << std::endl; // Evaluate a snippet std::string snippet_output; if (!jsonnet.evaluateSnippet( "snippet", "{ x: 1, y: self.x + 1 }", &snippet_output)) { std::cerr << "Error: " << jsonnet.lastError() << std::endl; return 1; } // Multi-file output std::map outputs; if (!jsonnet.evaluateFileMulti("multi.jsonnet", &outputs)) { std::cerr << "Error: " << jsonnet.lastError() << std::endl; return 1; } for (const auto& [filename, content] : outputs) { std::cout << "File: " << filename << std::endl; std::cout << content << std::endl; } return 0; } ``` -------------------------------- ### Serve Jsonnet Documentation Locally Source: https://github.com/google/jsonnet/blob/master/release_checklist.md Build or download libjsonnet.wasm, then use Jekyll to serve the documentation locally for testing. Ensure live evaluation in the tutorial works across different browsers. ```bash jekyll serve -s docs/ ``` -------------------------------- ### Bazel Jsonnet Rules Source: https://github.com/google/jsonnet/blob/master/doc/learning/tools.html Example of Bazel rules for integrating Jsonnet into your build system. These rules facilitate configuration generation as part of the build process. ```bazel jsonnet_library ``` ```bazel jsonnet_to_json ``` ```bazel jsonnet_to_json_test ``` -------------------------------- ### Define Pod Spec with Environment Variables Source: https://github.com/google/jsonnet/blob/master/doc/articles/kubernetes.html Defines a PodSpec with containers and their environment variables using a structured approach. This example sets up environment variables for 'foo' and 'bar' containers. ```jsonnet local PodSpec = { containers: [ { name: 'foo', env: [ { name: 'var1', value: 'somevalue' }, { name: 'var2', value: 'somevalue' }, ], }, { name: 'bar', env: [ { name: 'var2', value: 'somevalue' }, { name: 'var3', value: 'somevalue' }, ], }, ], }; ``` -------------------------------- ### Jsonnet Functions Source: https://github.com/google/jsonnet/blob/master/doc/learning/tutorial.html Explains Jsonnet functions, including positional and named parameters, default arguments, and closures. Mentions the standard library and provides an example for creating a custom function. ```jsonnet local is_even(n) = n % 2 == 0; { "is_4_even": is_even(4), "is_5_even": is_even(5) } ``` -------------------------------- ### Convert YAML to Jsonnet for Kubernetes Source: https://github.com/google/jsonnet/blob/master/doc/articles/kubernetes.html This tool converts YAML Kubernetes manifests into basic Jsonnet files. It helps in getting started with Jsonnet for Kubernetes configuration but loses original comments and requires further cleanup to remove duplication. ```yaml kind: ReplicationController apiVersion: v1 metadata: name: spark-master-controller spec: replicas: 1 selector: component: spark-master template: metadata: labels: component: spark-master spec: containers: - name: spark-master image: k8s.gcr.io/spark:1.5.2_v1 command: - "/start-master" ports: - containerPort: 7077 - containerPort: 8080 resources: requests: cpu: 100m ``` ```jsonnet { kind: 'ReplicationController', apiVersion: 'v1', metadata: { name: 'spark-master-controller' }, spec: { replicas: 1, selector: { component: 'spark-master' }, template: { metadata: { labels: { component: 'spark-master' } }, spec: { containers: [ { name: 'spark-master', image: 'k8s.gcr.io/spark:1.5.2_v1', command: [ '/start-master' ], ports: [ { containerPort: 7077 }, { containerPort: 8080 } ], resources: { requests: { cpu: '100m' } } } ] } } } } ``` -------------------------------- ### Run Bazel-built Binaries Source: https://github.com/google/jsonnet/blob/master/README.md Execute the Jsonnet and jsonnetfmt binaries built with Bazel. ```bash bazel-bin/cmd/jsonnet ``` ```bash bazel-bin/cmd/jsonnetfmt ``` -------------------------------- ### Basic Equation and Tagged Equation Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/sample-eqnum.html Demonstrates rendering a basic equation and a tagged equation using the \begin{equation} environment. ```tex \begin{equation} E = mc^2 \end{equation} ``` ```tex \begin{equation} E = mc^2 \tag{x} \end{equation} ``` -------------------------------- ### Add File to Startup Script Source: https://github.com/google/jsonnet/blob/master/doc/articles/fractal.2.html Generates a bash command to add a file to the startup script. Use this when you need to include specific files during instance initialization. ```jsonnet addFile(v, dest):: "echo %s > %s" % [std.escapeStringBash(v), std.escapeStringBash(dest)], ``` -------------------------------- ### User-Configurable Options Source: https://github.com/google/jsonnet/blob/master/CMakeLists.txt Sets up various build options that can be configured by the user, such as enabling/disabling the build of command-line tools, tests, static/shared libraries, and man pages. It also includes options for using system-provided libraries like gtest, json, and rapidyaml. ```cmake option(BUILD_JSONNET "Build jsonnet command-line tool." ON) option(BUILD_JSONNETFMT "Build jsonnetfmt command-line tool." ON) option(BUILD_TESTS "Build and run jsonnet tests." ON) option(BUILD_STATIC_LIBS "Build a static libjsonnet." ON) option(BUILD_SHARED_LIBS "Build shared libjsonnet." ON) option(BUILD_SHARED_BINARIES "Link binaries to the shared libjsonnet instead of the static one." OFF) option(BUILD_MAN_PAGES "Build manpages." ON) option(USE_SYSTEM_GTEST "Use system-provided gtest library" OFF) option(USE_SYSTEM_JSON "Use the system-provided json library" OFF) option(USE_SYSTEM_RAPIDYAML "Use the system-provided rapidyaml library" OFF) ``` -------------------------------- ### Jsonnet Sours Object-Oriented Example Source: https://github.com/google/jsonnet/blob/master/doc/learning/tutorial.html This example showcases an object-oriented approach to defining sours in Jsonnet. It utilizes object composition and inheritance patterns. ```jsonnet local sours = { "whiskey sour": { "whiskey": "bourbon", "lemon juice": "1 oz", "simple syrup": "0.5 oz", "garnish": "cherry", }, "pisco sour": { "pisco": "1.5 oz", "lemon juice": "1 oz", "simple syrup": "0.5 oz", "egg white": "1", "garnish": "angostura", }, }; local base = { "gin": "bombay", "vermouth": "dry", "garnish": "lemon twist", }; { "martini": base + cocktails.martini } // Apply overrides to base ``` -------------------------------- ### Run Comprehensive Tests Source: https://github.com/google/jsonnet/blob/master/README.md Execute the full suite of tests for Jsonnet using the Makefile. ```bash make test ``` -------------------------------- ### Initialize and Configure Jsonnet VM (C API) Source: https://context7.com/google/jsonnet/llms.txt Initializes a Jsonnet VM using the C API and configures its parameters such as stack limits, garbage collection settings, and error trace depth. This provides fine-grained control over the evaluation environment. ```c #include #include #include int main(int argc, char **argv) { // Create a new Jsonnet VM struct JsonnetVm *vm = jsonnet_make(); // Configure the VM jsonnet_max_stack(vm, 500); jsonnet_gc_min_objects(vm, 1000); jsonnet_gc_growth_trigger(vm, 2.0); jsonnet_max_trace(vm, 20); // Add library search paths jsonnet_jpath_add(vm, "/path/to/libs"); jsonnet_jpath_add(vm, "./local/libs"); // Set external variables jsonnet_ext_var(vm, "prefix", "Production "); jsonnet_ext_code(vm, "debug", "false"); // Set top-level arguments jsonnet_tla_var(vm, "name", "MyApp"); jsonnet_tla_code(vm, "replicas", "3"); // Evaluate a file int error; char *output = jsonnet_evaluate_file(vm, "config.jsonnet", &error); if (error) { fprintf(stderr, "Error: %s\n", output); jsonnet_realloc(vm, output, 0); // Free error message jsonnet_destroy(vm); return 1; } printf("%s\n", output); // Clean up jsonnet_realloc(vm, output, 0); // Free output jsonnet_destroy(vm); return 0; } ``` -------------------------------- ### Get All Fields from an Object Source: https://github.com/google/jsonnet/blob/master/doc/ref/stdlib.html Use `std.objectFields` to get an array of all field names (strings) in an object, excluding hidden fields. Available since version 0.10.0. ```jsonnet std.objectFields(o) ``` -------------------------------- ### Jsonnet Mixins Example Source: https://github.com/google/jsonnet/blob/master/doc/learning/tutorial.html This example demonstrates how to use mixins in Jsonnet to modify cocktails in a general way. It shows the core concept of applying overrides to existing objects. ```jsonnet local cocktails = { "martini": { "gin": "plymouth", "vermouth": "dry", "garnish": "olive", }, "manhattan": { "whiskey": "rye", "vermouth": "sweet", "bitters": "angostura", "garnish": "cherry", }, }; local sours = { "whiskey sour": { "whiskey": "bourbon", "lemon juice": "1 oz", "simple syrup": "0.5 oz", "garnish": "cherry", }, "pisco sour": { "pisco": "1.5 oz", "lemon juice": "1 oz", "simple syrup": "0.5 oz", "egg white": "1", "garnish": "angostura", }, }; local base = { "gin": "bombay", "vermouth": "dry", "garnish": "lemon twist", }; { "martini": base + cocktails.martini } // Apply overrides to base ``` -------------------------------- ### Align and Align* Environments Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/sample-eqnum.html The \begin{align} environment is for aligning multiple equations at specific points (like the equals sign). \begin{align*} is the unnumbered version. ```tex \begin{align} a_1& =b_1+c_1\\ a_2& =b_2+c_2-d_2+e_2 \end{align} ``` ```tex \begin{align*} a_1& =b_1+c_1\\ a_2& =b_2+c_2-d_2+e_2 \end{align*} ``` ```tex \begin{align} a_{11}& =b_{11}& a_{12}& =b_{12}\\ a_{21}& =b_{21}& a_{22}& =b_{22}+c_{22} \end{align} ``` -------------------------------- ### Jsonnet Basic Syntax with Comments and Text Blocks Source: https://context7.com/google/jsonnet/llms.txt Demonstrates basic Jsonnet syntax including C-style and Python-style comments, object definition, arrays, and multi-line text blocks using |||. ```jsonnet /* A C-style comment. */ # A Python-style comment. { cocktails: { // Ingredient quantities are in fl oz. 'Tom Collins': { ingredients: [ { kind: "Farmer's Gin", qty: 1.5 }, { kind: 'Lemon', qty: 1 }, { kind: 'Simple Syrup', qty: 0.5 }, { kind: 'Soda', qty: 2 }, { kind: 'Angostura', qty: 'dash' }, ], garnish: 'Maraschino Cherry', served: 'Tall', // Multi-line text block (||| preserves newlines) description: ||| The Tom Collins is essentially gin and lemonade. The bitters add complexity. |||, }, Manhattan: { ingredients: [ { kind: 'Rye', qty: 2.5 }, { kind: 'Sweet Red Vermouth', qty: 1 }, { kind: 'Angostura', qty: 'dash' }, ], garnish: 'Maraschino Cherry', served: 'Straight Up', // Verbatim string (@'...' preserves backslashes) description: @'A clear \ red drink.', }, }, } ``` -------------------------------- ### Get All Fields from an Object (Including Hidden) Source: https://github.com/google/jsonnet/blob/master/doc/ref/stdlib.html Use `std.objectFieldsAll` to get an array of all field names (strings) from an object, including hidden fields. Available since version 0.10.0. ```jsonnet std.objectFieldsAll(o) ``` -------------------------------- ### Initialize MathJax Queue and Display Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/sample-dynamic.html Sets up MathJax queue management and element handling for dynamic math rendering. It hides the output box initially to prevent flickering during updates. ```javascript // // Use a closure to hide the local variables from the // global namespace // (function () { var QUEUE = MathJax.Hub.queue; // shorthand for the queue var math = null, box = null; // the element jax for the math output, and the box it's in // // Hide and show the box (so it doesn't flicker as much) // var HIDEBOX = function () {box.style.visibility = "hidden"} var SHOWBOX = function () {box.style.visibility = "visible"} // // Get the element jax when MathJax has produced it. // QUEUE.Push(function () { math = MathJax.Hub.getAllJax("MathOutput")[0]; box = document.getElementById("box"); SHOWBOX(); // box is initially hidden so the braces don't show }); // // The onchange event handler that typesets the math entered // by the user. Hide the box, then typeset, then show it again // so we don't see a flash as the math is cleared and replaced. // window.UpdateMath = function (TeX) { QUEUE.Push( HIDEBOX, ["resetEquationNumbers",MathJax.InputJax.TeX], ["Text",math,"\\displaystyle{"+TeX+"}"], SHOWBOX ); } })(); ``` -------------------------------- ### Get Keys and Values from an Object Source: https://github.com/google/jsonnet/blob/master/doc/ref/stdlib.html Use `std.objectKeysValues` to get an array of objects, each containing a 'key' and 'value' field from the original object, excluding hidden fields. Available since version 0.20.0. ```jsonnet std.objectKeysValues(o) ``` -------------------------------- ### Build Jsonnet with Make (Clang) Source: https://github.com/google/jsonnet/blob/master/README.md Build the Jsonnet project using Make with Clang as the compiler. Specify the C and C++ compilers using CC and CXX environment variables. ```bash make CC=clang CXX=clang++ ``` -------------------------------- ### Build Jsonnet with Make (GCC) Source: https://github.com/google/jsonnet/blob/master/README.md Build the Jsonnet project using Make with GCC as the compiler. ```bash make ``` -------------------------------- ### Get Keys and Values from an Object (Including Hidden) Source: https://github.com/google/jsonnet/blob/master/doc/ref/stdlib.html Use `std.objectKeysValuesAll` to get an array of objects, each containing 'key' and 'value' fields from the original object, including hidden fields. Available since version 0.20.0. ```jsonnet std.objectKeysValuesAll(o) ``` -------------------------------- ### Download libjsonnet.wasm Source: https://github.com/google/jsonnet/blob/master/README.md Download the libjsonnet.wasm file from the production website using wget. This file is needed for locally serving the Jsonnet website. ```bash wget https://jsonnet.org/js/libjsonnet.wasm -O doc/js/libjsonnet.wasm ``` -------------------------------- ### mhchem Errors Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/localization.html Examples of errors in the mhchem package. ```jsonnet \( \ce{ ->[ } \) ``` -------------------------------- ### Color Errors Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/localization.html Examples of incorrect color definitions and usage. ```jsonnet \( \color[COLORMODEL]{}{} \) ``` ```jsonnet \( \color[RGB]{}{} \) ``` ```jsonnet \( \color[rgb]{,,}{} \) ``` ```jsonnet \( \color[RGB]{256,,}{} \) ``` ```jsonnet \( \color[RGB]{,,}{} \) ``` -------------------------------- ### Run Go Jsonnet Tests Source: https://github.com/google/jsonnet/blob/master/release_checklist.md Execute Go Jsonnet tests using the provided script and bazel. This is a crucial step for ensuring the Go implementation is stable. ```bash ./tests.sh ``` ```bash bazel test //:go_default_test ``` -------------------------------- ### Begingroup Errors Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/localization.html Examples of errors related to \begingroup and \endgroup. ```jsonnet \( \endgroup \) ``` ```jsonnet \( \global\unknown \) ``` -------------------------------- ### Bbox Errors Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/localization.html Examples of incorrect usage of the \bbox command. ```jsonnet \( \bbox[green,blue]{} \) ``` ```jsonnet \( \bbox[_INVALID_]{} \) ``` -------------------------------- ### Configure Application Instance with Jsonnet Source: https://github.com/google/jsonnet/blob/master/doc/articles/fractal.2.html This snippet shows how to configure an application instance using Jsonnet, defining database connection details and service endpoints. The configuration is passed as a JSON object to the instance. ```jsonnet resource.FractalInstance(k) { ... conf:: ApplicationConf { database_name: cassandraKeyspace, database_user: cassandraUser, database_pass: credentials.cassandraUserPass, tilegen: "${google_compute_address.tilegen.address}", db_endpoints: cassandraNodes, }, ``` -------------------------------- ### Jsonnet Emulating Functions with Objects Source: https://github.com/google/jsonnet/blob/master/doc/ref/language.html.md Shows how objects can be used to emulate functions by defining parameters and results, with dynamic inheritance for argument passing. ```jsonnet local add = { params: { a: error "please provide argument a", b: error "please provide argument b", }, result: self.params.a + self.params.b }; (add + { params: { a: 1, b: 2} }).result ``` -------------------------------- ### Math Syntax Errors Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/localization.html Examples of incorrect mathematical syntax in Jsonnet. ```jsonnet \( \right) \) ``` ```jsonnet \( x^ \) ``` ```jsonnet \( \left( \) ``` ```jsonnet \( & \) ``` ```jsonnet \( x__ \) ``` ```jsonnet \( x^^ \) ``` ```jsonnet \( x \over y \over z \) ``` ```jsonnet \( \begin{aligned} \end{eqarray} \) ``` ```jsonnet \( \begin{aligned} \) ``` ```jsonnet \( \raise 1pt \) ``` ```jsonnet \( \array{ \) ``` ```jsonnet \( \UNDEFINED \) ``` ```jsonnet \( x^3^2 \) ``` ```jsonnet \( x_3_2 \) ``` ```jsonnet \( x^2' \) ``` ```jsonnet \( # \) ``` ```jsonnet \( \middle| \) ``` ```jsonnet \( \limits \) ``` ```jsonnet \( \uproot \) ``` ```jsonnet \( \sqrt[\uproot{INVALID}]{x} \) ``` ```jsonnet \( \mmlToken{INVALID}{x} \) ``` ```jsonnet \( \mmlToken{mi}[_INVALID_]{x} \) ``` ```jsonnet \( \mmlToken{mi}[INVALIDATTR='']{x} \) ``` ```jsonnet \( \newcommand{\a}{\a} \a \) ``` ```jsonnet \( \newenvironment{a}{\begin{a}}{\end{a}} \begin{a}\end{a} \) ``` ```jsonnet \( \frac{a} \) ``` ```jsonnet \( \cases{a & b & c} \) ``` ```jsonnet \(\begin{array} x \\ [INVALID] y \end{array}\) ``` ```jsonnet \( \begin{_INVALID_} \end{_INVALID_} \) ``` ```jsonnet \( \begin{UNKNOWN} \end{UNKNOWN} \) ``` ```jsonnet \( \sqrt[}]x \) ``` ```jsonnet \( \sqrt[ \) ``` ```jsonnet \( \left \) ``` ```jsonnet \( x \above y \) ``` ```jsonnet \( \root{x} \) ``` ```jsonnet \( \text{$x} \) ``` ```jsonnet \( \def\mymacro#1{#2} \mymacro{x} \) ``` ```jsonnet \( \newcommand{\a}{\a\a} \a \) ``` -------------------------------- ### Verbbatim String Errors Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/localization.html Example of a missing closing delimiter for a verbatim string. ```jsonnet \( \verb?... \) ``` -------------------------------- ### Run Jsonnet Binary Source: https://github.com/google/jsonnet/blob/master/README.md Execute the compiled Jsonnet binary from the command line. ```bash ./jsonnet ``` -------------------------------- ### Array literal example Source: https://github.com/google/jsonnet/blob/master/doc/ref/language.html.md A simple array literal containing elements of different types. ```jsonnet [1, 2, "foo", 2 + 2] ``` -------------------------------- ### Importing Jsonnet Libraries and Data Source: https://github.com/google/jsonnet/blob/master/doc/learning/tutorial.html Shows how to import Jsonnet code, raw JSON, and text files. Imported Jsonnet libraries typically return an object. ```jsonnet local cosmopolitans = import 'martinis.libsonnet'; local garnish = importstr 'garnish.txt'; { cosmopolitan: cosmopolitans.cosmopolitan, garnish: garnish, } ``` ```jsonnet local martinis = { gin: { gin: 1, vermouth: 1, "olive or lemon twist": 1, }, vodka: { vodka: 1, vermouth: 1, "olive or lemon twist": 1, }, cosmopolitan: { vodka: 2, "cranberry juice": 3, "lime juice": 0.5, "triple sec": 0.5, }, }; martinis ``` ```text Garnish: Cherry ``` -------------------------------- ### AMS Math Environment Errors Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/localization.html Examples of errors within AMS math environments. ```jsonnet \(\begin{split} x \tag{x} \end{split} \) ``` ```jsonnet \( \tag{x} \tag{y} \) ``` ```jsonnet \( \label{x} \) \(\ \label{x} \) ``` ```jsonnet \( \shoveleft \) ``` ```jsonnet \( \cfrac[INVALID]{a}{b} \) ``` ```jsonnet \( \genfrac{\{}{\}}{0pt}{INVALID}{a}{b} \) ``` ```jsonnet \(\begin{alignedat}{INVALID}\end{alignedat}\) ``` ```jsonnet \( \begin{multline} \begin{multline} \end{multline} \end{multline} \) ``` ```jsonnet \( \begin{multline} x & y \end{multline} \) ``` -------------------------------- ### Post Custom Signal During MathJax Startup Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/sample-signals.html Posts a custom signal during the MathJax startup phase to indicate that the configuration code is running. This signal can be intercepted by other listeners. ```javascript // // Display a message that we are in the configuration code // (The Message function is not yet defined when this code // runs, so we can't use that here. Post a signal // of our own, so it will be displayed along with all // the other signals). // MathJax.Hub.Startup.signal.Post("*** In Startup Configuration code ***"); ``` -------------------------------- ### Split Equation Environment Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/sample-eqnum.html Use the \begin{split} environment within \begin{equation} for multi-line equations that should be treated as a single numbered unit. ```tex \begin{equation} \begin{split} a& =b+c-d\\ & \quad +e-f\\ & =g+h\\ & =i \end{split} \end{equation} ``` -------------------------------- ### Display Mathematical Equation Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/index-images.html Example of a mathematical equation using TeX notation, intended to be rendered by MathJax. ```tex \\\\[ \frac{-b\\pm\\sqrt{b^2-4ac}}{2a} \\\\\] ``` -------------------------------- ### Build Jsonnet with Bazel (Clang) Source: https://github.com/google/jsonnet/blob/master/README.md Build the Jsonnet project using Bazel with Clang. This can be done by setting the CC and CXX environment variables or using Bazel's action environment flags. ```bash env CC=clang CXX=clang++ bazel build -c opt //cmd:all ``` ```bash bazel build -c opt --action_env=CC=clang --action_env=CXX=clang++ //cmd:all ``` -------------------------------- ### String Prefix and Suffix Checks Source: https://github.com/google/jsonnet/blob/master/doc/ref/stdlib.html Functions to check if a string starts or ends with a specific prefix or suffix. ```APIDOC ## std.startsWith(a, b) ### Description Returns whether the string `a` is prefixed by the string `b`. ### Method Function ### Parameters - **a** (string) - The string to check. - **b** (string) - The prefix string. ``` ```APIDOC ## std.endsWith(a, b) ### Description Returns whether the string `a` is suffixed by the string `b`. ### Method Function ### Parameters - **a** (string) - The string to check. - **b** (string) - The suffix string. ``` -------------------------------- ### Gather and Gather* Environments Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/sample-eqnum.html The \begin{gather} environment is used for multiple equations on separate lines, each centered independently. \begin{gather*} is the unnumbered version. ```tex \begin{gather} a_1=b_1+c_1\\ a_2=b_2+c_2-d_2+e_2 \end{gather} ``` ```tex \begin{gather*} a_1=b_1+c_1\\ a_2=b_2+c_2-d_2+e_2 \end{gather*} ``` -------------------------------- ### Jsonnet CLI Executable Source: https://github.com/google/jsonnet/blob/master/CMakeLists.txt Defines the jsonnet command-line executable, linking against the jsonnet library. Installation is conditional on BUILD_JSONNET. ```cmake if(BUILD_JSONNET OR BUILD_TESTS) add_executable(jsonnet cmd/jsonnet.cpp $ ) target_link_libraries(jsonnet PRIVATE jsonnet_lib_for_binaries) if(BUILD_JSONNET) install(TARGETS jsonnet) endif() endif() ``` -------------------------------- ### Render Bold Text in LaTeX Source: https://github.com/google/jsonnet/blob/master/doc/third_party/MathJax-2.7.2/test/index.html Demonstrates rendering bold text using the \\bf command in LaTeX. ```tex \\bf MathJax\\ Appears\\ to\\ be\\ Working! ``` -------------------------------- ### Jsonnet Error Handling and Configuration Example Source: https://context7.com/google/jsonnet/llms.txt This snippet demonstrates custom error messages using the 'error' keyword, input validation with assertions, and conditional error handling based on environment variables. It also shows how to use std.assertEqual for validation and how to structure configurations. ```jsonnet local validate_port(port) = if port < 1 || port > 65535 then error 'Invalid port: %d (must be 1-65535)' % port else port; local config = { // Assertion with custom message assert self.replicas > 0 : 'replicas must be positive', replicas: 3, // Using std.assertEqual port:: validate_port(8080), validated: std.assertEqual(self.port, 8080), // Conditional error database: if std.extVar('DB_HOST') == '' then error 'DB_HOST environment variable is required' else { host: std.extVar('DB_HOST'), port: 5432, }, }; // Using assertions in objects { config: config, // Inline assertion result: ( assert std.length(config.database.host) > 0; 'Database configured at %s:%d' % [ config.database.host, config.database.port, ] ), } ``` -------------------------------- ### Check if a string starts with a prefix using std.startsWith Source: https://github.com/google/jsonnet/blob/master/doc/ref/stdlib.html Use std.startsWith to determine if a string begins with a specified prefix. ```jsonnet std.startsWith("hello world", "hello") ``` -------------------------------- ### Find all occurrences of a substring with std.findSubstr Source: https://github.com/google/jsonnet/blob/master/doc/ref/stdlib.html std.findSubstr returns an array of all starting indices where a pattern occurs within a string. ```jsonnet std.findSubstr("aba", "abababa") ``` -------------------------------- ### Commit Version Changes Source: https://github.com/google/jsonnet/blob/master/release_checklist.md Commit the version number changes with a descriptive message. This example uses a release candidate tag. ```bash git commit -m "release: prepare to release v0.21.0-rc2" ```