### Basic Magefile Example Source: https://github.com/magefile/mage/blob/master/site/content/index.md A simple Magefile demonstrating a 'Deploy' target that runs 'go mod download' and 'go install'. ```go //go:build mage package main //mage:multiline // enable line return retention in doc output. import ( "github.com/magefile/mage/sh" ) // Runs go mod download and then installs the binary. func Deploy(env string, dryrun *bool, // if set to true, only builds the artifacts ) error { if err := sh.Run("go", "mod", "download"); err != nil { return err } return sh.Run("go", "install", "./...") } ``` -------------------------------- ### Install Mage using Go Install (Go >= 1.18) Source: https://github.com/magefile/mage/blob/master/README.md Recommended installation for Go 1.18 and above using 'go install'. This method simplifies the installation process. ```bash go install github.com/magefile/mage@latest mage -init ``` -------------------------------- ### Zero-Install Mage Execution Examples Source: https://context7.com/magefile/mage/llms.txt These commands show how to execute Mage targets using the zero-install bootstrap file. No prior installation of the Mage binary is required. ```bash go run mage.go build # zero-install: no mage binary required go run mage.go -l ``` -------------------------------- ### Example Output for sh.Output Source: https://context7.com/magefile/mage/llms.txt Example of the output when running the 'mage showversion' command. ```bash mage showversion # Go version: go version go1.22.0 linux/amd64 # Git commit: a1b2c3d # Target arch: arm64 ``` -------------------------------- ### Example Usage for Runtime Environment Helpers Source: https://context7.com/magefile/mage/llms.txt Examples demonstrating how to enable verbose output and specify a custom Go command path using environment variables or Mage flags. ```bash MAGEFILE_VERBOSE=1 mage build # enables verbose output MAGEFILE_GOCMD=/usr/local/go/bin/go mage build mage -v build # also enables verbose mode ``` -------------------------------- ### Install Mage with Git Clone and Go Modules Source: https://github.com/magefile/mage/blob/master/site/content/blog/mage-in-ci.md When using Go modules, clone the Mage repository and then use the bootstrap.go file with `go run` to install Mage. The binary will be placed in your GOPATH. ```bash git clone git@github.com:magefile/mage cd mage go run bootstrap.go install ``` -------------------------------- ### Install Mage using Go Install Source: https://github.com/magefile/mage/blob/master/site/content/index.md Installs the latest version of Mage using the Go toolchain. You can specify a version tag instead of 'latest'. ```plain go install github.com/magefile/mage@latest ``` ```plain mage -init ``` ```plain go install github.com/magefile/mage@v1.16.0 ``` -------------------------------- ### Mage Command-Line Usage Examples Source: https://context7.com/magefile/mage/llms.txt Examples of how to invoke Mage targets from the command line, including running default targets, specific targets, targets with arguments, and listing/help commands. ```bash mage # runs Build (the Default) mage build # runs Build explicitly mage test 30s # runs Test with a 30-second timeout mage deploy production -greeting=Shipping mage -l # lists all available targets mage -h build # shows help for the Build target ``` -------------------------------- ### Example Dependency Tree Source: https://github.com/magefile/mage/blob/master/site/content/dependencies/_index.en.md This example demonstrates a dependency tree where 'Build' depends on 'f' and 'g', and both 'f' and 'g' depend on 'h'. 'h' runs first, followed by 'f' and 'g' in parallel, and finally 'Build'. ```go func Build() { mg.Deps(f, g) fmt.Println("Build running") } func f() { mg.Deps(h) fmt.Println("f running") } func g() { mg.Deps(h) fmt.Println("g running") } func h() { fmt.Println("h running") } ``` -------------------------------- ### Install Mage using asdf Source: https://github.com/magefile/mage/blob/master/site/content/index.md Installs Mage using the asdf version manager. This allows managing different Mage versions. ```shell asdf plugin add mage asdf install mage latest asdf global mage latest ``` -------------------------------- ### Install Mage with GOPATH Source: https://github.com/magefile/mage/blob/master/site/content/blog/mage-in-ci.md Use this command to download and install the Mage source code when using GOPATH. This ensures Mage is compiled with ldflags for version information. ```bash go get -d github.com/magefile/mage go run $GOPATH/src/github.com/magefile/mage/bootstrap.go install ``` -------------------------------- ### Install Tab Completion for Shells Source: https://github.com/magefile/mage/blob/master/site/content/tabcompletion/_index.en.md Run this command with your shell name (bash, zsh, fish, powershell) to install tab completion. It automatically configures your shell startup files. ```bash mage -install bash mage -install zsh mage -install fish mage -install powershell # also accepts "pwsh" ``` -------------------------------- ### Mage Help Output Examples Source: https://github.com/magefile/mage/blob/master/site/content/index.md Shows the command-line output for `mage -l` and `mage -h `, illustrating how help text is displayed. ```plain $ mage -l These docs will become the main help text when you run `mage` or `mage -l`. Targets: deploy runs the build and then uploads the artifacts to the server. $ mage -h deploy Deploy runs the build and then uploads the artifacts to the server. It deploys to the given environment. Usage: mage deploy [] Flags: -version= git tag for the build, defaults to the next minor build if not set -dryrun= if set to true, just outputs the build artifacts ``` -------------------------------- ### Markdown Ordered List Example Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/markdown.fr.md Demonstrates a standard ordered list in Markdown. ```markdown 1. Lorem ipsum dolor sit amet 2. Consectetur adipiscing elit 3. Integer molestie lorem at massa 4. Facilisis in pretium nisl aliquet 5. Nulla volutpat aliquam velit 6. Faucibus porta lacus fringilla vel 7. Aenean sit amet erat nunc 8. Eget porttitor lorem ``` -------------------------------- ### Install Mage using Go Modules Source: https://github.com/magefile/mage/blob/master/README.md Clone the Mage repository and run the bootstrap script to build Mage with embedded version information when using Go Modules. ```bash git clone https://github.com/magefile/mage cd mage go run bootstrap.go ``` -------------------------------- ### Install Mage using GOPATH (Go < 1.17) Source: https://github.com/magefile/mage/blob/master/README.md Use this method for older Go versions when managing dependencies with GOPATH. It involves downloading the source and running a bootstrap script. ```bash go get -u -d github.com/magefile/mage cd $GOPATH/src/github.com/magefile/mage go run bootstrap.go ``` -------------------------------- ### Rendered Button Examples Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/shortcodes/button.en.md These are the rendered outputs of the button shortcodes, showing different configurations. ```html {{% button href="https://getgrav.org/" %}}Get Grav{{% /button %}} ``` ```html {{% button href="https://getgrav.org/" icon="fa fa-download" %}}Get Grav with icon{{% /button %}} ``` ```html {{% button href="https://getgrav.org/" icon="fa fa-download" icon-position="right" %}}Get Grav with icon right{{% /button %}} ``` -------------------------------- ### Magefile with Targets and Comments Source: https://github.com/magefile/mage/blob/master/site/content/magefiles/_index.en.md Defines build targets like 'Install' and 'Target'. Comments are used for help text, with '//mage:multiline' preserving line breaks in documentation. ```go //go:build mage // A comment on the package will be output when you list the targets of a // magefile. // // If you set MAGEFILE_MULTILINE=true or have the //mage:multiline comment // in the file, mage will retain line returns in comments it outputs as help docs. // If you don't include those, it will convert line returns into spaces. package main //mage:multiline // enable retention of line returns in doc output. import ( "log" "os" ) // Build target is any exported function with zero args with no return or an error return. // If a target has an error return and returns an non-nil error, mage will print // that error to stdout and return with an exit code of 1. func Install() error { } // The first sentence in the comment will be the short help text shown with mage -l. // The rest of the comment is long help text that will be shown with mage -h func Target() { // by default, the log stdlib package will be set to discard output. // Running with mage -v will set the output to stdout. log.Printf("Hi!") } // A var named Default indicates which target is the default. If there is no // default, running mage will list the targets available. var Default = Install // Because build targets are case insensitive, you may not have two build targets // that lowercase to the same text. This would give you an error when you tried // to run the magefile: // func BUILD() {} // Targets may have a context argument, in which case a default context is passed // to the target, which will be cancelled after a timeout if the -t flag is used. func Build(ctx context.Context) { mg.CtxDeps(ctx, Target) } ``` -------------------------------- ### Launch Local Hugo Development Server Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/basics/installation/_index.en.md Starts the Hugo development server, allowing you to preview your site locally. The server automatically refreshes when files are saved. ```bash hugo serve ``` -------------------------------- ### Install Specific Mage Version Source: https://github.com/magefile/mage/blob/master/README.md To install a specific version of Mage, replace '@latest' with the desired version tag. ```bash go install github.com/magefile/mage@v1.15.0 ``` -------------------------------- ### Compile Mage into a Static Binary Source: https://github.com/magefile/mage/blob/master/site/content/zeroInstall/_index.en.md Compile Mage with your tasks included into a single static binary. This binary can then be run on any machine without requiring Mage or Go to be installed. ```plain $ mage -compile ./static-output ``` -------------------------------- ### Markdown Unordered List Example Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/markdown.fr.md Demonstrates a nested unordered list structure in Markdown. ```markdown + Lorem ipsum dolor sit amet + Consectetur adipiscing elit + Integer molestie lorem at massa + Facilisis in pretium nisl aliquet + Nulla volutpat aliquam velit - Phasellus iaculis neque - Purus sodales ultricies - Vestibulum laoreet porttitor sem - Ac tristique libero volutpat at + Faucibus porta lacus fringilla vel + Aenean sit amet erat nunc + Eget porttitor lorem ``` -------------------------------- ### HTML Ordered List Example Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/markdown.fr.md This is the HTML rendering of a Markdown ordered list. ```html
  1. Lorem ipsum dolor sit amet
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet
  5. Nulla volutpat aliquam velit
  6. Faucibus porta lacus fringilla vel
  7. Aenean sit amet erat nunc
  8. Eget porttitor lorem
