feat: templates for all segments

This commit is contained in:
Jan De Dobbeleer 2022-01-22 19:46:56 +01:00 committed by Jan De Dobbeleer
parent d71b6e8e07
commit b816a0bf70
135 changed files with 1109 additions and 1216 deletions

View file

@ -146,6 +146,7 @@ You can use these on any segment, the engine is responsible for adding them corr
- postfix: `string`
- include_folders: `[]string`
- exclude_folders: `[]string`
- template: `string` - A go text/template [template][templates] to render the text
#### Prefix
@ -217,3 +218,4 @@ This means that for user Bill, who has a user account `Bill` on Windows and `bil
[fg-templ]: /docs/config-overview#foreground-templates
[regex]: https://www.regular-expressions.info/tutorial.html
[aws]: /docs/aws
[templates]: /docs/config-text#templates

View file

@ -1,10 +1,24 @@
---
id: config-text-style
title: Text style
sidebar_label: Text style
id: config-text
title: Text
sidebar_label: Text
---
## Text decorations
## Templates
Every segment has a `template` property to tweak the text that is displayed.
Under the hood, this uses go's [text/template][go-text-template] feature extended with [sprig][sprig] and
offers a few standard properties to work with.
- `.Root`: `boolean` - is the current user root/admin or not
- `.PWD`: `string` - the current working directory
- `.Folder`: `string` - the current working folder
- `.Shell`: `string` - the current shell name
- `.UserName`: `string` - the current user name
- `.HostName`: `string` - the host name
- `.Env.VarName`: `string` - Any environment variable where `VarName` is the environment variable name
## Text decoration
You can make use of the following syntax to decorate text:
@ -38,3 +52,5 @@ When using in a template, the syntax is like markdown:
[terminal-list-hyperlinks]: https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
[path-segment]: /docs/path
[git-segment]: /docs/git
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/

View file

@ -30,22 +30,12 @@ To manipulate the console title, you can make use of the following properties:
You can create a more custom console title with the use of `"console_title_style" = "template"`.
When this is set, a `console_title_template` is also expected, otherwise, the title will remain empty.
Under the hood, this uses go's [text/template][go-text-template] feature extended with [sprig][sprig] and
offers a few standard properties to work with.
- `.Root`: `boolean` - is the current user root/admin or not
- `.PWD`: `string` - the current working directory
- `.Folder`: `string` - the current working folder
- `.Shell`: `string` - the current shell name
- `.UserName`: `string` - the current user name
- `.HostName`: `string` - the host name
- `.Env.VarName`: `string` - Any environment variable where `VarName` is the environment variable name
A `boolean` can be used for conditional display purposes, a `string` can be displayed.
The following examples illustrate possible contents for `console_title_template`, provided
the current working directory is `/usr/home/omp` and the shell is `zsh`.
To learn more about templates and their possibilities, have a look at the [template][templates] section.
```json
{
"console_title_template": "{{.Folder}}{{if .Root}} :: root{{end}} :: {{.Shell}}",
@ -61,3 +51,4 @@ the current working directory is `/usr/home/omp` and the shell is `zsh`.
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -49,10 +49,10 @@ The configuration has the following properties:
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below - defaults to `{{ .Shell }}> `
## Template Properties
## [Template][templates] Properties
- `.Root`: `boolean` - is the current user root/admin or not
- `.Path`: `string` - the current working directory
- `.PWD`: `string` - the current working directory
- `.Folder`: `string` - the current working folder
- `.Shell`: `string` - the current shell name
- `.UserName`: `string` - the current user name

View file

@ -25,14 +25,12 @@ Display the currently active Angular CLI version.
## Properties
- display_version: `boolean` - display the active version or not; useful if all you need is an icon indicating `ng`
- fetch_version: `boolean` - fetch the active version or not; useful if all you need is an icon indicating `ng`
- display_mode: `string` - determines when the segment is displayed
- `always`: the segment is always displayed
- `files`: the segment is only displayed when `angular.json` file is present (default)
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below. Defaults to `{{ .Full }}`
## Template Properties
## [Template][templates] Properties
- `.Full`: `string` - the full version
- `.Major`: `string` - major number
@ -42,5 +40,4 @@ properties below. Defaults to `{{ .Full }}`
- `.BuildMetadata`: `string` - build metadata
- `.Error`: `string` - when fetching the version string errors
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -26,15 +26,12 @@ Display the currently active AWS profile and region.
## Properties
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below - defaults to `{{.Context}}{{if .Namespace}} :: {{.Namespace}}{{end}}`
- display_default: `boolean` - display the segment or not when the user profile matches `default` - defaults
to `true`
## Template Properties
## [Template][templates] Properties
- `.Profile`: `string` - the currently active profile
- `.Region`: `string` - the currently active region
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -24,12 +24,7 @@ Display the currently active Azure subscription information.
}
```
## Properties
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below - defaults to `{{.Name}}`
## Template Properties
## [Template][templates] Properties
- `.EnvironmentName`: `string` - the account environment name
- `.HomeTenantID`: `string` - the home tenant id
@ -41,5 +36,4 @@ properties below - defaults to `{{.Name}}`
- `.UserName`: `string` - the user name
- `.Origin`: `string` - where we received the information from, can be `CLI` or `PWSH`
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -19,7 +19,7 @@ Display the currently active Azure functions CLI version.
"background": "#FEAC19",
"properties": {
"prefix": " \uf0e7 ",
"display_version": true,
"fetch_version": true,
"display_mode": "files"
}
}
@ -27,16 +27,14 @@ Display the currently active Azure functions CLI version.
## Properties
- display_version: `boolean` - display the Azure functions CLI version - defaults to `true`
- fetch_version: `boolean` - fetch the Azure functions CLI version - defaults to `true`
- display_error: `boolean` - show the error context when failing to retrieve the version information - defaults to `true`
- missing_command_text: `string` - text to display when the command is missing - defaults to empty
- display_mode: `string` - determines when the segment is displayed
- `always`: the segment is always displayed
- `files`: the segment is only displayed when a `host.json` or `local.settings.json` files is present (default)
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below. Defaults to `{{ .Full }}`
## Template Properties
## [Template][templates] Properties
- `.Full`: `string` - the full version
- `.Major`: `string` - major number
@ -46,5 +44,4 @@ properties below. Defaults to `{{ .Full }}`
- `.BuildMetadata`: `string` - build metadata
- `.Error`: `string` - when fetching the version string errors
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -34,14 +34,12 @@ Battery displays the remaining power percentage for your battery.
## Properties
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below - defaults to `{{.Icon}}{{ if not .Error }}{{.Percentage}}{{ end }}{{.Error}}`
- display_error: `boolean` - show the error context when failing to retrieve the battery information - defaults to `false`
- charging_icon: `string` - icon to display on the left when charging - defaults to empty
- discharging_icon: `string` - icon to display on the left when discharging - defaults to empty
- charged_icon: `string` - icon to display on the left when fully charged - defaults to empty
## Template Properties
## [Template][templates] Properties
- `.State`: `struct` - the battery state, has a `.String` function
- `.Current`: `float64` - Current (momentary) charge rate (in mW).
@ -60,5 +58,4 @@ the same value as `Voltage`, for convenience
[colors]: /docs/config-colors
[battery]: https://github.com/distatus/battery/blob/master/battery.go#L78
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -46,8 +46,6 @@ NOTE: Temperature units are in degrees C and specific gravity is expressed as `X
- batch_id: `string` - Get this by navigating to the desired batch on the brewfather website,
the batch id is at the end of the URL in the address bar.
- http_timeout: `int` in milliseconds - How long to wait for the Brewfather service to answer the request. Default 2 seconds.
- template: `string` - a go [text/template][go-text-template] template extended
with [sprig][sprig] utilizing the properties below.
- cache_timeout: `int` in minutes - How long to wait before updating the data from Brewfather. Default is 5 minutes.
- day_icon: `string` - icon or letter to use to indicate days. Default is "d".
@ -70,7 +68,7 @@ You can override the default icons for batch status as used by template property
- completed_status_icon
- archived_status_icon
## Template Properties
## [Template][templates] Properties
Commonly used fields
@ -166,7 +164,6 @@ To display gravity as SG in XXXX format (e.g. "1020" instead of "1.020"), use th
}
````
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates
[brewfather]: http://brewfather.app
[wikipedia_gravity_page]:https://en.wikipedia.org/wiki/Brix#Specific_gravity_2

View file

@ -45,4 +45,9 @@ error). The `&&` functionality will join the output of the commands when success
- shell: `string` - the shell in which to run the command in. Uses `shell -c command` under the hood.
- command: `string` - the command(s) to run
## [Template][templates] Properties
- `.Output`: `string` - the output of the command.
[env]: /docs/environment
[templates]: /docs/config-text#templates

View file

