Skip to content

Commit

Permalink
updating scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
asucrews authored Jul 5, 2024
1 parent 42e060b commit fc5f6a4
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 37 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/generate_automation_readme.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Update README
name: Update Automation README.md

on:
schedule:
Expand Down
106 changes: 70 additions & 36 deletions scripts/generate_automation_readme.py
Original file line number Diff line number Diff line change
@@ -1,49 +1,83 @@
import os
import subprocess
from datetime import datetime

def generate_readme():
base_url = "https://github.com/asucrews/ha-blueprints/blob/main/automations/"
import_base_url = "https://my.home-assistant.io/redirect/blueprint_import/?blueprint_url="
readme_content = """# Home Assistant Blueprints
Welcome to the **Home Assistant Blueprints** repository! This collection of automation blueprints is created by **asucrews** to help you set up automations for various Home Assistant setups. Each blueprint is designed to simplify and enhance your Home Assistant experience.
# Directory containing blueprint files
blueprint_directory = 'automations'
# Path to the README.md file in the automations directory
readme_path = 'automations/README.md'
# Directory name to ignore
ignore_folder = 'dev'

## Available Blueprints
"""
def get_last_commit_date(file_path):
"""Get the last commit date for a given file."""
result = subprocess.run(['git', 'log', '-1', '--format=%cd', '--', file_path],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
# Parse the date to remove time information
date = datetime.strptime(result.stdout.strip(), '%a %b %d %H:%M:%S %Y %z')
return date.strftime('%Y-%m-%d')

for root, dirs, files in os.walk("automations"):
# Skip 'dev' folders
if 'dev' in root.split(os.sep):
continue
for file in files:
if file.endswith(".yaml"):
blueprint_path = os.path.join(root, file)
blueprint_name = os.path.splitext(file)[0].replace('_', ' ').title()
blueprint_url = base_url + blueprint_path.replace("\\", "/")
import_url = import_base_url + blueprint_url
def get_blueprints(directory, ignore_folder):
"""Retrieve the list of blueprint files in the directory, ignoring specified folders."""
blueprints = []
base_url = "https://github.com/asucrews/ha-blueprints/blob/main/"
import_base_url = "https://my.home-assistant.io/redirect/blueprint_import/?blueprint_url="

readme_content += f"""
### [{blueprint_name}]({blueprint_url})
[![Import Blueprint](https://my.home-assistant.io/badges/blueprint_import.svg)]({import_url})
for root, _, files in os.walk(directory):
if ignore_folder not in root.split(os.sep):
for filename in files:
if filename.endswith('.yaml'):
filepath = os.path.join(root, filename)
name = os.path.splitext(filename)[0]
formatted_name = ' '.join(word.capitalize() for word in name.split('_'))
last_commit_date = get_last_commit_date(filepath)
blueprint_url = f"{base_url}{filepath.replace(os.sep, '/')}"
import_url = f"{import_base_url}{blueprint_url}"
blueprints.append({
"name": formatted_name,
"blueprint_url": blueprint_url,
"import_url": import_url,
"last_commit_date": last_commit_date
})
return blueprints

Description for {blueprint_name} blueprint.
---
"""
def update_readme(blueprints, readme_path):
"""Update the README.md file with the list of blueprints."""
with open(readme_path, 'r') as file:
lines = file.readlines()

readme_content += """
## Usage
# Find the section to update
start_line = None
end_line = None
for i, line in enumerate(lines):
if line.strip() == "## Available Blueprints":
start_line = i + 2 # Assume the list starts 2 lines after the header
elif start_line and line.strip() == "## Usage":
end_line = i
break

1. **Select a Blueprint:** Browse the list of available blueprints and select the one that matches your needs.
2. **Copy the YAML:** Click on the blueprint link to view the YAML file. Copy the YAML content.
3. **Import into Home Assistant:** In Home Assistant, navigate to `Configuration > Blueprints` and click on "Import Blueprint". Paste the YAML content and save.
4. **Create Automation:** Use the imported blueprint to create a new automation and configure it as needed.
if start_line is None or end_line is None:
print("Could not find the available blueprints section in README.md")
return

## Contributions
# Generate the new content
blueprint_lines = [
f"### [{blueprint['name']}]({blueprint['blueprint_url']})\n"
f"[![Import Blueprint](https://my.home-assistant.io/badges/blueprint_import.svg)]({blueprint['import_url']})\n\n"
f"Description for {blueprint['name']} blueprint. (Last updated: {blueprint['last_commit_date']})\n"
"---\n"
for blueprint in blueprints
]
new_content = lines[:start_line] + blueprint_lines + ["\n"] + lines[end_line:]

We welcome contributions to this repository! If you would like to add new blueprints or improve existing ones, please follow the guidelines provided in the [repository](https://github.com/asucrews/ha-blueprints).
"""
# Write the updated content back to the file
with open(readme_path, 'w') as file:
file.writelines(new_content)

with open("automations/README.md", "w") as f:
f.write(readme_content)
def main():
blueprints = get_blueprints(blueprint_directory, ignore_folder)
update_readme(blueprints, readme_path)
print("README.md updated successfully")

if __name__ == "__main__":
generate_readme()
main()

0 comments on commit fc5f6a4

Please sign in to comment.