``` -------------------------------- ### Run Mage with `go run` Source: https://github.com/magefile/mage/blob/master/site/content/zeroInstall/_index.en.md Use this method to execute Mage tasks directly from your vendor directory or GOPATH without installing Mage globally. Ensure the build tag is set to `//go:build ignore` or `// +build ignore` to prevent Mage from compiling this file. ```go //go:build ignore // +build ignore package main import ( "os" "github.com/magefile/mage/mage" ) func main() { os.Exit(mage.Main()) } ``` -------------------------------- ### Getting Help for a Magefile Target Source: https://github.com/magefile/mage/blob/master/site/content/magefiles/_index.en.md Command to display detailed help for a specific Magefile target. It shows the target's full comment. ```bash $ mage -h target mage target: The first sentence in the comment will be the short help text shown with mage -l. The rest of the comment is long help text that will be shown with mage -h ``` -------------------------------- ### Install Mage Shell Tab Completion Source: https://context7.com/magefile/mage/llms.txt Mage can install tab completion scripts for various shells (bash, zsh, fish, PowerShell). The `-autocomplete` flag outputs target names for custom completion scripts. ```bash # Install tab completion for your shell: mage -install bash # writes to /etc/bash_completion.d/ or ~/.bash_completion mage -install zsh # writes to a zsh completion directory mage -install fish # writes to ~/.config/fish/completions/ mage -install powershell # writes to the PowerShell profile # Print target names only (for custom completion scripts): mage -autocomplete # build # clean # deploy # test # Example custom bash completion function using -autocomplete: _mage_complete() { COMPREPLY=($(mage -autocomplete 2>/dev/null)) } complete -F _mage_complete mage ``` -------------------------------- ### HTML Unordered List Example Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/markdown.fr.md This is the HTML rendering of a nested Markdown unordered list. ```html
  • Lorem ipsum dolor sit amet
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet
  • Nulla volutpat aliquam velit
    • Phasellus iaculis neque
    • Purus sodales ultricies
    • Vestibulum laoreet porttitor sem
    • Ac tristique libero volutpat at
  • Faucibus porta lacus fringilla vel
  • Aenean sit amet erat nunc
  • Eget porttitor lorem
