Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for specifying environment variables in metadata.json #65

Merged
merged 4 commits into from
Jan 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,21 @@ Clone the repository:
```bash
git clone https://github.com/ForkbombEu/Twinroom
```
### Embedding Files

To embed files in your project, place them inside the `contracts` folder. Only contracts with the `.slang` extension will be considered for embedding.

For example:
```
contracts/
├── example1.slang
├── example2.slang
└── subfolder/
└── nested.slang
```
- Files such as `example1.slang` and `nested.slang` will be embedded.
- Other file types or folders not related to .slang files will be ignored during the embedding process, except for JSON files associated with the contracts.

### Build the executable:
You can build the executable using either the go build command or the provided Makefile.
Using go build:
Expand Down Expand Up @@ -112,14 +127,15 @@ hello.extra.json

### Command Arguments and Flags from `metadata.json`

In addition to the above parameters, Twinroom allows you to define custom arguments and flags for each embedded slangroom file using a metadata.json file. This file provides information on how to pass data to the contract through the CLI, including:
In addition to the above parameters, Twinroom allows you to define custom arguments, flags, and environment variables for each embedded slangroom file using a metadata.json file. This file provides information on how to pass data to the contract through the CLI, including:

* **Arguments**: Custom positional arguments for the command.
* **Options**: Custom flags that can be passed to the command.
* **Environment**: Key-value pairs of environment variables that are set dynamically when the command is executed.

#### Structure of `metadata.json`

The metadata file is automatically read by Twinroom to generate appropriate arguments and flags when executing embedded contract files. A typical metadata.json structure might look like this:
The metadata file is automatically read by Twinroom to generate appropriate arguments, flags, and environment variable settings when executing embedded contract files. A typical metadata.json structure might look like this:

```json
{
Expand Down Expand Up @@ -169,7 +185,11 @@ The metadata file is automatically read by Twinroom to generate appropriate argu
"file": true,
"rawdata": true
},
]
],
"environment": {
"VAR1": "value1",
"VAR2": "value2"
}
}
```
#### Field Descriptions:
Expand All @@ -187,6 +207,8 @@ The metadata file is automatically read by Twinroom to generate appropriate argu
* ***choices (optional)***: An array of allowed values for the flag, ensuring users provide a valid input.
* ***file (optional)***: If set to `true`, the flag requires a JSON file path. The file's contents will be added to the slangroom input data.
* ***rawdata (optional)***: If set to true alongside `file: true`, the contents of the file will be added as raw data, with the flag name serving as the key.
* **environment**:
* For example, "environment": `{ "VAR1": "value1", "VAR2": "value2" }` will set the environment variables `VAR1=value1` and`VAR2=value2` during command execution.

All values provided through arguments and flags are added to the slangroom input data as key-value pairs in the format `"flag_name": "value"`. If a parameter is present in both the CLI input and the corresponding `filename.data.json` file, the CLI input will take precedence, overwriting the value in the JSON file.

Expand Down
10 changes: 9 additions & 1 deletion cmd/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,9 @@ func addEmbeddedFileCommands() {
log.Printf("Failed to set arguments or flags: %v\n", err)
os.Exit(1)
}
isMetadata = true
if introspectionData != "" && introspectionData != "{}" {
isMetadata = true
}
}

fileCmd.PreRunE = func(cmd *cobra.Command, _ []string) error {
Expand Down Expand Up @@ -283,6 +285,12 @@ func runFileCommand(file fouter.SlangFile, args []string, metadata *utils.Comman
os.Exit(1)
}
if isMetadata {
for key, value := range metadata.Environment {
if err := os.Setenv(key, value); err != nil {
log.Println("Failed to set environment variable:", key)
os.Exit(1)
}
}
for i, arg := range args {
if i < len(metadata.Arguments) {
argContents[utils.NormalizeArgumentName(metadata.Arguments[i].Name)] = arg
Expand Down
1 change: 1 addition & 0 deletions cmd/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ type CommandMetadata struct {
Type string `json:"type,omitempty"`
Properties map[string]interface{} `json:"properties,omitempty"` // For complex object types
} `json:"options"`
Environment map[string]string `json:"environment,omitempty"` // Map of environment variable names to values
}

// FlagData contains the necessary data for a given flag
Expand Down
12 changes: 12 additions & 0 deletions contracts/test/read_from_path.metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"description": "read a file content from a path",
"options": [
{
"name": "-p, --file_path <path>",
"description": "file to read"
}
],
"environment": {
"FILES_DIR": "contracts/test"
}
}
4 changes: 4 additions & 0 deletions contracts/test/read_from_path.slang
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Rule unknown ignore
Given I send path 'file_path' and read verbatim file content and output into 'file_content'
Given I have a 'string' named 'file_content'
Then print the 'file_content'
22 changes: 22 additions & 0 deletions examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ func Example_listCmd() {
// Found file: test/hello
// Found file: test/introspection
// Found file: test/param
// Found file: test/read_from_path
// Found file: test/stdin
// Found file: test/test
// Found file: test/withschema
Expand Down Expand Up @@ -189,3 +190,24 @@ func Example_runCmdWithFilePath() {
// Output:
//{"file":"Hello World!"}
}

func Example_runCmdNeedEnvVariable() {
// Prepare the command to run the slang file
cmd := exec.Command("go", "run", "main.go", "test", "read_from_path", "-p", "hello.txt")
// Capture the output
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()

// Check for errors
if err != nil {
log.Println("Command execution failed:", err)
return
}

// Output the results
fmt.Print(out.String())

// Output:
//{"file_content":"Hello World!\n"}
}
Loading