Project import generated by Copybara.

GitOrigin-RevId: 3fc1143a04da49a92c3663813c6a0c1e8ccd477f
This commit is contained in:
Default email 2020-09-29 23:42:59 -04:00
parent 00c94273fd
commit c4fb0432ae
7389 changed files with 1663080 additions and 0 deletions

5
third_party/tvl/.envrc vendored Normal file
View file

@ -0,0 +1,5 @@
# Configure the local PATH to contain tools which are fetched ad-hoc
# from Nix.
export PATH="${PWD}/bin:${PATH}"
export REPO_ROOT="${PWD}"

23
third_party/tvl/.git-blame-ignore-revs vendored Normal file
View file

@ -0,0 +1,23 @@
# This file contains commits that should be ignored when calculating
# git blame layers.
#
# You should add it to your local configuration using:
# git config blame.ignoreRevsFile .git-blame-ignore-revs
# style(3p/nix): Reformat project in Google C++ style
0f2cf531f705d370321843e5ba9135b2ebdb5d19
# style(3p/nix): Reformat all includes to match new style
c758de9d22506eb279c5abe61f621e5c8f61af95
# style(3p/nix): Reformat all includes to match new style
c758de9d22506eb279c5abe61f621e5c8f61af95
# style(3p/nix): Add braces around single-line conditionals
867055133d3f487e52dd44149f76347c2c28bf10
# style(3p/nix): Add braces around single-line for-loops
1841d93ccbe5792a17f5b9a22e65ec898c7c2668
# style(3p/nix): Final act in the brace-wrapping saga
39087321811e81e26a1a47d6967df1088dcf0e95

7
third_party/tvl/.gitignore vendored Normal file
View file

@ -0,0 +1,7 @@
# Ignore the garbage folder, in which I slowly assemble a bunch of
# trash locally that might be valuable in the future.
garbage/
# Ignore Nix result symlinks
result
result-*

1
third_party/tvl/.hgignore vendored Normal file
View file

@ -0,0 +1 @@
.git

1
third_party/tvl/.mailmap vendored Normal file
View file

@ -0,0 +1 @@
Alyssa Ross <hi@alyssa.is>

1
third_party/tvl/.rgignore vendored Normal file
View file

@ -0,0 +1 @@
third_party/git

22
third_party/tvl/.rustfmt.toml vendored Normal file
View file

@ -0,0 +1,22 @@
# This configuration file changes some defaults from the ones
# documented on https://rust-lang.github.io/rustfmt/
#
# All other settings are left at the defaults.
edition = "2018"
newline_style = "Unix"
use_try_shorthand = true
# Unstable settings that we want in the future, once they are
# available:
#
# combine_control_expr = false
# comment_width = 100
# condense_wildcard_suffixes = true
# format_code_in_doc_comments = true
# inline_attribute_width = 100
# match_block_trailing_comma = true
# merge_imports = true
# normalize_comments = true
# overflow_delimited_expr = true
# wrap_comments = true

21
third_party/tvl/LICENSE vendored Normal file
View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2019 Vincent Ambo
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.

4
third_party/tvl/OWNERS vendored Normal file
View file

@ -0,0 +1,4 @@
inherited: false
owners:
- tazjin
- lukegb

109
third_party/tvl/README.md vendored Normal file
View file

@ -0,0 +1,109 @@
depot
=====
[![Build status](https://badge.buildkite.com/016bff4b8ae2704a3bbbb0a250784e6692007c582983b6dea7.svg?branch=canon)](https://buildkite.com/tvl/depot)
This repository is the [monorepo][] for the community around [tazjin's virus
lounge][tvl], containing our personal tools and infrastructure. Everything in
here is built using [Nix][].
A large portion of the software here is very self-referential, meaning that it
exists to sustain the operation of the repository. This is the case because we
partially see this as [an experiment][] in tooling for monorepos.
If you've ended up here and have no idea who I am, feel free to follow me [on
Twitter][].
# Highlights
## Services
* Source code is available primarily through Sourcegraph on
[cs.tvl.fyi](https://cs.tvl.fyi), where it is searchable and even semantically
indexed. A lower-tech view of the repository is also available via cgit on
[code.tvl.fyi](https://code.tvl.fyi).
The repository can be cloned using `git` from `https://cl.tvl.fyi/depot`.
* All code in the depot, with the exception of code that is checked in to
individual `//users` folders, needs to be reviewed. We use Gerrit on
[cl.tvl.fyi](https://cl.tvl.fyi) for this.
* Issues are tracked via our own issue tracker on
[b.tvl.fyi](https://b.tvl.fyi). Its source code lives at
[`//web/panettone/`][panettone].
* Smaller todo-list entries which do not warrant a separate issue are listed at
[todo.tvl.fyi](https://todo.tvl.fyi).
* We use Buildkite for CI. Recent builds are listed on
[tvl.fyi/builds](https://tvl.fyi/builds) and pipelines are configured
dynamically via
[`//ops/pipelines`](https://cs.tvl.fyi/depot/-/tree/ops/pipelines).
All services that we host are deployed on NixOS machines that we manage. Their
configuration is tracked in `//ops/nixos`.
## Nix
* `//third_party/nix` contains Tvix, [our fork][tvix] of the Nix package manager
* [`//nix/readTree`](https://cs.tvl.fyi/depot/-/blob/nix/readTree/README.md)
contains the Nix code which automatically registers projects in our Nix
attribute hierarchy based on their in-tree location
* `//nix/yants` contains **Y**et **A**nother **N**ix **T**ype **S**ystem, which
we use for a variety of things throughout the repository
* `//nix/buildGo` implements a Nix library that can build Go software in the
style of Bazel's `rules_go`. Go programs in this repository are built using
this library.
* `//nix/buildLisp` implements a Nix library that can build Common Lisp
software. Currently only SBCL is supported. Lisp programs in this repository
are built using this library.
We have a variety of other tools and libraries in the `//nix` folder which may
be of interest.
## Packages / Libraries
* `//net/alcoholic_jwt` contains an easy-to-use JWT-validation library for Rust
* `//net/crimp` contains a high-level HTTP client using cURL for Rust
* `//tools/emacs-pkgs` contains various useful Emacs libraries, for example:
* `dottime.el` provides [dottime][] in the Emacs modeline
* `nix-util.el` provides editing utilities for Nix files
* `term-switcher.el` is an ivy-function for switching between vterm buffers
* `tvl.el` provides helper functions for interacting with the TVL monorepo
* `//lisp/klatre` provides a grab-bag utility library for Common Lisp
## User packages
Contributors to the repository have user directories under
[`//users`](https://cs.tvl.fyi/depot@canon/-/tree/users), which can be used for
personal or experimental code that does not require review.
Some examples:
* `//users/tazjin/homepage` && `//users/tazjin/blog`: A Nix-based static site
generator which generates the web page and Atom feed for
[tazj.in](https://tazj.in)
* `//users/tazjin/finito`: A persistent finite-state machine library for Rust.
* `//users/glittershark/xanthous`: A (WIP) TUI RPG, written in Haskell.
* `//users/tazjin/emacs`: tazjin's Emacs & EXWM configuration
# Licensing
Unless otherwise stated in a subdirectory, all code is licensed under the MIT
license. See [LICENSE](./LICENSE) for details.
# Contributing
If you'd like to contribute to any of the tools in here, please check out the
[contribution guidelines](./docs/CONTRIBUTING.md) and our [code of
conduct](./docs/CODE_OF_CONDUCT.md).
[monorepo]: https://en.wikipedia.org/wiki/Monorepo
[tvl]: https://tvl.fyi
[Nix]: https://nixos.org/nix
[an experiment]: https://tvl.fyi/monorepo-doc
[on Twitter]: https://twitter.com/tazjin
[panettone]: https://cs.tvl.fyi/depot@canon/-/tree/web/panettone
[tvix]: https://cs.tvl.fyi/depot/-/blob/third_party/nix/README.md
[dottime]: https://dotti.me

1
third_party/tvl/RULES vendored Normal file
View file

@ -0,0 +1 @@
1. Only those who pay the Golden Price may bear The Wheel.

70
third_party/tvl/bin/__dispatch.sh vendored Executable file
View file

@ -0,0 +1,70 @@
#!/usr/bin/env bash
# This script dispatches invocations transparently to programs instantiated from
# Nix.
#
# To add a new tool, insert it into the case statement below by setting `attr`
# to the key in nixpkgs which represents the program you want to run.
set -ueo pipefail
readonly REPO_ROOT=$(dirname "$0")/..
TARGET_TOOL=$(basename "$0")
case "${TARGET_TOOL}" in
age)
attr="third_party.age"
;;
age-keygen)
attr="third_party.age"
;;
aoc2019)
attr="fun.aoc2019.${1}"
;;
depot-build)
attr="tools.depot-build"
;;
git-bug)
attr="third_party.git-bug"
;;
gerrit)
attr="tools.gerrit-cli"
;;
hash-password)
attr="tools.hash-password"
;;
kontemplate)
attr="kontemplate"
;;
meson)
attr="third_party.meson"
;;
ninja)
attr="third_party.ninja"
;;
perf-flamegraph)
attr="tools.perf-flamegraph"
;;
rebuild-system)
attr="ops.nixos.rebuild-system"
;;
rebuilder)
attr="users.tazjin.nixos.rebuilder"
;;
rink)
attr="third_party.rink"
;;
stern)
attr="third_party.stern"
;;
terraform)
attr="third_party.terraform-gcp"
;;
*)
echo "The tool '${TARGET_TOOL}' is currently not installed in this repository."
exit 1
;;
esac
result=$(nix-build --no-out-link --attr "${attr}" "${REPO_ROOT}")
PATH="${result}/bin:$PATH"
exec "${TARGET_TOOL}" "${@}"

70
third_party/tvl/bin/age vendored Executable file
View file

@ -0,0 +1,70 @@
#!/usr/bin/env bash
# This script dispatches invocations transparently to programs instantiated from
# Nix.
#
# To add a new tool, insert it into the case statement below by setting `attr`
# to the key in nixpkgs which represents the program you want to run.
set -ueo pipefail
readonly REPO_ROOT=$(dirname "$0")/..
TARGET_TOOL=$(basename "$0")
case "${TARGET_TOOL}" in
age)
attr="third_party.age"
;;
age-keygen)
attr="third_party.age"
;;
aoc2019)
attr="fun.aoc2019.${1}"
;;
depot-build)
attr="tools.depot-build"
;;
git-bug)
attr="third_party.git-bug"
;;
gerrit)
attr="tools.gerrit-cli"
;;
hash-password)
attr="tools.hash-password"
;;
kontemplate)
attr="kontemplate"
;;
meson)
attr="third_party.meson"
;;
ninja)
attr="third_party.ninja"
;;
perf-flamegraph)
attr="tools.perf-flamegraph"
;;
rebuild-system)
attr="ops.nixos.rebuild-system"
;;
rebuilder)
attr="users.tazjin.nixos.rebuilder"
;;
rink)
attr="third_party.rink"
;;
stern)
attr="third_party.stern"
;;
terraform)
attr="third_party.terraform-gcp"
;;
*)
echo "The tool '${TARGET_TOOL}' is currently not installed in this repository."
exit 1
;;
esac
result=$(nix-build --no-out-link --attr "${attr}" "${REPO_ROOT}")
PATH="${result}/bin:$PATH"
exec "${TARGET_TOOL}" "${@}"

70
third_party/tvl/bin/age-keygen vendored Executable file
View file

@ -0,0 +1,70 @@
#!/usr/bin/env bash
# This script dispatches invocations transparently to programs instantiated from
# Nix.
#
# To add a new tool, insert it into the case statement below by setting `attr`
# to the key in nixpkgs which represents the program you want to run.
set -ueo pipefail
readonly REPO_ROOT=$(dirname "$0")/..
TARGET_TOOL=$(basename "$0")
case "${TARGET_TOOL}" in
age)
attr="third_party.age"
;;
age-keygen)
attr="third_party.age"
;;
aoc2019)
attr="fun.aoc2019.${1}"
;;
depot-build)
attr="tools.depot-build"
;;
git-bug)
attr="third_party.git-bug"
;;
gerrit)
attr="tools.gerrit-cli"
;;
hash-password)
attr="tools.hash-password"
;;
kontemplate)
attr="kontemplate"
;;
meson)
attr="third_party.meson"
;;
ninja)
attr="third_party.ninja"
;;
perf-flamegraph)
attr="tools.perf-flamegraph"
;;
rebuild-system)
attr="ops.nixos.rebuild-system"
;;
rebuilder)
attr="users.tazjin.nixos.rebuilder"
;;
rink)
attr="third_party.rink"
;;
stern)
attr="third_party.stern"
;;
terraform)
attr="third_party.terraform-gcp"
;;
*)
echo "The tool '${TARGET_TOOL}' is currently not installed in this repository."
exit 1
;;
esac
result=$(nix-build --no-out-link --attr "${attr}" "${REPO_ROOT}")
PATH="${result}/bin:$PATH"
exec "${TARGET_TOOL}" "${@}"

70
third_party/tvl/bin/aoc2019 vendored Executable file
View file

@ -0,0 +1,70 @@
#!/usr/bin/env bash
# This script dispatches invocations transparently to programs instantiated from
# Nix.
#
# To add a new tool, insert it into the case statement below by setting `attr`
# to the key in nixpkgs which represents the program you want to run.
set -ueo pipefail
readonly REPO_ROOT=$(dirname "$0")/..
TARGET_TOOL=$(basename "$0")
case "${TARGET_TOOL}" in
age)
attr="third_party.age"
;;
age-keygen)
attr="third_party.age"
;;
aoc2019)
attr="fun.aoc2019.${1}"
;;
depot-build)
attr="tools.depot-build"
;;
git-bug)
attr="third_party.git-bug"
;;
gerrit)
attr="tools.gerrit-cli"
;;
hash-password)
attr="tools.hash-password"
;;
kontemplate)
attr="kontemplate"
;;
meson)
attr="third_party.meson"
;;
ninja)
attr="third_party.ninja"
;;
perf-flamegraph)
attr="tools.perf-flamegraph"
;;
rebuild-system)
attr="ops.nixos.rebuild-system"
;;
rebuilder)
attr="users.tazjin.nixos.rebuilder"
;;
rink)
attr="third_party.rink"
;;
stern)
attr="third_party.stern"
;;
terraform)
attr="third_party.terraform-gcp"
;;
*)
echo "The tool '${TARGET_TOOL}' is currently not installed in this repository."
exit 1
;;
esac
result=$(nix-build --no-out-link --attr "${attr}" "${REPO_ROOT}")
PATH="${result}/bin:$PATH"
exec "${TARGET_TOOL}" "${@}"

70
third_party/tvl/bin/depot-build vendored Executable file
View file

@ -0,0 +1,70 @@
#!/usr/bin/env bash
# This script dispatches invocations transparently to programs instantiated from
# Nix.
#
# To add a new tool, insert it into the case statement below by setting `attr`
# to the key in nixpkgs which represents the program you want to run.
set -ueo pipefail
readonly REPO_ROOT=$(dirname "$0")/..
TARGET_TOOL=$(basename "$0")
case "${TARGET_TOOL}" in
age)
attr="third_party.age"
;;
age-keygen)
attr="third_party.age"
;;
aoc2019)
attr="fun.aoc2019.${1}"
;;
depot-build)
attr="tools.depot-build"
;;
git-bug)
attr="third_party.git-bug"
;;
gerrit)
attr="tools.gerrit-cli"
;;
hash-password)
attr="tools.hash-password"
;;
kontemplate)
attr="kontemplate"
;;
meson)
attr="third_party.meson"
;;
ninja)
attr="third_party.ninja"
;;
perf-flamegraph)
attr="tools.perf-flamegraph"
;;
rebuild-system)
attr="ops.nixos.rebuild-system"
;;
rebuilder)
attr="users.tazjin.nixos.rebuilder"
;;
rink)
attr="third_party.rink"
;;
stern)
attr="third_party.stern"
;;
terraform)
attr="third_party.terraform-gcp"
;;
*)
echo "The tool '${TARGET_TOOL}' is currently not installed in this repository."
exit 1
;;
esac
result=$(nix-build --no-out-link --attr "${attr}" "${REPO_ROOT}")
PATH="${result}/bin:$PATH"
exec "${TARGET_TOOL}" "${@}"

70
third_party/tvl/bin/gerrit vendored Executable file
View file

@ -0,0 +1,70 @@
#!/usr/bin/env bash
# This script dispatches invocations transparently to programs instantiated from
# Nix.
#
# To add a new tool, insert it into the case statement below by setting `attr`
# to the key in nixpkgs which represents the program you want to run.
set -ueo pipefail
readonly REPO_ROOT=$(dirname "$0")/..
TARGET_TOOL=$(basename "$0")
case "${TARGET_TOOL}" in
age)
attr="third_party.age"
;;
age-keygen)
attr="third_party.age"
;;
aoc2019)
attr="fun.aoc2019.${1}"
;;
depot-build)
attr="tools.depot-build"
;;
git-bug)
attr="third_party.git-bug"
;;
gerrit)
attr="tools.gerrit-cli"
;;
hash-password)
attr="tools.hash-password"
;;
kontemplate)
attr="kontemplate"
;;
meson)
attr="third_party.meson"
;;
ninja)
attr="third_party.ninja"
;;
perf-flamegraph)
attr="tools.perf-flamegraph"
;;
rebuild-system)
attr="ops.nixos.rebuild-system"
;;
rebuilder)
attr="users.tazjin.nixos.rebuilder"
;;
rink)
attr="third_party.rink"
;;
stern)
attr="third_party.stern"
;;
terraform)
attr="third_party.terraform-gcp"
;;
*)
echo "The tool '${TARGET_TOOL}' is currently not installed in this repository."
exit 1
;;
esac
result=$(nix-build --no-out-link --attr "${attr}" "${REPO_ROOT}")
PATH="${result}/bin:$PATH"
exec "${TARGET_TOOL}" "${@}"

70
third_party/tvl/bin/git-bug vendored Executable file
View file

@ -0,0 +1,70 @@
#!/usr/bin/env bash
# This script dispatches invocations transparently to programs instantiated from
# Nix.
#
# To add a new tool, insert it into the case statement below by setting `attr`
# to the key in nixpkgs which represents the program you want to run.
set -ueo pipefail
readonly REPO_ROOT=$(dirname "$0")/..
TARGET_TOOL=$(basename "$0")
case "${TARGET_TOOL}" in
age)
attr="third_party.age"
;;
age-keygen)
attr="third_party.age"
;;
aoc2019)
attr="fun.aoc2019.${1}"
;;
depot-build)
attr="tools.depot-build"
;;
git-bug)
attr="third_party.git-bug"
;;
gerrit)
attr="tools.gerrit-cli"
;;
hash-password)
attr="tools.hash-password"
;;
kontemplate)
attr="kontemplate"
;;
meson)
attr="third_party.meson"
;;
ninja)
attr="third_party.ninja"
;;
perf-flamegraph)
attr="tools.perf-flamegraph"
;;
rebuild-system)
attr="ops.nixos.rebuild-system"
;;
rebuilder)
attr="users.tazjin.nixos.rebuilder"
;;
rink)
attr="third_party.rink"
;;
stern)
attr="third_party.stern"
;;
terraform)
attr="third_party.terraform-gcp"
;;
*)
echo "The tool '${TARGET_TOOL}' is currently not installed in this repository."
exit 1
;;
esac
result=$(nix-build --no-out-link --attr "${attr}" "${REPO_ROOT}")
PATH="${result}/bin:$PATH"
exec "${TARGET_TOOL}" "${@}"

70
third_party/tvl/bin/hash-password vendored Executable file
View file

@ -0,0 +1,70 @@
#!/usr/bin/env bash
# This script dispatches invocations transparently to programs instantiated from
# Nix.
#
# To add a new tool, insert it into the case statement below by setting `attr`
# to the key in nixpkgs which represents the program you want to run.
set -ueo pipefail
readonly REPO_ROOT=$(dirname "$0")/..
TARGET_TOOL=$(basename "$0")
case "${TARGET_TOOL}" in
age)
attr="third_party.age"
;;
age-keygen)
attr="third_party.age"
;;
aoc2019)
attr="fun.aoc2019.${1}"
;;
depot-build)
attr="tools.depot-build"
;;
git-bug)
attr="third_party.git-bug"
;;
gerrit)
attr="tools.gerrit-cli"
;;
hash-password)
attr="tools.hash-password"
;;
kontemplate)
attr="kontemplate"
;;
meson)
attr="third_party.meson"
;;
ninja)
attr="third_party.ninja"
;;
perf-flamegraph)
attr="tools.perf-flamegraph"
;;
rebuild-system)
attr="ops.nixos.rebuild-system"
;;
rebuilder)
attr="users.tazjin.nixos.rebuilder"
;;
rink)
attr="third_party.rink"
;;
stern)
attr="third_party.stern"
;;
terraform)
attr="third_party.terraform-gcp"
;;
*)
echo "The tool '${TARGET_TOOL}' is currently not installed in this repository."
exit 1
;;
esac
result=$(nix-build --no-out-link --attr "${attr}" "${REPO_ROOT}")
PATH="${result}/bin:$PATH"
exec "${TARGET_TOOL}" "${@}"

70
third_party/tvl/bin/kontemplate vendored Executable file
View file

