### Terramate LSP Sandbox Test Setup Source: https://github.com/terramate-io/terramate/blob/main/AGENTS.md Example of setting up a sandbox environment for testing Language Server Protocol (LSP) functionality in Terramate. ```go s := sandbox.New(t) s.BuildTree([]string{ `f:path/to/file.tm:content`, `s:stack/path`, // Create stack }) ``` -------------------------------- ### Environment Setup for Stack Execution Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/constants-and-exports.md Defines the environment structure and setup function for stack execution, including environment variables. ```go // Stack environment setup type Env struct { // Environment variables for stack execution } // Functions for setting up execution environment func SetupEnv(root *config.Root, stack *config.Stack) (*Env, error) ``` -------------------------------- ### Install tgdeps using make Source: https://github.com/terramate-io/terramate/blob/main/cmd/tgdeps/README.md Install the tgdeps tool by cloning the Terramate project and running the make install/tgdeps command. ```bash $ make install/tgdeps ``` -------------------------------- ### Structured Logging with Zerolog Source: https://github.com/terramate-io/terramate/blob/main/AGENTS.md Examples of using the zerolog library for structured logging with different log levels and context. ```go // Use zerolog for structured logging log.Debug().Str("key", value).Msg("description") log.Info().Int("count", n).Msg("operation complete") log.Error().Err(err).Msg("operation failed") ``` -------------------------------- ### Install tgdeps using go install Source: https://github.com/terramate-io/terramate/blob/main/cmd/tgdeps/README.md Install the tgdeps tool using the go install command with a specific version. ```bash go install github.com/terramate-io/terramate/cmd/tgdeps@ ``` -------------------------------- ### Install Dependencies and Check Versions Source: https://github.com/terramate-io/terramate/blob/main/AGENTS.md Installs all project dependencies using the ASDF package manager and checks the Go and make versions. ```bash # Install all dependencies using the ASDF package manager asdf install # Check versions go version # Should be 1.24+ make --version ``` -------------------------------- ### Install Terramate CLI with Go Source: https://github.com/terramate-io/terramate/blob/main/README.md Install the Terramate CLI using the Go programming language's install command. Ensure your Go environment is set up correctly. ```sh go install github.com/terramate-io/terramate/cmd/...@latest ``` -------------------------------- ### Get Configuration Tree Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Retrieves the entire configuration tree of the project. ```go tree := root.Tree() ``` -------------------------------- ### Full Git Wrapper Usage Example Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Demonstrates creating a Git wrapper, checking repository status, listing dirty files, and staging/committing changes. ```go // Create git wrapper git, err := git.WithConfig(git.Config{ Username: "Bot User", Email: "bot@example.com", WorkingDir: "/path/to/repo", AllowPorcelain: true, }) if err != nil { log.Fatal(err) } // Check if it's a repository if !git.IsRepository() { log.Fatal("Not a git repository") } // Get modified and untracked files modified, untracked, err := git.ListDirtyFiles() if err != nil { log.Fatal(err) } // Stage and commit changes if len(modified) > 0 { if err := git.Add(modified...); err != nil { log.Fatal(err) } if err := git.Commit("Automated update"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Get Git Version Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Retrieves the version of the installed Git program. This is useful for verifying the Git installation and compatibility. ```go version, err := gitWrapper.Version() if err != nil { log.Fatal(err) } fmt.Println("Git version:", version) ``` -------------------------------- ### Get All Stack Paths Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Returns a list of all stack paths present in the project. ```go allStacks := root.Stacks() for _, stackPath := range allStacks { fmt.Println(stackPath) } ``` -------------------------------- ### Testing Pattern with Sandbox in Go Source: https://github.com/terramate-io/terramate/blob/main/AGENTS.md Example of using a sandbox environment for file system tests in Go. It demonstrates building a file tree, creating a test server, and testing functionality like finding definitions. ```go // Use sandbox for file system tests s := sandbox.New(t) s.BuildTree([]string{ `f:globals.tm:globals { var = "value" }`, `f:stack.tm:stack { name = global.var }`, }) // Create test server srv := newTestServer(t, s.RootDir()) // Test functionality location, err := srv.findDefinition(...) assert.NoError(t, err) ``` -------------------------------- ### Terramate Configuration Loading and Usage Example Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Demonstrates how to load Terramate configuration from the current directory or its parents, list all stacks, retrieve a specific stack by ID, and look up a configuration node. ```go // Load configuration from current directory or parents root, _, found, err := config.TryLoadConfig(".", false) if err != nil { log.Fatal(err) } if !found { log.Fatal("No Terramate configuration found") } // List all stacks allStacks := root.Stacks() fmt.Printf("Found %d stacks\n", len(allStacks)) // Get a specific stack stack, found, err := root.StackByID("prod-vpc") if found { fmt.Printf("Stack: %s at %s\n", stack.Name, stack.Dir) } // Look up a configuration node node, found := root.Lookup(project.Path("/prod")) if found { fmt.Printf("Config at: %s\n", node.HostDir()) } ``` -------------------------------- ### Install Terramate CLI with Homebrew Source: https://github.com/terramate-io/terramate/blob/main/README.md Use this command to install the Terramate CLI if you are using Homebrew as your package manager. ```sh brew install terramate ``` -------------------------------- ### Get Runtime Configuration Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Retrieves the project's runtime configuration, including global variables and functions. ```go runtime := root.Runtime() ``` -------------------------------- ### Get Project Root Directory from Tree Node Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Returns the absolute file system path of the project root, starting from the current tree node. ```go root := tree.RootDir() ``` -------------------------------- ### Git Method: Version Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Retrieves the version of the installed git program. ```APIDOC ## Git Method: Version ### Description Returns the version of the git program. ### Method `Version()` ### Response #### Success Response - **version** (string) - The git program version ### Request Example ```go version, err := gitWrapper.Version() if err != nil { log.Fatal(err) } fmt.Println("Git version:", version) ``` ``` -------------------------------- ### PR Title Format Examples Source: https://github.com/terramate-io/terramate/blob/main/AGENTS.md Examples of correctly formatted PR titles, indicating the type of change (feat, fix, docs, test) and the affected component (ls). ```text feat(ls): add cursor-aware path navigation fix(ls): correct import resolution for circular imports docs(ls): update README with label renaming examples test(ls): add tests for nested object navigation ``` -------------------------------- ### Git Wrapper Usage Example Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Demonstrates how to create and use the Terramate Git wrapper for common operations like checking repository status, listing dirty files, staging changes, and committing. ```APIDOC ## Usage Example ```go // Create git wrapper git, err := git.WithConfig(git.Config{ Username: "Bot User", Email: "bot@example.com", WorkingDir: "/path/to/repo", AllowPorcelain: true, }) if err != nil { log.Fatal(err) } // Check if it's a repository if !git.IsRepository() { log.Fatal("Not a git repository") } // Get modified and untracked files modified, untracked, err := git.ListDirtyFiles() if err != nil { log.Fatal(err) } // Stage and commit changes if len(modified) > 0 { if err := git.Add(modified...); err != nil { log.Fatal(err) } if err := git.Commit("Automated update"); err != nil { log.Fatal(err) } } ``` ``` -------------------------------- ### Terramate Go API Usage Examples Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/README.md Demonstrates common Terramate operations using its Go API, including loading configuration, listing and querying stacks, detecting changes, and building dependency graphs. ```go root, _, _, _ := config.TryLoadConfig(".", false) entries, _ := stack.List(root, root.Tree()) stack, found, _ := root.StackByID("prod-vpc") manager := stack.NewGitAwareManager(root, gitRepo) report, _ := manager.ListChanged(stack.ChangeConfig{...}) graph := dag.New[*config.Stack]() graph.AddNode(id, stack, descendants, ancestors) reason, _ := graph.Validate() ``` -------------------------------- ### Get HCL Parser Options Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Retrieves the HCL parser options used during configuration loading. ```go opts := root.HCLOptions() ``` -------------------------------- ### Load Root Configuration from Directory Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Use `LoadRoot` to load the Terramate configuration starting from a specified directory. It can optionally load Terragrunt modules. Remember to close the root when done. ```go root, err := config.LoadRoot("/path/to/project", false) if err != nil { log.Fatal(err) } deffer root.Close() ``` -------------------------------- ### Get Stacks by Relative Paths Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Retrieves a list of stacks based on their relative paths from a specified base directory. ```go stacks := root.StacksByPaths( project.Path("/"), "prod/vpc", "prod/networking", ) ``` -------------------------------- ### Discover Terramate Stacks Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/constants-and-exports.md Use `List` to get all stacks or the `Manager` for more advanced discovery, including Git-aware options. ```go // List all stacks func List(root *config.Root, cfg *config.Tree) ([]Entry, error) ``` ```go // Manager-based discovery func NewManager(root *config.Root) *Manager func NewGitAwareManager(root *config.Root, git *git.Git) *Manager ``` ```go // Manager methods func (m *Manager) List(checkRepo bool) (*Report, error) func (m *Manager) ListChanged(cfg ChangeConfig) (*Report, error) ``` -------------------------------- ### Get Stack String Representation Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/stack.md Returns the string representation of the stack, which is its directory path. Useful for logging or display. ```go stack := &config.Stack{Dir: project.Path("/infrastructure")} fmt.Println(stack.String()) // Output: /infrastructure ``` -------------------------------- ### HasDirPrefix Check Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/project.md Tests if a path starts with a complete directory component. This is stricter than `HasPrefix` and ensures that only full directory names are matched. ```go path := project.NewPath("/prod/vpc") fmt.Println(path.HasDirPrefix("/prod")) // true fmt.Println(path.HasDirPrefix("/prod/vpc")) // true fmt.Println(path.HasDirPrefix("/prod/vpc/sub")) // false // Edge case: root fmt.Println(path.HasDirPrefix("/")) // true // Difference from HasPrefix: path2 := project.NewPath("/production/vpc") fmt.Println(path2.HasPrefix("/prod")) // true - string prefix fmt.Println(path2.HasDirPrefix("/prod")) // false - not a dir prefix ``` -------------------------------- ### Terramate Hierarchical Overrides Example Source: https://github.com/terramate-io/terramate/blob/main/AGENTS.md Demonstrates how child configurations override parent configurations in Terramate, showing the search order for definitions. ```hcl # Parent: /globals.tm globals { env = "default" } # Child: /stacks/prod/globals.tm globals { env = "production" # This wins! } ``` -------------------------------- ### Get Absolute Host Directory Path Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/stack.md Returns the absolute file system path for the stack's directory on the host machine. ```go absPath := stack.HostDir(root) // Returns: /home/user/project/prod/networking ``` -------------------------------- ### Get Project Root Host Directory Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Obtains the absolute file system path of the project's root directory. ```go hostdir := root.HostDir() // Returns: /home/user/my-project ``` -------------------------------- ### Run tgdeps in a Terragrunt repository Source: https://github.com/terramate-io/terramate/blob/main/cmd/tgdeps/README.md Clone the infrastructure-live for Terragrunt example repository and run tgdeps to discover module dependencies. The output shows modules and their respective dependencies. ```bash $ git clone https://github.com/gruntwork-io/terragrunt-infrastructure-live-example.git $ cd terragrunt-infrastructure-live-example.git $ tgdeps Module: /non-prod/us-east-1/qa/mysql - /_envcommon/mysql.hcl - /non-prod/account.hcl - /non-prod/us-east-1/qa/env.hcl - /non-prod/us-east-1/region.hcl - /terragrunt.hcl Module: /non-prod/us-east-1/qa/webserver-cluster - /_envcommon/webserver-cluster.hcl - /non-prod/account.hcl - /non-prod/us-east-1/qa/env.hcl - /non-prod/us-east-1/region.hcl - /terragrunt.hcl Module: /non-prod/us-east-1/stage/mysql - /_envcommon/mysql.hcl - /non-prod/account.hcl - /non-prod/us-east-1/region.hcl - /non-prod/us-east-1/stage/env.hcl - /terragrunt.hcl Module: /prod/us-east-1/prod/mysql - /_envcommon/mysql.hcl - /prod/account.hcl - /prod/us-east-1/prod/env.hcl - /prod/us-east-1/prod/mysql/config.hcl - /prod/us-east-1/region.hcl - /terragrunt.hcl ``` -------------------------------- ### Enable Debug Logging for Terramate Language Server Source: https://github.com/terramate-io/terramate/blob/main/AGENTS.md Start the Terramate language server with debug logging enabled and redirect output to a file. Use `tail -f` to monitor the log file in real-time. ```bash # Start language server with debug output ./bin/terramate-ls --log-level debug --log-fmt console 2> ls-debug.log # Watch logs tail -f ls-debug.log ``` -------------------------------- ### Terramate Import Resolution Example Source: https://github.com/terramate-io/terramate/blob/main/AGENTS.md Illustrates how Terramate resolves global variables defined in imported files, emphasizing the need to follow import chains. ```hcl # File A globals { project_id = "123" } # File B import { source = "/file_a.tm" } globals { x = global.project_id # Must resolve through import! } ``` -------------------------------- ### ProjectPath Type Definition Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/types.md Represents a project-relative path, always starting with '/'. Used for stack directory identification, configuration lookups, and file path references. ```go type Path string ``` -------------------------------- ### Example Usage of dag.ID Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/types.md Illustrates how to create a dag.ID, which serves as a unique identifier for nodes within a directed acyclic graph. These IDs are used to represent stacks or other ordered items. ```go dag.ID("/prod/vpc") ``` ```go dag.ID("infrastructure-stack") ``` -------------------------------- ### Get Short Commit ID Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Returns the short (7-character) commit ID from a `Ref` object. Example shows how to call the method and the expected output for a given commit ID. ```go shortID := ref.ShortCommitID() // If CommitID = "abc1234567890def", returns "abc1234" ``` -------------------------------- ### Git Method: Init Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Initializes a new git repository in the specified directory. This is a porcelain command. ```APIDOC ## Git Method: Init ### Description Initializes a git repository. Porcelain command. ### Method `Init(dir string, defaultBranch string, bare bool)` ### Parameters #### Request Body - **dir** (string) - Required - Directory to initialize - **defaultBranch** (string) - Required - Default branch name (e.g., "main") - **bare** (bool) - Required - Create bare repository (no working directory) ### Requirements: `AllowPorcelain = true` in config ### Request Example ```go err := gitWrapper.Init("/path/to/repo", "main", false) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Create Git Wrapper with Configuration Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Initializes a new Git wrapper instance using the provided configuration. It validates the Git program path and checks the Git version. Ensure the Git program is accessible and the configuration is valid. ```go git, err := git.WithConfig(git.Config{ Username: "Git User", Email: "user@example.com", WorkingDir: "/path/to/repo", }) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Documentation Features Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/COMPLETION_SUMMARY.txt Each API reference file within the Terramate project is designed to be thorough and user-friendly, including type definitions, method details, parameter tables, and usage examples. ```APIDOC ## Documentation Features ### Description Terramate's API documentation is structured to provide a complete understanding of the available functionalities. Each API reference file includes detailed explanations and examples to facilitate easy integration and usage. ### Key Features: - **Type Definitions**: Provided as code blocks, detailing all fields and their types. - **Constructor/Initialization Methods**: Documentation for creating new instances. - **Instance Methods**: Detailed explanations of methods available on instances, including parameters. - **Parameter Tables**: Clear tables outlining parameter name, type, required status, default values, and descriptions. - **Return Type Documentation**: Specifies the type of data returned by methods. - **Error Documentation**: Details error kinds, trigger conditions, and source file references. - **Usage Examples**: Minimal, practical examples demonstrating how to use the documented features. - **Source File References**: Links to the relevant source code files for deeper inspection. ``` -------------------------------- ### Convert Between Project and Absolute Paths Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/project.md Demonstrates converting paths between project-relative and absolute filesystem formats. ```go // Project relative to absolute filesystem projPath := project.NewPath("/prod/networking") absPath := projPath.HostPath("/home/user/myproject") // absPath = "/home/user/myproject/prod/networking" // Absolute filesystem to project relative fsPath := "/home/user/myproject/prod/vpc" projPath := project.PrjAbsPath("/home/user/myproject", fsPath) fmt.Println(projPath.String()) // /prod/vpc ``` -------------------------------- ### Initialize Git Operations Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/constants-and-exports.md Create a Git wrapper using `WithConfig`. The `Config` struct defines Git execution parameters. ```go // Create git wrapper from configuration func WithConfig(cfg Config) (*Git, error) ``` ```go // Git configuration type type Config struct { Username string Email string ProgramPath string WorkingDir string Env []string Isolated bool AllowPorcelain bool GlobalArgs []string } ``` -------------------------------- ### Terramate Project Testing Utilities Source: https://github.com/terramate-io/terramate/blob/main/AGENTS.md Illustrates using the sandbox utility from the test/ package to set up a test environment and assertions. ```go // Use test helpers from test/ package s := sandbox.New(t) s.BuildTree(layout) // Use assert package, not testing.T directly assert.NoError(t, err) assert.EqualStrings(t, want, got) assert.IsTrue(t, condition, "message") ``` -------------------------------- ### Typical DAG Usage Workflow Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/dag.md Demonstrates the common workflow for creating, adding nodes with dependencies, validating, and determining the execution order of a DAG. ```go // 1. Create a new DAG graph := dag.New[*config.Stack]() // 2. Add nodes with dependencies for _, stack := range stacks { graph.AddNode( dag.ID(stack.Dir.String()), stack, []dag.ID{}, // descendants (will be updated as dependencies are added) deps, // ancestors (dependencies) ) } // 3. Validate and detect cycles reason, err := graph.Validate() if err != nil { fmt.Printf("Cycle detected: %s\n", reason) return err } // 4. Get execution order order := graph.Order() for _, id := range order { stack, _ := graph.Node(id) fmt.Println("Execute:", stack.Name) } ``` -------------------------------- ### Check for Git Not Found Error Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Checks if an error is due to Git not being installed. ```go if errors.Is(err, git.ErrGitNotFound) { log.Fatal("Git is not installed") } ``` -------------------------------- ### Initialize Git Repository Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Initializes a new Git repository in the specified directory. This operation requires `AllowPorcelain = true` to be set in the Git configuration. You can specify the default branch name and whether to create a bare repository. ```go err := gitWrapper.Init("/path/to/repo", "main", false) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Tree Node Project-Relative Path Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Returns the project-relative path of the directory represented by this tree node. ```go relpath := tree.Dir() ``` -------------------------------- ### Initialize Git Client Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/INDEX.md Initializes a git client with a given configuration. Used for performing git operations within Terramate. ```go git, _ := git.WithConfig(git.Config{...}) ``` -------------------------------- ### Get All Node IDs Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/dag.md Retrieves a lexicographically sorted list of all node IDs currently present in the DAG. ```go allIDs := dag.IDs() for _, id := range allIDs { fmt.Println(id) } ``` -------------------------------- ### Git Constructor: WithConfig Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Creates a new git wrapper instance with the specified configuration. It validates the git program path and checks the git version. ```APIDOC ## Git Constructor: WithConfig ### Description Creates a new git wrapper with the specified configuration. Validates the git program path and checks the git version. ### Method `WithConfig(cfg Config)` ### Parameters #### Request Body - **cfg** (Config) - Required - Git configuration ### Errors: - `ErrGitNotFound`: Git program not found - `ErrInvalidConfig`: Configuration is invalid - Git version check failed ### Request Example ```go git, err := git.WithConfig(git.Config{ Username: "Git User", Email: "user@example.com", WorkingDir: "/path/to/repo", }) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Load Terramate Configuration Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/constants-and-exports.md Use `TryLoadConfig` to search for configuration in the current or parent directories. Use `LoadRoot` to load from a specific directory. ```go // Load configuration from directory or parents func TryLoadConfig( fromdir string, loadTerragruntModules bool, hclOpts ...hcl.Option, ) (*config.Root, string, bool, error) ``` ```go // Load configuration from specific directory func LoadRoot( rootdir string, loadTerragruntModules bool, hclOpts ...hcl.Option, ) (*config.Root, error) ``` ```go import "github.com/terramate-io/terramate/config" // Recommended: Search for config in current or parent directories root, configpath, found, err := config.TryLoadConfig(".", false) if err != nil { log.Fatal(err) } if !found { log.Fatal("No Terramate configuration found") } // Alternative: Load from specific directory root, err := config.LoadRoot("/path/to/project", false) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Discover Project Structure with Terramate Go SDK Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/GUIDE.md Loads Terramate configuration and lists all stacks, then groups them by their directory using the Terramate Go SDK. ```go // Load configuration root, _, _, err := config.TryLoadConfig(".", false) if err != nil { log.Fatal(err) } // List all stacks allStacks := root.Stacks() fmt.Printf("Found %d stacks\n", len(allStacks)) // Group by directory byDir := make(map[string][]string) for _, stackPath := range allStacks { dir := stackPath.Dir().String() byDir[dir] = append(byDir[dir], stackPath.String()) } ``` -------------------------------- ### Terramate Path Conversions Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/constants-and-exports.md Shows how to create project paths, convert them to host paths, and convert host paths back to project paths. ```go import "github.com/terramate-io/terramate/project" // Create project path projPath := project.NewPath("/prod/vpc") // Convert to filesystem path absPath := projPath.HostPath("/home/user/project") // Convert from filesystem to project path projPath := project.PrjAbsPath("/home/user/project", absPath) ``` -------------------------------- ### Get Ancestors of a Node Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/dag.md Returns a list of all direct ancestor node IDs (dependencies) for a given node ID. ```go ancestors := dag.AncestorsOf("stack-b") // Returns: []ID{"stack-a"} ``` -------------------------------- ### HasDirPrefix Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/project.md Tests if the path starts with a directory prefix, ensuring a full directory component match. This is stricter than HasPrefix. ```APIDOC ## HasDirPrefix(s string) → bool ### Description Tests whether the path starts with a directory prefix. This is stricter than `HasPrefix()` and only matches complete directory components. ### Parameters #### Path Parameters - **s** (string) - Required - Directory prefix to check ### Example ```go path := project.NewPath("/prod/vpc") fmt.Println(path.HasDirPrefix("/prod")) // true fmt.Println(path.HasDirPrefix("/prod/vpc")) // true fmt.Println(path.HasDirPrefix("/prod/vpc/sub")) // false // Edge case: root fmt.Println(path.HasDirPrefix("/")) // true // Difference from HasPrefix: path2 := project.NewPath("/production/vpc") fmt.Println(path2.HasPrefix("/prod")) // true - string prefix fmt.Println(path2.HasDirPrefix("/prod")) // false - not a dir prefix ``` ``` -------------------------------- ### NewPath Constructor Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/project.md Creates a new project path from a string. Panics if the provided path is not absolute. ```go path := project.NewPath("/infrastructure/vpc") // path.String() == "/infrastructure/vpc" ``` -------------------------------- ### Get Terramate Version Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/constants-and-exports.md Call this function to retrieve the current Terramate version string. Useful for logging or conditional logic. ```go // Version returns the Terramate version string func Version() string ``` ```go version := terramate.Version() // Returns something like "0.7.0" ``` -------------------------------- ### Sort and Convert Path Collections Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/project.md Shows how to sort a collection of project paths lexicographically and convert them to strings. ```go paths := project.Paths{ project.NewPath("/services/api"), project.NewPath("/infrastructure"), project.NewPath("/databases"), } // Sort lexicographically paths.Sort() // Convert to strings stringPaths := paths.Strings() for _, p := range stringPaths { fmt.Println(p) } ``` -------------------------------- ### Get Tree Node Host Directory Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Returns the absolute file system path for the directory represented by this tree node. ```go hostdir := tree.HostDir() ``` -------------------------------- ### Get Node Value Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/dag.md Retrieves the value associated with a specific node ID. Returns an error if the node does not exist in the DAG. ```go stack, err := dag.Node("stack-a") if err != nil { log.Fatal(err) } fmt.Println(stack) ``` -------------------------------- ### Format Code Source: https://github.com/terramate-io/terramate/blob/main/AGENTS.md Format the codebase according to project standards using the 'make fmt' command. ```bash make fmt ``` -------------------------------- ### Check Directory Prefixes Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/project.md Illustrates how to check if a given path has a specific directory prefix. ```go path := project.NewPath("/prod/networking/vpc") // Check if path is in prod environment if path.HasDirPrefix("/prod") { fmt.Println("This is a production stack") } // Check if path is under networking if path.HasDirPrefix("/prod/networking") { fmt.Println("This is a networking stack") } ``` -------------------------------- ### Get Remote URL Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Retrieves the URL associated with a specific remote name. Useful for verifying or accessing remote repository locations. ```go url, err := gitWrapper.URL("origin") if err != nil { log.Fatal(err) } fmt.Println("Origin URL:", url) ``` -------------------------------- ### Build fakecloud Source: https://github.com/terramate-io/terramate/blob/main/cloud/testserver/cmd/testserver/README.md Builds the fakecloud project. Use this command to compile the project. ```shell $ make test/build ``` -------------------------------- ### Manage Runtime Variables Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/project.md Demonstrates creating, merging, and accessing variables within a Terramate runtime context. ```go // Create runtime context runtime := project.Runtime{ "environment": cty.StringVal("production"), } // Merge additional values additional := project.Runtime{ "region": cty.StringVal("us-east-1"), } runtime.Merge(additional) // Access values env := runtime["environment"] ``` -------------------------------- ### HasPrefix Check Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/project.md Tests if a path begins with a specified string. This is a general prefix check. ```go path := project.NewPath("/prod/vpc") fmt.Println(path.HasPrefix("/prod")) // true fmt.Println(path.HasPrefix("/dev")) // false ``` -------------------------------- ### Get Relative Path to Project Root Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/stack.md Calculates and returns the relative path from the stack's directory to the project root directory. ```go relPath := stack.RelPathToRoot(root) // Returns: ../../ ``` -------------------------------- ### Get Git Status Output Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Retrieves the raw output of the `git status` command. This can be useful for detailed inspection of the repository's state. ```go status, err := gitWrapper.Status() if err != nil { log.Fatal(err) } fmt.Println(status) ``` -------------------------------- ### Get Stack Relative Path Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/stack.md Returns the project-relative path of the stack, excluding the leading slash. Useful for referencing stacks within the project. ```go stack := &config.Stack{Dir: project.Path("/prod/networking")} fmt.Println(stack.RelPath()) // Output: prod/networking ``` -------------------------------- ### Create Manager with Git Support Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/stack.md Constructs a new stack manager instance with Git support for change detection. Requires loading the configuration and initializing a Git repository object. ```go root, _, _, err := config.TryLoadConfig(".", false) if err != nil { log.Fatal(err) } gitRepo, err := git.New(root.HostDir()) if err != nil { log.Fatal(err) } manager := stack.NewGitAwareManager(root, gitRepo) ``` -------------------------------- ### Error Creation and Handling Patterns Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/constants-and-exports.md Demonstrates consistent patterns for creating, checking, wrapping, and chaining errors using the errors package. ```go // Create error with kind and context err := errors.E(ErrorKind, "context or wrapped error") // Check error kind if errors.Is(err, ErrorKind) { // Handle specific error } // Wrap errors err := errors.E(ErrorKind, otherErr) // Create error chain err := errors.L(err1, err2, err3).AsError() ``` -------------------------------- ### Prevent Path Traversal in Terramate Source: https://github.com/terramate-io/terramate/blob/main/AGENTS.md Ensures that resolved paths do not escape the workspace boundaries. This example shows a good practice using `strings.HasPrefix` for validation. ```go // Good if !strings.HasPrefix(resolvedPath, s.workspace) { return nil, errors.E("path outside workspace") } // Bad // Blindly joining paths without validation ``` -------------------------------- ### DAG Usage Pattern Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/dag.md Demonstrates the typical workflow for using the DAG API, including creating a new DAG, adding nodes with dependencies, validating the DAG for cycles, and obtaining the execution order. ```APIDOC ## DAG Usage Pattern ### Description Typical workflow for using the DAG: Create a new DAG, add nodes with dependencies, validate the DAG to detect cycles, and then get the execution order. ### Methods - **New[*T]()** → `*DAG[T]` - **AddNode(id ID, value any, descendants []ID, ancestors []ID)** - **Validate()** → `(string, error)` - **Order()** → `[]ID` - **Node(id ID)** → `(any, bool)` ### Example ```go // 1. Create a new DAG graph := dag.New[*config.Stack]() // 2. Add nodes with dependencies for _, stack := range stacks { graph.AddNode( dag.ID(stack.Dir.String()), stack, []dag.ID{}, // descendants (will be updated as dependencies are added) deps, // ancestors (dependencies) ) } // 3. Validate and detect cycles reason, err := graph.Validate() if err != nil { fmt.Printf("Cycle detected: %s\n", reason) return err } // 4. Get execution order order := graph.Order() for _, id := range order { stack, _ := graph.Node(id) fmt.Println("Execute:", stack.Name) } ``` ``` -------------------------------- ### List All Stacks Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/stack.md Lists all stacks in the project and optionally performs repository state checks for uncommitted and untracked files. Iterates through the report to print stack names and directories. ```go report, err := manager.List(true) if err != nil { log.Fatal(err) } for _, entry := range report.Stacks { fmt.Println(entry.Stack.Name, entry.Stack.Dir) } ``` -------------------------------- ### Git Method: Add Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Stages specified files, preparing them for the next commit. ```APIDOC ## Git Method: Add ### Description Stages files for commit. ### Method `Add(files ...string)` ### Parameters #### Request Body - **files** (...string) - Required - Files to stage ### Request Example ```go err := gitWrapper.Add("file1.txt", "file2.txt") if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Define a Simple Stack in HCL Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/GUIDE.md Example of a basic Terramate stack definition in HCL, specifying its ID, name, tags, and files to watch for changes. ```hcl # prod/vpc/terramate.tm.hcl stack { id = "prod-vpc" name = "Production VPC" tags = ["production", "networking"] watch = [ "terraform/**", ] } ``` -------------------------------- ### Get Commit Log Summary Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Retrieves a summary of commits within specified revision ranges. Each log entry includes the commit ID and message. ```go logs, err := gitWrapper.LogSummary("HEAD~5..HEAD") if err != nil { log.Fatal(err) } for _, log := range logs { fmt.Printf("%s: %s\n", log.CommitID, log.Message) } ``` -------------------------------- ### Get Stack from Tree Node Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Retrieves the stack configured at the current tree node. Handles errors if the node is not a stack or if configuration validation fails. ```go stack, err := tree.Stack() if err != nil { log.Fatal(err) } fmt.Println("Stack name:", stack.Name) ``` -------------------------------- ### Create a New Root Configuration Tree Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Use `NewRoot` to create a new configuration tree from an existing `Tree` object. This is useful when you have already constructed the tree structure programmatically. ```go tree := config.NewTree("/path/to/project") root := config.NewRoot(tree) ``` -------------------------------- ### Get Stack by ID Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Retrieves a specific stack using its unique ID. Returns the stack object, a boolean indicating if it was found, and any potential error. ```go stack, found, err := root.StackByID("prod-vpc") if err != nil { log.Fatal(err) } if found { fmt.Println("Stack:", stack.Name) } ``` -------------------------------- ### Run Tests and Format Code Source: https://github.com/terramate-io/terramate/blob/main/AGENTS.md Commands for running all tests, specific package tests, tests with race detection, code formatting, and installing/running linters. ```bash # Run all tests make test # Run specific package tests go test ./ls/... go test ./hcl/... # Run with race detector go test -race ./ls/... # Format code make fmt # Install linting make lint/install # Run linting make lint/all ``` -------------------------------- ### Build Terramate Binaries Source: https://github.com/terramate-io/terramate/blob/main/AGENTS.md Builds all project binaries, including the Terramate CLI, language server, and test helper. ```bash # Build all binaries make build # Output: # - bin/terramate (CLI) # - bin/terramate-ls (Language Server) # - bin/helper (test helper) ``` -------------------------------- ### Get Stack Path Base Name Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/stack.md Retrieves the base name of the stack's directory path. Useful for extracting the final component of a path. ```go stack := &config.Stack{Dir: project.Path("/prod/networking")} fmt.Println(stack.PathBase()) // Output: networking ``` -------------------------------- ### Git Error Handling Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Explains the custom error types used by the Git wrapper, including `Error` and `CmdError`, and provides examples of how to check for specific errors. ```APIDOC ## Error Type ### `Error` Type Sentinel error type for git wrapper errors. ```go type Error string ``` **Error Constants:** - `ErrGitNotFound` - Git program not found - `ErrInvalidConfig` - Configuration is invalid - `ErrDenyPorcelain` - Porcelain command executed when not allowed ```go if errors.Is(err, git.ErrGitNotFound) { log.Fatal("Git is not installed") } ``` ### `CmdError` Type Error returned when a git command fails. ```go type CmdError struct { // private fields } ``` **Methods:** - `Command()` → `string` - The executed command - `Stdout()` → `[]byte` - Standard output - `Stderr()` → `[]byte` - Standard error ```go if cmdErr, ok := err.(*git.CmdError); ok { fmt.Println("Command failed:", cmdErr.Command()) fmt.Println("Error:", string(cmdErr.Stderr())) } ``` ``` -------------------------------- ### Run fakecloud Source: https://github.com/terramate-io/terramate/blob/main/cloud/testserver/cmd/testserver/README.md Runs the fakecloud executable. Use this command after building the project. ```shell $ ./bin/fakecloud ``` -------------------------------- ### Get Current Git Branch Name Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Fetches the name of the currently active branch in the Git repository. This is essential for operations that depend on the current branch context. ```go branch, err := gitWrapper.CurrentBranch() if err != nil { log.Fatal(err) } fmt.Println("Current branch:", branch) ``` -------------------------------- ### Runtime() Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Retrieves the runtime configuration, including global variables and functions. ```APIDOC ## Runtime() ### Description Returns the runtime configuration (global variables and functions). ### Method Root Method ### Returns - `project.Runtime`: The runtime configuration object. ``` -------------------------------- ### Execute Raw Git Command Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Executes a raw git command and returns its output. Use this for git operations not directly supported by the wrapper. ```go output, err := gitWrapper.Exec("show", "--format=%H", "-s") if err != nil { log.Fatal(err) } ``` -------------------------------- ### HostDir() Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Returns the absolute file system path of the project root directory. ```APIDOC ## HostDir() ### Description Returns the file system absolute path of the project root. ### Method Root Method ### Returns - `string`: The absolute path to the project root. ``` -------------------------------- ### Get Git Repository Root Directory Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Retrieves the absolute path to the root directory of the current Git repository. This is useful for resolving paths relative to the repository root. ```go root, err := gitWrapper.Root() if err != nil { log.Fatal(err) } fmt.Println("Repository root:", root) ``` -------------------------------- ### Terramate Configuration Hierarchy Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/constants-and-exports.md Illustrates the different levels of configuration in Terramate: Root, Tree, and Stack. ```go // Root always contains the project root configuration root := config.Root // Root config tree // Tree is any node in the hierarchy tree := config.Tree // Represents a directory // Stack is a specific node that defines a stack stack := config.Stack // Evaluated stack at a node ``` -------------------------------- ### Get Topological Order Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/dag.md Returns the topological ordering of all nodes in the DAG. Nodes with no dependency conflicts are sorted lexicographically for consistent results. This method requires `Validate()` to have been called. ```go order := dag.Order() for i, id := range order { fmt.Printf("%d: %s\n", i, id) } ``` -------------------------------- ### Git Configuration Type Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Defines the configuration options for the Git wrapper, including credentials, paths, and environment settings. Use this when creating a new Git wrapper instance with `WithConfig()`. ```go type Config struct { Username string // Username for commits Email string // Email for commits ProgramPath string // Path to git executable (auto-detected if empty) WorkingDir string // Working directory (current dir if empty) Env []string // Environment variables (if nil, no env vars passed) Isolated bool // Use isolated git config (no global/system config) AllowPorcelain bool // Allow porcelain commands (Init, Clone) GlobalArgs []string // Global args added to all commands } ``` -------------------------------- ### Get Changed File Names Between Revisions Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Returns a list of file names that have changed between two specified Git revisions. This is useful for understanding the scope of changes between branches or commits. ```go changed, err := gitWrapper.DiffNames("origin/main", "HEAD") if err != nil { log.Fatal(err) } for _, file := range changed { fmt.Println("Changed:", file) } ``` -------------------------------- ### HostPath Conversion Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/project.md Converts a project-relative Path to an absolute file system path by prepending the project root directory. This is essential for interacting with the underlying file system. ```go projPath := project.NewPath("/prod/vpc") hostPath := projPath.HostPath("/home/user/myproject") // Returns: /home/user/myproject/prod/vpc ``` -------------------------------- ### HostDir() Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/stack.md Returns the file system absolute path of the stack. ```APIDOC ## HostDir(root *config.Root) Returns the file system absolute path of the stack. ```go absPath := stack.HostDir(root) // Returns: /home/user/project/prod/networking ``` ``` -------------------------------- ### Get Tree Diff Between Revisions Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Generates a tree diff between two Git revisions with options for relative paths, name-only output, and recursion into subdirectories. This provides a detailed view of changes. ```go diff, err := gitWrapper.DiffTree("HEAD~1", "HEAD", true, true, true) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Lookup Configuration Node by Path Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Finds a specific configuration node within the project using its relative path. Returns the node and a boolean indicating if it was found. ```go node, found := root.Lookup(project.Path("/prod/vpc")) if found { fmt.Println("Found node at:", node.Dir()) } ``` -------------------------------- ### HostPath Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/project.md Converts a project-relative path to an absolute file system path by joining it with the provided project root directory. ```APIDOC ## HostPath(rootdir string) → string ### Description Converts the project path to an absolute file system path given the project root directory. ### Parameters #### Path Parameters - **rootdir** (string) - Required - Project root directory ### Example ```go projPath := project.NewPath("/prod/vpc") hostPath := projPath.HostPath("/home/user/myproject") // Returns: /home/user/myproject/prod/vpc ``` ``` -------------------------------- ### Terramate Import Path Resolution Source: https://github.com/terramate-io/terramate/blob/main/AGENTS.md Illustrates the difference between absolute (project-relative) and relative import paths in Terramate. Absolute paths start with '/', while relative paths are resolved relative to the current directory. ```go // Absolute (project-relative): starts with / source = "/modules/shared/globals.tm" // Resolve: workspace + source // Relative: no leading / source = "../shared/globals.tm" // Resolve: currentDir + source ``` -------------------------------- ### Exec Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/git.md Executes a raw Git command. ```APIDOC ## Exec ### Description Executes a raw Git command. This is useful for commands not yet implemented by the wrapper. ### Method Not applicable (Go function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **command** (string) - Required - Git command (without "git" prefix) - **args** (...string) - Optional - Command arguments ### Request Example ```go output, err := gitWrapper.Exec("show", "--format=%H", "-s") if err != nil { log.Fatal(err) } ``` ### Response #### Success Response (string) Returns the standard output of the executed Git command. #### Response Example ```json "a1b2c3d4e5f67890abcdef1234567890abcdef12" ``` ``` -------------------------------- ### Project Configuration Limits Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/constants-and-exports.md Defines the maximum number of global variable labels allowed in a globals block. ```go const ( // MaxGlobalLabels is the maximum number of global variable labels // allowed in a globals block MaxGlobalLabels = 256 ) ``` -------------------------------- ### Load Terramate Configuration Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/INDEX.md Loads the Terramate configuration from the specified directory. This is typically the first step in interacting with Terramate programmatically. ```go root, _, _, _ := config.TryLoadConfig(".", false) ``` -------------------------------- ### Get Runtime Values for Stack Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/stack.md Retrieves a map of computed runtime values for the stack, including its absolute path, relative path, basename, and relation to the root. Also provides access to the stack object itself with its properties. ```go runtimeVals := stack.RuntimeValues(root) // Contains: name, path (deprecated), description (deprecated), stack // The stack object contains: name, description, tags, path (absolute, relative, basename, to_root), id, parent ``` -------------------------------- ### Load Subtree Configuration Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Loads the configuration for a subtree located at the specified directory path. Useful for lazy loading parts of the configuration. ```go if err := root.LoadSubTree(project.Path("/services")); err != nil { log.Fatal(err) } ``` -------------------------------- ### Stacks() Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/config.md Returns a list of all stack paths defined within the project. ```APIDOC ## Stacks() ### Description Returns all stack paths in the project. ### Method Root Method ### Returns - `project.Paths`: A list of all stack paths in the project. ``` -------------------------------- ### HasPrefix Source: https://github.com/terramate-io/terramate/blob/main/_autodocs/api-reference/project.md Checks if the path string begins with a specified prefix string. This is a simple string prefix check. ```APIDOC ## HasPrefix(s string) → bool ### Description Tests whether the path starts with the given string prefix. ### Parameters #### Path Parameters - **s** (string) - Required - String prefix to check ### Example ```go path := project.NewPath("/prod/vpc") fmt.Println(path.HasPrefix("/prod")) // true fmt.Println(path.HasPrefix("/dev")) // false ``` ```