Skip to content

Commit

Permalink
Script to upload to pypi
Browse files Browse the repository at this point in the history
  • Loading branch information
derailed-dash committed Sep 18, 2023
1 parent 610accf commit 5c38a19
Show file tree
Hide file tree
Showing 22 changed files with 212 additions and 157 deletions.
Binary file modified .env
Binary file not shown.
21 changes: 21 additions & 0 deletions scripts/build_aoc_commons.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Author: Darren
#
# Utility script to build dazbo-aoc-commons and upload it to PyPI.
# Then, install the module:
# py -m pip install dazbo-aoc-commons

Set-Location C:\Users\djl\localdev\Python\Advent-of-Code\scripts
Set-Location ..\src\aoc_common\
"`nDeleting dist folder..."
if (Test-Path "dist") {
Remove-Item -LiteralPath "dist" -Recurse -Force
}

"`nRunning package build..."
py -m setup sdist

"`nUploading to PyPi..."
py ..\..\scripts\upload_to_pypi.py

"`nResetting folder."
Set-Location ..\..
25 changes: 25 additions & 0 deletions scripts/upload_to_pypi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
""" Python to upload the dist folder to PyPi """
import os
import subprocess
from dotenv import load_dotenv

def upload_to_pypi():
"""
So that we can skip having to run this command (and pass in username and pwd) separately:
twine upload dist/*
"""
load_dotenv()

# expect vars to be stored in .env or environment vars
username = os.getenv('PYPI_USERNAME')
api_key = os.getenv('PYPI_API_KEY')

if username is None or api_key is None:
raise ValueError("PYPI_USERNAME and/or PYPI_PASSWORD are not set in the .env file")

try:
subprocess.run(['twine', 'upload', 'dist/*', '-u', username, '-p', api_key], check=True)
except subprocess.CalledProcessError as e:
print(f"An error occurred during the upload: {e}")

upload_to_pypi()
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,10 @@
import re
import logging
from collections import defaultdict
import aoc_common.aoc_commons as td
import aoc_commons as ac

locations = td.get_locations(__file__)
logger = td.retrieve_console_logger(locations.script_name)
locations = ac.get_locations(__file__)
logger = ac.retrieve_console_logger(locations.script_name)
logger.setLevel(logging.INFO)

def main():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@
import time
from collections import defaultdict
import logging
import aoc_common.aoc_commons as td
import aoc_commons as ac

locations = td.get_locations(__file__)
logger = td.retrieve_console_logger(locations.script_name)
locations = ac.get_locations(__file__)
logger = ac.retrieve_console_logger(locations.script_name)
logger.setLevel(logging.INFO)

TARGET = 36000000
Expand All @@ -53,7 +53,7 @@ def main():
presents_dropped, house_num = 0, 0
while presents_dropped < TARGET:
house_num += 1
presents_dropped = sum(factor * 10 for factor in td.get_factors(house_num))
presents_dropped = sum(factor * 10 for factor in ac.get_factors(house_num))

logger.info("Part 1: House=%d, presents dropped=%d", house_num, presents_dropped)