@ -0,0 +1,70 @@
#!/usr/bin/env bash
# This script dispatches invocations transparently to programs instantiated from
# Nix.
#
# To add a new tool, insert it into the case statement below by setting `attr`
# to the key in nixpkgs which represents the program you want to run.
set -ueo pipefail
readonly REPO_ROOT=$(dirname "$0")/..
TARGET_TOOL=$(basename "$0")
case "${TARGET_TOOL}" in
age)
attr="third_party.age"
;;
age-keygen)
attr="third_party.age"
;;
aoc2019)
attr="fun.aoc2019.${1}"
;;
depot-build)
attr="tools.depot-build"
;;
git-bug)
attr="third_party.git-bug"
;;
gerrit)
attr="tools.gerrit-cli"
;;
hash-password)
attr="tools.hash-password"
;;
kontemplate)
attr="kontemplate"
;;
meson)
attr="third_party.meson"
;;
ninja)
attr="third_party.ninja"
;;
perf-flamegraph)
attr="tools.perf-flamegraph"
;;
rebuild-system)
attr="ops.nixos.rebuild-system"
;;
rebuilder)
attr="users.tazjin.nixos.rebuilder"
;;
rink)
attr="third_party.rink"
;;
stern)
attr="third_party.stern"
;;
terraform)
attr="third_party.terraform-gcp"
;;
*)
echo "The tool '${TARGET_TOOL}' is currently not installed in this repository."
exit 1
;;
esac
result=$(nix-build --no-out-link --attr "${attr}" "${REPO_ROOT}")
PATH="${result}/bin:$PATH"
exec "${TARGET_TOOL}" "${@}"

70
third_party/tvl/bin/meson vendored Executable file
View file

@ -0,0 +1,70 @@
#!/usr/bin/env bash
# This script dispatches invocations transparently to programs instantiated from
# Nix.
#
# To add a new tool, insert it into the case statement below by setting `attr`
# to the key in nixpkgs which represents the program you want to run.
set -ueo pipefail
readonly REPO_ROOT=$(dirname "$0")/..
TARGET_TOOL=$(basename "$0")
case "${TARGET_TOOL}" in
age)
attr="third_party.age"
;;
age-keygen)
attr="third_party.age"
;;
aoc2019)
attr="fun.aoc2019.${1}"
;;
depot-build)
attr="tools.depot-build"
;;
git-bug)
attr="third_party.git-bug"
;;
gerrit)
attr="tools.gerrit-cli"
;;
hash-password)
attr="tools.hash-password"
;;
kontemplate)
attr="kontemplate"
;;
meson)
attr="third_party.meson"
;;
ninja)
attr="third_party.ninja"
;;
perf-flamegraph)
attr="tools.perf-flamegraph"
;;
rebuild-system)
attr="ops.nixos.rebuild-system"
;;
rebuilder)
attr="users.tazjin.nixos.rebuilder"
;;
rink)
attr="third_party.rink"
;;
stern)
attr="third_party.stern"
;;
terraform)
attr="third_party.terraform-gcp"
;;
*)
echo "The tool '${TARGET_TOOL}' is currently not installed in this repository."
exit 1
;;
esac
result=$(nix-build --no-out-link --attr "${attr}" "${REPO_ROOT}")
PATH="${result}/bin:$PATH"
exec "${TARGET_TOOL}" "${@}"

70
third_party/tvl/bin/ninja vendored Executable file
View file

@ -0,0 +1,70 @@
#!/usr/bin/env bash
# This script dispatches invocations transparently to programs instantiated from
# Nix.
#
# To add a new tool, insert it into the case statement below by setting `attr`
# to the key in nixpkgs which represents the program you want to run.
set -ueo pipefail
readonly REPO_ROOT=$(dirname "$0")/..
TARGET_TOOL=$(basename "$0")
case "${TARGET_TOOL}" in
age)
attr="third_party.age"
;;
age-keygen)
attr="third_party.age"
;;
aoc2019)
attr="fun.aoc2019.${1}"
;;
depot-build)
attr="tools.depot-build"
;;
git-bug)
attr="third_party.git-bug"
;;
gerrit)
attr="tools.gerrit-cli"
;;
hash-password)
attr="tools.hash-password"
;;
kontemplate)
attr="kontemplate"
;;
meson)
attr="third_party.meson"
;;
ninja)
attr="third_party.ninja"
;;
perf-flamegraph)
attr="tools.perf-flamegraph"
;;
rebuild-system)
attr="ops.nixos.rebuild-system"
;;
rebuilder)
attr="users.tazjin.nixos.rebuilder"
;;
rink)
attr="third_party.rink"
;;
stern)
attr="third_party.stern"
;;
terraform)
attr="third_party.terraform-gcp"
;;
*)
echo "The tool '${TARGET_TOOL}' is currently not installed in this repository."
exit 1
;;
esac
result=$(nix-build --no-out-link --attr "${attr}" "${REPO_ROOT}")
PATH="${result}/bin:$PATH"
exec "${TARGET_TOOL}" "${@}"

70
third_party/tvl/bin/perf-flamegraph vendored Executable file
View file

@ -0,0 +1,70 @@
#!/usr/bin/env bash
# This script dispatches invocations transparently to programs instantiated from
# Nix.
#
# To add a new tool, insert it into the case statement below by setting `attr`
# to the key in nixpkgs which represents the program you want to run.
set -ueo pipefail
readonly REPO_ROOT=$(dirname "$0")/..
TARGET_TOOL=$(basename "$0")
case "${TARGET_TOOL}" in
age)
attr="third_party.age"
;;
age-keygen)
attr="third_party.age"
;;
aoc2019)
attr="fun.aoc2019.${1}"
;;
depot-build)
attr="tools.depot-build"
;;
git-bug)
attr="third_party.git-bug"
;;
gerrit)
attr="tools.gerrit-cli"
;;
hash-password)
attr="tools.hash-password"
;;
kontemplate)
attr="kontemplate"
;;
meson)
attr="third_party.meson"
;;
ninja)
attr="third_party.ninja"
;;
perf-flamegraph)
attr="tools.perf-flamegraph"
;;
rebuild-system)
attr="ops.nixos.rebuild-system"
;;
rebuilder)
attr="users.tazjin.nixos.rebuilder"
;;
rink)
attr="third_party.rink"
;;
stern)
attr="third_party.stern"
;;
terraform)
attr="third_party.terraform-gcp"
;;
*)
echo "The tool '${TARGET_TOOL}' is currently not installed in this repository."
exit 1
;;
esac
result=$(nix-build --no-out-link --attr "${attr}" "${REPO_ROOT}")
PATH="${result}/bin:$PATH"
exec "${TARGET_TOOL}" "${@}"

70
third_party/tvl/bin/rebuild-system vendored Executable file
View file

@ -0,0 +1,70 @@
#!/usr/bin/env bash
# This script dispatches invocations transparently to programs instantiated from
# Nix.
#
# To add a new tool, insert it into the case statement below by setting `attr`
# to the key in nixpkgs which represents the program you want to run.
set -ueo pipefail
readonly REPO_ROOT=$(dirname "$0")/..
TARGET_TOOL=$(basename "$0")
case "${TARGET_TOOL}" in
age)
attr="third_party.age"
;;
age-keygen)
attr="third_party.age"
;;
aoc2019)
attr="fun.aoc2019.${1}"
;;
depot-build)
attr="tools.depot-build"
;;
git-bug)
attr="third_party.git-bug"
;;
gerrit)
attr="tools.gerrit-cli"
;;
hash-password)
attr="tools.hash-password"
;;
kontemplate)
attr="kontemplate"
;;
meson)
attr="third_party.meson"
;;
ninja)
attr="third_party.ninja"
;;
perf-flamegraph)
attr="tools.perf-flamegraph"
;;
rebuild-system)
attr="ops.nixos.rebuild-system"
;;
rebuilder)
attr="users.tazjin.nixos.rebuilder"
;;
rink)
attr="third_party.rink"
;;
stern)
attr="third_party.stern"
;;
terraform)
attr="third_party.terraform-gcp"
;;
*)
echo "The tool '${TARGET_TOOL}' is currently not installed in this repository."
exit 1
;;
esac
result=$(nix-build --no-out-link --attr "${attr}" "${REPO_ROOT}")
PATH="${result}/bin:$PATH"
exec "${TARGET_TOOL}" "${@}"

70
third_party/tvl/bin/rebuilder vendored Executable file
View file

@ -0,0 +1,70 @@
#!/usr/bin/env bash
# This script dispatches invocations transparently to programs instantiated from
# Nix.
#
# To add a new tool, insert it into the case statement below by setting `attr`
# to the key in nixpkgs which represents the program you want to run.
set -ueo pipefail
readonly REPO_ROOT=$(dirname "$0")/..
TARGET_TOOL=$(basename "$0")
case "${TARGET_TOOL}" in
age)
attr="third_party.age"
;;
age-keygen)
attr="third_party.age"
;;
aoc2019)
attr="fun.aoc2019.${1}"
;;
depot-build)
attr="tools.depot-build"
;;
git-bug)
attr="third_party.git-bug"
;;
gerrit)
attr="tools.gerrit-cli"
;;
hash-password)
attr="tools.hash-password"
;;
kontemplate)
attr="kontemplate"
;;
meson)
attr="third_party.meson"
;;
ninja)
attr="third_party.ninja"
;;
perf-flamegraph)
attr="tools.perf-flamegraph"
;;
rebuild-system)
attr="ops.nixos.rebuild-system"
;;
rebuilder)
attr="users.tazjin.nixos.rebuilder"
;;
rink)
attr="third_party.rink"
;;
stern)
attr="third_party.stern"
;;
terraform)
attr="third_party.terraform-gcp"
;;
*)
echo "The tool '${TARGET_TOOL}' is currently not installed in this repository."
exit 1
;;
esac
result=$(nix-build --no-out-link --attr "${attr}" "${REPO_ROOT}")
PATH="${result}/bin:$PATH"
exec "${TARGET_TOOL}" "${@}"

70
third_party/tvl/bin/rink vendored Executable file
View file

@ -0,0 +1,70 @@
#!/usr/bin/env bash
# This script dispatches invocations transparently to programs instantiated from
# Nix.
#
# To add a new tool, insert it into the case statement below by setting `attr`
# to the key in nixpkgs which represents the program you want to run.
set -ueo pipefail
readonly REPO_ROOT=$(dirname "$0")/..
TARGET_TOOL=$(basename "$0")
case "${TARGET_TOOL}" in
age)
attr="third_party.age"
;;
age-keygen)
attr="third_party.age"
;;
aoc2019)
attr="fun.aoc2019.${1}"
;;
depot-build)
attr="tools.depot-build"
;;
git-bug)
attr="third_party.git-bug"
;;
gerrit)
attr="tools.gerrit-cli"
;;
hash-password)
attr="tools.hash-password"
;;
kontemplate)
attr="kontemplate"
;;
meson)
attr="third_party.meson"
;;
ninja)
attr="third_party.ninja"
;;
perf-flamegraph)
attr="tools.perf-flamegraph"
;;
rebuild-system)
attr="ops.nixos.rebuild-system"
;;
rebuilder)
attr="users.tazjin.nixos.rebuilder"
;;
rink)
attr="third_party.rink"
;;
stern)
attr="third_party.stern"
;;
terraform)
attr="third_party.terraform-gcp"
;;
*)
echo "The tool '${TARGET_TOOL}' is currently not installed in this repository."
exit 1
;;
esac
result=$(nix-build --no-out-link --attr "${attr}" "${REPO_ROOT}")
PATH="${result}/bin:$PATH"
exec "${TARGET_TOOL}" "${@}"

70
third_party/tvl/bin/stern vendored Executable file
View file

@ -0,0 +1,70 @@
#!/usr/bin/env bash
# This script dispatches invocations transparently to programs instantiated from
# Nix.
#
# To add a new tool, insert it into the case statement below by setting `attr`
# to the key in nixpkgs which represents the program you want to run.
set -ueo pipefail
readonly REPO_ROOT=$(dirname "$0")/..
TARGET_TOOL=$(basename "$0")
case "${TARGET_TOOL}" in
age)
attr="third_party.age"
;;
age-keygen)
attr="third_party.age"
;;
aoc2019)
attr="fun.aoc2019.${1}"
;;
depot-build)
attr="tools.depot-build"
;;
git-bug)
attr="third_party.git-bug"
;;
gerrit)
attr="tools.gerrit-cli"
;;
hash-password)
attr="tools.hash-password"
;;
kontemplate)
attr="kontemplate"
;;
meson)
attr="third_party.meson"
;;
ninja)
attr="third_party.ninja"
;;
perf-flamegraph)
attr="tools.perf-flamegraph"
;;
rebuild-system)
attr="ops.nixos.rebuild-system"
;;
rebuilder)
attr="users.tazjin.nixos.rebuilder"
;;
rink)
attr="third_party.rink"
;;
stern)
attr="third_party.stern"
;;
terraform)
attr="third_party.terraform-gcp"
;;
*)
echo "The tool '${TARGET_TOOL}' is currently not installed in this repository."
exit 1
;;
esac
result=$(nix-build --no-out-link --attr "${attr}" "${REPO_ROOT}")
PATH="${result}/bin:$PATH"
exec "${TARGET_TOOL}" "${@}"

70
third_party/tvl/bin/terraform vendored Executable file
View file

@ -0,0 +1,70 @@
#!/usr/bin/env bash
# This script dispatches invocations transparently to programs instantiated from
# Nix.
#
# To add a new tool, insert it into the case statement below by setting `attr`
# to the key in nixpkgs which represents the program you want to run.
set -ueo pipefail
readonly REPO_ROOT=$(dirname "$0")/..
TARGET_TOOL=$(basename "$0")
case "${TARGET_TOOL}" in
age)
attr="third_party.age"
;;
age-keygen)
attr="third_party.age"
;;
aoc2019)
attr="fun.aoc2019.${1}"
;;
depot-build)
attr="tools.depot-build"
;;
git-bug)
attr="third_party.git-bug"
;;
gerrit)
attr="tools.gerrit-cli"
;;
hash-password)
attr="tools.hash-password"
;;
kontemplate)
attr="kontemplate"
;;
meson)
attr="third_party.meson"
;;
ninja)
attr="third_party.ninja"
;;
perf-flamegraph)
attr="tools.perf-flamegraph"
;;
rebuild-system)
attr="ops.nixos.rebuild-system"
;;
rebuilder)
attr="users.tazjin.nixos.rebuilder"
;;
rink)
attr="third_party.rink"
;;
stern)
attr="third_party.stern"
;;
terraform)
attr="third_party.terraform-gcp"
;;
*)
echo "The tool '${TARGET_TOOL}' is currently not installed in this repository."
exit 1
;;
esac
result=$(nix-build --no-out-link --attr "${attr}" "${REPO_ROOT}")
PATH="${result}/bin:$PATH"
exec "${TARGET_TOOL}" "${@}"

13
third_party/tvl/buf.yaml vendored Normal file
View file

@ -0,0 +1,13 @@
build:
roots:
#- proto
- third_party
lint:
ignore:
- nix/buildGo
use:
- BASIC
- FILE_LOWER_SNAKE_CASE
except:
- ENUM_VALUE_UPPER_SNAKE_CASE
- PACKAGE_DIRECTORY_MATCH

109
third_party/tvl/default.nix vendored Normal file
View file

@ -0,0 +1,109 @@
# This file sets up the top-level package set by traversing the package tree
# (see read-tree.nix for details) and constructing a matching attribute set
# tree.
#
# This makes packages accessible via the Nixery instance that is configured to
# use this repository as its nixpkgs source.
{ ... }@args:
with builtins;
let
# This definition of fix is identical to <nixpkgs>.lib.fix, but the global
# package set is not available here.
fix = f: let x = f x; in x;
# Global configuration that all packages are called with.
config = depot: {
inherit depot;
# Expose lib & ciBuilds attributes to packages.
inherit (depot) ciBuilds lib;
# Pass third_party as 'pkgs' (for compatibility with external
# imports for certain subdirectories)
pkgs = depot.third_party;
};
readTree' = import ./nix/readTree {};
localPkgs = readTree: {
fun = readTree ./fun;
lisp = readTree ./lisp;
net = readTree ./net;
nix = readTree ./nix;
ops = readTree ./ops;
third_party = readTree ./third_party;
tools = readTree ./tools;
users = readTree ./users;
web = readTree ./web;
};
# To determine build targets, we walk through the depot tree and
# fetch attributes that were imported by readTree and are buildable.
#
# Any build target that contains `meta.ci = false` will be skipped.
# Is this tree node eligible for build inclusion?
eligible = node: (node ? outPath) && (node.meta.ci or true);
# Walk the tree starting with 'node', recursively extending the list
# of build targets with anything that looks buildable.
#
# Any tree node can specify logical targets by exporting a
# 'meta.targets' attribute containing a list of keys in itself. This
# enables target specifications that do not exist on disk directly.
gather = node:
if node ? __readTree then
# Include the node itself if it is eligible.
(if eligible node then [ node ] else [])
# Include eligible children of the node
++ concatMap gather (attrValues node)
# Include specified sub-targets of the node
++ filter eligible (map
(k: (node."${k}" or {}) // {
# Keep the same tree location, but explicitly mark this
# node as a subtarget.
__readTree = node.__readTree;
__subtarget = k;
})
(node.meta.targets or []))
else [];
in fix(self: {
config = config self;
# Elevate 'lib' from nixpkgs
lib = import (self.third_party.nixpkgsSrc + "/lib");
# Expose readTree for downstream repo consumers.
readTree = {
__functor = x: (readTree' x.config);
config = self.config;
};
# Make the path to the depot available for things that might need it
# (e.g. NixOS module inclusions)
depotPath = ./.;
# List of all buildable targets, for CI purposes.
#
# Note: To prevent infinite recursion, this *must* be a nested
# attribute set (which does not have a __readTree attribute).
ci.targets = gather (self // {
# remove the pipelines themselves from the set over which to
# generate pipelines because that also leads to infinite
# recursion.
ops = self.ops // { pipelines = null; };
});
}
# Add local packages as structured by readTree
// (localPkgs (readTree' self.config))
# Load overrides into the top-level.
#
# This can be used to move things from third_party into the top-level, too (such
# as `lib`).
// (readTree' { depot = self; pkgs = self.third_party; }) ./overrides
)

29
third_party/tvl/docs/CODE_OF_CONDUCT.md vendored Normal file
View file

@ -0,0 +1,29 @@
A SERMON ON ETHICS AND LOVE
===========================
One day Mal-2 asked the messenger spirit Saint Gulik to approach the
Goddess and request Her presence for some desperate advice. Shortly
afterwards the radio came on by itself, and an ethereal female Voice
said **YES?**
"O! Eris! Blessed Mother of Man! Queen of Chaos! Daughter of Discord!
Concubine of Confusion! O! Exquisite Lady, I beseech You to lift a
heavy burden from my heart!"
**WHAT BOTHERS YOU, MAL? YOU DON'T SOUND WELL.**
"I am filled with fear and tormented with terrible visions of pain.
Everywhere people are hurting one another, the planet is rampant with
injustices, whole societies plunder groups of their own people,
mothers imprison sons, children perish while brothers war. O, woe."
**WHAT IS THE MATTER WITH THAT, IF IT IS WHAT YOU WANT TO DO?**
"But nobody Wants it! Everybody hates it."
**OH. WELL, THEN *STOP*.**
At which moment She turned herself into an aspirin commercial and left
The Polyfather stranded alone with his species.
SINISTER DEXTER HAS A BROKEN SPIROMETER.

119
third_party/tvl/docs/CONTRIBUTING.md vendored Normal file
View file

