black: Reformat without skipping string normalization.

This commit is contained in:
PIG208 2021-05-28 17:05:11 +08:00 committed by Tim Abbott
parent fba21bb00d
commit 6f3f9bf7e4
178 changed files with 5242 additions and 5242 deletions

File diff suppressed because it is too large Load diff

View file

@ -11,11 +11,11 @@ def main() -> None:
Prints the path to the Zulip API example scripts."""
parser = argparse.ArgumentParser(usage=usage)
parser.add_argument(
'script_name', nargs='?', default='', help='print path to the script <script_name>'
"script_name", nargs="?", default="", help="print path to the script <script_name>"
)
args = parser.parse_args()
zulip_path = os.path.abspath(os.path.dirname(zulip.__file__))
examples_path = os.path.abspath(os.path.join(zulip_path, 'examples', args.script_name))
examples_path = os.path.abspath(os.path.join(zulip_path, "examples", args.script_name))
if os.path.isdir(examples_path) or (args.script_name and os.path.isfile(examples_path)):
print(examples_path)
else:
@ -26,5 +26,5 @@ Prints the path to the Zulip API example scripts."""
)
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -14,17 +14,17 @@ Example: alert-words remove banana
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument('operation', choices=['get', 'add', 'remove'], type=str)
parser.add_argument('words', type=str, nargs='*')
parser.add_argument("operation", choices=["get", "add", "remove"], type=str)
parser.add_argument("words", type=str, nargs="*")
options = parser.parse_args()
client = zulip.init_from_options(options)
if options.operation == 'get':
if options.operation == "get":
result = client.get_alert_words()
elif options.operation == 'add':
elif options.operation == "add":
result = client.add_alert_words(options.words)
elif options.operation == 'remove':
elif options.operation == "remove":
result = client.remove_alert_words(options.words)
print(result)

View file

@ -15,10 +15,10 @@ Specify your Zulip API credentials and server in a ~/.zuliprc file or using the
import zulip
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument('--new-email', required=True)
parser.add_argument('--new-password', required=True)
parser.add_argument('--new-full-name', required=True)
parser.add_argument('--new-short-name', required=True)
parser.add_argument("--new-email", required=True)
parser.add_argument("--new-password", required=True)
parser.add_argument("--new-full-name", required=True)
parser.add_argument("--new-short-name", required=True)
options = parser.parse_args()
client = zulip.init_from_options(options)
@ -26,10 +26,10 @@ client = zulip.init_from_options(options)
print(
client.create_user(
{
'email': options.new_email,
'password': options.new_password,
'full_name': options.new_full_name,
'short_name': options.new_short_name,
"email": options.new_email,
"password": options.new_password,
"full_name": options.new_full_name,
"short_name": options.new_short_name,
}
)
)

View file

@ -13,7 +13,7 @@ Example: delete-message 42
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument('message_id', type=int)
parser.add_argument("message_id", type=int)
options = parser.parse_args()
client = zulip.init_from_options(options)

View file

@ -11,7 +11,7 @@ Example: delete-stream 42
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument('stream_id', type=int)
parser.add_argument("stream_id", type=int)
options = parser.parse_args()
client = zulip.init_from_options(options)

View file

@ -15,9 +15,9 @@ Specify your Zulip API credentials and server in a ~/.zuliprc file or using the
import zulip
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument('--message-id', type=int, required=True)
parser.add_argument('--subject', default="")
parser.add_argument('--content', default="")
parser.add_argument("--message-id", type=int, required=True)
parser.add_argument("--subject", default="")
parser.add_argument("--content", default="")
options = parser.parse_args()
client = zulip.init_from_options(options)

View file

