Skip to content

Commit

Permalink
feat: use woodchips for logging, bump pretty_tables (#10)
Browse files Browse the repository at this point in the history
* feat: use woodchips for logging, bump pretty_tables

* fix: small refactor to tests
  • Loading branch information
Justintime50 authored Nov 25, 2021
1 parent 26b7602 commit 5859b85
Show file tree
Hide file tree
Showing 17 changed files with 276 additions and 109 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: 3.9
python-version: "3.10"
- name: Install Dependencies
run: make install
- name: Run linting
Expand All @@ -31,7 +31,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
pythonversion: ["3.7", "3.8", "3.9"]
pythonversion: ["3.7", "3.8", "3.9", "3.10"]
steps:
- name: Checkout Repository
uses: actions/checkout@v2
Expand Down
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# CHANGELOG

## v0.9.0 (2021-11-24)

* Uses `woodchips` for logging
* Bumps `pretty_tables` to v2
* Bump Python version used from 3.9 to 3.10
* Adds Python type hinting

## v0.8.3 (2021-11-03)

* Fixes a bug that setup the git environment incorrectly after the shell refactor from the last release
Expand Down
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM python:3.9-alpine
FROM python:3.10-alpine

RUN apk add --no-cache \
# Install git to push new Homebrew formula
Expand Down
66 changes: 39 additions & 27 deletions homebrew_releaser/app.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import logging
import os

import woodchips

from homebrew_releaser.checksum import Checksum
from homebrew_releaser.constants import FORMULA_FOLDER, GITHUB_TOKEN, TAR_ARCHIVE
from homebrew_releaser.constants import (
FORMULA_FOLDER,
GITHUB_TOKEN,
LOGGER_NAME,
TAR_ARCHIVE,
)
from homebrew_releaser.formula import Formula
from homebrew_releaser.git import Git
from homebrew_releaser.readme_updater import ReadmeUpdater
Expand Down Expand Up @@ -32,7 +38,7 @@
class App:
@staticmethod
def run_github_action():
"""Runs the complete GitHub Action workflow
"""Runs the complete GitHub Action workflow.
1. Setup logging
2. Grab the details about the tap
Expand All @@ -42,33 +48,27 @@ def run_github_action():
6. Update README table (optional)
7. Add, commit, and push to GitHub
"""
if DEBUG:
logging_level = logging.DEBUG
else:
logging_level = logging.INFO
App.setup_logger()
logger = woodchips.get(LOGGER_NAME)

logging.basicConfig(
level=logging_level,
format='%(asctime)s - %(levelname)s - %(message)s',
)
logging.info('Starting Homebrew Releaser...')
logger.info('Starting Homebrew Releaser...')
App.check_required_env_variables()

logging.info('Setting up git environment...')
logger.info('Setting up git environment...')
Git.setup(COMMIT_OWNER, COMMIT_EMAIL, HOMEBREW_OWNER, HOMEBREW_TAP)

logging.info(f'Collecting data about {GITHUB_REPO}...')
logger.info(f'Collecting data about {GITHUB_REPO}...')
repository = Utils.make_get_request(f'{GITHUB_BASE_URL}/repos/{GITHUB_OWNER}/{GITHUB_REPO}', False).json()
tags = Utils.make_get_request(f'{GITHUB_BASE_URL}/repos/{GITHUB_OWNER}/{GITHUB_REPO}/tags', False).json()
version = tags[0]['name']
logging.info(f'Latest release of {version} successfully identified...')
logger.info(f'Latest release of {version} successfully identified...')
tar_url = f'https://github.com/{GITHUB_OWNER}/{GITHUB_REPO}/archive/{version}.tar.gz'

logging.info('Generating tar archive checksum...')
logger.info('Generating tar archive checksum...')
App.download_latest_tar_archive(tar_url)
checksum = Checksum.get_checksum(TAR_ARCHIVE)

logging.info(f'Generating Homebrew formula for {GITHUB_REPO}...')
logger.info(f'Generating Homebrew formula for {GITHUB_REPO}...')
template = Formula.generate_formula_data(
GITHUB_OWNER,
GITHUB_REPO,
Expand All @@ -82,24 +82,36 @@ def run_github_action():
Utils.write_file(f'{HOMEBREW_TAP}/{FORMULA_FOLDER}/{repository["name"]}.rb', template, 'w')

if UPDATE_README_TABLE:
logging.info('Attempting to update the README\'s project table...')
logger.info('Attempting to update the README\'s project table...')
ReadmeUpdater.update_readme(HOMEBREW_TAP)
else:
logging.debug('Skipping update to project README.')
logger.debug('Skipping update to project README.')

if SKIP_COMMIT:
logging.info(f'Skipping commit to {HOMEBREW_TAP}.')
logger.info(f'Skipping commit to {HOMEBREW_TAP}.')
else:
logging.info(f'Attempting to release {version} of {GITHUB_REPO} to {HOMEBREW_TAP}...')
logger.info(f'Attempting to release {version} of {GITHUB_REPO} to {HOMEBREW_TAP}...')
Git.add(HOMEBREW_TAP)
Git.commit(HOMEBREW_TAP, GITHUB_REPO, version)
Git.push(HOMEBREW_TAP, HOMEBREW_OWNER)
# TODO: Check the remote repo to ensure it got the new commit
logging.info(f'Successfully released {version} of {GITHUB_REPO} to {HOMEBREW_TAP}!')
logger.info(f'Successfully released {version} of {GITHUB_REPO} to {HOMEBREW_TAP}!')

@staticmethod
def setup_logger():
"""Setup a `woodchips` logger instance."""
logging_level = 'DEBUG' if DEBUG else 'INFO'

logger = woodchips.Logger(
name=LOGGER_NAME,
level=logging_level,
)
logger.log_to_console()

@staticmethod
def check_required_env_variables():
"""Checks that all required env variables are set"""
"""Checks that all required env variables are set."""
logger = woodchips.get(LOGGER_NAME)

required_env_variables = [
GITHUB_TOKEN,
HOMEBREW_OWNER,
Expand All @@ -111,11 +123,11 @@ def check_required_env_variables():
raise SystemExit(
'You must provide all necessary environment variables. Please reference the Homebrew Releaser documentation.' # noqa
)
logging.debug('All required environment variables are present.')
logger.debug('All required environment variables are present.')

@staticmethod
def download_latest_tar_archive(url):
"""Download the latest tar archive from GitHub"""
def download_latest_tar_archive(url: str):
"""Download the latest tar archive from GitHub."""
response = Utils.make_get_request(url, True)
Utils.write_file(TAR_ARCHIVE, response.content, 'wb')

Expand Down
16 changes: 10 additions & 6 deletions homebrew_releaser/checksum.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import logging
import subprocess

from homebrew_releaser.constants import SUBPROCESS_TIMEOUT
import woodchips

from homebrew_releaser.constants import LOGGER_NAME, SUBPROCESS_TIMEOUT


class Checksum:
@staticmethod
def get_checksum(tar_file):
"""Gets the checksum of a file"""
def get_checksum(tar_filepath: str) -> str:
"""Gets the checksum of a file."""
logger = woodchips.get(LOGGER_NAME)

# TODO: Create and upload a `checksums.txt` file to the release for the zip and tar archives
try:
command = ['shasum', '-a', '256', tar_file]
command = ['shasum', '-a', '256', tar_filepath]
output = subprocess.check_output(
command,
stdin=None,
Expand All @@ -19,9 +22,10 @@ def get_checksum(tar_file):
)
checksum = output.decode().split()[0]
checksum_file = output.decode().split()[1] # TODO: Use this to craft the `checksums.txt` file # noqa
logging.debug(f'Checksum generated successfully: {checksum}')
logger.debug(f'Checksum generated successfully: {checksum}')
except subprocess.TimeoutExpired as error:
raise SystemExit(error)
except subprocess.CalledProcessError as error:
raise SystemExit(error)

return checksum
1 change: 1 addition & 0 deletions homebrew_releaser/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
GITHUB_TOKEN = os.getenv('INPUT_GITHUB_TOKEN')

# App Constants
LOGGER_NAME = 'homebrew-releaser'
SUBPROCESS_TIMEOUT = 30
GITHUB_HEADERS = {
'accept': 'application/vnd.github.v3+json',
Expand Down
27 changes: 21 additions & 6 deletions homebrew_releaser/formula.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
import logging
import re
from typing import Optional

import woodchips

from homebrew_releaser.constants import LOGGER_NAME


class Formula:
@staticmethod
def generate_formula_data(owner, repo_name, repository, checksum, install, tar_url, test):
"""Generates the formula data for Homebrew
def generate_formula_data(
owner: str,
repo_name: str,
repository: str,
checksum: str,
install: str,
tar_url: str,
test: Optional[str] = None,
) -> str:
"""Generates the formula data for Homebrew.
We attempt to ensure generated formula will pass `brew audit --strict --online` if given correct inputs:
- Proper class name
Expand All @@ -17,6 +29,8 @@ def generate_formula_data(owner, repo_name, repository, checksum, install, tar_u
- Test is included
- No version attribute if Homebrew can reliably infer the version from the tar URL (GitHub tag)
"""
logger = woodchips.get(LOGGER_NAME)

repo_name_length = len(repo_name)
max_desc_field_length = 80
max_desc_field_buffer = 2
Expand All @@ -32,7 +46,7 @@ def generate_formula_data(owner, repo_name, repository, checksum, install, tar_u
description = first_word_of_desc[1].strip().capitalize()

# RUBY TEMPLATE DATA TO REMAIN DOUBLE SPACED
test = (
test_content = (
f"""
test do
{test.strip()}
Expand All @@ -56,7 +70,8 @@ class {class_name} < Formula
def install
{install.strip()}
end
{test}
{test_content}
"""
logging.debug('Homebrew formula generated successfully.')
logger.debug('Homebrew formula generated successfully.')

return template
35 changes: 22 additions & 13 deletions homebrew_releaser/git.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
import logging
import subprocess

from homebrew_releaser.constants import GITHUB_TOKEN, SUBPROCESS_TIMEOUT
import woodchips

from homebrew_releaser.constants import GITHUB_TOKEN, LOGGER_NAME, SUBPROCESS_TIMEOUT


class Git:
@staticmethod
def setup(commit_owner, commit_email, homebrew_owner, homebrew_tap):
def setup(commit_owner: str, commit_email: str, homebrew_owner: str, homebrew_tap: str):
"""Sets up the git environment we'll need to commit our changes to the
homebrew tap.
1) Clone the Homebrew tap repo
2) Navigate to the repo on disk
3) Set git config for the commit
"""
logger = woodchips.get(LOGGER_NAME)

try:
commands = [
['git', 'clone', '--depth=1', f'https://{GITHUB_TOKEN}@github.com/{homebrew_owner}/{homebrew_tap}.git'],
Expand All @@ -28,15 +31,17 @@ def setup(commit_owner, commit_email, homebrew_owner, homebrew_tap):
stderr=None,
timeout=SUBPROCESS_TIMEOUT,
)
logging.debug('Git environment setup successfully.')
logger.debug('Git environment setup successfully.')
except subprocess.TimeoutExpired as error:
raise SystemExit(error)
except subprocess.CalledProcessError as error:
raise SystemExit(error)

@staticmethod
def add(homebrew_tap):
"""Adds assets to a git commit"""
def add(homebrew_tap: str):
"""Adds assets to a git commit."""
logger = woodchips.get(LOGGER_NAME)

try:
command = ['git', '-C', homebrew_tap, 'add', '.']
subprocess.check_output(
Expand All @@ -45,15 +50,17 @@ def add(homebrew_tap):
stderr=None,
timeout=SUBPROCESS_TIMEOUT,
)
logging.debug('Assets added to git commit successfully.')
logger.debug('Assets added to git commit successfully.')
except subprocess.TimeoutExpired as error:
raise SystemExit(error)
except subprocess.CalledProcessError as error:
raise SystemExit(error)

@staticmethod
def commit(homebrew_tap, repo_name, version):
"""Commits assets to the Homebrew tap (repo)"""
def commit(homebrew_tap: str, repo_name: str, version: str):
"""Commits assets to the Homebrew tap (repo)."""
logger = woodchips.get(LOGGER_NAME)

try:
# fmt: off
command = ['git', '-C', homebrew_tap, 'commit', '-m', f'"Brew formula update for {repo_name} version {version}"'] # noqa
Expand All @@ -64,15 +71,17 @@ def commit(homebrew_tap, repo_name, version):
stderr=None,
timeout=SUBPROCESS_TIMEOUT,
)
logging.debug('Assets committed successfully.')
logger.debug('Assets committed successfully.')
except subprocess.TimeoutExpired as error:
raise SystemExit(error)
except subprocess.CalledProcessError as error:
raise SystemExit(error)

@staticmethod
def push(homebrew_tap, homebrew_owner):
"""Pushes assets to the remote Homebrew tap (repo)"""
def push(homebrew_tap: str, homebrew_owner: str):
"""Pushes assets to the remote Homebrew tap (repo)."""
logger = woodchips.get(LOGGER_NAME)

try:
# fmt: off
command = ['git', '-C', homebrew_tap, 'push', f'https://{GITHUB_TOKEN}@github.com/{homebrew_owner}/{homebrew_tap}.git'] # noqa
Expand All @@ -83,7 +92,7 @@ def push(homebrew_tap, homebrew_owner):
stderr=None,
timeout=SUBPROCESS_TIMEOUT,
)
logging.debug(f'Assets pushed successfully to {homebrew_tap}.')
logger.debug(f'Assets pushed successfully to {homebrew_tap}.')
except subprocess.TimeoutExpired as error:
raise SystemExit(error)
except subprocess.CalledProcessError as error:
Expand Down
Loading

0 comments on commit 5859b85

Please sign in to comment.