Compare commits

...

78 commits

Author SHA1 Message Date
34fb04a9d2
Merge branch 'dmitmel-master' 2021-04-26 12:14:31 +02:00
0a9b65af7b
Merged dmitmel:master into master. 2021-04-26 12:14:13 +02:00
Dmytro Meleshko
c12afbc6ff [nvim] move the flake8 config to an external file 2021-04-26 10:25:01 +03:00
Dmytro Meleshko
f8c01686ee reformat all remaining Python scripts 2021-04-26 10:20:57 +03:00
Dmytro Meleshko
dbd76019c8 at long last, reformat all Python code with 2 space indents 2021-04-26 10:11:02 +03:00
Dmytro Meleshko
74e978d78e [nvim] use Yapf with a modified config for formatting 2021-04-26 10:07:31 +03:00
pull[bot]
c1e451b5ce
Merge pull request #241 from dmitmel/master
[pull] master from dmitmel:master
2021-04-23 22:29:43 +00:00
pull[bot]
0643bdf1bf
Merge pull request #240 from dmitmel/master
[pull] master from dmitmel:master
2021-04-22 22:30:01 +00:00
pull[bot]
fc5e5f1951
Merge pull request #239 from dmitmel/master
[pull] master from dmitmel:master
2021-04-22 16:29:44 +00:00
pull[bot]
1cc52196dd
Merge pull request #238 from dmitmel/master
[pull] master from dmitmel:master
2021-04-18 16:31:04 +00:00
pull[bot]
0d82ed488b
Merge pull request #237 from dmitmel/master
[pull] master from dmitmel:master
2021-04-11 22:29:26 +00:00
pull[bot]
e5d942e860
Merge pull request #236 from dmitmel/master
[pull] master from dmitmel:master
2021-04-10 16:29:36 +00:00
5e7350f793
Merge branch 'dmitmel-master' 2021-04-09 21:50:58 +02:00
7a2ac38de7
Fixed conflict. 2021-04-09 21:50:38 +02:00
pull[bot]
3236718daf
Merge pull request #234 from dmitmel/master
[pull] master from dmitmel:master
2021-04-05 03:36:06 +00:00
Dmytro Meleshko
9253cb6a08 [crosscode] add an icon for the Arch mod 2021-04-05 02:07:00 +03:00
pull[bot]
49b67aea8d
Merge pull request #233 from dmitmel/master
[pull] master from dmitmel:master
2021-04-02 21:27:52 +00:00
pull[bot]
23a741be94
Merge pull request #232 from dmitmel/master
[pull] master from dmitmel:master
2021-03-30 14:59:34 +00:00
pull[bot]
5e0633ead5
Merge pull request #231 from dmitmel/master
[pull] master from dmitmel:master
2021-03-30 09:29:53 +00:00
pull[bot]
7867a5ddd9
Merge pull request #230 from dmitmel/master
[pull] master from dmitmel:master
2021-03-27 16:34:30 +00:00
pull[bot]
a089d68776
Merge pull request #229 from dmitmel/master
[pull] master from dmitmel:master
2021-03-27 02:18:23 +00:00
pull[bot]
fc159ec552
Merge pull request #228 from dmitmel/master
[pull] master from dmitmel:master
2021-03-26 06:38:12 +00:00
pull[bot]
4e1c759bbc
Merge pull request #227 from dmitmel/master
[pull] master from dmitmel:master
2021-03-25 06:41:49 +00:00
pull[bot]
9164088ecc
Merge pull request #226 from dmitmel/master
[pull] master from dmitmel:master
2021-03-21 15:54:50 +00:00
pull[bot]
1a248036aa
Merge pull request #225 from dmitmel/master
[pull] master from dmitmel:master
2021-03-21 12:34:14 +00:00
pull[bot]
f4a842d59e
Merge pull request #224 from dmitmel/master
[pull] master from dmitmel:master
2021-03-20 21:48:49 +00:00
pull[bot]
3b97435825
Merge pull request #223 from dmitmel/master
[pull] master from dmitmel:master
2021-03-20 06:03:32 +00:00
pull[bot]
626811a49f
Merge pull request #222 from dmitmel/master
[pull] master from dmitmel:master
2021-03-19 02:42:33 +00:00
5ab08f0f0b
Merge branch 'dmitmel-master' 2021-03-18 19:20:39 +01:00
ce9c2d33ae
Merged dmitmel:master into master. 2021-03-18 19:20:25 +01:00
Dmytro Meleshko
6577755555
[nvim] switch from coc-python to coc-pyright 2021-03-14 12:19:19 +01:00
dependabot[bot]
81d185be53
Bump prismjs from 1.21.0 to 1.23.0 in /script-resources/markdown2htmldoc
Bumps [prismjs](https://github.com/PrismJS/prism) from 1.21.0 to 1.23.0.
- [Release notes](https://github.com/PrismJS/prism/releases)
- [Changelog](https://github.com/PrismJS/prism/blob/master/CHANGELOG.md)
- [Commits](https://github.com/PrismJS/prism/compare/v1.21.0...v1.23.0)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-14 12:19:19 +01:00
pull[bot]
b31bea45ea
Merge pull request #218 from dmitmel/master
[pull] master from dmitmel:master
2021-02-27 14:13:28 +00:00
pull[bot]
86b542b4d0
Merge pull request #217 from dmitmel/master
[pull] master from dmitmel:master
2021-02-22 11:00:14 +00:00
pull[bot]
fc3afdf441
Merge pull request #216 from dmitmel/master
[pull] master from dmitmel:master
2021-02-20 13:47:09 +00:00
f9051aff76
Why was this on rebase again? 2021-02-19 21:47:22 +01:00
5517419413
Merge pull request #215 from dmitmel/master 2021-02-19 21:33:01 +01:00
Dmytro Meleshko
9555e5f706 [x11] add my xprofile 2021-02-12 15:13:05 +00:00
Dmytro Meleshko
6fc06191a5 [scripts/discord-stream-desktop-audio] allow specifying the audio device 2021-02-12 09:08:57 +00:00
Dmytro Meleshko
b0eef79602 [nvim] disable ESLint integration for Prettier, sync configs 2021-02-12 09:08:57 +00:00
Dmytro Meleshko
2a0ffb0cf5 [crosscode] add a mod for binding mouse buttons to actions 2021-02-12 09:08:57 +00:00
Dmytro Meleshko
6bd741c236 [nvim] disable matchpairs in all other JS-like filetypes 2021-02-09 12:29:26 +00:00
Dmytro Meleshko
851a494eb0 [nvim] properly display wavy underlines under spelling mistakes now that I have enabled all termcap features of kitty 2021-02-08 21:44:50 +00:00
Dmytro Meleshko
b15a03c3f9 [kitty] stop changing TERM to something non-default 2021-02-08 18:24:47 +00:00
Dmytro Meleshko
33ed3720c8 [ranger] add ranger config 2021-02-08 18:24:47 +00:00
Dmytro Meleshko
a59a693e98 [zsh] use Python 3 by default on macOS 2021-02-07 21:04:30 +00:00
Dmytro Meleshko
da7c44af35 [nvim] fix FixWhitespaceOnSave flooding the search history 2021-02-05 11:36:25 +00:00
Dmytro Meleshko
618995cc7f [nvim] add functions to workaround some interesting behaviors of vim 2021-02-05 11:36:25 +00:00
Dmytro Meleshko
a27c05856a [zsh] add a timestamp printing function 2021-02-05 11:36:25 +00:00
pull[bot]
0ec9d1ded1
Merge pull request #149 from dmitmel/master
[pull] master from dmitmel:master
2021-02-04 21:43:39 +00:00
Dmytro Meleshko
f288247671 [kitty] remove the sample config and keep only the changed bits 2021-02-04 18:30:58 +00:00
Dmytro Meleshko
bcf58ced93 [kitty] enable the only two layouts I actually use 2021-02-04 18:30:58 +00:00
Dmytro Meleshko
18700a8198 [scripts/welcome] add logo for Manjaro ARM 2021-02-04 14:54:46 +00:00
Dmytro Meleshko
60f8ca3788 [zsh] display the current pyenv version in the prompt 2021-02-02 22:52:58 +00:00
Dmytro Meleshko
ed93c816f9 [nvim] bring back a fix removed in 14e64127e4 2021-02-02 22:52:58 +00:00
Dmytro Meleshko
57f0e01b51 [nvim] disable rust-analyzer's diagnostics and autoimports 2021-02-01 11:18:52 +00:00
482828639e
Merge branch 'master' keanuplayz/dotfiles 2021-01-30 14:17:16 +01:00
a659106248
[scripts/copy-env-var] Script to copy envvars. 2021-01-30 14:17:07 +01:00
Dmytro Meleshko
b45d969f0c [git] add temporary files to the gitignore 2021-01-29 13:19:12 +00:00
Dmytro Meleshko
1e50762fcb [nvim+zsh] fix the need for resetting FZF_DEFAULT_OPTS on Ubuntu and derivatives 2021-01-29 01:19:21 +00:00
7f3dfb96be
[nvim] Added plugin coc-explorer. 2021-01-28 16:24:43 +01:00
Dmytro Meleshko
e277f19ed3 [zsh] fix the manpath-caused errors on shell startup once and for all 2021-01-25 19:28:31 +00:00
Dmytro Meleshko
4b6cf8c56a [nvim] fix the commentstring in po files 2021-01-25 12:40:11 +00:00
Dmytro Meleshko
06ff96bf30 [nvim] add a plugin for RON 2021-01-21 11:06:06 +00:00
Dmytro Meleshko
4cc4389455 [nvim] make the airline theme match my syntax theme even more 2021-01-21 01:20:43 +00:00
Dmytro Meleshko
819e5e5a33 update the copyright years 2021-01-20 10:04:09 +00:00
Dmytro Meleshko
3d7078d8a1 [scripts/copy-crosscode-emoji-url] change the order of URL params 2021-01-18 10:02:12 +00:00
15d01d0d4f
Merge pull request #18 from dmitmel/master
copy script update that was already done
2021-01-17 14:29:21 +01:00
pull[bot]
6998226ea1
updated 2021-01-17 14:28:31 +01:00
4d6ff353f9
Updated merge strategy. 2021-01-17 14:27:03 +01:00
159a142967
Removed fasd stuff. 2021-01-17 12:07:31 +01:00
62611bb01e
[nvim] Added WakaTime plugin. 2021-01-17 12:07:14 +01:00
9a36e9ecbb
merge dmitmel/master into master 2021-01-16 18:16:48 +01:00
5425d38058
Add pull config. 2021-01-16 18:15:58 +01:00
0ddb5c5777
[zsh] Added completions for gh cli. 2021-01-16 18:15:57 +01:00
51a3ea7777
[nvim] Added Lua to coc. 2021-01-16 18:15:57 +01:00
5e2ea81830
[scripts/copy-emote] Removed requirement of 'safe' 2021-01-16 18:15:57 +01:00
ab7320297f
[scripts/discord-stream] Now uses separate file. 2021-01-16 18:15:57 +01:00
39 changed files with 1516 additions and 1014 deletions

6
.github/pull.yml vendored Normal file
View file

@ -0,0 +1,6 @@
version: '1'
rules:
- base: master
upstream: dmitmel:master
mergeMethod: merge
mergeUnstable: true

View file

@ -32,8 +32,7 @@ selection_bg = base16_colors[0x2]
selection_fg = fg selection_fg = fg
ansi_colors = [ ansi_colors = [
base16_colors[int(i, 16)] base16_colors[int(i, 16)] for i in "0 8 B A D E C 5 3 8 B A D E C 7 9 F 1 2 4 6".split()
for i in "0 8 B A D E C 5 3 8 B A D E C 7 9 F 1 2 4 6".split()
] ]
link_color = ansi_colors[0xC] link_color = ansi_colors[0xC]

View file

@ -2,6 +2,7 @@
import _theme as theme import _theme as theme
print( print(
"""\ """\
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
@ -13,7 +14,7 @@ print(
def print_color(key_name, color): def print_color(key_name, color):
r, g, b = [float(int(color[2 * i + 1 : 2 * i + 3], 16)) / 255 for i in range(3)] r, g, b = [float(int(color[2 * i + 1:2 * i + 3], 16)) / 255 for i in range(3)]
print( print(
"""\ """\
<key>{} Color</key> <key>{} Color</key>
@ -27,9 +28,7 @@ def print_color(key_name, color):
<key>Blue Component</key> <key>Blue Component</key>
<real>{}</real> <real>{}</real>
</dict>\ </dict>\
""".format( """.format(key_name, r, g, b)
key_name, r, g, b
)
) )
@ -44,9 +43,7 @@ for index, color in enumerate(theme.ansi_colors[:16]):
print_color("Ansi " + str(index), color) print_color("Ansi " + str(index), color)
print_color("Link", theme.link_color) print_color("Link", theme.link_color)
print( print("""\
"""\
</dict> </dict>
</plist>\ </plist>\
""" """)
)

View file

@ -7,8 +7,6 @@ with open(os.path.join(os.path.dirname(__file__), "prismjs-theme-src.css")) as f
css_src = f.read() css_src = f.read()
for var_name, color in theme.css_variables.items(): for var_name, color in theme.css_variables.items():
css_src = css_src.replace( css_src = css_src.replace("var(--{}{})".format(theme.css_variables_prefix, var_name), color)
"var(--{}{})".format(theme.css_variables_prefix, var_name), color
)
print(css_src) print(css_src)

View file

@ -8,11 +8,4 @@ import _theme as theme
# 0,0,0,0,170,170,170,170,85,85,85,85,255,255,255,255 # 0,0,0,0,170,170,170,170,85,85,85,85,255,255,255,255
for i in range(3): for i in range(3):
print( print(",".join([str(int(color[2 * i + 1:2 * i + 3], 16)) for color in theme.ansi_colors[:16]]))
",".join(
[
str(int(color[2 * i + 1 : 2 * i + 3], 16))
for color in theme.ansi_colors[:16]
]
)
)

View file

@ -2,6 +2,7 @@
import _theme as theme import _theme as theme
print(":root {") print(":root {")
for var_name, color in theme.css_variables.items(): for var_name, color in theme.css_variables.items():
print(" --{}{}: {};".format(theme.css_variables_prefix, var_name, color)) print(" --{}{}: {};".format(theme.css_variables_prefix, var_name, color))

View file

@ -2,6 +2,7 @@
import _theme as theme import _theme as theme
print("let dotfiles_colorscheme_name = '{}'".format(theme.name)) print("let dotfiles_colorscheme_name = '{}'".format(theme.name))
print("let dotfiles_colorscheme_base16_name = '{}'".format(theme.base16_name)) print("let dotfiles_colorscheme_base16_name = '{}'".format(theme.base16_name))
print("let dotfiles_colorscheme_base16_colors = [") print("let dotfiles_colorscheme_base16_colors = [")

View file

@ -25,11 +25,7 @@ colors = {
for color_brightness in [False, True]: for color_brightness in [False, True]:
for color_index, color_name in enumerate(ANSI_COLOR_NAMES): for color_index, color_name in enumerate(ANSI_COLOR_NAMES):
color = theme.ansi_colors[ color = theme.ansi_colors[color_index + int(color_brightness) * len(ANSI_COLOR_NAMES)]
color_index + int(color_brightness) * len(ANSI_COLOR_NAMES) colors["terminal.ansi" + ("Bright" if color_brightness else "") + color_name] = color
]
colors[
"terminal.ansi" + ("Bright" if color_brightness else "") + color_name
] = color
print(json.dumps(colors, ensure_ascii=False, indent=2)) print(json.dumps(colors, ensure_ascii=False, indent=2))

View file

@ -2,6 +2,7 @@
import _theme as theme import _theme as theme
print("[Scheme]") print("[Scheme]")
print("Name=dmitmel's dotfiles colorscheme") print("Name=dmitmel's dotfiles colorscheme")
print("ColorForeground={}".format(theme.fg)) print("ColorForeground={}".format(theme.fg))

View file

@ -2,7 +2,6 @@
import _theme as theme import _theme as theme
for attr in [ for attr in [
"bg", "bg",
"fg", "fg",

View file

@ -0,0 +1,3 @@
let g:coc_global_extensions += ['coc-lua']
let s:filetypes = ['lua']
let g:coc_filetypes += s:filetypes

View file

@ -1,12 +1,15 @@
let g:coc_global_extensions += ['coc-pyright'] let g:coc_global_extensions += ['coc-pyright']
let g:coc_filetypes += ['python'] let g:coc_filetypes += ['python']
" let g:coc_user_config['pyls.plugins.pycodestyle.ignore'] = ['E501']
" let g:coc_user_config['python.autocomplete.showAdvancedMembers'] = v:false " let g:coc_user_config['python.autocomplete.showAdvancedMembers'] = v:false
let g:coc_user_config['python'] = { let g:coc_user_config['python'] = {
\ 'formatting': { 'provider': 'black' }, \ 'formatting': {
\ 'provider': 'yapf',
\ 'yapfArgs': ['--style=' . simplify(g:nvim_dotfiles_dir.'/../python/yapf.ini')]
\ },
\ 'linting': { \ 'linting': {
\ 'pylintEnabled': v:false, \ 'pylintEnabled': v:false,
\ 'flake8Enabled': v:true, \ 'flake8Enabled': v:true,
\ 'flake8Args': ['--ignore', 'E501'], \ 'flake8Args': ['--config=' . simplify(g:nvim_dotfiles_dir.'/../python/flake8.ini')],
\ }, \ },
\ } \ }

View file

@ -2,7 +2,9 @@
Plug 'tpope/vim-eunuch' Plug 'tpope/vim-eunuch'
if g:vim_ide if g:vim_ide
Plug 'francoiscabrol/ranger.vim' Plug 'francoiscabrol/ranger.vim'
Plug 'rbgrouleff/bclose.vim'
endif endif
Plug 'weirongxu/coc-explorer'
" }}} " }}}
" Editing {{{ " Editing {{{
@ -71,3 +73,7 @@
endif endif
endif endif
" }}} " }}}
" Misc {{{
Plug 'wakatime/vim-wakatime'
" }}}

12
python/flake8.ini Normal file
View file

@ -0,0 +1,12 @@
[flake8]
ignore =
# Indent is not a multiple of 4
E111
# Indent is not a multiple of 4 for comments
E114
# Indent for continuation lines is smaller than expected
E121
# Import not at the top of the file
E402
# Line too long
E501

9
python/yapf.ini Normal file
View file

@ -0,0 +1,9 @@
[style]
based_on_style = google
column_limit = 99
indent_width = 2
continuation_indent_width = 2
blank_lines_between_top_level_imports_and_variables = 2
dedent_closing_brackets = true
coalesce_brackets = true
spaces_around_power_operator = true

View file

@ -4,7 +4,6 @@ import subprocess
from pathlib import Path from pathlib import Path
from typing import Iterable, NoReturn from typing import Iterable, NoReturn
if os.name == "posix": if os.name == "posix":
DOTFILES_CONFIG_DIR: Path = Path.home() / ".config" / "dotfiles" DOTFILES_CONFIG_DIR: Path = Path.home() / ".config" / "dotfiles"
DOTFILES_CACHE_DIR: Path = Path.home() / ".cache" / "dotfiles" DOTFILES_CACHE_DIR: Path = Path.home() / ".cache" / "dotfiles"
@ -14,9 +13,7 @@ def platform_not_supported_error() -> NoReturn:
raise Exception("platform '{}' is not supported!".format(sys.platform)) raise Exception("platform '{}' is not supported!".format(sys.platform))
def run_chooser( def run_chooser(choices: Iterable[str], prompt: str = None, async_read: bool = False) -> int:
choices: Iterable[str], prompt: str = None, async_read: bool = False
) -> int:
supports_result_index = True supports_result_index = True
if os.isatty(sys.stderr.fileno()): if os.isatty(sys.stderr.fileno()):
process_args = [ process_args = [
@ -38,9 +35,7 @@ def run_chooser(
else: else:
platform_not_supported_error() platform_not_supported_error()
chooser_process = subprocess.Popen( chooser_process = subprocess.Popen(process_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE
)
with chooser_process.stdin as pipe: with chooser_process.stdin as pipe:
for index, choice in enumerate(choices): for index, choice in enumerate(choices):

View file

@ -1,5 +1,6 @@
from colorama import Fore, Style, ansi from colorama import Fore, Style, ansi
COLORS = [ansi.code_to_chars(30 + color_index) for color_index in range(0, 8)] COLORS = [ansi.code_to_chars(30 + color_index) for color_index in range(0, 8)]

View file

@ -5,6 +5,7 @@ import re
from colors import COLORS, Style from colors import COLORS, Style
from system_info import get_system_info from system_info import get_system_info
print("") print("")
logo_lines, info_lines = get_system_info() logo_lines, info_lines = get_system_info()

View file

@ -22,9 +22,7 @@ def get_system_info():
username = getuser() username = getuser()
hostname = _get_hostname() hostname = _get_hostname()
info_lines.append( info_lines.append(bright_colored(username, Fore.BLUE) + "@" + bright_colored(hostname, Fore.RED))
bright_colored(username, Fore.BLUE) + "@" + bright_colored(hostname, Fore.RED)
)
info_lines.append("") info_lines.append("")
distro_id, distro_name, distro_version, distro_codename = _get_distro_info() distro_id, distro_name, distro_version, distro_codename = _get_distro_info()
@ -94,9 +92,7 @@ def _get_users():
terminals = users[name] terminals = users[name]
colored_name = bright_colored(name, Fore.BLUE) colored_name = bright_colored(name, Fore.BLUE)
colored_terminals = [ colored_terminals = [colored(str(term), Style.DIM, Fore.WHITE) for term in terminals]
colored(str(term), Style.DIM, Fore.WHITE) for term in terminals
]
terminals_str = ", ".join(colored_terminals) terminals_str = ", ".join(colored_terminals)
if len(colored_terminals) > 1: if len(colored_terminals) > 1:
@ -140,14 +136,12 @@ def _get_disks():
continue continue
usage = psutil.disk_usage(disk.mountpoint) usage = psutil.disk_usage(disk.mountpoint)
result.append( result.append((
(
disk.mountpoint, disk.mountpoint,
humanize_bytes(usage.used), humanize_bytes(usage.used),
humanize_bytes(usage.total), humanize_bytes(usage.total),
colorize_percent(usage.percent, warning=70, critical=85), colorize_percent(usage.percent, warning=70, critical=85),
) ))
)
return result return result

View file

@ -9,35 +9,29 @@ from typing import Any, Generator, Optional, Union
import urllib.parse import urllib.parse
import urllib.request import urllib.request
sys.path.insert(1, os.path.join(os.path.dirname(__file__), "..", "script-resources")) sys.path.insert(1, os.path.join(os.path.dirname(__file__), "..", "script-resources"))
import common_script_utils import common_script_utils
DEFAULT_REGISTRY_DUMP_URL = "https://stronghold.crosscode.ru/~ccbot/emote-registry.json" DEFAULT_REGISTRY_DUMP_URL = "https://stronghold.crosscode.ru/~ccbot/emote-registry.json"
if os.name == "posix": if os.name == "posix":
config_path: Path = ( config_path: Path = (common_script_utils.DOTFILES_CONFIG_DIR / "copy-crosscode-emoji-url.ini")
common_script_utils.DOTFILES_CONFIG_DIR / "copy-crosscode-emoji-url.ini" default_registry_dump_file: Path = (common_script_utils.DOTFILES_CACHE_DIR / "dotfiles")
)
default_registry_dump_file: Path = (
common_script_utils.DOTFILES_CACHE_DIR / "dotfiles"
)
else: else:
common_script_utils.platform_not_supported_error() common_script_utils.platform_not_supported_error()
config = ConfigParser(interpolation=None) config = ConfigParser(interpolation=None)
config.read(config_path) config.read(config_path)
emotes: list[dict[str, Any]] = [] emotes: list[dict[str, Any]] = []
def emote_downloader_and_iterator() -> Generator[str, None, None]: def emote_downloader_and_iterator() -> Generator[str, None, None]:
global emotes global emotes
registry_dump_file: Optional[Union[str, Path]] = config.get( registry_dump_file: Optional[Union[
"default", "ccbot_emote_registry_dump_file", fallback=None str, Path]] = config.get("default", "ccbot_emote_registry_dump_file", fallback=None)
)
if registry_dump_file is not None: if registry_dump_file is not None:
registry_dump_file = os.path.expanduser(registry_dump_file) registry_dump_file = os.path.expanduser(registry_dump_file)
else: else:
@ -57,7 +51,7 @@ def emote_downloader_and_iterator() -> Generator[str, None, None]:
assert emote_registry_data["version"] == 1 assert emote_registry_data["version"] == 1
emotes = [emote for emote in emote_registry_data["list"] if emote["safe"]] emotes = [emote for emote in emote_registry_data["list"]]
for emote in emotes: for emote in emotes:
yield "{emote[ref]} [{emote[guild_name]}]".format(emote=emote) yield "{emote[ref]} [{emote[guild_name]}]".format(emote=emote)
@ -75,16 +69,12 @@ if chosen_index >= 0:
if config.getboolean("default", "add_emote_name_to_url", fallback=False): if config.getboolean("default", "add_emote_name_to_url", fallback=False):
emote_url_query["name"] = [chosen_emote["name"]] emote_url_query["name"] = [chosen_emote["name"]]
default_emote_image_size = config.getint( default_emote_image_size = config.getint("default", "default_emote_image_size", fallback=None)
"default", "default_emote_image_size", fallback=None
)
if default_emote_image_size is not None: if default_emote_image_size is not None:
emote_url_query["size"] = [str(default_emote_image_size)] emote_url_query["size"] = [str(default_emote_image_size)]
emote_url_query_str = urllib.parse.urlencode(emote_url_query, doseq=True) emote_url_query_str = urllib.parse.urlencode(emote_url_query, doseq=True)
emote_url_str = urllib.parse.urlunparse( emote_url_str = urllib.parse.urlunparse(emote_url._replace(query=emote_url_query_str))
emote_url._replace(query=emote_url_query_str)
)
common_script_utils.set_clipboard(emote_url_str) common_script_utils.set_clipboard(emote_url_str)

11
scripts/copy-env-var Executable file
View file

@ -0,0 +1,11 @@
#!/usr/bin/env bash
set -euo pipefail
if variable="$(set -euo pipefail; {
awk 'BEGIN{for(v in ENVIRON) print v}'
} | rofi -dmenu)" && [[ -n $variable ]]; then
variable="${variable%% *}"
echo ${!variable} | xclip -sel clip
fi

View file

@ -6,6 +6,7 @@ import sys
import colorama import colorama
import time import time
DISCORD_EPOCH = 1420070400000 # milliseconds DISCORD_EPOCH = 1420070400000 # milliseconds
user_snowflake = int(sys.argv[1]) user_snowflake = int(sys.argv[1])
@ -13,9 +14,7 @@ user_snowflake = int(sys.argv[1])
def print_field(name, value): def print_field(name, value):
print( print(
"{}{}:{} {}".format( "{}{}:{} {}".format(colorama.Style.BRIGHT, name.rjust(21), colorama.Style.RESET_ALL, value)
colorama.Style.BRIGHT, name.rjust(21), colorama.Style.RESET_ALL, value
)
) )

View file

@ -4,14 +4,14 @@ import discord
import sys import sys
import os import os
guild_id = int(sys.argv[1]) guild_id = int(sys.argv[1])
voice_channel_id = int(sys.argv[2]) voice_channel_id = int(sys.argv[2])
pulseaudio_device = sys.argv[3] pulseaudio_device = sys.argv[3]
with open(os.path.expanduser("~/.config/dotfiles/discord-tools-bot-token.txt")) as f: with open(os.path.expanduser("~/.config/dotfiles/discord-tools-user-token.txt")) as f:
bot_token = f.read().strip() bot_token = f.read().strip()
bot = discord.Client() bot = discord.Client()
@ -30,9 +30,7 @@ async def on_ready():
print("connected to {0} ({0.id}) in {1} ({1.id})".format(voice_channel, guild)) print("connected to {0} ({0.id}) in {1} ({1.id})".format(voice_channel, guild))
source = discord.FFmpegPCMAudio(pulseaudio_device, before_options="-f pulse") source = discord.FFmpegPCMAudio(pulseaudio_device, before_options="-f pulse")
voice_client.play( voice_client.play(source, after=lambda e: print("Player error: %s" % e) if e else None)
source, after=lambda e: print("Player error: %s" % e) if e else None
)
bot.run(bot_token) bot.run(bot_token, bot=False)

View file

@ -33,7 +33,6 @@ DISCORD_FLAGS = {
"Verified Bot Developer": 1 << 17, "Verified Bot Developer": 1 << 17,
} }
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument("user_snowflake", type=int) parser.add_argument("user_snowflake", type=int)
parser.add_argument("--bot-token", type=str) parser.add_argument("--bot-token", type=str)
@ -45,16 +44,13 @@ user_snowflake = cli_args.user_snowflake
bot_token = cli_args.bot_token bot_token = cli_args.bot_token
if bot_token is None: if bot_token is None:
with open( with open(os.path.expanduser("~/.config/dotfiles/discord-tools-bot-token.txt")) as f:
os.path.expanduser("~/.config/dotfiles/discord-tools-bot-token.txt")
) as f:
bot_token = f.read().strip() bot_token = f.read().strip()
image_size = cli_args.image_size image_size = cli_args.image_size
if not (image_size is None or (image_size > 0 and image_size & (image_size - 1)) == 0): if not (image_size is None or (image_size > 0 and image_size & (image_size - 1)) == 0):
parser.error("image_size must be greater than zero and a power of two") parser.error("image_size must be greater than zero and a power of two")
try: try:
opener = urllib.request.build_opener() opener = urllib.request.build_opener()
# Don't send the User-Agent header, Discord blocks the default one # Don't send the User-Agent header, Discord blocks the default one
@ -85,9 +81,7 @@ avatar_url = (
raw_data["id"], raw_data["id"],
raw_data["avatar"], raw_data["avatar"],
"gif" if raw_data["avatar"].startswith("a_") else "png", "gif" if raw_data["avatar"].startswith("a_") else "png",
) ) if raw_data["avatar"] is not None else default_avatar_url
if raw_data["avatar"] is not None
else default_avatar_url
) )
if image_size is not None: if image_size is not None:
avatar_url += "?size={}".format(image_size) avatar_url += "?size={}".format(image_size)
@ -115,7 +109,6 @@ else:
user_flag_names.append(flag_name) user_flag_names.append(flag_name)
data["Flags"] = ", ".join(user_flag_names) data["Flags"] = ", ".join(user_flag_names)
if cli_args.get_prop is None: if cli_args.get_prop is None:
max_name_length = max(map(len, data.keys())) max_name_length = max(map(len, data.keys()))
for name, value in data.items(): for name, value in data.items():

View file

@ -10,19 +10,17 @@ from pathlib import Path
import struct import struct
import json import json
sys.path.insert(1, os.path.join(os.path.dirname(__file__), "..", "script-resources")) sys.path.insert(1, os.path.join(os.path.dirname(__file__), "..", "script-resources"))
import factorio.property_tree import factorio.property_tree
with open(Path.home() / ".factorio" / "mods" / "mod-settings.dat", "rb") as f: with open(Path.home() / ".factorio" / "mods" / "mod-settings.dat", "rb") as f:
version_main: int version_main: int
version_major: int version_major: int
version_minor: int version_minor: int
version_developer: int version_developer: int
version_main, version_major, version_minor, version_developer = struct.unpack( version_main, version_major, version_minor, version_developer = struct.unpack("<HHHH", f.read(8))
"<HHHH", f.read(8)
)
always_false_flag = factorio.property_tree.read_bool(f) always_false_flag = factorio.property_tree.read_bool(f)
assert not always_false_flag assert not always_false_flag

View file

@ -7,6 +7,7 @@ import json
from sys import stdout from sys import stdout
import base64 import base64
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
encoding_names = ["utf8", "base16", "base32", "base64", "base85"] encoding_names = ["utf8", "base16", "base32", "base64", "base85"]
parser.add_argument("--encoding", "-e", choices=encoding_names, default="utf8") parser.add_argument("--encoding", "-e", choices=encoding_names, default="utf8")

View file

@ -1,11 +1,13 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Taken from <https://unix.stackexchange.com/a/509417/411555> # Taken from <https://unix.stackexchange.com/a/509417/411555>
import gi import gi
import sys import sys
gi.require_version("Gtk", "3.0") gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gio, GLib # noqa E402 from gi.repository import Gtk, Gio, GLib
rec_mgr = Gtk.RecentManager.get_default() rec_mgr = Gtk.RecentManager.get_default()
for arg in sys.argv[1:]: for arg in sys.argv[1:]:

View file

@ -38,7 +38,6 @@
# - The module `skins.citizen.scripts` references search inputs which aren't # - The module `skins.citizen.scripts` references search inputs which aren't
# created by this script. # created by this script.
import argparse import argparse
import mwclient import mwclient
import json import json
@ -137,13 +136,14 @@ parser.add_argument("--site", type=str, required=True)
parser.add_argument("--scheme", type=str, default="https") parser.add_argument("--scheme", type=str, default="https")
parser.add_argument("--skin", type=str, default="vector") parser.add_argument("--skin", type=str, default="vector")
parser.add_argument( parser.add_argument(
"--input", type=str, required=True, "--input",
type=str,
required=True,
) )
parser.add_argument("--title", type=str) parser.add_argument("--title", type=str)
parser.add_argument("--output", type=str, required=True) parser.add_argument("--output", type=str, required=True)
cli_args = parser.parse_args() cli_args = parser.parse_args()
site = mwclient.Site(cli_args.site, scheme=cli_args.scheme) site = mwclient.Site(cli_args.site, scheme=cli_args.scheme)
@ -151,7 +151,11 @@ def get_load_script_url(**args):
return "{path}load{ext}?{args}".format( return "{path}load{ext}?{args}".format(
path=site.path, path=site.path,
ext=site.ext, ext=site.ext,
args=urlencode({"lang": LANG, "skin": cli_args.skin, **args}), args=urlencode({
"lang": LANG,
"skin": cli_args.skin,
**args
}),
) )
@ -243,14 +247,12 @@ rendered_html = """\
lang=html.escape(LANG), lang=html.escape(LANG),
text_dir=html.escape(LANG_TEXT_DIRECTION), text_dir=html.escape(LANG_TEXT_DIRECTION),
base_url=html.escape("{}://{}".format(site.scheme, site.host)), base_url=html.escape("{}://{}".format(site.scheme, site.host)),
page_modules_state_json=json_dumps_compact( page_modules_state_json=json_dumps_compact({
{
"noscript": "ready", "noscript": "ready",
"user.options": "ready", "user.options": "ready",
"user.tokens": "loading", "user.tokens": "loading",
**{name: "ready" for name in MODULES_PRELOAD_STYLES[cli_args.skin]}, **{name: "ready" for name in MODULES_PRELOAD_STYLES[cli_args.skin]},
} }),
),
page_config_json=json_dumps_compact(result["jsconfigvars"]), page_config_json=json_dumps_compact(result["jsconfigvars"]),
page_modules_json=json_dumps_compact( page_modules_json=json_dumps_compact(
get_modules(result["modules"], MODULES_POST_LOAD, MODULES_POST_LOAD_BLOCKED) get_modules(result["modules"], MODULES_POST_LOAD, MODULES_POST_LOAD_BLOCKED)
@ -258,35 +260,27 @@ rendered_html = """\
style_url=html.escape( style_url=html.escape(
get_load_script_url( get_load_script_url(
only="styles", only="styles",
modules="|".join( modules="|".join(get_modules(result["modulestyles"], MODULES_PRELOAD_STYLES)),
get_modules(result["modulestyles"], MODULES_PRELOAD_STYLES)
),
) )
), ),
script_url=html.escape( script_url=html.escape(
get_load_script_url( get_load_script_url(
only="scripts", only="scripts",
modules="|".join( modules="|".join(get_modules(result["modulescripts"], MODULES_PRELOAD_SCRIPTS)),
get_modules(result["modulescripts"], MODULES_PRELOAD_SCRIPTS)
),
raw="1", raw="1",
) )
), ),
skin=html.escape(cli_args.skin), skin=html.escape(cli_args.skin),
page_class=html.escape(escape_css_class(result["displaytitle"])), page_class=html.escape(escape_css_class(result["displaytitle"])),
title=html.escape(result["displaytitle"]), title=html.escape(result["displaytitle"]),
indicators_html="\n".join( indicators_html="\n".join([
[
'<div id="mw-indicator-{}" class="mw-indicator">{}</div>'.format( '<div id="mw-indicator-{}" class="mw-indicator">{}</div>'.format(
indicator["name"], indicator["*"] indicator["name"], indicator["*"]
) ) for indicator in result["indicators"]
for indicator in result["indicators"] ]),
]
),
content_html=result["text"]["*"], content_html=result["text"]["*"],
categories_html=result["categorieshtml"]["*"], categories_html=result["categorieshtml"]["*"],
) )
with open(cli_args.output, "w") as f: with open(cli_args.output, "w") as f:
f.write(rendered_html) f.write(rendered_html)

View file

@ -2,8 +2,9 @@
import gi import gi
import argparse import argparse
gi.require_version("Gtk", "3.0") gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, Pango # noqa: E402 from gi.repository import Gtk, Gdk, Pango
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
@ -12,7 +13,6 @@ args = parser.parse_args()
message = " ".join(args.message) message = " ".join(args.message)
window = Gtk.ApplicationWindow() window = Gtk.ApplicationWindow()
window.set_keep_above(True) window.set_keep_above(True)
window.set_decorated(False) window.set_decorated(False)

View file

@ -9,12 +9,12 @@
import math import math
import gi import gi
gi.require_version("Playerctl", "2.0") gi.require_version("Playerctl", "2.0")
gi.require_version("Gtk", "3.0") gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0") gi.require_version("Gdk", "3.0")
gi.require_version("Pango", "1.0") gi.require_version("Pango", "1.0")
from gi.repository import Playerctl, Gtk, Gdk, GLib, Pango # noqa: E402 from gi.repository import Playerctl, Gtk, Gdk, GLib, Pango
# Larger priority values will make the player with this name appear higher in # Larger priority values will make the player with this name appear higher in
# the menu. The default priority is 0. # the menu. The default priority is 0.
@ -175,20 +175,18 @@ if len(player_names) > 0:
players = [] players = []
for player_name in player_names: for player_name in player_names:
player = Playerctl.Player.new_from_name(player_name) player = Playerctl.Player.new_from_name(player_name)
players.append( players.append({
{ "player":
"player": player, player,
"player_name": player_name, "player_name":
player_name,
"sorting_key": ( "sorting_key": (
player.props.playback_status != Playerctl.PlaybackStatus.PLAYING, player.props.playback_status != Playerctl.PlaybackStatus.PLAYING,
-PLAYER_NAME_PRIORITIES.get(player_name.name, 0), -PLAYER_NAME_PRIORITIES.get(player_name.name, 0),
player_name.instance, player_name.instance,
), ),
} })
) players = sorted(players, key=lambda player_and_meta: player_and_meta["sorting_key"])
players = sorted(
players, key=lambda player_and_meta: player_and_meta["sorting_key"]
)
for player_and_meta in players: for player_and_meta in players:
player_name = player_and_meta["player_name"] player_name = player_and_meta["player_name"]
@ -201,9 +199,7 @@ if len(player_names) > 0:
) )
) )
player_icon_name = PLAYER_ICON_NAME_FIXES.get( player_icon_name = PLAYER_ICON_NAME_FIXES.get(player_name.name, player_name.name)
player_name.name, player_name.name
)
player_icon = Gtk.Image.new_from_icon_name(player_icon_name, Gtk.IconSize.MENU) player_icon = Gtk.Image.new_from_icon_name(player_icon_name, Gtk.IconSize.MENU)
player_menu_item.set_image(player_icon) player_menu_item.set_image(player_icon)
@ -234,18 +230,14 @@ if len(player_names) > 0:
action_menu_item = Gtk.ImageMenuItem.new_with_mnemonic(action_name) action_menu_item = Gtk.ImageMenuItem.new_with_mnemonic(action_name)
if action_icon_name is not None: if action_icon_name is not None:
action_icon = Gtk.Image.new_from_icon_name( action_icon = Gtk.Image.new_from_icon_name(action_icon_name, Gtk.IconSize.MENU)
action_icon_name, Gtk.IconSize.MENU
)
action_menu_item.set_image(action_icon) action_menu_item.set_image(action_icon)
action_menu_item.set_sensitive(action_enabled) action_menu_item.set_sensitive(action_enabled)
if action_fn is not None: if action_fn is not None:
action_menu_item.connect( action_menu_item.connect(
"activate", "activate",
lambda _menu_item, action_fn, action_fn_args: action_fn( lambda _menu_item, action_fn, action_fn_args: action_fn(*action_fn_args),
*action_fn_args
),
action_fn, action_fn,
action_fn_args, action_fn_args,
) )
@ -259,7 +251,6 @@ else:
menu_item.set_sensitive(False) menu_item.set_sensitive(False)
root_menu.append(menu_item) root_menu.append(menu_item)
root_menu.connect("selection-done", Gtk.main_quit) root_menu.connect("selection-done", Gtk.main_quit)
root_menu.connect("deactivate", Gtk.main_quit) root_menu.connect("deactivate", Gtk.main_quit)
root_menu.connect("destroy", Gtk.main_quit) root_menu.connect("destroy", Gtk.main_quit)