@ -19,12 +19,12 @@ def quote(string: str) -> str:
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument('--stream-id', type=int, required=True)
parser.add_argument('--description')
parser.add_argument('--new-name')
parser.add_argument('--private', action='store_true')
parser.add_argument('--announcement-only', action='store_true')
parser.add_argument('--history-public-to-subscribers', action='store_true')
parser.add_argument("--stream-id", type=int, required=True)
parser.add_argument("--description")
parser.add_argument("--new-name")
parser.add_argument("--private", action="store_true")
parser.add_argument("--announcement-only", action="store_true")
parser.add_argument("--history-public-to-subscribers", action="store_true")
options = parser.parse_args()
client = zulip.init_from_options(options)
@ -32,12 +32,12 @@ client = zulip.init_from_options(options)
print(
client.update_stream(
{
'stream_id': options.stream_id,
'description': quote(options.description),
'new_name': quote(options.new_name),
'is_private': options.private,
'is_announcement_only': options.announcement_only,
'history_public_to_subscribers': options.history_public_to_subscribers,
"stream_id": options.stream_id,
"description": quote(options.description),
"new_name": quote(options.new_name),
"is_private": options.private,
"is_announcement_only": options.announcement_only,
"history_public_to_subscribers": options.history_public_to_subscribers,
}
)
)

View file

@ -13,11 +13,11 @@ and store them in JSON format.
Example: get-history --stream announce --topic important"""
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument('--stream', required=True, help="The stream name to get the history")
parser.add_argument('--topic', help="The topic name to get the history")
parser.add_argument("--stream", required=True, help="The stream name to get the history")
parser.add_argument("--topic", help="The topic name to get the history")
parser.add_argument(
'--filename',
default='history.json',
"--filename",
default="history.json",
help="The file name to store the fetched \
history.\n Default 'history.json'",
)
@ -25,19 +25,19 @@ options = parser.parse_args()
client = zulip.init_from_options(options)
narrow = [{'operator': 'stream', 'operand': options.stream}]
narrow = [{"operator": "stream", "operand": options.stream}]
if options.topic:
narrow.append({'operator': 'topic', 'operand': options.topic})
narrow.append({"operator": "topic", "operand": options.topic})
request = {
# Initially we have the anchor as 0, so that it starts fetching
# from the oldest message in the narrow
'anchor': 0,
'num_before': 0,
'num_after': 1000,
'narrow': narrow,
'client_gravatar': False,
'apply_markdown': False,
"anchor": 0,
"num_before": 0,
"num_after": 1000,
"narrow": narrow,
"client_gravatar": False,
"apply_markdown": False,
}
all_messages = [] # type: List[Dict[str, Any]]
@ -47,17 +47,17 @@ while not found_newest:
result = client.get_messages(request)
try:
found_newest = result["found_newest"]
if result['messages']:
if result["messages"]:
# Setting the anchor to the next immediate message after the last fetched message.
request['anchor'] = result['messages'][-1]['id'] + 1
request["anchor"] = result["messages"][-1]["id"] + 1
all_messages.extend(result["messages"])
except KeyError:
# Might occur when the request is not returned with a success status
print('Error occured: Payload was:')
print("Error occured: Payload was:")
print(result)
quit()
with open(options.filename, "w+") as f:
print('Writing %d messages...' % len(all_messages))
print("Writing %d messages..." % len(all_messages))
f.write(json.dumps(all_messages))

View file

@ -17,13 +17,13 @@ Example: get-messages --use-first-unread-anchor --num-before=5 \\
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument('--anchor', type=int)
parser.add_argument('--use-first-unread-anchor', action='store_true')
parser.add_argument('--num-before', type=int, required=True)
parser.add_argument('--num-after', type=int, required=True)
parser.add_argument('--client-gravatar', action='store_true')
parser.add_argument('--apply-markdown', action='store_true')
parser.add_argument('--narrow')
parser.add_argument("--anchor", type=int)
parser.add_argument("--use-first-unread-anchor", action="store_true")
parser.add_argument("--num-before", type=int, required=True)
parser.add_argument("--num-after", type=int, required=True)
parser.add_argument("--client-gravatar", action="store_true")
parser.add_argument("--apply-markdown", action="store_true")
parser.add_argument("--narrow")
options = parser.parse_args()
client = zulip.init_from_options(options)
@ -31,13 +31,13 @@ client = zulip.init_from_options(options)
print(
client.get_messages(
{
'anchor': options.anchor,
'use_first_unread_anchor': options.use_first_unread_anchor,
'num_before': options.num_before,
'num_after': options.num_after,
'narrow': options.narrow,
'client_gravatar': options.client_gravatar,
'apply_markdown': options.apply_markdown,
"anchor": options.anchor,
"use_first_unread_anchor": options.use_first_unread_anchor,
"num_before": options.num_before,
"num_after": options.num_after,
"narrow": options.narrow,
"client_gravatar": options.client_gravatar,
"apply_markdown": options.apply_markdown,
}
)
)

View file

@ -12,7 +12,7 @@ Example: get-raw-message 42
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument('message_id', type=int)
parser.add_argument("message_id", type=int)
options = parser.parse_args()
client = zulip.init_from_options(options)

View file

@ -10,7 +10,7 @@ Get all the topics for a specific stream.
import zulip
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument('--stream-id', required=True)
parser.add_argument("--stream-id", required=True)
options = parser.parse_args()
client = zulip.init_from_options(options)

View file

@ -10,7 +10,7 @@ Get presence data for another user.
import zulip
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument('--email', required=True)
parser.add_argument("--email", required=True)
options = parser.parse_args()
client = zulip.init_from_options(options)

View file

@ -10,7 +10,7 @@ Example: message-history 42
"""
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument('message_id', type=int)
parser.add_argument("message_id", type=int)
options = parser.parse_args()
client = zulip.init_from_options(options)