@ -0,0 +1,119 @@
Contribution Guidelines
=======================
<!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc-refresh-toc -->
**Table of Contents**
- [Contribution Guidelines](#contribution-guidelines)
- [Before making a change](#before-making-a-change)
- [Commit messages](#commit-messages)
- [Commit content](#commit-content)
- [Code quality](#code-quality)
- [Builds & tests](#builds--tests)
- [Submitting changes](#submitting-changes)
<!-- markdown-toc end -->
This is a loose set of "guidelines" for contributing to the depot. Please note
that we will not accept any patches that don't follow these guidelines.
Also consider the [code of conduct](./CODE_OF_CONDUCT.md). No really,
you should.
## Before making a change
Before making a change, consider your motivation for making the change.
Documentation updates, bug fixes and the like are *always* welcome.
When adding a feature you should consider whether it is only useful for your
particular use-case or whether it is generally applicable for other users of the
project.
When in doubt - just ask! You can reach out to us at
[depot@tazj.in](mailto:depot@tazj.in) or on Twitter, IRC, etc.
## Commit messages
All commit messages should be structured like this:
```
type(scope): Subject line with at most a 68 character length
Body of the commit message with an empty line between subject and
body. This text should explain what the change does and why it has
been made, *especially* if it introduces a new feature.
Relevant issues should be mentioned if they exist.
```
Where `type` can be one of:
* `feat`: A new feature has been introduced
* `fix`: An issue of some kind has been fixed
* `docs`: Documentation or comments have been updated
* `style`: Formatting changes only
* `refactor`: Hopefully self-explanatory!
* `test`: Added missing tests / fixed tests
* `chore`: Maintenance work
And `scope` should refer to some kind of logical grouping inside of the project.
It does not make sense to include the full path unless it aids in
disambiguating. For example, when changing the configuration of the host
`camden` at `//ops/nixos/camden` it is enough to write `feat(camden): ...`.
Please take a look at the existing commit log for examples.
## Commit content
Multiple changes should be divided into multiple git commits whenever possible.
Common sense applies.
The fix for a single-line whitespace issue is fine to include in a different
commit. Introducing a new feature and refactoring (unrelated) code in the same
commit is not fine.
`git commit -a` is generally **taboo**.
In my experience making "sane" commits becomes *significantly* easier as
developer tooling is improved. The interface to `git` that I recommend is
[magit][]. Even if you are not yet an Emacs user, it makes sense to install
Emacs just to be able to use magit - it is really that good.
For staging sane chunks on the command line with only git, consider `git add
-p`.
## Code quality
This one should go without saying - but please ensure that your code quality
does not fall below the rest of the project. This is of course very subjective,
but as an example if you place code that throws away errors into a block in
which errors are handled properly your change will be rejected.
In my experience there is a strong correlation between the visual appearance of
a code block and its quality. This is a simple way to sanity-check your work
while squinting and keeping some distance from your screen ;-)
## Builds & tests
All projects are built using [Nix][] to avoid "build pollution" via the user's
environment.
If you have Nix installed and are contributing to a project tracked in this
repository, you can usually build the project by calling `nix-build -A
path.to.project`.
For example, to build a project located at `//tools/foo` you would call
`nix-build -A tools.foo`
If the project has tests, check that they still work before submitting your
change.
## Submitting changes
The code review & change submission process is described in the [code
review][] documentation.
[magit]: https://magit.vc/
[Nix]: https://nixos.org/nix/
[code review]: ./REVIEWS.md

153
third_party/tvl/docs/REVIEWS.md vendored Normal file
View file

@ -0,0 +1,153 @@
TVL Code Reviews
================
<!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc-refresh-toc -->
**Table of Contents**
- [TVL Code Reviews](#tvl-code-reviews)
- [Gerrit setup](#gerrit-setup)
- [Gerrit workflows](#gerrit-workflows)
- [Review process & approvals](#review-process--approvals)
- [Registration](#registration)
- [Submitting changes via email](#submitting-changes-via-email)
<!-- markdown-toc end -->
This document describes the TVL code review process & tooling. If you are
looking for general contribution guidelines, please look at the [general
contribution guidelines](./CONTRIBUTING.md).
All changes are tracked at [cl.tvl.fyi](https://cl.tvl.fyi) using Gerrit. See
[Registration](#registration) for information on how to register an account.
## Gerrit setup
Gerrit uses the concept of change IDs to track commits across rebases and other
operations that might change their hashes, and link them to unique changes in
Gerrit.
First, [tell Gerrit][Gerrit SSH] about your SSH keys.
Then, to make using Gerrit smooth for users, the repository should be cloned and
a commit hook should be installed as follows:
```
git clone "ssh://$USER@code.tvl.fyi:29418/depot"
scp -p -P 29418 $USER@code.tvl.fyi:hooks/commit-msg "depot/.git/hooks/"
```
If you have a previous clone of the depot via HTTP you can use `git remote
set-url` to update the origin URL and install the hook in the same way as above.
## Gerrit workflows
The developer workflow on Gerrit is quite different from what GitHub-users are
used to.
The depot does not have branches (other than Gerrit's internal metadata refs)
and all development happens at `HEAD`.
Every time you create a new commit the change hook will insert a unique
`Change-Id` tag into the commit message. Once you are satisfied with the state
of your commit and want to submit it for review, you push it to a git ref called
`refs/for/canon`. This designates the commits as changelists (CLs) targeted for
the `canon` branch.
Sending a change for review is done by pushing to a special target. You can set
this to be the default push target through your git configuration:
```
git config remote.origin.url "ssh://$USER@code.tvl.fyi:29418/depot"
git config remote.origin.push HEAD:refs/for/canon
```
Then, after making your change, push to the default, or to a special target:
```
Example:
git commit -m 'docs(REVIEWS): Fixed all the errors in the reviews docs'
git push origin
# Uploading a work-in-progress CL:
git push origin HEAD:refs/for/canon%wip
```
TIP: Every individual commit will become a separate change. We do not merge
related commits, but instead submit them one by one. Be aware that if you are
expecting a different behaviour and attempt something like an unsquashed subtree
merge, you will produce a *lot* of CLs. This is strongly discouraged.
During your review, the reviewer(s) might ask you to make changes. You can
simply amend your commit(s) and push to the same ref. Gerrit will automatically
update your changes.
Read more about the Gerrit workflow in the [Gerrit walkthrough][].
## Review process & approvals
Each user has the ability to create their own users directory in
`//users/<username>` in which they can submit code without review from other
contributors (they will still need to +2 their own changes, and the initial
check-in of the `OWNERS` file needs to be reviewed).
You can set a directory like this up for yourself by proposing a change similar
to [CL/246](https://cl.tvl.fyi/c/depot/+/246).
For all paths outside of `//users`, code review is required. We have no strict
guidelines about the review process itself, as we're not a megacorp, but we have
formalised checks before submitting:
* At least one person who is [an owner][OWNERS] of the codepath must have given
a +2 review
* The commit message must conform to our [guidelines][]
* No code review comments must be left unresolved
If all these conditions are fulfilled, the **change author submits their change
themselves**.
## Registration
If you would like to have an account on the Gerrit instance, follow these
instructions:
1. Be a member of `##tvl`.
2. Clone the depot locally (via `git clone "https://cl.tvl.fyi/depot"`).
3. Create a user entry in our LDAP server in [tvl-slapd/default.nix][tvl-slapd].
We recommend using ARGON2 password hashes, which can be created
with the `slappasswd` tool if OpenLDAP was compiled with ARGON2
support.
For convenience, we provide a wrapper script for this that you can
build with `nix-build -A tools.hash-password` in a depot checkout.
Alternatively, if you have `direnv` installed, you can add the
depot to your allowlist and just run `hash-password` which should
be added to your `$PATH` by `direnv`.
You can probably create ARGON2 hashes with other tools, but that is
your job to figure out.
4. Create a commit adding yourself (see e.g.
[CL/223](https://cl.tvl.fyi/c/depot/+/223)).
5. Submit the commit via email (see below).
## Submitting changes via email
You can submit a patch via email to `depot@tazj.in` and it will be added to
Gerrit by a contributor.
Create an appropriate commit locally and send it us using either of these options:
* `git format-patch`: This will create a `.patch` file which you should email to
us.
* `git send-email`: If configured on your system, this will take care of the
whole emailing process for you.
The email address is a [public group][].
[Gerrit SSH]: https://cl.tvl.fyi/settings/#SSHKeys
[Gerrit walkthrough]: https://gerrit-review.googlesource.com/Documentation/intro-gerrit-walkthrough.html
[OWNERS]: https://cl.tvl.fyi/plugins/owners/Documentation/config.md
[guidelines]: ./CONTRIBUTING.md#commit-messages
[tvl-slapd]: ../ops/nixos/tvl-slapd/default.nix
[public group]: https://groups.google.com/a/tazj.in/forum/?hl=en#!forum/depot

View file

@ -0,0 +1,37 @@
Below is a prototype for a script to create Git sparse checkouts of the depot.
The script below works today with relatively recent versions of git.
Open items:
- Read-increment-write the checkout ID from a file in .git.
- `NICE_CHECKOUT_ROOT` should be a git configuration value.
- `tvl-get-depends` will be a script that contacts the build farm and asks for
the closure of a given source directory, using [depot-scan].
```bash
DEPOT_ROOT="${depot.depotPath}"
XDG_DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}"
CLIENT_ROOT="$XDG_DATA_HOME/tvlc/clients"
NICE_CHECKOUT_ROOT="$HOME/tvlc"
CHECKOUT_ID=1
CHECKOUT_NAME=myclient # command line variables
assertAbsolutePath "$CLIENT_ROOT"
mkdir "$CLIENT_ROOT"/"$CHECKOUT_ID"
ln -s "$CLIENT_ROOT"/"$CHECKOUT_ID" "$NICE_CHECKOUT_ROOT"/"$CHECKOUT_NAME"
cd "$DEPOT_ROOT"
git worktree add --no-checkout -b "tvlc-$CHECKOUT_ID" "$CLIENT_ROOT/$CHECKOUT_ID/" canon
# BUG: git not creating the /info/ subdir
mkdir "$DEPOT_ROOT"/.git/worktrees/"$CHECKOUT_ID"/info
cd "$CLIENT_ROOT/$CHECKOUT_ID"
git sparse-checkout init --cone
git sparse-checkout set "$TARGET_DIR" nix/readTree overrides
tvl-get-depends "$TARGET_DIR" | xargs git sparse-checkout add
cd "$NICE_CHECKOUT_ROOT"/"$CHECKOUT_NAME"
```
[depot-scan]: ../users/edef/depot-scan.nix

View file

@ -0,0 +1,13 @@
{ depot, ... }:
depot.nix.buildGo.program {
name = "amsterdump";
srcs = [
./main.go
];
deps = with depot.third_party; [
# gopkgs."golang.org".x.oauth2.google
gopkgs."googlemaps.github.io".maps
];
}

File diff suppressed because it is too large Load diff

108
third_party/tvl/fun/amsterdump/main.go vendored Normal file
View file

@ -0,0 +1,108 @@
// Amsterdump is a small program that populates a BigQuery table with
// a matrix of origin points scattered around Amsterdam and each
// respective points travel time to a given destination.
//
// The two destinations used here are the Schiphol Airport and
// Amsterdam Central station.
//
// To accomplish this the Google Maps Distance Matrix API [1] is
// queried with the points. A visualisation is later done using
// BigQuery GeoViz[2].
//
// [1]: https://developers.google.com/maps/documentation/distance-matrix/start#quotas
// [2]: https://bigquerygeoviz.appspot.com/
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"googlemaps.github.io/maps"
)
func failOn(err error, msg string) {
if err != nil {
log.Fatalln(msg, err)
}
}
type LocationResult struct {
Address string `json:"address"`
URL string `json:"url"`
Schiphol *maps.DistanceMatrixElement `json:"schiphol"`
Centraal *maps.DistanceMatrixElement `json:"centraal"`
}
type Listing struct {
URL string `json:"url"`
Address string `json:"address"`
}
func requestMatrix(ctx context.Context, client *maps.Client, listings []Listing) {
origins := make([]string, len(listings))
for i, l := range listings {
origins[i] = l.Address
}
request := &maps.DistanceMatrixRequest{
Mode: maps.TravelModeTransit,
Units: maps.UnitsMetric,
Origins: origins,
Destinations: []string{
"Schiphol Airport",
"Amsterdam Centraal",
},
}
response, err := client.DistanceMatrix(ctx, request)
failOn(err, "could not retrieve distance matrix:")
for idx, addr := range response.OriginAddresses {
result := LocationResult{
Address: addr,
URL: listings[idx].URL,
Schiphol: response.Rows[idx].Elements[0],
Centraal: response.Rows[idx].Elements[1],
}
j, _ := json.Marshal(result)
fmt.Println(string(j))
}
}
func main() {
var listings []Listing
input, err := ioutil.ReadFile("fun/amsterdump/input.json")
failOn(err, "could not read input file:")
err = json.Unmarshal(input, &listings)
failOn(err, "could not deserialise listings:")
ctx := context.Background()
apiKey := os.Getenv("MAPS_API_KEY")
if apiKey == "" {
log.Fatalln("API key must be supplied via MAPS_API_KEY")
}
client, err := maps.NewClient(maps.WithAPIKey(apiKey))
failOn(err, "could not create Google Maps API client:")
var chunk []Listing
for _, l := range listings {
if len(chunk) == 25 {
requestMatrix(ctx, client, chunk)
chunk = []Listing{}
} else {
chunk = append(chunk, l)
}
}
if len(chunk) > 1 {
requestMatrix(ctx, client, chunk)
}
}

View file

@ -0,0 +1,25 @@
;; Scraping funda.nl (this file is just notes and snippets, not full code)
;;
;; Begin by copying whole page into buffer (out of inspect element
;; because encoding is difficult)
(beginning-of-buffer)
;; zap everything that isn't a relevant result
(keep-lines "data-object-url-tracking\\|img alt")
;; mark all spans, move them to the end of the buffer
(cl-letf (((symbol-function 'read-regexp)
(lambda (&rest _) "</span>")))
(mc/mark-all-in-region-regexp (point-min) (point-max)))
;; mark all images lines (these contain street addresses for things
;; with images), clear up and join with previous
;;
;; mark all: data-image-error-fallback
;; delete all lines that don't either contain a span or an img tag
;; (there are duplicates)
(keep-lines "span class\\|img alt")
;; do some manual cleanup from the hrefs and done

22
third_party/tvl/fun/aoc2019/default.nix vendored Normal file
View file

@ -0,0 +1,22 @@
# Solutions for Advent of Code 2019, written in Emacs Lisp.
#
# For each day a new file is created as "solution-day$n.el".
{ depot, ... }:
let
inherit (builtins) attrNames filter head listToAttrs match readDir;
dir = readDir ./.;
matchSolution = match "solution-(.*)\.el";
isSolution = f: (matchSolution f) != null;
getDay = f: head (matchSolution f);
solutionFiles = filter (e: dir."${e}" == "regular" && isSolution e) (attrNames dir);
solutions = map (f: let day = getDay f; in {
name = day;
value = depot.writeElispBin { # TODO(tazjin): move writeElispBin to depot.nix
name = "aoc2019";
deps = p: with p; [ dash s ht ];
src = ./. + ("/" + f);
};
}) solutionFiles;
in listToAttrs solutions

View file

@ -0,0 +1,28 @@
;; Advent of Code 2019 - Day 1
(require 'dash)
;; Puzzle 1:
(defvar day-1/input
'(83285 96868 121640 51455 128067 128390 141809 52325 68310 140707 124520 149678
87961 52040 133133 52203 117483 85643 84414 86558 65402 122692 88565 61895
126271 128802 140363 109764 53600 114391 98973 124467 99574 69140 144856
56809 149944 138738 128823 82776 77557 51994 74322 64716 114506 124074
73096 97066 96731 149307 135626 121413 69575 98581 50570 60754 94843 72165
146504 53290 63491 50936 79644 119081 70218 85849 133228 114550 131943
67288 68499 80512 148872 99264 119723 68295 90348 146534 52661 99146 95993
130363 78956 126736 82065 77227 129950 97946 132345 107137 79623 148477
88928 118911 75277 97162 80664 149742 88983 74518))
(defun calculate-fuel (mass)
(- (/ mass 3) 2))
(message "Solution to day1/1: %d" (apply #'+ (-map #'calculate-fuel day-1/input)))
;; Puzzle 2:
(defun calculate-recursive-fuel (mass)
(let ((fuel (calculate-fuel mass)))
(if (< fuel 0) 0
(+ fuel (calculate-recursive-fuel fuel)))))
(message "Solution to day1/2: %d" (apply #'+ (-map #'calculate-recursive-fuel day-1/input)))

View file

@ -0,0 +1,53 @@
;; -*- lexical-binding: t; -*-
;; Advent of Code 2019 - Day 2
(require 'dash)
(require 'ht)
(defvar day2/input
[1 0 0 3 1 1 2 3 1 3 4 3 1 5 0 3 2 1 9 19 1 19 5 23 1 13 23 27 1 27 6 31
2 31 6 35 2 6 35 39 1 39 5 43 1 13 43 47 1 6 47 51 2 13 51 55 1 10 55
59 1 59 5 63 1 10 63 67 1 67 5 71 1 71 10 75 1 9 75 79 2 13 79 83 1 9
83 87 2 87 13 91 1 10 91 95 1 95 9 99 1 13 99 103 2 103 13 107 1 107 10
111 2 10 111 115 1 115 9 119 2 119 6 123 1 5 123 127 1 5 127 131 1 10
131 135 1 135 6 139 1 10 139 143 1 143 6 147 2 147 13 151 1 5 151 155 1
155 5 159 1 159 2 163 1 163 9 0 99 2 14 0 0])
;; Puzzle 1
(defun day2/single-op (f state idx)
(let* ((a (aref state (aref state (+ 1 idx))))
(b (aref state (aref state (+ 2 idx))))
(p (aref state (+ 3 idx)))
(result (funcall f a b)))
(aset state p (funcall f a b))))
(defun day2/operate (state idx)
(pcase (aref state idx)
(99 (aref state 0))
(1 (day2/single-op #'+ state idx)
(day2/operate state (+ 4 idx)))
(2 (day2/single-op #'* state idx)
(day2/operate state (+ 4 idx)))
(other (error "Unknown opcode: %s" other))))
(defun day2/program-with-inputs (noun verb)
(let* ((input (copy-tree day2/input t)))
(aset input 1 noun)
(aset input 2 verb)
(day2/operate input 0)))
(message "Solution to day2/1: %s" (day2/program-with-inputs 12 2))
;; Puzzle 2
(let* ((used (ht))
(noun 0)
(verb 0)
(result (day2/program-with-inputs noun verb)))
(while (/= 19690720 result)
(setq noun (random 100))
(setq verb (random 100))
(unless (ht-get used (format "%d%d" noun verb))
(ht-set used (format "%d%d" noun verb) t)
(setq result (day2/program-with-inputs noun verb))))
(message "Solution to day2/2: %s%s" noun verb))

View file

@ -0,0 +1,64 @@
;; -*- lexical-binding: t; -*-
;; Advent of Code 2019 - Day 3
(require 'cl-lib)
(require 'dash)
(require 'ht)
(require 's)
(defvar day3/input/wire1
"R1010,D422,L354,U494,L686,U894,R212,U777,L216,U9,L374,U77,R947,U385,L170,U916,R492,D553,L992,D890,L531,U360,R128,U653,L362,U522,R817,U198,L126,D629,L569,U300,L241,U145,R889,D196,L450,D576,L319,D147,R985,U889,L941,U837,L608,D77,L864,U911,L270,D869,R771,U132,L249,U603,L36,D328,L597,U992,L733,D370,L947,D595,L308,U536,L145,U318,R55,D773,R175,D505,R483,D13,R780,U778,R445,D107,R490,U245,L587,U502,R446,U639,R150,U35,L455,D522,R866,U858,R394,D975,R513,D378,R58,D646,L374,D675,R209,U228,R530,U543,L480,U677,L912,D164,L573,U587,L784,D626,L994,U250,L215,U985,R684,D79,L877,U811,L766,U617,L665,D246,L408,U800,L360,D272,L436,U138,R240,U735,L681,U68,L608,D59,R532,D808,L104,U968,R887,U819,R346,U698,L317,U582,R516,U55,L303,U607,L457,U479,L510,D366,L583,U519,R878,D195,R970,D267,R842,U784,R9,D946,R833,D238,L232,D94,L860,D47,L346,U951,R491,D745,R849,U273,R263,U392,L341,D808,R696,U326,R886,D296,L865,U833,R241,U644,R729,D216,R661,D712,L466,D699,L738,U5,L556,D693,R912,D13,R48,U63,L877,U628,L689,D929,R74,U924,R612,U153,R417,U425,L879,D378,R79,D248,L3,U519,R366,U281,R439,D823,R149,D668,R326,D342,L213,D735,R504,U265,L718,D842,L565,U105,L214,U963,R518,D681,R642,U170,L111,U6,R697,U572,R18,U331,L618,D255,R534,D322,L399,U595,L246,U651,L836,U757,R417,D795,R291,U759,L568,U965,R828,D570,R350,U317,R338,D173,L74,D833,L650,D844,L70,U913,R594,U407,R674,D684,L481,D564,L128,D277,R851,D274,L435,D582,R469,U729,R387,D818,R443,U504,R414,U8,L842,U845,R275,U986,R53,U660,R661,D225,R614,U159,R477")
(defvar day3/input/wire2
"L1010,D698,R442,U660,L719,U702,L456,D86,R938,D177,L835,D639,R166,D285,L694,U468,L569,D104,L234,D574,L669,U299,L124,D275,L179,D519,R617,U72,L985,D248,R257,D276,L759,D834,R490,U864,L406,U181,R911,U873,R261,D864,R260,U759,R648,U158,R308,D386,L835,D27,L745,U91,R840,U707,R275,U543,L663,U736,L617,D699,R924,U103,R225,U455,R708,U319,R569,U38,R315,D432,L179,D975,R519,D546,L295,U680,L685,U603,R262,D250,R7,U171,R261,U519,L832,U534,L471,U431,L474,U886,R10,D179,L79,D555,R452,U452,L832,U863,L367,U538,L237,D160,R441,U605,R942,U259,L811,D552,R646,D353,L225,D94,L35,D307,R752,U23,R698,U610,L379,D932,R698,D751,R178,D347,R325,D156,R471,D555,R558,D593,R773,U2,L955,U764,L735,U438,R364,D640,L757,U534,R919,U409,R361,U407,R336,D808,R877,D648,R610,U198,R340,U94,R795,D667,R811,U975,L965,D224,R565,D681,L64,U567,R621,U922,L665,U329,R242,U592,L727,D481,L339,U402,R213,D280,R656,U169,R976,D962,L294,D505,L251,D689,L497,U133,R230,D441,L90,D220,L896,D657,L500,U331,R502,U723,R762,D613,L447,D256,L226,U309,L935,U384,L740,D459,R309,D707,R952,D747,L304,D105,R977,D539,R941,D21,R291,U216,R132,D543,R515,U453,L854,D42,R982,U102,L469,D639,R559,D68,R302,U734,R980,D214,R107,D191,L730,D793,L63,U17,R807,U196,R412,D592,R330,D941,L87,D291,L44,D94,L272,D780,R968,U837,L712,D704,R163,U981,R537,U778,R220,D303,L196,D951,R163,D446,R11,D623,L72,D778,L158,U660,L189,D510,L247,D716,L89,U887,L115,U114,L36,U81,R927,U293,L265,U183,R331,D267,R745,D298,L561,D918,R299,U810,L322,U679,L739,D854,L581,U34,L862,D779,R23")
;; Puzzle 1
(defun wire-from (raw)
(-map (lambda (s)
(cons (substring s 0 1) (string-to-number (substring s 1))))
(s-split "," raw)))
(defun day3/move (x y next)
(cl-flet ((steps (by op)
(-map op (reverse (number-sequence 1 by)))))
(pcase next
(`("L" . ,by) (steps by (lambda (n) (cons (- x n) y))))
(`("R" . ,by) (steps by (lambda (n) (cons (+ x n) y))))
(`("U" . ,by) (steps by (lambda (n) (cons x (+ y n)))))
(`("D" . ,by) (steps by (lambda (n) (cons x (- y n))))))))
(defun day3/wire-points (wire)
(let ((points (ht))
(point-list (-reduce-from
(lambda (acc point)
(-let* (((x . y) (car acc))
(next (day3/move x y point)))
(-concat next acc)))
'((0 . 0)) wire)))
(-map (-lambda ((s . p)) (ht-set! points p s))
(-zip (reverse (number-sequence 0 (- (length point-list) 1))) point-list))
(ht-remove! points '(0 . 0))
points))
(defun day3/closest-intersection (crossed-points)
(car (-sort #'<
(-map (-lambda ((x . y))
(+ (abs x) (abs y)))
crossed-points))))
(defun day3/minimum-steps (wire1 wire2 crossed)
(car (-sort #'<
(-map (-lambda (p)
(+ (ht-get wire1 p) (ht-get wire2 p)))
crossed))))
;; Example:
(let* ((wire1-points (day3/wire-points (wire-from day3/input/wire1)))
(wire2-points (day3/wire-points (wire-from day3/input/wire2)))
(crossed-points (-filter (lambda (p) (ht-contains? wire1-points p))
(ht-keys wire2-points))))
(message "Solution for day3/1: %d" (day3/closest-intersection crossed-points))
(message "Solution for day3/2: %d" (day3/minimum-steps wire1-points
wire2-points
crossed-points)))

View file

@ -0,0 +1,73 @@
;; -*- lexical-binding: t; -*-
;; Advent of Code 2019 - Day 4
(require 'cl-lib)
(require 'dash)
;; Puzzle 1
(defun day4/to-digits (num)
"Convert NUM to a list of its digits."
(cl-labels ((steps (n digits)
(if (= n 0) digits
(steps (/ n 10) (cons (% n 10) digits)))))
(steps num '())))
(defvar day4/input (-map #'day4/to-digits (number-sequence 128392 643281)))
(defun day4/filter-password (digits)
"Determines whether the given rules match the supplied
number."
(and
;; It is a six digit number
(= 6 (length digits))
;; Value is within the range given in puzzle input
;; (noop because the range is generated from the input)
;; Two adjacent digits are the same (like 22 in 122345).
(car (-reduce-from (-lambda ((acc . prev) next)
(cons (or acc (= prev next)) next))
'(nil . 0) digits))
;; Going from left to right, the digits never decrease; they only
;; ever increase or stay the same (like 111123 or 135679).
(car (-reduce-from (-lambda ((acc . prev) next)
(cons (and acc (>= next prev)) next))
'(t . 0) digits))))
;; Puzzle 2
;;
;; Additional criteria: If there's matching digits, they're not in a group.
(cl-defstruct day4/acc state prev count)
(defun day4/filter-longer-groups (digits)
(let ((res (-reduce-from
(lambda (acc next)
(cond ;; sequence is broken and count was at 1 ->
;; match!
((and (= (day4/acc-count acc) 2)
(/= (day4/acc-prev acc) next))
(setf (day4/acc-state acc) t))
;; sequence continues, counter increment!
((= (day4/acc-prev acc) next)
(setf (day4/acc-count acc) (+ 1 (day4/acc-count acc))))
;; sequence broken, reset counter
((/= (day4/acc-prev acc) next)
(setf (day4/acc-count acc) 1)))
(setf (day4/acc-prev acc) next)
acc)
(make-day4/acc :prev 0 :count 0) digits)))
(or (day4/acc-state res)
(= 2 (day4/acc-count res)))))
(let* ((simple (-filter #'day4/filter-password day4/input))
(complex (-filter #'day4/filter-longer-groups simple)))
(message "Solution to day4/1: %d" (length simple))
(message "Solution to day4/2: %d" (length complex)))

View file

@ -0,0 +1,43 @@
// Package backoffutil provides useful utilities for backoff.
package backoffutil
import (
"time"
backoff "github.com/cenkalti/backoff/v4"
)
// ZeroStartingBackOff is a backoff.BackOff that returns "0" as the first Duration after a reset.
// This is useful for constructing loops and just enforcing a backoff duration on every loop, rather than incorporating this logic into the loop directly.
type ZeroStartingBackOff struct {
bo backoff.BackOff
initial bool
}
// NewZeroStartingBackOff creates a new ZeroStartingBackOff.
func NewZeroStartingBackOff(bo backoff.BackOff) *ZeroStartingBackOff {
return &ZeroStartingBackOff{bo: bo, initial: true}
}
// NewDefaultBackOff creates a sensibly configured BackOff that starts at zero.
func NewDefaultBackOff() backoff.BackOff {
ebo := backoff.NewExponentialBackOff()
ebo.MaxElapsedTime = 0
return NewZeroStartingBackOff(ebo)
}
// NextBackOff returns the next back off duration to use.
// For the first call after a call to Reset(), this is 0. For each subsequent duration, the underlying BackOff is consulted.
func (bo *ZeroStartingBackOff) NextBackOff() time.Duration {
if bo.initial == true {
bo.initial = false
return 0
}
return bo.bo.NextBackOff()
}
// Reset resets to the initial state, and also passes a Reset through to the underlying BackOff.
func (bo *ZeroStartingBackOff) Reset() {
bo.initial = true
bo.bo.Reset()
}

View file

@ -0,0 +1,14 @@
{ depot, ... }:
let
inherit (depot.third_party) gopkgs;
in
depot.nix.buildGo.package {
name = "code.tvl.fyi/fun/clbot/backoffutil";
srcs = [
./backoffutil.go
];
deps = [
gopkgs."github.com".cenkalti.backoff.gopkg
];
}

252
third_party/tvl/fun/clbot/clbot.go vendored Normal file
View file

@ -0,0 +1,252 @@
package main
import (
"context"
"crypto/tls"
"flag"
"fmt"
"io/ioutil"
"os"
"os/signal"
"strings"
"time"
"code.tvl.fyi/fun/clbot/backoffutil"
"code.tvl.fyi/fun/clbot/gerrit"
"code.tvl.fyi/fun/clbot/gerrit/gerritevents"
log "github.com/golang/glog"
"golang.org/x/crypto/ssh"
"gopkg.in/irc.v3"
)
var (
gerritAddr = flag.String("gerrit_host", "cl.tvl.fyi:29418", "Gerrit SSH host:port")
gerritSSHHostKey = flag.String("gerrit_ssh_pubkey", "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBIUNYBYPCCBNDFSd0BuCR+8kgeuJ7IA5S2nTNQmkQUYNyXK+ot5os7rHtCk96+grd5+J8jFCuFBWisUe8h8NC0Q=", "Gerrit SSH public key")
gerritSSHTimeout = flag.Duration("gerrit_tcp_timeout", 5*time.Second, "Gerrit SSH TCP connect timeout")
gerritAuthUsername = flag.String("gerrit_ssh_auth_username", "", "Gerrit SSH username")
gerritAuthKeyPath = flag.String("gerrit_ssh_auth_key", "", "Gerrit SSH private key path")
ircServer = flag.String("irc_server", "chat.freenode.net:7000", "IRC server to connect to")
ircNick = flag.String("irc_nick", "clbot", "Nick to use when connecting to IRC")
ircUser = flag.String("irc_user", "clbot", "User string to use for IRC")
ircName = flag.String("irc_name", "clbot", "Name string to use for IRC")
ircChannel = flag.String("irc_channel", "##tvl", "Channel to send messages to")
ircPassword = flag.String("irc_pass", "", "Password to use for IRC")
ircSendLimit = flag.Duration("irc_send_limit", 100*time.Millisecond, "Delay between messages")
ircSendBurst = flag.Int("irc_send_burst", 10, "Number of messages which can be sent in a burst")
notifyRepo = flag.String("notify_repo", "depot", "Repo name to notify about")
notifyBranches = stringSetFlag{}
)
func init() {
flag.Var(&notifyBranches, "notify_branches", "Branch names (comma-separated, or repeated flags, or both) to notify users about")
}
type stringSetFlag map[string]bool
func (f stringSetFlag) String() string {
return fmt.Sprintf("%q", map[string]bool(f))
}
func (f stringSetFlag) Set(s string) error {
if s == "" {
return nil
}
for _, k := range strings.Split(s, ",") {
if k != "" {
f[k] = true
}
}
return nil
}
func mustFixedHostKey(f string) ssh.HostKeyCallback {
pk, _, _, _, err := ssh.ParseAuthorizedKey([]byte(f))
if err != nil {
log.Exitf("ParseAuthorizedKey(%q): %v", f, err)
}
return ssh.FixedHostKey(pk)
}
func mustPrivateKey(p string) ssh.AuthMethod {
pkBytes, err := ioutil.ReadFile(p)
if err != nil {
log.Exitf("reading SSH private key from %q: %v", p, err)
}
pk, err := ssh.ParsePrivateKey(pkBytes)
if err != nil {
log.Exitf("parsing private key from %q: %v", p, err)
}
return ssh.PublicKeys(pk)
}
var shutdownFuncs []func()
func callOnShutdown(f func()) {
shutdownFuncs = append(shutdownFuncs, f)
}
// Unicode U+200B zero-width-space, to avoid triggering other bots
// or highlighting people on IRC.
const zeroWidthSpace = "\u200b"
func runIRC(ctx context.Context, ircCfg irc.ClientConfig, sendMsg <-chan string) {
bo := backoffutil.NewDefaultBackOff()
ircCfg.Handler = irc.HandlerFunc(func(c *irc.Client, m *irc.Message) {
if m.Command == "NOTICE" && m.Prefix.Name == "NickServ" && strings.Contains(m.Trailing(), "dentified") {
// We're probably identified now, go join the channel.
c.Writef("JOIN %s", *ircChannel)
}
})
for {
timer := time.NewTimer(bo.NextBackOff())
select {
case <-ctx.Done():
timer.Stop()
return
case <-timer.C:
break
}
(func() {
connectedStart := time.Now()
ircConn, err := tls.Dial("tcp", *ircServer, nil)
if err != nil {
log.Errorf("connecting to IRC at tcp/%s: %v", *ircServer, err)
return
}
ircClient := irc.NewClient(ircConn, ircCfg)
ircClientCtx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
for {
select {
case <-ircClientCtx.Done():
return
case msg := <-sendMsg:
log.Infof("sending message %q to %v", msg, *ircChannel)
ircClient.Writef("PRIVMSG %s :%s%s", *ircChannel, zeroWidthSpace, msg)
}
}
}()
log.Infof("connecting to IRC on tcp/%s", *ircServer)
if err := ircClient.RunContext(ircClientCtx); err != nil {
connectedEnd := time.Now()
connectedFor := connectedEnd.Sub(connectedStart)
if connectedFor > 60*time.Second {
bo.Reset()
}
log.Errorf("IRC RunContext: %v", err)
return
}
})()
}
}
func username(p gerritevents.PatchSet) string {
options := []string{
p.Uploader.Username,
p.Uploader.Name,
p.Uploader.Email,
}
for _, opt := range options {
if opt != "" {
return opt
}
}
return "UNKNOWN USER"
}
// noping inserts a Unicode zero-width space between the first and rest characters of `user`
// in an effort to avoid pinging that user on IRC.
func noping(user string) string {
un := []rune(user)
return string(un[0:1]) + zeroWidthSpace + string(un[1:])
}
func patchSetURL(c gerritevents.Change, p gerritevents.PatchSet) string {
return fmt.Sprintf("https://cl.tvl.fyi/%d", c.Number)
}
func main() {
flag.Parse()
failed := false
if *gerritAuthUsername == "" {
log.Errorf("gerrit_ssh_auth_username must be set")
failed = true
}
if *gerritAuthKeyPath == "" {
log.Errorf("gerrit_ssh_auth_key must be set")
failed = true
}
if failed {
os.Exit(2)
}
shutdownCh := make(chan os.Signal)
signal.Notify(shutdownCh, os.Interrupt)
go func() {
<-shutdownCh
signal.Reset(os.Interrupt)
for n := len(shutdownFuncs) - 1; n >= 0; n-- {
shutdownFuncs[n]()
}
}()
ctx, cancel := context.WithCancel(context.Background())
callOnShutdown(cancel)
cfg := &ssh.ClientConfig{
User: *gerritAuthUsername,
Auth: []ssh.AuthMethod{mustPrivateKey(*gerritAuthKeyPath)},
HostKeyCallback: mustFixedHostKey(*gerritSSHHostKey),
Timeout: *gerritSSHTimeout,
}
cfg.SetDefaults()
gw, err := gerrit.New(ctx, "tcp", *gerritAddr, cfg)
if err != nil {
log.Exitf("gerrit.New(%q): %v", *gerritAddr, err)
}
callOnShutdown(func() {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
gw.Close(ctx)
})
sendMsgChan := make(chan string, 5)
go func() {
for e := range gw.Events() {
var parsedMsg string
switch e := e.(type) {
case *gerritevents.PatchSetCreated:
if e.Change.Project != *notifyRepo || !notifyBranches[e.Change.Branch] || e.PatchSet.Number != 1 {
continue
}
parsedMsg = fmt.Sprintf("CL/%d: %q proposed by %s - %s", e.Change.Number, e.Change.Subject, noping(username(e.PatchSet)), patchSetURL(e.Change, e.PatchSet))
case *gerritevents.ChangeMerged:
if e.Change.Project != *notifyRepo || !notifyBranches[e.Change.Branch] {
continue
}
parsedMsg = fmt.Sprintf("CL/%d: %q applied by %s - %s", e.Change.Number, e.Change.Subject, noping(username(e.PatchSet)), patchSetURL(e.Change, e.PatchSet))
}
if parsedMsg != "" {
sendMsgChan <- parsedMsg
}
}
}()
ircCtx, ircCancel := context.WithCancel(ctx)
callOnShutdown(ircCancel)
go runIRC(ircCtx, irc.ClientConfig{
Nick: *ircNick,
User: *ircUser,
Name: *ircName,
Pass: *ircPassword,
SendLimit: *ircSendLimit,
SendBurst: *ircSendBurst,
}, sendMsgChan)
<-ctx.Done()
}

19
third_party/tvl/fun/clbot/default.nix vendored Normal file
View file

@ -0,0 +1,19 @@
{ depot, ... }@args:
let
clbot = depot.fun.clbot;
gopkgs = depot.third_party.gopkgs;
in
depot.nix.buildGo.program {
name = "clbot";
srcs = [
./clbot.go
];
deps = [
clbot.gerrit
gopkgs."github.com".davecgh.go-spew.spew.gopkg
gopkgs."github.com".golang.glog.gopkg
gopkgs."golang.org".x.crypto.ssh.gopkg
gopkgs."gopkg.in"."irc.v3".gopkg
];
}

View file

@ -0,0 +1,18 @@
{ depot, ... }:
let
inherit (depot.fun) clbot;
inherit (depot.third_party) gopkgs;
in
depot.nix.buildGo.package {
name = "code.tvl.fyi/fun/clbot/gerrit";
srcs = [
./watcher.go
];
deps = [
clbot.gerrit.gerritevents
clbot.backoffutil
gopkgs."github.com".golang.glog.gopkg
gopkgs."golang.org".x.crypto.ssh.gopkg
];
}

View file

@ -0,0 +1,10 @@
{ depot, ... }:
depot.nix.buildGo.package {
name = "code.tvl.fyi/fun/clbot/gerrit/gerritevents";
srcs = [
./time.go
./types.go
./events.go
];
}

View file

@ -0,0 +1,321 @@
package gerritevents
import (
"encoding/json"
"fmt"
)
var events = map[string]func() Event{}
func registerEvent(e func() Event) {
t := e().EventType()
if _, ok := events[t]; ok {
panic(fmt.Sprintf("%s already registered", t))
}
events[t] = e
}
// These events are taken from https://cl.tvl.fyi/Documentation/cmd-stream-events.html.
// Event is implemented by Gerrit event structs.
type Event interface {
EventType() string
}
type simpleEvent struct {
Type string `json:"type"`
}
// Parse parses a Gerrit event from JSON.
func Parse(bs []byte) (Event, error) {
var s simpleEvent
if err := json.Unmarshal(bs, &s); err != nil {
return nil, fmt.Errorf("unmarshalling %q as Gerrit Event: %v", string(bs), err)
}
ef, ok := events[s.Type]
if !ok {
return nil, fmt.Errorf("unknown event type %q", s.Type)
}
e := ef()
if err := json.Unmarshal(bs, e); err != nil {
return nil, fmt.Errorf("unmarshalling %q as Gerrit Event %q: %v", string(bs), e.EventType(), err)
}
return e, nil
}
// AssigneeChanged indicates that a change's assignee has been changed.
type AssigneeChanged struct {
Type string `json:"type"`
Change Change `json:"change"`
Changer Account `json:"changer"`
OldAssignee Account `json:"oldAssignee"`
EventCreatedOn Time `json:"eventCreatedOn"`
}
// EventType implements Event.
func (AssigneeChanged) EventType() string { return "assignee-changed" }
func init() {
registerEvent(func() Event { return &AssigneeChanged{} })
}
// ChangeAbandoned indicates that a change has been abandoned.
type ChangeAbandoned struct {
Type string `json:"type"`
Change Change `json:"change"`
PatchSet PatchSet `json:"patchSet"`
Abandoner Account `json:"abandoner"`
Reason string `json:"reason"`
EventCreatedOn Time `json:"eventCreatedOn"`
}
// EventType implements Event.
func (ChangeAbandoned) EventType() string { return "change-abandoned" }
func init() {
registerEvent(func() Event { return &ChangeAbandoned{} })
}
// ChangeDeleted indicates that a change has been deleted.
type ChangeDeleted struct {
Type string `json:"type"`
Change Change `json:"change"`
Deleter Account `json:"deleter"`
}
// EventType implements Event.
func (ChangeDeleted) EventType() string { return "change-deleted" }
func init() {
registerEvent(func() Event { return &ChangeDeleted{} })
}
// ChangeMerged indicates that a change has been merged into the target branch.
type ChangeMerged struct {
Type string `json:"type"`
Change Change `json:"change"`
PatchSet PatchSet `json:"patchSet"`
Submitter Account `json:"submitter"`
NewRev string `json:"newRev"`
EventCreatedOn Time `json:"eventCreatedOn"`
}
// EventType implements Event.
func (ChangeMerged) EventType() string { return "change-merged" }
func init() {
registerEvent(func() Event { return &ChangeMerged{} })
}
// ChangeRestored indicates a change has been restored (i.e. un-abandoned).
type ChangeRestored struct {
Type string `json:"type"`
Change Change `json:"change"`
PatchSet PatchSet `json:"patchSet"`
Restorer Account `json:"restorer"`
Reason string `json:"reason"`
EventCreatedOn Time `json:"eventCreatedOn"`
}
// EventType implements Event.
func (ChangeRestored) EventType() string { return "change-restored" }
func init() {
registerEvent(func() Event { return &ChangeRestored{} })
}
// CommentAdded indicates someone has commented on a patchset.
type CommentAdded struct {
Type string `json:"type"`
Change Change `json:"change"`
PatchSet PatchSet `json:"patchSet"`
Author Account `json:"author"`
Approvals []Approval `json:"approvals"`
Comment string `json:"comment"`
EventCreatedOn Time `json:"eventCreatedOn"`
}
// EventType implements Event.
func (CommentAdded) EventType() string { return "comment-added" }
func init() {
registerEvent(func() Event { return &CommentAdded{} })
}
// DroppedOutput indicates that some events may be missing from the stream.
type DroppedOutput struct {
Type string `json:"type"`
}
// EventType implements Event.
func (DroppedOutput) EventType() string { return "dropped-output" }
func init() {
registerEvent(func() Event { return &DroppedOutput{} })
}
// HashtagsChanged indicates that someone has added or removed hashtags from a change.
type HashtagsChanged struct {
Type string `json:"type"`
Change Change `json:"change"`
Editor Account `json:"editor"`
Added []string `json:"added"`
Removed []string `json:"removed"`
Hashtags []string `json:"hashtags"`
EventCreatedOn Time `json:"eventCreatedOn"`
}
// EventType implements Event.
func (HashtagsChanged) EventType() string { return "hashtags-changed" }
func init() {
registerEvent(func() Event { return &HashtagsChanged{} })
}
// ProjectCreated indicates that a new project has been created.
type ProjectCreated struct {
Type string `json:"type"`
ProjectName string `json:"projectName"`
ProjectHead string `json:"projectHead"`
EventCreatedOn Time `json:"eventCreatedOn"`
}
// EventType implements Event.
func (ProjectCreated) EventType() string { return "project-created" }
func init() {
registerEvent(func() Event { return &ProjectCreated{} })
}
// PatchSetCreated indicates that a new patchset has been added to a change.
type PatchSetCreated struct {
Type string `json:"type"`
Change Change `json:"change"`
PatchSet PatchSet `json:"patchSet"`
Uploader Account `json:"uploader"`
EventCreatedOn Time `json:"eventCreatedOn"`
}
// EventType implements Event.
func (PatchSetCreated) EventType() string { return "patchset-created" }
func init() {
registerEvent(func() Event { return &PatchSetCreated{} })
}
// RefUpdated indicates that a ref has been updated.
type RefUpdated struct {
Type string `json:"type"`
Submitter Account `json:"submitter"`
RefUpdate RefUpdate `json:"refUpdate"`
EventCreatedOn Time `json:"eventCreatedOn"`
}
// EventType implements Event.
func (RefUpdated) EventType() string { return "ref-updated" }
func init() {
registerEvent(func() Event { return &RefUpdated{} })
}
// ReviewerAdded indicates that a reviewer has been added to a change.
type ReviewerAdded struct {
Type string `json:"type"`
Change Change `json:"change"`
PatchSet PatchSet `json:"patchSet"`
Reviewer Account `json:"reviewer"`
Adder Account `json:"adder"`
EventCreatedOn Time `json:"eventCreatedOn"`
}
// EventType implements Event.
func (ReviewerAdded) EventType() string { return "reviewer-added" }
func init() {
registerEvent(func() Event { return &ReviewerAdded{} })
}
// ReviewerDeleted indicates that a reviewer has been removed from a change, possibly removing one or more approvals.
type ReviewerDeleted struct {
Type string `json:"type"`
Change Change `json:"change"`
PatchSet PatchSet `json:"patchSet"`
Reviewer Account `json:"reviewer"`
Remover Account `json:"remover"`
Approvals []Approval `json:"approvals"`
Comment string `json:"comment"`
EventCreatedOn Time `json:"eventCreatedOn"`
}
// EventType implements Event.
func (ReviewerDeleted) EventType() string { return "reviewer-deleted" }
func init() {
registerEvent(func() Event { return &ReviewerDeleted{} })
}
// TopicChanged indicates that the topic attached to a change has been changed.
type TopicChanged struct {
Type string `json:"type"`
Change Change `json:"change"`
Changer Account `json:"changer"`
OldTopic string `json:"oldTopic"`
EventCreatedOn Time `json:"eventCreatedOn"`
}
// EventType implements Event.
func (TopicChanged) EventType() string { return "topic-changed" }
func init() {
registerEvent(func() Event { return &TopicChanged{} })
}
// WIPStateChanged indicates that the work-in-progress state of a change has changed.
type WIPStateChanged struct {
Type string `json:"type"`
Change Change `json:"change"`
PatchSet PatchSet `json:"patchSet"`
Changer Account `json:"changer"`
EventCreatedOn Time `json:"eventCreatedOn"`
}
// EventType implements Event.
func (WIPStateChanged) EventType() string { return "wip-state-changed" }
func init() {
registerEvent(func() Event { return &WIPStateChanged{} })
}
// PrivateStateChanged indicates that the private state of a change has changed.
type PrivateStateChanged struct {
Type string `json:"type"`
Change Change `json:"change"`
PatchSet PatchSet `json:"patchSet"`
Changer Account `json:"changer"`
EventCreatedOn Time `json:"eventCreatedOn"`
}
// EventType implements Event.
func (PrivateStateChanged) EventType() string { return "private-state-changed" }
func init() {
registerEvent(func() Event { return &PrivateStateChanged{} })
}
// VoteDeleted indicates that an approval vote has been deleted from a change.
type VoteDeleted struct {
Type string `json:"type"`
Change Change `json:"change"`
PatchSet PatchSet `json:"patchSet"`
Reviewer Account `json:"reviewer"`
Remover Account `json:"remover"`
Approvals []Approval `json:"approvals"`
Comment string `json:"comment"`
}
// EventType implements Event.
func (VoteDeleted) EventType() string { return "vote-deleted" }
func init() {
registerEvent(func() Event { return &VoteDeleted{} })
}

View file

@ -0,0 +1,38 @@
package gerritevents
import (
"fmt"
"strconv"
"time"
)
// Time is a time.Time that is formatted as a Unix timestamp in JSON.
type Time struct {
time.Time
}
// UnmarshalJSON unmarshals a Unix timestamp into a Time.
func (t *Time) UnmarshalJSON(bs []byte) error {
if string(bs) == "null" {
return nil
}
u, err := strconv.ParseInt(string(bs), 10, 64)
if err != nil {
return err
}
t.Time = time.Unix(u, 0)
return nil
}
// MarshalJSON marshals a Time into a Unix timestamp.
func (t *Time) MarshalJSON() ([]byte, error) {
if t.IsZero() {
return []byte("null"), nil
}
return []byte(fmt.Sprintf("%d", t.Unix())), nil
}
// IsSet returns true if the time.Time is non-zero.
func (t *Time) IsSet() bool {
return !t.IsZero()
}

View file

@ -0,0 +1,221 @@
package gerritevents
// These types are taken from https://cl.tvl.fyi/Documentation/json.html.
// Account is a Gerrit account (or just a Git name+email pair).
type Account struct {
Name string `json:"name"`
Email string `json:"email"`
Username string `json:"username"`
}
// ChangeStatus represents the states a change can be in.
type ChangeStatus string
const (
// ChangeStatusNew is the state a change is in during review.
ChangeStatusNew ChangeStatus = "NEW"
// ChangeStatusMerged indicates a change was merged to the target branch.
ChangeStatusMerged ChangeStatus = "MERGED"
// ChangeStatusAbandoned indicates a change was marked as abandoned.
ChangeStatusAbandoned ChangeStatus = "ABANDONED"
)
// Message is a message left by a reviewer.
type Message struct {
Timestamp Time `json:"timestamp"`
Reviewer Account `json:"reviewer"`
Message string `json:"message"`
}
// TrackingID allows storing identifiers from external systems, i.e. bug trackers.
type TrackingID struct {
System string `json:"system"`
ID string `json:"id"`
}
// ChangeKind indicates the different changes that can be made to a change.
type ChangeKind string
const (
// ChangeKindRework indicates a non-trivial content change.
ChangeKindRework ChangeKind = "REWORK"
// ChangeKindTrivialRebase indicates a conflict-free merge between the new parent and the prior patch set.
ChangeKindTrivialRebase ChangeKind = "TRIVIAL_REBASE"
// ChangeKindMergeFirstParentUpdate indicates a conflict-free change of the first parent of a merge commit.
ChangeKindMergeFirstParentUpdate ChangeKind = "MERGE_FIRST_PARENT_UPDATE"
// ChangeKindNoCodeChange indicates no code change (the tree and parent trees are unchanged) - commit message probably changed.
ChangeKindNoCodeChange ChangeKind = "NO_CODE_CHANGE"
// ChangeKindNoChange indicates nothing changes: the commit message, tree, and parent tree are unchanged.
ChangeKindNoChange ChangeKind = "NO_CHANGE"
)
// Approval represents the current and past state of an approval label.
type Approval struct {
Type string `json:"type"`
Description string `json:"description"`
Value string `json:"value"`
OldValue *string `json:"oldValue"`
GrantedOn *Time `json:"grantedOn"`
By *Account `json:"by"`
}
// PatchSetComment is a single comment left on a patchset.
type PatchSetComment struct {
File string `json:"file"`
Line int `json:"line"`
Reviewer Account `json:"reviewer"`
Message string `json:"message"`
}
// FilePatchType represents the different modifications that can be made to a file by a patchset.
type FilePatchType string
const (
// FilePatchTypeAdded indicates the file did not exist, and this patchset adds it to the tree.
FilePatchTypeAdded FilePatchType = "ADDED"
// FilePatchTypeModified indicates the file exists before and after this patchset.
FilePatchTypeModified FilePatchType = "MODIFIED"
// FilePatchTypeDeleted indicates the file is removed by this patchset.
FilePatchTypeDeleted FilePatchType = "DELETED"
// FilePatchTypeRenamed indicates the file has a different name before this patchset than after.
FilePatchTypeRenamed FilePatchType = "RENAMED"
// FilePatchTypeCopied indicates the file was copied from a different file.
FilePatchTypeCopied FilePatchType = "COPIED"
// FilePatchTypeRewrite indicates the file had a significant quantity of content changed.
FilePatchTypeRewrite FilePatchType = "REWRITE"
)
// File represents a file in a patchset as well as how it is being modified.
type File struct {
File string `json:"file"`
FileOld string `json:"fileOld"`
Type FilePatchType `json:"type"`
}
// PatchSet represents a single patchset within a change.
type PatchSet struct {
Number int `json:"number"`
Revision string `json:"revision"`
Parents []string `json:"parents"`
Ref string `json:"ref"`
Uploader Account `json:"uploader"`
Author Account `json:"author"`
CreatedOn Time `json:"createdOn"`
Kind ChangeKind `json:"kind"`
Approvals []Approval `json:"approvals"`
Comments []PatchSetComment `json:"comments"`
Files []File `json:"file"`
SizeInsertions int `json:"sizeInsertions"`
SizeDeletions int `json:"sizeDeletions"`
}
// Dependency represents a change on which this change is dependent.
type Dependency struct {
ID string `json:"id"`
Number int `json:"number"`
Revision string `json:"revision"`
Ref string `json:"ref"`
IsCurrentPatchSet bool `json:"isCurrentPatchSet"`
}
// SubmitStatus indicates whether this change has met the submit conditions and is ready to submit.
type SubmitStatus string
const (
// SubmitStatusOK indicates this change is ready to submit - all submit requirements are met.
SubmitStatusOK SubmitStatus = "OK"
// SubmitStatusNotReady indicates this change cannot yet be submitted.
SubmitStatusNotReady SubmitStatus = "NOT_READY"
// SubmitStatusRuleError indicates the submit rules could not be evaluted. Administrator intervention is required.
SubmitStatusRuleError SubmitStatus = "RULE_ERROR"
)
// LabelStatus indicates whether this label permits submission and if the label can be granted by anyone.
type LabelStatus string
const (
// LabelStatusOK indicates that this label provides what is necessary for submission (e.g. CR+2).
LabelStatusOK LabelStatus = "OK"
// LabelStatusReject indicates this label prevents submission (e.g. CR-2).
LabelStatusReject LabelStatus = "REJECT"
// LabelStatusNeed indicates this label is required for submission, but has not been satisfied (e.g. CR0).
LabelStatusNeed LabelStatus = "NEED"
// LabelStatusMay indicates this label is not required for submission. It may or may not be set.
LabelStatusMay LabelStatus = "MAY"
// LabelStatusImpossible indicates this label is required for submission, but cannot be satisfied. The ACLs on this label may be set incorrectly.
LabelStatusImpossible LabelStatus = "IMPOSSIBLE"
)
// Label represents the status of a particular label.
type Label struct {
Label string `json:"label"`
Status LabelStatus `json:"status"`
By Account `json:"by"`
}
// Requirement represents a submit requirement.
type Requirement struct {
FallbackText string `json:"fallbackText"`
Type string `json:"type"`
// TODO(lukegb): data
}
// SubmitRecord represents the current submission state of a change.
type SubmitRecord struct {
Status SubmitStatus `json:"status"`
Labels []Label `json:"labels"`
Requirements []Requirement `json:"requirements"`
}
// Change represents a Gerrit CL.
type Change struct {
Project string `json:"project"`
Branch string `json:"branch"`
Topic string `json:"topic"`
ID string `json:"id"`
Number int `json:"number"`
Subject string `json:"subject"`
Owner Account `json:"owner"`
URL string `json:"url"`
CommitMessage string `json:"commitMessage"`
CreatedOn Time `json:"createdOn"`
LastUpdated *Time `json:"lastUpdated"`
Open bool `json:"open"`
Status ChangeStatus `json:"status"`
Private bool `json:"private"`
WIP bool `json:"wip"`
Comments []Message `json:"comments"`
TrackingIDs []TrackingID `json:"trackingIds"`
CurrentPatchSet *PatchSet `json:"currentPatchSet"`
PatchSets []PatchSet `json:"patchSets"`
DependsOn []Dependency `json:"dependsOn"`
NeededBy []Dependency `json:"neededBy"`
SubmitRecords []SubmitRecord `json:"submitRecord"`
AllReviewers []Account `json:"allReviewers"`
}
// RefUpdate represents a change in a ref.
type RefUpdate struct {
OldRev string `json:"oldRev"`
NewRev string `json:"newRev"`
RefName string `json:"refName"`
Project string `json:"project"`
}

View file

@ -0,0 +1,252 @@
// Package gerrit implements a watcher for Gerrit events.
package gerrit
import (
"context"
"errors"
"fmt"
"net"
"strings"
"time"
"code.tvl.fyi/fun/clbot/backoffutil"
"code.tvl.fyi/fun/clbot/gerrit/gerritevents"
log "github.com/golang/glog"
"golang.org/x/crypto/ssh"
)
// closer provides an embeddable implementation of Close which awaits a main loop acknowledging it has stopped.
type closer struct {
stop chan struct{}
stopped chan struct{}
}
// newCloser returns a closer with the channels initialised.
func newCloser() closer {
return closer{
stop: make(chan struct{}),
stopped: make(chan struct{}),
}
}
// Close stops the main loop, waiting for the main loop to stop until it stops or the context is cancelled, whichever happens first.
func (c *closer) Close(ctx context.Context) error {
select {
case <-c.stopped:
return nil
case <-c.stop:
return nil
case <-ctx.Done():
return ctx.Err()
default:
}
close(c.stop)
select {
case <-c.stopped:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// lineWriter is an io.Writer which splits on \n and outputs each line (with no trailing newline) to its output channel.
type lineWriter struct {
buf string
out chan string
}
// Write accepts a slice of bytes containing zero or more new lines.
// If the contained channel is non-buffering or is full, this will block.
func (w *lineWriter) Write(p []byte) (n int, err error) {
w.buf += string(p)
pieces := strings.Split(w.buf, "\n")
w.buf = pieces[len(pieces)-1]
for n := 0; n < len(pieces)-1; n++ {
w.out <- pieces[n]
}
return len(p), nil
}
// restartingClient is a simple SSH client that repeatedly connects to an SSH server, runs a command, and outputs the lines output by it on stdout onto a channel.
type restartingClient struct {
closer
network string
addr string
cfg *ssh.ClientConfig
exec string
output chan string
shutdown func()
}
var (
errStopConnect = errors.New("gerrit: told to stop reconnecting by remote server")
)
func (c *restartingClient) runOnce() error {
netConn, err := net.Dial(c.network, c.addr)
if err != nil {
return fmt.Errorf("connecting to %v/%v: %w", c.network, c.addr, err)
}
defer netConn.Close()
sshConn, newCh, newReq, err := ssh.NewClientConn(netConn, c.addr, c.cfg)
if err != nil {
return fmt.Errorf("creating SSH connection to %v/%v: %w", c.network, c.addr, err)
}
defer sshConn.Close()
goAway := false
passedThroughReqs := make(chan *ssh.Request)
go func() {
defer close(passedThroughReqs)
for req := range newReq {
if req.Type == "goaway" {
goAway = true
log.Warningf("remote end %v/%v told me to go away!", c.network, c.addr)
sshConn.Close()
netConn.Close()
}
passedThroughReqs <- req
}
}()
cl := ssh.NewClient(sshConn, newCh, passedThroughReqs)
sess, err := cl.NewSession()
if err != nil {
return fmt.Errorf("NewSession on %v/%v: %w", c.network, c.addr, err)
}
defer sess.Close()
sess.Stdout = &lineWriter{out: c.output}
if err := sess.Start(c.exec); err != nil {
return fmt.Errorf("Start(%q) on %v/%v: %w", c.exec, c.network, c.addr, err)
}
log.Infof("connected to %v/%v", c.network, c.addr)
done := make(chan struct{})
go func() {
sess.Wait()
close(done)
}()
go func() {
select {
case <-c.stop:
sess.Close()
case <-done:
}
return
}()
<-done
if goAway {
return errStopConnect
}
return nil
}
func (c *restartingClient) run() {
defer close(c.stopped)
bo := backoffutil.NewDefaultBackOff()
for {
timer := time.NewTimer(bo.NextBackOff())
select {
case <-c.stop:
timer.Stop()
return
case <-timer.C:
break
}
if err := c.runOnce(); err == errStopConnect {
if c.shutdown != nil {
c.shutdown()
return
}
} else if err != nil {
log.Errorf("SSH: %v", err)
} else {
bo.Reset()
}
}
}
// Output returns the channel on which each newline-delimited string output by the executed command's stdout can be received.
func (c *restartingClient) Output() <-chan string {
return c.output
}
// dialRestartingClient creates a new restartingClient.
func dialRestartingClient(network, addr string, config *ssh.ClientConfig, exec string, shutdown func()) (*restartingClient, error) {
c := &restartingClient{
closer: newCloser(),
network: network,
addr: addr,
cfg: config,
exec: exec,
output: make(chan string),
shutdown: shutdown,
}
go c.run()
return c, nil
}
// Watcher watches
type Watcher struct {
closer
c *restartingClient
output chan gerritevents.Event
}
// Close shuts down the SSH client connection, if any, and closes the output channel.
// It blocks until shutdown is complete or until the context is cancelled, whichever comes first.
func (w *Watcher) Close(ctx context.Context) {
w.c.Close(ctx)
w.closer.Close(ctx)
}
func (w *Watcher) run() {
defer close(w.stopped)
defer close(w.output)
for {
select {
case <-w.stop:
return
case o := <-w.c.Output():
ev, err := gerritevents.Parse([]byte(o))
if err != nil {
log.Errorf("failed to parse event %v: %v", o, err)
continue
}
w.output <- ev
}
}
}
// Events returns the channel upon which parsed Gerrit events can be received.
func (w *Watcher) Events() <-chan gerritevents.Event {
return w.output
}
// New returns a running Watcher from which events can be read.
// It will begin connecting to the provided address immediately.
func New(ctx context.Context, network, addr string, cfg *ssh.ClientConfig) (*Watcher, error) {
wc := newCloser()
rc, err := dialRestartingClient(network, addr, cfg, "gerrit stream-events", func() {
wc.Close(context.Background())
})
if err != nil {
return nil, fmt.Errorf("dialRestartingClient: %w", err)
}
w := &Watcher{
closer: wc,
c: rc,
output: make(chan gerritevents.Event),
}
go w.run()
return w, nil
}

View file

@ -0,0 +1,190 @@
package gerrit
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/subtle"
"fmt"
"net"
"testing"
"time"
"code.tvl.fyi/fun/clbot/gerrit/gerritevents"
log "github.com/golang/glog"
"github.com/google/go-cmp/cmp"
"golang.org/x/crypto/ssh"
)
var (
sshServerSigner, sshServerPublicKey = mustNewKey()
sshClientSigner, sshClientPublicKey = mustNewKey()
)
func mustNewKey() (ssh.Signer, ssh.PublicKey) {
key, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
panic(err)
}
signer, err := ssh.NewSignerFromKey(key)
if err != nil {
panic(err)
}
publicKey, err := ssh.NewPublicKey(key.Public())
if err != nil {
panic(err)
}
return signer, publicKey
}
func newSSHServer(lines string) (addr string, cleanup func(), err error) {
config := &ssh.ServerConfig{
PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
pkBytes := pubKey.Marshal()
wantPKBytes := sshClientPublicKey.Marshal()
if subtle.ConstantTimeCompare(pkBytes, wantPKBytes) == 0 {
return nil, fmt.Errorf("unauthorized")
}
return &ssh.Permissions{}, nil
},
}
config.AddHostKey(sshServerSigner)
ln, err := net.Listen("tcp", ":0")
if err != nil {
log.Fatalf("Listen on tcp/:0: %v", err)
}
handle := func(conn net.Conn) {
defer conn.Close()
sc, newchch, newreqch, err := ssh.NewServerConn(conn, config)
if err != nil {
log.Fatalf("NewServerConn: %v", err)
}
go ssh.DiscardRequests(newreqch)
for newCh := range newchch {
if newCh.ChannelType() != "session" {
newCh.Reject(ssh.UnknownChannelType, "unknown channel type")
continue
}
channel, reqs, err := newCh.Accept()
if err != nil {
log.Fatalf("Could not accept channel: %v", err)
}
go func(in <-chan *ssh.Request) {
for req := range in {
req.Reply(req.Type == "exec", nil)
}
}(reqs)
channel.Write([]byte(lines))
sc.SendRequest("goaway", false, nil)
}
}
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
go handle(conn)
}
}()
cleanup = func() {
ln.Close()
}
return ln.Addr().String(), cleanup, err
}
func ts(s string) gerritevents.Time {
t, err := time.Parse("2006-01-02 15:04:05 -0700 MST", s)
if err != nil {
panic(err)
}
return gerritevents.Time{t}
}
func optStr(s string) *string { return &s }
func TestWatcher(t *testing.T) {
tcs := []struct {
name string
lines string
want []gerritevents.Event
}{{
name: "no events",
}, {
name: "single test event",
lines: `{"author":{"name":"tazjin","email":"mail@tazj.in","username":"tazjin"},"approvals":[{"type":"Code-Review","description":"Code-Review","value":"2","oldValue":"0"}],"comment":"Patch Set 3: Code-Review+2","patchSet":{"number":3,"revision":"6fe272d3f82c6efdfe1167fab98bf918efc03fe5","parents":["d984b6018cf68c7e8b7169b475d90134fbcee767"],"ref":"refs/changes/44/244/3","uploader":{"name":"tazjin","email":"mail@tazj.in","username":"tazjin"},"createdOn":1592081910,"author":{"name":"tazjin","email":"mail@tazj.in","username":"tazjin"},"kind":"REWORK","sizeInsertions":83,"sizeDeletions":-156},"change":{"project":"depot","branch":"master","id":"I546c701145fa204b7ba7518a8a56a783588629e0","number":244,"subject":"refactor(ops/nixos): Move my NixOS configurations to //users/tazjin","owner":{"name":"tazjin","email":"mail@tazj.in","username":"tazjin"},"url":"https://cl.tvl.fyi/c/depot/+/244","commitMessage":"refactor(ops/nixos): Move my NixOS configurations to //users/tazjin\n\nNixOS modules move one level up because it\u0027s unlikely that //ops/nixos\nwill contain actual systems at this point (they\u0027re user-specific).\n\nThis is the first users folder, so it is also added to the root\nreadTree invocation for the repository.\n\nChange-Id: I546c701145fa204b7ba7518a8a56a783588629e0\n","createdOn":1592081577,"status":"NEW"},"project":"depot","refName":"refs/heads/master","changeKey":{"id":"I546c701145fa204b7ba7518a8a56a783588629e0"},"type":"comment-added","eventCreatedOn":1592081929}
`,
want: []gerritevents.Event{
&gerritevents.CommentAdded{
Type: "comment-added",
Change: gerritevents.Change{
Project: "depot",
Branch: "master",
ID: "I546c701145fa204b7ba7518a8a56a783588629e0",
Number: 244,
Subject: "refactor(ops/nixos): Move my NixOS configurations to //users/tazjin",
Owner: gerritevents.Account{Name: "tazjin", Email: "mail@tazj.in", Username: "tazjin"},
URL: "https://cl.tvl.fyi/c/depot/+/244",
CommitMessage: "refactor(ops/nixos): Move my NixOS configurations to //users/tazjin\n\nNixOS modules move one level up because it's unlikely that //ops/nixos\nwill contain actual systems at this point (they're user-specific).\n\nThis is the first users folder, so it is also added to the root\nreadTree invocation for the repository.\n\nChange-Id: I546c701145fa204b7ba7518a8a56a783588629e0\n",
CreatedOn: ts("2020-06-13 21:52:57 +0100 BST"),
Status: "NEW",
},
PatchSet: gerritevents.PatchSet{
Number: 3,
Revision: "6fe272d3f82c6efdfe1167fab98bf918efc03fe5",
Parents: []string{"d984b6018cf68c7e8b7169b475d90134fbcee767"},
Ref: "refs/changes/44/244/3",
Uploader: gerritevents.Account{Name: "tazjin", Email: "mail@tazj.in", Username: "tazjin"},
Author: gerritevents.Account{Name: "tazjin", Email: "mail@tazj.in", Username: "tazjin"},
CreatedOn: ts("2020-06-13 21:58:30 +0100 BST"),
Kind: "REWORK",
SizeInsertions: 83,
SizeDeletions: -156,
},
Author: gerritevents.Account{Name: "tazjin", Email: "mail@tazj.in", Username: "tazjin"},
Approvals: []gerritevents.Approval{{Type: "Code-Review", Description: "Code-Review", Value: "2", OldValue: optStr("0")}},
Comment: "Patch Set 3: Code-Review+2",
EventCreatedOn: ts("2020-06-13 21:58:49 +0100 BST"),
},
},
}}
for _, tc := range tcs {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
serverAddr, cleanup, err := newSSHServer(tc.lines)
if err != nil {
t.Fatalf("newSSHServer: %v", err)
}
t.Cleanup(cleanup)
config := &ssh.ClientConfig{
User: "bert",
Auth: []ssh.AuthMethod{ssh.PublicKeys(sshClientSigner)},
HostKeyCallback: ssh.FixedHostKey(sshServerPublicKey),
Timeout: 10 * time.Millisecond,
}
w, err := New(ctx, "tcp", serverAddr, config)
if err != nil {
t.Fatalf("New: %v", err)
}
var gotEvents []gerritevents.Event
for ev := range w.Events() {
gotEvents = append(gotEvents, ev)
}
if diff := cmp.Diff(gotEvents, tc.want); diff != "" {
t.Errorf("got events != want events: diff:\n%v", diff)
}
})
}
}

12
third_party/tvl/fun/clbot/go.mod vendored Normal file
View file

@ -0,0 +1,12 @@
module code.tvl.fyi/fun/clbot
go 1.14
require (
github.com/cenkalti/backoff/v4 v4.0.2
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b
github.com/google/go-cmp v0.4.1
golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9
gopkg.in/irc.v3 v3.1.3
)

31
third_party/tvl/fun/clbot/go.sum vendored Normal file
View file

@ -0,0 +1,31 @@
github.com/cenkalti/backoff/v4 v4.0.2 h1:JIufpQLbh4DkbQoii76ItQIUFzevQSqOLZca4eamEDs=
github.com/cenkalti/backoff/v4 v4.0.2/go.mod h1:eEew/i+1Q6OrCDZh3WiXYv3+nJwBASZ8Bog/87DQnVg=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/google/go-cmp v0.4.1 h1:/exdXoGamhu5ONeUJH0deniYLWYvQwW66yvlfiiKTu0=
github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9 h1:vEg9joUBmeBcK9iSJftGNf3coIG4HqZElCPehJsfAYM=
golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/irc.v3 v3.1.3 h1:yeTiJ365882L8h4AnBKYfesD92y5R5ZhGiylu9DfcPY=
gopkg.in/irc.v3 v3.1.3/go.mod h1:shO2gz8+PVeS+4E6GAny88Z0YVVQSxQghdrMVGQsR9s=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

View file

@ -0,0 +1,3 @@
/target/
**/*.rs.bk
Cargo.lock

View file

@ -0,0 +1,6 @@
[package]
name = "defer"
version = "0.1.0"
authors = ["Vincent Ambo <tazjin@gmail.com>"]
[dependencies]

53
third_party/tvl/fun/defer_rs/README.md vendored Normal file
View file

@ -0,0 +1,53 @@
defer in Rust
=============
After a Hacker News discussion about implementing Go's `defer` keyword in C++,
I stumbled upon [this comment](https://news.ycombinator.com/item?id=15523589)
and more specifically this response to it by "Occivink":
> There's plenty of one-time cases where you don't want to declare an entire
> class but still enjoy scope-based functions.
Specificall the "don't want to declare an entire class" suggests that languages
like C++ have high friction for explaining your desired invariant (cleanup is
run when `$thing` is destroyed) to the compiler.
It seems like most languages either hand-wave this away (*cough* Java *cough*)
or use what seems like a workaround (`defer`).
Rust has the so-called `Drop` trait, which is a typeclass that contains a single
method with no return value that is run when a variable is dropped (i.e. goes out
of scope).
This works fine for most general cases - i.e. closing file handlers - but can
get complicated if other use-cases of `defer` are considered:
* returning an error-value by mutating a reference in the enclosing scope (oh boy)
* deferring a decision about when/whether to run cleanup to the caller
While thinking about how to do this with the `Drop` trait I realised that `defer`
can actually be trivially implemented in Rust, using `Drop`.
A simple implementation of `defer` can be seen in [defer.rs](examples/defer.rs),
an implementation using shared mutable state for error returns is in the file
[defer-with-error.rs](examples/defer-with-error.rs) and an implementation that
allows cleanup to be *cancelled* (don't _actually_ do this, it leaks a pointer)
is in [undefer.rs](examples/undefer.rs).
Whether any of this is actually useful is not up to me to decide. I haven't
actually had a real-life need for this.
You can run the examples with `cargo run --example defer`, etc.
## Notes
* `Drop` is not guaranteed to run in case of panics or program aborts, if you
need support for that check out [scopeguard](https://github.com/bluss/scopeguard)
* `undefer` could be implemented safely by, for example, carrying a boolean that
by default causes execution to happen but can be flipped to disable it
## Further reading:
* [The Pain Of Real Linear Types in Rust](https://gankro.github.io/blah/linear-rust/)
* [Go's defer](https://tour.golang.org/flowcontrol/12)
* [Rust's Drop](https://doc.rust-lang.org/std/ops/trait.Drop.html)

View file

@ -0,0 +1,70 @@
// Go's defer in Rust, with error value return.
use std::rc::Rc;
use std::sync::RwLock;
struct Defer<F: Fn()> {
f: F
}
impl <F: Fn()> Drop for Defer<F> {
fn drop(&mut self) {
(self.f)()
}
}
// Only added this for Go-syntax familiarity ;-)
fn defer<F: Fn()>(f: F) -> Defer<F> {
Defer { f }
}
// Convenience type synonym. This is a reference-counted smart pointer to
// a shareable, mutable variable.
// Rust does not allow willy-nilly mutation of shared variables, so explicit
// write-locking must be performed.
type ErrorHandle<T> = Rc<RwLock<Option<T>>>;
///////////////////
// Usage example //
///////////////////
#[derive(Debug)] // Debug trait for some default way to print the type.
enum Error { DropError }
fn main() {
// Create a place to store the error.
let drop_err: ErrorHandle<Error> = Default::default(); // create empty error
// Introduce an arbitrary scope block (so that we still have control after
// the defer runs):
{
let mut i = 1;
// Rc types are safe to clone and share for multiple ownership.
let err_handle = drop_err.clone();
// Call defer and let the closure own the cloned handle to the error:
let token = defer(move || {
// do something!
println!("Value is: {}", i);
// ... oh no, it went wrong!
*err_handle.write().unwrap() = Some(Error::DropError);
});
i += 1;
println!("Value is: {}", i);
// token goes out of scope here - drop() is called.
}
match *drop_err.read().unwrap() {
Some(ref err) => println!("Oh no, an error occured: {:?}!", err),
None => println!("Phew, everything went well.")
};
}
// Prints:
// Value is: 2
// Value is: 1
// Oh no, an error occured: DropError!

View file

@ -0,0 +1,31 @@
// Go's defer in Rust!
struct Defer<F: Fn()> {
f: F
}
impl <F: Fn()> Drop for Defer<F> {
fn drop(&mut self) {
(self.f)()
}
}
// Only added this for Go-syntax familiarity ;-)
fn defer<F: Fn()>(f: F) -> Defer<F> {
Defer { f }
}
fn main() {
let mut i = 1;
// Calling it "token" ... could be something else. The lifetime of this
// controls when the action is run.
let _token = defer(move || println!("Value is: {}", i));
i += 1;
println!("Value is: {}", i);
}
// Prints:
// Value is: 2
// Value is: 1

View file

@ -0,0 +1,40 @@
// Go's defer in Rust, with a little twist!
struct Defer<F: Fn()> {
f: F
}
impl <F: Fn()> Drop for Defer<F> {
fn drop(&mut self) {
(self.f)()
}
}
// Only added this for Go-syntax familiarity ;-)
fn defer<F: Fn()>(f: F) -> Defer<F> {
Defer { f }
}
// Changed your mind about the defer?
// (Note: This leaks the closure! Don't actually do this!)
fn undefer<F: Fn()>(token: Defer<F>) {
use std::mem;
mem::forget(token);
}
fn main() {
let mut i = 1;
// Calling it "token" ... could be something else. The lifetime of this
// controls when the action is run.
let token = defer(move || println!("Value is: {}", i));
i += 1;
println!("Value is: {}", i);
// Oh, now I changed my mind about the previous defer:
undefer(token);
}
// Prints:
// Value is: 2

1
third_party/tvl/fun/elblog/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
*.elc

11
third_party/tvl/fun/elblog/README.md vendored Normal file
View file

@ -0,0 +1,11 @@
elblog
======
This is a simple blogging software written in Emacs Lisp.
The idea is that it should be able to do most of the things [my actual blog][]
does at the moment.
No documentation exists for now besides the commit messages, but it works!
[my actual blog]: https://www.tazj.in/

37
third_party/tvl/fun/elblog/blog.css vendored Normal file
View file

@ -0,0 +1,37 @@
<style type="text/css">
body {
margin: 40px auto;
max-width: 800px;
line-height: 1.6;
font-size: 18px;
color: #383838;
padding: 0 10px
}
h1, h2, h3 {
line-height: 1.2
}
.footer {
text-align: right;
}
.lod {
text-align: center;
}
.unstyled-link {
color: inherit;
text-decoration: none;
}
.uncoloured-link {
color: inherit;
}
.date {
text-align: right;
font-style: italic;
float: right;
}
.inline {
display: inline;
}
.navigation {
text-align: center;
}
</style>

123
third_party/tvl/fun/elblog/blog.el vendored Normal file
View file

@ -0,0 +1,123 @@
;;; blog.el --- A simple org-mode & elnode blog software.
;;; -*- lexical-binding: t; -*-
(require 'dash)
(require 'elnode)
(require 'f)
(require 'ht)
;; Definition of customization options
(defgroup elblog nil
"Configuration for the Emacs Lisp blog software"
:link '(url-link "https://github.com/tazjin/elblog"))
(defcustom elblog-port 8010
"Port to run elblog's HTTP server on"
:group 'elblog
:type 'integer)
(defcustom elblog-host "localhost"
"Host for elblog's HTTP server to listen on"
:group 'elblog
:type 'string)
(defcustom elblog-title "Elblog"
"Title text for this elblog instance"
:group 'elblog
:type 'string)
(defcustom elblog-article-directory nil
"Directory in which elblog articles are stored"
:group 'elblog
:type 'string)
(defcustom elblog-additional-routes '()
"Additional Elnode routes to register in the Elblog instance"
:group 'elblog
:type '(alist :key-type regexp :value-type function))
;; Declare user-configurable variables needed at runtime.
(defvar elblog-articles (ht-create)
"A hash-table of blog articles. This is used for looking up articles from
URL fragments as well as for rendering the index.")
;; HTML templating setup
(defun template-preamble ()
"Templates the preamble snippet with the correct blog title."
(format (f-read-text "preamble.html") elblog-title))
(defun configure-org-html-export ()
"Configure org-mode settings for elblog's HTML templating to work correctly."
(setq org-html-postamble t)
(setq org-html-doctype "html5")
(setq org-html-head-include-scripts nil)
(setq org-html-style-default (f-read-text "blog.css"))
(setq org-html-preamble-format `(("en" ,(template-preamble))))
(setq org-html-postamble-format `(("en" ,(f-read-text "postamble.html")))))
;; Article fetching & rendering functions
(defun render-org-buffer (input-buffer &optional force)
"Renders an org-mode buffer as HTML and returns the name of the output buffer."
(letrec ((output-buffer (concat (buffer-name input-buffer) "-rendered"))
;; Don't re-render articles unless forced.
(must-render (or force
(not (get-buffer output-buffer)))))
(if (and input-buffer must-render)
(with-current-buffer input-buffer
(org-export-to-buffer 'html output-buffer nil nil t)))
(if input-buffer output-buffer nil)))
(defun get-buffer-string (buffer)
"Returns the contents of the specified buffer as a string."
(with-current-buffer (get-buffer buffer)
(buffer-string)))
(defvar-local article-not-found
'(404 . "<html><body><p>Oh no, the article was not found.</p></body></html>"))
(defvar-local text-html '("Content-Type" . "text/html"))
(defun render-article (article)
"Renders an article, if it exists."
(letrec ((rendered (-some->>
(ht-get elblog-articles article)
(concat elblog-article-directory)
(find-file)
(render-org-buffer))))
(if rendered `(200 . ,(get-buffer-string rendered))
article-not-found)))
(defun blog-post-handler (httpcon)
"This handler servers a blog post from the configured blog post directory."
(let ((response (render-article (elnode-http-mapping httpcon 1))))
(elnode-http-start httpcon (car response) text-html)
(elnode-http-return httpcon (cdr response))))
;; Web server implementation
(defvar elblog-routes
'(("^.*//\\(.*\\)" . blog-post-handler))
"The default routes available in elblog. They can be extended by the user
by setting the elblog-additional-routes customize option.")
(defun elblog-handler (httpcon)
(elnode-hostpath-dispatcher
httpcon
(-concat elblog-additional-routes elblog-routes)))
(defun start-elblog ()
(interactive)
(configure-org-html-export)
(elnode-start 'elblog-handler
:port elblog-port
:host elblog-host))
(defun stop-elblog ()
(interactive)
(elnode-stop elblog-port))
(provide 'elblog)

View file

@ -0,0 +1,9 @@
<hr>
<footer><p class="footer">Served with <a class="uncoloured-link" href="https://github.com/tazjin/elblog">Emacs</a>.</p>
<p class="footer">
<a class="uncoloured-link" href="https://twitter.com/tazjin">Twitter</a>
|
<a class="uncoloured-link" href="mailto:blog@tazj.in">Mail</a>
</p>
<p class="lod">ಠ_ಠ</p>
</footer>

View file

@ -0,0 +1,6 @@
<header>
<h1>
<a class="unstyled-link" href="/">%s</a>
</h1>
<hr>
</header>

View file

@ -0,0 +1,20 @@
A SERMON ON ETHICS AND LOVE
===========================
One day Mal-2 asked the messenger spirit Saint Gulik to approach the Goddess and request Her presence for some desperate advice. Shortly afterwards the radio came on by itself, and an ethereal female Voice said **YES?**
"O! Eris! Blessed Mother of Man! Queen of Chaos! Daughter of Discord! Concubine of Confusion! O! Exquisite Lady, I beseech You to lift a heavy burden from my heart!"
**WHAT BOTHERS YOU, MAL? YOU DON'T SOUND WELL.**
"I am filled with fear and tormented with terrible visions of pain. Everywhere people are hurting one another, the planet is rampant with injustices, whole societies plunder groups of their own people, mothers imprison sons, children perish while brothers war. O, woe."
**WHAT IS THE MATTER WITH THAT, IF IT IS WHAT YOU WANT TO DO?**
"But nobody Wants it! Everybody hates it."
**OH. WELL, THEN *STOP*.**
At which moment She turned herself into an aspirin commercial and left The Polyfather stranded alone with his species.
SINISTER DEXTER HAS A BROKEN SPIROMETER.

674
third_party/tvl/fun/gemma/LICENSE vendored Normal file
View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<http://www.gnu.org/licenses/>.
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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

96
third_party/tvl/fun/gemma/README.md vendored Normal file
View file

@ -0,0 +1,96 @@
# Gemma
Gemma is a simple application to track *recurring* tasks, named after Gemma
Hartley who [wrote an article][] about task distribution issues in households.
## Background
(Skip this if you just want the technical bits)
Gemma's article launched a discussion in my friend circle about what causes an
uneven distribution of household workload. I theorised that this is not so much
a gender issue, but mostly a discoverability issue.
Usually one person in a household is aware of what needs to be done, but in many
cases the "overhead" of delegating the tasks would actually take more time than
simply doing the task.
I theorise further that the person (or people) who do a smaller share of the
household work would often do the work if they had a convenient way to become
aware of what needs to be done. Many times the "household manager" has the
function of tracking non-obvious tasks like when bedsheets were last changed -
shouldn't it be possible to actually distribute this information somehow?
## The Project
This project is an initial attempt at sketching out a little application that
aids with reminding users of recurring tasks. Some basic ideas:
* The system should be blame-free.
* There should be as little usage overhead as possible so that people actually
do use it.
* It should work mostly passively without much user interaction.
I believe that the basic (*very* simple) idea behind Gemma solves these issues.
Unfortunately my living situation changed before I actually got to test this out
in a real-life situation involving multiple people, but feedback from other
potential test subjects would be welcome! :)
## Overview
Gemma is a Common Lisp application in which a list of recurring tasks is
declared, together with the *maximum interval* at which they should be completed
(in days). Example:
```lisp
;; Bathroom tasks
(deftask bathroom/wipe-mirror 7)
(deftask bathroom/wipe-counter 7)
;; Bedroom tasks
(deftask bedroom/change-sheets 7)
(deftask bedroom/vacuum 10)
;; Kitchen tasks
(deftask kitchen/trash 3)
(deftask kitchen/wipe-counters 3)
(deftask kitchen/vacuum 5 "Kitchen has more crumbs and such!")
;; Entire place
(deftask clean-windows 60)
```
These tasks are marked with their last completion time and tracked by Gemma. A
simple Elm-based frontend application displays the tasks sorted by their
"urgency" and features a button to mark a task as completed:
![Gemma screenshot](http://i.imgur.com/n7FFMJH.png)
Marking a task as completed resets its counter and moves it to the bottom of the
task list.
In theory this *should be it*, the frontend is made available to household
members in some easily accessible place (e.g. an old phone glued to the fridge!)
and people should attempt to develop a habit of checking what needs to be done
occasionally.
The "household manager" still exists as a role of the household because someone
is entering the tasks into the application, but if my theory about people not
actually being actively *unwilling* to do tasks is correct this could help a
lot.
## Usage
(*Note*: Gemma is alpha software so the below is clearly not the final goal)
Right now using this is non-trivial, but I'll eventually make a better
distribution. Basically you need to know Common Lisp (in which case you'll know
how to get the backend running) and have `elm-reactor` installed to run the
development version of the frontend application.
Gemma is configured via a configuration file that should be located either at
`/etc/gemma/config.lisp` or at a custom location specified via the environment
variable `GEMMA_CONFIG`. Have a look at the `config.lisp` file in the repository
root for an example.
[wrote an article]: http://www.harpersbazaar.com/culture/features/a12063822/emotional-labor-gender-equality/

21
third_party/tvl/fun/gemma/config.lisp vendored Normal file
View file

@ -0,0 +1,21 @@
;; Example configuration file for Gemma
(config :port 4242
:data-dir "/tmp/gemma/")
(deftask bathroom/wipe-mirror 7)
(deftask bathroom/wipe-counter 7)
;; Bedroom tasks
(deftask bedroom/change-sheets 7)
(deftask bedroom/vacuum 10)
;; Kitchen tasks
(deftask kitchen/normal-trash 3)
(deftask kitchen/green-trash 5)
(deftask kitchen/blue-trash 5)
(deftask kitchen/wipe-counters 3)
(deftask kitchen/vacuum 5 "Kitchen has more crumbs and such!")
;; Entire place
(deftask clean-windows 60)

50
third_party/tvl/fun/gemma/default.nix vendored Normal file
View file

@ -0,0 +1,50 @@
{ depot, ... }:
let
inherit (depot) elmPackages;
inherit (depot.third_party) cacert iana-etc libredirect stdenv runCommandNoCC writeText;
frontend = stdenv.mkDerivation {
name = "gemma-frontend.html";
src = ./frontend;
buildInputs = [ cacert iana-etc elmPackages.elm ];
# The individual Elm packages this requires are not packaged and I
# can't be bothered to do that now, so lets open the escape hatch:
outputHashAlgo = "sha256";
outputHash = "000xhds5bsig3kbi7dhgbv9h7myacf34bqvw7avvz7m5mwnqlqg7";
phases = [ "unpackPhase" "buildPhase" ];
buildPhase = ''
export NIX_REDIRECTS=/etc/protocols=${iana-etc}/etc/protocols \
LD_PRELOAD=${libredirect}/lib/libredirect.so
export SYSTEM_CERTIFICATE_PATH=${cacert}/etc/ssl/certs
mkdir .home && export HOME="$PWD/.home"
elm-make --yes Main.elm --output $out
'';
};
injectFrontend = writeText "gemma-frontend.lisp" ''
(in-package :gemma)
(setq *static-file-location* "${runCommandNoCC "frontend" {} ''
mkdir -p $out
cp ${frontend} $out/index.html
''}/")
'';
in depot.nix.buildLisp.program {
name = "gemma";
deps = with depot.third_party.lisp; [
cl-json
cl-prevalence
hunchentoot
local-time
];
srcs = [
./src/gemma.lisp
injectFrontend
];
}

View file

@ -0,0 +1,221 @@
-- Copyright (C) 2016-2017 Vincent Ambo <mail@tazj.in>
--
-- This file is part of Gemma.
--
-- Gemma 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.
module Main exposing (..)
import Html exposing (Html, text, div, span)
import Html.Attributes exposing (style)
import Json.Decode exposing (..)
import Http
import Time
-- Material design imports
import Material
import Material.Card as Card
import Material.Color as Color
import Material.Grid exposing (grid, cell, size, Device(..))
import Material.Layout as Layout
import Material.Scheme as Scheme
import Material.Options as Options
import Material.Elevation as Elevation
import Material.Button as Button
-- API interface to Gemma
type alias Task =
{ name : String
, description : Maybe String
, remaining : Int
}
emptyStringFilter s =
if s == "" then
Nothing
else
Just s
decodeEmptyString : Decoder (Maybe String)
decodeEmptyString =
map emptyStringFilter string
decodeTask : Decoder Task
decodeTask =
map3 Task
(field "name" string)
(field "description" decodeEmptyString)
(field "remaining" int)
loadTasks : Cmd Msg
loadTasks =
let
request =
Http.get "/tasks" (list decodeTask)
in
Http.send NewTasks request
completeTask : Task -> Cmd Msg
completeTask task =
let
request =
Http.getString
(String.concat
[ "/complete?task="
, task.name
]
)
in
Http.send (\_ -> LoadTasks) request
-- Elm architecture implementation
type Msg
= None
| LoadTasks
| NewTasks (Result Http.Error (List Task))
| Mdl (Material.Msg Msg)
| Complete Task
type alias Model =
{ tasks : List Task
, error : Maybe String
, mdl : Material.Model
}
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
LoadTasks ->
( model, loadTasks )
Complete task ->
( model, completeTask task )
NewTasks (Ok tasks) ->
( { model | tasks = tasks, error = Nothing }, Cmd.none )
NewTasks (Err err) ->
( { model | error = Just (toString err) }, Cmd.none )
_ ->
( model, Cmd.none )
-- View implementation
white =
Color.text Color.white
taskColor : Task -> Color.Hue
taskColor task =
if task.remaining > 2 then
Color.Green
else if task.remaining < 0 then
Color.Red
else
Color.Yellow
within : Task -> String
within task =
if task.remaining < 0 then
"This task is overdue!"
else if task.remaining > 2 then
String.concat
[ "Relax, this task has "
, toString task.remaining
, " days left before it is due."
]
else
String.concat
[ "This task should be completed within "
, toString task.remaining
, " days. Consider doing it now!"
]
renderTask : Model -> Task -> Html Msg
renderTask model task =
Card.view
[ Color.background (Color.color (taskColor task) Color.S800)
, Elevation.e3
]
[ Card.title [] [ Card.head [ white ] [ text task.name ] ]
, Card.text [ white ]
[ text (Maybe.withDefault "" task.description)
, Html.br [] []
, text (within task)
]
, Card.actions
[ Card.border ]
[ Button.render Mdl
[ 0 ]
model.mdl
[ white, Button.ripple, Button.accent, Options.onClick (Complete task) ]
[ text "Completed" ]
]
]
gemmaView : Model -> Html Msg
gemmaView model =
grid []
(List.map (\t -> cell [ size All 4 ] [ renderTask model t ])
model.tasks
)
view : Model -> Html Msg
view model =
gemmaView model |> Scheme.top
-- subscriptions : Model -> Sub Msg
subscriptions model =
Sub.batch
[ Material.subscriptions Mdl model
, Time.every (15 * Time.second) (\_ -> LoadTasks)
]
main : Program Never Model Msg
main =
let
model =
{ tasks = []
, error = Nothing
, mdl = Material.model
}
in
Html.program
{ init = ( model, Cmd.batch [ loadTasks, Material.init Mdl ] )
, view = view
, update = update
, subscriptions = subscriptions
}

View file

@ -0,0 +1,17 @@
{
"version": "1.0.0",
"summary": "helpful summary of your project, less than 80 characters",
"repository": "https://github.com/user/project.git",
"license": "BSD3",
"source-directories": [
"."
],
"exposed-modules": [],
"dependencies": {
"elm-lang/core": "5.1.1 <= v < 6.0.0",
"elm-lang/html": "2.0.0 <= v < 3.0.0",
"elm-lang/http": "1.0.0 <= v < 2.0.0",
"debois/elm-mdl": "8.1.0 <= v < 9.0.0"
},
"elm-version": "0.18.0 <= v < 0.19.0"
}

192
third_party/tvl/fun/gemma/src/gemma.lisp vendored Normal file
View file

@ -0,0 +1,192 @@
;; Copyright (C) 2016-2020 Vincent Ambo <mail@tazj.in>
;;
;; This file is part of Gemma.
;;
;; Gemma 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.
(defpackage gemma
(:use :cl
:local-time
:cl-json)
(:import-from :sb-posix :getenv)
(:shadowing-import-from :sb-posix :getcwd)
(:export :start-gemma :config :main))
(in-package :gemma)
;; TODO: Store an average of how many days it was between task
;; completions. Some of the current numbers are just guesses
;; anyways.
(defmacro in-case-of (x &body body)
"Evaluate BODY if X is non-nil, binding the value of X to IT."
`(let ((it ,x))
(when it ,@body)))
;; Set default configuration parameters
(defvar *gemma-port* 4242
"Port on which the Gemma web server listens.")
(defvar *gemma-acceptor* nil
"Hunchentoot acceptor for Gemma's web server.")
(defvar *static-file-location* "frontend/"
"Folder from which to serve static assets. If built inside of Nix,
the path is injected during the build.")
(defvar *p-tasks* nil
"All tasks registered in this Gemma instance.")
(defun initialise-persistence (data-dir)
(setq *p-tasks* (cl-prevalence:make-prevalence-system data-dir))
;; Initialise database ID counter
(or (> (length (cl-prevalence:find-all-objects *p-tasks* 'task)) 0)
(cl-prevalence:tx-create-id-counter *p-tasks*)))
(defun config (&key port data-dir)
"Configuration function for use in the Gemma configuration file."
(in-package :gemma)
(in-case-of port (defparameter *gemma-port* it))
(initialise-persistence (or data-dir "data/")))
;;
;; Define task management system
;;
(defclass task ()
((id :reader id
:initarg :id)
;; (Unique) name of the task
(name :type symbol
:initarg :name
:accessor name-of)
;; Maximum completion interval
(days :type integer
:initarg :days
:accessor days-of)
;; Optional description
(description :type string
:initarg :description
:accessor description-of)
;; Last completion time
(done-at :type timestamp
:initarg :done-at
:accessor last-done-at)))
(defmacro deftask (task-name days &optional description)
(unless (get-task task-name)
`(progn (cl-prevalence:tx-create-object
*p-tasks*
'task
(quote ((name ,task-name)
(days ,days)
(description ,(or description ""))
(done-at ,(now)))))
(cl-prevalence:snapshot *p-tasks*))))
(defun get-task (name)
(cl-prevalence:find-object-with-slot *p-tasks* 'task 'name name))
(defun list-tasks ()
(cl-prevalence:find-all-objects *p-tasks* 'task))
(defun days-remaining (task)
"Returns the number of days remaining before the supplied TASK reaches its
maximum interval."
(let* ((expires-at (timestamp+ (last-done-at task)
(days-of task) :day))
(secs-until-expiry (timestamp-difference expires-at (now))))
(round (/ secs-until-expiry 60 60 24))))
(defun sort-tasks (tasks)
"Sorts TASKS in descending order by number of days remaining."
(sort (copy-list tasks)
(lambda (t1 t2) (< (days-remaining t1)
(days-remaining t2)))))
(defun complete-task (name &optional at)
"Mark the task with NAME as completed, either now or AT specified time."
(cl-prevalence:tx-change-object-slots *p-tasks* 'task
(id (get-task name))
`((done-at ,(or at (now)))))
(cl-prevalence:snapshot *p-tasks*))
;;
;; Define web API
;;
(defun response-for (task)
"Create a response object to be JSON encoded for TASK."
`((:name . ,(name-of task))
(:description . ,(description-of task))
(:remaining . ,(days-remaining task))))
(defun start-gemma ()
(in-package :gemma)
;; Load configuration
(load (pathname (or (getenv "GEMMA_CONFIG")
"/etc/gemma/config.lisp")))
;; Set up web server
(setq *gemma-acceptor* (make-instance 'hunchentoot:easy-acceptor
:port *gemma-port*
:document-root *static-file-location*))
(hunchentoot:start *gemma-acceptor*)
;; Task listing handler
(hunchentoot:define-easy-handler
(get-tasks :uri "/tasks") ()
(setf (hunchentoot:content-type*) "application/json")
(setf (hunchentoot:header-out "Access-Control-Allow-Origin") "*")
(encode-json-to-string
;; Construct a frontend-friendly representation of the tasks.
(mapcar #'response-for (sort-tasks (list-tasks)))))
;; Task completion handler
(hunchentoot:define-easy-handler
(complete-task-handler :uri "/complete") (task)
(setf (hunchentoot:content-type*) "application/json")
(let* ((key (find-symbol (camel-case-to-lisp task) "GEMMA")))
(format t "Marking task ~A as completed" key)
(complete-task key)
(encode-json-to-string (response-for (get-task key))))))
(defun main ()
"This function serves as the entrypoint for ASDF-built executables.
It joins the Hunchentoot server thread to keep the process running
for as long as the server is alive."
(start-gemma)
(sb-thread:join-thread
(find-if (lambda (th)
(string= (sb-thread:thread-name th)
(format nil "hunchentoot-listener-*:~A" *gemma-port*)))
(sb-thread:list-all-threads))))
;; Experimentation / testing stuff
(defun randomise-completion-times ()
"Set some random completion timestamps for all tasks"
(mapcar
(lambda (task)
(complete-task (name-of task)
(timestamp- (now)
(random 14)
:day)))
(cl-prevalence:find-all-objects *p-tasks* 'task)))
(defun clear-all-tasks ()
(mapcar (lambda (task) (cl-prevalence:tx-delete-object *p-tasks* 'task (id task)))
(cl-prevalence:find-all-objects *p-tasks* 'task)))
;; (randomise-completion-times)

34
third_party/tvl/fun/idual/README.md vendored Normal file
View file

@ -0,0 +1,34 @@
# iDual light control
This folder contains some tooling for controlling iDual LED lights
(which use infrared controls) using a "Broadlink RM Pro" infrared
controller.
The supported colour codes of the iDual remote are stored in
`codes.txt`.
The point of this is to make it possible for me to automate my lights
in the morning, so that I can actually get out of bed.
## Capturing codes
Capturing codes is relatively easy, assuming that the broadlink device
is set up:
```python
import broadlink
import base64
devices = broadlink.discover(timeout=5)
devices[0].auth()
```
For each code, the procedure is as follows:
```python
devices[0].find_rf_packet()
# wait until this returns True
devices[0].check_data()
# this will return the code
```

24
third_party/tvl/fun/idual/default.nix vendored Normal file
View file

@ -0,0 +1,24 @@
{ pkgs, lib, ... }:
let
inherit (pkgs) python python3 python3Packages;
opts = {
pname = "idualctl";
version = "0.1";
src = ./.;
propagatedBuildInputs = [
python.broadlink
];
};
package = python3Packages.buildPythonPackage opts;
script = python3Packages.buildPythonApplication opts;
in {
inherit script;
python = python3.withPackages (_: [ package ]);
setAlarm = pkgs.writeShellScriptBin "set-alarm" ''
echo "setting an alarm for ''${1}"
${pkgs.systemd}/bin/systemd-run --user --on-calendar="''${1} Europe/London" --unit=light-alarm.service
'';
}

View file

@ -0,0 +1,65 @@
import base64
import broadlink
import time
import sys
commands = {
# system commands
'on' : 'JgBIAAABK5AVERQ2FBEUERQSFBEUERQSFBEUNhQ2FDUUNhQ2FDYUNRU1FBIUERQRFBIUERQRFBIUERQ2FDYUNRQ2FDYUNhQ1FQANBQ==',
'off' : 'JgBIAAABLJAUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDUVNRQ2FDYUNhQRFDYUERQSFBEUERQSFBEUNhQRFDYUNhQ2FDUUNhQ2FAANBQ==',
'darker' : 'JgBIAAABLI8VERQ2FBEUERURFBEUEhQRFBEUNhQ2FDYUNRU1FDYUNhQRFBIUERQRFDYUEhQRFBEVNRQ2FDYUNhQRFDYUNhQ1FQANBQ==',
'brighter' : 'JgBIAAABLI8VERQ2FBEUERQSFBEUEhQRFBEUNhQ2FDUVNRQ2FDYUNRU1FBIUERQ2FBEUEhQRFBEUEhQ1FTUUEhQ1FTUUNhQ2FAANBQ==',
# presets
'candle' : 'JgBQAAABKZISExI4EhMSFBITEhQRFBITEhQROBI4EjgSOBE4EjgSOBI4ERQSExIUEjgRFBITEhQSExI4EjgROBIUEjcSOBI4EgAFJgABKUkSAA0FAAAAAAAAAAA=',
'bulb' : 'JgBYAAABK5AUERQ2FBEVERQRFBEVERQRFBEVNRQ2FDYUNRU1FDYUNhQRFDYUNRURFBEUEhQRFBEUNhQRFREUNhQ1FDYUNhQ2FAAFIwABKkgVAAxOAAErRxUADQU=',
'sun' : 'JgBQAAABLI8VERQ2FBEUERURFBEUEhQRFBEUNhQ2FDYUNRU1FTUUNhQSFDUUEhQ2FBEUERURFBEUNhQSFDUUEhQ2FDUVNRQ2FAAFJQABK0cVAA0FAAAAAAAAAAA=',
'cold' : 'JgBQAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDYUNRQ2FDYUNhQ1FTUUEhQRFBEUEhQRFBIUERQRFDYUNhQ2FDYUNRQ2FAAFJAABK0cVAA0FAAAAAAAAAAA=',
'eve_dark' : 'JgBQAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDYUNRU1FDYUNhQRFDYUERQSFDUUEhQRFBIUNRQSFDUUNhQSFDUUNhQ2FAAFIwABLEYVAA0FAAAAAAAAAAA=',
'eve_fade' : 'JgBIAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDYUNRQ2FDYUNhQ1FDYUNhQRFDYUERQSFBEUEhQRFBEUNhQSEzYUNhQ2FAANBQ==',
'reading' : 'JgBQAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDUVNRQ2FDYUNhQ1FDYUEhQ1FBIUERQRFBIUERQSFDUUEhQ1FTUUNhQ2FAAFJAABK0YVAA0FAAAAAAAAAAA=',
'yoga' : 'JgBYAAABLI8VERQ1FREUERQSFBEUERURFBEUNhQ1FTUUNhQ2FDYUNRURFBEUNhQRFBIUERMSExMTNxM2ExMTNxM2EzcTNxM3EwAFJQABKkgTAAxRAAErRxUADQU=',
'morning' : 'JgBQAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDUVNRQ2FDYUNRU1FDYUERURFDUVERQRFBIUERQRFTUUNhQRFDYUNhQ2FAAFIwABK0cVAA0FAAAAAAAAAAA=',
'colours' : 'JgBQAAABLI8VERQ2FBEUERQSFBEUERURFBEUNhQ1FTUUNhQ2FDYUNRQSFBEUERQ2FDYUERQSFBEUNhQ1FTUUEhQRFDYUNRU1FAAFJAABKkcVAA0FAAAAAAAAAAA=',
'random' : 'JgBQAAABK5AUEhQ1FREUERQSFBEUERQSExIUNhQ1EzcTNxM3EzYTNxMTEhMTNxM2ExMTEhMSExMTNxM2ExMTEhM3EzcTNhM3EwAFJQABK0cVAA0FAAAAAAAAAAA=',
'island' : 'JgBQAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDUVNRQ2FDYUNRU1FBIUNRURFBEUEhQRFBEUEhQ1FREUNhQ1FDYUNhQ2FAAFIwABK0cVAA0FAAAAAAAAAAA=',
'forest' : 'JgBQAAABK5AUEhQ1FREUERQSFBEUERQSFBEUNhQ1FTUUNhQ2FDUVNRQSFBEUNhQRFDYUERQSFBEUNhQ2FBEUNhQRFDYUNhQ1FQAFIwABK0cVAA0FAAAAAAAAAAA=',
'ocean' : 'JgBQAAABK5AUEhQ1FREUERQSFBEUERQRFREUNhQ1FTUUNhQ2FDUVNRQ2FBEUEhQ1FTUUEhQRFBEUEhQ1FTUUEhQRFDYUNRU1FAAFJAABK0cVAA0FAAAAAAAAAAA=',
'fire' : 'JgBQAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDUVNRQ2FDYUNRU1FBIUNRU1FBIUERQRFBIUERQ2FBEUEhQ1FTUUNhQ2FAAFIwABLEYVAA0FAAAAAAAAAAA=',
'love' : 'JgBQAAABL5AUEhQ1FREUERQSFBEUERQSFBEUNhQ1FDYUNhQ2FDUVNRQSFDUUNhQSFBEUERQSFBEUNhQRFBIUNRQ2FDYUNhQ1FAAFJAABK0cVAA0FAAAAAAAAAAA=',
# colour commands
'red' : 'JgBIAAABK5AUERQ2FBEUEhQRFBEVERQRFBEUNhQ2FDYUNRU1FDYUNhQRFDYUNhQ1FREUERQSFBEUNhQRFBIUERQ2FDUVNRQ2FAANBQ==',
'yellow' : 'JgBIAAABLI8UEhQ2FBEUERQSFBEUEhMSFBEUNhQ2FDUUNhQ2FDYUNRQ2FDYUNhQRFBIUERQRFBIUERQSExIUNhQ1FDYUNhQ2FAANBQ==',
'green' : 'JgBIAAABK5AUEhQ1FREUERQSFBEUERQSFBEUNhQ1FDYUNhQ2FDUVNRQSFBEUERQ2FBIUERQRFBIUNRU1FDYUERQ2FDYUNhQ1FQANBQ==',
'blue' : 'JgBIAAABK5AUERQ2FBEUEhQRFBITEhQRFBEUNhQ2FDYUNRQ2FDYUNhQ2ExIUNhQRFDYUERQSExIUERQ2FBEUNhQSEzYUNhQ2FAANBQ==',
'saturate' : 'JgBIAAABK5AUERQ2FBEUEhQRFBIUERQRFBEUNhQ2FDYUNRU1FDYUNhQRFDYUERQ2FDYUERQSFBEUNhQRFDYUERQSFDUUNhQ2FAANBQ==',
'desaturate' : 'JgBIAAABLI8VERQ2FBEUERQSFBEUERURFBEUNhQ1FTUUNhQ2FDYUNRQ2FDYUNhQ1FREUERQSFBEUERQSFBEUERQ2FDYUNhQ1FQANBQ==',
}
def cmd(name):
return base64.b64decode(commands[name])
class LightController:
def __init__(self):
self.devices = broadlink.discover(timeout=10, max_devices=2)
if self.devices == []:
raise Exception('no devices found')
for device in self.devices:
device.auth()
def send_cmd(self, name, iterations=5):
"Send a command, repeatedly for reliability"
packet = cmd(name)
for i in range(iterations):
for device in self.devices:
device.send_data(packet)
def wakey(self):
"Turn on the lights in the morning, try repeatedly for reasons."
print('Turning on the lights. Wakey, wakey!')
for i in range(5):
self.send_cmd('random')
time.sleep(0.3)
self.send_cmd('on')
time.sleep(0.3)

39
third_party/tvl/fun/idual/idualctl vendored Normal file
View file

@ -0,0 +1,39 @@
#!/usr/bin/env python
import idual
import sys
def help():
print('Available commands:')
for cmd in idual.commands:
print('- ' + cmd)
sys.exit(0)
def handle(ctrl, cmd):
if cmd == 'help':
help()
elif cmd == 'wakey':
ctrl.wakey()
sys.exit(0)
elif cmd == 'on':
print('Turning on the lights')
ctrl.send_cmd(cmd)
elif cmd == 'off':
print('Turning off the lights')
ctrl.send_cmd(cmd)
elif cmd in idual.commands:
print('Sending ' + cmd + '-command')
ctrl.send_cmd(cmd)
else:
print('unknown command \'' + cmd + '\'')
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) == 1:
help()
print('Initialising light controller')
ctrl = idual.LightController()
for cmd in sys.argv[1:]:
handle(ctrl, cmd)

15
third_party/tvl/fun/idual/setup.py vendored Normal file
View file

@ -0,0 +1,15 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='idualctl',
version='0.1',
author='Vincent Ambo',
author_email='mail@tazj.in',
url='https://git.tazj.in/about/fun/idual',
packages=['idual'],
scripts = ['idualctl'],
install_requires=['broadlink>=0.13.2'],
include_package_data=True,
)

BIN
third_party/tvl/fun/logo/depot-logo.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

BIN
third_party/tvl/fun/logo/depot-logo.xcf vendored Normal file

Binary file not shown.

View file

@ -0,0 +1,5 @@
/target
irc.toml
paroxysm-irc.toml
paroxysm.toml
**/*.rs.bk

1553
third_party/tvl/fun/paroxysm/Cargo.lock generated vendored Normal file

File diff suppressed because it is too large Load diff

22
third_party/tvl/fun/paroxysm/Cargo.toml vendored Normal file
View file

@ -0,0 +1,22 @@
[package]
authors = ["eeeeeta <eta@theta.eu.org>"]
edition = "2018"
name = "paroxysm"
version = "0.1.0"
[dependencies]
chrono = "0.4"
config = "0.9"
crimp = "0.2"
env_logger = "0.7"
failure = "0.1"
irc = "0.13"
lazy_static = "1.4"
log = "0.4"
rand = "0.7"
regex = "1.3"
serde = { version = "1.0", features = [ "derive" ] }
[dependencies.diesel]
features = [ "postgres", "chrono", "r2d2" ]
version = "1.4"

3
third_party/tvl/fun/paroxysm/OWNERS vendored Normal file
View file

@ -0,0 +1,3 @@
inherited: true
owners:
- eta

19
third_party/tvl/fun/paroxysm/README.md vendored Normal file
View file

@ -0,0 +1,19 @@
paroxysm
========
`paroxysm` is a bot for [internet relay chat
(IRC)](https://en.wikipedia.org/wiki/Internet_Relay_Chat) that lets you store
small pieces of information, called *factoids*, and retrieve them later. It's
useful for organising frequently-used information to avoid repeating oneself in
a busy chatroom, as well as making little todo lists or notes to self in a
private chatroom.
It was directly inspired by the
[LearnDB](https://github.com/crawl/sequell/blob/master/docs/learndb.md)
functionality offered in `##crawl` on chat.freenode.net, and uses similar
syntax.
## Usage instructions
Will come soon; the project is very much still in beta, and is subject to
change.

View file

@ -0,0 +1,17 @@
{ depot, ... }:
let
pkgs = depot.third_party;
in
pkgs.naersk.buildPackage {
name = "paroxysm";
version = "0.0.2";
src = ./.;
buildInputs = with pkgs; [
openssl
pkgconfig
postgresql.lib
curl
];
}

View file

@ -0,0 +1,7 @@
{ depot, ... }:
depot.third_party.dockerTools.buildLayeredImage {
name = "paroxysm";
contents = [ depot.fun.paroxysm ];
config.Entrypoint = [ "${depot.fun.paroxysm}/bin/paroxysm" ];
}

View file

@ -0,0 +1,2 @@
DROP TABLE entries;
DROP TABLE keywords;

View file

@ -0,0 +1,15 @@
CREATE TABLE keywords (
id SERIAL PRIMARY KEY,
name VARCHAR UNIQUE NOT NULL,
chan VARCHAR NOT NULL,
UNIQUE(name, chan)
);
CREATE TABLE entries (
id SERIAL PRIMARY KEY,
keyword_id INT NOT NULL REFERENCES keywords ON DELETE CASCADE,
idx INT NOT NULL,
text VARCHAR NOT NULL,
creation_ts TIMESTAMP NOT NULL,
created_by VARCHAR NOT NULL
);

View file

@ -0,0 +1 @@
-- This file should undo anything in `up.sql`

View file

@ -0,0 +1 @@
ALTER TABLE keywords DROP CONSTRAINT IF EXISTS keywords_name_key;

12
third_party/tvl/fun/paroxysm/src/cfg.rs vendored Normal file
View file

@ -0,0 +1,12 @@
use serde::Deserialize;
use std::collections::HashSet;
#[derive(Deserialize)]
pub struct Config {
pub database_url: String,
pub irc_config_path: String,
#[serde(default)]
pub admins: HashSet<String>,
#[serde(default)]
pub log_filter: Option<String>,
}

View file

@ -0,0 +1,220 @@
use crate::models::{Entry, Keyword, NewEntry, NewKeyword};
use diesel::pg::PgConnection;
use diesel::prelude::*;
use failure::format_err;
use failure::Error;
use std::borrow::Cow;
/// Maximum number of times we'll follow a `see: ` pointer.
const RECURSION_LIMIT: usize = 5;
pub struct KeywordDetails {
pub keyword: Keyword,
pub entries: Vec<Entry>,
}
impl KeywordDetails {
pub fn learn(&mut self, nick: &str, text: &str, dbc: &PgConnection) -> Result<usize, Error> {
let now = ::chrono::Utc::now().naive_utc();
let ins = NewEntry {
keyword_id: self.keyword.id,
idx: (self.entries.len() + 1) as _,
text,
creation_ts: now,
created_by: nick,
};
let new = {
use crate::schema::entries;
::diesel::insert_into(entries::table)
.values(ins)
.get_result(dbc)?
};
self.entries.push(new);
Ok(self.entries.len())
}
pub fn process_moves(&mut self, moves: &[(i32, i32)], dbc: &PgConnection) -> Result<(), Error> {
for (oid, new_idx) in moves {
{
use crate::schema::entries::dsl::*;
::diesel::update(entries.filter(id.eq(oid)))
.set(idx.eq(new_idx))
.execute(dbc)?;
}
}
self.entries = Self::get_entries(self.keyword.id, dbc)?;
Ok(())
}
pub fn swap(&mut self, idx_a: usize, idx_b: usize, dbc: &PgConnection) -> Result<(), Error> {
let mut moves = vec![];
for ent in self.entries.iter() {
if ent.idx == idx_a as i32 {
moves.push((ent.id, idx_b as i32));
}
if ent.idx == idx_b as i32 {
moves.push((ent.id, idx_a as i32));
}
}
if moves.len() != 2 {
Err(format_err!("Invalid swap operation."))?;
}
self.process_moves(&moves, dbc)?;
Ok(())
}
pub fn update(&mut self, idx: usize, val: &str, dbc: &PgConnection) -> Result<(), Error> {
let ent = self
.entries
.get_mut(idx.saturating_sub(1))
.ok_or(format_err!("No such element to update."))?;
{
use crate::schema::entries::dsl::*;
::diesel::update(entries.filter(id.eq(ent.id)))
.set(text.eq(val))
.execute(dbc)?;
}
ent.text = val.to_string();
Ok(())
}
pub fn delete(&mut self, idx: usize, dbc: &PgConnection) -> Result<(), Error> {
// step 1: delete the element
{
let ent = self
.entries
.get(idx.saturating_sub(1))
.ok_or(format_err!("No such element to delete."))?;
{
use crate::schema::entries::dsl::*;
::diesel::delete(entries.filter(id.eq(ent.id))).execute(dbc)?;
}
}
// step 2: move all the elements in front of it back one
let mut moves = vec![];
for ent in self.entries.iter() {
if idx > ent.idx as _ {
moves.push((ent.id, ent.idx.saturating_sub(1)));
}
}
self.process_moves(&moves, dbc)?;
Ok(())
}
pub fn add_zwsp_to_name(name: &str) -> Option<String> {
let second_index = name.char_indices().nth(1).map(|(i, _)| i)?;
let (start, end) = name.split_at(second_index);
Some(format!("{}{}", start, end))
}
pub fn format_entry(&self, idx: usize) -> Option<String> {
self.format_entry_colours(idx, true)
}
pub fn format_entry_colours(&self, idx: usize, with_colours: bool) -> Option<String> {
if let Some(ent) = self.entries.get(idx.saturating_sub(1)) {
let gen_clr = if self.keyword.chan == "*" && with_colours {
"\x0307"
} else {
""
};
let zwsp_name = Self::add_zwsp_to_name(&self.keyword.name)
.unwrap_or_else(|| self.keyword.name.clone());
Some(format!(
"{}{}{name}{}[{idx}/{total}]{}: {text} {}[{date}]{}",
if with_colours { "\x02" } else { "" },
gen_clr,
if with_colours { "\x0f\x0315" } else { "" },
if with_colours { "\x0f" } else { "" },
if with_colours { "\x0f\x0314" } else { "" },
if with_colours { "\x0f" } else { "" },
name = zwsp_name,
idx = idx,
total = self.entries.len(),
text = ent.text,
date = ent.creation_ts.date()
))
} else {
None
}
}
pub fn get_or_create(word: &str, c: &str, dbc: &PgConnection) -> Result<Self, Error> {
if let Some(ret) = Self::get(word, c, dbc)? {
Ok(ret)
} else {
Ok(Self::create(word, c, dbc)?)
}
}
pub fn create(word: &str, c: &str, dbc: &PgConnection) -> Result<Self, Error> {
let val = NewKeyword {
name: word,
chan: c,
};
let ret: Keyword = {
use crate::schema::keywords;
::diesel::insert_into(keywords::table)
.values(val)
.get_result(dbc)?
};
Ok(KeywordDetails {
keyword: ret,
entries: vec![],
})
}
fn get_entries(kid: i32, dbc: &PgConnection) -> Result<Vec<Entry>, Error> {
let entries: Vec<Entry> = {
use crate::schema::entries::dsl::*;
entries
.filter(keyword_id.eq(kid))
.order_by(idx.asc())
.load(dbc)?
};
Ok(entries)
}
fn get_inner<'a, T: Into<Cow<'a, str>>>(
word: T,
c: &str,
dbc: &PgConnection,
recursion_count: usize,
) -> Result<Option<Self>, Error> {
let word = word.into();
let keyword: Option<Keyword> = {
use crate::schema::keywords::dsl::*;
keywords
.filter(name.ilike(word).and(chan.eq(c).or(chan.eq("*"))))
.first(dbc)
.optional()?
};
if let Some(k) = keyword {
let entries = Self::get_entries(k.id, dbc)?;
if let Some(e0) = entries.get(0) {
if e0.text.starts_with("see: ") {
if recursion_count > RECURSION_LIMIT {
// Oh dear.
Err(format_err!("Halt. You're having a bit too much fun."))?
}
let new_word = e0.text.replace("see: ", "");
return Self::get_inner(new_word, c, dbc, recursion_count + 1);
}
}
Ok(Some(KeywordDetails {
keyword: k,
entries,
}))
} else {
Ok(None)
}
}
pub fn get<'a, T: Into<Cow<'a, str>>>(
word: T,
c: &str,
dbc: &PgConnection,
) -> Result<Option<Self>, Error> {
Self::get_inner(word, c, dbc, 0)
}
}

391
third_party/tvl/fun/paroxysm/src/main.rs vendored Normal file
View file

@ -0,0 +1,391 @@
// TODO(tazjin): Upgrade to a Diesel version with public derive
// macros.
#[macro_use]
extern crate diesel;
use crate::cfg::Config;
use crate::keyword::KeywordDetails;
use diesel::pg::PgConnection;
use diesel::r2d2::{ConnectionManager, Pool};
use failure::format_err;
use failure::Error;
use irc::client::prelude::*;
use lazy_static::lazy_static;
use log::{debug, info, warn};
use rand::rngs::ThreadRng;
use rand::{thread_rng, Rng};
use regex::{Captures, Regex};
use std::collections::HashMap;
use std::fmt::Display;
mod cfg;
mod keyword;
mod models;
mod schema;
lazy_static! {
static ref LEARN_RE: Regex =
Regex::new(r#"^\?\?(?P<gen>!)?\s*(?P<subj>[^\[:]*):\s*(?P<val>.*)"#).unwrap();
static ref QUERY_RE: Regex =
Regex::new(r#"^\?\?\s*(?P<subj>[^\[:]*)(?P<idx>\[[^\]]+\])?"#).unwrap();
static ref QLAST_RE: Regex = Regex::new(r#"^\?\?\s*(?P<subj>[^\[:]*)!"#).unwrap();
static ref INCREMENT_RE: Regex =
Regex::new(r#"^\?\?(?P<gen>!)?\s*(?P<subj>[^\[:]*)(?P<incrdecr>\+\+|\-\-)"#).unwrap();
static ref MOVE_RE: Regex =
Regex::new(r#"^\?\?(?P<gen>!)?\s*(?P<subj>[^\[:]*)(?P<idx>\[[^\]]+\])->(?P<new_idx>.*)"#)
.unwrap();
}
pub struct App {
client: IrcClient,
pg: Pool<ConnectionManager<PgConnection>>,
rng: ThreadRng,
cfg: Config,
last_msgs: HashMap<String, HashMap<String, String>>,
}
impl App {
pub fn report_error<T: Display>(
&mut self,
nick: &str,
chan: &str,
msg: T,
) -> Result<(), Error> {
self.client
.send_notice(nick, format!("[{}] \x0304Error:\x0f {}", chan, msg))?;
Ok(())
}
pub fn keyword_from_captures(
&mut self,
learn: &::regex::Captures,
nick: &str,
chan: &str,
) -> Result<KeywordDetails, Error> {
let db = self.pg.get()?;
debug!("Fetching keyword for captures: {:?}", learn);
let subj = &learn["subj"];
let learn_chan = if learn.name("gen").is_some() {
"*"
} else {
chan
};
if !chan.starts_with("#") && learn_chan != "*" {
Err(format_err!("Only general entries may be taught via PM."))?;
}
debug!("Fetching keyword '{}' for chan {}", subj, learn_chan);
let kwd = KeywordDetails::get_or_create(subj, learn_chan, &db)?;
if kwd.keyword.chan == "*" && !self.cfg.admins.contains(nick) {
Err(format_err!(
"Only administrators can create or modify general entries."
))?;
}
Ok(kwd)
}
pub fn handle_move(
&mut self,
target: &str,
nick: &str,
chan: &str,
mv: Captures,
) -> Result<(), Error> {
let db = self.pg.get()?;
let idx = &mv["idx"];
let idx = match idx[1..(idx.len() - 1)].parse::<usize>() {
Ok(i) => i,
Err(e) => Err(format_err!("Could not parse index: {}", e))?,
};
let new_idx = match mv["new_idx"].parse::<i32>() {
Ok(i) => i,
Err(e) => Err(format_err!("Could not parse target index: {}", e))?,
};
let mut kwd = self.keyword_from_captures(&mv, nick, chan)?;
if new_idx < 0 {
kwd.delete(idx, &db)?;
self.client.send_notice(
target,
format!("\x02{}\x0f: Deleted entry {}.", kwd.keyword.name, idx),
)?;
} else {
kwd.swap(idx, new_idx as _, &db)?;
self.client.send_notice(
target,
format!(
"\x02{}\x0f: Swapped entries {} and {}.",
kwd.keyword.name, idx, new_idx
),
)?;
}
Ok(())
}
pub fn handle_learn(
&mut self,
target: &str,
nick: &str,
chan: &str,
learn: Captures,
) -> Result<(), Error> {
let db = self.pg.get()?;
let val = &learn["val"];
let mut kwd = self.keyword_from_captures(&learn, nick, chan)?;
let idx = kwd.learn(nick, val, &db)?;
self.client
.send_notice(target, kwd.format_entry(idx).unwrap())?;
Ok(())
}
pub fn handle_insert_last_quote(
&mut self,
target: &str,
nick: &str,
chan: &str,
qlast: Captures,
) -> Result<(), Error> {
let db = self.pg.get()?;
let nick_to_grab = &qlast["subj"].to_ascii_lowercase();
let mut kwd = self.keyword_from_captures(&qlast, nick, chan)?;
let chan_lastmsgs = self
.last_msgs
.entry(chan.to_string())
.or_insert(HashMap::new());
// Use `nick` here, so things like "grfn: see glittershark" work.
let val = if let Some(last) = chan_lastmsgs.get(nick_to_grab) {
if last.starts_with("\x01ACTION ") {
// Yes, this is inefficient, but it's better than writing some hacky CTCP parsing code
// I guess (also, characters are hard, so just blindly slicing seems like a bad idea)
format!(
"* {} {}",
nick_to_grab,
last.replace("\x01ACTION ", "").replace("\x01", "")
)
} else {
format!("<{}> {}", nick_to_grab, last)
}
} else {
Err(format_err!("I dunno what {} said...", kwd.keyword.name))?
};
let idx = kwd.learn(nick, &val, &db)?;
self.client
.send_notice(target, kwd.format_entry(idx).unwrap())?;
Ok(())
}
pub fn handle_increment(
&mut self,
target: &str,
nick: &str,
chan: &str,
icr: Captures,
) -> Result<(), Error> {
let db = self.pg.get()?;
let mut kwd = self.keyword_from_captures(&icr, nick, chan)?;
let is_incr = &icr["incrdecr"] == "++";
let now = chrono::Utc::now().naive_utc().date();
let mut idx = None;
for (i, ent) in kwd.entries.iter().enumerate() {
if ent.creation_ts.date() == now {
if let Ok(val) = ent.text.parse::<i32>() {
let val = if is_incr { val + 1 } else { val - 1 };
idx = Some((i + 1, val));
}
}
}
if let Some((i, val)) = idx {
kwd.update(i, &val.to_string(), &db)?;
self.client
.send_notice(target, kwd.format_entry(i).unwrap())?;
} else {
let val = if is_incr { 1 } else { -1 };
let idx = kwd.learn(nick, &val.to_string(), &db)?;
self.client
.send_notice(target, kwd.format_entry(idx).unwrap())?;
}
Ok(())
}
pub fn handle_query(
&mut self,
target: &str,
nick: &str,
chan: &str,
query: Captures,
) -> Result<(), Error> {
let db = self.pg.get()?;
let subj = &query["subj"];
let idx = match query.name("idx") {
Some(i) => {
let i = i.as_str();
match &i[1..(i.len() - 1)] {
"*" => Some(-1),
x => x.parse::<usize>().map(|x| x as i32).ok(),
}
}
None => None,
};
debug!("Querying {} with idx {:?}", subj, idx);
match KeywordDetails::get(subj, chan, &db)? {
Some(kwd) => {
if let Some(mut idx) = idx {
if idx == -1 {
// 'get all entries' ('*' parses into this)
// step 1: make a blob of all the quotes
let mut data_to_upload = String::new();
for i in 0..kwd.entries.len() {
data_to_upload
.push_str(&kwd.format_entry_colours(i + 1, false).unwrap());
data_to_upload.push('\n');
}
// step 2: attempt to POST it to eta's pastebin
// TODO(eta): make configurable
let response = crimp::Request::put("https://theta.eu.org/lx/upload")
.user_agent("paroxysm/0.0.2 crimp/0.2")?
.header("Linx-Expiry", "7200")? // 2 hours
.body("text/plain", data_to_upload.as_bytes())
.timeout(std::time::Duration::from_secs(2))?
.send()?
.as_string()?;
// step 3: tell the world about it
if response.status != 200 {
Err(format_err!(
"upload returned {}: {}",
response.status,
response.body
))?
}
self.client.send_notice(
target,
format!(
"\x02{}\x0f: uploaded {} quotes to \x02\x0311{}\x0f (will expire in \x0224\x0f hours)",
subj,
kwd.entries.len(),
response.body
)
)?;
} else {
if idx == 0 {
idx = 1;
}
if let Some(ent) = kwd.format_entry(idx as _) {
self.client.send_notice(target, ent)?;
} else {
let pluralised = if kwd.entries.len() == 1 {
"entry"
} else {
"entries"
};
self.client.send_notice(
target,
format!(
"\x02{}\x0f: only has \x02\x0304{}\x0f {}",
subj,
kwd.entries.len(),
pluralised
),
)?;
}
}
} else {
let entry = if kwd.entries.len() < 2 {
1 // because [1, 1) does not a range make
} else {
self.rng.gen_range(1, kwd.entries.len())
};
if let Some(ent) = kwd.format_entry(entry) {
self.client.send_notice(target, ent)?;
} else {
self.client
.send_notice(target, format!("\x02{}\x0f: no entries yet", subj))?;
}
}
}
None => {
self.client
.send_notice(target, format!("\x02{}\x0f: never heard of it", subj))?;
}
}
Ok(())
}
pub fn handle_privmsg(&mut self, from: &str, chan: &str, msg: &str) -> Result<(), Error> {
let nick = from.split("!").next().ok_or(format_err!(
"Received PRIVMSG from a source without nickname (failed to split n!u@h)"
))?;
let target = if chan.starts_with("#") { chan } else { nick };
debug!("[{}] <{}> {}", chan, nick, msg);
if let Some(learn) = LEARN_RE.captures(msg) {
self.handle_learn(target, nick, chan, learn)?;
} else if let Some(qlast) = QLAST_RE.captures(msg) {
self.handle_insert_last_quote(target, nick, chan, qlast)?;
} else if let Some(mv) = MOVE_RE.captures(msg) {
self.handle_move(target, nick, chan, mv)?;
} else if let Some(icr) = INCREMENT_RE.captures(msg) {
self.handle_increment(target, nick, chan, icr)?;
} else if let Some(query) = QUERY_RE.captures(msg) {
self.handle_query(target, nick, chan, query)?;
} else {
let chan_lastmsgs = self
.last_msgs
.entry(chan.to_string())
.or_insert(HashMap::new());
chan_lastmsgs.insert(nick.to_string().to_ascii_lowercase(), msg.to_string());
}
Ok(())
}
pub fn handle_msg(&mut self, m: Message) -> Result<(), Error> {
match m.command {
Command::PRIVMSG(channel, message) => {
if let Some(src) = m.prefix {
if let Err(e) = self.handle_privmsg(&src, &channel, &message) {
warn!("error handling command in {} (src {}): {}", channel, src, e);
if let Some(nick) = src.split("!").next() {
self.report_error(nick, &channel, e)?;
}
}
}
}
Command::INVITE(nick, channel) => {
if self.cfg.admins.contains(&nick) {
info!("Joining {} after admin invite", channel);
self.client.send_join(channel)?;
}
}
_ => {}
}
Ok(())
}
}
fn main() -> Result<(), Error> {
println!("[+] loading configuration");
let default_log_filter = "paroxysm=info".to_string();
let mut settings = config::Config::default();
settings.merge(config::Environment::with_prefix("PARX"))?;
let cfg: Config = settings.try_into()?;
let env = env_logger::Env::new()
.default_filter_or(cfg.log_filter.clone().unwrap_or(default_log_filter));
env_logger::init_from_env(env);
info!("paroxysm starting up");
info!("connecting to database at {}", cfg.database_url);
let pg = Pool::new(ConnectionManager::new(&cfg.database_url))?;
info!("connecting to IRC using config {}", cfg.irc_config_path);
let client = IrcClient::new(&cfg.irc_config_path)?;
client.identify()?;
let st = client.stream();
let mut app = App {
client,
pg,
cfg,
rng: thread_rng(),
last_msgs: HashMap::new(),
};
info!("running!");
st.for_each_incoming(|m| {
if let Err(e) = app.handle_msg(m) {
warn!("Error processing message: {}", e);
}
})?;
Ok(())
}

View file

@ -0,0 +1,36 @@
use crate::schema::{entries, keywords};
use chrono::NaiveDateTime;
#[derive(Queryable)]
pub struct Keyword {
pub id: i32,
pub name: String,
pub chan: String,
}
#[derive(Queryable)]
pub struct Entry {
pub id: i32,
pub keyword_id: i32,
pub idx: i32,
pub text: String,
pub creation_ts: NaiveDateTime,
pub created_by: String,
}
#[derive(Insertable)]
#[table_name = "keywords"]
pub struct NewKeyword<'a> {
pub name: &'a str,
pub chan: &'a str,
}
#[derive(Insertable)]
#[table_name = "entries"]
pub struct NewEntry<'a> {
pub keyword_id: i32,
pub idx: i32,
pub text: &'a str,
pub creation_ts: NaiveDateTime,
pub created_by: &'a str,
}

View file

@ -0,0 +1,18 @@
table! {
entries (id) {
id -> Int4,
keyword_id -> Int4,
idx -> Int4,
text -> Varchar,
creation_ts -> Timestamp,
created_by -> Varchar,
}
}
table! {
keywords (id) {
id -> Int4,
name -> Varchar,
chan -> Varchar,
}
}

View file

@ -0,0 +1,2 @@
.idea/
quinistry

Some files were not shown because too many files have changed in this diff Show more