View file

@ -16,10 +16,10 @@ import shutil
import sqlite3 import sqlite3
from typing import Optional, Tuple, Generator from typing import Optional, Tuple, Generator
sys.path.insert(1, os.path.join(os.path.dirname(__file__), "..", "script-resources")) sys.path.insert(1, os.path.join(os.path.dirname(__file__), "..", "script-resources"))
import common_script_utils import common_script_utils
if sys.platform == "darwin": if sys.platform == "darwin":
firefox_home: Path = Path.home() / "Library" / "Application Support" / "Firefox" firefox_home: Path = Path.home() / "Library" / "Application Support" / "Firefox"
elif os.name == "posix": elif os.name == "posix":
@ -27,13 +27,10 @@ elif os.name == "posix":
else: else:
common_script_utils.platform_not_supported_error() common_script_utils.platform_not_supported_error()
profiles_config = ConfigParser(interpolation=None) profiles_config = ConfigParser(interpolation=None)
profiles_config.read(firefox_home / "profiles.ini") profiles_config.read(firefox_home / "profiles.ini")
installs_sections: list[str] = [ installs_sections: list[str] = [s for s in profiles_config.sections() if s.startswith("Install")]
s for s in profiles_config.sections() if s.startswith("Install")
]
if not installs_sections: if not installs_sections:
raise Exception("no Firefox installations detected!") raise Exception("no Firefox installations detected!")
if len(installs_sections) > 1: if len(installs_sections) > 1:
@ -45,7 +42,6 @@ db_path: Path = profile_dir / "weave" / "bookmarks.sqlite"
if not db_path.is_file(): if not db_path.is_file():
raise Exception("'{}' is not a file".format(db_path)) raise Exception("'{}' is not a file".format(db_path))
# Firefox holds a lock over the database file, so I can't connect to it even # Firefox holds a lock over the database file, so I can't connect to it even
# in the readonly mode: https://stackoverflow.com/a/7857866/12005228 # in the readonly mode: https://stackoverflow.com/a/7857866/12005228
# as a workaround I copy the file # as a workaround I copy the file
@ -97,9 +93,7 @@ try:
if folder_title is not None: if folder_title is not None:
folder_path.append(folder_title) folder_path.append(folder_title)
folder_path_str = ( folder_path_str = (("/" + "/".join(reversed(folder_path))) if len(folder_path) > 0 else None)
("/" + "/".join(reversed(folder_path))) if len(folder_path) > 0 else None
)
chooser_entries.append((url_title, url, folder_path_str)) chooser_entries.append((url_title, url, folder_path_str))
if url_keyword is not None: if url_keyword is not None:
@ -118,9 +112,7 @@ def chooser_entries_iter() -> Generator[str, None, None]:
yield entry yield entry
chosen_index = common_script_utils.run_chooser( chosen_index = common_script_utils.run_chooser(chooser_entries_iter(), prompt="bookmark")
chooser_entries_iter(), prompt="bookmark"
)
if chosen_index >= 0: if chosen_index >= 0:
_title, url, _folder_path_str = chooser_entries[chosen_index] _title, url, _folder_path_str = chooser_entries[chosen_index]

