Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GitHub integration revamp #38458

Closed
wants to merge 43 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
c9bbc5e
Basic setup of integration
timmo001 Jul 25, 2020
133f9df
Working sensor
timmo001 Jul 25, 2020
1ebd9cf
Add missing attrs
timmo001 Jul 25, 2020
088e433
Reauth flow
timmo001 Jul 25, 2020
db9d08e
Add views
timmo001 Jul 25, 2020
ef591ea
Order
timmo001 Jul 25, 2020
e595596
Add homepage
timmo001 Jul 25, 2020
aab3377
Super classes
timmo001 Jul 26, 2020
8df4193
Data update coordinator
timmo001 Jul 26, 2020
52bcd1f
Sensor entity
timmo001 Jul 26, 2020
95ef5b4
Move attributes set into update
timmo001 Jul 26, 2020
bc24053
Split sensor into individual sensors
timmo001 Jul 26, 2020
e149cb0
Add TODOs
timmo001 Jul 26, 2020
f1ff436
Add TODO
timmo001 Jul 26, 2020
5aaf11c
Change name
timmo001 Jul 26, 2020
6d8eddf
Fix for clones and views for those without push access
timmo001 Jul 26, 2020
253e513
Options flow
timmo001 Jul 26, 2020
9dfa281
Cleanup and fix update
timmo001 Jul 26, 2020
145dbf7
Update and handle errors
timmo001 Jul 26, 2020
8fffd53
Unique ids
timmo001 Aug 1, 2020
5ac5c28
Fix unique id set position
timmo001 Aug 1, 2020
164a37c
Add tests
timmo001 Aug 1, 2020
e783a39
Add untested to coverage
timmo001 Aug 1, 2020
550801c
Cleanup
timmo001 Aug 1, 2020
96e564e
Fix typo
timmo001 Aug 1, 2020
c205dfa
Add reauth tests
timmo001 Aug 2, 2020
5dab906
Add tests and json fixture
timmo001 Aug 2, 2020
36ea668
Update aiogithubapi to 1.1.1
timmo001 Aug 2, 2020
25c29d0
Update data
timmo001 Aug 2, 2020
80498f0
Update aiogithubapi to 1.1.2 and add sha and message
timmo001 Aug 2, 2020
6d9c6ad
Make push access true for fixture
timmo001 Aug 2, 2020
549fcbe
Rework reauth logic
timmo001 Aug 2, 2020
8ac5bb4
Update tests for changes
timmo001 Aug 2, 2020
421fc33
Add reauth invalid auth test
timmo001 Aug 2, 2020
ab86e66
Typo
timmo001 Aug 2, 2020
4963d0f
Split identifiers and set as service
timmo001 Aug 2, 2020
21763a6
Tests
timmo001 Aug 3, 2020
2c826b3
Format
timmo001 Sep 5, 2020
ab8f55c
Lint
timmo001 Sep 5, 2020
e621394
Remove bad lines from rebase
timmo001 Sep 5, 2020
9419154
Remove unneeded removal
timmo001 Sep 5, 2020
c06d978
Update to use CoordinatorEntity
timmo001 Sep 5, 2020
31712fe
Update aiogithubapi to v2.0.0
timmo001 Oct 11, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,7 @@ omit =
homeassistant/components/gc100/*
homeassistant/components/geniushub/*
homeassistant/components/geizhals/sensor.py
homeassistant/components/github/__init__.py
homeassistant/components/github/sensor.py
homeassistant/components/gitlab_ci/sensor.py
homeassistant/components/gitter/sensor.py
Expand Down
1 change: 1 addition & 0 deletions CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ homeassistant/components/geo_rss_events/* @exxamalte
homeassistant/components/geonetnz_quakes/* @exxamalte
homeassistant/components/geonetnz_volcano/* @exxamalte
homeassistant/components/gios/* @bieniu
homeassistant/components/github/* @timmo001
homeassistant/components/gitter/* @fabaff
homeassistant/components/glances/* @fabaff @engrbm87
homeassistant/components/goalzero/* @tkdrob
Expand Down
249 changes: 248 additions & 1 deletion homeassistant/components/github/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,248 @@
"""The github component."""
"""The GitHub integration."""
import asyncio
from datetime import timedelta
import logging
from typing import Any, Dict, List

from aiogithubapi import (
AIOGitHubAPIAuthenticationException,
AIOGitHubAPIException,
GitHub,
)
from aiogithubapi.objects.repos.commit import AIOGitHubAPIReposCommit
from aiogithubapi.objects.repos.traffic.clones import AIOGitHubAPIReposTrafficClones
from aiogithubapi.objects.repos.traffic.pageviews import (
AIOGitHubAPIReposTrafficPageviews,
)
from aiogithubapi.objects.repository import (
AIOGitHubAPIRepository,
AIOGitHubAPIRepositoryIssue,
AIOGitHubAPIRepositoryRelease,
)
import async_timeout

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_ACCESS_TOKEN
from homeassistant.core import Config, HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
UpdateFailed,
)

from .const import (
CONF_CLONES,
CONF_ISSUES_PRS,
CONF_LATEST_COMMIT,
CONF_LATEST_RELEASE,
CONF_REPOSITORY,
CONF_VIEWS,
DATA_COORDINATOR,
DATA_REPOSITORY,
DOMAIN,
)

_LOGGER = logging.getLogger(__name__)

PLATFORMS = ["sensor"]


class GitHubData:
"""Represents a GitHub data object."""

def __init__(
self,
repository: AIOGitHubAPIRepository,
latest_commit: AIOGitHubAPIReposCommit = None,
clones: AIOGitHubAPIReposTrafficClones = None,
issues: List[AIOGitHubAPIRepositoryIssue] = None,
releases: List[AIOGitHubAPIRepositoryRelease] = None,
views: AIOGitHubAPIReposTrafficPageviews = None,
) -> None:
"""Initialize the GitHub data object."""
self.repository = repository
self.latest_commit = latest_commit
self.clones = clones
self.issues = issues
self.releases = releases
self.views = views

if issues is not None:
open_issues: List[AIOGitHubAPIRepositoryIssue] = []
open_pull_requests: List[AIOGitHubAPIRepositoryIssue] = []
for issue in issues:
if issue.state == "open":
if "pull" in issue.html_url:
open_pull_requests.append(issue)
else:
open_issues.append(issue)

self.open_issues = open_issues
self.open_pull_requests = open_pull_requests
else:
self.open_issues = None
self.open_pull_requests = None


async def async_setup(hass: HomeAssistant, config: Config) -> bool:
"""Set up GitHub integration."""
return True


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up GitHub from a config entry."""
try:
github = GitHub(entry.data[CONF_ACCESS_TOKEN])
repository = await github.get_repo(entry.data[CONF_REPOSITORY])
except (AIOGitHubAPIAuthenticationException, AIOGitHubAPIException):
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={"source": "reauth"}, data=entry.data
)
)
return False

async def async_update_data() -> GitHubData:
"""Fetch data from GitHub."""
try:
async with async_timeout.timeout(60):
repository: AIOGitHubAPIRepository = await github.get_repo(
entry.data[CONF_REPOSITORY]
)
if entry.options.get(CONF_LATEST_COMMIT, True) is True:
latest_commit: AIOGitHubAPIReposCommit = (
await repository.get_last_commit()
)
else:
latest_commit = None
if entry.options.get(CONF_ISSUES_PRS, False) is True:
issues: List[
AIOGitHubAPIRepositoryIssue
] = await repository.get_issues()
else:
issues = None
if entry.options.get(CONF_LATEST_RELEASE, False) is True:
releases: List[
AIOGitHubAPIRepositoryRelease
] = await repository.get_releases()
else:
releases = None
if repository.attributes.get("permissions").get("push") is True:
if entry.options.get(CONF_CLONES, False) is True:
clones: AIOGitHubAPIReposTrafficClones = (
await repository.traffic.get_clones()
)
else:
clones = None
if entry.options.get(CONF_VIEWS, False) is True:
views: AIOGitHubAPIReposTrafficPageviews = (
await repository.traffic.get_views()
)
else:
views = None
else:
clones = None
views = None

return GitHubData(
repository, latest_commit, clones, issues, releases, views
)
except (AIOGitHubAPIAuthenticationException, AIOGitHubAPIException) as err:
raise UpdateFailed(f"Error communicating with GitHub: {err}") from err

coordinator = DataUpdateCoordinator(
hass,
_LOGGER,
# Name of the data. For logging purposes.
name=DOMAIN,
update_method=async_update_data,
# Polling interval. Will only be polled if there are subscribers.
update_interval=timedelta(seconds=120),
)

hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {
DATA_COORDINATOR: coordinator,
DATA_REPOSITORY: repository,
}

# Fetch initial data so we have data when entities subscribe
await coordinator.async_refresh()

if not coordinator.last_update_success:
raise ConfigEntryNotReady

for component in PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, component)
)

return True


async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry."""
unload_ok = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, component)
for component in PLATFORMS
]
)
)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)

return unload_ok


class GitHubEntity(CoordinatorEntity):
"""Defines a GitHub entity."""

def __init__(
self, coordinator: DataUpdateCoordinator, unique_id: str, name: str, icon: str
) -> None:
"""Set up GitHub Entity."""
super().__init__(coordinator)
self._unique_id = unique_id
self._name = name
self._icon = icon
self._available = True

@property
def unique_id(self):
"""Return the unique_id of the sensor."""
return self._unique_id

@property
def name(self) -> str:
"""Return the name of the entity."""
return self._name

@property
def icon(self) -> str:
"""Return the mdi icon of the entity."""
return self._icon

@property
def available(self) -> bool:
"""Return True if entity is available."""
return self.coordinator.last_update_success and self._available


class GitHubDeviceEntity(GitHubEntity):
"""Defines a GitHub device entity."""

@property
def device_info(self) -> Dict[str, Any]:
"""Return device information about this GitHub instance."""
data: GitHubData = self.coordinator.data

return {
"entry_type": "service",
"identifiers": {
(DOMAIN, data.repository.owner.login, data.repository.name)
},
"manufacturer": data.repository.attributes.get("owner").get("login"),
"name": data.repository.full_name,
}
Loading