TLDR: Collaborative Cheatsheets for Console Commands

What is tldr-pages?

The tldr-pages project is a collection of community-maintained help pages for command-line tools, that aims to be a simpler, more approachable complement to traditional man pages.

Maybe you're new to the command-line world? Perhaps you're just a little rusty or can't always recall the arguments for commands like lsof, or tar?

It certainly doesn't help that the first option explained in man tar is:

-b blocksize
   Specify the block size, in 512-byte records, for tape drive I/O.
   As a rule, this argument is only needed when reading from or writing to tape drives,
   and usually not even then as the default block size of 20 records (10240 bytes) is very common.

There seems to be room for simpler help pages, focused on practical examples. How about:

Animated SVG of the tldr client displaying the tar command.

This repository is just that: an ever-growing collection of examples for the most common UNIX, Linux, macOS, SunOS, Android and Windows command-line tools.

How do I use it?

A popular and convenient way to access these pages on your computer is to install the Node.js client, which is supported by the tldr-pages project maintainers:

npm install -g tldr

Alternatively, you can also use the Python client, which can be installed via pip3.

pip3 install tldr

Or Mac users can also install our C Client using Homebrew.

brew install tldr

Then you have direct access to simplified, easy-to-read help for commands, such as tar, accessible through typing tldr tar instead of the standard man tar.

If you want an offline version without installing any software, check out the PDF version.

For browsing without installing a client to your computer, see the web client at https://tldr.inbrowser.app (with offline support using PWA).

There are also various other clients provided by the community, both for the command-line and for other platforms. For a comprehensive list of clients, head over to our Wiki.

How do I contribute to tldr-pages?

All contributions are welcome!

Some ways to contribute include:

  • Adding your favorite command which isn't covered.
  • Adding examples or improving the content of an existing page.
  • Adding requested pages from our issues with the help wanted label.
  • Translating pages into different languages.

All tldr pages are written in markdown, so they can be edited quite easily and changes can be submitted in pull requests here using Git on the command-line or using the GitHub web interface.

But we already have some plugins for different editors to enhance the tldr page editing experience:

For editors without a plugin system, we provide a set of configurations in a separate repo.

We strive to maintain a welcoming and collaborative community. If it's your first time contributing, have a look at the contributing guidelines, and go ahead!

If you'd like to contribute to translations, you can visit https://lukwebsforge.github.io/tldri18n/ to see the overall progress of all translations, and which translations are missing or outdated.

Similar projects

Command Line Interface Pages allows you to write standardized help pages for CLI, directories and configs.

Cheat allows you to create and view interactive cheatsheets on the command-line. It was designed to help remind *nix system administrators of options for commands that they use frequently, but not frequently enough to remember.

cheat.sh Aggregates cheat sheets from multiple sources (including tldr-pages) into 1 unified interface.

devhints Rico's cheatsheets are not just focused on the command-line and include a plethora of other cheatsheets related to programming.

eg provides detailed examples with explanations on the command-line. Examples come from the repository, but eg supports displaying custom examples and commands alongside the defaults.

kb is a minimalist command-line knowledge base manager. kb can be used to organize your notes and cheatsheets in a minimalist and clean way. It also supports non-text files.

navi is an interactive cheatsheet tool, which allows you to browse through specific examples or complete commands on the fly.

bropages (deprecated) are a highly readable supplement to man pages. It shows concise, common-case examples for Unix commands. The examples are submitted by the user base, and can be voted up or down; the best entries are what people see first when they look up a command.

What does "tldr" mean?

TL;DR stands for "Too Long; Didn't Read". It originated as Internet slang, where it is used to indicate that a long text (or parts of it) has been skipped as too lengthy. Read more in How-To Geek's article.


Download Details:

Author: tldr-pages
Source Code: https://github.com/tldr-pages/tldr 
License: View license

#markdown #shell #console #documentation #terminal 

TLDR: Collaborative Cheatsheets for Console Commands
Elian  Harber

Elian Harber

1667488200

Cointop: A Fast and Lightweight interactive Terminal Based UI App

Cointop

Coin tracking for hackers

cointop is a fast and lightweight interactive terminal based UI application for tracking and monitoring cryptocurrency coin stats in real-time.

The interface is inspired by htop and shortcut keys are inspired by vim.

cointop screenshot

Demo

This connects to an instance of Cointop using SSH:

ssh cointop.sh

In action

screencast

Features

  • Shortcut keys: Vim-inspired shortcut keys, custom key bindings configuration
  • Colorschemes: Custom colorscheme configuration, 256-color and 24-bit support
  • Favorites: Save and view favorite coins
  • Portfolio: Portfolio tracking of holdings, view profit & loss
  • Charts: Charts for coin price history and global market graphs
  • Search: Fuzzy searching for finding coins
  • Conversion: Currency conversion
  • Price Alerts: Price alerts with desktop notifications
  • Multiple APIs: Supports multiple coin data APIs; CoinGecko and CoinMarketCap
  • Mouse: Mouse support
  • Offline: Offline cache
  • Fast: Fast sort shortcuts, pagination, chart date range change, auto-refresh
  • Lightweight: It's very lightweight; can be left running indefinitely

Contributing

See docs.cointop.sh/contributing

Many thanks to Simon Roberts, Alexis Hildebrandt, and all the contributors that made cointop better.

Social

Mentioned in

Cointop has been mentioned in:

Download Details:

Author: Cointop-sh
Source Code: https://github.com/cointop-sh/cointop 
License: Apache-2.0 license

#go #golang #macos #linux #cli #console 

Cointop: A Fast and Lightweight interactive Terminal Based UI App
Reid  Rohan

Reid Rohan

1667124660

Xterm.js: A Terminal for The Web

Xterm.js

Xterm.js is a front-end component written in TypeScript that lets applications bring fully-featured terminals to their users in the browser. It's used by popular projects such as VS Code, Hyper and Theia.

Features

  • Terminal apps just work: Xterm.js works with most terminal apps such as bash, vim, and tmux, including support for curses-based apps and mouse events.
  • Performant: Xterm.js is really fast, it even includes a GPU-accelerated renderer.
  • Rich Unicode support: Supports CJK, emojis, and IMEs.
  • Self-contained: Requires zero dependencies to work.
  • Accessible: Screen reader and minimum contrast ratio support can be turned on.
  • And much more: Links, theming, addons, well documented API, etc.

What xterm.js is not

  • Xterm.js is not a terminal application that you can download and use on your computer.
  • Xterm.js is not bash. Xterm.js can be connected to processes like bash and let you interact with them (provide input, receive output).

Getting Started

First, you need to install the module, we ship exclusively through npm, so you need that installed and then add xterm.js as a dependency by running:

npm install xterm

To start using xterm.js on your browser, add the xterm.js and xterm.css to the head of your HTML page. Then create a <div id="terminal"></div> onto which xterm can attach itself. Finally, instantiate the Terminal object and then call the open function with the DOM object of the div.

<!doctype html>
  <html>
    <head>
      <link rel="stylesheet" href="node_modules/xterm/css/xterm.css" />
      <script src="node_modules/xterm/lib/xterm.js"></script>
    </head>
    <body>
      <div id="terminal"></div>
      <script>
        var term = new Terminal();
        term.open(document.getElementById('terminal'));
        term.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ')
      </script>
    </body>
  </html>

Importing

The recommended way to load xterm.js is via the ES6 module syntax:

import { Terminal } from 'xterm';

Addons

⚠️ This section describes the new addon format introduced in v3.14.0, see here for the instructions on the old format

Addons are separate modules that extend the Terminal by building on the xterm.js API. To use an addon, you first need to install it in your project:

npm i -S xterm-addon-web-links

Then import the addon, instantiate it and call Terminal.loadAddon:

import { Terminal } from 'xterm';
import { WebLinksAddon } from 'xterm-addon-web-links';

const terminal = new Terminal();
// Load WebLinksAddon on terminal, this is all that's needed to get web links
// working in the terminal.
terminal.loadAddon(new WebLinksAddon());

The xterm.js team maintains the following addons, but anyone can build them:

Browser Support

Since xterm.js is typically implemented as a developer tool, only modern browsers are supported officially. Specifically the latest versions of Chrome, Edge, Firefox, and Safari.

Xterm.js works seamlessly in Electron apps and may even work on earlier versions of the browsers. These are the versions we strive to keep working.

Node.js Support

We also publish xterm-headless which is a stripped down version of xterm.js that runs in Node.js. An example use case for this is to keep track of a terminal's state where the process is running and using the serialize addon so it can get all state restored upon reconnection.

API

The full API for xterm.js is contained within the TypeScript declaration file, use the branch/tag picker in GitHub (w) to navigate to the correct version of the API.

Note that some APIs are marked experimental, these are added to enable experimentation with new ideas without committing to support it like a normal semver API. Note that these APIs can change radically between versions, so be sure to read release notes if you plan on using experimental APIs.

Releases

Xterm.js follows a monthly release cycle roughly.

All current and past releases are available on this repo's Releases page, you can view the high-level roadmap on the wiki and see what we're working on now by looking through Milestones.

Beta builds

Our CI releases beta builds to npm for every change that goes into master. Install the latest beta build with:

npm install -S xterm@beta

These should generally be stable, but some bugs may slip in. We recommend using the beta build primarily to test out new features and to verify bug fixes.

Contributing

You can read the guide on the wiki to learn how to contribute and set up xterm.js for development.

Real-world uses