@ -26,16 +26,14 @@ Display the currently active crystal version.
## Properties
- home_enabled: `boolean` - display the segment in the HOME folder or not - defaults to `false`
- display_version: `boolean` - display the julia version - defaults to `true`
- fetch_version: `boolean` - fetch the julia version - defaults to `true`
- display_error: `boolean` - show the error context when failing to retrieve the version information - defaults to `true`
- missing_command_text: `string` - text to display when the command is missing - defaults to empty
- display_mode: `string` - determines when the segment is displayed
- `always`: the segment is always displayed
- `files`: the segment is only displayed when `*.cr` or `shard.yml` files are present (default)
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below. Defaults to `{{ .Full }}`
## Template Properties
## [Template][templates] Properties
- `.Full`: `string` - the full version
- `.Major`: `string` - major number
@ -45,5 +43,4 @@ Display the currently active crystal version.
- `.BuildMetadata`: `string` - build metadata
- `.Error`: `string` - when fetching the version string errors
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -26,17 +26,15 @@ Display the currently active dart version.
## Properties
- home_enabled: `boolean` - display the segment in the HOME folder or not - defaults to `false`
- display_version: `boolean` - display the dart version - defaults to `true`
- fetch_version: `boolean` - fetch the dart version - defaults to `true`
- display_error: `boolean` - show the error context when failing to retrieve the version information - defaults to `true`
- missing_command_text: `string` - text to display when the command is missing - defaults to empty
- display_mode: `string` - determines when the segment is displayed
- `always`: the segment is always displayed
- `files`: the segment is only displayed when `*.dart`, `pubspec.yaml`, `pubspec.yml`, `pubspec.lock` files or the `.dart_tool`
folder are present (default)
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below. Defaults to `{{ .Full }}`
## Template Properties
## [Template][templates] Properties
- `.Full`: `string` - the full version
- `.Major`: `string` - major number
@ -46,5 +44,4 @@ properties below. Defaults to `{{ .Full }}`
- `.BuildMetadata`: `string` - build metadata
- `.Error`: `string` - when fetching the version string errors
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -26,7 +26,7 @@ Display the currently active .NET SDK version.
## Properties
- home_enabled: `boolean` - display the segment in the HOME folder or not - defaults to `false`
- display_version: `boolean` - display the active version or not; useful if all you need is an icon indicating `dotnet`
- fetch_version: `boolean` - fetch the active version or not; useful if all you need is an icon indicating `dotnet`
is present - defaults to `true`
- display_error: `boolean` - show the error context when failing to retrieve the version information - defaults to `true`
- missing_command_text: `string` - text to display when the command is missing - defaults to empty
@ -36,12 +36,10 @@ Display the currently active .NET SDK version.
or `*.fsproj` files are present (default)
- unsupported_version_icon: `string` - text/icon that is displayed when the active .NET SDK version (e.g., one specified
by `global.json`) is not installed/supported - defaults to `\uf071` (X in a rectangle box)
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below. Defaults to `{{ .Full }}`
- version_url_template: `string` - A go [text/template][go-text-template] template extended
with [sprig][sprig] utilizing the properties below. Defaults does nothing(backward compatibility).
## Template Properties
## [Template][templates] Properties
- `.Full`: `string` - the full version
- `.Major`: `string` - major number
@ -51,5 +49,4 @@ with [sprig][sprig] utilizing the properties below. Defaults does nothing(backwa
- `.BuildMetadata`: `string` - build metadata
- `.Error`: `string` - when fetching the version string errors
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -49,7 +49,9 @@ Style specifies the format in which the time will be displayed. The table below
| amarillo | `0.001s` | `2.1s` | `182.1s` | `14,582.1s` |
| round | `1ms` | `2s` | `3m 2s` | `4h 3m` |
## Template Properties
## [Template][templates] Properties
- `.Ms`: `number` - the execution time in milliseconds
- `.FormattedMs`: `string` - the formatted value based on the `style` above.
[templates]: /docs/config-text#templates

View file

@ -35,7 +35,9 @@ Displays the last exit code or that the last command failed based on the configu
[colors]: /docs/config-colors
## Template Properties
## [Template][templates] Properties
- `.Code`: `number` - the last known exit code
- `.Text`: `string` - the textual meaning linked to exit code (if applicable, otherwise identical to `.Code`)
[templates]: /docs/config-text#templates

View file

@ -53,9 +53,6 @@ An alternative is to use the [Posh-Git segment][poshgit]
## Properties
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below - defaults to empty.
### Fetching information
As doing multiple git calls can slow down the prompt experience, we do not fetch information by default.
@ -96,7 +93,7 @@ You can set the following properties to `true` to enable fetching additional inf
- azure_devops_icon: `string` - icon/text to display when the upstream is Azure DevOps - defaults to `\uFD03 `
- git_icon: `string` - icon/text to display when the upstream is not known/mapped - defaults to `\uE5FB `
## Template Properties
## [Template][templates] Properties
- `.Working`: `GitStatus` - changes in the working tree (see below)
- `.Staging`: `GitStatus` - staged changes in the work tree (see below)
@ -121,6 +118,5 @@ You can set the following properties to `true` to enable fetching additional inf
- `.String`: `string` - a string representation of the changes above
[poshgit]: /docs/poshgit
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[hyperlinks]: /docs/config-text-style#hyperlinks
[templates]: /docs/config-text#templates
[hyperlinks]: /docs/config-text#hyperlinks

View file

@ -26,17 +26,15 @@ Display the currently active golang version.
## Properties
- home_enabled: `boolean` - display the segment in the HOME folder or not - defaults to `false`
- display_version: `boolean` - display the golang version - defaults to `true`
- fetch_version: `boolean` - display the golang version - defaults to `true`
- display_error: `boolean` - show the error context when failing to retrieve the version information - defaults to `true`
- missing_command_text: `string` - text to display when the command is missing - defaults to empty
- display_mode: `string` - determines when the segment is displayed
- `always`: the segment is always displayed
- `files`: the segment is only displayed when `*.go` or `go.mod` files are present (default)
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below. Defaults to `{{ .Full }}`
- parse_mod_file: `boolean`: parse the go.mod file instead of calling `go version`
## Template Properties
## [Template][templates] Properties
- `.Full`: `string` - the full version
- `.Major`: `string` - major number
@ -45,3 +43,5 @@ properties below. Defaults to `{{ .Full }}`
- `.Prerelease`: `string` - prerelease info text
- `.BuildMetadata`: `string` - build metadata
- `.Error`: `string` - when fetching the version string errors
[templates]: /docs/config-text#templates

View file

@ -33,13 +33,10 @@ sidebar_label: Ipify
defaults to 20ms
- cache_timeout: `int` in minutes - How long do you want your IP address cached? -
defaults to 10 min
- template: `string` - a go [text/template][go-text-template] template extended
with [sprig][sprig] utilizing the properties below. - defaults to `{{ .IP }}`
## Template Properties
## [Template][templates] Properties
- .IP: `string` - Your external IP address
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates
[ipify]: https://www.ipify.org/

View file

@ -26,7 +26,7 @@ Display the currently active java version.
## Properties
- home_enabled: `boolean` - display the segment in the HOME folder or not - defaults to `false`
- display_version: `boolean` - display the java version - defaults to `true`
- fetch_version: `boolean` - display the java version - defaults to `true`
- display_error: `boolean` - show the error context when failing to retrieve the version information - defaults to `true`
- missing_command_text: `string` - text to display when the java command is missing - defaults to empty
- display_mode: `string` - determines when the segment is displayed
@ -45,10 +45,8 @@ Display the currently active java version.
- `*.jar`
- `*.clj`
- `*.cljc`
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below. Defaults to `{{ .Full }}`
## Template Properties
## [Template][templates] Properties
- `.Full`: `string` - the full version
- `.Major`: `string` - major number
@ -57,3 +55,5 @@ properties below. Defaults to `{{ .Full }}`
- `.Prerelease`: `string` - prerelease info text
- `.BuildMetadata`: `string` - build metadata
- `.Error`: `string` - when fetching the version string errors
[templates]: /docs/config-text#templates

View file

@ -26,16 +26,14 @@ Display the currently active julia version.
## Properties
- home_enabled: `boolean` - display the segment in the HOME folder or not - defaults to `false`
- display_version: `boolean` - display the julia version - defaults to `true`
- fetch_version: `boolean` - display the julia version - defaults to `true`
- display_error: `boolean` - show the error context when failing to retrieve the version information - defaults to `true`
- missing_command_text: `string` - text to display when the command is missing - defaults to empty
- display_mode: `string` - determines when the segment is displayed
- `always`: the segment is always displayed
- `files`: the segment is only displayed when `*.jl` files are present (default)
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below. Defaults to `{{ .Full }}`
## Template Properties
## [Template][templates] Properties
- `.Full`: `string` - the full version
- `.Major`: `string` - major number
@ -45,5 +43,4 @@ properties below. Defaults to `{{ .Full }}`
- `.BuildMetadata`: `string` - build metadata
- `.Error`: `string` - when fetching the version string errors
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -26,13 +26,11 @@ Display the currently active Kubernetes context name and namespace name.
## Properties
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below - defaults to `{{.Context}}{{if .Namespace}} :: {{.Namespace}}{{end}}`
- display_error: `boolean` - show the error context when failing to retrieve the kubectl information - defaults to `false`
- parse_kubeconfig: `boolean` - parse kubeconfig files instead of calling out to kubectl to improve
performance - defaults to `false`
## Template Properties
## [Template][templates] Properties
- `.Context`: `string` - the current kubectl context
- `.Namespace`: `string` - the current kubectl context namespace
@ -46,5 +44,4 @@ It is common for the Kubernetes "default" namespace to be used when no namespace
`{{.Context}} :: {{if .Namespace}}{{.Namespace}}{{else}}default{{end}}`
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -27,12 +27,7 @@ The Nerdbank.GitVersioning CLI can be a bit slow causing the prompt to feel slow
}
```
## Properties
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below - defaults to `{{ .Version }}`
## Template Properties
## [Template][templates] Properties
- `.Version`: `string` - the current version
- `.AssemblyVersion`: `string` - the current assembly version
@ -43,5 +38,4 @@ properties below - defaults to `{{ .Version }}`
- `.SimpleVersion`: `string` - the current simple version
[nbgv]: https://github.com/dotnet/Nerdbank.GitVersioning
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -64,12 +64,6 @@ Or display in mmol/l (instead of the default mg/dl) with the following template:
- http_timeout: `int` - How long do you want to wait before you want to see
your prompt more than your sugar? I figure a half second is a good default -
defaults to 500ms
- template: `string` - a go [text/template][go-text-template] template extended
with [sprig][sprig] utilizing the properties below.
See the example above where I added a syringe.
You can change the icon, put the trend elsewhere, add text, however you like!
Make sure your NerdFont has the glyph you want or search for one
at nerdfonts.com
- NSCacheTimeout: `int` in minutes - How long do you want your numbers cached? -
defaults to 5 min
@ -85,7 +79,7 @@ Or display in mmol/l (instead of the default mg/dl) with the following template:
- SingleDownIcon - defaults to ↓
- DoubleDownIcon - defaults to ↓↓
## Template Properties
## [Template][templates] Properties
- .ID: `string` - The internal ID of the object
- .Sgv: `int` - Your Serum Glucose Value (your sugar)
@ -100,6 +94,5 @@ Or display in mmol/l (instead of the default mg/dl) with the following template:
- .TrendIcon: `string` - By default, this will be something like ↑↑ or ↘ etc but you can
override them with any glpyh as seen above
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates
[nightscout]: http://www.nightscout.info/

View file

@ -33,10 +33,8 @@ Display the currently active node version.
- fetch_package_manager: `boolean` - define if the current project uses Yarn or NPM - defaults to `false`
- yarn_icon: `string` - the icon/text to display when using Yarn - defaults to ` \uF61A`
- npm_icon: `string` - the icon/text to display when using NPM - defaults to ` \uE71E`
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below. Defaults to `{{ .Full }}`
## Template Properties
## [Template][templates] Properties
- `.Full`: `string` - the full version
- `.Major`: `string` - major number
@ -48,5 +46,4 @@ properties below. Defaults to `{{ .Full }}`
- `.PackageManagerIcon`: `string` - the Yarn on NPM icon when setting `fetch_package_manager` to `true`
- `.Mismatch`: `boolean` - if the version in `.nvmrc` matches with `.Full`
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -28,8 +28,6 @@ Display OS specific info - defaults to Icon.
- macos: `string` - the string to use for macOS - defaults to macOS icon - defaults to `\uF179`
- linux: `string` - the icon to use for Linux - defaults to Linux icon - defaults to `\uF17C`
- windows: `string` - the icon to use for Windows - defaults to Windows icon - defaults to `\uE62A`
- wsl: `string` - the string/icon to use for WSL - defaults to `WSL`
- wsl_separator: `string` - the string to use for separating WSL from Linux - defaults to ` - `
- display_distro_name: `boolean` - display the distro name or icon (for WSL and Linux) - defaults to `false`
- alpine: `string` - the icon to use for Alpine - defaults to Alpine icon - defaults to `\uF300`
- aosc: `string` - the icon to use for Aosc - defaults to Aosc icon - defaults to `\uF301`
@ -51,6 +49,8 @@ Display OS specific info - defaults to Icon.
- slackware: `string` - the icon to use for Slackware - defaults to Slackware icon - defaults to `\uF319`
- ubuntu: `string` - the icon to use for Ubuntu - defaults to Ubuntu icon - defaults to `\uF31b`
## Template Properties
## [Template][templates] Properties
- `.OS`: `string` - the OS platform
[templates]: /docs/config-text#templates

View file

@ -12,7 +12,6 @@ Shows the current weather of a given location.
You **must** request an API key at the [Open Weather Map](https://openweathermap.org/price) website.
The free tier for *Current weather and forecasts collection* is sufficient.
:::
## Sample Configuration
@ -50,9 +49,11 @@ The free tier for *Current weather and forecasts collection* is sufficient.
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below - defaults to `{{.Weather}} ({{.Temperature}}{{.UnitIcon}})`
## Template Properties
## [Template][templates] Properties
- `.Weather`: `string` - the current weather icon
- `.Temperature`: `string` - the current temperature
- `.UnitIcon`: `string` - the current unit icon(based on units property)
- `.URL`: `string` - the url of the current api call
[templates]: /docs/config-text#templates

View file

@ -38,8 +38,6 @@ Display the current path.
- mixed_threshold: `number` - the maximum length of a path segment that will be displayed when using `Mixed` -
defaults to `4`
- max_depth: `number` - maximum path depth to display before shortening when using `Agnoster Short` - defaults to `1`
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below. Defaults to `{{ .Path }}`
## Mapped Locations
@ -125,10 +123,9 @@ starts with a symbol or icon.
- `__pycache__` will be shortened to `__p`
- `➼ folder` will be shortened to `➼ f`
## Template Properties
## [Template][templates] Properties
- `.Path`: `string` - the current directory (styled)
- `.StackCount`: `int` - the stack count
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -27,17 +27,15 @@ Display the currently active php version.
## Properties
- home_enabled: `boolean` - display the segment in the HOME folder or not - defaults to `false`
- display_version: `boolean` - display the php version - defaults to `true`
- fetch_version: `boolean` - display the php version - defaults to `true`
- display_error: `boolean` - show the error context when failing to retrieve the version information - defaults to `true`
- missing_command_text: `string` - text to display when the command is missing - defaults to empty
- display_mode: `string` - determines when the segment is displayed
- `always`: the segment is always displayed
- `files`: the segment is only displayed when `*.php, composer.json, composer.lock, .php-version` files are present (default)
- enable_hyperlink: `bool` - display an hyperlink to the php release notes - defaults to `false`
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below. Defaults to `{{ .Full }}`
## Template Properties
## [Template][templates] Properties
- `.Full`: `string` - the full version
- `.Major`: `string` - major number
@ -47,5 +45,4 @@ properties below. Defaults to `{{ .Full }}`
- `.BuildMetadata`: `string` - build metadata
- `.Error`: `string` - when fetching the version string errors
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -50,9 +50,6 @@ by leaving a like!
## Properties
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below - defaults to empty.
### Fetching information
As doing multiple `cm` calls can slow down the prompt experience, we do not fetch information by default.
@ -74,7 +71,7 @@ You can set the following property to `true` to enable fetching additional infor
- commit_icon: `string` - icon/text to display before the commit context (detached HEAD) - defaults to `\uF417`
- tag_icon: `string` - icon/text to display before the tag context - defaults to `\uF412`
## Template Properties
## [Template][templates] Properties
- `.Selector`: `string` - the current selector context (branch/changeset/label)
- `.Behind`: `bool` - the current workspace is behind and changes are incoming
@ -92,6 +89,5 @@ You can set the following property to `true` to enable fetching additional infor
- `.Changed`: `boolean` - if the status contains changes or not
- `.String`: `string` - a string representation of the changes above
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates
[fa-issue]: https://github.com/FortAwesome/Font-Awesome/issues/18504

View file

@ -25,4 +25,9 @@ To enable the `posh-git` module, set `$env:POSH_GIT_ENABLED = $true` in your `$P
}
```
## [Template][templates] Properties
- `.Status`: `string` - the status reported from posh-git
[posh-git]: https://github.com/dahlbyk/posh-git
[templates]: /docs/config-text#templates

View file

@ -30,7 +30,7 @@ Supports conda, virtualenv and pyenv.
- fetch_virtual_env: `boolean` - fetch the name of the virtualenv or not - defaults to `true`
- display_default: `boolean` - show the name of the virtualenv when it's default (`system`, `base`)
or not - defaults to `true`
- display_version: `boolean` - display the python version - defaults to `true`
- fetch_version: `boolean` - fetch the python version - defaults to `true`
- display_error: `boolean` - show the error context when failing to retrieve the version information - defaults to `true`
- missing_command_text: `string` - text to display when the command is missing - defaults to empty
- display_mode: `string` - determines when the segment is displayed
@ -39,10 +39,8 @@ or not - defaults to `true`
files are present (default)
- `environment`: the segment is only displayed when a virtual env is present
- `context`: the segment is only displayed when either `environment` or `files` is active
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below. Defaults to `{{ .Full }}`
## Template Properties
## [Template][templates] Properties
- `.Venv`: `string` - the virtual environment name (if present)
- `.Full`: `string` - the full version
@ -53,5 +51,4 @@ properties below. Defaults to `{{ .Full }}`
- `.BuildMetadata`: `string` - build metadata
- `.Error`: `string` - when fetching the version string errors
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -18,11 +18,7 @@ Show when the current user is root or when in an elevated shell (Windows).
"foreground": "#111111",
"background": "#ffff66",
"properties": {
"root_icon": "\uF0E7"
"template": "\uF0E7"
}
}
```
## Properties
- root_icon: `string` - icon to display in case of root/elevated - defaults to `\uF0E7`