Expand All @@ -77,7 +77,7 @@ def generate_presents_for_house(per_elf_multiplier: int, elf_visit_limit: int =
while True: # iterate for each house, yielding each time
house_num += 1
presents_dropped = 0
factors_for_house = td.get_factors(house_num)
factors_for_house = ac.get_factors(house_num)

# iterate through all the factors for this house
for factor in factors_for_house:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@
from os import path
from itertools import combinations
from player import Player
import aoc_common.aoc_commons as td
import aoc_commons as ac

locations = td.get_locations(__file__)
logger = td.retrieve_console_logger(locations.script_name)
locations = ac.get_locations(__file__)
logger = ac.retrieve_console_logger(locations.script_name)
logger.setLevel(logging.DEBUG)

BOSS_FILE = "boss_stats.txt"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@
from os import path
from typing import Iterable

import aoc_common.aoc_commons as td
import aoc_commons as ac

locations = td.get_locations(__file__)
logger = td.retrieve_console_logger(locations.script_name)
locations = ac.get_locations(__file__)
logger = ac.retrieve_console_logger(locations.script_name)
logger.setLevel(logging.INFO)
# td.setup_file_logging(logger, folder=locations.output_dir)

Expand Down Expand Up @@ -372,7 +372,7 @@ def attack_combos_generator(count_different_attacks: int) -> Iterable[str]:
i = 0
while True:
# convert i to base-n (where n is the number of attacks we can choose from)
yield td.to_base_n(i, count_different_attacks)
yield ac.to_base_n(i, count_different_attacks)
i += 1

@cache # I think there are only about 3000 different sorted attacks
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@
import time
from os import path
from typing import Iterable
import aoc_common.aoc_commons as td
import aoc_commons as ac

locations = td.get_locations(__file__)
logger = td.retrieve_console_logger(locations.script_name)
locations = ac.get_locations(__file__)
logger = ac.retrieve_console_logger(locations.script_name)
logger.setLevel(logging.INFO)
# td.setup_file_logging(logger, folder=locations.script_dir)

Expand Down
6 changes: 3 additions & 3 deletions src/AoC_2015/d23_computer/computer.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
"""
import logging
import time
import aoc_common.aoc_commons as td
import aoc_commons as ac

locations = td.get_locations(__file__)
logger = td.retrieve_console_logger(locations.script_name)
locations = ac.get_locations(__file__)
logger = ac.retrieve_console_logger(locations.script_name)
logger.setLevel(logging.INFO)

class Instructions():
Expand Down
8 changes: 4 additions & 4 deletions src/AoC_2015/d24_sleigh_balance_subset_sum/sleigh_balance.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,15 @@
import time
from math import prod
from itertools import combinations
import aoc_common.aoc_commons as td
import aoc_commons as ac

YEAR = 2015
DAY = 24

locations = td.get_locations(__file__)
logger = td.retrieve_console_logger(locations.script_name)
locations = ac.get_locations(__file__)
logger = ac.retrieve_console_logger(locations.script_name)
logger.setLevel(logging.INFO)
td.write_puzzle_input_file(YEAR, DAY, locations)
ac.write_puzzle_input_file(YEAR, DAY, locations)

def main():
# with open(locations.sample_input_file, mode="rt") as f:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@
"""
import logging
import time
import aoc_common.aoc_commons as td
import aoc_commons as ac

locations = td.get_locations(__file__)
logger = td.retrieve_console_logger(locations.script_name)
locations = ac.get_locations(__file__)
logger = ac.retrieve_console_logger(locations.script_name)
logger.setLevel(logging.DEBUG)

TARGET_ROW = 2947
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@
import logging
import time
import numpy as np
import aoc_common.aoc_commons as td
import aoc_commons as ac

locations = td.get_locations(__file__)
logger = td.retrieve_console_logger(locations.script_name)
locations = ac.get_locations(__file__)
logger = ac.retrieve_console_logger(locations.script_name)
logger.setLevel(logging.DEBUG)

TARGET_ROW = 2947
Expand Down
4 changes: 2 additions & 2 deletions src/AoC_2022/d01_calorie_counting/elf_calories.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import logging
from pathlib import Path
import time
import aoc_common.aoc_commons as td
import aoc_commons as ac

SCRIPT_NAME = Path(__file__).stem
SCRIPT_DIR = Path(__file__).parent
Expand All @@ -38,7 +38,7 @@

logger = logging.getLogger(SCRIPT_NAME)
logger.setLevel(logging.DEBUG)
logger.addHandler(td.stream_handler)
logger.addHandler(ac.stream_handler)

def main():
with open(INPUT_FILE, mode="rt") as f:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
from pathlib import Path
import time
from matplotlib import pyplot as plt
import aoc_common.aoc_commons as td
import aoc_commons as ac
from aoc_common.aoc_commons import Point

SCRIPT_NAME = Path(__file__).stem
Expand All @@ -42,7 +42,7 @@

logger = logging.getLogger(SCRIPT_NAME)
logger.setLevel(logging.DEBUG)
logger.addHandler(td.stream_handler)
logger.addHandler(ac.stream_handler)
# td.setup_file_logging(logger, OUTPUT_DIR, SCRIPT_NAME)

class Grid():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ pip install dazbo-aoc-commons

## Use

import aoc_common.aoc_commons as td
import aoc_commons as ac
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
A set of helper functions, reusable classes and attributes used by my AoC solutions
Test with tests/test_aoc_commons.py
You could import as follows:
import common.aoc_commons as td
You can import as follows:
import aoc_commons as ac
"""
# py -m pip install requests python-dotenv
from __future__ import annotations
Expand Down Expand Up @@ -111,7 +111,8 @@ class Locations:
sample_input_file: Path
input_file: Path

def get_locations(script_file):
def get_locations(script_file) -> Locations:
""" Set various paths, based on the location of the calling script. """
script_name = Path(script_file).stem # this script file, without .py
script_dir = Path(script_file).parent # the folder where this script lives
input_dir = Path(script_dir, "input")
Expand All @@ -128,51 +129,61 @@ def get_locations(script_file):
# Retrieving input data
##################################################################

def write_puzzle_input_file(year: int, day: int, locations: Locations) -> bool:
""" Use session key to obtain user's unique data for this year and day.
Only retrieve if the input file does not already exist.
Return True if retrieved; False if file exists.
"""
if os.path.exists(locations.input_file):
logger.debug("%s already exists", os.path.basename(locations.input_file))
return False

potential_paths = [
def get_envs_from_file() -> bool:
""" Look for .env files, read variables from it, and store as environment variables """
potential_paths = [ # look for .env
'.env',
os.path.join('..', '.env'),
os.path.join('..', '..', '.env'),
]

env_path = ""
for a_path in potential_paths:
if os.path.exists(a_path):
logger.info("Using .env at %s", a_path)
env_path = a_path
load_dotenv(a_path, verbose=True)
return True

logger.warning("No .env file found.")
return False

get_envs_from_file() # read env variables from a .env file, if we can find one

def write_puzzle_input_file(year: int, day: int, locations: Locations) -> bool:
""" Use session key to obtain user's unique data for this year and day.
Only retrieve if the input file does not already exist.
Return True if successful.
Requires env: AOC_SESSION_COOKIE, which can be set from the .env.
"""
if os.path.exists(locations.input_file):
logger.debug("%s already exists", os.path.basename(locations.input_file))
return True

load_dotenv(env_path)
SESSION_COOKIE = os.getenv('AOC_SESSION_COOKIE')
if SESSION_COOKIE:
session_cookie = os.getenv('AOC_SESSION_COOKIE')
if session_cookie:
logger.info('Session cookie retrieved.')
else:
logger.error('Failed to retrieve session cookie. Is it in your .env?')

url = f"https://adventofcode.com/{year}/day/{day}/input"
cookies = {"session": SESSION_COOKIE}
response = requests.get(url, cookies=cookies)
data = ""

if response.status_code == 200:
data = response.text
# Create input folder, if it doesn't exist
if not locations.input_dir.exists():
locations.input_dir.mkdir(parents=True, exist_ok=True)

url = f"https://adventofcode.com/{year}/day/{day}/input"
cookies = {"session": session_cookie}
response = requests.get(url, cookies=cookies, timeout=5)

data = ""
if response.status_code == 200:
data = response.text
else:
data = f"Failed to retrieve puzzle input: {response.status_code}"

with open(locations.input_file, 'w') as file:
logger.debug("Writing input file %s", os.path.basename(locations.input_file))
file.write(data)
return True
else:
data = f"Failed to retrieve puzzle input: {response.status_code}"

if not locations.input_dir.exists():
locations.input_dir.mkdir(parents=True, exist_ok=True)
logger.debug("Writing %s", os.path.basename(locations.input_file))
with open(locations.input_file, 'w') as file:
file.write(data)
logger.error('Failed to retrieve session cookie. Is it in your .env?')

return True
return False

#################################################################
# POINTS, VECTORS AND GRIDS
Expand Down
28 changes: 28 additions & 0 deletions src/aoc_common/setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""
Used to setup the aoc_commons package.
Make sure you have installed twine first.
py -m pip install twine
1. Delete any existing dist folder from aoc_commons_package.
2. Before updating, be sure to increment the version number.
3. Create the package. From the aoc_commons_package folder, run:
py -m setup sdist
4. Upload to PyPi:
twine upload dist/*
5. Install the package from your venv at the project folder level:
py -m pip install dazbo-aoc-commons
"""
from setuptools import setup

setup(
name='dazbo-aoc-commons',
version='0.1.10',
url='https://github.com/derailed-dash/Advent-of-Code',
author='derailed-dash',
description='A set up of helper functions and classes to assist with Advent of Code problems',
long_description=open('README.md').read(),
long_description_content_type="text/markdown",
py_modules=["aoc_commons"],
package_dir={'': '.'}, # Current directory
install_requires=[],
)
Binary file not shown.
Loading

0 comments on commit 5c38a19

Please sign in to comment.