Xterm.js is used in several world-class applications to provide great terminal experiences.

  • SourceLair: In-browser IDE that provides its users with fully-featured Linux terminals based on xterm.js.
  • Microsoft Visual Studio Code: Modern, versatile, and powerful open source code editor that provides an integrated terminal based on xterm.js.
  • ttyd: A command-line tool for sharing terminal over the web, with fully-featured terminal emulation based on xterm.js.
  • Katacoda: Katacoda is an Interactive Learning Platform for software developers, covering the latest Cloud Native technologies.
  • Eclipse Che: Developer workspace server, cloud IDE, and Eclipse next-generation IDE.
  • Codenvy: Cloud workspaces for development teams.
  • CoderPad: Online interviewing platform for programmers. Run code in many programming languages, with results displayed by xterm.js.
  • WebSSH2: A web based SSH2 client using xterm.js, socket.io, and ssh2.
  • Spyder Terminal: A full fledged system terminal embedded on Spyder IDE.
  • Cloud Commander: Orthodox web file manager with console and editor.
  • Next Tech: Online platform for interactive coding and web development courses. Live container-backed terminal uses xterm.js.
  • RStudio: RStudio is an integrated development environment (IDE) for R.
  • Terminal for Atom: A simple terminal for the Atom text editor.
  • Eclipse Orion: A modern, open source software development environment that runs in the cloud. Code, deploy, and run in the cloud.
  • Gravitational Teleport: Gravitational Teleport is a modern SSH server for remotely accessing clusters of Linux servers via SSH or HTTPS.
  • Hexlet: Practical programming courses (JavaScript, PHP, Unix, databases, functional programming). A steady path from the first line of code to the first job.
  • Selenoid UI: Simple UI for the scalable golang implementation of Selenium Hub named Selenoid. We use XTerm for streaming logs over websockets from docker containers.
  • Portainer: Simple management UI for Docker.
  • SSHy: HTML5 Based SSHv2 Web Client with E2E encryption utilising xterm.js, SJCL & websockets.
  • JupyterLab: An extensible computational environment for Jupyter, supporting interactive data science and scientific computing across all programming languages.
  • Theia: Theia is a cloud & desktop IDE framework implemented in TypeScript.
  • Opshell Ops Helper tool to make life easier working with AWS instances across multiple organizations.
  • Proxmox VE: Proxmox VE is a complete open-source platform for enterprise virtualization. It uses xterm.js for container terminals and the host shell.
  • Script Runner: Run scripts (or a shell) in Atom.
  • Whack Whack Terminal: Terminal emulator for Visual Studio 2017.
  • VTerm: Extensible terminal emulator based on Electron and React.
  • electerm: electerm is a terminal/ssh/sftp client(mac, win, linux) based on electron/node-pty/xterm.
  • Kubebox: Terminal console for Kubernetes clusters.
  • Azure Cloud Shell: Azure Cloud Shell is a Microsoft-managed admin machine built on Azure, for Azure.
  • atom-xterm: Atom plugin for providing terminals inside your Atom workspace.
  • rtty: Access your terminals from anywhere via the web.
  • Pisth: An SFTP and SSH client for iOS.
  • abstruse: Abstruse CI is a continuous integration platform based on Node.JS and Docker.
  • Azure Data Studio: A data management tool that enables working with SQL Server, Azure SQL DB and SQL DW from Windows, macOS and Linux.
  • FreeMAN: A free, cross-platform file manager for power users.
  • Fluent Terminal: A terminal emulator based on UWP and web technologies.
  • Hyper: A terminal built on web technologies.
  • Diag: A better way to troubleshoot problems faster. Capture, share and reapply troubleshooting knowledge so you can focus on solving problems that matter.
  • GoTTY: A simple command line tool that shares your terminal as a web application based on xterm.js.
  • genact: A nonsense activity generator.
  • cPanel & WHM: The hosting platform of choice.
  • Nutanix: Nutanix Enterprise Cloud uses xterm in the webssh functionality within Nutanix Calm, and is also looking to move our old noserial (termjs) functionality to xterm.js.
  • SSH Web Client: SSH Web Client with PHP.
  • Juno: A flexible Julia IDE, based on Atom.
  • webssh: Web based ssh client.
  • info-beamer hosted: Uses xterm.js to manage digital signage devices from the web dashboard.
  • Jumpserver: Jumpserver Luna project, Jumpserver is a bastion server project, Luna use xterm.js for web terminal emulation.
  • LxdMosaic: Uses xterm.js to give terminal access to containers through LXD
  • CodeInterview.io: A coding interview platform in 25+ languages and many web frameworks. Uses xterm.js to provide shell access.
  • Bastillion: Bastillion is an open-source web-based SSH console that centrally manages administrative access to systems.
  • PHP App Server: Create lightweight, installable almost-native applications for desktop OSes. ExecTerminal (nicely wraps the xterm.js Terminal), TerminalManager, and RunProcessSDK are self-contained, reusable ES5+ compliant Javascript components.
  • NgTerminal: NgTerminal is a web terminal that leverages xterm.js on Angular 7+. You can easily add it into your application by adding <ng-terminal></ng-terminal> into your component.
  • tty-share: Extremely simple terminal sharing over the Internet.
  • Ten Hands: One place to run your command-line tasks.
  • WebAssembly.sh: A WebAssembly WASI browser terminal
  • Gus: A shared coding pad where you can run Python with xterm.js
  • Linode: Linode uses xterm.js to provide users a web console for their Linode instances.
  • FluffOS: Active maintained LPMUD driver with websocket support.
  • x-terminal: Atom plugin for providing terminals inside your Atom workspace.
  • CoCalc: Lots of free software pre-installed, to chat, collaborate, develop, program, publish, research, share, teach, in C++, HTML, Julia, Jupyter, LaTeX, Markdown, Python, R, SageMath, Scala, ...
  • Dank Domain: Open source multiuser medieval game supporting old & new terminal emulation.
  • DockerStacks: Local LAMP/LEMP development studio
  • Codecademy: Uses xterm.js in its courses on Bash.
  • Laravel Ssh Web Client: Laravel server inventory with ssh web client to connect at server using xterm.js
  • Replit: Collaborative browser based IDE with support for 50+ different languages.
  • TeleType: cli tool that allows you to share your terminal online conveniently. Show off mad cli-fu, help a colleague, teach, or troubleshoot.
  • Intervue: Pair programming for interviews. Multiple programming languages are supported, with results displayed by xterm.js.
  • TRASA: Zero trust access to Web, SSH, RDP, and Database services.
  • Commas: Commas is a hackable terminal and command runner.
  • Devtron: Software Delivery Workflow For Kubernetes.
  • NxShell: An easy to use new terminal for SSH.
  • gifcast: Converts an asciinema cast to an animated GIF.
  • WizardWebssh: A terminal with Pyqt5 Widget for embedding, which can be used as an ssh client to connect to your ssh servers. It is written in Python, based on tornado, paramiko, and xterm.js.
  • Wizard Assistant: Wizard Assistant comes with advanced automation tools, preloaded common and special time-saving commands, and a built-in SSH terminal. Now you can remotely administer, troubleshoot, and analyze any system with ease.
  • ucli: Command Line for everyone :family_man_woman_girl_boy: at www.ucli.tech.
  • Tess: Simple Terminal Fully Customizable for Everyone. Discover more at tessapp.dev
  • HashiCorp Nomad: A container orchestrator with the ability to connect to remote tasks via a web interface using websockets and xterm.js.
  • TermPair: View and control terminals from your browser with end-to-end encryption
  • gdbgui: Browser-based frontend to gdb (gnu debugger)
  • goormIDE: Run almost every programming languages with real-time collaboration, live pair programming, and built-in messenger.
  • FleetDeck: Remote desktop & virtual terminal
  • OpenSumi: A framework helps you quickly build Cloud or Desktop IDE products.
  • KubeSail: The Self-Hosting Company - uses xterm to allow users to exec into kubernetes pods and build github apps
  • WiTTY: Web-based interactive terminal emulator that allows users to easily record, share, and replay console sessions.
  • libv86 Terminal Forwarding: Peer-to-peer SSH for the web, using WebRTC via Bugout for data transfer and v86 for web-based virtualization.
  • hack.courses: Interactive Linux and command-line classes using xterm.js to expose a real terminal available for everyone.
  • Render: Platform-as-a-service for your apps, websites, and databases using xterm.js to provide a command prompt for user containers and for streaming build and runtime logs.
  • CloudTTY: A Friendly Kubernetes CloudShell (Web Terminal).
  • Go SSH Web Client: A simple SSH web client using Go, WebSocket and Xterm.js.
  • web3os: A decentralized operating system for the next web
  • Cratecode: Learn to program for free through interactive online lessons. Cratecode uses xterm.js to give users access to their own Linux environment.
  • And much more...

Do you use xterm.js in your application as well? Please open a Pull Request to include it here. We would love to have it on our list. Note: Please add any new contributions to the end of the list only.

Download Details:

Author: xtermjs
Source Code: https://github.com/xtermjs/xterm.js 
License: MIT license

#typescript #javascript #console #ssh 

Xterm.js: A Terminal for The Web
Gordon  Matlala

Gordon Matlala

1666727400

A Jekyll Theme inspired By Linux Consoles for Hackers, Developers

jekyll-theme-console

A jekyll theme with inspiration from linux consoles for hackers, developers and script kiddies.

Installation

First, follow the steps in this Quickstart Guide if you're starting with Jekyll from scratch. Skip this if you already have an existing jekyll project.

You can also use the demo site's source code as template for an easy start.

Remote theme method for GitHub Pages

Use this method for sites hosted with GitHub Pages only. To install:

Set remote_theme in your project's Jekyll _config.yml file:

remote_theme: b2a3e8/jekyll-theme-console

Gem-based method

With Gem-based themes, directories such as the assets, _layouts, _includes, and _sass are stored in the theme’s gem, hidden from your immediate view. Yet all of the necessary directories will be read and processed during Jekyll’s build process.

This allows for easier installation and updating as you don't have to manage any of the theme files. To install:

Add this line to your Jekyll site's Gemfile:

gem "jekyll-theme-console"

Fetch and update bundled gems by running the following Bundler command:

bundle

Set theme in your project's Jekyll _config.yml file:

theme: jekyll-theme-console

To update the theme run bundle update.

Usage

_config.yaml

