pax_global_header00006660000000000000000000000064146501062630014515gustar00rootroot0000000000000052 comment=8b37d4ece5d980a9e00d9b70a287eda2d714be05 golang-github-pterm-pterm-0.12.79/000077500000000000000000000000001465010626300166765ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/.github/000077500000000000000000000000001465010626300202365ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/.github/CODEOWNERS000066400000000000000000000000261465010626300216270ustar00rootroot00000000000000* @MarvinJWendt golang-github-pterm-pterm-0.12.79/.github/FUNDING.yml000066400000000000000000000013651465010626300220600ustar00rootroot00000000000000# These are supported funding model platforms github: [ MarvinJWendt ] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: ['https://marvin.ws/donate'] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] golang-github-pterm-pterm-0.12.79/.github/ISSUE_TEMPLATE/000077500000000000000000000000001465010626300224215ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000001631465010626300251130ustar00rootroot00000000000000--- name: Bug report about: 🐞 Create a bug report to help us improve title: '' labels: bug assignees: '' --- golang-github-pterm-pterm-0.12.79/.github/ISSUE_TEMPLATE/config.yml000066400000000000000000000002421465010626300244070ustar00rootroot00000000000000contact_links: - name: Twitter url: https://marvin.ws/twitter about: 💬 For questions, feedback and support, you can contact me directly via Twitter! golang-github-pterm-pterm-0.12.79/.github/ISSUE_TEMPLATE/feature_request.md000066400000000000000000000001701465010626300261440ustar00rootroot00000000000000--- name: Feature request about: "✨ Suggest an idea for this project" title: '' labels: proposal assignees: '' --- golang-github-pterm-pterm-0.12.79/.github/dependabot.yml000066400000000000000000000007671465010626300231000ustar00rootroot00000000000000# To get started with Dependabot version updates, you'll need to specify which # package ecosystems to update and where the package manifests are located. # Please see the documentation for all configuration options: # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates version: 2 updates: - package-ecosystem: "gomod" # See documentation for possible values directory: "/" # Location of package manifests schedule: interval: "daily" golang-github-pterm-pterm-0.12.79/.github/pull_request_template.md000066400000000000000000000001621465010626300251760ustar00rootroot00000000000000 Fixes #YOUR_ISSUE_NUMBER golang-github-pterm-pterm-0.12.79/.github/release.yml000066400000000000000000000005371465010626300224060ustar00rootroot00000000000000changelog: exclude: labels: - ignore-for-release authors: - octocat categories: - title: Breaking Changes 🛠 labels: - breaking - title: Exciting New Features 🎉 labels: - feature - title: Fixes 🔧 labels: - fix - title: Other Changes labels: - "*" golang-github-pterm-pterm-0.12.79/.github/workflows/000077500000000000000000000000001465010626300222735ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/.github/workflows/animator.yml000066400000000000000000000006701465010626300246330ustar00rootroot00000000000000on: push: branches: master name: Update Animations jobs: animator: if: "!contains(github.event.head_commit.message, 'autoupdate')" runs-on: ubuntu-latest steps: - name: Git Setup run: git config --global --add safe.directory /github/workspace - name: Update Docs uses: pterm/animation-ci@master env: ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }} TERM: xterm-256color golang-github-pterm-pterm-0.12.79/.github/workflows/conventional-label.yaml000066400000000000000000000003021465010626300267260ustar00rootroot00000000000000on: pull_request_target: types: [ opened, edited ] name: conventional-release-labels jobs: label: runs-on: ubuntu-latest steps: - uses: bcoe/conventional-release-labels@v1 golang-github-pterm-pterm-0.12.79/.github/workflows/go.yml000066400000000000000000000015701465010626300234260ustar00rootroot00000000000000name: Go on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: if: "!contains(github.event.head_commit.message, 'autoupdate')" name: Build runs-on: ${{ matrix.os }} strategy: matrix: os: [ windows-latest ] steps: - name: Set up Go 1.x uses: actions/setup-go@v4 with: go-version: 1.21 cache-dependency-path: go.sum id: go - name: Check out code into the Go module directory uses: actions/checkout@v3 - name: Get dependencies run: go get -v -t -d ./... - name: Build run: go build -v . - name: Test run: go test -coverprofile="coverage.txt" -covermode=atomic -p 1 . - name: Upload coverage to Codecov if: success() && matrix.os == 'windows-latest' uses: codecov/codecov-action@v3 golang-github-pterm-pterm-0.12.79/.github/workflows/lint.yml000066400000000000000000000006471465010626300237730ustar00rootroot00000000000000name: Code Analysis on: [ push, pull_request ] jobs: lint: if: "!contains(github.event.head_commit.message, 'autoupdate')" runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Go uses: actions/setup-go@v4 with: go-version: 'stable' - name: golangci-lint uses: golangci/golangci-lint-action@v3 with: version: latest golang-github-pterm-pterm-0.12.79/.gitignore000066400000000000000000000005261465010626300206710ustar00rootroot00000000000000# Binaries for programs and plugins *.exe *.exe~ *.dll *.so *.dylib # Test binary, built with `go test -c` *.test # Output of the go coverage tool, specifically when used with LiteIDE *.out # Dependency directories (remove the comment below to include it) vendor/ # This is where we test stuff /experimenting/* /.history /.vscode /.idea golang-github-pterm-pterm-0.12.79/.golangci.yml000066400000000000000000000034721465010626300212700ustar00rootroot00000000000000linters-settings: gocritic: enabled-tags: - diagnostic - experimental - opinionated - performance - style disabled-checks: - dupImport - ifElseChain - octalLiteral - whyNoLint - wrapperFunc - exitAfterDefer - hugeParam - ptrToRefParam - paramTypeCombine - unnamedResult # maligned: # suggest-new: true misspell: locale: US linters: disable-all: true enable: - gocritic - gosec - govet - ineffassign - unconvert - gosimple - godox - whitespace - staticcheck # - bodyclose # - maligned # - godot # - deadcode # - depguard # - dogsled # - dupl # - errcheck # - exhaustive # - funlen # - gochecknoinits # - goconst # - gocyclo # - gofmt # - goimports # - golint # - gomnd # - goprintffuncname # - lll # - misspell # - nakedret # - noctx # - nolintlint # - rowserrcheck # - scopelint # - structcheck # - stylecheck # - typecheck # - unparam # - unused # - varcheck # - whitespace # - asciicheck # - gochecknoglobals # - gocognit # - goerr113 # - nestif # - prealloc # - testpackage # - wsl issues: # Excluding configuration per-path, per-linter, per-text and per-source exclude-rules: - path: _test\.go linters: - gocyclo - errcheck - dupl - gosec - gocritic # https://github.com/go-critic/go-critic/issues/926 - linters: - gocritic text: "unnecessaryDefer:" - linters: - gocritic text: "preferDecodeRune:" service: golangci-lint-version: 1.31.x # use the fixed version to not introduce new linters unexpectedly golang-github-pterm-pterm-0.12.79/CODE_OF_CONDUCT.md000066400000000000000000000064321465010626300215020ustar00rootroot00000000000000# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at pterm@marvinjwendt.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq golang-github-pterm-pterm-0.12.79/CONTRIBUTING.md000066400000000000000000000136071465010626300211360ustar00rootroot00000000000000# Contributing to PTerm > This document explains how to participate in the development of PTerm.\ If your goal is to report a bug instead of programming PTerm, you can do so [here](https://github.com/pterm/pterm/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc). ## Best practise We enforce some best practises, especially made for PTerm, to provide a clean and consistent user experience. ### Styles Styles should always be consumed as pointers. That way, the user can change the style of printers globally. ## Creating a new printer > In this chapter we will show you how to create a new printer. ### `TextPrinter` Template ```go package pterm type TemplatePrinter struct{ // TODO: Add printer settings here } // Sprint formats using the default formats for its operands and returns the resulting string. // Spaces are added between operands when neither is a string. func (p TemplatePrinter) Sprint(a ...interface{}) string { panic("write printer code here") } // Sprintln formats using the default formats for its operands and returns the resulting string. // Spaces are always added between operands and a newline is appended. func (p TemplatePrinter) Sprintln(a ...interface{}) string { return Sprintln(p.Sprint(a...)) } // Sprintf formats according to a format specifier and returns the resulting string. func (p TemplatePrinter) Sprintf(format string, a ...interface{}) string { return p.Sprint(Sprintf(format, a...)) } // Print formats using the default formats for its operands and writes to standard output. // Spaces are added between operands when neither is a string. // It returns the number of bytes written and any write error encountered. func (p TemplatePrinter) Print(a ...interface{}) *TextPrinter { Print(p.Sprint(a...)) tp := TextPrinter(p) return &tp } // Println formats using the default formats for its operands and writes to standard output. // Spaces are always added between operands and a newline is appended. // It returns the number of bytes written and any write error encountered. func (p TemplatePrinter) Println(a ...interface{}) *TextPrinter { Println(p.Sprint(a...)) tp := TextPrinter(p) return &tp } // Printf formats according to a format specifier and writes to standard output. // It returns the number of bytes written and any write error encountered. func (p TemplatePrinter) Printf(format string, a ...interface{}) *TextPrinter { Print(p.Sprintf(format, a...)) tp := TextPrinter(p) return &tp } ``` ### `RenderablePrinter` Template ```go package pterm type TemplatePrinter struct{ // TODO: Add printer settings here } // Srender renders the Template as a string. func (p TemplatePrinter) Srender() (string, error) { var ret string return ret, nil } // Render prints the Template to the terminal. func (p TemplatePrinter) Render() error { s, err := p.Srender() if err != nil { return err } Println(s) return nil } ``` ### `LivePrinter` Template ```go // Start the TemplatePrinter. package pterm import "github.com/pterm/pterm" type TemplatePrinter struct{ } func (s TemplatePrinter) Start(text...interface{}) (*TemplatePrinter, error) { // TODO: Replace Template with actual printer. // TODO: start logic return &s, nil } // Stop terminates the TemplatePrinter immediately. // The TemplatePrinter will not resolve into anything. func (s *TemplatePrinter) Stop() error { // TODO: stop logic return nil } // GenericStart runs Start, but returns a LivePrinter. // This is used for the interface LivePrinter. // You most likely want to use Start instead of this in your program. func (s *TemplatePrinter) GenericStart() (*LivePrinter, error) { _, err := s.Start() lp := LivePrinter(s) return &lp, err } // GenericStop runs Stop, but returns a LivePrinter. // This is used for the interface LivePrinter. // You most likely want to use Stop instead of this in your program. func (s *TemplatePrinter) GenericStop() (*LivePrinter, error) { err := s.Stop() lp := LivePrinter(s) return &lp, err } ``` ## Writing Tests > Each method of PTerm must be tested. ### Required tests for every printer #### Nil Check > This ensures that a printer without set values will not produce errors. ```go func TestTemplatePrinterNilPrint(t *testing.T) { // TODO: Replace "Template" with actual printer name. p := TemplatePrinter{} // TODO: Replace "Template" with actual printer name. p.Println("Hello, World!") } ``` #### `WithXxx()` Methods > Each method, which starts with `With` can be tested by checking if it actually creates a new printer and sets the value. Example from `SectionPrinter`: ```go func TestSectionPrinter_WithStyle(t *testing.T) { p := SectionPrinter{} s := NewStyle(FgRed, BgRed, Bold) p2 := p.WithStyle(s) assert.Equal(t, s, p2.Style) assert.Empty(t, p.Style) } func TestSectionPrinter_WithTopPadding(t *testing.T) { p := SectionPrinter{} p2 := p.WithTopPadding(1337) assert.Equal(t, 1337, p2.TopPadding) assert.Empty(t, p.TopPadding) } ``` ### `TextPrinter` Tests Template ```go func TestTemplatePrinterPrintMethods(t *testing.T) { // TODO: Replace "Template" with actual printer name. p := DefaultTemplate // TODO: Replace "Template" with actual printer name. t.Run("Print", func(t *testing.T) { testPrintContains(t, func(w io.Writer, a interface{}) { p.Print(a) }) }) t.Run("Printf", func(t *testing.T) { testPrintfContains(t, func(w io.Writer, format string, a interface{}) { p.Printf(format, a) }) }) t.Run("Println", func(t *testing.T) { testPrintlnContains(t, func(w io.Writer, a interface{}) { p.Println(a) }) }) t.Run("Sprint", func(t *testing.T) { testSprintContains(t, func(a interface{}) string { return p.Sprint(a) }) }) t.Run("Sprintf", func(t *testing.T) { testSprintfContains(t, func(format string, a interface{}) string { return p.Sprintf(format, a) }) }) t.Run("Sprintln", func(t *testing.T) { testSprintlnContains(t, func(a interface{}) string { return p.Sprintln(a) }) }) } ``` golang-github-pterm-pterm-0.12.79/LICENSE000066400000000000000000000020461465010626300177050ustar00rootroot00000000000000MIT License Copyright (c) 2020 pterm Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. golang-github-pterm-pterm-0.12.79/README.md000066400000000000000000003212141465010626300201600ustar00rootroot00000000000000

💻 PTerm | Pretty Terminal Printer

A modern Go framework to make beautiful CLIs

Latest Release Stars Forks License: MIT Downloads Forks
Downloads

PTerm

Show Demo Code

---

PTerm.sh | Installation | Getting Started | Documentation | Examples | Q&A | Discord

--- ## 📦 Installation To make PTerm available in your project, you can run the following command.\ Make sure to run this command inside your project, when you're using go modules 😉 ```sh go get github.com/pterm/pterm ``` ## ⭐ Main Features | Feature | Description | |------------------|-----------------------------------------------------| | 🪀 Easy to use | PTerm emphasizes ease of use, with [examples](#-examples) and consistent component design. | | 🤹‍♀️ Cross-Platform | PTerm works on various OS and terminals, including `Windows CMD`, `macOS iTerm2`, and in CI systems like `GitHub Actions`. | | 🧪 Well tested | A high test coverage and `28774` automated tests ensure PTerm's reliability. | | ✨ Consistent Colors | PTerm uses the [ANSI color scheme](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) for uniformity and supports `TrueColor` for advanced terminals. | | 📚 Component system | PTerm's flexible `Printers` can be used individually or combined to generate beautiful console output. | | 🛠 Configurable | PTerm is ready to use without configuration but allows easy customization for unique terminal output. | | ✏ Documentation | Access comprehensive docs on [pkg.go.dev](https://pkg.go.dev/github.com/pterm/pterm#section-documentation) and view practical examples in the [examples section](#-examples). | ### Printers (Components)
| Feature | Feature | Feature | Feature | Feature | | :-------: | :-------: | :-------: | :-------: | :-------: | | Area
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/area) |Barchart
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/barchart) |Basictext
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/basictext) |Bigtext
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/bigtext) |Box
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/box) | | Bulletlist
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/bulletlist) |Center
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/center) |Coloring
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/coloring) |Header
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/header) |Heatmap
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/heatmap) | | Interactive confirm
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/interactive_confirm) |Interactive continue
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/interactive_continue) |Interactive multiselect
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/interactive_multiselect) |Interactive select
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/interactive_select) |Interactive textinput
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/interactive_textinput) | | Logger
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/logger) |Multiple-live-printers
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/multiple-live-printers) |Panel
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/panel) |Paragraph
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/paragraph) |Prefix
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/prefix) | | Progressbar
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/progressbar) |Section
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/section) |Slog
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/slog) |Spinner
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/spinner) |Style
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/style) | | Table
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/table) |Theme
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/theme) |Tree
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/tree) | | |
---
### 🦸‍♂️ Sponsors ---
## 🧪 Examples


‼️ You can find all the examples, in a much better structure and their source code, in "_examples" ‼️
Click on the link above to show the examples folder.

### area/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/area/demo/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Print an informational message using PTerm's Info printer. // This message will stay in place while the area updates. pterm.Info.Println("The previous text will stay in place, while the area updates.") // Print two new lines as spacer. pterm.Print("\n\n") // Start the Area printer from PTerm's DefaultArea, with the Center option. // The Area printer allows us to update a specific area of the console output. // The returned 'area' object is used to control the area updates. area, _ := pterm.DefaultArea.WithCenter().Start() // Loop 10 times to update the area with the current time. for i := 0; i < 10; i++ { // Get the current time, format it as "15:04:05" (hour:minute:second), and convert it to a string. // Then, create a BigText from the time string using PTerm's DefaultBigText and putils NewLettersFromString. // The Srender() function is used to save the BigText as a string. str, _ := pterm.DefaultBigText.WithLetters(putils.LettersFromString(time.Now().Format("15:04:05"))).Srender() // Update the Area contents with the current time string. area.Update(str) // Sleep for a second before the next update. time.Sleep(time.Second) } // Stop the Area printer after all updates are done. area.Stop() } ```
### area/center ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/area/center/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new default area in the center of the terminal. // The Start() function returns the created area and an error. area, _ := pterm.DefaultArea.WithCenter().Start() // Loop 5 times to simulate a dynamic update. for i := 0; i < 5; i++ { // Update the content of the area with the current count. // The Sprintf function is used to format the string. area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second to simulate a time-consuming task. time.Sleep(time.Second) } // Stop the area after all updates are done. area.Stop() } ```
### area/default ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/area/default/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new default area and get a reference to it. // The second return value is an error which is ignored here. area, _ := pterm.DefaultArea.Start() // Loop 5 times for i := 0; i < 5; i++ { // Update the content of the area dynamically. // Here we're just displaying the current count. area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second before the next update. time.Sleep(time.Second) } // Stop the area after all updates are done. // This will clean up and free resources used by the area. area.Stop() } ```
### area/dynamic-chart ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/area/dynamic-chart/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new fullscreen centered area. // This area will be used to display the bar chart. area, _ := pterm.DefaultArea.WithFullscreen().WithCenter().Start() // Ensure the area stops updating when we're done. defer area.Stop() // Loop to update the bar chart 10 times. for i := 0; i < 10; i++ { // Create a new bar chart with dynamic bars. // The bars will change based on the current iteration. barchart := pterm.DefaultBarChart.WithBars(dynamicBars(i)) // Render the bar chart to a string. // This string will be used to update the area. content, _ := barchart.Srender() // Update the area with the new bar chart. area.Update(content) // Wait for half a second before the next update. time.Sleep(500 * time.Millisecond) } } // dynamicBars generates a set of bars for the bar chart. // The bars will change based on the current iteration. func dynamicBars(i int) pterm.Bars { return pterm.Bars{ {Label: "A", Value: 10}, // A static bar. {Label: "B", Value: 20 * i}, // A bar that grows with each iteration. {Label: "C", Value: 30}, // Another static bar. {Label: "D", Value: 40 + i}, // A bar that grows slowly with each iteration. } } ```
### area/fullscreen ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/area/fullscreen/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new fullscreen area. This will return an area instance and an error. // The underscore (_) is used to ignore the error. area, _ := pterm.DefaultArea.WithFullscreen().Start() // Loop 5 times to update the area content. for i := 0; i < 5; i++ { // Update the content of the area with the current count. // The Sprintf function is used to format the string. area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second before the next update. time.Sleep(time.Second) } // Stop the area after all updates are done. area.Stop() } ```
### area/fullscreen-center ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/area/fullscreen-center/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Initialize a new PTerm area with fullscreen and center options // The Start() function returns the created area and an error (ignored here) area, _ := pterm.DefaultArea.WithFullscreen().WithCenter().Start() // Loop 5 times to demonstrate dynamic content update for i := 0; i < 5; i++ { // Update the content of the area with the current count // The Sprintf function is used to format the string with the count area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second time.Sleep(time.Second) } // Stop the area after all updates are done // This will clear the area and return the terminal to its normal state area.Stop() } ```
### barchart/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the bars for the chart bars := []pterm.Bar{ {Label: "Bar 1", Value: 5}, {Label: "Bar 2", Value: 3}, {Label: "Longer Label", Value: 7}, } // Print an informational message pterm.Info.Println("Chart example with positive only values (bars use 100% of chart area)") // Create a bar chart with the defined bars and render it // The DefaultBarChart is used as a base, and the bars are added with the WithBars option // The Render function is then called to display the chart pterm.DefaultBarChart.WithBars(bars).Render() // Create a horizontal bar chart with the defined bars and render it // The DefaultBarChart is used as a base, the chart is made horizontal with the WithHorizontal option, and the bars are added with the WithBars option // The Render function is then called to display the chart pterm.DefaultBarChart.WithHorizontal().WithBars(bars).Render() } ```
### barchart/custom-height ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/custom-height/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define a slice of Bar structs. Each struct represents a bar in the chart. // The Label field is the name of the bar and the Value field is the height of the bar. bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create and render a bar chart with the defined bars and a height of 5. // The WithBars method is used to set the bars of the chart. // The WithHeight method is used to set the height of the chart. // The Render method is used to display the chart in the terminal. pterm.DefaultBarChart.WithBars(bars).WithHeight(5).Render() } ```
### barchart/custom-width ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/custom-width/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart barData := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined data // The chart is horizontal and has a width of 5 // The Render() function is called to display the chart pterm.DefaultBarChart.WithBars(barData).WithHorizontal().WithWidth(5).Render() } ```
### barchart/default ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/default/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart. Each bar is represented by a `pterm.Bar` struct. // The `Label` field represents the label of the bar, and the `Value` field represents the value of the bar. bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Use the `DefaultBarChart` from the `pterm` package to create a bar chart. // The `WithBars` method is used to set the bars of the chart. // The `Render` method is used to display the chart. pterm.DefaultBarChart.WithBars(bars).Render() } ```
### barchart/horizontal ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/horizontal/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined data // The chart is displayed horizontally // The Render() function is called to display the chart pterm.DefaultBarChart.WithBars(bars).WithHorizontal().Render() } ```
### barchart/horizontal-show-value ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/horizontal-show-value/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart barData := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined data // The chart is horizontal and displays the value of each bar // The Render() function is called to display the chart pterm.DefaultBarChart.WithBars(barData).WithHorizontal().WithShowValue().Render() } ```
### barchart/mixed-values ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/mixed-values/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define a set of bars for the chart. // Each bar has a label and a value. bars := []pterm.Bar{ {Label: "Bar 1", Value: 2}, {Label: "Bar 2", Value: -3}, {Label: "Bar 3", Value: -2}, {Label: "Bar 4", Value: 5}, {Label: "Longer Label", Value: 7}, } // Print a section header. // This is useful for separating different parts of the output. pterm.DefaultSection.Println("Chart example with mixed values (note screen space usage in case when ABSOLUTE values of negative and positive parts are differ too much)") // Create a bar chart with the defined bars. // The chart will display the value of each bar. // The Render() function is called to display the chart. pterm.DefaultBarChart.WithBars(bars).WithShowValue().Render() // Create a horizontal bar chart with the same bars. // The chart will display the value of each bar. // The Render() function is called to display the chart. pterm.DefaultBarChart.WithHorizontal().WithBars(bars).WithShowValue().Render() } ```
### barchart/negative-values ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/negative-values/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define a set of bars with negative values. // Each bar is represented by a struct with a label and a value. negativeBars := pterm.Bars{ {Label: "Bar 1", Value: -5}, {Label: "Bar 2", Value: -3}, {Label: "Longer Label", Value: -7}, } // Print an informational message to the console. pterm.Info.Println("Chart example with negative only values (bars use 100% of chart area)") // Create a vertical bar chart with the defined bars. // The WithShowValue() option is used to display the value of each bar in the chart. // The Render() method is called to draw the chart. _ = pterm.DefaultBarChart.WithBars(negativeBars).WithShowValue().Render() // Create a horizontal bar chart with the same bars. // The WithHorizontal() option is used to orient the chart horizontally. // The WithShowValue() option and Render() method are used in the same way as before. _ = pterm.DefaultBarChart.WithHorizontal().WithBars(negativeBars).WithShowValue().Render() } ```
### barchart/show-value ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/show-value/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define a slice of bars for the bar chart. Each bar is represented by a struct // with a Label and a Value. The Label is a string that represents the name of the bar, // and the Value is an integer that represents the height of the bar. bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined bars using the DefaultBarChart object from PTerm. // Chain the WithBars method to set the bars of the chart. // Chain the WithShowValue method to display the value of each bar on the chart. // Finally, call the Render method to display the chart. pterm.DefaultBarChart.WithBars(bars).WithShowValue().Render() } ```
### basictext/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/basictext/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // The DefaultBasicText is a basic text printer provided by PTerm. // It is used to print text without any special formatting. pterm.DefaultBasicText.Println("Default basic text printer.") // The DefaultBasicText can be used in any context that requires a TextPrinter. // Here, we're using it with the LightMagenta function to color a portion of the text. pterm.DefaultBasicText.Println("Can be used in any" + pterm.LightMagenta(" TextPrinter ") + "context.") // The DefaultBasicText is also useful for resolving progress bars and spinners. } ```
### bigtext/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/bigtext/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Create a large text with the LetterStyle from the standard theme. // This is useful for creating title screens. pterm.DefaultBigText.WithLetters(putils.LettersFromString("PTerm")).Render() // Create a large text with differently colored letters. // Here, the first letter 'P' is colored cyan and the rest 'Term' is colored light magenta. // This can be used to highlight specific parts of the text. pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithStyle("P", pterm.FgCyan.ToStyle()), putils.LettersFromStringWithStyle("Term", pterm.FgLightMagenta.ToStyle()), ).Render() // Create a large text with a specific RGB color. // This can be used when you need a specific color that is not available in the standard colors. // Here, the color is gold (RGB: 255, 215, 0). pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithRGB("PTerm", pterm.NewRGB(255, 215, 0)), ).Render() } ```
### bigtext/colored ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/bigtext/colored/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Initialize a big text display with the letters "P" and "Term" // "P" is displayed in cyan and "Term" is displayed in light magenta pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithStyle("P", pterm.FgCyan.ToStyle()), putils.LettersFromStringWithStyle("Term", pterm.FgLightMagenta.ToStyle())). Render() // Render the big text to the terminal } ```
### bigtext/default ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/bigtext/default/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Define the text to be rendered var text = "PTerm" // Convert the text into a format suitable for PTerm var letters = putils.LettersFromString(text) // Render the text using PTerm's default big text style pterm.DefaultBigText.WithLetters(letters).Render() } ```
### box/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/box/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Print an informational message. pterm.Info.Println("This might not be rendered correctly on GitHub,\nbut it will work in a real terminal.\nThis is because GitHub does not use a monospaced font by default for SVGs") // Create three panels with text, some of them with titles. // The panels are created using the DefaultBox style. panel1 := pterm.DefaultBox.Sprint("Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit,\nsed do eiusmod tempor incididunt\nut labore et dolore\nmagna aliqua.") panel2 := pterm.DefaultBox.WithTitle("title").Sprint("Ut enim ad minim veniam,\nquis nostrud exercitation\nullamco laboris\nnisi ut aliquip\nex ea commodo\nconsequat.") panel3 := pterm.DefaultBox.WithTitle("bottom center title").WithTitleBottomCenter().Sprint("Duis aute irure\ndolor in reprehenderit\nin voluptate velit esse cillum\ndolore eu fugiat\nnulla pariatur.") // Combine the panels into a layout using the DefaultPanel style. // The layout is a 2D grid, with each row being an array of panels. // In this case, the first row contains panel1 and panel2, and the second row contains only panel3. panels, _ := pterm.DefaultPanel.WithPanels(pterm.Panels{ {{Data: panel1}, {Data: panel2}}, {{Data: panel3}}, }).Srender() // Print the panels layout inside a box with a title. // The box is created using the DefaultBox style, with the title positioned at the bottom right. pterm.DefaultBox.WithTitle("Lorem Ipsum").WithTitleBottomRight().WithRightPadding(0).WithBottomPadding(0).Println(panels) } ```
### box/custom-padding ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/box/custom-padding/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a default box with custom padding options and print "Hello, World!" inside it. pterm.DefaultBox.WithRightPadding(10).WithLeftPadding(10).WithTopPadding(2).WithBottomPadding(2).Println("Hello, World!") } ```
### box/default ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/box/default/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a default box with PTerm and print a message in it. // The DefaultBox.Println method automatically starts, prints the message, and stops the box. pterm.DefaultBox.Println("Hello, World!") } ```
### box/title ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/box/title/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a default box with specified padding paddedBox := pterm.DefaultBox.WithLeftPadding(4).WithRightPadding(4).WithTopPadding(1).WithBottomPadding(1) // Define a title for the box title := pterm.LightRed("I'm a box!") // Create boxes with the title positioned differently and containing different content box1 := paddedBox.WithTitle(title).Sprint("Hello, World!\n 1") // Title at default position (top left) box2 := paddedBox.WithTitle(title).WithTitleTopCenter().Sprint("Hello, World!\n 2") // Title at top center box3 := paddedBox.WithTitle(title).WithTitleTopRight().Sprint("Hello, World!\n 3") // Title at top right box4 := paddedBox.WithTitle(title).WithTitleBottomRight().Sprint("Hello, World!\n 4") // Title at bottom right box5 := paddedBox.WithTitle(title).WithTitleBottomCenter().Sprint("Hello, World!\n 5") // Title at bottom center box6 := paddedBox.WithTitle(title).WithTitleBottomLeft().Sprint("Hello, World!\n 6") // Title at bottom left box7 := paddedBox.WithTitle(title).WithTitleTopLeft().Sprint("Hello, World!\n 7") // Title at top left // Render the boxes in a panel layout pterm.DefaultPanel.WithPanels([][]pterm.Panel{ {{box1}, {box2}, {box3}}, {{box4}, {box5}, {box6}}, {{box7}}, }).Render() } ```
### bulletlist/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/bulletlist/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Define a list of bullet list items with different levels. bulletListItems := []pterm.BulletListItem{ {Level: 0, Text: "Level 0"}, // Level 0 item {Level: 1, Text: "Level 1"}, // Level 1 item {Level: 2, Text: "Level 2"}, // Level 2 item } // Use the default bullet list style to render the list items. pterm.DefaultBulletList.WithItems(bulletListItems).Render() // Define a string with different levels of indentation. text := `0 1 2 3` // Convert the indented string to a bullet list and render it. putils.BulletListFromString(text, " ").Render() } ```
### bulletlist/customized ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/bulletlist/customized/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define a list of bullet list items with different styles and levels. bulletListItems := []pterm.BulletListItem{ { Level: 0, // Level 0 (top level) Text: "Blue", // Text to display TextStyle: pterm.NewStyle(pterm.FgBlue), // Text color BulletStyle: pterm.NewStyle(pterm.FgRed), // Bullet color }, { Level: 1, // Level 1 (sub-item) Text: "Green", // Text to display TextStyle: pterm.NewStyle(pterm.FgGreen), // Text color Bullet: "-", // Custom bullet symbol BulletStyle: pterm.NewStyle(pterm.FgLightWhite), // Bullet color }, { Level: 2, // Level 2 (sub-sub-item) Text: "Cyan", // Text to display TextStyle: pterm.NewStyle(pterm.FgCyan), // Text color Bullet: ">", // Custom bullet symbol BulletStyle: pterm.NewStyle(pterm.FgYellow), // Bullet color }, } // Create a bullet list with the defined items and render it. pterm.DefaultBulletList.WithItems(bulletListItems).Render() } ```
### center/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/center/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Print a block of text centered in the terminal pterm.DefaultCenter.Println("This text is centered!\nIt centers the whole block by default.\nIn that way you can do stuff like this:") // Generate BigLetters and store in 's' s, _ := pterm.DefaultBigText.WithLetters(putils.LettersFromString("PTerm")).Srender() // Print the BigLetters 's' centered in the terminal pterm.DefaultCenter.Println(s) // Print each line of the text separately centered in the terminal pterm.DefaultCenter.WithCenterEachLineSeparately().Println("This text is centered!\nBut each line is\ncentered\nseparately") } ```
### coloring/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a table with different foreground and background colors. pterm.DefaultTable.WithData([][]string{ {pterm.FgBlack.Sprint("Black"), pterm.FgRed.Sprint("Red"), pterm.FgGreen.Sprint("Green"), pterm.FgYellow.Sprint("Yellow")}, {"", pterm.FgLightRed.Sprint("Light Red"), pterm.FgLightGreen.Sprint("Light Green"), pterm.FgLightYellow.Sprint("Light Yellow")}, {pterm.BgBlack.Sprint("Black"), pterm.BgRed.Sprint("Red"), pterm.BgGreen.Sprint("Green"), pterm.BgYellow.Sprint("Yellow")}, {"", pterm.BgLightRed.Sprint("Light Red"), pterm.BgLightGreen.Sprint("Light Green"), pterm.BgLightYellow.Sprint("Light Yellow")}, {pterm.FgBlue.Sprint("Blue"), pterm.FgMagenta.Sprint("Magenta"), pterm.FgCyan.Sprint("Cyan"), pterm.FgWhite.Sprint("White")}, {pterm.FgLightBlue.Sprint("Light Blue"), pterm.FgLightMagenta.Sprint("Light Magenta"), pterm.FgLightCyan.Sprint("Light Cyan"), pterm.FgLightWhite.Sprint("Light White")}, {pterm.BgBlue.Sprint("Blue"), pterm.BgMagenta.Sprint("Magenta"), pterm.BgCyan.Sprint("Cyan"), pterm.BgWhite.Sprint("White")}, {pterm.BgLightBlue.Sprint("Light Blue"), pterm.BgLightMagenta.Sprint("Light Magenta"), pterm.BgLightCyan.Sprint("Light Cyan"), pterm.BgLightWhite.Sprint("Light White")}, }).Render() // Render the table. pterm.Println() // Print words in different colors. pterm.Println(pterm.Red("Hello, ") + pterm.Green("World") + pterm.Cyan("!")) pterm.Println(pterm.Red("Even " + pterm.Cyan("nested ") + pterm.Green("colors ") + "are supported!")) pterm.Println() // Create a new style with a red background, light green foreground, and bold text. style := pterm.NewStyle(pterm.BgRed, pterm.FgLightGreen, pterm.Bold) // Print text using the created style. style.Println("This text uses a style and is bold and light green with a red background!") } ```
### coloring/disable-output ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/disable-output/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Loop from 0 to 14 for i := 0; i < 15; i++ { switch i { case 5: // At the 5th iteration, print a message and disable the output pterm.Info.Println("Disabled Output!") pterm.DisableOutput() case 10: // At the 10th iteration, enable the output and print a message pterm.EnableOutput() pterm.Info.Println("Enabled Output!") } // Print a progress message for each iteration pterm.Printf("Printing something... [%d/%d]\n", i, 15) } } ```
### coloring/fade-colors ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/fade-colors/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Print an informational message. pterm.Info.Println("RGB colors only work in Terminals which support TrueColor.") // Define the start and end points for the color gradient. startColor := pterm.NewRGB(0, 255, 255) // Cyan endColor := pterm.NewRGB(255, 0, 255) // Magenta // Get the terminal height to determine the gradient range. terminalHeight := pterm.GetTerminalHeight() // Loop over the range of the terminal height to create a color gradient. for i := 0; i < terminalHeight-2; i++ { // Calculate the fade factor for the current step in the gradient. fadeFactor := float32(i) / float32(terminalHeight-2) // Create a color that represents the current step in the gradient. currentColor := startColor.Fade(0, 1, fadeFactor, endColor) // Print a string with the current color. currentColor.Println("Hello, World!") } } ```
### coloring/fade-colors-rgb-style ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/fade-colors-rgb-style/animation.svg)
SHOW SOURCE ```go package main import ( "strings" "github.com/pterm/pterm" ) func main() { // Define RGB colors white := pterm.NewRGB(255, 255, 255) grey := pterm.NewRGB(128, 128, 128) black := pterm.NewRGB(0, 0, 0) red := pterm.NewRGB(255, 0, 0) purple := pterm.NewRGB(255, 0, 255) green := pterm.NewRGB(0, 255, 0) // Define strings to be printed str1 := "RGB colors only work in Terminals which support TrueColor." str2 := "The background and foreground colors can be customized individually." str3 := "Styles can also be applied. For example: Bold or Italic." // Print first string with color fading from white to purple printFadedString(str1, white, purple, grey, black) // Print second string with color fading from purple to red printFadedString(str2, black, purple, red, red) // Print third string with color fading from white to green and style changes printStyledString(str3, white, green, red, black) } // printFadedString prints a string with color fading effect func printFadedString(str string, fgStart, fgEnd, bgStart, bgEnd pterm.RGB) { strs := strings.Split(str, "") var result string for i := 0; i < len(str); i++ { // Create a style with color fading effect style := pterm.NewRGBStyle(fgStart.Fade(0, float32(len(str)), float32(i), fgEnd), bgStart.Fade(0, float32(len(str)), float32(i), bgEnd)) // Append styled letter to result string result += style.Sprint(strs[i]) } pterm.Println(result) } // printStyledString prints a string with color fading and style changes func printStyledString(str string, fgStart, fgEnd, bgStart, bgEnd pterm.RGB) { strs := strings.Split(str, "") var result string boldStr := strings.Split("Bold", "") italicStr := strings.Split("Italic", "") bold, italic := 0, 0 for i := 0; i < len(str); i++ { // Create a style with color fading effect style := pterm.NewRGBStyle(fgStart.Fade(0, float32(len(str)), float32(i), fgEnd), bgStart.Fade(0, float32(len(str)), float32(i), bgEnd)) // Check if the next letters are "Bold" or "Italic" and add the corresponding style if bold < len(boldStr) && i+len(boldStr)-bold <= len(strs) && strings.Join(strs[i:i+len(boldStr)-bold], "") == strings.Join(boldStr[bold:], "") { style = style.AddOptions(pterm.Bold) bold++ } else if italic < len(italicStr) && i+len(italicStr)-italic < len(strs) && strings.Join(strs[i:i+len(italicStr)-italic], "") == strings.Join(italicStr[italic:], "") { style = style.AddOptions(pterm.Italic) italic++ } // Append styled letter to result string result += style.Sprint(strs[i]) } pterm.Println(result) } ```
### coloring/fade-multiple-colors ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/fade-multiple-colors/animation.svg)
SHOW SOURCE ```go package main import ( "strings" "github.com/pterm/pterm" ) func main() { // Define RGB values for gradient points. startColor := pterm.NewRGB(0, 255, 255) firstPoint := pterm.NewRGB(255, 0, 255) secondPoint := pterm.NewRGB(255, 0, 0) thirdPoint := pterm.NewRGB(0, 255, 0) endColor := pterm.NewRGB(255, 255, 255) // Define the string to be printed. str := "RGB colors only work in Terminals which support TrueColor." strs := strings.Split(str, "") // Initialize an empty string for the faded info. var fadeInfo string // Loop over the string length to create a gradient effect. for i := 0; i < len(str); i++ { // Append each character of the string with a faded color to the info string. fadeInfo += startColor.Fade(0, float32(len(str)), float32(i), firstPoint).Sprint(strs[i]) } // Print the info string with gradient effect. pterm.Info.Println(fadeInfo) // Get the terminal height. terminalHeight := pterm.GetTerminalHeight() // Loop over the terminal height to print "Hello, World!" with a gradient effect. for i := 0; i < terminalHeight-2; i++ { // Print the string with a color that fades from startColor to endColor. startColor.Fade(0, float32(terminalHeight-2), float32(i), firstPoint, secondPoint, thirdPoint, endColor).Println("Hello, World!") } } ```
### coloring/override-default-printers ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/override-default-printers/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Print a default error message with PTerm's built-in Error style. pterm.Error.Println("This is the default Error") // Override the default error prefix with a new text and style. pterm.Error.Prefix = pterm.Prefix{Text: "OVERRIDE", Style: pterm.NewStyle(pterm.BgCyan, pterm.FgRed)} // Print the error message again, this time with the overridden prefix. pterm.Error.Println("This is the default Error after the prefix was overridden") } ```
### coloring/print-color-rgb ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/print-color-rgb/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a new RGB color with values 178, 44, 199. // This color will be used for the text. pterm.NewRGB(178, 44, 199).Println("This text is printed with a custom RGB!") // Create a new RGB color with values 15, 199, 209. // This color will be used for the text. pterm.NewRGB(15, 199, 209).Println("This text is printed with a custom RGB!") // Create a new RGB color with values 201, 144, 30. // This color will be used for the background. // The 'true' argument indicates that the color is for the background. pterm.NewRGB(201, 144, 30, true).Println("This text is printed with a custom RGB background!") } ```
### coloring/print-color-rgb-style ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/print-color-rgb-style/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define RGB colors for foreground and background. foregroundRGB := pterm.RGB{R: 187, G: 80, B: 0} backgroundRGB := pterm.RGB{R: 0, G: 50, B: 123} // Create a new RGB style with the defined foreground and background colors. rgbStyle := pterm.NewRGBStyle(foregroundRGB, backgroundRGB) // Print a string with the custom RGB style. rgbStyle.Println("This text is not styled.") // Add the 'Bold' option to the RGB style and print a string with this style. rgbStyle.AddOptions(pterm.Bold).Println("This text is bold.") // Add the 'Italic' option to the RGB style and print a string with this style. rgbStyle.AddOptions(pterm.Italic).Println("This text is italic.") } ```
### demo/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/demo/demo/animation.svg)
SHOW SOURCE ```go package main import ( "flag" "math/rand" "reflect" "strconv" "strings" "time" "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) // Speed the demo up, by setting this flag. // Usefull for debugging. // Example: // // go run main.go -speedup var speedup = flag.Bool("speedup", false, "Speed up the demo") var skipIntro = flag.Bool("skip-intro", false, "Skips the intro") var second = time.Second var pseudoProgramList = strings.Split("pseudo-excel pseudo-photoshop pseudo-chrome pseudo-outlook pseudo-explorer "+ "pseudo-git pseudo-vsc pseudo-intellij pseudo-minecraft pseudo-scoop pseudo-chocolatey", " ") func main() { setup() // Setup the demo (flags etc.) // Show intro if !*skipIntro { introScreen() clear() } showcase("Structured Logging", 5, func() { logger := pterm.DefaultLogger. WithLevel(pterm.LogLevelTrace) logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) time.Sleep(time.Second * 3) interstingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } logger.Debug("This might be interesting", logger.ArgsFromMap(interstingStuff)) time.Sleep(time.Second * 3) logger.Info("That was actually interesting", logger.Args("such", "wow")) time.Sleep(time.Second * 3) logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) time.Sleep(time.Second * 3) logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) time.Sleep(time.Second * 3) logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) }) showcase("Progress bar", 2, func() { pb, _ := pterm.DefaultProgressbar.WithTotal(len(pseudoProgramList)).WithTitle("Installing stuff").Start() for i := 0; i < pb.Total; i++ { pb.UpdateTitle("Installing " + pseudoProgramList[i]) if pseudoProgramList[i] == "pseudo-minecraft" { pterm.Warning.Println("Could not install pseudo-minecraft\nThe company policy forbids games.") } else { pterm.Success.Println("Installing " + pseudoProgramList[i]) } pb.Increment() time.Sleep(second / 2) } pb.Stop() }) showcase("Spinner", 2, func() { list := pseudoProgramList[7:] spinner, _ := pterm.DefaultSpinner.Start("Installing stuff") for i := 0; i < len(list); i++ { spinner.UpdateText("Installing " + list[i]) if list[i] == "pseudo-minecraft" { pterm.Warning.Println("Could not install pseudo-minecraft\nThe company policy forbids games.") } else { pterm.Success.Println("Installing " + list[i]) } time.Sleep(second) } spinner.Success() }) showcase("Live Output", 2, func() { pterm.Info.Println("You can use an Area to display changing output:") pterm.Println() area, _ := pterm.DefaultArea.WithCenter().Start() // Start the Area printer, with the Center option. for i := 0; i < 10; i++ { str, _ := pterm.DefaultBigText.WithLetters(putils.LettersFromString(time.Now().Format("15:04:05"))).Srender() // Save current time in str. area.Update(str) // Update Area contents. time.Sleep(time.Second) } area.Stop() }) showcase("Tables", 4, func() { for i := 0; i < 3; i++ { pterm.Println() } td := [][]string{ {"Library", "Description"}, {"PTerm", "Make beautiful CLIs"}, {"Testza", "Programmer friendly test framework"}, {"Cursor", "Move the cursor around the terminal"}, } table, _ := pterm.DefaultTable.WithHasHeader().WithData(td).Srender() boxedTable, _ := pterm.DefaultTable.WithHasHeader().WithData(td).WithBoxed().Srender() pterm.DefaultCenter.Println(table) pterm.DefaultCenter.Println(boxedTable) }) showcase("TrueColor Support", 7, func() { from := pterm.NewRGB(0, 255, 255) // This RGB value is used as the gradients start point. to := pterm.NewRGB(255, 0, 255) // This RGB value is used as the gradients first point. str := "If your terminal has TrueColor support, you can use RGB colors!\nYou can even fade them :)\n\nLorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet." strs := strings.Split(str, "") var fadeInfo string // String which will be used to print info. // For loop over the range of the string length. for i := 0; i < len(str); i++ { // Append faded letter to info string. fadeInfo += from.Fade(0, float32(len(str)), float32(i), to).Sprint(strs[i]) } pterm.DefaultCenter.WithCenterEachLineSeparately().Println(fadeInfo) }) showcase("Fully Customizable", 2, func() { for i := 0; i < 4; i++ { pterm.Println() } text := "All printers are fully customizable!" area := pterm.DefaultArea.WithCenter() area.Update(pterm.DefaultBox.Sprintln(text)) time.Sleep(second) area.Update(pterm.DefaultBox.WithTopPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleTopLeft().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleTopCenter().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleTopRight().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleBottomRight().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleBottomCenter().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleBottomLeft().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithBoxStyle(pterm.NewStyle(pterm.FgCyan)).Sprintln(text)) time.Sleep(second / 5) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithBoxStyle(pterm.NewStyle(pterm.FgRed)).Sprintln(text)) time.Sleep(second / 5) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithBoxStyle(pterm.NewStyle(pterm.FgGreen)).Sprintln(text)) time.Sleep(second / 5) area.Update(pterm.DefaultBox.WithTopPadding(1). WithBottomPadding(1). WithLeftPadding(1). WithRightPadding(1). WithHorizontalString("═"). WithVerticalString("║"). WithBottomLeftCornerString("╗"). WithBottomRightCornerString("╔"). WithTopLeftCornerString("╝"). WithTopRightCornerString("╚"). Sprintln(text)) area.Stop() }) showcase("Themes", 2, func() { pterm.Info.Println("You can change the color theme of PTerm easily to fit your needs!\nThis is the default one:") time.Sleep(second / 2) // Print every value of the default theme with its own style. v := reflect.ValueOf(pterm.ThemeDefault) typeOfS := v.Type() if typeOfS == reflect.TypeOf(pterm.Theme{}) { for i := 0; i < v.NumField(); i++ { field, ok := v.Field(i).Interface().(pterm.Style) if ok { field.Println(typeOfS.Field(i).Name) } time.Sleep(time.Millisecond * 250) } } }) showcase("And much more!", 3, func() { for i := 0; i < 4; i++ { pterm.Println() } box := pterm.DefaultBox. WithBottomPadding(1). WithTopPadding(1). WithLeftPadding(3). WithRightPadding(3). Sprintf("Have fun exploring %s!", pterm.Cyan("PTerm")) pterm.DefaultCenter.Println(box) }) } func setup() { flag.Parse() if *speedup { second = time.Millisecond * 200 } } func introScreen() { ptermLogo, _ := pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithStyle("P", pterm.NewStyle(pterm.FgLightCyan)), putils.LettersFromStringWithStyle("Term", pterm.NewStyle(pterm.FgLightMagenta))). Srender() pterm.DefaultCenter.Print(ptermLogo) pterm.DefaultCenter.Print(pterm.DefaultHeader.WithFullWidth().WithBackgroundStyle(pterm.NewStyle(pterm.BgLightBlue)).WithMargin(10).Sprint("PTDP - PTerm Demo Program")) pterm.Info.Println("This animation was generated with the latest version of PTerm!" + "\nPTerm works on nearly every terminal and operating system." + "\nIt's super easy to use!" + "\nIf you want, you can customize everything :)" + "\nYou can see the code of this demo in the " + pterm.LightMagenta("./_examples/demo") + " directory." + "\n" + "\nThis demo was updated at: " + pterm.Green(time.Now().Format("02 Jan 2006 - 15:04:05 MST"))) pterm.Println() introSpinner, _ := pterm.DefaultSpinner.WithShowTimer(false).WithRemoveWhenDone(true).Start("Waiting for 15 seconds...") time.Sleep(second) for i := 14; i > 0; i-- { if i > 1 { introSpinner.UpdateText("Waiting for " + strconv.Itoa(i) + " seconds...") } else { introSpinner.UpdateText("Waiting for " + strconv.Itoa(i) + " second...") } time.Sleep(second) } introSpinner.Stop() } func clear() { print("\033[H\033[2J") } func showcase(title string, seconds int, content func()) { pterm.DefaultHeader.WithBackgroundStyle(pterm.NewStyle(pterm.BgLightBlue)).WithFullWidth().Println(title) pterm.Println() time.Sleep(second / 2) content() time.Sleep(second * time.Duration(seconds)) print("\033[H\033[2J") } func randomInt(min, max int) int { rand.Seed(time.Now().UnixNano()) return rand.Intn(max-min+1) + min } ```
### header/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/header/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Print a default header. // This uses the default settings of PTerm to print a header. pterm.DefaultHeader.Println("This is the default header!") // Print a spacer line for better readability. pterm.Println() // Print a full-width header. // This uses the WithFullWidth() option of PTerm to print a header that spans the full width of the terminal. pterm.DefaultHeader.WithFullWidth().Println("This is a full-width header.") } ```
### header/custom ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/header/custom/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Customize the DefaultHeader with a cyan background, black text, and a margin of 15. pterm.DefaultHeader.WithMargin(15).WithBackgroundStyle(pterm.NewStyle(pterm.BgCyan)).WithTextStyle(pterm.NewStyle(pterm.FgBlack)).Println("This is a custom header!") // Define a new HeaderPrinter with a red background, black text, and a margin of 20. newHeader := pterm.HeaderPrinter{ TextStyle: pterm.NewStyle(pterm.FgBlack), BackgroundStyle: pterm.NewStyle(pterm.BgRed), Margin: 20, } // Print the custom header using the new HeaderPrinter. newHeader.Println("This is a custom header!") } ```
### heatmap/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/heatmap/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap. Each sub-array represents a row in the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the labels for the X and Y axes of the heatmap. headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Create a heatmap with the defined data and axis labels, and enable RGB colors. // Then render the heatmap. pterm.DefaultHeatmap.WithAxisData(headerData).WithData(data).WithEnableRGB().Render() } ```
### heatmap/custom_colors ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/heatmap/custom_colors/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis labels for the heatmap headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message pterm.Info.Println("The following table has no rgb (supported by every terminal), no axis data and a legend.") pterm.Println() // Create the heatmap with the defined data and options, and render it pterm.DefaultHeatmap. WithData(data). WithBoxed(false). WithAxisData(headerData). WithLegend(false). WithColors(pterm.BgBlue, pterm.BgRed, pterm.BgGreen, pterm.BgYellow). WithLegend(). Render() } ```
### heatmap/custom_legend ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/heatmap/custom_legend/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the header data for the heatmap headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message pterm.Info.Println("The following table has rgb (not supported by every terminal), axis data and a custom legend.") pterm.Println() // Create the heatmap with the defined data and options // Options are chained in a single line for simplicity pterm.DefaultHeatmap. WithData(data). WithBoxed(false). WithAxisData(headerData). WithEnableRGB(). WithLegendLabel("custom"). WithLegendOnlyColoredCells(). Render() // Render the heatmap } ```
### heatmap/custom_rgb ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/heatmap/custom_rgb/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis labels for the heatmap. axisLabels := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message. pterm.Info.Println("The following table has rgb (not supported by every terminal), axis data and a legend.") pterm.Println() // Define the color range for the heatmap. rgbRange := []pterm.RGB{ pterm.NewRGB(0, 0, 255), pterm.NewRGB(255, 0, 0), pterm.NewRGB(0, 255, 0), pterm.NewRGB(255, 255, 0), } // Create and render the heatmap. pterm.DefaultHeatmap. WithData(data). WithBoxed(false). WithAxisData(axisLabels). WithEnableRGB(). WithRGBRange(rgbRange...). Render() } ```
### heatmap/no_grid ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/heatmap/no_grid/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis data for the heatmap. axisData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message. pterm.Info.Println("The following table has rgb (not supported by every terminal), axis data and a legend.") pterm.Println() // Create the heatmap with the defined data and options, then render it. pterm.DefaultHeatmap.WithData(data).WithBoxed(false).WithAxisData(axisData).WithEnableRGB().WithLegend().WithGrid(false).Render() } ```
### heatmap/separated ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/heatmap/separated/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis labels for the heatmap. headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message. pterm.Info.Println("The following table has no rgb (supported by every terminal), no axis data and no legend.") pterm.Println() // Create the heatmap with the specified data and options, and render it. pterm.DefaultHeatmap.WithData(data).WithBoxed(false).WithAxisData(headerData).WithLegend(false).Render() } ```
### interactive_confirm/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_confirm/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Show an interactive confirmation dialog and get the result. result, _ := pterm.DefaultInteractiveConfirm.Show() // Print a blank line for better readability. pterm.Println() // Print the user's answer in a formatted way. pterm.Info.Printfln("You answered: %s", boolToText(result)) } // boolToText converts a boolean value to a colored text. // If the value is true, it returns a green "Yes". // If the value is false, it returns a red "No". func boolToText(b bool) string { if b { return pterm.Green("Yes") } return pterm.Red("No") } ```
### interactive_continue/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_continue/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Create an interactive continue prompt with default settings // This will pause the program execution until the user presses enter // The message displayed is "Press 'Enter' to continue..." prompt := pterm.DefaultInteractiveContinue // Show the prompt and wait for user input // The returned result is the user's input (should be empty as it's a continue prompt) // The second return value is an error which is ignored here result, _ := prompt.Show() // Print a blank line for better readability pterm.Println() // Print the user's input with an info prefix // As this is a continue prompt, the input should be empty pterm.Info.Printfln("You answered: %s", result) } ```
### interactive_multiselect/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_multiselect/demo/animation.svg)
SHOW SOURCE ```go package main import ( "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options. var options []string // Populate the options slice with 100 options. for i := 0; i < 100; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Add 5 more options to the slice, indicating the availability of fuzzy searching. for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("You can use fuzzy searching (%d)", i)) } // Use PTerm's interactive multiselect to present the options to the user and capture their selections. // The Show() method displays the options and waits for user input. selectedOptions, _ := pterm.DefaultInteractiveMultiselect.WithOptions(options).Show() // Print the selected options, highlighted in green. pterm.Info.Printfln("Selected options: %s", pterm.Green(selectedOptions)) } ```
### interactive_multiselect/custom-checkmarks ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_multiselect/custom-checkmarks/animation.svg)
SHOW SOURCE ```go package main import ( "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options var options []string // Populate the options slice with 5 options for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Create a new interactive multiselect printer with the options // Disable the filter and define the checkmark symbols printer := pterm.DefaultInteractiveMultiselect. WithOptions(options). WithFilter(false). WithCheckmark(&pterm.Checkmark{Checked: pterm.Green("+"), Unchecked: pterm.Red("-")}) // Show the interactive multiselect and get the selected options selectedOptions, _ := printer.Show() // Print the selected options pterm.Info.Printfln("Selected options: %s", pterm.Green(selectedOptions)) } ```
### interactive_multiselect/custom-keys ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_multiselect/custom-keys/animation.svg)
SHOW SOURCE ```go package main import ( "atomicgo.dev/keyboard/keys" "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options var options []string // Populate the options slice with 5 options for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Create a new interactive multiselect printer with the options // Disable the filter and set the keys for confirming and selecting options printer := pterm.DefaultInteractiveMultiselect. WithOptions(options). WithFilter(false). WithKeyConfirm(keys.Enter). WithKeySelect(keys.Space) // Show the interactive multiselect and get the selected options selectedOptions, _ := printer.Show() // Print the selected options pterm.Info.Printfln("Selected options: %s", pterm.Green(selectedOptions)) } ```
### interactive_select/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_select/demo/animation.svg)
SHOW SOURCE ```go package main import ( "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options var options []string // Generate 100 options and add them to the options slice for i := 0; i < 100; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Generate 5 additional options with a specific message and add them to the options slice for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("You can use fuzzy searching (%d)", i)) } // Use PTerm's interactive select feature to present the options to the user and capture their selection // The Show() method displays the options and waits for the user's input selectedOption, _ := pterm.DefaultInteractiveSelect.WithOptions(options).Show() // Display the selected option to the user with a green color for emphasis pterm.Info.Printfln("Selected option: %s", pterm.Green(selectedOption)) } ```
### interactive_textinput/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_textinput/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Create an interactive text input with single line input mode and show it result, _ := pterm.DefaultInteractiveTextInput.Show() // Print a blank line for better readability pterm.Println() // Print the user's answer with an info prefix pterm.Info.Printfln("You answered: %s", result) } ```
### interactive_textinput/default-value ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_textinput/default-value/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Create an interactive text input with single line input mode and show it result, _ := pterm.DefaultInteractiveTextInput.WithDefaultValue("Some default value").Show() // Print a blank line for better readability pterm.Println() // Print the user's answer with an info prefix pterm.Info.Printfln("You answered: %s", result) } ```
### interactive_textinput/multi-line ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_textinput/multi-line/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Create a default interactive text input with multi-line enabled. // This allows the user to input multiple lines of text. textInput := pterm.DefaultInteractiveTextInput.WithMultiLine() // Show the text input to the user and store the result. // The second return value (an error) is ignored with '_'. result, _ := textInput.Show() // Print a blank line for better readability in the output. pterm.Println() // Print the user's input prefixed with an informational message. // The '%s' placeholder is replaced with the user's input. pterm.Info.Printfln("You answered: %s", result) } ```
### interactive_textinput/password ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_textinput/password/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create an interactive text input with a mask for password input passwordInput := pterm.DefaultInteractiveTextInput.WithMask("*") // Show the password input prompt and store the result result, _ := passwordInput.Show("Enter your password") // Get the default logger from PTerm logger := pterm.DefaultLogger // Log the received password (masked) // Note: In a real-world application, you should never log passwords logger.Info("Password received", logger.Args("password", result)) } ```
### logger/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/logger/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "time" ) func main() { // Create a logger with trace level logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace) // Log a trace level message logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Pause for 3 seconds sleep() // Define a map with interesting stuff interstingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a debug level message with arguments from the map logger.Debug("This might be interesting", logger.ArgsFromMap(interstingStuff)) // Pause for 3 seconds sleep() // Log an info level message logger.Info("That was actually interesting", logger.Args("such", "wow")) // Pause for 3 seconds sleep() // Log a warning level message logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) // Pause for 3 seconds sleep() // Log an error level message logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) // Pause for 3 seconds sleep() // Log an info level message with a long text that will be automatically wrapped logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) // Pause for 3 seconds sleep() // Log a fatal level message logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } // Function to pause the execution for 3 seconds func sleep() { time.Sleep(time.Second * 3) } ```
### logger/custom-key-styles ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/logger/custom-key-styles/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a logger with a level of Trace or higher. logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace) // Define a new style for the "priority" key. priorityStyle := map[string]pterm.Style{ "priority": *pterm.NewStyle(pterm.FgRed), } // Overwrite all key styles with the new map. logger = logger.WithKeyStyles(priorityStyle) // Log an info message. The "priority" key will be displayed in red. logger.Info("The priority key should now be red", logger.Args("priority", "low", "foo", "bar")) // Define a new style for the "foo" key. fooStyle := *pterm.NewStyle(pterm.FgBlue) // Append the new style to the existing ones. logger.AppendKeyStyle("foo", fooStyle) // Log another info message. The "foo" key will be displayed in blue. logger.Info("The foo key should now be blue", logger.Args("priority", "low", "foo", "bar")) } ```
### logger/default ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/logger/default/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "time" ) func main() { // Create a logger with a level of Trace or higher. logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace) // Log a trace message with additional arguments. logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Create a map of interesting stuff. interstingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a debug message with arguments from a map. logger.Debug("This might be interesting", logger.ArgsFromMap(interstingStuff)) // Log an info message with additional arguments. logger.Info("That was actually interesting", logger.Args("such", "wow")) // Log a warning message with additional arguments. logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) // Log an error message with additional arguments. logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) // Log an info message with additional arguments. PTerm will automatically wrap long logs. logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) // Pause for 2 seconds. time.Sleep(time.Second * 2) // Log a fatal message with additional arguments. This will terminate the process. logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } ```
### logger/json ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/logger/json/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a logger with Trace level and JSON formatter logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace).WithFormatter(pterm.LogFormatterJSON) // Log a Trace level message with additional arguments logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Create a map of interesting stuff interestingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a Debug level message with arguments from the map logger.Debug("This might be interesting", logger.ArgsFromMap(interestingStuff)) // Log Info, Warn, Error, and Fatal level messages with additional arguments logger.Info("That was actually interesting", logger.Args("such", "wow")) logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } ```
### logger/with-caller ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/logger/with-caller/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a logger with Trace level and caller information logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace).WithCaller() // Log a trace message with additional arguments logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Create a map of interesting stuff interestingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a debug message with arguments from a map logger.Debug("This might be interesting", logger.ArgsFromMap(interestingStuff)) // Log an info message with additional arguments logger.Info("That was actually interesting", logger.Args("such", "wow")) // Log a warning message with additional arguments logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) // Log an error message with additional arguments logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) // Log an info message with additional arguments. PTerm will automatically wrap long logs. logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) // Log a fatal message with additional arguments. This will terminate the process. logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } ```
### multiple-live-printers/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/multiple-live-printers/demo/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create a multi printer for managing multiple printers multi := pterm.DefaultMultiPrinter // Create two spinners with their own writers spinner1, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 1") spinner2, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 2") // Create five progress bars with their own writers and a total of 100 pb1, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 1") pb2, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 2") pb3, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 3") pb4, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 4") pb5, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 5") // Start the multi printer multi.Start() // Increment progress bars and spinners based on certain conditions for i := 1; i <= 100; i++ { pb1.Increment() // Increment progress bar 1 every iteration if i%2 == 0 { pb2.Add(3) // Add 3 to progress bar 2 every even iteration } if i%5 == 0 { pb3.Increment() // Increment progress bar 3 every 5th iteration } if i%10 == 0 { pb4.Increment() // Increment progress bar 4 every 10th iteration } if i%3 == 0 { pb5.Increment() // Increment progress bar 5 every 3rd iteration } if i%50 == 0 { spinner1.Success("Spinner 1 is done!") // Mark spinner 1 as successful every 50th iteration } if i%60 == 0 { spinner2.Fail("Spinner 2 failed!") // Mark spinner 2 as failed every 60th iteration } time.Sleep(time.Millisecond * 50) // Sleep for 50 milliseconds between each iteration } // Stop the multi printer multi.Stop() } ```
### panel/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/panel/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define panels in a 2D grid system panels := pterm.Panels{ { {Data: "This is the first panel"}, {Data: pterm.DefaultHeader.Sprint("Hello, World!")}, {Data: "This\npanel\ncontains\nmultiple\nlines"}, }, { {Data: pterm.Red("This is another\npanel line")}, {Data: "This is the second panel\nwith a new line"}, }, } // Render the panels with a padding of 5 _ = pterm.DefaultPanel.WithPanels(panels).WithPadding(5).Render() } ```
### paragraph/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/paragraph/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Using the default paragraph printer to print a long text. // The text is split at the spaces, which is useful for continuous text of all kinds. // The line width can be manually adjusted if needed. pterm.DefaultParagraph.Println("This is the default paragraph printer. As you can see, no words are separated, " + "but the text is split at the spaces. This is useful for continuous text of all kinds. You can manually change the line width if you want to." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam") // Printing a line space for separation. pterm.Println() // Printing a long text without using the paragraph printer. // The default Println() function is used here, which does not provide intelligent splitting. pterm.Println("This text is written with the default Println() function. No intelligent splitting here." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam") } ```
### paragraph/customized ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/paragraph/customized/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define a long text to be printed as a paragraph. longText := "This is a custom paragraph printer. As you can see, no words are separated, " + "but the text is split at the spaces. This is useful for continuous text of all kinds. You can manually change the line width if you want to." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam" // Print the long text as a paragraph with a custom maximal width of 60 characters. pterm.DefaultParagraph.WithMaxWidth(60).Println(longText) // Print a line space to separate the paragraph from the following text. pterm.Println() // Define another long text to be printed without a paragraph printer. longTextWithoutParagraph := "This text is written with the default Println() function. No intelligent splitting here." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam" // Print the long text without using a paragraph printer. pterm.Println(longTextWithoutParagraph) } ```
### prefix/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/prefix/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Enable debug messages in PTerm. pterm.EnableDebugMessages() // Print a debug message with PTerm. pterm.Debug.Println("Hello, World!") // Print an informational message with PTerm. pterm.Info.Println("Hello, World!") // Print a success message with PTerm. pterm.Success.Println("Hello, World!") // Print a warning message with PTerm. pterm.Warning.Println("Hello, World!") // Print an error message with PTerm. This will also display the filename and line number in the terminal. pterm.Error.Println("Errors show the filename and linenumber inside the terminal!") // Print an informational message with PTerm, with line number. // This demonstrates that other PrefixPrinters can also display line numbers. pterm.Info.WithShowLineNumber().Println("Other PrefixPrinters can do that too!") // Temporarily set Fatal to false, so that the CI won't crash. // This will print a fatal message with PTerm, but won't terminate the program. pterm.Fatal.WithFatal(false).Println("Hello, World!") } ```
### progressbar/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/progressbar/demo/animation.svg)
SHOW SOURCE ```go package main import ( "strings" "time" "github.com/pterm/pterm" ) // Slice of strings representing names of pseudo applications to be downloaded. var fakeInstallList = strings.Split("pseudo-excel pseudo-photoshop pseudo-chrome pseudo-outlook pseudo-explorer "+ "pseudo-dops pseudo-git pseudo-vsc pseudo-intellij pseudo-minecraft pseudo-scoop pseudo-chocolatey", " ") func main() { // Create a progressbar with the total steps equal to the number of items in fakeInstallList. // Set the initial title of the progressbar to "Downloading stuff". p, _ := pterm.DefaultProgressbar.WithTotal(len(fakeInstallList)).WithTitle("Downloading stuff").Start() // Loop over each item in the fakeInstallList. for i := 0; i < p.Total; i++ { // Simulate a slow download for the 7th item. if i == 6 { time.Sleep(time.Second * 3) } // Update the title of the progressbar with the current item being downloaded. p.UpdateTitle("Downloading " + fakeInstallList[i]) // Print a success message for the current download. This will be printed above the progressbar. pterm.Success.Println("Downloading " + fakeInstallList[i]) // Increment the progressbar by one to indicate progress. p.Increment() // Pause for 350 milliseconds to simulate the time taken for each download. time.Sleep(time.Millisecond * 350) } } ```
### progressbar/multiple ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/progressbar/multiple/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create a multi printer instance from the default one multi := pterm.DefaultMultiPrinter // Create five progress bars with a total of 100 units each, and assign each a new writer from the multi printer pb1, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 1") pb2, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 2") pb3, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 3") pb4, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 4") pb5, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 5") // Start the multi printer multi.Start() // Loop to increment progress bars based on certain conditions for i := 1; i <= 100; i++ { pb1.Increment() // Increment the first progress bar at each iteration if i%2 == 0 { pb2.Add(3) // Add 3 units to the second progress bar at every even iteration } if i%5 == 0 { pb3.Increment() // Increment the third progress bar at every fifth iteration } if i%10 == 0 { pb4.Increment() // Increment the fourth progress bar at every tenth iteration } if i%3 == 0 { pb5.Increment() // Increment the fifth progress bar at every third iteration } time.Sleep(time.Millisecond * 50) // Pause for 50 milliseconds at each iteration } // Stop the multi printer multi.Stop() } ```
### section/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/section/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a section with level one and print it. pterm.DefaultSection.Println("This is a section!") // Print an informational message. pterm.Info.Println("And here is some text.\nThis text could be anything.\nBasically it's just a placeholder") // Create a section with level two and print it. pterm.DefaultSection.WithLevel(2).Println("This is another section!") // Print another informational message. pterm.Info.Println("And this is\nmore placeholder text") } ```
### slog/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/slog/demo/animation.svg)
SHOW SOURCE ```go package main import ( "log/slog" "github.com/pterm/pterm" ) func main() { // Create a new slog handler with the default PTerm logger handler := pterm.NewSlogHandler(&pterm.DefaultLogger) // Create a new slog logger with the handler logger := slog.New(handler) // Log a debug message (won't show by default) logger.Debug("This is a debug message that won't show") // Change the log level to debug to enable debug messages pterm.DefaultLogger.Level = pterm.LogLevelDebug // Log a debug message (will show because debug level is enabled) logger.Debug("This is a debug message", "changedLevel", true) // Log an info message logger.Info("This is an info message") // Log a warning message logger.Warn("This is a warning message") // Log an error message logger.Error("This is an error message") } ```
### spinner/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/spinner/demo/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create and start a fork of the default spinner. spinnerInfo, _ := pterm.DefaultSpinner.Start("Some informational action...") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerInfo.Info() // Resolve spinner with error message. // Create and start a fork of the default spinner. spinnerSuccess, _ := pterm.DefaultSpinner.Start("Doing something important... (will succeed)") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerSuccess.Success() // Resolve spinner with success message. // Create and start a fork of the default spinner. spinnerWarning, _ := pterm.DefaultSpinner.Start("Doing something important... (will warn)") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerWarning.Warning() // Resolve spinner with warning message. // Create and start a fork of the default spinner. spinnerFail, _ := pterm.DefaultSpinner.Start("Doing something important... (will fail)") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerFail.Fail() // Resolve spinner with error message. // Create and start a fork of the default spinner. spinnerNochange, _ := pterm.DefaultSpinner.Start("Checking something important... (will result in no change)") // Replace the InfoPrinter with a custom "NOCHG" one spinnerNochange.InfoPrinter = &pterm.PrefixPrinter{ MessageStyle: &pterm.Style{pterm.FgLightBlue}, Prefix: pterm.Prefix{ Style: &pterm.Style{pterm.FgBlack, pterm.BgLightBlue}, Text: " NOCHG ", }, } time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerNochange.Info("No change were required") // Resolve spinner with error message. // Create and start a fork of the default spinner. spinnerLiveText, _ := pterm.DefaultSpinner.Start("Doing a lot of stuff...") time.Sleep(time.Second) // Simulate 2 seconds of processing something. spinnerLiveText.UpdateText("It's really much") // Update spinner text. time.Sleep(time.Second) // Simulate 2 seconds of processing something. spinnerLiveText.UpdateText("We're nearly done!") // Update spinner text. time.Sleep(time.Second) // Simulate 2 seconds of processing something. spinnerLiveText.Success("Finally!") // Resolve spinner with success message. } ```
### spinner/multiple ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/spinner/multiple/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create a multi printer. This allows multiple spinners to print simultaneously. multi := pterm.DefaultMultiPrinter // Create and start spinner 1 with a new writer from the multi printer. // The spinner will display the message "Spinner 1". spinner1, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 1") // Create and start spinner 2 with a new writer from the multi printer. // The spinner will display the message "Spinner 2". spinner2, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 2") // Create and start spinner 3 with a new writer from the multi printer. // The spinner will display the message "Spinner 3". spinner3, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 3") // Start the multi printer. This will start printing all the spinners. multi.Start() // Wait for 1 second. time.Sleep(time.Millisecond * 1000) // Stop spinner 1 with a success message. spinner1.Success("Spinner 1 is done!") // Wait for 750 milliseconds. time.Sleep(time.Millisecond * 750) // Stop spinner 2 with a failure message. spinner2.Fail("Spinner 2 failed!") // Wait for 500 milliseconds. time.Sleep(time.Millisecond * 500) // Stop spinner 3 with a warning message. spinner3.Warning("Spinner 3 has a warning!") // Stop the multi printer. This will stop printing all the spinners. multi.Stop() } ```
### style/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/style/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define a primary style with light cyan foreground, gray background, and bold text primary := pterm.NewStyle(pterm.FgLightCyan, pterm.BgGray, pterm.Bold) // Define a secondary style with light green foreground, white background, and italic text secondary := pterm.NewStyle(pterm.FgLightGreen, pterm.BgWhite, pterm.Italic) // Print "Hello, World!" with the primary style primary.Println("Hello, World!") // Print "Hello, World!" with the secondary style secondary.Println("Hello, World!") } ```
### table/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/table/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the first table tableData1 := pterm.TableData{ {"Firstname", "Lastname", "Email", "Note"}, {"Paul", "Dean", "augue@velitAliquam.co.uk", ""}, {"Callie", "Mckay", "nunc.sed@est.com", "这是一个测试, haha!"}, {"Libby", "Camacho", "lobortis@semper.com", "just a test, hey!"}, {"张", "小宝", "zhang@example.com", ""}, } // Create a table with a header and the defined data, then render it pterm.DefaultTable.WithHasHeader().WithData(tableData1).Render() pterm.Println() // Blank line // Define the data for the second table tableData2 := pterm.TableData{ {"Firstname", "Lastname", "Email"}, {"Paul\n\nNewline", "Dean", "augue@velitAliquam.co.uk"}, {"Callie", "Mckay", "nunc.sed@est.com\nNewline"}, {"Libby", "Camacho", "lobortis@semper.com"}, {"张", "小宝", "zhang@example.com"}, } // Create another table with a header and the defined data, then render it pterm.DefaultTable.WithHasHeader().WithData(tableData2).Render() } ```
### table/boxed ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/table/boxed/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the table. // Each inner slice represents a row in the table. // The first row is considered as the header of the table. tableData := pterm.TableData{ {"Firstname", "Lastname", "Email", "Note"}, {"Paul", "Dean", "augue@velitAliquam.co.uk", ""}, {"Callie", "Mckay", "nunc.sed@est.com", "这是一个测试, haha!"}, {"Libby", "Camacho", "lobortis@semper.com", "just a test, hey!"}, {"张", "小宝", "zhang@example.com", ""}, } // Create a table with the defined data. // The table has a header and is boxed. // Finally, render the table to print it. pterm.DefaultTable.WithHasHeader().WithBoxed().WithData(tableData).Render() } ```
### table/multiple-lines ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/table/multiple-lines/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the table. data := pterm.TableData{ {"Firstname", "Lastname", "Email"}, {"Paul\n\nNewline", "Dean", "augue@velitAliquam.co.uk"}, {"Callie", "Mckay", "nunc.sed@est.com\nNewline"}, {"Libby", "Camacho", "lobortis@semper.com"}, {"张", "小宝", "zhang@example.com"}, } // Create and render the table. // The options are chained in a single line for simplicity. // The table has a header, a row separator, and a header row separator. pterm.DefaultTable.WithHasHeader().WithRowSeparator("-").WithHeaderRowSeparator("-").WithData(data).Render() } ```
### table/right-alignment ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/table/right-alignment/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the table. // Each inner slice represents a row in the table. // The first row is considered as the header. tableData := pterm.TableData{ {"Firstname", "Lastname", "Email", "Note"}, {"Paul", "Dean", "augue@velitAliquam.co.uk", ""}, {"Callie", "Mckay", "nunc.sed@est.com", "这是一个测试, haha!"}, {"Libby", "Camacho", "lobortis@semper.com", "just a test, hey!"}, {"张", "小宝", "zhang@example.com", ""}, } // Create a table with the defined data. // The table has a header and the text in the cells is right-aligned. // The Render() method is used to print the table to the console. pterm.DefaultTable.WithHasHeader().WithRightAlignment().WithData(tableData).Render() } ```
### theme/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/theme/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "reflect" "time" ) func main() { // Print an informational message about the default theme styles. pterm.Info.Println("These are the default theme styles.\nYou can modify them easily to your personal preference,\nor create new themes from scratch :)") // Print a blank line for better readability. pterm.Println() // Get the value and type of the default theme. v := reflect.ValueOf(pterm.ThemeDefault) typeOfS := v.Type() // Check if the type of the default theme is 'pterm.Theme'. if typeOfS == reflect.TypeOf(pterm.Theme{}) { // Iterate over each field in the default theme. for i := 0; i < v.NumField(); i++ { // Try to convert the field to 'pterm.Style'. field, ok := v.Field(i).Interface().(pterm.Style) if ok { // Print the field name using its own style. field.Println(typeOfS.Field(i).Name) } // Pause for a quarter of a second to make the output easier to read. time.Sleep(time.Millisecond * 250) } } } ```
### tree/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/tree/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define a tree structure using pterm.TreeNode tree := pterm.TreeNode{ // The top node of the tree Text: "Top node", // The children of the top node Children: []pterm.TreeNode{{ // A child node Text: "Child node", // The children of the child node Children: []pterm.TreeNode{ // Grandchildren nodes {Text: "Grandchild node"}, {Text: "Grandchild node"}, {Text: "Grandchild node"}, }, }}, } // Render the tree with the defined structure as the root pterm.DefaultTree.WithRoot(tree).Render() } ```
### tree/from-leveled-list ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/tree/from-leveled-list/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Define a leveled list to represent the structure of the directories. leveledList := pterm.LeveledList{ {Level: 0, Text: "C:"}, {Level: 1, Text: "Users"}, {Level: 1, Text: "Windows"}, {Level: 1, Text: "Programs"}, {Level: 1, Text: "Programs(x86)"}, {Level: 1, Text: "dev"}, {Level: 0, Text: "D:"}, {Level: 0, Text: "E:"}, {Level: 1, Text: "Movies"}, {Level: 1, Text: "Music"}, {Level: 2, Text: "LinkinPark"}, {Level: 1, Text: "Games"}, {Level: 2, Text: "Shooter"}, {Level: 3, Text: "CallOfDuty"}, {Level: 3, Text: "CS:GO"}, {Level: 3, Text: "Battlefield"}, {Level: 4, Text: "Battlefield 1"}, {Level: 4, Text: "Battlefield 2"}, {Level: 0, Text: "F:"}, {Level: 1, Text: "dev"}, {Level: 2, Text: "dops"}, {Level: 2, Text: "PTerm"}, } // Convert the leveled list into a tree structure. root := putils.TreeFromLeveledList(leveledList) root.Text = "Computer" // Set the root node text. // Render the tree structure using the default tree printer. pterm.DefaultTree.WithRoot(root).Render() } ```
--- > GitHub [@pterm](https://github.com/pterm)  ·  > Author [@MarvinJWendt](https://github.com/MarvinJWendt) > | [PTerm.sh](https://pterm.sh) golang-github-pterm-pterm-0.12.79/SECURITY.md000066400000000000000000000027201465010626300204700ustar00rootroot00000000000000# PTerm Security Policy This security policy applies to the PTerm GitHub repository and outlines the process for reporting security issues and handling security incidents. The primary goal of this policy is to ensure the safety and integrity of the PTerm codebase and to minimize the impact of security incidents on our users. ## 1. Overview PTerm is a command-line interface (CLI) tool library, and we believe the security risks associated with it are minimal. However, we recognize that vulnerabilities can still arise, and we are committed to addressing them promptly and transparently. ## 2. Reporting Security Issues If you discover a security issue in PTerm, please follow these steps: Open a new issue in the PTerm GitHub repository, describing the security problem in detail. ## 3. Vulnerable Dependencies If a dependency of PTerm is found to be vulnerable or infected and requires immediate updates, please follow these steps: 1. Open a new issue in the PTerm GitHub repository, describing the vulnerable dependency and the need for an update. 2. *Optional: Contact @MarvinJWendt directly via Twitter or Discord to alert them to the issue.* ## 4. Incident Response Upon receiving a security report, the PTerm team will: 1. Acknowledge receipt of the report and review the issue. 2. Investigate the issue and determine the severity and impact. 3. Develop and implement a fix or mitigation plan, as necessary. 4. Update the PTerm repository and notify users, if applicable. golang-github-pterm-pterm-0.12.79/_examples/000077500000000000000000000000001465010626300206535ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/README.md000066400000000000000000003017351465010626300221430ustar00rootroot00000000000000# PTerm Examples > This directory contains examples of using the PTerm library. ### area/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/area/demo/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Print an informational message using PTerm's Info printer. // This message will stay in place while the area updates. pterm.Info.Println("The previous text will stay in place, while the area updates.") // Print two new lines as spacer. pterm.Print("\n\n") // Start the Area printer from PTerm's DefaultArea, with the Center option. // The Area printer allows us to update a specific area of the console output. // The returned 'area' object is used to control the area updates. area, _ := pterm.DefaultArea.WithCenter().Start() // Loop 10 times to update the area with the current time. for i := 0; i < 10; i++ { // Get the current time, format it as "15:04:05" (hour:minute:second), and convert it to a string. // Then, create a BigText from the time string using PTerm's DefaultBigText and putils NewLettersFromString. // The Srender() function is used to save the BigText as a string. str, _ := pterm.DefaultBigText.WithLetters(putils.LettersFromString(time.Now().Format("15:04:05"))).Srender() // Update the Area contents with the current time string. area.Update(str) // Sleep for a second before the next update. time.Sleep(time.Second) } // Stop the Area printer after all updates are done. area.Stop() } ```
### area/center ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/area/center/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new default area in the center of the terminal. // The Start() function returns the created area and an error. area, _ := pterm.DefaultArea.WithCenter().Start() // Loop 5 times to simulate a dynamic update. for i := 0; i < 5; i++ { // Update the content of the area with the current count. // The Sprintf function is used to format the string. area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second to simulate a time-consuming task. time.Sleep(time.Second) } // Stop the area after all updates are done. area.Stop() } ```
### area/default ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/area/default/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new default area and get a reference to it. // The second return value is an error which is ignored here. area, _ := pterm.DefaultArea.Start() // Loop 5 times for i := 0; i < 5; i++ { // Update the content of the area dynamically. // Here we're just displaying the current count. area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second before the next update. time.Sleep(time.Second) } // Stop the area after all updates are done. // This will clean up and free resources used by the area. area.Stop() } ```
### area/dynamic-chart ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/area/dynamic-chart/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new fullscreen centered area. // This area will be used to display the bar chart. area, _ := pterm.DefaultArea.WithFullscreen().WithCenter().Start() // Ensure the area stops updating when we're done. defer area.Stop() // Loop to update the bar chart 10 times. for i := 0; i < 10; i++ { // Create a new bar chart with dynamic bars. // The bars will change based on the current iteration. barchart := pterm.DefaultBarChart.WithBars(dynamicBars(i)) // Render the bar chart to a string. // This string will be used to update the area. content, _ := barchart.Srender() // Update the area with the new bar chart. area.Update(content) // Wait for half a second before the next update. time.Sleep(500 * time.Millisecond) } } // dynamicBars generates a set of bars for the bar chart. // The bars will change based on the current iteration. func dynamicBars(i int) pterm.Bars { return pterm.Bars{ {Label: "A", Value: 10}, // A static bar. {Label: "B", Value: 20 * i}, // A bar that grows with each iteration. {Label: "C", Value: 30}, // Another static bar. {Label: "D", Value: 40 + i}, // A bar that grows slowly with each iteration. } } ```
### area/fullscreen ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/area/fullscreen/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new fullscreen area. This will return an area instance and an error. // The underscore (_) is used to ignore the error. area, _ := pterm.DefaultArea.WithFullscreen().Start() // Loop 5 times to update the area content. for i := 0; i < 5; i++ { // Update the content of the area with the current count. // The Sprintf function is used to format the string. area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second before the next update. time.Sleep(time.Second) } // Stop the area after all updates are done. area.Stop() } ```
### area/fullscreen-center ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/area/fullscreen-center/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Initialize a new PTerm area with fullscreen and center options // The Start() function returns the created area and an error (ignored here) area, _ := pterm.DefaultArea.WithFullscreen().WithCenter().Start() // Loop 5 times to demonstrate dynamic content update for i := 0; i < 5; i++ { // Update the content of the area with the current count // The Sprintf function is used to format the string with the count area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second time.Sleep(time.Second) } // Stop the area after all updates are done // This will clear the area and return the terminal to its normal state area.Stop() } ```
### barchart/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the bars for the chart bars := []pterm.Bar{ {Label: "Bar 1", Value: 5}, {Label: "Bar 2", Value: 3}, {Label: "Longer Label", Value: 7}, } // Print an informational message pterm.Info.Println("Chart example with positive only values (bars use 100% of chart area)") // Create a bar chart with the defined bars and render it // The DefaultBarChart is used as a base, and the bars are added with the WithBars option // The Render function is then called to display the chart pterm.DefaultBarChart.WithBars(bars).Render() // Create a horizontal bar chart with the defined bars and render it // The DefaultBarChart is used as a base, the chart is made horizontal with the WithHorizontal option, and the bars are added with the WithBars option // The Render function is then called to display the chart pterm.DefaultBarChart.WithHorizontal().WithBars(bars).Render() } ```
### barchart/custom-height ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/custom-height/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define a slice of Bar structs. Each struct represents a bar in the chart. // The Label field is the name of the bar and the Value field is the height of the bar. bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create and render a bar chart with the defined bars and a height of 5. // The WithBars method is used to set the bars of the chart. // The WithHeight method is used to set the height of the chart. // The Render method is used to display the chart in the terminal. pterm.DefaultBarChart.WithBars(bars).WithHeight(5).Render() } ```
### barchart/custom-width ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/custom-width/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart barData := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined data // The chart is horizontal and has a width of 5 // The Render() function is called to display the chart pterm.DefaultBarChart.WithBars(barData).WithHorizontal().WithWidth(5).Render() } ```
### barchart/default ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/default/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart. Each bar is represented by a `pterm.Bar` struct. // The `Label` field represents the label of the bar, and the `Value` field represents the value of the bar. bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Use the `DefaultBarChart` from the `pterm` package to create a bar chart. // The `WithBars` method is used to set the bars of the chart. // The `Render` method is used to display the chart. pterm.DefaultBarChart.WithBars(bars).Render() } ```
### barchart/horizontal ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/horizontal/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined data // The chart is displayed horizontally // The Render() function is called to display the chart pterm.DefaultBarChart.WithBars(bars).WithHorizontal().Render() } ```
### barchart/horizontal-show-value ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/horizontal-show-value/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart barData := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined data // The chart is horizontal and displays the value of each bar // The Render() function is called to display the chart pterm.DefaultBarChart.WithBars(barData).WithHorizontal().WithShowValue().Render() } ```
### barchart/mixed-values ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/mixed-values/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define a set of bars for the chart. // Each bar has a label and a value. bars := []pterm.Bar{ {Label: "Bar 1", Value: 2}, {Label: "Bar 2", Value: -3}, {Label: "Bar 3", Value: -2}, {Label: "Bar 4", Value: 5}, {Label: "Longer Label", Value: 7}, } // Print a section header. // This is useful for separating different parts of the output. pterm.DefaultSection.Println("Chart example with mixed values (note screen space usage in case when ABSOLUTE values of negative and positive parts are differ too much)") // Create a bar chart with the defined bars. // The chart will display the value of each bar. // The Render() function is called to display the chart. pterm.DefaultBarChart.WithBars(bars).WithShowValue().Render() // Create a horizontal bar chart with the same bars. // The chart will display the value of each bar. // The Render() function is called to display the chart. pterm.DefaultBarChart.WithHorizontal().WithBars(bars).WithShowValue().Render() } ```
### barchart/negative-values ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/negative-values/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define a set of bars with negative values. // Each bar is represented by a struct with a label and a value. negativeBars := pterm.Bars{ {Label: "Bar 1", Value: -5}, {Label: "Bar 2", Value: -3}, {Label: "Longer Label", Value: -7}, } // Print an informational message to the console. pterm.Info.Println("Chart example with negative only values (bars use 100% of chart area)") // Create a vertical bar chart with the defined bars. // The WithShowValue() option is used to display the value of each bar in the chart. // The Render() method is called to draw the chart. _ = pterm.DefaultBarChart.WithBars(negativeBars).WithShowValue().Render() // Create a horizontal bar chart with the same bars. // The WithHorizontal() option is used to orient the chart horizontally. // The WithShowValue() option and Render() method are used in the same way as before. _ = pterm.DefaultBarChart.WithHorizontal().WithBars(negativeBars).WithShowValue().Render() } ```
### barchart/show-value ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/show-value/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define a slice of bars for the bar chart. Each bar is represented by a struct // with a Label and a Value. The Label is a string that represents the name of the bar, // and the Value is an integer that represents the height of the bar. bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined bars using the DefaultBarChart object from PTerm. // Chain the WithBars method to set the bars of the chart. // Chain the WithShowValue method to display the value of each bar on the chart. // Finally, call the Render method to display the chart. pterm.DefaultBarChart.WithBars(bars).WithShowValue().Render() } ```
### basictext/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/basictext/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // The DefaultBasicText is a basic text printer provided by PTerm. // It is used to print text without any special formatting. pterm.DefaultBasicText.Println("Default basic text printer.") // The DefaultBasicText can be used in any context that requires a TextPrinter. // Here, we're using it with the LightMagenta function to color a portion of the text. pterm.DefaultBasicText.Println("Can be used in any" + pterm.LightMagenta(" TextPrinter ") + "context.") // The DefaultBasicText is also useful for resolving progress bars and spinners. } ```
### bigtext/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/bigtext/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Create a large text with the LetterStyle from the standard theme. // This is useful for creating title screens. pterm.DefaultBigText.WithLetters(putils.LettersFromString("PTerm")).Render() // Create a large text with differently colored letters. // Here, the first letter 'P' is colored cyan and the rest 'Term' is colored light magenta. // This can be used to highlight specific parts of the text. pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithStyle("P", pterm.FgCyan.ToStyle()), putils.LettersFromStringWithStyle("Term", pterm.FgLightMagenta.ToStyle()), ).Render() // Create a large text with a specific RGB color. // This can be used when you need a specific color that is not available in the standard colors. // Here, the color is gold (RGB: 255, 215, 0). pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithRGB("PTerm", pterm.NewRGB(255, 215, 0)), ).Render() } ```
### bigtext/colored ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/bigtext/colored/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Initialize a big text display with the letters "P" and "Term" // "P" is displayed in cyan and "Term" is displayed in light magenta pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithStyle("P", pterm.FgCyan.ToStyle()), putils.LettersFromStringWithStyle("Term", pterm.FgLightMagenta.ToStyle())). Render() // Render the big text to the terminal } ```
### bigtext/default ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/bigtext/default/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Define the text to be rendered var text = "PTerm" // Convert the text into a format suitable for PTerm var letters = putils.LettersFromString(text) // Render the text using PTerm's default big text style pterm.DefaultBigText.WithLetters(letters).Render() } ```
### box/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/box/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Print an informational message. pterm.Info.Println("This might not be rendered correctly on GitHub,\nbut it will work in a real terminal.\nThis is because GitHub does not use a monospaced font by default for SVGs") // Create three panels with text, some of them with titles. // The panels are created using the DefaultBox style. panel1 := pterm.DefaultBox.Sprint("Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit,\nsed do eiusmod tempor incididunt\nut labore et dolore\nmagna aliqua.") panel2 := pterm.DefaultBox.WithTitle("title").Sprint("Ut enim ad minim veniam,\nquis nostrud exercitation\nullamco laboris\nnisi ut aliquip\nex ea commodo\nconsequat.") panel3 := pterm.DefaultBox.WithTitle("bottom center title").WithTitleBottomCenter().Sprint("Duis aute irure\ndolor in reprehenderit\nin voluptate velit esse cillum\ndolore eu fugiat\nnulla pariatur.") // Combine the panels into a layout using the DefaultPanel style. // The layout is a 2D grid, with each row being an array of panels. // In this case, the first row contains panel1 and panel2, and the second row contains only panel3. panels, _ := pterm.DefaultPanel.WithPanels(pterm.Panels{ {{Data: panel1}, {Data: panel2}}, {{Data: panel3}}, }).Srender() // Print the panels layout inside a box with a title. // The box is created using the DefaultBox style, with the title positioned at the bottom right. pterm.DefaultBox.WithTitle("Lorem Ipsum").WithTitleBottomRight().WithRightPadding(0).WithBottomPadding(0).Println(panels) } ```
### box/custom-padding ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/box/custom-padding/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a default box with custom padding options and print "Hello, World!" inside it. pterm.DefaultBox.WithRightPadding(10).WithLeftPadding(10).WithTopPadding(2).WithBottomPadding(2).Println("Hello, World!") } ```
### box/default ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/box/default/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a default box with PTerm and print a message in it. // The DefaultBox.Println method automatically starts, prints the message, and stops the box. pterm.DefaultBox.Println("Hello, World!") } ```
### box/title ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/box/title/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a default box with specified padding paddedBox := pterm.DefaultBox.WithLeftPadding(4).WithRightPadding(4).WithTopPadding(1).WithBottomPadding(1) // Define a title for the box title := pterm.LightRed("I'm a box!") // Create boxes with the title positioned differently and containing different content box1 := paddedBox.WithTitle(title).Sprint("Hello, World!\n 1") // Title at default position (top left) box2 := paddedBox.WithTitle(title).WithTitleTopCenter().Sprint("Hello, World!\n 2") // Title at top center box3 := paddedBox.WithTitle(title).WithTitleTopRight().Sprint("Hello, World!\n 3") // Title at top right box4 := paddedBox.WithTitle(title).WithTitleBottomRight().Sprint("Hello, World!\n 4") // Title at bottom right box5 := paddedBox.WithTitle(title).WithTitleBottomCenter().Sprint("Hello, World!\n 5") // Title at bottom center box6 := paddedBox.WithTitle(title).WithTitleBottomLeft().Sprint("Hello, World!\n 6") // Title at bottom left box7 := paddedBox.WithTitle(title).WithTitleTopLeft().Sprint("Hello, World!\n 7") // Title at top left // Render the boxes in a panel layout pterm.DefaultPanel.WithPanels([][]pterm.Panel{ {{box1}, {box2}, {box3}}, {{box4}, {box5}, {box6}}, {{box7}}, }).Render() } ```
### bulletlist/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/bulletlist/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Define a list of bullet list items with different levels. bulletListItems := []pterm.BulletListItem{ {Level: 0, Text: "Level 0"}, // Level 0 item {Level: 1, Text: "Level 1"}, // Level 1 item {Level: 2, Text: "Level 2"}, // Level 2 item } // Use the default bullet list style to render the list items. pterm.DefaultBulletList.WithItems(bulletListItems).Render() // Define a string with different levels of indentation. text := `0 1 2 3` // Convert the indented string to a bullet list and render it. putils.BulletListFromString(text, " ").Render() } ```
### bulletlist/customized ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/bulletlist/customized/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define a list of bullet list items with different styles and levels. bulletListItems := []pterm.BulletListItem{ { Level: 0, // Level 0 (top level) Text: "Blue", // Text to display TextStyle: pterm.NewStyle(pterm.FgBlue), // Text color BulletStyle: pterm.NewStyle(pterm.FgRed), // Bullet color }, { Level: 1, // Level 1 (sub-item) Text: "Green", // Text to display TextStyle: pterm.NewStyle(pterm.FgGreen), // Text color Bullet: "-", // Custom bullet symbol BulletStyle: pterm.NewStyle(pterm.FgLightWhite), // Bullet color }, { Level: 2, // Level 2 (sub-sub-item) Text: "Cyan", // Text to display TextStyle: pterm.NewStyle(pterm.FgCyan), // Text color Bullet: ">", // Custom bullet symbol BulletStyle: pterm.NewStyle(pterm.FgYellow), // Bullet color }, } // Create a bullet list with the defined items and render it. pterm.DefaultBulletList.WithItems(bulletListItems).Render() } ```
### center/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/center/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Print a block of text centered in the terminal pterm.DefaultCenter.Println("This text is centered!\nIt centers the whole block by default.\nIn that way you can do stuff like this:") // Generate BigLetters and store in 's' s, _ := pterm.DefaultBigText.WithLetters(putils.LettersFromString("PTerm")).Srender() // Print the BigLetters 's' centered in the terminal pterm.DefaultCenter.Println(s) // Print each line of the text separately centered in the terminal pterm.DefaultCenter.WithCenterEachLineSeparately().Println("This text is centered!\nBut each line is\ncentered\nseparately") } ```
### coloring/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a table with different foreground and background colors. pterm.DefaultTable.WithData([][]string{ {pterm.FgBlack.Sprint("Black"), pterm.FgRed.Sprint("Red"), pterm.FgGreen.Sprint("Green"), pterm.FgYellow.Sprint("Yellow")}, {"", pterm.FgLightRed.Sprint("Light Red"), pterm.FgLightGreen.Sprint("Light Green"), pterm.FgLightYellow.Sprint("Light Yellow")}, {pterm.BgBlack.Sprint("Black"), pterm.BgRed.Sprint("Red"), pterm.BgGreen.Sprint("Green"), pterm.BgYellow.Sprint("Yellow")}, {"", pterm.BgLightRed.Sprint("Light Red"), pterm.BgLightGreen.Sprint("Light Green"), pterm.BgLightYellow.Sprint("Light Yellow")}, {pterm.FgBlue.Sprint("Blue"), pterm.FgMagenta.Sprint("Magenta"), pterm.FgCyan.Sprint("Cyan"), pterm.FgWhite.Sprint("White")}, {pterm.FgLightBlue.Sprint("Light Blue"), pterm.FgLightMagenta.Sprint("Light Magenta"), pterm.FgLightCyan.Sprint("Light Cyan"), pterm.FgLightWhite.Sprint("Light White")}, {pterm.BgBlue.Sprint("Blue"), pterm.BgMagenta.Sprint("Magenta"), pterm.BgCyan.Sprint("Cyan"), pterm.BgWhite.Sprint("White")}, {pterm.BgLightBlue.Sprint("Light Blue"), pterm.BgLightMagenta.Sprint("Light Magenta"), pterm.BgLightCyan.Sprint("Light Cyan"), pterm.BgLightWhite.Sprint("Light White")}, }).Render() // Render the table. pterm.Println() // Print words in different colors. pterm.Println(pterm.Red("Hello, ") + pterm.Green("World") + pterm.Cyan("!")) pterm.Println(pterm.Red("Even " + pterm.Cyan("nested ") + pterm.Green("colors ") + "are supported!")) pterm.Println() // Create a new style with a red background, light green foreground, and bold text. style := pterm.NewStyle(pterm.BgRed, pterm.FgLightGreen, pterm.Bold) // Print text using the created style. style.Println("This text uses a style and is bold and light green with a red background!") } ```
### coloring/disable-output ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/disable-output/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Loop from 0 to 14 for i := 0; i < 15; i++ { switch i { case 5: // At the 5th iteration, print a message and disable the output pterm.Info.Println("Disabled Output!") pterm.DisableOutput() case 10: // At the 10th iteration, enable the output and print a message pterm.EnableOutput() pterm.Info.Println("Enabled Output!") } // Print a progress message for each iteration pterm.Printf("Printing something... [%d/%d]\n", i, 15) } } ```
### coloring/fade-colors ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/fade-colors/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Print an informational message. pterm.Info.Println("RGB colors only work in Terminals which support TrueColor.") // Define the start and end points for the color gradient. startColor := pterm.NewRGB(0, 255, 255) // Cyan endColor := pterm.NewRGB(255, 0, 255) // Magenta // Get the terminal height to determine the gradient range. terminalHeight := pterm.GetTerminalHeight() // Loop over the range of the terminal height to create a color gradient. for i := 0; i < terminalHeight-2; i++ { // Calculate the fade factor for the current step in the gradient. fadeFactor := float32(i) / float32(terminalHeight-2) // Create a color that represents the current step in the gradient. currentColor := startColor.Fade(0, 1, fadeFactor, endColor) // Print a string with the current color. currentColor.Println("Hello, World!") } } ```
### coloring/fade-colors-rgb-style ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/fade-colors-rgb-style/animation.svg)
SHOW SOURCE ```go package main import ( "strings" "github.com/pterm/pterm" ) func main() { // Define RGB colors white := pterm.NewRGB(255, 255, 255) grey := pterm.NewRGB(128, 128, 128) black := pterm.NewRGB(0, 0, 0) red := pterm.NewRGB(255, 0, 0) purple := pterm.NewRGB(255, 0, 255) green := pterm.NewRGB(0, 255, 0) // Define strings to be printed str1 := "RGB colors only work in Terminals which support TrueColor." str2 := "The background and foreground colors can be customized individually." str3 := "Styles can also be applied. For example: Bold or Italic." // Print first string with color fading from white to purple printFadedString(str1, white, purple, grey, black) // Print second string with color fading from purple to red printFadedString(str2, black, purple, red, red) // Print third string with color fading from white to green and style changes printStyledString(str3, white, green, red, black) } // printFadedString prints a string with color fading effect func printFadedString(str string, fgStart, fgEnd, bgStart, bgEnd pterm.RGB) { strs := strings.Split(str, "") var result string for i := 0; i < len(str); i++ { // Create a style with color fading effect style := pterm.NewRGBStyle(fgStart.Fade(0, float32(len(str)), float32(i), fgEnd), bgStart.Fade(0, float32(len(str)), float32(i), bgEnd)) // Append styled letter to result string result += style.Sprint(strs[i]) } pterm.Println(result) } // printStyledString prints a string with color fading and style changes func printStyledString(str string, fgStart, fgEnd, bgStart, bgEnd pterm.RGB) { strs := strings.Split(str, "") var result string boldStr := strings.Split("Bold", "") italicStr := strings.Split("Italic", "") bold, italic := 0, 0 for i := 0; i < len(str); i++ { // Create a style with color fading effect style := pterm.NewRGBStyle(fgStart.Fade(0, float32(len(str)), float32(i), fgEnd), bgStart.Fade(0, float32(len(str)), float32(i), bgEnd)) // Check if the next letters are "Bold" or "Italic" and add the corresponding style if bold < len(boldStr) && i+len(boldStr)-bold <= len(strs) && strings.Join(strs[i:i+len(boldStr)-bold], "") == strings.Join(boldStr[bold:], "") { style = style.AddOptions(pterm.Bold) bold++ } else if italic < len(italicStr) && i+len(italicStr)-italic < len(strs) && strings.Join(strs[i:i+len(italicStr)-italic], "") == strings.Join(italicStr[italic:], "") { style = style.AddOptions(pterm.Italic) italic++ } // Append styled letter to result string result += style.Sprint(strs[i]) } pterm.Println(result) } ```
### coloring/fade-multiple-colors ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/fade-multiple-colors/animation.svg)
SHOW SOURCE ```go package main import ( "strings" "github.com/pterm/pterm" ) func main() { // Define RGB values for gradient points. startColor := pterm.NewRGB(0, 255, 255) firstPoint := pterm.NewRGB(255, 0, 255) secondPoint := pterm.NewRGB(255, 0, 0) thirdPoint := pterm.NewRGB(0, 255, 0) endColor := pterm.NewRGB(255, 255, 255) // Define the string to be printed. str := "RGB colors only work in Terminals which support TrueColor." strs := strings.Split(str, "") // Initialize an empty string for the faded info. var fadeInfo string // Loop over the string length to create a gradient effect. for i := 0; i < len(str); i++ { // Append each character of the string with a faded color to the info string. fadeInfo += startColor.Fade(0, float32(len(str)), float32(i), firstPoint).Sprint(strs[i]) } // Print the info string with gradient effect. pterm.Info.Println(fadeInfo) // Get the terminal height. terminalHeight := pterm.GetTerminalHeight() // Loop over the terminal height to print "Hello, World!" with a gradient effect. for i := 0; i < terminalHeight-2; i++ { // Print the string with a color that fades from startColor to endColor. startColor.Fade(0, float32(terminalHeight-2), float32(i), firstPoint, secondPoint, thirdPoint, endColor).Println("Hello, World!") } } ```
### coloring/override-default-printers ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/override-default-printers/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Print a default error message with PTerm's built-in Error style. pterm.Error.Println("This is the default Error") // Override the default error prefix with a new text and style. pterm.Error.Prefix = pterm.Prefix{Text: "OVERRIDE", Style: pterm.NewStyle(pterm.BgCyan, pterm.FgRed)} // Print the error message again, this time with the overridden prefix. pterm.Error.Println("This is the default Error after the prefix was overridden") } ```
### coloring/print-color-rgb ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/print-color-rgb/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a new RGB color with values 178, 44, 199. // This color will be used for the text. pterm.NewRGB(178, 44, 199).Println("This text is printed with a custom RGB!") // Create a new RGB color with values 15, 199, 209. // This color will be used for the text. pterm.NewRGB(15, 199, 209).Println("This text is printed with a custom RGB!") // Create a new RGB color with values 201, 144, 30. // This color will be used for the background. // The 'true' argument indicates that the color is for the background. pterm.NewRGB(201, 144, 30, true).Println("This text is printed with a custom RGB background!") } ```
### coloring/print-color-rgb-style ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/print-color-rgb-style/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define RGB colors for foreground and background. foregroundRGB := pterm.RGB{R: 187, G: 80, B: 0} backgroundRGB := pterm.RGB{R: 0, G: 50, B: 123} // Create a new RGB style with the defined foreground and background colors. rgbStyle := pterm.NewRGBStyle(foregroundRGB, backgroundRGB) // Print a string with the custom RGB style. rgbStyle.Println("This text is not styled.") // Add the 'Bold' option to the RGB style and print a string with this style. rgbStyle.AddOptions(pterm.Bold).Println("This text is bold.") // Add the 'Italic' option to the RGB style and print a string with this style. rgbStyle.AddOptions(pterm.Italic).Println("This text is italic.") } ```
### demo/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/demo/demo/animation.svg)
SHOW SOURCE ```go package main import ( "flag" "math/rand" "reflect" "strconv" "strings" "time" "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) // Speed the demo up, by setting this flag. // Usefull for debugging. // Example: // // go run main.go -speedup var speedup = flag.Bool("speedup", false, "Speed up the demo") var skipIntro = flag.Bool("skip-intro", false, "Skips the intro") var second = time.Second var pseudoProgramList = strings.Split("pseudo-excel pseudo-photoshop pseudo-chrome pseudo-outlook pseudo-explorer "+ "pseudo-git pseudo-vsc pseudo-intellij pseudo-minecraft pseudo-scoop pseudo-chocolatey", " ") func main() { setup() // Setup the demo (flags etc.) // Show intro if !*skipIntro { introScreen() clear() } showcase("Structured Logging", 5, func() { logger := pterm.DefaultLogger. WithLevel(pterm.LogLevelTrace) logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) time.Sleep(time.Second * 3) interstingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } logger.Debug("This might be interesting", logger.ArgsFromMap(interstingStuff)) time.Sleep(time.Second * 3) logger.Info("That was actually interesting", logger.Args("such", "wow")) time.Sleep(time.Second * 3) logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) time.Sleep(time.Second * 3) logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) time.Sleep(time.Second * 3) logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) }) showcase("Progress bar", 2, func() { pb, _ := pterm.DefaultProgressbar.WithTotal(len(pseudoProgramList)).WithTitle("Installing stuff").Start() for i := 0; i < pb.Total; i++ { pb.UpdateTitle("Installing " + pseudoProgramList[i]) if pseudoProgramList[i] == "pseudo-minecraft" { pterm.Warning.Println("Could not install pseudo-minecraft\nThe company policy forbids games.") } else { pterm.Success.Println("Installing " + pseudoProgramList[i]) } pb.Increment() time.Sleep(second / 2) } pb.Stop() }) showcase("Spinner", 2, func() { list := pseudoProgramList[7:] spinner, _ := pterm.DefaultSpinner.Start("Installing stuff") for i := 0; i < len(list); i++ { spinner.UpdateText("Installing " + list[i]) if list[i] == "pseudo-minecraft" { pterm.Warning.Println("Could not install pseudo-minecraft\nThe company policy forbids games.") } else { pterm.Success.Println("Installing " + list[i]) } time.Sleep(second) } spinner.Success() }) showcase("Live Output", 2, func() { pterm.Info.Println("You can use an Area to display changing output:") pterm.Println() area, _ := pterm.DefaultArea.WithCenter().Start() // Start the Area printer, with the Center option. for i := 0; i < 10; i++ { str, _ := pterm.DefaultBigText.WithLetters(putils.LettersFromString(time.Now().Format("15:04:05"))).Srender() // Save current time in str. area.Update(str) // Update Area contents. time.Sleep(time.Second) } area.Stop() }) showcase("Tables", 4, func() { for i := 0; i < 3; i++ { pterm.Println() } td := [][]string{ {"Library", "Description"}, {"PTerm", "Make beautiful CLIs"}, {"Testza", "Programmer friendly test framework"}, {"Cursor", "Move the cursor around the terminal"}, } table, _ := pterm.DefaultTable.WithHasHeader().WithData(td).Srender() boxedTable, _ := pterm.DefaultTable.WithHasHeader().WithData(td).WithBoxed().Srender() pterm.DefaultCenter.Println(table) pterm.DefaultCenter.Println(boxedTable) }) showcase("TrueColor Support", 7, func() { from := pterm.NewRGB(0, 255, 255) // This RGB value is used as the gradients start point. to := pterm.NewRGB(255, 0, 255) // This RGB value is used as the gradients first point. str := "If your terminal has TrueColor support, you can use RGB colors!\nYou can even fade them :)\n\nLorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet." strs := strings.Split(str, "") var fadeInfo string // String which will be used to print info. // For loop over the range of the string length. for i := 0; i < len(str); i++ { // Append faded letter to info string. fadeInfo += from.Fade(0, float32(len(str)), float32(i), to).Sprint(strs[i]) } pterm.DefaultCenter.WithCenterEachLineSeparately().Println(fadeInfo) }) showcase("Fully Customizable", 2, func() { for i := 0; i < 4; i++ { pterm.Println() } text := "All printers are fully customizable!" area := pterm.DefaultArea.WithCenter() area.Update(pterm.DefaultBox.Sprintln(text)) time.Sleep(second) area.Update(pterm.DefaultBox.WithTopPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleTopLeft().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleTopCenter().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleTopRight().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleBottomRight().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleBottomCenter().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleBottomLeft().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithBoxStyle(pterm.NewStyle(pterm.FgCyan)).Sprintln(text)) time.Sleep(second / 5) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithBoxStyle(pterm.NewStyle(pterm.FgRed)).Sprintln(text)) time.Sleep(second / 5) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithBoxStyle(pterm.NewStyle(pterm.FgGreen)).Sprintln(text)) time.Sleep(second / 5) area.Update(pterm.DefaultBox.WithTopPadding(1). WithBottomPadding(1). WithLeftPadding(1). WithRightPadding(1). WithHorizontalString("═"). WithVerticalString("║"). WithBottomLeftCornerString("╗"). WithBottomRightCornerString("╔"). WithTopLeftCornerString("╝"). WithTopRightCornerString("╚"). Sprintln(text)) area.Stop() }) showcase("Themes", 2, func() { pterm.Info.Println("You can change the color theme of PTerm easily to fit your needs!\nThis is the default one:") time.Sleep(second / 2) // Print every value of the default theme with its own style. v := reflect.ValueOf(pterm.ThemeDefault) typeOfS := v.Type() if typeOfS == reflect.TypeOf(pterm.Theme{}) { for i := 0; i < v.NumField(); i++ { field, ok := v.Field(i).Interface().(pterm.Style) if ok { field.Println(typeOfS.Field(i).Name) } time.Sleep(time.Millisecond * 250) } } }) showcase("And much more!", 3, func() { for i := 0; i < 4; i++ { pterm.Println() } box := pterm.DefaultBox. WithBottomPadding(1). WithTopPadding(1). WithLeftPadding(3). WithRightPadding(3). Sprintf("Have fun exploring %s!", pterm.Cyan("PTerm")) pterm.DefaultCenter.Println(box) }) } func setup() { flag.Parse() if *speedup { second = time.Millisecond * 200 } } func introScreen() { ptermLogo, _ := pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithStyle("P", pterm.NewStyle(pterm.FgLightCyan)), putils.LettersFromStringWithStyle("Term", pterm.NewStyle(pterm.FgLightMagenta))). Srender() pterm.DefaultCenter.Print(ptermLogo) pterm.DefaultCenter.Print(pterm.DefaultHeader.WithFullWidth().WithBackgroundStyle(pterm.NewStyle(pterm.BgLightBlue)).WithMargin(10).Sprint("PTDP - PTerm Demo Program")) pterm.Info.Println("This animation was generated with the latest version of PTerm!" + "\nPTerm works on nearly every terminal and operating system." + "\nIt's super easy to use!" + "\nIf you want, you can customize everything :)" + "\nYou can see the code of this demo in the " + pterm.LightMagenta("./_examples/demo") + " directory." + "\n" + "\nThis demo was updated at: " + pterm.Green(time.Now().Format("02 Jan 2006 - 15:04:05 MST"))) pterm.Println() introSpinner, _ := pterm.DefaultSpinner.WithShowTimer(false).WithRemoveWhenDone(true).Start("Waiting for 15 seconds...") time.Sleep(second) for i := 14; i > 0; i-- { if i > 1 { introSpinner.UpdateText("Waiting for " + strconv.Itoa(i) + " seconds...") } else { introSpinner.UpdateText("Waiting for " + strconv.Itoa(i) + " second...") } time.Sleep(second) } introSpinner.Stop() } func clear() { print("\033[H\033[2J") } func showcase(title string, seconds int, content func()) { pterm.DefaultHeader.WithBackgroundStyle(pterm.NewStyle(pterm.BgLightBlue)).WithFullWidth().Println(title) pterm.Println() time.Sleep(second / 2) content() time.Sleep(second * time.Duration(seconds)) print("\033[H\033[2J") } func randomInt(min, max int) int { rand.Seed(time.Now().UnixNano()) return rand.Intn(max-min+1) + min } ```
### header/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/header/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Print a default header. // This uses the default settings of PTerm to print a header. pterm.DefaultHeader.Println("This is the default header!") // Print a spacer line for better readability. pterm.Println() // Print a full-width header. // This uses the WithFullWidth() option of PTerm to print a header that spans the full width of the terminal. pterm.DefaultHeader.WithFullWidth().Println("This is a full-width header.") } ```
### header/custom ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/header/custom/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Customize the DefaultHeader with a cyan background, black text, and a margin of 15. pterm.DefaultHeader.WithMargin(15).WithBackgroundStyle(pterm.NewStyle(pterm.BgCyan)).WithTextStyle(pterm.NewStyle(pterm.FgBlack)).Println("This is a custom header!") // Define a new HeaderPrinter with a red background, black text, and a margin of 20. newHeader := pterm.HeaderPrinter{ TextStyle: pterm.NewStyle(pterm.FgBlack), BackgroundStyle: pterm.NewStyle(pterm.BgRed), Margin: 20, } // Print the custom header using the new HeaderPrinter. newHeader.Println("This is a custom header!") } ```
### heatmap/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/heatmap/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap. Each sub-array represents a row in the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the labels for the X and Y axes of the heatmap. headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Create a heatmap with the defined data and axis labels, and enable RGB colors. // Then render the heatmap. pterm.DefaultHeatmap.WithAxisData(headerData).WithData(data).WithEnableRGB().Render() } ```
### heatmap/custom_colors ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/heatmap/custom_colors/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis labels for the heatmap headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message pterm.Info.Println("The following table has no rgb (supported by every terminal), no axis data and a legend.") pterm.Println() // Create the heatmap with the defined data and options, and render it pterm.DefaultHeatmap. WithData(data). WithBoxed(false). WithAxisData(headerData). WithLegend(false). WithColors(pterm.BgBlue, pterm.BgRed, pterm.BgGreen, pterm.BgYellow). WithLegend(). Render() } ```
### heatmap/custom_legend ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/heatmap/custom_legend/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the header data for the heatmap headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message pterm.Info.Println("The following table has rgb (not supported by every terminal), axis data and a custom legend.") pterm.Println() // Create the heatmap with the defined data and options // Options are chained in a single line for simplicity pterm.DefaultHeatmap. WithData(data). WithBoxed(false). WithAxisData(headerData). WithEnableRGB(). WithLegendLabel("custom"). WithLegendOnlyColoredCells(). Render() // Render the heatmap } ```
### heatmap/custom_rgb ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/heatmap/custom_rgb/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis labels for the heatmap. axisLabels := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message. pterm.Info.Println("The following table has rgb (not supported by every terminal), axis data and a legend.") pterm.Println() // Define the color range for the heatmap. rgbRange := []pterm.RGB{ pterm.NewRGB(0, 0, 255), pterm.NewRGB(255, 0, 0), pterm.NewRGB(0, 255, 0), pterm.NewRGB(255, 255, 0), } // Create and render the heatmap. pterm.DefaultHeatmap. WithData(data). WithBoxed(false). WithAxisData(axisLabels). WithEnableRGB(). WithRGBRange(rgbRange...). Render() } ```
### heatmap/no_grid ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/heatmap/no_grid/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis data for the heatmap. axisData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message. pterm.Info.Println("The following table has rgb (not supported by every terminal), axis data and a legend.") pterm.Println() // Create the heatmap with the defined data and options, then render it. pterm.DefaultHeatmap.WithData(data).WithBoxed(false).WithAxisData(axisData).WithEnableRGB().WithLegend().WithGrid(false).Render() } ```
### heatmap/separated ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/heatmap/separated/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis labels for the heatmap. headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message. pterm.Info.Println("The following table has no rgb (supported by every terminal), no axis data and no legend.") pterm.Println() // Create the heatmap with the specified data and options, and render it. pterm.DefaultHeatmap.WithData(data).WithBoxed(false).WithAxisData(headerData).WithLegend(false).Render() } ```
### interactive_confirm/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_confirm/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Show an interactive confirmation dialog and get the result. result, _ := pterm.DefaultInteractiveConfirm.Show() // Print a blank line for better readability. pterm.Println() // Print the user's answer in a formatted way. pterm.Info.Printfln("You answered: %s", boolToText(result)) } // boolToText converts a boolean value to a colored text. // If the value is true, it returns a green "Yes". // If the value is false, it returns a red "No". func boolToText(b bool) string { if b { return pterm.Green("Yes") } return pterm.Red("No") } ```
### interactive_continue/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_continue/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Create an interactive continue prompt with default settings // This will pause the program execution until the user presses enter // The message displayed is "Press 'Enter' to continue..." prompt := pterm.DefaultInteractiveContinue // Show the prompt and wait for user input // The returned result is the user's input (should be empty as it's a continue prompt) // The second return value is an error which is ignored here result, _ := prompt.Show() // Print a blank line for better readability pterm.Println() // Print the user's input with an info prefix // As this is a continue prompt, the input should be empty pterm.Info.Printfln("You answered: %s", result) } ```
### interactive_multiselect/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_multiselect/demo/animation.svg)
SHOW SOURCE ```go package main import ( "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options. var options []string // Populate the options slice with 100 options. for i := 0; i < 100; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Add 5 more options to the slice, indicating the availability of fuzzy searching. for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("You can use fuzzy searching (%d)", i)) } // Use PTerm's interactive multiselect to present the options to the user and capture their selections. // The Show() method displays the options and waits for user input. selectedOptions, _ := pterm.DefaultInteractiveMultiselect.WithOptions(options).Show() // Print the selected options, highlighted in green. pterm.Info.Printfln("Selected options: %s", pterm.Green(selectedOptions)) } ```
### interactive_multiselect/custom-checkmarks ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_multiselect/custom-checkmarks/animation.svg)
SHOW SOURCE ```go package main import ( "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options var options []string // Populate the options slice with 5 options for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Create a new interactive multiselect printer with the options // Disable the filter and define the checkmark symbols printer := pterm.DefaultInteractiveMultiselect. WithOptions(options). WithFilter(false). WithCheckmark(&pterm.Checkmark{Checked: pterm.Green("+"), Unchecked: pterm.Red("-")}) // Show the interactive multiselect and get the selected options selectedOptions, _ := printer.Show() // Print the selected options pterm.Info.Printfln("Selected options: %s", pterm.Green(selectedOptions)) } ```
### interactive_multiselect/custom-keys ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_multiselect/custom-keys/animation.svg)
SHOW SOURCE ```go package main import ( "atomicgo.dev/keyboard/keys" "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options var options []string // Populate the options slice with 5 options for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Create a new interactive multiselect printer with the options // Disable the filter and set the keys for confirming and selecting options printer := pterm.DefaultInteractiveMultiselect. WithOptions(options). WithFilter(false). WithKeyConfirm(keys.Enter). WithKeySelect(keys.Space) // Show the interactive multiselect and get the selected options selectedOptions, _ := printer.Show() // Print the selected options pterm.Info.Printfln("Selected options: %s", pterm.Green(selectedOptions)) } ```
### interactive_select/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_select/demo/animation.svg)
SHOW SOURCE ```go package main import ( "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options var options []string // Generate 100 options and add them to the options slice for i := 0; i < 100; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Generate 5 additional options with a specific message and add them to the options slice for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("You can use fuzzy searching (%d)", i)) } // Use PTerm's interactive select feature to present the options to the user and capture their selection // The Show() method displays the options and waits for the user's input selectedOption, _ := pterm.DefaultInteractiveSelect.WithOptions(options).Show() // Display the selected option to the user with a green color for emphasis pterm.Info.Printfln("Selected option: %s", pterm.Green(selectedOption)) } ```
### interactive_textinput/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_textinput/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Create an interactive text input with single line input mode and show it result, _ := pterm.DefaultInteractiveTextInput.Show() // Print a blank line for better readability pterm.Println() // Print the user's answer with an info prefix pterm.Info.Printfln("You answered: %s", result) } ```
### interactive_textinput/default-value ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_textinput/default-value/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Create an interactive text input with single line input mode and show it result, _ := pterm.DefaultInteractiveTextInput.WithDefaultValue("Some default value").Show() // Print a blank line for better readability pterm.Println() // Print the user's answer with an info prefix pterm.Info.Printfln("You answered: %s", result) } ```
### interactive_textinput/multi-line ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_textinput/multi-line/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Create a default interactive text input with multi-line enabled. // This allows the user to input multiple lines of text. textInput := pterm.DefaultInteractiveTextInput.WithMultiLine() // Show the text input to the user and store the result. // The second return value (an error) is ignored with '_'. result, _ := textInput.Show() // Print a blank line for better readability in the output. pterm.Println() // Print the user's input prefixed with an informational message. // The '%s' placeholder is replaced with the user's input. pterm.Info.Printfln("You answered: %s", result) } ```
### interactive_textinput/password ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_textinput/password/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create an interactive text input with a mask for password input passwordInput := pterm.DefaultInteractiveTextInput.WithMask("*") // Show the password input prompt and store the result result, _ := passwordInput.Show("Enter your password") // Get the default logger from PTerm logger := pterm.DefaultLogger // Log the received password (masked) // Note: In a real-world application, you should never log passwords logger.Info("Password received", logger.Args("password", result)) } ```
### logger/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/logger/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "time" ) func main() { // Create a logger with trace level logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace) // Log a trace level message logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Pause for 3 seconds sleep() // Define a map with interesting stuff interstingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a debug level message with arguments from the map logger.Debug("This might be interesting", logger.ArgsFromMap(interstingStuff)) // Pause for 3 seconds sleep() // Log an info level message logger.Info("That was actually interesting", logger.Args("such", "wow")) // Pause for 3 seconds sleep() // Log a warning level message logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) // Pause for 3 seconds sleep() // Log an error level message logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) // Pause for 3 seconds sleep() // Log an info level message with a long text that will be automatically wrapped logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) // Pause for 3 seconds sleep() // Log a fatal level message logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } // Function to pause the execution for 3 seconds func sleep() { time.Sleep(time.Second * 3) } ```
### logger/custom-key-styles ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/logger/custom-key-styles/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a logger with a level of Trace or higher. logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace) // Define a new style for the "priority" key. priorityStyle := map[string]pterm.Style{ "priority": *pterm.NewStyle(pterm.FgRed), } // Overwrite all key styles with the new map. logger = logger.WithKeyStyles(priorityStyle) // Log an info message. The "priority" key will be displayed in red. logger.Info("The priority key should now be red", logger.Args("priority", "low", "foo", "bar")) // Define a new style for the "foo" key. fooStyle := *pterm.NewStyle(pterm.FgBlue) // Append the new style to the existing ones. logger.AppendKeyStyle("foo", fooStyle) // Log another info message. The "foo" key will be displayed in blue. logger.Info("The foo key should now be blue", logger.Args("priority", "low", "foo", "bar")) } ```
### logger/default ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/logger/default/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "time" ) func main() { // Create a logger with a level of Trace or higher. logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace) // Log a trace message with additional arguments. logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Create a map of interesting stuff. interstingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a debug message with arguments from a map. logger.Debug("This might be interesting", logger.ArgsFromMap(interstingStuff)) // Log an info message with additional arguments. logger.Info("That was actually interesting", logger.Args("such", "wow")) // Log a warning message with additional arguments. logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) // Log an error message with additional arguments. logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) // Log an info message with additional arguments. PTerm will automatically wrap long logs. logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) // Pause for 2 seconds. time.Sleep(time.Second * 2) // Log a fatal message with additional arguments. This will terminate the process. logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } ```
### logger/json ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/logger/json/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a logger with Trace level and JSON formatter logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace).WithFormatter(pterm.LogFormatterJSON) // Log a Trace level message with additional arguments logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Create a map of interesting stuff interestingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a Debug level message with arguments from the map logger.Debug("This might be interesting", logger.ArgsFromMap(interestingStuff)) // Log Info, Warn, Error, and Fatal level messages with additional arguments logger.Info("That was actually interesting", logger.Args("such", "wow")) logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } ```
### logger/with-caller ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/logger/with-caller/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a logger with Trace level and caller information logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace).WithCaller() // Log a trace message with additional arguments logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Create a map of interesting stuff interestingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a debug message with arguments from a map logger.Debug("This might be interesting", logger.ArgsFromMap(interestingStuff)) // Log an info message with additional arguments logger.Info("That was actually interesting", logger.Args("such", "wow")) // Log a warning message with additional arguments logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) // Log an error message with additional arguments logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) // Log an info message with additional arguments. PTerm will automatically wrap long logs. logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) // Log a fatal message with additional arguments. This will terminate the process. logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } ```
### multiple-live-printers/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/multiple-live-printers/demo/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create a multi printer for managing multiple printers multi := pterm.DefaultMultiPrinter // Create two spinners with their own writers spinner1, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 1") spinner2, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 2") // Create five progress bars with their own writers and a total of 100 pb1, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 1") pb2, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 2") pb3, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 3") pb4, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 4") pb5, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 5") // Start the multi printer multi.Start() // Increment progress bars and spinners based on certain conditions for i := 1; i <= 100; i++ { pb1.Increment() // Increment progress bar 1 every iteration if i%2 == 0 { pb2.Add(3) // Add 3 to progress bar 2 every even iteration } if i%5 == 0 { pb3.Increment() // Increment progress bar 3 every 5th iteration } if i%10 == 0 { pb4.Increment() // Increment progress bar 4 every 10th iteration } if i%3 == 0 { pb5.Increment() // Increment progress bar 5 every 3rd iteration } if i%50 == 0 { spinner1.Success("Spinner 1 is done!") // Mark spinner 1 as successful every 50th iteration } if i%60 == 0 { spinner2.Fail("Spinner 2 failed!") // Mark spinner 2 as failed every 60th iteration } time.Sleep(time.Millisecond * 50) // Sleep for 50 milliseconds between each iteration } // Stop the multi printer multi.Stop() } ```
### panel/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/panel/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define panels in a 2D grid system panels := pterm.Panels{ { {Data: "This is the first panel"}, {Data: pterm.DefaultHeader.Sprint("Hello, World!")}, {Data: "This\npanel\ncontains\nmultiple\nlines"}, }, { {Data: pterm.Red("This is another\npanel line")}, {Data: "This is the second panel\nwith a new line"}, }, } // Render the panels with a padding of 5 _ = pterm.DefaultPanel.WithPanels(panels).WithPadding(5).Render() } ```
### paragraph/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/paragraph/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Using the default paragraph printer to print a long text. // The text is split at the spaces, which is useful for continuous text of all kinds. // The line width can be manually adjusted if needed. pterm.DefaultParagraph.Println("This is the default paragraph printer. As you can see, no words are separated, " + "but the text is split at the spaces. This is useful for continuous text of all kinds. You can manually change the line width if you want to." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam") // Printing a line space for separation. pterm.Println() // Printing a long text without using the paragraph printer. // The default Println() function is used here, which does not provide intelligent splitting. pterm.Println("This text is written with the default Println() function. No intelligent splitting here." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam") } ```
### paragraph/customized ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/paragraph/customized/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define a long text to be printed as a paragraph. longText := "This is a custom paragraph printer. As you can see, no words are separated, " + "but the text is split at the spaces. This is useful for continuous text of all kinds. You can manually change the line width if you want to." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam" // Print the long text as a paragraph with a custom maximal width of 60 characters. pterm.DefaultParagraph.WithMaxWidth(60).Println(longText) // Print a line space to separate the paragraph from the following text. pterm.Println() // Define another long text to be printed without a paragraph printer. longTextWithoutParagraph := "This text is written with the default Println() function. No intelligent splitting here." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam" // Print the long text without using a paragraph printer. pterm.Println(longTextWithoutParagraph) } ```
### prefix/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/prefix/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Enable debug messages in PTerm. pterm.EnableDebugMessages() // Print a debug message with PTerm. pterm.Debug.Println("Hello, World!") // Print an informational message with PTerm. pterm.Info.Println("Hello, World!") // Print a success message with PTerm. pterm.Success.Println("Hello, World!") // Print a warning message with PTerm. pterm.Warning.Println("Hello, World!") // Print an error message with PTerm. This will also display the filename and line number in the terminal. pterm.Error.Println("Errors show the filename and linenumber inside the terminal!") // Print an informational message with PTerm, with line number. // This demonstrates that other PrefixPrinters can also display line numbers. pterm.Info.WithShowLineNumber().Println("Other PrefixPrinters can do that too!") // Temporarily set Fatal to false, so that the CI won't crash. // This will print a fatal message with PTerm, but won't terminate the program. pterm.Fatal.WithFatal(false).Println("Hello, World!") } ```
### progressbar/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/progressbar/demo/animation.svg)
SHOW SOURCE ```go package main import ( "strings" "time" "github.com/pterm/pterm" ) // Slice of strings representing names of pseudo applications to be downloaded. var fakeInstallList = strings.Split("pseudo-excel pseudo-photoshop pseudo-chrome pseudo-outlook pseudo-explorer "+ "pseudo-dops pseudo-git pseudo-vsc pseudo-intellij pseudo-minecraft pseudo-scoop pseudo-chocolatey", " ") func main() { // Create a progressbar with the total steps equal to the number of items in fakeInstallList. // Set the initial title of the progressbar to "Downloading stuff". p, _ := pterm.DefaultProgressbar.WithTotal(len(fakeInstallList)).WithTitle("Downloading stuff").Start() // Loop over each item in the fakeInstallList. for i := 0; i < p.Total; i++ { // Simulate a slow download for the 7th item. if i == 6 { time.Sleep(time.Second * 3) } // Update the title of the progressbar with the current item being downloaded. p.UpdateTitle("Downloading " + fakeInstallList[i]) // Print a success message for the current download. This will be printed above the progressbar. pterm.Success.Println("Downloading " + fakeInstallList[i]) // Increment the progressbar by one to indicate progress. p.Increment() // Pause for 350 milliseconds to simulate the time taken for each download. time.Sleep(time.Millisecond * 350) } } ```
### progressbar/multiple ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/progressbar/multiple/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create a multi printer instance from the default one multi := pterm.DefaultMultiPrinter // Create five progress bars with a total of 100 units each, and assign each a new writer from the multi printer pb1, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 1") pb2, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 2") pb3, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 3") pb4, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 4") pb5, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 5") // Start the multi printer multi.Start() // Loop to increment progress bars based on certain conditions for i := 1; i <= 100; i++ { pb1.Increment() // Increment the first progress bar at each iteration if i%2 == 0 { pb2.Add(3) // Add 3 units to the second progress bar at every even iteration } if i%5 == 0 { pb3.Increment() // Increment the third progress bar at every fifth iteration } if i%10 == 0 { pb4.Increment() // Increment the fourth progress bar at every tenth iteration } if i%3 == 0 { pb5.Increment() // Increment the fifth progress bar at every third iteration } time.Sleep(time.Millisecond * 50) // Pause for 50 milliseconds at each iteration } // Stop the multi printer multi.Stop() } ```
### section/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/section/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a section with level one and print it. pterm.DefaultSection.Println("This is a section!") // Print an informational message. pterm.Info.Println("And here is some text.\nThis text could be anything.\nBasically it's just a placeholder") // Create a section with level two and print it. pterm.DefaultSection.WithLevel(2).Println("This is another section!") // Print another informational message. pterm.Info.Println("And this is\nmore placeholder text") } ```
### slog/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/slog/demo/animation.svg)
SHOW SOURCE ```go package main import ( "log/slog" "github.com/pterm/pterm" ) func main() { // Create a new slog handler with the default PTerm logger handler := pterm.NewSlogHandler(&pterm.DefaultLogger) // Create a new slog logger with the handler logger := slog.New(handler) // Log a debug message (won't show by default) logger.Debug("This is a debug message that won't show") // Change the log level to debug to enable debug messages pterm.DefaultLogger.Level = pterm.LogLevelDebug // Log a debug message (will show because debug level is enabled) logger.Debug("This is a debug message", "changedLevel", true) // Log an info message logger.Info("This is an info message") // Log a warning message logger.Warn("This is a warning message") // Log an error message logger.Error("This is an error message") } ```
### spinner/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/spinner/demo/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create and start a fork of the default spinner. spinnerInfo, _ := pterm.DefaultSpinner.Start("Some informational action...") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerInfo.Info() // Resolve spinner with error message. // Create and start a fork of the default spinner. spinnerSuccess, _ := pterm.DefaultSpinner.Start("Doing something important... (will succeed)") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerSuccess.Success() // Resolve spinner with success message. // Create and start a fork of the default spinner. spinnerWarning, _ := pterm.DefaultSpinner.Start("Doing something important... (will warn)") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerWarning.Warning() // Resolve spinner with warning message. // Create and start a fork of the default spinner. spinnerFail, _ := pterm.DefaultSpinner.Start("Doing something important... (will fail)") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerFail.Fail() // Resolve spinner with error message. // Create and start a fork of the default spinner. spinnerNochange, _ := pterm.DefaultSpinner.Start("Checking something important... (will result in no change)") // Replace the InfoPrinter with a custom "NOCHG" one spinnerNochange.InfoPrinter = &pterm.PrefixPrinter{ MessageStyle: &pterm.Style{pterm.FgLightBlue}, Prefix: pterm.Prefix{ Style: &pterm.Style{pterm.FgBlack, pterm.BgLightBlue}, Text: " NOCHG ", }, } time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerNochange.Info("No change were required") // Resolve spinner with error message. // Create and start a fork of the default spinner. spinnerLiveText, _ := pterm.DefaultSpinner.Start("Doing a lot of stuff...") time.Sleep(time.Second) // Simulate 2 seconds of processing something. spinnerLiveText.UpdateText("It's really much") // Update spinner text. time.Sleep(time.Second) // Simulate 2 seconds of processing something. spinnerLiveText.UpdateText("We're nearly done!") // Update spinner text. time.Sleep(time.Second) // Simulate 2 seconds of processing something. spinnerLiveText.Success("Finally!") // Resolve spinner with success message. } ```
### spinner/multiple ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/spinner/multiple/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create a multi printer. This allows multiple spinners to print simultaneously. multi := pterm.DefaultMultiPrinter // Create and start spinner 1 with a new writer from the multi printer. // The spinner will display the message "Spinner 1". spinner1, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 1") // Create and start spinner 2 with a new writer from the multi printer. // The spinner will display the message "Spinner 2". spinner2, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 2") // Create and start spinner 3 with a new writer from the multi printer. // The spinner will display the message "Spinner 3". spinner3, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 3") // Start the multi printer. This will start printing all the spinners. multi.Start() // Wait for 1 second. time.Sleep(time.Millisecond * 1000) // Stop spinner 1 with a success message. spinner1.Success("Spinner 1 is done!") // Wait for 750 milliseconds. time.Sleep(time.Millisecond * 750) // Stop spinner 2 with a failure message. spinner2.Fail("Spinner 2 failed!") // Wait for 500 milliseconds. time.Sleep(time.Millisecond * 500) // Stop spinner 3 with a warning message. spinner3.Warning("Spinner 3 has a warning!") // Stop the multi printer. This will stop printing all the spinners. multi.Stop() } ```
### style/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/style/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define a primary style with light cyan foreground, gray background, and bold text primary := pterm.NewStyle(pterm.FgLightCyan, pterm.BgGray, pterm.Bold) // Define a secondary style with light green foreground, white background, and italic text secondary := pterm.NewStyle(pterm.FgLightGreen, pterm.BgWhite, pterm.Italic) // Print "Hello, World!" with the primary style primary.Println("Hello, World!") // Print "Hello, World!" with the secondary style secondary.Println("Hello, World!") } ```
### table/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/table/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the first table tableData1 := pterm.TableData{ {"Firstname", "Lastname", "Email", "Note"}, {"Paul", "Dean", "augue@velitAliquam.co.uk", ""}, {"Callie", "Mckay", "nunc.sed@est.com", "这是一个测试, haha!"}, {"Libby", "Camacho", "lobortis@semper.com", "just a test, hey!"}, {"张", "小宝", "zhang@example.com", ""}, } // Create a table with a header and the defined data, then render it pterm.DefaultTable.WithHasHeader().WithData(tableData1).Render() pterm.Println() // Blank line // Define the data for the second table tableData2 := pterm.TableData{ {"Firstname", "Lastname", "Email"}, {"Paul\n\nNewline", "Dean", "augue@velitAliquam.co.uk"}, {"Callie", "Mckay", "nunc.sed@est.com\nNewline"}, {"Libby", "Camacho", "lobortis@semper.com"}, {"张", "小宝", "zhang@example.com"}, } // Create another table with a header and the defined data, then render it pterm.DefaultTable.WithHasHeader().WithData(tableData2).Render() } ```
### table/boxed ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/table/boxed/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the table. // Each inner slice represents a row in the table. // The first row is considered as the header of the table. tableData := pterm.TableData{ {"Firstname", "Lastname", "Email", "Note"}, {"Paul", "Dean", "augue@velitAliquam.co.uk", ""}, {"Callie", "Mckay", "nunc.sed@est.com", "这是一个测试, haha!"}, {"Libby", "Camacho", "lobortis@semper.com", "just a test, hey!"}, {"张", "小宝", "zhang@example.com", ""}, } // Create a table with the defined data. // The table has a header and is boxed. // Finally, render the table to print it. pterm.DefaultTable.WithHasHeader().WithBoxed().WithData(tableData).Render() } ```
### table/multiple-lines ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/table/multiple-lines/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the table. data := pterm.TableData{ {"Firstname", "Lastname", "Email"}, {"Paul\n\nNewline", "Dean", "augue@velitAliquam.co.uk"}, {"Callie", "Mckay", "nunc.sed@est.com\nNewline"}, {"Libby", "Camacho", "lobortis@semper.com"}, {"张", "小宝", "zhang@example.com"}, } // Create and render the table. // The options are chained in a single line for simplicity. // The table has a header, a row separator, and a header row separator. pterm.DefaultTable.WithHasHeader().WithRowSeparator("-").WithHeaderRowSeparator("-").WithData(data).Render() } ```
### table/right-alignment ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/table/right-alignment/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the table. // Each inner slice represents a row in the table. // The first row is considered as the header. tableData := pterm.TableData{ {"Firstname", "Lastname", "Email", "Note"}, {"Paul", "Dean", "augue@velitAliquam.co.uk", ""}, {"Callie", "Mckay", "nunc.sed@est.com", "这是一个测试, haha!"}, {"Libby", "Camacho", "lobortis@semper.com", "just a test, hey!"}, {"张", "小宝", "zhang@example.com", ""}, } // Create a table with the defined data. // The table has a header and the text in the cells is right-aligned. // The Render() method is used to print the table to the console. pterm.DefaultTable.WithHasHeader().WithRightAlignment().WithData(tableData).Render() } ```
### theme/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/theme/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "reflect" "time" ) func main() { // Print an informational message about the default theme styles. pterm.Info.Println("These are the default theme styles.\nYou can modify them easily to your personal preference,\nor create new themes from scratch :)") // Print a blank line for better readability. pterm.Println() // Get the value and type of the default theme. v := reflect.ValueOf(pterm.ThemeDefault) typeOfS := v.Type() // Check if the type of the default theme is 'pterm.Theme'. if typeOfS == reflect.TypeOf(pterm.Theme{}) { // Iterate over each field in the default theme. for i := 0; i < v.NumField(); i++ { // Try to convert the field to 'pterm.Style'. field, ok := v.Field(i).Interface().(pterm.Style) if ok { // Print the field name using its own style. field.Println(typeOfS.Field(i).Name) } // Pause for a quarter of a second to make the output easier to read. time.Sleep(time.Millisecond * 250) } } } ```
### tree/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/tree/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define a tree structure using pterm.TreeNode tree := pterm.TreeNode{ // The top node of the tree Text: "Top node", // The children of the top node Children: []pterm.TreeNode{{ // A child node Text: "Child node", // The children of the child node Children: []pterm.TreeNode{ // Grandchildren nodes {Text: "Grandchild node"}, {Text: "Grandchild node"}, {Text: "Grandchild node"}, }, }}, } // Render the tree with the defined structure as the root pterm.DefaultTree.WithRoot(tree).Render() } ```
### tree/from-leveled-list ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/tree/from-leveled-list/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Define a leveled list to represent the structure of the directories. leveledList := pterm.LeveledList{ {Level: 0, Text: "C:"}, {Level: 1, Text: "Users"}, {Level: 1, Text: "Windows"}, {Level: 1, Text: "Programs"}, {Level: 1, Text: "Programs(x86)"}, {Level: 1, Text: "dev"}, {Level: 0, Text: "D:"}, {Level: 0, Text: "E:"}, {Level: 1, Text: "Movies"}, {Level: 1, Text: "Music"}, {Level: 2, Text: "LinkinPark"}, {Level: 1, Text: "Games"}, {Level: 2, Text: "Shooter"}, {Level: 3, Text: "CallOfDuty"}, {Level: 3, Text: "CS:GO"}, {Level: 3, Text: "Battlefield"}, {Level: 4, Text: "Battlefield 1"}, {Level: 4, Text: "Battlefield 2"}, {Level: 0, Text: "F:"}, {Level: 1, Text: "dev"}, {Level: 2, Text: "dops"}, {Level: 2, Text: "PTerm"}, } // Convert the leveled list into a tree structure. root := putils.TreeFromLeveledList(leveledList) root.Text = "Computer" // Set the root node text. // Render the tree structure using the default tree printer. pterm.DefaultTree.WithRoot(root).Render() } ```
golang-github-pterm-pterm-0.12.79/_examples/area/000077500000000000000000000000001465010626300215635ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/area/README.md000066400000000000000000000147441465010626300230540ustar00rootroot00000000000000### area/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/area/demo/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Print an informational message using PTerm's Info printer. // This message will stay in place while the area updates. pterm.Info.Println("The previous text will stay in place, while the area updates.") // Print two new lines as spacer. pterm.Print("\n\n") // Start the Area printer from PTerm's DefaultArea, with the Center option. // The Area printer allows us to update a specific area of the console output. // The returned 'area' object is used to control the area updates. area, _ := pterm.DefaultArea.WithCenter().Start() // Loop 10 times to update the area with the current time. for i := 0; i < 10; i++ { // Get the current time, format it as "15:04:05" (hour:minute:second), and convert it to a string. // Then, create a BigText from the time string using PTerm's DefaultBigText and putils NewLettersFromString. // The Srender() function is used to save the BigText as a string. str, _ := pterm.DefaultBigText.WithLetters(putils.LettersFromString(time.Now().Format("15:04:05"))).Srender() // Update the Area contents with the current time string. area.Update(str) // Sleep for a second before the next update. time.Sleep(time.Second) } // Stop the Area printer after all updates are done. area.Stop() } ```
### area/center ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/area/center/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new default area in the center of the terminal. // The Start() function returns the created area and an error. area, _ := pterm.DefaultArea.WithCenter().Start() // Loop 5 times to simulate a dynamic update. for i := 0; i < 5; i++ { // Update the content of the area with the current count. // The Sprintf function is used to format the string. area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second to simulate a time-consuming task. time.Sleep(time.Second) } // Stop the area after all updates are done. area.Stop() } ```
### area/default ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/area/default/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new default area and get a reference to it. // The second return value is an error which is ignored here. area, _ := pterm.DefaultArea.Start() // Loop 5 times for i := 0; i < 5; i++ { // Update the content of the area dynamically. // Here we're just displaying the current count. area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second before the next update. time.Sleep(time.Second) } // Stop the area after all updates are done. // This will clean up and free resources used by the area. area.Stop() } ```
### area/dynamic-chart ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/area/dynamic-chart/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new fullscreen centered area. // This area will be used to display the bar chart. area, _ := pterm.DefaultArea.WithFullscreen().WithCenter().Start() // Ensure the area stops updating when we're done. defer area.Stop() // Loop to update the bar chart 10 times. for i := 0; i < 10; i++ { // Create a new bar chart with dynamic bars. // The bars will change based on the current iteration. barchart := pterm.DefaultBarChart.WithBars(dynamicBars(i)) // Render the bar chart to a string. // This string will be used to update the area. content, _ := barchart.Srender() // Update the area with the new bar chart. area.Update(content) // Wait for half a second before the next update. time.Sleep(500 * time.Millisecond) } } // dynamicBars generates a set of bars for the bar chart. // The bars will change based on the current iteration. func dynamicBars(i int) pterm.Bars { return pterm.Bars{ {Label: "A", Value: 10}, // A static bar. {Label: "B", Value: 20 * i}, // A bar that grows with each iteration. {Label: "C", Value: 30}, // Another static bar. {Label: "D", Value: 40 + i}, // A bar that grows slowly with each iteration. } } ```
### area/fullscreen ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/area/fullscreen/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new fullscreen area. This will return an area instance and an error. // The underscore (_) is used to ignore the error. area, _ := pterm.DefaultArea.WithFullscreen().Start() // Loop 5 times to update the area content. for i := 0; i < 5; i++ { // Update the content of the area with the current count. // The Sprintf function is used to format the string. area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second before the next update. time.Sleep(time.Second) } // Stop the area after all updates are done. area.Stop() } ```
### area/fullscreen-center ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/area/fullscreen-center/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Initialize a new PTerm area with fullscreen and center options // The Start() function returns the created area and an error (ignored here) area, _ := pterm.DefaultArea.WithFullscreen().WithCenter().Start() // Loop 5 times to demonstrate dynamic content update for i := 0; i < 5; i++ { // Update the content of the area with the current count // The Sprintf function is used to format the string with the count area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second time.Sleep(time.Second) } // Stop the area after all updates are done // This will clear the area and return the terminal to its normal state area.Stop() } ```
golang-github-pterm-pterm-0.12.79/_examples/area/center/000077500000000000000000000000001465010626300230435ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/area/center/README.md000066400000000000000000000013501465010626300243210ustar00rootroot00000000000000# area/center ![Animation](animation.svg) ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new default area in the center of the terminal. // The Start() function returns the created area and an error. area, _ := pterm.DefaultArea.WithCenter().Start() // Loop 5 times to simulate a dynamic update. for i := 0; i < 5; i++ { // Update the content of the area with the current count. // The Sprintf function is used to format the string. area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second to simulate a time-consuming task. time.Sleep(time.Second) } // Stop the area after all updates are done. area.Stop() } ``` golang-github-pterm-pterm-0.12.79/_examples/area/center/animation.svg000066400000000000000000000126521465010626300255510ustar00rootroot00000000000000Currentcount:0Areascanupdatetheircontentdynamically!Currentcount:1Currentcount:2Currentcount:3Currentcount:4Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/area/center/main.go000066400000000000000000000012611465010626300243160ustar00rootroot00000000000000package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new default area in the center of the terminal. // The Start() function returns the created area and an error. area, _ := pterm.DefaultArea.WithCenter().Start() // Loop 5 times to simulate a dynamic update. for i := 0; i < 5; i++ { // Update the content of the area with the current count. // The Sprintf function is used to format the string. area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second to simulate a time-consuming task. time.Sleep(time.Second) } // Stop the area after all updates are done. area.Stop() } golang-github-pterm-pterm-0.12.79/_examples/area/default/000077500000000000000000000000001465010626300232075ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/area/default/README.md000066400000000000000000000013321465010626300244650ustar00rootroot00000000000000# area/default ![Animation](animation.svg) ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new default area and get a reference to it. // The second return value is an error which is ignored here. area, _ := pterm.DefaultArea.Start() // Loop 5 times for i := 0; i < 5; i++ { // Update the content of the area dynamically. // Here we're just displaying the current count. area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second before the next update. time.Sleep(time.Second) } // Stop the area after all updates are done. // This will clean up and free resources used by the area. area.Stop() } ``` golang-github-pterm-pterm-0.12.79/_examples/area/default/animation.svg000066400000000000000000000102201465010626300257020ustar00rootroot00000000000000Currentcount:0Areascanupdatetheircontentdynamically!Currentcount:3Currentcount:4Currentcount:1Currentcount:2Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/area/default/main.go000066400000000000000000000012421465010626300244610ustar00rootroot00000000000000package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new default area and get a reference to it. // The second return value is an error which is ignored here. area, _ := pterm.DefaultArea.Start() // Loop 5 times for i := 0; i < 5; i++ { // Update the content of the area dynamically. // Here we're just displaying the current count. area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second before the next update. time.Sleep(time.Second) } // Stop the area after all updates are done. // This will clean up and free resources used by the area. area.Stop() } golang-github-pterm-pterm-0.12.79/_examples/area/demo/000077500000000000000000000000001465010626300225075ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/area/demo/README.md000066400000000000000000000026041465010626300237700ustar00rootroot00000000000000# area/demo ![Animation](animation.svg) ```go package main import ( "time" "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Print an informational message using PTerm's Info printer. // This message will stay in place while the area updates. pterm.Info.Println("The previous text will stay in place, while the area updates.") // Print two new lines as spacer. pterm.Print("\n\n") // Start the Area printer from PTerm's DefaultArea, with the Center option. // The Area printer allows us to update a specific area of the console output. // The returned 'area' object is used to control the area updates. area, _ := pterm.DefaultArea.WithCenter().Start() // Loop 10 times to update the area with the current time. for i := 0; i < 10; i++ { // Get the current time, format it as "15:04:05" (hour:minute:second), and convert it to a string. // Then, create a BigText from the time string using PTerm's DefaultBigText and putils NewLettersFromString. // The Srender() function is used to save the BigText as a string. str, _ := pterm.DefaultBigText.WithLetters(putils.LettersFromString(time.Now().Format("15:04:05"))).Srender() // Update the Area contents with the current time string. area.Update(str) // Sleep for a second before the next update. time.Sleep(time.Second) } // Stop the Area printer after all updates are done. area.Stop() } ``` golang-github-pterm-pterm-0.12.79/_examples/area/demo/animation.svg000066400000000000000000000543171465010626300252210ustar00rootroot00000000000000 INFO Theprevioustextwillstayinplace,whiletheareaupdates.████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/area/demo/main.go000066400000000000000000000025171465010626300237670ustar00rootroot00000000000000package main import ( "time" "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Print an informational message using PTerm's Info printer. // This message will stay in place while the area updates. pterm.Info.Println("The previous text will stay in place, while the area updates.") // Print two new lines as spacer. pterm.Print("\n\n") // Start the Area printer from PTerm's DefaultArea, with the Center option. // The Area printer allows us to update a specific area of the console output. // The returned 'area' object is used to control the area updates. area, _ := pterm.DefaultArea.WithCenter().Start() // Loop 10 times to update the area with the current time. for i := 0; i < 10; i++ { // Get the current time, format it as "15:04:05" (hour:minute:second), and convert it to a string. // Then, create a BigText from the time string using PTerm's DefaultBigText and putils NewLettersFromString. // The Srender() function is used to save the BigText as a string. str, _ := pterm.DefaultBigText.WithLetters(putils.LettersFromString(time.Now().Format("15:04:05"))).Srender() // Update the Area contents with the current time string. area.Update(str) // Sleep for a second before the next update. time.Sleep(time.Second) } // Stop the Area printer after all updates are done. area.Stop() } golang-github-pterm-pterm-0.12.79/_examples/area/dynamic-chart/000077500000000000000000000000001465010626300243065ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/area/dynamic-chart/README.md000066400000000000000000000024541465010626300255720ustar00rootroot00000000000000# area/dynamic-chart ![Animation](animation.svg) ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new fullscreen centered area. // This area will be used to display the bar chart. area, _ := pterm.DefaultArea.WithFullscreen().WithCenter().Start() // Ensure the area stops updating when we're done. defer area.Stop() // Loop to update the bar chart 10 times. for i := 0; i < 10; i++ { // Create a new bar chart with dynamic bars. // The bars will change based on the current iteration. barchart := pterm.DefaultBarChart.WithBars(dynamicBars(i)) // Render the bar chart to a string. // This string will be used to update the area. content, _ := barchart.Srender() // Update the area with the new bar chart. area.Update(content) // Wait for half a second before the next update. time.Sleep(500 * time.Millisecond) } } // dynamicBars generates a set of bars for the bar chart. // The bars will change based on the current iteration. func dynamicBars(i int) pterm.Bars { return pterm.Bars{ {Label: "A", Value: 10}, // A static bar. {Label: "B", Value: 20 * i}, // A bar that grows with each iteration. {Label: "C", Value: 30}, // Another static bar. {Label: "D", Value: 40 + i}, // A bar that grows slowly with each iteration. } } ``` golang-github-pterm-pterm-0.12.79/_examples/area/dynamic-chart/animation.svg000066400000000000000000001203221465010626300270060ustar00rootroot00000000000000████████████ABCD████████████████████Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/area/dynamic-chart/main.go000066400000000000000000000023561465010626300255670ustar00rootroot00000000000000package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new fullscreen centered area. // This area will be used to display the bar chart. area, _ := pterm.DefaultArea.WithFullscreen().WithCenter().Start() // Ensure the area stops updating when we're done. defer area.Stop() // Loop to update the bar chart 10 times. for i := 0; i < 10; i++ { // Create a new bar chart with dynamic bars. // The bars will change based on the current iteration. barchart := pterm.DefaultBarChart.WithBars(dynamicBars(i)) // Render the bar chart to a string. // This string will be used to update the area. content, _ := barchart.Srender() // Update the area with the new bar chart. area.Update(content) // Wait for half a second before the next update. time.Sleep(500 * time.Millisecond) } } // dynamicBars generates a set of bars for the bar chart. // The bars will change based on the current iteration. func dynamicBars(i int) pterm.Bars { return pterm.Bars{ {Label: "A", Value: 10}, // A static bar. {Label: "B", Value: 20 * i}, // A bar that grows with each iteration. {Label: "C", Value: 30}, // Another static bar. {Label: "D", Value: 40 + i}, // A bar that grows slowly with each iteration. } } golang-github-pterm-pterm-0.12.79/_examples/area/fullscreen-center/000077500000000000000000000000001465010626300252035ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/area/fullscreen-center/README.md000066400000000000000000000015231465010626300264630ustar00rootroot00000000000000# area/fullscreen-center ![Animation](animation.svg) ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Initialize a new PTerm area with fullscreen and center options // The Start() function returns the created area and an error (ignored here) area, _ := pterm.DefaultArea.WithFullscreen().WithCenter().Start() // Loop 5 times to demonstrate dynamic content update for i := 0; i < 5; i++ { // Update the content of the area with the current count // The Sprintf function is used to format the string with the count area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second time.Sleep(time.Second) } // Stop the area after all updates are done // This will clear the area and return the terminal to its normal state area.Stop() } ``` golang-github-pterm-pterm-0.12.79/_examples/area/fullscreen-center/animation.svg000066400000000000000000000167011465010626300277100ustar00rootroot00000000000000Currentcount:0Areascanupdatetheircontentdynamically!Currentcount:1Currentcount:2Currentcount:3Currentcount:4Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/area/fullscreen-center/main.go000066400000000000000000000014211465010626300264540ustar00rootroot00000000000000package main import ( "time" "github.com/pterm/pterm" ) func main() { // Initialize a new PTerm area with fullscreen and center options // The Start() function returns the created area and an error (ignored here) area, _ := pterm.DefaultArea.WithFullscreen().WithCenter().Start() // Loop 5 times to demonstrate dynamic content update for i := 0; i < 5; i++ { // Update the content of the area with the current count // The Sprintf function is used to format the string with the count area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second time.Sleep(time.Second) } // Stop the area after all updates are done // This will clear the area and return the terminal to its normal state area.Stop() } golang-github-pterm-pterm-0.12.79/_examples/area/fullscreen/000077500000000000000000000000001465010626300237255ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/area/fullscreen/README.md000066400000000000000000000013541465010626300252070ustar00rootroot00000000000000# area/fullscreen ![Animation](animation.svg) ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new fullscreen area. This will return an area instance and an error. // The underscore (_) is used to ignore the error. area, _ := pterm.DefaultArea.WithFullscreen().Start() // Loop 5 times to update the area content. for i := 0; i < 5; i++ { // Update the content of the area with the current count. // The Sprintf function is used to format the string. area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second before the next update. time.Sleep(time.Second) } // Stop the area after all updates are done. area.Stop() } ``` golang-github-pterm-pterm-0.12.79/_examples/area/fullscreen/animation.svg000066400000000000000000000210141465010626300264230ustar00rootroot00000000000000Currentcount:0Areascanupdatetheircontentdynamically!Currentcount:1Currentcount:2Currentcount:3Currentcount:4Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/area/fullscreen/main.go000066400000000000000000000012611465010626300252000ustar00rootroot00000000000000package main import ( "time" "github.com/pterm/pterm" ) func main() { // Start a new fullscreen area. This will return an area instance and an error. // The underscore (_) is used to ignore the error. area, _ := pterm.DefaultArea.WithFullscreen().Start() // Loop 5 times to update the area content. for i := 0; i < 5; i++ { // Update the content of the area with the current count. // The Sprintf function is used to format the string. area.Update(pterm.Sprintf("Current count: %d\nAreas can update their content dynamically!", i)) // Pause for a second before the next update. time.Sleep(time.Second) } // Stop the area after all updates are done. area.Stop() } golang-github-pterm-pterm-0.12.79/_examples/barchart/000077500000000000000000000000001465010626300224415ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/barchart/README.md000066400000000000000000000220361465010626300237230ustar00rootroot00000000000000### barchart/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the bars for the chart bars := []pterm.Bar{ {Label: "Bar 1", Value: 5}, {Label: "Bar 2", Value: 3}, {Label: "Longer Label", Value: 7}, } // Print an informational message pterm.Info.Println("Chart example with positive only values (bars use 100% of chart area)") // Create a bar chart with the defined bars and render it // The DefaultBarChart is used as a base, and the bars are added with the WithBars option // The Render function is then called to display the chart pterm.DefaultBarChart.WithBars(bars).Render() // Create a horizontal bar chart with the defined bars and render it // The DefaultBarChart is used as a base, the chart is made horizontal with the WithHorizontal option, and the bars are added with the WithBars option // The Render function is then called to display the chart pterm.DefaultBarChart.WithHorizontal().WithBars(bars).Render() } ```
### barchart/custom-height ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/custom-height/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define a slice of Bar structs. Each struct represents a bar in the chart. // The Label field is the name of the bar and the Value field is the height of the bar. bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create and render a bar chart with the defined bars and a height of 5. // The WithBars method is used to set the bars of the chart. // The WithHeight method is used to set the height of the chart. // The Render method is used to display the chart in the terminal. pterm.DefaultBarChart.WithBars(bars).WithHeight(5).Render() } ```
### barchart/custom-width ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/custom-width/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart barData := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined data // The chart is horizontal and has a width of 5 // The Render() function is called to display the chart pterm.DefaultBarChart.WithBars(barData).WithHorizontal().WithWidth(5).Render() } ```
### barchart/default ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/default/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart. Each bar is represented by a `pterm.Bar` struct. // The `Label` field represents the label of the bar, and the `Value` field represents the value of the bar. bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Use the `DefaultBarChart` from the `pterm` package to create a bar chart. // The `WithBars` method is used to set the bars of the chart. // The `Render` method is used to display the chart. pterm.DefaultBarChart.WithBars(bars).Render() } ```
### barchart/horizontal ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/horizontal/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined data // The chart is displayed horizontally // The Render() function is called to display the chart pterm.DefaultBarChart.WithBars(bars).WithHorizontal().Render() } ```
### barchart/horizontal-show-value ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/horizontal-show-value/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart barData := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined data // The chart is horizontal and displays the value of each bar // The Render() function is called to display the chart pterm.DefaultBarChart.WithBars(barData).WithHorizontal().WithShowValue().Render() } ```
### barchart/mixed-values ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/mixed-values/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define a set of bars for the chart. // Each bar has a label and a value. bars := []pterm.Bar{ {Label: "Bar 1", Value: 2}, {Label: "Bar 2", Value: -3}, {Label: "Bar 3", Value: -2}, {Label: "Bar 4", Value: 5}, {Label: "Longer Label", Value: 7}, } // Print a section header. // This is useful for separating different parts of the output. pterm.DefaultSection.Println("Chart example with mixed values (note screen space usage in case when ABSOLUTE values of negative and positive parts are differ too much)") // Create a bar chart with the defined bars. // The chart will display the value of each bar. // The Render() function is called to display the chart. pterm.DefaultBarChart.WithBars(bars).WithShowValue().Render() // Create a horizontal bar chart with the same bars. // The chart will display the value of each bar. // The Render() function is called to display the chart. pterm.DefaultBarChart.WithHorizontal().WithBars(bars).WithShowValue().Render() } ```
### barchart/negative-values ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/negative-values/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define a set of bars with negative values. // Each bar is represented by a struct with a label and a value. negativeBars := pterm.Bars{ {Label: "Bar 1", Value: -5}, {Label: "Bar 2", Value: -3}, {Label: "Longer Label", Value: -7}, } // Print an informational message to the console. pterm.Info.Println("Chart example with negative only values (bars use 100% of chart area)") // Create a vertical bar chart with the defined bars. // The WithShowValue() option is used to display the value of each bar in the chart. // The Render() method is called to draw the chart. _ = pterm.DefaultBarChart.WithBars(negativeBars).WithShowValue().Render() // Create a horizontal bar chart with the same bars. // The WithHorizontal() option is used to orient the chart horizontally. // The WithShowValue() option and Render() method are used in the same way as before. _ = pterm.DefaultBarChart.WithHorizontal().WithBars(negativeBars).WithShowValue().Render() } ```
### barchart/show-value ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/barchart/show-value/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define a slice of bars for the bar chart. Each bar is represented by a struct // with a Label and a Value. The Label is a string that represents the name of the bar, // and the Value is an integer that represents the height of the bar. bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined bars using the DefaultBarChart object from PTerm. // Chain the WithBars method to set the bars of the chart. // Chain the WithShowValue method to display the value of each bar on the chart. // Finally, call the Render method to display the chart. pterm.DefaultBarChart.WithBars(bars).WithShowValue().Render() } ```
golang-github-pterm-pterm-0.12.79/_examples/barchart/custom-height/000077500000000000000000000000001465010626300252215ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/barchart/custom-height/README.md000066400000000000000000000016011465010626300264760ustar00rootroot00000000000000# barchart/custom-height ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Define a slice of Bar structs. Each struct represents a bar in the chart. // The Label field is the name of the bar and the Value field is the height of the bar. bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create and render a bar chart with the defined bars and a height of 5. // The WithBars method is used to set the bars of the chart. // The WithHeight method is used to set the height of the chart. // The Render method is used to display the chart in the terminal. pterm.DefaultBarChart.WithBars(bars).WithHeight(5).Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/barchart/custom-height/animation.svg000066400000000000000000000104151465010626300277220ustar00rootroot00000000000000██████████████████████████████████████████████████ABCDEFGHIRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/barchart/custom-height/main.go000066400000000000000000000014771465010626300265050ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Define a slice of Bar structs. Each struct represents a bar in the chart. // The Label field is the name of the bar and the Value field is the height of the bar. bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create and render a bar chart with the defined bars and a height of 5. // The WithBars method is used to set the bars of the chart. // The WithHeight method is used to set the height of the chart. // The Render method is used to display the chart in the terminal. pterm.DefaultBarChart.WithBars(bars).WithHeight(5).Render() } golang-github-pterm-pterm-0.12.79/_examples/barchart/custom-width/000077500000000000000000000000001465010626300250705ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/barchart/custom-width/README.md000066400000000000000000000012351465010626300263500ustar00rootroot00000000000000# barchart/custom-width ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart barData := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined data // The chart is horizontal and has a width of 5 // The Render() function is called to display the chart pterm.DefaultBarChart.WithBars(barData).WithHorizontal().WithWidth(5).Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/barchart/custom-width/animation.svg000066400000000000000000000070451465010626300275760ustar00rootroot00000000000000AB██C███D████E█████F████G███H██IRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/barchart/custom-width/main.go000066400000000000000000000011341465010626300263420ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart barData := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined data // The chart is horizontal and has a width of 5 // The Render() function is called to display the chart pterm.DefaultBarChart.WithBars(barData).WithHorizontal().WithWidth(5).Render() } golang-github-pterm-pterm-0.12.79/_examples/barchart/default/000077500000000000000000000000001465010626300240655ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/barchart/default/README.md000066400000000000000000000015011465010626300253410ustar00rootroot00000000000000# barchart/default ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart. Each bar is represented by a `pterm.Bar` struct. // The `Label` field represents the label of the bar, and the `Value` field represents the value of the bar. bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Use the `DefaultBarChart` from the `pterm` package to create a bar chart. // The `WithBars` method is used to set the bars of the chart. // The `Render` method is used to display the chart. pterm.DefaultBarChart.WithBars(bars).Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/barchart/default/animation.svg000066400000000000000000000121501465010626300265640ustar00rootroot00000000000000██████████████████████████████████████████████████ABCDEFGHIRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/barchart/default/main.go000066400000000000000000000014051465010626300253400ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart. Each bar is represented by a `pterm.Bar` struct. // The `Label` field represents the label of the bar, and the `Value` field represents the value of the bar. bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Use the `DefaultBarChart` from the `pterm` package to create a bar chart. // The `WithBars` method is used to set the bars of the chart. // The `Render` method is used to display the chart. pterm.DefaultBarChart.WithBars(bars).Render() } golang-github-pterm-pterm-0.12.79/_examples/barchart/demo/000077500000000000000000000000001465010626300233655ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/barchart/demo/README.md000066400000000000000000000017671465010626300246570ustar00rootroot00000000000000# barchart/demo ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the bars for the chart bars := []pterm.Bar{ {Label: "Bar 1", Value: 5}, {Label: "Bar 2", Value: 3}, {Label: "Longer Label", Value: 7}, } // Print an informational message pterm.Info.Println("Chart example with positive only values (bars use 100% of chart area)") // Create a bar chart with the defined bars and render it // The DefaultBarChart is used as a base, and the bars are added with the WithBars option // The Render function is then called to display the chart pterm.DefaultBarChart.WithBars(bars).Render() // Create a horizontal bar chart with the defined bars and render it // The DefaultBarChart is used as a base, the chart is made horizontal with the WithHorizontal option, and the bars are added with the WithBars option // The Render function is then called to display the chart pterm.DefaultBarChart.WithHorizontal().WithBars(bars).Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/barchart/demo/animation.svg000066400000000000000000000756561465010626300261100ustar00rootroot00000000000000 INFO Chartexamplewithpositiveonlyvalues(barsuse100%ofchartarea)████████████Bar1Bar2LongerLabelBar1█████████████████████████████████████Bar2██████████████████████LongerLabel█████████████████████████████████████████████████████LongerLabel██████████████████████Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/barchart/demo/main.go000066400000000000000000000016761465010626300246520ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" ) func main() { // Define the bars for the chart bars := []pterm.Bar{ {Label: "Bar 1", Value: 5}, {Label: "Bar 2", Value: 3}, {Label: "Longer Label", Value: 7}, } // Print an informational message pterm.Info.Println("Chart example with positive only values (bars use 100% of chart area)") // Create a bar chart with the defined bars and render it // The DefaultBarChart is used as a base, and the bars are added with the WithBars option // The Render function is then called to display the chart pterm.DefaultBarChart.WithBars(bars).Render() // Create a horizontal bar chart with the defined bars and render it // The DefaultBarChart is used as a base, the chart is made horizontal with the WithHorizontal option, and the bars are added with the WithBars option // The Render function is then called to display the chart pterm.DefaultBarChart.WithHorizontal().WithBars(bars).Render() } golang-github-pterm-pterm-0.12.79/_examples/barchart/horizontal-show-value/000077500000000000000000000000001465010626300267225ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/barchart/horizontal-show-value/README.md000066400000000000000000000012671465010626300302070ustar00rootroot00000000000000# barchart/horizontal-show-value ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart barData := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined data // The chart is horizontal and displays the value of each bar // The Render() function is called to display the chart pterm.DefaultBarChart.WithBars(barData).WithHorizontal().WithShowValue().Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/barchart/horizontal-show-value/animation.svg000066400000000000000000000120341465010626300314220ustar00rootroot00000000000000A██████████10B█████████████████████20C███████████████████████████████30D██████████████████████████████████████████40E████████████████████████████████████████████████████50F██████████████████████████████████████████40G███████████████████████████████30H█████████████████████20I██████████10F██████████████████████Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/barchart/horizontal-show-value/main.go000066400000000000000000000011551465010626300301770ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart barData := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined data // The chart is horizontal and displays the value of each bar // The Render() function is called to display the chart pterm.DefaultBarChart.WithBars(barData).WithHorizontal().WithShowValue().Render() } golang-github-pterm-pterm-0.12.79/_examples/barchart/horizontal/000077500000000000000000000000001465010626300246325ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/barchart/horizontal/README.md000066400000000000000000000011771465010626300261170ustar00rootroot00000000000000# barchart/horizontal ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined data // The chart is displayed horizontally // The Render() function is called to display the chart pterm.DefaultBarChart.WithBars(bars).WithHorizontal().Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/barchart/horizontal/animation.svg000066400000000000000000000110621465010626300273320ustar00rootroot00000000000000A██████████B█████████████████████C███████████████████████████████D██████████████████████████████████████████E████████████████████████████████████████████████████F██████████████████████████████████████████G███████████████████████████████H█████████████████████I██████████F████████████████████Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/barchart/horizontal/main.go000066400000000000000000000011001465010626300260750ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Define the data for the bar chart bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined data // The chart is displayed horizontally // The Render() function is called to display the chart pterm.DefaultBarChart.WithBars(bars).WithHorizontal().Render() } golang-github-pterm-pterm-0.12.79/_examples/barchart/mixed-values/000077500000000000000000000000001465010626300250445ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/barchart/mixed-values/README.md000066400000000000000000000021411465010626300263210ustar00rootroot00000000000000# barchart/mixed-values ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define a set of bars for the chart. // Each bar has a label and a value. bars := []pterm.Bar{ {Label: "Bar 1", Value: 2}, {Label: "Bar 2", Value: -3}, {Label: "Bar 3", Value: -2}, {Label: "Bar 4", Value: 5}, {Label: "Longer Label", Value: 7}, } // Print a section header. // This is useful for separating different parts of the output. pterm.DefaultSection.Println("Chart example with mixed values (note screen space usage in case when ABSOLUTE values of negative and positive parts are differ too much)") // Create a bar chart with the defined bars. // The chart will display the value of each bar. // The Render() function is called to display the chart. pterm.DefaultBarChart.WithBars(bars).WithShowValue().Render() // Create a horizontal bar chart with the same bars. // The chart will display the value of each bar. // The Render() function is called to display the chart. pterm.DefaultBarChart.WithHorizontal().WithBars(bars).WithShowValue().Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/barchart/mixed-values/animation.svg000066400000000000000000000302751465010626300275530ustar00rootroot00000000000000#Chartexamplewithmixedvalues(notescreenspaceusageincasewhenABSOLUTEvaluesofnegativeandpositivepartsarediffertoomuch)257██████████████████-3-2Bar1Bar2Bar3Bar4LongerLabelBar1███████2Bar2███████████-3Bar3███████-2Bar4██████████████████5LongerLabel██████████████████████████7Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/barchart/mixed-values/main.go000066400000000000000000000020401465010626300263130ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" ) func main() { // Define a set of bars for the chart. // Each bar has a label and a value. bars := []pterm.Bar{ {Label: "Bar 1", Value: 2}, {Label: "Bar 2", Value: -3}, {Label: "Bar 3", Value: -2}, {Label: "Bar 4", Value: 5}, {Label: "Longer Label", Value: 7}, } // Print a section header. // This is useful for separating different parts of the output. pterm.DefaultSection.Println("Chart example with mixed values (note screen space usage in case when ABSOLUTE values of negative and positive parts are differ too much)") // Create a bar chart with the defined bars. // The chart will display the value of each bar. // The Render() function is called to display the chart. pterm.DefaultBarChart.WithBars(bars).WithShowValue().Render() // Create a horizontal bar chart with the same bars. // The chart will display the value of each bar. // The Render() function is called to display the chart. pterm.DefaultBarChart.WithHorizontal().WithBars(bars).WithShowValue().Render() } golang-github-pterm-pterm-0.12.79/_examples/barchart/negative-values/000077500000000000000000000000001465010626300255405ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/barchart/negative-values/README.md000066400000000000000000000021201465010626300270120ustar00rootroot00000000000000# barchart/negative-values ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define a set of bars with negative values. // Each bar is represented by a struct with a label and a value. negativeBars := pterm.Bars{ {Label: "Bar 1", Value: -5}, {Label: "Bar 2", Value: -3}, {Label: "Longer Label", Value: -7}, } // Print an informational message to the console. pterm.Info.Println("Chart example with negative only values (bars use 100% of chart area)") // Create a vertical bar chart with the defined bars. // The WithShowValue() option is used to display the value of each bar in the chart. // The Render() method is called to draw the chart. _ = pterm.DefaultBarChart.WithBars(negativeBars).WithShowValue().Render() // Create a horizontal bar chart with the same bars. // The WithHorizontal() option is used to orient the chart horizontally. // The WithShowValue() option and Render() method are used in the same way as before. _ = pterm.DefaultBarChart.WithHorizontal().WithBars(negativeBars).WithShowValue().Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/barchart/negative-values/animation.svg000066400000000000000000000275021465010626300302460ustar00rootroot00000000000000 INFO Chartexamplewithnegativeonlyvalues(barsuse100%ofchartarea)████████████-5-3-7Bar1Bar2LongerLabelBar1█████████████████████████████████████-5Bar2██████████████████████-3LongerLabel█████████████████████████████████████████████████████-7LongerLabel██████████████████████Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/barchart/negative-values/main.go000066400000000000000000000020141465010626300270100ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" ) func main() { // Define a set of bars with negative values. // Each bar is represented by a struct with a label and a value. negativeBars := pterm.Bars{ {Label: "Bar 1", Value: -5}, {Label: "Bar 2", Value: -3}, {Label: "Longer Label", Value: -7}, } // Print an informational message to the console. pterm.Info.Println("Chart example with negative only values (bars use 100% of chart area)") // Create a vertical bar chart with the defined bars. // The WithShowValue() option is used to display the value of each bar in the chart. // The Render() method is called to draw the chart. _ = pterm.DefaultBarChart.WithBars(negativeBars).WithShowValue().Render() // Create a horizontal bar chart with the same bars. // The WithHorizontal() option is used to orient the chart horizontally. // The WithShowValue() option and Render() method are used in the same way as before. _ = pterm.DefaultBarChart.WithHorizontal().WithBars(negativeBars).WithShowValue().Render() } golang-github-pterm-pterm-0.12.79/_examples/barchart/show-value/000077500000000000000000000000001465010626300245335ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/barchart/show-value/README.md000066400000000000000000000017361465010626300260210ustar00rootroot00000000000000# barchart/show-value ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Define a slice of bars for the bar chart. Each bar is represented by a struct // with a Label and a Value. The Label is a string that represents the name of the bar, // and the Value is an integer that represents the height of the bar. bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined bars using the DefaultBarChart object from PTerm. // Chain the WithBars method to set the bars of the chart. // Chain the WithShowValue method to display the value of each bar on the chart. // Finally, call the Render method to display the chart. pterm.DefaultBarChart.WithBars(bars).WithShowValue().Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/barchart/show-value/animation.svg000066400000000000000000000132431465010626300272360ustar00rootroot00000000000000102030405040302010██████████████████████████████████████████████████ABCDEFGHIRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/barchart/show-value/main.go000066400000000000000000000016371465010626300260150ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Define a slice of bars for the bar chart. Each bar is represented by a struct // with a Label and a Value. The Label is a string that represents the name of the bar, // and the Value is an integer that represents the height of the bar. bars := []pterm.Bar{ {Label: "A", Value: 10}, {Label: "B", Value: 20}, {Label: "C", Value: 30}, {Label: "D", Value: 40}, {Label: "E", Value: 50}, {Label: "F", Value: 40}, {Label: "G", Value: 30}, {Label: "H", Value: 20}, {Label: "I", Value: 10}, } // Create a bar chart with the defined bars using the DefaultBarChart object from PTerm. // Chain the WithBars method to set the bars of the chart. // Chain the WithShowValue method to display the value of each bar on the chart. // Finally, call the Render method to display the chart. pterm.DefaultBarChart.WithBars(bars).WithShowValue().Render() } golang-github-pterm-pterm-0.12.79/_examples/basictext/000077500000000000000000000000001465010626300226415ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/basictext/README.md000066400000000000000000000014471465010626300241260ustar00rootroot00000000000000### basictext/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/basictext/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // The DefaultBasicText is a basic text printer provided by PTerm. // It is used to print text without any special formatting. pterm.DefaultBasicText.Println("Default basic text printer.") // The DefaultBasicText can be used in any context that requires a TextPrinter. // Here, we're using it with the LightMagenta function to color a portion of the text. pterm.DefaultBasicText.Println("Can be used in any" + pterm.LightMagenta(" TextPrinter ") + "context.") // The DefaultBasicText is also useful for resolving progress bars and spinners. } ```
golang-github-pterm-pterm-0.12.79/_examples/basictext/demo/000077500000000000000000000000001465010626300235655ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/basictext/demo/README.md000066400000000000000000000012371465010626300250470ustar00rootroot00000000000000# basictext/demo ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // The DefaultBasicText is a basic text printer provided by PTerm. // It is used to print text without any special formatting. pterm.DefaultBasicText.Println("Default basic text printer.") // The DefaultBasicText can be used in any context that requires a TextPrinter. // Here, we're using it with the LightMagenta function to color a portion of the text. pterm.DefaultBasicText.Println("Can be used in any" + pterm.LightMagenta(" TextPrinter ") + "context.") // The DefaultBasicText is also useful for resolving progress bars and spinners. } ``` golang-github-pterm-pterm-0.12.79/_examples/basictext/demo/animation.svg000066400000000000000000000050251465010626300262670ustar00rootroot00000000000000Defaultbasictextprinter.CanbeusedinanyTextPrintercontext.Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/basictext/demo/main.go000066400000000000000000000011451465010626300250410ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // The DefaultBasicText is a basic text printer provided by PTerm. // It is used to print text without any special formatting. pterm.DefaultBasicText.Println("Default basic text printer.") // The DefaultBasicText can be used in any context that requires a TextPrinter. // Here, we're using it with the LightMagenta function to color a portion of the text. pterm.DefaultBasicText.Println("Can be used in any" + pterm.LightMagenta(" TextPrinter ") + "context.") // The DefaultBasicText is also useful for resolving progress bars and spinners. } golang-github-pterm-pterm-0.12.79/_examples/bigtext/000077500000000000000000000000001465010626300223215ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/bigtext/README.md000066400000000000000000000045771465010626300236150ustar00rootroot00000000000000### bigtext/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/bigtext/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Create a large text with the LetterStyle from the standard theme. // This is useful for creating title screens. pterm.DefaultBigText.WithLetters(putils.LettersFromString("PTerm")).Render() // Create a large text with differently colored letters. // Here, the first letter 'P' is colored cyan and the rest 'Term' is colored light magenta. // This can be used to highlight specific parts of the text. pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithStyle("P", pterm.FgCyan.ToStyle()), putils.LettersFromStringWithStyle("Term", pterm.FgLightMagenta.ToStyle()), ).Render() // Create a large text with a specific RGB color. // This can be used when you need a specific color that is not available in the standard colors. // Here, the color is gold (RGB: 255, 215, 0). pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithRGB("PTerm", pterm.NewRGB(255, 215, 0)), ).Render() } ```
### bigtext/colored ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/bigtext/colored/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Initialize a big text display with the letters "P" and "Term" // "P" is displayed in cyan and "Term" is displayed in light magenta pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithStyle("P", pterm.FgCyan.ToStyle()), putils.LettersFromStringWithStyle("Term", pterm.FgLightMagenta.ToStyle())). Render() // Render the big text to the terminal } ```
### bigtext/default ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/bigtext/default/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Define the text to be rendered var text = "PTerm" // Convert the text into a format suitable for PTerm var letters = putils.LettersFromString(text) // Render the text using PTerm's default big text style pterm.DefaultBigText.WithLetters(letters).Render() } ```
golang-github-pterm-pterm-0.12.79/_examples/bigtext/colored/000077500000000000000000000000001465010626300237505ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/bigtext/colored/README.md000066400000000000000000000010151465010626300252240ustar00rootroot00000000000000# bigtext/colored ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Initialize a big text display with the letters "P" and "Term" // "P" is displayed in cyan and "Term" is displayed in light magenta pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithStyle("P", pterm.FgCyan.ToStyle()), putils.LettersFromStringWithStyle("Term", pterm.FgLightMagenta.ToStyle())). Render() // Render the big text to the terminal } ``` golang-github-pterm-pterm-0.12.79/_examples/bigtext/colored/animation.svg000066400000000000000000000104311465010626300264470ustar00rootroot00000000000000███████████████████████████████████████████████████████████████████████████████████████████████████████████████████Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/bigtext/colored/main.go000066400000000000000000000007221465010626300252240ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Initialize a big text display with the letters "P" and "Term" // "P" is displayed in cyan and "Term" is displayed in light magenta pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithStyle("P", pterm.FgCyan.ToStyle()), putils.LettersFromStringWithStyle("Term", pterm.FgLightMagenta.ToStyle())). Render() // Render the big text to the terminal } golang-github-pterm-pterm-0.12.79/_examples/bigtext/default/000077500000000000000000000000001465010626300237455ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/bigtext/default/README.md000066400000000000000000000006521465010626300252270ustar00rootroot00000000000000# bigtext/default ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Define the text to be rendered var text = "PTerm" // Convert the text into a format suitable for PTerm var letters = putils.LettersFromString(text) // Render the text using PTerm's default big text style pterm.DefaultBigText.WithLetters(letters).Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/bigtext/default/animation.svg000066400000000000000000000103121465010626300264420ustar00rootroot00000000000000███████████████████████████████████████████████████████████████████████████████████████████████████████████████████Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/bigtext/default/main.go000066400000000000000000000005571465010626300252270ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Define the text to be rendered var text = "PTerm" // Convert the text into a format suitable for PTerm var letters = putils.LettersFromString(text) // Render the text using PTerm's default big text style pterm.DefaultBigText.WithLetters(letters).Render() } golang-github-pterm-pterm-0.12.79/_examples/bigtext/demo/000077500000000000000000000000001465010626300232455ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/bigtext/demo/README.md000066400000000000000000000020601465010626300245220ustar00rootroot00000000000000# bigtext/demo ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Create a large text with the LetterStyle from the standard theme. // This is useful for creating title screens. pterm.DefaultBigText.WithLetters(putils.LettersFromString("PTerm")).Render() // Create a large text with differently colored letters. // Here, the first letter 'P' is colored cyan and the rest 'Term' is colored light magenta. // This can be used to highlight specific parts of the text. pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithStyle("P", pterm.FgCyan.ToStyle()), putils.LettersFromStringWithStyle("Term", pterm.FgLightMagenta.ToStyle()), ).Render() // Create a large text with a specific RGB color. // This can be used when you need a specific color that is not available in the standard colors. // Here, the color is gold (RGB: 255, 215, 0). pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithRGB("PTerm", pterm.NewRGB(255, 215, 0)), ).Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/bigtext/demo/animation.svg000066400000000000000000000230231465010626300257450ustar00rootroot00000000000000█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/bigtext/demo/main.go000066400000000000000000000017701465010626300245250ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Create a large text with the LetterStyle from the standard theme. // This is useful for creating title screens. pterm.DefaultBigText.WithLetters(putils.LettersFromString("PTerm")).Render() // Create a large text with differently colored letters. // Here, the first letter 'P' is colored cyan and the rest 'Term' is colored light magenta. // This can be used to highlight specific parts of the text. pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithStyle("P", pterm.FgCyan.ToStyle()), putils.LettersFromStringWithStyle("Term", pterm.FgLightMagenta.ToStyle()), ).Render() // Create a large text with a specific RGB color. // This can be used when you need a specific color that is not available in the standard colors. // Here, the color is gold (RGB: 255, 215, 0). pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithRGB("PTerm", pterm.NewRGB(255, 215, 0)), ).Render() } golang-github-pterm-pterm-0.12.79/_examples/box/000077500000000000000000000000001465010626300214435ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/box/README.md000066400000000000000000000102421465010626300227210ustar00rootroot00000000000000### box/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/box/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Print an informational message. pterm.Info.Println("This might not be rendered correctly on GitHub,\nbut it will work in a real terminal.\nThis is because GitHub does not use a monospaced font by default for SVGs") // Create three panels with text, some of them with titles. // The panels are created using the DefaultBox style. panel1 := pterm.DefaultBox.Sprint("Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit,\nsed do eiusmod tempor incididunt\nut labore et dolore\nmagna aliqua.") panel2 := pterm.DefaultBox.WithTitle("title").Sprint("Ut enim ad minim veniam,\nquis nostrud exercitation\nullamco laboris\nnisi ut aliquip\nex ea commodo\nconsequat.") panel3 := pterm.DefaultBox.WithTitle("bottom center title").WithTitleBottomCenter().Sprint("Duis aute irure\ndolor in reprehenderit\nin voluptate velit esse cillum\ndolore eu fugiat\nnulla pariatur.") // Combine the panels into a layout using the DefaultPanel style. // The layout is a 2D grid, with each row being an array of panels. // In this case, the first row contains panel1 and panel2, and the second row contains only panel3. panels, _ := pterm.DefaultPanel.WithPanels(pterm.Panels{ {{Data: panel1}, {Data: panel2}}, {{Data: panel3}}, }).Srender() // Print the panels layout inside a box with a title. // The box is created using the DefaultBox style, with the title positioned at the bottom right. pterm.DefaultBox.WithTitle("Lorem Ipsum").WithTitleBottomRight().WithRightPadding(0).WithBottomPadding(0).Println(panels) } ```
### box/custom-padding ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/box/custom-padding/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a default box with custom padding options and print "Hello, World!" inside it. pterm.DefaultBox.WithRightPadding(10).WithLeftPadding(10).WithTopPadding(2).WithBottomPadding(2).Println("Hello, World!") } ```
### box/default ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/box/default/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a default box with PTerm and print a message in it. // The DefaultBox.Println method automatically starts, prints the message, and stops the box. pterm.DefaultBox.Println("Hello, World!") } ```
### box/title ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/box/title/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a default box with specified padding paddedBox := pterm.DefaultBox.WithLeftPadding(4).WithRightPadding(4).WithTopPadding(1).WithBottomPadding(1) // Define a title for the box title := pterm.LightRed("I'm a box!") // Create boxes with the title positioned differently and containing different content box1 := paddedBox.WithTitle(title).Sprint("Hello, World!\n 1") // Title at default position (top left) box2 := paddedBox.WithTitle(title).WithTitleTopCenter().Sprint("Hello, World!\n 2") // Title at top center box3 := paddedBox.WithTitle(title).WithTitleTopRight().Sprint("Hello, World!\n 3") // Title at top right box4 := paddedBox.WithTitle(title).WithTitleBottomRight().Sprint("Hello, World!\n 4") // Title at bottom right box5 := paddedBox.WithTitle(title).WithTitleBottomCenter().Sprint("Hello, World!\n 5") // Title at bottom center box6 := paddedBox.WithTitle(title).WithTitleBottomLeft().Sprint("Hello, World!\n 6") // Title at bottom left box7 := paddedBox.WithTitle(title).WithTitleTopLeft().Sprint("Hello, World!\n 7") // Title at top left // Render the boxes in a panel layout pterm.DefaultPanel.WithPanels([][]pterm.Panel{ {{box1}, {box2}, {box3}}, {{box4}, {box5}, {box6}}, {{box7}}, }).Render() } ```
golang-github-pterm-pterm-0.12.79/_examples/box/custom-padding/000077500000000000000000000000001465010626300243615ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/box/custom-padding/README.md000066400000000000000000000005221465010626300256370ustar00rootroot00000000000000# box/custom-padding ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Create a default box with custom padding options and print "Hello, World!" inside it. pterm.DefaultBox.WithRightPadding(10).WithLeftPadding(10).WithTopPadding(2).WithBottomPadding(2).Println("Hello, World!") } ``` golang-github-pterm-pterm-0.12.79/_examples/box/custom-padding/animation.svg000066400000000000000000000060171465010626300270650ustar00rootroot00000000000000┌─────────────────────────────────┐|||Hello,World!|└─────────────────────────────────┘Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/box/custom-padding/main.go000066400000000000000000000004241465010626300256340ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Create a default box with custom padding options and print "Hello, World!" inside it. pterm.DefaultBox.WithRightPadding(10).WithLeftPadding(10).WithTopPadding(2).WithBottomPadding(2).Println("Hello, World!") } golang-github-pterm-pterm-0.12.79/_examples/box/default/000077500000000000000000000000001465010626300230675ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/box/default/README.md000066400000000000000000000004771465010626300243560ustar00rootroot00000000000000# box/default ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Create a default box with PTerm and print a message in it. // The DefaultBox.Println method automatically starts, prints the message, and stops the box. pterm.DefaultBox.Println("Hello, World!") } ``` golang-github-pterm-pterm-0.12.79/_examples/box/default/animation.svg000066400000000000000000000047431465010626300255770ustar00rootroot00000000000000┌───────────────┐|Hello,World!|└───────────────┘Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/box/default/main.go000066400000000000000000000004101465010626300243350ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Create a default box with PTerm and print a message in it. // The DefaultBox.Println method automatically starts, prints the message, and stops the box. pterm.DefaultBox.Println("Hello, World!") } golang-github-pterm-pterm-0.12.79/_examples/box/demo/000077500000000000000000000000001465010626300223675ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/box/demo/README.md000066400000000000000000000031411465010626300236450ustar00rootroot00000000000000# box/demo ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Print an informational message. pterm.Info.Println("This might not be rendered correctly on GitHub,\nbut it will work in a real terminal.\nThis is because GitHub does not use a monospaced font by default for SVGs") // Create three panels with text, some of them with titles. // The panels are created using the DefaultBox style. panel1 := pterm.DefaultBox.Sprint("Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit,\nsed do eiusmod tempor incididunt\nut labore et dolore\nmagna aliqua.") panel2 := pterm.DefaultBox.WithTitle("title").Sprint("Ut enim ad minim veniam,\nquis nostrud exercitation\nullamco laboris\nnisi ut aliquip\nex ea commodo\nconsequat.") panel3 := pterm.DefaultBox.WithTitle("bottom center title").WithTitleBottomCenter().Sprint("Duis aute irure\ndolor in reprehenderit\nin voluptate velit esse cillum\ndolore eu fugiat\nnulla pariatur.") // Combine the panels into a layout using the DefaultPanel style. // The layout is a 2D grid, with each row being an array of panels. // In this case, the first row contains panel1 and panel2, and the second row contains only panel3. panels, _ := pterm.DefaultPanel.WithPanels(pterm.Panels{ {{Data: panel1}, {Data: panel2}}, {{Data: panel3}}, }).Srender() // Print the panels layout inside a box with a title. // The box is created using the DefaultBox style, with the title positioned at the bottom right. pterm.DefaultBox.WithTitle("Lorem Ipsum").WithTitleBottomRight().WithRightPadding(0).WithBottomPadding(0).Println(panels) } ``` golang-github-pterm-pterm-0.12.79/_examples/box/demo/animation.svg000066400000000000000000001070201465010626300250670ustar00rootroot00000000000000 INFO ThismightnotberenderedcorrectlyonGitHub, butitwillworkinarealterminal. ThisisbecauseGitHubdoesnotuseamonospacedfontbydefaultforSVGs┌────────────────────────────────────────────────────────────────────┐|┌──────────────────────────────────┐┌─title───────────────────┐|||Loremipsumdolorsitamet,||Utenimadminimveniam,||||consecteturadipiscingelit,||quisnostrudexercitation||||seddoeiusmodtemporincididunt||ullamcolaboris||||utlaboreetdolore||nisiutaliquip||||magnaaliqua.||exeacommodo|||└──────────────────────────────────┘|consequat.|||└───────────────────────────┘||┌────────────────────────────────┐|||Duisauteirure||||dolorinreprehenderit||||involuptatevelitessecillum||||doloreeufugiat||||nullapariatur.|||└─────bottomcentertitle──────┘|||└──────────────────────────────────────────────────────LoremIpsum─┘|┌─────────────────|||└──────────────────────────────────|┌──────────────────────────|Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/box/demo/main.go000066400000000000000000000030551465010626300236450ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Print an informational message. pterm.Info.Println("This might not be rendered correctly on GitHub,\nbut it will work in a real terminal.\nThis is because GitHub does not use a monospaced font by default for SVGs") // Create three panels with text, some of them with titles. // The panels are created using the DefaultBox style. panel1 := pterm.DefaultBox.Sprint("Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit,\nsed do eiusmod tempor incididunt\nut labore et dolore\nmagna aliqua.") panel2 := pterm.DefaultBox.WithTitle("title").Sprint("Ut enim ad minim veniam,\nquis nostrud exercitation\nullamco laboris\nnisi ut aliquip\nex ea commodo\nconsequat.") panel3 := pterm.DefaultBox.WithTitle("bottom center title").WithTitleBottomCenter().Sprint("Duis aute irure\ndolor in reprehenderit\nin voluptate velit esse cillum\ndolore eu fugiat\nnulla pariatur.") // Combine the panels into a layout using the DefaultPanel style. // The layout is a 2D grid, with each row being an array of panels. // In this case, the first row contains panel1 and panel2, and the second row contains only panel3. panels, _ := pterm.DefaultPanel.WithPanels(pterm.Panels{ {{Data: panel1}, {Data: panel2}}, {{Data: panel3}}, }).Srender() // Print the panels layout inside a box with a title. // The box is created using the DefaultBox style, with the title positioned at the bottom right. pterm.DefaultBox.WithTitle("Lorem Ipsum").WithTitleBottomRight().WithRightPadding(0).WithBottomPadding(0).Println(panels) } golang-github-pterm-pterm-0.12.79/_examples/box/title/000077500000000000000000000000001465010626300225645ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/box/title/README.md000066400000000000000000000026321465010626300240460ustar00rootroot00000000000000# box/title ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Create a default box with specified padding paddedBox := pterm.DefaultBox.WithLeftPadding(4).WithRightPadding(4).WithTopPadding(1).WithBottomPadding(1) // Define a title for the box title := pterm.LightRed("I'm a box!") // Create boxes with the title positioned differently and containing different content box1 := paddedBox.WithTitle(title).Sprint("Hello, World!\n 1") // Title at default position (top left) box2 := paddedBox.WithTitle(title).WithTitleTopCenter().Sprint("Hello, World!\n 2") // Title at top center box3 := paddedBox.WithTitle(title).WithTitleTopRight().Sprint("Hello, World!\n 3") // Title at top right box4 := paddedBox.WithTitle(title).WithTitleBottomRight().Sprint("Hello, World!\n 4") // Title at bottom right box5 := paddedBox.WithTitle(title).WithTitleBottomCenter().Sprint("Hello, World!\n 5") // Title at bottom center box6 := paddedBox.WithTitle(title).WithTitleBottomLeft().Sprint("Hello, World!\n 6") // Title at bottom left box7 := paddedBox.WithTitle(title).WithTitleTopLeft().Sprint("Hello, World!\n 7") // Title at top left // Render the boxes in a panel layout pterm.DefaultPanel.WithPanels([][]pterm.Panel{ {{box1}, {box2}, {box3}}, {{box4}, {box5}, {box6}}, {{box7}}, }).Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/box/title/animation.svg000066400000000000000000000217751465010626300253000ustar00rootroot00000000000000┌─I'mabox!────────┐┌────I'mabox!─────┐┌────────I'mabox!─┐|||||||Hello,World!||Hello,World!||Hello,World!||1||2||3|└─────────────────────┘└─────────────────────┘└─────────────────────┘┌─────────────────────┐┌─────────────────────┐┌─────────────────────┐|4||5||6|└────────I'mabox!─┘└────I'mabox!─────┘└─I'mabox!────────┘┌─I'mabox!────────┐|||Hello,World!||7|└─────────────────────┘|||Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/box/title/main.go000066400000000000000000000025451465010626300240450ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Create a default box with specified padding paddedBox := pterm.DefaultBox.WithLeftPadding(4).WithRightPadding(4).WithTopPadding(1).WithBottomPadding(1) // Define a title for the box title := pterm.LightRed("I'm a box!") // Create boxes with the title positioned differently and containing different content box1 := paddedBox.WithTitle(title).Sprint("Hello, World!\n 1") // Title at default position (top left) box2 := paddedBox.WithTitle(title).WithTitleTopCenter().Sprint("Hello, World!\n 2") // Title at top center box3 := paddedBox.WithTitle(title).WithTitleTopRight().Sprint("Hello, World!\n 3") // Title at top right box4 := paddedBox.WithTitle(title).WithTitleBottomRight().Sprint("Hello, World!\n 4") // Title at bottom right box5 := paddedBox.WithTitle(title).WithTitleBottomCenter().Sprint("Hello, World!\n 5") // Title at bottom center box6 := paddedBox.WithTitle(title).WithTitleBottomLeft().Sprint("Hello, World!\n 6") // Title at bottom left box7 := paddedBox.WithTitle(title).WithTitleTopLeft().Sprint("Hello, World!\n 7") // Title at top left // Render the boxes in a panel layout pterm.DefaultPanel.WithPanels([][]pterm.Panel{ {{box1}, {box2}, {box3}}, {{box4}, {box5}, {box6}}, {{box7}}, }).Render() } golang-github-pterm-pterm-0.12.79/_examples/bulletlist/000077500000000000000000000000001465010626300230365ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/bulletlist/README.md000066400000000000000000000045011465010626300243150ustar00rootroot00000000000000### bulletlist/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/bulletlist/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Define a list of bullet list items with different levels. bulletListItems := []pterm.BulletListItem{ {Level: 0, Text: "Level 0"}, // Level 0 item {Level: 1, Text: "Level 1"}, // Level 1 item {Level: 2, Text: "Level 2"}, // Level 2 item } // Use the default bullet list style to render the list items. pterm.DefaultBulletList.WithItems(bulletListItems).Render() // Define a string with different levels of indentation. text := `0 1 2 3` // Convert the indented string to a bullet list and render it. putils.BulletListFromString(text, " ").Render() } ```
### bulletlist/customized ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/bulletlist/customized/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define a list of bullet list items with different styles and levels. bulletListItems := []pterm.BulletListItem{ { Level: 0, // Level 0 (top level) Text: "Blue", // Text to display TextStyle: pterm.NewStyle(pterm.FgBlue), // Text color BulletStyle: pterm.NewStyle(pterm.FgRed), // Bullet color }, { Level: 1, // Level 1 (sub-item) Text: "Green", // Text to display TextStyle: pterm.NewStyle(pterm.FgGreen), // Text color Bullet: "-", // Custom bullet symbol BulletStyle: pterm.NewStyle(pterm.FgLightWhite), // Bullet color }, { Level: 2, // Level 2 (sub-sub-item) Text: "Cyan", // Text to display TextStyle: pterm.NewStyle(pterm.FgCyan), // Text color Bullet: ">", // Custom bullet symbol BulletStyle: pterm.NewStyle(pterm.FgYellow), // Bullet color }, } // Create a bullet list with the defined items and render it. pterm.DefaultBulletList.WithItems(bulletListItems).Render() } ```
golang-github-pterm-pterm-0.12.79/_examples/bulletlist/customized/000077500000000000000000000000001465010626300252245ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/bulletlist/customized/README.md000066400000000000000000000025131465010626300265040ustar00rootroot00000000000000# bulletlist/customized ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define a list of bullet list items with different styles and levels. bulletListItems := []pterm.BulletListItem{ { Level: 0, // Level 0 (top level) Text: "Blue", // Text to display TextStyle: pterm.NewStyle(pterm.FgBlue), // Text color BulletStyle: pterm.NewStyle(pterm.FgRed), // Bullet color }, { Level: 1, // Level 1 (sub-item) Text: "Green", // Text to display TextStyle: pterm.NewStyle(pterm.FgGreen), // Text color Bullet: "-", // Custom bullet symbol BulletStyle: pterm.NewStyle(pterm.FgLightWhite), // Bullet color }, { Level: 2, // Level 2 (sub-sub-item) Text: "Cyan", // Text to display TextStyle: pterm.NewStyle(pterm.FgCyan), // Text color Bullet: ">", // Custom bullet symbol BulletStyle: pterm.NewStyle(pterm.FgYellow), // Bullet color }, } // Create a bullet list with the defined items and render it. pterm.DefaultBulletList.WithItems(bulletListItems).Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/bulletlist/customized/animation.svg000066400000000000000000000051521465010626300277270ustar00rootroot00000000000000Blue-Green>CyanRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/bulletlist/customized/main.go000066400000000000000000000024121465010626300264760ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" ) func main() { // Define a list of bullet list items with different styles and levels. bulletListItems := []pterm.BulletListItem{ { Level: 0, // Level 0 (top level) Text: "Blue", // Text to display TextStyle: pterm.NewStyle(pterm.FgBlue), // Text color BulletStyle: pterm.NewStyle(pterm.FgRed), // Bullet color }, { Level: 1, // Level 1 (sub-item) Text: "Green", // Text to display TextStyle: pterm.NewStyle(pterm.FgGreen), // Text color Bullet: "-", // Custom bullet symbol BulletStyle: pterm.NewStyle(pterm.FgLightWhite), // Bullet color }, { Level: 2, // Level 2 (sub-sub-item) Text: "Cyan", // Text to display TextStyle: pterm.NewStyle(pterm.FgCyan), // Text color Bullet: ">", // Custom bullet symbol BulletStyle: pterm.NewStyle(pterm.FgYellow), // Bullet color }, } // Create a bullet list with the defined items and render it. pterm.DefaultBulletList.WithItems(bulletListItems).Render() } golang-github-pterm-pterm-0.12.79/_examples/bulletlist/demo/000077500000000000000000000000001465010626300237625ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/bulletlist/demo/README.md000066400000000000000000000013361465010626300252440ustar00rootroot00000000000000# bulletlist/demo ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Define a list of bullet list items with different levels. bulletListItems := []pterm.BulletListItem{ {Level: 0, Text: "Level 0"}, // Level 0 item {Level: 1, Text: "Level 1"}, // Level 1 item {Level: 2, Text: "Level 2"}, // Level 2 item } // Use the default bullet list style to render the list items. pterm.DefaultBulletList.WithItems(bulletListItems).Render() // Define a string with different levels of indentation. text := `0 1 2 3` // Convert the indented string to a bullet list and render it. putils.BulletListFromString(text, " ").Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/bulletlist/demo/animation.svg000066400000000000000000000067161465010626300264740ustar00rootroot00000000000000Level0Level1Level20123Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/bulletlist/demo/main.go000066400000000000000000000012431465010626300252350ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Define a list of bullet list items with different levels. bulletListItems := []pterm.BulletListItem{ {Level: 0, Text: "Level 0"}, // Level 0 item {Level: 1, Text: "Level 1"}, // Level 1 item {Level: 2, Text: "Level 2"}, // Level 2 item } // Use the default bullet list style to render the list items. pterm.DefaultBulletList.WithItems(bulletListItems).Render() // Define a string with different levels of indentation. text := `0 1 2 3` // Convert the indented string to a bullet list and render it. putils.BulletListFromString(text, " ").Render() } golang-github-pterm-pterm-0.12.79/_examples/center/000077500000000000000000000000001465010626300221335ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/center/README.md000066400000000000000000000015671465010626300234230ustar00rootroot00000000000000### center/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/center/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Print a block of text centered in the terminal pterm.DefaultCenter.Println("This text is centered!\nIt centers the whole block by default.\nIn that way you can do stuff like this:") // Generate BigLetters and store in 's' s, _ := pterm.DefaultBigText.WithLetters(putils.LettersFromString("PTerm")).Srender() // Print the BigLetters 's' centered in the terminal pterm.DefaultCenter.Println(s) // Print each line of the text separately centered in the terminal pterm.DefaultCenter.WithCenterEachLineSeparately().Println("This text is centered!\nBut each line is\ncentered\nseparately") } ```
golang-github-pterm-pterm-0.12.79/_examples/center/demo/000077500000000000000000000000001465010626300230575ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/center/demo/README.md000066400000000000000000000013621465010626300243400ustar00rootroot00000000000000# center/demo ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Print a block of text centered in the terminal pterm.DefaultCenter.Println("This text is centered!\nIt centers the whole block by default.\nIn that way you can do stuff like this:") // Generate BigLetters and store in 's' s, _ := pterm.DefaultBigText.WithLetters(putils.LettersFromString("PTerm")).Srender() // Print the BigLetters 's' centered in the terminal pterm.DefaultCenter.Println(s) // Print each line of the text separately centered in the terminal pterm.DefaultCenter.WithCenterEachLineSeparately().Println("This text is centered!\nBut each line is\ncentered\nseparately") } ``` golang-github-pterm-pterm-0.12.79/_examples/center/demo/animation.svg000066400000000000000000000152221465010626300255610ustar00rootroot00000000000000Thistextiscentered!Itcentersthewholeblockbydefault.Inthatwayyoucandostufflikethis:███████████████████████████████████████████████████████████████████████████████████████████████████████████████████Thistextiscentered!ButeachlineiscenteredseparatelyRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/center/demo/main.go000066400000000000000000000012731465010626300243350ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Print a block of text centered in the terminal pterm.DefaultCenter.Println("This text is centered!\nIt centers the whole block by default.\nIn that way you can do stuff like this:") // Generate BigLetters and store in 's' s, _ := pterm.DefaultBigText.WithLetters(putils.LettersFromString("PTerm")).Srender() // Print the BigLetters 's' centered in the terminal pterm.DefaultCenter.Println(s) // Print each line of the text separately centered in the terminal pterm.DefaultCenter.WithCenterEachLineSeparately().Println("This text is centered!\nBut each line is\ncentered\nseparately") } golang-github-pterm-pterm-0.12.79/_examples/coloring/000077500000000000000000000000001465010626300224675ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/coloring/README.md000066400000000000000000000251351465010626300237540ustar00rootroot00000000000000### coloring/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a table with different foreground and background colors. pterm.DefaultTable.WithData([][]string{ {pterm.FgBlack.Sprint("Black"), pterm.FgRed.Sprint("Red"), pterm.FgGreen.Sprint("Green"), pterm.FgYellow.Sprint("Yellow")}, {"", pterm.FgLightRed.Sprint("Light Red"), pterm.FgLightGreen.Sprint("Light Green"), pterm.FgLightYellow.Sprint("Light Yellow")}, {pterm.BgBlack.Sprint("Black"), pterm.BgRed.Sprint("Red"), pterm.BgGreen.Sprint("Green"), pterm.BgYellow.Sprint("Yellow")}, {"", pterm.BgLightRed.Sprint("Light Red"), pterm.BgLightGreen.Sprint("Light Green"), pterm.BgLightYellow.Sprint("Light Yellow")}, {pterm.FgBlue.Sprint("Blue"), pterm.FgMagenta.Sprint("Magenta"), pterm.FgCyan.Sprint("Cyan"), pterm.FgWhite.Sprint("White")}, {pterm.FgLightBlue.Sprint("Light Blue"), pterm.FgLightMagenta.Sprint("Light Magenta"), pterm.FgLightCyan.Sprint("Light Cyan"), pterm.FgLightWhite.Sprint("Light White")}, {pterm.BgBlue.Sprint("Blue"), pterm.BgMagenta.Sprint("Magenta"), pterm.BgCyan.Sprint("Cyan"), pterm.BgWhite.Sprint("White")}, {pterm.BgLightBlue.Sprint("Light Blue"), pterm.BgLightMagenta.Sprint("Light Magenta"), pterm.BgLightCyan.Sprint("Light Cyan"), pterm.BgLightWhite.Sprint("Light White")}, }).Render() // Render the table. pterm.Println() // Print words in different colors. pterm.Println(pterm.Red("Hello, ") + pterm.Green("World") + pterm.Cyan("!")) pterm.Println(pterm.Red("Even " + pterm.Cyan("nested ") + pterm.Green("colors ") + "are supported!")) pterm.Println() // Create a new style with a red background, light green foreground, and bold text. style := pterm.NewStyle(pterm.BgRed, pterm.FgLightGreen, pterm.Bold) // Print text using the created style. style.Println("This text uses a style and is bold and light green with a red background!") } ```
### coloring/disable-output ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/disable-output/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Loop from 0 to 14 for i := 0; i < 15; i++ { switch i { case 5: // At the 5th iteration, print a message and disable the output pterm.Info.Println("Disabled Output!") pterm.DisableOutput() case 10: // At the 10th iteration, enable the output and print a message pterm.EnableOutput() pterm.Info.Println("Enabled Output!") } // Print a progress message for each iteration pterm.Printf("Printing something... [%d/%d]\n", i, 15) } } ```
### coloring/fade-colors ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/fade-colors/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Print an informational message. pterm.Info.Println("RGB colors only work in Terminals which support TrueColor.") // Define the start and end points for the color gradient. startColor := pterm.NewRGB(0, 255, 255) // Cyan endColor := pterm.NewRGB(255, 0, 255) // Magenta // Get the terminal height to determine the gradient range. terminalHeight := pterm.GetTerminalHeight() // Loop over the range of the terminal height to create a color gradient. for i := 0; i < terminalHeight-2; i++ { // Calculate the fade factor for the current step in the gradient. fadeFactor := float32(i) / float32(terminalHeight-2) // Create a color that represents the current step in the gradient. currentColor := startColor.Fade(0, 1, fadeFactor, endColor) // Print a string with the current color. currentColor.Println("Hello, World!") } } ```
### coloring/fade-colors-rgb-style ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/fade-colors-rgb-style/animation.svg)
SHOW SOURCE ```go package main import ( "strings" "github.com/pterm/pterm" ) func main() { // Define RGB colors white := pterm.NewRGB(255, 255, 255) grey := pterm.NewRGB(128, 128, 128) black := pterm.NewRGB(0, 0, 0) red := pterm.NewRGB(255, 0, 0) purple := pterm.NewRGB(255, 0, 255) green := pterm.NewRGB(0, 255, 0) // Define strings to be printed str1 := "RGB colors only work in Terminals which support TrueColor." str2 := "The background and foreground colors can be customized individually." str3 := "Styles can also be applied. For example: Bold or Italic." // Print first string with color fading from white to purple printFadedString(str1, white, purple, grey, black) // Print second string with color fading from purple to red printFadedString(str2, black, purple, red, red) // Print third string with color fading from white to green and style changes printStyledString(str3, white, green, red, black) } // printFadedString prints a string with color fading effect func printFadedString(str string, fgStart, fgEnd, bgStart, bgEnd pterm.RGB) { strs := strings.Split(str, "") var result string for i := 0; i < len(str); i++ { // Create a style with color fading effect style := pterm.NewRGBStyle(fgStart.Fade(0, float32(len(str)), float32(i), fgEnd), bgStart.Fade(0, float32(len(str)), float32(i), bgEnd)) // Append styled letter to result string result += style.Sprint(strs[i]) } pterm.Println(result) } // printStyledString prints a string with color fading and style changes func printStyledString(str string, fgStart, fgEnd, bgStart, bgEnd pterm.RGB) { strs := strings.Split(str, "") var result string boldStr := strings.Split("Bold", "") italicStr := strings.Split("Italic", "") bold, italic := 0, 0 for i := 0; i < len(str); i++ { // Create a style with color fading effect style := pterm.NewRGBStyle(fgStart.Fade(0, float32(len(str)), float32(i), fgEnd), bgStart.Fade(0, float32(len(str)), float32(i), bgEnd)) // Check if the next letters are "Bold" or "Italic" and add the corresponding style if bold < len(boldStr) && i+len(boldStr)-bold <= len(strs) && strings.Join(strs[i:i+len(boldStr)-bold], "") == strings.Join(boldStr[bold:], "") { style = style.AddOptions(pterm.Bold) bold++ } else if italic < len(italicStr) && i+len(italicStr)-italic < len(strs) && strings.Join(strs[i:i+len(italicStr)-italic], "") == strings.Join(italicStr[italic:], "") { style = style.AddOptions(pterm.Italic) italic++ } // Append styled letter to result string result += style.Sprint(strs[i]) } pterm.Println(result) } ```
### coloring/fade-multiple-colors ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/fade-multiple-colors/animation.svg)
SHOW SOURCE ```go package main import ( "strings" "github.com/pterm/pterm" ) func main() { // Define RGB values for gradient points. startColor := pterm.NewRGB(0, 255, 255) firstPoint := pterm.NewRGB(255, 0, 255) secondPoint := pterm.NewRGB(255, 0, 0) thirdPoint := pterm.NewRGB(0, 255, 0) endColor := pterm.NewRGB(255, 255, 255) // Define the string to be printed. str := "RGB colors only work in Terminals which support TrueColor." strs := strings.Split(str, "") // Initialize an empty string for the faded info. var fadeInfo string // Loop over the string length to create a gradient effect. for i := 0; i < len(str); i++ { // Append each character of the string with a faded color to the info string. fadeInfo += startColor.Fade(0, float32(len(str)), float32(i), firstPoint).Sprint(strs[i]) } // Print the info string with gradient effect. pterm.Info.Println(fadeInfo) // Get the terminal height. terminalHeight := pterm.GetTerminalHeight() // Loop over the terminal height to print "Hello, World!" with a gradient effect. for i := 0; i < terminalHeight-2; i++ { // Print the string with a color that fades from startColor to endColor. startColor.Fade(0, float32(terminalHeight-2), float32(i), firstPoint, secondPoint, thirdPoint, endColor).Println("Hello, World!") } } ```
### coloring/override-default-printers ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/override-default-printers/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Print a default error message with PTerm's built-in Error style. pterm.Error.Println("This is the default Error") // Override the default error prefix with a new text and style. pterm.Error.Prefix = pterm.Prefix{Text: "OVERRIDE", Style: pterm.NewStyle(pterm.BgCyan, pterm.FgRed)} // Print the error message again, this time with the overridden prefix. pterm.Error.Println("This is the default Error after the prefix was overridden") } ```
### coloring/print-color-rgb ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/print-color-rgb/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a new RGB color with values 178, 44, 199. // This color will be used for the text. pterm.NewRGB(178, 44, 199).Println("This text is printed with a custom RGB!") // Create a new RGB color with values 15, 199, 209. // This color will be used for the text. pterm.NewRGB(15, 199, 209).Println("This text is printed with a custom RGB!") // Create a new RGB color with values 201, 144, 30. // This color will be used for the background. // The 'true' argument indicates that the color is for the background. pterm.NewRGB(201, 144, 30, true).Println("This text is printed with a custom RGB background!") } ```
### coloring/print-color-rgb-style ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/coloring/print-color-rgb-style/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define RGB colors for foreground and background. foregroundRGB := pterm.RGB{R: 187, G: 80, B: 0} backgroundRGB := pterm.RGB{R: 0, G: 50, B: 123} // Create a new RGB style with the defined foreground and background colors. rgbStyle := pterm.NewRGBStyle(foregroundRGB, backgroundRGB) // Print a string with the custom RGB style. rgbStyle.Println("This text is not styled.") // Add the 'Bold' option to the RGB style and print a string with this style. rgbStyle.AddOptions(pterm.Bold).Println("This text is bold.") // Add the 'Italic' option to the RGB style and print a string with this style. rgbStyle.AddOptions(pterm.Italic).Println("This text is italic.") } ```
golang-github-pterm-pterm-0.12.79/_examples/coloring/demo/000077500000000000000000000000001465010626300234135ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/coloring/demo/README.md000066400000000000000000000036021465010626300246730ustar00rootroot00000000000000# coloring/demo ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Create a table with different foreground and background colors. pterm.DefaultTable.WithData([][]string{ {pterm.FgBlack.Sprint("Black"), pterm.FgRed.Sprint("Red"), pterm.FgGreen.Sprint("Green"), pterm.FgYellow.Sprint("Yellow")}, {"", pterm.FgLightRed.Sprint("Light Red"), pterm.FgLightGreen.Sprint("Light Green"), pterm.FgLightYellow.Sprint("Light Yellow")}, {pterm.BgBlack.Sprint("Black"), pterm.BgRed.Sprint("Red"), pterm.BgGreen.Sprint("Green"), pterm.BgYellow.Sprint("Yellow")}, {"", pterm.BgLightRed.Sprint("Light Red"), pterm.BgLightGreen.Sprint("Light Green"), pterm.BgLightYellow.Sprint("Light Yellow")}, {pterm.FgBlue.Sprint("Blue"), pterm.FgMagenta.Sprint("Magenta"), pterm.FgCyan.Sprint("Cyan"), pterm.FgWhite.Sprint("White")}, {pterm.FgLightBlue.Sprint("Light Blue"), pterm.FgLightMagenta.Sprint("Light Magenta"), pterm.FgLightCyan.Sprint("Light Cyan"), pterm.FgLightWhite.Sprint("Light White")}, {pterm.BgBlue.Sprint("Blue"), pterm.BgMagenta.Sprint("Magenta"), pterm.BgCyan.Sprint("Cyan"), pterm.BgWhite.Sprint("White")}, {pterm.BgLightBlue.Sprint("Light Blue"), pterm.BgLightMagenta.Sprint("Light Magenta"), pterm.BgLightCyan.Sprint("Light Cyan"), pterm.BgLightWhite.Sprint("Light White")}, }).Render() // Render the table. pterm.Println() // Print words in different colors. pterm.Println(pterm.Red("Hello, ") + pterm.Green("World") + pterm.Cyan("!")) pterm.Println(pterm.Red("Even " + pterm.Cyan("nested ") + pterm.Green("colors ") + "are supported!")) pterm.Println() // Create a new style with a red background, light green foreground, and bold text. style := pterm.NewStyle(pterm.BgRed, pterm.FgLightGreen, pterm.Bold) // Print text using the created style. style.Println("This text uses a style and is bold and light green with a red background!") } ``` golang-github-pterm-pterm-0.12.79/_examples/coloring/demo/animation.svg000066400000000000000000000201411465010626300261110ustar00rootroot00000000000000Black|Red|Green|Yellow|LightRed|LightGreen|LightYellow0Black|Red|Green|Yellow|Light Red|Light Green|Light YellowBlue|Magenta|Cyan|WhiteLightBlue|LightMagenta|LightCyan|LightWhiteBlue|Magenta|Cyan|WhiteLight Blue|Light Magenta|Light Cyan|Light WhiteHello,World!Evennestedcolorsaresupported!This text uses a style and is bold and light green with a red background!Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/coloring/demo/main.go000066400000000000000000000035111465010626300246660ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Create a table with different foreground and background colors. pterm.DefaultTable.WithData([][]string{ {pterm.FgBlack.Sprint("Black"), pterm.FgRed.Sprint("Red"), pterm.FgGreen.Sprint("Green"), pterm.FgYellow.Sprint("Yellow")}, {"", pterm.FgLightRed.Sprint("Light Red"), pterm.FgLightGreen.Sprint("Light Green"), pterm.FgLightYellow.Sprint("Light Yellow")}, {pterm.BgBlack.Sprint("Black"), pterm.BgRed.Sprint("Red"), pterm.BgGreen.Sprint("Green"), pterm.BgYellow.Sprint("Yellow")}, {"", pterm.BgLightRed.Sprint("Light Red"), pterm.BgLightGreen.Sprint("Light Green"), pterm.BgLightYellow.Sprint("Light Yellow")}, {pterm.FgBlue.Sprint("Blue"), pterm.FgMagenta.Sprint("Magenta"), pterm.FgCyan.Sprint("Cyan"), pterm.FgWhite.Sprint("White")}, {pterm.FgLightBlue.Sprint("Light Blue"), pterm.FgLightMagenta.Sprint("Light Magenta"), pterm.FgLightCyan.Sprint("Light Cyan"), pterm.FgLightWhite.Sprint("Light White")}, {pterm.BgBlue.Sprint("Blue"), pterm.BgMagenta.Sprint("Magenta"), pterm.BgCyan.Sprint("Cyan"), pterm.BgWhite.Sprint("White")}, {pterm.BgLightBlue.Sprint("Light Blue"), pterm.BgLightMagenta.Sprint("Light Magenta"), pterm.BgLightCyan.Sprint("Light Cyan"), pterm.BgLightWhite.Sprint("Light White")}, }).Render() // Render the table. pterm.Println() // Print words in different colors. pterm.Println(pterm.Red("Hello, ") + pterm.Green("World") + pterm.Cyan("!")) pterm.Println(pterm.Red("Even " + pterm.Cyan("nested ") + pterm.Green("colors ") + "are supported!")) pterm.Println() // Create a new style with a red background, light green foreground, and bold text. style := pterm.NewStyle(pterm.BgRed, pterm.FgLightGreen, pterm.Bold) // Print text using the created style. style.Println("This text uses a style and is bold and light green with a red background!") } golang-github-pterm-pterm-0.12.79/_examples/coloring/disable-output/000077500000000000000000000000001465010626300254305ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/coloring/disable-output/README.md000066400000000000000000000011211465010626300267020ustar00rootroot00000000000000# coloring/disable-output ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Loop from 0 to 14 for i := 0; i < 15; i++ { switch i { case 5: // At the 5th iteration, print a message and disable the output pterm.Info.Println("Disabled Output!") pterm.DisableOutput() case 10: // At the 10th iteration, enable the output and print a message pterm.EnableOutput() pterm.Info.Println("Enabled Output!") } // Print a progress message for each iteration pterm.Printf("Printing something... [%d/%d]\n", i, 15) } } ``` golang-github-pterm-pterm-0.12.79/_examples/coloring/disable-output/animation.svg000066400000000000000000000126431465010626300301360ustar00rootroot00000000000000Printingsomething...[0/15]Printingsomething...[1/15]Printingsomething...[2/15]Printingsomething...[3/15]Printingsomething...[4/15] INFO DisabledOutput! INFO EnabledOutput!Printingsomething...[10/15]Printingsomething...[11/15]Printingsomething...[12/15]Printingsomething...[13/15]Printingsomething...[14/15]Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/coloring/disable-output/main.go000066400000000000000000000010161465010626300267010ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Loop from 0 to 14 for i := 0; i < 15; i++ { switch i { case 5: // At the 5th iteration, print a message and disable the output pterm.Info.Println("Disabled Output!") pterm.DisableOutput() case 10: // At the 10th iteration, enable the output and print a message pterm.EnableOutput() pterm.Info.Println("Enabled Output!") } // Print a progress message for each iteration pterm.Printf("Printing something... [%d/%d]\n", i, 15) } } golang-github-pterm-pterm-0.12.79/_examples/coloring/fade-colors-rgb-style/000077500000000000000000000000001465010626300265735ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/coloring/fade-colors-rgb-style/README.md000066400000000000000000000051301465010626300300510ustar00rootroot00000000000000# coloring/fade-colors-rgb-style ![Animation](animation.svg) ```go package main import ( "strings" "github.com/pterm/pterm" ) func main() { // Define RGB colors white := pterm.NewRGB(255, 255, 255) grey := pterm.NewRGB(128, 128, 128) black := pterm.NewRGB(0, 0, 0) red := pterm.NewRGB(255, 0, 0) purple := pterm.NewRGB(255, 0, 255) green := pterm.NewRGB(0, 255, 0) // Define strings to be printed str1 := "RGB colors only work in Terminals which support TrueColor." str2 := "The background and foreground colors can be customized individually." str3 := "Styles can also be applied. For example: Bold or Italic." // Print first string with color fading from white to purple printFadedString(str1, white, purple, grey, black) // Print second string with color fading from purple to red printFadedString(str2, black, purple, red, red) // Print third string with color fading from white to green and style changes printStyledString(str3, white, green, red, black) } // printFadedString prints a string with color fading effect func printFadedString(str string, fgStart, fgEnd, bgStart, bgEnd pterm.RGB) { strs := strings.Split(str, "") var result string for i := 0; i < len(str); i++ { // Create a style with color fading effect style := pterm.NewRGBStyle(fgStart.Fade(0, float32(len(str)), float32(i), fgEnd), bgStart.Fade(0, float32(len(str)), float32(i), bgEnd)) // Append styled letter to result string result += style.Sprint(strs[i]) } pterm.Println(result) } // printStyledString prints a string with color fading and style changes func printStyledString(str string, fgStart, fgEnd, bgStart, bgEnd pterm.RGB) { strs := strings.Split(str, "") var result string boldStr := strings.Split("Bold", "") italicStr := strings.Split("Italic", "") bold, italic := 0, 0 for i := 0; i < len(str); i++ { // Create a style with color fading effect style := pterm.NewRGBStyle(fgStart.Fade(0, float32(len(str)), float32(i), fgEnd), bgStart.Fade(0, float32(len(str)), float32(i), bgEnd)) // Check if the next letters are "Bold" or "Italic" and add the corresponding style if bold < len(boldStr) && i+len(boldStr)-bold <= len(strs) && strings.Join(strs[i:i+len(boldStr)-bold], "") == strings.Join(boldStr[bold:], "") { style = style.AddOptions(pterm.Bold) bold++ } else if italic < len(italicStr) && i+len(italicStr)-italic < len(strs) && strings.Join(strs[i:i+len(italicStr)-italic], "") == strings.Join(italicStr[italic:], "") { style = style.AddOptions(pterm.Italic) italic++ } // Append styled letter to result string result += style.Sprint(strs[i]) } pterm.Println(result) } ``` golang-github-pterm-pterm-0.12.79/_examples/coloring/fade-colors-rgb-style/animation.svg000066400000000000000000001165371465010626300313100ustar00rootroot00000000000000RGB colors only work in Terminals which support TrueColor.The background and foreground colors can be customized individually.Styles can also be applied. For example: Bold or Italic.Styles can also be applied. For example: Bold orRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/coloring/fade-colors-rgb-style/main.go000066400000000000000000000050161465010626300300500ustar00rootroot00000000000000package main import ( "strings" "github.com/pterm/pterm" ) func main() { // Define RGB colors white := pterm.NewRGB(255, 255, 255) grey := pterm.NewRGB(128, 128, 128) black := pterm.NewRGB(0, 0, 0) red := pterm.NewRGB(255, 0, 0) purple := pterm.NewRGB(255, 0, 255) green := pterm.NewRGB(0, 255, 0) // Define strings to be printed str1 := "RGB colors only work in Terminals which support TrueColor." str2 := "The background and foreground colors can be customized individually." str3 := "Styles can also be applied. For example: Bold or Italic." // Print first string with color fading from white to purple printFadedString(str1, white, purple, grey, black) // Print second string with color fading from purple to red printFadedString(str2, black, purple, red, red) // Print third string with color fading from white to green and style changes printStyledString(str3, white, green, red, black) } // printFadedString prints a string with color fading effect func printFadedString(str string, fgStart, fgEnd, bgStart, bgEnd pterm.RGB) { strs := strings.Split(str, "") var result string for i := 0; i < len(str); i++ { // Create a style with color fading effect style := pterm.NewRGBStyle(fgStart.Fade(0, float32(len(str)), float32(i), fgEnd), bgStart.Fade(0, float32(len(str)), float32(i), bgEnd)) // Append styled letter to result string result += style.Sprint(strs[i]) } pterm.Println(result) } // printStyledString prints a string with color fading and style changes func printStyledString(str string, fgStart, fgEnd, bgStart, bgEnd pterm.RGB) { strs := strings.Split(str, "") var result string boldStr := strings.Split("Bold", "") italicStr := strings.Split("Italic", "") bold, italic := 0, 0 for i := 0; i < len(str); i++ { // Create a style with color fading effect style := pterm.NewRGBStyle(fgStart.Fade(0, float32(len(str)), float32(i), fgEnd), bgStart.Fade(0, float32(len(str)), float32(i), bgEnd)) // Check if the next letters are "Bold" or "Italic" and add the corresponding style if bold < len(boldStr) && i+len(boldStr)-bold <= len(strs) && strings.Join(strs[i:i+len(boldStr)-bold], "") == strings.Join(boldStr[bold:], "") { style = style.AddOptions(pterm.Bold) bold++ } else if italic < len(italicStr) && i+len(italicStr)-italic < len(strs) && strings.Join(strs[i:i+len(italicStr)-italic], "") == strings.Join(italicStr[italic:], "") { style = style.AddOptions(pterm.Italic) italic++ } // Append styled letter to result string result += style.Sprint(strs[i]) } pterm.Println(result) } golang-github-pterm-pterm-0.12.79/_examples/coloring/fade-colors/000077500000000000000000000000001465010626300246655ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/coloring/fade-colors/README.md000066400000000000000000000017251465010626300261510ustar00rootroot00000000000000# coloring/fade-colors ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" ) func main() { // Print an informational message. pterm.Info.Println("RGB colors only work in Terminals which support TrueColor.") // Define the start and end points for the color gradient. startColor := pterm.NewRGB(0, 255, 255) // Cyan endColor := pterm.NewRGB(255, 0, 255) // Magenta // Get the terminal height to determine the gradient range. terminalHeight := pterm.GetTerminalHeight() // Loop over the range of the terminal height to create a color gradient. for i := 0; i < terminalHeight-2; i++ { // Calculate the fade factor for the current step in the gradient. fadeFactor := float32(i) / float32(terminalHeight-2) // Create a color that represents the current step in the gradient. currentColor := startColor.Fade(0, 1, fadeFactor, endColor) // Print a string with the current color. currentColor.Println("Hello, World!") } } ``` golang-github-pterm-pterm-0.12.79/_examples/coloring/fade-colors/animation.svg000066400000000000000000000176551465010626300274030ustar00rootroot00000000000000 INFO RGBcolorsonlyworkinTerminalswhichsupportTrueColor.Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/coloring/fade-colors/main.go000066400000000000000000000016251465010626300261440ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" ) func main() { // Print an informational message. pterm.Info.Println("RGB colors only work in Terminals which support TrueColor.") // Define the start and end points for the color gradient. startColor := pterm.NewRGB(0, 255, 255) // Cyan endColor := pterm.NewRGB(255, 0, 255) // Magenta // Get the terminal height to determine the gradient range. terminalHeight := pterm.GetTerminalHeight() // Loop over the range of the terminal height to create a color gradient. for i := 0; i < terminalHeight-2; i++ { // Calculate the fade factor for the current step in the gradient. fadeFactor := float32(i) / float32(terminalHeight-2) // Create a color that represents the current step in the gradient. currentColor := startColor.Fade(0, 1, fadeFactor, endColor) // Print a string with the current color. currentColor.Println("Hello, World!") } } golang-github-pterm-pterm-0.12.79/_examples/coloring/fade-multiple-colors/000077500000000000000000000000001465010626300265165ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/coloring/fade-multiple-colors/README.md000066400000000000000000000025311465010626300277760ustar00rootroot00000000000000# coloring/fade-multiple-colors ![Animation](animation.svg) ```go package main import ( "strings" "github.com/pterm/pterm" ) func main() { // Define RGB values for gradient points. startColor := pterm.NewRGB(0, 255, 255) firstPoint := pterm.NewRGB(255, 0, 255) secondPoint := pterm.NewRGB(255, 0, 0) thirdPoint := pterm.NewRGB(0, 255, 0) endColor := pterm.NewRGB(255, 255, 255) // Define the string to be printed. str := "RGB colors only work in Terminals which support TrueColor." strs := strings.Split(str, "") // Initialize an empty string for the faded info. var fadeInfo string // Loop over the string length to create a gradient effect. for i := 0; i < len(str); i++ { // Append each character of the string with a faded color to the info string. fadeInfo += startColor.Fade(0, float32(len(str)), float32(i), firstPoint).Sprint(strs[i]) } // Print the info string with gradient effect. pterm.Info.Println(fadeInfo) // Get the terminal height. terminalHeight := pterm.GetTerminalHeight() // Loop over the terminal height to print "Hello, World!" with a gradient effect. for i := 0; i < terminalHeight-2; i++ { // Print the string with a color that fades from startColor to endColor. startColor.Fade(0, float32(terminalHeight-2), float32(i), firstPoint, secondPoint, thirdPoint, endColor).Println("Hello, World!") } } ``` golang-github-pterm-pterm-0.12.79/_examples/coloring/fade-multiple-colors/animation.svg000066400000000000000000000274121465010626300312240ustar00rootroot00000000000000 INFO RGBcolorsonlyworkinTerminalswhichsupportTrueColor.Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Hello,World!Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/coloring/fade-multiple-colors/main.go000066400000000000000000000024201465010626300277670ustar00rootroot00000000000000package main import ( "strings" "github.com/pterm/pterm" ) func main() { // Define RGB values for gradient points. startColor := pterm.NewRGB(0, 255, 255) firstPoint := pterm.NewRGB(255, 0, 255) secondPoint := pterm.NewRGB(255, 0, 0) thirdPoint := pterm.NewRGB(0, 255, 0) endColor := pterm.NewRGB(255, 255, 255) // Define the string to be printed. str := "RGB colors only work in Terminals which support TrueColor." strs := strings.Split(str, "") // Initialize an empty string for the faded info. var fadeInfo string // Loop over the string length to create a gradient effect. for i := 0; i < len(str); i++ { // Append each character of the string with a faded color to the info string. fadeInfo += startColor.Fade(0, float32(len(str)), float32(i), firstPoint).Sprint(strs[i]) } // Print the info string with gradient effect. pterm.Info.Println(fadeInfo) // Get the terminal height. terminalHeight := pterm.GetTerminalHeight() // Loop over the terminal height to print "Hello, World!" with a gradient effect. for i := 0; i < terminalHeight-2; i++ { // Print the string with a color that fades from startColor to endColor. startColor.Fade(0, float32(terminalHeight-2), float32(i), firstPoint, secondPoint, thirdPoint, endColor).Println("Hello, World!") } } golang-github-pterm-pterm-0.12.79/_examples/coloring/override-default-printers/000077500000000000000000000000001465010626300275745ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/coloring/override-default-printers/README.md000066400000000000000000000011111465010626300310450ustar00rootroot00000000000000# coloring/override-default-printers ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Print a default error message with PTerm's built-in Error style. pterm.Error.Println("This is the default Error") // Override the default error prefix with a new text and style. pterm.Error.Prefix = pterm.Prefix{Text: "OVERRIDE", Style: pterm.NewStyle(pterm.BgCyan, pterm.FgRed)} // Print the error message again, this time with the overridden prefix. pterm.Error.Println("This is the default Error after the prefix was overridden") } ``` golang-github-pterm-pterm-0.12.79/_examples/coloring/override-default-printers/animation.svg000066400000000000000000000060751465010626300323040ustar00rootroot00000000000000 ERROR ThisisthedefaultError OVERRIDE ThisisthedefaultErroraftertheprefixwasoverriddenRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/coloring/override-default-printers/main.go000066400000000000000000000007731465010626300310560ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Print a default error message with PTerm's built-in Error style. pterm.Error.Println("This is the default Error") // Override the default error prefix with a new text and style. pterm.Error.Prefix = pterm.Prefix{Text: "OVERRIDE", Style: pterm.NewStyle(pterm.BgCyan, pterm.FgRed)} // Print the error message again, this time with the overridden prefix. pterm.Error.Println("This is the default Error after the prefix was overridden") } golang-github-pterm-pterm-0.12.79/_examples/coloring/print-color-rgb-style/000077500000000000000000000000001465010626300266455ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/coloring/print-color-rgb-style/README.md000066400000000000000000000014621465010626300301270ustar00rootroot00000000000000# coloring/print-color-rgb-style ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define RGB colors for foreground and background. foregroundRGB := pterm.RGB{R: 187, G: 80, B: 0} backgroundRGB := pterm.RGB{R: 0, G: 50, B: 123} // Create a new RGB style with the defined foreground and background colors. rgbStyle := pterm.NewRGBStyle(foregroundRGB, backgroundRGB) // Print a string with the custom RGB style. rgbStyle.Println("This text is not styled.") // Add the 'Bold' option to the RGB style and print a string with this style. rgbStyle.AddOptions(pterm.Bold).Println("This text is bold.") // Add the 'Italic' option to the RGB style and print a string with this style. rgbStyle.AddOptions(pterm.Italic).Println("This text is italic.") } ``` golang-github-pterm-pterm-0.12.79/_examples/coloring/print-color-rgb-style/animation.svg000066400000000000000000000051151465010626300313470ustar00rootroot00000000000000This text is not styled.This text is bold.This text is italic.Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/coloring/print-color-rgb-style/main.go000066400000000000000000000013501465010626300301170ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" ) func main() { // Define RGB colors for foreground and background. foregroundRGB := pterm.RGB{R: 187, G: 80, B: 0} backgroundRGB := pterm.RGB{R: 0, G: 50, B: 123} // Create a new RGB style with the defined foreground and background colors. rgbStyle := pterm.NewRGBStyle(foregroundRGB, backgroundRGB) // Print a string with the custom RGB style. rgbStyle.Println("This text is not styled.") // Add the 'Bold' option to the RGB style and print a string with this style. rgbStyle.AddOptions(pterm.Bold).Println("This text is bold.") // Add the 'Italic' option to the RGB style and print a string with this style. rgbStyle.AddOptions(pterm.Italic).Println("This text is italic.") } golang-github-pterm-pterm-0.12.79/_examples/coloring/print-color-rgb/000077500000000000000000000000001465010626300255075ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/coloring/print-color-rgb/README.md000066400000000000000000000013561465010626300267730ustar00rootroot00000000000000# coloring/print-color-rgb ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Create a new RGB color with values 178, 44, 199. // This color will be used for the text. pterm.NewRGB(178, 44, 199).Println("This text is printed with a custom RGB!") // Create a new RGB color with values 15, 199, 209. // This color will be used for the text. pterm.NewRGB(15, 199, 209).Println("This text is printed with a custom RGB!") // Create a new RGB color with values 201, 144, 30. // This color will be used for the background. // The 'true' argument indicates that the color is for the background. pterm.NewRGB(201, 144, 30, true).Println("This text is printed with a custom RGB background!") } ``` golang-github-pterm-pterm-0.12.79/_examples/coloring/print-color-rgb/animation.svg000066400000000000000000000062271465010626300302160ustar00rootroot00000000000000ThistextisprintedwithacustomRGB!ThistextisprintedwithacustomRGB!This text is printed with a custom RGB background!Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/coloring/print-color-rgb/main.go000066400000000000000000000012521465010626300267620ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Create a new RGB color with values 178, 44, 199. // This color will be used for the text. pterm.NewRGB(178, 44, 199).Println("This text is printed with a custom RGB!") // Create a new RGB color with values 15, 199, 209. // This color will be used for the text. pterm.NewRGB(15, 199, 209).Println("This text is printed with a custom RGB!") // Create a new RGB color with values 201, 144, 30. // This color will be used for the background. // The 'true' argument indicates that the color is for the background. pterm.NewRGB(201, 144, 30, true).Println("This text is printed with a custom RGB background!") } golang-github-pterm-pterm-0.12.79/_examples/demo/000077500000000000000000000000001465010626300215775ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/demo/README.md000066400000000000000000000253471465010626300230710ustar00rootroot00000000000000### demo/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/demo/demo/animation.svg)
SHOW SOURCE ```go package main import ( "flag" "math/rand" "reflect" "strconv" "strings" "time" "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) // Speed the demo up, by setting this flag. // Usefull for debugging. // Example: // // go run main.go -speedup var speedup = flag.Bool("speedup", false, "Speed up the demo") var skipIntro = flag.Bool("skip-intro", false, "Skips the intro") var second = time.Second var pseudoProgramList = strings.Split("pseudo-excel pseudo-photoshop pseudo-chrome pseudo-outlook pseudo-explorer "+ "pseudo-git pseudo-vsc pseudo-intellij pseudo-minecraft pseudo-scoop pseudo-chocolatey", " ") func main() { setup() // Setup the demo (flags etc.) // Show intro if !*skipIntro { introScreen() clear() } showcase("Structured Logging", 5, func() { logger := pterm.DefaultLogger. WithLevel(pterm.LogLevelTrace) logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) time.Sleep(time.Second * 3) interstingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } logger.Debug("This might be interesting", logger.ArgsFromMap(interstingStuff)) time.Sleep(time.Second * 3) logger.Info("That was actually interesting", logger.Args("such", "wow")) time.Sleep(time.Second * 3) logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) time.Sleep(time.Second * 3) logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) time.Sleep(time.Second * 3) logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) }) showcase("Progress bar", 2, func() { pb, _ := pterm.DefaultProgressbar.WithTotal(len(pseudoProgramList)).WithTitle("Installing stuff").Start() for i := 0; i < pb.Total; i++ { pb.UpdateTitle("Installing " + pseudoProgramList[i]) if pseudoProgramList[i] == "pseudo-minecraft" { pterm.Warning.Println("Could not install pseudo-minecraft\nThe company policy forbids games.") } else { pterm.Success.Println("Installing " + pseudoProgramList[i]) } pb.Increment() time.Sleep(second / 2) } pb.Stop() }) showcase("Spinner", 2, func() { list := pseudoProgramList[7:] spinner, _ := pterm.DefaultSpinner.Start("Installing stuff") for i := 0; i < len(list); i++ { spinner.UpdateText("Installing " + list[i]) if list[i] == "pseudo-minecraft" { pterm.Warning.Println("Could not install pseudo-minecraft\nThe company policy forbids games.") } else { pterm.Success.Println("Installing " + list[i]) } time.Sleep(second) } spinner.Success() }) showcase("Live Output", 2, func() { pterm.Info.Println("You can use an Area to display changing output:") pterm.Println() area, _ := pterm.DefaultArea.WithCenter().Start() // Start the Area printer, with the Center option. for i := 0; i < 10; i++ { str, _ := pterm.DefaultBigText.WithLetters(putils.LettersFromString(time.Now().Format("15:04:05"))).Srender() // Save current time in str. area.Update(str) // Update Area contents. time.Sleep(time.Second) } area.Stop() }) showcase("Tables", 4, func() { for i := 0; i < 3; i++ { pterm.Println() } td := [][]string{ {"Library", "Description"}, {"PTerm", "Make beautiful CLIs"}, {"Testza", "Programmer friendly test framework"}, {"Cursor", "Move the cursor around the terminal"}, } table, _ := pterm.DefaultTable.WithHasHeader().WithData(td).Srender() boxedTable, _ := pterm.DefaultTable.WithHasHeader().WithData(td).WithBoxed().Srender() pterm.DefaultCenter.Println(table) pterm.DefaultCenter.Println(boxedTable) }) showcase("TrueColor Support", 7, func() { from := pterm.NewRGB(0, 255, 255) // This RGB value is used as the gradients start point. to := pterm.NewRGB(255, 0, 255) // This RGB value is used as the gradients first point. str := "If your terminal has TrueColor support, you can use RGB colors!\nYou can even fade them :)\n\nLorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet." strs := strings.Split(str, "") var fadeInfo string // String which will be used to print info. // For loop over the range of the string length. for i := 0; i < len(str); i++ { // Append faded letter to info string. fadeInfo += from.Fade(0, float32(len(str)), float32(i), to).Sprint(strs[i]) } pterm.DefaultCenter.WithCenterEachLineSeparately().Println(fadeInfo) }) showcase("Fully Customizable", 2, func() { for i := 0; i < 4; i++ { pterm.Println() } text := "All printers are fully customizable!" area := pterm.DefaultArea.WithCenter() area.Update(pterm.DefaultBox.Sprintln(text)) time.Sleep(second) area.Update(pterm.DefaultBox.WithTopPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleTopLeft().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleTopCenter().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleTopRight().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleBottomRight().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleBottomCenter().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleBottomLeft().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithBoxStyle(pterm.NewStyle(pterm.FgCyan)).Sprintln(text)) time.Sleep(second / 5) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithBoxStyle(pterm.NewStyle(pterm.FgRed)).Sprintln(text)) time.Sleep(second / 5) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithBoxStyle(pterm.NewStyle(pterm.FgGreen)).Sprintln(text)) time.Sleep(second / 5) area.Update(pterm.DefaultBox.WithTopPadding(1). WithBottomPadding(1). WithLeftPadding(1). WithRightPadding(1). WithHorizontalString("═"). WithVerticalString("║"). WithBottomLeftCornerString("╗"). WithBottomRightCornerString("╔"). WithTopLeftCornerString("╝"). WithTopRightCornerString("╚"). Sprintln(text)) area.Stop() }) showcase("Themes", 2, func() { pterm.Info.Println("You can change the color theme of PTerm easily to fit your needs!\nThis is the default one:") time.Sleep(second / 2) // Print every value of the default theme with its own style. v := reflect.ValueOf(pterm.ThemeDefault) typeOfS := v.Type() if typeOfS == reflect.TypeOf(pterm.Theme{}) { for i := 0; i < v.NumField(); i++ { field, ok := v.Field(i).Interface().(pterm.Style) if ok { field.Println(typeOfS.Field(i).Name) } time.Sleep(time.Millisecond * 250) } } }) showcase("And much more!", 3, func() { for i := 0; i < 4; i++ { pterm.Println() } box := pterm.DefaultBox. WithBottomPadding(1). WithTopPadding(1). WithLeftPadding(3). WithRightPadding(3). Sprintf("Have fun exploring %s!", pterm.Cyan("PTerm")) pterm.DefaultCenter.Println(box) }) } func setup() { flag.Parse() if *speedup { second = time.Millisecond * 200 } } func introScreen() { ptermLogo, _ := pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithStyle("P", pterm.NewStyle(pterm.FgLightCyan)), putils.LettersFromStringWithStyle("Term", pterm.NewStyle(pterm.FgLightMagenta))). Srender() pterm.DefaultCenter.Print(ptermLogo) pterm.DefaultCenter.Print(pterm.DefaultHeader.WithFullWidth().WithBackgroundStyle(pterm.NewStyle(pterm.BgLightBlue)).WithMargin(10).Sprint("PTDP - PTerm Demo Program")) pterm.Info.Println("This animation was generated with the latest version of PTerm!" + "\nPTerm works on nearly every terminal and operating system." + "\nIt's super easy to use!" + "\nIf you want, you can customize everything :)" + "\nYou can see the code of this demo in the " + pterm.LightMagenta("./_examples/demo") + " directory." + "\n" + "\nThis demo was updated at: " + pterm.Green(time.Now().Format("02 Jan 2006 - 15:04:05 MST"))) pterm.Println() introSpinner, _ := pterm.DefaultSpinner.WithShowTimer(false).WithRemoveWhenDone(true).Start("Waiting for 15 seconds...") time.Sleep(second) for i := 14; i > 0; i-- { if i > 1 { introSpinner.UpdateText("Waiting for " + strconv.Itoa(i) + " seconds...") } else { introSpinner.UpdateText("Waiting for " + strconv.Itoa(i) + " second...") } time.Sleep(second) } introSpinner.Stop() } func clear() { print("\033[H\033[2J") } func showcase(title string, seconds int, content func()) { pterm.DefaultHeader.WithBackgroundStyle(pterm.NewStyle(pterm.BgLightBlue)).WithFullWidth().Println(title) pterm.Println() time.Sleep(second / 2) content() time.Sleep(second * time.Duration(seconds)) print("\033[H\033[2J") } func randomInt(min, max int) int { rand.Seed(time.Now().UnixNano()) return rand.Intn(max-min+1) + min } ```
golang-github-pterm-pterm-0.12.79/_examples/demo/demo/000077500000000000000000000000001465010626300225235ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/demo/demo/README.md000066400000000000000000000251441465010626300240100ustar00rootroot00000000000000# demo/demo ![Animation](animation.svg) ```go package main import ( "flag" "math/rand" "reflect" "strconv" "strings" "time" "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) // Speed the demo up, by setting this flag. // Usefull for debugging. // Example: // // go run main.go -speedup var speedup = flag.Bool("speedup", false, "Speed up the demo") var skipIntro = flag.Bool("skip-intro", false, "Skips the intro") var second = time.Second var pseudoProgramList = strings.Split("pseudo-excel pseudo-photoshop pseudo-chrome pseudo-outlook pseudo-explorer "+ "pseudo-git pseudo-vsc pseudo-intellij pseudo-minecraft pseudo-scoop pseudo-chocolatey", " ") func main() { setup() // Setup the demo (flags etc.) // Show intro if !*skipIntro { introScreen() clear() } showcase("Structured Logging", 5, func() { logger := pterm.DefaultLogger. WithLevel(pterm.LogLevelTrace) logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) time.Sleep(time.Second * 3) interstingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } logger.Debug("This might be interesting", logger.ArgsFromMap(interstingStuff)) time.Sleep(time.Second * 3) logger.Info("That was actually interesting", logger.Args("such", "wow")) time.Sleep(time.Second * 3) logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) time.Sleep(time.Second * 3) logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) time.Sleep(time.Second * 3) logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) }) showcase("Progress bar", 2, func() { pb, _ := pterm.DefaultProgressbar.WithTotal(len(pseudoProgramList)).WithTitle("Installing stuff").Start() for i := 0; i < pb.Total; i++ { pb.UpdateTitle("Installing " + pseudoProgramList[i]) if pseudoProgramList[i] == "pseudo-minecraft" { pterm.Warning.Println("Could not install pseudo-minecraft\nThe company policy forbids games.") } else { pterm.Success.Println("Installing " + pseudoProgramList[i]) } pb.Increment() time.Sleep(second / 2) } pb.Stop() }) showcase("Spinner", 2, func() { list := pseudoProgramList[7:] spinner, _ := pterm.DefaultSpinner.Start("Installing stuff") for i := 0; i < len(list); i++ { spinner.UpdateText("Installing " + list[i]) if list[i] == "pseudo-minecraft" { pterm.Warning.Println("Could not install pseudo-minecraft\nThe company policy forbids games.") } else { pterm.Success.Println("Installing " + list[i]) } time.Sleep(second) } spinner.Success() }) showcase("Live Output", 2, func() { pterm.Info.Println("You can use an Area to display changing output:") pterm.Println() area, _ := pterm.DefaultArea.WithCenter().Start() // Start the Area printer, with the Center option. for i := 0; i < 10; i++ { str, _ := pterm.DefaultBigText.WithLetters(putils.LettersFromString(time.Now().Format("15:04:05"))).Srender() // Save current time in str. area.Update(str) // Update Area contents. time.Sleep(time.Second) } area.Stop() }) showcase("Tables", 4, func() { for i := 0; i < 3; i++ { pterm.Println() } td := [][]string{ {"Library", "Description"}, {"PTerm", "Make beautiful CLIs"}, {"Testza", "Programmer friendly test framework"}, {"Cursor", "Move the cursor around the terminal"}, } table, _ := pterm.DefaultTable.WithHasHeader().WithData(td).Srender() boxedTable, _ := pterm.DefaultTable.WithHasHeader().WithData(td).WithBoxed().Srender() pterm.DefaultCenter.Println(table) pterm.DefaultCenter.Println(boxedTable) }) showcase("TrueColor Support", 7, func() { from := pterm.NewRGB(0, 255, 255) // This RGB value is used as the gradients start point. to := pterm.NewRGB(255, 0, 255) // This RGB value is used as the gradients first point. str := "If your terminal has TrueColor support, you can use RGB colors!\nYou can even fade them :)\n\nLorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet." strs := strings.Split(str, "") var fadeInfo string // String which will be used to print info. // For loop over the range of the string length. for i := 0; i < len(str); i++ { // Append faded letter to info string. fadeInfo += from.Fade(0, float32(len(str)), float32(i), to).Sprint(strs[i]) } pterm.DefaultCenter.WithCenterEachLineSeparately().Println(fadeInfo) }) showcase("Fully Customizable", 2, func() { for i := 0; i < 4; i++ { pterm.Println() } text := "All printers are fully customizable!" area := pterm.DefaultArea.WithCenter() area.Update(pterm.DefaultBox.Sprintln(text)) time.Sleep(second) area.Update(pterm.DefaultBox.WithTopPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleTopLeft().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleTopCenter().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleTopRight().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleBottomRight().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleBottomCenter().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleBottomLeft().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithBoxStyle(pterm.NewStyle(pterm.FgCyan)).Sprintln(text)) time.Sleep(second / 5) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithBoxStyle(pterm.NewStyle(pterm.FgRed)).Sprintln(text)) time.Sleep(second / 5) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithBoxStyle(pterm.NewStyle(pterm.FgGreen)).Sprintln(text)) time.Sleep(second / 5) area.Update(pterm.DefaultBox.WithTopPadding(1). WithBottomPadding(1). WithLeftPadding(1). WithRightPadding(1). WithHorizontalString("═"). WithVerticalString("║"). WithBottomLeftCornerString("╗"). WithBottomRightCornerString("╔"). WithTopLeftCornerString("╝"). WithTopRightCornerString("╚"). Sprintln(text)) area.Stop() }) showcase("Themes", 2, func() { pterm.Info.Println("You can change the color theme of PTerm easily to fit your needs!\nThis is the default one:") time.Sleep(second / 2) // Print every value of the default theme with its own style. v := reflect.ValueOf(pterm.ThemeDefault) typeOfS := v.Type() if typeOfS == reflect.TypeOf(pterm.Theme{}) { for i := 0; i < v.NumField(); i++ { field, ok := v.Field(i).Interface().(pterm.Style) if ok { field.Println(typeOfS.Field(i).Name) } time.Sleep(time.Millisecond * 250) } } }) showcase("And much more!", 3, func() { for i := 0; i < 4; i++ { pterm.Println() } box := pterm.DefaultBox. WithBottomPadding(1). WithTopPadding(1). WithLeftPadding(3). WithRightPadding(3). Sprintf("Have fun exploring %s!", pterm.Cyan("PTerm")) pterm.DefaultCenter.Println(box) }) } func setup() { flag.Parse() if *speedup { second = time.Millisecond * 200 } } func introScreen() { ptermLogo, _ := pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithStyle("P", pterm.NewStyle(pterm.FgLightCyan)), putils.LettersFromStringWithStyle("Term", pterm.NewStyle(pterm.FgLightMagenta))). Srender() pterm.DefaultCenter.Print(ptermLogo) pterm.DefaultCenter.Print(pterm.DefaultHeader.WithFullWidth().WithBackgroundStyle(pterm.NewStyle(pterm.BgLightBlue)).WithMargin(10).Sprint("PTDP - PTerm Demo Program")) pterm.Info.Println("This animation was generated with the latest version of PTerm!" + "\nPTerm works on nearly every terminal and operating system." + "\nIt's super easy to use!" + "\nIf you want, you can customize everything :)" + "\nYou can see the code of this demo in the " + pterm.LightMagenta("./_examples/demo") + " directory." + "\n" + "\nThis demo was updated at: " + pterm.Green(time.Now().Format("02 Jan 2006 - 15:04:05 MST"))) pterm.Println() introSpinner, _ := pterm.DefaultSpinner.WithShowTimer(false).WithRemoveWhenDone(true).Start("Waiting for 15 seconds...") time.Sleep(second) for i := 14; i > 0; i-- { if i > 1 { introSpinner.UpdateText("Waiting for " + strconv.Itoa(i) + " seconds...") } else { introSpinner.UpdateText("Waiting for " + strconv.Itoa(i) + " second...") } time.Sleep(second) } introSpinner.Stop() } func clear() { print("\033[H\033[2J") } func showcase(title string, seconds int, content func()) { pterm.DefaultHeader.WithBackgroundStyle(pterm.NewStyle(pterm.BgLightBlue)).WithFullWidth().Println(title) pterm.Println() time.Sleep(second / 2) content() time.Sleep(second * time.Duration(seconds)) print("\033[H\033[2J") } func randomInt(min, max int) int { rand.Seed(time.Now().UnixNano()) return rand.Intn(max-min+1) + min } ``` golang-github-pterm-pterm-0.12.79/_examples/demo/demo/animation.svg000066400000000000000000010176131465010626300252340ustar00rootroot00000000000000███████████████████████████████████████████████████████████████████████████████████████████████████████████████████ PTDP - PTerm Demo Program INFO ThisanimationwasgeneratedwiththelatestversionofPTerm! PTermworksonnearlyeveryterminalandoperatingsystem. It'ssupereasytouse! Ifyouwant,youcancustomizeeverything:) Youcanseethecodeofthisdemointhe./_examples/demodirectory. Thisdemowasupdatedat:09Feb2024-18:54:11UTCWaitingfor15seconds...Waitingfor14seconds...Waitingfor14seconds...Waitingfor13seconds...Waitingfor13seconds...Waitingfor12seconds...Waitingfor12seconds...Waitingfor11seconds...Waitingfor11seconds...Waitingfor10seconds...Waitingfor10seconds...Waitingfor9seconds....Waitingfor9seconds....Waitingfor8seconds....Waitingfor8seconds....Waitingfor7seconds....Waitingfor7seconds....Waitingfor6seconds....Waitingfor6seconds....Waitingfor5seconds....Waitingfor5seconds....Waitingfor4seconds....Waitingfor4seconds....Waitingfor3seconds....Waitingfor3seconds....Waitingfor2seconds....Waitingfor2seconds....Waitingfor1second.....Waitingfor1second..... Structured Logging 2024-02-0918:54:26TRACEDoingnotsoimportantstuffpriority:superlow2024-02-0918:54:29DEBUGThismightbeinterestingwhatisthemeaningoflife:42isthisinteresting:truewhenwerecrayonsinvented:19032024-02-0918:54:32INFOThatwasactuallyinterestingsuch:wow2024-02-0918:54:35WARNOhno,Iseeanerrorcomingtous!speed:88measures:mph2024-02-0918:54:38ERRORDamn,hereitis!error:somethingwentwrong Progress bar Installingpseudo-excel[00/11]█████████████████████████████████████0%|0s SUCCESS Installingpseudo-excelInstallingpseudo-photoshop[01/11]██████████████████████████████████9%|1s SUCCESS Installingpseudo-photoshopInstallingpseudo-photoshop[02/11]██████████████████████████████████18%|1sInstallingpseudo-chrome[02/11]█████████████████████████████████████18%|1s SUCCESS Installingpseudo-chromeInstallingpseudo-outlook[03/11]████████████████████████████████████27%|2s SUCCESS Installingpseudo-outlookInstallingpseudo-outlook[04/11]████████████████████████████████████36%|2sInstallingpseudo-explorer[04/11]███████████████████████████████████36%|2s SUCCESS Installingpseudo-explorerInstallingpseudo-git[05/11]████████████████████████████████████████45%|3s SUCCESS Installingpseudo-gitInstallingpseudo-git[06/11]████████████████████████████████████████55%|3sInstallingpseudo-vsc[06/11]████████████████████████████████████████55%|3s SUCCESS Installingpseudo-vscInstallingpseudo-intellij[07/11]███████████████████████████████████64%|4s SUCCESS Installingpseudo-intellijInstallingpseudo-intellij[08/11]███████████████████████████████████73%|4sInstallingpseudo-minecraft[08/11]██████████████████████████████████73%|4s WARNING Couldnotinstallpseudo-minecraft Thecompanypolicyforbidsgames.Installingpseudo-scoop[09/11]██████████████████████████████████████82%|5s SUCCESS Installingpseudo-scoop Installingpseudo-scoop[10/11]██████████████████████████████████████91%|5sInstallingpseudo-chocolatey[10/11]█████████████████████████████████91%|5s SUCCESS Installingpseudo-chocolatey Installingpseudo-chocolatey[11/11]█████████████████████████████████100%|5s Spinner SUCCESS Installingpseudo-scoop SUCCESS Installingpseudo-chocolatey Live Output INFO YoucanuseanAreatodisplaychangingoutput:████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ Tables Library|DescriptionPTerm|MakebeautifulCLIsTestza|ProgrammerfriendlytestframeworkCursor|Movethecursoraroundtheterminal TrueColor Support IfyourterminalhasTrueColorsupport,youcanuseRGBcolors!Youcanevenfadethem:)Loremipsumdolorsitamet,consetetursadipscingelitr,seddiamnonumyeirmodtemporinviduntutlaboreetdoloremagnaaliquyamerat,seddiamvoluptua.Atveroeosetaccusametjustoduodoloresetearebum.Stetclitakasdgubergren,noseatakimatasanctusestLoremipsumdolorsitamet.Loremipsumdolorsitamet,consetetursadipscingelitr,seddiamnonumyeirmodtemporinviduntutlaboreetdoloremagnaaliquyamerat,seddiamvoluptua.Atveroeosetaccusametju Fully Customizable ┌──────────────────────────────────────┐|Allprintersarefullycustomizable!|└──────────────────────────────────────┘|||||||| Themes INFO YoucanchangethecolorthemeofPTermeasilytofityourneeds! Thisisthedefaultone:DefaultTextPrimaryStyleSecondaryStyleHighlightStyleInfoMessageStyleInfoPrefixStyleSuccessMessageStyleSuccessPrefixStyleWarningMessageStyleWarningPrefixStyleErrorMessageStyleErrorPrefixStyleFatalMessageStyleFatalPrefixStyleDescriptionMessageStyleDescriptionPrefixStyleScopeStyleProgressbarBarStyleProgressbarTitleStyleHeaderTextStyleHeaderBackgroundStyleSpinnerStyleSpinnerTextStyleTimerStyleTableStyleTableHeaderStyleTableSeparatorStyleHeatmapStyleHeatmapHeaderStyleHeatmapSeparatorStyleSectionStyleBulletListTextStyleBulletListBulletStyleTreeStyleTreeTextStyleLetterStyleDebugMessageStyleDebugPrefixStyleBoxStyleBoxTextStyleBarLabelStyle And much more! ||Waitingfor15seconds...Waitingfor15seconds...Waitingfor15seconds...Waitingfor14seconds...Waitingfor14seconds...Waitingfor13seconds...Waitingfor13seconds...Waitingfor12seconds...Waitingfor12seconds...Waitingfor11seconds...Waitingfor11seconds...Waitingfor10seconds...Waitingfor10seconds...Waitingfor9seconds....Waitingfor9seconds....Waitingfor8seconds....Waitingfor8seconds....Waitingfor7seconds....Waitingfor7seconds....Waitingfor6seconds....Waitingfor6seconds....Waitingfor5seconds....Waitingfor5seconds....Waitingfor4seconds....Waitingfor4seconds....Waitingfor3seconds....Waitingfor3seconds....Waitingfor2seconds....Waitingfor2seconds....Waitingfor1second.....Waitingfor1second.....2024-02-0918:54:41INFOButwhat'sreallycoolis,thatyoucanprintverylonglogs,andPTermwillautomaticallywrapthemforyou!Saygoodbyetotext,thathasweirdlinebreaks!very:longInstallingstuff[00/11]████████████████████████████████████████████0%|0sInstallingpseudo-excel[01/11]██████████████████████████████████████9%|0sInstallingpseudo-chrome[03/11]█████████████████████████████████████27%|1sInstallingpseudo-explorer[05/11]███████████████████████████████████45%|2sInstallingpseudo-vsc[07/11]████████████████████████████████████████64%|3sInstallingpseudo-minecraft[09/11]██████████████████████████████████82%|4sInstallingpseudo-intellij(0s)Installingpseudo-intellij(0s)Installingpseudo-intellij(0s)Installingpseudo-intellij(1s)Installingpseudo-intellij(1s)Installingpseudo-minecraft(1s)Installingpseudo-minecraft(1s)Installingpseudo-minecraft(1s)Installingpseudo-minecraft(2s)Installingpseudo-minecraft(2s)Installingpseudo-scoop(2s)Installingpseudo-scoop(2s)Installingpseudo-scoop(2s)Installingpseudo-scoop(3s)Installingpseudo-scoop(3s)Installingpseudo-chocolatey(3s)Installingpseudo-chocolatey(3s)Installingpseudo-chocolatey(3s)Installingpseudo-chocolatey(4s)Installingpseudo-chocolatey(4s)████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████┌───────────────────────────────────────────────┐|Library|Description||PTerm|MakebeautifulCLIs||Testza|Programmerfriendlytestframework||Cursor|Movethecursoraroundtheterminal|└───────────────────────────────────────────────┘temporinviduntutlaboreetdoloremagnaaliquyamerat,seddiamvoluptuaet,costoduodoloresetearestoduodoloresetearebum.Stetclitakasdgubergren,noseatakimatasanctusestLoremipsumdolorsitamet.┌─Sometitle!────────────────────────┐┌────────────Sometitle!─────────────┐┌────────────────────────Sometitle!─┐└────────────────────────Sometitle!─┘└────────────Sometitle!─────────────┘└─Sometitle!────────────────────────┘┌──────────────────────────────────────┐|Allprintersarefullycustomizable!|└──────────────────────────────────────┘┌──────────────────────────────────────┐|Allprintersarefullycustomizable!|└──────────────────────────────────────┘┌──────────────────────────────────────┐|Allprintersarefullycustomizable!|└──────────────────────────────────────┘╔══════════════════════════════════════╗Allprintersarefullycustomizable!╚══════════════════════════════════════╝BarStyle┌───────────────────────────────┐|HavefunexploringPTerm!|└───────────────────────────────┘Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/demo/demo/main.go000066400000000000000000000250571465010626300240070ustar00rootroot00000000000000package main import ( "flag" "math/rand" "reflect" "strconv" "strings" "time" "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) // Speed the demo up, by setting this flag. // Usefull for debugging. // Example: // // go run main.go -speedup var speedup = flag.Bool("speedup", false, "Speed up the demo") var skipIntro = flag.Bool("skip-intro", false, "Skips the intro") var second = time.Second var pseudoProgramList = strings.Split("pseudo-excel pseudo-photoshop pseudo-chrome pseudo-outlook pseudo-explorer "+ "pseudo-git pseudo-vsc pseudo-intellij pseudo-minecraft pseudo-scoop pseudo-chocolatey", " ") func main() { setup() // Setup the demo (flags etc.) // Show intro if !*skipIntro { introScreen() clear() } showcase("Structured Logging", 5, func() { logger := pterm.DefaultLogger. WithLevel(pterm.LogLevelTrace) logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) time.Sleep(time.Second * 3) interstingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } logger.Debug("This might be interesting", logger.ArgsFromMap(interstingStuff)) time.Sleep(time.Second * 3) logger.Info("That was actually interesting", logger.Args("such", "wow")) time.Sleep(time.Second * 3) logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) time.Sleep(time.Second * 3) logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) time.Sleep(time.Second * 3) logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) }) showcase("Progress bar", 2, func() { pb, _ := pterm.DefaultProgressbar.WithTotal(len(pseudoProgramList)).WithTitle("Installing stuff").Start() for i := 0; i < pb.Total; i++ { pb.UpdateTitle("Installing " + pseudoProgramList[i]) if pseudoProgramList[i] == "pseudo-minecraft" { pterm.Warning.Println("Could not install pseudo-minecraft\nThe company policy forbids games.") } else { pterm.Success.Println("Installing " + pseudoProgramList[i]) } pb.Increment() time.Sleep(second / 2) } pb.Stop() }) showcase("Spinner", 2, func() { list := pseudoProgramList[7:] spinner, _ := pterm.DefaultSpinner.Start("Installing stuff") for i := 0; i < len(list); i++ { spinner.UpdateText("Installing " + list[i]) if list[i] == "pseudo-minecraft" { pterm.Warning.Println("Could not install pseudo-minecraft\nThe company policy forbids games.") } else { pterm.Success.Println("Installing " + list[i]) } time.Sleep(second) } spinner.Success() }) showcase("Live Output", 2, func() { pterm.Info.Println("You can use an Area to display changing output:") pterm.Println() area, _ := pterm.DefaultArea.WithCenter().Start() // Start the Area printer, with the Center option. for i := 0; i < 10; i++ { str, _ := pterm.DefaultBigText.WithLetters(putils.LettersFromString(time.Now().Format("15:04:05"))).Srender() // Save current time in str. area.Update(str) // Update Area contents. time.Sleep(time.Second) } area.Stop() }) showcase("Tables", 4, func() { for i := 0; i < 3; i++ { pterm.Println() } td := [][]string{ {"Library", "Description"}, {"PTerm", "Make beautiful CLIs"}, {"Testza", "Programmer friendly test framework"}, {"Cursor", "Move the cursor around the terminal"}, } table, _ := pterm.DefaultTable.WithHasHeader().WithData(td).Srender() boxedTable, _ := pterm.DefaultTable.WithHasHeader().WithData(td).WithBoxed().Srender() pterm.DefaultCenter.Println(table) pterm.DefaultCenter.Println(boxedTable) }) showcase("TrueColor Support", 7, func() { from := pterm.NewRGB(0, 255, 255) // This RGB value is used as the gradients start point. to := pterm.NewRGB(255, 0, 255) // This RGB value is used as the gradients first point. str := "If your terminal has TrueColor support, you can use RGB colors!\nYou can even fade them :)\n\nLorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet." strs := strings.Split(str, "") var fadeInfo string // String which will be used to print info. // For loop over the range of the string length. for i := 0; i < len(str); i++ { // Append faded letter to info string. fadeInfo += from.Fade(0, float32(len(str)), float32(i), to).Sprint(strs[i]) } pterm.DefaultCenter.WithCenterEachLineSeparately().Println(fadeInfo) }) showcase("Fully Customizable", 2, func() { for i := 0; i < 4; i++ { pterm.Println() } text := "All printers are fully customizable!" area := pterm.DefaultArea.WithCenter() area.Update(pterm.DefaultBox.Sprintln(text)) time.Sleep(second) area.Update(pterm.DefaultBox.WithTopPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleTopLeft().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleTopCenter().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleTopRight().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleBottomRight().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleBottomCenter().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithTitle("Some title!").WithTitleBottomLeft().Sprintln(text)) time.Sleep(second / 3) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithBoxStyle(pterm.NewStyle(pterm.FgCyan)).Sprintln(text)) time.Sleep(second / 5) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithBoxStyle(pterm.NewStyle(pterm.FgRed)).Sprintln(text)) time.Sleep(second / 5) area.Update(pterm.DefaultBox.WithTopPadding(1).WithBottomPadding(1).WithLeftPadding(1).WithRightPadding(1).WithBoxStyle(pterm.NewStyle(pterm.FgGreen)).Sprintln(text)) time.Sleep(second / 5) area.Update(pterm.DefaultBox.WithTopPadding(1). WithBottomPadding(1). WithLeftPadding(1). WithRightPadding(1). WithHorizontalString("═"). WithVerticalString("║"). WithBottomLeftCornerString("╗"). WithBottomRightCornerString("╔"). WithTopLeftCornerString("╝"). WithTopRightCornerString("╚"). Sprintln(text)) area.Stop() }) showcase("Themes", 2, func() { pterm.Info.Println("You can change the color theme of PTerm easily to fit your needs!\nThis is the default one:") time.Sleep(second / 2) // Print every value of the default theme with its own style. v := reflect.ValueOf(pterm.ThemeDefault) typeOfS := v.Type() if typeOfS == reflect.TypeOf(pterm.Theme{}) { for i := 0; i < v.NumField(); i++ { field, ok := v.Field(i).Interface().(pterm.Style) if ok { field.Println(typeOfS.Field(i).Name) } time.Sleep(time.Millisecond * 250) } } }) showcase("And much more!", 3, func() { for i := 0; i < 4; i++ { pterm.Println() } box := pterm.DefaultBox. WithBottomPadding(1). WithTopPadding(1). WithLeftPadding(3). WithRightPadding(3). Sprintf("Have fun exploring %s!", pterm.Cyan("PTerm")) pterm.DefaultCenter.Println(box) }) } func setup() { flag.Parse() if *speedup { second = time.Millisecond * 200 } } func introScreen() { ptermLogo, _ := pterm.DefaultBigText.WithLetters( putils.LettersFromStringWithStyle("P", pterm.NewStyle(pterm.FgLightCyan)), putils.LettersFromStringWithStyle("Term", pterm.NewStyle(pterm.FgLightMagenta))). Srender() pterm.DefaultCenter.Print(ptermLogo) pterm.DefaultCenter.Print(pterm.DefaultHeader.WithFullWidth().WithBackgroundStyle(pterm.NewStyle(pterm.BgLightBlue)).WithMargin(10).Sprint("PTDP - PTerm Demo Program")) pterm.Info.Println("This animation was generated with the latest version of PTerm!" + "\nPTerm works on nearly every terminal and operating system." + "\nIt's super easy to use!" + "\nIf you want, you can customize everything :)" + "\nYou can see the code of this demo in the " + pterm.LightMagenta("./_examples/demo") + " directory." + "\n" + "\nThis demo was updated at: " + pterm.Green(time.Now().Format("02 Jan 2006 - 15:04:05 MST"))) pterm.Println() introSpinner, _ := pterm.DefaultSpinner.WithShowTimer(false).WithRemoveWhenDone(true).Start("Waiting for 15 seconds...") time.Sleep(second) for i := 14; i > 0; i-- { if i > 1 { introSpinner.UpdateText("Waiting for " + strconv.Itoa(i) + " seconds...") } else { introSpinner.UpdateText("Waiting for " + strconv.Itoa(i) + " second...") } time.Sleep(second) } introSpinner.Stop() } func clear() { print("\033[H\033[2J") } func showcase(title string, seconds int, content func()) { pterm.DefaultHeader.WithBackgroundStyle(pterm.NewStyle(pterm.BgLightBlue)).WithFullWidth().Println(title) pterm.Println() time.Sleep(second / 2) content() time.Sleep(second * time.Duration(seconds)) print("\033[H\033[2J") } func randomInt(min, max int) int { rand.Seed(time.Now().UnixNano()) return rand.Intn(max-min+1) + min } golang-github-pterm-pterm-0.12.79/_examples/header/000077500000000000000000000000001465010626300221035ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/header/README.md000066400000000000000000000030151465010626300233610ustar00rootroot00000000000000### header/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/header/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Print a default header. // This uses the default settings of PTerm to print a header. pterm.DefaultHeader.Println("This is the default header!") // Print a spacer line for better readability. pterm.Println() // Print a full-width header. // This uses the WithFullWidth() option of PTerm to print a header that spans the full width of the terminal. pterm.DefaultHeader.WithFullWidth().Println("This is a full-width header.") } ```
### header/custom ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/header/custom/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Customize the DefaultHeader with a cyan background, black text, and a margin of 15. pterm.DefaultHeader.WithMargin(15).WithBackgroundStyle(pterm.NewStyle(pterm.BgCyan)).WithTextStyle(pterm.NewStyle(pterm.FgBlack)).Println("This is a custom header!") // Define a new HeaderPrinter with a red background, black text, and a margin of 20. newHeader := pterm.HeaderPrinter{ TextStyle: pterm.NewStyle(pterm.FgBlack), BackgroundStyle: pterm.NewStyle(pterm.BgRed), Margin: 20, } // Print the custom header using the new HeaderPrinter. newHeader.Println("This is a custom header!") } ```
golang-github-pterm-pterm-0.12.79/_examples/header/custom/000077500000000000000000000000001465010626300234155ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/header/custom/README.md000066400000000000000000000013261465010626300246760ustar00rootroot00000000000000# header/custom ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Customize the DefaultHeader with a cyan background, black text, and a margin of 15. pterm.DefaultHeader.WithMargin(15).WithBackgroundStyle(pterm.NewStyle(pterm.BgCyan)).WithTextStyle(pterm.NewStyle(pterm.FgBlack)).Println("This is a custom header!") // Define a new HeaderPrinter with a red background, black text, and a margin of 20. newHeader := pterm.HeaderPrinter{ TextStyle: pterm.NewStyle(pterm.FgBlack), BackgroundStyle: pterm.NewStyle(pterm.BgRed), Margin: 20, } // Print the custom header using the new HeaderPrinter. newHeader.Println("This is a custom header!") } ``` golang-github-pterm-pterm-0.12.79/_examples/header/custom/animation.svg000066400000000000000000000061011465010626300261130ustar00rootroot00000000000000 This is a custom header! This is a custom header! Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/header/custom/main.go000066400000000000000000000012351465010626300246710ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Customize the DefaultHeader with a cyan background, black text, and a margin of 15. pterm.DefaultHeader.WithMargin(15).WithBackgroundStyle(pterm.NewStyle(pterm.BgCyan)).WithTextStyle(pterm.NewStyle(pterm.FgBlack)).Println("This is a custom header!") // Define a new HeaderPrinter with a red background, black text, and a margin of 20. newHeader := pterm.HeaderPrinter{ TextStyle: pterm.NewStyle(pterm.FgBlack), BackgroundStyle: pterm.NewStyle(pterm.BgRed), Margin: 20, } // Print the custom header using the new HeaderPrinter. newHeader.Println("This is a custom header!") } golang-github-pterm-pterm-0.12.79/_examples/header/demo/000077500000000000000000000000001465010626300230275ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/header/demo/README.md000066400000000000000000000010531465010626300243050ustar00rootroot00000000000000# header/demo ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Print a default header. // This uses the default settings of PTerm to print a header. pterm.DefaultHeader.Println("This is the default header!") // Print a spacer line for better readability. pterm.Println() // Print a full-width header. // This uses the WithFullWidth() option of PTerm to print a header that spans the full width of the terminal. pterm.DefaultHeader.WithFullWidth().Println("This is a full-width header.") } ``` golang-github-pterm-pterm-0.12.79/_examples/header/demo/animation.svg000066400000000000000000000062271465010626300255360ustar00rootroot00000000000000 This is the default header! This is a full-width header. Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/header/demo/main.go000066400000000000000000000007641465010626300243110ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Print a default header. // This uses the default settings of PTerm to print a header. pterm.DefaultHeader.Println("This is the default header!") // Print a spacer line for better readability. pterm.Println() // Print a full-width header. // This uses the WithFullWidth() option of PTerm to print a header that spans the full width of the terminal. pterm.DefaultHeader.WithFullWidth().Println("This is a full-width header.") } golang-github-pterm-pterm-0.12.79/_examples/heatmap/000077500000000000000000000000001465010626300222725ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/heatmap/README.md000066400000000000000000000173701465010626300235610ustar00rootroot00000000000000### heatmap/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/heatmap/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap. Each sub-array represents a row in the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the labels for the X and Y axes of the heatmap. headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Create a heatmap with the defined data and axis labels, and enable RGB colors. // Then render the heatmap. pterm.DefaultHeatmap.WithAxisData(headerData).WithData(data).WithEnableRGB().Render() } ```
### heatmap/custom_colors ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/heatmap/custom_colors/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis labels for the heatmap headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message pterm.Info.Println("The following table has no rgb (supported by every terminal), no axis data and a legend.") pterm.Println() // Create the heatmap with the defined data and options, and render it pterm.DefaultHeatmap. WithData(data). WithBoxed(false). WithAxisData(headerData). WithLegend(false). WithColors(pterm.BgBlue, pterm.BgRed, pterm.BgGreen, pterm.BgYellow). WithLegend(). Render() } ```
### heatmap/custom_legend ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/heatmap/custom_legend/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the header data for the heatmap headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message pterm.Info.Println("The following table has rgb (not supported by every terminal), axis data and a custom legend.") pterm.Println() // Create the heatmap with the defined data and options // Options are chained in a single line for simplicity pterm.DefaultHeatmap. WithData(data). WithBoxed(false). WithAxisData(headerData). WithEnableRGB(). WithLegendLabel("custom"). WithLegendOnlyColoredCells(). Render() // Render the heatmap } ```
### heatmap/custom_rgb ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/heatmap/custom_rgb/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis labels for the heatmap. axisLabels := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message. pterm.Info.Println("The following table has rgb (not supported by every terminal), axis data and a legend.") pterm.Println() // Define the color range for the heatmap. rgbRange := []pterm.RGB{ pterm.NewRGB(0, 0, 255), pterm.NewRGB(255, 0, 0), pterm.NewRGB(0, 255, 0), pterm.NewRGB(255, 255, 0), } // Create and render the heatmap. pterm.DefaultHeatmap. WithData(data). WithBoxed(false). WithAxisData(axisLabels). WithEnableRGB(). WithRGBRange(rgbRange...). Render() } ```
### heatmap/no_grid ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/heatmap/no_grid/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis data for the heatmap. axisData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message. pterm.Info.Println("The following table has rgb (not supported by every terminal), axis data and a legend.") pterm.Println() // Create the heatmap with the defined data and options, then render it. pterm.DefaultHeatmap.WithData(data).WithBoxed(false).WithAxisData(axisData).WithEnableRGB().WithLegend().WithGrid(false).Render() } ```
### heatmap/separated ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/heatmap/separated/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis labels for the heatmap. headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message. pterm.Info.Println("The following table has no rgb (supported by every terminal), no axis data and no legend.") pterm.Println() // Create the heatmap with the specified data and options, and render it. pterm.DefaultHeatmap.WithData(data).WithBoxed(false).WithAxisData(headerData).WithLegend(false).Render() } ```
golang-github-pterm-pterm-0.12.79/_examples/heatmap/custom_colors/000077500000000000000000000000001465010626300251655ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/heatmap/custom_colors/README.md000066400000000000000000000023111465010626300264410ustar00rootroot00000000000000# heatmap/custom_colors ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis labels for the heatmap headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message pterm.Info.Println("The following table has no rgb (supported by every terminal), no axis data and a legend.") pterm.Println() // Create the heatmap with the defined data and options, and render it pterm.DefaultHeatmap. WithData(data). WithBoxed(false). WithAxisData(headerData). WithLegend(false). WithColors(pterm.BgBlue, pterm.BgRed, pterm.BgGreen, pterm.BgYellow). WithLegend(). Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/heatmap/custom_colors/animation.svg000066400000000000000000000714541465010626300277000ustar00rootroot00000000000000 INFO Thefollowingtablehasnorgb(supportedbyeveryterminal),noaxisdataandalegend.1 0.9 0.2-0.7 0.4-0.5 0.6-0.3 0.8-0.1 -1 0.1-0.8 0.3────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────2 0.2-0.7-0.5-0.3-0.1 0.1 0.3 0.5 0.9-0.9-0.7-0.5-0.33 0.4 0.4-0.3 -1 0.3-0.2-0.9 0.5-0.3 -1 0.6-0.2-0.94 0.9-0.5-0.1 0.3 1 -0.7-0.3 0.1 0.7-0.9-0.5 0.2 0.65 0.5 0.6 0.1-0.2-0.7 0.8 0.6 0.1-0.5-0.7 0.7 0.3 0 abcdefghijklmLegend -1 -0.33 0.33 1 ────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼──────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼──────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼──Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/heatmap/custom_colors/main.go000066400000000000000000000022101465010626300264330ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis labels for the heatmap headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message pterm.Info.Println("The following table has no rgb (supported by every terminal), no axis data and a legend.") pterm.Println() // Create the heatmap with the defined data and options, and render it pterm.DefaultHeatmap. WithData(data). WithBoxed(false). WithAxisData(headerData). WithLegend(false). WithColors(pterm.BgBlue, pterm.BgRed, pterm.BgGreen, pterm.BgYellow). WithLegend(). Render() } golang-github-pterm-pterm-0.12.79/_examples/heatmap/custom_legend/000077500000000000000000000000001465010626300251225ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/heatmap/custom_legend/README.md000066400000000000000000000023601465010626300264020ustar00rootroot00000000000000# heatmap/custom_legend ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the header data for the heatmap headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message pterm.Info.Println("The following table has rgb (not supported by every terminal), axis data and a custom legend.") pterm.Println() // Create the heatmap with the defined data and options // Options are chained in a single line for simplicity pterm.DefaultHeatmap. WithData(data). WithBoxed(false). WithAxisData(headerData). WithEnableRGB(). WithLegendLabel("custom"). WithLegendOnlyColoredCells(). Render() // Render the heatmap } ``` golang-github-pterm-pterm-0.12.79/_examples/heatmap/custom_legend/animation.svg000066400000000000000000000631461465010626300276340ustar00rootroot00000000000000 INFO Thefollowingtablehasrgb(notsupportedbyeveryterminal),axisdataandacustomlegend.1 0.9 0.2-0.7 0.4-0.5 0.6-0.3 0.8-0.1 -1 0.1-0.8 0.3────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────2 0.2-0.7-0.5-0.3-0.1 0.1 0.3 0.5 0.9-0.9-0.7-0.5-0.33 0.4 0.4-0.3 -1 0.3-0.2-0.9 0.5-0.3 -1 0.6-0.2-0.94 0.9-0.5-0.1 0.3 1 -0.7-0.3 0.1 0.7-0.9-0.5 0.2 0.65 0.5 0.6 0.1-0.2-0.7 0.8 0.6 0.1-0.5-0.7 0.7 0.3 0 abcdefghijklmcustom ────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼───────┼────┼────┼────┼────┼────┼────┼───custom Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/heatmap/custom_legend/main.go000066400000000000000000000022571465010626300264030ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the header data for the heatmap headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message pterm.Info.Println("The following table has rgb (not supported by every terminal), axis data and a custom legend.") pterm.Println() // Create the heatmap with the defined data and options // Options are chained in a single line for simplicity pterm.DefaultHeatmap. WithData(data). WithBoxed(false). WithAxisData(headerData). WithEnableRGB(). WithLegendLabel("custom"). WithLegendOnlyColoredCells(). Render() // Render the heatmap } golang-github-pterm-pterm-0.12.79/_examples/heatmap/custom_rgb/000077500000000000000000000000001465010626300244365ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/heatmap/custom_rgb/README.md000066400000000000000000000024351465010626300257210ustar00rootroot00000000000000# heatmap/custom_rgb ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis labels for the heatmap. axisLabels := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message. pterm.Info.Println("The following table has rgb (not supported by every terminal), axis data and a legend.") pterm.Println() // Define the color range for the heatmap. rgbRange := []pterm.RGB{ pterm.NewRGB(0, 0, 255), pterm.NewRGB(255, 0, 0), pterm.NewRGB(0, 255, 0), pterm.NewRGB(255, 255, 0), } // Create and render the heatmap. pterm.DefaultHeatmap. WithData(data). WithBoxed(false). WithAxisData(axisLabels). WithEnableRGB(). WithRGBRange(rgbRange...). Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/heatmap/custom_rgb/animation.svg000066400000000000000000000505651465010626300271510ustar00rootroot00000000000000 INFO Thefollowingtablehasrgb(notsupportedbyeveryterminal),axisdataandalegend.1 0.9 0.2-0.7 0.4-0.5 0.6-0.3 0.8-0.1 -1 0.1-0.8 0.3────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────2 0.2-0.7-0.5-0.3-0.1 0.1 0.3 0.5 0.9-0.9-0.7-0.5-0.33 0.4 0.4-0.3 -1 0.3-0.2-0.9 0.5-0.3 -1 0.6-0.2-0.94 0.9-0.5-0.1 0.3 1 -0.7-0.3 0.1 0.7-0.9-0.5 0.2 0.65 0.5 0.6 0.1-0.2-0.7 0.8 0.6 0.1-0.5-0.7 0.7 0.3 0 abcdefghijklmLegend -1 -0.78 -0.56 -0.33 -0.11 0.11 0.33 0.56 0.78 1 ────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────────┼────┼────┼────┼────┼────┼────┼────Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/heatmap/custom_rgb/main.go000066400000000000000000000023371465010626300257160ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis labels for the heatmap. axisLabels := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message. pterm.Info.Println("The following table has rgb (not supported by every terminal), axis data and a legend.") pterm.Println() // Define the color range for the heatmap. rgbRange := []pterm.RGB{ pterm.NewRGB(0, 0, 255), pterm.NewRGB(255, 0, 0), pterm.NewRGB(0, 255, 0), pterm.NewRGB(255, 255, 0), } // Create and render the heatmap. pterm.DefaultHeatmap. WithData(data). WithBoxed(false). WithAxisData(axisLabels). WithEnableRGB(). WithRGBRange(rgbRange...). Render() } golang-github-pterm-pterm-0.12.79/_examples/heatmap/demo/000077500000000000000000000000001465010626300232165ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/heatmap/demo/README.md000066400000000000000000000020121465010626300244700ustar00rootroot00000000000000# heatmap/demo ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap. Each sub-array represents a row in the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the labels for the X and Y axes of the heatmap. headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Create a heatmap with the defined data and axis labels, and enable RGB colors. // Then render the heatmap. pterm.DefaultHeatmap.WithAxisData(headerData).WithData(data).WithEnableRGB().Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/heatmap/demo/animation.svg000066400000000000000000000701211465010626300257170ustar00rootroot00000000000000┌────┬────┬────┬────┬────┬────┬────┬────┬────┬────┬────┬────┬────┬────┐1 0.9 0.2-0.7 0.4-0.5 0.6-0.3 0.8-0.1 -1 0.1-0.8 0.3├────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┤2 0.2-0.7-0.5-0.3-0.1 0.1 0.3 0.5 0.9-0.9-0.7-0.5-0.33 0.4 0.4-0.3 -1 0.3-0.2-0.9 0.5-0.3 -1 0.6-0.2-0.94 0.9-0.5-0.1 0.3 1 -0.7-0.3 0.1 0.7-0.9-0.5 0.2 0.65 0.5 0.6 0.1-0.2-0.7 0.8 0.6 0.1-0.5-0.7 0.7 0.3 0 abcdefghijklm└────┴────┴────┴────┴────┴────┴────┴────┴────┴────┴────┴────┴────┴────┘┌──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┐Legend -1 -0.78 -0.56 -0.33 -0.11 0.11 0.33 0.56 0.78 1 └──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┘├────┼────┼────┼────┼────┼────┼────┼────┼────┼─├────┼────┼────┼────┼───└────┴───┌──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬────┌──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────└──────┴──────┴──────┴──────┴──────┴──────┴──────┴─Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/heatmap/demo/main.go000066400000000000000000000017221465010626300244730ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap. Each sub-array represents a row in the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the labels for the X and Y axes of the heatmap. headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Create a heatmap with the defined data and axis labels, and enable RGB colors. // Then render the heatmap. pterm.DefaultHeatmap.WithAxisData(headerData).WithData(data).WithEnableRGB().Render() } golang-github-pterm-pterm-0.12.79/_examples/heatmap/no_grid/000077500000000000000000000000001465010626300237135ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/heatmap/no_grid/README.md000066400000000000000000000021641465010626300251750ustar00rootroot00000000000000# heatmap/no_grid ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis data for the heatmap. axisData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message. pterm.Info.Println("The following table has rgb (not supported by every terminal), axis data and a legend.") pterm.Println() // Create the heatmap with the defined data and options, then render it. pterm.DefaultHeatmap.WithData(data).WithBoxed(false).WithAxisData(axisData).WithEnableRGB().WithLegend().WithGrid(false).Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/heatmap/no_grid/animation.svg000066400000000000000000000333701465010626300264210ustar00rootroot00000000000000 INFO Thefollowingtablehasrgb(notsupportedbyeveryterminal),axisdataandalegend.1 0.9 0.2-0.7 0.4-0.5 0.6-0.3 0.8-0.1 -1 0.1-0.8 0.32 0.2-0.7-0.5-0.3-0.1 0.1 0.3 0.5 0.9-0.9-0.7-0.5-0.33 0.4 0.4-0.3 -1 0.3-0.2-0.9 0.5-0.3 -1 0.6-0.2-0.94 0.9-0.5-0.1 0.3 1 -0.7-0.3 0.1 0.7-0.9-0.5 0.2 0.65 0.5 0.6 0.1-0.2-0.7 0.8 0.6 0.1-0.5-0.7 0.7 0.3 0 abcdefghijklmLegend -1 -0.78 -0.56 -0.33 -0.11 0.11 0.33 0.56 0.78 1 Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/heatmap/no_grid/main.go000066400000000000000000000020711465010626300251660ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" ) func main() { // Define the data for the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis data for the heatmap. axisData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message. pterm.Info.Println("The following table has rgb (not supported by every terminal), axis data and a legend.") pterm.Println() // Create the heatmap with the defined data and options, then render it. pterm.DefaultHeatmap.WithData(data).WithBoxed(false).WithAxisData(axisData).WithEnableRGB().WithLegend().WithGrid(false).Render() } golang-github-pterm-pterm-0.12.79/_examples/heatmap/separated/000077500000000000000000000000001465010626300242425ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/heatmap/separated/README.md000066400000000000000000000021401465010626300255160ustar00rootroot00000000000000# heatmap/separated ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis labels for the heatmap. headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message. pterm.Info.Println("The following table has no rgb (supported by every terminal), no axis data and no legend.") pterm.Println() // Create the heatmap with the specified data and options, and render it. pterm.DefaultHeatmap.WithData(data).WithBoxed(false).WithAxisData(headerData).WithLegend(false).Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/heatmap/separated/animation.svg000066400000000000000000000440151465010626300267460ustar00rootroot00000000000000 INFO Thefollowingtablehasnorgb(supportedbyeveryterminal),noaxisdataandnolegend.1 0.9 0.2-0.7 0.4-0.5 0.6-0.3 0.8-0.1 -1 0.1-0.8 0.3────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────2 0.2-0.7-0.5-0.3-0.1 0.1 0.3 0.5 0.9-0.9-0.7-0.5-0.33 0.4 0.4-0.3 -1 0.3-0.2-0.9 0.5-0.3 -1 0.6-0.2-0.94 0.9-0.5-0.1 0.3 1 -0.7-0.3 0.1 0.7-0.9-0.5 0.2 0.65 0.5 0.6 0.1-0.2-0.7 0.8 0.6 0.1-0.5-0.7 0.7 0.3 0 abcdefghijklm────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼───────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼───Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/heatmap/separated/main.go000066400000000000000000000020431465010626300255140ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Define the data for the heatmap. data := [][]float32{ {0.9, 0.2, -0.7, 0.4, -0.5, 0.6, -0.3, 0.8, -0.1, -1.0, 0.1, -0.8, 0.3}, {0.2, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.9, -0.9, -0.7, -0.5, -0.3}, {0.4, 0.4, -0.3, -1.0, 0.3, -0.2, -0.9, 0.5, -0.3, -1.0, 0.6, -0.2, -0.9}, {0.9, -0.5, -0.1, 0.3, 1, -0.7, -0.3, 0.1, 0.7, -0.9, -0.5, 0.2, 0.6}, {0.5, 0.6, 0.1, -0.2, -0.7, 0.8, 0.6, 0.1, -0.5, -0.7, 0.7, 0.3, 0.0}, } // Define the axis labels for the heatmap. headerData := pterm.HeatmapAxis{ XAxis: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, YAxis: []string{"1", "2", "3", "4", "5"}, } // Print an informational message. pterm.Info.Println("The following table has no rgb (supported by every terminal), no axis data and no legend.") pterm.Println() // Create the heatmap with the specified data and options, and render it. pterm.DefaultHeatmap.WithData(data).WithBoxed(false).WithAxisData(headerData).WithLegend(false).Render() } golang-github-pterm-pterm-0.12.79/_examples/interactive_confirm/000077500000000000000000000000001465010626300247055ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/interactive_confirm/README.md000066400000000000000000000014771465010626300261750ustar00rootroot00000000000000### interactive_confirm/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_confirm/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Show an interactive confirmation dialog and get the result. result, _ := pterm.DefaultInteractiveConfirm.Show() // Print a blank line for better readability. pterm.Println() // Print the user's answer in a formatted way. pterm.Info.Printfln("You answered: %s", boolToText(result)) } // boolToText converts a boolean value to a colored text. // If the value is true, it returns a green "Yes". // If the value is false, it returns a red "No". func boolToText(b bool) string { if b { return pterm.Green("Yes") } return pterm.Red("No") } ```
golang-github-pterm-pterm-0.12.79/_examples/interactive_confirm/demo/000077500000000000000000000000001465010626300256315ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/interactive_confirm/demo/README.md000066400000000000000000000012551465010626300271130ustar00rootroot00000000000000# interactive_confirm/demo ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" ) func main() { // Show an interactive confirmation dialog and get the result. result, _ := pterm.DefaultInteractiveConfirm.Show() // Print a blank line for better readability. pterm.Println() // Print the user's answer in a formatted way. pterm.Info.Printfln("You answered: %s", boolToText(result)) } // boolToText converts a boolean value to a colored text. // If the value is true, it returns a green "Yes". // If the value is false, it returns a red "No". func boolToText(b bool) string { if b { return pterm.Green("Yes") } return pterm.Red("No") } ``` golang-github-pterm-pterm-0.12.79/_examples/interactive_confirm/demo/animation.svg000066400000000000000000000101211465010626300303240ustar00rootroot00000000000000Pleaseconfirm[y/N]:Yes INFO Youanswered:YesPleaseconfirm[y/N]:Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/interactive_confirm/demo/ci.go000066400000000000000000000005541465010626300265570ustar00rootroot00000000000000package main import ( "os" "time" "atomicgo.dev/keyboard" ) // ------ Automation for CI ------ // You can ignore this function, it is used to automatically run the demo and generate the example animation in our CI system. func init() { if os.Getenv("CI") == "true" { go func() { time.Sleep(time.Second * 2) keyboard.SimulateKeyPress('y') }() } } golang-github-pterm-pterm-0.12.79/_examples/interactive_confirm/demo/main.go000066400000000000000000000011511465010626300271020ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" ) func main() { // Show an interactive confirmation dialog and get the result. result, _ := pterm.DefaultInteractiveConfirm.Show() // Print a blank line for better readability. pterm.Println() // Print the user's answer in a formatted way. pterm.Info.Printfln("You answered: %s", boolToText(result)) } // boolToText converts a boolean value to a colored text. // If the value is true, it returns a green "Yes". // If the value is false, it returns a red "No". func boolToText(b bool) string { if b { return pterm.Green("Yes") } return pterm.Red("No") } golang-github-pterm-pterm-0.12.79/_examples/interactive_continue/000077500000000000000000000000001465010626300250745ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/interactive_continue/README.md000066400000000000000000000017071465010626300263600ustar00rootroot00000000000000### interactive_continue/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_continue/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Create an interactive continue prompt with default settings // This will pause the program execution until the user presses enter // The message displayed is "Press 'Enter' to continue..." prompt := pterm.DefaultInteractiveContinue // Show the prompt and wait for user input // The returned result is the user's input (should be empty as it's a continue prompt) // The second return value is an error which is ignored here result, _ := prompt.Show() // Print a blank line for better readability pterm.Println() // Print the user's input with an info prefix // As this is a continue prompt, the input should be empty pterm.Info.Printfln("You answered: %s", result) } ```
golang-github-pterm-pterm-0.12.79/_examples/interactive_continue/demo/000077500000000000000000000000001465010626300260205ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/interactive_continue/demo/README.md000066400000000000000000000014641465010626300273040ustar00rootroot00000000000000# interactive_continue/demo ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" ) func main() { // Create an interactive continue prompt with default settings // This will pause the program execution until the user presses enter // The message displayed is "Press 'Enter' to continue..." prompt := pterm.DefaultInteractiveContinue // Show the prompt and wait for user input // The returned result is the user's input (should be empty as it's a continue prompt) // The second return value is an error which is ignored here result, _ := prompt.Show() // Print a blank line for better readability pterm.Println() // Print the user's input with an info prefix // As this is a continue prompt, the input should be empty pterm.Info.Printfln("You answered: %s", result) } ``` golang-github-pterm-pterm-0.12.79/_examples/interactive_continue/demo/animation.svg000066400000000000000000000100411465010626300305140ustar00rootroot00000000000000Doyouwanttocontinue[Yes/no/all/cancel]:yes INFO Youanswered:yesDoyouwanttocontinue[Yes/no/all/cancel]:Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/interactive_continue/demo/ci.go000066400000000000000000000005541465010626300267460ustar00rootroot00000000000000package main import ( "os" "time" "atomicgo.dev/keyboard" ) // ------ Automation for CI ------ // You can ignore this function, it is used to automatically run the demo and generate the example animation in our CI system. func init() { if os.Getenv("CI") == "true" { go func() { time.Sleep(time.Second * 2) keyboard.SimulateKeyPress('y') }() } } golang-github-pterm-pterm-0.12.79/_examples/interactive_continue/demo/main.go000066400000000000000000000013571465010626300273010ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" ) func main() { // Create an interactive continue prompt with default settings // This will pause the program execution until the user presses enter // The message displayed is "Press 'Enter' to continue..." prompt := pterm.DefaultInteractiveContinue // Show the prompt and wait for user input // The returned result is the user's input (should be empty as it's a continue prompt) // The second return value is an error which is ignored here result, _ := prompt.Show() // Print a blank line for better readability pterm.Println() // Print the user's input with an info prefix // As this is a continue prompt, the input should be empty pterm.Info.Printfln("You answered: %s", result) } golang-github-pterm-pterm-0.12.79/_examples/interactive_multiselect/000077500000000000000000000000001465010626300256025ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/interactive_multiselect/README.md000066400000000000000000000061721465010626300270670ustar00rootroot00000000000000### interactive_multiselect/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_multiselect/demo/animation.svg)
SHOW SOURCE ```go package main import ( "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options. var options []string // Populate the options slice with 100 options. for i := 0; i < 100; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Add 5 more options to the slice, indicating the availability of fuzzy searching. for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("You can use fuzzy searching (%d)", i)) } // Use PTerm's interactive multiselect to present the options to the user and capture their selections. // The Show() method displays the options and waits for user input. selectedOptions, _ := pterm.DefaultInteractiveMultiselect.WithOptions(options).Show() // Print the selected options, highlighted in green. pterm.Info.Printfln("Selected options: %s", pterm.Green(selectedOptions)) } ```
### interactive_multiselect/custom-checkmarks ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_multiselect/custom-checkmarks/animation.svg)
SHOW SOURCE ```go package main import ( "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options var options []string // Populate the options slice with 5 options for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Create a new interactive multiselect printer with the options // Disable the filter and define the checkmark symbols printer := pterm.DefaultInteractiveMultiselect. WithOptions(options). WithFilter(false). WithCheckmark(&pterm.Checkmark{Checked: pterm.Green("+"), Unchecked: pterm.Red("-")}) // Show the interactive multiselect and get the selected options selectedOptions, _ := printer.Show() // Print the selected options pterm.Info.Printfln("Selected options: %s", pterm.Green(selectedOptions)) } ```
### interactive_multiselect/custom-keys ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_multiselect/custom-keys/animation.svg)
SHOW SOURCE ```go package main import ( "atomicgo.dev/keyboard/keys" "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options var options []string // Populate the options slice with 5 options for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Create a new interactive multiselect printer with the options // Disable the filter and set the keys for confirming and selecting options printer := pterm.DefaultInteractiveMultiselect. WithOptions(options). WithFilter(false). WithKeyConfirm(keys.Enter). WithKeySelect(keys.Space) // Show the interactive multiselect and get the selected options selectedOptions, _ := printer.Show() // Print the selected options pterm.Info.Printfln("Selected options: %s", pterm.Green(selectedOptions)) } ```
golang-github-pterm-pterm-0.12.79/_examples/interactive_multiselect/custom-checkmarks/000077500000000000000000000000001465010626300312255ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/interactive_multiselect/custom-checkmarks/README.md000066400000000000000000000015621465010626300325100ustar00rootroot00000000000000# interactive_multiselect/custom-checkmarks ![Animation](animation.svg) ```go package main import ( "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options var options []string // Populate the options slice with 5 options for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Create a new interactive multiselect printer with the options // Disable the filter and define the checkmark symbols printer := pterm.DefaultInteractiveMultiselect. WithOptions(options). WithFilter(false). WithCheckmark(&pterm.Checkmark{Checked: pterm.Green("+"), Unchecked: pterm.Red("-")}) // Show the interactive multiselect and get the selected options selectedOptions, _ := printer.Show() // Print the selected options pterm.Info.Printfln("Selected options: %s", pterm.Green(selectedOptions)) } ``` golang-github-pterm-pterm-0.12.79/_examples/interactive_multiselect/custom-checkmarks/animation.svg000066400000000000000000001057121465010626300337330ustar00rootroot00000000000000Pleaseselectyouroptions:>[-]Option0[-]Option1[-]Option2[-]Option3[-]Option4enter:select|tab:confirm|left:none|right:all[-]Option0>[-]Option1>[+]Option1[+]Option1>[-]Option2>[-]Option3>[+]Option3[+]Option3>[-]Option4>[+]Option0[+]Option0>[+]Option2[+]Option2[+]Option4>Option1>Option3>Option2>Option4 INFO Selectedoptions:[Option1Option3Option2Option4]>[+]Option4Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/interactive_multiselect/custom-checkmarks/ci.go000066400000000000000000000015341465010626300321520ustar00rootroot00000000000000package main import ( "os" "time" "atomicgo.dev/keyboard" "atomicgo.dev/keyboard/keys" ) // ------ Automation for CI ------ // You can ignore this function, it is used to automatically run the demo and generate the example animation in our CI system. func init() { if os.Getenv("CI") == "true" { go func() { time.Sleep(time.Second) for i := 0; i < 10; i++ { keyboard.SimulateKeyPress(keys.Down) if i%2 == 0 { time.Sleep(time.Millisecond * 100) keyboard.SimulateKeyPress(keys.Enter) } time.Sleep(time.Millisecond * 500) } time.Sleep(time.Second) for _, s := range "fuzzy" { keyboard.SimulateKeyPress(s) time.Sleep(time.Millisecond * 150) } time.Sleep(time.Second) keyboard.SimulateKeyPress(keys.Enter) time.Sleep(time.Millisecond * 350) keyboard.SimulateKeyPress(keys.Tab) }() } } golang-github-pterm-pterm-0.12.79/_examples/interactive_multiselect/custom-checkmarks/main.go000066400000000000000000000014351465010626300325030ustar00rootroot00000000000000package main import ( "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options var options []string // Populate the options slice with 5 options for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Create a new interactive multiselect printer with the options // Disable the filter and define the checkmark symbols printer := pterm.DefaultInteractiveMultiselect. WithOptions(options). WithFilter(false). WithCheckmark(&pterm.Checkmark{Checked: pterm.Green("+"), Unchecked: pterm.Red("-")}) // Show the interactive multiselect and get the selected options selectedOptions, _ := printer.Show() // Print the selected options pterm.Info.Printfln("Selected options: %s", pterm.Green(selectedOptions)) } golang-github-pterm-pterm-0.12.79/_examples/interactive_multiselect/custom-keys/000077500000000000000000000000001465010626300300655ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/interactive_multiselect/custom-keys/README.md000066400000000000000000000016011465010626300313420ustar00rootroot00000000000000# interactive_multiselect/custom-keys ![Animation](animation.svg) ```go package main import ( "atomicgo.dev/keyboard/keys" "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options var options []string // Populate the options slice with 5 options for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Create a new interactive multiselect printer with the options // Disable the filter and set the keys for confirming and selecting options printer := pterm.DefaultInteractiveMultiselect. WithOptions(options). WithFilter(false). WithKeyConfirm(keys.Enter). WithKeySelect(keys.Space) // Show the interactive multiselect and get the selected options selectedOptions, _ := printer.Show() // Print the selected options pterm.Info.Printfln("Selected options: %s", pterm.Green(selectedOptions)) } ``` golang-github-pterm-pterm-0.12.79/_examples/interactive_multiselect/custom-keys/animation.svg000066400000000000000000000320521465010626300325670ustar00rootroot00000000000000Pleaseselectyouroptions:[]Option2[]Option3[]Option4space:select|enter:confirm|left:none|right:all[]Option0>[]Option1>[]Option1[]Option1>[]Option2>[]Option2>Option1>Option2 INFO Selectedoptions:[Option1Option2]>[]Option0[]Option1Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/interactive_multiselect/custom-keys/ci.go000066400000000000000000000013121465010626300310040ustar00rootroot00000000000000package main import ( "os" "time" "atomicgo.dev/keyboard" "atomicgo.dev/keyboard/keys" ) // ------ Automation for CI ------ // You can ignore this function, it is used to automatically run the demo and generate the example animation in our CI system. func init() { if os.Getenv("CI") == "true" { go func() { time.Sleep(time.Second) keyboard.SimulateKeyPress(keys.Down) time.Sleep(time.Millisecond * 100) keyboard.SimulateKeyPress(keys.Space) time.Sleep(time.Millisecond * 300) keyboard.SimulateKeyPress(keys.Down) time.Sleep(time.Millisecond * 100) keyboard.SimulateKeyPress(keys.Space) time.Sleep(time.Millisecond * 300) keyboard.SimulateKeyPress(keys.Enter) }() } } golang-github-pterm-pterm-0.12.79/_examples/interactive_multiselect/custom-keys/main.go000066400000000000000000000014621465010626300313430ustar00rootroot00000000000000package main import ( "atomicgo.dev/keyboard/keys" "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options var options []string // Populate the options slice with 5 options for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Create a new interactive multiselect printer with the options // Disable the filter and set the keys for confirming and selecting options printer := pterm.DefaultInteractiveMultiselect. WithOptions(options). WithFilter(false). WithKeyConfirm(keys.Enter). WithKeySelect(keys.Space) // Show the interactive multiselect and get the selected options selectedOptions, _ := printer.Show() // Print the selected options pterm.Info.Printfln("Selected options: %s", pterm.Green(selectedOptions)) } golang-github-pterm-pterm-0.12.79/_examples/interactive_multiselect/demo/000077500000000000000000000000001465010626300265265ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/interactive_multiselect/demo/README.md000066400000000000000000000016611465010626300300110ustar00rootroot00000000000000# interactive_multiselect/demo ![Animation](animation.svg) ```go package main import ( "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options. var options []string // Populate the options slice with 100 options. for i := 0; i < 100; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Add 5 more options to the slice, indicating the availability of fuzzy searching. for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("You can use fuzzy searching (%d)", i)) } // Use PTerm's interactive multiselect to present the options to the user and capture their selections. // The Show() method displays the options and waits for user input. selectedOptions, _ := pterm.DefaultInteractiveMultiselect.WithOptions(options).Show() // Print the selected options, highlighted in green. pterm.Info.Printfln("Selected options: %s", pterm.Green(selectedOptions)) } ``` golang-github-pterm-pterm-0.12.79/_examples/interactive_multiselect/demo/animation.svg000066400000000000000000001651451465010626300312420ustar00rootroot00000000000000Pleaseselectyouroptions:>[]Option0[]Option1[]Option2[]Option3[]Option4enter:select|tab:confirm|left:none|right:all|typetofilter[]Option0>[]Option1>[]Option1[]Option1>[]Option3>[]Option3[]Option3>[]Option4>[]Option5>[]Option5[]Option5>[]Option6[]Option6>[]Option7>[]Option7[]Option7>[]Option8[]Option8>[]Option9>[]Option9[]Option9>[]Option10Pleaseselectyouroptions:f>[]Youcanusefuzzysearching(0)[]Youcanusefuzzysearching(1)[]Youcanusefuzzysearching(2)[]Youcanusefuzzysearching(3)[]Youcanusefuzzysearching(4)Pleaseselectyouroptions:fuPleaseselectyouroptions:fuzPleaseselectyouroptions:fuzzPleaseselectyouroptions:fuzzy[]Youcanusefuzzysearching(0)>[]Youcanusefuzzysearching(1)>[]Youcanusefuzzysearching(2)>[]Youcanusefuzzysearching(2)>Option1>Option3>Option5>Option7>Option9>Youcanusefuzzysearching(2) INFO Selectedoptions:[Option1Option3Option5Option7Option9Youcanusefuzzysearching(2)]>[]Option2Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/interactive_multiselect/demo/ci.go000066400000000000000000000017161465010626300274550ustar00rootroot00000000000000package main import ( "os" "time" "atomicgo.dev/keyboard" "atomicgo.dev/keyboard/keys" ) // ------ Automation for CI ------ // You can ignore this function, it is used to automatically run the demo and generate the example animation in our CI system. func init() { if os.Getenv("CI") == "true" { go func() { time.Sleep(time.Second) for i := 0; i < 10; i++ { keyboard.SimulateKeyPress(keys.Down) if i%2 == 0 { time.Sleep(time.Millisecond * 100) keyboard.SimulateKeyPress(keys.Enter) } time.Sleep(time.Millisecond * 500) } time.Sleep(time.Second) for _, s := range "fuzzy" { keyboard.SimulateKeyPress(s) time.Sleep(time.Millisecond * 150) } time.Sleep(time.Second) for i := 0; i < 2; i++ { keyboard.SimulateKeyPress(keys.Down) time.Sleep(time.Millisecond * 300) } keyboard.SimulateKeyPress(keys.Enter) time.Sleep(time.Millisecond * 350) keyboard.SimulateKeyPress(keys.Tab) }() } } golang-github-pterm-pterm-0.12.79/_examples/interactive_multiselect/demo/main.go000066400000000000000000000015511465010626300300030ustar00rootroot00000000000000package main import ( "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options. var options []string // Populate the options slice with 100 options. for i := 0; i < 100; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Add 5 more options to the slice, indicating the availability of fuzzy searching. for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("You can use fuzzy searching (%d)", i)) } // Use PTerm's interactive multiselect to present the options to the user and capture their selections. // The Show() method displays the options and waits for user input. selectedOptions, _ := pterm.DefaultInteractiveMultiselect.WithOptions(options).Show() // Print the selected options, highlighted in green. pterm.Info.Printfln("Selected options: %s", pterm.Green(selectedOptions)) } golang-github-pterm-pterm-0.12.79/_examples/interactive_select/000077500000000000000000000000001465010626300245275ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/interactive_select/README.md000066400000000000000000000021411465010626300260040ustar00rootroot00000000000000### interactive_select/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_select/demo/animation.svg)
SHOW SOURCE ```go package main import ( "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options var options []string // Generate 100 options and add them to the options slice for i := 0; i < 100; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Generate 5 additional options with a specific message and add them to the options slice for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("You can use fuzzy searching (%d)", i)) } // Use PTerm's interactive select feature to present the options to the user and capture their selection // The Show() method displays the options and waits for the user's input selectedOption, _ := pterm.DefaultInteractiveSelect.WithOptions(options).Show() // Display the selected option to the user with a green color for emphasis pterm.Info.Printfln("Selected option: %s", pterm.Green(selectedOption)) } ```
golang-github-pterm-pterm-0.12.79/_examples/interactive_select/demo/000077500000000000000000000000001465010626300254535ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/interactive_select/demo/README.md000066400000000000000000000017201465010626300267320ustar00rootroot00000000000000# interactive_select/demo ![Animation](animation.svg) ```go package main import ( "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options var options []string // Generate 100 options and add them to the options slice for i := 0; i < 100; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Generate 5 additional options with a specific message and add them to the options slice for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("You can use fuzzy searching (%d)", i)) } // Use PTerm's interactive select feature to present the options to the user and capture their selection // The Show() method displays the options and waits for the user's input selectedOption, _ := pterm.DefaultInteractiveSelect.WithOptions(options).Show() // Display the selected option to the user with a green color for emphasis pterm.Info.Printfln("Selected option: %s", pterm.Green(selectedOption)) } ``` golang-github-pterm-pterm-0.12.79/_examples/interactive_select/demo/animation.svg000066400000000000000000000716671465010626300301740ustar00rootroot00000000000000Pleaseselectanoption[typetosearch]:>Option0Option1Option2Option3Option4Option0>Option1>Option3>Option4>Option5Option5Option6>Option7Option7Option8>Option9>Youcanusefuzzysearching(0)Youcanusefuzzysearching(1)Youcanusefuzzysearching(2)Youcanusefuzzysearching(3)Youcanusefuzzysearching(4)Pleaseselectanoption[typetosearch]:fuzPleaseselectanoption[typetosearch]:fuzzPleaseselectanoption[typetosearch]:fuzzyYoucanusefuzzysearching(0)>Youcanusefuzzysearching(1)>Youcanusefuzzysearching(2)Pleaseselectanoption:fuzzy>Youcanusefuzzysearching(2) INFO Selectedoption:Youcanusefuzzysearching(2)>Option2>Option6>Option8Option9>Option10Pleaseselectanoption[typetosearch]:fPleaseselectanoption[typetosearch]:fuRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/interactive_select/demo/ci.go000066400000000000000000000014261465010626300264000ustar00rootroot00000000000000package main import ( "os" "time" "atomicgo.dev/keyboard" "atomicgo.dev/keyboard/keys" ) // ------ Automation for CI ------ // You can ignore this function, it is used to automatically run the demo and generate the example animation in our CI system. func init() { if os.Getenv("CI") == "true" { go func() { time.Sleep(time.Second) for i := 0; i < 10; i++ { keyboard.SimulateKeyPress(keys.Down) time.Sleep(time.Millisecond * 250) } time.Sleep(time.Second) for _, s := range "fuzzy" { keyboard.SimulateKeyPress(s) time.Sleep(time.Millisecond * 150) } time.Sleep(time.Second) for i := 0; i < 2; i++ { keyboard.SimulateKeyPress(keys.Down) time.Sleep(time.Millisecond * 300) } keyboard.SimulateKeyPress(keys.Enter) }() } } golang-github-pterm-pterm-0.12.79/_examples/interactive_select/demo/main.go000066400000000000000000000016151465010626300267310ustar00rootroot00000000000000package main import ( "fmt" "github.com/pterm/pterm" ) func main() { // Initialize an empty slice to hold the options var options []string // Generate 100 options and add them to the options slice for i := 0; i < 100; i++ { options = append(options, fmt.Sprintf("Option %d", i)) } // Generate 5 additional options with a specific message and add them to the options slice for i := 0; i < 5; i++ { options = append(options, fmt.Sprintf("You can use fuzzy searching (%d)", i)) } // Use PTerm's interactive select feature to present the options to the user and capture their selection // The Show() method displays the options and waits for the user's input selectedOption, _ := pterm.DefaultInteractiveSelect.WithOptions(options).Show() // Display the selected option to the user with a green color for emphasis pterm.Info.Printfln("Selected option: %s", pterm.Green(selectedOption)) } golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/000077500000000000000000000000001465010626300253145ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/README.md000066400000000000000000000055171465010626300266030ustar00rootroot00000000000000### interactive_textinput/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_textinput/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Create an interactive text input with single line input mode and show it result, _ := pterm.DefaultInteractiveTextInput.Show() // Print a blank line for better readability pterm.Println() // Print the user's answer with an info prefix pterm.Info.Printfln("You answered: %s", result) } ```
### interactive_textinput/default-value ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_textinput/default-value/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Create an interactive text input with single line input mode and show it result, _ := pterm.DefaultInteractiveTextInput.WithDefaultValue("Some default value").Show() // Print a blank line for better readability pterm.Println() // Print the user's answer with an info prefix pterm.Info.Printfln("You answered: %s", result) } ```
### interactive_textinput/multi-line ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_textinput/multi-line/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Create a default interactive text input with multi-line enabled. // This allows the user to input multiple lines of text. textInput := pterm.DefaultInteractiveTextInput.WithMultiLine() // Show the text input to the user and store the result. // The second return value (an error) is ignored with '_'. result, _ := textInput.Show() // Print a blank line for better readability in the output. pterm.Println() // Print the user's input prefixed with an informational message. // The '%s' placeholder is replaced with the user's input. pterm.Info.Printfln("You answered: %s", result) } ```
### interactive_textinput/password ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/interactive_textinput/password/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create an interactive text input with a mask for password input passwordInput := pterm.DefaultInteractiveTextInput.WithMask("*") // Show the password input prompt and store the result result, _ := passwordInput.Show("Enter your password") // Get the default logger from PTerm logger := pterm.DefaultLogger // Log the received password (masked) // Note: In a real-world application, you should never log passwords logger.Info("Password received", logger.Args("password", result)) } ```
golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/default-value/000077500000000000000000000000001465010626300300525ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/default-value/README.md000066400000000000000000000007401465010626300313320ustar00rootroot00000000000000# interactive_textinput/default-value ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" ) func main() { // Create an interactive text input with single line input mode and show it result, _ := pterm.DefaultInteractiveTextInput.WithDefaultValue("Some default value").Show() // Print a blank line for better readability pterm.Println() // Print the user's answer with an info prefix pterm.Info.Printfln("You answered: %s", result) } ``` golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/default-value/animation.svg000066400000000000000000000354501465010626300325610ustar00rootroot00000000000000Inputtext:SomedefaultvalueInputtext:HInputtext:HelInputtext:HelloInputtext:Hello;Inputtext:Hello;WInputtext:Hello;WorlInputtext:Hello;WorldInputtext:Hello;World!Inputtext:Hello,World! INFO Youanswered:Hello,World!Inputtext:Inputtext:HeInputtext:HellInputtext:Hello;WoInputtext:Hello;WorInputtext:HelloWorld!Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/default-value/ci.go000066400000000000000000000014651465010626300310020ustar00rootroot00000000000000package main import ( "os" "time" "atomicgo.dev/keyboard" "atomicgo.dev/keyboard/keys" ) // ------ Automation for CI ------ // You can ignore this function, it is used to automatically run the demo and generate the example animation in our CI system. func init() { if os.Getenv("CI") == "true" { go func() { time.Sleep(time.Millisecond * 1500) input := "Hello; World!" for _, r := range []rune(input) { keyboard.SimulateKeyPress(r) time.Sleep(time.Millisecond * 250) } for i := 0; i < 7; i++ { keyboard.SimulateKeyPress(keys.Left) time.Sleep(time.Millisecond * 150) } keyboard.SimulateKeyPress(keys.Backspace) time.Sleep(time.Millisecond * 500) keyboard.SimulateKeyPress(',') time.Sleep(time.Millisecond * 500) keyboard.SimulateKeyPress(keys.Enter) }() } } golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/default-value/main.go000066400000000000000000000006211465010626300313240ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" ) func main() { // Create an interactive text input with single line input mode and show it result, _ := pterm.DefaultInteractiveTextInput.WithDefaultValue("Some default value").Show() // Print a blank line for better readability pterm.Println() // Print the user's answer with an info prefix pterm.Info.Printfln("You answered: %s", result) } golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/demo/000077500000000000000000000000001465010626300262405ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/demo/README.md000066400000000000000000000006601465010626300275210ustar00rootroot00000000000000# interactive_textinput/demo ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" ) func main() { // Create an interactive text input with single line input mode and show it result, _ := pterm.DefaultInteractiveTextInput.Show() // Print a blank line for better readability pterm.Println() // Print the user's answer with an info prefix pterm.Info.Printfln("You answered: %s", result) } ``` golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/demo/animation.svg000066400000000000000000000400431465010626300307410ustar00rootroot00000000000000Inputtext:Inputtext:HInputtext:HeInputtext:HelInputtext:HelloInputtext:Hello;Inputtext:Hello;WInputtext:Hello;WoInputtext:Hello;WorInputtext:Hello;WorlInputtext:Hello;WorldInputtext:Hello;World!Inputtext:HelloWorld!Inputtext:Hello,World! INFO Youanswered:Hello,World!Inputtext:HellRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/demo/ci.go000066400000000000000000000014511465010626300271630ustar00rootroot00000000000000package main import ( "os" "time" "atomicgo.dev/keyboard" "atomicgo.dev/keyboard/keys" ) // ------ Automation for CI ------ // You can ignore this function, it is used to automatically run the demo and generate the example animation in our CI system. func init() { if os.Getenv("CI") == "true" { go func() { time.Sleep(time.Second) input := "Hello; World!" for _, r := range []rune(input) { keyboard.SimulateKeyPress(r) time.Sleep(time.Millisecond * 250) } for i := 0; i < 7; i++ { keyboard.SimulateKeyPress(keys.Left) time.Sleep(time.Millisecond * 150) } keyboard.SimulateKeyPress(keys.Backspace) time.Sleep(time.Millisecond * 500) keyboard.SimulateKeyPress(',') time.Sleep(time.Millisecond * 500) keyboard.SimulateKeyPress(keys.Enter) }() } } golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/demo/main.go000066400000000000000000000005521465010626300275150ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" ) func main() { // Create an interactive text input with single line input mode and show it result, _ := pterm.DefaultInteractiveTextInput.Show() // Print a blank line for better readability pterm.Println() // Print the user's answer with an info prefix pterm.Info.Printfln("You answered: %s", result) } golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/multi-line/000077500000000000000000000000001465010626300273735ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/multi-line/README.md000066400000000000000000000013451465010626300306550ustar00rootroot00000000000000# interactive_textinput/multi-line ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" ) func main() { // Create a default interactive text input with multi-line enabled. // This allows the user to input multiple lines of text. textInput := pterm.DefaultInteractiveTextInput.WithMultiLine() // Show the text input to the user and store the result. // The second return value (an error) is ignored with '_'. result, _ := textInput.Show() // Print a blank line for better readability in the output. pterm.Println() // Print the user's input prefixed with an informational message. // The '%s' placeholder is replaced with the user's input. pterm.Info.Printfln("You answered: %s", result) } ``` golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/multi-line/animation.svg000066400000000000000000001147241465010626300321040ustar00rootroot00000000000000Inputtext[Presstabtosubmit]:111111111111111111112222222222222222222222221111111222222233333333333333333333333333333345555555555555555555555555555 INFO Youanswered:11111112222222 33333333 4 5555555111111112222333333Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/multi-line/ci.go000066400000000000000000000021321465010626300303130ustar00rootroot00000000000000package main import ( "os" "time" "atomicgo.dev/keyboard" "atomicgo.dev/keyboard/keys" ) // ------ Automation for CI ------ // You can ignore this function, it is used to automatically run the demo and generate the example animation in our CI system. func init() { if os.Getenv("CI") == "true" { go func() { time.Sleep(time.Second) input := "1111111\n2222222" for _, r := range input { if r == '\n' { keyboard.SimulateKeyPress(keys.Enter) } else { keyboard.SimulateKeyPress(r) } time.Sleep(time.Millisecond * 250) } for i := 0; i < 7; i++ { keyboard.SimulateKeyPress(keys.Left) time.Sleep(time.Millisecond * 150) } keyboard.SimulateKeyPress(keys.Backspace) time.Sleep(time.Millisecond * 500) keyboard.SimulateKeyPress(keys.Enter) time.Sleep(time.Millisecond * 500) input = "33333333\n4\n5555555" for _, r := range input { if r == '\n' { keyboard.SimulateKeyPress(keys.Enter) } else { keyboard.SimulateKeyPress(r) } time.Sleep(time.Millisecond * 250) } keyboard.SimulateKeyPress(keys.Tab) }() } } golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/multi-line/main.go000066400000000000000000000012311465010626300306430ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" ) func main() { // Create a default interactive text input with multi-line enabled. // This allows the user to input multiple lines of text. textInput := pterm.DefaultInteractiveTextInput.WithMultiLine() // Show the text input to the user and store the result. // The second return value (an error) is ignored with '_'. result, _ := textInput.Show() // Print a blank line for better readability in the output. pterm.Println() // Print the user's input prefixed with an informational message. // The '%s' placeholder is replaced with the user's input. pterm.Info.Printfln("You answered: %s", result) } golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/password/000077500000000000000000000000001465010626300271565ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/password/README.md000066400000000000000000000011671465010626300304420ustar00rootroot00000000000000# interactive_textinput/password ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Create an interactive text input with a mask for password input passwordInput := pterm.DefaultInteractiveTextInput.WithMask("*") // Show the password input prompt and store the result result, _ := passwordInput.Show("Enter your password") // Get the default logger from PTerm logger := pterm.DefaultLogger // Log the received password (masked) // Note: In a real-world application, you should never log passwords logger.Info("Password received", logger.Args("password", result)) } ``` golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/password/animation.svg000066400000000000000000000323411465010626300316610ustar00rootroot00000000000000Enteryourpassword:Enteryourpassword:*Enteryourpassword:***Enteryourpassword:****Enteryourpassword:*****Enteryourpassword:******Enteryourpassword:*******Enteryourpassword:********Enteryourpassword:*********Enteryourpassword:**********Enteryourpassword:***********Enteryourpassword:************Enteryourpassword:*************2024-02-0918:53:11INFOPasswordreceivedpassword:Hello,World!Enteryourpassword:**Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/password/ci.go000066400000000000000000000011461465010626300301020ustar00rootroot00000000000000package main import ( "os" "time" "atomicgo.dev/keyboard" "atomicgo.dev/keyboard/keys" ) // ------ Automation for CI ------ // You can ignore this function, it is used to automatically run the demo and generate the example animation in our CI system. func init() { if os.Getenv("CI") == "true" { go func() { time.Sleep(time.Second) input := "Hello, World!" for _, r := range input { if r == '\n' { keyboard.SimulateKeyPress(keys.Enter) } else { keyboard.SimulateKeyPress(r) } time.Sleep(time.Millisecond * 250) } keyboard.SimulateKeyPress(keys.Enter) }() } } golang-github-pterm-pterm-0.12.79/_examples/interactive_textinput/password/main.go000066400000000000000000000010551465010626300304320ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Create an interactive text input with a mask for password input passwordInput := pterm.DefaultInteractiveTextInput.WithMask("*") // Show the password input prompt and store the result result, _ := passwordInput.Show("Enter your password") // Get the default logger from PTerm logger := pterm.DefaultLogger // Log the received password (masked) // Note: In a real-world application, you should never log passwords logger.Info("Password received", logger.Args("password", result)) } golang-github-pterm-pterm-0.12.79/_examples/logger/000077500000000000000000000000001465010626300221325ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/logger/README.md000066400000000000000000000175171465010626300234240ustar00rootroot00000000000000### logger/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/logger/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "time" ) func main() { // Create a logger with trace level logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace) // Log a trace level message logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Pause for 3 seconds sleep() // Define a map with interesting stuff interstingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a debug level message with arguments from the map logger.Debug("This might be interesting", logger.ArgsFromMap(interstingStuff)) // Pause for 3 seconds sleep() // Log an info level message logger.Info("That was actually interesting", logger.Args("such", "wow")) // Pause for 3 seconds sleep() // Log a warning level message logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) // Pause for 3 seconds sleep() // Log an error level message logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) // Pause for 3 seconds sleep() // Log an info level message with a long text that will be automatically wrapped logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) // Pause for 3 seconds sleep() // Log a fatal level message logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } // Function to pause the execution for 3 seconds func sleep() { time.Sleep(time.Second * 3) } ```
### logger/custom-key-styles ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/logger/custom-key-styles/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a logger with a level of Trace or higher. logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace) // Define a new style for the "priority" key. priorityStyle := map[string]pterm.Style{ "priority": *pterm.NewStyle(pterm.FgRed), } // Overwrite all key styles with the new map. logger = logger.WithKeyStyles(priorityStyle) // Log an info message. The "priority" key will be displayed in red. logger.Info("The priority key should now be red", logger.Args("priority", "low", "foo", "bar")) // Define a new style for the "foo" key. fooStyle := *pterm.NewStyle(pterm.FgBlue) // Append the new style to the existing ones. logger.AppendKeyStyle("foo", fooStyle) // Log another info message. The "foo" key will be displayed in blue. logger.Info("The foo key should now be blue", logger.Args("priority", "low", "foo", "bar")) } ```
### logger/default ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/logger/default/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "time" ) func main() { // Create a logger with a level of Trace or higher. logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace) // Log a trace message with additional arguments. logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Create a map of interesting stuff. interstingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a debug message with arguments from a map. logger.Debug("This might be interesting", logger.ArgsFromMap(interstingStuff)) // Log an info message with additional arguments. logger.Info("That was actually interesting", logger.Args("such", "wow")) // Log a warning message with additional arguments. logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) // Log an error message with additional arguments. logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) // Log an info message with additional arguments. PTerm will automatically wrap long logs. logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) // Pause for 2 seconds. time.Sleep(time.Second * 2) // Log a fatal message with additional arguments. This will terminate the process. logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } ```
### logger/json ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/logger/json/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a logger with Trace level and JSON formatter logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace).WithFormatter(pterm.LogFormatterJSON) // Log a Trace level message with additional arguments logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Create a map of interesting stuff interestingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a Debug level message with arguments from the map logger.Debug("This might be interesting", logger.ArgsFromMap(interestingStuff)) // Log Info, Warn, Error, and Fatal level messages with additional arguments logger.Info("That was actually interesting", logger.Args("such", "wow")) logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } ```
### logger/with-caller ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/logger/with-caller/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a logger with Trace level and caller information logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace).WithCaller() // Log a trace message with additional arguments logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Create a map of interesting stuff interestingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a debug message with arguments from a map logger.Debug("This might be interesting", logger.ArgsFromMap(interestingStuff)) // Log an info message with additional arguments logger.Info("That was actually interesting", logger.Args("such", "wow")) // Log a warning message with additional arguments logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) // Log an error message with additional arguments logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) // Log an info message with additional arguments. PTerm will automatically wrap long logs. logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) // Log a fatal message with additional arguments. This will terminate the process. logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } ```
golang-github-pterm-pterm-0.12.79/_examples/logger/custom-key-styles/000077500000000000000000000000001465010626300255535ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/logger/custom-key-styles/README.md000066400000000000000000000017301465010626300270330ustar00rootroot00000000000000# logger/custom-key-styles ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Create a logger with a level of Trace or higher. logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace) // Define a new style for the "priority" key. priorityStyle := map[string]pterm.Style{ "priority": *pterm.NewStyle(pterm.FgRed), } // Overwrite all key styles with the new map. logger = logger.WithKeyStyles(priorityStyle) // Log an info message. The "priority" key will be displayed in red. logger.Info("The priority key should now be red", logger.Args("priority", "low", "foo", "bar")) // Define a new style for the "foo" key. fooStyle := *pterm.NewStyle(pterm.FgBlue) // Append the new style to the existing ones. logger.AppendKeyStyle("foo", fooStyle) // Log another info message. The "foo" key will be displayed in blue. logger.Info("The foo key should now be blue", logger.Args("priority", "low", "foo", "bar")) } ``` golang-github-pterm-pterm-0.12.79/_examples/logger/custom-key-styles/animation.svg000066400000000000000000000077121465010626300302620ustar00rootroot000000000000002024-02-0918:53:08INFOTheprioritykeyshouldnowberedpriority:lowfoo:bar2024-02-0918:53:08INFOThefookeyshouldnowbebluepriority:lowfoo:barRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/logger/custom-key-styles/main.go000066400000000000000000000016241465010626300270310ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Create a logger with a level of Trace or higher. logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace) // Define a new style for the "priority" key. priorityStyle := map[string]pterm.Style{ "priority": *pterm.NewStyle(pterm.FgRed), } // Overwrite all key styles with the new map. logger = logger.WithKeyStyles(priorityStyle) // Log an info message. The "priority" key will be displayed in red. logger.Info("The priority key should now be red", logger.Args("priority", "low", "foo", "bar")) // Define a new style for the "foo" key. fooStyle := *pterm.NewStyle(pterm.FgBlue) // Append the new style to the existing ones. logger.AppendKeyStyle("foo", fooStyle) // Log another info message. The "foo" key will be displayed in blue. logger.Info("The foo key should now be blue", logger.Args("priority", "low", "foo", "bar")) } golang-github-pterm-pterm-0.12.79/_examples/logger/default/000077500000000000000000000000001465010626300235565ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/logger/default/README.md000066400000000000000000000031551465010626300250410ustar00rootroot00000000000000# logger/default ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" "time" ) func main() { // Create a logger with a level of Trace or higher. logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace) // Log a trace message with additional arguments. logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Create a map of interesting stuff. interstingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a debug message with arguments from a map. logger.Debug("This might be interesting", logger.ArgsFromMap(interstingStuff)) // Log an info message with additional arguments. logger.Info("That was actually interesting", logger.Args("such", "wow")) // Log a warning message with additional arguments. logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) // Log an error message with additional arguments. logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) // Log an info message with additional arguments. PTerm will automatically wrap long logs. logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) // Pause for 2 seconds. time.Sleep(time.Second * 2) // Log a fatal message with additional arguments. This will terminate the process. logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } ``` golang-github-pterm-pterm-0.12.79/_examples/logger/default/animation.svg000066400000000000000000000265771465010626300262770ustar00rootroot000000000000002024-02-0918:53:10TRACEDoingnotsoimportantstuffpriority:superlow2024-02-0918:53:10DEBUGThismightbeinterestingwhenwerecrayonsinvented:1903whatisthemeaningoflife:42isthisinteresting:true2024-02-0918:53:10INFOThatwasactuallyinterestingsuch:wow2024-02-0918:53:10WARNOhno,Iseeanerrorcomingtous!speed:88measures:mph2024-02-0918:53:10ERRORDamn,hereitis!error:somethingwentwrong2024-02-0918:53:10INFOButwhat'sreallycoolis,thatyoucanprintverylonglogs,andPTermwillautomaticallywrapthemforyou!Saygoodbyetotext,thathasweirdlinebreaks!very:long2024-02-0918:53:12FATALOhno,thisprocessisgettingkilled!fatal:trueRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/logger/default/main.go000066400000000000000000000030631465010626300250330ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" "time" ) func main() { // Create a logger with a level of Trace or higher. logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace) // Log a trace message with additional arguments. logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Create a map of interesting stuff. interstingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a debug message with arguments from a map. logger.Debug("This might be interesting", logger.ArgsFromMap(interstingStuff)) // Log an info message with additional arguments. logger.Info("That was actually interesting", logger.Args("such", "wow")) // Log a warning message with additional arguments. logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) // Log an error message with additional arguments. logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) // Log an info message with additional arguments. PTerm will automatically wrap long logs. logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) // Pause for 2 seconds. time.Sleep(time.Second * 2) // Log a fatal message with additional arguments. This will terminate the process. logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } golang-github-pterm-pterm-0.12.79/_examples/logger/demo/000077500000000000000000000000001465010626300230565ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/logger/demo/README.md000066400000000000000000000033031465010626300243340ustar00rootroot00000000000000# logger/demo ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" "time" ) func main() { // Create a logger with trace level logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace) // Log a trace level message logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Pause for 3 seconds sleep() // Define a map with interesting stuff interstingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a debug level message with arguments from the map logger.Debug("This might be interesting", logger.ArgsFromMap(interstingStuff)) // Pause for 3 seconds sleep() // Log an info level message logger.Info("That was actually interesting", logger.Args("such", "wow")) // Pause for 3 seconds sleep() // Log a warning level message logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) // Pause for 3 seconds sleep() // Log an error level message logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) // Pause for 3 seconds sleep() // Log an info level message with a long text that will be automatically wrapped logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) // Pause for 3 seconds sleep() // Log a fatal level message logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } // Function to pause the execution for 3 seconds func sleep() { time.Sleep(time.Second * 3) } ``` golang-github-pterm-pterm-0.12.79/_examples/logger/demo/animation.svg000066400000000000000000000303561465010626300255650ustar00rootroot000000000000002024-02-0918:53:07TRACEDoingnotsoimportantstuffpriority:superlow2024-02-0918:53:10DEBUGThismightbeinterestingwhenwerecrayonsinvented:1903whatisthemeaningoflife:42isthisinteresting:true2024-02-0918:53:13INFOThatwasactuallyinterestingsuch:wow2024-02-0918:53:16WARNOhno,Iseeanerrorcomingtous!speed:88measures:mph2024-02-0918:53:19ERRORDamn,hereitis!error:somethingwentwrong2024-02-0918:53:22INFOButwhat'sreallycoolis,thatyoucanprintverylonglogs,andPTermwillautomaticallywrapthemforyou!Saygoodbyetotext,thathasweirdlinebreaks!very:long2024-02-0918:53:25FATALOhno,thisprocessisgettingkilled!fatal:trueRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/logger/demo/main.go000066400000000000000000000032141465010626300243310ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" "time" ) func main() { // Create a logger with trace level logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace) // Log a trace level message logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Pause for 3 seconds sleep() // Define a map with interesting stuff interstingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a debug level message with arguments from the map logger.Debug("This might be interesting", logger.ArgsFromMap(interstingStuff)) // Pause for 3 seconds sleep() // Log an info level message logger.Info("That was actually interesting", logger.Args("such", "wow")) // Pause for 3 seconds sleep() // Log a warning level message logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) // Pause for 3 seconds sleep() // Log an error level message logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) // Pause for 3 seconds sleep() // Log an info level message with a long text that will be automatically wrapped logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) // Pause for 3 seconds sleep() // Log a fatal level message logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } // Function to pause the execution for 3 seconds func sleep() { time.Sleep(time.Second * 3) } golang-github-pterm-pterm-0.12.79/_examples/logger/json/000077500000000000000000000000001465010626300231035ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/logger/json/README.md000066400000000000000000000025321465010626300243640ustar00rootroot00000000000000# logger/json ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Create a logger with Trace level and JSON formatter logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace).WithFormatter(pterm.LogFormatterJSON) // Log a Trace level message with additional arguments logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Create a map of interesting stuff interestingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a Debug level message with arguments from the map logger.Debug("This might be interesting", logger.ArgsFromMap(interestingStuff)) // Log Info, Warn, Error, and Fatal level messages with additional arguments logger.Info("That was actually interesting", logger.Args("such", "wow")) logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } ``` golang-github-pterm-pterm-0.12.79/_examples/logger/json/animation.svg000066400000000000000000000224611465010626300256100ustar00rootroot00000000000000{"level":"TRACE","msg":"Doingnotsoimportantstuff","priority":"superlow","timestamp":"2024-02-0918:53:08"}{"isthisinteresting":true,"level":"DEBUG","msg":"Thismightbeinteresting","timestamp":"2024-02-0918:53:08","whatisthemeaningoflife":42,"whenwerecrayonsinvented":"1903"}{"level":"INFO","msg":"Thatwasactuallyinteresting","such":"wow","timestamp":"2024-02-0918:53:08"}{"level":"WARN","measures":"mph","msg":"Ohno,Iseeanerrorcomingtous!","speed":88,"timestamp":"2024-02-0918:53:08"}{"error":"somethingwentwrong","level":"ERROR","msg":"Damn,hereitis!","timestamp":"2024-02-0918:53:08"}{"level":"INFO","msg":"Butwhat'sreallycoolis,thatyoucanprintverylonglogs,andPTermwillautomaticallywrapthemforyou!Saygoodbyetotext,thathasweirdlinebreaks!","timestamp":"2024-02-0918:53:08","very":"long"}{"fatal":true,"level":"FATAL","msg":"Ohno,thisprocessisgettingkilled!","tiRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/logger/json/main.go000066400000000000000000000024431465010626300243610ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Create a logger with Trace level and JSON formatter logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace).WithFormatter(pterm.LogFormatterJSON) // Log a Trace level message with additional arguments logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Create a map of interesting stuff interestingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a Debug level message with arguments from the map logger.Debug("This might be interesting", logger.ArgsFromMap(interestingStuff)) // Log Info, Warn, Error, and Fatal level messages with additional arguments logger.Info("That was actually interesting", logger.Args("such", "wow")) logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } golang-github-pterm-pterm-0.12.79/_examples/logger/with-caller/000077500000000000000000000000001465010626300243455ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/logger/with-caller/README.md000066400000000000000000000030751465010626300256310ustar00rootroot00000000000000# logger/with-caller ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Create a logger with Trace level and caller information logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace).WithCaller() // Log a trace message with additional arguments logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Create a map of interesting stuff interestingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a debug message with arguments from a map logger.Debug("This might be interesting", logger.ArgsFromMap(interestingStuff)) // Log an info message with additional arguments logger.Info("That was actually interesting", logger.Args("such", "wow")) // Log a warning message with additional arguments logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) // Log an error message with additional arguments logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) // Log an info message with additional arguments. PTerm will automatically wrap long logs. logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) // Log a fatal message with additional arguments. This will terminate the process. logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } ``` golang-github-pterm-pterm-0.12.79/_examples/logger/with-caller/animation.svg000066400000000000000000000432031465010626300270470ustar00rootroot000000000000002024-02-0918:53:09TRACEDoingnotsoimportantstuffpriority:superlowcaller:/_examples/logger/with-caller/main.go:102024-02-0918:53:09DEBUGThismightbeinterestingisthisinteresting:truewhenwerecrayonsinvented:1903whatisthemeaningoflife:42caller:/_examples/logger/with-caller/main.go:202024-02-0918:53:09INFOThatwasactuallyinterestingsuch:wowcaller:/_examples/logger/with-caller/main.go:232024-02-0918:53:09WARNOhno,Iseeanerrorcomingtous!speed:88measures:mphcaller:/_examples/logger/with-caller/main.go:262024-02-0918:53:09ERRORDamn,hereitis!error:somethingwentwrongcaller:/_examples/logger/with-caller/main.go:292024-02-0918:53:09INFOButwhat'sreallycoolis,thatyoucanprintverylonglogs,andPTermwillautomaticallywrapthemforyou!Saygoodbyetotext,thathasweirdlinebreaks!very:longcaller:/_examples/logger/with-caller/main.go:322024-02-0918:53:09FATALOhno,thisprocessisgettingkilled!fatal:truecaller:/_examples/logger/with-caller/main.go:35Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/logger/with-caller/main.go000066400000000000000000000027771465010626300256350ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Create a logger with Trace level and caller information logger := pterm.DefaultLogger.WithLevel(pterm.LogLevelTrace).WithCaller() // Log a trace message with additional arguments logger.Trace("Doing not so important stuff", logger.Args("priority", "super low")) // Create a map of interesting stuff interestingStuff := map[string]any{ "when were crayons invented": "1903", "what is the meaning of life": 42, "is this interesting": true, } // Log a debug message with arguments from a map logger.Debug("This might be interesting", logger.ArgsFromMap(interestingStuff)) // Log an info message with additional arguments logger.Info("That was actually interesting", logger.Args("such", "wow")) // Log a warning message with additional arguments logger.Warn("Oh no, I see an error coming to us!", logger.Args("speed", 88, "measures", "mph")) // Log an error message with additional arguments logger.Error("Damn, here it is!", logger.Args("error", "something went wrong")) // Log an info message with additional arguments. PTerm will automatically wrap long logs. logger.Info("But what's really cool is, that you can print very long logs, and PTerm will automatically wrap them for you! Say goodbye to text, that has weird line breaks!", logger.Args("very", "long")) // Log a fatal message with additional arguments. This will terminate the process. logger.Fatal("Oh no, this process is getting killed!", logger.Args("fatal", true)) } golang-github-pterm-pterm-0.12.79/_examples/multiple-live-printers/000077500000000000000000000000001465010626300253075ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/multiple-live-printers/README.md000066400000000000000000000041061465010626300265670ustar00rootroot00000000000000### multiple-live-printers/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/multiple-live-printers/demo/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create a multi printer for managing multiple printers multi := pterm.DefaultMultiPrinter // Create two spinners with their own writers spinner1, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 1") spinner2, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 2") // Create five progress bars with their own writers and a total of 100 pb1, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 1") pb2, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 2") pb3, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 3") pb4, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 4") pb5, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 5") // Start the multi printer multi.Start() // Increment progress bars and spinners based on certain conditions for i := 1; i <= 100; i++ { pb1.Increment() // Increment progress bar 1 every iteration if i%2 == 0 { pb2.Add(3) // Add 3 to progress bar 2 every even iteration } if i%5 == 0 { pb3.Increment() // Increment progress bar 3 every 5th iteration } if i%10 == 0 { pb4.Increment() // Increment progress bar 4 every 10th iteration } if i%3 == 0 { pb5.Increment() // Increment progress bar 5 every 3rd iteration } if i%50 == 0 { spinner1.Success("Spinner 1 is done!") // Mark spinner 1 as successful every 50th iteration } if i%60 == 0 { spinner2.Fail("Spinner 2 failed!") // Mark spinner 2 as failed every 60th iteration } time.Sleep(time.Millisecond * 50) // Sleep for 50 milliseconds between each iteration } // Stop the multi printer multi.Stop() } ```
golang-github-pterm-pterm-0.12.79/_examples/multiple-live-printers/demo/000077500000000000000000000000001465010626300262335ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/multiple-live-printers/demo/README.md000066400000000000000000000036611465010626300275200ustar00rootroot00000000000000# multiple-live-printers/demo ![Animation](animation.svg) ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create a multi printer for managing multiple printers multi := pterm.DefaultMultiPrinter // Create two spinners with their own writers spinner1, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 1") spinner2, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 2") // Create five progress bars with their own writers and a total of 100 pb1, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 1") pb2, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 2") pb3, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 3") pb4, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 4") pb5, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 5") // Start the multi printer multi.Start() // Increment progress bars and spinners based on certain conditions for i := 1; i <= 100; i++ { pb1.Increment() // Increment progress bar 1 every iteration if i%2 == 0 { pb2.Add(3) // Add 3 to progress bar 2 every even iteration } if i%5 == 0 { pb3.Increment() // Increment progress bar 3 every 5th iteration } if i%10 == 0 { pb4.Increment() // Increment progress bar 4 every 10th iteration } if i%3 == 0 { pb5.Increment() // Increment progress bar 5 every 3rd iteration } if i%50 == 0 { spinner1.Success("Spinner 1 is done!") // Mark spinner 1 as successful every 50th iteration } if i%60 == 0 { spinner2.Fail("Spinner 2 failed!") // Mark spinner 2 as failed every 60th iteration } time.Sleep(time.Millisecond * 50) // Sleep for 50 milliseconds between each iteration } // Stop the multi printer multi.Stop() } ``` golang-github-pterm-pterm-0.12.79/_examples/multiple-live-printers/demo/animation.svg000066400000000000000000004077771465010626300307610ustar00rootroot00000000000000Spinner1(0s)Spinner2(0s)Progressbar1[004/100]██████████████████████████████████████████████4%|0sProgressbar2[006/100]██████████████████████████████████████████████6%|0sProgressbar3[000/100]█████████████████████████████████████████████0%|0sProgressbar4[000/100]█████████████████████████████████████████████0%|0sProgressbar5[001/100]█████████████████████████████████████████████1%|0sSpinner1(0s)Progressbar1[008/100]██████████████████████████████████████████████8%|0sProgressbar2[012/100]██████████████████████████████████████████████12%|0sProgressbar3[001/100]█████████████████████████████████████████████1%|0sProgressbar5[002/100]█████████████████████████████████████████████2%|0sSpinner1(0s)Spinner2(0s)Progressbar1[012/100]██████████████████████████████████████████████12%|1sProgressbar2[018/100]██████████████████████████████████████████████18%|1sProgressbar3[002/100]█████████████████████████████████████████████2%|0sProgressbar4[001/100]█████████████████████████████████████████████1%|0sSpinner1(1s)Spinner2(1s)Progressbar1[016/100]██████████████████████████████████████████████16%|1sProgressbar2[024/100]██████████████████████████████████████████████24%|1sProgressbar3[003/100]██████████████████████████████████████████████3%|1sProgressbar5[005/100]██████████████████████████████████████████████5%|1sSpinner1(1s)Spinner2(1s)Progressbar1[020/100]██████████████████████████████████████████████20%|1sProgressbar2[030/100]██████████████████████████████████████████████30%|1sProgressbar3[004/100]██████████████████████████████████████████████4%|1sProgressbar4[002/100]█████████████████████████████████████████████2%|1sProgressbar5[006/100]██████████████████████████████████████████████6%|1sSpinner1(1s)Spinner2(1s)Progressbar1[024/100]██████████████████████████████████████████████24%|1sProgressbar2[036/100]██████████████████████████████████████████████36%|1sProgressbar5[008/100]██████████████████████████████████████████████8%|1sSpinner1(1s)Spinner2(1s)Progressbar1[028/100]██████████████████████████████████████████████28%|1sProgressbar2[042/100]██████████████████████████████████████████████42%|1sProgressbar3[005/100]██████████████████████████████████████████████5%|1sProgressbar5[009/100]██████████████████████████████████████████████9%|1sProgressbar1[032/100]██████████████████████████████████████████████32%|2sProgressbar2[048/100]██████████████████████████████████████████████48%|2sProgressbar3[006/100]██████████████████████████████████████████████6%|1sProgressbar4[003/100]██████████████████████████████████████████████3%|1sProgressbar5[010/100]██████████████████████████████████████████████10%|1sSpinner1(2s)Spinner2(2s)Progressbar1[036/100]██████████████████████████████████████████████36%|2sProgressbar2[054/100]██████████████████████████████████████████████54%|2sProgressbar3[007/100]██████████████████████████████████████████████7%|2sProgressbar5[012/100]██████████████████████████████████████████████12%|2sSpinner1(2s)Spinner2(2s)Progressbar1[040/100]██████████████████████████████████████████████40%|2sProgressbar2[060/100]██████████████████████████████████████████████60%|2sProgressbar3[008/100]██████████████████████████████████████████████8%|2sProgressbar4[004/100]██████████████████████████████████████████████4%|2sSpinner1(2s)Spinner2(2s)Progressbar1[044/100]██████████████████████████████████████████████44%|2sProgressbar2[066/100]██████████████████████████████████████████████66%|2sProgressbar5[014/100]██████████████████████████████████████████████14%|2sSpinner1(2s)Spinner2(2s)Progressbar1[048/100]██████████████████████████████████████████████48%|2sProgressbar2[072/100]██████████████████████████████████████████████72%|2sProgressbar3[009/100]██████████████████████████████████████████████9%|2sProgressbar5[016/100]██████████████████████████████████████████████16%|2s SUCCESS Spinner1isdone!Progressbar1[052/100]██████████████████████████████████████████████52%|3sProgressbar2[078/100]██████████████████████████████████████████████78%|3sProgressbar3[010/100]██████████████████████████████████████████████10%|2sProgressbar4[005/100]██████████████████████████████████████████████5%|2sProgressbar5[017/100]██████████████████████████████████████████████17%|3sSpinner2(3s)Progressbar1[053/100]██████████████████████████████████████████████53%|3s ERROR Spinner2failed!Progressbar1[061/100]██████████████████████████████████████████████61%|3sProgressbar2[090/100]██████████████████████████████████████████████90%|3sProgressbar3[012/100]██████████████████████████████████████████████12%|3sProgressbar4[006/100]██████████████████████████████████████████████6%|3sProgressbar5[020/100]██████████████████████████████████████████████20%|3sProgressbar1[064/100]██████████████████████████████████████████████64%|3sProgressbar2[096/100]██████████████████████████████████████████████96%|3sProgressbar5[021/100]██████████████████████████████████████████████21%|3sProgressbar1[068/100]██████████████████████████████████████████████68%|4sProgressbar2[102/102]██████████████████████████████████████████████100%|4sProgressbar3[013/100]██████████████████████████████████████████████13%|4sProgressbar4[006/100]██████████████████████████████████████████████6%|4sProgressbar5[022/100]██████████████████████████████████████████████22%|4sProgressbar1[072/100]██████████████████████████████████████████████72%|4sProgressbar3[014/100]██████████████████████████████████████████████14%|4sProgressbar4[007/100]██████████████████████████████████████████████7%|4sProgressbar5[024/100]██████████████████████████████████████████████24%|4sProgressbar1[076/100]██████████████████████████████████████████████76%|4sProgressbar3[015/100]██████████████████████████████████████████████15%|4sProgressbar5[025/100]██████████████████████████████████████████████25%|4sProgressbar1[080/100]██████████████████████████████████████████████80%|4sProgressbar3[016/100]██████████████████████████████████████████████16%|4sProgressbar4[008/100]██████████████████████████████████████████████8%|4sProgressbar5[026/100]██████████████████████████████████████████████26%|4sProgressbar1[084/100]██████████████████████████████████████████████84%|4sProgressbar5[028/100]██████████████████████████████████████████████28%|4sProgressbar1[088/100]██████████████████████████████████████████████88%|5sProgressbar3[017/100]██████████████████████████████████████████████17%|4sProgressbar5[029/100]██████████████████████████████████████████████29%|5sProgressbar1[092/100]██████████████████████████████████████████████92%|5sProgressbar3[018/100]██████████████████████████████████████████████18%|5sProgressbar4[009/100]██████████████████████████████████████████████9%|5sProgressbar5[030/100]██████████████████████████████████████████████30%|5sProgressbar1[096/100]██████████████████████████████████████████████96%|5sProgressbar3[019/100]██████████████████████████████████████████████19%|5sProgressbar5[032/100]██████████████████████████████████████████████32%|5sProgressbar1[100/100]██████████████████████████████████████████████100%|5sProgressbar3[020/100]██████████████████████████████████████████████20%|5sProgressbar4[010/100]██████████████████████████████████████████████10%|5sProgressbar5[033/100]██████████████████████████████████████████████33%|5sProgressbar3[000/100]████████████████████████████████████████Progressbar5[004/100]██████████████████████████████████████████████4%|1sProgressbar5[013/100]██████████████████████████████████████████████13%|2sProgressbar4[005/100]█████████████████████████████Spinner2(3s)Progressbar1[057/100]██████████████████████████████████████████████57%|3sProgressbar2[084/100]██████████████████████████████████████████████84%|3sProgressbar3[011/100]██████████████████████████████████████████████11%|3sProgressbar4[005/100]██████████████████████████████████████████████5%|3sProgressbar5[019/100]██████████████████████████████████████████████19%|3sProgressbar5[030/100Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/multiple-live-printers/demo/main.go000066400000000000000000000035521465010626300275130ustar00rootroot00000000000000package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create a multi printer for managing multiple printers multi := pterm.DefaultMultiPrinter // Create two spinners with their own writers spinner1, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 1") spinner2, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 2") // Create five progress bars with their own writers and a total of 100 pb1, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 1") pb2, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 2") pb3, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 3") pb4, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 4") pb5, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 5") // Start the multi printer multi.Start() // Increment progress bars and spinners based on certain conditions for i := 1; i <= 100; i++ { pb1.Increment() // Increment progress bar 1 every iteration if i%2 == 0 { pb2.Add(3) // Add 3 to progress bar 2 every even iteration } if i%5 == 0 { pb3.Increment() // Increment progress bar 3 every 5th iteration } if i%10 == 0 { pb4.Increment() // Increment progress bar 4 every 10th iteration } if i%3 == 0 { pb5.Increment() // Increment progress bar 5 every 3rd iteration } if i%50 == 0 { spinner1.Success("Spinner 1 is done!") // Mark spinner 1 as successful every 50th iteration } if i%60 == 0 { spinner2.Fail("Spinner 2 failed!") // Mark spinner 2 as failed every 60th iteration } time.Sleep(time.Millisecond * 50) // Sleep for 50 milliseconds between each iteration } // Stop the multi printer multi.Stop() } golang-github-pterm-pterm-0.12.79/_examples/panel/000077500000000000000000000000001465010626300217525ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/panel/README.md000066400000000000000000000012731465010626300232340ustar00rootroot00000000000000### panel/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/panel/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define panels in a 2D grid system panels := pterm.Panels{ { {Data: "This is the first panel"}, {Data: pterm.DefaultHeader.Sprint("Hello, World!")}, {Data: "This\npanel\ncontains\nmultiple\nlines"}, }, { {Data: pterm.Red("This is another\npanel line")}, {Data: "This is the second panel\nwith a new line"}, }, } // Render the panels with a padding of 5 _ = pterm.DefaultPanel.WithPanels(panels).WithPadding(5).Render() } ```
golang-github-pterm-pterm-0.12.79/_examples/panel/demo/000077500000000000000000000000001465010626300226765ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/panel/demo/README.md000066400000000000000000000010671465010626300241610ustar00rootroot00000000000000# panel/demo ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Define panels in a 2D grid system panels := pterm.Panels{ { {Data: "This is the first panel"}, {Data: pterm.DefaultHeader.Sprint("Hello, World!")}, {Data: "This\npanel\ncontains\nmultiple\nlines"}, }, { {Data: pterm.Red("This is another\npanel line")}, {Data: "This is the second panel\nwith a new line"}, }, } // Render the panels with a padding of 5 _ = pterm.DefaultPanel.WithPanels(panels).WithPadding(5).Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/panel/demo/animation.svg000066400000000000000000000102641465010626300254010ustar00rootroot00000000000000Thisisthefirstpanel This Hello, World! panel containsmultiplelinesThisisanotherThisisthesecondpanelpanellinewithanewlineRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/panel/demo/main.go000066400000000000000000000010011465010626300241410ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Define panels in a 2D grid system panels := pterm.Panels{ { {Data: "This is the first panel"}, {Data: pterm.DefaultHeader.Sprint("Hello, World!")}, {Data: "This\npanel\ncontains\nmultiple\nlines"}, }, { {Data: pterm.Red("This is another\npanel line")}, {Data: "This is the second panel\nwith a new line"}, }, } // Render the panels with a padding of 5 _ = pterm.DefaultPanel.WithPanels(panels).WithPadding(5).Render() } golang-github-pterm-pterm-0.12.79/_examples/paragraph/000077500000000000000000000000001465010626300226205ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/paragraph/README.md000066400000000000000000000052001465010626300240740ustar00rootroot00000000000000### paragraph/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/paragraph/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Using the default paragraph printer to print a long text. // The text is split at the spaces, which is useful for continuous text of all kinds. // The line width can be manually adjusted if needed. pterm.DefaultParagraph.Println("This is the default paragraph printer. As you can see, no words are separated, " + "but the text is split at the spaces. This is useful for continuous text of all kinds. You can manually change the line width if you want to." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam") // Printing a line space for separation. pterm.Println() // Printing a long text without using the paragraph printer. // The default Println() function is used here, which does not provide intelligent splitting. pterm.Println("This text is written with the default Println() function. No intelligent splitting here." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam") } ```
### paragraph/customized ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/paragraph/customized/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define a long text to be printed as a paragraph. longText := "This is a custom paragraph printer. As you can see, no words are separated, " + "but the text is split at the spaces. This is useful for continuous text of all kinds. You can manually change the line width if you want to." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam" // Print the long text as a paragraph with a custom maximal width of 60 characters. pterm.DefaultParagraph.WithMaxWidth(60).Println(longText) // Print a line space to separate the paragraph from the following text. pterm.Println() // Define another long text to be printed without a paragraph printer. longTextWithoutParagraph := "This text is written with the default Println() function. No intelligent splitting here." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam" // Print the long text without using a paragraph printer. pterm.Println(longTextWithoutParagraph) } ```
golang-github-pterm-pterm-0.12.79/_examples/paragraph/customized/000077500000000000000000000000001465010626300250065ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/paragraph/customized/README.md000066400000000000000000000023101465010626300262610ustar00rootroot00000000000000# paragraph/customized ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Define a long text to be printed as a paragraph. longText := "This is a custom paragraph printer. As you can see, no words are separated, " + "but the text is split at the spaces. This is useful for continuous text of all kinds. You can manually change the line width if you want to." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam" // Print the long text as a paragraph with a custom maximal width of 60 characters. pterm.DefaultParagraph.WithMaxWidth(60).Println(longText) // Print a line space to separate the paragraph from the following text. pterm.Println() // Define another long text to be printed without a paragraph printer. longTextWithoutParagraph := "This text is written with the default Println() function. No intelligent splitting here." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam" // Print the long text without using a paragraph printer. pterm.Println(longTextWithoutParagraph) } ``` golang-github-pterm-pterm-0.12.79/_examples/paragraph/customized/animation.svg000066400000000000000000000173021465010626300275110ustar00rootroot00000000000000Thisisacustomparagraphprinter.Asyoucansee,nowordsareseparated,butthetextissplitatthespaces.Thisisusefulforcontinuoustextofallkinds.Youcanmanuallychangethelinewidthifyouwantto.Loremipsumdolorsitamet,consetetursadipscingelitr,seddiamnonumyeirmodtemporinviduntutlaboreetdoloremagnaaliquyamThistextiswrittenwiththedefaultPrintln()function.Nointelligentsplittinghere.Loremipsumdolorsitamet,consetetursadipscingelitr,seddiamnonumyeirmodtemporinviduntutlaboreetdoloremagnaaliquyamRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/paragraph/customized/main.go000066400000000000000000000022101465010626300262540ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Define a long text to be printed as a paragraph. longText := "This is a custom paragraph printer. As you can see, no words are separated, " + "but the text is split at the spaces. This is useful for continuous text of all kinds. You can manually change the line width if you want to." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam" // Print the long text as a paragraph with a custom maximal width of 60 characters. pterm.DefaultParagraph.WithMaxWidth(60).Println(longText) // Print a line space to separate the paragraph from the following text. pterm.Println() // Define another long text to be printed without a paragraph printer. longTextWithoutParagraph := "This text is written with the default Println() function. No intelligent splitting here." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam" // Print the long text without using a paragraph printer. pterm.Println(longTextWithoutParagraph) } golang-github-pterm-pterm-0.12.79/_examples/paragraph/demo/000077500000000000000000000000001465010626300235445ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/paragraph/demo/README.md000066400000000000000000000022421465010626300250230ustar00rootroot00000000000000# paragraph/demo ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Using the default paragraph printer to print a long text. // The text is split at the spaces, which is useful for continuous text of all kinds. // The line width can be manually adjusted if needed. pterm.DefaultParagraph.Println("This is the default paragraph printer. As you can see, no words are separated, " + "but the text is split at the spaces. This is useful for continuous text of all kinds. You can manually change the line width if you want to." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam") // Printing a line space for separation. pterm.Println() // Printing a long text without using the paragraph printer. // The default Println() function is used here, which does not provide intelligent splitting. pterm.Println("This text is written with the default Println() function. No intelligent splitting here." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam") } ``` golang-github-pterm-pterm-0.12.79/_examples/paragraph/demo/animation.svg000066400000000000000000000170521465010626300262510ustar00rootroot00000000000000Thisisthedefaultparagraphprinter.Asyoucansee,nowordsareseparated,butthetextissplitatthespaces.Thisisusefulforcontinuoustextofallkinds.Youcanmanuallychangethelinewidthifyouwantto.Loremipsumdolorsitamet,consetetursadipscingelitr,seddiamnonumyeirmodtemporinviduntutlaboreetdoloremagnaaliquyamThistextiswrittenwiththedefaultPrintln()function.Nointelligentsplittinghere.Loremipsumdolorsitamet,consetetursadipscingelitr,seddiamnonumyeirmodtemporinviduntutlaboreetdoloremagnaaliquyamRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/paragraph/demo/main.go000066400000000000000000000021501465010626300250150ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Using the default paragraph printer to print a long text. // The text is split at the spaces, which is useful for continuous text of all kinds. // The line width can be manually adjusted if needed. pterm.DefaultParagraph.Println("This is the default paragraph printer. As you can see, no words are separated, " + "but the text is split at the spaces. This is useful for continuous text of all kinds. You can manually change the line width if you want to." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam") // Printing a line space for separation. pterm.Println() // Printing a long text without using the paragraph printer. // The default Println() function is used here, which does not provide intelligent splitting. pterm.Println("This text is written with the default Println() function. No intelligent splitting here." + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam") } golang-github-pterm-pterm-0.12.79/_examples/prefix/000077500000000000000000000000001465010626300221505ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/prefix/README.md000066400000000000000000000023561465010626300234350ustar00rootroot00000000000000### prefix/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/prefix/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Enable debug messages in PTerm. pterm.EnableDebugMessages() // Print a debug message with PTerm. pterm.Debug.Println("Hello, World!") // Print an informational message with PTerm. pterm.Info.Println("Hello, World!") // Print a success message with PTerm. pterm.Success.Println("Hello, World!") // Print a warning message with PTerm. pterm.Warning.Println("Hello, World!") // Print an error message with PTerm. This will also display the filename and line number in the terminal. pterm.Error.Println("Errors show the filename and linenumber inside the terminal!") // Print an informational message with PTerm, with line number. // This demonstrates that other PrefixPrinters can also display line numbers. pterm.Info.WithShowLineNumber().Println("Other PrefixPrinters can do that too!") // Temporarily set Fatal to false, so that the CI won't crash. // This will print a fatal message with PTerm, but won't terminate the program. pterm.Fatal.WithFatal(false).Println("Hello, World!") } ```
golang-github-pterm-pterm-0.12.79/_examples/prefix/demo/000077500000000000000000000000001465010626300230745ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/prefix/demo/README.md000066400000000000000000000021511465010626300243520ustar00rootroot00000000000000# prefix/demo ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Enable debug messages in PTerm. pterm.EnableDebugMessages() // Print a debug message with PTerm. pterm.Debug.Println("Hello, World!") // Print an informational message with PTerm. pterm.Info.Println("Hello, World!") // Print a success message with PTerm. pterm.Success.Println("Hello, World!") // Print a warning message with PTerm. pterm.Warning.Println("Hello, World!") // Print an error message with PTerm. This will also display the filename and line number in the terminal. pterm.Error.Println("Errors show the filename and linenumber inside the terminal!") // Print an informational message with PTerm, with line number. // This demonstrates that other PrefixPrinters can also display line numbers. pterm.Info.WithShowLineNumber().Println("Other PrefixPrinters can do that too!") // Temporarily set Fatal to false, so that the CI won't crash. // This will print a fatal message with PTerm, but won't terminate the program. pterm.Fatal.WithFatal(false).Println("Hello, World!") } ``` golang-github-pterm-pterm-0.12.79/_examples/prefix/demo/animation.svg000066400000000000000000000121431465010626300255750ustar00rootroot00000000000000 DEBUG Hello,World! INFO Hello,World! SUCCESS Hello,World! WARNING Hello,World! ERROR Errorsshowthefilenameandlinenumberinsidetheterminal! INFO OtherPrefixPrinterscandothattoo!(/github/workspace/_examples/prefix/demo/main.go:26) FATAL Hello,World!Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/prefix/demo/main.go000066400000000000000000000020621465010626300243470ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Enable debug messages in PTerm. pterm.EnableDebugMessages() // Print a debug message with PTerm. pterm.Debug.Println("Hello, World!") // Print an informational message with PTerm. pterm.Info.Println("Hello, World!") // Print a success message with PTerm. pterm.Success.Println("Hello, World!") // Print a warning message with PTerm. pterm.Warning.Println("Hello, World!") // Print an error message with PTerm. This will also display the filename and line number in the terminal. pterm.Error.Println("Errors show the filename and linenumber inside the terminal!") // Print an informational message with PTerm, with line number. // This demonstrates that other PrefixPrinters can also display line numbers. pterm.Info.WithShowLineNumber().Println("Other PrefixPrinters can do that too!") // Temporarily set Fatal to false, so that the CI won't crash. // This will print a fatal message with PTerm, but won't terminate the program. pterm.Fatal.WithFatal(false).Println("Hello, World!") } golang-github-pterm-pterm-0.12.79/_examples/progressbar/000077500000000000000000000000001465010626300232045ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/progressbar/README.md000066400000000000000000000063241465010626300244700ustar00rootroot00000000000000### progressbar/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/progressbar/demo/animation.svg)
SHOW SOURCE ```go package main import ( "strings" "time" "github.com/pterm/pterm" ) // Slice of strings representing names of pseudo applications to be downloaded. var fakeInstallList = strings.Split("pseudo-excel pseudo-photoshop pseudo-chrome pseudo-outlook pseudo-explorer "+ "pseudo-dops pseudo-git pseudo-vsc pseudo-intellij pseudo-minecraft pseudo-scoop pseudo-chocolatey", " ") func main() { // Create a progressbar with the total steps equal to the number of items in fakeInstallList. // Set the initial title of the progressbar to "Downloading stuff". p, _ := pterm.DefaultProgressbar.WithTotal(len(fakeInstallList)).WithTitle("Downloading stuff").Start() // Loop over each item in the fakeInstallList. for i := 0; i < p.Total; i++ { // Simulate a slow download for the 7th item. if i == 6 { time.Sleep(time.Second * 3) } // Update the title of the progressbar with the current item being downloaded. p.UpdateTitle("Downloading " + fakeInstallList[i]) // Print a success message for the current download. This will be printed above the progressbar. pterm.Success.Println("Downloading " + fakeInstallList[i]) // Increment the progressbar by one to indicate progress. p.Increment() // Pause for 350 milliseconds to simulate the time taken for each download. time.Sleep(time.Millisecond * 350) } } ```
### progressbar/multiple ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/progressbar/multiple/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create a multi printer instance from the default one multi := pterm.DefaultMultiPrinter // Create five progress bars with a total of 100 units each, and assign each a new writer from the multi printer pb1, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 1") pb2, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 2") pb3, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 3") pb4, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 4") pb5, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 5") // Start the multi printer multi.Start() // Loop to increment progress bars based on certain conditions for i := 1; i <= 100; i++ { pb1.Increment() // Increment the first progress bar at each iteration if i%2 == 0 { pb2.Add(3) // Add 3 units to the second progress bar at every even iteration } if i%5 == 0 { pb3.Increment() // Increment the third progress bar at every fifth iteration } if i%10 == 0 { pb4.Increment() // Increment the fourth progress bar at every tenth iteration } if i%3 == 0 { pb5.Increment() // Increment the fifth progress bar at every third iteration } time.Sleep(time.Millisecond * 50) // Pause for 50 milliseconds at each iteration } // Stop the multi printer multi.Stop() } ```
golang-github-pterm-pterm-0.12.79/_examples/progressbar/demo/000077500000000000000000000000001465010626300241305ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/progressbar/demo/README.md000066400000000000000000000025561465010626300254170ustar00rootroot00000000000000# progressbar/demo ![Animation](animation.svg) ```go package main import ( "strings" "time" "github.com/pterm/pterm" ) // Slice of strings representing names of pseudo applications to be downloaded. var fakeInstallList = strings.Split("pseudo-excel pseudo-photoshop pseudo-chrome pseudo-outlook pseudo-explorer "+ "pseudo-dops pseudo-git pseudo-vsc pseudo-intellij pseudo-minecraft pseudo-scoop pseudo-chocolatey", " ") func main() { // Create a progressbar with the total steps equal to the number of items in fakeInstallList. // Set the initial title of the progressbar to "Downloading stuff". p, _ := pterm.DefaultProgressbar.WithTotal(len(fakeInstallList)).WithTitle("Downloading stuff").Start() // Loop over each item in the fakeInstallList. for i := 0; i < p.Total; i++ { // Simulate a slow download for the 7th item. if i == 6 { time.Sleep(time.Second * 3) } // Update the title of the progressbar with the current item being downloaded. p.UpdateTitle("Downloading " + fakeInstallList[i]) // Print a success message for the current download. This will be printed above the progressbar. pterm.Success.Println("Downloading " + fakeInstallList[i]) // Increment the progressbar by one to indicate progress. p.Increment() // Pause for 350 milliseconds to simulate the time taken for each download. time.Sleep(time.Millisecond * 350) } } ``` golang-github-pterm-pterm-0.12.79/_examples/progressbar/demo/animation.svg000066400000000000000000001425001465010626300266320ustar00rootroot00000000000000Downloadingpseudo-excel[00/12]████████████████████████████████████0%|0s SUCCESS Downloadingpseudo-excelDownloadingpseudo-photoshop[01/12]█████████████████████████████████8%|0s SUCCESS Downloadingpseudo-photoshopDownloadingpseudo-chrome[02/12]████████████████████████████████████17%|1s SUCCESS Downloadingpseudo-chromeDownloadingpseudo-chrome[03/12]████████████████████████████████████25%|1sDownloadingpseudo-outlook[03/12]███████████████████████████████████25%|1s SUCCESS Downloadingpseudo-outlookDownloadingpseudo-explorer[04/12]██████████████████████████████████33%|1s SUCCESS Downloadingpseudo-explorerDownloadingpseudo-dops[05/12]██████████████████████████████████████42%|2s SUCCESS Downloadingpseudo-dopsDownloadingpseudo-dops[06/12]██████████████████████████████████████50%|2sDownloadingpseudo-git[06/12]███████████████████████████████████████50%|5s SUCCESS Downloadingpseudo-gitDownloadingpseudo-vsc[07/12]███████████████████████████████████████58%|5s SUCCESS Downloadingpseudo-vscDownloadingpseudo-intellij[08/12]██████████████████████████████████67%|6s SUCCESS Downloadingpseudo-intellijDownloadingpseudo-intellij[09/12]██████████████████████████████████75%|6sDownloadingpseudo-minecraft[09/12]█████████████████████████████████75%|6s SUCCESS Downloadingpseudo-minecraftDownloadingpseudo-scoop[10/12]█████████████████████████████████████83%|7s SUCCESS Downloadingpseudo-scoopDownloadingpseudo-chocolatey[11/12]████████████████████████████████92%|7s SUCCESS Downloadingpseudo-chocolateyDownloadingpseudo-chocolatey[12/12]████████████████████████████████100%|7sDownloadingpseudo-excel[01/12]█████████████████████████████████████8%|0sDownloadingpseudo-photoshop[02/12]█████████████████████████████████17%|0sDownloadingpseudo-outlook[04/12]███████████████████████████████████33%|1sDownloadingpseudo-explorer[05/12]██████████████████████████████████42%|1sDownloadingpseudo-dops[06/12]██████████████████████████████████████50%|3sDownloadingpseudo-dops[06/12]██████████████████████████████████████50%|4sDownloadingpseudo-dops[06/12]██████████████████████████████████████50%|5sDownloadingpseudo-git[07/12]███████████████████████████████████████58%|5sDownloadingpseudo-vsc[08/12]███████████████████████████████████████67%|5sDownloadingpseudo-minecraft[10/12]█████████████████████████████████83%|6sDownloadingpseudo-scoop[11/12]█████████████████████████████████████92%|7sRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/progressbar/demo/main.go000066400000000000000000000024621465010626300254070ustar00rootroot00000000000000package main import ( "strings" "time" "github.com/pterm/pterm" ) // Slice of strings representing names of pseudo applications to be downloaded. var fakeInstallList = strings.Split("pseudo-excel pseudo-photoshop pseudo-chrome pseudo-outlook pseudo-explorer "+ "pseudo-dops pseudo-git pseudo-vsc pseudo-intellij pseudo-minecraft pseudo-scoop pseudo-chocolatey", " ") func main() { // Create a progressbar with the total steps equal to the number of items in fakeInstallList. // Set the initial title of the progressbar to "Downloading stuff". p, _ := pterm.DefaultProgressbar.WithTotal(len(fakeInstallList)).WithTitle("Downloading stuff").Start() // Loop over each item in the fakeInstallList. for i := 0; i < p.Total; i++ { // Simulate a slow download for the 7th item. if i == 6 { time.Sleep(time.Second * 3) } // Update the title of the progressbar with the current item being downloaded. p.UpdateTitle("Downloading " + fakeInstallList[i]) // Print a success message for the current download. This will be printed above the progressbar. pterm.Success.Println("Downloading " + fakeInstallList[i]) // Increment the progressbar by one to indicate progress. p.Increment() // Pause for 350 milliseconds to simulate the time taken for each download. time.Sleep(time.Millisecond * 350) } } golang-github-pterm-pterm-0.12.79/_examples/progressbar/multiple/000077500000000000000000000000001465010626300250375ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/progressbar/multiple/README.md000066400000000000000000000031161465010626300263170ustar00rootroot00000000000000# progressbar/multiple ![Animation](animation.svg) ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create a multi printer instance from the default one multi := pterm.DefaultMultiPrinter // Create five progress bars with a total of 100 units each, and assign each a new writer from the multi printer pb1, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 1") pb2, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 2") pb3, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 3") pb4, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 4") pb5, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 5") // Start the multi printer multi.Start() // Loop to increment progress bars based on certain conditions for i := 1; i <= 100; i++ { pb1.Increment() // Increment the first progress bar at each iteration if i%2 == 0 { pb2.Add(3) // Add 3 units to the second progress bar at every even iteration } if i%5 == 0 { pb3.Increment() // Increment the third progress bar at every fifth iteration } if i%10 == 0 { pb4.Increment() // Increment the fourth progress bar at every tenth iteration } if i%3 == 0 { pb5.Increment() // Increment the fifth progress bar at every third iteration } time.Sleep(time.Millisecond * 50) // Pause for 50 milliseconds at each iteration } // Stop the multi printer multi.Stop() } ``` golang-github-pterm-pterm-0.12.79/_examples/progressbar/multiple/animation.svg000066400000000000000000003365751465010626300275620ustar00rootroot00000000000000Progressbar1[004/100]██████████████████████████████████████████████4%|0sProgressbar2[006/100]██████████████████████████████████████████████6%|0sProgressbar3[000/100]█████████████████████████████████████████████0%|0sProgressbar4[000/100]█████████████████████████████████████████████0%|0sProgressbar5[001/100]█████████████████████████████████████████████1%|0sProgressbar1[008/100]██████████████████████████████████████████████8%|0sProgressbar2[012/100]██████████████████████████████████████████████12%|0sProgressbar3[001/100]█████████████████████████████████████████████1%|0sProgressbar5[002/100]█████████████████████████████████████████████2%|0sProgressbar1[012/100]██████████████████████████████████████████████12%|1sProgressbar2[018/100]██████████████████████████████████████████████18%|1sProgressbar3[002/100]█████████████████████████████████████████████2%|0sProgressbar4[001/100]█████████████████████████████████████████████1%|0sProgressbar5[004/100]██████████████████████████████████████████████4%|1sProgressbar1[016/100]██████████████████████████████████████████████16%|1sProgressbar2[024/100]██████████████████████████████████████████████24%|1sProgressbar3[003/100]██████████████████████████████████████████████3%|1sProgressbar5[005/100]██████████████████████████████████████████████5%|1sProgressbar1[020/100]██████████████████████████████████████████████20%|1sProgressbar3[004/100]██████████████████████████████████████████████4%|1sProgressbar4[002/100]█████████████████████████████████████████████2%|1sProgressbar1[024/100]██████████████████████████████████████████████24%|1sProgressbar2[036/100]██████████████████████████████████████████████36%|1sProgressbar5[008/100]██████████████████████████████████████████████8%|1sProgressbar1[028/100]██████████████████████████████████████████████28%|1sProgressbar2[042/100]██████████████████████████████████████████████42%|1sProgressbar3[005/100]██████████████████████████████████████████████5%|1sProgressbar5[009/100]██████████████████████████████████████████████9%|1sProgressbar1[032/100]██████████████████████████████████████████████32%|2sProgressbar2[048/100]██████████████████████████████████████████████48%|2sProgressbar3[006/100]██████████████████████████████████████████████6%|1sProgressbar4[003/100]██████████████████████████████████████████████3%|1sProgressbar1[036/100]██████████████████████████████████████████████36%|2sProgressbar2[054/100]██████████████████████████████████████████████54%|2sProgressbar3[007/100]██████████████████████████████████████████████7%|2sProgressbar5[012/100]██████████████████████████████████████████████12%|2sProgressbar1[040/100]██████████████████████████████████████████████40%|2sProgressbar2[060/100]██████████████████████████████████████████████60%|2sProgressbar3[008/100]██████████████████████████████████████████████8%|2sProgressbar4[004/100]██████████████████████████████████████████████4%|2sProgressbar5[013/100]██████████████████████████████████████████████13%|2sProgressbar1[044/100]██████████████████████████████████████████████44%|2sProgressbar2[066/100]██████████████████████████████████████████████66%|2sProgressbar5[014/100]██████████████████████████████████████████████14%|2sProgressbar1[048/100]██████████████████████████████████████████████48%|2sProgressbar2[072/100]██████████████████████████████████████████████72%|2sProgressbar3[009/100]██████████████████████████████████████████████9%|2sProgressbar5[016/100]██████████████████████████████████████████████16%|2sProgressbar1[052/100]██████████████████████████████████████████████52%|3sProgressbar2[078/100]██████████████████████████████████████████████78%|3sProgressbar3[010/100]██████████████████████████████████████████████10%|2sProgressbar4[005/100]██████████████████████████████████████████████5%|2sProgressbar5[017/100]██████████████████████████████████████████████17%|3sProgressbar1[060/100]██████████████████████████████████████████████60%|3sProgressbar2[090/100]██████████████████████████████████████████████90%|3sProgressbar3[012/100]██████████████████████████████████████████████12%|3sProgressbar4[006/100]██████████████████████████████████████████████6%|3sProgressbar5[020/100]██████████████████████████████████████████████20%|3sProgressbar1[064/100]██████████████████████████████████████████████64%|3sProgressbar2[096/100]██████████████████████████████████████████████96%|3sProgressbar5[021/100]██████████████████████████████████████████████21%|3sProgressbar1[068/100]██████████████████████████████████████████████68%|3sProgressbar2[102/102]██████████████████████████████████████████████100%|3sProgressbar3[013/100]██████████████████████████████████████████████13%|3sProgressbar5[022/100]██████████████████████████████████████████████22%|3sProgressbar1[072/100]██████████████████████████████████████████████72%|4sProgressbar3[014/100]██████████████████████████████████████████████14%|3sProgressbar4[007/100]██████████████████████████████████████████████7%|3sProgressbar5[024/100]██████████████████████████████████████████████24%|4sProgressbar1[076/100]██████████████████████████████████████████████76%|4sProgressbar3[015/100]██████████████████████████████████████████████15%|4sProgressbar5[025/100]██████████████████████████████████████████████25%|4sProgressbar1[080/100]██████████████████████████████████████████████80%|4sProgressbar3[016/100]██████████████████████████████████████████████16%|4sProgressbar4[008/100]██████████████████████████████████████████████8%|4sProgressbar5[026/100]██████████████████████████████████████████████26%|4sProgressbar1[084/100]██████████████████████████████████████████████84%|4sProgressbar5[028/100]██████████████████████████████████████████████28%|4sProgressbar1[087/100]██████████████████████████████████████████████87%|4sProgressbar3[017/100]██████████████████████████████████████████████17%|4sProgressbar5[029/100]██████████████████████████████████████████████29%|4sProgressbar1[091/100]██████████████████████████████████████████████91%|5sProgressbar3[018/100]██████████████████████████████████████████████18%|5sProgressbar4[009/100]██████████████████████████████████████████████9%|5sProgressbar5[030/100]██████████████████████████████████████████████30%|5sProgressbar1[095/100]██████████████████████████████████████████████95%|5sProgressbar3[019/100]██████████████████████████████████████████████19%|5sProgressbar5[031/100]██████████████████████████████████████████████31%|5sProgressbar1[099/100]█████████████████████████████████████████████99%|5sProgressbar5[033/100]██████████████████████████████████████████████33%|5sProgressbar1[100/100]██████████████████████████████████████████████100%|5sProgressbar3[020/100]██████████████████████████████████████████████20%|5sProgressbar4[010/100]██████████████████████████████████████████████10%|5sProgressbar4[000/Progressbar2[030/100]██████████████████████████████████████████████30%|1sProgressbar5[006/100]██████████████████████████████████████████████6%|1sProgressbar5[010/100]██████████████████████████████████████████████10%|1sProgressbar4[005/100]█████████████████████████████████████████Progressbar1[056/100]██████████████████████████████████████████████56%|3sProgressbar2[084/100]██████████████████████████████████████████████84%|3sProgressbar3[011/100]██████████████████████████████████████████████11%|3sProgressbar5[018/100]██████████████████████████████████████████████18%|3sRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/progressbar/multiple/main.go000066400000000000000000000030161465010626300263120ustar00rootroot00000000000000package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create a multi printer instance from the default one multi := pterm.DefaultMultiPrinter // Create five progress bars with a total of 100 units each, and assign each a new writer from the multi printer pb1, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 1") pb2, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 2") pb3, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 3") pb4, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 4") pb5, _ := pterm.DefaultProgressbar.WithTotal(100).WithWriter(multi.NewWriter()).Start("Progressbar 5") // Start the multi printer multi.Start() // Loop to increment progress bars based on certain conditions for i := 1; i <= 100; i++ { pb1.Increment() // Increment the first progress bar at each iteration if i%2 == 0 { pb2.Add(3) // Add 3 units to the second progress bar at every even iteration } if i%5 == 0 { pb3.Increment() // Increment the third progress bar at every fifth iteration } if i%10 == 0 { pb4.Increment() // Increment the fourth progress bar at every tenth iteration } if i%3 == 0 { pb5.Increment() // Increment the fifth progress bar at every third iteration } time.Sleep(time.Millisecond * 50) // Pause for 50 milliseconds at each iteration } // Stop the multi printer multi.Stop() } golang-github-pterm-pterm-0.12.79/_examples/section/000077500000000000000000000000001465010626300223175ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/section/README.md000066400000000000000000000013251465010626300235770ustar00rootroot00000000000000### section/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/section/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Create a section with level one and print it. pterm.DefaultSection.Println("This is a section!") // Print an informational message. pterm.Info.Println("And here is some text.\nThis text could be anything.\nBasically it's just a placeholder") // Create a section with level two and print it. pterm.DefaultSection.WithLevel(2).Println("This is another section!") // Print another informational message. pterm.Info.Println("And this is\nmore placeholder text") } ```
golang-github-pterm-pterm-0.12.79/_examples/section/demo/000077500000000000000000000000001465010626300232435ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/section/demo/README.md000066400000000000000000000011171465010626300245220ustar00rootroot00000000000000# section/demo ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Create a section with level one and print it. pterm.DefaultSection.Println("This is a section!") // Print an informational message. pterm.Info.Println("And here is some text.\nThis text could be anything.\nBasically it's just a placeholder") // Create a section with level two and print it. pterm.DefaultSection.WithLevel(2).Println("This is another section!") // Print another informational message. pterm.Info.Println("And this is\nmore placeholder text") } ``` golang-github-pterm-pterm-0.12.79/_examples/section/demo/animation.svg000066400000000000000000000116051465010626300257460ustar00rootroot00000000000000#Thisisasection! INFO Andhereissometext. Thistextcouldbeanything. Basicallyit'sjustaplaceholder##Thisisanothersection! INFO Andthisis moreplaceholdertextRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/section/demo/main.go000066400000000000000000000010271465010626300245160ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Create a section with level one and print it. pterm.DefaultSection.Println("This is a section!") // Print an informational message. pterm.Info.Println("And here is some text.\nThis text could be anything.\nBasically it's just a placeholder") // Create a section with level two and print it. pterm.DefaultSection.WithLevel(2).Println("This is another section!") // Print another informational message. pterm.Info.Println("And this is\nmore placeholder text") } golang-github-pterm-pterm-0.12.79/_examples/slog/000077500000000000000000000000001465010626300216175ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/slog/README.md000066400000000000000000000017541465010626300231050ustar00rootroot00000000000000### slog/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/slog/demo/animation.svg)
SHOW SOURCE ```go package main import ( "log/slog" "github.com/pterm/pterm" ) func main() { // Create a new slog handler with the default PTerm logger handler := pterm.NewSlogHandler(&pterm.DefaultLogger) // Create a new slog logger with the handler logger := slog.New(handler) // Log a debug message (won't show by default) logger.Debug("This is a debug message that won't show") // Change the log level to debug to enable debug messages pterm.DefaultLogger.Level = pterm.LogLevelDebug // Log a debug message (will show because debug level is enabled) logger.Debug("This is a debug message", "changedLevel", true) // Log an info message logger.Info("This is an info message") // Log a warning message logger.Warn("This is a warning message") // Log an error message logger.Error("This is an error message") } ```
golang-github-pterm-pterm-0.12.79/_examples/slog/demo/000077500000000000000000000000001465010626300225435ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/slog/demo/README.md000066400000000000000000000015511465010626300240240ustar00rootroot00000000000000# slog/demo ![Animation](animation.svg) ```go package main import ( "log/slog" "github.com/pterm/pterm" ) func main() { // Create a new slog handler with the default PTerm logger handler := pterm.NewSlogHandler(&pterm.DefaultLogger) // Create a new slog logger with the handler logger := slog.New(handler) // Log a debug message (won't show by default) logger.Debug("This is a debug message that won't show") // Change the log level to debug to enable debug messages pterm.DefaultLogger.Level = pterm.LogLevelDebug // Log a debug message (will show because debug level is enabled) logger.Debug("This is a debug message", "changedLevel", true) // Log an info message logger.Info("This is an info message") // Log a warning message logger.Warn("This is a warning message") // Log an error message logger.Error("This is an error message") } ``` golang-github-pterm-pterm-0.12.79/_examples/slog/demo/animation.svg000066400000000000000000000103161465010626300252440ustar00rootroot000000000000002024-02-0918:53:09DEBUGThisisadebugmessagechangedLevel:true2024-02-0918:53:09INFOThisisaninfomessage2024-02-0918:53:09WARNThisisawarningmessage2024-02-0918:53:09ERRORThisisanerrormessageRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/slog/demo/main.go000066400000000000000000000014641465010626300240230ustar00rootroot00000000000000package main import ( "log/slog" "github.com/pterm/pterm" ) func main() { // Create a new slog handler with the default PTerm logger handler := pterm.NewSlogHandler(&pterm.DefaultLogger) // Create a new slog logger with the handler logger := slog.New(handler) // Log a debug message (won't show by default) logger.Debug("This is a debug message that won't show") // Change the log level to debug to enable debug messages pterm.DefaultLogger.Level = pterm.LogLevelDebug // Log a debug message (will show because debug level is enabled) logger.Debug("This is a debug message", "changedLevel", true) // Log an info message logger.Info("This is an info message") // Log a warning message logger.Warn("This is a warning message") // Log an error message logger.Error("This is an error message") } golang-github-pterm-pterm-0.12.79/_examples/spinner/000077500000000000000000000000001465010626300223315ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/spinner/README.md000066400000000000000000000103771465010626300236200ustar00rootroot00000000000000### spinner/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/spinner/demo/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create and start a fork of the default spinner. spinnerInfo, _ := pterm.DefaultSpinner.Start("Some informational action...") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerInfo.Info() // Resolve spinner with error message. // Create and start a fork of the default spinner. spinnerSuccess, _ := pterm.DefaultSpinner.Start("Doing something important... (will succeed)") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerSuccess.Success() // Resolve spinner with success message. // Create and start a fork of the default spinner. spinnerWarning, _ := pterm.DefaultSpinner.Start("Doing something important... (will warn)") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerWarning.Warning() // Resolve spinner with warning message. // Create and start a fork of the default spinner. spinnerFail, _ := pterm.DefaultSpinner.Start("Doing something important... (will fail)") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerFail.Fail() // Resolve spinner with error message. // Create and start a fork of the default spinner. spinnerNochange, _ := pterm.DefaultSpinner.Start("Checking something important... (will result in no change)") // Replace the InfoPrinter with a custom "NOCHG" one spinnerNochange.InfoPrinter = &pterm.PrefixPrinter{ MessageStyle: &pterm.Style{pterm.FgLightBlue}, Prefix: pterm.Prefix{ Style: &pterm.Style{pterm.FgBlack, pterm.BgLightBlue}, Text: " NOCHG ", }, } time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerNochange.Info("No change were required") // Resolve spinner with error message. // Create and start a fork of the default spinner. spinnerLiveText, _ := pterm.DefaultSpinner.Start("Doing a lot of stuff...") time.Sleep(time.Second) // Simulate 2 seconds of processing something. spinnerLiveText.UpdateText("It's really much") // Update spinner text. time.Sleep(time.Second) // Simulate 2 seconds of processing something. spinnerLiveText.UpdateText("We're nearly done!") // Update spinner text. time.Sleep(time.Second) // Simulate 2 seconds of processing something. spinnerLiveText.Success("Finally!") // Resolve spinner with success message. } ```
### spinner/multiple ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/spinner/multiple/animation.svg)
SHOW SOURCE ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create a multi printer. This allows multiple spinners to print simultaneously. multi := pterm.DefaultMultiPrinter // Create and start spinner 1 with a new writer from the multi printer. // The spinner will display the message "Spinner 1". spinner1, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 1") // Create and start spinner 2 with a new writer from the multi printer. // The spinner will display the message "Spinner 2". spinner2, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 2") // Create and start spinner 3 with a new writer from the multi printer. // The spinner will display the message "Spinner 3". spinner3, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 3") // Start the multi printer. This will start printing all the spinners. multi.Start() // Wait for 1 second. time.Sleep(time.Millisecond * 1000) // Stop spinner 1 with a success message. spinner1.Success("Spinner 1 is done!") // Wait for 750 milliseconds. time.Sleep(time.Millisecond * 750) // Stop spinner 2 with a failure message. spinner2.Fail("Spinner 2 failed!") // Wait for 500 milliseconds. time.Sleep(time.Millisecond * 500) // Stop spinner 3 with a warning message. spinner3.Warning("Spinner 3 has a warning!") // Stop the multi printer. This will stop printing all the spinners. multi.Stop() } ```
golang-github-pterm-pterm-0.12.79/_examples/spinner/demo/000077500000000000000000000000001465010626300232555ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/spinner/demo/README.md000066400000000000000000000047751465010626300245510ustar00rootroot00000000000000# spinner/demo ![Animation](animation.svg) ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create and start a fork of the default spinner. spinnerInfo, _ := pterm.DefaultSpinner.Start("Some informational action...") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerInfo.Info() // Resolve spinner with error message. // Create and start a fork of the default spinner. spinnerSuccess, _ := pterm.DefaultSpinner.Start("Doing something important... (will succeed)") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerSuccess.Success() // Resolve spinner with success message. // Create and start a fork of the default spinner. spinnerWarning, _ := pterm.DefaultSpinner.Start("Doing something important... (will warn)") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerWarning.Warning() // Resolve spinner with warning message. // Create and start a fork of the default spinner. spinnerFail, _ := pterm.DefaultSpinner.Start("Doing something important... (will fail)") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerFail.Fail() // Resolve spinner with error message. // Create and start a fork of the default spinner. spinnerNochange, _ := pterm.DefaultSpinner.Start("Checking something important... (will result in no change)") // Replace the InfoPrinter with a custom "NOCHG" one spinnerNochange.InfoPrinter = &pterm.PrefixPrinter{ MessageStyle: &pterm.Style{pterm.FgLightBlue}, Prefix: pterm.Prefix{ Style: &pterm.Style{pterm.FgBlack, pterm.BgLightBlue}, Text: " NOCHG ", }, } time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerNochange.Info("No change were required") // Resolve spinner with error message. // Create and start a fork of the default spinner. spinnerLiveText, _ := pterm.DefaultSpinner.Start("Doing a lot of stuff...") time.Sleep(time.Second) // Simulate 2 seconds of processing something. spinnerLiveText.UpdateText("It's really much") // Update spinner text. time.Sleep(time.Second) // Simulate 2 seconds of processing something. spinnerLiveText.UpdateText("We're nearly done!") // Update spinner text. time.Sleep(time.Second) // Simulate 2 seconds of processing something. spinnerLiveText.Success("Finally!") // Resolve spinner with success message. } ``` golang-github-pterm-pterm-0.12.79/_examples/spinner/demo/animation.svg000066400000000000000000001216631465010626300257660ustar00rootroot00000000000000Someinformationalaction...(1s) INFO Someinformationalaction...Doingsomethingimportant...(willsucceed)(1s) SUCCESS Doingsomethingimportant...(willsucceed)Doingsomethingimportant...(willwarn)(1s) WARNING Doingsomethingimportant...(willwarn)Doingsomethingimportant...(willfail)(1s) ERROR Doingsomethingimportant...(willfail)Checkingsomethingimportant...(willresultinnochange)(1s) NOCHG Nochangewererequired SUCCESS Finally!Someinformationalaction...(0s)Someinformationalaction...(0s)Someinformationalaction...(0s)Someinformationalaction...(1s)Someinformationalaction...(1s)Someinformationalaction...(1s)Someinformationalaction...(2s)Someinformationalaction...(2s)Doingsomethingimportant...(willsucceed)(0s)Doingsomethingimportant...(willsucceed)(0s)Doingsomethingimportant...(willsucceed)(0s)Doingsomethingimportant...(willsucceed)(1s)Doingsomethingimportant...(willsucceed)(1s)Doingsomethingimportant...(willsucceed)(1s)Doingsomethingimportant...(willsucceed)(2s)Doingsomethingimportant...(willsucceed)(2s)Doingsomethingimportant...(willwarn)(0s)Doingsomethingimportant...(willwarn)(0s)Doingsomethingimportant...(willwarn)(0s)Doingsomethingimportant...(willwarn)(1s)Doingsomethingimportant...(willwarn)(1s)Doingsomethingimportant...(willwarn)(1s)Doingsomethingimportant...(willwarn)(2s)Doingsomethingimportant...(willwarn)(2s)Doingsomethingimportant...(willfail)(0s)Doingsomethingimportant...(willfail)(0s)Doingsomethingimportant...(willfail)(0s)Doingsomethingimportant...(willfail)(1s)Doingsomethingimportant...(willfail)(1s)Doingsomethingimportant...(willfail)(1s)Doingsomethingimportant...(willfail)(2s)Doingsomethingimportant...(willfail)(2s)Checkingsomethingimportant...(willresultinnochange)(0s)Checkingsomethingimportant...(willresultinnochange)(0s)Checkingsomethingimportant...(willresultinnochange)(0s)Checkingsomethingimportant...(willresultinnochange)(1s)Checkingsomethingimportant...(willresultinnochange)(1s)Checkingsomethingimportant...(willresultinnochange)(1s)Checkingsomethingimportant...(willresultinnochange)(2s)Checkingsomethingimportant...(willresultinnochange)(2s)Doingalotofstuff...(0s)Doingalotofstuff...(0s)Doingalotofstuff...(0s)Doingalotofstuff...(1s)Doingalotofstuff...(1s)It'sreallymuchtuff...(1s)It'sreallymuch(1s)..(1s)It'sreallymuch(1s)..(1s)It'sreallymuch(1s)..(1s)It'sreallymuch(2s)..(1s)It'sreallymuch(2s)..(1s)We'renearlydone!2s)..(1s)We'renearlydone!(2s)(1s)We'renearlydone!(2s)(1s)We'renearlydone!(2s)(1s)We'renearlydone!(3s)(1s)We'renearlydone!(3s)(1s)Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/spinner/demo/main.go000066400000000000000000000047051465010626300245360ustar00rootroot00000000000000package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create and start a fork of the default spinner. spinnerInfo, _ := pterm.DefaultSpinner.Start("Some informational action...") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerInfo.Info() // Resolve spinner with error message. // Create and start a fork of the default spinner. spinnerSuccess, _ := pterm.DefaultSpinner.Start("Doing something important... (will succeed)") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerSuccess.Success() // Resolve spinner with success message. // Create and start a fork of the default spinner. spinnerWarning, _ := pterm.DefaultSpinner.Start("Doing something important... (will warn)") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerWarning.Warning() // Resolve spinner with warning message. // Create and start a fork of the default spinner. spinnerFail, _ := pterm.DefaultSpinner.Start("Doing something important... (will fail)") time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerFail.Fail() // Resolve spinner with error message. // Create and start a fork of the default spinner. spinnerNochange, _ := pterm.DefaultSpinner.Start("Checking something important... (will result in no change)") // Replace the InfoPrinter with a custom "NOCHG" one spinnerNochange.InfoPrinter = &pterm.PrefixPrinter{ MessageStyle: &pterm.Style{pterm.FgLightBlue}, Prefix: pterm.Prefix{ Style: &pterm.Style{pterm.FgBlack, pterm.BgLightBlue}, Text: " NOCHG ", }, } time.Sleep(time.Second * 2) // Simulate 3 seconds of processing something. spinnerNochange.Info("No change were required") // Resolve spinner with error message. // Create and start a fork of the default spinner. spinnerLiveText, _ := pterm.DefaultSpinner.Start("Doing a lot of stuff...") time.Sleep(time.Second) // Simulate 2 seconds of processing something. spinnerLiveText.UpdateText("It's really much") // Update spinner text. time.Sleep(time.Second) // Simulate 2 seconds of processing something. spinnerLiveText.UpdateText("We're nearly done!") // Update spinner text. time.Sleep(time.Second) // Simulate 2 seconds of processing something. spinnerLiveText.Success("Finally!") // Resolve spinner with success message. } golang-github-pterm-pterm-0.12.79/_examples/spinner/multiple/000077500000000000000000000000001465010626300241645ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/spinner/multiple/README.md000066400000000000000000000027621465010626300254520ustar00rootroot00000000000000# spinner/multiple ![Animation](animation.svg) ```go package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create a multi printer. This allows multiple spinners to print simultaneously. multi := pterm.DefaultMultiPrinter // Create and start spinner 1 with a new writer from the multi printer. // The spinner will display the message "Spinner 1". spinner1, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 1") // Create and start spinner 2 with a new writer from the multi printer. // The spinner will display the message "Spinner 2". spinner2, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 2") // Create and start spinner 3 with a new writer from the multi printer. // The spinner will display the message "Spinner 3". spinner3, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 3") // Start the multi printer. This will start printing all the spinners. multi.Start() // Wait for 1 second. time.Sleep(time.Millisecond * 1000) // Stop spinner 1 with a success message. spinner1.Success("Spinner 1 is done!") // Wait for 750 milliseconds. time.Sleep(time.Millisecond * 750) // Stop spinner 2 with a failure message. spinner2.Fail("Spinner 2 failed!") // Wait for 500 milliseconds. time.Sleep(time.Millisecond * 500) // Stop spinner 3 with a warning message. spinner3.Warning("Spinner 3 has a warning!") // Stop the multi printer. This will stop printing all the spinners. multi.Stop() } ``` golang-github-pterm-pterm-0.12.79/_examples/spinner/multiple/animation.svg000066400000000000000000000316641465010626300266760ustar00rootroot00000000000000Spinner1(0s)Spinner2(0s)Spinner3(0s)Spinner1(0s)Spinner2(0s)Spinner1(0s)Spinner2(0s)Spinner3(1s)Spinner1(1s)Spinner2(1s)Spinner3(1s) SUCCESS Spinner1isdone!Spinner2(1s)Spinner2(1s)Spinner3(1s)Spinner2(1s)Spinner3(1s) ERROR Spinner2failed!Spinner3(2s)Spinner3(2s)Spinner3(2s) WARNING Spinner3hasawarning!Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/spinner/multiple/main.go000066400000000000000000000026661465010626300254510ustar00rootroot00000000000000package main import ( "time" "github.com/pterm/pterm" ) func main() { // Create a multi printer. This allows multiple spinners to print simultaneously. multi := pterm.DefaultMultiPrinter // Create and start spinner 1 with a new writer from the multi printer. // The spinner will display the message "Spinner 1". spinner1, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 1") // Create and start spinner 2 with a new writer from the multi printer. // The spinner will display the message "Spinner 2". spinner2, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 2") // Create and start spinner 3 with a new writer from the multi printer. // The spinner will display the message "Spinner 3". spinner3, _ := pterm.DefaultSpinner.WithWriter(multi.NewWriter()).Start("Spinner 3") // Start the multi printer. This will start printing all the spinners. multi.Start() // Wait for 1 second. time.Sleep(time.Millisecond * 1000) // Stop spinner 1 with a success message. spinner1.Success("Spinner 1 is done!") // Wait for 750 milliseconds. time.Sleep(time.Millisecond * 750) // Stop spinner 2 with a failure message. spinner2.Fail("Spinner 2 failed!") // Wait for 500 milliseconds. time.Sleep(time.Millisecond * 500) // Stop spinner 3 with a warning message. spinner3.Warning("Spinner 3 has a warning!") // Stop the multi printer. This will stop printing all the spinners. multi.Stop() } golang-github-pterm-pterm-0.12.79/_examples/style/000077500000000000000000000000001465010626300220135ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/style/README.md000066400000000000000000000013561465010626300232770ustar00rootroot00000000000000### style/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/style/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define a primary style with light cyan foreground, gray background, and bold text primary := pterm.NewStyle(pterm.FgLightCyan, pterm.BgGray, pterm.Bold) // Define a secondary style with light green foreground, white background, and italic text secondary := pterm.NewStyle(pterm.FgLightGreen, pterm.BgWhite, pterm.Italic) // Print "Hello, World!" with the primary style primary.Println("Hello, World!") // Print "Hello, World!" with the secondary style secondary.Println("Hello, World!") } ```
golang-github-pterm-pterm-0.12.79/_examples/style/demo/000077500000000000000000000000001465010626300227375ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/style/demo/README.md000066400000000000000000000011521465010626300242150ustar00rootroot00000000000000# style/demo ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Define a primary style with light cyan foreground, gray background, and bold text primary := pterm.NewStyle(pterm.FgLightCyan, pterm.BgGray, pterm.Bold) // Define a secondary style with light green foreground, white background, and italic text secondary := pterm.NewStyle(pterm.FgLightGreen, pterm.BgWhite, pterm.Italic) // Print "Hello, World!" with the primary style primary.Println("Hello, World!") // Print "Hello, World!" with the secondary style secondary.Println("Hello, World!") } ``` golang-github-pterm-pterm-0.12.79/_examples/style/demo/animation.svg000066400000000000000000000046041465010626300254430ustar00rootroot00000000000000Hello, World!Hello, World!Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/style/demo/main.go000066400000000000000000000010641465010626300242130ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Define a primary style with light cyan foreground, gray background, and bold text primary := pterm.NewStyle(pterm.FgLightCyan, pterm.BgGray, pterm.Bold) // Define a secondary style with light green foreground, white background, and italic text secondary := pterm.NewStyle(pterm.FgLightGreen, pterm.BgWhite, pterm.Italic) // Print "Hello, World!" with the primary style primary.Println("Hello, World!") // Print "Hello, World!" with the secondary style secondary.Println("Hello, World!") } golang-github-pterm-pterm-0.12.79/_examples/table/000077500000000000000000000000001465010626300217425ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/table/README.md000066400000000000000000000076321465010626300232310ustar00rootroot00000000000000### table/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/table/demo/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the first table tableData1 := pterm.TableData{ {"Firstname", "Lastname", "Email", "Note"}, {"Paul", "Dean", "augue@velitAliquam.co.uk", ""}, {"Callie", "Mckay", "nunc.sed@est.com", "这是一个测试, haha!"}, {"Libby", "Camacho", "lobortis@semper.com", "just a test, hey!"}, {"张", "小宝", "zhang@example.com", ""}, } // Create a table with a header and the defined data, then render it pterm.DefaultTable.WithHasHeader().WithData(tableData1).Render() pterm.Println() // Blank line // Define the data for the second table tableData2 := pterm.TableData{ {"Firstname", "Lastname", "Email"}, {"Paul\n\nNewline", "Dean", "augue@velitAliquam.co.uk"}, {"Callie", "Mckay", "nunc.sed@est.com\nNewline"}, {"Libby", "Camacho", "lobortis@semper.com"}, {"张", "小宝", "zhang@example.com"}, } // Create another table with a header and the defined data, then render it pterm.DefaultTable.WithHasHeader().WithData(tableData2).Render() } ```
### table/boxed ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/table/boxed/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the table. // Each inner slice represents a row in the table. // The first row is considered as the header of the table. tableData := pterm.TableData{ {"Firstname", "Lastname", "Email", "Note"}, {"Paul", "Dean", "augue@velitAliquam.co.uk", ""}, {"Callie", "Mckay", "nunc.sed@est.com", "这是一个测试, haha!"}, {"Libby", "Camacho", "lobortis@semper.com", "just a test, hey!"}, {"张", "小宝", "zhang@example.com", ""}, } // Create a table with the defined data. // The table has a header and is boxed. // Finally, render the table to print it. pterm.DefaultTable.WithHasHeader().WithBoxed().WithData(tableData).Render() } ```
### table/multiple-lines ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/table/multiple-lines/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the table. data := pterm.TableData{ {"Firstname", "Lastname", "Email"}, {"Paul\n\nNewline", "Dean", "augue@velitAliquam.co.uk"}, {"Callie", "Mckay", "nunc.sed@est.com\nNewline"}, {"Libby", "Camacho", "lobortis@semper.com"}, {"张", "小宝", "zhang@example.com"}, } // Create and render the table. // The options are chained in a single line for simplicity. // The table has a header, a row separator, and a header row separator. pterm.DefaultTable.WithHasHeader().WithRowSeparator("-").WithHeaderRowSeparator("-").WithData(data).Render() } ```
### table/right-alignment ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/table/right-alignment/animation.svg)
SHOW SOURCE ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the table. // Each inner slice represents a row in the table. // The first row is considered as the header. tableData := pterm.TableData{ {"Firstname", "Lastname", "Email", "Note"}, {"Paul", "Dean", "augue@velitAliquam.co.uk", ""}, {"Callie", "Mckay", "nunc.sed@est.com", "这是一个测试, haha!"}, {"Libby", "Camacho", "lobortis@semper.com", "just a test, hey!"}, {"张", "小宝", "zhang@example.com", ""}, } // Create a table with the defined data. // The table has a header and the text in the cells is right-aligned. // The Render() method is used to print the table to the console. pterm.DefaultTable.WithHasHeader().WithRightAlignment().WithData(tableData).Render() } ```
golang-github-pterm-pterm-0.12.79/_examples/table/boxed/000077500000000000000000000000001465010626300230435ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/table/boxed/README.md000066400000000000000000000014231465010626300243220ustar00rootroot00000000000000# table/boxed ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the table. // Each inner slice represents a row in the table. // The first row is considered as the header of the table. tableData := pterm.TableData{ {"Firstname", "Lastname", "Email", "Note"}, {"Paul", "Dean", "augue@velitAliquam.co.uk", ""}, {"Callie", "Mckay", "nunc.sed@est.com", "这是一个测试, haha!"}, {"Libby", "Camacho", "lobortis@semper.com", "just a test, hey!"}, {"张", "小宝", "zhang@example.com", ""}, } // Create a table with the defined data. // The table has a header and is boxed. // Finally, render the table to print it. pterm.DefaultTable.WithHasHeader().WithBoxed().WithData(tableData).Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/table/boxed/animation.svg000066400000000000000000000127041465010626300255470ustar00rootroot00000000000000┌───────────────────────────────────────────────────────────────────────┐|Firstname|Lastname|Email|Note||Paul|Dean|augue@velitAliquam.co.uk|||Callie|Mckay|nunc.sed@est.com|这是一个测试,haha!||Libby|Camacho|lobortis@semper.com|justatest,hey!|||小宝|zhang@example.com||└───────────────────────────────────────────────────────────────────────┘Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/table/boxed/main.go000066400000000000000000000013341465010626300243170ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Define the data for the table. // Each inner slice represents a row in the table. // The first row is considered as the header of the table. tableData := pterm.TableData{ {"Firstname", "Lastname", "Email", "Note"}, {"Paul", "Dean", "augue@velitAliquam.co.uk", ""}, {"Callie", "Mckay", "nunc.sed@est.com", "这是一个测试, haha!"}, {"Libby", "Camacho", "lobortis@semper.com", "just a test, hey!"}, {"张", "小宝", "zhang@example.com", ""}, } // Create a table with the defined data. // The table has a header and is boxed. // Finally, render the table to print it. pterm.DefaultTable.WithHasHeader().WithBoxed().WithData(tableData).Render() } golang-github-pterm-pterm-0.12.79/_examples/table/demo/000077500000000000000000000000001465010626300226665ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/table/demo/README.md000066400000000000000000000021171465010626300241460ustar00rootroot00000000000000# table/demo ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the first table tableData1 := pterm.TableData{ {"Firstname", "Lastname", "Email", "Note"}, {"Paul", "Dean", "augue@velitAliquam.co.uk", ""}, {"Callie", "Mckay", "nunc.sed@est.com", "这是一个测试, haha!"}, {"Libby", "Camacho", "lobortis@semper.com", "just a test, hey!"}, {"张", "小宝", "zhang@example.com", ""}, } // Create a table with a header and the defined data, then render it pterm.DefaultTable.WithHasHeader().WithData(tableData1).Render() pterm.Println() // Blank line // Define the data for the second table tableData2 := pterm.TableData{ {"Firstname", "Lastname", "Email"}, {"Paul\n\nNewline", "Dean", "augue@velitAliquam.co.uk"}, {"Callie", "Mckay", "nunc.sed@est.com\nNewline"}, {"Libby", "Camacho", "lobortis@semper.com"}, {"张", "小宝", "zhang@example.com"}, } // Create another table with a header and the defined data, then render it pterm.DefaultTable.WithHasHeader().WithData(tableData2).Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/table/demo/animation.svg000066400000000000000000000154671465010626300254030ustar00rootroot00000000000000Firstname|Lastname|Email|NotePaul|Dean|augue@velitAliquam.co.uk|Callie|Mckay|nunc.sed@est.com|这是一个测试,haha!Libby|Camacho|lobortis@semper.com|justatest,hey!|小宝|zhang@example.com|Firstname|Lastname|EmailPaul|Dean|augue@velitAliquam.co.uk||Newline||Callie|Mckay|nunc.sed@est.com||NewlineLibby|Camacho|lobortis@semper.com|小宝|zhang@example.comRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/table/demo/main.go000066400000000000000000000020311465010626300241350ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Define the data for the first table tableData1 := pterm.TableData{ {"Firstname", "Lastname", "Email", "Note"}, {"Paul", "Dean", "augue@velitAliquam.co.uk", ""}, {"Callie", "Mckay", "nunc.sed@est.com", "这是一个测试, haha!"}, {"Libby", "Camacho", "lobortis@semper.com", "just a test, hey!"}, {"张", "小宝", "zhang@example.com", ""}, } // Create a table with a header and the defined data, then render it pterm.DefaultTable.WithHasHeader().WithData(tableData1).Render() pterm.Println() // Blank line // Define the data for the second table tableData2 := pterm.TableData{ {"Firstname", "Lastname", "Email"}, {"Paul\n\nNewline", "Dean", "augue@velitAliquam.co.uk"}, {"Callie", "Mckay", "nunc.sed@est.com\nNewline"}, {"Libby", "Camacho", "lobortis@semper.com"}, {"张", "小宝", "zhang@example.com"}, } // Create another table with a header and the defined data, then render it pterm.DefaultTable.WithHasHeader().WithData(tableData2).Render() } golang-github-pterm-pterm-0.12.79/_examples/table/multiple-lines/000077500000000000000000000000001465010626300247055ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/table/multiple-lines/README.md000066400000000000000000000013031465010626300261610ustar00rootroot00000000000000# table/multiple-lines ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the table. data := pterm.TableData{ {"Firstname", "Lastname", "Email"}, {"Paul\n\nNewline", "Dean", "augue@velitAliquam.co.uk"}, {"Callie", "Mckay", "nunc.sed@est.com\nNewline"}, {"Libby", "Camacho", "lobortis@semper.com"}, {"张", "小宝", "zhang@example.com"}, } // Create and render the table. // The options are chained in a single line for simplicity. // The table has a header, a row separator, and a header row separator. pterm.DefaultTable.WithHasHeader().WithRowSeparator("-").WithHeaderRowSeparator("-").WithData(data).Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/table/multiple-lines/animation.svg000066400000000000000000000132621465010626300274110ustar00rootroot00000000000000Firstname|Lastname|Email-----------------------------------------------Paul|Dean|augue@velitAliquam.co.uk||Newline||Callie|Mckay|nunc.sed@est.com||NewlineLibby|Camacho|lobortis@semper.com|小宝|zhang@example.com|小宝|zhang@Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/table/multiple-lines/main.go000066400000000000000000000012031465010626300261540ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Define the data for the table. data := pterm.TableData{ {"Firstname", "Lastname", "Email"}, {"Paul\n\nNewline", "Dean", "augue@velitAliquam.co.uk"}, {"Callie", "Mckay", "nunc.sed@est.com\nNewline"}, {"Libby", "Camacho", "lobortis@semper.com"}, {"张", "小宝", "zhang@example.com"}, } // Create and render the table. // The options are chained in a single line for simplicity. // The table has a header, a row separator, and a header row separator. pterm.DefaultTable.WithHasHeader().WithRowSeparator("-").WithHeaderRowSeparator("-").WithData(data).Render() } golang-github-pterm-pterm-0.12.79/_examples/table/right-alignment/000077500000000000000000000000001465010626300250335ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/table/right-alignment/README.md000066400000000000000000000015171465010626300263160ustar00rootroot00000000000000# table/right-alignment ![Animation](animation.svg) ```go package main import "github.com/pterm/pterm" func main() { // Define the data for the table. // Each inner slice represents a row in the table. // The first row is considered as the header. tableData := pterm.TableData{ {"Firstname", "Lastname", "Email", "Note"}, {"Paul", "Dean", "augue@velitAliquam.co.uk", ""}, {"Callie", "Mckay", "nunc.sed@est.com", "这是一个测试, haha!"}, {"Libby", "Camacho", "lobortis@semper.com", "just a test, hey!"}, {"张", "小宝", "zhang@example.com", ""}, } // Create a table with the defined data. // The table has a header and the text in the cells is right-aligned. // The Render() method is used to print the table to the console. pterm.DefaultTable.WithHasHeader().WithRightAlignment().WithData(tableData).Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/table/right-alignment/animation.svg000066400000000000000000000103141465010626300275320ustar00rootroot00000000000000Firstname|Lastname|Email|NotePaul|Dean|augue@velitAliquam.co.uk|Callie|Mckay|nunc.sed@est.com|这是一个测试,haha!Libby|Camacho|lobortis@semper.com|justatest,hey!|小宝|zhang@example.com|Restartinganimation...golang-github-pterm-pterm-0.12.79/_examples/table/right-alignment/main.go000066400000000000000000000014161465010626300263100ustar00rootroot00000000000000package main import "github.com/pterm/pterm" func main() { // Define the data for the table. // Each inner slice represents a row in the table. // The first row is considered as the header. tableData := pterm.TableData{ {"Firstname", "Lastname", "Email", "Note"}, {"Paul", "Dean", "augue@velitAliquam.co.uk", ""}, {"Callie", "Mckay", "nunc.sed@est.com", "这是一个测试, haha!"}, {"Libby", "Camacho", "lobortis@semper.com", "just a test, hey!"}, {"张", "小宝", "zhang@example.com", ""}, } // Create a table with the defined data. // The table has a header and the text in the cells is right-aligned. // The Render() method is used to print the table to the console. pterm.DefaultTable.WithHasHeader().WithRightAlignment().WithData(tableData).Render() } golang-github-pterm-pterm-0.12.79/_examples/theme/000077500000000000000000000000001465010626300217555ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/theme/README.md000066400000000000000000000022541465010626300232370ustar00rootroot00000000000000### theme/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/theme/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "reflect" "time" ) func main() { // Print an informational message about the default theme styles. pterm.Info.Println("These are the default theme styles.\nYou can modify them easily to your personal preference,\nor create new themes from scratch :)") // Print a blank line for better readability. pterm.Println() // Get the value and type of the default theme. v := reflect.ValueOf(pterm.ThemeDefault) typeOfS := v.Type() // Check if the type of the default theme is 'pterm.Theme'. if typeOfS == reflect.TypeOf(pterm.Theme{}) { // Iterate over each field in the default theme. for i := 0; i < v.NumField(); i++ { // Try to convert the field to 'pterm.Style'. field, ok := v.Field(i).Interface().(pterm.Style) if ok { // Print the field name using its own style. field.Println(typeOfS.Field(i).Name) } // Pause for a quarter of a second to make the output easier to read. time.Sleep(time.Millisecond * 250) } } } ```
golang-github-pterm-pterm-0.12.79/_examples/theme/demo/000077500000000000000000000000001465010626300227015ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/theme/demo/README.md000066400000000000000000000020501465010626300241550ustar00rootroot00000000000000# theme/demo ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" "reflect" "time" ) func main() { // Print an informational message about the default theme styles. pterm.Info.Println("These are the default theme styles.\nYou can modify them easily to your personal preference,\nor create new themes from scratch :)") // Print a blank line for better readability. pterm.Println() // Get the value and type of the default theme. v := reflect.ValueOf(pterm.ThemeDefault) typeOfS := v.Type() // Check if the type of the default theme is 'pterm.Theme'. if typeOfS == reflect.TypeOf(pterm.Theme{}) { // Iterate over each field in the default theme. for i := 0; i < v.NumField(); i++ { // Try to convert the field to 'pterm.Style'. field, ok := v.Field(i).Interface().(pterm.Style) if ok { // Print the field name using its own style. field.Println(typeOfS.Field(i).Name) } // Pause for a quarter of a second to make the output easier to read. time.Sleep(time.Millisecond * 250) } } } ``` golang-github-pterm-pterm-0.12.79/_examples/theme/demo/animation.svg000066400000000000000000001577521465010626300254220ustar00rootroot00000000000000 INFO Thesearethedefaultthemestyles. Youcanmodifythemeasilytoyourpersonalpreference, orcreatenewthemesfromscratch:)DefaultTextPrimaryStyleSecondaryStyleHighlightStyleInfoMessageStyleInfoPrefixStyleSuccessMessageStyleSuccessPrefixStyleWarningMessageStyleWarningPrefixStyleErrorMessageStyleErrorPrefixStyleFatalMessageStyleFatalPrefixStyleDescriptionMessageStyleDescriptionPrefixStyleScopeStyleProgressbarBarStyleProgressbarTitleStyleHeaderTextStyleHeaderBackgroundStyleSpinnerStyleSpinnerTextStyleTimerStyleTableStyleTableHeaderStyleTableSeparatorStyleHeatmapStyleHeatmapHeaderStyleHeatmapSeparatorStyleSectionStyleBulletListTextStyleBulletListBulletStyleTreeStyleTreeTextStyleLetterStyleDebugMessageStyleDebugPrefixStyleBoxStyleBoxTextStyleBarLabelStyleBarStyleRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/theme/demo/main.go000066400000000000000000000017621465010626300241620ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" "reflect" "time" ) func main() { // Print an informational message about the default theme styles. pterm.Info.Println("These are the default theme styles.\nYou can modify them easily to your personal preference,\nor create new themes from scratch :)") // Print a blank line for better readability. pterm.Println() // Get the value and type of the default theme. v := reflect.ValueOf(pterm.ThemeDefault) typeOfS := v.Type() // Check if the type of the default theme is 'pterm.Theme'. if typeOfS == reflect.TypeOf(pterm.Theme{}) { // Iterate over each field in the default theme. for i := 0; i < v.NumField(); i++ { // Try to convert the field to 'pterm.Style'. field, ok := v.Field(i).Interface().(pterm.Style) if ok { // Print the field name using its own style. field.Println(typeOfS.Field(i).Name) } // Pause for a quarter of a second to make the output easier to read. time.Sleep(time.Millisecond * 250) } } } golang-github-pterm-pterm-0.12.79/_examples/tree/000077500000000000000000000000001465010626300216125ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/tree/README.md000066400000000000000000000041331465010626300230720ustar00rootroot00000000000000### tree/demo ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/tree/demo/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define a tree structure using pterm.TreeNode tree := pterm.TreeNode{ // The top node of the tree Text: "Top node", // The children of the top node Children: []pterm.TreeNode{{ // A child node Text: "Child node", // The children of the child node Children: []pterm.TreeNode{ // Grandchildren nodes {Text: "Grandchild node"}, {Text: "Grandchild node"}, {Text: "Grandchild node"}, }, }}, } // Render the tree with the defined structure as the root pterm.DefaultTree.WithRoot(tree).Render() } ```
### tree/from-leveled-list ![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/tree/from-leveled-list/animation.svg)
SHOW SOURCE ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Define a leveled list to represent the structure of the directories. leveledList := pterm.LeveledList{ {Level: 0, Text: "C:"}, {Level: 1, Text: "Users"}, {Level: 1, Text: "Windows"}, {Level: 1, Text: "Programs"}, {Level: 1, Text: "Programs(x86)"}, {Level: 1, Text: "dev"}, {Level: 0, Text: "D:"}, {Level: 0, Text: "E:"}, {Level: 1, Text: "Movies"}, {Level: 1, Text: "Music"}, {Level: 2, Text: "LinkinPark"}, {Level: 1, Text: "Games"}, {Level: 2, Text: "Shooter"}, {Level: 3, Text: "CallOfDuty"}, {Level: 3, Text: "CS:GO"}, {Level: 3, Text: "Battlefield"}, {Level: 4, Text: "Battlefield 1"}, {Level: 4, Text: "Battlefield 2"}, {Level: 0, Text: "F:"}, {Level: 1, Text: "dev"}, {Level: 2, Text: "dops"}, {Level: 2, Text: "PTerm"}, } // Convert the leveled list into a tree structure. root := putils.TreeFromLeveledList(leveledList) root.Text = "Computer" // Set the root node text. // Render the tree structure using the default tree printer. pterm.DefaultTree.WithRoot(root).Render() } ```
golang-github-pterm-pterm-0.12.79/_examples/tree/demo/000077500000000000000000000000001465010626300225365ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/tree/demo/README.md000066400000000000000000000012221465010626300240120ustar00rootroot00000000000000# tree/demo ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" ) func main() { // Define a tree structure using pterm.TreeNode tree := pterm.TreeNode{ // The top node of the tree Text: "Top node", // The children of the top node Children: []pterm.TreeNode{{ // A child node Text: "Child node", // The children of the child node Children: []pterm.TreeNode{ // Grandchildren nodes {Text: "Grandchild node"}, {Text: "Grandchild node"}, {Text: "Grandchild node"}, }, }}, } // Render the tree with the defined structure as the root pterm.DefaultTree.WithRoot(tree).Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/tree/demo/animation.svg000066400000000000000000000055721465010626300252470ustar00rootroot00000000000000Topnode└─┬Childnode├──Grandchildnode└──GrandchildnodeRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/tree/demo/main.go000066400000000000000000000011351465010626300240110ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" ) func main() { // Define a tree structure using pterm.TreeNode tree := pterm.TreeNode{ // The top node of the tree Text: "Top node", // The children of the top node Children: []pterm.TreeNode{{ // A child node Text: "Child node", // The children of the child node Children: []pterm.TreeNode{ // Grandchildren nodes {Text: "Grandchild node"}, {Text: "Grandchild node"}, {Text: "Grandchild node"}, }, }}, } // Render the tree with the defined structure as the root pterm.DefaultTree.WithRoot(tree).Render() } golang-github-pterm-pterm-0.12.79/_examples/tree/from-leveled-list/000077500000000000000000000000001465010626300251445ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/_examples/tree/from-leveled-list/README.md000066400000000000000000000022661465010626300264310ustar00rootroot00000000000000# tree/from-leveled-list ![Animation](animation.svg) ```go package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Define a leveled list to represent the structure of the directories. leveledList := pterm.LeveledList{ {Level: 0, Text: "C:"}, {Level: 1, Text: "Users"}, {Level: 1, Text: "Windows"}, {Level: 1, Text: "Programs"}, {Level: 1, Text: "Programs(x86)"}, {Level: 1, Text: "dev"}, {Level: 0, Text: "D:"}, {Level: 0, Text: "E:"}, {Level: 1, Text: "Movies"}, {Level: 1, Text: "Music"}, {Level: 2, Text: "LinkinPark"}, {Level: 1, Text: "Games"}, {Level: 2, Text: "Shooter"}, {Level: 3, Text: "CallOfDuty"}, {Level: 3, Text: "CS:GO"}, {Level: 3, Text: "Battlefield"}, {Level: 4, Text: "Battlefield 1"}, {Level: 4, Text: "Battlefield 2"}, {Level: 0, Text: "F:"}, {Level: 1, Text: "dev"}, {Level: 2, Text: "dops"}, {Level: 2, Text: "PTerm"}, } // Convert the leveled list into a tree structure. root := putils.TreeFromLeveledList(leveledList) root.Text = "Computer" // Set the root node text. // Render the tree structure using the default tree printer. pterm.DefaultTree.WithRoot(root).Render() } ``` golang-github-pterm-pterm-0.12.79/_examples/tree/from-leveled-list/animation.svg000066400000000000000000000157601465010626300276550ustar00rootroot00000000000000├──Windows├──Programs├──Programs(x86)└──dev├──D:├─┬E:├──Movies├─┬Music└──LinkinPark└─┬Games└─┬Shooter├──CallOfDuty├──CS:GO└─┬Battlefield├──Battlefield1└──Battlefield2└─┬F:└─┬dev├──dops└──PTermComputer├─┬C:├──UsersRestartinganimation...golang-github-pterm-pterm-0.12.79/_examples/tree/from-leveled-list/main.go000066400000000000000000000021641465010626300264220ustar00rootroot00000000000000package main import ( "github.com/pterm/pterm" "github.com/pterm/pterm/putils" ) func main() { // Define a leveled list to represent the structure of the directories. leveledList := pterm.LeveledList{ {Level: 0, Text: "C:"}, {Level: 1, Text: "Users"}, {Level: 1, Text: "Windows"}, {Level: 1, Text: "Programs"}, {Level: 1, Text: "Programs(x86)"}, {Level: 1, Text: "dev"}, {Level: 0, Text: "D:"}, {Level: 0, Text: "E:"}, {Level: 1, Text: "Movies"}, {Level: 1, Text: "Music"}, {Level: 2, Text: "LinkinPark"}, {Level: 1, Text: "Games"}, {Level: 2, Text: "Shooter"}, {Level: 3, Text: "CallOfDuty"}, {Level: 3, Text: "CS:GO"}, {Level: 3, Text: "Battlefield"}, {Level: 4, Text: "Battlefield 1"}, {Level: 4, Text: "Battlefield 2"}, {Level: 0, Text: "F:"}, {Level: 1, Text: "dev"}, {Level: 2, Text: "dops"}, {Level: 2, Text: "PTerm"}, } // Convert the leveled list into a tree structure. root := putils.TreeFromLeveledList(leveledList) root.Text = "Computer" // Set the root node text. // Render the tree structure using the default tree printer. pterm.DefaultTree.WithRoot(root).Render() } golang-github-pterm-pterm-0.12.79/area_printer.go000066400000000000000000000063651465010626300217120ustar00rootroot00000000000000package pterm import ( "io" "strings" "atomicgo.dev/cursor" "github.com/pterm/pterm/internal" ) // DefaultArea is the default area printer. var DefaultArea = AreaPrinter{} // AreaPrinter prints an area which can be updated easily. // use this printer for live output like charts, algorithm visualizations, simulations and even games. type AreaPrinter struct { RemoveWhenDone bool Fullscreen bool Center bool content string isActive bool area *cursor.Area } // GetContent returns the current area content. func (p *AreaPrinter) GetContent() string { return p.content } // WithRemoveWhenDone removes the AreaPrinter content after it is stopped. func (p AreaPrinter) WithRemoveWhenDone(b ...bool) *AreaPrinter { p.RemoveWhenDone = internal.WithBoolean(b) return &p } // WithFullscreen sets the AreaPrinter height the same height as the terminal, making it fullscreen. func (p AreaPrinter) WithFullscreen(b ...bool) *AreaPrinter { p.Fullscreen = internal.WithBoolean(b) return &p } // WithCenter centers the AreaPrinter content to the terminal. func (p AreaPrinter) WithCenter(b ...bool) *AreaPrinter { p.Center = internal.WithBoolean(b) return &p } // SetWriter sets the writer for the AreaPrinter. func (p *AreaPrinter) SetWriter(writer io.Writer) { } // Update overwrites the content of the AreaPrinter. // Can be used live. func (p *AreaPrinter) Update(text ...interface{}) { if p.area == nil { newArea := cursor.NewArea() p.area = &newArea } str := Sprint(text...) p.content = str if p.Center { str = DefaultCenter.Sprint(str) } if p.Fullscreen { str = strings.TrimRight(str, "\n") height := GetTerminalHeight() contentHeight := strings.Count(str, "\n") topPadding := 0 bottomPadding := height - contentHeight - 2 if p.Center { topPadding = (bottomPadding / 2) + 1 bottomPadding /= 2 } if height > contentHeight { str = strings.Repeat("\n", topPadding) + str str += strings.Repeat("\n", bottomPadding) } } p.area.Update(str) } // Start the AreaPrinter. func (p *AreaPrinter) Start(text ...interface{}) (*AreaPrinter, error) { p.isActive = true str := Sprint(text...) newArea := cursor.NewArea() p.area = &newArea p.Update(str) return p, nil } // Stop terminates the AreaPrinter immediately. // The AreaPrinter will not resolve into anything. func (p *AreaPrinter) Stop() error { if !p.isActive { return nil } p.isActive = false if p.RemoveWhenDone { p.Clear() } return nil } // GenericStart runs Start, but returns a LivePrinter. // This is used for the interface LivePrinter. // You most likely want to use Start instead of this in your program. func (p *AreaPrinter) GenericStart() (*LivePrinter, error) { _, _ = p.Start() lp := LivePrinter(p) return &lp, nil } // GenericStop runs Stop, but returns a LivePrinter. // This is used for the interface LivePrinter. // You most likely want to use Stop instead of this in your program. func (p *AreaPrinter) GenericStop() (*LivePrinter, error) { _ = p.Stop() lp := LivePrinter(p) return &lp, nil } // Clear is a Wrapper function that clears the content of the Area // moves the cursor to the bottom of the terminal, clears n lines upwards from // the current position and moves the cursor again. func (p *AreaPrinter) Clear() { p.area.Clear() } golang-github-pterm-pterm-0.12.79/area_printer_test.go000066400000000000000000000064411465010626300227440ustar00rootroot00000000000000package pterm_test import ( "os" "testing" "github.com/MarvinJWendt/testza" "github.com/pterm/pterm" ) func TestAreaPrinter_NilPrint(t *testing.T) { originalStdout := os.Stdout os.Stdout = os.NewFile(0, os.DevNull) // Set os.Stdout to DevNull to hide output from cursor.Area p := pterm.AreaPrinter{} p.Update("asd") os.Stdout = originalStdout // Restore original os.Stdout } func TestAreaPrinter_GenericStart(t *testing.T) { originalStdout := os.Stdout os.Stdout = os.NewFile(0, os.DevNull) // Set os.Stdout to DevNull to hide output from cursor.Area p := pterm.DefaultArea p.GenericStart() os.Stdout = originalStdout // Restore original os.Stdout } func TestAreaPrinter_GenericStartRawOutput(t *testing.T) { originalStdout := os.Stdout os.Stdout = os.NewFile(0, os.DevNull) // Set os.Stdout to DevNull to hide output from cursor.Area pterm.DisableStyling() p := pterm.DefaultArea p.GenericStart() pterm.EnableStyling() os.Stdout = originalStdout // Restore original os.Stdout } func TestAreaPrinter_GenericStop(t *testing.T) { originalStdout := os.Stdout os.Stdout = os.NewFile(0, os.DevNull) // Set os.Stdout to DevNull to hide output from cursor.Area p := pterm.DefaultArea p.GenericStop() os.Stdout = originalStdout // Restore original os.Stdout } func TestAreaPrinter_RemoveWhenDone(t *testing.T) { originalStdout := os.Stdout os.Stdout = os.NewFile(0, os.DevNull) // Set os.Stdout to DevNull to hide output from cursor.Area a, _ := pterm.DefaultArea.WithRemoveWhenDone().Start() a.Update("asd") a.Stop() os.Stdout = originalStdout // Restore original os.Stdout } func TestAreaPrinter_CenterFullscreen(t *testing.T) { originalStdout := os.Stdout os.Stdout = os.NewFile(0, os.DevNull) // Set os.Stdout to DevNull to hide output from cursor.Area a, _ := pterm.DefaultArea.WithRemoveWhenDone().WithFullscreen().WithCenter().Start() a.Update("asd") a.Stop() os.Stdout = originalStdout // Restore original os.Stdout } func TestAreaPrinter_GetContent(t *testing.T) { originalStdout := os.Stdout os.Stdout = os.NewFile(0, os.DevNull) // Set os.Stdout to DevNull to hide output from cursor.Area a, _ := pterm.DefaultArea.Start() for _, printable := range printables { a.Update(printable) testza.AssertEqual(t, a.GetContent(), pterm.Sprint(printable)) } a.Stop() os.Stdout = originalStdout // Restore original os.Stdout } func TestAreaPrinter_WithRemoveWhenDone(t *testing.T) { originalStdout := os.Stdout os.Stdout = os.NewFile(0, os.DevNull) // Set os.Stdout to DevNull to hide output from cursor.Area p := pterm.AreaPrinter{} p2 := p.WithRemoveWhenDone() testza.AssertTrue(t, p2.RemoveWhenDone) os.Stdout = originalStdout // Restore original os.Stdout } func TestAreaPrinter_WithFullscreen(t *testing.T) { originalStdout := os.Stdout os.Stdout = os.NewFile(0, os.DevNull) // Set os.Stdout to DevNull to hide output from cursor.Area p := pterm.AreaPrinter{} p2 := p.WithFullscreen() testza.AssertTrue(t, p2.Fullscreen) os.Stdout = originalStdout // Restore original os.Stdout } func TestAreaPrinter_Clear(t *testing.T) { originalStdout := os.Stdout os.Stdout = os.NewFile(0, os.DevNull) // Set os.Stdout to DevNull to hide output from cursor.Area p := pterm.AreaPrinter{} p.Update("asd") p.Clear() os.Stdout = originalStdout // Restore original os.Stdout } golang-github-pterm-pterm-0.12.79/atoms.go000066400000000000000000000015141465010626300203510ustar00rootroot00000000000000package pterm // Checkmark is used in the interactive multiselect printer. type Checkmark struct { Checked string Unchecked string } // Bars is used to display multiple Bar. type Bars []Bar // Bar is used in bar charts. type Bar struct { Label string Value int Style *Style LabelStyle *Style } // WithLabel returns a new Bar with a specific option. func (p Bar) WithLabel(s string) *Bar { p.Label = s return &p } // WithLabelStyle returns a new Bar with a specific option. func (p Bar) WithLabelStyle(style *Style) *Bar { p.LabelStyle = style return &p } // WithValue returns a new Bar with a specific option. func (p Bar) WithValue(value int) *Bar { p.Value = value return &p } // WithStyle returns a new Bar with a specific option. func (p Bar) WithStyle(style *Style) *Bar { p.Style = style return &p } golang-github-pterm-pterm-0.12.79/atoms_test.go000066400000000000000000000015401465010626300214070ustar00rootroot00000000000000package pterm_test import ( "testing" "github.com/MarvinJWendt/testza" "github.com/pterm/pterm" ) func TestBar_WithLabel(t *testing.T) { p := pterm.Bar{} s := "X" p2 := p.WithLabel(s) testza.AssertEqual(t, s, p2.Label) testza.AssertZero(t, p.Label) } func TestBar_WithStyle(t *testing.T) { p := pterm.Bar{} s := pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold) p2 := p.WithStyle(s) testza.AssertEqual(t, s, p2.Style) testza.AssertZero(t, p.Style) } func TestBar_WithValue(t *testing.T) { p := pterm.Bar{} s := 1337 p2 := p.WithValue(s) testza.AssertEqual(t, s, p2.Value) testza.AssertZero(t, p.Value) } func TestBar_WithLabelStyle(t *testing.T) { p := pterm.Bar{} s := pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold) p2 := p.WithLabelStyle(s) testza.AssertEqual(t, s, p2.LabelStyle) testza.AssertZero(t, p.LabelStyle) } golang-github-pterm-pterm-0.12.79/barchart.go000066400000000000000000000316071465010626300210220ustar00rootroot00000000000000package pterm import ( "io" "strconv" "strings" "github.com/mattn/go-runewidth" "github.com/pterm/pterm/internal" ) // BarChartPrinter is used to print bar charts. type BarChartPrinter struct { Writer io.Writer Bars Bars Horizontal bool ShowValue bool // Height sets the maximum height of a vertical bar chart. // The default is calculated to fit into the terminal. // Ignored if Horizontal is set to true. Height int // Width sets the maximum width of a horizontal bar chart. // The default is calculated to fit into the terminal. // Ignored if Horizontal is set to false. Width int VerticalBarCharacter string HorizontalBarCharacter string } var ( // DefaultBarChart is the default BarChartPrinter. DefaultBarChart = BarChartPrinter{ Horizontal: false, VerticalBarCharacter: "██", HorizontalBarCharacter: "█", // keep in sync with RecalculateTerminalSize() Height: GetTerminalHeight() * 2 / 3, Width: GetTerminalWidth() * 2 / 3, } ) // WithBars returns a new BarChartPrinter with a specific option. func (p BarChartPrinter) WithBars(bars Bars) *BarChartPrinter { p.Bars = bars return &p } // WithVerticalBarCharacter returns a new BarChartPrinter with a specific option. func (p BarChartPrinter) WithVerticalBarCharacter(char string) *BarChartPrinter { p.VerticalBarCharacter = char return &p } // WithHorizontalBarCharacter returns a new BarChartPrinter with a specific option. func (p BarChartPrinter) WithHorizontalBarCharacter(char string) *BarChartPrinter { p.HorizontalBarCharacter = char return &p } // WithHorizontal returns a new BarChartPrinter with a specific option. func (p BarChartPrinter) WithHorizontal(b ...bool) *BarChartPrinter { b2 := internal.WithBoolean(b) p.Horizontal = b2 return &p } // WithHeight returns a new BarChartPrinter with a specific option. func (p BarChartPrinter) WithHeight(value int) *BarChartPrinter { p.Height = value return &p } // WithWidth returns a new BarChartPrinter with a specific option. func (p BarChartPrinter) WithWidth(value int) *BarChartPrinter { p.Width = value return &p } // WithShowValue returns a new BarChartPrinter with a specific option. func (p BarChartPrinter) WithShowValue(b ...bool) *BarChartPrinter { p.ShowValue = internal.WithBoolean(b) return &p } // WithWriter sets the custom Writer. func (p BarChartPrinter) WithWriter(writer io.Writer) *BarChartPrinter { p.Writer = writer return &p } func (p BarChartPrinter) getRawOutput() string { var ret string for _, bar := range p.Bars { ret += Sprintfln("%s: %d", bar.Label, bar.Value) } return ret } // Srender renders the BarChart as a string. func (p BarChartPrinter) Srender() (string, error) { maxAbsValue := func(value1 int, value2 int) int { min := value1 max := value2 if value1 > value2 { min = value2 max = value1 } maxAbs := max if min < 0 && -min > max { // This is to avoid something like "int(math.Abs(float64(minBarValue)))" maxAbs = -min // (--) == (+) } return maxAbs } abs := func(value int) int { if value < 0 { return -value } return value } // =================================== VERTICAL BARS RENDERER ====================================================== type renderParams struct { repeatCount int bar Bar positiveChartPartHeight int negativeChartPartHeight int positiveChartPartWidth int negativeChartPartWidth int indent string showValue bool moveUp bool moveRight bool } renderPositiveVerticalBar := func(renderedBarRef *string, rParams renderParams) { if rParams.showValue { *renderedBarRef += Sprint(rParams.indent + strconv.Itoa(rParams.bar.Value) + rParams.indent + "\n") } for i := rParams.positiveChartPartHeight; i > 0; i-- { if i > rParams.repeatCount { *renderedBarRef += rParams.indent + " " + rParams.indent + " \n" } else { *renderedBarRef += rParams.indent + rParams.bar.Style.Sprint(p.VerticalBarCharacter) + rParams.indent + " \n" } } // Used when we draw diagram with both POSITIVE and NEGATIVE values. // In such case we separately draw top and bottom half of chart. // And we need MOVE UP positive part to top part of chart, // technically by adding empty pillars with height == height of chart's bottom part. if rParams.moveUp { for i := 0; i <= rParams.negativeChartPartHeight; i++ { *renderedBarRef += rParams.indent + " " + rParams.indent + " \n" } } } renderNegativeVerticalBar := func(renderedBarRef *string, rParams renderParams) { for i := 0; i > -rParams.negativeChartPartHeight; i-- { if i > rParams.repeatCount { *renderedBarRef += rParams.indent + rParams.bar.Style.Sprint(p.VerticalBarCharacter) + rParams.indent + " \n" } else { *renderedBarRef += rParams.indent + " " + rParams.indent + " \n" } } if rParams.showValue { *renderedBarRef += Sprint(rParams.indent + strconv.Itoa(rParams.bar.Value) + rParams.indent + "\n") } } // =================================== HORIZONTAL BARS RENDERER ==================================================== renderPositiveHorizontalBar := func(renderedBarRef *string, rParams renderParams) { if rParams.moveRight { for i := 0; i < rParams.negativeChartPartWidth; i++ { *renderedBarRef += " " } } for i := 0; i < rParams.positiveChartPartWidth; i++ { if i < rParams.repeatCount { *renderedBarRef += rParams.bar.Style.Sprint(p.HorizontalBarCharacter) } else { *renderedBarRef += " " } } if rParams.showValue { // For positive horizontal bars we add one more space before adding value, // so they will be well aligned with negative values, which have "-" sign before them *renderedBarRef += " " *renderedBarRef += " " + strconv.Itoa(rParams.bar.Value) } } renderNegativeHorizontalBar := func(renderedBarRef *string, rParams renderParams) { for i := -rParams.negativeChartPartWidth; i < 0; i++ { if i < rParams.repeatCount { *renderedBarRef += " " } else { *renderedBarRef += rParams.bar.Style.Sprint(p.HorizontalBarCharacter) } } // In order to print values well-aligned (in case when we have both - positive and negative part of chart), // we should insert an indent with width == width of positive chart part if rParams.positiveChartPartWidth > 0 { for i := 0; i < rParams.positiveChartPartWidth; i++ { *renderedBarRef += " " } } if rParams.showValue { /* This is in order to achieve this effect: 0 -15 0 -19 INSTEAD OF THIS: 0 -15 0 -19 */ if rParams.repeatCount == 0 { *renderedBarRef += " " } *renderedBarRef += " " + strconv.Itoa(rParams.bar.Value) } } // ================================================================================================================= if RawOutput { return p.getRawOutput(), nil } for i, bar := range p.Bars { if bar.Style == nil { p.Bars[i].Style = &ThemeDefault.BarStyle } if bar.LabelStyle == nil { p.Bars[i].LabelStyle = &ThemeDefault.BarLabelStyle } p.Bars[i].Label = p.Bars[i].LabelStyle.Sprint(bar.Label) } var ret string var maxLabelHeight int var maxBarValue int var minBarValue int var maxAbsBarValue int var rParams renderParams for _, bar := range p.Bars { if bar.Value > maxBarValue { maxBarValue = bar.Value } if bar.Value < minBarValue { minBarValue = bar.Value } labelHeight := len(strings.Split(bar.Label, "\n")) if labelHeight > maxLabelHeight { maxLabelHeight = labelHeight } } maxAbsBarValue = maxAbsValue(maxBarValue, minBarValue) if p.Horizontal { panels := Panels{[]Panel{{}, {}}} rParams.showValue = p.ShowValue rParams.positiveChartPartWidth = p.Width rParams.negativeChartPartWidth = p.Width // If chart will consist of two parts - positive and negative - we should recalculate max bars WIDTH in LEFT and RIGHT parts if minBarValue < 0 && maxBarValue > 0 { rParams.positiveChartPartWidth = abs(internal.MapRangeToRange(-float32(maxAbsBarValue), float32(maxAbsBarValue), -float32(p.Width)/2, float32(p.Width)/2, float32(maxBarValue))) rParams.negativeChartPartWidth = abs(internal.MapRangeToRange(-float32(maxAbsBarValue), float32(maxAbsBarValue), -float32(p.Width)/2, float32(p.Width)/2, float32(minBarValue))) } for _, bar := range p.Bars { rParams.bar = bar panels[0][0].Data += "\n" + bar.Label panels[0][1].Data += "\n" if minBarValue >= 0 { // As we don't have negative values, draw only positive (right) part of the chart: rParams.repeatCount = internal.MapRangeToRange(0, float32(maxAbsBarValue), 0, float32(p.Width), float32(bar.Value)) rParams.moveRight = false renderPositiveHorizontalBar(&panels[0][1].Data, rParams) } else if maxBarValue <= 0 { // As we have only negative values, draw only negative (left) part of the chart: rParams.repeatCount = internal.MapRangeToRange(-float32(maxAbsBarValue), 0, -float32(p.Width), 0, float32(bar.Value)) rParams.positiveChartPartWidth = 0 renderNegativeHorizontalBar(&panels[0][1].Data, rParams) } else { // We have positive and negative values, so draw both (left+right) parts of the chart: rParams.repeatCount = internal.MapRangeToRange(-float32(maxAbsBarValue), float32(maxAbsBarValue), -float32(p.Width)/2, float32(p.Width)/2, float32(bar.Value)) if bar.Value >= 0 { rParams.moveRight = true renderPositiveHorizontalBar(&panels[0][1].Data, rParams) } if bar.Value < 0 { renderNegativeHorizontalBar(&panels[0][1].Data, rParams) } } } ret, _ = DefaultPanel.WithPanels(panels).Srender() return ret, nil } else { renderedBars := make([]string, len(p.Bars)) rParams.showValue = p.ShowValue rParams.positiveChartPartHeight = p.Height rParams.negativeChartPartHeight = p.Height // If chart will consist of two parts - positive and negative - we should recalculate max bars height in top and bottom parts if minBarValue < 0 && maxBarValue > 0 { rParams.positiveChartPartHeight = abs(internal.MapRangeToRange(-float32(maxAbsBarValue), float32(maxAbsBarValue), -float32(p.Height)/2, float32(p.Height)/2, float32(maxBarValue))) rParams.negativeChartPartHeight = abs(internal.MapRangeToRange(-float32(maxAbsBarValue), float32(maxAbsBarValue), -float32(p.Height)/2, float32(p.Height)/2, float32(minBarValue))) } for i, bar := range p.Bars { var renderedBar string rParams.bar = bar rParams.indent = strings.Repeat(" ", internal.GetStringMaxWidth(RemoveColorFromString(bar.Label))/2) if minBarValue >= 0 { // As we don't have negative values, draw only positive (top) part of the chart: rParams.repeatCount = internal.MapRangeToRange(0, float32(maxAbsBarValue), 0, float32(p.Height), float32(bar.Value)) rParams.moveUp = false // Don't MOVE UP as we have ONLY positive part of chart. renderPositiveVerticalBar(&renderedBar, rParams) } else if maxBarValue <= 0 { // As we have only negative values, draw only negative (bottom) part of the chart: rParams.repeatCount = internal.MapRangeToRange(-float32(maxAbsBarValue), 0, -float32(p.Height), 0, float32(bar.Value)) renderNegativeVerticalBar(&renderedBar, rParams) } else { // We have positive and negative values, so draw both (top+bottom) parts of the chart: rParams.repeatCount = internal.MapRangeToRange(-float32(maxAbsBarValue), float32(maxAbsBarValue), -float32(p.Height)/2, float32(p.Height)/2, float32(bar.Value)) if bar.Value >= 0 { rParams.moveUp = true // MOVE UP positive part, because we have both positive and negative parts of chart. renderPositiveVerticalBar(&renderedBar, rParams) } if bar.Value < 0 { renderNegativeVerticalBar(&renderedBar, rParams) } } labelHeight := len(strings.Split(bar.Label, "\n")) renderedBars[i] = renderedBar + bar.Label + strings.Repeat("\n", maxLabelHeight-labelHeight) + " " } var maxBarHeight int for _, bar := range renderedBars { totalBarHeight := len(strings.Split(bar, "\n")) if totalBarHeight > maxBarHeight { maxBarHeight = totalBarHeight } } for i, bar := range renderedBars { totalBarHeight := len(strings.Split(bar, "\n")) if totalBarHeight < maxBarHeight { renderedBars[i] = strings.Repeat("\n", maxBarHeight-totalBarHeight) + renderedBars[i] } } for i := 0; i <= maxBarHeight; i++ { for _, barString := range renderedBars { var barLine string letterLines := strings.Split(barString, "\n") maxBarWidth := internal.GetStringMaxWidth(RemoveColorFromString(barString)) if len(letterLines) > i { barLine = letterLines[i] } letterLineLength := runewidth.StringWidth(RemoveColorFromString(barLine)) if letterLineLength < maxBarWidth { barLine += strings.Repeat(" ", maxBarWidth-letterLineLength) } ret += barLine } ret += "\n" } } return ret, nil } // Render prints the Template to the terminal. func (p BarChartPrinter) Render() error { s, _ := p.Srender() Fprintln(p.Writer, s) return nil } golang-github-pterm-pterm-0.12.79/barchart_test.go000066400000000000000000000237371465010626300220660ustar00rootroot00000000000000package pterm_test import ( "os" "testing" "github.com/MarvinJWendt/testza" "github.com/pterm/pterm" ) func TestBarChartPrinterNilPrint(t *testing.T) { proxyToDevNull() p := pterm.BarChartPrinter{} err := p.Render() if err != nil { panic(err) } } func TestBarChartPrinter_NilStylePrint(t *testing.T) { bars := pterm.Bars{ pterm.Bar{ Label: "Bar 1", Value: 5, }, pterm.Bar{ Label: "Bar 2", Value: 3, }, pterm.Bar{ Label: "Longer Label", Value: 7, }, } pterm.DefaultBarChart.WithBars(bars).Render() } // VERTICAL bars + MIXED values test func TestBarChartPrinter_RenderExample(t *testing.T) { bars := pterm.Bars{ pterm.Bar{ Label: "Bar 1", Value: 5, Style: pterm.NewStyle(pterm.FgCyan), }, pterm.Bar{ Label: "Bar 2", Value: 3, Style: pterm.NewStyle(pterm.FgCyan), }, pterm.Bar{ Label: "Long Label Example", Value: 7, Style: pterm.NewStyle(pterm.FgCyan), }, pterm.Bar{ Label: "Zero", Value: 0, Style: pterm.NewStyle(pterm.FgCyan), }, pterm.Bar{ Label: "Negative Value", Value: -4, Style: pterm.NewStyle(pterm.FgCyan), }, pterm.Bar{ Label: "NV", Value: -5, Style: pterm.NewStyle(pterm.FgCyan), }, } pterm.DefaultBarChart.WithBars(bars).Render() } // VERTICAL bars + NEGATIVE values test func TestBarChartPrinter_RenderNegativeBarValues(t *testing.T) { pterm.DefaultBarChart.WithShowValue().WithBars(pterm.Bars{ pterm.Bar{ Label: "Test", Value: -1337, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: -1000, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: -950, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: -1500, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: -10, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: -100, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, }).Render() } // VERTICAL bars + POSITIVE values test func TestBarChartPrinter_RenderPositiveBarValues(t *testing.T) { pterm.DefaultBarChart.WithShowValue().WithBars(pterm.Bars{ pterm.Bar{ Label: "Test", Value: 1000, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: 1400, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: 900, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, }).Render() } // VERTICAL bars + ZERO values test func TestBarChartPrinter_RenderZeroBarValues(t *testing.T) { pterm.DefaultBarChart.WithShowValue().WithBars(pterm.Bars{ pterm.Bar{ Label: "Test", Value: 0, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: 0, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, }).Render() } // HORIZONTAL bars + MIXED values test func TestBarChartPrinter_RenderExampleHorizontal(t *testing.T) { pterm.DefaultBarChart.WithShowValue().WithHorizontal().WithBars(pterm.Bars{ pterm.Bar{ Label: "Test", Value: 1337, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: 1000, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Zero", Value: 0, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: -800, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: -500, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, }).Render() } // HORIZONTAL bars + NEGATIVE values test func TestBarChartPrinter_RenderNegativeBarValuesHorizontal(t *testing.T) { pterm.DefaultBarChart.WithShowValue().WithHorizontal().WithBars(pterm.Bars{ pterm.Bar{ Label: "Test", Value: -999, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: -500, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: -653, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: 0, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: -20, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: -100, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: 0, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: -30, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, }).Render() } // HORIZONTAL bars + POSITIVE values test func TestBarChartPrinter_RenderPositiveBarValuesHorizontal(t *testing.T) { pterm.DefaultBarChart.WithShowValue().WithHorizontal().WithBars(pterm.Bars{ pterm.Bar{ Label: "Test", Value: 30, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: 70, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: 80, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: 90, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: 40, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: 30, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, }).Render() } // HORIZONTAL bars + ZERO values test func TestBarChartPrinter_RenderZeroBarValuesHorizontal(t *testing.T) { pterm.DefaultBarChart.WithShowValue().WithHorizontal().WithBars(pterm.Bars{ pterm.Bar{ Label: "Test", Value: 0, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: 0, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, }).Render() } func TestBarChartPrinter_RenderExampleRawOutput(t *testing.T) { pterm.DisableStyling() bars := pterm.Bars{ pterm.Bar{ Label: "Bar 1", Value: 5, Style: pterm.NewStyle(pterm.FgCyan), }, pterm.Bar{ Label: "Bar 2", Value: 3, Style: pterm.NewStyle(pterm.FgCyan), }, pterm.Bar{ Label: "Long Label Example", Value: 7, Style: pterm.NewStyle(pterm.FgCyan), }, pterm.Bar{ Label: "Zero", Value: 0, Style: pterm.NewStyle(pterm.FgCyan), }, pterm.Bar{ Label: "Negative Value", Value: -4, Style: pterm.NewStyle(pterm.FgCyan), }, pterm.Bar{ Label: "NV", Value: -5, Style: pterm.NewStyle(pterm.FgCyan), }, } pterm.DefaultBarChart.WithBars(bars).Render() pterm.EnableStyling() } func TestBarChartPrinter_RenderMultipleLineLabel(t *testing.T) { pterm.DefaultBarChart.WithShowValue().WithBars(pterm.Bars{ pterm.Bar{ Label: "Test", Value: -1337, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test\nNew Line", Value: -1337, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: -1337, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, }).Render() } func TestBarChartPrinter_RenderLowBarValues(t *testing.T) { pterm.DefaultBarChart.WithShowValue().WithBars(pterm.Bars{ pterm.Bar{ Label: "Test", Value: 1, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: 1, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, }).Render() } func TestBarChartPrinter_Render(t *testing.T) { pterm.DefaultBarChart.WithShowValue().WithBars(pterm.Bars{ pterm.Bar{ Label: "Test", Value: 1337, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: 1337, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, }).Render() } func TestBarChartPrinter_WithHorizontalBarCharacter(t *testing.T) { p := pterm.BarChartPrinter{} s := "X" p2 := p.WithHorizontalBarCharacter(s) testza.AssertEqual(t, s, p2.HorizontalBarCharacter) testza.AssertZero(t, p.HorizontalBarCharacter) } func TestBarChartPrinter_WithVerticalBarCharacter(t *testing.T) { p := pterm.BarChartPrinter{} s := "X" p2 := p.WithVerticalBarCharacter(s) testza.AssertEqual(t, s, p2.VerticalBarCharacter) testza.AssertZero(t, p.VerticalBarCharacter) } func TestBarChartPrinter_WithBars(t *testing.T) { p := pterm.BarChartPrinter{} s := pterm.Bars{ pterm.Bar{ Label: "Test", Value: 1337, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Bar{ Label: "Test", Value: 1337, Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, } p2 := p.WithBars(s) testza.AssertEqual(t, s, p2.Bars) testza.AssertZero(t, p.Bars) } func TestBarChartPrinter_WithHeight(t *testing.T) { p := pterm.BarChartPrinter{} s := 1337 p2 := p.WithHeight(s) testza.AssertEqual(t, s, p2.Height) testza.AssertZero(t, p.Height) } func TestBarChartPrinter_WithHorizontal(t *testing.T) { p := pterm.BarChartPrinter{} s := true p2 := p.WithHorizontal(s) testza.AssertEqual(t, s, p2.Horizontal) testza.AssertZero(t, p.Horizontal) } func TestBarChartPrinter_WithShowValue(t *testing.T) { p := pterm.BarChartPrinter{} s := true p2 := p.WithShowValue(s) testza.AssertEqual(t, s, p2.ShowValue) testza.AssertZero(t, p.ShowValue) } func TestBarChartPrinter_WithWidth(t *testing.T) { p := pterm.BarChartPrinter{} s := 1337 p2 := p.WithWidth(s) testza.AssertEqual(t, s, p2.Width) testza.AssertZero(t, p.Width) } func TestBarChartPrinter_WithWriter(t *testing.T) { p := pterm.BarChartPrinter{} s := os.Stderr p2 := p.WithWriter(s) testza.AssertEqual(t, s, p2.Writer) testza.AssertZero(t, p.Writer) } golang-github-pterm-pterm-0.12.79/basic_text_printer.go000066400000000000000000000076121465010626300231230ustar00rootroot00000000000000package pterm import ( "fmt" "io" ) var ( // DefaultBasicText returns a default BasicTextPrinter, which can be used to print text as is. // No default style is present for BasicTextPrinter. DefaultBasicText = BasicTextPrinter{} ) // BasicTextPrinter is the printer used to print the input as-is or as specified by user formatting. type BasicTextPrinter struct { Style *Style Writer io.Writer } // WithStyle adds a style to the printer. func (p BasicTextPrinter) WithStyle(style *Style) *BasicTextPrinter { p.Style = style return &p } func (p BasicTextPrinter) WithWriter(writer io.Writer) *BasicTextPrinter { p.Writer = writer return &p } // Sprint formats using the default formats for its operands and returns the resulting string. // Spaces are added between operands when neither is a string. func (p BasicTextPrinter) Sprint(a ...interface{}) string { if p.Style == nil { p.Style = NewStyle() } return p.Style.Sprint(a...) } // Sprintln formats using the default formats for its operands and returns the resulting string. // Spaces are always added between operands and a newline is appended. func (p BasicTextPrinter) Sprintln(a ...interface{}) string { str := fmt.Sprintln(a...) return Sprintln(p.Sprint(str)) } // Sprintf formats according to a format specifier and returns the resulting string. func (p BasicTextPrinter) Sprintf(format string, a ...interface{}) string { return p.Sprint(Sprintf(format, a...)) } // Sprintfln formats according to a format specifier and returns the resulting string. // Spaces are always added between operands and a newline is appended. func (p BasicTextPrinter) Sprintfln(format string, a ...interface{}) string { return p.Sprintf(format, a...) + "\n" } // Print formats using the default formats for its operands and writes to provided writer. // Spaces are added between operands when neither is a string. // It returns the number of bytes written and any write error encountered. func (p *BasicTextPrinter) Print(a ...interface{}) *TextPrinter { Fprint(p.Writer, p.Sprint(a...)) tp := TextPrinter(p) return &tp } // Println formats using the default formats for its operands and writes to provided writer. // Spaces are always added between operands and a newline is appended. // It returns the number of bytes written and any write error encountered. func (p *BasicTextPrinter) Println(a ...interface{}) *TextPrinter { Fprint(p.Writer, p.Sprintln(a...)) tp := TextPrinter(p) return &tp } // Printf formats according to a format specifier and writes to provided writer. // It returns the number of bytes written and any write error encountered. func (p *BasicTextPrinter) Printf(format string, a ...interface{}) *TextPrinter { Fprint(p.Writer, p.Sprintf(format, a...)) tp := TextPrinter(p) return &tp } // Printfln formats according to a format specifier and writes to provided writer. // Spaces are always added between operands and a newline is appended. // It returns the number of bytes written and any write error encountered. func (p *BasicTextPrinter) Printfln(format string, a ...interface{}) *TextPrinter { Fprint(p.Writer, p.Sprintfln(format, a...)) tp := TextPrinter(p) return &tp } // PrintOnError prints every error which is not nil. // If every error is nil, nothing will be printed. // This can be used for simple error checking. func (p *BasicTextPrinter) PrintOnError(a ...interface{}) *TextPrinter { for _, arg := range a { if err, ok := arg.(error); ok { if err != nil { p.Println(err) } } } tp := TextPrinter(p) return &tp } // PrintOnErrorf wraps every error which is not nil and prints it. // If every error is nil, nothing will be printed. // This can be used for simple error checking. func (p *BasicTextPrinter) PrintOnErrorf(format string, a ...interface{}) *TextPrinter { for _, arg := range a { if err, ok := arg.(error); ok { if err != nil { p.Println(fmt.Errorf(format, err)) } } } tp := TextPrinter(p) return &tp } golang-github-pterm-pterm-0.12.79/basic_text_printer_test.go000066400000000000000000000050421465010626300241550ustar00rootroot00000000000000package pterm_test import ( "errors" "io" "os" "testing" "github.com/MarvinJWendt/testza" "github.com/pterm/pterm" ) func TestBasicTextPrinterNilPrint(t *testing.T) { proxyToDevNull() p := pterm.BasicTextPrinter{} p.Println("Hello, World!") } func TestBasicTextPrinterPrintMethods(t *testing.T) { p := pterm.DefaultBasicText t.Run("Print", func(t *testing.T) { testPrintContains(t, func(w io.Writer, a interface{}) { p.Print(a) }) }) t.Run("Printf", func(t *testing.T) { testPrintfContains(t, func(w io.Writer, format string, a interface{}) { p.Printf(format, a) }) }) t.Run("Printfln", func(t *testing.T) { testPrintflnContains(t, func(w io.Writer, format string, a interface{}) { p.Printfln(format, a) }) }) t.Run("Println", func(t *testing.T) { testPrintlnContains(t, func(w io.Writer, a interface{}) { p.Println(a) }) }) t.Run("Sprint", func(t *testing.T) { testSprintContains(t, func(a interface{}) string { return p.Sprint(a) }) }) t.Run("Sprintf", func(t *testing.T) { testSprintfContains(t, func(format string, a interface{}) string { return p.Sprintf(format, a) }) }) t.Run("Sprintfln", func(t *testing.T) { testSprintflnContains(t, func(format string, a interface{}) string { return p.Sprintfln(format, a) }) }) t.Run("Sprintln", func(t *testing.T) { testSprintlnContains(t, func(a interface{}) string { return p.Sprintln(a) }) }) t.Run("PrintOnError", func(t *testing.T) { result := captureStdout(func(w io.Writer) { p.PrintOnError(errors.New("hello world")) }) testza.AssertContains(t, result, "hello world") }) t.Run("PrintIfError_WithoutError", func(t *testing.T) { result := captureStdout(func(w io.Writer) { p.PrintOnError(nil) }) testza.AssertZero(t, result) }) t.Run("PrintOnErrorf", func(t *testing.T) { result := captureStdout(func(w io.Writer) { p.PrintOnErrorf("wrapping error : %w", errors.New("hello world")) }) testza.AssertContains(t, result, "hello world") }) t.Run("PrintIfError_WithoutErrorf", func(t *testing.T) { result := captureStdout(func(w io.Writer) { p.PrintOnErrorf("", nil) }) testza.AssertZero(t, result) }) } func TestBasicTextPrinter_WithStyle(t *testing.T) { s := pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold) p := pterm.BasicTextPrinter{} p2 := p.WithStyle(s) testza.AssertEqual(t, s, p2.Style) } func TestBasicTextPrinter_WithWriter(t *testing.T) { p := pterm.BasicTextPrinter{} s := os.Stderr p2 := p.WithWriter(s) testza.AssertEqual(t, s, p2.Writer) testza.AssertZero(t, p.Writer) } golang-github-pterm-pterm-0.12.79/bigtext_printer.go000066400000000000000000000245111465010626300224410ustar00rootroot00000000000000package pterm import ( "io" "strings" "github.com/gookit/color" "github.com/mattn/go-runewidth" "github.com/pterm/pterm/internal" ) // Letters is a slice of Letter. type Letters []Letter // Letter is an object, which holds a string and a specific Style for it. type Letter struct { String string Style *Style RGB RGB } // WithStyle returns a new Letter with a specific Style. func (l Letter) WithStyle(style *Style) *Letter { l.Style = style return &l } // WithRGB returns a new Letter with a specific RGB color (overwrites style). func (l Letter) WithRGB(rgb RGB) *Letter { l.RGB = rgb return &l } // WithString returns a new Letter with a specific String. func (l Letter) WithString(s string) *Letter { l.String = s return &l } // BigTextPrinter renders big text. // You can use this as title screen for your application. type BigTextPrinter struct { // BigCharacters holds the map from a normal character to it's big version. BigCharacters map[string]string Letters Letters Writer io.Writer } // WithBigCharacters returns a new BigTextPrinter with specific BigCharacters. func (p BigTextPrinter) WithBigCharacters(chars map[string]string) *BigTextPrinter { p.BigCharacters = chars return &p } // WithLetters returns a new BigTextPrinter with specific Letters func (p BigTextPrinter) WithLetters(letters ...Letters) *BigTextPrinter { l := Letters{} for _, letter := range letters { l = append(l, letter...) } p.Letters = l return &p } // WithWriter sets the custom Writer. func (p BigTextPrinter) WithWriter(writer io.Writer) *BigTextPrinter { p.Writer = writer return &p } // Srender renders the BigText as a string. func (p BigTextPrinter) Srender() (string, error) { var ret string if RawOutput { for _, letter := range p.Letters { ret += letter.String } return ret, nil } var bigLetters Letters for _, l := range p.Letters { if val, ok := p.BigCharacters[l.String]; ok { bigLetters = append(bigLetters, Letter{ String: val, Style: l.Style, RGB: l.RGB, }) } } var maxHeight int for _, l := range bigLetters { h := strings.Count(l.String, "\n") if h > maxHeight { maxHeight = h } } for i := 0; i <= maxHeight; i++ { for _, letter := range bigLetters { var letterLine string letterLines := strings.Split(letter.String, "\n") maxLetterWidth := internal.GetStringMaxWidth(letter.String) if len(letterLines) > i { letterLine = letterLines[i] } letterLineLength := runewidth.StringWidth(letterLine) if letterLineLength < maxLetterWidth { letterLine += strings.Repeat(" ", maxLetterWidth-letterLineLength) } if letter.RGB != (RGB{}) && (color.IsSupportRGBColor() || internal.RunsInCi()) { ret += letter.RGB.Sprint(letterLine) } else { ret += letter.Style.Sprint(letterLine) } } ret += "\n" } return ret, nil } // Render prints the BigText to the terminal. func (p BigTextPrinter) Render() error { s, _ := p.Srender() Fprintln(p.Writer, s) return nil } // DefaultBigText contains default values for BigTextPrinter. var DefaultBigText = BigTextPrinter{ BigCharacters: map[string]string{ "a": ` █████ ██ ██ ███████ ██ ██ ██ ██ `, "A": ` █████ ██ ██ ███████ ██ ██ ██ ██ `, "b": `██████ ██ ██ ██████ ██ ██ ██████`, "B": `██████ ██ ██ ██████ ██ ██ ██████`, "c": ` ██████ ██ ██ ██ ██████`, "C": ` ██████ ██ ██ ██ ██████`, "d": `██████ ██ ██ ██ ██ ██ ██ ██████ `, "D": `██████ ██ ██ ██ ██ ██ ██ ██████ `, "e": `███████ ██ █████ ██ ███████`, "E": `███████ ██ █████ ██ ███████`, "f": `███████ ██ █████ ██ ██ `, "F": `███████ ██ █████ ██ ██ `, "g": ` ██████ ██ ██ ███ ██ ██ ██████ `, "G": ` ██████ ██ ██ ███ ██ ██ ██████ `, "h": `██ ██ ██ ██ ███████ ██ ██ ██ ██ `, "H": `██ ██ ██ ██ ███████ ██ ██ ██ ██ `, "i": `██ ██ ██ ██ ██`, "I": `██ ██ ██ ██ ██`, "j": ` ██ ██ ██ ██ ██ █████ `, "J": ` ██ ██ ██ ██ ██ █████ `, "k": `██ ██ ██ ██ █████ ██ ██ ██ ██`, "K": `██ ██ ██ ██ █████ ██ ██ ██ ██`, "l": `██ ██ ██ ██ ███████ `, "L": `██ ██ ██ ██ ███████ `, "m": `███ ███ ████ ████ ██ ████ ██ ██ ██ ██ ██ ██`, "M": `███ ███ ████ ████ ██ ████ ██ ██ ██ ██ ██ ██`, "n": `███ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ████`, "N": `███ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ████`, "o": ` ██████ ██ ██ ██ ██ ██ ██ ██████ `, "O": ` ██████ ██ ██ ██ ██ ██ ██ ██████ `, "p": `██████ ██ ██ ██████ ██ ██ `, "P": `██████ ██ ██ ██████ ██ ██ `, "q": ` ██████ ██ ██ ██ ██ ██ ▄▄ ██ ██████ ▀▀ `, "Q": ` ██████ ██ ██ ██ ██ ██ ▄▄ ██ ██████ ▀▀ `, "r": `██████ ██ ██ ██████ ██ ██ ██ ██`, "R": `██████ ██ ██ ██████ ██ ██ ██ ██`, "s": `███████ ██ ███████ ██ ███████`, "S": `███████ ██ ███████ ██ ███████`, "t": `████████ ██ ██ ██ ██ `, "T": `████████ ██ ██ ██ ██ `, "u": `██ ██ ██ ██ ██ ██ ██ ██ ██████ `, "U": `██ ██ ██ ██ ██ ██ ██ ██ ██████ `, "v": `██ ██ ██ ██ ██ ██ ██ ██ ████ `, "V": `██ ██ ██ ██ ██ ██ ██ ██ ████ `, "w": `██ ██ ██ ██ ██ █ ██ ██ ███ ██ ███ ███ `, "W": `██ ██ ██ ██ ██ █ ██ ██ ███ ██ ███ ███ `, "x": `██ ██ ██ ██ ███ ██ ██ ██ ██ `, "X": `██ ██ ██ ██ ███ ██ ██ ██ ██ `, "y": `██ ██ ██ ██ ████ ██ ██ `, "Y": `██ ██ ██ ██ ████ ██ ██ `, "z": `███████ ███ ███ ███ ███████`, "Z": `███████ ███ ███ ███ ███████`, "0": ` ██████ ██ ████ ██ ██ ██ ████ ██ ██████ `, "1": ` ██ ███ ██ ██ ██ `, "2": `██████ ██ █████ ██ ███████ `, "3": `██████ ██ █████ ██ ██████ `, "4": `██ ██ ██ ██ ███████ ██ ██ `, "5": `███████ ██ ███████ ██ ███████`, "6": ` ██████ ██ ███████ ██ ██ ██████ `, "7": `███████ ██ ██ ██ ██`, "8": ` █████ ██ ██ █████ ██ ██ █████ `, "9": ` █████ ██ ██ ██████ ██ █████ `, " ": " ", "!": `██ ██ ██ ██ `, "$": `▄▄███▄▄· ██ ███████ ██ ███████ ▀▀▀ `, "%": `██ ██ ██ ██ ██ ██ ██`, "/": ` ██ ██ ██ ██ ██ `, "(": ` ██ ██ ██ ██ ██ `, ")": `██ ██ ██ ██ ██ `, "?": `██████ ██ ▄███ ▀▀ ██ `, "[": `███ ██ ██ ██ ███`, "]": `███ ██ ██ ██ ███ `, ".": ` ██`, ",": ` ▄█`, "-": ` █████ `, "<": ` ██ ██ ██ ██ ██ `, ">": `██ ██ ██ ██ ██ `, "*": ` ▄ ██ ▄ ████ ▀ ██ ▀ `, "#": ` ██ ██ ████████ ██ ██ ████████ ██ ██ `, "_": ` ███████ `, ":": ` ██ ██ `, "°": ` ████ ██ ██ ████ `, }, } golang-github-pterm-pterm-0.12.79/bigtext_printer_test.go000066400000000000000000000073161465010626300235040ustar00rootroot00000000000000package pterm_test import ( "fmt" "os" "strings" "testing" "github.com/MarvinJWendt/testza" "github.com/pterm/pterm" ) func TestBigTextPrinterNilPrint(t *testing.T) { p := pterm.BigTextPrinter{} p.Render() } func TestBigTextPrinter_Render(t *testing.T) { printer := pterm.DefaultBigText.WithLetters(pterm.NewLettersFromString("Hello")) content, err := printer.Srender() testza.AssertNoError(t, err) testza.AssertNotZero(t, content) } func TestBigTextPrinter_RenderRGB(t *testing.T) { printer := pterm.DefaultBigText.WithLetters(pterm.NewLettersFromStringWithRGB("Hello", pterm.NewRGB(255, 0, 0))) content, err := printer.Srender() testza.AssertNoError(t, err) testza.AssertNotZero(t, content) } func TestBigTextPrinter_RenderRawOutput(t *testing.T) { printer := pterm.DefaultBigText.WithLetters(pterm.NewLettersFromString("Hello")) pterm.DisableStyling() content, err := printer.Srender() pterm.EnableStyling() testza.AssertNoError(t, err) testza.AssertNotZero(t, content) } func TestBigTextPrinter_WithBigCharacters(t *testing.T) { e := map[string]string{"a": "b", "c": "d"} p := pterm.BigTextPrinter{} p2 := p.WithBigCharacters(e) testza.AssertEqual(t, e, p2.BigCharacters) testza.AssertZero(t, p.BigCharacters) } func TestBigTextPrinter_WithLetters(t *testing.T) { e := pterm.Letters{ pterm.Letter{ String: "test", Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Letter{ String: "test2", Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, } p := pterm.BigTextPrinter{} p2 := p.WithLetters(e) testza.AssertEqual(t, e, p2.Letters) testza.AssertZero(t, p.Letters) } func TestLetter_WithString(t *testing.T) { e := "Hello, World!" p := pterm.Letter{} p2 := p.WithString(e) testza.AssertEqual(t, e, p2.String) testza.AssertZero(t, p.String) } func TestLetter_WithStyle(t *testing.T) { p := pterm.Letter{} s := pterm.NewStyle(pterm.FgRed, pterm.BgRed, pterm.Bold) p2 := p.WithStyle(s) testza.AssertEqual(t, s, p2.Style) testza.AssertZero(t, p.Style) } func TestLetter_WithRGB(t *testing.T) { p := pterm.Letter{} rgb := pterm.NewRGB(0, 0, 0) p2 := p.WithRGB(rgb) testza.AssertEqual(t, rgb, p2.RGB) testza.AssertZero(t, p.RGB) } func TestNewLettersFromText(t *testing.T) { e := pterm.Letters{ pterm.Letter{ String: "a", Style: &pterm.ThemeDefault.LetterStyle, }, pterm.Letter{ String: "b", Style: &pterm.ThemeDefault.LetterStyle, }, } p := pterm.NewLettersFromString("ab") testza.AssertEqual(t, e, p) } func TestNewLettersFromTextWithStyle(t *testing.T) { e := pterm.Letters{ pterm.Letter{ String: "a", Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, pterm.Letter{ String: "b", Style: pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold), }, } p := pterm.NewLettersFromStringWithStyle("ab", pterm.NewStyle(pterm.FgRed, pterm.BgBlue, pterm.Bold)) testza.AssertEqual(t, e, p) } func TestNewLettersFromTextWithRGB(t *testing.T) { e := pterm.Letters{ pterm.Letter{ String: "a", Style: pterm.NewStyle(), RGB: pterm.NewRGB(0, 0, 0), }, pterm.Letter{ String: "b", Style: pterm.NewStyle(), RGB: pterm.NewRGB(0, 0, 0), }, } p := pterm.NewLettersFromStringWithRGB("ab", pterm.NewRGB(0, 0, 0)) testza.AssertEqual(t, e, p) } func TestDefaultLettersMaxHeight(t *testing.T) { maxHeight := 5 chars := pterm.DefaultBigText.BigCharacters for s, l := range chars { h := strings.Count(l, "\n") testza.AssertTrue(t, h <= maxHeight, fmt.Sprintf("'%s' is too high", s)) } } func TestBigTextPrinter_WithWriter(t *testing.T) { p := pterm.BigTextPrinter{} s := os.Stderr p2 := p.WithWriter(s) testza.AssertEqual(t, s, p2.Writer) testza.AssertZero(t, p.Writer) } golang-github-pterm-pterm-0.12.79/box_printer.go000066400000000000000000000323621465010626300215660ustar00rootroot00000000000000package pterm import ( "fmt" "io" "strings" "github.com/mattn/go-runewidth" "github.com/pterm/pterm/internal" ) // BoxPrinter is able to render a box around printables. type BoxPrinter struct { Title string TitleTopLeft bool TitleTopRight bool TitleTopCenter bool TitleBottomLeft bool TitleBottomRight bool TitleBottomCenter bool TextStyle *Style VerticalString string BoxStyle *Style HorizontalString string TopRightCornerString string TopLeftCornerString string BottomLeftCornerString string BottomRightCornerString string TopPadding int BottomPadding int RightPadding int LeftPadding int Writer io.Writer } // DefaultBox is the default BoxPrinter. var DefaultBox = BoxPrinter{ VerticalString: "|", TopRightCornerString: "└", TopLeftCornerString: "┘", BottomLeftCornerString: "┐", BottomRightCornerString: "┌", HorizontalString: "─", BoxStyle: &ThemeDefault.BoxStyle, TextStyle: &ThemeDefault.BoxTextStyle, RightPadding: 1, LeftPadding: 1, TopPadding: 0, BottomPadding: 0, TitleTopLeft: true, } // WithTitle returns a new box with a specific Title. func (p BoxPrinter) WithTitle(str string) *BoxPrinter { p.Title = str return &p } // WithTitleTopLeft returns a new box with a specific Title alignment. func (p BoxPrinter) WithTitleTopLeft(b ...bool) *BoxPrinter { b2 := internal.WithBoolean(b) p.TitleTopLeft = b2 p.TitleTopRight = false p.TitleTopCenter = false p.TitleBottomLeft = false p.TitleBottomRight = false p.TitleBottomCenter = false return &p } // WithTitleTopRight returns a new box with a specific Title alignment. func (p BoxPrinter) WithTitleTopRight(b ...bool) *BoxPrinter { b2 := internal.WithBoolean(b) p.TitleTopLeft = false p.TitleTopRight = b2 p.TitleTopCenter = false p.TitleBottomLeft = false p.TitleBottomRight = false p.TitleBottomCenter = false return &p } // WithTitleTopCenter returns a new box with a specific Title alignment. func (p BoxPrinter) WithTitleTopCenter(b ...bool) *BoxPrinter { b2 := internal.WithBoolean(b) p.TitleTopLeft = false p.TitleTopRight = false p.TitleTopCenter = b2 p.TitleBottomLeft = false p.TitleBottomRight = false p.TitleBottomCenter = false return &p } // WithTitleBottomLeft returns a new box with a specific Title alignment. func (p BoxPrinter) WithTitleBottomLeft(b ...bool) *BoxPrinter { b2 := internal.WithBoolean(b) p.TitleTopLeft = false p.TitleTopRight = false p.TitleTopCenter = false p.TitleBottomLeft = b2 p.TitleBottomRight = false p.TitleBottomCenter = false return &p } // WithTitleBottomRight returns a new box with a specific Title alignment. func (p BoxPrinter) WithTitleBottomRight(b ...bool) *BoxPrinter { b2 := internal.WithBoolean(b) p.TitleTopLeft = false p.TitleTopRight = false p.TitleTopCenter = false p.TitleBottomLeft = false p.TitleBottomRight = b2 p.TitleBottomCenter = false return &p } // WithTitleBottomCenter returns a new box with a specific Title alignment. func (p BoxPrinter) WithTitleBottomCenter(b ...bool) *BoxPrinter { b2 := internal.WithBoolean(b) p.TitleTopLeft = false p.TitleTopRight = false p.TitleTopCenter = false p.TitleBottomLeft = false p.TitleBottomRight = false p.TitleBottomCenter = b2 return &p } // WithBoxStyle returns a new box with a specific box Style. func (p BoxPrinter) WithBoxStyle(style *Style) *BoxPrinter { p.BoxStyle = style return &p } // WithTextStyle returns a new box with a specific text Style. func (p BoxPrinter) WithTextStyle(style *Style) *BoxPrinter { p.TextStyle = style return &p } // WithTopRightCornerString returns a new box with a specific TopRightCornerString. func (p BoxPrinter) WithTopRightCornerString(str string) *BoxPrinter { p.TopRightCornerString = str return &p } // WithTopLeftCornerString returns a new box with a specific TopLeftCornerString. func (p BoxPrinter) WithTopLeftCornerString(str string) *BoxPrinter { p.TopLeftCornerString = str return &p } // WithBottomRightCornerString returns a new box with a specific BottomRightCornerString. func (p BoxPrinter) WithBottomRightCornerString(str string) *BoxPrinter { p.BottomRightCornerString = str return &p } // WithBottomLeftCornerString returns a new box with a specific BottomLeftCornerString. func (p BoxPrinter) WithBottomLeftCornerString(str string) *BoxPrinter { p.BottomLeftCornerString = str return &p } // WithVerticalString returns a new box with a specific VerticalString. func (p BoxPrinter) WithVerticalString(str string) *BoxPrinter { p.VerticalString = str return &p } // WithHorizontalString returns a new box with a specific HorizontalString. func (p BoxPrinter) WithHorizontalString(str string) *BoxPrinter { p.HorizontalString = str return &p } // WithTopPadding returns a new box with a specific TopPadding. func (p BoxPrinter) WithTopPadding(padding int) *BoxPrinter { if padding < 0 { padding = 0 } p.TopPadding = padding return &p } // WithBottomPadding returns a new box with a specific BottomPadding. func (p BoxPrinter) WithBottomPadding(padding int) *BoxPrinter { if padding < 0 { padding = 0 } p.BottomPadding = padding return &p } // WithRightPadding returns a new box with a specific RightPadding. func (p BoxPrinter) WithRightPadding(padding int) *BoxPrinter { if padding < 0 { padding = 0 } p.RightPadding = padding return &p } // WithLeftPadding returns a new box with a specific LeftPadding. func (p BoxPrinter) WithLeftPadding(padding int) *BoxPrinter { if padding < 0 { padding = 0 } p.LeftPadding = padding return &p } // WithWriter sets the custom Writer. func (p BoxPrinter) WithWriter(writer io.Writer) *BoxPrinter { p.Writer = writer return &p } // Sprint formats using the default formats for its operands and returns the resulting string. // Spaces are added between operands when neither is a string. func (p BoxPrinter) Sprint(a ...interface{}) string { if p.BoxStyle == nil { p.BoxStyle = &ThemeDefault.BoxStyle } if p.TextStyle == nil { p.TextStyle = &ThemeDefault.BoxTextStyle } maxWidth := internal.GetStringMaxWidth(Sprint(a...)) var topLine string var bottomLine string if p.Title == "" { topLine = p.BoxStyle.Sprint(p.BottomRightCornerString) + strings.Repeat(p.BoxStyle.Sprint(p.HorizontalString), maxWidth+p.LeftPadding+p.RightPadding) + p.BoxStyle.Sprint(p.BottomLeftCornerString) bottomLine = p.BoxStyle.Sprint(p.TopRightCornerString) + strings.Repeat(p.BoxStyle.Sprint(p.HorizontalString), maxWidth+p.LeftPadding+p.RightPadding) + p.BoxStyle.Sprint(p.TopLeftCornerString) } else { p.Title = strings.ReplaceAll(p.Title, "\n", " ") if (maxWidth + p.RightPadding + p.LeftPadding - 4) < internal.GetStringMaxWidth(p.Title) { p.RightPadding = internal.GetStringMaxWidth(p.Title) - (maxWidth + p.RightPadding + p.LeftPadding - 5) } if p.TitleTopLeft { topLine = p.BoxStyle.Sprint(p.BottomRightCornerString) + internal.AddTitleToLine(p.Title, p.BoxStyle.Sprint(p.HorizontalString), maxWidth+p.LeftPadding+p.RightPadding, true) + p.BoxStyle.Sprint(p.BottomLeftCornerString) bottomLine = p.BoxStyle.Sprint(p.TopRightCornerString) + strings.Repeat(p.BoxStyle.Sprint(p.HorizontalString), maxWidth+p.LeftPadding+p.RightPadding) + p.BoxStyle.Sprint(p.TopLeftCornerString) } else if p.TitleTopRight { topLine = p.BoxStyle.Sprint(p.BottomRightCornerString) + internal.AddTitleToLine(p.Title, p.BoxStyle.Sprint(p.HorizontalString), maxWidth+p.LeftPadding+p.RightPadding, false) + p.BoxStyle.Sprint(p.BottomLeftCornerString) bottomLine = p.BoxStyle.Sprint(p.TopRightCornerString) + strings.Repeat(p.BoxStyle.Sprint(p.HorizontalString), maxWidth+p.LeftPadding+p.RightPadding) + p.BoxStyle.Sprint(p.TopLeftCornerString) } else if p.TitleTopCenter { topLine = p.BoxStyle.Sprint(p.BottomRightCornerString) + internal.AddTitleToLineCenter(p.Title, p.BoxStyle.Sprint(p.HorizontalString), maxWidth+p.LeftPadding+p.RightPadding) + p.BoxStyle.Sprint(p.BottomLeftCornerString) bottomLine = p.BoxStyle.Sprint(p.TopRightCornerString) + strings.Repeat(p.BoxStyle.Sprint(p.HorizontalString), maxWidth+p.LeftPadding+p.RightPadding) + p.BoxStyle.Sprint(p.TopLeftCornerString) } else if p.TitleBottomLeft { topLine = p.BoxStyle.Sprint(p.BottomRightCornerString) + strings.Repeat(p.BoxStyle.Sprint(p.HorizontalString), maxWidth+p.LeftPadding+p.RightPadding) + p.BoxStyle.Sprint(p.BottomLeftCornerString) bottomLine = p.BoxStyle.Sprint(p.TopRightCornerString) + internal.AddTitleToLine(p.Title, p.BoxStyle.Sprint(p.HorizontalString), maxWidth+p.LeftPadding+p.RightPadding, true) + p.BoxStyle.Sprint(p.TopLeftCornerString) } else if p.TitleBottomRight { topLine = p.BoxStyle.Sprint(p.BottomRightCornerString) + strings.Repeat(p.BoxStyle.Sprint(p.HorizontalString), maxWidth+p.LeftPadding+p.RightPadding) + p.BoxStyle.Sprint(p.BottomLeftCornerString) bottomLine = p.BoxStyle.Sprint(p.TopRightCornerString) + internal.AddTitleToLine(p.Title, p.BoxStyle.Sprint(p.HorizontalString), maxWidth+p.LeftPadding+p.RightPadding, false) + p.BoxStyle.Sprint(p.TopLeftCornerString) } else if p.TitleBottomCenter { topLine = p.BoxStyle.Sprint(p.BottomRightCornerString) + strings.Repeat(p.BoxStyle.Sprint(p.HorizontalString), maxWidth+p.LeftPadding+p.RightPadding) + p.BoxStyle.Sprint(p.BottomLeftCornerString) bottomLine = p.BoxStyle.Sprint(p.TopRightCornerString) + internal.AddTitleToLineCenter(p.Title, p.BoxStyle.Sprint(p.HorizontalString), maxWidth+p.LeftPadding+p.RightPadding) + p.BoxStyle.Sprint(p.TopLeftCornerString) } } boxString := strings.Repeat("\n", p.TopPadding) + Sprint(a...) + strings.Repeat("\n", p.BottomPadding) ss := strings.Split(boxString, "\n") for i, s2 := range ss { if runewidth.StringWidth(RemoveColorFromString(s2)) < maxWidth { ss[i] = p.BoxStyle.Sprint(p.VerticalString) + strings.Repeat(" ", p.LeftPadding) + p.TextStyle.Sprint(s2) + strings.Repeat(" ", maxWidth-runewidth.StringWidth(RemoveColorFromString(s2))+p.RightPadding) + p.BoxStyle.Sprint(p.VerticalString) } else { ss[i] = p.BoxStyle.Sprint(p.VerticalString) + strings.Repeat(" ", p.LeftPadding) + p.TextStyle.Sprint(s2) + strings.Repeat(" ", p.RightPadding) + p.BoxStyle.Sprint(p.VerticalString) } } return topLine + "\n" + strings.Join(ss, "\n") + "\n" + bottomLine } // Sprintln formats using the default formats for its operands and returns the resulting string. // Spaces are always added between operands and a newline is appended. func (p BoxPrinter) Sprintln(a ...interface{}) string { return p.Sprint(strings.TrimSuffix(Sprintln(a...), "\n")) + "\n" } // Sprintf formats according to a format specifier and returns the resulting string. func (p BoxPrinter) Sprintf(format string, a ...interface{}) string { return p.Sprint(Sprintf(format, a...)) } // Sprintfln formats according to a format specifier and returns the resulting string. // Spaces are always added between operands and a newline is appended. func (p BoxPrinter) Sprintfln(format string, a ...interface{}) string { return p.Sprintf(format, a...) + "\n" } // Print formats using the default formats for its operands and writes to standard output. // Spaces are added between operands when neither is a string. // It returns the number of bytes written and any write error encountered. func (p BoxPrinter) Print(a ...interface{}) *TextPrinter { Fprint(p.Writer, p.Sprint(a...)) tp := TextPrinter(p) return &tp } // Println formats using the default formats for its operands and writes to standard output. // Spaces are always added between operands and a newline is appended. // It returns the number of bytes written and any write error encountered. func (p BoxPrinter) Println(a ...interface{}) *TextPrinter { Fprint(p.Writer, p.Sprintln(a...)) tp := TextPrinter(p) return &tp } // Printf formats according to a format specifier and writes to standard output. // It returns the number of bytes written and any write error encountered. func (p BoxPrinter) Printf(format string, a ...interface{}) *TextPrinter { Fprint(p.Writer, p.Sprintf(format, a...)) tp := TextPrinter(p) return &tp } // Printfln formats according to a format specifier and writes to standard output. // Spaces are always added between operands and a newline is appended. // It returns the number of bytes written and any write error encountered. func (p BoxPrinter) Printfln(format string, a ...interface{}) *TextPrinter { Fprint(p.Writer, p.Sprintfln(format, a...)) tp := TextPrinter(p) return &tp } // PrintOnError prints every error which is not nil. // If every error is nil, nothing will be printed. // This can be used for simple error checking. func (p BoxPrinter) PrintOnError(a ...interface{}) *TextPrinter { for _, arg := range a { if err, ok := arg.(error); ok { if err != nil { p.Println(err) } } } tp := TextPrinter(p) return &tp } // PrintOnErrorf wraps every error which is not nil and prints it. // If every error is nil, nothing will be printed. // This can be used for simple error checking. func (p BoxPrinter) PrintOnErrorf(format string, a ...interface{}) *TextPrinter { for _, arg := range a { if err, ok := arg.(error); ok { if err != nil { p.Println(fmt.Errorf(format, err)) } } } tp := TextPrinter(p) return &tp } golang-github-pterm-pterm-0.12.79/box_printer_test.go000066400000000000000000000207741465010626300226310ustar00rootroot00000000000000package pterm_test import ( "errors" "io" "os" "testing" "github.com/MarvinJWendt/testza" "github.com/pterm/pterm" ) func TestBoxPrinterNilPrint(t *testing.T) { p := pterm.BoxPrinter{} p.Println("Hello, World!") } func TestBoxPrinterPrintMethods(t *testing.T) { p := pterm.DefaultBox t.Run("Print", func(t *testing.T) { testPrintContains(t, func(w io.Writer, a interface{}) { p.Print(a) }) }) t.Run("Printf", func(t *testing.T) { testPrintfContains(t, func(w io.Writer, format string, a interface{}) { p.Printf(format, a) }) }) t.Run("Printfln", func(t *testing.T) { testPrintflnContains(t, func(w io.Writer, format string, a interface{}) { p.Printfln(format, a) }) }) t.Run("Println", func(t *testing.T) { testPrintlnContains(t, func(w io.Writer, a interface{}) { p.Println(a) }) }) t.Run("Sprint", func(t *testing.T) { testSprintContains(t, func(a interface{}) string { return p.Sprint(a) }) }) t.Run("SprintWithTitle", func(t *testing.T) { testSprintContains(t, func(a interface{}) string { return p.WithTitle("a").Sprint(a) }) }) t.Run("Sprintf", func(t *testing.T) { testSprintfContains(t, func(format string, a interface{}) string { return p.Sprintf(format, a) }) }) t.Run("Sprintfln", func(t *testing.T) { testSprintflnContains(t, func(format string, a interface{}) string { return p.Sprintfln(format, a) }) }) t.Run("Sprintln", func(t *testing.T) { testSprintlnContains(t, func(a interface{}) string { return p.Sprintln(a) }) }) t.Run("SprintMultipleLines", func(t *testing.T) { testSprintContains(t, func(a interface{}) string { return p.Sprint("testing\ntesting2" + pterm.Sprint(a)) }) }) t.Run("PrintOnError", func(t *testing.T) { result := captureStdout(func(w io.Writer) { p.PrintOnError(errors.New("hello world")) }) testza.AssertContains(t, result, "hello world") }) t.Run("PrintIfError_WithoutError", func(t *testing.T) { result := captureStdout(func(w io.Writer) { p.PrintOnError(nil) }) testza.AssertZero(t, result) }) t.Run("PrintOnErrorf", func(t *testing.T) { result := captureStdout(func(w io.Writer) { p.PrintOnErrorf("wrapping error : %w", errors.New("hello world")) }) testza.AssertContains(t, result, "hello world") }) t.Run("PrintIfError_WithoutErrorf", func(t *testing.T) { result := captureStdout(func(w io.Writer) { p.PrintOnErrorf("", nil) }) testza.AssertZero(t, result) }) } func TestBoxPrinter_WithBottomLeftCornerString(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithBottomLeftCornerString("-") testza.AssertEqual(t, "-", p2.BottomLeftCornerString) testza.AssertZero(t, p.BottomLeftCornerString) } func TestBoxPrinter_WithBottomPadding(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithBottomPadding(5) testza.AssertEqual(t, 5, p2.BottomPadding) testza.AssertZero(t, p.BottomPadding) } func TestBoxPrinter_WithBottomRightCornerString(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithBottomRightCornerString("-") testza.AssertEqual(t, "-", p2.BottomRightCornerString) testza.AssertZero(t, p.BottomRightCornerString) } func TestBoxPrinter_WithTitle(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithTitle("-") testza.AssertEqual(t, "-", p2.Title) testza.AssertZero(t, p.Title) } func TestBoxPrinter_WithTitleTopLeft(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithTitleTopLeft() testza.AssertEqual(t, true, p2.TitleTopLeft) testza.AssertEqual(t, false, p.TitleTopLeft) } func TestBoxPrinter_WithTitleTopRight(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithTitleTopRight() testza.AssertEqual(t, true, p2.TitleTopRight) testza.AssertEqual(t, false, p.TitleTopRight) } func TestBoxPrinter_WithTitleTopCenter(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithTitleTopCenter() testza.AssertEqual(t, true, p2.TitleTopCenter) testza.AssertEqual(t, false, p.TitleTopCenter) } func TestBoxPrinter_WithTitleBottomRight(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithTitleBottomRight() testza.AssertEqual(t, true, p2.TitleBottomRight) testza.AssertEqual(t, false, p.TitleBottomRight) } func TestBoxPrinter_WithTitleBottomLeft(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithTitleBottomLeft() testza.AssertEqual(t, true, p2.TitleBottomLeft) testza.AssertEqual(t, false, p.TitleBottomLeft) } func TestBoxPrinter_WithTitleBottomCenter(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithTitleBottomCenter() testza.AssertEqual(t, true, p2.TitleBottomCenter) testza.AssertEqual(t, false, p.TitleBottomCenter) } func TestBoxPrinter_WithTitleWithTitleBottomLeft(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithTitleBottomLeft().WithTitle("a").Sprint("Lorem Ipsum") testza.AssertContains(t, p2, "Lorem Ipsum") } func TestBoxPrinter_WithTitleWithTitleTopLeft(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithTitleTopLeft().WithTitle("a").Sprint("Lorem Ipsum") testza.AssertContains(t, p2, "Lorem Ipsum") } func TestBoxPrinter_WithTitleWithTitleBottomRight(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithTitleBottomRight().WithTitle("a").Sprint("Lorem Ipsum") testza.AssertContains(t, p2, "Lorem Ipsum") } func TestBoxPrinter_WithTitleWithTitleTopRight(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithTitleTopRight().WithTitle("a").Sprint("Lorem Ipsum") testza.AssertContains(t, p2, "Lorem Ipsum") } func TestBoxPrinter_WithTitleWithTitleTopCenter(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithTitleTopCenter().WithTitle("a").Sprint("Lorem Ipsum") testza.AssertContains(t, p2, "Lorem Ipsum") } func TestBoxPrinter_WithTitleWithTitleBottomCenter(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithTitleBottomCenter().WithTitle("a").Sprint("Lorem Ipsum") testza.AssertContains(t, p2, "Lorem Ipsum") } func TestBoxPrinter_WithBoxStyle(t *testing.T) { p := pterm.BoxPrinter{} s := pterm.NewStyle(pterm.FgRed, pterm.BgRed, pterm.Bold) p2 := p.WithBoxStyle(s) testza.AssertEqual(t, s, p2.BoxStyle) testza.AssertZero(t, p.BoxStyle) } func TestBoxPrinter_WithLeftPadding(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithLeftPadding(5) testza.AssertEqual(t, 5, p2.LeftPadding) testza.AssertZero(t, p.LeftPadding) } func TestBoxPrinter_WithRightPadding(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithRightPadding(5) testza.AssertEqual(t, 5, p2.RightPadding) testza.AssertZero(t, p.RightPadding) } func TestBoxPrinter_WithTextStyle(t *testing.T) { p := pterm.BoxPrinter{} s := pterm.NewStyle(pterm.FgRed, pterm.BgRed, pterm.Bold) p2 := p.WithTextStyle(s) testza.AssertEqual(t, s, p2.TextStyle) testza.AssertZero(t, p.TextStyle) } func TestBoxPrinter_WithTopLeftCornerString(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithTopLeftCornerString("-") testza.AssertEqual(t, "-", p2.TopLeftCornerString) testza.AssertZero(t, p.TopLeftCornerString) } func TestBoxPrinter_WithTopPadding(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithTopPadding(5) testza.AssertEqual(t, 5, p2.TopPadding) testza.AssertZero(t, p.TopPadding) } func TestBoxPrinter_WithInvalidTopPadding(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithTopPadding(-5) testza.AssertEqual(t, 0, p2.TopPadding) testza.AssertZero(t, p.TopPadding) } func TestBoxPrinter_WithInvalidBottomPadding(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithBottomPadding(-5) testza.AssertEqual(t, 0, p2.BottomPadding) testza.AssertZero(t, p.BottomPadding) } func TestBoxPrinter_WithInvalidLeftPadding(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithLeftPadding(-5) testza.AssertEqual(t, 0, p2.LeftPadding) testza.AssertZero(t, p.LeftPadding) } func TestBoxPrinter_WithInvalidRightPadding(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithRightPadding(-5) testza.AssertEqual(t, 0, p2.RightPadding) testza.AssertZero(t, p.RightPadding) } func TestBoxPrinter_WithTopRightCornerString(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithTopRightCornerString("-") testza.AssertEqual(t, "-", p2.TopRightCornerString) testza.AssertZero(t, p.TopRightCornerString) } func TestBoxPrinter_WithVerticalString(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithVerticalString("-") testza.AssertEqual(t, "-", p2.VerticalString) testza.AssertZero(t, p.VerticalString) } func TestBoxPrinter_WithHorizontalString(t *testing.T) { p := pterm.BoxPrinter{} p2 := p.WithHorizontalString("-") testza.AssertEqual(t, "-", p2.HorizontalString) testza.AssertZero(t, p.HorizontalString) } func TestBoxPrinter_WithWriter(t *testing.T) { p := pterm.BoxPrinter{} s := os.Stderr p2 := p.WithWriter(s) testza.AssertEqual(t, s, p2.Writer) testza.AssertZero(t, p.Writer) } golang-github-pterm-pterm-0.12.79/bulletlist_printer.go000066400000000000000000000067521465010626300231650ustar00rootroot00000000000000package pterm import ( "io" "strings" ) // BulletListItem is able to render a ListItem. type BulletListItem struct { Level int Text string TextStyle *Style Bullet string BulletStyle *Style } // WithLevel returns a new BulletListItem with a specific Level. func (p BulletListItem) WithLevel(level int) *BulletListItem { p.Level = level return &p } // WithText returns a new BulletListItem with a specific Text. func (p BulletListItem) WithText(text string) *BulletListItem { p.Text = text return &p } // WithTextStyle returns a new BulletListItem with a specific TextStyle. func (p BulletListItem) WithTextStyle(style *Style) *BulletListItem { p.TextStyle = style return &p } // WithBullet returns a new BulletListItem with a specific Prefix. func (p BulletListItem) WithBullet(bullet string) *BulletListItem { p.Bullet = bullet return &p } // WithBulletStyle returns a new BulletListItem with a specific BulletStyle. func (p BulletListItem) WithBulletStyle(style *Style) *BulletListItem { p.BulletStyle = style return &p } // DefaultBulletList contains standards, which can be used to print a BulletListPrinter. var DefaultBulletList = BulletListPrinter{ Bullet: "•", TextStyle: &ThemeDefault.BulletListTextStyle, BulletStyle: &ThemeDefault.BulletListBulletStyle, } // BulletListPrinter is able to render a list. type BulletListPrinter struct { Items []BulletListItem TextStyle *Style Bullet string BulletStyle *Style Writer io.Writer } // WithItems returns a new list with specific Items. func (l BulletListPrinter) WithItems(items []BulletListItem) *BulletListPrinter { l.Items = append(l.Items, items...) return &l } // WithTextStyle returns a new list with a specific text style. func (l BulletListPrinter) WithTextStyle(style *Style) *BulletListPrinter { l.TextStyle = style return &l } // WithBullet returns a new list with a specific bullet. func (l BulletListPrinter) WithBullet(bullet string) *BulletListPrinter { l.Bullet = bullet return &l } // WithBulletStyle returns a new list with a specific bullet style. func (l BulletListPrinter) WithBulletStyle(style *Style) *BulletListPrinter { l.BulletStyle = style return &l } // WithWriter sets the custom Writer. func (l BulletListPrinter) WithWriter(writer io.Writer) *BulletListPrinter { l.Writer = writer return &l } // Render prints the list to the terminal. func (l BulletListPrinter) Render() error { s, _ := l.Srender() Fprintln(l.Writer, s) return nil } // Srender renders the list as a string. func (l BulletListPrinter) Srender() (string, error) { var ret string for _, item := range l.Items { if item.TextStyle == nil { if l.TextStyle == nil { item.TextStyle = &ThemeDefault.BulletListTextStyle } else { item.TextStyle = l.TextStyle } } if item.BulletStyle == nil { if l.BulletStyle == nil { item.BulletStyle = &ThemeDefault.BulletListBulletStyle } else { item.BulletStyle = l.BulletStyle } } split := strings.Split(item.Text, "\n") for i, line := range split { if i == 0 { if item.Bullet == "" { ret += strings.Repeat(" ", item.Level) + item.BulletStyle.Sprint(l.Bullet) + " " + item.TextStyle.Sprint(line) + "\n" } else { ret += strings.Repeat(" ", item.Level) + item.BulletStyle.Sprint(item.Bullet) + " " + item.TextStyle.Sprint(line) + "\n" } } else { ret += strings.Repeat(" ", item.Level) + strings.Repeat(" ", len(item.Bullet)) + " " + item.TextStyle.Sprint(line) + "\n" } } } return ret, nil } golang-github-pterm-pterm-0.12.79/bulletlist_printer_test.go000066400000000000000000000073651465010626300242250ustar00rootroot00000000000000package pterm_test import ( "fmt" "io" "os" "testing" "github.com/MarvinJWendt/testza" "github.com/pterm/pterm" ) func TestBulletListPrinterNilPrint(t *testing.T) { p := pterm.BulletListPrinter{} p.Render() } func TestBulletListPrinter_Render(t *testing.T) { testPrintContains(t, func(w io.Writer, a interface{}) { pterm.DefaultBulletList.WithItems([]pterm.BulletListItem{ {Level: 0, Text: fmt.Sprint(a)}, }).Render() }) } func TestBulletListPrinter_RenderWithoutStyle(t *testing.T) { testPrintContains(t, func(w io.Writer, a interface{}) { pterm.BulletListPrinter{}.WithItems([]pterm.BulletListItem{ {Level: 0, Text: fmt.Sprint(a)}, }).Render() }) } func TestBulletListPrinter_RenderWithBullet(t *testing.T) { testPrintContains(t, func(w io.Writer, a interface{}) { pterm.DefaultBulletList.WithItems([]pterm.BulletListItem{ { Level: 0, Text: fmt.Sprint(a), Bullet: "-", }, }).Render() }) } func TestBulletListPrinter_Srender(t *testing.T) { testSprintContainsWithoutError(t, func(a interface{}) (string, error) { return pterm.DefaultBulletList.WithItems([]pterm.BulletListItem{ {Level: 0, Text: fmt.Sprint(a)}, }).Srender() }) } func TestBulletListPrinter_WithBullet(t *testing.T) { p := pterm.BulletListPrinter{} p2 := p.WithBullet("-") testza.AssertEqual(t, "-", p2.Bullet) testza.AssertZero(t, p.Bullet) } func TestBulletListPrinter_WithBulletStyle(t *testing.T) { p := pterm.BulletListPrinter{} s := pterm.NewStyle(pterm.FgRed, pterm.BgRed, pterm.Bold) p2 := p.WithBulletStyle(s) testza.AssertEqual(t, s, p2.BulletStyle) testza.AssertZero(t, p.BulletStyle) } func TestBulletListPrinter_WithItems(t *testing.T) { p := pterm.BulletListPrinter{} li := []pterm.BulletListItem{{ Level: 0, Text: "test", TextStyle: nil, Bullet: "+", BulletStyle: nil, }} p2 := p.WithItems(li) testza.AssertEqual(t, li, p2.Items) testza.AssertZero(t, p.Items) } func TestBulletListPrinter_WithTextStyle(t *testing.T) { p := pterm.BulletListPrinter{} s := pterm.NewStyle(pterm.FgRed, pterm.BgRed, pterm.Bold) p2 := p.WithTextStyle(s) testza.AssertEqual(t, s, p2.TextStyle) testza.AssertZero(t, p.TextStyle) } func TestBulletListItem_WithBullet(t *testing.T) { p := pterm.BulletListItem{} p2 := p.WithBullet("-") testza.AssertEqual(t, "-", p2.Bullet) testza.AssertZero(t, p.Bullet) } func TestBulletListItem_WithBulletStyle(t *testing.T) { p := pterm.BulletListItem{} s := pterm.NewStyle(pterm.FgRed, pterm.BgRed, pterm.Bold) p2 := p.WithBulletStyle(s) testza.AssertEqual(t, s, p2.BulletStyle) testza.AssertZero(t, p.BulletStyle) } func TestBulletListItem_WithLevel(t *testing.T) { p := pterm.BulletListItem{} p2 := p.WithLevel(1) testza.AssertEqual(t, 1, p2.Level) testza.AssertZero(t, p.Level) } func TestBulletListItem_WithText(t *testing.T) { p := pterm.BulletListItem{} p2 := p.WithText("test") testza.AssertEqual(t, "test", p2.Text) testza.AssertZero(t, p.Text) } func TestBulletListItem_WithTextStyle(t *testing.T) { p := pterm.BulletListItem{} s := pterm.NewStyle(pterm.FgRed, pterm.BgRed, pterm.Bold) p2 := p.WithTextStyle(s) testza.AssertEqual(t, s, p2.TextStyle) testza.AssertZero(t, p.TextStyle) } func TestNewBulletListFromString(t *testing.T) { p := *pterm.DefaultBulletList.WithItems([]pterm.BulletListItem{ {Level: 0, Text: "0"}, {Level: 1, Text: "1"}, {Level: 2, Text: "2"}, {Level: 3, Text: "3"}, {Level: 4, Text: "4"}, {Level: 5, Text: "5"}, }) s := `0 1 2 3 4 5` p2 := pterm.NewBulletListFromString(s, " ") testza.AssertEqual(t, p, p2) } func TestBulletListPrinter_WithWriter(t *testing.T) { p := pterm.BulletListPrinter{} s := os.Stderr p2 := p.WithWriter(s) testza.AssertEqual(t, s, p2.Writer) testza.AssertZero(t, p.Writer) } golang-github-pterm-pterm-0.12.79/center_printer.go000066400000000000000000000112051465010626300222470ustar00rootroot00000000000000package pterm import ( "fmt" "io" "strings" "github.com/mattn/go-runewidth" "github.com/pterm/pterm/internal" ) // DefaultCenter is the default CenterPrinter. var DefaultCenter = CenterPrinter{ CenterEachLineSeparately: false, } // CenterPrinter prints centered text. type CenterPrinter struct { CenterEachLineSeparately bool Writer io.Writer } // WithCenterEachLineSeparately centers each line separately. func (p CenterPrinter) WithCenterEachLineSeparately(b ...bool) *CenterPrinter { bt := internal.WithBoolean(b) p.CenterEachLineSeparately = bt return &p } // WithWriter sets the custom Writer. func (p CenterPrinter) WithWriter(writer io.Writer) *CenterPrinter { p.Writer = writer return &p } // Sprint formats using the default formats for its operands and returns the resulting string. // Spaces are added between operands when neither is a string. func (p CenterPrinter) Sprint(a ...interface{}) string { if RawOutput { return Sprint(a...) } lines := strings.Split(Sprint(a...), "\n") var ret string if p.CenterEachLineSeparately { for _, line := range lines { margin := (GetTerminalWidth() - runewidth.StringWidth(RemoveColorFromString(line))) / 2 if margin < 1 { ret += line + "\n" } else { ret += strings.Repeat(" ", margin) + line + "\n" } } return ret } var maxLineWidth int for _, line := range lines { lineLength := runewidth.StringWidth(RemoveColorFromString(line)) if maxLineWidth < lineLength { maxLineWidth = lineLength } } indent := GetTerminalWidth() - maxLineWidth if indent/2 < 1 { for _, line := range lines { ret += line + "\n" } return ret } for _, line := range lines { ret += strings.Repeat(" ", indent/2) + line + "\n" } return ret } // Sprintln formats using the default formats for its operands and returns the resulting string. // Spaces are always added between operands and a newline is appended. func (p CenterPrinter) Sprintln(a ...interface{}) string { return p.Sprint(Sprintln(a...)) } // Sprintf formats according to a format specifier and returns the resulting string. func (p CenterPrinter) Sprintf(format string, a ...interface{}) string { return p.Sprint(Sprintf(format, a...)) } // Sprintfln formats according to a format specifier and returns the resulting string. // Spaces are always added between operands and a newline is appended. func (p CenterPrinter) Sprintfln(format string, a ...interface{}) string { return p.Sprintf(format, a...) + "\n" } // Print formats using the default formats for its operands and writes to standard output. // Spaces are added between operands when neither is a string. // It returns the number of bytes written and any write error encountered. func (p CenterPrinter) Print(a ...interface{}) *TextPrinter { Fprint(p.Writer, p.Sprint(a...)) tp := TextPrinter(p) return &tp } // Println formats using the default formats for its operands and writes to standard output. // Spaces are always added between operands and a newline is appended. // It returns the number of bytes written and any write error encountered. func (p CenterPrinter) Println(a ...interface{}) *TextPrinter { Fprint(p.Writer, p.Sprintln(a...)) tp := TextPrinter(p) return &tp } // Printf formats according to a format specifier and writes to standard output. // It returns the number of bytes written and any write error encountered. func (p CenterPrinter) Printf(format string, a ...interface{}) *TextPrinter { Fprint(p.Writer, p.Sprintf(format, a...)) tp := TextPrinter(p) return &tp } // Printfln formats according to a format specifier and writes to standard output. // Spaces are always added between operands and a newline is appended. // It returns the number of bytes written and any write error encountered. func (p CenterPrinter) Printfln(format string, a ...interface{}) *TextPrinter { Fprint(p.Writer, p.Sprintfln(format, a...)) tp := TextPrinter(p) return &tp } // PrintOnError prints every error which is not nil. // If every error is nil, nothing will be printed. // This can be used for simple error checking. func (p CenterPrinter) PrintOnError(a ...interface{}) *TextPrinter { for _, arg := range a { if err, ok := arg.(error); ok { if err != nil { p.Println(err) } } } tp := TextPrinter(p) return &tp } // PrintOnErrorf wraps every error which is not nil and prints it. // If every error is nil, nothing will be printed. // This can be used for simple error checking. func (p CenterPrinter) PrintOnErrorf(format string, a ...interface{}) *TextPrinter { for _, arg := range a { if err, ok := arg.(error); ok { if err != nil { p.Println(fmt.Errorf(format, err)) } } } tp := TextPrinter(p) return &tp } golang-github-pterm-pterm-0.12.79/center_printer_test.go000066400000000000000000000077131465010626300233170ustar00rootroot00000000000000package pterm_test import ( "errors" "io" "os" "testing" "github.com/MarvinJWendt/testza" "github.com/pterm/pterm" ) func TestCenterPrinter_WithCenterEachLineSeparately(t *testing.T) { p := pterm.CenterPrinter{} p2 := p.WithCenterEachLineSeparately() testza.AssertTrue(t, p2.CenterEachLineSeparately) testza.AssertFalse(t, p.CenterEachLineSeparately) } func TestCenterPrinterPrintMethods(t *testing.T) { p := pterm.DefaultCenter t.Run("Print", func(t *testing.T) { testPrintContains(t, func(w io.Writer, a interface{}) { p.Print(a) }) }) t.Run("Printf", func(t *testing.T) { testPrintfContains(t, func(w io.Writer, format string, a interface{}) { p.Printf(format, a) }) }) t.Run("Printfln", func(t *testing.T) { testPrintflnContains(t, func(w io.Writer, format string, a interface{}) { p.Printfln(format, a) }) }) t.Run("Println", func(t *testing.T) { testPrintlnContains(t, func(w io.Writer, a interface{}) { p.Println(a) }) }) t.Run("Sprint", func(t *testing.T) { testSprintContains(t, func(a interface{}) string { return p.Sprint(a) }) }) t.Run("Sprintf", func(t *testing.T) { testSprintfContains(t, func(format string, a interface{}) string { return p.Sprintf(format, a) }) }) t.Run("Sprintfln", func(t *testing.T) { testSprintflnContains(t, func(format string, a interface{}) string { return p.Sprintfln(format, a) }) }) t.Run("Sprintln", func(t *testing.T) { testSprintlnContains(t, func(a interface{}) string { return p.Sprintln(a) }) }) t.Run("PrintOnError", func(t *testing.T) { result := captureStdout(func(w io.Writer) { p.PrintOnError(errors.New("hello world")) }) testza.AssertContains(t, result, "hello world") }) t.Run("PrintIfError_WithoutError", func(t *testing.T) { result := captureStdout(func(w io.Writer) { p.PrintOnError(nil) }) testza.AssertZero(t, result) }) t.Run("PrintOnErrorf", func(t *testing.T) { result := captureStdout(func(w io.Writer) { p.PrintOnErrorf("wrapping error : %w", errors.New("hello world")) }) testza.AssertContains(t, result, "hello world") }) t.Run("PrintIfError_WithoutErrorf", func(t *testing.T) { result := captureStdout(func(w io.Writer) { p.PrintOnErrorf("", nil) }) testza.AssertZero(t, result) }) } func TestCenterPrinterPrintMethodsCenterSeparately(t *testing.T) { p := pterm.DefaultCenter.WithCenterEachLineSeparately() t.Run("Print", func(t *testing.T) { testPrintContains(t, func(w io.Writer, a interface{}) { p.Print(a) }) }) t.Run("Printf", func(t *testing.T) { testPrintfContains(t, func(w io.Writer, format string, a interface{}) { p.Printf(format, a) }) }) t.Run("Println", func(t *testing.T) { testPrintlnContains(t, func(w io.Writer, a interface{}) { p.Println(a) }) }) t.Run("Sprint", func(t *testing.T) { testSprintContains(t, func(a interface{}) string { return p.Sprint(a) }) }) t.Run("Sprintf", func(t *testing.T) { testSprintfContains(t, func(format string, a interface{}) string { return p.Sprintf(format, a) }) }) t.Run("Sprintln", func(t *testing.T) { testSprintlnContains(t, func(a interface{}) string { return p.Sprintln(a) }) }) } func TestCenterPrinter_SprintLineLongerThanTerminal(t *testing.T) { p := pterm.DefaultCenter p2 := p.Sprint("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") testza.AssertContains(t, p2, "a") } func TestCenterPrinter_SprintLineLongerThanTerminalWithCenterEachLineSeparately(t *testing.T) { p := pterm.DefaultCenter p2 := p.WithCenterEachLineSeparately().Sprint("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") testza.AssertContains(t, p2, "a") } func TestCenterPrinter_WithWriter(t *testing.T) { p := pterm.CenterPrinter{} s := os.Stderr p2 := p.WithWriter(s) testza.AssertEqual(t, s, p2.Writer) testza.AssertZero(t, p.Writer) } golang-github-pterm-pterm-0.12.79/ci/000077500000000000000000000000001465010626300172715ustar00rootroot00000000000000golang-github-pterm-pterm-0.12.79/ci/main.go000066400000000000000000000312751465010626300205540ustar00rootroot00000000000000package main import ( "fmt" "log" "os" "os/exec" "regexp" "sort" "strconv" "strings" "sync" "time" "github.com/pterm/pterm" ) type Example struct { name string content string } type Examples struct { mu sync.Mutex examples []Example } func (e *Examples) Add(name, content string) { e.mu.Lock() defer e.mu.Unlock() e.examples = append(e.examples, Example{ name: name, content: content, }) } func (e *Examples) GetSorted() []Example { e.mu.Lock() defer e.mu.Unlock() sort.Slice(e.examples, func(i, j int) bool { return e.examples[i].name < e.examples[j].name }) return e.examples } func (e *Examples) String() string { var output string for _, example := range e.GetSorted() { output += example.content } return output } func main() { pterm.Info.Prefix = pterm.Prefix{ Text: "LOG", Style: pterm.NewStyle(pterm.FgGray), } pterm.Info.MessageStyle = pterm.NewStyle(pterm.FgDefault) do("Running PTerm CI System", 1, func(currentLevel int) { do("Generating PUtils Docs", currentLevel, func(currentLevel int) { pterm.Info.Println("Getting docs from 'go doc'...") goDocOutputBytes, err := exec.Command("go", "doc", "-all", "./putils").Output() if err != nil { log.Panic(err) } goDocOutput := string(goDocOutputBytes) goDocOutput = strings.Join(strings.Split(goDocOutput, "FUNCTIONS")[1:], "") goDocOutputLines := strings.Split(goDocOutput, "\n") pterm.Info.Println("Parsing docs...") var goDocOutputFiltered []string for _, line := range goDocOutputLines { if strings.HasPrefix(line, "func") { goDocOutputFiltered = append(goDocOutputFiltered, line) } } pterm.Info.Println("Reading README Template") putilsTemplateBytes, err := os.ReadFile("./putils/README.template.md") if err != nil { log.Panic(err) } pterm.Info.Println("Generating README.md") putilsReadme := string(putilsTemplateBytes) putilsReadme += "\n## Util Functions\n\n" putilsReadme += fmt.Sprintf("```go\n%s\n```\n", strings.Join(goDocOutputFiltered, "\n")) pterm.Info.Println("Writing './putils/README.md'") os.WriteFile("./putils/README.md", []byte(putilsReadme), 0600) pterm.Info.Println("Writing './docs/docs/putils.md'") os.WriteFile("./docs/docs/putils.md", []byte(putilsReadme), 0600) }) var allPrinters []string do("Geneating printers Table", currentLevel, func(currentLevel int) { // get features located in "_examples/*" dirs, _ := os.ReadDir("./_examples/") for _, dir := range dirs { if dir.Name() == "README.md" { continue } // Exclude demo folder if dir.Name() == "demo" { continue } allPrinters = append(allPrinters, dir.Name()) } // generate table tableContent := "| Feature | Feature | Feature | Feature | Feature |\n| :-------: | :-------: | :-------: | :-------: | :-------: |\n" for i, feature := range allPrinters { // the table should contain 5 columns. Each cell is a feature. // Make multiple rows, if there are more than 4 features. // A link to the examples should be included in every cell. // Format: "[Example](https://github.com/pterm/pterm/tree/master/_examples/FEATURE)" if i%5 == 0 { tableContent += "| " } name := strings.ToUpper(string(feature[0])) + feature[1:] name = strings.ReplaceAll(name, "_", " ") tableContent += fmt.Sprintf("%s
[(Examples)](https://github.com/pterm/pterm/tree/master/_examples/%s) |", name, feature) if (i+1)%5 == 0 { tableContent += "\n" } // fill left over cells with empty strings if in the last row if i == len(allPrinters)-1 { tableContent += strings.Repeat(" | ", 5-(i+1)%5) } } // read readme readme, _ := os.ReadFile("./README.md") // replace table in readme readmeString := string(readme) readmeString = writeBetween("printers", readmeString, "\n"+tableContent+"\n") // write readme os.WriteFile("./README.md", []byte(readmeString), 0600) }) do("Write printers to website", currentLevel, func(currentLevel int) { pterm.Info.Println("Writing printers to website") websiteIndex, _ := os.ReadFile("./docs/index.html") websiteIndexString := string(websiteIndex) // Write as li elements, which contain a link to the example. (https://github.com/pterm/pterm/tree/master/_examples/{name}) var links []string for _, printer := range allPrinters { links = append(links, fmt.Sprintf(`
  • %s
  • `, printer, printer)) } // Replace placeholder with li elements. websiteIndexString = writeBetween("printers", websiteIndexString, "\n"+strings.Join(links, "\n")+"\n") os.WriteFile("./docs/index.html", []byte(websiteIndexString), 0600) }) var readmeExamples string do("Generating Examples", currentLevel, func(currentLevel int) { files, _ := os.ReadDir("./_examples/") var sectionExamples sync.Map var wg sync.WaitGroup for _, section := range files { if section.Name() == "README.md" { continue } wg.Add(1) go func(section os.DirEntry) { defer wg.Done() sectionContent := generateSectionContent(section) sectionExamples.Store(section.Name(), sectionContent) }(section) } pterm.Info.Println("Waiting for all examples to be generated...") wg.Wait() var keys []string sectionExamples.Range(func(key, value interface{}) bool { keys = append(keys, key.(string)) return true }) sort.Strings(keys) for _, key := range keys { value, _ := sectionExamples.Load(key) readmeExamples += value.(string) } pterm.Info.Println("Writing '/_examples/README.md'") examplesReadme, _ := os.ReadFile("./_examples/README.md") examplesReadmeContent := string(examplesReadme) examplesReadmeContent = writeBetween("examples", examplesReadmeContent, "\n"+readmeExamples+"\n") os.WriteFile("./_examples/README.md", []byte(examplesReadmeContent), 0600) }) var newReadmeContent string readmeContent, err := os.ReadFile("./README.md") if err != nil { log.Panic(err) } do("Counting Unit Tests", currentLevel, func(currentLevel int) { unittestTimeout := make(chan string, 1) go func() { cmd := exec.Command("bash", "-c", "go test -v -p 1 ./...") json, _ := cmd.CombinedOutput() unitTestCount := fmt.Sprint(strings.Count(string(json), "RUN")) pterm.Info.Println("Unit test count:", unitTestCount) unittestTimeout <- unitTestCount }() pterm.Info.Println("Replacing Strings in README") newReadmeContent = string(readmeContent) select { case res := <-unittestTimeout: newReadmeContent = writeBetween("unittestcount", newReadmeContent, `Forks`) newReadmeContent = writeBetween("unittestcount2", newReadmeContent, "**`"+res+"`**") case <-time.After(time.Second * 10): pterm.Info.Println("!!! Timeout in counting unit tests") } newReadmeContent = writeBetween("examples", newReadmeContent, "\n"+readmeExamples+"\n") }) do("Writing README", currentLevel, func(currentLevel int) { pterm.Info.Println("Appending examples to root README.md") pterm.Info.Println("Writing README") err = os.WriteFile("./README.md", []byte(newReadmeContent), 0600) if err != nil { log.Panic(err) } }) }) } func generateSectionContent(section os.DirEntry) string { var sectionExamples string examples, _ := os.ReadDir("./_examples/" + section.Name()) var exampleMap sync.Map var wg sync.WaitGroup for _, example := range examples { if example.Name() == "README.md" { continue } wg.Add(1) go func(section os.DirEntry, example os.DirEntry) { defer wg.Done() dir := section.Name() + "/" + example.Name() content := generateExampleContent(dir, section, example) pterm.Info.Println("Storing to map: " + section.Name() + "/" + example.Name() + "...") exampleMap.Store(example.Name(), content) pterm.Info.Println("Stored to map: " + section.Name() + "/" + example.Name()) }(section, example) } wg.Wait() var keys []string exampleMap.Range(func(key, value interface{}) bool { keys = append(keys, key.(string)) return true }) sort.Slice(keys, func(i, j int) bool { if keys[i] == "demo" { return true } if keys[j] == "demo" { return false } return keys[i] < keys[j] }) for _, key := range keys { value, _ := exampleMap.Load(key) sectionExamples += value.(string) } os.WriteFile("./_examples/"+section.Name()+"/README.md", []byte(sectionExamples), 0600) return sectionExamples } func generateExampleContent(dir string, section os.DirEntry, example os.DirEntry) string { var content string exampleRenderStart := time.Now() animationDataPath := "./_examples/" + dir + "/animation_data.json" animationSvgPath := "./_examples/" + dir + "/animation.svg" exampleCode, err := os.ReadFile("./_examples/" + dir + "/main.go") if err != nil { log.Panic(err) } if fileExists(animationDataPath) { pterm.Info.Println("[" + dir + "] 'animation_data.json' already exists. Removing it.") err = os.Remove(animationDataPath) if err != nil { log.Panic(err) } } if fileExists(animationSvgPath) { pterm.Info.Println("[" + dir + "] 'animation.svg' already exists. Removing it.") err := os.Remove(animationSvgPath) if err != nil { log.Panic(err) } } pterm.Info.Println("[" + dir + "] Running asciinema") execute(`go build -o ./_examples/` + dir + `/bundle ./_examples/` + dir) execute(`asciinema rec ` + animationDataPath + ` -c "./_examples/` + dir + `/bundle && sleep 1"`) os.Remove("./_examples/" + dir + "/bundle") pterm.Info.Println("[" + dir + "] Adding sleep to end of 'animation_data.json'") addSleepToEndOfAnimationData(dir, animationDataPath) pterm.Info.Println("[" + dir + "] Generating SVG") generateSVG(animationDataPath, animationSvgPath) pterm.Info.Println("[" + dir + "] Overwriting SVG font") overwriteSVGFont(dir, animationSvgPath) pterm.Info.Println("[" + dir + "] Generating README") readmeString := generateExampleReadme(dir, exampleCode) err = os.WriteFile("./_examples/"+dir+"/README.md", []byte(readmeString), 0600) if err != nil { log.Panic(err) } pterm.Info.Println("[" + dir + "] Cleaning files") os.Remove(animationDataPath) content += "### " + section.Name() + "/" + example.Name() + "\n\n" content += "![Animation](https://raw.githubusercontent.com/pterm/pterm/master/_examples/" + section.Name() + "/" + example.Name() + "/animation.svg)\n\n" content += "
    \n\nSHOW SOURCE\n\n" content += "```go\n" content += string(exampleCode) + "\n" content += "```\n\n" content += "
    \n\n" pterm.Info.Println("[" + dir + "] This example took: " + time.Since(exampleRenderStart).String()) return content } func generateSVG(animationDataPath, animationSvgPath string) { noCursorFlag := "--no-cursor" if strings.Contains(animationDataPath, "interactive") { noCursorFlag = "" } execute(`svg-term --in ` + animationDataPath + ` --out ` + animationSvgPath + " " + noCursorFlag + ` --window true --no-optimize --profile "./ci/terminal-theme.txt" --term "iterm2"`) } func addSleepToEndOfAnimationData(dir, animationDataPath string) { animationDataLines := getLinesFromFile(animationDataPath) animationDataLastLine := animationDataLines[len(animationDataLines)-1] re := regexp.MustCompile(`\[\d[^,]*`).FindAllString(animationDataLastLine, 1)[0] lastTime, _ := strconv.ParseFloat(strings.ReplaceAll(re, "[", ""), 64) sleepString := `[` + strconv.FormatFloat(lastTime+5, 'f', 6, 64) + `, "o", "\nRestarting animation...\n"]` animationDataFile, err := os.OpenFile(animationDataPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600) if err != nil { log.Panicf("[%s] %s", dir, err.Error()) } defer animationDataFile.Close() _, err = animationDataFile.WriteString(sleepString) if err != nil { log.Panicf("[%s] %s", dir, err.Error()) } } func overwriteSVGFont(dir, animationSvgPath string) { svgContent, err := os.ReadFile(animationSvgPath) if err != nil { log.Panicf("[%s] %s", dir, err.Error()) } svgContent = []byte(strings.ReplaceAll(string(svgContent), `font-family:`, `font-family:'Courier New',`)) svgContent = []byte(strings.ReplaceAll(string(svgContent), `font-family="`, `font-family="'Courier New',`)) svgContent = []byte(strings.Replace(string(svgContent), "