init: pristine aerc 0.20.0 source

This commit is contained in:
Mortdecai
2026-04-07 19:54:54 -04:00
commit 083402a548
502 changed files with 68722 additions and 0 deletions
+16
View File
@@ -0,0 +1,16 @@
[Desktop Entry]
Version=1.0
Name=aerc
GenericName=Mail Client
GenericName[de]=Email Client
Comment=Launches the aerc email client
Comment[de]=Startet den aerc Email-Client
Keywords=Email,Mail,IMAP,SMTP
Categories=Office;Network;Email;ConsoleOnly
Type=Application
Icon=utilities-terminal
Terminal=true
Exec=aerc %u
MimeType=x-scheme-handler/mailto
+268
View File
@@ -0,0 +1,268 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# Copyright (c) 2023 Robin Jarry
"""
Query a CardDAV server for contact names and emails.
"""
import argparse
import base64
import configparser
import os
import re
import subprocess
import sys
import xml.etree.ElementTree as xml
from urllib import error, parse, request
def main():
try:
args = parse_args()
C = "urn:ietf:params:xml:ns:carddav"
D = "DAV:"
xml.register_namespace("C", C)
xml.register_namespace("D", D)
# perform the actual address book query
query = xml.Element(f"{{{C}}}addressbook-query")
prop = xml.SubElement(query, f"{{{D}}}prop")
xml.SubElement(prop, f"{{{D}}}getetag")
data = xml.SubElement(prop, f"{{{C}}}address-data")
xml.SubElement(data, f"{{{C}}}prop", name="FN")
xml.SubElement(data, f"{{{C}}}prop", name="EMAIL")
limit = xml.SubElement(query, f"{{{C}}}limit")
xml.SubElement(limit, f"{{{C}}}nresults").text = str(args.limit)
filtre = xml.SubElement(query, f"{{{C}}}filter", test="anyof")
for term in args.terms:
for attr in "FN", "EMAIL", "NICKNAME", "ORG", "TITLE":
prop = xml.SubElement(filtre, f"{{{C}}}prop-filter", name=attr)
match = xml.SubElement(
prop, f"{{{C}}}text-match", {"match-type": "contains"}
)
match.text = term
data = http_request_xml(
"REPORT",
args.server_url,
query,
username=args.username,
password=args.password,
debug=args.verbose,
Depth="1",
)
for vcard in data.iterfind(f".//{{{C}}}address-data"):
for name, email in parse_vcard(vcard.text.strip()):
print(f"{email}\t{name}")
except Exception as e:
if isinstance(e, error.HTTPError):
if args.verbose:
debug_response(e.fp)
e = e.fp.read().decode()
print(f"error: {e}", file=sys.stderr)
sys.exit(1)
def http_request_xml(
method: str,
url: str,
data: xml.Element,
username: str = None,
password: str = None,
debug: bool = False,
**headers,
) -> xml.Element:
req = request.Request(
url=url,
method=method,
headers={
"Content-Type": 'text/xml; charset="utf-8"',
**headers,
},
data=xml.tostring(data, encoding="utf-8", xml_declaration=True),
)
if username is not None and password is not None:
auth = f"{username}:{password}"
auth = base64.standard_b64encode(auth.encode("utf-8")).decode("ascii")
req.add_header("Authorization", f"Basic {auth}")
if debug:
uri = parse.urlparse(req.full_url)
print(f"> {req.method} {uri.path} HTTP/1.1", file=sys.stderr)
print(f"> Host: {uri.hostname}", file=sys.stderr)
for name, value in req.headers.items():
print(f"> {name}: {value}", file=sys.stderr)
print(f"{req.data.decode('utf-8')}\n", file=sys.stderr)
with request.urlopen(req) as resp:
data = resp.read().decode("utf-8")
if debug:
debug_response(resp)
print(f"{data}", file=sys.stderr)
return xml.fromstring(data)
def debug_response(resp):
print(f"< HTTP/1.1 {resp.code}", file=sys.stderr)
for name, value in resp.headers.items():
print(f"< {name}: {value}", file=sys.stderr)
def parse_vcard(txt):
lines = txt.splitlines()
if len(lines) < 4 or lines[0] != "BEGIN:VCARD" or lines[-1] != "END:VCARD":
return
name = None
emails = []
for line in lines[1:-1]:
if line.startswith("FN:"):
name = line[len("FN:") :].replace("\\,", ",")
continue
match = re.match(r"^(?:ITEM\d+\.)?EMAIL(?:;[\w-]+=[^;:]+)*:(.+@.+)$", line)
if match:
email = match.group(1).lower().replace("\\,", ",")
if email not in emails:
if "TYPE=pref" in line or "PREF=1" in line:
emails.insert(0, email)
else:
emails.append(email)
if name is not None:
for e in emails:
yield name, e
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"-l",
"--limit",
default=10,
type=int,
help="""
Maximum number of results returned by the server (default: 10).
If the server does not support limiting, this will be disregarded.
""",
)
parser.add_argument(
"-v",
"--verbose",
action="store_true",
help="""
Print debug info on stderr.
""",
)
parser.add_argument(
"-c",
"--config-file",
metavar="FILE",
default=os.path.expanduser("~/.config/aerc/accounts.conf"),
help="""
INI configuration file from which to read the CardDAV URL endpoint
(default: ~/.config/aerc/accounts.conf).
""",
)
parser.add_argument(
"-S",
"--config-section",
metavar="SECTION",
help="""
INI configuration section where to find CONFIG_KEY. By default the
first section where CONFIG_KEY is found will be used.
""",
)
parser.add_argument(
"-k",
"--config-key-source",
metavar="KEY_SOURCE",
default="carddav-source",
help="""
INI configuration key to lookup in CONFIG_SECTION from CONFIG_FILE.
The value must respect the following format:
https?://USERNAME[:PASSWORD]@HOSTNAME/PATH/TO/ADDRESSBOOK.
Both USERNAME and PASSWORD must be percent encoded.
""",
)
parser.add_argument(
"-C",
"--config-key-cred-cmd",
metavar="KEY_CRED_CMD",
default="carddav-source-cred-cmd",
help="""
INI configuration key to lookup in CONFIG_SECTION from CONFIG_FILE. The
value is a command that will be used to determine PASSWORD if it is not
present in CONFIG_KEY_SOURCE.
""",
)
parser.add_argument(
"-s",
"--server-url",
help="""
CardDAV server URL endpoint. Overrides configuration file.
""",
)
parser.add_argument(
"-u",
"--username",
help="""
Username to authenticate on the server. Overrides configuration file.
""",
)
parser.add_argument(
"-p",
"--password",
help="""
Password for the specified user. Overrides configuration file.
""",
)
parser.add_argument(
"terms",
nargs="+",
metavar="TERM",
help="""
Search term. Will be used to search contacts from their FN (formatted
name), EMAIL, NICKNAME, ORG (company) and TITLE fields.
""",
)
args = parser.parse_args()
cfg = configparser.RawConfigParser(strict=False)
cfg.read([args.config_file])
source = cred_cmd = None
if args.config_section:
source = cfg.get(args.config_section, args.config_key_source, fallback=None)
cred_cmd = cfg.get(args.config_section, args.config_key_cred_cmd, fallback=None)
else:
for sec in cfg.sections():
source = cfg.get(sec, args.config_key_source, fallback=None)
if source is not None:
cred_cmd = cfg.get(sec, args.config_key_cred_cmd, fallback=None)
break
if source is not None:
try:
u = parse.urlparse(source)
if args.username is None and u.username is not None:
args.username = parse.unquote(u.username)
if args.password is None and u.password is not None:
args.password = parse.unquote(u.password)
if not args.password and cred_cmd is not None:
args.password = subprocess.check_output(
cred_cmd, shell=True, text=True, encoding="utf-8"
).strip()
if args.server_url is None:
args.server_url = f"{u.scheme}://{u.hostname}"
if u.port is not None:
args.server_url += f":{u.port}"
args.server_url += u.path
except ValueError as e:
parser.error(f"{args.config_file}: {e}")
if args.server_url is None:
parser.error("SERVER_URL is required")
return args
if __name__ == "__main__":
main()
+67
View File
@@ -0,0 +1,67 @@
#!/bin/sh
tmp=$(mktemp)
trap "rm -f $tmp" EXIT
global_fail=0
cmd_scd_sed='s/^\*:([a-z][a-z -]*)\*.*/\1/p'
cmd_go_sed='/^func ([[:alnum:]][[:alnum:]]*) Aliases() \[\]string {$/{n;
s/", "/ /g;
s/.*return \[\]string{"\(.*\)"}/\1/p
}'
grep_color=
if echo . | grep --color . >/dev/null 2>&1; then
grep_color=--color
fi
fail=0
sed -nE "$cmd_scd_sed" doc/*.scd | tr ' ' '\n' > "$tmp"
for f in $(find commands -type f -name '*.go'); do
for cmd in $(sed -n "$cmd_go_sed" "$f"); do
if ! grep -qFx "$cmd" "$tmp"; then
grep -HnF $grep_color "\"$cmd\"" "$f"
fail=$((fail+1))
fi
done
done
if [ "$fail" -gt 0 ]; then
echo "error: $fail command(s) not documented in man pages" >&2
global_fail=1
fi
fail=0
sed -n "$cmd_go_sed" $(find commands -type f -name '*.go') | tr ' ' '\n' > "$tmp"
for f in doc/*.scd; do
for cmd in $(sed -nE "$cmd_scd_sed" "$f" | tr ' ' '\n' | sed '/^-/d;/^$/d'); do
if ! grep -qFx "$cmd" "$tmp"; then
grep -Hn $grep_color "^\\*:$cmd\\*" "$f"
fail=$((fail+1))
fi
done
done
if [ "$fail" -gt 0 ]; then
echo "error: $fail non-existent command(s) documented in man pages" >&2
global_fail=1
fi
fail=0
sed -nE 's/^\*([a-z][a-z-]*)\* = .*/\1/p' doc/*.scd > "$tmp"
for f in $(find config -type f -name '*.go'); do
for opt in $(sed -nE 's/.*`ini:"([a-z][a-z-]*)".*/\1/p' $f); do
if ! grep -qFx "$opt" "$tmp"; then
grep -HnF $grep_color "\"$opt\"" "$f"
fail=$((fail+1))
fi
done
done
if [ "$fail" -gt 0 ]; then
echo "error: $fail option(s) not documented in man pages" >&2
global_fail=1
fi
exit $global_fail
+95
View File
@@ -0,0 +1,95 @@
#!/bin/sh
set -e
revision_range="${1?revision range}"
valid=0
revisions=$(git rev-list --reverse "$revision_range")
total=$(echo $revisions | wc -w)
if [ "$total" -eq 0 ]; then
exit 0
fi
allowed_trailers="
Fixes
Implements
References
Link
Changelog-added
Changelog-fixed
Changelog-changed
Changelog-deprecated
Cc
Suggested-by
Requested-by
Reported-by
Co-authored-by
Signed-off-by
Tested-by
Reviewed-by
Acked-by
"
n=0
title=
fail=false
err() {
echo "error [PATCH $n/$total] '$title' $*" >&2
fail=true
}
for rev in $revisions; do
n=$((n + 1))
title=$(git log --format='%s' -1 "$rev")
fail=false
if [ "$(echo "$title" | wc -m)" -gt 72 ]; then
err "title is longer than 72 characters, please make it shorter"
fi
if ! echo "$title" | grep -qE '^[a-z0-9,{}/_-]+: '; then
err "title lacks a topic prefix (e.g. 'imap:')"
fi
author=$(git log --format='%an <%ae>' -1 "$rev")
if ! git log --format="%(trailers:key=Signed-off-by,only,valueonly,unfold)" -1 "$rev" |
grep -qFx "$author"; then
err "'Signed-off-by: $author' trailer is missing"
fi
for trailer in $(git log --format="%(trailers:only,keyonly)" -1 "$rev"); do
if ! echo "$allowed_trailers" | grep -qFx "$trailer"; then
err "trailer '$trailer' is misspelled or not in the sanctioned list"
fi
done
if git log --format="%(trailers:only,unfold)" -1 "$rev" | \
grep -vE '^Changelog-[a-z]+: [A-Z`\*_].+\.$' | \
grep -qE '^Changelog-[a-z]+: '; then
err "Changelog-* trailers should start with a capital letter and end with a period"
fi
body=$(git log --format='%b' -1 "$rev")
body=${body%$(git log --format='%(trailers)' -1 "$rev")}
if [ "$(echo "$body" | wc -w)" -lt 3 ]; then
err "body has less than three words, please describe your changes"
fi
if ! git log --format='%s%n%b' -1 "$rev" | codespell -; then
err "typos in title and/or body"
fi
if [ "$fail" = true ]; then
continue
fi
echo "ok [PATCH $n/$total] '$title'"
valid=$((valid + 1))
done
echo "$valid/$total valid patches"
if [ "$valid" -ne "$total" ]; then
exit 1
fi
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/awk -f
BEGIN {
isatty = system("test -t 1") == "0"
retcode = 0
}
function color(code, s) {
if (isatty) {
return "\033[" code "m" s "\033[0m"
}
return s
}
function red(s) { return color("31", s) }
function green(s) { return color("32", s) }
function magenta(s) { return color("35", s) }
function cyan(s) { return color("36", s) }
function bg_red(s) { return color("41", s) }
function hl_ws(s, pattern) {
gsub(pattern, bg_red("&"), s)
# convert tab characters to 8 spaces to allow coloring
gsub(/\t/, " ", s)
return s
}
/ +\t+/ {
retcode = 1
print magenta(FILENAME) cyan(":") green(FNR) cyan(":") \
hl_ws($0, " +\\t+") red("<-- space(s) followed by tab(s)")
}
/[ \t]+$/ {
retcode = 1
print magenta(FILENAME) cyan(":") green(FNR) cyan(":") \
hl_ws($0, "[ \\t]+$") red("<-- trailing whitespace")
}
ENDFILE {
# will only match on GNU awk, ignored on non-GNU versions
if ($0 ~ /^[ \t]*$/) {
retcode = 1
print magenta(FILENAME) cyan(": ") red("trailing new line(s)")
} else if (RT != "\n") {
retcode = 1
print magenta(FILENAME) cyan(": ") red("no new line at end of file")
}
}
END {
exit retcode
}
+80
View File
@@ -0,0 +1,80 @@
#!/bin/sh
set -e
debug() {
if [ "$GIT_TRAILER_DEBUG" = 1 ]; then
"$@" >&2
fi
}
trailer_order="
Closes:
Fixes:
Implements:
References:
Link:
Changelog-added:
Changelog-fixed:
Changelog-changed:
Changelog-deprecated:
Cc:
Suggested-by:
Requested-by:
Reported-by:
Co-authored-by:
Signed-off-by:
Tested-by:
Reviewed-by:
Acked-by:
"
file=${1?file}
tmp=$(mktemp)
trap "rm -f $tmp" EXIT
# Read unfolded trailers and normalize case.
git interpret-trailers --parse --trim-empty "$file" |
while read -r key value; do
# Force title case on trailer key.
first_letter=$(echo "$key" | sed 's/^\(.\).*/\1/' | tr '[:lower:]' '[:upper:]')
other_letters=$(echo "$key" | sed 's/^.\(.*\)/\1/' | tr '[:upper:]' '[:lower:]')
key="$first_letter$other_letters"
# Find sort order of this key.
order=$(echo "$trailer_order" | grep -Fxn "$key" | sed -nE 's/^([0-9]+):.*/\1/p')
if [ -z "$order" ]; then
echo "warning: unknown trailer '$key'" >&2
# Unknown trailers are always first.
order="0"
fi
echo "$order $key $value"
done |
# Sort trailers according to their numeric order, trim the numeric order.
LC_ALL=C sort -n | sed -E 's/^[0-9]+ //' > "$tmp"
debug echo ==== sanitized trailers ====
debug cat "$tmp"
# Unfortunately, reordering trailers is not possible at the moment. Delete all
# trailers first. The only way to do it is to force replace existing trailers
# with empty values and trim empty trailers one by one.
while read -r key value; do
git interpret-trailers --in-place --if-exists=replace \
--trailer="$key " "$file"
git interpret-trailers --in-place --trim-empty "$file"
done < "$tmp"
set --
while read -r trailer; do
case "$trailer" in
Changelog-*)
# Wrap changelog entries indenting with a space.
trailer=$(echo "$trailer" | fmt -w 72 | sed '2,$s/^/ /')
;;
esac
set -- "$@" --trailer="$trailer"
done < "$tmp"
# Remove duplicate "key: value" trailers (e.g. duplicate signed-off-by).
git interpret-trailers --in-place --if-exists=addIfDifferent "$@" "$file"
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# Copyright (c) 2024 Robin Jarry
import argparse
import re
import subprocess
DEP_CHANGE_RE = re.compile(
r"""
^
(?P<diff>[\+\-])\s*
(?P<name>\S+)\s*
(?P<version>v\S+)\s*
(?://\s*indirect)?
$
""",
re.VERBOSE,
)
REPLACE_RE = re.compile(
r"""
^
(?P<diff>[\+\-])\s*
replace
(?P<name>\S+)\s*
=>\s*
(?P<replacement>\S+)\s*
(?P<version>v\S+)\s*
$
""",
re.VERBOSE,
)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"git_range",
metavar="GIT_RANGE",
help="The git revision range (see gitrevisions(7)).",
)
args = parser.parse_args()
old_deps = {}
new_deps = {}
with subprocess.Popen(
["git", "diff", "-U0", "--ignore-all-space", args.git_range, "--", "go.mod"],
stdout=subprocess.PIPE,
encoding="utf-8",
) as proc:
for line in proc.stdout:
match = DEP_CHANGE_RE.match(line.strip())
if not match:
match = REPLACE_RE.match(line.strip())
if not match:
continue
diff, name, replacement, version = match.groups()
if diff == "+":
new_deps[replacement] = version
del new_deps[name]
continue
diff, name, version = match.groups()
if diff == "+":
new_deps[name] = version
else:
old_deps[name] = version
once = False
added = new_deps.keys() - old_deps.keys()
if added:
print("## New")
print()
for a in sorted(added):
print("+", a, new_deps[a])
once = True
updated = old_deps.keys() & new_deps.keys()
if updated:
if once:
print()
print("## Updated")
print()
for u in sorted(updated):
print("*", u, old_deps[u], "=>", new_deps[u])
once = True
removed = old_deps.keys() - new_deps.keys()
if removed:
if once:
print()
print("## Removed")
print()
for r in sorted(removed):
print("-", r)
once = True
if not once:
print("none")
if __name__ == "__main__":
main()
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# Copyright (c) 2023 Bence Ferdinandy <bence@ferdinandy.com>
"""
Create graphs about development statistics of releases.
"""
from datetime import date
from subprocess import check_output
from matplotlib import pyplot as plt
def git(*args):
return check_output(["git"] + list(args)).decode("utf-8").strip()
def stats():
"""
Returns statistics from the git repo:
tags: sorted list of minor version tags (assumes semver)
The first element is the hash of the first commit, last element is HEAD. All
the other return values are one shorter as, there's no statistics returned for
the first commit.
counts: number of commits (between this and the previous release)
dates: dates of the releases
files: number of files changed (between this and the previous release)
inserts: number of lines inserted (between this and the previous release)
deletions: number of lines deleted (between this and the previous release)
"""
tags = git("tag").split("\n")
tags = [t for t in tags if t.split(".")[-1] == "0"] # drop patch versions
tags = sorted(tags, key=lambda x: [int(t) for t in x.split(".")])
first_commit = git("rev-list", "--max-parents=0", "HEAD")
tags = [first_commit] + tags + ["HEAD"]
counts = []
dates = []
files = []
inserts = []
deletions = []
for i, t in enumerate(tags[:-1]):
counts.append(int(git("rev-list", f"{t}..{tags[i+1]}", "--count")))
dates.append(
date.fromisoformat(
git("show", "-s", "--format=%cs", tags[i + 1]).split("\n")[-1]
)
)
statline = git("diff", "--stat", t, tags[i + 1]).split("\n")[-1]
fnum, _, _, ins, _, dels, _ = statline.split()
files.append(int(fnum))
inserts.append(int(ins))
deletions.append(int(dels))
return tags, counts, dates, files, inserts, deletions
def main(output):
tags, counts, dates, files, inserts, deletions = stats()
fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 11))
fig.suptitle("aerc release statistics", fontweight="bold")
# commit counts subplot
ax1.plot(dates, counts, "o-")
# alternate placement of text above and below for readability
text_y = []
for i, t in enumerate(tags[1:]):
downpad = 25 if len(t) == 5 else 30
p = counts[i] + (-1) ** (i + 1) * 10 - (i + 1) % 2 * downpad
if p < 5:
p = counts[i] + 10
text_y.append(p)
for i, t in enumerate(tags[1:]):
ax1.text(
dates[i],
text_y[i],
t,
horizontalalignment="center",
rotation="vertical",
)
ax1.set_ylabel("# of commits")
ax1.set_ylim(bottom=0)
ax1.set_title("commits per release")
# lines added/deleted subplot
#
ax2.plot(dates, inserts, "o-", label="insertions(+)", color="green")
ax2.plot(dates, deletions, "o-.", label="deletions(-)", color="red")
ax2.set_ylabel("# of lines")
ax2.legend(loc="upper left")
ax2.set_ylim(top=max(max(inserts), max(deletions)) + 2000)
for i, t in enumerate(tags[1:]):
ax2.text(
dates[i],
max(inserts[i], deletions[i]) + 500,
t,
horizontalalignment="center",
rotation="vertical",
)
ax2.set_xlabel("date")
ax2.set_title("insertion/deletions per release")
plt.tight_layout()
plt.savefig(output, dpi=300)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"-o",
"--output",
default="aerc-release-stats.png",
help="""
Path to output image (defaults to 'aerc-release-stats.png',
respects file extensions via matplotlib)
""",
)
args = parser.parse_args()
main(args.output)
+38
View File
@@ -0,0 +1,38 @@
#!/bin/bash
set -e
set -o pipefail
columns="Author,Commits,Changed Files,Insertions,Deletions"
git shortlog -sn "$@" |
while read -r commits author; do
git log --author="$author" --pretty=tformat: --numstat "$@" | {
adds=0
subs=0
files=0
while read -r a s f; do
adds=$((adds + a))
subs=$((subs + s))
files=$((files + 1))
done
printf '%s;%d;%d;%+d;%+d;\n' \
"$author" "$commits" "$files" "$adds" "-$subs"
}
done |
column -t -s ';' -N "$columns" -R "${columns#*,}" |
sed -E 's/[[:space:]]+$//'
echo
columns="Reviewer/Tester,Commits"
git shortlog -sn \
--group=trailer:acked-by \
--group=trailer:tested-by \
--group=trailer:reviewed-by "$@" |
while read -r commits author; do
printf '%s;%s\n' "$author" "$commits"
done |
column -t -s ';' -N "$columns" -R "${columns#*,}" |
sed -E 's/[[:space:]]+$//'
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
set -e
tags=
if ${CC:-cc} -x c - -o/dev/null -lnotmuch 2>/dev/null; then
tags="$tags,notmuch"
fi <<EOF
#include <notmuch.h>
#if !LIBNOTMUCH_CHECK_VERSION(5, 6, 0)
#error "aerc requires libnotmuch.so.5.6 or later"
#endif
void main(void) {
notmuch_status_to_string(NOTMUCH_STATUS_SUCCESS);
}
EOF
if [ -n "$tags" ]; then
printf -- '-tags=%s\n' "${tags#,}"
fi
+63
View File
@@ -0,0 +1,63 @@
###
# Copyright (c) 2005, Jeremiah Fincher
# Copyright (c) 2010-2021, Valentin Lorentz
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
"""
Plugin for keeping track of Karma for users and things in a channel.
"""
import supybot
import supybot.world as world
# Use this for the version of this plugin. You may wish to put a CVS keyword
# in here if you're keeping the plugin in CVS or some similar system.
__version__ = ""
__author__ = supybot.authors.jemfinch
__maintainer__ = supybot.authors.limnoria_core
# This is a dictionary mapping supybot.Author instances to lists of
# contributions.
__contributors__ = {}
from . import config
from . import plugin
from importlib import reload
reload(plugin) # In case we're being reloaded.
# Add more reloads here if you add third-party modules and want them to be
# reloaded when this plugin is reloaded. Don't forget to import them as well!
if world.testing:
from . import test
Class = plugin.Class
configure = config.configure
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
+74
View File
@@ -0,0 +1,74 @@
###
# Copyright (c) 2005, Jeremiah Fincher
# Copyright (c) 2010-2021, Valentin Lorentz
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
import supybot.conf as conf
import supybot.registry as registry
from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization('Karma')
def configure(advanced):
# This will be called by supybot to configure this module. advanced is
# a bool that specifies whether the user identified themself as an advanced
# user or not. You should effect your configuration by manipulating the
# registry as appropriate.
from supybot.questions import expect, anything, something, yn
conf.registerPlugin('Karma', True)
Karma = conf.registerPlugin('Karma')
conf.registerChannelValue(Karma, 'simpleOutput',
registry.Boolean(False, _("""Determines whether the bot will output shorter
versions of the karma output when requesting a single thing's karma.""")))
conf.registerChannelValue(Karma, 'incrementChars',
registry.SpaceSeparatedListOfStrings(['++'], _("""A space separated list of
characters to increase karma.""")))
conf.registerChannelValue(Karma, 'decrementChars',
registry.SpaceSeparatedListOfStrings(['--'], _("""A space separated list of
characters to decrease karma.""")))
conf.registerChannelValue(Karma, 'response',
registry.Boolean(False, _("""Determines whether the bot will reply with a
success message when something's karma is increased or decreased.""")))
conf.registerChannelValue(Karma, 'rankingDisplay',
registry.Integer(3, _("""Determines how many highest/lowest karma things
are shown when karma is called with no arguments.""")))
conf.registerChannelValue(Karma, 'mostDisplay',
registry.Integer(25, _("""Determines how many karma things are shown when
the most command is called.""")))
conf.registerChannelValue(Karma, 'allowSelfRating',
registry.Boolean(False, _("""Determines whether users can adjust the karma
of their nick.""")))
conf.registerChannelValue(Karma, 'allowUnaddressedKarma',
registry.Boolean(True, _("""Determines whether the bot will
increase/decrease karma without being addressed.""")))
conf.registerChannelValue(Karma, 'onlyNicks',
registry.Boolean(False, _("""Determines whether the bot will
only increase/decrease karma for nicks in the current channel.""")))
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
+469
View File
@@ -0,0 +1,469 @@
###
# Copyright (c) 2005, Jeremiah Fincher
# Copyright (c) 2010, James McCoy
# Copyright (c) 2010-2021, Valentin Lorentz
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
import os
import re
import sys
import csv
import time
import random
import supybot.conf as conf
import supybot.utils as utils
from supybot.commands import *
import supybot.utils.minisix as minisix
import supybot.plugins as plugins
import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
import supybot.schedule as schedule
from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization('Karma')
import sqlite3
def checkAllowShell(irc):
if not conf.supybot.commands.allowShell():
irc.error('This command is not available, because '
'supybot.commands.allowShell is False.', Raise=True)
class SqliteKarmaDB(object):
def __init__(self, filename):
self.dbs = ircutils.IrcDict()
self.filename = filename
def close(self):
for db in self.dbs.values():
db.close()
def _getDb(self, channel):
filename = plugins.makeChannelFilename(self.filename, channel)
if filename in self.dbs:
return self.dbs[filename]
if os.path.exists(filename):
db = sqlite3.connect(filename, check_same_thread=False)
if minisix.PY2:
db.text_factory = str
self.dbs[filename] = db
return db
db = sqlite3.connect(filename, check_same_thread=False)
if minisix.PY2:
db.text_factory = str
self.dbs[filename] = db
cursor = db.cursor()
cursor.execute("""CREATE TABLE karma (
id INTEGER PRIMARY KEY,
name TEXT,
normalized TEXT UNIQUE ON CONFLICT IGNORE,
added INTEGER,
subtracted INTEGER
)""")
db.commit()
def p(s1, s2):
return int(ircutils.nickEqual(s1, s2))
db.create_function('nickeq', 2, p)
return db
def get(self, channel, thing):
db = self._getDb(channel)
thing = thing.lower()
cursor = db.cursor()
cursor.execute("""SELECT added, subtracted FROM karma
WHERE normalized=?""", (thing,))
results = cursor.fetchall()
if len(results) == 0:
return None
else:
return list(map(int, results[0]))
def gets(self, channel, things):
db = self._getDb(channel)
cursor = db.cursor()
normalizedThings = dict(list(zip([s.lower() for s in things], things)))
criteria = ' OR '.join(['normalized=?'] * len(normalizedThings))
sql = """SELECT name, added-subtracted FROM karma
WHERE %s ORDER BY added-subtracted DESC""" % criteria
cursor.execute(sql, list(normalizedThings.keys()))
L = [(name, int(karma)) for (name, karma) in cursor.fetchall()]
for (name, _) in L:
del normalizedThings[name.lower()]
neutrals = list(normalizedThings.values())
neutrals.sort()
return (L, neutrals)
def top(self, channel, limit):
db = self._getDb(channel)
cursor = db.cursor()
cursor.execute("""SELECT name, added-subtracted FROM karma
ORDER BY added-subtracted DESC LIMIT ?""", (limit,))
return [(t[0], int(t[1])) for t in cursor.fetchall()]
def bottom(self, channel, limit):
db = self._getDb(channel)
cursor = db.cursor()
cursor.execute("""SELECT name, added-subtracted FROM karma
ORDER BY added-subtracted ASC LIMIT ?""", (limit,))
return [(t[0], int(t[1])) for t in cursor.fetchall()]
def rank(self, channel, thing):
db = self._getDb(channel)
cursor = db.cursor()
cursor.execute("""SELECT added-subtracted FROM karma
WHERE name=?""", (thing,))
results = cursor.fetchall()
if len(results) == 0:
return None
karma = int(results[0][0])
cursor.execute("""SELECT COUNT(*) FROM karma
WHERE added-subtracted > ?""", (karma,))
rank = int(cursor.fetchone()[0])
return rank+1
def size(self, channel):
db = self._getDb(channel)
cursor = db.cursor()
cursor.execute("""SELECT COUNT(*) FROM karma""")
return int(cursor.fetchone()[0])
def increment(self, channel, name):
db = self._getDb(channel)
cursor = db.cursor()
normalized = name.lower()
cursor.execute("""INSERT INTO karma VALUES (NULL, ?, ?, 0, 0)""",
(name, normalized,))
cursor.execute("""UPDATE karma SET added=added+1
WHERE normalized=?""", (normalized,))
db.commit()
def decrement(self, channel, name):
db = self._getDb(channel)
cursor = db.cursor()
normalized = name.lower()
cursor.execute("""INSERT INTO karma VALUES (NULL, ?, ?, 0, 0)""",
(name, normalized,))
cursor.execute("""UPDATE karma SET subtracted=subtracted+1
WHERE normalized=?""", (normalized,))
db.commit()
def most(self, channel, kind, limit):
if kind == 'increased':
orderby = 'added'
elif kind == 'decreased':
orderby = 'subtracted'
elif kind == 'active':
orderby = 'added+subtracted'
else:
raise ValueError('invalid kind')
sql = """SELECT name, %s FROM karma ORDER BY %s DESC LIMIT %s""" % \
(orderby, orderby, limit)
db = self._getDb(channel)
cursor = db.cursor()
cursor.execute(sql)
return [(name, int(i)) for (name, i) in cursor.fetchall()]
def clear(self, channel, name=None):
db = self._getDb(channel)
cursor = db.cursor()
if name:
normalized = name.lower()
cursor.execute("""DELETE FROM karma
WHERE normalized=?""", (normalized,))
else:
cursor.execute("""DELETE FROM karma""")
db.commit()
def dump(self, channel, filename):
filename = conf.supybot.directories.data.dirize(filename)
fd = utils.file.AtomicFile(filename)
out = csv.writer(fd)
db = self._getDb(channel)
cursor = db.cursor()
cursor.execute("""SELECT name, added, subtracted FROM karma""")
for (name, added, subtracted) in cursor.fetchall():
out.writerow([name, added, subtracted])
fd.close()
def load(self, channel, filename):
filename = conf.supybot.directories.data.dirize(filename)
fd = open(filename, encoding='utf8')
reader = csv.reader(fd)
db = self._getDb(channel)
cursor = db.cursor()
cursor.execute("""DELETE FROM karma""")
for (name, added, subtracted) in reader:
normalized = name.lower()
cursor.execute("""INSERT INTO karma
VALUES (NULL, ?, ?, ?, ?)""",
(name, normalized, added, subtracted,))
db.commit()
fd.close()
KarmaDB = plugins.DB('Karma',
{'sqlite3': SqliteKarmaDB})
class Karma(callbacks.Plugin):
"""
Provides a simple tracker for setting Karma (thing++, thing--).
If ``config plugins.karma.allowUnaddressedKarma`` is set to ``True``
(default since 2014.05.07), saying `boats++` will give 1 karma
to ``boats``, and ``ships--`` will subtract 1 karma from ``ships``.
However, if you use this in a sentence, like
``That deserves a ++. Kevin++``, 1 karma will be added to
``That deserves a ++. Kevin``, so you should only add or subtract karma
in a line that doesn't have anything else in it.
Alternatively, you can restrict karma tracking to nicks in the current
channel by setting `config plugins.Karma.onlyNicks` to ``True``.
If ``config plugins.karma.allowUnaddressedKarma` is set to `False``,
you must address the bot with nick or prefix to add or subtract karma.
"""
callBefore = ('Factoids', 'MoobotFactoids', 'Infobot')
def __init__(self, irc):
self.__parent = super(Karma, self)
self.__parent.__init__(irc)
self.db = KarmaDB()
def die(self):
self.__parent.die()
self.db.close()
def _normalizeThing(self, thing):
assert thing
if thing[0] == '(' and thing[-1] == ')':
thing = thing[1:-1]
return thing
def _respond(self, irc, channel, thing, karma):
if self.registryValue('response', channel, irc.network):
irc.reply(_('%(thing)s\'s karma is now %(karma)i') %
{'thing': thing, 'karma': karma})
else:
irc.noReply()
IRC_NICK = r'\w[\w\\`\[\]\{\}\^-]*'
TABLE_FLIP = re.compile(r'\s*[\(]╯...[\)]╯\s*︵\s*.*', re.U)
def _doKarma(self, irc, msg, channel, line):
match = self.TABLE_FLIP.match(line)
if match:
event_name = f'unflip {msg.nic}'
try:
schedule.removeEvent(event_name)
except KeyError:
pass
schedule.addEvent(
irc.reply,
time.time() + random.lognormvariate(0.5, 0.5),
name=event_name,
args=['┳━┳ノ(°_°ノ)'],
)
return
inc = self.registryValue('incrementChars', channel, irc.network)
dec = self.registryValue('decrementChars', channel, irc.network)
onlynicks = self.registryValue('onlyNicks', channel, irc.network)
karma = {}
for s in inc:
regex = re.compile(rf'\b({self.IRC_NICK})\b{re.escape(s)}')
for match in regex.finditer(line):
thing = match.group(1)
# Don't reply if the target isn't a nick
if onlynicks and thing.lower() not in map(ircutils.toLower,
irc.state.channels[channel].users):
return
if ircutils.strEqual(thing, msg.nick) and \
not self.registryValue('allowSelfRating',
channel, irc.network):
irc.error(_('You\'re not allowed to adjust your own karma.'))
return
self.db.increment(channel, self._normalizeThing(thing))
scores = self.db.get(channel, self._normalizeThing(thing))
if scores:
karma[thing] = scores[0] - scores[1]
for s in dec:
regex = re.compile(rf'\b({self.IRC_NICK})\b{re.escape(s)}')
for match in regex.finditer(line):
thing = match.group(1)
if onlynicks and thing.lower() not in map(ircutils.toLower,
irc.state.channels[channel].users):
return
if ircutils.strEqual(thing, msg.nick) and \
not self.registryValue('allowSelfRating',
channel, irc.network):
irc.error(_('You\'re not allowed to adjust your own karma.'))
return
self.db.decrement(channel, self._normalizeThing(thing))
scores = self.db.get(channel, self._normalizeThing(thing))
if scores:
karma[thing] = scores[0] - scores[1]
for thing, score in karma.items():
self._respond(irc, channel, thing, score)
def invalidCommand(self, irc, msg, tokens):
if msg.channel and tokens:
line = msg.args[1].rstrip()
self._doKarma(irc, msg, msg.channel, line)
def doPrivmsg(self, irc, msg):
# We don't handle this if we've been addressed because invalidCommand
# will handle it for us. This prevents us from accessing the db twice
# and therefore crashing.
if not (msg.addressed or msg.repliedTo):
if msg.channel and \
not ircmsgs.isCtcp(msg) and \
self.registryValue('allowUnaddressedKarma',
msg.channel, irc.network):
irc = callbacks.SimpleProxy(irc, msg)
line = msg.args[1].rstrip()
self._doKarma(irc, msg, msg.channel, line)
@internationalizeDocstring
def karma(self, irc, msg, args, channel, things):
"""[<channel>] [<thing> ...]
Returns the karma of <thing>. If <thing> is not given, returns the top
N karmas, where N is determined by the config variable
supybot.plugins.Karma.rankingDisplay. If one <thing> is given, returns
the details of its karma; if more than one <thing> is given, returns
the total karma of each of the things. <channel> is only necessary
if the message isn't sent on the channel itself.
"""
if len(things) == 1:
name = things[0]
t = self.db.get(channel, name)
if t is None:
irc.reply(format(_('%s has neutral karma.'), name))
else:
(added, subtracted) = t
total = added - subtracted
if self.registryValue('simpleOutput', channel, irc.network):
s = format('%s: %i', name, total)
else:
s = format(_('Karma for %q has been increased %n and '
'decreased %n for a total karma of %s.'),
name, (added, _('time')),
(subtracted, _('time')),
total)
irc.reply(s)
elif len(things) > 1:
(L, neutrals) = self.db.gets(channel, things)
if L:
s = format('%L', [format('%s: %i', *t) for t in L])
if neutrals:
neutral = format('. %L %h neutral karma',
neutrals, len(neutrals))
s += neutral
irc.reply(s + '.')
else:
irc.reply(_('I didn\'t know the karma for any of those '
'things.'))
else: # No name was given. Return the top/bottom N karmas.
limit = self.registryValue('rankingDisplay', channel, irc.network)
highest = [format('%q (%s)', s, t)
for (s, t) in self.db.top(channel, limit)]
lowest = [format('%q (%s)', s, t)
for (s, t) in self.db.bottom(channel, limit)]
if not (highest and lowest):
irc.error(_('I have no karma for this channel.'))
return
rank = self.db.rank(channel, msg.nick)
if rank is not None:
total = self.db.size(channel)
rankS = format(_(' You (%s) are ranked %i out of %i.'),
msg.nick, rank, total)
else:
rankS = ''
s = format(_('Highest karma: %L. Lowest karma: %L.%s'),
highest, lowest, rankS)
irc.reply(s)
karma = wrap(karma, ['channel', any('something')])
_mostAbbrev = utils.abbrev(['increased', 'decreased', 'active'])
@internationalizeDocstring
def most(self, irc, msg, args, channel, kind):
"""[<channel>] {increased,decreased,active}
Returns the most increased, the most decreased, or the most active
(the sum of increased and decreased) karma things. <channel> is only
necessary if the message isn't sent in the channel itself.
"""
L = self.db.most(channel, kind,
self.registryValue('mostDisplay',
channel, irc.network))
if L:
L = [format('%q: %i', name, i) for (name, i) in L]
irc.reply(format('%L', L))
else:
irc.error(_('I have no karma for this channel.'))
most = wrap(most, ['channel',
('literal', ['increased', 'decreased', 'active'])])
@internationalizeDocstring
def clear(self, irc, msg, args, channel, name):
"""[<channel>] [<name>]
Resets the karma of <name> to 0. If <name> is not given, resets
everything.
"""
self.db.clear(channel, name or None)
irc.replySuccess()
clear = wrap(clear, [('checkChannelCapability', 'op'), optional('text')])
@internationalizeDocstring
def dump(self, irc, msg, args, channel, filename):
"""[<channel>] <filename>
Dumps the Karma database for <channel> to <filename> in the bot's
data directory. <channel> is only necessary if the message isn't sent
in the channel itself.
"""
checkAllowShell(irc)
self.db.dump(channel, filename)
irc.replySuccess()
dump = wrap(dump, [('checkCapability', 'owner'), 'channeldb', 'filename'])
@internationalizeDocstring
def load(self, irc, msg, args, channel, filename):
"""[<channel>] <filename>
Loads the Karma database for <channel> from <filename> in the bot's
data directory. <channel> is only necessary if the message isn't sent
in the channel itself.
"""
checkAllowShell(irc)
self.db.load(channel, filename)
irc.replySuccess()
load = wrap(load, [('checkCapability', 'owner'), 'channeldb', 'filename'])
Class = Karma
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
+1
View File
@@ -0,0 +1 @@
Supybot plugin to receive Sourcehut webhooks
+21
View File
@@ -0,0 +1,21 @@
"""
Sourcehut: Supybot plugin to receive Sourcehut webhooks
"""
import sys
import supybot
__version__ = "0.1"
__author__ = supybot.authors.unknown
__contributors__ = {}
__url__ = ''
from . import config
from . import plugin
from importlib import reload
reload(config)
reload(plugin)
Class = plugin.Class
configure = config.configure
+14
View File
@@ -0,0 +1,14 @@
from supybot import conf, registry
try:
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('Sourcehut')
except:
_ = lambda x: x
def configure(advanced):
from supybot.questions import expect, anything, something, yn
conf.registerPlugin('Sourcehut', True)
Sourcehut = conf.registerPlugin('Sourcehut')
@@ -0,0 +1 @@
# Stub so local is a module, used for third-party modules
+141
View File
@@ -0,0 +1,141 @@
import email.header
import email.utils
import json
import mailbox
from urllib.parse import quote
from urllib.request import urlopen
import re
import traceback
from supybot import callbacks, httpserver, ircmsgs, world
from supybot.ircutils import bold, italic, mircColor, underline
class Sourcehut(callbacks.Plugin):
"""
Supybot plugin to receive Sourcehut webhooks
"""
def __init__(self, irc):
super().__init__(irc)
httpserver.hook("sourcehut", SourcehutServerCallback(self))
def die(self):
httpserver.unhook("sourcehut")
super().die()
def announce(self, channel, message):
libera = world.getIrc("libera")
if libera is None:
print("error: no irc libera")
return
if channel not in libera.state.channels:
print(f"error: not in {channel} channel")
return
libera.sendMsg(ircmsgs.notice(channel, message))
def decode_header(header: str) -> str:
if not header:
return ""
text = ""
for chunk, encoding in email.header.decode_header(header):
if isinstance(chunk, bytes):
chunk = chunk.decode(encoding or "us-ascii")
text += chunk
return text
class SourcehutServerCallback(httpserver.SupyHTTPServerCallback):
name = "Sourcehut"
defaultResponse = "Bad request\n"
def __init__(self, plugin: Sourcehut):
super().__init__()
self.plugin = plugin
SUBJECT = "[PATCH {prefix} v{version}] {subject}"
URL = "https://lists.sr.ht/{list[owner][canonicalName]}/{list[name]}"
CHANS = {
"#public-inbox": "##rjarry",
"#aerc-devel": "#aerc",
}
def announce_patch(self, patchset):
subject = self.SUBJECT.format(**patchset)
url = self.URL.format(**patchset)
if not url.startswith("https://lists.sr.ht/~rjarry/"):
raise ValueError("unknown list")
url += "/patches/{id}".format(**patchset)
channel = f"#{patchset['list']['name']}"
channel = self.CHANS.get(channel, channel)
try:
submitter = patchset["submitter"]["canonicalName"]
except KeyError:
try:
submitter = patchset["submitter"]["name"]
except KeyError:
submitter = patchset["submitter"]["address"]
msg = f"{mircColor('received', 'light gray')} {bold(subject)}"
msg += f" from {italic(submitter)}: {underline(url)}"
self.plugin.announce(channel, msg)
def announce_apply(self, mail):
channel = f"#{mail['list']['name']}"
channel = self.CHANS.get(channel, channel)
refs = []
for header in mail['references']:
refs += header.split()
for ref in refs:
url = self.URL.format(**mail) + quote(f"/{ref}")
print(f"GET {url}/raw")
with urlopen(f"{url}/raw") as u:
msg = mailbox.Message(u.read())
subject = re.sub(r"\s+", " ", decode_header(msg["subject"]))
if not subject.startswith("[PATCH"):
continue
for name, addr in email.utils.getaddresses([decode_header(msg["from"])]):
if name:
submitter = name
else:
submitter = addr
msg = f"{bold(mircColor('applied', 'green'))} {bold(subject)}"
msg += f" from {italic(submitter)}: {underline(url)}"
self.plugin.announce(channel, msg)
return
def doPost(self, handler, path, form=None):
if hasattr(form, "decode"):
form = form.decode("utf-8")
print(f"POST {path} {form}")
try:
body = json.loads(form)
hook = body["data"]["webhook"]
if hook["event"] == "PATCHSET_RECEIVED":
self.announce_patch(hook["patchset"])
handler.send_response(200)
handler.end_headers()
handler.wfile.write(b"")
return
if hook["event"] == "EMAIL_RECEIVED":
if hook["email"]["patchset_update"] == ["APPLIED"]:
self.announce_apply(hook["email"])
handler.send_response(200)
handler.end_headers()
handler.wfile.write(b"")
return
raise ValueError(f"unsupported webhook: {hook}")
except Exception as e:
traceback.print_exception(e)
handler.send_response(400)
handler.end_headers()
handler.wfile.write(b"Bad request\n")
def log_message(self, format, *args):
pass
Class = Sourcehut
+3
View File
@@ -0,0 +1,3 @@
from supybot.setup import plugin_setup
plugin_setup('Sourcehut')
+67
View File
@@ -0,0 +1,67 @@
#!/bin/sh
set -xe
list="${1:-https://lists.sr.ht/~rjarry/aerc-devel}"
url="${2:-https://bot.diabeteman.com/sourcehut/}"
hut lists webhook create "$list" --stdin -e patchset_received -u "$url" <<EOF
query {
webhook {
uuid
event
date
... on PatchsetEvent {
patchset {
id
subject
version
prefix
list {
name
owner {
... on User {
canonicalName
}
}
}
submitter {
... on User {
canonicalName
}
... on Mailbox {
name
address
}
}
}
}
}
}
EOF
hut lists webhook create "$list" --stdin -e email_received -u "$url" <<EOF
query {
webhook {
uuid
event
date
... on EmailEvent {
email {
id
subject
patchset_update: header(want: "X-Sourcehut-Patchset-Update")
references: header(want: "References")
list {
name
owner {
... on User {
canonicalName
}
}
}
}
}
}
}
EOF
+35
View File
@@ -0,0 +1,35 @@
limit_req_zone $binary_remote_addr zone=aercbot:1m rate=1r/s;
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name bot.diabeteman.com;
ssl_certificate /etc/dehydrated/certs/diabeteman.com/fullchain.pem;
ssl_certificate_key /etc/dehydrated/certs/diabeteman.com/privkey.pem;
client_max_body_size 150K;
limit_req zone=aercbot burst=10 nodelay;
location / {
allow 46.23.81.128/25;
allow 2a03:6000:1813::/48;
deny all;
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_redirect off;
proxy_buffering off;
proxy_request_buffering off;
proxy_pass http://127.0.0.1:7777;
}
}
server {
listen 80;
listen [::]:80;
server_name bot.diabeteman.com;
return 301 https://$host$request_uri;
}
+40
View File
@@ -0,0 +1,40 @@
supybot.commands.allowShell = False
supybot.ident = aercbot
supybot.log.format = %(name)s: %(message)s
supybot.log.plugins.format = %(message)s
supybot.log.stdout.colorized = False
supybot.log.stdout.format = %(message)s
supybot.log.stdout.level = INFO
supybot.log.stdout.wrap = False
supybot.log.stdout = True
supybot.networks.libera.channels = #aerc
supybot.networks.libera.requireStarttls = False
supybot.networks.libera.sasl.password = ********************
supybot.networks.libera.sasl.required = True
supybot.networks.libera.sasl.username = aercbot
supybot.networks.libera.servers = irc.libera.chat:6697
supybot.networks.libera.ssl = True
supybot.networks = libera
supybot.nick.alternates = %s` %s_
supybot.nick = aercbot
supybot.plugins.Channel.partMsg = KTHXBYE
supybot.plugins.Karma.allowSelfRating = False
supybot.plugins.Karma.allowUnaddressedKarma = True
supybot.plugins.Karma.decrementChars = --
supybot.plugins.Karma.incrementChars = ++
supybot.plugins.Karma.mostDisplay = 25
supybot.plugins.Karma.onlyNicks = False
supybot.plugins.Karma.public = True
supybot.plugins.Karma.rankingDisplay = 3
supybot.plugins.Karma.response = True
supybot.plugins.Karma.simpleOutput = True
supybot.plugins.Karma = True
supybot.plugins.Sourcehut.public = False
supybot.plugins.Sourcehut = True
supybot.servers.http.hosts4 = 127.0.0.1
supybot.servers.http.hosts6 = ::1
supybot.servers.http.keepAlive = False
supybot.servers.http.port = 7777
supybot.servers.http.publicUrl = https://bot.diabeteman.com/
supybot.servers.http.singleStack = True
supybot.user = aerc's IRC bot
+19
View File
@@ -0,0 +1,19 @@
[Unit]
Description=IRC bot
After=network.target auditd.service
[Service]
ExecStart=/usr/bin/supybot /var/lib/supybot/supybot.conf
User=supybot
Group=supybot
WorkingDirectory=/var/lib/supybot
ProtectHome=true
ProtectSystem=strict
ReadWritePaths=/var/lib/supybot /tmp
PrivateTmp=true
SyslogIdentifier=supybot
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
+163
View File
@@ -0,0 +1,163 @@
package main
import (
"go/ast"
"go/token"
"go/types"
"reflect"
"strings"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/multichecker"
)
type indirectCalls struct {
methods map[token.Pos]string
functions map[string]token.Pos
}
var PanicAnalyzer = &analysis.Analyzer{
Name: "panic",
Doc: "finds goroutines that do not initialize the panic handler",
Run: runPanic,
ResultType: reflect.TypeOf(&indirectCalls{}),
}
var PanicIndirectAnalyzer = &analysis.Analyzer{
Name: "panicindirect",
Doc: "finds functions called as goroutines that do not initialize the panic handler",
Run: runPanicIndirect,
Requires: []*analysis.Analyzer{PanicAnalyzer},
}
func runPanic(pass *analysis.Pass) (interface{}, error) {
var calls indirectCalls
calls.methods = make(map[token.Pos]string)
calls.functions = make(map[string]token.Pos)
for _, file := range pass.Files {
ast.Inspect(file, func(n ast.Node) bool {
g, ok := n.(*ast.GoStmt)
if !ok {
return true
}
var block *ast.BlockStmt
expr := g.Call.Fun
if e, ok := expr.(*ast.ParenExpr); ok {
expr = e.X
}
switch e := expr.(type) {
case *ast.FuncLit:
block = e.Body
case *ast.SelectorExpr:
sel, ok := pass.TypesInfo.Selections[e]
if ok {
f, ok := sel.Obj().(*types.Func)
if ok {
calls.methods[f.Pos()] = f.Name()
}
}
case *ast.Ident:
block = inlineFuncBody(e)
if block == nil {
calls.functions[e.Name] = e.NamePos
}
}
if block == nil {
return true
}
if !isPanicHandlerInstall(block.List[0]) {
path := pass.Fset.File(block.Pos()).Name()
if !strings.HasSuffix(path, "_test.go") {
pass.Report(panicDiag(block.Pos()))
}
}
return true
})
}
return &calls, nil
}
func runPanicIndirect(pass *analysis.Pass) (interface{}, error) {
calls := pass.ResultOf[PanicAnalyzer].(*indirectCalls)
for _, file := range pass.Files {
if strings.HasSuffix(file.Name.Name, "_test") {
continue
}
for _, decl := range file.Decls {
if f, ok := decl.(*ast.FuncDecl); ok {
if _, ok := calls.methods[f.Name.Pos()]; ok {
delete(calls.methods, f.Name.Pos())
} else if _, ok := calls.functions[f.Name.Name]; ok {
delete(calls.functions, f.Name.Name)
} else {
continue
}
if !isPanicHandlerInstall(f.Body.List[0]) {
path := pass.Fset.File(f.Body.Pos()).Name()
if !strings.HasSuffix(path, "_test.go") {
pass.Report(panicDiag(f.Body.Pos()))
}
}
}
}
}
return nil, nil
}
func panicDiag(pos token.Pos) analysis.Diagnostic {
return analysis.Diagnostic{
Pos: pos,
Category: "panic",
Message: "missing defer log.PanicHandler() as first statement",
}
}
func inlineFuncBody(s *ast.Ident) *ast.BlockStmt {
if s.Obj == nil || s.Obj.Decl == nil {
return nil
}
d, ok := s.Obj.Decl.(*ast.AssignStmt)
if !ok {
return nil
}
for _, r := range d.Rhs {
if f, ok := r.(*ast.FuncLit); ok {
return f.Body
}
}
return nil
}
func isPanicHandlerInstall(stmt ast.Stmt) bool {
d, ok := stmt.(*ast.DeferStmt)
if !ok {
return false
}
s, ok := d.Call.Fun.(*ast.SelectorExpr)
if !ok {
return false
}
i, ok := s.X.(*ast.Ident)
if !ok {
return false
}
return i.Name == "log" && s.Sel.Name == "PanicHandler"
}
func main() {
multichecker.Main(
PanicAnalyzer,
PanicIndirectAnalyzer,
)
}
+136
View File
@@ -0,0 +1,136 @@
#!/bin/sh
set -e
dry_run=false
case "$1" in
-n|--dry-run)
dry_run=true
;;
esac
changelog() {
title_prefix=$1
width=$2
first=true
wrap=cat
if [ -n "$width" ]; then
wrap="./wrap -r -w$width"
fi
for kind in Added Fixed Changed Deprecated; do
format="%(trailers:key=Changelog-$kind,unfold,valueonly)"
if git log --format="$format" $prev_tag.. | grep -q .; then
if [ "$first" = true ]; then
first=false
else
echo
fi
echo "$title_prefix $kind"
echo
git log --reverse --format="$format" $prev_tag.. | \
sed -E '/^$/d; s/[[:space:]]+/ /; s/^/- /' | \
$wrap
fi
done
format="%(trailers:key=Fixes,key=Closes,key=Implements,unfold,valueonly)"
if git log --format="$format" $prev_tag.. | grep -q "^https://todo.sr.ht"; then
if [ "$first" = true ]; then
first=false
else
echo
fi
echo "$title_prefix Closed Tickets"
echo
git log --format="$format" $prev_tag.. |
grep "^https://todo.sr.ht" | sort -u |
while read -r url; do
title=$(hut todo ticket show "$url" | head -n1) &&
id=$(basename "$url") &&
echo "- [#$id: $title]($url)"
done
fi
}
echo "======= Determining next version..."
prev_tag=$(git describe --tags --abbrev=0)
next_tag=$(echo $prev_tag | awk -F. -v OFS=. '{$(NF-1) += 1; print}')
read -rp "next tag ($next_tag)? " n
if [ -n "$n" ]; then
next_tag="$n"
fi
tag_url="https://git.sr.ht/~rjarry/aerc/refs/$next_tag"
if [ "$dry_run" = false ]; then
echo "======= Creating release commit..."
sed -i GNUmakefile -e "s/$prev_tag/$next_tag/g"
make wrap
{
echo
echo "## [$next_tag]($tag_url) - $(date +%Y-%m-%d)"
echo
changelog "###" 80
} > .changelog.md
sed -i CHANGELOG.md -e '/^The format is based on/ r .changelog.md'
${EDITOR:-vi} CHANGELOG.md
rm -f .changelog.md
git add GNUmakefile CHANGELOG.md
git commit -vesm "Release version $next_tag"
echo "======= Creating tag..."
git -c core.commentchar='%' tag --edit --sign \
-m "Release $next_tag highlights:" \
-m "$(changelog '#' 72)" \
-m "Thanks to all contributors!" \
-m "~\$ contrib/git-stats.sh $prev_tag..$next_tag
$(contrib/git-stats.sh $prev_tag..)" \
"$next_tag"
echo "======= Pushing to remote..."
git push origin master "$next_tag"
fi
echo "======= Sending release email..."
email=$(mktemp aerc-release-XXXXXXXX.eml)
trap "rm -f -- $email" EXIT
cat >"$email" <<EOF
From: $(git config user.name) <$(git config user.email)>
To: aerc-annouce <~rjarry/aerc-announce@lists.sr.ht>
Cc: aerc-devel <~rjarry/aerc-devel@lists.sr.ht>
Bcc: aerc <~sircmpwn/aerc@lists.sr.ht>,
$(git config user.name) <$(git config user.email)>
Reply-To: aerc-devel <~rjarry/aerc-devel@lists.sr.ht>
Subject: aerc $next_tag
User-Agent: aerc/$next_tag
Message-ID: <$(date +%Y%m%d%H%M%S).$(base32 -w12 < /dev/urandom | head -n1)@$(hostname)>
Content-Transfer-Encoding: 8bit
Content-Type: text/plain; charset=UTF-8
MIME-Version: 1.0
Hi all,
I am glad to announce the release of aerc $next_tag.
$tag_url
Release highlights:
$(changelog '#')
# Changed dependencies for downstream packagers
$(contrib/depends-diff.py $prev_tag..)
Thanks to all contributors!
~\$ contrib/git-stats.sh $prev_tag..$next_tag
$(contrib/git-stats.sh $prev_tag..)
EOF
${EDITOR:-vi} "$email"
if [ "$dry_run" = false ]; then
/usr/sbin/sendmail -t < "$email"
fi
+78
View File
@@ -0,0 +1,78 @@
#!/bin/sh
# An example hook script to validate a patch (and/or patch series) before
# sending it via email.
#
# The hook should exit with non-zero status after issuing an appropriate
# message if it wants to prevent the email(s) from being sent.
#
# To enable this hook, rename this file to "sendemail-validate".
#
# By default, it will only check that the patch(es) can be applied on top of
# the default upstream branch without conflicts in a secondary worktree. After
# validation (successful or not) of the last patch of a series, the worktree
# will be deleted.
#
# The following config variables can be set to change the default remote and
# remote ref that are used to apply the patches against:
#
# sendemail.validateRemote (default: origin)
# sendemail.validateRemoteRef (default: HEAD)
validate_cover_letter () {
file="$1"
true
}
validate_patch () {
file="$1"
# Ensure that the patch applies without conflicts.
git am -3 "$file" || return
# Sign the patch if patatt is available.
case "$(git config --default false --get sendemail.runPatatt)" in
TRUE|True|true|yes|YES|Yes|Y|y|on|ON|On|1)
command -v patatt >/dev/null 2>&1 || return
patatt sign --hook "$file" || return 1
;;
esac
}
validate_series () {
command -v gmake >/dev/null 2>&1 && make="gmake" || make="make"
$make validate
}
# fallback for git 2.40 and older
: ${GIT_SENDEMAIL_FILE_COUNTER:=1}
: ${GIT_SENDEMAIL_FILE_TOTAL:=1}
if test "$GIT_SENDEMAIL_FILE_COUNTER" = 1
then
remote=$(git config --default origin --get sendemail.validateRemote) &&
ref=$(git config --default master --get sendemail.validateRemoteRef) &&
worktree=$(mktemp -d -t sendemail-validate.XXXXXXX) &&
git worktree add -fd --checkout "$worktree" "refs/remotes/$remote/$ref" &&
git config --replace-all sendemail.validateWorktree "$worktree"
else
worktree=$(git config --get sendemail.validateWorktree)
fi || {
echo "sendemail-validate: error: failed to prepare worktree" >&2
exit 1
}
unset GIT_DIR GIT_WORK_TREE
cd "$worktree" &&
if grep -q "^diff --git " "$1"
then
validate_patch "$1"
else
validate_cover_letter "$1"
fi &&
if test "$GIT_SENDEMAIL_FILE_COUNTER" = "$GIT_SENDEMAIL_FILE_TOTAL"
then
git config --unset-all sendemail.validateWorktree &&
trap 'git worktree remove -ff "$worktree"' EXIT &&
validate_series
fi