commit 747cb2f03632567f81a7274287d7e99b87ec4824 Author: viridian Date: Tue Oct 8 19:20:05 2024 +0200 initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..eddfc89 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +secrets.py +lib/ +bin/ +__pycache__/ +lib64 diff --git a/config.py b/config.py new file mode 100644 index 0000000..84245a6 --- /dev/null +++ b/config.py @@ -0,0 +1,3 @@ +instance = 'https://plasmatrap.com' +antenna = '9z48cl4wkb' +prometheus_port = 8000 diff --git a/main.py b/main.py new file mode 100644 index 0000000..6ebe9f4 --- /dev/null +++ b/main.py @@ -0,0 +1,34 @@ +import asyncio +import config +import secrets +from aiohttp import ClientWebSocketResponse +from mipa.ext import commands +from mipac.models.note import Note +from prometheus_client import Counter, start_http_server + +MATCHING_NOTES = Counter('matching_notes', 'Amount of notes in the antenna') + +class MyBot(commands.Bot): + def __init__(self): + super().__init__() + + async def _connect_channel(self): + await self.router.connect_channel(['antenna'], config.antenna) + + async def on_ready(self, ws: ClientWebSocketResponse): + print(f'connected: {self.user.username}') + await self._connect_channel() + + async def on_reconnect(self, ws: ClientWebSocketResponse): + print('Disconnected from server. Will try to reconnect.') + await self._connect_channel() + + async def on_note(self, note: Note): + MATCHING_NOTES.inc() + + +if __name__ == '__main__': + start_http_server(config.prometheus_port) + + bot = MyBot() + asyncio.run(bot.start(config.instance, secrets.token)) diff --git a/modules/MiPA/.editorconfig b/modules/MiPA/.editorconfig new file mode 100644 index 0000000..d5ef61f --- /dev/null +++ b/modules/MiPA/.editorconfig @@ -0,0 +1,13 @@ +root = true + + +[*] +end_of_line = lf +insert_final_newline = true + +[*.py] +charset = utf-8 + +[*.py] +indent_style = space +indent_size = 4 diff --git a/modules/MiPA/.flake8 b/modules/MiPA/.flake8 new file mode 100644 index 0000000..743147a --- /dev/null +++ b/modules/MiPA/.flake8 @@ -0,0 +1,4 @@ +[flake8] +per-file-ignores= + ./mipa/__init__.py:E402,F403,F401 + ./mipa/**/__init__.py:F403,F401 diff --git a/modules/MiPA/.gitattributes b/modules/MiPA/.gitattributes new file mode 100644 index 0000000..a1996a5 --- /dev/null +++ b/modules/MiPA/.gitattributes @@ -0,0 +1 @@ +mipa/_version.py export-subst diff --git a/modules/MiPA/.github/workflows/python-publish.yml b/modules/MiPA/.github/workflows/python-publish.yml new file mode 100644 index 0000000..1c0b6e0 --- /dev/null +++ b/modules/MiPA/.github/workflows/python-publish.yml @@ -0,0 +1,31 @@ +name: Upload Python Package + +on: + release: + types: [published] + +permissions: + contents: read + +jobs: + deploy: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up Python + uses: actions/setup-python@v3 + with: + python-version: '3.11' + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install build + - name: Build package + run: python -m build + - name: Publish package + uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29 + with: + user: __token__ + password: ${{ secrets.PYPI_API_TOKEN }} diff --git a/modules/MiPA/.gitignore b/modules/MiPA/.gitignore new file mode 100644 index 0000000..e3bce87 --- /dev/null +++ b/modules/MiPA/.gitignore @@ -0,0 +1,7 @@ +.venv +main.py +__pycache__ +*.egg-info +build +dist +!examples/**/main.py diff --git a/modules/MiPA/.onedev-buildspec.yml b/modules/MiPA/.onedev-buildspec.yml new file mode 100644 index 0000000..3ecfd83 --- /dev/null +++ b/modules/MiPA/.onedev-buildspec.yml @@ -0,0 +1,29 @@ +version: 15 +jobs: +- name: test + steps: + - !CheckoutStep + name: checkout + cloneCredential: !DefaultCredential {} + withLfs: false + withSubmodules: false + condition: ALL_PREVIOUS_STEPS_WERE_SUCCESSFUL + - !CommandStep + name: check error + runInContainer: true + image: python:3.10.4-slim + interpreter: !DefaultInterpreter + commands: + - pip install . .[ci] + - mypy mipac + - flake8 mipac + useTTY: true + condition: ALL_PREVIOUS_STEPS_WERE_SUCCESSFUL + triggers: + - !BranchUpdateTrigger {} + retryCondition: never + maxRetries: 3 + retryDelay: 30 + cpuRequirement: 250 + memoryRequirement: 256 + timeout: 3600 diff --git a/modules/MiPA/CHANGELOG.md b/modules/MiPA/CHANGELOG.md new file mode 100644 index 0000000..db57f1f --- /dev/null +++ b/modules/MiPA/CHANGELOG.md @@ -0,0 +1,241 @@ +# Change Log + +## v0.4.2 + +[compare changes](https://github.com/yupix/MiPA/compare/0.4.1...v0.4.2) + +### 🏡 Chore + +- MiPACのバージョンを0.7.0以上0.8.0まで許可するように + - MiPACの最低バージョンが0.7.0に変更されています。詳細は [MiPACのリリースノート](https://github.com/yupix/MiPAC/releases/tag/0.7.0) をご覧ください。 + +### ❤️ Contributors + +- Yupix ([@yupix](http://github.com/yupix)) + +## v0.4.1 + +[compare changes](https://github.com/yupix/MiPA/compare/0.4.0...v0.4.1) + +### 🏡 Chore + +- MiPACのバージョンを0.7.0までは許可するように ([4bc8aec](https://github.com/yupix/MiPA/commit/4bc8aec)) + +### ❤️ Contributors + +- Yupix ([@yupix](http://github.com/yupix)) + +## v0.4.0 + +このバージョンから developブランチは v13以降のみをサポートします。今まで通りの全てのイベントがあるのは shared ブランチのみとなります + +[compare changes](https://github.com/yupix/MiPA/compare/0.3.5...v0.4.0) + +### 🚀 Enhancements + +- MiPAC v0.6.0への対応 ([36494ef](https://github.com/yupix/MiPA/commit/36494ef)) +- Python3.12を必須に ([2abd5ed](https://github.com/yupix/MiPA/commit/2abd5ed)) + +### 🩹 Fixes + +- Timelinesがpackagesに含まれていない ([d0caa63](https://github.com/yupix/MiPA/commit/d0caa63)) +- 直せる範囲で型エラーを修正 ([8e5a58d](https://github.com/yupix/MiPA/commit/8e5a58d)) + +### ❤️ Contributors + +- Yupix ([@yupix](http://github.com/yupix)) + +## [0.3.5] 2023-11-18 + +### Fixed + +- 0.3.4 では直しきれなかった一部の不具合を修正しました + +## [0.3.4] 2023-11-01 + +### Fixed + +- ほとんどのイベントで引数エラーが発生する + +## [0.3.1] 2023-10-30 + +### Added + +#### チャンネルに接続した際、チャンネル名と UUID の dict が帰ってくるように + +例としては以下のような物が返ってきます。 + +```python +await self.router.connect_channel(['main', 'home']) +>>> {'main': 'ce9b318b-3f7b-4227-b843-1b694112567e', 'home': '934b460d-50c5-463e-b975-9db7bf6ba42d'} +``` + +この ID は `connect_channel` を実行した際にのみ `チャンネル名: UUID` という形式になっており他の場所で取得したい場合は `router.channel_ids` プロパティを使用する必要があります。この場合は `UUID: チャンネル名` というキーと値が逆の状態で取得されるため注意してください。 + +#### チャンネルを切断できるように + +最初に紹介した チャンネル名と UUID の dict を用いて特定のチャンネルから切断できるようになりました。 + +```python +channel_ids = await self.router.connect_channel(['main', 'home']) +await self.router.disconnect_channel(channel_ids['main']) +``` + +#### チャンネルごとに専用のクラスを使用できるように + +以下のように グローバルタイムラインに対して `AbstractTimeline` を継承した `GlobalTimeline` を実装することで作成が可能です。 `on_note` メソッドを抽象クラスに沿って作成する必要もあります。また、別にクラスを渡したくないけど、チャンネルには接続したいという場合は `None` を値として渡してください。 + +注意点として、チャンネル専用のクラスを渡したからと言って、今回の場合でいう `MyBot` クラスにある `on_note` が発火されなくなるわけではありません。この機能の追加は多くのチャンネルに接続したいが、それぞれに別々の処理を実行したい場合を想定しています。そのため、`MyBot` 側の `on_note` には今までと変わらず**全ての**チャンネルのノートが流れてきます。 + +```python +from aiohttp import ClientWebSocketResponse +from loguru import logger +from mipac import Note + +from mipa.ext.commands.bot import Bot +from mipa.ext.timelines.core import AbstractTimeline + + +class GlobalTimeline(AbstractTimeline): + async def on_note(self, note: Note): + logger.info(f'{note.author.username}: {note.content}') + +class MyBot(Bot): + def __init__(self): + super().__init__() + + async def _connect_channel(self): + await self.router.connect_channel({'global': GlobalTimeline(), 'main': None, 'home': None}) + + async def on_ready(self, ws: ClientWebSocketResponse): + await self._connect_channel() + logger.info('Logged in ', self.user.username) +``` + +また、この機能が追加されたからと言って、今までのコードに特別な変更は必要ありません。今まで通りの `list` 形式の引数も引き続きサポートしています。 + +```python +await self.router.connect_channel(['global', 'main', 'home']) +``` + +## [0.3.0] 2023-04-25 + +### Changes by Package 📦 + +MiPAC に破壊的変更を含む更新があるため、よく MiPAC の CHANGELOG を読むことを推奨します。 + +- [MiPAC](https://github.com/yupix/MiPAC/releases) + +### Changed + +- [@omg-xtao](https://github.com/omg-xtao) can cancel setup_logging when init client. + +## [0.2.2] 2023-04-25 + +### Added + +- v13, v12? で 絵文字が削除された際に `on_emoji_deleted` イベントを発火するように +- v13, v12? で 絵文字が更新された際に `on_emoji_updated` イベントを発火するように + +### Changed + +- 使用する MiPAC のバージョンを`0.4.3`に + - 詳しい変更点は[こちらをご覧ください](https://github.com/yupix/MiPAC/releases) + +### Fixed + +- `Cog.listener` を使った際に型エラーが出る + +## [0.2.1] 2023-03-22 + +### Changed + +- 使用する MiPAC のバージョンを`0.4.2`に + +## [0.2.0] 2023-03-20 + +### Added + +- `setup_hook` イベントが追加されました + - `load_extension` 等はこのイベントで行うことを推奨します +- `ExtensionNotLoaded` 例外が追加されました + +### Changed + +- **BREAKING CHANGES** 以下のメソッドが非同期になります + - Cogs 内の `setup` 関数 + - `add_cog` + - `remove_cog` + - `load_extension` + +### Fixed + +- `tasks.loop` をクラス内で使用すると `self` が受け取れない + +## [0.1.2] 2023-03-14 + +### Added + +- ✨ added event `on_achievement_earned`. +- ✨ added `disconnect` method to `Client` class. + +### Fixed + +- incorrect URL for streaming API #16, #17 + +### Changed + +- 使用する MiPAC のバージョンを`0.4.1`に + +## [0.1.1] 2023-01-18 + +### Added + +- ✨ feat: support all notifications #MA-11 + - `on_user_follow` when you follow a user + - `on_user_unfollow` when you unfollow a user + - `on_user_followed` when someone follows you + - `on_mention` when someone mentions you + - `on_reply` when someone replies to your note + - `on_renote` when someone renote your note + - `on_quote` when someone quote your note + - `on_reaction` when someone react to your note + - `on_poll_vote` when someone vote to your poll + - `on_poll_end` when a poll is ended + - `on_follow_request` when someone send you a follow request + - `on_follow_request_accept` when someone accept your follow request + +### Changed + +- 使用する MiPAC のバージョンを`0.4.0`に + +### Fixed + +- 🐛 fix: ws reconnect +- 🐛 fix: Separate unread chat message + +## [0.1.0] 2022-12-24 + +### Added + +- ✨ feat: add .flake8 config. +- ✨ feat: To be able to capture notes. +- ✨ added event `on_note_deleted`. +- ✨ added event `on_reacted`. +- ✨ added event `on_unreacted`. +- ✨ added `router` property a `Client` class attributes. + - 💡 Direct instantiation of the `Router` class is deprecated. +- [@omg-xtao](https://github.com/omg-xtao) ✨ feat: added `hybridTimeline` channel [#9](https://github.com/yupix/MiPA/pull/9). + +### Changed + +- ⬆️ feat(deps): update mipac update mipac version. +- ✨ chore: Changed `parse_` lineage functions to asynchronous. +- 💥 feat: **BREAKING CHANGE** Change event name `on_message` from `on_note`. +- 💥 feat: **BREAKING CHANGE** Required Python version is 3.11. + +### Fixed + +- 🐛 fix: not working command Framework. +- 🐛 fix: Chat related stuff is flowing `on_message`. + - 💡 Please use `on_chat` in the future! diff --git a/modules/MiPA/LICENSE b/modules/MiPA/LICENSE new file mode 100644 index 0000000..0bdd348 --- /dev/null +++ b/modules/MiPA/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 yupix + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/modules/MiPA/MANIFEST.in b/modules/MiPA/MANIFEST.in new file mode 100644 index 0000000..03ab1dd --- /dev/null +++ b/modules/MiPA/MANIFEST.in @@ -0,0 +1,7 @@ +include README.md +include LICENSE +include requirements.txt +graft mipa +recursive-exclude * *.py[co] +include versioneer.py +include mipa/_version.py diff --git a/modules/MiPA/README.md b/modules/MiPA/README.md new file mode 100644 index 0000000..4961a73 --- /dev/null +++ b/modules/MiPA/README.md @@ -0,0 +1,81 @@ +# MiPA + +Discord server invite +[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff) + + +## Overview + +[日本語版](./README_JP.md) + +MiPA is a Misskey Bot Framework created to allow for [Discord.py](https://github.com/Rapptz/discord.py)-like coding. + + +## About MiPAC +The API wrapper functionality provided by MiPA is managed by a library called [MiPAC](https://github.com/yupix/mipac). Since the amount of work is significantly higher than that of MiPA, we are looking for people to work with us. + + +## Supported Misskey Versions + +- [Misskey Official v13](https://github.com/misskey-dev/misskey) +- [Misskey Official v12](https://github.com/misskey-dev/misskey) +- [Misskey Official v11](https://github.com/misskey-dev/misskey) + +### Examples + +```py +import asyncio + +from aiohttp import ClientWebSocketResponse +from mipac.models.note import Note + +from mipa.ext.commands.bot import Bot + + +class MyBot(Bot): + def __init__(self): + super().__init__() + + async def _connect_channel(self): + await self.router.connect_channel(['main', 'home']) + + async def on_ready(self, ws: ClientWebSocketResponse): + await self._connect_channel() + print('Logged in ', self.user.username) + + async def on_reconnect(self, ws: ClientWebSocketResponse): + await self._connect_channel() + + async def on_note(self, note: Note): + print(note.author.username, note.content) + + +if __name__ == '__main__': + bot = MyBot() + asyncio.run(bot.start('wss://example.com/streaming', 'your token here')) +``` + +For more examples, please see the [examples folder](examples). If you don't know how to do what you want in the examples, please feel free to create an issue. + + + + +## LICENSE +This project is provided under the [MIT LICENSE](./LICENSE). + +MiPA has been inspired by Discord.py in many ways. Therefore, in places where we use the source code of Discord.py, we specify the license of Discord.py at the beginning of the file. Please check the code for details. + + + +[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fyupix%2FMiPA.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Fyupix%2FMiPA?ref=badge_large) + +## Special Thanks + +- [Discord.py](https://github.com/Rapptz/discord.py) + - We have been inspired by many aspects of Discord.py, such as the mechanism of Cogs and the management of tasks and states. + +

+ Documentation + * + Discord Server +

diff --git a/modules/MiPA/README_JP.md b/modules/MiPA/README_JP.md new file mode 100644 index 0000000..a8162f9 --- /dev/null +++ b/modules/MiPA/README_JP.md @@ -0,0 +1,79 @@ +# MiPA + +Discord server invite +[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff) + + +## 概要 + +[English](./README.md) + +MiPA は[Discord.py](https://github.com/Rapptz/discord.py) +ライクな書き方ができるように作っている Misskey Bot Frameworkです。 + +## MiPACについて + +MiPAが提供するApi Wrapperとしての機能は [MiPAC](https://github.com/yupix/mipac) と呼ばれるライブラリで管理されています。MiPAと比較して作業量が非常に多いため一緒に作業をしてくださる方を募集しています。 + + +## サポートしているMisskey + +- [Misskey Official v13](https://github.com/misskey-dev/misskey) +- [Misskey Official v12](https://github.com/misskey-dev/misskey) +- [Misskey Official v11](https://github.com/misskey-dev/misskey) + +### Examples + +```py +import asyncio + +from aiohttp import ClientWebSocketResponse +from mipac.models.note import Note + +from mipa.ext.commands.bot import Bot + + +class MyBot(Bot): + def __init__(self): + super().__init__() + + async def _connect_channel(self): + await self.router.connect_channel(['main', 'home']) + + async def on_ready(self, ws: ClientWebSocketResponse): + await self._connect_channel() + print('Logged in ', self.user.username) + + async def on_reconnect(self, ws: ClientWebSocketResponse): + await self._connect_channel() + + async def on_note(self, note: Note): + print(note.author.username, note.content) + + +if __name__ == '__main__': + bot = MyBot() + asyncio.run(bot.start('wss://example.com/streaming', 'your token here')) +``` + +より多くの例は [examples フォルダ](examples) をご覧ください。もしexamplesであなたのしたいことが分からなかった場合は遠慮なくIssueを作成してください。 + +## LICENSE + +このプロジェクトは [MIT LICENSE](./LICENSE) で提供されます。 + +MiPAでは多くの部分においてDiscord.pyを参考にさせていただきました。そのため、Discord.pyのソースコードを利用させていただいている個所ではファイルの初めにDiscord.py側のライセンスを明記しています。詳しくはコードを確認してください。 + + +[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fyupix%2FMiPA.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Fyupix%2FMiPA?ref=badge_large) + +## Special Thanks + +- [Discord.py](https://github.com/Rapptz/discord.py) + - Cogの仕組みやtask,stateの管理等多くの部分で参考にさせていただきました。 + +

+ Documentation + * + Discord Server +