View file

@ -26,16 +26,14 @@ Display the currently active ruby version.
## Properties
- home_enabled: `boolean` - display the segment in the HOME folder or not - defaults to `false`
- display_version: `boolean` - display the ruby version - defaults to `true`
- fetch_version: `boolean` - display the ruby version - defaults to `true`
- display_error: `boolean` - show the error context when failing to retrieve the version information - defaults to `true`
- missing_command_text: `string` - text to display when the command is missing - defaults to empty
- display_mode: `string` - determines when the segment is displayed
- `always`: the segment is always displayed
- `files`: the segment is only displayed when `*.rb`, `Gemfile` or `Rakefile` files are present (default)
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below. Defaults to `{{ .Full }}`
## Template Properties
## [Template][templates] Properties
- `.Full`: `string` - the full version
- `.Major`: `string` - major number
@ -45,5 +43,4 @@ properties below. Defaults to `{{ .Full }}`
- `.BuildMetadata`: `string` - build metadata
- `.Error`: `string` - when fetching the version string errors
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -26,16 +26,14 @@ Display the currently active rust version.
## Properties
- home_enabled: `boolean` - display the segment in the HOME folder or not - defaults to `false`
- display_version: `boolean` - display the rust version (`rustc --version`) - defaults to `true`
- fetch_version: `boolean` - display the rust version (`rustc --version`) - defaults to `true`
- display_error: `boolean` - show the error context when failing to retrieve the version information - defaults to `true`
- missing_command_text: `string` - text to display when the command is missing - defaults to empty
- display_mode: `string` - determines when the segment is displayed
- `always`: the segment is always displayed
- `files`: the segment is only displayed when `*.rs`, `Cargo.toml` or `Cargo.lock` files are present (default)
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below. Defaults to `{{ .Full }}`
## Template Properties
## [Template][templates] Properties
- `.Full`: `string` - the full version
- `.Major`: `string` - major number
@ -45,5 +43,4 @@ properties below. Defaults to `{{ .Full }}`
- `.BuildMetadata`: `string` - build metadata
- `.Error`: `string` - when fetching the version string errors
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -24,17 +24,11 @@ Show the current user and host name.
}
```
## Properties
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below.
## Template Properties
## [Template][templates] Properties
- `.UserName`: `string` - the current user's name
- `.HostName`: `string` - the current computer's name
- `.SSHSession`: `boolean` - active SSH session or not
- `.Root`: `boolean` - are you a root/admin user or not
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -28,3 +28,9 @@ Show the current shell name (ZSH, powershell, bash, ...).
## Properties
- mapped_shell_names: `object` - custom glyph/text to use in place of specified shell names (case-insensitive)
## [Template][templates] Properties
- `.Name`: `string` - the shell name
[templates]: /docs/config-text#templates

View file

@ -24,8 +24,7 @@ On macOS, all states are supported (playing/paused/stopped).
"prefix": "\uF9C6 ",
"playing_icon": "\uE602 ",
"paused_icon": "\uF8E3 ",
"stopped_icon": "\uF04D ",
"track_separator" : " - "
"stopped_icon": "\uF04D "
}
}
```
@ -35,4 +34,12 @@ On macOS, all states are supported (playing/paused/stopped).
- playing_icon: `string` - text/icon to show when playing - defaults to `\uE602 `
- paused_icon: `string` - text/icon to show when paused - defaults to `\uF8E3 `
- stopped_icon: `string` - text/icon to show when stopped - defaults to `\uF04D `
- track_separator: `string` - text/icon to put between the artist and song name - defaults to ` - `
## [Template][templates] Properties
- `.Status`: `string` - player status (`playing`, `paused`, `stopped`)
- `.Artist`: `string` - current artist
- `.Track`: `string` - current track
- `.Icon`: `string` - icon (based on `.Status`)
[templates]: /docs/config-text#templates

View file

@ -62,8 +62,6 @@ if that color is visible against any of your backgrounds.
- refresh_token: `string` - token from Strava login, see login link in section above. It has the following format: `1111111111111111111111111`
- expires_in: `int` - the default timeout of the token from the Strava login
- http_timeout: `int` - how long do you want to wait before you want to see your prompt more than your strava data? - defaults to 500ms
- template: `string` - a go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the properties below.
See the example above. Make sure your NerdFont has the glyph you want or search for one at nerdfonts.com
- CacheTimeout: `int` in minutes - How long do you want your numbers cached? - defaults to 5 min
- RideIcon - defaults to `\uf5a2`
- RunIcon - defaults to `\ufc0c`
@ -72,7 +70,7 @@ See the example above. Make sure your NerdFont has the glyph you want or search
- UnknownActivityIcon - defaults to `\ue213`
- enable_hyperlink - display an hyperlink to activities - defaults to `false`
## Template Properties
## [Template][templates] Properties
The properties below are available for use in your template
@ -94,7 +92,6 @@ The properties below are available for use in your template
Now, go out and have a fun ride or run!
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates
[strava]: http://www.strava.com/
[strava-connect]: https://www.strava.com/oauth/authorize?client_id=76033&response_type=code&redirect_uri=https://ohmyposh.dev/api/auth&approval_prompt=force&scope=read,activity:read

View file

@ -1,7 +1,7 @@
---
id: sysinfo
title: SysInfo
sidebar_label: SysInfo
title: System Info
sidebar_label: System Info
---
## SysInfo
@ -30,10 +30,8 @@ Display SysInfo.
## Properties
- Precision: `int` - The precision used for any float values - defaults to 2
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below - defaults to `{{ round .PhysicalPercentUsed .Precision }}> `
## Template Properties
## [Template][templates] Properties
- `.PhysicalTotalMemory`: `int` - is the total of used physical memory
- `.PhysicalFreeMemory`: `int` - is the total of free physical memory
@ -47,3 +45,4 @@ properties below - defaults to `{{ round .PhysicalPercentUsed .Precision }}> `
- `.CPU`: `[]struct` - an array of [InfoStat][cpuinfo] object, you can use any property it has e.g. `(index .CPU 0).Cores`
[cpuinfo]: https://github.com/shirou/gopsutil/blob/78065a7ce2021f6a78c8d6f586a2683ba501dcec/cpu/cpu.go#L32
[templates]: /docs/config-text#templates

View file