View file

@ -11,17 +11,17 @@ Example: mute-topic unmute Denmark party
"""
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument('op', choices=['mute', 'unmute'])
parser.add_argument('stream')
parser.add_argument('topic')
parser.add_argument("op", choices=["mute", "unmute"])
parser.add_argument("stream")
parser.add_argument("topic")
options = parser.parse_args()
client = zulip.init_from_options(options)
OPERATIONS = {'mute': 'add', 'unmute': 'remove'}
OPERATIONS = {"mute": "add", "unmute": "remove"}
print(
client.mute_topic(
{'op': OPERATIONS[options.op], 'stream': options.stream, 'topic': options.topic}
{"op": OPERATIONS[options.op], "stream": options.stream, "topic": options.topic}
)
)

View file

@ -12,18 +12,18 @@ Example: send-message --type=stream commits --subject="my subject" --message="te
Example: send-message user1@example.com user2@example.com
"""
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument('recipients', nargs='+')
parser.add_argument('--subject', default='test')
parser.add_argument('--message', default='test message')
parser.add_argument('--type', default='private')
parser.add_argument("recipients", nargs="+")
parser.add_argument("--subject", default="test")
parser.add_argument("--message", default="test message")
parser.add_argument("--type", default="private")
options = parser.parse_args()
client = zulip.init_from_options(options)
message_data = {
'type': options.type,
'content': options.message,
'subject': options.subject,
'to': options.recipients,
"type": options.type,
"content": options.message,
"subject": options.subject,
"to": options.recipients,
}
print(client.send_message(message_data))

View file

@ -15,7 +15,7 @@ Specify your Zulip API credentials and server in a ~/.zuliprc file or using the
import zulip
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument('--streams', action='store', required=True)
parser.add_argument("--streams", action="store", required=True)
options = parser.parse_args()
client = zulip.init_from_options(options)

View file

@ -15,7 +15,7 @@ Specify your Zulip API credentials and server in a ~/.zuliprc file or using the
import zulip
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument('--streams', action='store', required=True)
parser.add_argument("--streams", action="store", required=True)
options = parser.parse_args()
client = zulip.init_from_options(options)

View file