diff --git a/modules/MiPA/cogs/basic.py b/modules/MiPA/cogs/basic.py new file mode 100644 index 0000000..baf4a7d --- /dev/null +++ b/modules/MiPA/cogs/basic.py @@ -0,0 +1,18 @@ +import asyncio +from mipa.ext import commands +from mipa.ext.commands.bot import Bot +from mipa.ext.commands.context import Context + +class BasicCog(commands.Cog): + def __init__(self, bot: Bot) -> None: + self.bot = bot + + @commands.mention_command(regex=r'(\d+)秒タイマー') + async def timer(self, ctx: Context, time: str): + await ctx.message.api.action.reply(f'{time}秒ですね。よーいドン!') + await asyncio.sleep(int(time)) + await ctx.message.api.action.reply(f'{time}秒経ちました!') + + +async def setup(bot: Bot): + await bot.add_cog(BasicCog(bot)) diff --git a/modules/MiPA/examples/split_timeline/main.py b/modules/MiPA/examples/split_timeline/main.py new file mode 100644 index 0000000..127ca0e --- /dev/null +++ b/modules/MiPA/examples/split_timeline/main.py @@ -0,0 +1,33 @@ +import asyncio + +from aiohttp import ClientWebSocketResponse +from mipac import Note + +from mipa.ext.commands.bot import Bot +from mipa.ext.timelines.core import AbstractTimeline + +class GlobalTimeline(AbstractTimeline): + async def on_note(self, note: Note): # This event is only received in the global timeline notes + print(f'{note.author.username}: {note.content}') + +class MyBot(Bot): + def __init__(self): + super().__init__() + + async def _connect_channel(self): + await self.router.connect_channel({'global': GlobalTimeline(), 'main': None, 'home': None}) + + async def on_ready(self, ws: ClientWebSocketResponse): + await self._connect_channel() + print('Logged in ', self.user.username) + + async def on_reconnect(self, ws: ClientWebSocketResponse): + await self._connect_channel() + + async def on_note(self, note: Note): # This event receives all channel notes + print(f'{note.author.username}: {note.content}') + + +if __name__ == '__main__': + bot = MyBot() + asyncio.run(bot.start('instance url', 'your token')) \ No newline at end of file diff --git a/modules/MiPA/examples/use_cog/cogs/basic.py b/modules/MiPA/examples/use_cog/cogs/basic.py new file mode 100644 index 0000000..9e6768b --- /dev/null +++ b/modules/MiPA/examples/use_cog/cogs/basic.py @@ -0,0 +1,23 @@ +import asyncio +from mipa.ext import commands +from mipa.ext.commands.bot import Bot +from mipa.ext.commands.context import Context + +class BasicCog(commands.Cog): + def __init__(self, bot: Bot) -> None: + self.bot = bot + + @commands.mention_command(text='hello') + async def hello(self, ctx: Context): + await ctx.message.api.action.reply(f'hello! {ctx.message.author.username}') + + + @commands.mention_command(regex=r'(\d+) second timer') + async def timer(self, ctx: Context, time: str): + await ctx.message.api.action.reply(f'That\'s {time} seconds. Okay, start') + await asyncio.sleep(int(time)) + await ctx.message.api.action.reply(f'{time} seconds have passed!') + + +async def setup(bot: Bot): + await bot.add_cog(BasicCog(bot)) diff --git a/modules/MiPA/examples/use_cog/main.py b/modules/MiPA/examples/use_cog/main.py new file mode 100644 index 0000000..6924211 --- /dev/null +++ b/modules/MiPA/examples/use_cog/main.py @@ -0,0 +1,40 @@ +import asyncio + +from aiohttp import ClientWebSocketResponse +from mipac.models.notification import NotificationNote +from mipa.ext import commands +from mipac.models.note import Note + +COGS = [ + 'cogs.basic' +] + +class MyBot(commands.Bot): + def __init__(self): + super().__init__() + + async def _connect_channel(self): + await self.router.connect_channel(['main', 'global']) + + async def on_ready(self, ws: ClientWebSocketResponse): + print(f'connected: {self.user.username}') + await self._connect_channel() + for cog in COGS: + await self.load_extension(cog) + + async def on_reconnect(self, ws: ClientWebSocketResponse): + print('Disconnected from server. Will try to reconnect.') + await self._connect_channel() + + async def on_note(self, note: Note): + print(f'{note.author.username}: {note.content}') + + async def on_mention(self, notice: NotificationNote): + + # When using this event, if you use MENTION_COMMAND, you must call this method for it to work. + await self.progress_command(notice) + + +if __name__ == '__main__': + bot = MyBot() + asyncio.run(bot.start('instance url', 'your token')) \ No newline at end of file diff --git a/modules/MiPA/mipa/__init__.py b/modules/MiPA/mipa/__init__.py new file mode 100644 index 0000000..912815b --- /dev/null +++ b/modules/MiPA/mipa/__init__.py @@ -0,0 +1,21 @@ +from ._version import get_versions + +__title__ = "mipa" +__author__ = "yupix" +__license__ = "MIT" +__copyright__ = "Copyright 2022-present yupix" +__author_email__ = "yupi0982@outlook.jp" +__version__ = get_versions()["version"] + +__path__ = __import__("pkgutil").extend_path(__path__, __name__) + +del get_versions + +from .client import Client +from .ext import * + +__all__ = ("Client",) + +from . import _version + +__version__ = _version.get_versions()["version"] diff --git a/modules/MiPA/mipa/_version.py b/modules/MiPA/mipa/_version.py new file mode 100644 index 0000000..28e1aa0 --- /dev/null +++ b/modules/MiPA/mipa/_version.py @@ -0,0 +1,710 @@ +# This file helps to compute a version number in source trees obtained from +# git-archive tarball (such as those provided by githubs download-from-tag +# feature). Distribution tarballs (built by setup.py sdist) and build +# directories (produced by setup.py build) will contain a much shorter file +# that just contains the computed version number. + +# This file is released into the public domain. +# Generated by versioneer-0.28 +# https://github.com/python-versioneer/python-versioneer + +"""Git implementation of _version.py.""" + +import errno +import functools +import os +import re +import subprocess +import sys +from typing import Callable, Dict + + +def get_keywords(): + """Get the keywords needed to look up the version information.""" + # these strings will be replaced by git during git-archive. + # setup.py/versioneer.py will grep for the variable names, so they must + # each be defined on a line of their own. _version.py will just call + # get_keywords(). + git_refnames = '$Format:%d$' + git_full = '$Format:%H$' + git_date = '$Format:%ci$' + keywords = {'refnames': git_refnames, 'full': git_full, 'date': git_date} + return keywords + + +class VersioneerConfig: + """Container for Versioneer configuration parameters.""" + + +def get_config(): + """Create, populate and return the VersioneerConfig() object.""" + # these strings are filled in when 'setup.py versioneer' creates + # _version.py + cfg = VersioneerConfig() + cfg.VCS = 'git' + cfg.style = 'pep440' + cfg.tag_prefix = '' + cfg.parentdir_prefix = '' + cfg.versionfile_source = 'mipa/_version.py' + cfg.verbose = False + return cfg + + +class NotThisMethod(Exception): + """Exception raised if a method is not valid for the current scenario.""" + + +LONG_VERSION_PY: Dict[str, str] = {} +HANDLERS: Dict[str, Dict[str, Callable]] = {} + + +def register_vcs_handler(vcs, method): # decorator + """Create decorator to mark a method as the handler of a VCS.""" + + def decorate(f): + """Store f in HANDLERS[vcs][method].""" + if vcs not in HANDLERS: + HANDLERS[vcs] = {} + HANDLERS[vcs][method] = f + return f + + return decorate + + +def run_command( + commands, args, cwd=None, verbose=False, hide_stderr=False, env=None +): + """Call the given command(s).""" + assert isinstance(commands, list) + process = None + + popen_kwargs = {} + if sys.platform == 'win32': + # This hides the console window if pythonw.exe is used + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + popen_kwargs['startupinfo'] = startupinfo + + for command in commands: + try: + dispcmd = str([command] + args) + # remember shell=False, so use git.cmd on windows, not just git + process = subprocess.Popen( + [command] + args, + cwd=cwd, + env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr else None), + **popen_kwargs, + ) + break + except OSError: + e = sys.exc_info()[1] + if e.errno == errno.ENOENT: + continue + if verbose: + print('unable to run %s' % dispcmd) + print(e) + return None, None + else: + if verbose: + print('unable to find command, tried %s' % (commands,)) + return None, None + stdout = process.communicate()[0].strip().decode() + if process.returncode != 0: + if verbose: + print('unable to run %s (error)' % dispcmd) + print('stdout was %s' % stdout) + return None, process.returncode + return stdout, process.returncode + + +def versions_from_parentdir(parentdir_prefix, root, verbose): + """Try to determine the version from the parent directory name. + + Source tarballs conventionally unpack into a directory that includes both + the project name and a version string. We will also support searching up + two directory levels for an appropriately named parent directory + """ + rootdirs = [] + + for _ in range(3): + dirname = os.path.basename(root) + if dirname.startswith(parentdir_prefix): + return { + 'version': dirname[len(parentdir_prefix) :], + 'full-revisionid': None, + 'dirty': False, + 'error': None, + 'date': None, + } + rootdirs.append(root) + root = os.path.dirname(root) # up a level + + if verbose: + print( + 'Tried directories %s but none started with prefix %s' + % (str(rootdirs), parentdir_prefix) + ) + raise NotThisMethod("rootdir doesn't start with parentdir_prefix") + + +@register_vcs_handler('git', 'get_keywords') +def git_get_keywords(versionfile_abs): + """Extract version information from the given file.""" + # the code embedded in _version.py can just fetch the value of these + # keywords. When used from setup.py, we don't want to import _version.py, + # so we do it with a regexp instead. This function is not used from + # _version.py. + keywords = {} + try: + with open(versionfile_abs, 'r') as fobj: + for line in fobj: + if line.strip().startswith('git_refnames ='): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords['refnames'] = mo.group(1) + if line.strip().startswith('git_full ='): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords['full'] = mo.group(1) + if line.strip().startswith('git_date ='): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords['date'] = mo.group(1) + except OSError: + pass + return keywords + + +@register_vcs_handler('git', 'keywords') +def git_versions_from_keywords(keywords, tag_prefix, verbose): + """Get version information from git keywords.""" + if 'refnames' not in keywords: + raise NotThisMethod('Short version file found') + date = keywords.get('date') + if date is not None: + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + + # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant + # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 + # -like" string, which we must then edit to make compliant), because + # it's been around since git-1.5.3, and it's too difficult to + # discover which version we're using, or to work around using an + # older one. + date = date.strip().replace(' ', 'T', 1).replace(' ', '', 1) + refnames = keywords['refnames'].strip() + if refnames.startswith('$Format'): + if verbose: + print('keywords are unexpanded, not using') + raise NotThisMethod('unexpanded keywords, not a git-archive tarball') + refs = {r.strip() for r in refnames.strip('()').split(',')} + # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of + # just "foo-1.0". If we see a "tag: " prefix, prefer those. + TAG = 'tag: ' + tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)} + if not tags: + # Either we're using git < 1.8.3, or there really are no tags. We use + # a heuristic: assume all version tags have a digit. The old git %d + # expansion behaves like git log --decorate=short and strips out the + # refs/heads/ and refs/tags/ prefixes that would let us distinguish + # between branches and tags. By ignoring refnames without digits, we + # filter out many common branch names like "release" and + # "stabilization", as well as "HEAD" and "master". + tags = {r for r in refs if re.search(r'\d', r)} + if verbose: + print("discarding '%s', no digits" % ','.join(refs - tags)) + if verbose: + print('likely tags: %s' % ','.join(sorted(tags))) + for ref in sorted(tags): + # sorting will prefer e.g. "2.0" over "2.0rc1" + if ref.startswith(tag_prefix): + r = ref[len(tag_prefix) :] + # Filter out refs that exactly match prefix or that don't start + # with a number once the prefix is stripped (mostly a concern + # when prefix is '') + if not re.match(r'\d', r): + continue + if verbose: + print('picking %s' % r) + return { + 'version': r, + 'full-revisionid': keywords['full'].strip(), + 'dirty': False, + 'error': None, + 'date': date, + } + # no suitable tags, so version is "0+unknown", but full hex is still there + if verbose: + print('no suitable tags, using unknown + full revision id') + return { + 'version': '0+unknown', + 'full-revisionid': keywords['full'].strip(), + 'dirty': False, + 'error': 'no suitable tags', + 'date': None, + } + + +@register_vcs_handler('git', 'pieces_from_vcs') +def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): + """Get version from 'git describe' in the root of the source tree. + + This only gets called if the git-archive 'subst' keywords were *not* + expanded, and _version.py hasn't already been rewritten with a short + version string, meaning we're inside a checked out source tree. + """ + GITS = ['git'] + if sys.platform == 'win32': + GITS = ['git.cmd', 'git.exe'] + + # GIT_DIR can interfere with correct operation of Versioneer. + # It may be intended to be passed to the Versioneer-versioned project, + # but that should not change where we get our version from. + env = os.environ.copy() + env.pop('GIT_DIR', None) + runner = functools.partial(runner, env=env) + + _, rc = runner( + GITS, ['rev-parse', '--git-dir'], cwd=root, hide_stderr=not verbose + ) + if rc != 0: + if verbose: + print('Directory %s not under git control' % root) + raise NotThisMethod("'git rev-parse --git-dir' returned error") + + # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] + # if there isn't one, this yields HEX[-dirty] (no NUM) + describe_out, rc = runner( + GITS, + [ + 'describe', + '--tags', + '--dirty', + '--always', + '--long', + '--match', + f'{tag_prefix}[[:digit:]]*', + ], + cwd=root, + ) + # --long was added in git-1.5.5 + if describe_out is None: + raise NotThisMethod("'git describe' failed") + describe_out = describe_out.strip() + full_out, rc = runner(GITS, ['rev-parse', 'HEAD'], cwd=root) + if full_out is None: + raise NotThisMethod("'git rev-parse' failed") + full_out = full_out.strip() + + pieces = {} + pieces['long'] = full_out + pieces['short'] = full_out[:7] # maybe improved later + pieces['error'] = None + + branch_name, rc = runner( + GITS, ['rev-parse', '--abbrev-ref', 'HEAD'], cwd=root + ) + # --abbrev-ref was added in git-1.6.3 + if rc != 0 or branch_name is None: + raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") + branch_name = branch_name.strip() + + if branch_name == 'HEAD': + # If we aren't exactly on a branch, pick a branch which represents + # the current commit. If all else fails, we are on a branchless + # commit. + branches, rc = runner(GITS, ['branch', '--contains'], cwd=root) + # --contains was added in git-1.5.4 + if rc != 0 or branches is None: + raise NotThisMethod("'git branch --contains' returned error") + branches = branches.split('\n') + + # Remove the first line if we're running detached + if '(' in branches[0]: + branches.pop(0) + + # Strip off the leading "* " from the list of branches. + branches = [branch[2:] for branch in branches] + if 'master' in branches: + branch_name = 'master' + elif not branches: + branch_name = None + else: + # Pick the first branch that is returned. Good or bad. + branch_name = branches[0] + + pieces['branch'] = branch_name + + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] + # TAG might have hyphens. + git_describe = describe_out + + # look for -dirty suffix + dirty = git_describe.endswith('-dirty') + pieces['dirty'] = dirty + if dirty: + git_describe = git_describe[: git_describe.rindex('-dirty')] + + # now we have TAG-NUM-gHEX or HEX + + if '-' in git_describe: + # TAG-NUM-gHEX + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + if not mo: + # unparsable. Maybe git-describe is misbehaving? + pieces['error'] = ( + "unable to parse git-describe output: '%s'" % describe_out + ) + return pieces + + # tag + full_tag = mo.group(1) + if not full_tag.startswith(tag_prefix): + if verbose: + fmt = "tag '%s' doesn't start with prefix '%s'" + print(fmt % (full_tag, tag_prefix)) + pieces['error'] = "tag '%s' doesn't start with prefix '%s'" % ( + full_tag, + tag_prefix, + ) + return pieces + pieces['closest-tag'] = full_tag[len(tag_prefix) :] + + # distance: number of commits since tag + pieces['distance'] = int(mo.group(2)) + + # commit: short hex revision ID + pieces['short'] = mo.group(3) + + else: + # HEX: no tags + pieces['closest-tag'] = None + out, rc = runner(GITS, ['rev-list', 'HEAD', '--left-right'], cwd=root) + pieces['distance'] = len(out.split()) # total number of commits + + # commit date: see ISO-8601 comment in git_versions_from_keywords() + date = runner(GITS, ['show', '-s', '--format=%ci', 'HEAD'], cwd=root)[ + 0 + ].strip() + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + pieces['date'] = date.strip().replace(' ', 'T', 1).replace(' ', '', 1) + + return pieces + + +def plus_or_dot(pieces): + """Return a + if we don't already have one, else return a .""" + if '+' in pieces.get('closest-tag', ''): + return '.' + return '+' + + +def render_pep440(pieces): + """Build up version string, with post-release "local version identifier". + + Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you + get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty + + Exceptions: + 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces['closest-tag']: + rendered = pieces['closest-tag'] + if pieces['distance'] or pieces['dirty']: + rendered += plus_or_dot(pieces) + rendered += '%d.g%s' % (pieces['distance'], pieces['short']) + if pieces['dirty']: + rendered += '.dirty' + else: + # exception #1 + rendered = '0+untagged.%d.g%s' % (pieces['distance'], pieces['short']) + if pieces['dirty']: + rendered += '.dirty' + return rendered + + +def render_pep440_branch(pieces): + """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . + + The ".dev0" means not master branch. Note that .dev0 sorts backwards + (a feature branch will appear "older" than the master branch). + + Exceptions: + 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces['closest-tag']: + rendered = pieces['closest-tag'] + if pieces['distance'] or pieces['dirty']: + if pieces['branch'] != 'master': + rendered += '.dev0' + rendered += plus_or_dot(pieces) + rendered += '%d.g%s' % (pieces['distance'], pieces['short']) + if pieces['dirty']: + rendered += '.dirty' + else: + # exception #1 + rendered = '0' + if pieces['branch'] != 'master': + rendered += '.dev0' + rendered += '+untagged.%d.g%s' % (pieces['distance'], pieces['short']) + if pieces['dirty']: + rendered += '.dirty' + return rendered + + +def pep440_split_post(ver): + """Split pep440 version string at the post-release segment. + + Returns the release segments before the post-release and the + post-release version number (or -1 if no post-release segment is present). + """ + vc = str.split(ver, '.post') + return vc[0], int(vc[1] or 0) if len(vc) == 2 else None + + +def render_pep440_pre(pieces): + """TAG[.postN.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post0.devDISTANCE + """ + if pieces['closest-tag']: + if pieces['distance']: + # update the post release segment + tag_version, post_version = pep440_split_post( + pieces['closest-tag'] + ) + rendered = tag_version + if post_version is not None: + rendered += '.post%d.dev%d' % ( + post_version + 1, + pieces['distance'], + ) + else: + rendered += '.post0.dev%d' % (pieces['distance']) + else: + # no commits, use the tag as the version + rendered = pieces['closest-tag'] + else: + # exception #1 + rendered = '0.post0.dev%d' % pieces['distance'] + return rendered + + +def render_pep440_post(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX] . + + The ".dev0" means dirty. Note that .dev0 sorts backwards + (a dirty tree will appear "older" than the corresponding clean one), + but you shouldn't be releasing software with -dirty anyways. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces['closest-tag']: + rendered = pieces['closest-tag'] + if pieces['distance'] or pieces['dirty']: + rendered += '.post%d' % pieces['distance'] + if pieces['dirty']: + rendered += '.dev0' + rendered += plus_or_dot(pieces) + rendered += 'g%s' % pieces['short'] + else: + # exception #1 + rendered = '0.post%d' % pieces['distance'] + if pieces['dirty']: + rendered += '.dev0' + rendered += '+g%s' % pieces['short'] + return rendered + + +def render_pep440_post_branch(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . + + The ".dev0" means not master branch. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] + """ + if pieces['closest-tag']: + rendered = pieces['closest-tag'] + if pieces['distance'] or pieces['dirty']: + rendered += '.post%d' % pieces['distance'] + if pieces['branch'] != 'master': + rendered += '.dev0' + rendered += plus_or_dot(pieces) + rendered += 'g%s' % pieces['short'] + if pieces['dirty']: + rendered += '.dirty' + else: + # exception #1 + rendered = '0.post%d' % pieces['distance'] + if pieces['branch'] != 'master': + rendered += '.dev0' + rendered += '+g%s' % pieces['short'] + if pieces['dirty']: + rendered += '.dirty' + return rendered + + +def render_pep440_old(pieces): + """TAG[.postDISTANCE[.dev0]] . + + The ".dev0" means dirty. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces['closest-tag']: + rendered = pieces['closest-tag'] + if pieces['distance'] or pieces['dirty']: + rendered += '.post%d' % pieces['distance'] + if pieces['dirty']: + rendered += '.dev0' + else: + # exception #1 + rendered = '0.post%d' % pieces['distance'] + if pieces['dirty']: + rendered += '.dev0' + return rendered + + +def render_git_describe(pieces): + """TAG[-DISTANCE-gHEX][-dirty]. + + Like 'git describe --tags --dirty --always'. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces['closest-tag']: + rendered = pieces['closest-tag'] + if pieces['distance']: + rendered += '-%d-g%s' % (pieces['distance'], pieces['short']) + else: + # exception #1 + rendered = pieces['short'] + if pieces['dirty']: + rendered += '-dirty' + return rendered + + +def render_git_describe_long(pieces): + """TAG-DISTANCE-gHEX[-dirty]. + + Like 'git describe --tags --dirty --always -long'. + The distance/hash is unconditional. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces['closest-tag']: + rendered = pieces['closest-tag'] + rendered += '-%d-g%s' % (pieces['distance'], pieces['short']) + else: + # exception #1 + rendered = pieces['short'] + if pieces['dirty']: + rendered += '-dirty' + return rendered + + +def render(pieces, style): + """Render the given version pieces into the requested style.""" + if pieces['error']: + return { + 'version': 'unknown', + 'full-revisionid': pieces.get('long'), + 'dirty': None, + 'error': pieces['error'], + 'date': None, + } + + if not style or style == 'default': + style = 'pep440' # the default + + if style == 'pep440': + rendered = render_pep440(pieces) + elif style == 'pep440-branch': + rendered = render_pep440_branch(pieces) + elif style == 'pep440-pre': + rendered = render_pep440_pre(pieces) + elif style == 'pep440-post': + rendered = render_pep440_post(pieces) + elif style == 'pep440-post-branch': + rendered = render_pep440_post_branch(pieces) + elif style == 'pep440-old': + rendered = render_pep440_old(pieces) + elif style == 'git-describe': + rendered = render_git_describe(pieces) + elif style == 'git-describe-long': + rendered = render_git_describe_long(pieces) + else: + raise ValueError("unknown style '%s'" % style) + + return { + 'version': rendered, + 'full-revisionid': pieces['long'], + 'dirty': pieces['dirty'], + 'error': None, + 'date': pieces.get('date'), + } + + +def get_versions(): + """Get version information or return default if unable to do so.""" + # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have + # __file__, we can work backwards from there to the root. Some + # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which + # case we can only use expanded keywords. + + cfg = get_config() + verbose = cfg.verbose + + try: + return git_versions_from_keywords( + get_keywords(), cfg.tag_prefix, verbose + ) + except NotThisMethod: + pass + + try: + root = os.path.realpath(__file__) + # versionfile_source is the relative path from the top of the source + # tree (where the .git directory might live) to this file. Invert + # this to find the root from __file__. + for _ in cfg.versionfile_source.split('/'): + root = os.path.dirname(root) + except NameError: + return { + 'version': '0+unknown', + 'full-revisionid': None, + 'dirty': None, + 'error': 'unable to find root of source tree', + 'date': None, + } + + try: + pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) + return render(pieces, cfg.style) + except NotThisMethod: + pass + + try: + if cfg.parentdir_prefix: + return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) + except NotThisMethod: + pass + + return { + 'version': '0+unknown', + 'full-revisionid': None, + 'dirty': None, + 'error': 'unable to compute version', + 'date': None, + } diff --git a/modules/MiPA/mipa/client.py b/modules/MiPA/mipa/client.py new file mode 100644 index 0000000..e6e3972 --- /dev/null +++ b/modules/MiPA/mipa/client.py @@ -0,0 +1,334 @@ +""" +The MIT License (MIT) + +Copyright (c) 2015-present Rapptz + +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 modified as follows: + - Delete unused functions and method. + - Removing functions beyond what is necessary to make it work. + - Simplification of some functions. + +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. +""" + +from __future__ import annotations + +import asyncio +import importlib +import inspect +import logging +import re +import sys +import traceback +from typing import Any, Callable, Coroutine, Dict, Optional, Tuple, Union + +from aiohttp import ClientWebSocketResponse +from mipac.client import Client as API +from mipac.manager.client import ClientManager +from mipac.models.user import MeDetailed + +from mipa.exception import WebSocketNotConnected, WebSocketReconnect +from mipa.gateway import MisskeyWebSocket +from mipa.router import Router +from mipa.state import ConnectionState +from mipa.utils import LOGING_LEVEL_TYPE, setup_logging + +_log = logging.getLogger() + + +class Client: + def __init__( + self, + loop: Optional[asyncio.AbstractEventLoop] = None, + max_capture: int = 100, + **options: Dict[Any, Any], + ): + super().__init__(**options) + self.max_capture = max_capture + self._router: Router + self.url = None + self.extra_events: Dict[str, Any] = {} + self.special_events: Dict[str, Any] = {} + self.token: Optional[str] = None + self.origin_uri: Optional[str] = None + self.loop = asyncio.get_event_loop() if loop is None else loop + self.core: API + self._connection: ConnectionState + self.user: MeDetailed + self.ws: Optional[MisskeyWebSocket] = None + self.should_reconnect = True + + def _get_state(self, **options: Any) -> ConnectionState: + return ConnectionState( + dispatch=self.dispatch, loop=self.loop, client=self + ) + + async def on_ready(self, ws: ClientWebSocketResponse): + """ + on_readyのデフォルト処理 + + Parameters + ---------- + ws : WebSocketClientProtocol + """ + + def event(self, name: Optional[str] = None): + def decorator(func: Coroutine[Any, Any, Any]): + self.add_event(func, name) + return func + + return decorator + + def add_event( + self, func: Coroutine[Any, Any, Any], name: Optional[str] = None + ): + name = func.__name__ if name is None else name + if not asyncio.iscoroutinefunction(func): + raise TypeError("Listeners must be coroutines") + + if name in self.extra_events: + self.special_events[name].append(func) + else: + self.special_events[name] = [func] + + def listen(self, name: Optional[str] = None): + def decorator(func: Coroutine[Any, Any, Any]): + self.add_listener(func, name) + return func + + return decorator + + def add_listener( + self, + func: Union[Coroutine[Any, Any, Any], Callable[..., Any]], + name: Optional[str] = None, + ): + name = func.__name__ if name is None else name + if not asyncio.iscoroutinefunction(func): + raise TypeError("Listeners must be coroutines") + _log.debug(f"add_listener: {name} {func.__name__}") + if name in self.extra_events: + self.extra_events[name].append(func) + else: + self.extra_events[name] = [func] + + def event_dispatch( + self, event_name: str, *args: Tuple[Any], **kwargs: Dict[Any, Any] + ) -> bool: + """ + on_ready等といった + + Parameters + ---------- + event_name : + args : + kwargs : + + Returns + ------- + + """ + + ev = f"on_{event_name}" + for event in self.special_events.get(ev, []): + foo = importlib.import_module(event.__module__) + coro = getattr(foo, ev) + self.schedule_event(coro, event, *args, **kwargs) + if ev in dir(self): + self.schedule_event(getattr(self, ev), ev, *args, **kwargs) + return ev in dir(self) + + def dispatch( + self, event_name: str, *args: tuple[Any], **kwargs: Dict[Any, Any] + ): + ev = f"on_{event_name}" + for event in self.extra_events.get(ev, []): + if inspect.ismethod(event): + coro = event + event = event.__name__ + else: + foo = importlib.import_module(event.__module__) + coro = getattr(foo, ev) + self.schedule_event(coro, event, *args, **kwargs) + if ev in dir(self): + self.schedule_event(getattr(self, ev), ev, *args, **kwargs) + + def schedule_event( + self, + coro: Callable[..., Coroutine[Any, Any, Any]], + event_name: str, + *args: tuple[Any], + **kwargs: Dict[Any, Any], + ) -> asyncio.Task[Any]: + return self.loop.create_task( + self._run_event(coro, event_name, *args, **kwargs), + name=f"MiPA: {event_name}", + ) + + async def _run_event( + self, + coro: Callable[..., Coroutine[Any, Any, Any]], + event_name: str, + *args: Any, + **kwargs: Any, + ) -> None: + try: + await coro(*args, **kwargs) + except asyncio.CancelledError: + pass + except Exception: + try: + await self.__on_error(event_name) + except asyncio.CancelledError: + pass + + @staticmethod + async def __on_error(event_method: str) -> None: + print(f"Ignoring exception in {event_method}", file=sys.stderr) + traceback.print_exc() + + async def on_error(self, err): + self.event_dispatch("error", err) + + async def create_api_session( + self, + token: str, + url: str, + log_level: LOGING_LEVEL_TYPE | None, + ) -> API: + self.core = API(url, token, log_level=log_level) + return self.core + + async def setup_hook(self) -> None: ... + + async def login( + self, token: str, url: str, log_level: LOGING_LEVEL_TYPE | None + ): + """ + ユーザーにログインし、ユーザー情報を取得します + + Parameters + ---------- + token : str + BOTにするユーザーのTOKEN + url : str + BOTにするユーザーがいるインスタンスのURL + log_level : LOGING_LEVEL_TYPE + The log level to use for logging. Defaults to ``INFO``. + """ + + core = await self.create_api_session(token, url, log_level) + await core.http.login() + self.user = await core.api.get_me() + await self.setup_hook() + + async def _connect( + self, + *, + timeout: int = 60, + event_name: str = "ready", + ) -> None: + self._connection = self._get_state() + coro = MisskeyWebSocket.from_client( + self, timeout=timeout, event_name=event_name + ) + self.ws = await asyncio.wait_for(coro, timeout=60) + while True: + await self.ws.poll_event() + + async def connect( + self, + *, + reconnect: bool = True, + timeout: int = 60, + ) -> None: + self.should_reconnect = reconnect + event_name = "ready" + while True: + try: + await self._connect(timeout=timeout, event_name=event_name) + except (WebSocketReconnect, asyncio.exceptions.TimeoutError): + if not self.should_reconnect: + break + event_name = "reconnect" + await asyncio.sleep(3) + + async def disconnect(self): + if not self.ws: + raise WebSocketNotConnected() + self.should_reconnect = False + await self.ws.socket.close() + + @property + def client(self) -> ClientManager: + return self.core.api + + @property + def router(self) -> Router: + return self._router + + async def start( + self, + url: str, + token: str, + *, + debug: bool = False, + reconnect: bool = True, + timeout: int = 60, + is_ayuskey: bool = False, + log_level: LOGING_LEVEL_TYPE | None = "INFO", + ): + """ + Starting Bot + + Parameters + ---------- + url: str + Misskey Instance Websocket URL (wss://example.com) + token: str + User Token + debug: bool, default False + debugging mode + reconnect: bool, default True + coming soon... + timeout: int, default 60 + Time until websocket times out + """ + if log_level is not None: + setup_logging(level=log_level) + self.token = token + url = url[:-1] if url[-1] == "/" else url + split_url = url.split("/") + + if origin_url := re.search(r"wss?://(.*)", url): + origin_url = ( + origin_url.group(0) + .replace("wss", "https") + .replace("ws", "http") + .replace("/streaming", "") + ) + else: + origin_url = url + if "streaming" not in split_url: + split_url.append("streaming") + url = "/".join(split_url) + self.url = url.replace("https", "wss").replace("http", "ws") + self.origin_url = origin_url + await self.login(token, origin_url, log_level) + await self.connect(reconnect=reconnect, timeout=timeout) diff --git a/modules/MiPA/mipa/exception.py b/modules/MiPA/mipa/exception.py new file mode 100644 index 0000000..a681913 --- /dev/null +++ b/modules/MiPA/mipa/exception.py @@ -0,0 +1,61 @@ +__all__ = ( + "MIPABaseException", + "MIPABaseWebSocketError", + "WebSocketNotConnected", + "WebSocketReconnect", + "CogNameDuplicate", + "ExtensionAlreadyLoaded", + "ExtensionFailed", + "InvalidCogPath", + "NoEntryPointError", + "ClientConnectorError", + "TaskNotRunningError", +) + + +class MIPABaseException(Exception): + """MIPA Base Exception""" + + +class MIPABaseWebSocketError(MIPABaseException): + """Websocket Base Exception""" + + +class WebSocketNotConnected(MIPABaseWebSocketError): + """Websocket not connected""" + + +class WebSocketReconnect(MIPABaseWebSocketError): + """Websocket should reconnect""" + + +class CogNameDuplicate(MIPABaseException): + """Cogの名前が重複している""" + + +class ExtensionNotLoaded(MIPABaseException): + """Cogが読み込まれていない""" + + +class ExtensionAlreadyLoaded(MIPABaseException): + """Cogは既に読み込まれている""" + + +class ExtensionFailed(MIPABaseException): + """Cog周りのエラー""" + + +class InvalidCogPath(MIPABaseException): + """無効なCogのパス""" + + +class NoEntryPointError(MIPABaseException): + """Cogにsetup関数が存在しない""" + + +class ClientConnectorError(MIPABaseException): + """WebSocketの接続に問題が発生した""" + + +class TaskNotRunningError(MIPABaseException): + """タスクが動いてない状態で停止しようとした""" diff --git a/modules/MiPA/mipa/ext/__init__.py b/modules/MiPA/mipa/ext/__init__.py new file mode 100644 index 0000000..9da2f4d --- /dev/null +++ b/modules/MiPA/mipa/ext/__init__.py @@ -0,0 +1,2 @@ +from .commands import * +from .tasks import * diff --git a/modules/MiPA/mipa/ext/commands/__init__.py b/modules/MiPA/mipa/ext/commands/__init__.py new file mode 100644 index 0000000..eb3d4df --- /dev/null +++ b/modules/MiPA/mipa/ext/commands/__init__.py @@ -0,0 +1,4 @@ +from .bot import * +from .cog import * +from .context import * +from .core import * diff --git a/modules/MiPA/mipa/ext/commands/_types.py b/modules/MiPA/mipa/ext/commands/_types.py new file mode 100644 index 0000000..4e9230c --- /dev/null +++ b/modules/MiPA/mipa/ext/commands/_types.py @@ -0,0 +1,31 @@ +""" +The MIT License (MIT) + +Copyright (c) 2015-present Rapptz + +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 modified as follows: + - Delete unused functions and method. + - Removing functions beyond what is necessary to make it work. + +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. +""" + + +class _BaseCommand: + __slots__ = () diff --git a/modules/MiPA/mipa/ext/commands/bot.py b/modules/MiPA/mipa/ext/commands/bot.py new file mode 100644 index 0000000..f11d399 --- /dev/null +++ b/modules/MiPA/mipa/ext/commands/bot.py @@ -0,0 +1,455 @@ +""" +The MIT License (MIT) + +Copyright (c) 2015-present Rapptz + +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 modified as follows: + - Delete unused functions and method. + - Removing functions beyond what is necessary to make it work. + - Adding new functions and methods + +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. +""" + +from __future__ import annotations + +import asyncio +import importlib +import inspect +import re +import sys +import traceback +from types import ModuleType +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Coroutine, + List, + Optional, + Tuple, + Union, +) + +from mipac.models.emoji import CustomEmoji +from mipac.models.user import MeDetailed, UserDetailedNotMe + +from mipa import Client +from mipa.exception import ( + CogNameDuplicate, + ExtensionAlreadyLoaded, + ExtensionFailed, + InvalidCogPath, + NoEntryPointError, +) +from mipa.ext.commands.context import Context +from mipa.ext.commands.core import CommandManager + +if TYPE_CHECKING: + from aiohttp.client_ws import ClientWebSocketResponse + from mipac.models.notification import ( + NotificationAchievement, + NotificationFollow, + NotificationFollowRequest, + NotificationNote, + NotificationPollEnd, + NotificationReaction, + ) + + from mipa.ext import Cog + + +__all__ = ["BotBase", "Bot"] + + +class BotBase(CommandManager): + def __init__(self, **options: dict[Any, Any]): + super().__init__(**options) + self.extra_events: dict[str, Any] = {} + self.special_events: dict[str, Any] = {} + self._check_once: List[Any] = [] # TODO: いつか確認する + self._checks: List[Any] = [] # TODO: いつか確認する + self._after_invoke = None + self.token: Optional[str] = None + self.origin_uri: Optional[str] = None + self.__extensions: dict[str, Any] = {} + self.user: MeDetailed + self.__cogs: dict[str, Cog] = {} + self.strip_after_prefix = options.get("strip_after_prefix", False) + # self.logger = get_module_logger(__name__) TODO: 直す + self.loop = asyncio.get_event_loop() + + def _on_note(self, message): + self.dispatch("note", message) + + async def on_ready(self, ws: ClientWebSocketResponse): + """ + on_readyのデフォルト処理 + + Parameters + ---------- + ws : ClientWebSocketResponse + """ + + def event(self, name: Optional[str] = None): + def decorator(func: Coroutine[Any, Any, Any]): + self.add_event(func, name) + return func + + return decorator + + def add_event( + self, func: Coroutine[Any, Any, Any], name: Optional[str] = None + ): + name = func.__name__ if name is None else name + if not asyncio.iscoroutinefunction(func): + raise TypeError("Listeners must be coroutines") + + if name in self.extra_events: + self.special_events[name].append(func) + else: + self.special_events[name] = [func] + + def listen(self, name: Optional[str] = None): + def decorator(func: Coroutine[Any, Any, Any]): + self.add_listener(func, name) + return func + + return decorator + + def add_listener( + self, + func: Union[Coroutine[Any, Any, Any], Callable[..., Any]], + name: Optional[str] = None, + ): + name = func.__name__ if name is None else name + if not asyncio.iscoroutinefunction(func): + raise TypeError("Listeners must be coroutines") + + if name in self.extra_events: + self.extra_events[name].append(func) + else: + self.extra_events[name] = [func] + + async def event_dispatch( + self, event_name: str, *args: Tuple[Any], **kwargs: dict[Any, Any] + ) -> bool: + """ + on_ready等といった + + Parameters + ---------- + event_name : + args : + kwargs : + + Returns + ------- + + """ + ev = f"on_{event_name}" + for event in self.special_events.get(ev, []): + foo = importlib.import_module(event.__module__) + coro = getattr(foo, ev) + await self.schedule_event(coro, event, *args, **kwargs) + if ev in dir(self): + await self.schedule_event(getattr(self, ev), ev, *args, **kwargs) + return ev in dir(self) + + def dispatch( + self, event_name: str, *args: tuple[Any], **kwargs: dict[Any, Any] + ): + ev = f"on_{event_name}" + for event in self.extra_events.get(ev, []): + if inspect.ismethod(event): + coro = event + event = event.__name__ + else: + foo = importlib.import_module(event.__module__) + coro = getattr(foo, ev) + self.schedule_event(coro, event, *args, **kwargs) + if ev in dir(self): + self.schedule_event(getattr(self, ev), ev, *args, **kwargs) + + async def add_cog(self, cog: Cog, override: bool = False) -> None: + cog_name = cog.__cog_name__ + existing = self.__cogs.get(cog_name) + if existing is not None: + if not override: + raise CogNameDuplicate() + await self.remove_cog(cog_name) # TODO: 作る + + cog = cog._inject(self) + self.__cogs[cog_name] = cog + + async def remove_cog(self, name: str): # TODO: Optional[Cog]を返すように + """Cogを削除します""" + cog = self.__cogs.get(name) + if cog is None: + return + + cog._inject(self) + + return cog + + async def _load_from_module(self, spec: ModuleType, key: str) -> None: + try: + setup = spec.setup + except AttributeError as e: + raise NoEntryPointError(f"{key} にsetupが存在しません") from e + + try: + await setup(self) + except Exception as e: + raise ExtensionFailed(key, e) from e + else: + self.__extensions[key] = spec + + @staticmethod + def _resolve_name(name: str, package: Optional[str]) -> str: + try: + return importlib.util.resolve_name(name, package) # pyright: ignore + except ImportError as e: + raise InvalidCogPath(name) from e + + async def load_extension( + self, name: str, *, package: Optional[str] = None + ) -> None: + """拡張をロードする + + Parameters + ---------- + name : str + [description] + package : Optional[str], optional + [description], by default None + """ + name = self._resolve_name(name, package) + if name in self.__extensions: + raise ExtensionAlreadyLoaded + try: + module = importlib.import_module(name) + except ModuleNotFoundError as e: + raise InvalidCogPath(f"cog: {name} へのパスが無効です") from e + await self._load_from_module(module, name) + + def schedule_event( + self, + coro: Callable[..., Coroutine[Any, Any, Any]], + event_name: str, + *args: tuple[Any], + **kwargs: dict[Any, Any], + ) -> asyncio.Task[Any]: + return asyncio.create_task( + self._run_event(coro, event_name, *args, **kwargs), + name=f"MiPA: {event_name}", + ) + + async def _run_event( + self, + coro: Callable[..., Coroutine[Any, Any, Any]], + event_name: str, + *args: Any, + **kwargs: Any, + ) -> None: + try: + await coro(*args, **kwargs) + except asyncio.CancelledError: + pass + except Exception: + try: + await self.__on_error(event_name) + except asyncio.CancelledError: + pass + + @staticmethod + async def __on_error(event_method: str) -> None: + print(f"Ignoring exception in {event_method}", file=sys.stderr) + traceback.print_exc() + + async def on_error(self, err): + await self.event_dispatch("error", err) + + def get_cog(self, name: str) -> Cog | None: + return self.__cogs.get(name) + + async def get_context(self, message, cmd, cls=Context) -> Context: + return cls(message=message, bot=self, cmd=cmd) + + async def progress_command(self, message): + for cmd in self.all_commands: + ctx = await self.get_context(message, cmd) + if cmd.cmd_type == "regex": + if re.search(cmd.key, message.content): + hit_list = re.findall(cmd.key, message.content) + if isinstance(hit_list, list): + hit_list = tuple(hit_list) + + if isinstance(hit_list[0], tuple): + hit_list = tuple( + i for i in hit_list[0] if len(i.rstrip()) > 0 + ) + ctx.args = hit_list + await cmd.func.invoke(ctx) + elif message.content.find(cmd.key) != -1: + await cmd.func.invoke(ctx) + else: + continue + + async def on_user_follow(self, user: UserDetailedNotMe): + """ + When you follow a user + + Parameters + ---------- + user : UserDetailed + """ + + async def on_user_unfollow(self, user: UserDetailedNotMe): + """ + When you unfollow a user + + Parameters + ---------- + user : UserDetailed + """ + + async def on_user_followed(self, notice: NotificationFollow): + """ + When someone follows you + + Parameters + ---------- + notice : NotificationFollow + """ + + async def on_mention(self, notice: NotificationNote): + """ + When someone mentions you + + Parameters + ---------- + notice : NotificationNote + """ + await self.progress_command(notice.note) + + async def on_reply(self, notice: NotificationNote): + """ + When someone replies to you + + Parameters + ---------- + notice : NotificationNote + """ + + async def on_renote(self, notice: NotificationNote): + """ + When someone renote your note + + Parameters + ---------- + notice : NotificationNote + """ + + async def on_quote(self, notice: NotificationNote): + """ + When someone quote your note + + Parameters + ---------- + notice : NotificationNote + """ + + async def on_reaction(self, notice: NotificationReaction): + """ + When someone react to your note + + Parameters + ---------- + notice : NotificationReaction + """ + + async def on_poll_vote(self, notice: NotificationNote): + """ + When someone vote to your poll + + Parameters + ---------- + notice : NotificationNote + """ + + async def on_poll_end(self, notice: NotificationPollEnd): + """ + When a poll is ended + + Parameters + ---------- + notice : NotificationPollEnd + """ + + async def on_follow_request(self, notice: NotificationFollowRequest): + """ + When someone send you a follow request + + Parameters + ---------- + notice : NotificationFollowRequest + """ + + async def on_follow_request_accept(self, notice: NotificationFollow): + """ + When someone accept your follow request + + Parameters + ---------- + notice : NotificationFollow + """ + + async def on_achievement_earned(self, notice: NotificationAchievement): + """ + When you earn an achievement + + Parameters + ---------- + notice : NotificationAchievement + """ + + async def on_emoji_deleted(self, emojis: list[CustomEmoji]): + """ + カスタム絵文字が削除された + + Parameters + ---------- + emojis : list[CustomEmoji] + 削除された絵文字のリスト + """ + + async def on_emoji_updated(self, emojis: list[CustomEmoji]): + """ + カスタム絵文字が更新された + + Parameters + ---------- + emojis : list[CustomEmoji] + 更新された絵文字のリスト + """ + + +class Bot(BotBase, Client): + pass diff --git a/modules/MiPA/mipa/ext/commands/cog.py b/modules/MiPA/mipa/ext/commands/cog.py new file mode 100644 index 0000000..8a67ab3 --- /dev/null +++ b/modules/MiPA/mipa/ext/commands/cog.py @@ -0,0 +1,154 @@ +""" +The MIT License (MIT) + +Copyright (c) 2015-present Rapptz + +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 modified as follows: + - Delete unused functions and method. + - Removing functions beyond what is necessary to make it work. + +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. +""" + +from __future__ import annotations + +import inspect +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + List, + Optional, + Tuple, + TypeVar, +) + +from mipa.ext.commands._types import _BaseCommand +from mipa.ext.commands.core import Command + +if TYPE_CHECKING: + from mipa.ext.commands.bot import BotBase + +FuncT = TypeVar("FuncT", bound=Callable[..., Any]) + + +class CogMeta(type): + __cog_name__: str + __cog_settings__: dict[str, Any] = {} + __cog_listeners__: list[Tuple[str, str]] + __cog_commands__: list[Command] = [] + + def __new__(cls, *args: Any, **kwargs: Dict[str, Any]): + name, bases, attrs = args + attrs["__cog_name__"] = kwargs.pop("name", name) + attrs["__cog_settings__"] = kwargs.pop("command_attrs", {}) + listeners = {} + commands = {} + no_bot_cog = "Commands or listeners must not start with cog_ or bot_ (in method {0.__name__}.{1})" # noqa: E501 + new_cls = super().__new__(cls, name, bases, attrs, **kwargs) + + for base in reversed( + new_cls.__mro__ + ): # 多重継承を確認 !コマンドを登録 + for elem, value in base.__dict__.items(): + if elem in commands: + del commands[elem] # commandsから削除 + if elem in listeners: + del listeners[elem] # listenersから削除 + is_static_method = isinstance(value, staticmethod) + + if isinstance(value, Command): + commands[elem] = value + + if is_static_method: # staticmethodか確認 + value = value.__func__ # + # 関数をvalueに !valueが重要 + if isinstance(value, _BaseCommand): + commands[elem] = value + elif inspect.iscoroutinefunction(value): + try: + value.__cog_listener__ + except AttributeError: + continue + else: + if elem.startswith(("cog", "bot_")): + raise TypeError(no_bot_cog.format(base, elem)) + listeners[elem] = value + new_cls.__cog_commands__ = list(commands.values()) + + listeners_as_list: List[tuple[str, Any]] = [] + for listener in listeners.values(): + for listener_name in listener.__cog_listener_names__: + listeners_as_list.append((listener_name, listener)) + + new_cls.__cog_listeners__ = listeners_as_list + return new_cls + + def __init__(self, *args: Tuple[Any], **kwargs: Dict[str, Any]): + super().__init__(*args, **kwargs) + + @classmethod + def qualified_name(cls) -> str: + return cls.__cog_name__ + + +class Cog(metaclass=CogMeta): + __cog_name__: str + __cog_settings__: dict[str, Any] = {} + __cog_listeners__: list[Tuple[str, str]] + __cog_commands__: list[Command] = [] + + def __new__(cls, *args: Any, **kwargs: Any): + self = super().__new__(cls) + self.__cog_commands__ = tuple(cls.__cog_commands__) + return self + + @classmethod + def listener(cls, name: Optional[str] = None) -> Callable[[FuncT], FuncT]: + def decorator(func: FuncT): + actual = func + if isinstance(actual, staticmethod): + actual = actual.__func__ + if not inspect.iscoroutinefunction(actual): + raise TypeError( + "Listener function must be a coroutine function." + ) + actual.__cog_listener__ = True + to_assign = name or actual.__name__ + try: + actual.__cog_listener_names__.append(to_assign) + except AttributeError: + actual.__cog_listener_names__ = [to_assign] + return func + + return decorator + + @classmethod + def qualified_name(cls) -> str: + return cls.__cog_name__ + + def _inject(self, bot: BotBase): + for command in self.__cog_commands__: + bot.add_command(command, self.__cog_name__) + + for name, method_func in self.__cog_listeners__: + bot.add_listener(getattr(self, name), name) + + return self diff --git a/modules/MiPA/mipa/ext/commands/context.py b/modules/MiPA/mipa/ext/commands/context.py new file mode 100644 index 0000000..b620b2e --- /dev/null +++ b/modules/MiPA/mipa/ext/commands/context.py @@ -0,0 +1,69 @@ +""" +The MIT License (MIT) + +Copyright (c) 2015-present Rapptz + +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 modified as follows: + - Delete unused functions and method. + - Removing functions beyond what is necessary to make it work. + +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. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from mipac import Note +from mipac.models.lite.user import PartialUser + +if TYPE_CHECKING: + from mipa.ext.commands import CMD, BotBase + + +class Context: + __slots__ = ("__message", "bot", "args", "kwargs", "command", "__cmd") + + def __init__( + self, + *, + message, + bot: BotBase, + args: tuple | None = None, + kwargs=None, + cmd: CMD = None, + ): + self.__message: Note = message + self.bot: BotBase = bot + self.args: tuple = args or () + self.kwargs = kwargs or {} + self.command = cmd.func + self.__cmd = cmd + + @property + def message(self) -> Note: + return self.__message + + @property + def author(self) -> PartialUser: + return self.__message.author + + @property + def cog(self): + return self.bot.get_cog(self.__cmd.cog_name) diff --git a/modules/MiPA/mipa/ext/commands/core.py b/modules/MiPA/mipa/ext/commands/core.py new file mode 100644 index 0000000..c6ac228 --- /dev/null +++ b/modules/MiPA/mipa/ext/commands/core.py @@ -0,0 +1,110 @@ +""" +The MIT License (MIT) + +Copyright (c) 2015-present Rapptz + +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 modified as follows: + - Delete unused functions and method. + - Removing functions beyond what is necessary to make it work. + +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. +""" + +from __future__ import annotations + +import asyncio +import functools +from typing import TYPE_CHECKING, List + +from mipa.ext.commands._types import _BaseCommand + +if TYPE_CHECKING: + from mipa.ext.commands import Context + + +def hooked_wrapped_callback(coro): + @functools.wraps(coro) + async def wrapped(*args, **kwargs): + ret = await coro(*args, **kwargs) + return ret + + return wrapped + + +class CMD: + def __init__( + self, cmd_type: str, key: str, func: "Command", cog_name: str + ): + self.cmd_type = cmd_type + self.key = key + self.func = func + self.cog_name = cog_name + + +class CommandManager: + def __init__(self, *args, **kwargs): + self.all_commands: List[CMD] = [] + super().__init__(*args, **kwargs) # Clientクラスを初期化する + + def add_command(self, command: "Command", cog_name: str): + if not isinstance(command, Command): + raise TypeError(f"{command}はCommandクラスである必要があります") + command_type = "regex" if command.regex else "text" + command_key = command.regex or command.text + self.all_commands.append( + CMD(command_type, command_key, command, cog_name) + ) + + +class Command(_BaseCommand): + def __new__(cls, *args, **kwargs): + self = super().__new__(cls) + return self + + def __init__(self, func, regex: str, text: str, **kwargs): + if not asyncio.iscoroutinefunction(func): + raise TypeError(f"{func}はコルーチンでなければなりません") + self.regex: str = regex + self.text: str = text + self.callback = func + self.cog = None + + @property + def qualified_name(self) -> str: + return self.regex or self.text + + def __str__(self): + return self.qualified_name + + @staticmethod + async def _parse_arguments(ctx: Context): + args = (ctx,) if ctx.cog is None else (ctx.cog, ctx) + ctx.args = args + ctx.args + return ctx + + async def invoke(self, ctx: Context, *args, **kwargs): + ctx = await self._parse_arguments(ctx) + await self.callback(*ctx.args, **ctx.kwargs) + + +def mention_command(regex: str | None = None, text: str | None = None): + def decorator(func, **kwargs): + return Command(func, regex=regex, text=text, **kwargs) + + return decorator diff --git a/modules/MiPA/mipa/ext/tasks/__init__.py b/modules/MiPA/mipa/ext/tasks/__init__.py new file mode 100644 index 0000000..c77c80b --- /dev/null +++ b/modules/MiPA/mipa/ext/tasks/__init__.py @@ -0,0 +1,146 @@ +""" +The MIT License (MIT) + +Copyright (c) 2015-present Rapptz + +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 modified as follows: + - Delete unused functions and method. + - Removing functions beyond what is necessary to make it work. + - Simplification of some functions. + +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. +""" + +import asyncio +import inspect +from typing import ( + Any, + Callable, + Coroutine, + Dict, + Generic, + Optional, + Type, + TypeVar, +) + +from mipa.exception import TaskNotRunningError +from mipa.utils import MISSING + +__all__ = ["Loop", "loop"] + +_func = Callable[..., Coroutine[Any, Any, Any]] +LF = TypeVar("LF", bound=_func) +T = TypeVar("T") + + +class Loop(Generic[LF]): + def __init__( + self, + coro: LF, + seconds: float, + count: Optional[int], + ): + self.seconds = seconds + self.coro: LF = coro + self.count: Optional[int] = count + self._current_loop = 0 + self._task: Optional[asyncio.Task[None]] = None + self._injected = None + + self._stop_next_iteration = False + + if self.count is not None and self.count <= 0: + raise ValueError("count must be greater than 0 or None.") + + if not inspect.iscoroutinefunction(self.coro): + raise TypeError( + f"Expected coroutine function, not {type(self.coro).__name__!r}." + ) + + def start( + self, *args: tuple[Any], **kwargs: Dict[Any, Any] + ) -> asyncio.Task[Any]: + """ + タスクを開始する + + Parameters + ---------- + args : Any + kwargs : Any + + Returns + ------- + _task : asyncio.Task[Any] + """ + if self._injected is not None: + args = (self._injected, *args) + self._task = asyncio.create_task(self._loop(*args, **kwargs)) + return self._task + + def stop(self): + """ + タスクを停止 + """ + + if self._task is None: + raise TaskNotRunningError("タスクは起動していません") + + if not self._task.done(): + self._stop_next_iteration = True + + async def _loop(self, *args: tuple[Any], **kwargs: Dict[Any, Any]): + while True: + if self._stop_next_iteration is True: + return + await self.coro(*args, **kwargs) + await asyncio.sleep(self.seconds) + + self._current_loop += 1 + if self._current_loop == self.count: + break + + def __get__(self, obj: T, objtype: Type[T]): + if obj is None: + return self + + copy: Loop[LF] = Loop( + self.coro, + seconds=self.seconds, + count=self.count, + ) + copy._injected = obj + + setattr(obj, self.coro.__name__, copy) + return copy + + +def loop( + *, + seconds: float = MISSING, + count: Optional[int] = None, +) -> Callable[[LF], Loop[LF]]: + def decorator(func: LF) -> Loop[LF]: + return Loop[LF]( + func, + seconds=seconds, + count=count, + ) + + return decorator diff --git a/modules/MiPA/mipa/ext/timelines/__init__.py b/modules/MiPA/mipa/ext/timelines/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/modules/MiPA/mipa/ext/timelines/core.py b/modules/MiPA/mipa/ext/timelines/core.py new file mode 100644 index 0000000..032b99f --- /dev/null +++ b/modules/MiPA/mipa/ext/timelines/core.py @@ -0,0 +1,8 @@ +from abc import ABC + +from mipac.models.note import Note + + +class AbstractTimeline(ABC): + async def on_note(self, note: Note): + pass diff --git a/modules/MiPA/mipa/gateway.py b/modules/MiPA/mipa/gateway.py new file mode 100644 index 0000000..0269745 --- /dev/null +++ b/modules/MiPA/mipa/gateway.py @@ -0,0 +1,100 @@ +""" +The MIT License (MIT) + +Copyright (c) 2015-present Rapptz + +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 modified as follows: + - Delete unused functions and method. + - Removing functions beyond what is necessary to make it work. + - Simplification of some functions. + +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. +""" + +from __future__ import annotations + +import asyncio +import json +from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, TypeVar + +import aiohttp +from aiohttp import ClientError + +from mipa.utils import str_lower +from mipa.exception import ClientConnectorError, WebSocketReconnect +from mipa.router import Router + +if TYPE_CHECKING: + from .client import Client + +__all__ = ("MisskeyWebSocket",) + + +MS = TypeVar("MS", bound="aiohttp.ClientWebSocketResponse") + + +class MisskeyWebSocket: + def __init__(self, socket: MS, client: Client): + self.socket: MS = socket + self._dispatch = lambda *args: None + self._connection = None + self.client = client + self._misskey_parsers: Optional[Dict[str, Callable[..., Any]]] = None + + @classmethod + async def from_client( + cls, client: Client, *, timeout: int = 60, event_name: str = "ready" + ): + try: + socket = await client.core.http.session.ws_connect( + f"{client.url}?i={client.token}" + ) + ws = cls(socket, client) + ws._dispatch = client.dispatch + ws._connection = client._connection + ws._misskey_parsers = client._connection.parsers + client._router = Router(socket, max_capure=client.max_capture) + client.dispatch(event_name, socket) + return ws + except (ClientConnectorError, ClientError): + while True: + await asyncio.sleep(3) + return await cls.from_client( + client, timeout=timeout, event_name=event_name + ) + + # await ws.poll_event(timeout=timeout) + + async def received_message(self, msg, /): + if isinstance(msg, bytes): + msg = msg.decode() + + await self._misskey_parsers[str_lower(msg["type"]).upper()](msg) + + async def poll_event(self, *, timeout: int = 60): + msg = await self.socket.receive(timeout=timeout) + + if msg is aiohttp.http.WS_CLOSED_MESSAGE: + raise WebSocketReconnect() + elif msg is aiohttp.http.WS_CLOSING_MESSAGE: + raise WebSocketReconnect() + elif msg.type is aiohttp.WSMsgType.TEXT: + await self.received_message(json.loads(msg.data)) + elif msg.type is aiohttp.WSMsgType.ERROR: + raise WebSocketReconnect() diff --git a/modules/MiPA/mipa/http.py b/modules/MiPA/mipa/http.py new file mode 100644 index 0000000..2d7a1f9 --- /dev/null +++ b/modules/MiPA/mipa/http.py @@ -0,0 +1,79 @@ +""" +The MIT License (MIT) + +Copyright (c) 2015-present Rapptz + +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 modified as follows: + - Delete unused functions and method. + - Removing functions beyond what is necessary to make it work. + - Simplification of some functions. + +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. +""" + +import json +import sys +from typing import Any, Optional + +import aiohttp + +from mipa import __version__ +from mipa.exception import ClientConnectorError +from mipa.utils import MISSING + +__all__ = ("HTTPClient", "HTTPSession") + + +async def json_or_text(response: aiohttp.ClientResponse): + text = await response.text(encoding="utf-8") + try: + if "application/json" in response.headers["Content-Type"]: + return json.loads(text) + except KeyError: + pass + + +class HTTPClient: + def __init__(self) -> None: + self.__session: aiohttp.ClientSession = MISSING + self.token: Optional[str] = None + user_agent = "Misskey Bot (https://github.com/yupix/MiPA {0}) Python/{1[0]}.{1[1]} aiohttp/{2}" # noqa: E501 + self.user_agent = user_agent.format( + __version__, sys.version_info, aiohttp.__version__ + ) + + async def close_session(self): + await self.__session.close() + + async def ws_connect(self, url: str, *, compress: int = 0) -> Any: + kwargs = { + "autoclose": False, + "max_msg_size": 0, + "timeout": 30.0, + "headers": {"User-Agent": self.user_agent}, + "compress": compress, + } + try: + ws = await self.__session.ws_connect(url, **kwargs) + except aiohttp.client_exceptions.ClientConnectorError: + raise ClientConnectorError() + return ws + + +HTTPSession: HTTPClient = HTTPClient() diff --git a/modules/MiPA/mipa/router.py b/modules/MiPA/mipa/router.py new file mode 100644 index 0000000..a323c27 --- /dev/null +++ b/modules/MiPA/mipa/router.py @@ -0,0 +1,151 @@ +from __future__ import annotations + +import uuid +from typing import TYPE_CHECKING, Iterable, Literal, overload + + +if TYPE_CHECKING: + from mipa.ext.timelines.core import AbstractTimeline + from aiohttp.client_ws import ClientWebSocketResponse + +__all__ = ["Router"] + +IChannel = Literal["global", "main", "home", "local", "hybrid", "antenna"] + + +CHANNELS: dict[str, str] = { + "global": "globalTimeline", + "main": "main", + "home": "homeTimeline", + "local": "localTimeline", + "hybrid": "hybridTimeline", + "antenna": "antenna", +} + + +class Router: + def __init__( + self, web_socket: ClientWebSocketResponse, max_capure: int = 100 + ): + self.web_socket: ClientWebSocketResponse = web_socket + self.captured_note: list[str] = [] + self.max_capture: int = max_capure + self.__channel_ids: dict[str, IChannel] = {} + self.__channel_handlers: dict[str, AbstractTimeline] = {} + + @overload + async def connect_channel(self, channel_list: Iterable[IChannel]): ... + + @overload + async def connect_channel( + self, channel_list: dict[IChannel, AbstractTimeline | None] + ): ... + + async def connect_channel( + self, + channel_list: Iterable[IChannel] + | dict[IChannel, AbstractTimeline | None], + antenna_id = None + ): + """ + Connects to a channel based on the list passed. + + Parameters + ---------- + channel_list : IChannel + ['global', 'main', 'home', 'local', 'hybrid'] + + Returns + ------- + dict[IChannel, str] + """ + + _channel_ids: dict[IChannel, str] = {} + try: + for channel in channel_list: + channel_id = f"{uuid.uuid4()}" + _channel_ids[channel] = channel_id + self.__channel_ids[channel_id] = channel + if isinstance(channel_list, dict): + channel_handler = channel_list[channel] + if channel_handler: + self.__channel_handlers[channel_id] = channel_handler + if antenna_id == None: + await self.web_socket.send_json( + { + "type": "connect", + "body": { + "channel": f"{CHANNELS[channel]}", + "id": f"{_channel_ids[channel]}", + }, + } + ) + else: + await self.web_socket.send_json( + { + "type": "connect", + "body": { + "channel": f"{CHANNELS[channel]}", + "id": f"{_channel_ids[channel]}", + "params": { + "antennaId": antenna_id, + }, + }, + } + ) + except KeyError: + pass + return _channel_ids + + async def disconnect_channel(self, channel_id: str): + """ + Disconnects from a channel based on the id passed. + + Parameters + ---------- + channel_id : str + """ + + self.__channel_ids.pop(channel_id) + await self.web_socket.send_json( + {"type": "disconnect", "body": {"id": f"{channel_id}"}} + ) + + async def capture_message(self, note_id: str) -> None: + """ + Captures a message based on the id passed. + Parameters + ---------- + note_id : str + """ + if len(self.captured_note) > self.max_capture: + await self.web_socket.send_json( + {"type": "unsubNote", "body": {"id": f"{note_id}"}} + ) + del self.captured_note[0] + self.captured_note.append(note_id) + await self.web_socket.send_json( + {"type": "subNote", "body": {"id": f"{note_id}"}} + ) + + @property + def channel_ids(self) -> dict[str, IChannel]: + """ + Returns the unique ID of the connected channel and the channel mapping + + Returns + ------- + dict[str, IChannel] + """ + return self.__channel_ids + + @property + def channel_handlers(self) -> dict[str, AbstractTimeline]: + """ + Returns the unique ID of the connected channel and the channel mapping + + Returns + ------- + dict[str, AbstractTimeline] + """ + return self.__channel_handlers diff --git a/modules/MiPA/mipa/state.py b/modules/MiPA/mipa/state.py new file mode 100644 index 0000000..d9032a1 --- /dev/null +++ b/modules/MiPA/mipa/state.py @@ -0,0 +1,338 @@ +""" +The MIT License (MIT) + +Copyright (c) 2015-present Rapptz + +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 modified as follows: + - Delete unused functions and method. + - Removing functions beyond what is necessary to make it work. + - Simplification of some functions. + +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. +""" + +from __future__ import annotations + +import asyncio +import inspect +import logging +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Generic, + TypedDict, + TypeVar, +) + +from mipac.models import Note +from mipac.models.emoji import CustomEmoji +from mipac.models.note import NoteDeleted +from mipac.models.notification import ( + NotificationAchievement, + NotificationFollow, + NotificationFollowRequest, + NotificationNote, + NotificationPollEnd, + NotificationReaction, +) +from mipac.models.reaction import PartialReaction +from mipac.models.user import MeDetailed, UserDetailedNotMe +from mipac.types.user import IUserDetailedNotMeSchema, IMeDetailedSchema +from mipac.types import INote +from mipac.types.emoji import ICustomEmoji +from mipac.types.note import ( + INoteUpdated, + INoteUpdatedDelete, + INoteUpdatedReaction, +) +from mipac.utils.format import upper_to_lower +from mipac.types.notification import INotification + +from mipa.utils import str_lower + +if TYPE_CHECKING: + from mipa.client import Client + +_log = logging.getLogger(__name__) + +T = TypeVar("T") + + +class IMessage(TypedDict, Generic[T]): + type: str + body: dict[str, T] + + +class ConnectionState: + def __init__( + self, + dispatch: Callable[..., Any], + loop: asyncio.AbstractEventLoop, + client: Client, + ): + self.__client: Client = client + self.__dispatch = dispatch + self.api = client.core.api + self.loop: asyncio.AbstractEventLoop = loop + self.parsers = parsers = {} + for attr, func in inspect.getmembers(self): + if attr.startswith("parse"): + parsers[attr[6:].upper()] = func + + async def parse_emoji_added(self, message: Dict[str, Any], **kwargs): + self.__dispatch( + "emoji_add", CustomEmoji(message["body"]["emoji"], client=self.api) + ) + + async def parse_emoji_deleted( + self, message: IMessage[list[ICustomEmoji]], **kwargs + ): + self.__dispatch( + "emoji_deleted", + [ + CustomEmoji(emoji, client=self.api) + for emoji in message["body"]["emojis"] + ], + ) + + async def parse_emoji_updated( + self, message: IMessage[list[ICustomEmoji]], **kwargs + ): + self.__dispatch( + "emoji_updated", + [ + CustomEmoji(emoji, client=self.api) + for emoji in message["body"]["emojis"] + ], + ) + + async def parse_channel(self, message: Dict[str, Any], **kwargs) -> None: + """parse_channel is a function to parse channel event + + チャンネルタイプのデータを解析後適切なパーサーに移動させます + + Parameters + ---------- + message : Dict[str, Any] + Received message + """ + base_msg = upper_to_lower(message["body"]) + channel_type = str_lower(base_msg.get("type")) + _log.debug(f"ChannelType: {channel_type}") + _log.debug(f"recv event type: {channel_type}") + if func := getattr(self, f"parse_{channel_type}", None): + await func( + base_msg["body"], channel_id=base_msg["id"] + ) # parse_note意外が呼ばれたらエラー出るかも + else: + _log.debug(f"Unknown event type: {channel_type}") + + async def parse_follow( + self, message: IUserDetailedNotMeSchema, **kwargs + ) -> None: + """ + When you follow someone, this event will be called + """ + user = UserDetailedNotMe( + message, + client=self.api, + ) + self.__dispatch("user_follow", user) + + async def parse_unfollow( + self, message: IUserDetailedNotMeSchema, **kwargs + ): + """ + When you unfollow someone, this event will be called + """ + user = UserDetailedNotMe( + message, + client=self.api, + ) + self.__dispatch("user_unfollow", user) + + async def parse_signin(self, message: Dict[str, Any], **kwargs): + """ + ログインが発生した際のイベント + """ + + async def parse_note_updated(self, note_data: INoteUpdated[Any], **kwargs): + message: Dict[str, Any] = upper_to_lower(note_data) + if func := getattr(self, f'parse_{message["body"]["type"]}', None): + await func(message) + else: + _log.debug( + f'Unknown note_updated event type: {message["body"]["type"]}' + ) + + async def parse_deleted( + self, note: INoteUpdated[INoteUpdatedDelete], **kwargs + ): + self.__dispatch("note_deleted", NoteDeleted(note)) + + async def parse_unreacted( + self, reaction: INoteUpdated[INoteUpdatedReaction], **kwargs + ): + self.__dispatch( + "unreacted", PartialReaction(reaction, client=self.api) + ) + + async def parse_reacted( + self, reaction: INoteUpdated[INoteUpdatedReaction], **kwargs + ): + self.__dispatch("reacted", PartialReaction(reaction, client=self.api)) + + async def parse_me_updated(self, user: IMeDetailedSchema, **kwargs): + self.__dispatch("me_updated", MeDetailed(user, client=self.api)) + + async def parse_announcement_created( + self, message: Dict[str, Any], **kwargs + ): + pass + + async def parse_read_all_announcements( + self, message: Dict[str, Any], **kwargs + ) -> None: + pass # TODO: 実装 + + async def parse_drive_file_created( + self, message: Dict[str, Any], **kwargs + ) -> None: + self.__dispatch("drive_file_created", message) + + async def parse_read_all_unread_mentions( + self, message: Dict[str, Any], **kwargs + ) -> None: + pass # TODO:実装 + + async def parse_read_all_unread_specified_notes( + self, message: Dict[str, Any], **kwargs + ) -> None: + pass # TODO:実装 + + async def parse_read_all_channels( + self, message: Dict[str, Any], **kwargs + ) -> None: + pass # TODO:実装 + + async def parse_read_all_notifications( + self, message: Dict[str, Any], **kwargs + ) -> None: + pass # TODO:実装 + + async def parse_url_upload_finished( + self, message: Dict[str, Any], **kwargs + ) -> None: + pass # TODO:実装 + + async def parse_unread_mention( + self, message: Dict[str, Any], **kwargs + ) -> None: + pass + + async def parse_unread_specified_note( + self, message: Dict[str, Any], **kwargs + ) -> None: + pass + + async def parse_read_all_messaging_messages( + self, message: Dict[str, Any], **kwargs + ) -> None: + pass + + async def parse_notification( + self, notification_data: Dict[str, Any], **kwargs + ) -> None: + """ + Parse notification event + + Parameters + ---------- + message: Dict[str, Any] + Received message + """ + message: INotification = upper_to_lower(notification_data) + notification_map: dict[ + str, + tuple[ + str, + [ + NotificationFollow + | NotificationNote + | NotificationReaction + | NotificationPollEnd + | NotificationFollowRequest + ], + ], + ] = { + "follow": ("user_followed", NotificationFollow), + "mention": ("mention", NotificationNote), + "reply": ("reply", NotificationNote), + "renote": ("renote", NotificationNote), + "quote": ("quote", NotificationNote), + "reaction": ("reaction", NotificationReaction), + "poll_vote": ("poll_vote", NotificationNote), + "poll_ended": ("poll_end", NotificationPollEnd), + "receive_follow_request": ( + "follow_request", + NotificationFollowRequest, + ), + "follow_request_accepted": ( + "follow_request_accept", + NotificationFollow, + ), + "achievement_earned": ( + "achievement_earned", + NotificationAchievement, + ), + } + dispatch_path, parse_class = notification_map.get( + str_lower(message["type"]), (None, None) + ) + if dispatch_path and parse_class: + self.__dispatch( + dispatch_path, parse_class(message, client=self.api) + ) + + async def parse_unread_notification( + self, message: Dict[str, Any], **kwargs + ) -> None: + """ + 未読の通知を解析する関数 + + Parameters + ---------- + message : Dict[str, Any] + Received message + """ + # notification_type = str_lower(message['type']) + # getattr(self, f'parse_{notification_type}')(message) + + async def parse_note(self, message: INote, channel_id: str) -> None: + """ + ノートイベントを解析する関数 + """ + note = Note(message, self.api) + await self.__client.router.capture_message(note.id) + handler = self.__client.router.channel_handlers.get(channel_id) + if handler: + await handler.on_note(note) + self.__dispatch("note", note) diff --git a/modules/MiPA/mipa/utils.py b/modules/MiPA/mipa/utils.py new file mode 100644 index 0000000..9fd98c6 --- /dev/null +++ b/modules/MiPA/mipa/utils.py @@ -0,0 +1,74 @@ +import logging +import re +from typing import Any, Literal + +LOGING_LEVEL_TYPE = Literal[ + "NOTSET", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL" +] +LOGING_LEVELS = { + "NOTSET": 0, + "DEBUG": 10, + "INFO": 20, + "WARNING": 30, + "ERROR": 40, + "CRITICAL": 50, +} + + +class _MissingSentinel: + def __eq__(self, other): + return False + + def __bool__(self): + return False + + def __repr__(self): + return "..." + + +MISSING: Any = _MissingSentinel() + + +def str_lower(text: str): + pattern = re.compile("[A-Z]") + large = [i.group().lower() for i in pattern.finditer(text)] + result: list[Any | str] = [None] * (len(large + pattern.split(text))) + result[::2] = pattern.split(text) + result[1::2] = ["_" + i.lower() for i in large] + return "".join(result) + + +def parse_logging_level(level: LOGING_LEVEL_TYPE): + if level in LOGING_LEVELS: + return LOGING_LEVELS[level] + raise Exception("Not found logging level {0}" % (level)) + + +def setup_logging( + *, + handler: logging.Handler | None = None, + formatter: logging.Formatter | None = None, + level: LOGING_LEVEL_TYPE = "INFO", +) -> None: + _level = parse_logging_level(level) + + if _level is None: + _level = logging.INFO + + if handler is None: + handler = logging.StreamHandler() + + if formatter is None: + # if isinstance(handler, logging.StreamHandler): TODO: カラー出力に対応する + # pass + # else: + dt_fmt = "%Y-%m-%d %H:%M:%S" + formatter = logging.Formatter( + "[{asctime}] [{levelname:<8}] {name}: {message}", dt_fmt, style="{" + ) + + logger = logging.getLogger() + + handler.setFormatter(formatter) + logger.setLevel(_level) + logger.addHandler(handler) diff --git a/modules/MiPA/package.json b/modules/MiPA/package.json new file mode 100644 index 0000000..01db1de --- /dev/null +++ b/modules/MiPA/package.json @@ -0,0 +1,20 @@ +{ + "name": "mipa", + "version": "0.4.0", + "description": "Python Misskey Bot Framework", + "repository": { + "type": "git", + "url": "git+https://github.com/yupix/MiPA.git" + }, + "keywords": [ + "python", + "misskey", + "bot-framework" + ], + "author": "yupix ", + "license": "MIT", + "bugs": { + "url": "https://github.com/yupix/MiPA/issues" + }, + "homepage": "https://github.com/yupix/MiPA#readme" +} \ No newline at end of file diff --git a/modules/MiPA/pyproject.toml b/modules/MiPA/pyproject.toml new file mode 100644 index 0000000..60cf732 --- /dev/null +++ b/modules/MiPA/pyproject.toml @@ -0,0 +1,8 @@ +[tool.ruff] +line-length = 79 + +[tool.ruff.lint] +exclude = ["mipa/**/__init__.py"] + +[tool.ruff.format] +exclude = ["mipa/_version.py"] \ No newline at end of file diff --git a/modules/MiPA/requirements.txt b/modules/MiPA/requirements.txt new file mode 100644 index 0000000..eb65d3d --- /dev/null +++ b/modules/MiPA/requirements.txt @@ -0,0 +1,3 @@ +aiohttp==3.9.1 +mipac>=0.7.0,<0.8.0 +versioneer diff --git a/modules/MiPA/setup.cfg b/modules/MiPA/setup.cfg new file mode 100644 index 0000000..6c0e9e8 --- /dev/null +++ b/modules/MiPA/setup.cfg @@ -0,0 +1,7 @@ +[versioneer] +VCS = git +style = pep440 +versionfile_source = mipa/_version.py +versionfile_build = mipa/_version.py +tag_prefix = +parentdir_prefix = diff --git a/modules/MiPA/setup.py b/modules/MiPA/setup.py new file mode 100644 index 0000000..00b8ebb --- /dev/null +++ b/modules/MiPA/setup.py @@ -0,0 +1,42 @@ +import pathlib + +from setuptools import setup +import versioneer + +description = 'Python Misskey Bot Framework' +readme_file = pathlib.Path(__file__).parent / 'README.md' +with readme_file.open(encoding='utf-8') as fh: + long_description = fh.read() + +with open('requirements.txt', 'r') as f: + requirements = f.read().splitlines() + +extras_require = { + 'dev': ['ruff', 'isort', 'mypy', 'flake8'], + 'ci': ['flake8', 'mypy'], +} + +packages = ['mipa', 'mipa.ext', 'mipa.ext.commands', 'mipa.ext.tasks', 'mipa.ext.timelines'] + +setup( + name='mipa', + version=versioneer.get_version(), + cmdclass=versioneer.get_cmdclass(), + install_requires=requirements, + url='https://github.com/yupix/MiPA', + author='yupix', + author_email='yupi0982@outlook.jp', + license='MIT', + python_requires='>=3.12, <4.0', + description=description, + long_description=long_description, + long_description_content_type='text/markdown', + packages=packages, + classifiers=[ + 'Development Status :: 2 - Pre-Alpha', + 'Programming Language :: Python :: 3.12', + 'Natural Language :: Japanese', + 'License :: OSI Approved :: MIT License', + ], + extras_require=extras_require, +) diff --git a/modules/MiPA/versioneer.py b/modules/MiPA/versioneer.py new file mode 100644 index 0000000..18e34c2 --- /dev/null +++ b/modules/MiPA/versioneer.py @@ -0,0 +1,2205 @@ + +# Version: 0.28 + +"""The Versioneer - like a rocketeer, but for versions. + +The Versioneer +============== + +* like a rocketeer, but for versions! +* https://github.com/python-versioneer/python-versioneer +* Brian Warner +* License: Public Domain (Unlicense) +* Compatible with: Python 3.7, 3.8, 3.9, 3.10 and pypy3 +* [![Latest Version][pypi-image]][pypi-url] +* [![Build Status][travis-image]][travis-url] + +This is a tool for managing a recorded version number in setuptools-based +python projects. The goal is to remove the tedious and error-prone "update +the embedded version string" step from your release process. Making a new +release should be as easy as recording a new tag in your version-control +system, and maybe making new tarballs. + + +## Quick Install + +Versioneer provides two installation modes. The "classic" vendored mode installs +a copy of versioneer into your repository. The experimental build-time dependency mode +is intended to allow you to skip this step and simplify the process of upgrading. + +### Vendored mode + +* `pip install versioneer` to somewhere in your $PATH + * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is + available, so you can also use `conda install -c conda-forge versioneer` +* add a `[tool.versioneer]` section to your `pyproject.toml` or a + `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) + * Note that you will need to add `tomli; python_version < "3.11"` to your + build-time dependencies if you use `pyproject.toml` +* run `versioneer install --vendor` in your source tree, commit the results +* verify version information with `python setup.py version` + +### Build-time dependency mode + +* `pip install versioneer` to somewhere in your $PATH + * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is + available, so you can also use `conda install -c conda-forge versioneer` +* add a `[tool.versioneer]` section to your `pyproject.toml` or a + `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) +* add `versioneer` (with `[toml]` extra, if configuring in `pyproject.toml`) + to the `requires` key of the `build-system` table in `pyproject.toml`: + ```toml + [build-system] + requires = ["setuptools", "versioneer[toml]"] + build-backend = "setuptools.build_meta" + ``` +* run `versioneer install --no-vendor` in your source tree, commit the results +* verify version information with `python setup.py version` + +## Version Identifiers + +Source trees come from a variety of places: + +* a version-control system checkout (mostly used by developers) +* a nightly tarball, produced by build automation +* a snapshot tarball, produced by a web-based VCS browser, like github's + "tarball from tag" feature +* a release tarball, produced by "setup.py sdist", distributed through PyPI + +Within each source tree, the version identifier (either a string or a number, +this tool is format-agnostic) can come from a variety of places: + +* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows + about recent "tags" and an absolute revision-id +* the name of the directory into which the tarball was unpacked +* an expanded VCS keyword ($Id$, etc) +* a `_version.py` created by some earlier build step + +For released software, the version identifier is closely related to a VCS +tag. Some projects use tag names that include more than just the version +string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool +needs to strip the tag prefix to extract the version identifier. For +unreleased software (between tags), the version identifier should provide +enough information to help developers recreate the same tree, while also +giving them an idea of roughly how old the tree is (after version 1.2, before +version 1.3). Many VCS systems can report a description that captures this, +for example `git describe --tags --dirty --always` reports things like +"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the +0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has +uncommitted changes). + +The version identifier is used for multiple purposes: + +* to allow the module to self-identify its version: `myproject.__version__` +* to choose a name and prefix for a 'setup.py sdist' tarball + +## Theory of Operation + +Versioneer works by adding a special `_version.py` file into your source +tree, where your `__init__.py` can import it. This `_version.py` knows how to +dynamically ask the VCS tool for version information at import time. + +`_version.py` also contains `$Revision$` markers, and the installation +process marks `_version.py` to have this marker rewritten with a tag name +during the `git archive` command. As a result, generated tarballs will +contain enough information to get the proper version. + +To allow `setup.py` to compute a version too, a `versioneer.py` is added to +the top level of your source tree, next to `setup.py` and the `setup.cfg` +that configures it. This overrides several distutils/setuptools commands to +compute the version when invoked, and changes `setup.py build` and `setup.py +sdist` to replace `_version.py` with a small static file that contains just +the generated version data. + +## Installation + +See [INSTALL.md](./INSTALL.md) for detailed installation instructions. + +## Version-String Flavors + +Code which uses Versioneer can learn about its version string at runtime by +importing `_version` from your main `__init__.py` file and running the +`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can +import the top-level `versioneer.py` and run `get_versions()`. + +Both functions return a dictionary with different flavors of version +information: + +* `['version']`: A condensed version string, rendered using the selected + style. This is the most commonly used value for the project's version + string. The default "pep440" style yields strings like `0.11`, + `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section + below for alternative styles. + +* `['full-revisionid']`: detailed revision identifier. For Git, this is the + full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". + +* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the + commit date in ISO 8601 format. This will be None if the date is not + available. + +* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that + this is only accurate if run in a VCS checkout, otherwise it is likely to + be False or None + +* `['error']`: if the version string could not be computed, this will be set + to a string describing the problem, otherwise it will be None. It may be + useful to throw an exception in setup.py if this is set, to avoid e.g. + creating tarballs with a version string of "unknown". + +Some variants are more useful than others. Including `full-revisionid` in a +bug report should allow developers to reconstruct the exact code being tested +(or indicate the presence of local changes that should be shared with the +developers). `version` is suitable for display in an "about" box or a CLI +`--version` output: it can be easily compared against release notes and lists +of bugs fixed in various releases. + +The installer adds the following text to your `__init__.py` to place a basic +version in `YOURPROJECT.__version__`: + + from ._version import get_versions + __version__ = get_versions()['version'] + del get_versions + +## Styles + +The setup.cfg `style=` configuration controls how the VCS information is +rendered into a version string. + +The default style, "pep440", produces a PEP440-compliant string, equal to the +un-prefixed tag name for actual releases, and containing an additional "local +version" section with more detail for in-between builds. For Git, this is +TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags +--dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the +tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and +that this commit is two revisions ("+2") beyond the "0.11" tag. For released +software (exactly equal to a known tag), the identifier will only contain the +stripped tag, e.g. "0.11". + +Other styles are available. See [details.md](details.md) in the Versioneer +source tree for descriptions. + +## Debugging + +Versioneer tries to avoid fatal errors: if something goes wrong, it will tend +to return a version of "0+unknown". To investigate the problem, run `setup.py +version`, which will run the version-lookup code in a verbose mode, and will +display the full contents of `get_versions()` (including the `error` string, +which may help identify what went wrong). + +## Known Limitations + +Some situations are known to cause problems for Versioneer. This details the +most significant ones. More can be found on Github +[issues page](https://github.com/python-versioneer/python-versioneer/issues). + +### Subprojects + +Versioneer has limited support for source trees in which `setup.py` is not in +the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are +two common reasons why `setup.py` might not be in the root: + +* Source trees which contain multiple subprojects, such as + [Buildbot](https://github.com/buildbot/buildbot), which contains both + "master" and "slave" subprojects, each with their own `setup.py`, + `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI + distributions (and upload multiple independently-installable tarballs). +* Source trees whose main purpose is to contain a C library, but which also + provide bindings to Python (and perhaps other languages) in subdirectories. + +Versioneer will look for `.git` in parent directories, and most operations +should get the right version string. However `pip` and `setuptools` have bugs +and implementation details which frequently cause `pip install .` from a +subproject directory to fail to find a correct version string (so it usually +defaults to `0+unknown`). + +`pip install --editable .` should work correctly. `setup.py install` might +work too. + +Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in +some later version. + +[Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking +this issue. The discussion in +[PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the +issue from the Versioneer side in more detail. +[pip PR#3176](https://github.com/pypa/pip/pull/3176) and +[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve +pip to let Versioneer work correctly. + +Versioneer-0.16 and earlier only looked for a `.git` directory next to the +`setup.cfg`, so subprojects were completely unsupported with those releases. + +### Editable installs with setuptools <= 18.5 + +`setup.py develop` and `pip install --editable .` allow you to install a +project into a virtualenv once, then continue editing the source code (and +test) without re-installing after every change. + +"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a +convenient way to specify executable scripts that should be installed along +with the python package. + +These both work as expected when using modern setuptools. When using +setuptools-18.5 or earlier, however, certain operations will cause +`pkg_resources.DistributionNotFound` errors when running the entrypoint +script, which must be resolved by re-installing the package. This happens +when the install happens with one version, then the egg_info data is +regenerated while a different version is checked out. Many setup.py commands +cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into +a different virtualenv), so this can be surprising. + +[Bug #83](https://github.com/python-versioneer/python-versioneer/issues/83) describes +this one, but upgrading to a newer version of setuptools should probably +resolve it. + + +## Updating Versioneer + +To upgrade your project to a new release of Versioneer, do the following: + +* install the new Versioneer (`pip install -U versioneer` or equivalent) +* edit `setup.cfg` and `pyproject.toml`, if necessary, + to include any new configuration settings indicated by the release notes. + See [UPGRADING](./UPGRADING.md) for details. +* re-run `versioneer install --[no-]vendor` in your source tree, to replace + `SRC/_version.py` +* commit any changed files + +## Future Directions + +This tool is designed to make it easily extended to other version-control +systems: all VCS-specific components are in separate directories like +src/git/ . The top-level `versioneer.py` script is assembled from these +components by running make-versioneer.py . In the future, make-versioneer.py +will take a VCS name as an argument, and will construct a version of +`versioneer.py` that is specific to the given VCS. It might also take the +configuration arguments that are currently provided manually during +installation by editing setup.py . Alternatively, it might go the other +direction and include code from all supported VCS systems, reducing the +number of intermediate scripts. + +## Similar projects + +* [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time + dependency +* [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of + versioneer +* [versioningit](https://github.com/jwodder/versioningit) - a PEP 518-based setuptools + plugin + +## License + +To make Versioneer easier to embed, all its code is dedicated to the public +domain. The `_version.py` that it creates is also in the public domain. +Specifically, both are released under the "Unlicense", as described in +https://unlicense.org/. + +[pypi-image]: https://img.shields.io/pypi/v/versioneer.svg +[pypi-url]: https://pypi.python.org/pypi/versioneer/ +[travis-image]: +https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg +[travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer + +""" +# pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring +# pylint:disable=missing-class-docstring,too-many-branches,too-many-statements +# pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error +# pylint:disable=too-few-public-methods,redefined-outer-name,consider-using-with +# pylint:disable=attribute-defined-outside-init,too-many-arguments + +import configparser +import errno +import json +import os +import re +import subprocess +import sys +from pathlib import Path +from typing import Callable, Dict +import functools + +have_tomllib = True +if sys.version_info >= (3, 11): + import tomllib +else: + try: + import tomli as tomllib + except ImportError: + have_tomllib = False + + +class VersioneerConfig: + """Container for Versioneer configuration parameters.""" + + +def get_root(): + """Get the project root directory. + + We require that all commands are run from the project root, i.e. the + directory that contains setup.py, setup.cfg, and versioneer.py . + """ + root = os.path.realpath(os.path.abspath(os.getcwd())) + setup_py = os.path.join(root, "setup.py") + versioneer_py = os.path.join(root, "versioneer.py") + if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): + # allow 'python path/to/setup.py COMMAND' + root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) + setup_py = os.path.join(root, "setup.py") + versioneer_py = os.path.join(root, "versioneer.py") + if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): + err = ("Versioneer was unable to run the project root directory. " + "Versioneer requires setup.py to be executed from " + "its immediate directory (like 'python setup.py COMMAND'), " + "or in a way that lets it use sys.argv[0] to find the root " + "(like 'python path/to/setup.py COMMAND').") + raise VersioneerBadRootError(err) + try: + # Certain runtime workflows (setup.py install/develop in a setuptools + # tree) execute all dependencies in a single python process, so + # "versioneer" may be imported multiple times, and python's shared + # module-import table will cache the first one. So we can't use + # os.path.dirname(__file__), as that will find whichever + # versioneer.py was first imported, even in later projects. + my_path = os.path.realpath(os.path.abspath(__file__)) + me_dir = os.path.normcase(os.path.splitext(my_path)[0]) + vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) + if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals(): + print("Warning: build in %s is using versioneer.py from %s" + % (os.path.dirname(my_path), versioneer_py)) + except NameError: + pass + return root + + +def get_config_from_root(root): + """Read the project setup.cfg file to determine Versioneer config.""" + # This might raise OSError (if setup.cfg is missing), or + # configparser.NoSectionError (if it lacks a [versioneer] section), or + # configparser.NoOptionError (if it lacks "VCS="). See the docstring at + # the top of versioneer.py for instructions on writing your setup.cfg . + root = Path(root) + pyproject_toml = root / "pyproject.toml" + setup_cfg = root / "setup.cfg" + section = None + if pyproject_toml.exists() and have_tomllib: + try: + with open(pyproject_toml, 'rb') as fobj: + pp = tomllib.load(fobj) + section = pp['tool']['versioneer'] + except (tomllib.TOMLDecodeError, KeyError): + pass + if not section: + parser = configparser.ConfigParser() + with open(setup_cfg) as cfg_file: + parser.read_file(cfg_file) + parser.get("versioneer", "VCS") # raise error if missing + + section = parser["versioneer"] + + cfg = VersioneerConfig() + cfg.VCS = section['VCS'] + cfg.style = section.get("style", "") + cfg.versionfile_source = section.get("versionfile_source") + cfg.versionfile_build = section.get("versionfile_build") + cfg.tag_prefix = section.get("tag_prefix") + if cfg.tag_prefix in ("''", '""', None): + cfg.tag_prefix = "" + cfg.parentdir_prefix = section.get("parentdir_prefix") + cfg.verbose = section.get("verbose") + return cfg + + +class NotThisMethod(Exception): + """Exception raised if a method is not valid for the current scenario.""" + + +# these dictionaries contain VCS-specific tools +LONG_VERSION_PY: Dict[str, str] = {} +HANDLERS: Dict[str, Dict[str, Callable]] = {} + + +def register_vcs_handler(vcs, method): # decorator + """Create decorator to mark a method as the handler of a VCS.""" + def decorate(f): + """Store f in HANDLERS[vcs][method].""" + HANDLERS.setdefault(vcs, {})[method] = f + return f + return decorate + + +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, + env=None): + """Call the given command(s).""" + assert isinstance(commands, list) + process = None + + popen_kwargs = {} + if sys.platform == "win32": + # This hides the console window if pythonw.exe is used + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + popen_kwargs["startupinfo"] = startupinfo + + for command in commands: + try: + dispcmd = str([command] + args) + # remember shell=False, so use git.cmd on windows, not just git + process = subprocess.Popen([command] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None), **popen_kwargs) + break + except OSError: + e = sys.exc_info()[1] + if e.errno == errno.ENOENT: + continue + if verbose: + print("unable to run %s" % dispcmd) + print(e) + return None, None + else: + if verbose: + print("unable to find command, tried %s" % (commands,)) + return None, None + stdout = process.communicate()[0].strip().decode() + if process.returncode != 0: + if verbose: + print("unable to run %s (error)" % dispcmd) + print("stdout was %s" % stdout) + return None, process.returncode + return stdout, process.returncode + + +LONG_VERSION_PY['git'] = r''' +# This file helps to compute a version number in source trees obtained from +# git-archive tarball (such as those provided by githubs download-from-tag +# feature). Distribution tarballs (built by setup.py sdist) and build +# directories (produced by setup.py build) will contain a much shorter file +# that just contains the computed version number. + +# This file is released into the public domain. +# Generated by versioneer-0.28 +# https://github.com/python-versioneer/python-versioneer + +"""Git implementation of _version.py.""" + +import errno +import os +import re +import subprocess +import sys +from typing import Callable, Dict +import functools + + +def get_keywords(): + """Get the keywords needed to look up the version information.""" + # these strings will be replaced by git during git-archive. + # setup.py/versioneer.py will grep for the variable names, so they must + # each be defined on a line of their own. _version.py will just call + # get_keywords(). + git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" + git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" + git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" + keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} + return keywords + + +class VersioneerConfig: + """Container for Versioneer configuration parameters.""" + + +def get_config(): + """Create, populate and return the VersioneerConfig() object.""" + # these strings are filled in when 'setup.py versioneer' creates + # _version.py + cfg = VersioneerConfig() + cfg.VCS = "git" + cfg.style = "%(STYLE)s" + cfg.tag_prefix = "%(TAG_PREFIX)s" + cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" + cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" + cfg.verbose = False + return cfg + + +class NotThisMethod(Exception): + """Exception raised if a method is not valid for the current scenario.""" + + +LONG_VERSION_PY: Dict[str, str] = {} +HANDLERS: Dict[str, Dict[str, Callable]] = {} + + +def register_vcs_handler(vcs, method): # decorator + """Create decorator to mark a method as the handler of a VCS.""" + def decorate(f): + """Store f in HANDLERS[vcs][method].""" + if vcs not in HANDLERS: + HANDLERS[vcs] = {} + HANDLERS[vcs][method] = f + return f + return decorate + + +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, + env=None): + """Call the given command(s).""" + assert isinstance(commands, list) + process = None + + popen_kwargs = {} + if sys.platform == "win32": + # This hides the console window if pythonw.exe is used + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + popen_kwargs["startupinfo"] = startupinfo + + for command in commands: + try: + dispcmd = str([command] + args) + # remember shell=False, so use git.cmd on windows, not just git + process = subprocess.Popen([command] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None), **popen_kwargs) + break + except OSError: + e = sys.exc_info()[1] + if e.errno == errno.ENOENT: + continue + if verbose: + print("unable to run %%s" %% dispcmd) + print(e) + return None, None + else: + if verbose: + print("unable to find command, tried %%s" %% (commands,)) + return None, None + stdout = process.communicate()[0].strip().decode() + if process.returncode != 0: + if verbose: + print("unable to run %%s (error)" %% dispcmd) + print("stdout was %%s" %% stdout) + return None, process.returncode + return stdout, process.returncode + + +def versions_from_parentdir(parentdir_prefix, root, verbose): + """Try to determine the version from the parent directory name. + + Source tarballs conventionally unpack into a directory that includes both + the project name and a version string. We will also support searching up + two directory levels for an appropriately named parent directory + """ + rootdirs = [] + + for _ in range(3): + dirname = os.path.basename(root) + if dirname.startswith(parentdir_prefix): + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None, "date": None} + rootdirs.append(root) + root = os.path.dirname(root) # up a level + + if verbose: + print("Tried directories %%s but none started with prefix %%s" %% + (str(rootdirs), parentdir_prefix)) + raise NotThisMethod("rootdir doesn't start with parentdir_prefix") + + +@register_vcs_handler("git", "get_keywords") +def git_get_keywords(versionfile_abs): + """Extract version information from the given file.""" + # the code embedded in _version.py can just fetch the value of these + # keywords. When used from setup.py, we don't want to import _version.py, + # so we do it with a regexp instead. This function is not used from + # _version.py. + keywords = {} + try: + with open(versionfile_abs, "r") as fobj: + for line in fobj: + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + except OSError: + pass + return keywords + + +@register_vcs_handler("git", "keywords") +def git_versions_from_keywords(keywords, tag_prefix, verbose): + """Get version information from git keywords.""" + if "refnames" not in keywords: + raise NotThisMethod("Short version file found") + date = keywords.get("date") + if date is not None: + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + + # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant + # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 + # -like" string, which we must then edit to make compliant), because + # it's been around since git-1.5.3, and it's too difficult to + # discover which version we're using, or to work around using an + # older one. + date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + refnames = keywords["refnames"].strip() + if refnames.startswith("$Format"): + if verbose: + print("keywords are unexpanded, not using") + raise NotThisMethod("unexpanded keywords, not a git-archive tarball") + refs = {r.strip() for r in refnames.strip("()").split(",")} + # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of + # just "foo-1.0". If we see a "tag: " prefix, prefer those. + TAG = "tag: " + tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} + if not tags: + # Either we're using git < 1.8.3, or there really are no tags. We use + # a heuristic: assume all version tags have a digit. The old git %%d + # expansion behaves like git log --decorate=short and strips out the + # refs/heads/ and refs/tags/ prefixes that would let us distinguish + # between branches and tags. By ignoring refnames without digits, we + # filter out many common branch names like "release" and + # "stabilization", as well as "HEAD" and "master". + tags = {r for r in refs if re.search(r'\d', r)} + if verbose: + print("discarding '%%s', no digits" %% ",".join(refs - tags)) + if verbose: + print("likely tags: %%s" %% ",".join(sorted(tags))) + for ref in sorted(tags): + # sorting will prefer e.g. "2.0" over "2.0rc1" + if ref.startswith(tag_prefix): + r = ref[len(tag_prefix):] + # Filter out refs that exactly match prefix or that don't start + # with a number once the prefix is stripped (mostly a concern + # when prefix is '') + if not re.match(r'\d', r): + continue + if verbose: + print("picking %%s" %% r) + return {"version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None, + "date": date} + # no suitable tags, so version is "0+unknown", but full hex is still there + if verbose: + print("no suitable tags, using unknown + full revision id") + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags", "date": None} + + +@register_vcs_handler("git", "pieces_from_vcs") +def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): + """Get version from 'git describe' in the root of the source tree. + + This only gets called if the git-archive 'subst' keywords were *not* + expanded, and _version.py hasn't already been rewritten with a short + version string, meaning we're inside a checked out source tree. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + + # GIT_DIR can interfere with correct operation of Versioneer. + # It may be intended to be passed to the Versioneer-versioned project, + # but that should not change where we get our version from. + env = os.environ.copy() + env.pop("GIT_DIR", None) + runner = functools.partial(runner, env=env) + + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=not verbose) + if rc != 0: + if verbose: + print("Directory %%s not under git control" %% root) + raise NotThisMethod("'git rev-parse --git-dir' returned error") + + # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] + # if there isn't one, this yields HEX[-dirty] (no NUM) + describe_out, rc = runner(GITS, [ + "describe", "--tags", "--dirty", "--always", "--long", + "--match", f"{tag_prefix}[[:digit:]]*" + ], cwd=root) + # --long was added in git-1.5.5 + if describe_out is None: + raise NotThisMethod("'git describe' failed") + describe_out = describe_out.strip() + full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) + if full_out is None: + raise NotThisMethod("'git rev-parse' failed") + full_out = full_out.strip() + + pieces = {} + pieces["long"] = full_out + pieces["short"] = full_out[:7] # maybe improved later + pieces["error"] = None + + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], + cwd=root) + # --abbrev-ref was added in git-1.6.3 + if rc != 0 or branch_name is None: + raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") + branch_name = branch_name.strip() + + if branch_name == "HEAD": + # If we aren't exactly on a branch, pick a branch which represents + # the current commit. If all else fails, we are on a branchless + # commit. + branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) + # --contains was added in git-1.5.4 + if rc != 0 or branches is None: + raise NotThisMethod("'git branch --contains' returned error") + branches = branches.split("\n") + + # Remove the first line if we're running detached + if "(" in branches[0]: + branches.pop(0) + + # Strip off the leading "* " from the list of branches. + branches = [branch[2:] for branch in branches] + if "master" in branches: + branch_name = "master" + elif not branches: + branch_name = None + else: + # Pick the first branch that is returned. Good or bad. + branch_name = branches[0] + + pieces["branch"] = branch_name + + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] + # TAG might have hyphens. + git_describe = describe_out + + # look for -dirty suffix + dirty = git_describe.endswith("-dirty") + pieces["dirty"] = dirty + if dirty: + git_describe = git_describe[:git_describe.rindex("-dirty")] + + # now we have TAG-NUM-gHEX or HEX + + if "-" in git_describe: + # TAG-NUM-gHEX + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + if not mo: + # unparsable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%%s'" + %% describe_out) + return pieces + + # tag + full_tag = mo.group(1) + if not full_tag.startswith(tag_prefix): + if verbose: + fmt = "tag '%%s' doesn't start with prefix '%%s'" + print(fmt %% (full_tag, tag_prefix)) + pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" + %% (full_tag, tag_prefix)) + return pieces + pieces["closest-tag"] = full_tag[len(tag_prefix):] + + # distance: number of commits since tag + pieces["distance"] = int(mo.group(2)) + + # commit: short hex revision ID + pieces["short"] = mo.group(3) + + else: + # HEX: no tags + pieces["closest-tag"] = None + out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) + pieces["distance"] = len(out.split()) # total number of commits + + # commit date: see ISO-8601 comment in git_versions_from_keywords() + date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + + return pieces + + +def plus_or_dot(pieces): + """Return a + if we don't already have one, else return a .""" + if "+" in pieces.get("closest-tag", ""): + return "." + return "+" + + +def render_pep440(pieces): + """Build up version string, with post-release "local version identifier". + + Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you + get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty + + Exceptions: + 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += plus_or_dot(pieces) + rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_branch(pieces): + """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . + + The ".dev0" means not master branch. Note that .dev0 sorts backwards + (a feature branch will appear "older" than the master branch). + + Exceptions: + 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0" + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+untagged.%%d.g%%s" %% (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def pep440_split_post(ver): + """Split pep440 version string at the post-release segment. + + Returns the release segments before the post-release and the + post-release version number (or -1 if no post-release segment is present). + """ + vc = str.split(ver, ".post") + return vc[0], int(vc[1] or 0) if len(vc) == 2 else None + + +def render_pep440_pre(pieces): + """TAG[.postN.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post0.devDISTANCE + """ + if pieces["closest-tag"]: + if pieces["distance"]: + # update the post release segment + tag_version, post_version = pep440_split_post(pieces["closest-tag"]) + rendered = tag_version + if post_version is not None: + rendered += ".post%%d.dev%%d" %% (post_version + 1, pieces["distance"]) + else: + rendered += ".post0.dev%%d" %% (pieces["distance"]) + else: + # no commits, use the tag as the version + rendered = pieces["closest-tag"] + else: + # exception #1 + rendered = "0.post0.dev%%d" %% pieces["distance"] + return rendered + + +def render_pep440_post(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX] . + + The ".dev0" means dirty. Note that .dev0 sorts backwards + (a dirty tree will appear "older" than the corresponding clean one), + but you shouldn't be releasing software with -dirty anyways. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%%s" %% pieces["short"] + else: + # exception #1 + rendered = "0.post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%%s" %% pieces["short"] + return rendered + + +def render_pep440_post_branch(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . + + The ".dev0" means not master branch. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%%d" %% pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%%s" %% pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0.post%%d" %% pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+g%%s" %% pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_old(pieces): + """TAG[.postDISTANCE[.dev0]] . + + The ".dev0" means dirty. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + else: + # exception #1 + rendered = "0.post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + return rendered + + +def render_git_describe(pieces): + """TAG[-DISTANCE-gHEX][-dirty]. + + Like 'git describe --tags --dirty --always'. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render_git_describe_long(pieces): + """TAG-DISTANCE-gHEX[-dirty]. + + Like 'git describe --tags --dirty --always -long'. + The distance/hash is unconditional. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render(pieces, style): + """Render the given version pieces into the requested style.""" + if pieces["error"]: + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None} + + if not style or style == "default": + style = "pep440" # the default + + if style == "pep440": + rendered = render_pep440(pieces) + elif style == "pep440-branch": + rendered = render_pep440_branch(pieces) + elif style == "pep440-pre": + rendered = render_pep440_pre(pieces) + elif style == "pep440-post": + rendered = render_pep440_post(pieces) + elif style == "pep440-post-branch": + rendered = render_pep440_post_branch(pieces) + elif style == "pep440-old": + rendered = render_pep440_old(pieces) + elif style == "git-describe": + rendered = render_git_describe(pieces) + elif style == "git-describe-long": + rendered = render_git_describe_long(pieces) + else: + raise ValueError("unknown style '%%s'" %% style) + + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None, + "date": pieces.get("date")} + + +def get_versions(): + """Get version information or return default if unable to do so.""" + # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have + # __file__, we can work backwards from there to the root. Some + # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which + # case we can only use expanded keywords. + + cfg = get_config() + verbose = cfg.verbose + + try: + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, + verbose) + except NotThisMethod: + pass + + try: + root = os.path.realpath(__file__) + # versionfile_source is the relative path from the top of the source + # tree (where the .git directory might live) to this file. Invert + # this to find the root from __file__. + for _ in cfg.versionfile_source.split('/'): + root = os.path.dirname(root) + except NameError: + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to find root of source tree", + "date": None} + + try: + pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) + return render(pieces, cfg.style) + except NotThisMethod: + pass + + try: + if cfg.parentdir_prefix: + return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) + except NotThisMethod: + pass + + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", "date": None} +''' + + +@register_vcs_handler("git", "get_keywords") +def git_get_keywords(versionfile_abs): + """Extract version information from the given file.""" + # the code embedded in _version.py can just fetch the value of these + # keywords. When used from setup.py, we don't want to import _version.py, + # so we do it with a regexp instead. This function is not used from + # _version.py. + keywords = {} + try: + with open(versionfile_abs, "r") as fobj: + for line in fobj: + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + except OSError: + pass + return keywords + + +@register_vcs_handler("git", "keywords") +def git_versions_from_keywords(keywords, tag_prefix, verbose): + """Get version information from git keywords.""" + if "refnames" not in keywords: + raise NotThisMethod("Short version file found") + date = keywords.get("date") + if date is not None: + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + + # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant + # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 + # -like" string, which we must then edit to make compliant), because + # it's been around since git-1.5.3, and it's too difficult to + # discover which version we're using, or to work around using an + # older one. + date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + refnames = keywords["refnames"].strip() + if refnames.startswith("$Format"): + if verbose: + print("keywords are unexpanded, not using") + raise NotThisMethod("unexpanded keywords, not a git-archive tarball") + refs = {r.strip() for r in refnames.strip("()").split(",")} + # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of + # just "foo-1.0". If we see a "tag: " prefix, prefer those. + TAG = "tag: " + tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} + if not tags: + # Either we're using git < 1.8.3, or there really are no tags. We use + # a heuristic: assume all version tags have a digit. The old git %d + # expansion behaves like git log --decorate=short and strips out the + # refs/heads/ and refs/tags/ prefixes that would let us distinguish + # between branches and tags. By ignoring refnames without digits, we + # filter out many common branch names like "release" and + # "stabilization", as well as "HEAD" and "master". + tags = {r for r in refs if re.search(r'\d', r)} + if verbose: + print("discarding '%s', no digits" % ",".join(refs - tags)) + if verbose: + print("likely tags: %s" % ",".join(sorted(tags))) + for ref in sorted(tags): + # sorting will prefer e.g. "2.0" over "2.0rc1" + if ref.startswith(tag_prefix): + r = ref[len(tag_prefix):] + # Filter out refs that exactly match prefix or that don't start + # with a number once the prefix is stripped (mostly a concern + # when prefix is '') + if not re.match(r'\d', r): + continue + if verbose: + print("picking %s" % r) + return {"version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None, + "date": date} + # no suitable tags, so version is "0+unknown", but full hex is still there + if verbose: + print("no suitable tags, using unknown + full revision id") + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags", "date": None} + + +@register_vcs_handler("git", "pieces_from_vcs") +def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): + """Get version from 'git describe' in the root of the source tree. + + This only gets called if the git-archive 'subst' keywords were *not* + expanded, and _version.py hasn't already been rewritten with a short + version string, meaning we're inside a checked out source tree. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + + # GIT_DIR can interfere with correct operation of Versioneer. + # It may be intended to be passed to the Versioneer-versioned project, + # but that should not change where we get our version from. + env = os.environ.copy() + env.pop("GIT_DIR", None) + runner = functools.partial(runner, env=env) + + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=not verbose) + if rc != 0: + if verbose: + print("Directory %s not under git control" % root) + raise NotThisMethod("'git rev-parse --git-dir' returned error") + + # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] + # if there isn't one, this yields HEX[-dirty] (no NUM) + describe_out, rc = runner(GITS, [ + "describe", "--tags", "--dirty", "--always", "--long", + "--match", f"{tag_prefix}[[:digit:]]*" + ], cwd=root) + # --long was added in git-1.5.5 + if describe_out is None: + raise NotThisMethod("'git describe' failed") + describe_out = describe_out.strip() + full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) + if full_out is None: + raise NotThisMethod("'git rev-parse' failed") + full_out = full_out.strip() + + pieces = {} + pieces["long"] = full_out + pieces["short"] = full_out[:7] # maybe improved later + pieces["error"] = None + + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], + cwd=root) + # --abbrev-ref was added in git-1.6.3 + if rc != 0 or branch_name is None: + raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") + branch_name = branch_name.strip() + + if branch_name == "HEAD": + # If we aren't exactly on a branch, pick a branch which represents + # the current commit. If all else fails, we are on a branchless + # commit. + branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) + # --contains was added in git-1.5.4 + if rc != 0 or branches is None: + raise NotThisMethod("'git branch --contains' returned error") + branches = branches.split("\n") + + # Remove the first line if we're running detached + if "(" in branches[0]: + branches.pop(0) + + # Strip off the leading "* " from the list of branches. + branches = [branch[2:] for branch in branches] + if "master" in branches: + branch_name = "master" + elif not branches: + branch_name = None + else: + # Pick the first branch that is returned. Good or bad. + branch_name = branches[0] + + pieces["branch"] = branch_name + + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] + # TAG might have hyphens. + git_describe = describe_out + + # look for -dirty suffix + dirty = git_describe.endswith("-dirty") + pieces["dirty"] = dirty + if dirty: + git_describe = git_describe[:git_describe.rindex("-dirty")] + + # now we have TAG-NUM-gHEX or HEX + + if "-" in git_describe: + # TAG-NUM-gHEX + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + if not mo: + # unparsable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%s'" + % describe_out) + return pieces + + # tag + full_tag = mo.group(1) + if not full_tag.startswith(tag_prefix): + if verbose: + fmt = "tag '%s' doesn't start with prefix '%s'" + print(fmt % (full_tag, tag_prefix)) + pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" + % (full_tag, tag_prefix)) + return pieces + pieces["closest-tag"] = full_tag[len(tag_prefix):] + + # distance: number of commits since tag + pieces["distance"] = int(mo.group(2)) + + # commit: short hex revision ID + pieces["short"] = mo.group(3) + + else: + # HEX: no tags + pieces["closest-tag"] = None + out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) + pieces["distance"] = len(out.split()) # total number of commits + + # commit date: see ISO-8601 comment in git_versions_from_keywords() + date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + + return pieces + + +def do_vcs_install(versionfile_source, ipy): + """Git-specific installation logic for Versioneer. + + For Git, this means creating/changing .gitattributes to mark _version.py + for export-subst keyword substitution. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + files = [versionfile_source] + if ipy: + files.append(ipy) + if "VERSIONEER_PEP518" not in globals(): + try: + my_path = __file__ + if my_path.endswith((".pyc", ".pyo")): + my_path = os.path.splitext(my_path)[0] + ".py" + versioneer_file = os.path.relpath(my_path) + except NameError: + versioneer_file = "versioneer.py" + files.append(versioneer_file) + present = False + try: + with open(".gitattributes", "r") as fobj: + for line in fobj: + if line.strip().startswith(versionfile_source): + if "export-subst" in line.strip().split()[1:]: + present = True + break + except OSError: + pass + if not present: + with open(".gitattributes", "a+") as fobj: + fobj.write(f"{versionfile_source} export-subst\n") + files.append(".gitattributes") + run_command(GITS, ["add", "--"] + files) + + +def versions_from_parentdir(parentdir_prefix, root, verbose): + """Try to determine the version from the parent directory name. + + Source tarballs conventionally unpack into a directory that includes both + the project name and a version string. We will also support searching up + two directory levels for an appropriately named parent directory + """ + rootdirs = [] + + for _ in range(3): + dirname = os.path.basename(root) + if dirname.startswith(parentdir_prefix): + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None, "date": None} + rootdirs.append(root) + root = os.path.dirname(root) # up a level + + if verbose: + print("Tried directories %s but none started with prefix %s" % + (str(rootdirs), parentdir_prefix)) + raise NotThisMethod("rootdir doesn't start with parentdir_prefix") + + +SHORT_VERSION_PY = """ +# This file was generated by 'versioneer.py' (0.28) from +# revision-control system data, or from the parent directory name of an +# unpacked source archive. Distribution tarballs contain a pre-generated copy +# of this file. + +import json + +version_json = ''' +%s +''' # END VERSION_JSON + + +def get_versions(): + return json.loads(version_json) +""" + + +def versions_from_file(filename): + """Try to determine the version from _version.py if present.""" + try: + with open(filename) as f: + contents = f.read() + except OSError: + raise NotThisMethod("unable to read _version.py") + mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", + contents, re.M | re.S) + if not mo: + mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", + contents, re.M | re.S) + if not mo: + raise NotThisMethod("no version_json in _version.py") + return json.loads(mo.group(1)) + + +def write_to_version_file(filename, versions): + """Write the given version number to the given _version.py file.""" + os.unlink(filename) + contents = json.dumps(versions, sort_keys=True, + indent=1, separators=(",", ": ")) + with open(filename, "w") as f: + f.write(SHORT_VERSION_PY % contents) + + print("set %s to '%s'" % (filename, versions["version"])) + + +def plus_or_dot(pieces): + """Return a + if we don't already have one, else return a .""" + if "+" in pieces.get("closest-tag", ""): + return "." + return "+" + + +def render_pep440(pieces): + """Build up version string, with post-release "local version identifier". + + Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you + get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty + + Exceptions: + 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += plus_or_dot(pieces) + rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_branch(pieces): + """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . + + The ".dev0" means not master branch. Note that .dev0 sorts backwards + (a feature branch will appear "older" than the master branch). + + Exceptions: + 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0" + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def pep440_split_post(ver): + """Split pep440 version string at the post-release segment. + + Returns the release segments before the post-release and the + post-release version number (or -1 if no post-release segment is present). + """ + vc = str.split(ver, ".post") + return vc[0], int(vc[1] or 0) if len(vc) == 2 else None + + +def render_pep440_pre(pieces): + """TAG[.postN.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post0.devDISTANCE + """ + if pieces["closest-tag"]: + if pieces["distance"]: + # update the post release segment + tag_version, post_version = pep440_split_post(pieces["closest-tag"]) + rendered = tag_version + if post_version is not None: + rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) + else: + rendered += ".post0.dev%d" % (pieces["distance"]) + else: + # no commits, use the tag as the version + rendered = pieces["closest-tag"] + else: + # exception #1 + rendered = "0.post0.dev%d" % pieces["distance"] + return rendered + + +def render_pep440_post(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX] . + + The ".dev0" means dirty. Note that .dev0 sorts backwards + (a dirty tree will appear "older" than the corresponding clean one), + but you shouldn't be releasing software with -dirty anyways. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%s" % pieces["short"] + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + return rendered + + +def render_pep440_post_branch(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . + + The ".dev0" means not master branch. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%s" % pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_old(pieces): + """TAG[.postDISTANCE[.dev0]] . + + The ".dev0" means dirty. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + return rendered + + +def render_git_describe(pieces): + """TAG[-DISTANCE-gHEX][-dirty]. + + Like 'git describe --tags --dirty --always'. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render_git_describe_long(pieces): + """TAG-DISTANCE-gHEX[-dirty]. + + Like 'git describe --tags --dirty --always -long'. + The distance/hash is unconditional. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render(pieces, style): + """Render the given version pieces into the requested style.""" + if pieces["error"]: + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None} + + if not style or style == "default": + style = "pep440" # the default + + if style == "pep440": + rendered = render_pep440(pieces) + elif style == "pep440-branch": + rendered = render_pep440_branch(pieces) + elif style == "pep440-pre": + rendered = render_pep440_pre(pieces) + elif style == "pep440-post": + rendered = render_pep440_post(pieces) + elif style == "pep440-post-branch": + rendered = render_pep440_post_branch(pieces) + elif style == "pep440-old": + rendered = render_pep440_old(pieces) + elif style == "git-describe": + rendered = render_git_describe(pieces) + elif style == "git-describe-long": + rendered = render_git_describe_long(pieces) + else: + raise ValueError("unknown style '%s'" % style) + + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None, + "date": pieces.get("date")} + + +class VersioneerBadRootError(Exception): + """The project root directory is unknown or missing key files.""" + + +def get_versions(verbose=False): + """Get the project version from whatever source is available. + + Returns dict with two keys: 'version' and 'full'. + """ + if "versioneer" in sys.modules: + # see the discussion in cmdclass.py:get_cmdclass() + del sys.modules["versioneer"] + + root = get_root() + cfg = get_config_from_root(root) + + assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" + handlers = HANDLERS.get(cfg.VCS) + assert handlers, "unrecognized VCS '%s'" % cfg.VCS + verbose = verbose or cfg.verbose + assert cfg.versionfile_source is not None, \ + "please set versioneer.versionfile_source" + assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" + + versionfile_abs = os.path.join(root, cfg.versionfile_source) + + # extract version from first of: _version.py, VCS command (e.g. 'git + # describe'), parentdir. This is meant to work for developers using a + # source checkout, for users of a tarball created by 'setup.py sdist', + # and for users of a tarball/zipball created by 'git archive' or github's + # download-from-tag feature or the equivalent in other VCSes. + + get_keywords_f = handlers.get("get_keywords") + from_keywords_f = handlers.get("keywords") + if get_keywords_f and from_keywords_f: + try: + keywords = get_keywords_f(versionfile_abs) + ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) + if verbose: + print("got version from expanded keyword %s" % ver) + return ver + except NotThisMethod: + pass + + try: + ver = versions_from_file(versionfile_abs) + if verbose: + print("got version from file %s %s" % (versionfile_abs, ver)) + return ver + except NotThisMethod: + pass + + from_vcs_f = handlers.get("pieces_from_vcs") + if from_vcs_f: + try: + pieces = from_vcs_f(cfg.tag_prefix, root, verbose) + ver = render(pieces, cfg.style) + if verbose: + print("got version from VCS %s" % ver) + return ver + except NotThisMethod: + pass + + try: + if cfg.parentdir_prefix: + ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) + if verbose: + print("got version from parentdir %s" % ver) + return ver + except NotThisMethod: + pass + + if verbose: + print("unable to compute version") + + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, "error": "unable to compute version", + "date": None} + + +def get_version(): + """Get the short version string for this project.""" + return get_versions()["version"] + + +def get_cmdclass(cmdclass=None): + """Get the custom setuptools subclasses used by Versioneer. + + If the package uses a different cmdclass (e.g. one from numpy), it + should be provide as an argument. + """ + if "versioneer" in sys.modules: + del sys.modules["versioneer"] + # this fixes the "python setup.py develop" case (also 'install' and + # 'easy_install .'), in which subdependencies of the main project are + # built (using setup.py bdist_egg) in the same python process. Assume + # a main project A and a dependency B, which use different versions + # of Versioneer. A's setup.py imports A's Versioneer, leaving it in + # sys.modules by the time B's setup.py is executed, causing B to run + # with the wrong versioneer. Setuptools wraps the sub-dep builds in a + # sandbox that restores sys.modules to it's pre-build state, so the + # parent is protected against the child's "import versioneer". By + # removing ourselves from sys.modules here, before the child build + # happens, we protect the child from the parent's versioneer too. + # Also see https://github.com/python-versioneer/python-versioneer/issues/52 + + cmds = {} if cmdclass is None else cmdclass.copy() + + # we add "version" to setuptools + from setuptools import Command + + class cmd_version(Command): + description = "report generated version string" + user_options = [] + boolean_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + vers = get_versions(verbose=True) + print("Version: %s" % vers["version"]) + print(" full-revisionid: %s" % vers.get("full-revisionid")) + print(" dirty: %s" % vers.get("dirty")) + print(" date: %s" % vers.get("date")) + if vers["error"]: + print(" error: %s" % vers["error"]) + cmds["version"] = cmd_version + + # we override "build_py" in setuptools + # + # most invocation pathways end up running build_py: + # distutils/build -> build_py + # distutils/install -> distutils/build ->.. + # setuptools/bdist_wheel -> distutils/install ->.. + # setuptools/bdist_egg -> distutils/install_lib -> build_py + # setuptools/install -> bdist_egg ->.. + # setuptools/develop -> ? + # pip install: + # copies source tree to a tempdir before running egg_info/etc + # if .git isn't copied too, 'git describe' will fail + # then does setup.py bdist_wheel, or sometimes setup.py install + # setup.py egg_info -> ? + + # pip install -e . and setuptool/editable_wheel will invoke build_py + # but the build_py command is not expected to copy any files. + + # we override different "build_py" commands for both environments + if 'build_py' in cmds: + _build_py = cmds['build_py'] + else: + from setuptools.command.build_py import build_py as _build_py + + class cmd_build_py(_build_py): + def run(self): + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + _build_py.run(self) + if getattr(self, "editable_mode", False): + # During editable installs `.py` and data files are + # not copied to build_lib + return + # now locate _version.py in the new build/ directory and replace + # it with an updated value + if cfg.versionfile_build: + target_versionfile = os.path.join(self.build_lib, + cfg.versionfile_build) + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + cmds["build_py"] = cmd_build_py + + if 'build_ext' in cmds: + _build_ext = cmds['build_ext'] + else: + from setuptools.command.build_ext import build_ext as _build_ext + + class cmd_build_ext(_build_ext): + def run(self): + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + _build_ext.run(self) + if self.inplace: + # build_ext --inplace will only build extensions in + # build/lib<..> dir with no _version.py to write to. + # As in place builds will already have a _version.py + # in the module dir, we do not need to write one. + return + # now locate _version.py in the new build/ directory and replace + # it with an updated value + if not cfg.versionfile_build: + return + target_versionfile = os.path.join(self.build_lib, + cfg.versionfile_build) + if not os.path.exists(target_versionfile): + print(f"Warning: {target_versionfile} does not exist, skipping " + "version update. This can happen if you are running build_ext " + "without first running build_py.") + return + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + cmds["build_ext"] = cmd_build_ext + + if "cx_Freeze" in sys.modules: # cx_freeze enabled? + from cx_Freeze.dist import build_exe as _build_exe + # nczeczulin reports that py2exe won't like the pep440-style string + # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. + # setup(console=[{ + # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION + # "product_version": versioneer.get_version(), + # ... + + class cmd_build_exe(_build_exe): + def run(self): + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + target_versionfile = cfg.versionfile_source + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + + _build_exe.run(self) + os.unlink(target_versionfile) + with open(cfg.versionfile_source, "w") as f: + LONG = LONG_VERSION_PY[cfg.VCS] + f.write(LONG % + {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) + cmds["build_exe"] = cmd_build_exe + del cmds["build_py"] + + if 'py2exe' in sys.modules: # py2exe enabled? + try: + from py2exe.setuptools_buildexe import py2exe as _py2exe + except ImportError: + from py2exe.distutils_buildexe import py2exe as _py2exe + + class cmd_py2exe(_py2exe): + def run(self): + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + target_versionfile = cfg.versionfile_source + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + + _py2exe.run(self) + os.unlink(target_versionfile) + with open(cfg.versionfile_source, "w") as f: + LONG = LONG_VERSION_PY[cfg.VCS] + f.write(LONG % + {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) + cmds["py2exe"] = cmd_py2exe + + # sdist farms its file list building out to egg_info + if 'egg_info' in cmds: + _egg_info = cmds['egg_info'] + else: + from setuptools.command.egg_info import egg_info as _egg_info + + class cmd_egg_info(_egg_info): + def find_sources(self): + # egg_info.find_sources builds the manifest list and writes it + # in one shot + super().find_sources() + + # Modify the filelist and normalize it + root = get_root() + cfg = get_config_from_root(root) + self.filelist.append('versioneer.py') + if cfg.versionfile_source: + # There are rare cases where versionfile_source might not be + # included by default, so we must be explicit + self.filelist.append(cfg.versionfile_source) + self.filelist.sort() + self.filelist.remove_duplicates() + + # The write method is hidden in the manifest_maker instance that + # generated the filelist and was thrown away + # We will instead replicate their final normalization (to unicode, + # and POSIX-style paths) + from setuptools import unicode_utils + normalized = [unicode_utils.filesys_decode(f).replace(os.sep, '/') + for f in self.filelist.files] + + manifest_filename = os.path.join(self.egg_info, 'SOURCES.txt') + with open(manifest_filename, 'w') as fobj: + fobj.write('\n'.join(normalized)) + + cmds['egg_info'] = cmd_egg_info + + # we override different "sdist" commands for both environments + if 'sdist' in cmds: + _sdist = cmds['sdist'] + else: + from setuptools.command.sdist import sdist as _sdist + + class cmd_sdist(_sdist): + def run(self): + versions = get_versions() + self._versioneer_generated_versions = versions + # unless we update this, the command will keep using the old + # version + self.distribution.metadata.version = versions["version"] + return _sdist.run(self) + + def make_release_tree(self, base_dir, files): + root = get_root() + cfg = get_config_from_root(root) + _sdist.make_release_tree(self, base_dir, files) + # now locate _version.py in the new base_dir directory + # (remembering that it may be a hardlink) and replace it with an + # updated value + target_versionfile = os.path.join(base_dir, cfg.versionfile_source) + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, + self._versioneer_generated_versions) + cmds["sdist"] = cmd_sdist + + return cmds + + +CONFIG_ERROR = """ +setup.cfg is missing the necessary Versioneer configuration. You need +a section like: + + [versioneer] + VCS = git + style = pep440 + versionfile_source = src/myproject/_version.py + versionfile_build = myproject/_version.py + tag_prefix = + parentdir_prefix = myproject- + +You will also need to edit your setup.py to use the results: + + import versioneer + setup(version=versioneer.get_version(), + cmdclass=versioneer.get_cmdclass(), ...) + +Please read the docstring in ./versioneer.py for configuration instructions, +edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. +""" + +SAMPLE_CONFIG = """ +# See the docstring in versioneer.py for instructions. Note that you must +# re-run 'versioneer.py setup' after changing this section, and commit the +# resulting files. + +[versioneer] +#VCS = git +#style = pep440 +#versionfile_source = +#versionfile_build = +#tag_prefix = +#parentdir_prefix = + +""" + +OLD_SNIPPET = """ +from ._version import get_versions +__version__ = get_versions()['version'] +del get_versions +""" + +INIT_PY_SNIPPET = """ +from . import {0} +__version__ = {0}.get_versions()['version'] +""" + + +def do_setup(): + """Do main VCS-independent setup function for installing Versioneer.""" + root = get_root() + try: + cfg = get_config_from_root(root) + except (OSError, configparser.NoSectionError, + configparser.NoOptionError) as e: + if isinstance(e, (OSError, configparser.NoSectionError)): + print("Adding sample versioneer config to setup.cfg", + file=sys.stderr) + with open(os.path.join(root, "setup.cfg"), "a") as f: + f.write(SAMPLE_CONFIG) + print(CONFIG_ERROR, file=sys.stderr) + return 1 + + print(" creating %s" % cfg.versionfile_source) + with open(cfg.versionfile_source, "w") as f: + LONG = LONG_VERSION_PY[cfg.VCS] + f.write(LONG % {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) + + ipy = os.path.join(os.path.dirname(cfg.versionfile_source), + "__init__.py") + if os.path.exists(ipy): + try: + with open(ipy, "r") as f: + old = f.read() + except OSError: + old = "" + module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0] + snippet = INIT_PY_SNIPPET.format(module) + if OLD_SNIPPET in old: + print(" replacing boilerplate in %s" % ipy) + with open(ipy, "w") as f: + f.write(old.replace(OLD_SNIPPET, snippet)) + elif snippet not in old: + print(" appending to %s" % ipy) + with open(ipy, "a") as f: + f.write(snippet) + else: + print(" %s unmodified" % ipy) + else: + print(" %s doesn't exist, ok" % ipy) + ipy = None + + # Make VCS-specific changes. For git, this means creating/changing + # .gitattributes to mark _version.py for export-subst keyword + # substitution. + do_vcs_install(cfg.versionfile_source, ipy) + return 0 + + +def scan_setup_py(): + """Validate the contents of setup.py against Versioneer's expectations.""" + found = set() + setters = False + errors = 0 + with open("setup.py", "r") as f: + for line in f.readlines(): + if "import versioneer" in line: + found.add("import") + if "versioneer.get_cmdclass()" in line: + found.add("cmdclass") + if "versioneer.get_version()" in line: + found.add("get_version") + if "versioneer.VCS" in line: + setters = True + if "versioneer.versionfile_source" in line: + setters = True + if len(found) != 3: + print("") + print("Your setup.py appears to be missing some important items") + print("(but I might be wrong). Please make sure it has something") + print("roughly like the following:") + print("") + print(" import versioneer") + print(" setup( version=versioneer.get_version(),") + print(" cmdclass=versioneer.get_cmdclass(), ...)") + print("") + errors += 1 + if setters: + print("You should remove lines like 'versioneer.VCS = ' and") + print("'versioneer.versionfile_source = ' . This configuration") + print("now lives in setup.cfg, and should be removed from setup.py") + print("") + errors += 1 + return errors + + +def setup_command(): + """Set up Versioneer and exit with appropriate error code.""" + errors = do_setup() + errors += scan_setup_py() + sys.exit(1 if errors else 0) + + +if __name__ == "__main__": + cmd = sys.argv[1] + if cmd == "setup": + setup_command() diff --git a/pyvenv.cfg b/pyvenv.cfg new file mode 100644 index 0000000..3e18ed6 --- /dev/null +++ b/pyvenv.cfg @@ -0,0 +1,5 @@ +home = /usr/bin +include-system-site-packages = false +version = 3.12.6 +executable = /usr/bin/python3.12 +command = /usr/bin/python -m venv /home/leonie/Documents/projects/meta-kitties diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..7a74960 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +-e modules/MiPA +prometheus-client