@ -27,9 +27,8 @@ This requires a terraform binary in your PATH and will only show in directories
}
```
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below - defaults to `{{ .WorkspaceName }}> `
## Template Properties
## [Template][templates] Properties
- `.WorkspaceName`: `string` - is the current workspace name
[templates]: /docs/config-text#templates

View file

@ -35,12 +35,7 @@ New-Alias -Name 'Set-PoshContext' -Value 'Set-EnvVar' -Scope Global -Force
:::
## Properties
- template: `string` - text/icon to display. Powered by go [text/template][go-text-template] templates extended
with [sprig][sprig] utilizing the properties below.
## Template Properties
## [Template][templates] Properties
- `.Root`: `boolean` - is the current user root/admin or not
- `.Path`: `string` - the current working directory
@ -51,5 +46,4 @@ with [sprig][sprig] utilizing the properties below.
- `.Env.VarName`: `string` - Any environment variable where `VarName` is the environment variable name
[coloring]: /docs/config-colors
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -25,14 +25,7 @@ Show the current timestamp.
- time_format: `string` - format to use, follows the [golang standard][format] - defaults to `15:04:05`
[format]: https://yourbasic.org/golang/format-parse-string-time-date-example/
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below. Only used when a value is set, making the above properties obsolete.
example: `{{ now | date \"January 02, 2006 15:04:05 PM\" | lower }}`
## Template Properties
## [Template][templates] Properties
- `.CurrentDate`: `time` - The time to display(testing purpose)
@ -72,5 +65,5 @@ Show the current timestamp.
- StampMicro = "Jan _2 15:04:05.000000"
- StampNano = "Jan _2 15:04:05.000000000"
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates
[format]: https://yourbasic.org/golang/format-parse-string-time-date-example/

View file

@ -39,10 +39,8 @@ The free tier for is sufficient. You'll find the API key in your profile setting
works if you can curl it yourself and a result. - defaults to ``
- http_timeout: `int` - The default timeout for http request is 20ms. If no segment is shown, try increasing this timeout.
- cache_timeout: `int` - The default timeout for request caching is 10m. A value of 0 disables the cache.
- template: `string` - A go [text/template][go-text-template] template extended with [sprig][sprig] utilizing the
properties below - defaults to `{{ secondsRound .CummulativeTotal.Seconds }}`
## Template Properties
## [Template][templates] Properties
- `.CummulativeTotal`: `wtTotals` - object holding total tracked time values
@ -53,5 +51,4 @@ properties below - defaults to `{{ secondsRound .CummulativeTotal.Seconds }}`
[wt]: https://wakatime.com
[wk-summaries]: https://wakatime.com/developers#summaries
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -30,12 +30,7 @@ Currently only supports Windows and WSL. Pull requests for Darwin and Linux supp
}
```
## Properties
- template: `string` - A go [text/template][go-text-template] extended with [sprig][sprig] using the properties below.
Defaults to `{{ if .Error }}{{ .Error }}{{ else }}\uFAA8 {{ .SSID }} {{ .Signal }}% {{ .ReceiveRate }}Mbps{{ end }}`
## Template Properties
## [Template][templates] Properties
- `.SSID`: `string` - the SSID of the current wifi network
- `.RadioType`: `string` - the radio type - _e.g. 802.11ac, 802.11ax, 802.11n, etc._
@ -45,5 +40,4 @@ Defaults to `{{ if .Error }}{{ .Error }}{{ else }}\uFAA8 {{ .SSID }} {{ .Signal
- `.TransmitRate`: `int` - the transmit rate (Mbps)
- `.Signal`: `int` - the signal strength (%)
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -37,12 +37,9 @@ Supported registry key types:
- path: `string` - registry path to the desired key using backslashes and with a valid root HKEY name.
Ending path with \ will get the (Default) key from that path.
- fallback: `string` - the value to fall back to if no entry is found
- template: `string` - a go [text/template][go-text-template] template extended
with [sprig][sprig] utilizing the properties below.
## Template Properties
## [Template][templates] Properties
- .Value: `string` - The result of your query, or fallback if not found.
[go-text-template]: https://golang.org/pkg/text/template/
[sprig]: https://masterminds.github.io/sprig/
[templates]: /docs/config-text#templates

View file

@ -26,8 +26,7 @@ Remote Control password.
"prefix": "\uF16A ",
"playing_icon": "\uE602 ",
"paused_icon": "\uF8E3 ",
"stopped_icon": "\uF04D ",
"track_separator" : " - "
"stopped_icon": "\uF04D "
}
}
```
@ -37,5 +36,15 @@ Remote Control password.
- playing_icon: `string` - text/icon to show when playing - defaults to `\uE602 `
- paused_icon: `string` - text/icon to show when paused - defaults to `\uF8E3 `
- stopped_icon: `string` - text/icon to show when paused - defaults to `\uF04D `
- track_separator: `string` - text/icon to put between the artist and song name - defaults to ` - `
- api_url: `string` - the YTMDA Remote Control API URL- defaults to `http://127.0.0.1:9863`
## [Template][templates] Properties
- `.Status`: `string` - player status (`playing`, `paused`, `stopped`)
- `.Artist`: `string` - current artist
- `.Track`: `string` - current track
- `.Icon`: `string` - icon (based on `.Status`)
[templates]: /docs/config-text#templates
[templates]: /docs/config-text#templates

View file

@ -25,7 +25,7 @@ module.exports = {
"config-sample",
"config-title",
"config-colors",
"config-text-style",
"config-text",
"config-transient",
"config-tooltips",
"config-fonts"

View file

@ -558,6 +558,7 @@ func (env *environment) templateCache() *templateCache {
Root: env.isRunningAsRoot(),
Shell: env.getShellName(),
Code: env.lastErrorCode(),
WSL: env.isWsl(),
}
tmplCache.Env = make(map[string]string)
const separator = "="

View file

@ -10,8 +10,12 @@ type angular struct {
}
func (a *angular) string() string {
segmentTemplate := a.language.props.getString(SegmentTemplate, "")
if len(segmentTemplate) == 0 {
return a.language.string()
}
return a.language.renderTemplate(segmentTemplate, a)
}
func (a *angular) init(props Properties, env Environment) {
a.language = language{

View file

@ -5,8 +5,12 @@ type azfunc struct {
}
func (az *azfunc) string() string {
segmentTemplate := az.language.props.getString(SegmentTemplate, "")
if len(segmentTemplate) == 0 {
return az.language.string()
}
return az.language.renderTemplate(segmentTemplate, az)
}
func (az *azfunc) init(props Properties, env Environment) {
az.language = language{

View file

@ -5,7 +5,8 @@ import "strings"
type command struct {
props Properties
env Environment
value string
Output string
}
const (
@ -24,9 +25,9 @@ func (c *command) enabled() bool {
if strings.Contains(command, "||") {
commands := strings.Split(command, "||")
for _, cmd := range commands {
output := c.env.runShellCommand(shell, cmd)
output := c.env.runShellCommand(shell, strings.TrimSpace(cmd))
if output != "" {
c.value = output
c.Output = output
return true
}
}
@ -35,17 +36,27 @@ func (c *command) enabled() bool {
var output string
commands := strings.Split(command, "&&")
for _, cmd := range commands {
output += c.env.runShellCommand(shell, cmd)
output += c.env.runShellCommand(shell, strings.TrimSpace(cmd))
}
c.value = output
return c.value != ""
c.Output = output
return c.Output != ""
}
c.value = c.env.runShellCommand(shell, command)
return c.value != ""
c.Output = c.env.runShellCommand(shell, strings.TrimSpace(command))
return c.Output != ""
}
func (c *command) string() string {
return c.value
segmentTemplate := c.props.getString(SegmentTemplate, "{{.Output}}")
template := &textTemplate{
Template: segmentTemplate,
Context: c,
Env: c.env,
}
text, err := template.render()
if err != nil {
return err.Error()
}
return text
}
func (c *command) init(props Properties, env Environment) {

View file

@ -1,5 +1,3 @@
//go:build !windows
package main
import (
@ -9,11 +7,10 @@ import (
)
func TestExecuteCommand(t *testing.T) {
env := &environment{}
debug := false
env.init(&args{
Debug: &debug,
})
env := new(MockedEnvironment)
env.On("hasCommand", "bash").Return(true)
env.On("runShellCommand", "bash", "echo hello").Return("hello")
env.onTemplate()
props := properties{
Command: "echo hello",
}
@ -27,11 +24,12 @@ func TestExecuteCommand(t *testing.T) {
}
func TestExecuteMultipleCommandsOrFirst(t *testing.T) {
env := &environment{}
debug := false
env.init(&args{
Debug: &debug,
})
env := new(MockedEnvironment)
env.On("hasCommand", "bash").Return(true)
env.On("runShellCommand", "bash", "exit 1").Return("")
env.On("runShellCommand", "bash", "echo hello").Return("hello")
env.On("runShellCommand", "bash", "exit 1 || echo hello").Return("hello")
env.onTemplate()
props := properties{
Command: "exit 1 || echo hello",
}
@ -45,11 +43,11 @@ func TestExecuteMultipleCommandsOrFirst(t *testing.T) {
}
func TestExecuteMultipleCommandsOrSecond(t *testing.T) {
env := &environment{}
debug := false
env.init(&args{
Debug: &debug,
})
env := new(MockedEnvironment)
env.On("hasCommand", "bash").Return(true)
env.On("runShellCommand", "bash", "echo hello").Return("hello")
env.On("runShellCommand", "bash", "echo world").Return("world")
env.onTemplate()
props := properties{
Command: "echo hello || echo world",
}
@ -63,11 +61,11 @@ func TestExecuteMultipleCommandsOrSecond(t *testing.T) {
}
func TestExecuteMultipleCommandsAnd(t *testing.T) {
env := &environment{}
debug := false
env.init(&args{
Debug: &debug,
})
env := new(MockedEnvironment)
env.On("hasCommand", "bash").Return(true)
env.On("runShellCommand", "bash", "echo hello").Return("hello")
env.On("runShellCommand", "bash", "echo world").Return("world")
env.onTemplate()
props := properties{
Command: "echo hello && echo world",
}
@ -81,11 +79,10 @@ func TestExecuteMultipleCommandsAnd(t *testing.T) {
}
func TestExecuteSingleCommandEmpty(t *testing.T) {
env := &environment{}
debug := false
env.init(&args{
Debug: &debug,
})
env := new(MockedEnvironment)
env.On("hasCommand", "bash").Return(true)
env.On("runShellCommand", "bash", "").Return("")
env.onTemplate()
props := properties{
Command: "",
}
@ -98,11 +95,10 @@ func TestExecuteSingleCommandEmpty(t *testing.T) {
}
func TestExecuteSingleCommandNoCommandProperty(t *testing.T) {
env := &environment{}
debug := false
env.init(&args{
Debug: &debug,
})
env := new(MockedEnvironment)
env.On("hasCommand", "bash").Return(true)
env.On("runShellCommand", "bash", "echo no command specified").Return("no command specified")
env.onTemplate()
var props properties
c := &command{
props: props,
@ -110,15 +106,14 @@ func TestExecuteSingleCommandNoCommandProperty(t *testing.T) {
}
enabled := c.enabled()
assert.True(t, enabled)
assert.Equal(t, "no command specified", c.value)
assert.Equal(t, "no command specified", c.Output)
}
func TestExecuteMultipleCommandsAndDisabled(t *testing.T) {
env := &environment{}
debug := false
env.init(&args{
Debug: &debug,
})
env := new(MockedEnvironment)
env.On("hasCommand", "bash").Return(true)
env.On("runShellCommand", "bash", "echo").Return("")
env.onTemplate()
props := properties{
Command: "echo && echo",
}
@ -131,11 +126,11 @@ func TestExecuteMultipleCommandsAndDisabled(t *testing.T) {
}
func TestExecuteMultipleCommandsOrDisabled(t *testing.T) {
env := &environment{}
debug := false
env.init(&args{
Debug: &debug,
})
env := new(MockedEnvironment)
env.On("hasCommand", "bash").Return(true)
env.On("runShellCommand", "bash", "echo").Return("")
env.On("runShellCommand", "bash", "echo|| echo").Return("")
env.onTemplate()
props := properties{
Command: "echo|| echo",
}

View file

@ -5,8 +5,12 @@ type crystal struct {
}
func (c *crystal) string() string {
segmentTemplate := c.language.props.getString(SegmentTemplate, "")
if len(segmentTemplate) == 0 {
return c.language.string()
}
return c.language.renderTemplate(segmentTemplate, c)
}
func (c *crystal) init(props Properties, env Environment) {
c.language = language{

View file

@ -5,8 +5,12 @@ type dart struct {
}
func (d *dart) string() string {
segmentTemplate := d.language.props.getString(SegmentTemplate, "")
if len(segmentTemplate) == 0 {
return d.language.string()
}
return d.language.renderTemplate(segmentTemplate, d)
}
func (d *dart) init(props Properties, env Environment) {
d.language = language{

View file

@ -181,13 +181,14 @@ const (
func (e *exit) deprecatedString() string {
colorBackground := e.props.getBool(ColorBackground, false)
if e.code != 0 && !colorBackground {
code := e.env.lastErrorCode()
if code != 0 && !colorBackground {
e.props.set(ForegroundOverride, e.props.getColor(ErrorColor, e.props.getColor(ForegroundOverride, "")))
}
if e.code != 0 && colorBackground {
if code != 0 && colorBackground {
e.props.set(BackgroundOverride, e.props.getColor(ErrorColor, e.props.getColor(BackgroundOverride, "")))
}
if e.code == 0 {
if code == 0 {
return e.props.getString(SuccessIcon, "")
}
errorIcon := e.props.getString(ErrorIcon, "")
@ -195,7 +196,7 @@ func (e *exit) deprecatedString() string {
return errorIcon
}
if e.props.getBool(AlwaysNumeric, false) {
return fmt.Sprintf("%s%d", errorIcon, e.code)
return fmt.Sprintf("%s%d", errorIcon, code)
}
return fmt.Sprintf("%s%s", errorIcon, e.Text)
}
@ -297,7 +298,7 @@ func (s *session) legacyEnabled() bool {
return true
}
func (s *session) getFormattedText() string {
func (s *session) legacyString() string {
separator := ""
if s.props.getBool(DisplayHost, true) && s.props.getBool(DisplayUser, true) {
separator = s.props.getString(UserInfoSeparator, "@")
@ -336,17 +337,9 @@ func (l *language) string() string {
if !l.props.getOneOfBool(FetchVersion, DisplayVersion, true) {
return ""
}
err := l.setVersion()
if err != nil {
l.Error = err.Error()
}
displayError := l.props.getBool(DisplayError, true)
if err != nil && displayError {
return err.Error()
}
if err != nil {
return ""
if len(l.Error) != 0 && displayError {
return l.Error
}
segmentTemplate := l.props.getString(SegmentTemplate, "{{ .Full }}")
@ -458,3 +451,11 @@ func (e *envvar) init(props Properties, env Environment) {
e.props = props
e.env = env
}
// Dotnet
const (
// UnsupportedDotnetVersionIcon is displayed when the dotnet version in
// the current folder isn't supported by the installed dotnet SDK set.
UnsupportedDotnetVersionIcon Property = "unsupported_version_icon"
)

View file

@ -2,6 +2,7 @@ package main
import (
"errors"
"fmt"
"testing"
"github.com/distatus/battery"
@ -271,18 +272,26 @@ func TestStatusColorsWithoutDisplayStatus(t *testing.T) {
status := "## main...origin/main [ahead 33]\n M myfile"
env := new(MockedEnvironment)
env.On("isWsl").Return(false)
env.On("inWSLSharedDrive").Return(false)
env.On("getRuntimeGOOS").Return("unix")
env.On("hasFolder", "/rebase-merge").Return(false)
env.On("hasFolder", "/rebase-apply").Return(false)
env.On("hasFolder", "/sequencer").Return(false)
env.On("getFileContent", "/HEAD").Return(status)
env.On("hasFilesInDir", "", "CHERRY_PICK_HEAD").Return(false)
env.On("hasFilesInDir", "", "REVERT_HEAD").Return(false)
env.On("hasFilesInDir", "", "MERGE_MSG").Return(false)
env.On("hasFilesInDir", "", "MERGE_HEAD").Return(false)
env.On("hasFilesInDir", "", "sequencer/todo").Return(false)
env.mockGitCommand("", "describe", "--tags", "--exact-match")
env.mockGitCommand(status, "status", "-unormal", "--branch", "--porcelain=2")
env.On("hasCommand", "git").Return(true)
fileInfo := &fileInfo{
path: "/dir/hello",
parentFolder: "/dir",
isDir: true,
}
env.On("hasParentFilePath", ".git").Return(fileInfo, nil)
env.On("getFileContent", fmt.Sprintf("%s/HEAD", fileInfo.path)).Return("")
env.mockGitCommand(fileInfo.path, "", "describe", "--tags", "--exact-match")
env.mockGitCommand(fileInfo.path, status, "status", "-unormal", "--branch", "--porcelain=2")
env.On("hasFolder", fmt.Sprintf("%s/rebase-merge", fileInfo.path)).Return(false)
env.On("hasFolder", fmt.Sprintf("%s/rebase-apply", fileInfo.path)).Return(false)
env.On("hasFilesInDir", fileInfo.path, "CHERRY_PICK_HEAD").Return(false)
env.On("hasFilesInDir", fileInfo.path, "REVERT_HEAD").Return(false)
env.On("hasFilesInDir", fileInfo.path, "MERGE_MSG").Return(false)
env.On("hasFilesInDir", fileInfo.path, "MERGE_HEAD").Return(false)
env.On("hasFilesInDir", fileInfo.path, "sequencer/todo").Return(false)
props := properties{
DisplayStatus: false,
StatusColorsEnabled: true,
@ -297,6 +306,7 @@ func TestStatusColorsWithoutDisplayStatus(t *testing.T) {
}
g.Working = &GitStatus{}
g.Staging = &GitStatus{}
_ = g.enabled()
g.string()
assert.Equal(t, expected, g.props.getColor(BackgroundOverride, ""))
}
@ -335,7 +345,8 @@ func TestExitWriterDeprecatedString(t *testing.T) {
env: env,
props: props,
}
assert.Equal(t, tc.Expected, e.string())
_ = e.enabled()
assert.Equal(t, tc.Expected, e.deprecatedString())
}
}

View file

@ -2,23 +2,19 @@ package main
type dotnet struct {
language
}
const (
// UnsupportedDotnetVersionIcon is displayed when the dotnet version in
// the current folder isn't supported by the installed dotnet SDK set.
UnsupportedDotnetVersionIcon Property = "unsupported_version_icon"
)
Unsupported bool
}
func (d *dotnet) string() string {
version := d.language.string()
exitCode := d.language.exitCode
if exitCode == dotnetExitCode {
segmentTemplate := d.language.props.getString(SegmentTemplate, "")
if len(segmentTemplate) != 0 {
return d.language.renderTemplate(segmentTemplate, d)
}
if d.Unsupported {
return d.language.props.getString(UnsupportedDotnetVersionIcon, "\uf071 ")
}
return version
return d.language.string()
}
func (d *dotnet) init(props Properties, env Environment) {
@ -39,5 +35,10 @@ func (d *dotnet) init(props Properties, env Environment) {
}
func (d *dotnet) enabled() bool {
return d.language.enabled()
enabled := d.language.enabled()
if !enabled {
return false
}
d.Unsupported = d.language.exitCode == dotnetExitCode
return true
}

View file

@ -60,7 +60,17 @@ func (t *executiontime) enabled() bool {
}
func (t *executiontime) string() string {
return t.FormattedMs
segmentTemplate := t.props.getString(SegmentTemplate, "{{.FormattedMs}}")
template := &textTemplate{
Template: segmentTemplate,
Context: t,
Env: t.env,
}
text, err := template.render()
if err != nil {
return err.Error()
}
return text
}
func (t *executiontime) init(props Properties, env Environment) {

View file

@ -6,11 +6,11 @@ type exit struct {
props Properties
env Environment
code int
Text string
}
func (e *exit) enabled() bool {
e.Text = e.getMeaningFromExitCode(e.env.lastErrorCode())
if e.props.getBool(AlwaysEnabled, false) {
return true
}
@ -18,17 +18,6 @@ func (e *exit) enabled() bool {
}
func (e *exit) string() string {
return e.getFormattedText()
}
func (e *exit) init(props Properties, env Environment) {
e.props = props
e.env = env
}
func (e *exit) getFormattedText() string {
e.code = e.env.lastErrorCode()
e.Text = e.getMeaningFromExitCode()
segmentTemplate := e.props.getString(SegmentTemplate, "")
if len(segmentTemplate) == 0 {
return e.deprecatedString()
@ -45,8 +34,13 @@ func (e *exit) getFormattedText() string {
return text
}
func (e *exit) getMeaningFromExitCode() string {
switch e.code {
func (e *exit) init(props Properties, env Environment) {
e.props = props
e.env = env
}
func (e *exit) getMeaningFromExitCode(code int) string {
switch code {
case 1:
return "ERROR"
case 2:
@ -100,6 +94,6 @@ func (e *exit) getMeaningFromExitCode() string {
case 128 + 22:
return "SIGTTOU"
default:
return strconv.Itoa(e.code)
return strconv.Itoa(code)
}
}

View file

@ -59,8 +59,7 @@ func TestGetMeaningFromExitCode(t *testing.T) {
errorMap[7000] = "7000"
for exitcode, want := range errorMap {
e := &exit{}
e.code = exitcode
assert.Equal(t, want, e.getMeaningFromExitCode())
assert.Equal(t, want, e.getMeaningFromExitCode(exitcode))
}
}

View file

@ -105,6 +105,35 @@ const (
)
func (g *git) enabled() bool {
if !g.shouldDisplay() {
return false
}
statusColorsEnabled := g.props.getBool(StatusColorsEnabled, false)
displayStatus := g.props.getOneOfBool(FetchStatus, DisplayStatus, false)
if !displayStatus {
g.setPrettyHEADName()
}
if displayStatus || statusColorsEnabled {
g.setGitStatus()
g.setGitHEADContext()
g.setBranchStatus()
} else {
g.Working = &GitStatus{}
g.Staging = &GitStatus{}
}
if g.Upstream != "" && g.props.getOneOfBool(FetchUpstreamIcon, DisplayUpstreamIcon, false) {
g.UpstreamIcon = g.getUpstreamIcon()
}
if g.props.getOneOfBool(FetchStashCount, DisplayStashCount, false) {
g.StashCount = g.getStashContext()
}
if g.props.getOneOfBool(FetchWorktreeCount, DisplayWorktreeCount, false) {
g.WorktreeCount = g.getWorktreeContext()
}
return true
}
func (g *git) shouldDisplay() bool {
// when in wsl/wsl2 and in a windows shared folder
// we must use git.exe and convert paths accordingly
// for worktrees, stashes, and path to work
@ -162,36 +191,13 @@ func (g *git) enabled() bool {
}
func (g *git) string() string {
statusColorsEnabled := g.props.getBool(StatusColorsEnabled, false)
displayStatus := g.props.getOneOfBool(FetchStatus, DisplayStatus, false)
if !displayStatus {
g.setPrettyHEADName()
}
if displayStatus || statusColorsEnabled {
g.setGitStatus()
g.setGitHEADContext()
g.setBranchStatus()
} else {
g.Working = &GitStatus{}
g.Staging = &GitStatus{}
}
if g.Upstream != "" && g.props.getOneOfBool(FetchUpstreamIcon, DisplayUpstreamIcon, false) {
g.UpstreamIcon = g.getUpstreamIcon()
}
if g.props.getOneOfBool(FetchStashCount, DisplayStashCount, false) {
g.StashCount = g.getStashContext()
}
if g.props.getOneOfBool(FetchWorktreeCount, DisplayWorktreeCount, false) {
g.WorktreeCount = g.getWorktreeContext()
}
// use template if available
segmentTemplate := g.props.getString(SegmentTemplate, "")
if len(segmentTemplate) > 0 {
return g.templateString(segmentTemplate)
}
// legacy render string if no template
// remove this for 6.0
return g.deprecatedString(statusColorsEnabled)
return g.deprecatedString(g.props.getBool(StatusColorsEnabled, false))
}
func (g *git) templateString(segmentTemplate string) string {

View file

@ -29,16 +29,18 @@ func TestEnabledGitNotFound(t *testing.T) {
}
func TestEnabledInWorkingDirectory(t *testing.T) {
env := new(MockedEnvironment)
env.On("inWSLSharedDrive").Return(false)
env.On("hasCommand", "git").Return(true)
env.On("getRuntimeGOOS").Return("")
env.On("isWsl").Return(false)
fileInfo := &fileInfo{
path: "/dir/hello",
parentFolder: "/dir",
isDir: true,
}
env := new(MockedEnvironment)
env.On("inWSLSharedDrive").Return(false)
env.On("hasCommand", "git").Return(true)
env.On("getRuntimeGOOS").Return("")
env.On("getFileContent", "/dir/hello/HEAD").Return("")
env.mockGitCommand(fileInfo.path, "", "describe", "--tags", "--exact-match")
env.On("isWsl").Return(false)
env.On("hasParentFilePath", ".git").Return(fileInfo, nil)
g := &git{
scm: scm{
@ -61,6 +63,8 @@ func TestEnabledInWorkingTree(t *testing.T) {
parentFolder: "/dev/folder_worktree",
isDir: false,
}
env.On("getFileContent", "/dev/real_folder/.git/worktrees/folder_worktree/HEAD").Return("")
env.mockGitCommand(fileInfo.parentFolder, "", "describe", "--tags", "--exact-match")
env.On("hasParentFilePath", ".git").Return(fileInfo, nil)
env.On("getFileContent", "/dev/folder_worktree/.git").Return("gitdir: /dev/real_folder/.git/worktrees/folder_worktree")
env.On("getFileContent", "/dev/real_folder/.git/worktrees/folder_worktree/gitdir").Return("/dev/folder_worktree.git\n")
@ -86,6 +90,8 @@ func TestEnabledInSubmodule(t *testing.T) {
parentFolder: "/dev/parent/test-submodule",
isDir: false,
}
env.On("getFileContent", "/dev/parent/test-submodule/../.git/modules/test-submodule/HEAD").Return("")
env.mockGitCommand("/dev/parent/test-submodule/../.git/modules/test-submodule", "", "describe", "--tags", "--exact-match")
env.On("hasParentFilePath", ".git").Return(fileInfo, nil)
env.On("getFileContent", "/dev/parent/test-submodule/.git").Return("gitdir: ../.git/modules/test-submodule")
env.On("getFileContent", "/dev/parent/.git/modules/test-submodule").Return("/dev/folder_worktree.git\n")
@ -119,8 +125,8 @@ func TestGetGitOutputForCommand(t *testing.T) {
assert.Equal(t, want, got)
}
func (m *MockedEnvironment) mockGitCommand(returnValue string, args ...string) {
args = append([]string{"-C", "", "--no-optional-locks", "-c", "core.quotepath=false", "-c", "color.status=false"}, args...)
func (m *MockedEnvironment) mockGitCommand(dir, returnValue string, args ...string) {
args = append([]string{"-C", dir, "--no-optional-locks", "-c", "core.quotepath=false", "-c", "color.status=false"}, args...)
m.On("runCommand", "git", args).Return(returnValue, nil)
}
@ -231,9 +237,9 @@ func TestSetGitHEADContextClean(t *testing.T) {
env.On("inWSLSharedDrive").Return(false)
env.On("getRuntimeGOOS").Return("unix")
env.On("isWsl").Return(false)
env.mockGitCommand("", "describe", "--tags", "--exact-match")
env.mockGitCommand(tc.Theirs, "name-rev", "--name-only", "--exclude=tags/*", tc.Theirs)
env.mockGitCommand(tc.Ours, "name-rev", "--name-only", "--exclude=tags/*", tc.Ours)
env.mockGitCommand("", "", "describe", "--tags", "--exact-match")
env.mockGitCommand("", tc.Theirs, "name-rev", "--name-only", "--exclude=tags/*", tc.Theirs)
env.mockGitCommand("", tc.Ours, "name-rev", "--name-only", "--exclude=tags/*", tc.Ours)
// rebase merge
env.On("hasFolder", "/rebase-merge").Return(tc.RebaseMerge)
env.On("getFileContent", "/rebase-merge/head-name").Return(tc.Ours)
@ -299,7 +305,7 @@ func TestSetPrettyHEADName(t *testing.T) {
env.On("getFileContent", "/HEAD").Return(tc.HEAD)
env.On("getRuntimeGOOS").Return("unix")
env.On("isWsl").Return(false)
env.mockGitCommand(tc.Tag, "describe", "--tags", "--exact-match")
env.mockGitCommand("", tc.Tag, "describe", "--tags", "--exact-match")
g := &git{
scm: scm{
env: env,
@ -416,7 +422,7 @@ func TestSetGitStatus(t *testing.T) {
env := new(MockedEnvironment)
env.On("getRuntimeGOOS").Return("unix")
env.On("isWsl").Return(false)
env.mockGitCommand(strings.ReplaceAll(tc.Output, "\t", ""), "status", "-unormal", "--branch", "--porcelain=2")
env.mockGitCommand("", strings.ReplaceAll(tc.Output, "\t", ""), "status", "-unormal", "--branch", "--porcelain=2")
g := &git{
scm: scm{
env: env,

View file

@ -13,8 +13,12 @@ const (
)
func (g *golang) string() string {
segmentTemplate := g.language.props.getString(SegmentTemplate, "")
if len(segmentTemplate) == 0 {
return g.language.string()
}
return g.language.renderTemplate(segmentTemplate, g)
}
func (g *golang) init(props Properties, env Environment) {
g.language = language{

View file

@ -7,8 +7,12 @@ type java struct {
}
func (j *java) string() string {
segmentTemplate := j.language.props.getString(SegmentTemplate, "")
if len(segmentTemplate) == 0 {
return j.language.string()
}
return j.language.renderTemplate(segmentTemplate, j)
}
func (j *java) init(props Properties, env Environment) {
javaRegex := `(?: JRE)(?: \(.*\))? \((?P<version>(?P<major>[0-9]+)(?:\.(?P<minor>[0-9]+))?(?:\.(?P<patch>[0-9]+))?).*\),`

View file

@ -5,8 +5,12 @@ type julia struct {
}
func (j *julia) string() string {
segmentTemplate := j.language.props.getString(SegmentTemplate, "")
if len(segmentTemplate) == 0 {
return j.language.string()
}
return j.language.renderTemplate(segmentTemplate, j)
}
func (j *julia) init(props Properties, env Environment) {
j.language = language{

View file

@ -84,13 +84,6 @@ const (
)
func (l *language) renderTemplate(segmentTemplate string, context SegmentWriter) string {
if l.props.getBool(FetchVersion, true) {
err := l.setVersion()
if err != nil {
l.Error = err.Error()
}
}
template := &textTemplate{
Template: segmentTemplate,
Context: context,
@ -101,6 +94,7 @@ func (l *language) renderTemplate(segmentTemplate string, context SegmentWriter)
return err.Error()
}
// TODO: this needs to be removed or refactored
if !l.props.getBool(EnableHyperlink, false) {
return text
}
@ -124,14 +118,14 @@ func (l *language) renderTemplate(segmentTemplate string, context SegmentWriter)
func (l *language) enabled() bool {
// override default extensions if needed
l.extensions = l.props.getStringArray(LanguageExtensions, l.extensions)
inHomeDir := func() bool {
return l.env.pwd() == l.env.homeDir()
}
var enabled bool
homeEnabled := l.props.getBool(HomeEnabled, l.homeEnabled)
if inHomeDir() && !homeEnabled {
return false
}
enabled = false
} else {
// set default mode when not set
if len(l.displayMode) == 0 {
l.displayMode = l.props.getString(DisplayMode, DisplayModeFiles)
@ -139,17 +133,26 @@ func (l *language) enabled() bool {
l.loadLanguageContext()
switch l.displayMode {
case DisplayModeAlways:
return true
enabled = true
case DisplayModeEnvironment:
return l.inLanguageContext()
enabled = l.inLanguageContext()
case DisplayModeFiles:
return l.hasLanguageFiles()
enabled = l.hasLanguageFiles()
case DisplayModeContext:
fallthrough
default:
return l.hasLanguageFiles() || l.inLanguageContext()
enabled = l.hasLanguageFiles() || l.inLanguageContext()
}
}
if !enabled || !l.props.getOneOfBool(FetchVersion, DisplayVersion, true) {
return enabled
}
err := l.setVersion()
if err != nil {
l.Error = err.Error()
}
return enabled
}
// hasLanguageFiles will return true at least one file matching the extensions is found
func (l *language) hasLanguageFiles() bool {

View file

@ -1,14 +1,10 @@
package main
import (
"fmt"
)
type osInfo struct {
props Properties
env Environment
os string
Icon string
}
const (
@ -18,10 +14,6 @@ const (
Linux Property = "linux"
// Windows the string/icon to use for windows
Windows Property = "windows"
// WSL the string/icon to use for WSL
WSL Property = "wsl"
// WSLSeparator shows between WSL and Linux properties when WSL is detected
WSLSeparator Property = "wsl_separator"
// Alpine the string/icon to use for Alpine
Alpine Property = "alpine"
// Aosc the string/icon to use for Aosc
@ -65,41 +57,41 @@ const (
)
func (n *osInfo) enabled() bool {
goos := n.env.getRuntimeGOOS()
switch goos {
case windowsPlatform:
n.Icon = n.props.getString(Windows, "\uE62A")
case darwinPlatform:
n.Icon = n.props.getString(MacOS, "\uF179")
case linuxPlatform:
platform := n.env.getPlatform()
displayDistroName := n.props.getBool(DisplayDistroName, false)
if displayDistroName {
n.Icon = platform
break
}
n.Icon = n.getDistroIcon(platform)
default:
n.Icon = goos
}
return true
}
func (n *osInfo) string() string {
goos := n.env.getRuntimeGOOS()
switch goos {
case windowsPlatform:
n.os = windowsPlatform
return n.props.getString(Windows, "\uE62A")
case darwinPlatform:
n.os = darwinPlatform
return n.props.getString(MacOS, "\uF179")
case linuxPlatform:
n.os = n.env.getPlatform()
if !n.env.isWsl() {
return n.getDistroName(n.os, "")
segmentTemplate := n.props.getString(SegmentTemplate, "{{ if .WSL }}WSL at {{ end }}{{.Icon}}")
template := &textTemplate{
Template: segmentTemplate,
Context: n,
Env: n.env,
}
return fmt.Sprintf("%s%s%s",
n.props.getString(WSL, "WSL"),
n.props.getString(WSLSeparator, " - "),
n.getDistroName(n.os, n.os))
default:
n.os = goos
return goos
text, err := template.render()
if err != nil {
return err.Error()
}
return text
}
func (n *osInfo) getDistroName(distro, defaultName string) string {
displayDistroName := n.props.getBool(DisplayDistroName, false)
if displayDistroName && len(defaultName) > 0 {
return defaultName
}
if displayDistroName {
return distro
}
func (n *osInfo) getDistroIcon(distro string) string {
switch distro {
case "alpine":
return n.props.getString(Alpine, "\uF300")

View file

@ -62,23 +62,20 @@ func TestOSInfo(t *testing.T) {
for _, tc := range cases {
env := new(MockedEnvironment)
env.On("getRuntimeGOOS").Return(tc.GOOS)
env.On("isWsl").Return(tc.IsWSL)
env.On("getPlatform").Return(tc.Platform)
env.On("templateCache").Return(&templateCache{
Env: make(map[string]string),
WSL: tc.IsWSL,
})
osInfo := &osInfo{
env: env,
props: properties{
WSL: "WSL",
WSLSeparator: " at ",
DisplayDistroName: tc.DisplayDistroName,
Windows: "windows",
MacOS: "darwin",
},
}
_ = osInfo.enabled()
assert.Equal(t, tc.ExpectedString, osInfo.string(), tc.Case)
if tc.Platform != "" {
assert.Equal(t, tc.Platform, osInfo.os, tc.Case)
} else {
assert.Equal(t, tc.GOOS, osInfo.os, tc.Case)
}
}
}

View file

@ -51,17 +51,6 @@ func (d *owm) enabled() bool {
}
func (d *owm) string() string {
d.UnitIcon = "\ue33e"
switch d.units {
case "imperial":
d.UnitIcon = "°F" // \ue341"
case "metric":
d.UnitIcon = "°C" // \ue339"
case "":
fallthrough
case "standard":
d.UnitIcon = "°K" // \ufa05"
}
segmentTemplate := d.props.getString(SegmentTemplate, "{{.Weather}} ({{.Temperature}}{{.UnitIcon}})")
template := &textTemplate{
Template: segmentTemplate,
@ -72,7 +61,6 @@ func (d *owm) string() string {
if err != nil {
return err.Error()
}
return text
}
@ -118,7 +106,6 @@ func (d *owm) getResult() (*owmDataResponse, error) {
func (d *owm) setStatus() error {
units := d.props.getString(Units, "standard")
q, err := d.getResult()
if err != nil {
return err
@ -170,6 +157,17 @@ func (d *owm) setStatus() error {
}
d.Weather = icon
d.units = units
d.UnitIcon = "\ue33e"
switch d.units {
case "imperial":
d.UnitIcon = "°F" // \ue341"
case "metric":
d.UnitIcon = "°C" // \ue339"
case "":
fallthrough
case "standard":
d.UnitIcon = "°K" // \ufa05"
}
return nil
}

View file

@ -54,10 +54,6 @@ const (
)
func (pt *path) enabled() bool {
return true
}
func (pt *path) string() string {
pt.pwd = pt.env.pwd()
switch style := pt.props.getString(Style, Agnoster); style {
case Agnoster:
@ -80,7 +76,7 @@ func (pt *path) string() string {
case Folder:
pt.Path = pt.getFolderPath()
default:
return fmt.Sprintf("Path style: %s is not available", style)
pt.Path = fmt.Sprintf("Path style: %s is not available", style)
}
pt.Path = pt.formatWindowsDrive(pt.Path)
if pt.props.getBool(EnableHyperlink, false) {
@ -92,6 +88,10 @@ func (pt *path) string() string {
}
pt.StackCount = pt.env.stackCount()
return true
}
func (pt *path) string() string {
segmentTemplate := pt.props.getString(SegmentTemplate, "{{ .Path }}")
template := &textTemplate{
Template: segmentTemplate,

View file

@ -443,6 +443,7 @@ func TestAgnosterPathStyles(t *testing.T) {
SegmentTemplate: "{{ .Path }}",
},
}
_ = path.enabled()
got := path.string()
assert.Equal(t, tc.Expected, got)
}
@ -572,6 +573,7 @@ func TestGetFullPath(t *testing.T) {
env: env,
props: props,
}
_ = path.enabled()
got := path.string()
assert.Equal(t, tc.Expected, got)
}

View file

@ -4,12 +4,16 @@ type php struct {
language
}
func (n *php) string() string {
return n.language.string()
func (p *php) string() string {
segmentTemplate := p.language.props.getString(SegmentTemplate, "")
if len(segmentTemplate) == 0 {
return p.language.string()
}
return p.language.renderTemplate(segmentTemplate, p)
}
func (n *php) init(props Properties, env Environment) {
n.language = language{
func (p *php) init(props Properties, env Environment) {
p.language = language{
env: env,
props: props,
extensions: []string{"*.php", "composer.json", "composer.lock", ".php-version"},
@ -24,6 +28,6 @@ func (n *php) init(props Properties, env Environment) {
}
}
func (n *php) enabled() bool {
return n.language.enabled()
func (p *php) enabled() bool {
return p.language.enabled()
}

View file

@ -50,34 +50,20 @@ func (p *plastic) enabled() bool {
if p.shouldIgnoreRootRepository(wkdir.parentFolder) {
return false
}
if wkdir.isDir {
p.plasticWorkspaceFolder = wkdir.parentFolder
return true
}
if !wkdir.isDir {
return false
}
func (p *plastic) string() string {
p.plasticWorkspaceFolder = wkdir.parentFolder
displayStatus := p.props.getOneOfBool(FetchStatus, DisplayStatus, false)
p.setSelector()
if displayStatus {
p.setPlasticStatus()
}
// use template if available
segmentTemplate := p.props.getString(SegmentTemplate, "")
if len(segmentTemplate) > 0 {
return p.templateString(segmentTemplate)
return true
}
// default: only selector is returned
return p.Selector
}
func (p *plastic) templateString(segmentTemplate string) string {
func (p *plastic) string() string {
segmentTemplate := p.props.getString(SegmentTemplate, "{{ .Selector }}")
template := &textTemplate{
Template: segmentTemplate,
Context: p,

View file

@ -25,6 +25,7 @@ func TestPlasticEnabledInWorkspaceDirectory(t *testing.T) {
env.On("hasCommand", "cm").Return(true)
env.On("getRuntimeGOOS").Return("")
env.On("isWsl").Return(false)
env.On("getFileContent", "/dir/.plastic//plastic.selector").Return("")
fileInfo := &fileInfo{
path: "/dir/hello",
parentFolder: "/dir",
@ -288,7 +289,7 @@ func TestPlasticTemplateString(t *testing.T) {
Plastic *plastic
}{
{
Case: "Only Selector name",
Case: "Default template",
Expected: "/main",
Template: "{{ .Selector }}",
Plastic: &plastic{
@ -326,11 +327,12 @@ func TestPlasticTemplateString(t *testing.T) {
for _, tc := range cases {
props := properties{
FetchStatus: true,
SegmentTemplate: tc.Template,
}
tc.Plastic.props = props
env := new(MockedEnvironment)
env.onTemplate()
tc.Plastic.env = env
assert.Equal(t, tc.Expected, tc.Plastic.templateString(tc.Template), tc.Case)
assert.Equal(t, tc.Expected, tc.Plastic.string(), tc.Case)
}
}

View file

@ -5,7 +5,8 @@ import "strings"
type poshgit struct {
props Properties
env Environment
gitStatus string
Status string
}
const (
@ -14,12 +15,22 @@ const (
func (p *poshgit) enabled() bool {
status := p.env.getenv(poshGitEnv)
p.gitStatus = strings.TrimSpace(status)
return p.gitStatus != ""
p.Status = strings.TrimSpace(status)
return p.Status != ""
}
func (p *poshgit) string() string {
return p.gitStatus
segmentTemplate := p.props.getString(SegmentTemplate, "{{ .Status }}")
template := &textTemplate{
Template: segmentTemplate,
Context: p,
Env: p.env,
}
text, err := template.render()
if err != nil {
return err.Error()
}
return text
}
func (p *poshgit) init(props Properties, env Environment) {

View file

@ -20,9 +20,11 @@ func TestPoshGitSegment(t *testing.T) {
for _, tc := range cases {
env := new(MockedEnvironment)
env.onTemplate()
env.On("getenv", poshGitEnv).Return(tc.PoshGitPrompt)
p := &poshgit{
env: env,
props: &properties{},
}
assert.Equal(t, tc.Enabled, p.enabled())
if tc.Enabled {

View file

@ -5,17 +5,22 @@ type root struct {
env Environment
}
const (
// RootIcon indicates the root user
RootIcon Property = "root_icon"
)
func (rt *root) enabled() bool {
return rt.env.isRunningAsRoot()
}
func (rt *root) string() string {
return rt.props.getString(RootIcon, "\uF0E7")
segmentTemplate := rt.props.getString(SegmentTemplate, "\uF0E7")
template := &textTemplate{
Template: segmentTemplate,
Context: rt,
Env: rt.env,
}
text, err := template.render()
if err != nil {
return err.Error()
}
return text
}
func (rt *root) init(props Properties, env Environment) {

View file

@ -5,6 +5,8 @@ type ruby struct {
}
func (r *ruby) string() string {
segmentTemplate := r.language.props.getString(SegmentTemplate, "")
if len(segmentTemplate) == 0 {
version := r.language.string()
// asdf default non-set version
if version == "______" {
@ -12,6 +14,8 @@ func (r *ruby) string() string {
}
return version
}
return r.language.renderTemplate(segmentTemplate, r)
}
func (r *ruby) init(props Properties, env Environment) {
r.language = language{

View file

@ -5,8 +5,12 @@ type rust struct {
}
func (r *rust) string() string {
segmentTemplate := r.language.props.getString(SegmentTemplate, "")
if len(segmentTemplate) == 0 {
return r.language.string()
}
return r.language.renderTemplate(segmentTemplate, r)
}
func (r *rust) init(props Properties, env Environment) {
r.language = language{

View file

@ -5,7 +5,7 @@ import "strings"
type session struct {
props Properties
env Environment
text string
// text string
userName string
hostName string
@ -21,24 +21,24 @@ func (s *session) enabled() bool {
if segmentTemplate == "" {
return s.legacyEnabled()
}
return true
}
func (s *session) string() string {
segmentTemplate := s.props.getString(SegmentTemplate, "")
if segmentTemplate == "" {
return s.legacyString()
}
template := &textTemplate{
Template: segmentTemplate,
Context: s,
Env: s.env,
}
var err error
s.text, err = template.render()
text, err := template.render()
if err != nil {
s.text = err.Error()
text = err.Error()
}
return len(s.text) > 0
}
func (s *session) string() string {
if len(s.text) != 0 {
return s.text
}
return s.getFormattedText()
return text
}
func (s *session) init(props Properties, env Environment) {

View file

@ -9,7 +9,6 @@ import (
func TestSessionSegmentTemplate(t *testing.T) {
cases := []struct {
Case string
ExpectedEnabled bool
ExpectedString string
UserName string
DefaultUserName string
@ -24,14 +23,12 @@ func TestSessionSegmentTemplate(t *testing.T) {
ComputerName: "company-laptop",
UserName: "john",
Template: "{{.UserName}}@{{.HostName}}",
ExpectedEnabled: true,
},
{
Case: "user only",
ExpectedString: "john",
UserName: "john",
Template: "{{.UserName}}",
ExpectedEnabled: true,
},
{
Case: "user with ssh",
@ -40,7 +37,6 @@ func TestSessionSegmentTemplate(t *testing.T) {
SSHSession: true,
ComputerName: "remote",
Template: "{{.UserName}}{{if .SSHSession}} on {{.HostName}}{{end}}",
ExpectedEnabled: true,
},
{
Case: "user without ssh",
@ -49,7 +45,6 @@ func TestSessionSegmentTemplate(t *testing.T) {
SSHSession: false,
ComputerName: "remote",
Template: "{{.UserName}}{{if .SSHSession}} on {{.HostName}}{{end}}",
ExpectedEnabled: true,
},
{
Case: "user with root and ssh",
@ -59,7 +54,6 @@ func TestSessionSegmentTemplate(t *testing.T) {
ComputerName: "remote",
Root: true,
Template: "{{if .Root}}super {{end}}{{.UserName}}{{if .SSHSession}} on {{.HostName}}{{end}}",
ExpectedEnabled: true,
},
{
Case: "no template",
@ -68,7 +62,6 @@ func TestSessionSegmentTemplate(t *testing.T) {
SSHSession: true,
ComputerName: "remote",
Root: true,
ExpectedEnabled: true,
},
{
Case: "default user not equal",
@ -79,7 +72,6 @@ func TestSessionSegmentTemplate(t *testing.T) {
ComputerName: "remote",
Root: true,
Template: "{{if ne .Env.POSH_SESSION_DEFAULT_USER .UserName}}{{.UserName}}{{end}}",
ExpectedEnabled: true,
},
{
Case: "default user equal",
@ -90,7 +82,6 @@ func TestSessionSegmentTemplate(t *testing.T) {
ComputerName: "remote",
Root: true,
Template: "{{if ne .Env.POSH_SESSION_DEFAULT_USER .UserName}}{{.UserName}}{{end}}",
ExpectedEnabled: false,
},
}
@ -122,9 +113,7 @@ func TestSessionSegmentTemplate(t *testing.T) {
SegmentTemplate: tc.Template,
},
}
assert.Equal(t, tc.ExpectedEnabled, session.enabled(), tc.Case)
if tc.ExpectedEnabled {
_ = session.enabled()
assert.Equal(t, tc.ExpectedString, session.string(), tc.Case)
}
}
}

View file

@ -5,6 +5,8 @@ import "strings"
type shell struct {
props Properties
env Environment
Name string
}
const (
@ -13,19 +15,29 @@ const (
)
func (s *shell) enabled() bool {
mappedNames := s.props.getKeyValueMap(MappedShellNames, make(map[string]string))
s.Name = s.env.getShellName()
for key, val := range mappedNames {
if strings.EqualFold(s.Name, key) {
s.Name = val
break
}
}
return true
}
func (s *shell) string() string {
mappedNames := s.props.getKeyValueMap(MappedShellNames, make(map[string]string))
shellName := s.env.getShellName()
for key, val := range mappedNames {
if strings.EqualFold(shellName, key) {
shellName = val
break
segmentTemplate := s.props.getString(SegmentTemplate, "{{.Name}}")
template := &textTemplate{
Template: segmentTemplate,
Context: s,
Env: s.env,
}
text, err := template.render()
if err != nil {
return err.Error()
}
return shellName
return text
}
func (s *shell) init(props Properties, env Environment) {

View file

@ -10,10 +10,12 @@ func TestWriteCurrentShell(t *testing.T) {
expected := "zsh"
env := new(MockedEnvironment)
env.On("getShellName").Return(expected, nil)
env.onTemplate()
s := &shell{
env: env,
props: properties{},
}
_ = s.enabled()
assert.Equal(t, expected, s.string())
}
@ -29,12 +31,14 @@ func TestUseMappedShellNames(t *testing.T) {
for _, tc := range cases {
env := new(MockedEnvironment)
env.On("getShellName").Return(tc.Expected, nil)
env.onTemplate()
s := &shell{
env: env,
props: properties{
MappedShellNames: map[string]string{"pwsh": "PS"},
},
}
_ = s.enabled()
got := s.string()
assert.Equal(t, tc.Expected, got)
}

View file

@ -1,15 +1,17 @@
package main
import (
"fmt"
)
type spotify struct {
props Properties
env Environment
status string
artist string
track string
MusicPlayer
}
type MusicPlayer struct {
Status string
Artist string
Track string
Icon string
}
const (
@ -19,24 +21,35 @@ const (
PausedIcon Property = "paused_icon"
// StoppedIcon indicates a song is stopped
StoppedIcon Property = "stopped_icon"
// TrackSeparator is put between the artist and the track
TrackSeparator Property = "track_separator"
playing = "playing"
stopped = "stopped"
paused = "paused"
)
func (s *spotify) string() string {
icon := ""
switch s.status {
case "stopped":
// in this case, no artist or track info
icon = s.props.getString(StoppedIcon, "\uF04D ")
return icon
case "paused":
icon = s.props.getString(PausedIcon, "\uF8E3 ")
case "playing":
icon = s.props.getString(PlayingIcon, "\uE602 ")
segmentTemplate := s.props.getString(SegmentTemplate, "{{.Icon}}{{ if ne .Status \"stopped\"}}{{.Artist}} - {{.Track}}{{ end }}")
template := &textTemplate{
Template: segmentTemplate,
Context: s,
Env: s.env,
}
text, err := template.render()
if err != nil {
return err.Error()
}
return text
}
func (s *spotify) resolveIcon() {
switch s.Status {
case stopped:
// in this case, no artist or track info
s.Icon = s.props.getString(StoppedIcon, "\uF04D ")
case paused:
s.Icon = s.props.getString(PausedIcon, "\uF8E3 ")
case playing:
s.Icon = s.props.getString(PlayingIcon, "\uE602 ")
}
separator := s.props.getString(TrackSeparator, " - ")
return fmt.Sprintf("%s%s%s%s", icon, s.artist, separator, s.track)
}
func (s *spotify) init(props Properties, env Environment) {

View file

@ -9,15 +9,16 @@ func (s *spotify) enabled() bool {
if running == "false" || running == "" {
return false
}
s.status = s.runAppleScriptCommand("tell application \"Spotify\" to player state as string")
s.Status = s.runAppleScriptCommand("tell application \"Spotify\" to player state as string")
if err != nil {
return false
}
if s.status == "stopped" {
if s.Status == stopped {
return false
}
s.artist = s.runAppleScriptCommand("tell application \"Spotify\" to artist of current track as string")
s.track = s.runAppleScriptCommand("tell application \"Spotify\" to name of current track as string")
s.Artist = s.runAppleScriptCommand("tell application \"Spotify\" to artist of current track as string")
s.Track = s.runAppleScriptCommand("tell application \"Spotify\" to name of current track as string")
s.resolveIcon()
return true
}

View file

@ -22,6 +22,7 @@ func bootStrapSpotifyDarwinTest(args *spotifyArgs) *spotify {
env.On("runCommand", "osascript", []string{"-e", "tell application \"Spotify\" to player state as string"}).Return(args.status, nil)
env.On("runCommand", "osascript", []string{"-e", "tell application \"Spotify\" to artist of current track as string"}).Return(args.artist, nil)
env.On("runCommand", "osascript", []string{"-e", "tell application \"Spotify\" to name of current track as string"}).Return(args.track, nil)
env.onTemplate()
s := &spotify{
env: env,
props: properties{},

View file

@ -8,33 +8,34 @@ import (
func TestSpotifyStringPlayingSong(t *testing.T) {
expected := "\ue602 Candlemass - Spellbreaker"
env := new(MockedEnvironment)
env.onTemplate()
s := &spotify{
artist: "Candlemass",
track: "Spellbreaker",
status: "playing",
props: properties{},
}
assert.Equal(t, expected, s.string())
}
func TestSpotifyStringPausedSong(t *testing.T) {
expected := "\uF8E3 Candlemass - Spellbreaker"
s := &spotify{
artist: "Candlemass",
track: "Spellbreaker",
status: "paused",
MusicPlayer: MusicPlayer{
Artist: "Candlemass",
Track: "Spellbreaker",
Status: "playing",
Icon: "\ue602 ",
},
props: properties{},
env: env,
}
assert.Equal(t, expected, s.string())
}
func TestSpotifyStringStoppedSong(t *testing.T) {
expected := "\uf04d "
env := new(MockedEnvironment)
env.onTemplate()
s := &spotify{
artist: "Candlemass",
track: "Spellbreaker",
status: "stopped",
MusicPlayer: MusicPlayer{
Artist: "Candlemass",
Track: "Spellbreaker",
Status: "stopped",
Icon: "\uf04d ",
},
props: properties{},
env: env,
}
assert.Equal(t, expected, s.string())
}

View file

@ -15,14 +15,15 @@ func (s *spotify) enabled() bool {
}
if !strings.Contains(spotifyWindowTitle, " - ") {
s.status = "stopped"
s.Status = stopped
return false
}
infos := strings.Split(spotifyWindowTitle, " - ")
s.artist = infos[0]
s.Artist = infos[0]
// remove first element and concat others(a song can contains also a " - ")
s.track = strings.Join(infos[1:], " - ")
s.status = "playing"
s.Track = strings.Join(infos[1:], " - ")
s.Status = playing
s.resolveIcon()
return true
}

View file

@ -17,6 +17,7 @@ type spotifyArgs struct {
func bootStrapSpotifyWindowsTest(args *spotifyArgs) *spotify {
env := new(MockedEnvironment)
env.On("getWindowTitle", "spotify.exe").Return(args.title, args.runError)
env.onTemplate()
s := &spotify{
env: env,
props: properties{},

View file

@ -23,9 +23,10 @@ func (s *spotify) enabled() bool {
title := record[len(record)-1]
if strings.Contains(title, " - ") {
infos := strings.Split(title, " - ")
s.artist = infos[0]
s.track = strings.Join(infos[1:], " - ")
s.status = "playing"
s.Artist = infos[0]
s.Track = strings.Join(infos[1:], " - ")
s.Status = playing
s.resolveIcon()
return true
}
}

View file

@ -54,6 +54,7 @@ func TestSpotifyWsl(t *testing.T) {
env := new(MockedEnvironment)
env.On("isWsl").Return(true)
env.On("runCommand", "tasklist.exe", []string{"/V", "/FI", "Imagename eq Spotify.exe", "/FO", "CSV", "/NH"}).Return(tc.ExecOutput, nil)
env.onTemplate()
s := &spotify{
env: env,
props: properties{},

View file

@ -3,7 +3,8 @@ package main
type text struct {
props Properties
env Environment
content string
Text string
}
const (
@ -19,14 +20,24 @@ func (t *text) enabled() bool {
Env: t.env,
}
if text, err := template.render(); err == nil {
t.content = text
return len(t.content) > 0
t.Text = text
return len(t.Text) > 0
}
return false
}
func (t *text) string() string {
return t.content
segmentTemplate := t.props.getString(SegmentTemplate, "{{.Text}}")
template := &textTemplate{
Template: segmentTemplate,
Context: t,
Env: t.env,
}
text, err := template.render()
if err != nil {
return err.Error()
}
return text
}
func (t *text) init(props Properties, env Environment) {

View file

@ -19,6 +19,11 @@ func (t *tempus) enabled() bool {
if t.CurrentDate.IsZero() {
t.CurrentDate = time.Now()
}
return true
}
func (t *tempus) string() string {
segmentTemplate := t.props.getString(SegmentTemplate, "")
if segmentTemplate != "" {
template := &textTemplate{
@ -31,25 +36,16 @@ func (t *tempus) enabled() bool {
if err != nil {
t.templateText = err.Error()
}
return len(t.templateText) > 0
if len(t.templateText) > 0 {
return t.templateText
}
return true
}
func (t *tempus) string() string {
return t.getFormattedText()
// keep old behaviour if no template for now
timeFormatProperty := t.props.getString(TimeFormat, "15:04:05")
return t.CurrentDate.Format(timeFormatProperty)
}
func (t *tempus) init(props Properties, env Environment) {
t.props = props
t.env = env
}
func (t *tempus) getFormattedText() string {
if len(t.templateText) > 0 {
return t.templateText
}
// keep old behaviour if no template
timeFormatProperty := t.props.getString(TimeFormat, "15:04:05")
return t.CurrentDate.Format(timeFormatProperty)
}

View file

@ -2,15 +2,13 @@ package main
import (
"encoding/json"
"fmt"
)
type ytm struct {
props Properties
env Environment
status playStatus
artist string
track string
MusicPlayer
}
const (
@ -19,17 +17,17 @@ const (
)
func (y *ytm) string() string {
icon := ""
separator := y.props.getString(TrackSeparator, " - ")
switch y.status {
case paused:
icon = y.props.getString(PausedIcon, "\uF8E3 ")
case playing:
icon = y.props.getString(PlayingIcon, "\uE602 ")
case stopped:
return y.props.getString(StoppedIcon, "\uF04D ")
segmentTemplate := y.props.getString(SegmentTemplate, "{{.Icon}}{{ if ne .Status \"stopped\"}}{{.Artist}} - {{.Track}}{{ end }}")
template := &textTemplate{
Template: segmentTemplate,
Context: y,
Env: y.env,
}
return fmt.Sprintf("%s%s%s%s", icon, y.artist, separator, y.track)
text, err := template.render()
if err != nil {
return err.Error()
}
return text
}
func (y *ytm) enabled() bool {
@ -44,14 +42,6 @@ func (y *ytm) init(props Properties, env Environment) {
y.env = env
}
type playStatus int
const (
playing playStatus = iota
paused
stopped
)
type ytmdaStatusResponse struct {
player `json:"player"`
track `json:"track"`
@ -95,13 +85,16 @@ func (y *ytm) setStatus() error {
if err != nil {
return err
}
y.status = playing
y.Status = playing
y.Icon = y.props.getString(PlayingIcon, "\uE602 ")
if !q.player.HasSong {
y.status = stopped
y.Status = stopped
y.Icon = y.props.getString(StoppedIcon, "\uF04D ")
} else if q.player.IsPaused {
y.status = paused
y.Status = paused
y.Icon = y.props.getString(PausedIcon, "\uF8E3 ")
}
y.artist = q.track.Author
y.track = q.track.Title
y.Artist = q.track.Author
y.Track = q.track.Title
return nil
}

View file

@ -7,39 +7,6 @@ import (
"github.com/stretchr/testify/assert"
)
func TestYTMStringPlayingSong(t *testing.T) {
expected := "\ue602 Candlemass - Spellbreaker"
y := &ytm{
artist: "Candlemass",
track: "Spellbreaker",
status: playing,
props: properties{},
}
assert.Equal(t, expected, y.string())
}
func TestYTMStringPausedSong(t *testing.T) {
expected := "\uF8E3 Candlemass - Spellbreaker"
y := &ytm{
artist: "Candlemass",
track: "Spellbreaker",
status: paused,
props: properties{},
}
assert.Equal(t, expected, y.string())
}
func TestYTMStringStoppedSong(t *testing.T) {
expected := "\uf04d "
y := &ytm{
artist: "Candlemass",
track: "Spellbreaker",
status: stopped,
props: properties{},
}
assert.Equal(t, expected, y.string())
}
func bootstrapYTMDATest(json string, err error) *ytm {
url := "http://127.0.0.1:9863"
env := new(MockedEnvironment)
@ -58,9 +25,9 @@ func TestYTMDAPlaying(t *testing.T) {
ytm := bootstrapYTMDATest(json, nil)
err := ytm.setStatus()
assert.NoError(t, err)
assert.Equal(t, playing, ytm.status)
assert.Equal(t, "Candlemass", ytm.artist)
assert.Equal(t, "Spellbreaker", ytm.track)
assert.Equal(t, "playing", ytm.Status)
assert.Equal(t, "Candlemass", ytm.Artist)
assert.Equal(t, "Spellbreaker", ytm.Track)
}
func TestYTMDAPaused(t *testing.T) {
@ -68,9 +35,9 @@ func TestYTMDAPaused(t *testing.T) {
ytm := bootstrapYTMDATest(json, nil)
err := ytm.setStatus()
assert.NoError(t, err)
assert.Equal(t, paused, ytm.status)
assert.Equal(t, "Candlemass", ytm.artist)
assert.Equal(t, "Spellbreaker", ytm.track)
assert.Equal(t, "paused", ytm.Status)
assert.Equal(t, "Candlemass", ytm.Artist)
assert.Equal(t, "Spellbreaker", ytm.Track)
}
func TestYTMDAStopped(t *testing.T) {
@ -78,9 +45,9 @@ func TestYTMDAStopped(t *testing.T) {
ytm := bootstrapYTMDATest(json, nil)
err := ytm.setStatus()
assert.NoError(t, err)
assert.Equal(t, stopped, ytm.status)
assert.Equal(t, "", ytm.artist)
assert.Equal(t, "", ytm.track)
assert.Equal(t, "stopped", ytm.Status)
assert.Equal(t, "", ytm.Artist)
assert.Equal(t, "", ytm.Track)
}
func TestYTMDAError(t *testing.T) {

View file

@ -39,6 +39,7 @@ type templateCache struct {
Code int
Env map[string]string
OS string
WSL bool
}
func (c *Context) init(t *textTemplate) {
@ -85,7 +86,7 @@ func (t *textTemplate) cleanTemplate() {
*knownVariables = append(*knownVariables, splitted[0])
return splitted[0], true
}
knownVariables := []string{"Root", "PWD", "Folder", "Shell", "UserName", "HostName", "Env", "Data", "Code", "OS"}
knownVariables := []string{"Root", "PWD", "Folder", "Shell", "UserName", "HostName", "Env", "Data", "Code", "OS", "WSL"}
matches := findAllNamedRegexMatch(`(?: |{|\()(?P<var>(\.[a-zA-Z_][a-zA-Z0-9]*)+)`, t.Template)
for _, match := range matches {
if variable, OK := unknownVariable(match["var"], &knownVariables); OK {

View file

@ -89,7 +89,7 @@
"background": "p:node",
"properties": {
"prefix": " \uF898 ",
"display_version": true
"fetch_version": true
}
},
{
@ -100,7 +100,7 @@
"background": "p:go",
"properties": {
"prefix": " \uE626 ",
"display_version": true
"fetch_version": true
}
},
{
@ -111,7 +111,7 @@
"background": "p:julia",
"properties": {
"prefix": " \uE624 ",
"display_version": true
"fetch_version": true
}
},
{
@ -135,7 +135,7 @@
"background": "p:ruby",
"properties": {
"prefix": " \uE791 ",
"display_version": true,
"fetch_version": true,
"display_mode": "files"
}
},
@ -147,7 +147,7 @@
"background": "p:azfunc",
"properties": {
"prefix": " \uf0e7",
"display_version": false,
"fetch_version": false,
"display_mode": "files"
}
},
@ -172,7 +172,7 @@
"foreground": "p:black",
"background": "p:root",
"properties": {
"root_icon": ""
"template": ""
}
},
{

View file

@ -58,7 +58,7 @@
"background": "#6CA35E",
"properties": {
"prefix": " \uF898 ",
"display_version": true
"fetch_version": true
}
},
{
@ -69,7 +69,7 @@
"background": "#8ED1F7",
"properties": {
"prefix": " \uE626 ",
"display_version": true
"fetch_version": true
}
},
{
@ -80,7 +80,7 @@
"background": "#4063D8",
"properties": {
"prefix": " \uE624 ",
"display_version": true
"fetch_version": true
}
},
{
@ -104,7 +104,7 @@
"background": "#AE1401",
"properties": {
"prefix": " \uE791 ",
"display_version": true,
"fetch_version": true,
"display_mode": "files"
}
},
@ -116,7 +116,7 @@
"background": "#FEAC19",
"properties": {
"prefix": " \uf0e7",
"display_version": false,
"fetch_version": false,
"display_mode": "files"
}
},
@ -141,7 +141,7 @@
"foreground": "#111111",
"background": "#ffff66",
"properties": {
"root_icon": ""
"template": ""
}
},
{

View file

@ -50,7 +50,7 @@
"foreground": "#cd5e42",
"properties": {
"prefix": "",
"root_icon": "\ue3bf"
"template": "\ue3bf"
}
},
{

Some files were not shown because too many files have changed in this diff Show more