``` -------------------------------- ### HTML Blockquote Example Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/markdown.fr.md This is the HTML rendering of a Markdown blockquote. ```html

Fusion Drive combines a hard drive with a flash storage (solid-state drive) and presents it as a single logical volume with the space of both drives combined.

``` -------------------------------- ### Example POSIX-Shell Completion Function Source: https://github.com/magefile/mage/blob/master/site/content/tabcompletion/_index.en.md A minimal POSIX-shell function demonstrating how to wire up `mage -autocomplete` for custom shell integration. Ensure the function runs mage from the project directory. ```sh _mage_complete() { COMPREPLY=( $(mage -autocomplete 2>/dev/null) ) } complete -F _mage_complete mage ``` -------------------------------- ### Markdown Auto-Numbered Ordered List Example Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/markdown.fr.md Using `1.` for each item in an ordered list allows Markdown to automatically number them sequentially. ```markdown 1. Lorem ipsum dolor sit amet 1. Consectetur adipiscing elit 1. Integer molestie lorem at massa 1. Facilisis in pretium nisl aliquet 1. Nulla volutpat aliquam velit 1. Faucibus porta lacus fringilla vel 1. Aenean sit amet erat nunc 1. Eget porttitor lorem ``` -------------------------------- ### Add Icon to Menu Entry Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/pages/_index.en.md Prepend an HTML icon to a menu entry by setting the `pre` parameter in the page's Front Matter. This example uses a Font Awesome Github icon. ```toml +++ title = "Github repo" pre = " " +++ ``` -------------------------------- ### Acceptable Target Function Signatures Source: https://github.com/magefile/mage/blob/master/site/content/targets/_index.en.md Examples of valid function signatures for Mage targets. Targets can accept an optional context.Context, return an error, and take string, int, float64, bool, or time.Duration arguments. ```go func Build() func Install(ctx context.Context) error func Run(what string) error func Exec(ctx context.Context, name string, count int, debug bool, timeout time.Duration) error func Greet(name string, greeting *string) ``` -------------------------------- ### Mermaid Sequence Diagram Shortcode Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/shortcodes/mermaid.en.md Embed Mermaid syntax for sequence diagrams using the mermaid shortcode. This example demonstrates a basic interaction between participants Alice and Bob. ```html {{}} sequenceDiagram participant Alice participant Bob Alice->>John: Hello John, how are you? loop Healthcheck John->John: Fight against hypochondria end Note right of John: Rational thoughts
prevail... John-->Alice: Great! John->Bob: How about you? Bob-->John: Jolly good! {{}} ``` -------------------------------- ### Mage Zero-Install Bootstrap Source: https://context7.com/magefile/mage/llms.txt This Go file acts as a bootstrap for running Mage targets without a pre-installed Mage binary. It uses `go run` to execute Mage as a library. ```go //go:build ignore // +build ignore // mage.go — zero-install bootstrap. Run with: go run mage.go package main import ( "os" "github.com/magefile/mage/mage" ) func main() { os.Exit(mage.Main()) } ``` -------------------------------- ### Create New Hugo Site Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/basics/installation/_index.en.md Use this command to initialize a new Hugo project. Replace `` with your desired project name. ```bash hugo new site ``` -------------------------------- ### Greet Target with Optional Argument Source: https://github.com/magefile/mage/blob/master/site/content/targets/_index.en.md Demonstrates a target function that accepts an optional string argument using a pointer. If the pointer is nil, a default greeting is used. ```go func Greet(name string, greeting *string) { if greeting != nil { fmt.Printf("%s, %s!\n", *greeting, name) } else { fmt.Printf("Hello, %s!\n", name) } } ``` -------------------------------- ### List Namespaced Targets with Help Source: https://github.com/magefile/mage/blob/master/site/content/targets/_index.en.md Use the `mage -l` command to view all available targets, including those organized within namespaces. This helps in understanding the available build commands and their structure. ```bash $ mage -l build:docs Builds the pdf docs. build:site Builds the site using hugo. ``` -------------------------------- ### Markdown Blockquote Example Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/markdown.fr.md Use `>` to create a blockquote in Markdown. This is useful for quoting content from other sources. ```markdown > **Fusion Drive** combines a hard drive with a flash storage (solid-state drive) and presents it as a single logical volume with the space of both drives combined. ``` -------------------------------- ### Nested Markdown Blockquote Example Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/markdown.fr.md Blockquotes can be nested by using multiple `>` symbols. This allows for hierarchical quoting. ```markdown > Donec massa lacus, ultricies a ullamcorper in, fermentum sed augue. Nunc augue augue, aliquam non hendrerit ac, commodo vel nisi. >> Sed adipiscing elit vitae augue consectetur a gravida nunc vehicula. Donec auctor odio non est accumsan facilisis. Aliquam id turpis in dolor tincidunt mollis ac eu diam. ``` -------------------------------- ### Markdown Notice Example Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/markdown.fr.md Notices are handled via a dedicated plugin. The old mechanism for notices overriding block quote syntax has been deprecated. ```markdown {{% notice note %}} The old mechanism for notices overriding the block quote syntax (`>>>`) has been deprecated. Notices are now handled via a dedicated plugin called [Markdown Notices](https://github.com/getgrav/grav-plugin-markdown-notices) {{% /notice %}} ``` -------------------------------- ### Build Static Website Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/basics/installation/_index.en.md Generates the static files for your website, typically in a 'public' folder, ready for deployment to any web server. ```bash hugo ``` -------------------------------- ### Magefile with Help Text Comments Source: https://github.com/magefile/mage/blob/master/site/content/index.md Demonstrates how comments in a Magefile are used for generating help text for targets and flags. ```go //go:build mage // These docs will become the main help text when you run `mage` or `mage -l`. // This is where you talk about what the thing does. package main //mage:multiline // enable line return retention in doc output. import ( "github.com/any-go-packge/youwant" ) // Deploy runs the build and then uploads the artifacts to the server. // It deploys to the given environment. func Deploy(ctx context.Context, env string, version *string, // git tag for the build, defaults to the next minor build if not set dryRun *bool, // if set to true, just outputs the build artifacts ) error { return youwant.ToCallGoCode() } ``` -------------------------------- ### Basic Multilingual Configuration Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/i18n/_index.en.md Configure your Hugo site for multilingual support, defining default language and subdirectories. This setup ensures distinct URLs for each language. ```toml # English is the default language defaultContentLanguage = "en" # Force to have /en/my-page and /fr/my-page routes, even for default language. defaultContentLanguageInSubdir= true [Languages] [Languages.en] title = "Documentation for Hugo Learn Theme" weight = 1 languageName = "English" [Languages.fr] title = "Documentation du thème Hugo Learn" weight = 2 languageName = "Français" ``` -------------------------------- ### Configure Multilingual Menu Shortcuts Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/menushortcuts.en.md For multilingual sites, define language-specific menu shortcuts by prefixing the configuration with `Languages.`. This allows different menu items for each language. ```toml [Languages] [Languages.en] title = "Documentation for Hugo Learn Theme" weight = 1 languageName = "English" [[Languages.en.menu.shortcuts]] name = " Github repo" identifier = "ds" url = "https://github.com/matcornic/hugo-theme-learn" weight = 10 [[Languages.en.menu.shortcuts]] name = " Showcases" url = "/showcase" weight = 11 [[Languages.en.menu.shortcuts]] name = " Hugo Documentation" identifier = "hugodoc" url = "https://gohugo.io/" weight = 20 [[Languages.en.menu.shortcuts]] name = " Credits" url = "/credits" weight = 30 [Languages.fr] title = "Documentation du thème Hugo Learn" weight = 2 languageName = "Français" [[Languages.fr.menu.shortcuts]] name = " Repo Github" identifier = "ds" url = "https://github.com/matcornic/hugo-theme-learn" weight = 10 [[Languages.fr.menu.shortcuts]] name = " Vitrine" url = "/showcase" weight = 11 [[Languages.fr.menu.shortcuts]] name = " Documentation Hugo" identifier = "hugodoc" url = "https://gohugo.io/" weight = 20 [[Languages.fr.menu.shortcuts]] name = " Crédits" url = "/credits" weight = 30 ``` -------------------------------- ### Indented Code Block Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/markdown.en.md Indent lines of code by at least four spaces to create a block of code. This preserves whitespace and is suitable for longer code examples. ```text // Some comments line 1 of code line 2 of code line 3 of code ``` -------------------------------- ### Sequential Dependencies with mg.SerialCtxDeps Source: https://context7.com/magefile/mage/llms.txt Employ `mg.SerialCtxDeps` for sequential execution of context-aware dependencies, ideal for resource-intensive or order-sensitive tasks. Dependencies are executed in the order they are provided. ```go //go:build mage // +build mage package main import ( "context" "fmt" "github.com/magefile/mage/mg" "github.com/magefile/mage/sh" ) // MigrateDB runs database migrations sequentially to avoid lock conflicts. func MigrateDB(ctx context.Context) error { mg.SerialCtxDeps(ctx, MigrateV1, MigrateV2, MigrateV3) fmt.Println("All migrations complete.") return nil } func MigrateV1(ctx context.Context) error { fmt.Println("Running v1 migration...") return sh.Run("psql", "-f", "migrations/001_init.sql") } func MigrateV2(ctx context.Context) error { fmt.Println("Running v2 migration...") return sh.Run("psql", "-f", "migrations/002_add_users.sql") } func MigrateV3(ctx context.Context) error { fmt.Println("Running v3 migration...") return sh.Run("psql", "-f", "migrations/003_add_index.sql") } ``` ```bash mage migratedb # Output (strictly ordered): # Running v1 migration... # Running v2 migration... # Running v3 migration... # All migrations complete. ``` -------------------------------- ### Fenced Code Block Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/markdown.fr.md Use triple backticks (```) to create fenced code blocks for multi-line code examples. This is the most common method for displaying code. ```text Sample text here... ``` -------------------------------- ### Create a Chapter Archetype Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/archetypes.en.md Use this command to create a new chapter page with predefined front matter. Replace `` with your desired chapter name. ```bash hugo new --kind chapter /_index.md ``` -------------------------------- ### Define Target Aliases Source: https://github.com/magefile/mage/blob/master/site/content/targets/_index.en.md Shows how to define a map of string aliases to target functions. These aliases can be used interchangeably with the original target names. ```go var Aliases = map[string]interface{} { "i": Install, "build": Install, "ls": List, } ``` -------------------------------- ### Compile a static Mage binary Source: https://github.com/magefile/mage/blob/master/site/content/compiling/_index.en.md Pass the output path to the `-compile` flag to create a static binary. This binary will contain the Mage execution runtime and your tasks. ```bash $ mage -compile ./static-output ``` -------------------------------- ### Basic Button Shortcode Usage Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/shortcodes/button.en.md Demonstrates the basic usage of the button shortcode to create a clickable link. ```html {{%/* button href="https://getgrav.org/" */%}}Get Grav{{%/* /button */%}} ``` -------------------------------- ### Add Menu Shortcuts in config.toml Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/menushortcuts.en.md Define custom menu entries and shortcuts by adding `[[menu.shortcuts]]` sections to your `config.toml`. Each entry can have a name, identifier, URL, and weight. ```toml [[menu.shortcuts]] name = " Github repo" identifier = "ds" url = "https://github.com/matcornic/hugo-theme-learn" weight = 10 [[menu.shortcuts]] name = " Showcases" url = "/showcase" weight = 11 [[menu.shortcuts]] name = " Hugo Documentation" identifier = "hugodoc" url = "https://gohugo.io/" weight = 20 [[menu.shortcuts]] name = " Credits" url = "/credits" weight = 30 ``` -------------------------------- ### Runtime Environment Helpers with mg Package Source: https://context7.com/magefile/mage/llms.txt The mg package provides functions like mg.Verbose(), mg.Debug(), mg.GoCmd(), and mg.CacheDir() to access Mage's runtime configuration. These are useful for conditional logging and discovering tool locations. ```go //go:build mage // +build mage package main import ( "fmt" "github.com/magefile/mage/mg" "github.com/magefile/mage/sh" ) func Build() error { if mg.Verbose() { fmt.Println("Verbose mode enabled; showing all output.") } if mg.Debug() { fmt.Println("Debug mode enabled.") } // Use whatever go binary the user configured (MAGEFILE_GOCMD). goCmd := mg.GoCmd() if err := sh.Run(goCmd, "build", "-o", "bin/app", "./..."); err != nil { return err } fmt.Println("Cached binaries stored in:", mg.CacheDir()) return nil } ``` -------------------------------- ### Indented Code Block Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/markdown.fr.md Indent lines of code by at least four spaces to create a block of code. This is useful for longer code examples when fenced code blocks are not preferred. ```text // Some comments line 1 of code line 2 of code line 3 of code ``` -------------------------------- ### File System Helpers: sh.Rm and sh.Copy Source: https://context7.com/magefile/mage/llms.txt sh.Rm removes files or directories without error if they don't exist. sh.Copy copies files, overwriting the destination and preserving permissions. Use these for cleaning build artifacts and packaging. ```go //go:build mage // +build mage package main import ( "github.com/magefile/mage/mg" "github.com/magefile/mage/sh" ) // Clean removes build artifacts. func Clean() error { if err := sh.Rm("bin"); err != nil { return err } return sh.Rm("dist") } // Package builds and copies the binary into a distribution folder. func Package() error { mg.Deps(Build) if err := sh.Copy("dist/app", "bin/app"); err != nil { return err } return sh.Copy("dist/app.conf", "config/default.conf") } func Build() error { return sh.Run("go", "build", "-o", "bin/app", "./...") } ``` -------------------------------- ### Display Children Pages with Shortcode Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/shortcodes/_index.en.md Use the 'children' shortcode to display a list of child pages. Configure the style and whether to include descriptions. ```gohtml {{% children style="h2" description="true" %}} ``` -------------------------------- ### Create a Default Archetype Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/archetypes.en.md Use either of these commands to create a new default content page. The first creates an index file within a chapter, while the second creates a standalone markdown file. ```bash # Either hugo new //_index.md # Or hugo new /.md ``` -------------------------------- ### Mermaid GANTT Chart Shortcode Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/shortcodes/mermaid.en.md Utilize the mermaid shortcode to define and render GANTT charts. This example showcases task completion, active tasks, and future tasks with date and duration specifications. ```html {{}} gantt dateFormat YYYY-MM-DD title Adding GANTT diagram functionality to mermaid section A section Completed task :done, des1, 2014-01-06,2014-01-08 Active task :active, des2, 2014-01-09, 3d Future task : des3, after des2, 5d Future task2 : des4, after des3, 5d section Critical tasks Completed task in the critical line :crit, done, 2014-01-06,24h Implement parser and jison :crit, done, after des1, 2d Create tests for parser :crit, active, 3d Future task in critical line :crit, 5d Create tests for renderer :2d Add to mermaid :1d {{}} ``` -------------------------------- ### Basic Dependency Declaration Source: https://github.com/magefile/mage/blob/master/site/content/dependencies/_index.en.md Use mg.Deps as the first line in a function to ensure its dependencies run before the function executes. This is the most common way to manage dependencies. ```go mg.Deps(Install) ``` -------------------------------- ### Add Mage to `dep` `Gopkg.toml` Source: https://github.com/magefile/mage/blob/master/site/content/zeroInstall/_index.en.md If using `dep` for dependency management, add Mage to the `required` clause in `Gopkg.toml`. This prevents Mage from being removed due to the `+build ignore` tag. ```toml required = ["github.com/magefile/mage/mage"] ``` -------------------------------- ### Create Reusable Command Aliases with sh.RunCmd and sh.OutCmd Source: https://context7.com/magefile/mage/llms.txt Use sh.RunCmd and sh.OutCmd to create reusable command aliases. These functions return closures that bake in a command and optional prefix arguments, ideal for frequently used tools. ```go //go:build mage // +build mage package main import ( "fmt" "github.com/magefile/mage/sh" ) // Go is a keyword, so alias the go tool. var goCmd = sh.RunCmd("go") var goInstall = sh.RunCmd("go", "install") var gitHash = sh.OutCmd("git", "rev-parse", "--short") func Install() error { return goInstall("github.com/golangci/golangci-lint/cmd/golangci-lint@latest") } func Vet() error { return goCmd("vet", "./...") } func PrintHash() error { hash, err := gitHash("HEAD") if err != nil { return err } fmt.Println("HEAD:", hash) return nil } ``` -------------------------------- ### Dependencies with Arguments using mg.F Source: https://context7.com/magefile/mage/llms.txt Use `mg.F` to wrap functions with specific arguments for use with `mg.Deps`. Different arguments create distinct dependencies, while identical calls are deduplicated. Supported argument types include string, int, bool, and time.Duration. ```go //go:build mage // +build mage package main import ( "fmt" "github.com/magefile/mage/mg" "github.com/magefile/mage/sh" ) // BuildAll compiles server and client binaries in parallel. func BuildAll() { mg.Deps( mg.F(Compile, "server"), mg.F(Compile, "client"), ) } // Compile compiles a named binary. Multiple calls with the same name run only once. func Compile(name string) error { fmt.Printf("Compiling %s...\n", name) return sh.Run("go", "build", "-o", "bin/"+name, "./cmd/"+name) } // Test runs tests for a specific package. func TestPkg() { // mg.F(Compile, "server") here reuses the already-run result from BuildAll's dep. mg.Deps(mg.F(Compile, "server")) _ = sh.Run("go", "test", "./cmd/server/...") } ``` ```bash mage buildall # server and client compile concurrently # Output (order of server/client lines is non-deterministic): # Compiling server... # Compiling client... ``` -------------------------------- ### Cross-compile a static Mage binary Source: https://github.com/magefile/mage/blob/master/site/content/compiling/_index.en.md Use the `-goos` and `-goarch` flags with `-compile` to build a static binary for a different operating system and architecture. Refer to the Go documentation for valid values. ```bash mage -compile ./static-output -goos linux -goarch amd64 ``` -------------------------------- ### Button Shortcode with Icon Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/shortcodes/button.en.md Shows how to add an icon to the button using the 'icon' parameter. ```html {{%/* button href="https://getgrav.org/" icon="fa fa-download" */%}}Get Grav with icon{{%/* /button */%}} ``` -------------------------------- ### Import Mage Targets with Namespace Source: https://github.com/magefile/mage/blob/master/site/content/importing/_index.en.md Import targets from a package into a specific namespace. If the imported package 'builder' has a 'func All()', it will be available as 'build:all'. Use underscore imports if the package itself is not needed in the root namespace. ```go import ( //mage:import _ "example.com/me/foobar" //mage:import build "example.com/me/builder" ) ``` -------------------------------- ### Global Site Parameters Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/basics/configuration/_index.en.md Define global site parameters in your config.toml file to customize the Learn theme's behavior and appearance. These include options for editing URLs, author information, site description, and various display settings. ```toml [params] # Prefix URL to edit current page. Will display an "Edit this page" button on top right hand corner of every page. # Useful to give opportunity to people to create merge request for your doc. # See the config.toml file from this documentation site to have an example. editURL = "" # Author of the site, will be used in meta information author = "" # Description of the site, will be used in meta information description = "" # Shows a checkmark for visited pages on the menu showVisitedLinks = false # Disable search function. It will hide search bar disableSearch = false # Javascript and CSS cache are automatically busted when new version of site is generated. # Set this to true to disable this behavior (some proxies don't handle well this optimization) disableAssetsBusting = false # Set this to true to disable copy-to-clipboard button for inline code. disableInlineCopyToClipBoard = false # A title for shortcuts in menu is set by default. Set this to true to disable it. disableShortcutsTitle = false # When using mulitlingual website, disable the switch language button. disableLanguageSwitchingButton = false # Order sections in menu by "weight" or "title". Default to "weight" ordersectionsby = "weight" # Change default color scheme with a variant one. Can be "red", "blue", "green". themeVariant = "" ``` -------------------------------- ### Create Aliases for Magefile Targets Source: https://context7.com/magefile/mage/llms.txt Define a package-level `var Aliases = map[string]interface{}{...}` to map short names to target functions. These aliases are interchangeable with their targets at the CLI. ```go //go:build mage // +build mage package main import ( "fmt" "github.com/magefile/mage/mg" ) type Test mg.Namespace var Aliases = map[string]interface{}{ "b": Build, "t": Test.Unit, "lint": Lint, } func Build() error { fmt.Println("building...") return nil } func (Test) Unit() error { fmt.Println("running unit tests...") return nil } func Lint() error { fmt.Println("linting...") return nil } ``` ```bash mage b # same as: mage build mage t # same as: mage test:unit mage lint # same as: mage lint ``` -------------------------------- ### Compile Mage Static Binary Source: https://context7.com/magefile/mage/llms.txt This command compiles a self-contained Mage binary. The resulting executable includes the Mage runtime and all targets, and does not require a Go toolchain at runtime. ```bash # Compile a self-contained build tool binary for the current platform: mage -compile ./build-tool # Cross-compile for Linux/amd64: mage -compile ./build-tool-linux -goos linux -goarch amd64 # Cross-compile for Windows: mage -compile ./build-tool.exe -goos windows -goarch amd64 # Run the compiled binary directly (no mage or Go required on target machine): ./build-tool -l ./build-tool build ./build-tool -t 10m test ``` -------------------------------- ### Create New Chapter Page Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/basics/installation/_index.en.md Use this command to create a new chapter page using the 'chapter' archetype. This is useful for organizing content into sections. ```bash hugo new --kind chapter basics/_index.md ``` -------------------------------- ### Context-Aware Parallel Dependencies with mg.CtxDeps Source: https://context7.com/magefile/mage/llms.txt Use `mg.CtxDeps` to propagate a `context.Context` to parallel dependencies, enabling timeout and cancellation. Ensure dependencies accept a `context.Context` argument. ```go //go:build mage // +build mage package main import ( "context" "fmt" "github.com/magefile/mage/mg" "github.com/magefile/mage/sh" ) func IntegrationTest(ctx context.Context) error { // Both deps receive the same context (which may have a timeout from -t flag). mg.CtxDeps(ctx, StartDB, StartServer) defer stopServices() return sh.Run("go", "test", "-tags=integration", "./...") } func StartDB(ctx context.Context) error { fmt.Println("Starting database...") return sh.Run("docker", "compose", "up", "-d", "db") } func StartServer(ctx context.Context) error { fmt.Println("Starting server...") return sh.Run("docker", "compose", "up", "-d", "server") } func stopServices() { _ = sh.Run("docker", "compose", "down") } ``` ```bash mage -t 5m integrationtest # context cancels after 5 minutes ``` -------------------------------- ### Basic Expand Shortcode Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/shortcodes/expand.en.md Use this shortcode to create a simple expandable section with default 'Expand me...' text. The content within the shortcode will be hidden until the user clicks to expand it. ```gohtml {{%expand%}} Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. {{%/expand%}} ``` -------------------------------- ### Listing Magefile Targets Source: https://github.com/magefile/mage/blob/master/site/content/magefiles/_index.en.md Command to list available Magefile targets and their descriptions. The output format depends on the '//mage:multiline' directive in the Magefile. ```bash $ mage -l A comment on the package will be output when you list the targets of a magefile. If you set MAGEFILE_MULTILINE=true or have the //mage:multiline comment in the file, mage will retain line returns in comments it outputs as help docs. If you don't include those, it will convert line returns into spaces. Targets: install* Build target is any exported function with zero args with no return or an error return. target The first sentence in the comment will be the short help text shown with mage -l. * default target ``` -------------------------------- ### Basic Markdown Link Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/markdown.fr.md Create a basic hyperlink using square brackets for the link text and parentheses for the URL. This is the standard way to link to external resources. ```markdown [Assemble](http://assemble.io) ``` -------------------------------- ### Basic Markdown Image Syntax Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/markdown.en.md Use this syntax to include an image with an alt text and URL. The alt text is displayed if the image cannot be loaded. ```markdown ![Minion](http://octodex.github.com/images/minion.png) ``` ```markdown ![Alt text](http://octodex.github.com/images/stormtroopocat.jpg "The Stormtroopocat") ``` -------------------------------- ### Activate Search Functionality Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/basics/configuration/_index.en.md Enable the search functionality by adding the specified output format to your config.toml file. This configuration is necessary for the theme to generate the JSON index required by the lunr.js search engine. ```toml [outputs] home = [ "HTML", "RSS", "JSON"] ``` -------------------------------- ### Basic Magefile Build Tag Source: https://github.com/magefile/mage/blob/master/site/content/magefiles/_index.en.md This is the minimum required content for a file to be recognized as a Magefile. It uses a Go build tag to identify it. ```go //go:build mage package main ``` -------------------------------- ### Resize Image using Height and Width Parameters in Markdown Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/cont/markdown.fr.md Specify both height and width for an image using URL parameters to achieve precise dimensions. Ensure values are valid CSS units. ```markdown ![Minion](http://octodex.github.com/images/minion.png?height=50px&width=300px) ``` -------------------------------- ### Create New Content Pages Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/basics/installation/_index.en.md Commands to create new content pages within a chapter. The first creates a standard content page, and the second creates a content page that acts as a chapter index. ```bash hugo new basics/first-content.md hugo new basics/second-content/_index.md ``` -------------------------------- ### Capture Command Output with sh.Output and sh.OutputWith Source: https://context7.com/magefile/mage/llms.txt Use sh.Output to run a command and capture its trimmed stdout as a string. sh.OutputWith allows specifying extra environment variables for the command. Both functions pass stderr to the terminal. ```go //go:build mage // +build mage package main import ( "fmt" "github.com/magefile/mage/sh" ) func ShowVersion() error { goVersion, err := sh.Output("go", "version") if err != nil { return err } fmt.Println("Go version:", goVersion) gitHash, err := sh.Output("git", "rev-parse", "--short", "HEAD") if err != nil { return err } fmt.Println("Git commit:", gitHash) // With extra env vars linuxArch, err := sh.OutputWith( map[string]string{"GOOS": "linux", "GOARCH": "arm64"}, "go", "env", "GOARCH", ) if err != nil { return err } fmt.Println("Target arch:", linuxArch) // arm64 return nil } ``` -------------------------------- ### Execute Shell Commands with Magefile's `sh` Package Source: https://context7.com/magefile/mage/llms.txt The `sh` package provides wrappers for `os/exec`. `sh.Run` silently swallows stdout (visible with `-v`), `sh.RunV` always forwards stdout, and `sh.RunWith` accepts additional environment variables. Exit-code errors are automatically wrapped. ```go //go:build mage // +build mage package main import ( "github.com/magefile/mage/sh" ) func Build() error { // Only shows output with `mage -v` return sh.Run("go", "build", "-o", "bin/app", "./...") } func Test() error { // Always streams output to terminal return sh.RunV("go", "test", "-race", "-count=1", "./...") } func CrossCompile() error { // Injects environment variables for the subprocess return sh.RunWith( map[string]string{"GOOS": "linux", "GOARCH": "amd64"}, "go", "build", "-o", "bin/app-linux-amd64", "./...", ) } ``` ```bash mage build # silent unless -v mage test # always streams test output mage crosscompile ``` -------------------------------- ### View Available Targets with -autocomplete Source: https://github.com/magefile/mage/blob/master/site/content/tabcompletion/_index.en.md This flag prints a plain list of available targets, one per line, for the current directory. It's used internally by completion scripts and can be run manually to see potential completions. ```bash mage -autocomplete ``` -------------------------------- ### Children List with Descriptions Source: https://github.com/magefile/mage/blob/master/site/themes/learn/exampleSite/content/shortcodes/children/_index.en.md Includes a short text description under each child page link. If no description is found, it defaults to the first 70 words of the content. ```gohtml {{%/* children description="true" */%}} ``` ```gohtml {{%children description="true" %}} ```