1
0
mirror of https://github.com/chubin/cheat.sh.git synced 2026-06-20 13:16:44 +02:00

Merge pull request #264 from chubin/fixes

Show multiple cheat sheets when found (#147)
This commit is contained in:
Igor Chubin
2020-11-23 08:26:14 +01:00
committed by GitHub
9 changed files with 219 additions and 68 deletions
+2 -2
View File
@@ -11,7 +11,7 @@ Exports:
import re
import json
from routing import get_answer_dict, get_topics_list
from routing import get_answers, get_topics_list
from search import find_answers_by_keyword
from languages_data import LANGUAGE_ALIAS, rewrite_editor_section_name
import postprocessing
@@ -98,7 +98,7 @@ def cheat_wrapper(query, request_options=None, output_format='ansi'):
answers = find_answers_by_keyword(
topic, keyword, options=search_options, request_options=request_options)
else:
answers = [get_answer_dict(topic, request_options=request_options)]
answers = get_answers(topic, request_options=request_options)
answers = [
postprocessing.postprocess(
+12 -6
View File
@@ -101,6 +101,10 @@ def _visualize(answers, request_options, search_mode=False):
if color_style not in CONFIG['frontend.styles']:
color_style = ''
# if there is more than one answer,
# show the source of the answer
multiple_answers = len(answers) > 1
found = True
result = ""
for answer_dict in answers:
@@ -109,14 +113,16 @@ def _visualize(answers, request_options, search_mode=False):
answer = answer_dict['answer']
found = found and not topic_type == 'unknown'
if search_mode and topic != 'LIMITED':
if multiple_answers and topic != 'LIMITED':
section_name = f"{topic_type}:{topic}"
if not highlight:
result += "\n[%s]\n" % topic
result += f"#[{section_name}]\n"
else:
result += "\n%s%s %s %s%s\n" % (
colored.bg('dark_gray'), colored.attr("res_underlined"),
topic,
colored.attr("res_underlined"), colored.attr('reset'))
result += "".join([
"\n", colored.bg('dark_gray'), colored.attr("res_underlined"),
f" {section_name} ",
colored.attr("res_underlined"), colored.attr('reset'), "\n"])
if answer_dict['format'] in ['ansi', 'text']:
result += answer
+66 -35
View File
@@ -4,12 +4,13 @@ Queries routing and caching.
Exports:
get_topics_list()
get_answer_dict()
get_answers()
"""
from __future__ import print_function
import re
import random
import re
from typing import Any, Dict, List
import cache
import adapter.cheat_sheets
import adapter.cmd
@@ -83,20 +84,28 @@ class Router(object):
self._cached_topics_list = answer
return answer
def get_topic_type(self, topic):
def get_topic_type(self, topic: str) -> List[str]:
"""
Return topic type for `topic` or "unknown" if topic can't be determined.
Return list of topic types for `topic`
or ["unknown"] if topic can't be determined.
"""
def __get_topic_type(topic):
def __get_topic_type(topic: str) -> List[str]:
result = []
for regexp, route in self.routing_table:
if re.search(regexp, topic):
if route in self._adapter:
if self._adapter[route].is_found(topic):
return route
result.append(route)
else:
return route
return CONFIG["routing.default"]
result.append(route)
if not result:
return [CONFIG["routing.default"]]
# cut the default route off, if there are more than one route found
if len(result) > 1:
return result[:-1]
return result
if topic not in self._cached_topic_type:
self._cached_topic_type[topic] = __get_topic_type(topic)
@@ -111,7 +120,9 @@ class Router(object):
def handle_if_random_request(self, topic):
"""
Check if the `query` if a :random one, if yes we check its correctness and then randomly select a topic, based on the provided prefix.
Check if the `query` is a :random one,
if yes we check its correctness and then randomly select a topic,
based on the provided prefix.
"""
@@ -152,60 +163,80 @@ class Router(object):
#Here if not a random requst, we just forward the topic
return topic
def get_answer_dict(self, topic, request_options=None):
def get_answers(self, topic: str, request_options:Dict[str, str] = None) -> List[Dict[str, Any]]:
"""
Find cheat sheet for the topic.
Find cheat sheets for the topic.
Args:
`topic` (str): the name of the topic of the cheat sheet
Returns:
answer_dict: the answer dictionary
[answer_dict]: list of answers (dictionaries)
"""
# if topic specified as <topic_type>:<topic>,
# cut <topic_type> off
topic_type = ""
if re.match("[^/]+:", topic):
topic_type, topic = topic.split(":", 1)
topic = self.handle_if_random_request(topic)
topic_type = self.get_topic_type(topic)
topic_types = self.get_topic_type(topic)
# if topic_type is specified explicitly,
# show pages only of that type
if topic_type and topic_type in topic_types:
topic_types = [topic_type]
# 'question' queries are pretty expensive, that's why they should be handled
# in a special way:
# we do not drop the old style cache entries and try to reuse them if possible
if topic_type == 'question':
if topic_types == ['question']:
answer = cache.get('q:' + topic)
if answer:
if isinstance(answer, dict):
return answer
return {
return [answer]
return [{
'topic': topic,
'topic_type': 'question',
'answer': answer,
'format': 'text+code',
}
}]
answer = self._get_page_dict(topic, topic_type, request_options=request_options)
answer = self._get_page_dict(topic, topic_types[0], request_options=request_options)
if answer.get("cache", True):
cache.put('q:' + topic, answer)
return answer
return [answer]
# Try to find cacheable queries in the cache.
# If answer was not found in the cache, resolve it in a normal way and save in the cache
cache_needed = self._adapter[topic_type].is_cache_needed()
if cache_needed:
answer = cache.get(topic)
if not isinstance(answer, dict):
answer = None
if answer:
return answer
answers = []
for topic_type in topic_types:
answer = self._get_page_dict(topic, topic_type, request_options=request_options)
if isinstance(answer, dict):
if "cache" in answer:
cache_needed = answer["cache"]
cache_entry_name = f"{topic_type}:{topic}"
cache_needed = self._adapter[topic_type].is_cache_needed()
if cache_needed and answer:
cache.put(topic, answer)
return answer
if cache_needed:
answer = cache.get(cache_entry_name)
if not isinstance(answer, dict):
answer = None
if answer:
answers.append(answer)
continue
answer = self._get_page_dict(topic, topic_type, request_options=request_options)
if isinstance(answer, dict):
if "cache" in answer:
cache_needed = answer["cache"]
if cache_needed and answer:
cache.put(cache_entry_name, answer)
answers.append(answer)
return answers
# pylint: disable=invalid-name
_ROUTER = Router()
get_topics_list = _ROUTER.get_topics_list
get_answer_dict = _ROUTER.get_answer_dict
get_answers = _ROUTER.get_answers
+6 -5
View File
@@ -22,7 +22,7 @@ Configuration parameters:
import re
from config import CONFIG
from routing import get_answer_dict, get_topics_list
from routing import get_answers, get_topics_list
def _limited_entry():
return {
@@ -100,10 +100,11 @@ def find_answers_by_keyword(directory, keyword, options="", request_options=None
if not options_dict["recursive"] and '/' in subtopic:
continue
answer_dict = get_answer_dict(topic, request_options=request_options)
answer_text = answer_dict.get('answer', '')
if match(answer_text, keyword, options_dict=options_dict):
answers_found.append(answer_dict)
answer_dicts = get_answers(topic, request_options=request_options)
for answer_dict in answer_dicts:
answer_text = answer_dict.get('answer', '')
if match(answer_text, keyword, options_dict=options_dict):
answers_found.append(answer_dict)
if len(answers_found) > CONFIG['search.limit']:
answers_found.append(
+48 -19
View File
@@ -1,14 +1,18 @@
 cheat.sheets:az 
# Microsoft Azure CLI 2.0
# Command-line tools for Azure
# Install Azure CLI 2.0 with one curl command.
curl -L https://aka.ms/InstallAzureCli | bash
# create a resource group named "MyResourceGroup" in the westus2 region of Azure
az group create -n MyResourceGroup -l westus2
# create a resource group named "MyRG" in the 'westus2' region
az group create -n MyRG -l westus2
# create a Linux VM using the UbuntuTLS image, with two attached storage disks of 10 GB and 20 GB
az vm create -n MyLinuxVM -g MyResourceGroup --ssh-key-value $HOME/.ssh/id_rsa.pub --image UbuntuLTS --data-disk-sizes-gb 10 20
# create a Linux VM using the UbuntuTLS image,
# with two attached storage disks of 10 GB and 20 GB
az vm create -n MyLinuxVM -g MyRG \
 --ssh-key-value $HOME/.ssh/id_rsa.pub --image UbuntuLTS \
 --data-disk-sizes-gb 10 20
# list VMs
az vm list --output table
@@ -16,28 +20,28 @@
# list only VMs having distinct state
az vm list -d --query "[?powerState=='VM running']" --output table
# delete VM (with the name MyLinuxVM in the group MyResourceGroup)
az vm delete -g MyResourceGroup -n MyLinuxVM --yes
# delete VM (with the name MyLinuxVM in the group MyRG)
az vm delete -g MyRG -n MyLinuxVM --yes
# Delete all VMs in a resource group
az vm delete --ids $(az vm list -g MyResourceGroup --query "[].id" -o tsv)
az vm delete --ids $(az vm list -g MyRG --query "[].id" -o tsv)
# Create an Image based on a running VM
az vm deallocate -g MyResourceGroup -n MyLinuxVM
az vm generalize -g MyResourceGroup -n MyLinuxVM
az image create --resource-group MyResourceGroup --name MyTestImage --source MyLinuxVM
az vm deallocate -g MyRG -n MyLinuxVM
az vm generalize -g MyRG -n MyLinuxVM
az image create --resource-group MyRG --name MyTestImage --source MyLinuxVM
# Running VM based on a VHD
az storage blob upload --account-name "${account_name}" \
 --account-key "${account_key}" --container-name "${container_name}" --type page \
 --file "${file}" --name "${vhd_name}"
 --account-key "${account_key}" --container-name "${container}" --type page \
 --file "${file}" --name "${vhd}"
az disk create \
 --resource-group ${resource_group} \
 --resource-group "${resource_group}" \
 --name myManagedDisk \
 --source https://${account_name}.blob.core.windows.net/${container_name}/${vhd_name}
 --source "https://${account_name}.blob.core.windows.net/${container}/${vhd}"
# open port
az vm open-port --resource-group MyResourceGroup --name MyLinuxVM --port 443 --priority 899
az vm open-port --resource-group MyRG --name MyLinuxVM --port 443 --priority 899
# Show storage accounts
az storage account list --output table
@@ -46,7 +50,8 @@
az storage container list --account-name mystorageaccount --output table
# Show blobs in a container
az storage blob list --account-name mystorageaccount --container-name mycontainer --output table
az storage blob list --account-name mystorageaccount \
 --container-name mycontainer --output table
# list account keys
az storage account keys list --account-name STORAGE_NAME --resource-group RESOURCE_GROUP
@@ -62,8 +67,8 @@
# Copy blob
az storage blob copy start \
 --source-uri 'https://md-ldh5nknx2rkz.blob.core.windows.net/jzwuuuzzapn0/abcd?sv=2017-04-17&sr=b&si=68041718-6828-4f5e-9e6e-a1b719975062&sig=XXX' \
 --account-key XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX== \
 --source-uri 'https://xxx.blob.core.windows.net/jzwuuuzzapn0/abcd?...' \
 --account-key XXXXXXXXXX== \
 --account-name destaccount \
 --destination-container vms \
 --destination-blob DESTINATION-blob.vhd
@@ -81,10 +86,34 @@
az snapshot create --resource-group IC-EXASOL-001 --source vm1-disk1 -n vm1-snap1
# create SAS url for a snapshot
az snapshot grant-access --resource-group IC-EXASOL-001 --name vm1-snap1 --duration-in-seconds 36000 --query '[accessSas]' -o tsv
az snapshot grant-access --resource-group IC-EXASOL-001 --name vm1-snap1\
 --duration-in-seconds 36000 --query '[accessSas]' -o tsv
# attach disk
az vm disk attach --vm-name vm1 -g RESOURCE_GROUP --disk DISK1_ID
# detach disk
az vm disk detach --vm-name vm1 -g RESOURCE_GROUP --name DISK1_ID
 tldr:az 
# az
# The official CLI tool for Microsoft Azure.
# More information: <https://docs.microsoft.com/cli/azure>.
# Log in to Azure:
az login
# Manage azure subscription information:
az account
# List all Azure Managed Disks:
az disk list
# List all Azure virtual machines:
az vm list
# Manage Azure Kubernetes Services:
az aks
# Manage Azure Network resources:
az network
+26
View File
@@ -1,3 +1,4 @@
 cheat:ls 
# To display everything in <dir>, excluding hidden files:
ls <dir>
@@ -15,3 +16,28 @@
# To display directories only, include hidden:
ls -d .*/ */ <dir>
 tldr:ls 
# ls
# List directory contents.
# List files one per line:
ls -1
# List all files, including hidden files:
ls -a
# List all files, with trailing `/` added to directory names:
ls -F
# Long format list (permissions, ownership, size and modification date) of all files:
ls -la
# Long format list with size displayed using human readable units (KB, MB, GB):
ls -lh
# Long format list sorted by size (descending):
ls -lS
# Long format list of all files, sorted by modification date (oldest first):
ls -ltr
+25
View File
@@ -1,3 +1,4 @@
#[cheat:ls]
# To display everything in <dir>, excluding hidden files:
ls <dir>
@@ -15,3 +16,27 @@ ls -d */ <dir>
# To display directories only, include hidden:
ls -d .*/ */ <dir>
#[tldr:ls]
# ls
# List directory contents.
# List files one per line:
ls -1
# List all files, including hidden files:
ls -a
# List all files, with trailing `/` added to directory names:
ls -F
# Long format list (permissions, ownership, size and modification date) of all files:
ls -la
# Long format list with size displayed using human readable units (KB, MB, GB):
ls -lh
# Long format list sorted by size (descending):
ls -lS
# Long format list of all files, sorted by modification date (oldest first):
ls -ltr
+20
View File
@@ -1,3 +1,4 @@
 cheat.sheets:btrfs 
# Create a btrfs file system on /dev/sdb, /dev/sdc, and /dev/sdd
mkfs.btrfs /dev/sdb /dev/sdc /dev/sdd
@@ -52,3 +53,22 @@
# convert btrfs to ext3/ext4
btrfs-convert -r /dev/sdb1
 tldr:btrfs 
# btrfs
# A filesystem based on the copy-on-write (COW) principle for Linux.
# Create subvolume:
sudo btrfs subvolume create path/to/subvolume
# List subvolumes:
sudo btrfs subvolume list path/to/mount_point
# Show space usage information:
sudo btrfs filesystem df path/to/mount_point
# Enable quota:
sudo btrfs quota enable path/to/subvolume
# Show quota:
sudo btrfs qgroup show path/to/subvolume
+14 -1
View File
@@ -1,4 +1,4 @@
 btrfs 
 cheat.sheets:btrfs 
# create the subvolume /mnt/sv1 in the /mnt volume
btrfs subvolume create /mnt/sv1
@@ -13,3 +13,16 @@
# taking snapshot of a subvolume
btrfs subvolume snapshot /mnt/sv1 /mnt/sv1_snapshot
 tldr:btrfs 
# Create subvolume:
sudo btrfs subvolume create path/to/subvolume
# List subvolumes:
sudo btrfs subvolume list path/to/mount_point
# Enable quota:
sudo btrfs quota enable path/to/subvolume
# Show quota:
sudo btrfs qgroup show path/to/subvolume