@ -12,15 +12,15 @@ Example: update-message-flags remove starred 16 23 42
"""
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument('op', choices=['add', 'remove'])
parser.add_argument('flag')
parser.add_argument('messages', type=int, nargs='+')
parser.add_argument("op", choices=["add", "remove"])
parser.add_argument("flag")
parser.add_argument("messages", type=int, nargs="+")
options = parser.parse_args()
client = zulip.init_from_options(options)
print(
client.update_message_flags(
{'op': options.op, 'flag': options.flag, 'messages': options.messages}
{"op": options.op, "flag": options.flag, "messages": options.messages}
)
)

View file

@ -8,7 +8,7 @@ import zulip
class StringIO(_StringIO):
name = '' # https://github.com/python/typeshed/issues/598
name = "" # https://github.com/python/typeshed/issues/598
usage = """upload-file [options]
@ -22,20 +22,20 @@ If no --file-path is specified, a placeholder text file will be used instead.
"""
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument('--file-path', required=True)
parser.add_argument("--file-path", required=True)
options = parser.parse_args()
client = zulip.init_from_options(options)
if options.file_path:
file = open(options.file_path, 'rb') # type: IO[Any]
file = open(options.file_path, "rb") # type: IO[Any]
else:
file = StringIO('This is a test file.')
file.name = 'test.txt'
file = StringIO("This is a test file.")
file.name = "test.txt"
response = client.upload_file(file)
try:
print('File URI: {}'.format(response['uri']))
print("File URI: {}".format(response["uri"]))
except KeyError:
print('Error! API response was: {}'.format(response))
print("Error! API response was: {}".format(response))

View file

@ -4,7 +4,7 @@ from typing import Any, Dict, List
import zulip
welcome_text = 'Hello {}, Welcome to Zulip!\n \
welcome_text = "Hello {}, Welcome to Zulip!\n \
* The first thing you should do is to install the development environment. \
We recommend following the vagrant setup as it is well documented and used \
by most of the contributors. If you face any trouble during installation \
@ -21,7 +21,7 @@ of the main projects you can contribute to are Zulip \
a [bot](https://github.com/zulip/zulipbot) that you can contribute to!!\n \
* We host our source code on GitHub. If you are not familiar with Git or \
GitHub checkout [this](http://zulip.readthedocs.io/en/latest/git-guide.html) \
guide. You don\'t have to learn everything but please go through it and learn \
guide. You don't have to learn everything but please go through it and learn \
the basics. We are here to help you if you are having any trouble. Post your \
questions in #git help . \
* Once you have completed these steps you can start contributing. You \
@ -33,55 +33,55 @@ but if you want a bite size issue for mobile or electron feel free post in #mobi
or #electron .\n \
* Solving the first issue can be difficult. The key is to not give up. If you spend \
enough time on the issue you should be able to solve it no matter what.\n \
* Use `grep` command when you can\'t figure out what files to change :) For example \
* Use `grep` command when you can't figure out what files to change :) For example \
if you want know what files to modify in order to change Invite more users to Add \
more users which you can see below the user status list, grep for "Invite more \
users" in terminal.\n \
* If you are stuck with something and can\'t figure out what to do you can ask \
more users which you can see below the user status list, grep for \"Invite more \
users\" in terminal.\n \
* If you are stuck with something and can't figure out what to do you can ask \
for help in #development help . But make sure that you tried your best to figure \
out the issue by yourself\n \
* If you are here for #Outreachy 2017-2018 or #GSoC don\'t worry much about \
* If you are here for #Outreachy 2017-2018 or #GSoC don't worry much about \
whether you will get selected or not. You will learn a lot contributing to \
Zulip in course of next few months and if you do a good job at that you \
will get selected too :)\n \
* Most important of all welcome to the Zulip family :octopus:'
* Most important of all welcome to the Zulip family :octopus:"
# These streams will cause the message to be sent
streams_to_watch = ['new members']
streams_to_watch = ["new members"]
# These streams will cause anyone who sends a message there to be removed from the watchlist
streams_to_cancel = ['development help']
streams_to_cancel = ["development help"]
def get_watchlist() -> List[Any]:
storage = client.get_storage()
return list(storage['storage'].values())
return list(storage["storage"].values())
def set_watchlist(watchlist: List[str]) -> None:
client.update_storage({'storage': dict(enumerate(watchlist))})
client.update_storage({"storage": dict(enumerate(watchlist))})
def handle_event(event: Dict[str, Any]) -> None:
try:
if event['type'] == 'realm_user' and event['op'] == 'add':
if event["type"] == "realm_user" and event["op"] == "add":
watchlist = get_watchlist()
watchlist.append(event['person']['email'])
watchlist.append(event["person"]["email"])
set_watchlist(watchlist)
return
if event['type'] == 'message':
stream = event['message']['display_recipient']
if event["type"] == "message":
stream = event["message"]["display_recipient"]
if stream not in streams_to_watch and stream not in streams_to_cancel:
return
watchlist = get_watchlist()
if event['message']['sender_email'] in watchlist:
watchlist.remove(event['message']['sender_email'])
if event["message"]["sender_email"] in watchlist:
watchlist.remove(event["message"]["sender_email"])
if stream not in streams_to_cancel:
client.send_message(
{
'type': 'private',
'to': event['message']['sender_email'],
'content': welcome_text.format(event['message']['sender_short_name']),
"type": "private",
"to": event["message"]["sender_email"],
"content": welcome_text.format(event["message"]["sender_short_name"]),
}
)
set_watchlist(watchlist)
@ -92,7 +92,7 @@ def handle_event(event: Dict[str, Any]) -> None:
def start_event_handler() -> None:
print("Starting event handler...")
client.call_on_each_event(handle_event, event_types=['realm_user', 'message'])
client.call_on_each_event(handle_event, event_types=["realm_user", "message"])
client = zulip.Client()

View file

@ -10,25 +10,25 @@ import zulip
logging.basicConfig()
log = logging.getLogger('zulip-send')
log = logging.getLogger("zulip-send")
def do_send_message(client: zulip.Client, message_data: Dict[str, Any]) -> bool:
'''Sends a message and optionally prints status about the same.'''
"""Sends a message and optionally prints status about the same."""
if message_data['type'] == 'stream':
if message_data["type"] == "stream":
log.info(
'Sending message to stream "%s", subject "%s"... '
% (message_data['to'], message_data['subject'])
% (message_data["to"], message_data["subject"])
)
else:
log.info('Sending message to %s... ' % (message_data['to'],))
log.info("Sending message to %s... " % (message_data["to"],))
response = client.send_message(message_data)
if response['result'] == 'success':
log.info('Message sent.')
if response["result"] == "success":
log.info("Message sent.")
return True
else:
log.error(response['msg'])
log.error(response["msg"])
return False
@ -46,27 +46,27 @@ def main() -> int:
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage=usage))
parser.add_argument(
'recipients', nargs='*', help='email addresses of the recipients of the message'
"recipients", nargs="*", help="email addresses of the recipients of the message"
)
parser.add_argument(
'-m', '--message', help='Specifies the message to send, prevents interactive prompting.'
"-m", "--message", help="Specifies the message to send, prevents interactive prompting."
)
group = parser.add_argument_group('Stream parameters')
group = parser.add_argument_group("Stream parameters")
group.add_argument(
'-s',
'--stream',
dest='stream',
action='store',
help='Allows the user to specify a stream for the message.',
"-s",
"--stream",
dest="stream",
action="store",
help="Allows the user to specify a stream for the message.",
)
group.add_argument(
'-S',
'--subject',
dest='subject',
action='store',
help='Allows the user to specify a subject for the message.',
"-S",
"--subject",
dest="subject",
action="store",
help="Allows the user to specify a subject for the message.",
)
options = parser.parse_args()
@ -75,11 +75,11 @@ def main() -> int:
logging.getLogger().setLevel(logging.INFO)
# Sanity check user data
if len(options.recipients) != 0 and (options.stream or options.subject):
parser.error('You cannot specify both a username and a stream/subject.')
parser.error("You cannot specify both a username and a stream/subject.")
if len(options.recipients) == 0 and (bool(options.stream) != bool(options.subject)):
parser.error('Stream messages must have a subject')
parser.error("Stream messages must have a subject")
if len(options.recipients) == 0 and not (options.stream and options.subject):
parser.error('You must specify a stream/subject or at least one recipient.')
parser.error("You must specify a stream/subject or at least one recipient.")
client = zulip.init_from_options(options)
@ -88,16 +88,16 @@ def main() -> int:
if options.stream:
message_data = {
'type': 'stream',
'content': options.message,
'subject': options.subject,
'to': options.stream,
"type": "stream",
"content": options.message,
"subject": options.subject,
"to": options.stream,
}
else:
message_data = {
'type': 'private',
'content': options.message,
'to': options.recipients,
"type": "private",
"content": options.message,
"to": options.recipients,
}
if not do_send_message(client, message_data):
@ -105,5 +105,5 @@ def main() -> int:
return 0
if __name__ == '__main__':
if __name__ == "__main__":
sys.exit(main())