In addition to jekyll's default configuration options, you can provide:

  • header_pages to specify which pages should be displayed in navbar
  • footer string, which will be inserted on the end of the page (doesn't support markup, but html)
  • google_analytics tracking id (tracking will be enabled only in production environments and only if you set this option, no Google Analytics code will be loaded if you don't set this option)
  • listen_for_clients_preferred_style boolean, used to allow users to choose light or dark style based on their preferences (mostly affected by OS dark or light theme, details see https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)
  • style to specify which predefined style (colors) should be used
header_pages:
  - index.md
  - about.md

style: dark # dark (default), light or hacker
listen_for_clients_preferred_style: true # false (default) or true

footer: 'follow us on <a href="https://twitter.com/xxx">twitter</a>'

google_analytics: UA-NNNNNNNN-N

front matter variables

Besides the predefined front matter variables from jekyll this theme also supports following variables:

  • title to set a title for the page
  • lang to specify the language, defaults to 'en'
  • robots to control the robot meta tag (details) - this may be useful for example to set NOINDEX to tag pages

Customization

If you want to customize this theme, follow this steps:

  1. Fork this repository (you can use the fork as your own theme or directly as your website)
  2. Create or modify files in _layouts directory for html-based changes
  3. Create or modify files in _sass and assets for css-based changes
    • You can change things which are used in light and dark theme (like font-size) in _sass/base.scss. You'll find style variables at the top.
    • Style-specific definitions are in _sass/_dark.scss respectively in _sass/_light.scss. You can change things like background-color there.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/b2a3e8/jekyll-theme-console. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

Development

To set up your environment to develop this theme, run bundle install.

Your theme is setup just like a normal Jekyll site! To test your theme, run bundle exec jekyll serve and open your browser at http://localhost:4000. This starts a Jekyll server using your theme. Add pages, documents, data, etc. like normal to test your theme's contents. As you make modifications to your theme and to your content, your site will regenerate and you should see the changes in the browser after a refresh, just like normal.

When your theme is released, only the files in _layouts, _includes, _sass and assets tracked with Git will be bundled. To add a custom directory to your theme-gem, please edit the regexp in jekyll-theme-console.gemspec accordingly.

Screenshots

Demo

dark style (source code):

light style (source code):

hacker style (source code):

Download Details:

Author: b2a3e8
Source Code: https://github.com/b2a3e8/jekyll-theme-console
License: MIT license

#jekyll #theme #console 

A Jekyll Theme inspired By Linux Consoles for Hackers, Developers

Collision: A Beautiful Error Reporting tool for Command-line Apps

Collision was created by, and is maintained by Nuno Maduro, and is a package designed to give you beautiful error reporting when interacting with your app through the command line.

  • It's included on Laravel, the most popular free, open-source PHP framework in the world.
  • Built on top of the Whoops error handler.
  • Supports Laravel, Symfony, PHPUnit, and many other frameworks.
Collision code example

Installation & Usage

Requires PHP 8.1+

Require Collision using Composer:

composer require nunomaduro/collision --dev

Laravel Version Compatibility

LaravelCollision
6.x3.x
7.x4.x
8.x5.x
9.x6.x (PHPUnit 9.x or Pest v1.x)
9.x7.x (PHPUnit 10.x or Pest v2.x)

As an example, here is how to require Collision on Laravel 8.x:

composer require nunomaduro/collision:^5.0 --dev

Phpunit adapter

Phpunit must be 9.0 or higher.

Add the Collision printerClass to your phpunit.xml in the phpunit section:

<phpunit
        printerClass="NunoMaduro\Collision\Adapters\Phpunit\Printer">

No adapter

You need to register the handler in your code:

(new \NunoMaduro\Collision\Provider)->register();

Contributing

Thank you for considering to contribute to Collision. All the contribution guidelines are mentioned here.

You can have a look at the CHANGELOG for constant updates & detailed information about the changes. You can also follow the twitter account for latest announcements or just come say hi!: @enunomaduro

Download Details:

Author: Nunomaduro
Source Code: https://github.com/nunomaduro/collision 
License: MIT license

#php #laravel #cli #console 

Collision: A Beautiful Error Reporting tool for Command-line Apps

PHPinsights: Instant PHP Quality Checks From Your Console

PHPinsights

PHP Insights was carefully crafted to simplify the analysis of your code directly from your terminal, and is the perfect starting point to analyze the code quality of your PHP projects. It was created by Nuno Maduro, logo design Caneco, and currently is maintained by Chris Gmyr, Jibé Barth, and Steve McDougall.

🚀 Quick start

# First, install:
composer require nunomaduro/phpinsights --dev

# Then, use it:
./vendor/bin/phpinsights

# For Laravel:
First, publish the configuration file:
php artisan vendor:publish --provider="NunoMaduro\PhpInsights\Application\Adapters\Laravel\InsightsServiceProvider"

Then, use it:
php artisan insights

✨ Features

  • Analysis of code quality and coding style
  • Beautiful overview of code architecture and its complexity
  • Designed to work out-of-the-box with Laravel, Symfony, Yii, Magento, and more
  • Contains built-in checks for making code reliable, loosely coupled, simple, and clean

For full documentation, visit phpinsights.com.

Download Details:

Author: Nunomaduro
Source Code: https://github.com/nunomaduro/phpinsights 
License: MIT license

#php #cli #console #analytics 

PHPinsights: Instant PHP Quality Checks From Your Console
Nigel  Uys

Nigel Uys

1663151064

10 Popular Libraries for Advanced Console UIs in Go

In today's post we will learn about 10 Popular Libraries for Advanced Console UIs in Go. 

Console user interface may refer to: Command-line interface, user interface using only text. Text-based user interface, user interface with simple text-based menus and dialogues.

Table of contents:

  • Asciigraph - Go package to make lightweight ASCII line graph ╭┈╯ in command line apps with no other dependencies.
  • Aurora - ANSI terminal colors that supports fmt.Printf/Sprintf.
  • Box-cli-maker - Make Highly Customized Boxes for your CLI.
  • cfmt - Contextual fmt inspired by bootstrap color classes.
  • cfmt - Simple and convenient formatted stylized output fully compatible with fmt library.
  • Chalk - Intuitive package for prettifying terminal/console output.
  • Colourize - Go library for ANSI colour text in terminals.
  • Crab-config-files-templating - Dynamic configuration file templating tool for kubernetes manifest or general configuration files.
  • ctc - The non-invasive cross-platform terminal color library does not need to modify the Print method.
  • Go-ataman - Go library for rendering ANSI colored text templates in terminals.

1 - Asciigraph: Go package to make lightweight ASCII line graph ╭┈╯ in command line apps with no other dependencies.

Go package to make lightweight ASCII line graphs ╭┈╯.

Installation

go get github.com/guptarohit/asciigraph

Usage

Basic graph

package main

import (
    "fmt"
    "github.com/guptarohit/asciigraph"
)

func main() {
    data := []float64{3, 4, 9, 6, 2, 4, 5, 8, 5, 10, 2, 7, 2, 5, 6}
    graph := asciigraph.Plot(data)

    fmt.Println(graph)
}

Running this example would render the following graph:

  10.00 ┤        ╭╮
   9.00 ┤ ╭╮     ││
   8.00 ┤ ││   ╭╮││
   7.00 ┤ ││   ││││╭╮
   6.00 ┤ │╰╮  ││││││ ╭
   5.00 ┤ │ │ ╭╯╰╯│││╭╯
   4.00 ┤╭╯ │╭╯   ││││
   3.00 ┼╯  ││    ││││
   2.00 ┤   ╰╯    ╰╯╰╯

Multiple Series

package main

import (
    "fmt"
    "github.com/guptarohit/asciigraph"
)

func main() {
	data := [][]float64{{0, 1, 2, 3, 3, 3, 2, 0}, {5, 4, 2, 1, 4, 6, 6}}
	graph := asciigraph.PlotMany(data)

	fmt.Println(graph)
}

Running this example would render the following graph:

 6.00 ┤    ╭─
 5.00 ┼╮   │
 4.00 ┤╰╮ ╭╯
 3.00 ┤ │╭│─╮
 2.00 ┤ ╰╮│ ╰╮
 1.00 ┤╭╯╰╯  │
 0.00 ┼╯     ╰

View on Github

2 - Aurora: ANSI terminal colors that supports fmt.Printf/Sprintf.

Ultimate ANSI colors for Golang. The package supports Printf/Sprintf etc.

Installation

Version 1.x

Using gopkg.in.

go get -u gopkg.in/logrusorgru/aurora.v1

Version 2.x

go get -u github.com/logrusorgru/aurora

Go modules support, version v3+

Get

go get -u github.com/logrusorgru/aurora/v3

The v3 was introduced to support go.mod and leave previous import paths as is. Currently, there is no changes between them (excluding the importpath's /v3 tail).

Test

go test -cover github.com/logrusorgru/aurora/v3

Replace the import path with your, if it's different.

Usage

Simple

package main

import (
	"fmt"

	. "github.com/logrusorgru/aurora"
)

func main() {
	fmt.Println("Hello,", Magenta("Aurora"))
	fmt.Println(Bold(Cyan("Cya!")))
}

simple png

View on Github

3 - Box-cli-maker: Make Highly Customized Boxes for your CLI.

Box CLI Maker is a Highly Customized Terminal Box Creator.

Installation

 go get github.com/Delta456/box-cli-maker/v2

Usage

In main.go

package main

import "github.com/Delta456/box-cli-maker/v2"

func main() {
 Box := box.New(box.Config{Px: 2, Py: 5, Type: "Single", Color: "Cyan"})
 Box.Print("Box CLI Maker", "Highly Customized Terminal Box Maker")
}

box.New(config Config) accepts a Config struct with following parameters and returns a Box struct.

  • Parameters
    • Px : Horizontal Padding
    • Py : Vertical Padding
    • ContentAlign : Align the content inside the Box i.e. Center, Left and Right
    • Type: Type of Box
    • TitlePos : Position of the Title i.e. Inside, Top and Bottom
    • Color : Color of the Box

Box struct Methods

Box.Print(title, lines string) prints Box from the specified arguments.

  • Parameters
    • title : Title of the Box
    • lines : Content to be written inside the Box

Box.Println(title, lines string) prints Box in a newline from the specified arguments.

  • Parameters
    • title : Title of the Box
    • lines : Content to be written inside the Box

Box.String(title, lines string) string return string representation of Box.

  • Parameters
    • title : Title of the Box
    • lines : Content to be written inside the Box

View on Github

4 - cfmt: Contextual fmt inspired by bootstrap color classes.

It provides contextual formatting functions that have nearly identical usage of the fmt package. The ideas were borrowed from bootstrap's contextual color classes.

Installation

go get github.com/mingrammer/cfmt

Usage

package main

import (
    "log"

    "github.com/mingrammer/cfmt"
)

func main() {
    cfmt.Success("User was created successfully")
    cfmt.Infoln("Here are some candidates")
    cfmt.Warningf("%s is not valid integer value\n", "123a")
    log.Fatal(cfmt.Serrorf("Only numeric is allowed, got %s", "123.456a"))
}

cfmt output

View on Github

5 - cfmt: Simple and convenient formatted stylized output fully compatible with fmt library.

cfmt is a small library for simple and convenient formatted stylized output to the console, providing an interface that is exactly the same as the standard fmt and log libraries.

Install

go get -v github.com/i582/cfmt

Usage

To switch to cfmt anywhere in the code, it is enough to add one letter c to fmt (or to log), import the required part (cfmt or clog):

import (
	"github.com/i582/cfmt/cmd/cfmt"
	// or
	"github.com/i582/cfmt/cmd/clog"
)

and you get all the possibilities, the library is fully compatible with the standard libraries fmt and log

Simple usage

Let's take an example:

Suppose you need to display text and highlight some word or phrase. Using cfmt, all that is needed is to wrap the desired part in {{}} and after :: write the desired styles:

cfmt.Println("This is a {{red color}}::red")

If we compare this with the gookit/color library, then this example looks more complicated and less readable there:

fmt.Printf("This is a %s", color.Red.Sprintf("red color"))

View on Github

6 - Chalk: Intuitive package for prettifying terminal/console output.

Chalk is a go package for styling console/terminal output.

The api is pretty clean, there are default Colors and TextStyles which can be mixed to create more intense Styles. Styles and Colors can be printed in normal strings (i.e. fmt.Sprintf(chalk.Red)), but Styles, Colors and TextStyles are more meant to be used to style specific text segments (i.e. fmt.Println(chalk.Red.Color("this is red")) or fmt.Println(myStyle.Style("this is blue text that is underlined"))).

Examples

There are a few examples in the examples directory if you want to see a very simplified version of what you can do with chalk.

The following code:

package main

import (
	"fmt"

	"github.com/ttacon/chalk"
)

func main() {
	// You can just use colors
	fmt.Println(chalk.Red, "Writing in colors", chalk.Cyan, "is so much fun", chalk.Reset)
	fmt.Println(chalk.Magenta.Color("You can use colors to color specific phrases"))

	// You can just use text styles
	fmt.Println(chalk.Bold.TextStyle("We can have bold text"))
	fmt.Println(chalk.Underline.TextStyle("We can have underlined text"))
	fmt.Println(chalk.Bold, "But text styles don't work quite like colors :(")

	// Or you can use styles
	blueOnWhite := chalk.Blue.NewStyle().WithBackground(chalk.White)
	fmt.Printf("%s%s%s\n", blueOnWhite, "And they also have backgrounds!", chalk.Reset)
	fmt.Println(
		blueOnWhite.Style("You can style strings the same way you can color them!"))
	fmt.Println(
		blueOnWhite.WithTextStyle(chalk.Bold).
			Style("You can mix text styles with colors, too!"))

	// You can also easily make styling functions thanks to go's functional side
	lime := chalk.Green.NewStyle().
		WithBackground(chalk.Black).
		WithTextStyle(chalk.Bold).
		Style
	fmt.Println(lime("look at this cool lime text!"))
}

View on Github

7 - Colourize: Go library for ANSI colour text in terminals.

An ANSI colour terminal package for Go. Supports all ANSI colours and emphasis. Not compatible with Windows systems.

Project is no longer maintained.

This project is no longer maintained. However it's also complete. It has not and will not be updated with new Go features.

Installation

 go get github.com/TreyBastian/colourize 

Usage

package main
import (
    c "github.com/TreyBastian/colourize"
    "fmt"
)

func main() {
  fmt.Println(c.Colourize("Hello World!", c.Green, c.Whitebg, c.Bold))
}

View on Github

8 - Crab-config-files-templating: Dynamic configuration file templating tool for kubernetes manifest or general configuration files.

Dynamic configuration file templating tool for kubernetes manifest or general configuration files. 

How to install

Download according to your computer architecture at release page go to release page

OSPlatformStatus
Ubuntu, Debianamd64, arm64, 386available
MacOS, Darwinamd64, arm64, 386available
Windowsamd64, arm64, 386available

Extract using command like :

tar -xzf crab-cli-v0.1.0-darwin-amd64.tar.gz -C crab

Move to /usr/local/bin (Optional) :

cp crab/crab /usr/local/bin

Then check crab cli working properly :

Build From Source

  • clone this repository
  • make sure you have go version 18
  • run make build

How to use

basic command fromat :

  crab -f <fileinputpath> -r <keyvalue> -o <outputfilepath>

View on Github

9 - ctc: The non-invasive cross-platform terminal color library does not need to modify the Print method.

The non-invasive cross-platform terminal color library does not need to modify the Print method

Support style

  •  console
    •  unix-like (mac & linux)
    •  windows

example

package main

import (
	"fmt"

	"github.com/wzshiming/ctc"
)

func main() {
	// No invasion
	fmt.Println(ctc.BackgroundRed|ctc.ForegroundBlue, "Hello world", ctc.Reset)
}

SGR (Select Graphic Rendition)

ValueDescriptionBehavior
0DefaultReturns all attributes to the default state prior to modification
4UnderlineAdds underline
7NegativeSwaps foreground and background colors
30~37ForegroundApplies non-bold/bright color to foreground
40~47BackgroundApplies non-bold/bright color to background
90~97Bright ForegroundApplies bold/bright color to foreground
100~107Bright BackgroundApplies bold/bright color to background

View on Github

10 - Go-ataman: Go library for rendering ANSI colored text templates in terminals.

The goal of the project is to help render colored text in terminal applications with text attribute manipulation contained in text template. The idea is similar to HTML, e.g. <span style="color:green">Hello!</span>

ataman is not a full-featured template processor. It aims only on simple terminal text attribute, graphic mode in ANSI terms, manipulations using ANSI sequences.

Installation

To install the package use go get gopkg.in/workanator/go-ataman.v1

Quick Example

The next example shows basic usage of the package. The renderer here uses basic decoration style.

rndr := ataman.NewRenderer(ataman.BasicStyle())
tpl := "<light+green>%s<->, <bg+light+yellow,black,bold> <<%s>> <-><red>!"
fmt.Println(rndr.MustRenderf(tpl, "Hello", "Terminal World"))

This example produces colored text like this.

Example Output

Renderer is able to pre-render templates so in further output operations they can be reused without parsing and rendering. In this example the renderer uses curly brackets decoration style.

rndr := ataman.NewRenderer(ataman.CurlyStyle())
prep := rndr.MustPrepare("{light_green}%s{-}, {bg_light_yellow+black+bold} <%s> {-}{red}!")
fmt.Println(rndr.MustRenderf(tpl, "Hi", "Everybody"))

The pre-rendered template implements fmt.Stringer interface so it can be used in output operations without additional code, e.g.

prep := rndr.MustPrepare("{red}Red {green}Green {blue}Blue{-}")
fmt.Println(prep)

View on Github

Thank you for following this article.

Related videos:

Golang UI Frameworks You MUST Learn 2022

#go #golang #console 

10 Popular Libraries for Advanced Console UIs in Go
Lawrence  Lesch

Lawrence Lesch

1662416880

Inspect JavaScript Object Methods and Properties In The Console

console-probe

Inspect JavaScript object methods and properties in the console.  

Event Emitter Example

NPM

Provides colourful functions to inspect JavaScript objects.

  • The probe() function outputs a prototype hierarchy tree to the console.
  • The json() function safely writes a stringified object output to the console.
  • The yaml() function converts objects into yaml format and outputs to the console.
  • The ls() function converts objects into a colourful format and outputs to the console.

Installing

  • Node: v6.0.0 or later.
  • Browser: Not tested
npm install --save-dev console-probe

Quick Start

Not recommended for production environments


const cp = require('./console-probe')
const arrLen = 2

const aussieSlang = {
  'name': 'Aussie Slang Words',
  'gday': Infinity,
  'maccas': Number.NaN,
  'arvo': undefined,
  'straya': null,
  'footy': {specky: true},
  'biccy': (size, toppings) => {},
  'servo': true,
  'choccy': Symbol('Mmmmm...'),
  'bottle-o': Error('Cheers mate! My shout next'),
  'tinny': 42,
  'coppa': new Date(),
  'tradie': 'She\'ll be right mate?',
  'postie': /a.long.regexp.that.keeps.giving/,
  'garbo': [1, 2, 3],
  'muso': new Int8Array(arrLen),
  'cabbie': new Uint8Array(arrLen),
  'ambo': new Uint8ClampedArray(arrLen),
  'prezzie': new Int16Array(arrLen),
  'chrissie': new Uint16Array(arrLen),
  'cuppa': new Int32Array(arrLen),
  'mate': new Uint32Array(arrLen),
  'snag': new Float32Array(arrLen),
  'drongo': new Float64Array(arrLen),
  'fairDinkum': new Map([['foo', 'bar']]),
  'bonza': new Set([['foo', 'bar']]),
  'tooRight': new WeakMap(),
  'dunny': new WeakSet(),
  'cobber': new ArrayBuffer(arrLen),
  'barbie': new SharedArrayBuffer(arrLen),
  'stickybeak': Atomics,
  'stoked': new DataView(new ArrayBuffer(arrLen)),
  'ripper': Promise.resolve(),
  'mongrel': (function * () {})(),
  'holyDooley': function * (foo, bar) {},
  'roo': async function (foo, bar) {}
}
const secret = Symbol('Hidden Property')
aussieSlang[secret] = 'Bogan'

// Calling console-probe functions.
cp.probe(aussieSlang) // Writes a prototype tree to the console
cp.json(aussieSlang) // Writes a JSON formatted object to the console
cp.yaml(aussieSlang) // Writes a YAML formatted object to the console
cp.ls(aussieSlang) // Writes a formatted object to the console

// Adding console-probe functions to the console.
console.probe(aussieSlang) // Throws exception 'console.probe is not a function'
console.json(aussieSlang) // Throws exception 'console.json is not a function'
console.yaml(aussieSlang) // Throws exception 'console.yaml is not a function'
console.ls(aussieSlang) // Throws exception 'console.ls is not a function'
cp.apply()
console.probe(aussieSlang) // Writes a prototype tree to the console
console.json(aussieSlang) // Writes a JSON formatted object to the console
console.yaml(aussieSlang) // Writes a YAML formatted object to the console
console.ls(aussieSlang) // Writes a formatted object to the console

// Adding console-probe functions to an object.
const foo = {}
cp.apply(foo)
foo.probe(aussieSlang) // Writes prototype tree to the console
foo.json(aussieSlang) // Writes a JSON formatted object to the console
foo.yaml(aussieSlang) // Writes a YAML formatted object to the console
foo.ls(aussieSlang) // Writes a formatted object to the console

The above code will produce the following results when it writes to the console.

The probe function output:

Note: Type detection errors will display as [Unknown].

Example Probe Output

The json function output:

Example Json Output

The yaml function output:

Example Yaml Output

The ls function output:

Example ls Output

Rational

There are many amazing packages on npm. Many of those packages are not well documented. Rather than go straight to reading source code I wrote console-probe to inspect objects and discover methods and properties. Using Node.js with inspect is often a better approach however I don't always have it running; this is when console-probe comes in handy.

Function

The console-probe package provides four functions that will write to the console:

  • probe(obj): The probe function uses Object.getOwnPropertyNames() and Object.getOwnPropertySymbols() to enumerate the members of an object through its prototype hierarchy. Using the type list from MDN the types are detected. After a little formatting the result is written to the console using the archy package with some colour added by chalk.
  • json(obj, replacer, spacer, color): Uses fast-safe-stringify and json-colorizer to safely write the stringified object out to the console.
  • yaml(obj, options, indentation): A simple wrapper around the prettyjson package render function.
  • ls(obj): A simple wrapper around the jsome package render function.

API

probe Function

Description: Inspects the passed objects properties and methods, then the prototype of the passed object, and so on till the last prototype is analyzed. A tree of the properties and methods on each prototype is written to the console.

Method Signature: probe(object)

Parameter: object can be any JavaScript type.

Details:

  • Passing either null or undefined will write [console-probe] Invalid Type: to the console.
  • String values with newline characters are stripped from string stubs.

Example:

const cp = require('console-probe')
cp.probe({ key: 'value' })
// Writes the object prototype hierarchy to the console
// See above for an example of the output

json Function

Description: This function simply calls fast-safe-stringify and then adds color via json-colorizer. Once that is done it writes the result to the console.

Method Signature: json(object, replacer, spacer, color)

Parameter:

  • object can be any object you wish to stringify.
  • replacer alters the behavior of the stringification process.
  • spacer inserts white space into the output JSON string for readability purposes.
  • color enables customization of the colour displayed.

Details:

Example:

const cp = require('console-probe')
cp.json({ key: 'value' })
// Outputs the following to the console:
// {
//   "key": "value"
// }

yaml Function

Description: This function wraps the prettyjson render function and writes the result to the console. The result is a colorized formatted YAML representation of the object data.

Signature: yaml(object, options, indentation)

Parameter:

  • object can be any object you wish to display in YAML format.
  • options should hold options for the prettyjson render function.
  • indentation controls the indentation for the YAML output.

Details:

  • The yaml function is simply a wrapper around the prettyjson package.
  • See the prettyjson documentation and code for the options and indentation.

Example:

const cp = require('console-probe')
cp.yaml({ key: 'value' })
// Outputs the following to the console:
// key: value

ls Function

Description: This function wraps the jsome render function and writes the result to the console. The result is a colorized formatted representation of the object data.

Signature: ls(object)

Parameter:

  • object can be any object you wish to display.

Details:

  • The ls function is simply a wrapper around the jsome package.
  • See the jsome documentation for more detail.

Example:

const cp = require('console-probe')
cp.ls({ key: 'value' })
// Outputs the following to the console:
// {
//   key: "value"
// }

apply Function

Signature: apply(object)

Parameter: object can be any object you would like to add console-probe functions to.

Details:

  • The apply function is a convenience method to add the console-probe functions to an object.
  • If no object is passed to the apply function then the console-probe functions will be added to the console object.
  • Passing an object, such as a logger, will add the console-probe functions to the object.

Example:

const cp = require('console-probe')
cp.apply()
// console now has a probe, json, yaml, and ls functions.

const foo = {}
cp.apply(foo)
// foo now has a probe, json, yaml, and ls functions.

Another approach to simply augment the console:

require('console-probe').apply()
// console.probe, console.json, console.yaml, and console.ls are now ready for use.

About the Owner

I, Grant Carthew, am a technologist, trainer, and Dad from Queensland, Australia. I work on code in a number of personal projects and when the need arises I build my own packages.

This project exists because I wanted to inspect objects from the console.

Everything I do in open source is done in my own time and as a contribution to the open source community.

If you are using my projects and would like to thank me or support me, please click the Patreon link below.

Patreon Donation

See my other projects on NPM.

Contributing

  1. Fork it!
  2. Create your feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request :D

Change Log

  • v3.3.2 [2019-10-14]: Added 'name' to the name getter.
  • v3.3.1 [2019-10-14]: Fixed Getter support (#5). Removed NSP from readme.
  • v3.3.0 [2018-07-05]: Added new method ls. Fixed README badges. Fixed null/undefined error.
  • v3.2.1 [2018-07-05]: Added BigInt type support. Updated dependencies.
  • v3.2.0 [2018-03-02]: Multiple type support. Probe format updated.
  • v3.1.0 [2018-02-19]: Added colour to json. Added yaml function.
  • v3.0.0 [2018-02-18]: Added json function. Improved API. Removed newline chrs.
  • v2.0.4 [2018-01-29]: Changed node label format.
  • v2.0.3 [2018-01-26]: Fix example image url.
  • v2.0.2 [2018-01-26]: Added support for arrays and values. Fixed sort.
  • v2.0.1 [2018-01-25]: Added repository url to package.json.
  • v2.0.0 [2018-01-24]: Changed API. Improved type support.
  • v1.0.2 [2018-01-23]: Updated Readme.
  • v1.0.1 [2018-01-23]: Updated NSP link.
  • v1.0.0 [2018-01-23]: Initial release.

Download Details:

Author: Grantcarthew
Source Code: https://github.com/grantcarthew/node-console-probe 
License: MIT license

#javascript #node #console 

Inspect JavaScript Object Methods and Properties In The Console
Elian  Harber

Elian Harber

1661338860

Chroma: A General Purpose Syntax Highlighter in Pure Go

Chroma — A general purpose syntax highlighter in pure Go  

NOTE: As Chroma has just been released, its API is still in flux. That said, the high-level interface should not change significantly.

Chroma takes source code and other structured text and converts it into syntax highlighted HTML, ANSI-coloured text, etc.

Chroma is based heavily on Pygments, and includes translators for Pygments lexers and styles.

Supported languages

PrefixLanguage
AABAP, ABNF, ActionScript, ActionScript 3, Ada, Angular2, ANTLR, ApacheConf, APL, AppleScript, Arduino, Awk
BBallerina, Base Makefile, Bash, Batchfile, BibTeX, Bicep, BlitzBasic, BNF, Brainfuck
CC, C#, C++, Caddyfile, Caddyfile Directives, Cap'n Proto, Cassandra CQL, Ceylon, CFEngine3, cfstatement, ChaiScript, Chapel, Cheetah, Clojure, CMake, COBOL, CoffeeScript, Common Lisp, Coq, Crystal, CSS, Cython
DD, Dart, Diff, Django/Jinja, Docker, DTD, Dylan
EEBNF, Elixir, Elm, EmacsLisp, Erlang
FFactor, Fish, Forth, Fortran, FSharp
GGAS, GDScript, Genshi, Genshi HTML, Genshi Text, Gherkin, GLSL, Gnuplot, Go, Go HTML Template, Go Text Template, GraphQL, Groff, Groovy
HHandlebars, Haskell, Haxe, HCL, Hexdump, HLB, HTML, HTTP, Hy
IIdris, Igor, INI, Io
JJ, Java, JavaScript, JSON, Julia, Jungle
KKotlin
LLighttpd configuration file, LLVM, Lua
MMako, markdown, Mason, Mathematica, Matlab, MiniZinc, MLIR, Modula-2, MonkeyC, MorrowindScript, Myghty, MySQL
NNASM, Newspeak, Nginx configuration file, Nim, Nix
OObjective-C, OCaml, Octave, OnesEnterprise, OpenEdge ABL, OpenSCAD, Org Mode
PPacmanConf, Perl, PHP, PHTML, Pig, PkgConfig, PL/pgSQL, plaintext, Pony, PostgreSQL SQL dialect, PostScript, POVRay, PowerShell, Prolog, PromQL, Protocol Buffer, Puppet, Python 2, Python
QQBasic
RR, Racket, Ragel, Raku, react, ReasonML, reg, reStructuredText, Rexx, Ruby, Rust
SSAS, Sass, Scala, Scheme, Scilab, SCSS, Smalltalk, Smarty, Snobol, Solidity, SPARQL, SQL, SquidConf, Standard ML, Stylus, Svelte, Swift, SYSTEMD, systemverilog
TTableGen, TASM, Tcl, Tcsh, Termcap, Terminfo, Terraform, TeX, Thrift, TOML, TradingView, Transact-SQL, Turing, Turtle, Twig, TypeScript, TypoScript, TypoScriptCssData, TypoScriptHtmlData
VVB.net, verilog, VHDL, VimL, vue
WWDTE
XXML, Xorg
YYAML, YANG
ZZig

I will attempt to keep this section up to date, but an authoritative list can be displayed with chroma --list.

Try it

Try out various languages and styles on the Chroma Playground.

Using the library

Chroma, like Pygments, has the concepts of lexers, formatters and styles.

Lexers convert source text into a stream of tokens, styles specify how token types are mapped to colours, and formatters convert tokens and styles into formatted output.

A package exists for each of these, containing a global Registry variable with all of the registered implementations. There are also helper functions for using the registry in each package, such as looking up lexers by name or matching filenames, etc.

In all cases, if a lexer, formatter or style can not be determined, nil will be returned. In this situation you may want to default to the Fallback value in each respective package, which provides sane defaults.

Quick start

A convenience function exists that can be used to simply format some source text, without any effort:

err := quick.Highlight(os.Stdout, someSourceCode, "go", "html", "monokai")

Identifying the language

To highlight code, you'll first have to identify what language the code is written in. There are three primary ways to do that:

Detect the language from its filename.

lexer := lexers.Match("foo.go")

Explicitly specify the language by its Chroma syntax ID (a full list is available from lexers.Names()).

lexer := lexers.Get("go")

Detect the language from its content.

lexer := lexers.Analyse("package main\n\nfunc main()\n{\n}\n")

In all cases, nil will be returned if the language can not be identified.

if lexer == nil {
  lexer = lexers.Fallback
}

At this point, it should be noted that some lexers can be extremely chatty. To mitigate this, you can use the coalescing lexer to coalesce runs of identical token types into a single token:

lexer = chroma.Coalesce(lexer)

Formatting the output

Once a language is identified you will need to pick a formatter and a style (theme).

style := styles.Get("swapoff")
if style == nil {
  style = styles.Fallback
}
formatter := formatters.Get("html")
if formatter == nil {
  formatter = formatters.Fallback
}

Then obtain an iterator over the tokens:

contents, err := ioutil.ReadAll(r)
iterator, err := lexer.Tokenise(nil, string(contents))

And finally, format the tokens from the iterator:

err := formatter.Format(w, style, iterator)

The HTML formatter

By default the html registered formatter generates standalone HTML with embedded CSS. More flexibility is available through the formatters/html package.

Firstly, the output generated by the formatter can be customised with the following constructor options:

  • Standalone() - generate standalone HTML with embedded CSS.
  • WithClasses() - use classes rather than inlined style attributes.
  • ClassPrefix(prefix) - prefix each generated CSS class.
  • TabWidth(width) - Set the rendered tab width, in characters.
  • WithLineNumbers() - Render line numbers (style with LineNumbers).
  • LinkableLineNumbers() - Make the line numbers linkable and be a link to themselves.
  • HighlightLines(ranges) - Highlight lines in these ranges (style with LineHighlight).
  • LineNumbersInTable() - Use a table for formatting line numbers and code, rather than spans.

If WithClasses() is used, the corresponding CSS can be obtained from the formatter with:

formatter := html.New(html.WithClasses(true))
err := formatter.WriteCSS(w, style)

More detail

Lexers

See the Pygments documentation for details on implementing lexers. Most concepts apply directly to Chroma, but see existing lexer implementations for real examples.

In many cases lexers can be automatically converted directly from Pygments by using the included Python 3 script pygments2chroma.py. I use something like the following:

python3 _tools/pygments2chroma.py \
  pygments.lexers.jvm.KotlinLexer \
  > lexers/k/kotlin.go \
  && gofmt -s -w lexers/k/kotlin.go

See notes in pygments-lexers.txt for a list of lexers, and notes on some of the issues importing them.

Formatters

Chroma supports HTML output, as well as terminal output in 8 colour, 256 colour, and true-colour.

A noop formatter is included that outputs the token text only, and a tokens formatter outputs raw tokens. The latter is useful for debugging lexers.

Styles

Chroma styles use the same syntax as Pygments.

All Pygments styles have been converted to Chroma using the _tools/style.py script.

When you work with one of Chroma's styles, know that the chroma.Background token type provides the default style for tokens. It does so by defining a foreground color and background color.

For example, this gives each token name not defined in the style a default color of #f8f8f8 and uses #000000 for the highlighted code block's background:

chroma.Background: "#f8f8f2 bg:#000000",

Also, token types in a style file are hierarchical. For instance, when CommentSpecial is not defined, Chroma uses the token style from Comment. So when several comment tokens use the same color, you'll only need to define Comment and override the one that has a different color.

For a quick overview of the available styles and how they look, check out the Chroma Style Gallery.

Command-line interface

A command-line interface to Chroma is included.

Binaries are available to install from the releases page.

The CLI can be used as a preprocessor to colorise output of less(1), see documentation for the LESSOPEN environment variable.

The --fail flag can be used to suppress output and return with exit status 1 to facilitate falling back to some other preprocessor in case chroma does not resolve a specific lexer to use for the given file. For example:

export LESSOPEN='| p() { chroma --fail "$1" || cat "$1"; }; p "%s"'

Replace cat with your favourite fallback preprocessor.

When invoked as .lessfilter, the --fail flag is automatically turned on under the hood for easy integration with lesspipe shipping with Debian and derivatives; for that setup the chroma executable can be just symlinked to ~/.lessfilter.

What's missing compared to Pygments?

  • Quite a few lexers, for various reasons (pull-requests welcome):
    • Pygments lexers for complex languages often include custom code to handle certain aspects, such as Raku's ability to nest code inside regular expressions. These require time and effort to convert.
    • I mostly only converted languages I had heard of, to reduce the porting cost.
  • Some more esoteric features of Pygments are omitted for simplicity.
  • Though the Chroma API supports content detection, very few languages support them. I have plans to implement a statistical analyser at some point, but not enough time.

Download Details:

Author: Alecthomas
Source Code: https://github.com/alecthomas/chroma 
License: MIT license

#go #golang #html #console 

Chroma: A General Purpose Syntax Highlighter in Pure Go
Lawrence  Lesch

Lawrence Lesch

1661013180

Signale: Highly Configurable Logging Utility

Signale

Highly configurable logging utility

Header

Description

Hackable and configurable to the core, signale can be used for logging purposes, status reporting, as well as for handling the output rendering process of other node modules and applications.

Read this document in: 简体中文.

You can now support the development process through GitHub Sponsors.

Visit the contributing guidelines to learn more on how to translate this document into more languages.

Come over to Gitter or Twitter to share your thoughts on the project.

Highlights

  • 19 out-of-the-box loggers
  • Hackable to the core
  • Clean and beautiful output
  • Integrated timers
  • Custom pluggable loggers
  • TypeScript support
  • Interactive and regular modes
  • Secrets & sensitive information filtering
  • Filename, date and timestamp support
  • Scoped loggers and timers
  • Scaled logging levels mechanism
  • String interpolation support
  • Multiple configurable writable streams
  • Simple and minimal syntax
  • Globally configurable through package.json
  • Overridable configuration per file and logger

Install

Yarn

yarn add signale

NPM

npm install signale

Usage

Default Loggers

Import signale and start using any of the default loggers.

View all of the available loggers.
 

  • await
  • complete
  • error
  • debug
  • fatal
  • fav
  • info
  • note
  • pause
  • pending
  • star
  • start
  • success
  • wait
  • warn
  • watch
  • log
     
const signale = require('signale');

signale.success('Operation successful');
signale.debug('Hello', 'from', 'L59');
signale.pending('Write release notes for %s', '1.2.0');
signale.fatal(new Error('Unable to acquire lock'));
signale.watch('Recursively watching build directory...');
signale.complete({prefix: '[task]', message: 'Fix issue #59', suffix: '(@klauscfhq)'});

Default Loggers

Custom Loggers

To create a custom logger define an options object yielding a types field with the logger data and pass it as argument to a new signale instance.

const {Signale} = require('signale');

const options = {
  disabled: false,
  interactive: false,
  logLevel: 'info',
  scope: 'custom',
  secrets: [],
  stream: process.stdout,
  types: {
    remind: {
      badge: '**',
      color: 'yellow',
      label: 'reminder',
      logLevel: 'info'
    },
    santa: {
      badge: '🎅',
      color: 'red',
      label: 'santa',
      logLevel: 'info'
    }
  }
};

const custom = new Signale(options);
custom.remind('Improve documentation.');
custom.santa('Hoho! You have an unused variable on L45.');

Custom Loggers

Here is an example where we override the default error and success loggers.

const {Signale} = require('signale');

const options = {
  types: {
    error: {
      badge: '!!',
      label: 'fatal error'
    },
    success: {
      badge: '++',
      label: 'huge success'
    }
  }
};

const signale = new Signale();
signale.error('Default Error Log');
signale.success('Default Success Log');

const custom = new Signale(options);
custom.error('Custom Error Log');
custom.success('Custom Success Log');

Default Loggers

The options object can hold any of the following attributes: disabled, interactive, logLevel, secrets, stream, scope and types.

disabled

  • Type: Boolean
  • Default: false

Disables the logging functionality of all loggers belonging to the created instance.

interactive

  • Type: Boolean
  • Default: false

Switches all loggers belonging to the created instance into the interactive mode.

logLevel

  • Type: String
  • Default: 'info'

Sets the general logging level of the created instance. Can be one of the following:

  • 'info' - Displays all messages from all loggers.
  • 'timer' - Displays messages only from the time, timeEnd, debug, warn, error & fatal loggers.
  • 'debug' - Displays messages only from the debug, warn, error & fatal loggers.
  • 'warn' - Displays messages only from the warn, error & fatal loggers.
  • 'error' - Displays messages only from the error & fatal loggers.

secrets

  • Type: (String|Number)[]
  • Default: []

An array holding secrets/sensitive-information to be removed from the body and metadata of to-be-logged messages and replaced with the default '[secure]' string.

stream

  • Type: stream.Writable|stream.Writable[]
  • Default: process.stdout

Destination to which the data is written, can be a single valid Writable stream or an array holding multiple valid Writable streams.

scope

  • Type: String|String[]

Name of the scope the logger is reporting from.

types

  • Type: Object

Holds the configuration of the custom and default loggers.

Additionally, the configuration object of each custom/default logger type, defined in the types option, can hold any of the following attributes: badge, label, color, logLevel & stream.

badge

  • Type: String

The icon corresponding to the logger.

label

  • Type: String

The label used to identify the type of the logger.

color

  • Type: String

The color of the label, can be any of the foreground colors supported by chalk.

logLevel

  • Type: String
  • Default: 'info'

The log level corresponding to the logger. Messages originating from the logger are displayed only if the log level is greater or equal to the above described general logging level logLevel of the Signale instance.

stream

  • Type: stream.Writable|stream.Writable[]
  • Default: process.stdout

Destination to which the data is written, can be a single valid Writable stream or an array holding multiple valid Writable streams.

Scoped Loggers

To create a scoped logger from scratch, define the scope field inside the options object and pass it as argument to a new signale instance.

const {Signale} = require('signale');

const options = {
  scope: 'global scope'
};

const global = new Signale(options);
global.success('Successful Operation');

Scope Vanilla

To create a scoped logger based on an already existing one, use the scope() function, which will return a new signale instance, inheriting all custom loggers, timers, secrets, streams, configuration, log level, interactive mode & disabled statuses from the initial one.

const signale = require('signale');

const global = signale.scope('global scope');
global.success('Hello from the global scope');

function foo() {
  const outer = global.scope('outer', 'scope');
  outer.success('Hello from the outer scope');
  
  setTimeout(() => {
    const inner = outer.scope('inner', 'scope'); 
    inner.success('Hello from the inner scope');
  }, 500);
}

foo();

Scope Existing

Interactive Loggers

To initialize an interactive logger, create a new signale instance with the interactive attribute set to true. While into the interactive mode, previously logged messages originating from an interactive logger, will be overridden only by new ones originating from the same or a different interactive logger. Note that regular messages originating from regular loggers are not overridden by the interactive ones.

const {Signale} = require('signale');

const interactive = new Signale({interactive: true, scope: 'interactive'});

interactive.await('[%d/4] - Process A', 1);

setTimeout(() => {
  interactive.success('[%d/4] - Process A', 2);
  setTimeout(() => {
    interactive.await('[%d/4] - Process B', 3);
    setTimeout(() => {
      interactive.error('[%d/4] - Process B', 4);
      setTimeout(() => {}, 1000);
    }, 1000);
  }, 1000);
}, 1000);

Interactive Mode

Writable Streams

By default, all signale instances log their messages to the process.stdout stream. This can be modified, to match your own preference, through the stream property, where you can define a single or multiple valid Writable streams, which will be used by all logger types to log your data. Additionally, it is possible to define one or more Writable streams exclusively for a specific logger type, thus write data independently from the rest logger types.

const {Signale} = require('signale');

const options = {
  stream: process.stderr, // All loggers will now write to `process.stderr`
  types: {
    error: {
      // Only `error` will write to both `process.stdout` & `process.stderr`
      stream: [process.stdout, process.stderr]
    }
  }
};

const signale = new Signale(options);
signale.success('Message will appear on `process.stderr`');
signale.error('Message will appear on both `process.stdout` & `process.stderr`');

Writable Streams

Secrets Filtering

By utilizing the secrets option, secrets and other sensitive information can be filtered out from the body as well as the metadata, i.e. scope names etc, of to-be-logged messages. The option is part of the configuration object passed to a Signale instance on its initialization, and is of type Array<String|Number>. The array can hold multiple secrets, all of which are removed, if present, from the to-be-logged messages and are replaced with the default '[secure]' string. Additionally, when the unary signale.scope(name) function is used, the returned Signale instance inherits all the secrets belonging to its parent. The secrets checking process is performed in a case-sensitive manner. Also, the unary signale.addSecrets() and the nullary signale.clearSecrets() functions are available through the API for adding and clearing secrets respectively.

It is critical and highly recommended to not type directly secrets in your code, thus the following example serves only as a simple & easily reproducible usage demonstration.

const {Signale} = require('signale');

// In reality secrets could be securely fetched/decrypted through a dedicated API 
const [USERNAME, TOKEN] = ['klaussinani', 'token'];

const logger1 = new Signale({
  secrets: [USERNAME, TOKEN]
});

logger1.log('$ exporting USERNAME=%s', USERNAME);
logger1.log('$ exporting TOKEN=%s', TOKEN);

// `logger2` inherits all secrets from its parent `logger1`
const logger2 = logger1.scope('parent');

logger2.log('$ exporting USERNAME=%s', USERNAME);
logger2.log('$ exporting TOKEN=%s', TOKEN);

Secrets Filtering

Timers

Timer are managed by the time() and timeEnd() functions. A unique label can be used to identify a timer on initialization, though if none is provided the timer will be assigned one automatically. In addition, calling the timeEnd() function without a specified label will have as effect the termination of the most recently initialized timer, that was created without providing a label.

const signale = require('signale');

signale.time('test');
signale.time();
signale.time();

setTimeout(() => {
  signale.timeEnd();
  signale.timeEnd();
  signale.timeEnd('test');
}, 500);

Timers

Configuration

Global

To enable global configuration define the options under the signale namespace in your package.json.

The following illustrates all the available options with their respective default values.

{
  "signale": {
    "displayScope": true,
    "displayBadge": true,
    "displayDate": false,
    "displayFilename": false,
    "displayLabel": true,
    "displayTimestamp": false,
    "underlineLabel": true,
    "underlineMessage": false,
    "underlinePrefix": false,
    "underlineSuffix": false,
    "uppercaseLabel": false
  }
}

View all of the available options in detail.

Local

To enable local configuration call the config() function on your signale instance. Local configurations will always override any pre-existing configuration inherited from package.json.

In the following example, loggers in the foo.js file will run under their own configuration, overriding the package.json one.

// foo.js
const signale = require('signale');

// Overrides any existing `package.json` config
signale.config({
  displayFilename: true,
  displayTimestamp: true,
  displayDate: false
}); 

signale.success('Hello from the Global scope');

Local Config

Also, scoped loggers can have their own independent configuration, overriding the one inherited by the parent instance or package.json.

// foo.js
const signale = require('signale');

signale.config({
  displayFilename: true,
  displayTimestamp: true,
  displayDate: false
});

signale.success('Hello from the Global scope');

function foo() {
  // `fooLogger` inherits the config of `signale`
  const fooLogger = signale.scope('foo scope');

  // Overrides both `signale` and `package.json` configs
  fooLogger.config({
    displayFilename: true,
    displayTimestamp: false,
    displayDate: true
  });

  fooLogger.success('Hello from the Local scope');
}

foo();

Scope Config

API

signale.<logger>(message[, message]|messageObj|errorObj)

logger

  • Type: Function

Can be any default or custom logger.

message

  • Type: String

Can be one or more comma delimited strings.

const signale = require('signale');

signale.success('Successful operation');
//=> ✔  success  Successful operation

signale.success('Successful', 'operation');
//=> ✔  success  Successful operation

signale.success('Successful %s', 'operation');
//=> ✔  success  Successful operation

errorObj

  • Type: Error Object

Can be any error object.

const signale = require('signale');

signale.error(new Error('Unsuccessful operation'));
//=> ✖  error  Error: Unsuccessful operation
//        at Module._compile (module.js:660:30)
//        at Object.Module._extensions..js (module.js:671:10)
//        ...

messageObj

  • Type: Object

Can be an object holding the prefix, message and suffix attributes, with prefix and suffix always prepended and appended respectively to the logged message.

const signale = require('signale');

signale.complete({prefix: '[task]', message: 'Fix issue #59', suffix: '(@klaussinani)'});
//=> [task] ☒  complete  Fix issue #59 (@klaussinani)

signale.complete({prefix: '[task]', message: ['Fix issue #%d', 59], suffix: '(@klaussinani)'});
//=> [task] ☒  complete  Fix issue #59 (@klaussinani)

signale.scope(name[, name])

Defines the scope name of the logger.

name

  • Type: String

Can be one or more comma delimited strings.

const signale = require('signale');

const foo = signale.scope('foo'); 
const fooBar = signale.scope('foo', 'bar');

foo.success('foo');
//=> [foo] › ✔  success  foo

fooBar.success('foo bar');
//=> [foo] [bar] › ✔  success  foo bar

signale.unscope()

Clears the scope name of the logger.

const signale = require('signale');

const foo = signale.scope('foo'); 

foo.success('foo');
//=> [foo] › ✔  success  foo

foo.unscope();

foo.success('foo');
//=> ✔  success  foo

signale.config(settingsObj)

Sets the configuration of an instance overriding any existing global or local configuration.

settingsObj

  • Type: Object

Can hold any of the documented options.

// foo.js
const signale = require('signale');

signale.config({
  displayFilename: true,
  displayTimestamp: true,
  displayDate: true
});

signale.success('Successful operations');
//=> [2018-5-15] [11:12:38] [foo.js] › ✔  success  Successful operations

signale.time([, label])

  • Return Type: String

Sets a timers and accepts an optional label. If none provided the timer will receive a unique label automatically.

Returns a string corresponding to the timer label.

label

  • Type: String

Label corresponding to the timer. Each timer must have its own unique label.

const signale = require('signale');

signale.time();
//=> ▶  timer_0  Initialized timer...

signale.time();
//=> ▶  timer_1  Initialized timer...

signale.time('label');
//=> ▶  label    Initialized timer...

signale.timeEnd([, label])

  • Return Type: Object

Deactivates the timer to which the given label corresponds. If no label is provided the most recent timer, that was created without providing a label, will be deactivated.

Returns an object {label, span} holding the timer label and the total running time.

label

  • Type: String

Label corresponding to the timer, each timer has its own unique label.

const signale = require('signale');

signale.time();
//=> ▶  timer_0  Initialized timer...

signale.time();
//=> ▶  timer_1  Initialized timer...

signale.time('label');
//=> ▶  label    Initialized timer...

signale.timeEnd();
//=> ◼  timer_1  Timer run for: 2ms

signale.timeEnd();
//=> ◼  timer_0  Timer run for: 2ms

signale.timeEnd('label');
//=> ◼  label    Timer run for: 2ms

signale.disable()

Disables the logging functionality of all loggers belonging to a specific instance.

const signale = require('signale');

signale.success('foo');
//=> ✔  success  foo

signale.disable();

signale.success('foo');
//=>

signale.enable()

Enables the logging functionality of all loggers belonging to a specific instance.

const signale = require('signale');

signale.disable();

signale.success('foo');
//=>

signale.enable();

signale.success('foo');
//=> ✔  success  foo

signale.isEnabled()

Checks whether the logging functionality of a specific instance is enabled.

const signale = require('signale');

signale.success('foo');
//=> ✔  success  foo

signale.isEnabled();
// => true

signale.disable();

signale.success('foo');
//=>

signale.isEnabled();
// => false

signale.addSecrets(secrets)

Adds new secrets/sensitive-information to the targeted Signale instance.

secrets

  • Type: (String|Number)[]

Array holding the secrets/sensitive-information to be filtered out.

const signale = require('signale');

signale.log('$ exporting USERNAME=%s', 'klaussinani');
//=> $ exporting USERNAME=klaussinani signale.addSecrets(['klaussinani']);

signale.log('$ exporting USERNAME=%s', 'klaussinani');
//=> $ exporting USERNAME=[secure]

signale.clearSecrets()

Removes all secrets/sensitive-information from the targeted Signale instance.

const signale = require('signale');

signale.addSecrets(['klaussinani']);

signale.log('$ exporting USERNAME=%s', 'klaussinani');
//=> $ exporting USERNAME=[secure]

signale.clearSecrets();

signale.log('$ exporting USERNAME=%s', 'klaussinani');
//=> $ exporting USERNAME=klaussinani

Development

For more info on how to contribute to the project, please read the contributing guidelines.

  • Fork the repository and clone it to your machine
  • Navigate to your local fork: cd signale
  • Install the project dependencies: npm install or yarn install
  • Lint code for errors: npm test or yarn test

Related

  • qoa - Minimal interactive command-line prompts
  • taskbook - Tasks, boards & notes for the command-line habitat
  • hyperocean - Deep oceanic blue Hyper terminal theme

Who's Using It?

View in detail all the packages and repositories that are using Signale here.

Team

Download Details:

Author: Klaussinani
Source Code: https://github.com/klaussinani/signale 
License: MIT license

#javascript #node #cli #console #log 

Signale: Highly Configurable Logging Utility
Reid  Rohan

Reid Rohan

1660547940

Colorette: Easily Set Your Terminal Text Color & Styles

🌈Colorette

Easily set your terminal text color & styles.

  • No dependecies
  • Automatic color support detection
  • Up to 2x faster than alternatives
  • TypeScript support
  • NO_COLOR friendly
  • Node >= 10

Upgrading from Colorette 1.x?

Quickstart

import { blue, bold, underline } from "colorette"

console.log(
  blue("I'm blue"),
  bold(blue("da ba dee")),
  underline(bold(blue("da ba daa")))
)

Here's an example using template literals.

console.log(`
  There's a ${underline(blue("house"))},
  With a ${bold(blue("window"))},
  And a ${blue("corvette")}
  And everything is blue
`)

You can also nest styles without breaking existing color sequences.

console.log(bold(`I'm ${blue(`da ba ${underline("dee")} da ba`)} daa`))

Need to override terminal color detection? You can do that too.

import { createColors } from "colorette"

const { blue } = createColors({ useColor: false })

console.log(blue("Blue? Nope, nah"))

Installation

npm install colorette

API

<color>()

See all supported colors.

import { blue } from "colorette"

blue("I'm blue") //=> \x1b[34mI'm blue\x1b[39m

createColors()

Override terminal color detection via createColors({ useColor }).

import { createColors } from "colorette"

const { blue } = createColors({ useColor: false })

isColorSupported

true if your terminal supports color, false otherwise. Used internally, but exposed for convenience.

Environment

You can override color detection from the CLI by setting the --no-color or --color flags.

$ ./example.js --no-color | ./consumer.js

Or if you can't use CLI flags, by setting the NO_COLOR= or FORCE_COLOR= environment variables.

$ NO_COLOR= ./example.js | ./consumer.js

Supported colors

ColorsBackground ColorsBright ColorsBright Background ColorsModifiers
blackbgBlackblackBrightbgBlackBrightdim
redbgRedredBrightbgRedBrightbold
greenbgGreengreenBrightbgGreenBrighthidden
yellowbgYellowyellowBrightbgYellowBrightitalic
bluebgBlueblueBrightbgBlueBrightunderline
magentabgMagentamagentaBrightbgMagentaBrightstrikethrough
cyanbgCyancyanBrightbgCyanBrightreset
whitebgWhitewhiteBrightbgWhiteBright 
gray    

Benchmarks

npm --prefix bench start
  chalk         1,786,703 ops/sec
  kleur         1,618,960 ops/sec
  colors          646,823 ops/sec
  ansi-colors     786,149 ops/sec
  picocolors    2,871,758 ops/sec
+ colorette     3,002,751 ops/sec

Acknowledgments

Colorette started out in 2015 by @jorgebucaran as a lightweight alternative to Chalk and was introduced originally as Clor. Our terminal color detection logic borrows heavily from @sindresorhus and @Qix- work on Chalk. The idea of slicing strings to clear bleeding sequences was adapted from a similar technique used by @alexeyraspopov in picocolors. Thank you to all our contributors! <3

Download Details:

Author: jorgebucaran
Source Code: https://github.com/jorgebucaran/colorette 
License: MIT license

#javascript #cli #console #node #browser 

Colorette: Easily Set Your Terminal Text Color & Styles
Mike  Kozey

Mike Kozey

1660320000

Sprint: A tool for Printing Messages To The Web Console

The simplest way to print messages in your Dart project

Usage

If you like your code verbose, you may use long function names:

final log = Sprint('Sample', productionMode: false);

log.debug('Debug message');
log.success('Success message');
log.info('Info message');
log.warn('Warning message');
log.severe('Severe message');
log.fatal('Fatal message');

If you prefer to be brief in your writing, use short function names instead:

final log = Sprint('Sample', productionMode: false);

log.d('Debug message');
log.s('Success message');
log.i('Info message');
log.w('Warning message');
log.sv('Severe message');
log.f('Fatal message');

Most of the time, however, you will simply need to use the Sprint instance name:

log('Info message');

The display of messages can be controlled using the quietMode field. If set to true, no messages will be printed.

log.quietMode = true;
log('This message will not be posted.');

log.quietMode = false;
log('However, this one *will* be.');

Installing

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add sprint

With Flutter:

 $ flutter pub add sprint

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  sprint: ^1.0.4

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:sprint/sprint.dart';

example/example.dart

import 'package:sprint/sprint.dart';

class Server {
  final Sprint log = Sprint('Server');

  Future init() async {
    doWork();

    try {
      doCrucialButErrorProneWork();
    } on Exception catch (exception) {
      return log.fatal('Failed to initialise server: $exception');
    }

    log.info('Initialised server');
  }

  void doWork() {}
  void doCrucialButErrorProneWork() {}
}

Download Details:

Author: Wordcollector
Source Code: https://github.com/wordcollector/sprint 
License: MIT license

#flutter #dart #console #terminal #logger 

Sprint: A tool for Printing Messages To The Web Console
Nat  Grady

Nat Grady

1659526500

Radian: A 21 Century R Console

radian: A 21 century R console

radian is an alternative console for the R program with multiline editing and rich syntax highlight. One would consider radian as a ipython clone for R, though its design is more aligned to julia.

Features

  • cross platform, runs on Windows, macOS and Linux
  • shell mode: hit ; to enter and <backspace> to leave
  • reticulate python repl mode: hit ~ to enter
  • improved R prompt and reticulate python prompt
    • multiline editing
    • syntax highlight
    • auto completion (reticulate autocompletion depends on jedi)
  • unicode support
  • latex completion
  • auto matching parens/quotes.
  • bracketed paste mode
  • emacs/vi editing mode
  • automatically adjust to terminal width
  • read more than 4096 bytes per line

Installation

Requirements:

# install released version
pip3 install -U radian
# to run radian
radian
# or the development version
pip3 install -U git+https://github.com/randy3k/radian

Alternatively, if you use conda or miniconda,

conda install -c conda-forge radian

Alias on unix system

You could alias r to radian by putting

alias r="radian"

in ~/.bash_profile such that r would open radian and R would still open the traditional R console. (R is still useful, e.g, running R CMD BUILD.)

Settings

radian can be customized by specifying the below options in various locations

  • $XDG_CONFIG_HOME/radian/profile or $HOME/.config/radian/profile (Unix)
  • %USERPROFILE%/radian/profile (Windows)
  • $HOME/.radian_profile (Unix)
  • %USERPROFILE%/.radian_profile (Windows)
  • .radian_profile in the working directory

The options could be also specified in the .Rprofile files, however, it is not recommended because

  1. the settings are not persistent when vanilla mode is used;
  2. it doesn't work well with packrat or renv.
# Do not copy the whole configuration, just specify what you need!
# see https://help.farbox.com/pygments.html
# for a list of supported color schemes, default scheme is "native"
options(radian.color_scheme = "native")

# either  `"emacs"` (default) or `"vi"`.
options(radian.editing_mode = "emacs")
# enable various emacs bindings in vi insert mode
options(radian.emacs_bindings_in_vi_insert_mode = FALSE)
# show vi mode state when radian.editing_mode is `vi`
options(radian.show_vi_mode_prompt = TRUE)
options(radian.vi_mode_prompt = "\033[0;34m[{}]\033[0m ")

# indent continuation lines
# turn this off if you want to copy code without the extra indentation;
# but it leads to less elegent layout
options(radian.indent_lines = TRUE)

# auto match brackets and quotes
options(radian.auto_match = TRUE)

# enable the [prompt_toolkit](https://python-prompt-toolkit.readthedocs.io/en/master/index.html) [`auto_suggest` feature](https://python-prompt-toolkit.readthedocs.io/en/master/pages/asking_for_input.html#auto-suggestion)
# this option is experimental and is known to break python prompt, use it with caution
options(radian.auto_suggest = FALSE)

# highlight matching bracket
options(radian.highlight_matching_bracket = FALSE)

# auto indentation for new line and curly braces
options(radian.auto_indentation = TRUE)
options(radian.tab_size = 4)

# pop up completion while typing
options(radian.complete_while_typing = TRUE)
# the minimum length of prefix to trigger auto completions
options(radian.completion_prefix_length = 2)
# timeout in seconds to cancel completion if it takes too long
# set it to 0 to disable it
options(radian.completion_timeout = 0.05)
# add spaces around equals in function argument completion
options(radian.completion_adding_spaces_around_equals = TRUE)

# automatically adjust R buffer size based on terminal width
options(radian.auto_width = TRUE)

# insert new line between prompts
options(radian.insert_new_line = TRUE)

# max number of history records
options(radian.history_size = 20000)
# where the global history is stored, environmental variables will be expanded
# note that "~" is expanded to %USERPROFILE% or %HOME% in Windows
options(radian.global_history_file = "~/.radian_history")
# the filename that local history is stored, this file would be used instead of
# `radian.global_history_file` if it exists in the current working directory
options(radian.local_history_file = ".radian_history")
# when using history search (ctrl-r/ctrl-s in emacs mode), do not show duplicate results
options(radian.history_search_no_duplicates = FALSE)
# ignore case in history search
options(radian.history_search_ignore_case = FALSE)
# do not save debug browser commands such as `Q` in history
options(radian.history_ignore_browser_commands = TRUE)

# custom prompt for different modes
options(radian.prompt = "\033[0;34mr$>\033[0m ")
options(radian.shell_prompt = "\033[0;31m#!>\033[0m ")
options(radian.browse_prompt = "\033[0;33mBrowse[{}]>\033[0m ")

# stderr color format
options(radian.stderr_format = "\033[0;31m{}\033[0m")

# enable reticulate prompt and trigger `~`
options(radian.enable_reticulate_prompt = TRUE)

Custom key bindings

# allows user defined shortcuts, these keys should be escaped when send through the terminal.
# In the following example, `esc` + `-` sends `<-` and `esc` + `m` sends `%>%`.
# Note that in some terminals, you could mark `alt` as `escape` so you could use `alt` + `-` instead.
options(radian.escape_key_map = list(
    list(key = "-", value = " <- "),
    list(key = "m", value = " %>% ")
))

FAQ

Unicode doesn't work in Windows and R 4.2+.

The latest version of R supports Unicode codepage directly. However, radian relies on Python and Python doesn't support Unicode in the way that R supports it. A workaround could be found here: https://github.com/randy3k/radian/issues/269#issuecomment-1169663251

I can't specify python runtime in reticulate.

It is expected. radian runs on python and the python runtime used by radian is forced in reticulate. reticulate::py_config() gives the note:

NOTE: Python version was forced by the current process

In order to use radian with another python runtime, you will need to install radian on that python environment.

How to switch to a different R or specify the version of R.

There are serveral options.

  • The easiest option is to pass the path to the R binary with --r-binary, i.e., radian --r-binary=/path/to/R
  • Also, one could expose the path to the R binary in the PATH variable
  • The environment variable R_BINARY could also be used to specify the path to R.
  • The environment variable R_HOME could also be used to specify R home directory. Note that it is should be set as the result of R.home(), not the directory where R is located. For example, in Unix
$ env R_HOME=/usr/local/lib/R radian

Cannot find shared library

Please also make sure that R was installed with the R shared library libR.so or libR.dylib or libR.dll. On Linux, the configure flag ./configure --enable-R-shlib may be needed to install R from the source. Do not forget to make clean to force the recompilation of the files with the correct compiler options.

Outdated setuptools

If you encounter

The package setup script has attempted to modify files on your system that are not within the EasyInstall build area.

Please update your setuptools by

pip install -U setuptools

How to use local history file

radian maintains its own history file .radian_history and doesn't use the .Rhistory file. A local .radian_history is used if it is found in the launch directory. Otherwise, the global history file ~/.radian_history would be used. To override the default behavior, you could launch radian with the options: radian --local-history, radian --global-history or radian --no-history.

Does it slow down my R program?

radian only provides a frontend to the R program, the actual running eventloop is the same as that of the traditional R console. There is no performance sacrifice (or gain) while using this modern command line interface.

Nvim-R support

Put

let R_app = "radian"
let R_cmd = "R"
let R_hl_term = 0
let R_args = []  " if you had set any
let R_bracketed_paste = 1

in your vim config.

reticulate Auto Completions

To enable reticulate prompt completions, make sure that jedi is installed.

pip install jedi

Alternatively, if you use conda,

conda install -c conda-forge jedi

Prompt not shown inside a docker container

It maybe caused by the invalid terminal size, try running stty size in your terminal to see if it returns a correct size. You could change the values of it from the environmental variables $COLUMNS and $LINES when you log-in the docker container.

docker exec -it <container> bash -c "stty cols $COLUMNS rows $LINES && bash"

Why called radian?

radian is powered by (π)thon.

Credits

radian wouldn't be possible without the creative work prompt_toolkit by Jonathan Slenders.

Author: Randy3k
Source Code: https://github.com/randy3k/radian 
License: MIT license

#r #cli #console 

Radian: A 21 Century R Console
Rupert  Beatty

Rupert Beatty

1659272280

Laravel-langman: Language files manager in your artisan console

Laravel Langman

Langman is a language files manager in your artisan console, it helps you search, update, add, and remove translation lines with ease. Taking care of a multilingual interface is not a headache anymore.    

Installation

Begin by installing the package through Composer. Run the following command in your terminal:

$ composer require themsaid/laravel-langman

Once done, add the following line in your providers array of config/app.php:

Themsaid\Langman\LangmanServiceProvider::class

This package has a single configuration option that points to the resources/lang directory, if only you need to change the path then publish the config file:

php artisan vendor:publish --provider="Themsaid\Langman\LangmanServiceProvider"

Usage

Showing lines of a translation file

php artisan langman:show users

You get:

+---------+---------------+-------------+
| key     | en            | nl          |
+---------+---------------+-------------+
| name    | name          | naam        |
| job     | job           | baan        |
+---------+---------------+-------------+

php artisan langman:show users.name

Brings only the translation of the name key in all languages.


php artisan langman:show users.name.first

Brings the translation of a nested key.


php artisan langman:show package::users.name

Brings the translation of a vendor package language file.


php artisan langman:show users --lang=en,it

Brings the translation of only the "en" and "it" languages.


php artisan langman:show users.nam -c

Brings only the translation lines with keys matching the given key via close match, so searching for nam brings values for keys like (name, username, branch_name_required, etc...).

In the table returned by this command, if a translation is missing it'll be marked in red.

Finding a translation line

php artisan langman:find 'log in first'

You get a table of language lines where any of the values matches the given phrase by close match.

Searching view files for missing translations

php artisan langman:sync

This command will look into all files in resources/views and app and find all translation keys that are not covered in your translation files, after that it appends those keys to the files with a value equal to an empty string.

Filling missing translations

php artisan langman:missing

It'll collect all the keys that are missing in any of the languages or has values equals to an empty string, prompt asking you to give a translation for each, and finally save the given values to the files.

Translating a key

php artisan langman:trans users.name
php artisan langman:trans users.name.first
php artisan langman:trans users.name --lang=en
php artisan langman:trans package::users.name

Using this command you may set a language key (plain or nested) for a given group, you may also specify which language you wish to set leaving the other languages as is.

This command will add a new key if not existing, and updates the key if it is already there.

Removing a key

php artisan langman:remove users.name
php artisan langman:remove package::users.name

It'll remove that key from all language files.

Renaming a key

php artisan langman:rename users.name full_name

This will rename users.name to be users.full_name, the console will output a list of files where the key used to exist.

Notes

langman:sync, langman:missing, langman:trans, and langman:remove will update your language files by writing them completely, meaning that any comments or special styling will be removed, so I recommend you backup your files.

Web interface

If you want a web interface to manage your language files instead, I recommend Laravel 5 Translation Manager by Barry vd. Heuvel.

Author: Themsaid
Source Code: https://github.com/themsaid/laravel-langman 
License: MIT license

#laravel #files #console 

Laravel-langman: Language files manager in your artisan console
Nat  Grady

Nat Grady

1658618040

Electron-log: Just A Simple Logging Module for Your Electron App

electron-log

Just a simple logging module for your Electron or NW.js application. No dependencies. No complicated configuration. Just require and use. Also, it can be used without Electron in any node.js application.

By default, it writes logs to the following locations:

  • on Linux: ~/.config/{app name}/logs/{process type}.log
  • on macOS: ~/Library/Logs/{app name}/{process type}.log
  • on Windows: %USERPROFILE%\AppData\Roaming\{app name}\logs\{process type}.log

Installation

Install with npm:

npm install electron-log

Usage

const log = require('electron-log');

log.info('Hello, log');
log.warn('Some problem appears');

electron-log v2.x, v3.x

If you would like to upgrade to the latest version, read the migration guide and the changelog.

Log levels

electron-log supports the following log levels:

error, warn, info, verbose, debug, silly

nodeIntegration

If you've got an error like require is not defined in a renderer process, read the nodeIntegration section.

Transport

Transport is a simple function which does some work with log message. By default, two transports are active: console and file.

If you change some transport options, make sure you apply the changes both in main and renderer processes.

You can set transport options or use methods using:

log.transports.console.format = '{h}:{i}:{s} {text}';

log.transports.file.getFile();

Console transport

Just prints a log message to application console (main process) or to DevTools console (renderer process).

Options

  • format, default '%c{h}:{i}:{s}.{ms}%c › {text}' (main), '{h}:{i}:{s}.{ms} › {text}' (renderer)
  • level, default 'silly'
  • useStyles, use styles in the main process even if TTY isn't attached, default null

File transport

The file transport writes log messages to a file.

Options

  • format, default '[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}] {text}'
  • level, default 'silly'
  • resolvePath function sets the log path, for example
log.transports.file.resolvePath = () => path.join(APP_DATA, 'logs/main.log');

Read more about file transport.

IPC transport

When logging inside renderer process, it also shows log in application console and vice versa. This transport can impact on performance, so it's disabled by default for packaged application.

If you don't use electron-log in the main process but want to show renderer logs in the console, add require('electron-log') somewhere in the main code.

Options

  • level, default 'silly'

Remote transport

Sends a JSON POST request with LogMessage in the body to the specified url.

Options

  • level, default false
  • url, remote endpoint

Read more about remote transport.

Disable a transport

Just set level property to false, for example:

log.transports.file.level = false;
log.transports.console.level = false;

Override/add a custom transport

Transport is just a function (msg: LogMessage) => void, so you can easily override/add your own transport. More info.

Overriding console.log

Sometimes it's helpful to use electron-log instead of default console. It's pretty easy:

console.log = log.log;

If you would like to override other functions like error, warn and so on:

Object.assign(console, log.functions);

Colors

Colors can be used for both main and DevTools console.

log.info('%cRed text. %cGreen text', 'color: red', 'color: green')

Available colors:

  • unset (reset to default color)
  • black
  • red
  • green
  • yellow
  • blue
  • magenta
  • cyan
  • white

For DevTools console you can use other CSS properties.

Catch errors

electron-log can catch and log unhandled errors/rejected promises:

log.catchErrors(options?);

More info.

Hooks

In some situations, you may want to get more control over logging. Hook is a function which is called on each transport call.

(message: LogMessage, transport: Transport) => LogMessage

More info.

Multiple logger instances

You can create multiple logger instances with different settings:

const electronLog = require('electron-log');

const log = electronLog.create('anotherInstance');

Logging scopes

const log = require('electron-log');
const userLog = log.scope('user');

userLog.info('message with user scope');
// Prints 12:12:21.962 (user) › message with user scope

Web Worker

It's possible to use the module with Web Worker. However, ipc transport is not active, so log messages from worker are not displayed in the main app console.

Related

Author: Megahertz
Source Code: https://github.com/megahertz/electron-log 
License: MIT license

#electron #logging #console 

Electron-log: Just A Simple Logging Module for Your Electron App