View file

@ -1,4 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python3
import random import random

159
zsh/completions/_gh Normal file
View file

@ -0,0 +1,159 @@
#compdef _gh gh
# zsh completion for gh -*- shell-script -*-
__gh_debug()
{
local file="$BASH_COMP_DEBUG_FILE"
if [[ -n ${file} ]]; then
echo "$*" >> "${file}"
fi
}
_gh()
{
local shellCompDirectiveError=1
local shellCompDirectiveNoSpace=2
local shellCompDirectiveNoFileComp=4
local shellCompDirectiveFilterFileExt=8
local shellCompDirectiveFilterDirs=16
local lastParam lastChar flagPrefix requestComp out directive compCount comp lastComp
local -a completions
__gh_debug "\n========= starting completion logic =========="
__gh_debug "CURRENT: ${CURRENT}, words[*]: ${words[*]}"
# The user could have moved the cursor backwards on the command-line.
# We need to trigger completion from the $CURRENT location, so we need
# to truncate the command-line ($words) up to the $CURRENT location.
# (We cannot use $CURSOR as its value does not work when a command is an alias.)
words=("${=words[1,CURRENT]}")
__gh_debug "Truncated words[*]: ${words[*]},"
lastParam=${words[-1]}
lastChar=${lastParam[-1]}
__gh_debug "lastParam: ${lastParam}, lastChar: ${lastChar}"
# For zsh, when completing a flag with an = (e.g., gh -n=<TAB>)
# completions must be prefixed with the flag
setopt local_options BASH_REMATCH
if [[ "${lastParam}" =~ '-.*=' ]]; then
# We are dealing with a flag with an =
flagPrefix="-P ${BASH_REMATCH}"
fi
# Prepare the command to obtain completions
requestComp="${words[1]} __complete ${words[2,-1]}"
if [ "${lastChar}" = "" ]; then
# If the last parameter is complete (there is a space following it)
# We add an extra empty parameter so we can indicate this to the go completion code.
__gh_debug "Adding extra empty parameter"
requestComp="${requestComp} \"\""
fi
__gh_debug "About to call: eval ${requestComp}"
# Use eval to handle any environment variables and such
out=$(eval ${requestComp} 2>/dev/null)
__gh_debug "completion output: ${out}"
# Extract the directive integer following a : from the last line
local lastLine
while IFS='\n' read -r line; do
lastLine=${line}
done < <(printf "%s\n" "${out[@]}")
__gh_debug "last line: ${lastLine}"
if [ "${lastLine[1]}" = : ]; then
directive=${lastLine[2,-1]}
# Remove the directive including the : and the newline
local suffix
(( suffix=${#lastLine}+2))
out=${out[1,-$suffix]}
else
# There is no directive specified. Leave $out as is.
__gh_debug "No directive found. Setting do default"
directive=0
fi
__gh_debug "directive: ${directive}"
__gh_debug "completions: ${out}"
__gh_debug "flagPrefix: ${flagPrefix}"
if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
__gh_debug "Completion received error. Ignoring completions."
return
fi
compCount=0
while IFS='\n' read -r comp; do
if [ -n "$comp" ]; then
# If requested, completions are returned with a description.
# The description is preceded by a TAB character.
# For zsh's _describe, we need to use a : instead of a TAB.
# We first need to escape any : as part of the completion itself.
comp=${comp//:/\\:}
local tab=$(printf '\t')
comp=${comp//$tab/:}
((compCount++))
__gh_debug "Adding completion: ${comp}"
completions+=${comp}
lastComp=$comp
fi
done < <(printf "%s\n" "${out[@]}")
if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
# File extension filtering
local filteringCmd
filteringCmd='_files'
for filter in ${completions[@]}; do
if [ ${filter[1]} != '*' ]; then
# zsh requires a glob pattern to do file filtering
filter="\*.$filter"
fi
filteringCmd+=" -g $filter"
done
filteringCmd+=" ${flagPrefix}"
__gh_debug "File filtering command: $filteringCmd"
_arguments '*:filename:'"$filteringCmd"
elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
# File completion for directories only
local subDir
subdir="${completions[1]}"
if [ -n "$subdir" ]; then
__gh_debug "Listing directories in $subdir"
pushd "${subdir}" >/dev/null 2>&1
else
__gh_debug "Listing directories in ."
fi
_arguments '*:dirname:_files -/'" ${flagPrefix}"
if [ -n "$subdir" ]; then
popd >/dev/null 2>&1
fi
elif [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ] && [ ${compCount} -eq 1 ]; then
__gh_debug "Activating nospace."
# We can use compadd here as there is no description when
# there is only one completion.
compadd -S '' "${lastComp}"
elif [ ${compCount} -eq 0 ]; then
if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
__gh_debug "deactivating file completion"
else
# Perform file completion
__gh_debug "activating file completion"
_arguments '*:filename:_files'" ${flagPrefix}"
fi
else
_describe "completions" completions $(echo $flagPrefix)
fi
}
# don't run the completion function when being source-ed or eval-ed
if [ "$funcstack[1]" = "_gh" ]; then
_gh
fi

359
zsh/completions/_keybase Normal file
View file

@ -0,0 +1,359 @@
#compdef keybase
#autoload
# keybase completion, based on cli help text
# https://github.com/fnoris/keybase-zsh-completion
# The MIT License (MIT)
#
# Copyright (c) 2014 David Tiersch
#
# 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.
local curcontext="$curcontext" state line ret=1
local -a _command_args
local -a _global_args
local -a _subcommands
local IFS=$'\n'
_global_args=($(keybase advanced | grep '^\s*--' | sed -r 's/^[\t ]*(--[^\t ,]+)( [^\t ,]*)?,? ?(--?[^\t ]+)?[\t ]*(.*)$/(\3)\1[\4]/'))
_arguments -C -A "-v" -A "--version"\
'(- 1 *)'{-v,--version}'[display version information]' \
'1: :->cmds' \
$_global_args \
'*:: :->args' && ret=0
case $state in
cmds)
_subcommands=(
"base62:base62 operations"
"cert:print the CA cert for api.keybase.io"
"chat:chat securely with keybase users"
"ctl:control the background keybase service"
"currency:manage cyrptocurrency address"
"decrypt:decrypt messages or files for keybase users"
"deprovision:revoke the current device, log out, and delete local state"
"device:manage your devices"
"dump-keyfamily:print out a user's current key family"
"encrypt:encrypt messages or files for keybase users"
"follow:verify a user's authenticity and optionally follow them"
"track:verify a user's authenticity and optionally follow them"
"fs:perform filesystem operations"
"id:identify a user and check their signature chain"
"list-followers:list thost who follow you"
"list-following:list who you or the given user is following"
"log:manage keybase log"
"login:establish a session with the keybase server"
"logout:logout and remove session information"
"paperkey:generate paper keys for recovering your account"
"passphrase:change or recover your keybase passphrase"
"pgp:manage keybase PGP keys"
"ping:ping the keybase API server"
"prove:generate a new proof"
"rekey:rekey status and actions"
"search:search for keybase users"
"sign:sign a document"
"signup:signup for a new account"
"sigs:manage signatures"
"status:show information about current user"
"unfollow:unfollow a user"
"untrack:unfollow a user"
"update:the updater"
"verify:verify message or file signatures for keybase users"
"version:print out version and build information"
"help, h:shows a list fo commands or help for one command"
)
_describe -t subcommands 'Keybase subcommands' _subcommands && ret=0
;;
args)
case $line[1] in
help)
_values 'commands' \
'base62' \
'cert' \
'chat' \
'ctl' \
'currency' \
'decrypt' \
'deprovision' \
'device' \
'dump-keyfamily' \
'encrypt' \
'follow' \
'track' \
'fs' \
'id' \
'list-followers' \
'list-following' \
'log' \
'login' \
'logout' \
'paperkey' \
'pasphrase' \
'pgp' \
'ping' \
'prove' \
'rekey' \
'search' \
'sign' \
'signup' \
'sigs' \
'status' \
'unfollow' \
'untrack' \
'update' \
'verify' \
'version' \
'help, h' && ret=0
;;
base62)
_values "command" \
'decode[base62 decode]' \
'encode[base62 encode]' \
'help[Shows a list of commands or help for one command]'
;;
chat)
_values "command" \
'api[JSON api]' \
'download[Download an attachment from a conversation]' \
'hide[Hide or block a conversation]' \
'list[List conversations, sorted by activity]' \
'ls[List conversations, sorted by activity]' \
"list-unread[List conversations, with unread messages at the top]" \
"lsur[List conversations, with unread messages at the top]" \
'mute[Mute or unmute a conversation]' \
'read[Show new messages in a conversation and mark them as read]' \
'report[Report a conversation (also blocks it)]' \
'send[Send a message to a conversation]' \
'upload[Upload an attachment to a conversation]' \
'help[Shows a list of commands or help for one command]'
;;
ctl)
_values "command" \
'start[Start the backgroung keybase service]' \
'stop[Stop the backgroung keybase service]' \
'reload[Reload config file]' \
'restart[Restart the background keybase service]' \
"log-rotate[Close and open the keybase service's log file]" \
'watchdog[Start, watch and prop up the backgound service]' \
'watchdog2[Start and monitor background services]' \
'app-exit[Exit the Keybase app]' \
'help[Shows a list of commands or help for one command]'
;;
currency)
_values "command" \
'add[Sign a cryptocurrency (bitcoin or zcash) address into your identity]' \
'help[Shows a list of commands or help for one command]'
;;
decrypt)
_command_args=(
'(--infile)--infile[Specify an input file]' \
'(--message)--message[Provide the message on the command line]' \
'(--outfile)--outfile[Specify an outfile (stdout by default)]' \
'(--interactive)--interactive[Interactive prompt for decryption after sender verification]' \
'(--force)--force[Force unprompted decryption, even on an indentify failure]' \
'(--paperkey)--paperkey[Use a paper key for decryption]' \
'(--encryptor-outfile)--encryptor-outfile[Write the Keybase name of the encryptor to this file]'
)
;;
device)
_values "command" \
'remove[Remove a device]' \
'list[List devices]' \
'add[Authorize a new device]' \
'help[Shows a list of commands or help for one command]'
;;
encrypt)
_command_args=(
'(--binary)--binary[Output in binary (rather than ASCII/armored)]' \
'(--infile)--infile[Specify an input file]' \
'(message)--message[Provide the message on the command line]' \
'(--outfile)--outfile[Specify an outfile (stdout by default)]' \
"(--hide-recipients)--hide-recipients[Don't include recipients in metadata]" \
"(--anonymous)--anonymous[Don't include sender or recipients in metadata. Implies --hide-recipients]" \
"(--no-self)--no-self[Don't encrypt for yourself]"
)
;;
follow)
_command_args=(
"(--local)--local[Only follow locally, don't send a public statement to the server]" \
'(-y)-y[Approve remote following without prompting]' \
'(--skip-proof-cache)--skip-proof-cache[Skip cached proofs, force re-check]'
)
;;
track)
_command_args=(
"(--local)--local[Only follow locally, don't send a public statement to the server]" \
'(-y)-y[Approve remote following without prompting]' \
'(--skip-proof-cache)--skip-proof-cache[Skip cached proofs, force re-check]'
)
;;
fs)
_values "command" \
'ls[list directory contents]' \
'cp[copy one or more directory elements to dest]' \
'mv[move one or more directory elements to dest]' \
'read[output file contents to standard output]' \
'rm[remove one or more directory elements]' \
'mkdir[create directory]' \
'stat[stat directory element]' \
'get-status[get status of pending operation]' \
'kill[kill operation]' \
'ps[list running operations]' \
'write[write input to file]' \
'help[Shows a list of commands or help for one command]'
;;
id)
_command_args=(
'(--skip-proof-cache)--skip-proof-cache[Skip cached proofs, force re-check]'
)
;;
list-followers)
_command_args=(
'(--verbose)--verbose[A full dump, with more gory details]'
)
;;
list-following)
_command_args=(
'(--filter)--filter[Provide a regex filter]' \
'(--headers)--headers[Show column headers]' \
'(--json)--json[Output as JSON (default is text)]' \
'(--verbose)--verbose[A full dump, with more gory details]'
)
;;
log)
_values "command" \
'send[Send recent debug logs to keybase]' \
'help[Shows a list of commands or help for one command]'
;;
login)
_command_args=(
'(--provision-by-email)--provision-by-email[Use an email address associated with a keybase account to provision a device]'
)
;;
passphrase)
_values "command" \
'change[Change your keybase account passphrase]' \
'recover[Recover your keybase account passphrase]' \
'help[Shows a list of commands or help for one command]'
;;
pgp)
_values "command" \
'gen[Generate a new PGP key and write to local secret keychain]' \
'pull[Download the latest PGP keys for people you track]' \
'update[Update your public PGP keys on keybase with those exported from the local GPG keyring]' \
'select[Select a key as your own and register the public half with the server]' \
'sign[PGP sign a document]' \
'encrypt[PGP encrypt messages or files for keybase users]' \
'decrypt[PGP decrypt messages or files for keybase users]' \
'verify[PGP verify message or file signatures for keybase users]' \
'export[Export a PGP key from keybase]' \
'import[Import a PGP key into keybase]' \
'drop[Drop Keybases use of a PGP key]' \
'list[List the active PGP keys in your account]' \
'purge[Purge all PGP keys from Keybase keyring]' \
'help[Shows a list of commands or help for one command]'
;;
ping)
_command_args=(
'(--gregor)--gregor[Ping the Gregor server]'
)
;;
prove)
_command_args=(
'(--output)--output[Output proof text to file (rather than standard out)]' \
"(--force)--force[Don't prompt]" \
)
_values "prove command" \
'service[Supported services are: coinbase, hackernews, reddit, dns, github, twitter, web, http, https]' \
'service username[Username or hostname at that service]'
;;
rekey)
_values "command" \
'status[Get pending rekey status]' \
'paper[Submit a paper key to help rekeying]' \
'help[Shows a list of commands or help for one command]'
;;
search)
_command_args=(
'(--json)--json[Output as JSON]'
)
;;
sign)
_command_args=(
'(--binary)--binary[Output binary message (default is armored)]' \
'(--detached)--detached[Detached signature (default is attached)]' \
'(--infile)--infile[Specify an input file]' \
'(--message)--message[Provide the message to sign on the command line]' \
'(--outfile)--outfile[Specify an outfile (default is STDOUT)]'
)
;;
signup)
_command_args=(
'(--invite-code)--invite-code[Specify an invite code]' \
'(--email)--email[Specify an account email]' \
'(--username)--username[Specify a username]'
)
;;
sigs)
_values "command" \
'list[List signatures]' \
'revoke[Revoke a signature by sig ID]' \
'help[Shows a list of commands or help for one command]'
;;
status)
_command_args=(
'(--json)--json[Output status as JSON]' \
)
;;
update)
_values "command" \
'check[Trigger an update check]' \
'run[Run the update with custom options]' \
'check-in-use[Check if we are in use (safe for restart)]' \
'notify[Notify the service about an update event]'
;;
verify)
_command_args=(
'(--detached)--detached[Specify a detached signature file]' \
'(--infile)--infile[Specify an input file]' \
'(--message)--message[Provide the message to verify on the command line]' \
"(--no-output)--no-output[Don't output the verified message]" \
'(--outfile)--outfile[Specify an outfile (default is STDOUT)]'
'(--signed-by)--signed-by[Assert signed by the given user (can use user assertion fomat)]' \
)
;;
version)
_command_args=(
"(--format)--format[Alternate format for version output. Specify 's' for simple (1.2.3) or 'v' for verbose. Default (blank) includes build number (1.2.3-400)]" \
"(--no-service)--no-service[Don't report on the service's build information]"
)
;;
esac
;;
esac
_arguments \
$_command_args \
&& ret=0
return ret
s