Skip to content

Instantly share code, notes, and snippets.

@driazati
Last active August 6, 2020 19:30
Show Gist options
  • Save driazati/622d968b3255f92236b11a683ffe4974 to your computer and use it in GitHub Desktop.
Save driazati/622d968b3255f92236b11a683ffe4974 to your computer and use it in GitHub Desktop.
import datetime
import json
import os
import re
import subprocess
import sys
# Get all changed files
# For each one, if there is a setup.py in any directory between it and the repo
# root, change the version=.... if the version is a date
r = subprocess.run("hg status --template json", shell=True, capture_output=True)
stderr = r.stderr.decode("utf-8")
if stderr != '':
print("Skipped changing setup.py versions since stderr was not empty")
sys.exit(0)
status = r.stdout.decode("utf-8")
files = json.loads(status)
def search_for_parent_setup_py(dirname):
if dirname == "":
return None
if not os.path.exists(dirname):
return None
if "setup.py" in os.listdir(dirname):
return os.path.join(dirname, "setup.py")
return search_for_parent_setup_py(os.path.dirname(dirname))
def find_parent_setup_py(path):
# search up from path, looking for any `setup.py` files (assumes they are
# not nested)
if path.endswith("setup.py") and os.path.exists(path):
return path
if path == "":
return None
return search_for_parent_setup_py(os.path.dirname(path))
seen_files = set()
for file in files:
if file["status"] == "?":
# Ignore un-added files
continue
setup_py_path = find_parent_setup_py(file["path"])
if setup_py_path is None:
continue
if setup_py_path in seen_files:
continue
current_date = datetime.datetime.now().strftime("%Y.%m.%d")
# Only match dates of the format 20**.**.**
changed = re.subn(
"version=(\"|')20\d+\.\d+\.\d+(\"|')",
f'version="{current_date}"',
open(setup_py_path, "r").read(),
)
if changed[1] > 1:
raise RuntimeError(
"Found multiple matches for 'version=....', not doing anything"
)
if changed[1] == 1:
print(f"Changed version to {current_date} for {setup_py_path}")
seen_files.add(setup_py_path)
open(setup_py_path, "w").write(changed[0])
@driazati
Copy link
Author

driazati commented Jul 11, 2020

Installation

# run from repo root
curl -LO https://gist.github.com/driazati/622d968b3255f92236b11a683ffe4974/raw/db678cbd76312bc900e41cdddb7080b44a63f266/change_setuppy_date.py
mv change_setuppy_date.py ~/.change_setuppy_date.py
echo -e "[hooks]\nprecommit.when = python3 ~/.change_setuppy_date.py" >> .hg/hgrc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment