diff --git a/.github/PULL_REQUEST_TEMPLATE/new_icon.md b/.github/PULL_REQUEST_TEMPLATE/new_icon.md
index bcc4f6a726..7cd7fb33b5 100644
--- a/.github/PULL_REQUEST_TEMPLATE/new_icon.md
+++ b/.github/PULL_REQUEST_TEMPLATE/new_icon.md
@@ -3,12 +3,12 @@
- [ ] PR does not match another non-stale PR currently opened
- [ ] PR name matches the format *new icon: Icon name (versions separated by comma)*. More details [here](https://github.com/devicons/devicon/wiki/Overview-on-Submitting-Icons)
-- [ ] PR's base is the `develop` branch.
+- [ ] PR's base is the `master` branch.
- [ ] Your icons are inside a folder as seen [here](https://github.com/devicons/devicon/wiki/Organizing-SVGs)
- [ ] SVG matches the standards laid out [here](https://github.com/devicons/devicon/wiki/SVG-Standards)
- [ ] A new object is added in the `devicon.json` file at the correct alphabetic position as seen [here](https://github.com/devicons/devicon/wiki/Updating-%60devicon.json%60)
-
+
**This PR closes NONE**
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000000..5e285578d1
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,13 @@
+# Actions are pinned to commit SHAs (a tag can be moved to malicious code);
+# Dependabot keeps the pins and their "# vX.Y.Z" comments up to date.
+version: 2
+updates:
+ - package-ecosystem: github-actions
+ directory: /
+ schedule:
+ interval: monthly
+ groups:
+ actions:
+ patterns: ['*']
+ commit-message:
+ prefix: ci
diff --git a/.github/scripts/build_assets/api_handler.py b/.github/scripts/build_assets/api_handler.py
deleted file mode 100644
index b11c2dc675..0000000000
--- a/.github/scripts/build_assets/api_handler.py
+++ /dev/null
@@ -1,198 +0,0 @@
-import requests
-import sys
-import re
-from typing import List
-from io import FileIO
-
-
-# our base url which leads to devicon
-base_url = "https://api.github.com/repos/devicons/devicon/"
-
-def get_merged_pull_reqs_since_last_release(token, log_output: FileIO=sys.stdout):
- """
- Get all the merged pull requests since the last release.
- """
- stopPattern = r"^(r|R)elease v"
- pull_reqs = []
- found_last_release = False
- page = 1
-
- while not found_last_release:
- data = get_merged_pull_reqs(token, page, log_output)
- # assume we don't encounter it during the loop
- last_release_index = 101
-
- for i in range(len(data)):
- if re.search(stopPattern, data[i]["title"]):
- found_last_release = True
- last_release_index = i
- break
- pull_reqs.extend(data[:last_release_index])
- page += 1
-
- # should contain all the PRs since last release
- return pull_reqs
-
-
-def get_merged_pull_reqs(token, page, log_output: FileIO=sys.stdout):
- """
- Get the merged pull requests based on page. There are
- 100 results per page. See https://docs.github.com/en/rest/reference/pulls
- for more details on the parameters.
- :param token, a GitHub API token.
- :param page, the page number.
- """
- url = base_url + "pulls"
- headers = {
- "Authorization": f"token {token}"
- }
- params = {
- "accept": "application/vnd.github.v3+json",
- "state": "closed",
- "per_page": 100,
- "page": page
- }
-
- print(f"Querying the GitHub API for requests page #{page}", file=log_output)
- response = requests.get(url, headers=headers, params=params)
- if not response:
- print(f"Can't query the GitHub API. Status code is {response.status_code}. Message is {response.text}")
- sys.exit(1)
-
- closed_pull_reqs = response.json()
- return [merged_pull_req
- for merged_pull_req in closed_pull_reqs
- if merged_pull_req["merged_at"] is not None]
-
-
-def is_feature_icon(pull_req_data):
- """
- Check whether the pullData is a feature:icon PR.
- :param pull_req_data - the data on a specific pull request from GitHub.
- :return true if the pullData has a label named "feature:icon"
- """
- for label in pull_req_data["labels"]:
- if label["name"] == "feature:icon":
- return True
- return False
-
-
-def find_all_authors(pull_req_data, token):
- """
- Find all the authors of a PR based on its commits.
- :param pull_req_data - the data on a specific pull request from GitHub.
- :param token - a GitHub API token.
- """
- headers = {
- "Authorization": f"token {token}"
- }
- response = requests.get(pull_req_data["commits_url"], headers=headers)
- if not response:
- print(f"Can't query the GitHub API. Status code is {response.status_code}")
- print("Response is: ", response.text)
- return
-
- commits = response.json()
- authors = set() # want unique authors only
- for commit in commits:
- try:
- # this contains proper referenceable github name
- authors.add(commit["author"]["login"])
- except TypeError:
- # special case
- authors.add(commit["commit"]["author"]["name"])
- print(f"This URL didn't have an `author` attribute: {pull_req_data['commits_url']}")
- return ", ".join(["@" + author for author in list(authors)])
-
-
-def label_issues(token: str, issues: List[str], labels: List[str]):
- """
- Label the issues specified with the label specified.
- :param token: the GitHub API token.
- :param issues: the issue numbers (as str) that we are labelling.
- :param labels: the labels that we are labelling.
- """
- headers = {
- "Authorization": f"token {token}",
- "accept": "application/vnd.github.v3+json"
- }
- url = base_url + "issues/{}/labels"
- for issue in issues:
- body = {
- "labels": labels
- }
- response = requests.post(url.format(issue), headers=headers, json=body)
- if not response:
- raise Exception(f"Can't label the Issue provided. Issue: {issue}, labels: {labels}, API response: " + response.text)
- else:
- print(f"Successfully labelled issue {issue}")
-
-
-def close_issues(token: str, issues: List[str]):
- """
- Close issues.
- :param token: the GitHub API token.
- :param issues: the issue numbers (as str) that we are labelling.
- """
- headers = {
- "Authorization": f"token {token}",
- "accept": "application/vnd.github.v3+json"
- }
- url = base_url + "issues/{}"
- body = {
- "state": "closed"
- }
- for issue in issues:
- response = requests.patch(url.format(issue), headers=headers, json=body)
- if not response:
- raise Exception(f"Can't close Issue provided. Issue: {issue}, API response: " + response.text)
- else:
- print(f"Successfully closed issue {issue}")
-
-
-def get_issues_by_labels(token: str, labels: List[str]):
- """
- Get a list of issues based on their labels.
- :param token: the GitHub API token.
- :param labels: the labels that we are labelling.
- """
- url = base_url + "issues?per_page=100&labels={}&page={}"
- headers = {
- "Authorization": f"token {token}",
- "accept": "application/vnd.github.v3+json"
- }
- issues = []
- done = False
- page_num = 1
- while not done:
- response = requests.get(url.format(",".join(labels), page_num), headers=headers)
- if not response:
- raise Exception(f"Can't access API. Can't get issues for labels: {labels}, API response: " + response.text)
- else:
- results = response.json()
- if len(results) < 100:
- done = True # we are done
- else:
- page_num += 1 # page is full => might need to check another page
-
- # GitHub API also returns PRs for issues queries => have to check
- issues_only = [issue for issue in results if issue.get("pull_request") is None]
- issues.extend(issues_only)
-
- return issues
-
-
-def get_pr_by_number(token: str, pr_num: str):
- url = base_url + "pulls/" + pr_num
- headers = {
- "Authorization": f"token {token}"
- }
-
- print(f"Querying the GitHub API for requests")
- response = requests.get(url, headers=headers)
- if not response:
- print(f"Can't query the GitHub API. Status code is {response.status_code}. Message is {response.text}")
- sys.exit(1)
-
- pr = response.json()
- return pr
diff --git a/.github/scripts/build_assets/arg_getters.py b/.github/scripts/build_assets/arg_getters.py
index 8f82f0e6dd..6dde66c0e3 100644
--- a/.github/scripts/build_assets/arg_getters.py
+++ b/.github/scripts/build_assets/arg_getters.py
@@ -2,10 +2,10 @@
from build_assets.PathResolverAction import PathResolverAction
-def get_selenium_runner_args(has_token=True, peek_mode=False):
+def get_selenium_runner_args(has_token=True, peek_mode=False, build_since=False):
"""
Get the commandline arguments for the icomoon_peek.py and
- icomoon_build.py.
+ icomoon_build_githubless.py.
"""
parser = ArgumentParser(description="Upload svgs to Icomoon to create icon files.")
@@ -34,11 +34,16 @@ def get_selenium_runner_args(has_token=True, peek_mode=False):
action=PathResolverAction)
if peek_mode:
- parser.add_argument("pr_title",
- help="The title of the PR that we are peeking at")
+ parser.add_argument("--base",
+ help="Commit to diff against to find the PR's changes (HEAD^1 in a PR merge commit)",
+ default="HEAD^1")
if has_token != False:
parser.add_argument("token",
help="The GitHub token to access the GitHub REST API.")
+ if build_since:
+ parser.add_argument("--since",
+ help="Commit to diff against to find updated SVGs (usually the last build commit)",
+ default=None)
return parser.parse_args()
@@ -50,7 +55,7 @@ def get_check_icon_pr_args():
parser = ArgumentParser(description="Check the SVGs to ensure their attributes are correct. Run whenever a PR is opened")
parser.add_argument("pr_title",
- help="The title of the PR that we are peeking at")
+ help="The title of the PR that we are checking")
parser.add_argument("icons_folder_path",
help="The path to the icons folder",
@@ -60,29 +65,10 @@ def get_check_icon_pr_args():
help="The path to the devicon.json",
action=PathResolverAction)
- return parser.parse_args()
-
+ parser.add_argument("--base",
+ help="Commit to diff against to find the PR's changes (HEAD^1 in a PR merge commit)",
+ default="HEAD^1")
-def get_release_message_args():
- """
- Get the commandline arguments for get_release_message.py.
- """
- parser = ArgumentParser(description="Create a text containing the icons and features added since last release.")
- parser.add_argument("token",
- help="The GitHub token to access the GitHub REST API.")
return parser.parse_args()
-def get_in_develop_labeler_args():
- """
- Get the commandline arguments for in_develop_labeler.py.
- """
- parser = ArgumentParser(description="Parse the PR body to find the issue(s) we are labelling.")
- parser.add_argument("token",
- help="The GitHub token to access the GitHub REST API.",
- type=str)
-
- parser.add_argument("pr_num",
- help="The PR's number",
- type=str)
- return parser.parse_args()
diff --git a/.github/scripts/build_assets/filehandler.py b/.github/scripts/build_assets/filehandler.py
index dd54f190d3..f03db4c71a 100644
--- a/.github/scripts/build_assets/filehandler.py
+++ b/.github/scripts/build_assets/filehandler.py
@@ -236,26 +236,3 @@ def write_to_file(path: str, value):
file.write(value)
# --- NOT USED CURRENTLY ---
-def get_added_modified_svgs(files_added_json_path: str,
- files_modified_json_path: str):
- """
- Get the svgs added and modified from the files_changed_json_path.
- :param: files_added_json_path, the path to the files_added.json created by the gh-action-get-changed-files@2.1.4
- :param: files_modified_json_path, the path to the files_modified.json created by the gh-action-get-changed-files@2.1.4
- :return: a list of the svg file paths that were added/modified in this pr as Path. It will only return icons in /icons path (see https://github.com/devicons/devicon/issues/505)
- """
- files_added = get_json_file_content(files_added_json_path)
- files_modified = get_json_file_content(files_modified_json_path)
-
- svgs = []
- for file in files_added:
- path = Path(file)
- if path.suffix.lower() == ".svg" and path.as_posix().lower().startswith('icons/'):
- svgs.append(path)
-
- for file in files_modified:
- path = Path(file)
- if path.suffix.lower() == ".svg" and path.as_posix().lower().startswith('icons/'):
- svgs.append(path)
-
- return svgs
diff --git a/.github/scripts/build_assets/selenium_runner/BuildSeleniumRunner.py b/.github/scripts/build_assets/selenium_runner/BuildSeleniumRunner.py
index 4cc81564ab..bbce9f9800 100644
--- a/.github/scripts/build_assets/selenium_runner/BuildSeleniumRunner.py
+++ b/.github/scripts/build_assets/selenium_runner/BuildSeleniumRunner.py
@@ -14,12 +14,18 @@ class BuildSeleniumRunner(SeleniumRunner):
def build_icons(self, icomoon_json_path: str,
zip_path: Path, svgs: List[str], screenshot_folder: str):
self.upload_icomoon(icomoon_json_path)
- # necessary so we can take screenshot of only the
- # recently uploaded icons later
+ # Deselect all existing icons BEFORE uploading new SVGs. upload_svgs()
+ # then selects only the new icons for the "new icons only" screenshot.
+ # download_icomoon_fonts() calls select_all before opening the Generate
+ # Font page, so the full icon set is always used for font generation.
+ #
+ # Never open the Generate Font page with only some icons selected:
+ # icomoon.io assigns codepoints to the selection when the page opens, so
+ # a partial selection would give the new icons the first codepoints and
+ # shift existing glyphs. icomoon_build_githubless.py verifies this.
self.deselect_all_icons_in_top_set()
self.upload_svgs(svgs, screenshot_folder)
- self.take_icon_screenshot(screenshot_folder)
- self.download_icomoon_fonts(zip_path)
+ self.download_icomoon_fonts(zip_path, screenshot_folder)
def upload_icomoon(self, icomoon_json_path: str):
"""
@@ -90,36 +96,17 @@ def upload_svgs(self, svgs: List[str], screenshot_folder: str):
message = "BuildSeleniumRunner - Issues found when uploading SVGs:\n"
raise Exception(message + '\n'.join(err_messages))
- # take a screenshot of the svgs that were just added
- # select the latest icons
+ # Select only the newly uploaded SVGs, so the screenshot below shows just
+ # those. icomoon.io doesn't select uploaded icons by itself; new icons
+ # are the first ones in the top set.
self.switch_toolbar_option(IcomoonOptionState.SELECT)
- self.select_all_icons_in_top_set()
+ self.click_latest_icons_in_top_set(len(svgs))
+ print(f"Selected the {len(svgs)} new icon(s).", file=self.log_output)
new_svgs_path = str(Path(screenshot_folder, "new_svgs.png").resolve())
self.driver.save_screenshot(new_svgs_path)
print("Finished uploading the svgs...", file=self.log_output)
- def take_icon_screenshot(self, screenshot_folder: str):
- """
- Take the overview icon screenshot of the uploaded icons.
- :param svgs: a list of svg Paths that we'll upload to icomoon.
- :param screenshot_folder: the name of the screenshot_folder.
- """
- # take pictures
- print("Taking screenshot of the new icons...", file=self.log_output)
- self.go_to_generate_font_page()
-
- # take an overall screenshot of the icons that were just added
- # also include the glyph count
- new_icons_path = str(Path(screenshot_folder, "new_icons.png").resolve())
- main_content_xpath = "/html/body/div[4]/div[2]/div/div[1]"
- main_content = self.driver.find_element_by_xpath(main_content_xpath)
-
- # wait a bit for all the icons to load before we take a pic
- time.sleep(SeleniumRunner.MED_WAIT_IN_SEC)
- main_content.screenshot(new_icons_path)
- print("Saved screenshot of the new icons...", file=self.log_output)
-
def go_to_generate_font_page(self):
"""
Go to the generate font page. Also handles the "Deselect Icons
@@ -135,19 +122,31 @@ def go_to_generate_font_page(self):
else:
raise Exception(f"Unexpected alert found: {alert}")
- def download_icomoon_fonts(self, zip_path: Path):
+ def download_icomoon_fonts(self, zip_path: Path, screenshot_folder: str):
"""
- Download the icomoon.zip from icomoon.io. Also take a picture of
- what the icons look like.
+ Download the icomoon.zip from icomoon.io. Also take a screenshot of
+ the Generate Font page, which shows the total glyph count.
:param zip_path: the path to the zip file after it's downloaded.
+ :param screenshot_folder: the name of the screenshot_folder.
"""
print("Downloading Font files...", file=self.log_output)
if self.current_page != IcomoonPage.SELECTION:
self.go_to_page(IcomoonPage.SELECTION)
+ # select_all is required here — after deselect_all + new SVG uploads,
+ # only the new icons are selected. We must select everything before
+ # opening the Generate Font page, or the existing icons would be missing
+ # from the output and get new codepoints (see build_icons).
self.select_all_icons_in_top_set()
self.go_to_generate_font_page()
+ # wait a bit for the glyphs to render; full-page screenshot to avoid
+ # canvas taint restrictions
+ time.sleep(SeleniumRunner.MED_WAIT_IN_SEC)
+ font_glyphs_path = str(Path(screenshot_folder, "font_glyphs.png").resolve())
+ self.driver.save_screenshot(font_glyphs_path)
+ print("Saved screenshot of the Generate Font page.", file=self.log_output)
+
download_btn = WebDriverWait(self.driver, SeleniumRunner.LONG_WAIT_IN_SEC).until(
ec.presence_of_element_located((By.CSS_SELECTOR, "button.btn4 span"))
)
diff --git a/.github/scripts/build_assets/selenium_runner/PeekSeleniumRunner.py b/.github/scripts/build_assets/selenium_runner/PeekSeleniumRunner.py
index eb1fa64413..2726d7518e 100644
--- a/.github/scripts/build_assets/selenium_runner/PeekSeleniumRunner.py
+++ b/.github/scripts/build_assets/selenium_runner/PeekSeleniumRunner.py
@@ -10,13 +10,13 @@ def peek(self, svgs: List[str], screenshot_folder: str, icon_info: dict):
Upload the SVGs and peek at how Icomoon interpret its SVGs and
font versions.
:param svgs: a list of svg Paths that we'll upload to icomoon.
- :param screenshot_folder: the name of the screenshot_folder.
+ :param screenshot_folder: the name of the screenshot_folder.
:param icon_info: a dictionary containing info on an icon. Taken from the devicon.json.
:return an array of svgs with strokes as strings. These show which icon
contains stroke.
"""
- messages = self.peek_svgs(svgs, screenshot_folder)
- self.peek_icons(screenshot_folder, icon_info)
+ messages = self.peek_svgs(svgs, screenshot_folder)
+ self.peek_icons(screenshot_folder, icon_info, len(svgs))
return messages
def peek_svgs(self, svgs: List[str], screenshot_folder: str):
@@ -52,24 +52,19 @@ def peek_svgs(self, svgs: List[str], screenshot_folder: str):
self.edit_svg(screenshot_folder, i)
- # take a screenshot of the svgs that were just added
- self.select_all_icons_in_top_set()
- new_svgs_path = str(Path(screenshot_folder, "new_svgs.png").resolve())
- icon_set_xpath = "/html/body/div[4]/div[1]/div[2]/div[1]"
- icon_set = self.driver.find_element_by_xpath(icon_set_xpath)
- icon_set.screenshot(new_svgs_path)
-
print("Finished peeking the svgs...", file=self.log_output)
return svgs_with_strokes
- def peek_icons(self, screenshot_folder: str, icon_info: dict):
+ def peek_icons(self, screenshot_folder: str, icon_info: dict, num_svgs: int):
"""
Peek at the icon versions of the SVGs that were uploaded.
- :param screenshot_folder: the name of the screenshot_folder.
+ :param screenshot_folder: the name of the screenshot_folder.
:param icon_info: a dictionary containing info on an icon. Taken from the devicon.json.
+ :param num_svgs: the number of SVGs that were uploaded (used to guard against
+ extra icons from icomoon's default sets leaking into the font preview).
"""
print("Begin peeking at the icons...", file=self.log_output)
- # ensure all icons in the set is selected.
+ # Select only the newly uploaded icons in the top set before generating font.
self.select_all_icons_in_top_set()
self.go_to_page(IcomoonPage.GENERATE_FONT)
alert = self.test_for_possible_alert(self.MED_WAIT_IN_SEC)
@@ -80,43 +75,28 @@ def peek_icons(self, screenshot_folder: str, icon_info: dict):
else:
raise Exception(f"Unexpected alert found: {alert}")
- # take an overall screenshot of the icons that were just added
- # also include the glyph count
- new_icons_path = str(Path(screenshot_folder, "new_icons.png").resolve())
- main_content_xpath = "/html/body/div[4]/div[2]/div/div[1]"
- main_content = self.driver.find_element_by_xpath(main_content_xpath)
- main_content.screenshot(new_icons_path);
-
- # go in reverse order so we get the oldest icon first
+ # Collect glyph divs; reverse so screenshots are ordered oldest-first
+ # (matching the SVG upload order). Cap at num_svgs as a safety guard
+ # in case any icons from icomoon's default sets bleed into glyphSet0.
icon_divs_xpath = f'//div[@id="glyphSet0"]/div'
- icon_divs = self.driver.find_elements_by_xpath(icon_divs_xpath)
- icon_divs.reverse()
- i = 0
- for icon_div in icon_divs:
- if not icon_div.is_displayed():
- continue
+ all_icon_divs = self.driver.find_elements_by_xpath(icon_divs_xpath)
+ all_icon_divs.reverse()
+ icon_divs = [d for d in all_icon_divs if d.is_displayed()][:num_svgs]
+ for i, icon_div in enumerate(icon_divs):
icon_screenshot = str(
Path(screenshot_folder, f"new_icon_{i}.png").resolve()
)
icon_div.screenshot(icon_screenshot)
- i += 1
-
# test the colors
style = "#glyphSet0 span:first-of-type {color: " + icon_info["color"] + "}"
script = f"document.styleSheets[0].insertRule('{style}', 0)"
self.driver.execute_script(script)
- i = 0
- for icon_div in icon_divs:
- if not icon_div.is_displayed():
- continue
-
+ for i, icon_div in enumerate(icon_divs):
icon_screenshot = str(
Path(screenshot_folder, f"new_colored_icon_{i}.png").resolve()
)
icon_div.screenshot(icon_screenshot)
- i += 1
-
print("Finished peeking the icons...", file=self.log_output)
diff --git a/.github/scripts/build_assets/selenium_runner/SeleniumRunner.py b/.github/scripts/build_assets/selenium_runner/SeleniumRunner.py
index 680344c789..fc91f55c00 100644
--- a/.github/scripts/build_assets/selenium_runner/SeleniumRunner.py
+++ b/.github/scripts/build_assets/selenium_runner/SeleniumRunner.py
@@ -160,11 +160,29 @@ def set_browser_options(self, download_path: str, geckodriver_path: str,
self.driver = self.create_driver_instance(options, geckodriver_path)
self.driver.get(self.ICOMOON_URL)
- # wait until the whole web page is loaded by testing the hamburger input
- WebDriverWait(self.driver, self.LONG_WAIT_IN_SEC).until(
- ec.element_to_be_clickable((By.XPATH, "(//i[@class='icon-menu'])[2]"))
- )
- print("Accessed icomoon.io", file=self.log_output)
+
+ # wait until the whole web page is loaded
+ # Try original selector first, fall back to a more generic check
+ try:
+ WebDriverWait(self.driver, self.MED_WAIT_IN_SEC).until(
+ ec.element_to_be_clickable((By.XPATH, "(//i[@class='icon-menu'])[2]"))
+ )
+ print("Accessed icomoon.io (via icon-menu selector)", file=self.log_output)
+ except SeleniumTimeoutException:
+ print("icon-menu selector not found, trying fallback selectors...", file=self.log_output)
+ # Fallback: wait up to 90s for any file input (the core upload mechanism)
+ # icomoon.io can be slow to initialize the Angular app
+ try:
+ WebDriverWait(self.driver, 90).until(
+ ec.presence_of_element_located((By.CSS_SELECTOR, "input[type='file']"))
+ )
+ print("Accessed icomoon.io (via file input fallback)", file=self.log_output)
+ except SeleniumTimeoutException:
+ self.driver.save_screenshot("./screenshots/icomoon_load_failed.png")
+ raise Exception(
+ f"Could not load icomoon.io after 90s. Page title: '{self.driver.title}'. "
+ "The page may have changed structure or blocked headless browsing."
+ )
def create_driver_instance(self, options: Options, geckodriver_path: str):
"""
@@ -227,7 +245,10 @@ def click_hamburger_input(self):
input two times before the menu appears.
:return: None.
"""
- top_set_hamburger_input_xpath = '//*[@id="setH2"]/button[1]/i'
+ # Target the first icon-menu button inside any h1 set header.
+ # icomoon always renders the most recently uploaded (top) set first in the DOM,
+ # so [1] reliably selects it without relying on a hardcoded element ID.
+ top_set_hamburger_input_xpath = '(//h1//i[@class="icon-menu"])[1]'
hamburger_input = self.driver.find_element_by_xpath(
top_set_hamburger_input_xpath
)
diff --git a/.github/scripts/build_assets/util.py b/.github/scripts/build_assets/util.py
index e98b2a900c..9c871f229e 100644
--- a/.github/scripts/build_assets/util.py
+++ b/.github/scripts/build_assets/util.py
@@ -1,10 +1,10 @@
-import os
from pathlib import Path
import re
-from typing import List
-import platform
+from typing import List, Tuple
import sys
import traceback
+import json
+import subprocess
from io import FileIO
def exit_with_err(err: Exception, logfile: FileIO=None):
@@ -19,57 +19,107 @@ def exit_with_err(err: Exception, logfile: FileIO=None):
sys.exit(1)
-def set_env_var(key: str, value: str, delimiter: str='~'):
+def get_pr_icon_changes(devicon_json: List[dict], base: str="HEAD^1"):
"""
- Set the GitHub env variable of 'key' to 'value' using
- the method specified here:
- https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#setting-an-environment-variable
- Support both Windows and Ubuntu machines provided by GitHub Actions.
-
- :param: key, the name of the env variable.
- :param: value, the value of the env variable.
- :param: delimiter, the delimiter that you want to use
- to write to the file. Only applicable if the 'value' contains
- '\n' character aka a multiline string.
+ Find out which icons a PR touches by diffing against `base`. In a PR's
+ merge commit (what actions/checkout checks out), HEAD^1 is the target branch.
+ :param devicon_json, the devicon.json content of the PR.
+ :param base, the commit to compare against.
+ :return a dict with:
+ "svgs": {icon folder name: [SVG file names added/modified]}
+ "icon_folders": sorted names of the icons// folders with any change
+ (added, modified or deleted files)
+ "other_files": changed paths outside icons// and devicon.json
+ "json": names of devicon.json entries that were added, changed or removed
+ "existing": names of devicon.json entries that already existed at `base`
"""
- if platform.system() == "Windows":
- if "\n" in value:
- os.system(f'echo "{key}<<{delimiter}" >> %GITHUB_ENV%')
- os.system(f'echo "{value}" >> %GITHUB_ENV%')
- os.system(f'echo "{delimiter}" >> %GITHUB_ENV%')
+ # -z: NUL-separated "status, path" pairs, so unusual file names parse safely.
+ # --no-renames: a rename shows up as a delete + add, so both paths count.
+ out = subprocess.run(
+ ["git", "diff", "--name-status", "-z", "--no-renames", base, "HEAD"],
+ capture_output=True, text=True, check=True).stdout.split("\0")
+ svgs, icon_folders, other_files = {}, set(), []
+ for status, path in zip(out[0::2], out[1::2]):
+ if path == "devicon.json":
+ continue
+ parts = path.split("/") # icons//
+ if len(parts) == 3 and parts[0] == "icons":
+ icon_folders.add(parts[1])
+ if status != "D" and parts[2].endswith(".svg"):
+ svgs.setdefault(parts[1], []).append(parts[2])
else:
- os.system(f'echo "{key}={value}" >> %GITHUB_ENV%')
- elif platform.system() == "Linux":
- if "\n" in value:
- os.system(f'echo "{key}<<{delimiter}" >> $GITHUB_ENV')
- os.system(f'echo "{value}" >> $GITHUB_ENV')
- os.system(f'echo "{delimiter}" >> $GITHUB_ENV')
+ other_files.append(path)
+
+ try:
+ base_json = json.loads(subprocess.run(["git", "show", f"{base}:devicon.json"],
+ capture_output=True, text=True, check=True).stdout)
+ except subprocess.CalledProcessError:
+ base_json = []
+ base_icons = {icon["name"]: icon for icon in base_json}
+ current_names = {icon["name"] for icon in devicon_json}
+ changed_json = [icon["name"] for icon in devicon_json if base_icons.get(icon["name"]) != icon]
+ changed_json += [name for name in base_icons if name not in current_names]
+
+ return {"svgs": svgs, "icon_folders": sorted(icon_folders), "other_files": other_files,
+ "json": changed_json, "existing": set(base_icons)}
+
+
+def get_svg_versions(icon: dict, svg_files: List[str]) -> Tuple[List[str], List[str]]:
+ """
+ Get the versions of the given SVG files of an icon.
+ :param icon, the icon's devicon.json object.
+ :param svg_files, SVG file names in the icon's folder.
+ :return (versions, invalid file names). Versions are ordered like
+ versions.svg in devicon.json.
+ """
+ versions, invalid = [], []
+ for file in svg_files:
+ stem = Path(file).stem
+ version = stem[len(icon["name"]) + 1:]
+ if stem.startswith(icon["name"] + "-") and is_svg_version_valid(version):
+ versions.append(version)
else:
- os.system(f'echo "{key}={value}" >> $GITHUB_ENV')
- else:
- raise Exception("This function doesn't support this platform: " + platform.system())
+ invalid.append(file)
+
+ order = icon["versions"]["svg"]
+ versions.sort(key=lambda v: (order.index(v) if v in order else len(order), v))
+ return versions, invalid
-def find_object_added_in_pr(icons: List[dict], pr_title: str):
+pr_title_pattern = re.compile(r"^(new|update) icon:\s*([\w.-]+)\s*\(([^)]*)\)\s*$", re.I)
+def check_pr_title(pr_title: str, icon: dict, is_new: bool, versions: List[str]):
"""
- Find the icon name from the PR title.
- :param icons, a list of the font objects found in the devicon.json.
- :pr_title, the title of the PR that this workflow was called on.
- :return a dictionary with the "name"
- entry's value matching the name in the pr_title.
- :raise If no object can be found, raise an Exception.
+ Check that an icon PR's title is `new icon: ()` or
+ `update icon: ()`, matching what the PR actually does.
+ :param pr_title, the PR title.
+ :param icon, the devicon.json object of the icon whose SVGs the PR changes.
+ :param is_new, whether the icon is new (not in the target branch's devicon.json).
+ :param versions, the SVG versions the PR adds/changes.
+ :return (problems, expected title): problems is a string with the issues and
+ the expected title, or "" if the title is fine.
"""
- try:
- pattern = re.compile(r"(?<=^new icon: )\w+ (?=\(.+\))|(?<=^update icon: )\w+ (?=\(.+\))", re.I)
- icon_name_index = 0
- icon_name = pattern.findall(pr_title)[icon_name_index].lower().strip() # should only have one match
- icon = [icon for icon in icons if icon["name"] == icon_name][0]
- return icon
- except IndexError as e: # there are no match in the findall()
- print(e)
- message = "util.find_object_added_in_pr: Couldn't find an icon matching the name in the PR title.\n" \
- f"PR title is: '{pr_title}'"
- raise Exception(message)
+ kind = "new" if is_new else "update"
+ expected = f"{kind} icon: {icon['name']} ({', '.join(versions)})"
+
+ problems = []
+ match = pr_title_pattern.match(pr_title.strip())
+ if not match:
+ problems.append("it doesn't follow the format `new icon: ()` or `update icon: ()`")
+ else:
+ title_kind, title_name = match.group(1).lower(), match.group(2).lower()
+ title_versions = {v.strip().lower() for v in match.group(3).split(",") if v.strip()}
+ if title_kind != kind:
+ what = "adds a new icon" if is_new else "updates an existing icon"
+ problems.append(f"this PR {what}, so the title should start with `{kind} icon:`")
+ if title_name != icon["name"]:
+ problems.append(f"the icon name should be `{icon['name']}` (as in the folder name and `devicon.json`), not `{title_name}`")
+ if title_versions != set(versions):
+ verb = "adds" if is_new else "changes"
+ problems.append(f"the versions should be the SVGs this PR {verb}: {', '.join(versions)}")
+
+ if problems:
+ return "PR title issues:\n" + "\n".join(f"- {p}" for p in problems) + f"\n\nExpected title:\n{expected}", expected
+ return "", expected
def is_svg_in_font_attribute(svg_file_path: Path, devicon_object: dict):
diff --git a/.github/scripts/check_icon_pr.py b/.github/scripts/check_icon_pr.py
index dc5eec7712..f023fccaa1 100644
--- a/.github/scripts/check_icon_pr.py
+++ b/.github/scripts/check_icon_pr.py
@@ -1,4 +1,5 @@
from typing import List
+import json
import xml.etree.ElementTree as et
from pathlib import Path
@@ -10,57 +11,130 @@
def main():
"""
- Check the quality of the svgs IF this is an icon PR. Else, does nothing.
- If any svg error is found, create a json file called 'svg_err_messages.json'
- in the root folder that will contains the error messages.
+ Check the icons touched by this PR, found from the changed files: the
+ `devicon.json` entries and the SVGs.
+
+ An icon PR (one that changes anything in icons/) must only change one
+ icons// folder and that icon's `devicon.json` entry (or rename one
+ icon), and its title must describe it. If the title is the only thing wrong about the PR's scope, the
+ expected title is written to './expected_title.txt' so the bot can rename the
+ PR, instead of reporting it as an error.
+
+ Error messages are written to './err_messages.txt' (empty if all is well).
"""
args = arg_getters.get_check_icon_pr_args()
try:
all_icons = filehandler.get_json_file_content(args.devicon_json_path)
+ icons_by_name = {icon["name"]: icon for icon in all_icons}
+ changes = util.get_pr_icon_changes(all_icons, args.base)
+ print("Changed icon folders:", changes["icon_folders"])
+ print("Changed SVGs:", changes["svgs"])
+ print("Changed devicon.json entries:", changes["json"])
+ print("Other changed files:", changes["other_files"])
- devicon_err_msg = []
+ err_msg = []
#First check if devicon.json is sorted
if sorted(all_icons, key=lambda d: d['name']) != all_icons:
- devicon_err_msg.append(f"devicon.json is not sorted correctly.\nPlease make sure that your icon is added in the `devicon.json` file at the correct alphabetic position\nas seen here: https://github.com/devicons/devicon/wiki/Updating-%60devicon.json%60")
-
- # get only the icon object that has the name matching the pr title
- filtered_icon = util.find_object_added_in_pr(all_icons, args.pr_title)
- print("Checking devicon.json object: " + str(filtered_icon))
- devicon_err_msg.append(check_devicon_object(filtered_icon))
-
- # check the file names
- filename_err_msg = ""
- svgs = None
- try:
- svgs = filehandler.get_svgs_paths([filtered_icon], args.icons_folder_path, as_str=False)
- print("SVGs to check: ", *svgs, sep='\n')
- except ValueError as e:
- filename_err_msg = "Error found regarding filenames:\n- " + e.args[0]
-
- # check the svgs
- if svgs is None or len(svgs) == 0:
- print("No SVGs to check, ending script.")
- svg_err_msg = "Error checking SVGs: no SVGs to check. Might be caused by above issues."
- else:
- svg_err_msg = check_svgs(svgs, filtered_icon)
-
- err_msg = []
- if devicon_err_msg != []:
- err_msg.extend(devicon_err_msg)
-
- if filename_err_msg != "":
- err_msg.append(filename_err_msg)
-
- if svg_err_msg != "":
- err_msg.append(svg_err_msg)
+ err_msg.append(f"devicon.json is not sorted correctly.\nPlease make sure that your icon is added in the `devicon.json` file at the correct alphabetic position\nas seen here: https://github.com/devicons/devicon/wiki/Updating-%60devicon.json%60")
+
+ # An icon PR only touches one icons// folder and that icon's devicon.json entry
+ icon_folders = changes["icon_folders"]
+ removed = sorted(changes["existing"] - set(icons_by_name))
+ added = sorted(set(icons_by_name) - changes["existing"])
+
+ # A rename moves one icon folder to another and renames its devicon.json
+ # entry; treat it as a change to the new icon
+ renamed_from = None
+ if len(icon_folders) == 2 and len(removed) == 1 and len(added) == 1 and set(icon_folders) == {removed[0], added[0]}:
+ renamed_from = removed[0]
+ icon_folders = [added[0]]
+ print(f"Rename: {renamed_from} -> {added[0]}")
+
+ if icon_folders:
+ if changes["other_files"]:
+ err_msg.append("Icon PRs should only change files in `icons//` and `devicon.json`, but this PR also changes:\n" +
+ "\n".join(f"- {path}" for path in changes["other_files"]) +
+ "\nPlease remove these changes from this PR (open a separate PR for them if they're needed).")
+ if len(icon_folders) > 1:
+ err_msg.append(f"This PR changes several icons ({', '.join(icon_folders)}).\nPlease open a separate PR for each icon.")
+
+ expected_title = ""
+ if len(icon_folders) == 1:
+ name = icon_folders[0]
+ other_entries = [n for n in changes["json"] if n not in (name, renamed_from)]
+ if other_entries:
+ err_msg.append(f"Icon PRs should only change the `devicon.json` entry of their own icon (\"{name}\"), but this PR also changes: {', '.join(other_entries)}.")
+
+ if name in changes["svgs"] and name not in icons_by_name:
+ err_msg.append(f"`icons/{name}/` was changed, but `devicon.json` has no entry named \"{name}\".")
+ elif name in changes["svgs"]:
+ icon = icons_by_name[name]
+ versions, invalid_files = util.get_svg_versions(icon, changes["svgs"][name])
+ if invalid_files:
+ err_msg.append("These SVG file names don't match our pattern of `-(original|plain|line)(-wordmark)?.svg`:\n" +
+ "\n".join(f"- icons/{name}/{file}" for file in invalid_files))
+ if versions:
+ is_new = name not in changes["existing"] and not renamed_from
+ title_err, title = util.check_pr_title(args.pr_title, icon, is_new, versions)
+ # Only rename automatically when the PR's scope is clean
+ if title_err and not (changes["other_files"] or other_entries or invalid_files):
+ expected_title = title
+ elif title_err:
+ err_msg.append(title_err)
+
+ # Check every icon this PR touches
+ to_check = sorted(set(icon_folders) | set(changes["json"]))
+ for name in to_check:
+ if name not in icons_by_name:
+ continue
+ icon = icons_by_name[name]
+ print("Checking devicon.json object: " + str(icon))
+ devicon_err = check_devicon_object(icon)
+ if devicon_err:
+ err_msg.append(devicon_err)
+
+ try:
+ svgs = filehandler.get_svgs_paths([icon], args.icons_folder_path, as_str=False)
+ print("SVGs to check: ", *svgs, sep='\n')
+ except ValueError as e:
+ err_msg.append(f"Error found regarding filenames of \"{name}\":\n- " + e.args[0])
+ continue
+
+ if len(svgs) == 0:
+ err_msg.append(f"Error checking SVGs of \"{name}\": no SVGs to check. Might be caused by above issues.")
+ else:
+ svg_err = check_svgs(svgs, icon)
+ if svg_err:
+ err_msg.append(svg_err)
filehandler.write_to_file("./err_messages.txt", "\n\n".join(err_msg))
+ filehandler.write_to_file("./expected_title.txt", expected_title)
+ if expected_title:
+ print(f"PR title should be: {expected_title}")
+ filehandler.write_to_file("./release_label.txt", get_release_label(changes, set(icons_by_name)))
+ # Facts for the bot's "why this is a major release" comment; the comment
+ # workflow writes the actual message
+ notice = {"renamed": [renamed_from, added[0]]} if renamed_from else {"removed": removed} if removed else {}
+ filehandler.write_to_file("./release_notice.json", json.dumps(notice))
print("Task completed.")
except Exception as e:
filehandler.write_to_file("./err_messages.txt", str(e))
util.exit_with_err(e)
+def get_release_label(changes: dict, current_names: set):
+ """
+ The release label the check-bot adds to this PR: major if an icon was
+ renamed or removed (its classes disappear), minor if an icon was added or
+ updated, none (patch) otherwise.
+ """
+ if changes["existing"] - current_names:
+ return "release: major"
+ if changes["icon_folders"]:
+ return "release: minor"
+ return ""
+
+
def check_devicon_object(icon: dict):
"""
Check that the devicon object added is up to standard.
diff --git a/.github/scripts/generate_screenshot_markdown.py b/.github/scripts/generate_screenshot_markdown.py
deleted file mode 100644
index e5a516132a..0000000000
--- a/.github/scripts/generate_screenshot_markdown.py
+++ /dev/null
@@ -1,10 +0,0 @@
-import json
-import os
-
-
-if __name__ == "__main__":
- img_urls_list = json.loads(os.environ["IMG_URLS"])
- template = ""
- markdown = [template.format(img_url) for img_url in img_urls_list]
- print("\n\n".join(markdown))
-
diff --git a/.github/scripts/icomoon_build.py b/.github/scripts/icomoon_build.py
deleted file mode 100644
index 3dafe3a68e..0000000000
--- a/.github/scripts/icomoon_build.py
+++ /dev/null
@@ -1,196 +0,0 @@
-from pathlib import Path
-import sys
-from selenium.common.exceptions import TimeoutException
-import re
-import subprocess
-import json
-from typing import List, Dict
-from io import FileIO
-
-
-# pycharm complains that build_assets is an unresolved ref
-# don't worry about it, the script still runs
-from build_assets.selenium_runner.BuildSeleniumRunner import BuildSeleniumRunner
-from build_assets import filehandler, arg_getters, util, api_handler
-
-
-def main():
- """
- Build the icons using Icomoon. Also optimize the svgs.
- """
- runner = None
- logfile = open("log.txt", "w")
- try:
- args = arg_getters.get_selenium_runner_args()
- new_icons = get_icons_for_building(args.icomoon_json_path, args.devicon_json_path, args.token, logfile)
- if len(new_icons) == 0:
- sys.exit("No files need to be uploaded. Ending script...")
-
- print(f"There are {len(new_icons)} icons to be build. Here are they:", *new_icons, sep = "\n", file=logfile)
-
- print("Begin optimizing files...", file=logfile)
- optimize_svgs(new_icons, args.icons_folder_path, logfile=logfile)
-
- print("Updating the icomoon json...", file=logfile)
- update_icomoon_json(new_icons, args.icomoon_json_path, logfile)
-
- print("Start the building icons process...", file=logfile)
- icon_svgs = filehandler.get_svgs_paths(
- new_icons, args.icons_folder_path, icon_versions_only=True)
- zip_name = "devicon-v1.0.zip"
- zip_path = Path(args.download_path, zip_name)
- screenshot_folder = filehandler.create_screenshot_folder("./")
-
- runner = BuildSeleniumRunner(args.download_path,
- args.geckodriver_path, args.headless, log_output=logfile)
- runner.build_icons(args.icomoon_json_path, zip_path,
- icon_svgs, screenshot_folder)
-
- filehandler.extract_files(str(zip_path), args.download_path, logfile)
- filehandler.rename_extracted_files(args.download_path, logfile)
-
- print("Creating the release message by querying the GitHub API...", file=logfile)
- get_release_message(args.token, logfile)
-
- print("Closing issues with the `in-develop` label.", file=logfile)
- issues = api_handler.get_issues_by_labels(args.token, ["in-develop"])
- issue_nums = [issue_num["number"] for issue_num in issues]
- api_handler.close_issues(args.token, issue_nums)
-
- print("Task completed.", file=logfile)
- except TimeoutException as e:
- util.exit_with_err(Exception("Selenium Time Out Error: \n" + str(e)), logfile)
- except Exception as e:
- util.exit_with_err(e, logfile)
- finally:
- print("Exiting", file=logfile)
- if runner is not None:
- runner.close()
- logfile.close()
-
-
-def get_icons_for_building(icomoon_json_path: str, devicon_json_path: str, token: str, logfile: FileIO):
- """
- Get the icons for building.
- :param icomoon_json_path - the path to the `icomoon.json`.
- :param devicon_json_path - the path to the `devicon.json`.
- :param token - the token to access the GitHub API.
- :param logfile.
- :return a list of dict containing info on the icons. These are
- from the `devicon.json`.
- """
- devicon_json = filehandler.get_json_file_content(devicon_json_path)
- pull_reqs = api_handler.get_merged_pull_reqs_since_last_release(token, logfile)
- new_icons = []
-
- for pull_req in pull_reqs:
- if api_handler.is_feature_icon(pull_req):
- filtered_icon = util.find_object_added_in_pr(devicon_json, pull_req["title"])
- if filtered_icon not in new_icons:
- new_icons.append(filtered_icon)
-
- # get any icons that might not have been found by the API
- # sometimes happen due to the PR being opened before the latest build release
- new_icons_from_devicon_json = filehandler.find_new_icons_in_devicon_json(
- devicon_json_path, icomoon_json_path)
-
- for icon in new_icons_from_devicon_json:
- if icon not in new_icons:
- new_icons.append(icon)
-
- return new_icons
-
-
-def optimize_svgs(new_icons: List[str], icons_folder_path: str, logfile: FileIO):
- """
- Optimize the newly added svgs. This is done in batches
- since the command line has a limit on characters allowed.
- :param new_icons - the new icons that need to be optimized.
- :param icons_folder_path - the path to the /icons folder.
- :param logfile - the file obj to store logging info in.
- """
- svgs = filehandler.get_svgs_paths(new_icons, icons_folder_path, icon_versions_only=False)
- start = 0
- step = 10
- for i in range(start, len(svgs), step):
- batch = svgs[i:i + step]
- print(f"Optimizing these files\n{batch}", file=logfile)
- subprocess.run(["npm", "run", "optimize-svg", "--", f"--svgFiles={json.dumps(batch)}"], shell=True)
-
-
-def update_icomoon_json(new_icons: List[str], icomoon_json_path: str, logfile: FileIO):
- """
- Update the `icomoon.json` if it contains any icons
- that needed to be updated. This will remove the icons
- from the `icomoon.json` so the build script will reupload
- it later.
- """
- icomoon_json = filehandler.get_json_file_content(icomoon_json_path)
- cur_len = len(icomoon_json["icons"])
- messages = []
-
- wrapper_function = lambda icomoon_icon : find_icomoon_icon_not_in_new_icons(
- icomoon_icon, new_icons, messages)
- icons_to_keep = filter(wrapper_function, icomoon_json["icons"])
- icomoon_json["icons"] = list(icons_to_keep)
-
- new_len = len(icomoon_json["icons"])
- print(f"Update completed. Removed {cur_len - new_len} icons:", *messages, sep='\n', file=logfile)
- filehandler.write_to_file(icomoon_json_path, json.dumps(icomoon_json))
-
-
-def find_icomoon_icon_not_in_new_icons(icomoon_icon: Dict, new_icons: List, messages: List):
- """
- Find all the icomoon icons that are not listed in the new icons.
- This also add logging for which icons were removed.
- :param icomoon_icon - a dict object from the icomoon.json's `icons` attribute.
- :param new_icons - a list of new icons. Each element is an object from the `devicon.json`.
- :param messages - an empty list where the function can attach logging on which
- icon were removed.
- """
- for new_icon in new_icons:
- pattern = re.compile(f"^{new_icon['name']}-")
- if pattern.search(icomoon_icon["properties"]["name"]):
- message = f"-'{icomoon_icon['properties']['name']}' cause it matches '{new_icon['name']}'"
- messages.append(message)
- return False
- return True
-
-
-def get_release_message(token, logfile: FileIO):
- """
- Get the release message for the latest build and write
- the result in a file.
- :param token: the GitHub API token to access the API.
- """
- # fetch first page by default
- data = api_handler.get_merged_pull_reqs_since_last_release(token, logfile)
- newIcons = []
- features = []
-
- print("Parsing through the pull requests...", file=logfile)
- for pullData in data:
- authors = api_handler.find_all_authors(pullData, token)
- markdown = f"- [{pullData['title']}]({pullData['html_url']}) by {authors}."
-
- if api_handler.is_feature_icon(pullData):
- newIcons.append(markdown)
- else:
- features.append(markdown)
-
- print("Constructing message...", file=logfile)
- thankYou = "A huge thanks to all our maintainers and contributors for making this release possible!"
- iconTitle = f"**{len(newIcons)} New Icons**"
- featureTitle = f"**{len(features)} New Features**"
- finalString = "{0}\n\n {1}\n{2}\n\n {3}\n{4}".format(thankYou,
- iconTitle, "\n".join(newIcons),
- featureTitle, "\n".join(features))
-
- print("--------------Here is the build message--------------\n", finalString, file=logfile)
- release_message_path = "./release_message.txt"
- filehandler.write_to_file(release_message_path, finalString)
- print("Script finished", file=logfile)
-
-
-if __name__ == "__main__":
- main()
diff --git a/.github/scripts/icomoon_build_githubless.py b/.github/scripts/icomoon_build_githubless.py
index 92fb1aba94..12127aecad 100644
--- a/.github/scripts/icomoon_build_githubless.py
+++ b/.github/scripts/icomoon_build_githubless.py
@@ -1,6 +1,4 @@
from pathlib import Path
-import sys
-from selenium.common.exceptions import TimeoutException
import re
import subprocess
import json
@@ -9,23 +7,33 @@
# pycharm complains that build_assets is an unresolved ref
# don't worry about it, the script still runs
-from build_assets.selenium_runner.BuildSeleniumRunner import BuildSeleniumRunner
-from build_assets import filehandler, arg_getters, util, api_handler
+from build_assets import filehandler, arg_getters, util
def main():
"""
Build the icons using Icomoon. Also optimize the svgs.
"""
+ # Imported here so the build workflow can call get_icons_for_building with
+ # a plain python3, before Selenium is installed
+ from selenium.common.exceptions import TimeoutException
+ from build_assets.selenium_runner.BuildSeleniumRunner import BuildSeleniumRunner
+
runner = None
logfile = open("log.txt", "w")
try:
- args = arg_getters.get_selenium_runner_args(has_token=False)
- new_icons = get_icons_for_building(args.icomoon_json_path, args.devicon_json_path, logfile)
+ args = arg_getters.get_selenium_runner_args(has_token=False, build_since=True)
+ new_icons = get_icons_for_building(args.icomoon_json_path, args.devicon_json_path, args.since, logfile)
if len(new_icons) == 0:
- sys.exit("No files need to be uploaded. Ending script...")
+ msg = "No new or changed font icons — nothing to build."
+ print(msg, file=logfile)
+ print(msg)
+ return
print(f"There are {len(new_icons)} icons to be build. Here are they:", *new_icons, sep = "\n", file=logfile)
+ # Snapshot the codepoints so we can verify icomoon.io kept them
+ codes_before = get_glyph_codes(args.icomoon_json_path)
+
print("Begin optimizing files...", file=logfile)
optimize_svgs(new_icons, args.icons_folder_path, logfile=logfile)
@@ -50,6 +58,9 @@ def main():
print("Renaming extracted files...", file=logfile)
filehandler.rename_extracted_files(args.download_path, logfile)
+ print("Verifying codepoints...", file=logfile)
+ verify_glyph_codes(codes_before, get_glyph_codes(args.icomoon_json_path), new_icons, logfile)
+
print("Task completed!", file=logfile)
except TimeoutException as e:
util.exit_with_err(Exception("Selenium Time Out Error: \n" + str(e)), logfile)
@@ -62,28 +73,117 @@ def main():
logfile.close()
-def get_icons_for_building(icomoon_json_path: str, devicon_json_path: str, logfile: FileIO):
+GLYPH_NAME_PATTERN = re.compile(r"^(.+)-((?:original|plain|line)(?:-wordmark)?)$")
+
+
+def get_glyph_codes(icomoon_json_path: str) -> Dict[str, int]:
+ """
+ Get the codepoint of every glyph in the `icomoon.json`.
+ :return a dict of glyph name -> codepoint.
+ """
+ icomoon_json = filehandler.get_json_file_content(icomoon_json_path)
+ return {glyph["properties"]["name"]: glyph["properties"]["code"] for glyph in icomoon_json["icons"]}
+
+
+def verify_glyph_codes(codes_before: Dict[str, int], codes_after: Dict[str, int], built_icons: List[dict], logfile: FileIO):
"""
- Get the icons for building.
+ Make sure icomoon.io kept the codepoints of every glyph that wasn't rebuilt,
+ so the icons people already use keep their codepoints. Rebuilt glyphs are
+ re-uploaded and get their codepoint from icomoon.io; those are only logged.
+ :param codes_before - glyph name -> codepoint before the build.
+ :param codes_after - glyph name -> codepoint in the downloaded icomoon.json.
+ :param built_icons - the devicon.json objects of the icons that were (re)built.
+ :raise Exception if a glyph that wasn't rebuilt changed or disappeared, or
+ two glyphs share a codepoint.
+ """
+ built_names = {icon["name"] for icon in built_icons}
+ def is_built(glyph_name):
+ match = GLYPH_NAME_PATTERN.match(glyph_name)
+ return match is not None and match.group(1) in built_names
+
+ problems = []
+ for name, code in codes_before.items():
+ if is_built(name):
+ continue
+ if name not in codes_after:
+ problems.append(f"- {name}: missing from the new font")
+ elif codes_after[name] != code:
+ problems.append(f"- {name}: codepoint changed {code:x} -> {codes_after[name]:x}")
+
+ glyphs_by_code = {}
+ for name, code in codes_after.items():
+ glyphs_by_code.setdefault(code, []).append(name)
+ for code, names in glyphs_by_code.items():
+ if len(names) > 1:
+ problems.append(f"- codepoint {code:x} is used by several glyphs: {', '.join(names)}")
+
+ for name in sorted(n for n in codes_after if is_built(n)):
+ before = f"{codes_before[name]:x}" if name in codes_before else "new"
+ print(f"Rebuilt glyph {name}: codepoint {before} -> {codes_after[name]:x}", file=logfile)
+
+ if problems:
+ raise Exception(f"icomoon.io changed existing glyphs ({len(problems)} problems), not committing this build:\n" + "\n".join(problems))
+ kept = sum(1 for name in codes_before if not is_built(name))
+ print(f"Codepoints verified: all {kept} existing glyphs that weren't rebuilt kept theirs.", file=logfile)
+
+
+def get_icons_for_building(icomoon_json_path: str, devicon_json_path: str, since: str, logfile: FileIO):
+ """
+ Get the icons whose font glyphs need to be (re)built. An icon is built when:
+ - its glyphs in `icomoon.json` don't match its font versions in `devicon.json`
+ (new icon, or font versions added/removed/renamed), or
+ - one of its font SVGs changed since the `since` commit (updated icon).
+ Font versions that are aliases are ignored, since the CSS provides those.
:param icomoon_json_path - the path to the `icomoon.json`.
:param devicon_json_path - the path to the `devicon.json`.
+ :param since - commit to diff against for changed SVGs. None to skip that check.
:param logfile.
- :return a list of dict containing info on the icons. These are
+ :return a list of dict containing info on the icons. These are
from the `devicon.json`.
"""
+ devicon_json = filehandler.get_json_file_content(devicon_json_path)
+ icomoon_json = filehandler.get_json_file_content(icomoon_json_path)
+
+ glyphs_by_icon = {}
+ for glyph in icomoon_json["icons"]:
+ match = GLYPH_NAME_PATTERN.match(glyph["properties"]["name"])
+ if match:
+ glyphs_by_icon.setdefault(match.group(1), set()).add(match.group(2))
+
+ changed_svgs = get_changed_svgs(since, logfile) if since else set()
- new_icons = []
+ icons_to_build = []
+ for icon in devicon_json:
+ aliases = {alias["alias"] for alias in icon["aliases"]}
+ expected = {v for v in icon["versions"]["font"] if v not in aliases}
+ if not expected:
+ continue
- # get any icons that might not have been found by the API
- # sometimes happen due to the PR being opened before the latest build release
- new_icons_from_devicon_json = filehandler.find_new_icons_in_devicon_json(
- devicon_json_path, icomoon_json_path)
+ actual = glyphs_by_icon.get(icon["name"], set())
+ if not actual:
+ reason = "new icon"
+ elif expected != actual:
+ reason = f"font versions changed (devicon.json: {sorted(expected)}, icomoon.json: {sorted(actual)})"
+ elif any(f"icons/{icon['name']}/{icon['name']}-{v}.svg" in changed_svgs for v in expected):
+ reason = "font SVG updated"
+ else:
+ continue
- for icon in new_icons_from_devicon_json:
- if icon not in new_icons:
- new_icons.append(icon)
+ print(f"{icon['name']}: {reason}", file=logfile)
+ icons_to_build.append(icon)
- return new_icons
+ return icons_to_build
+
+
+def get_changed_svgs(since: str, logfile: FileIO):
+ """
+ Get the SVG paths (relative to the repo root) changed between `since` and HEAD.
+ """
+ result = subprocess.run(["git", "diff", "--name-only", since, "HEAD", "--", "icons"],
+ capture_output=True, text=True, check=True)
+ changed = {path for path in result.stdout.splitlines() if path.endswith(".svg")}
+ print(f"{len(changed)} SVGs changed since {since}", file=logfile)
+ return changed
def optimize_svgs(new_icons: List[str], icons_folder_path: str, logfile: FileIO):
@@ -133,9 +233,10 @@ def find_icomoon_icon_not_in_new_icons(icomoon_icon: Dict, new_icons: List, mess
:param messages - an empty list where the function can attach logging on which
icon were removed.
"""
+ match = GLYPH_NAME_PATTERN.match(icomoon_icon["properties"]["name"])
for new_icon in new_icons:
- pattern = re.compile(f"^{new_icon['name']}-")
- if pattern.search(icomoon_icon["properties"]["name"]):
+ # exact name match, so rebuilding "foo" never removes "foo-bar" glyphs
+ if match and match.group(1) == new_icon["name"]:
message = f"-'{icomoon_icon['properties']['name']}' cause it matches '{new_icon['name']}'"
messages.append(message)
return False
diff --git a/.github/scripts/icomoon_peek.py b/.github/scripts/icomoon_peek.py
index 7d66d1117b..34436cdce8 100644
--- a/.github/scripts/icomoon_peek.py
+++ b/.github/scripts/icomoon_peek.py
@@ -8,8 +8,20 @@ def main():
args = arg_getters.get_selenium_runner_args(has_token=False, peek_mode=True)
all_icons = filehandler.get_json_file_content(args.devicon_json_path)
- # get only the icon object that has the name matching the pr title
- filtered_icon = util.find_object_added_in_pr(all_icons, args.pr_title)
+ # peek at the icon whose SVGs this PR adds/changes
+ changes = util.get_pr_icon_changes(all_icons, args.base)
+ svg_icons = sorted(changes["svgs"])
+ if len(svg_icons) == 0:
+ # e.g. a devicon.json-only change: nothing to peek, no screenshots
+ print("No icon SVGs changed in this PR, nothing to peek.")
+ filehandler.write_to_file("./err_messages.txt", "")
+ return
+ if len(svg_icons) > 1:
+ raise Exception(f"This PR changes the SVGs of several icons ({', '.join(svg_icons)}). Please open a separate PR for each icon.")
+ filtered_icon = next((icon for icon in all_icons if icon["name"] == svg_icons[0]), None)
+ if filtered_icon is None:
+ raise Exception(f"`icons/{svg_icons[0]}/` was changed, but `devicon.json` has no entry named \"{svg_icons[0]}\".")
+
svgs = filehandler.get_svgs_paths([filtered_icon], args.icons_folder_path, True)
screenshot_folder = filehandler.create_screenshot_folder("./")
diff --git a/.github/scripts/in_develop_labeler.py b/.github/scripts/in_develop_labeler.py
deleted file mode 100644
index 3d329c9942..0000000000
--- a/.github/scripts/in_develop_labeler.py
+++ /dev/null
@@ -1,24 +0,0 @@
-import re
-from build_assets import arg_getters, api_handler
-
-def main():
- args = arg_getters.get_in_develop_labeler_args()
- try:
- #get pr body
- pr_body = api_handler.get_pr_by_number(args.token, args.pr_num)["body"]
-
- # find the issue closing line
- print(pr_body.split("\n"))
- issue_line = [line for line in pr_body.split("\n") if line.startswith("**This PR closes")][0]
-
- print("Issue Line is " + issue_line)
- issue_pattern = re.compile(r"\d+")
- issues_numbers = issue_pattern.findall(issue_line)
- print("Labelling issues: " + str(issues_numbers))
- api_handler.label_issues(args.token, issues_numbers, ["in-develop"])
- except IndexError: # if can't find the issue line
- print("The PR body doesn't contain `**This PR closes` keywords. Ending workflow.")
- return
-
-if __name__ == "__main__":
- main()
diff --git a/.github/scripts/requirements.txt b/.github/scripts/requirements.txt
index dc367f599f..f2865f5dfd 100644
--- a/.github/scripts/requirements.txt
+++ b/.github/scripts/requirements.txt
@@ -1,2 +1 @@
selenium==4.1.0
-requests==2.34.2
diff --git a/.github/workflows/build_icons.yml b/.github/workflows/build_icons.yml
deleted file mode 100644
index ced81ade8d..0000000000
--- a/.github/workflows/build_icons.yml
+++ /dev/null
@@ -1,97 +0,0 @@
-name: Build Icons
-on: workflow_dispatch
-jobs:
- build:
- name: Get Fonts From Icomoon
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v5
- - uses: actions/setup-python@v5
- with:
- python-version: '3.10'
-
- - name: Install dependencies (python, pip, npm)
- run: |
- python -m pip install --upgrade pip
- pip install -r ./.github/scripts/requirements.txt
- npm install
-
- - name: Executing build and create fonts via icomoon
- shell: bash
- env:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- run: >
- python ./.github/scripts/icomoon_build.py
- ./.github/scripts/build_assets/geckodriver-v0.32.2-linux64/geckodriver ./icomoon.json
- ./devicon.json ./icons ./ $GITHUB_TOKEN --headless
-
- - name: Upload geckodriver.log for debugging purposes
- uses: actions/upload-artifact@v4
- if: failure()
- with:
- name: geckodriver-log
- path: ./geckodriver.log
-
- - name: Upload log file for debugging purposes
- uses: actions/upload-artifact@v4
- if: always()
- with:
- name: logfile
- path: ./log.txt
-
- - name: Build devicon.min.css
- if: success()
- run: npm run build-css
-
- # - name: Upload screenshot of the newly made icons
- # id: imgur_step
- # uses: devicons/public-upload-to-imgur@v2.2.2
- # if: success()
- # with:
- # # will have "new_icons.png" and "new_svgs.png"
- # # in that order (cause sorted alphabetically)
- # path: ./screenshots/*.png
- # client_id: ${{secrets.IMGUR_CLIENT_ID}}
-
- - name: Get the release message from file
- id: release_message_step
- uses: juliangruber/read-file-action@v1.0.0
- with:
- # taken from icomoon_build.py's get_release_message()
- path: ./release_message.txt
-
- - name: Create Pull Request
- if: success()
- uses: peter-evans/create-pull-request@v7
- env:
- MESSAGE: |
- Hello,
-
- I'm Devicon's Build Bot and I just built some new font files and devicon.min.css file.
-
- The devicon.min.css file contains:
- -The icon content
- -The aliases
- -The colored classes
-
- I also compiled a list of new features and icons that were added since last release.
- ```
- {0}
- ```
-
- More information can be found in the GitHub Action logs for this workflow.
-
- Adios,
- Build Bot :sunglasses:
- with:
- branch: 'bot/build-result'
- commit-message: 'Built new icons, icomoon.json and devicon.css'
- title: 'bot:build new icons, icomoon.json and devicon.css'
- body: >
- ${{
- format(
- env.MESSAGE,
- steps.release_message_step.outputs.content
- )
- }}
- delete-branch: true
diff --git a/.github/workflows/build_weekly.yml b/.github/workflows/build_weekly.yml
new file mode 100644
index 0000000000..325791714b
--- /dev/null
+++ b/.github/workflows/build_weekly.yml
@@ -0,0 +1,464 @@
+name: Weekly Build and Release
+# Runs every Monday at 2 AM UTC, or manually via workflow_dispatch (same steps).
+#
+# build - (re)builds font glyphs for new/changed icons and the CSS, commits
+# them to master as "build: ...". Decides whether there's anything
+# to release.
+# release - waits for approval on the "production" environment, then bumps
+# the version, tags and creates the GitHub release.
+# publish - publishes the release to npm.
+
+on:
+ schedule:
+ - cron: '0 2 * * 1' # 2 AM UTC every Monday
+ workflow_dispatch:
+ inputs:
+ bump:
+ description: 'Version bump level (auto = derive from PR labels)'
+ required: false
+ default: 'auto'
+ type: choice
+ options:
+ - auto
+ - patch
+ - minor
+ - major
+
+permissions:
+ contents: write
+ issues: write
+ pull-requests: read # PR labels for the release check and notes
+
+# Never run two builds/releases at once — they'd race on icomoon.json and tags
+concurrency:
+ group: build-and-release
+ cancel-in-progress: false
+
+jobs:
+ build:
+ name: Build Fonts and CSS
+ runs-on: ubuntu-24.04
+ outputs:
+ should_release: ${{ steps.release-check.outputs.should_release }}
+
+ steps:
+ # Token for pushing to master. See "Pushing to a protected master" below.
+ - name: Get bot token
+ id: bot-token
+ if: vars.BOT_APP_ID != ''
+ uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0
+ with:
+ app-id: ${{ vars.BOT_APP_ID }}
+ private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }}
+ # Only what this workflow needs; fails here if the installation lacks it
+ permission-contents: write
+
+ - name: Checkout master
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ token: ${{ steps.bot-token.outputs.token || secrets.GITHUB_TOKEN }}
+ fetch-depth: 0
+
+ - name: Check for icon changes since last build
+ id: check-changes
+ run: |
+ # Find the last commit whose message starts with "build:"
+ SINCE=$(git log --format="%H %s" | awk '/^[a-f0-9]+ build:/ { print $1; exit }')
+
+ if [ -z "$SINCE" ]; then
+ echo "No previous build commit found - falling back to last release tag"
+ SINCE=$(git describe --tags --abbrev=0 --match 'v[0-9]*' 2>/dev/null || true)
+ fi
+ if [ -z "$SINCE" ]; then
+ echo "No release tag found either - checking all history"
+ SINCE=$(git rev-list --max-parents=0 HEAD | tail -1)
+ fi
+ echo "Building changes since $SINCE"
+ echo "since=$SINCE" >> $GITHUB_OUTPUT
+
+ if git diff --quiet "$SINCE" HEAD -- icons/ devicon.json; then
+ echo "No icon changes since last build — skipping build"
+ echo "has_changes=false" >> $GITHUB_OUTPUT
+ exit 0
+ fi
+ echo "has_changes=true" >> $GITHUB_OUTPUT
+
+ # Which icons need new glyphs? Pure JSON/git, so the runner's own
+ # python3 can answer before the slow icomoon setup (pip, Firefox).
+ # Changes that need no glyphs (tags, colours, aliases) only rebuild the
+ # CSS; otherwise the "last build" marker wouldn't move and every later
+ # run would install everything before finding nothing to build.
+ COUNT=$(python3 -c 'import sys; sys.path.insert(0, ".github/scripts"); from icomoon_build_githubless import get_icons_for_building; print(len(get_icons_for_building("icomoon.json", "devicon.json", sys.argv[1], sys.stderr)))' "$SINCE")
+ echo "$COUNT icons need new glyphs"
+ echo "needs_glyphs=$([ "$COUNT" -gt 0 ] && echo true || echo false)" >> $GITHUB_OUTPUT
+
+ - name: Setup Python 3.12
+ if: steps.check-changes.outputs.needs_glyphs == 'true'
+ uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
+ with:
+ python-version: '3.12'
+
+ - name: Setup Node.js
+ if: steps.check-changes.outputs.has_changes == 'true'
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: '24'
+
+ - name: Install Python dependencies
+ if: steps.check-changes.outputs.needs_glyphs == 'true'
+ run: |
+ python -m pip install --upgrade pip
+ pip install -r ./.github/scripts/requirements.txt
+
+ - name: Install Node dependencies
+ if: steps.check-changes.outputs.has_changes == 'true'
+ run: npm install
+
+ - name: Install Firefox
+ if: steps.check-changes.outputs.needs_glyphs == 'true'
+ uses: browser-actions/setup-firefox@0bc507ddf224827e3b1af68e014d5e42ab93e795 # v1.7.2
+
+ - name: Make geckodriver executable
+ if: steps.check-changes.outputs.needs_glyphs == 'true'
+ run: chmod +x ./.github/scripts/build_assets/geckodriver-v0.32.2-linux64/geckodriver
+
+ # Rebuilds icons whose glyphs don't match devicon.json (new icons, changed
+ # font versions) or whose font SVGs changed since the last build. Exits
+ # successfully without touching anything if there's nothing to build.
+ # icomoon.io often fails for a while (timeouts, a slow page), so a failed
+ # build is retried twice, a minute apart, from a clean tree. Each failed
+ # attempt's log is kept as log-attempt-N.txt.
+ - name: Run Icomoon build
+ if: steps.check-changes.outputs.needs_glyphs == 'true'
+ id: build
+ continue-on-error: true
+ env:
+ SINCE: ${{ steps.check-changes.outputs.since }}
+ run: |
+ for attempt in 1 2 3; do
+ if python ./.github/scripts/icomoon_build_githubless.py \
+ ./.github/scripts/build_assets/geckodriver-v0.32.2-linux64/geckodriver \
+ ./icomoon.json \
+ ./devicon.json \
+ ./icons \
+ ./ \
+ --headless \
+ --since "$SINCE"; then
+ exit 0
+ fi
+ echo "::warning::Icomoon build attempt $attempt of 3 failed"
+ cp log.txt "log-attempt-$attempt.txt" || true
+ [ "$attempt" = 3 ] && exit 1
+ # Undo the failed attempt (optimized SVGs, icomoon.json, downloads).
+ # Ignored files (node_modules, logs, screenshots) stay.
+ git checkout -- .
+ git clean -fdq
+ sleep 60
+ done
+
+ # Always rebuilt when icons/devicon.json changed: aliases and colors in
+ # devicon.json end up in devicon.min.css even when no glyphs change.
+ - name: Build CSS
+ if: steps.check-changes.outputs.has_changes == 'true' && steps.build.outcome != 'failure'
+ id: build-css
+ continue-on-error: true
+ run: npm run build-css
+
+ - name: Upload build log
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ if: always() && steps.check-changes.outputs.needs_glyphs == 'true'
+ with:
+ name: build-log
+ path: ./log*.txt
+
+ - name: Upload screenshots
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ if: always() && steps.check-changes.outputs.needs_glyphs == 'true'
+ with:
+ name: build-screenshots
+ path: ./screenshots/
+ if-no-files-found: ignore
+
+ - name: Upload geckodriver log on failure
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ if: failure()
+ with:
+ name: geckodriver-log
+ path: ./geckodriver.log
+
+ # Opens a "build-failed" issue. Set the repository variable
+ # BUILD_FAILURE_MENTION (e.g. "@devicons/devicon__maintain") to notify
+ # maintainers in it.
+ - name: Handle build failure
+ if: steps.check-changes.outputs.has_changes == 'true' && (steps.build.outcome == 'failure' || steps.build-css.outcome == 'failure')
+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
+ env:
+ GLYPHS_FAILED: ${{ steps.build.outcome == 'failure' }}
+ MENTION: ${{ vars.BUILD_FAILURE_MENTION }}
+ with:
+ script: |
+ const today = new Date().toISOString().split('T')[0];
+ const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
+
+ // Ensure the build-failed label exists
+ try {
+ await github.rest.issues.getLabel({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ name: 'build-failed'
+ });
+ } catch (e) {
+ await github.rest.issues.createLabel({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ name: 'build-failed',
+ color: 'd73a4a',
+ description: 'Weekly build failed'
+ });
+ }
+
+ await github.rest.issues.create({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ title: `Weekly build failed - ${today}`,
+ body: `The weekly Icomoon build failed${process.env.GLYPHS_FAILED === 'true' ? ' 3 times in a row' : ''}.\n\n**Workflow run:** ${runUrl}\n\nPlease investigate and re-run manually once fixed using the \`workflow_dispatch\` trigger on \`build_weekly.yml\`.${process.env.MENTION ? `\n\ncc ${process.env.MENTION}` : ''}`,
+ labels: ['build-failed']
+ });
+
+ core.setFailed('Weekly build failed - issue created');
+
+ - name: Commit build artifacts
+ if: steps.check-changes.outputs.has_changes == 'true' && steps.build.outcome != 'failure' && steps.build-css.outcome == 'success'
+ run: |
+ git config --local user.email "github-actions[bot]@users.noreply.github.com"
+ git config --local user.name "github-actions[bot]"
+ git add -A
+ if ! git diff --staged --quiet; then
+ git commit -m "build: generate font files and CSS"
+ # master may have moved while the build ran
+ git pull --rebase origin master
+ git push origin HEAD:master
+ else
+ echo "No build artifacts changed"
+ fi
+
+ # Release when anything users get (via npm / jsDelivr) changed since the
+ # last release tag (SVGs, devicon.json, CSS or fonts), when a PR merged
+ # since then carries a "release: ..." label (e.g. a website or workflow
+ # feature), or when a manual run picks a bump level. Decided here rather
+ # than in the release job so weeks with nothing to ship don't ask for an
+ # approval. Skipped (= no release) if the build failed.
+ - name: Check for changes to release
+ id: release-check
+ env:
+ GH_TOKEN: ${{ github.token }}
+ MANUAL_BUMP: ${{ inputs.bump }}
+ run: |
+ SHIPPED="icons devicon.json devicon.min.css devicon-base.css fonts"
+ LAST_TAG=$(git describe --tags --abbrev=0 --match 'v[0-9]*' 2>/dev/null || true)
+ if [ -z "$LAST_TAG" ]; then
+ echo "No previous release tag — releasing"
+ echo "should_release=true" >> $GITHUB_OUTPUT
+ exit 0
+ fi
+ if ! git diff --quiet "$LAST_TAG" HEAD -- $SHIPPED; then
+ echo "Changes to release since $LAST_TAG:"
+ git diff --stat "$LAST_TAG" HEAD -- $SHIPPED | tail -1
+ echo "should_release=true" >> $GITHUB_OUTPUT
+ exit 0
+ fi
+ if [ -n "$MANUAL_BUMP" ] && [ "$MANUAL_BUMP" != "auto" ]; then
+ echo "Manual run with bump '$MANUAL_BUMP' — releasing"
+ echo "should_release=true" >> $GITHUB_OUTPUT
+ exit 0
+ fi
+ # PR numbers from squash commit titles like "feat: foo (#123)"
+ for PR in $(git log --format=%s "$LAST_TAG..HEAD" | grep -oE '\(#[0-9]+\)' | tr -d '(#)' | sort -u); do
+ LABEL=$(gh pr view "$PR" --repo "$GITHUB_REPOSITORY" --json labels --jq '[.labels[].name | select(startswith("release: "))][0] // empty' 2>/dev/null || true)
+ if [ -n "$LABEL" ]; then
+ echo "PR #$PR is labelled '$LABEL' — releasing"
+ echo "should_release=true" >> $GITHUB_OUTPUT
+ exit 0
+ fi
+ done
+ echo "Nothing to release since $LAST_TAG"
+ echo "should_release=false" >> $GITHUB_OUTPUT
+
+ # ── Release gate ─────────────────────────────────────────────────────────────
+ # This job requires a manual approval in the "production" GitHub Environment
+ # before bumping the version and publishing the release.
+ #
+ # One-time setup (repo admin):
+ # Settings → Environments → New environment → name it "production"
+ # Add required reviewers (maintainers who should approve releases).
+ #
+ # ── Pushing to a protected master ────────────────────────────────────────────
+ # The build and release jobs push commits/tags straight to master. When master
+ # is protected, GITHUB_TOKEN can't do that, so both jobs use a token from a
+ # GitHub App that is on the ruleset's bypass list:
+ # vars.BOT_APP_ID - the App ID
+ # secrets.BOT_APP_PRIVATE_KEY - a private key generated for the app
+ # The app only needs "Contents: Read and write". Without these set, the jobs
+ # fall back to GITHUB_TOKEN (fine for an unprotected master).
+ release:
+ name: Bump Version and Release
+ needs: build
+ if: needs.build.outputs.should_release == 'true'
+ runs-on: ubuntu-24.04
+ environment: production
+ outputs:
+ version: ${{ steps.bump.outputs.version }}
+
+ steps:
+ - name: Get bot token
+ id: bot-token
+ if: vars.BOT_APP_ID != ''
+ uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0
+ with:
+ app-id: ${{ vars.BOT_APP_ID }}
+ private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }}
+ # Only what this workflow needs; fails here if the installation lacks it
+ permission-contents: write
+
+ - name: Checkout master
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ # Explicit ref so we get the build: commit pushed by the build job,
+ # not the commit the workflow was triggered on
+ ref: master
+ token: ${{ steps.bot-token.outputs.token || secrets.GITHUB_TOKEN }}
+ fetch-depth: 0
+
+ - name: Find commits since last release
+ id: range
+ run: |
+ LAST_TAG=$(git describe --tags --abbrev=0 --match 'v[0-9]*' 2>/dev/null || true)
+ if [ -z "$LAST_TAG" ]; then
+ echo "No previous release tag — using full history"
+ echo "range=HEAD" >> $GITHUB_OUTPUT
+ else
+ echo "Last release: $LAST_TAG"
+ echo "range=${LAST_TAG}..HEAD" >> $GITHUB_OUTPUT
+ fi
+
+ # Collects the PRs merged since the last release (from the "(#123)" in
+ # squash commit titles) and derives from them:
+ # - the version bump: highest of the "release: major/minor" labels, else patch
+ # - the release notes, in the same format as earlier devicon releases
+ - name: Determine version bump and release notes
+ id: version-bump
+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
+ with:
+ script: |
+ const range = '${{ steps.range.outputs.range }}';
+ const { execSync } = require('child_process');
+ const repo = { owner: context.repo.owner, repo: context.repo.repo };
+
+ let log = '';
+ try {
+ log = execSync(`git log --format="%s" ${range}`).toString().trim();
+ } catch (e) {
+ console.log('Could not get git log:', e.message);
+ }
+
+ // Extract PR numbers from squash commit messages like "new icon: foo (#123)".
+ // git log lists newest first, so the notes do too.
+ const prNumbers = [...new Set([...log.matchAll(/\(#(\d+)\)/g)].map(m => parseInt(m[1])))];
+ console.log('PR numbers found in commits:', prNumbers);
+
+ let bump = 'patch';
+ const icons = [], features = [];
+
+ for (const prNumber of prNumbers) {
+ let pr;
+ try {
+ ({ data: pr } = await github.rest.pulls.get({ ...repo, pull_number: prNumber }));
+ } catch (e) {
+ console.log(`Could not fetch PR #${prNumber}:`, e.message);
+ continue;
+ }
+
+ const labels = pr.labels.map(l => l.name);
+ console.log(`PR #${prNumber} labels:`, labels);
+ if (labels.includes('release: major')) {
+ bump = 'major';
+ } else if (labels.includes('release: minor') && bump !== 'major') {
+ bump = 'minor';
+ }
+
+ // Credit everyone who made commits in the PR
+ const commits = await github.paginate(github.rest.pulls.listCommits, { ...repo, pull_number: prNumber, per_page: 100 });
+ const authors = [...new Set(commits.map(c => c.author ? c.author.login : c.commit.author.name))];
+ const line = `- [${pr.title}](${pr.html_url}) by ${authors.map(a => '@' + a).join(', ')}.`;
+
+ // Icon PR titles are enforced (and auto-fixed) by the check-bot
+ (/^(new|update) icon:/i.test(pr.title) ? icons : features).push(line);
+ }
+
+ const manualBump = '${{ inputs.bump }}';
+ if (manualBump && manualBump !== 'auto') {
+ console.log('Manual bump override:', manualBump);
+ bump = manualBump;
+ }
+ console.log('Final version bump:', bump);
+ core.setOutput('bump', bump);
+
+ const sections = [];
+ if (icons.length) sections.push(` **${icons.length} New/Updated Icons**\n${icons.join('\n')}`);
+ if (features.length) sections.push(` **${features.length} New Features/Fixes**\n${features.join('\n')}`);
+ const notes = ['A huge thanks to all our maintainers and contributors for making this release possible!', ...sections].join('\n\n');
+ console.log('Release notes:\n' + notes);
+ core.setOutput('notes', notes);
+
+ - name: Setup Node.js
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: '24'
+
+ - name: Install Node dependencies
+ run: npm install
+
+ - name: Bump version
+ id: bump
+ run: |
+ BUMP="${{ steps.version-bump.outputs.bump }}"
+ git config --local user.email "github-actions[bot]@users.noreply.github.com"
+ git config --local user.name "github-actions[bot]"
+ npm version $BUMP -m "chore: bump version to %s"
+ VERSION=$(node -p "require('./package.json').version")
+ echo "version=$VERSION" >> $GITHUB_OUTPUT
+ git push --follow-tags
+
+ # Deliberately uses GITHUB_TOKEN (github-script's default), not the bot
+ # token: a release created with GITHUB_TOKEN doesn't trigger npm_publish.yml,
+ # so the publish job below is the only thing that publishes to npm.
+ - name: Create GitHub release
+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
+ env:
+ NOTES: ${{ steps.version-bump.outputs.notes }}
+ with:
+ script: |
+ const version = '${{ steps.bump.outputs.version }}';
+ const bump = '${{ steps.version-bump.outputs.bump }}';
+
+ await github.rest.repos.createRelease({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ tag_name: `v${version}`,
+ name: `Release v${version}`,
+ body: process.env.NOTES,
+ draft: false
+ });
+
+ console.log(`Released v${version} (${bump} bump).`);
+
+ publish:
+ name: Publish to npm
+ needs: release
+ # npm trusted publishing (OIDC): the called workflow needs an id-token
+ permissions:
+ id-token: write
+ contents: read
+ uses: ./.github/workflows/npm_publish.yml
+ with:
+ ref: v${{ needs.release.outputs.version }}
diff --git a/.github/workflows/check_icon_pr.yml b/.github/workflows/check_icon_pr.yml
index 4c93418799..fe30fe22ef 100644
--- a/.github/workflows/check_icon_pr.yml
+++ b/.github/workflows/check_icon_pr.yml
@@ -1,53 +1,83 @@
name: Check Icon PR
-on: pull_request
+on:
+ pull_request:
+ # edited: re-check when the PR title is fixed
+ types: [opened, synchronize, reopened, edited]
+ paths:
+ - 'icons/**'
+ - 'devicon.json'
jobs:
check:
name: Check the `devicon.json` and the SVGs' quality
runs-on: ubuntu-24.04
- if: startsWith(github.event.pull_request.title, 'new icon') || startsWith(github.event.pull_request.title, 'update icon') # only checks icon PR
steps:
- - uses: actions/checkout@v5
+ # Checks out the PR's merge commit; depth 2 so HEAD^1 (the target branch)
+ # is available to diff against
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ fetch-depth: 2
- - name: Check if PR is develop
- if: ${{ github.base_ref != 'develop' }}
+ - name: Check if PR targets master
+ if: ${{ github.base_ref != 'master' }}
run: |
- echo -e "The PR's base branch is \`${{ github.base_ref }}\`, but should be \`develop\`\nPlease change the PR so that it's based on, and merged into \`develop\`" > ./err_messages.txt
- echo "wrong_branch=true" >> $GITHUB_ENV
+ echo "Error: This PR targets '${{ github.base_ref }}' but should target 'master'"
+ echo "Please change the PR so that it's based on, and merged into 'master'"
+ exit 1
- - uses: actions/setup-python@v5
- if: ${{ !env.wrong_branch }}
+ - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
- python-version: 3.12
+ python-version: '3.12'
- name: Install dependencies
- if: ${{ !env.wrong_branch }}
run: |
python -m pip install --upgrade pip
- python -m pip install -r ./.github/scripts/requirements.txt
-
- - name: Run the check_svg script
- if: ${{ !env.wrong_branch }}
- env:
- PR_TITLE: ${{ github.event.pull_request.title }}
- run: python ./.github/scripts/check_icon_pr.py "$PR_TITLE" ./icons ./devicon.json
-
- - name: Upload the err messages
- uses: actions/upload-artifact@v4
- if: success()
- with:
- name: err_messages
- path: ./err_messages.txt
+ pip install -r ./.github/scripts/requirements.txt
- name: Save the pr num in an artifact
shell: bash
- if: success()
env:
PR_NUM: ${{ github.event.number }}
run: echo $PR_NUM > pr_num.txt
- name: Upload the pr num
- uses: actions/upload-artifact@v4
- if: success()
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: pr_num
path: ./pr_num.txt
+
+ - name: Run the check_svg script
+ env:
+ PR_TITLE: ${{ github.event.pull_request.title }}
+ run: python ./.github/scripts/check_icon_pr.py "$PR_TITLE" ./icons ./devicon.json
+
+ # Uploaded even if the script crashed: it writes the error to err_messages.txt.
+ # expected_title.txt is set when the bot should rename the PR.
+ - name: Upload the err messages
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ if: always()
+ with:
+ name: err_messages
+ path: |
+ ./err_messages.txt
+ ./expected_title.txt
+ ./release_label.txt
+ ./release_notice.json
+ if-no-files-found: ignore
+
+ # Fail the check when issues were found or the title is wrong, so the PR
+ # shows a red check. post_check_icon_pr_comment.yml posts the details and
+ # renames the PR; the rename re-runs this check.
+ - name: Fail if issues were found
+ shell: bash
+ run: |
+ FAIL=0
+ if [ -s expected_title.txt ]; then
+ echo "::error::PR title should be: $(cat expected_title.txt) (the check-bot will rename the PR)"
+ FAIL=1
+ fi
+ if [ -s err_messages.txt ]; then
+ echo "::error::Issues found in this PR (details in the check-bot comment):"
+ cat err_messages.txt
+ FAIL=1
+ fi
+ exit $FAIL
diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
index cac4c6baf3..e116dea8e5 100644
--- a/.github/workflows/codeql-analysis.yml
+++ b/.github/workflows/codeql-analysis.yml
@@ -2,9 +2,9 @@ name: "Code Scanning - Action"
on:
push:
- branches: [master, develop]
+ branches: [master]
pull_request:
- branches: [master, develop]
+ branches: [master]
schedule:
- cron: 30 1 * * 0 # Runs every Sunday 1:30 am UTC
@@ -15,15 +15,15 @@ jobs:
security-events: write
steps:
- name: Checkout repository
- uses: actions/checkout@v5
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Initialize CodeQL
- uses: github/codeql-action/init@v2
+ uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
with:
languages: javascript
- name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@v2
+ uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
CodeQL-Python-dot-github:
runs-on: ubuntu-latest
@@ -31,13 +31,13 @@ jobs:
security-events: write
steps:
- name: Checkout repository
- uses: actions/checkout@v5
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Set up Python
- uses: actions/setup-python@v5
+ uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
id: setup-python
with:
- python-version: '3.10'
+ python-version: '3.12'
- name: Install dependencies
run: |
@@ -50,14 +50,14 @@ jobs:
echo "CODEQL_PYTHON=${{ steps.setup-python.outputs.python-path }}" >> $GITHUB_ENV
- name: Initialize CodeQL
- uses: github/codeql-action/init@v2
+ uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
with:
languages: python
setup-python-dependencies: false
source-root: .github/
- name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@v2
+ uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
CodeQL-Python-rest:
runs-on: ubuntu-latest
@@ -65,7 +65,7 @@ jobs:
security-events: write
steps:
- name: Checkout repository
- uses: actions/checkout@v5
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Find Python files outside the .github folder
id: find_files
@@ -76,10 +76,10 @@ jobs:
- name: Initialize CodeQL
if: ${{ steps.find_files.outputs.python_files != '0' }}
- uses: github/codeql-action/init@v2
+ uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
with:
languages: python
- name: Perform CodeQL Analysis
if: ${{ steps.find_files.outputs.python_files != '0' }}
- uses: github/codeql-action/analyze@v2
+ uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
diff --git a/.github/workflows/in_develop_labeler.yml b/.github/workflows/in_develop_labeler.yml
deleted file mode 100644
index f47d8b8400..0000000000
--- a/.github/workflows/in_develop_labeler.yml
+++ /dev/null
@@ -1,47 +0,0 @@
-name: Label Issue In Develop
-on:
- workflow_run:
- workflows: ['On Develop PR Merge']
- types:
- - completed
-jobs:
- on-failure:
- runs-on: ubuntu-latest
- if: ${{ github.event.workflow_run.conclusion == 'failure' }}
- steps:
- - run: echo "First workflow was a failure"
- label_preflight:
- name: Label Issue In Develop
- runs-on: ubuntu-24.04
- if: ${{ github.event.workflow_run.conclusion == 'success' }}
- steps:
- - uses: actions/checkout@v5
-
- - name: Setup Python v3.12
- uses: actions/setup-python@v5
- with:
- python-version: 3.12
-
- - name: Install dependencies
- run: |
- python -m pip install --upgrade pip
- python -m pip install -r ./.github/scripts/requirements.txt
-
- - name: Download workflow artifact
- uses: dawidd6/action-download-artifact@v7
- with:
- github_token: ${{ secrets.GITHUB_TOKEN }}
- workflow: peek_icons.yml
- run_id: ${{ github.event.workflow_run.id }}
-
- - name: Read the pr_num file
- id: pr_num_reader
- uses: juliangruber/read-file-action@v1.0.0
- with:
- path: ./pr_num/pr_num.txt
-
- - name: Run in_develop_labeler.py
- env:
- TOKEN: ${{ secrets.GITHUB_TOKEN }}
- PR_NUM: ${{ steps.pr_num_reader.outputs.content }}
- run: python ./.github/scripts/in_develop_labeler.py $TOKEN "$PR_NUM"
diff --git a/.github/workflows/in_develop_labeler_preflight.yml b/.github/workflows/in_develop_labeler_preflight.yml
deleted file mode 100644
index c59e03aa1b..0000000000
--- a/.github/workflows/in_develop_labeler_preflight.yml
+++ /dev/null
@@ -1,24 +0,0 @@
-name: On Develop PR Merge
-on:
- pull_request:
- types: [closed]
- branches: [develop]
-jobs:
- save_pr_num_in_artifact:
- name: Preflight Label Issue In Develop
- runs-on: ubuntu-latest
- if: github.event.pull_request.merged == true
- steps:
- - uses: actions/checkout@v5
-
- - name: Save the PR number in an artifact
- shell: bash
- env:
- PR_NUM: ${{ github.event.number }}
- run: echo $PR_NUM > pr_num.txt
-
- - name: Upload the PR number
- uses: actions/upload-artifact@v4
- with:
- name: pr_num
- path: ./pr_num.txt
diff --git a/.github/workflows/npm_publish.yml b/.github/workflows/npm_publish.yml
index 8e8d1f0a78..1d3ba3491b 100644
--- a/.github/workflows/npm_publish.yml
+++ b/.github/workflows/npm_publish.yml
@@ -1,7 +1,16 @@
name: "Publish to npm"
on:
+ # Releases created by hand in the GitHub UI
release:
types: [released]
+ # Releases created by build_weekly.yml. Those use GITHUB_TOKEN, which doesn't
+ # trigger other workflows, so build_weekly.yml calls this one directly.
+ workflow_call:
+ inputs:
+ ref:
+ description: 'Tag or branch to publish'
+ required: true
+ type: string
# Allows re-running a failed publish by hand from the Actions tab
workflow_dispatch:
permissions: {}
@@ -13,19 +22,20 @@ jobs:
id-token: write # Required for npm trusted publishing (OIDC)
contents: read
steps:
- - uses: actions/checkout@v7
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
- # Check out the release tag for release events.
- # For manual runs, use the branch or tag selected in the Actions tab.
- ref: ${{ github.event_name == 'release' && github.event.release.tag_name || github.ref }}
+ # inputs.ref is set when called from build_weekly.yml; release events check
+ # out the release tag; manual runs use the branch or tag selected in the Actions tab.
+ ref: ${{ inputs.ref || (github.event_name == 'release' && github.event.release.tag_name) || github.ref }}
persist-credentials: false
# Node 24 ships with npm 11.5.1 or later, which trusted publishing requires
- name: Use Node.js v24
- uses: actions/setup-node@v7
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 24
package-manager-cache: false
# No dependencies are installed: the package has no build step, and skipping
# them keeps third-party install scripts out of the job that can publish.
- # Authenticates through the trusted publisher configured on npmjs.com, so no token is needed
- - run: npm publish
+ # Authenticates through the trusted publisher configured on npmjs.com, so no token is needed.
+ # Forks only do a dry run so they can't publish the real package.
+ - run: npm publish ${{ github.repository != 'devicons/devicon' && '--dry-run' || '' }}
diff --git a/.github/workflows/peek_icons.yml b/.github/workflows/peek_icons.yml
index 6a003492ed..e1b7aecb63 100644
--- a/.github/workflows/peek_icons.yml
+++ b/.github/workflows/peek_icons.yml
@@ -11,17 +11,21 @@ jobs:
if: github.event.label.name == 'bot:peek'
runs-on: ubuntu-24.04
steps:
- - uses: actions/checkout@v5
+ # Checks out the PR's merge commit; depth 2 so HEAD^1 (the target branch)
+ # is available to diff against
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ fetch-depth: 2
- name: Setup Python v3.12
- uses: actions/setup-python@v5
+ uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
- python-version: 3.12
+ python-version: '3.12'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
- python -m pip install -r ./.github/scripts/requirements.txt
+ pip install -r ./.github/scripts/requirements.txt
- name: Save the PR number in an artifact
shell: bash
@@ -30,36 +34,34 @@ jobs:
run: echo $PR_NUM > pr_num.txt
- name: Upload the PR number
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: pr_num
path: ./pr_num.txt
- name: Run icomoon_peek.py
- env:
- PR_TITLE: ${{ github.event.pull_request.title }}
shell: bash
run: >
python ./.github/scripts/icomoon_peek.py
./.github/scripts/build_assets/geckodriver-v0.32.2-linux64/geckodriver ./icomoon.json
- ./devicon.json ./icons ./ --headless "$PR_TITLE"
+ ./devicon.json ./icons ./ --headless
- name: Upload the err messages (created by icomoon_peek.py)
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: always()
with:
name: err_messages
path: ./err_messages.txt
- name: Upload screenshots for comments
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: success()
with:
name: screenshots
path: ./screenshots/*.png
- name: Upload geckodriver.log for debugging purposes
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: failure()
with:
name: geckodriver-log
diff --git a/.github/workflows/post_check_icon_pr_comment.yml b/.github/workflows/post_check_icon_pr_comment.yml
index 681fa8e12f..340a10e00c 100644
--- a/.github/workflows/post_check_icon_pr_comment.yml
+++ b/.github/workflows/post_check_icon_pr_comment.yml
@@ -4,77 +4,236 @@ on:
workflows: ['Check Icon PR']
types:
- completed
+
+permissions:
+ actions: read
+ issues: write
+ pull-requests: write
+
jobs:
post_result_of_svg_check:
name: Post the result of the Check SVG Action
runs-on: ubuntu-latest
+ # The check fails when it finds issues, so post on failure too. If the check
+ # couldn't produce its artifacts at all, the steps below fail and the
+ # "Failure" comment is posted instead.
+ if: github.event.workflow_run.conclusion == 'success' || github.event.workflow_run.conclusion == 'failure'
steps:
- - name: Check if the trigger run worked. If it failed, fail the current run.
- if: github.event.workflow_run.conclusion != 'success'
- uses: cutenode/action-always-fail@v1.0.1
-
- name: Download workflow artifact
- uses: dawidd6/action-download-artifact@v7
- if: success()
+ uses: dawidd6/action-download-artifact@eab87c9830c39eff17e5a6eadb20bfb4bc880477 # v27
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
workflow: check_icon_pr.yml
run_id: ${{ github.event.workflow_run.id }}
- - name: Read the pr_num file
- if: success()
- id: pr_num_reader
- uses: juliangruber/read-file-action@v1.1.6
+ # For PRs from forks the check runs the fork's own workflow code, so its
+ # artifacts can't be trusted. Only act on the PR if its head is the commit
+ # that was checked.
+ - name: Verify the PR
+ id: pr
+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
- path: ./pr_num/pr_num.txt
+ script: |
+ const fs = require('fs');
+ const num = parseInt(fs.readFileSync('./pr_num/pr_num.txt', 'utf8').trim(), 10);
+ if (!Number.isInteger(num) || num <= 0) {
+ core.setFailed('pr_num artifact is not a PR number');
+ return;
+ }
+ const { data: pr } = await github.rest.pulls.get({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ pull_number: num
+ });
+ const checked = context.payload.workflow_run.head_sha;
+ if (pr.head.sha !== checked) {
+ core.setFailed(`PR #${num} is at ${pr.head.sha}, but the check ran on ${checked}. Not acting on it.`);
+ return;
+ }
+ core.setOutput('number', String(num));
- - name: Read the err message file
- if: success()
- id: err_message_reader
- uses: juliangruber/read-file-action@v1.1.6
+ - name: Read the expected title
+ id: title
+ run: |
+ TITLE=""
+ if [ -f ./err_messages/expected_title.txt ]; then
+ TITLE=$(head -c 300 ./err_messages/expected_title.txt | tr -d '\r\n')
+ fi
+ echo "expected=$TITLE" >> $GITHUB_OUTPUT
+
+ # Renaming with the bot app's token (not GITHUB_TOKEN) re-runs the check
+ # on the new title. See build_weekly.yml for the app setup; it also needs
+ # the "Pull requests: Read and write" permission for this.
+ - name: Get bot token
+ id: bot-token
+ if: steps.title.outputs.expected != '' && vars.BOT_APP_ID != ''
+ uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0
with:
- path: ./err_messages/err_messages.txt
+ app-id: ${{ vars.BOT_APP_ID }}
+ private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }}
+ # Only what this workflow needs; fails here if the installation lacks it
+ permission-pull-requests: write
- - name: Comment on the PR about the result - SVG Error
- uses: jungwinter/comment@v1.1.0 # let us comment on a specific PR
- if: success() && (steps.err_message_reader.outputs.content != '')
+ - name: Validate the expected title
+ id: validate
+ if: steps.title.outputs.expected != ''
+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
+ env:
+ EXPECTED: ${{ steps.title.outputs.expected }}
+ PR_NUM: ${{ steps.pr.outputs.number }}
+ with:
+ script: |
+ const expected = process.env.EXPECTED;
+ const version = '(original|plain|line)(-wordmark)?';
+ const valid = new RegExp(`^(new|update) icon: [a-z0-9._-]+ \\(${version}(, ${version})*\\)$`);
+ if (expected.length > 200 || !valid.test(expected)) {
+ core.setFailed(`Refusing to use an unexpected title: ${expected}`);
+ return;
+ }
+ const { data: pr } = await github.rest.pulls.get({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ pull_number: parseInt(process.env.PR_NUM, 10)
+ });
+ core.setOutput('old_title', pr.title);
+
+ # Its own step so it runs as the bot app (github-token), not GITHUB_TOKEN
+ - name: Rename the PR
+ if: steps.title.outputs.expected != '' && steps.bot-token.outputs.token != ''
+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
+ env:
+ EXPECTED: ${{ steps.title.outputs.expected }}
+ PR_NUM: ${{ steps.pr.outputs.number }}
+ with:
+ github-token: ${{ steps.bot-token.outputs.token }}
+ script: |
+ await github.rest.pulls.update({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ pull_number: parseInt(process.env.PR_NUM, 10),
+ title: process.env.EXPECTED
+ });
+
+ - name: Comment on the PR about the title
+ if: steps.title.outputs.expected != ''
+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
- MESSAGE: |
- Hi!
+ EXPECTED: ${{ steps.title.outputs.expected }}
+ OLD_TITLE: ${{ steps.validate.outputs.old_title }}
+ PR_NUM: ${{ steps.pr.outputs.number }}
+ RENAMED: ${{ steps.bot-token.outputs.token != '' }}
+ with:
+ script: |
+ const body = process.env.RENAMED === 'true'
+ ? [
+ "Hi!", "",
+ "I'm the `check-bot`. The PR title didn't match the icon this PR changes, so I renamed it:", "",
+ "```", `from: ${process.env.OLD_TITLE}`, `to: ${process.env.EXPECTED}`, "```", "",
+ "The title becomes the commit message and the line in the release notes. I'll check the PR again with the new title.", "",
+ "Thanks for your help,", "SVG-Checker Bot :smile:"
+ ]
+ : [
+ // Without the bot app a rename wouldn't re-run the check, so ask instead
+ "Hi!", "",
+ "I'm the `check-bot`. This PR's title doesn't match the icon it changes. Please rename it to:", "",
+ "```", process.env.EXPECTED, "```", "",
+ "Thanks for your help,", "SVG-Checker Bot :smile:"
+ ];
+ await github.rest.issues.createComment({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: parseInt(process.env.PR_NUM, 10),
+ body: body.join('\n')
+ });
- I'm the `check-bot` and we have some issues with your PR:
+ # Add the release label the check suggests, unless the PR already has a
+ # release label (maintainers override by setting another one, e.g.
+ # "release: patch").
+ - name: Label the release level
+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
+ continue-on-error: true
+ env:
+ PR_NUM: ${{ steps.pr.outputs.number }}
+ with:
+ script: |
+ const fs = require('fs');
+ const file = './err_messages/release_label.txt';
+ const label = fs.existsSync(file) ? fs.readFileSync(file, 'utf8').trim() : '';
+ if (!['release: major', 'release: minor'].includes(label)) return;
- ```
- {0}
- ```
+ const issue = { owner: context.repo.owner, repo: context.repo.repo, issue_number: parseInt(process.env.PR_NUM, 10) };
+ const { data: labels } = await github.rest.issues.listLabelsOnIssue(issue);
+ if (labels.some(l => l.name.startsWith('release:'))) return;
+ await github.rest.issues.addLabels({ ...issue, labels: [label] });
+ if (label !== 'release: major') return;
- Check our [CONTRIBUTING guide](https://github.com/devicons/devicon/wiki/SVG-Standards) for more details regarding these errors.
+ // Explain why a rename or removal is a major release. The check only
+ // passes the icon names; the message is written here.
+ const noticeFile = './err_messages/release_notice.json';
+ const notice = fs.existsSync(noticeFile) ? JSON.parse(fs.readFileSync(noticeFile, 'utf8')) : {};
+ const names = [...(notice.renamed || []), ...(notice.removed || [])];
+ if (!names.length || !names.every(n => /^[a-z0-9._-]{1,50}$/.test(n))) return;
- Please address these issues. When you update this PR, I will check your SVGs again.
+ let what, old;
+ if (notice.renamed) {
+ const [from, to] = notice.renamed;
+ what = `**\`${from}\` is renamed to \`${to}\`.**`;
+ old = [from];
+ } else {
+ what = `**This PR removes ${notice.removed.map(n => `\`${n}\``).join(', ')}.**`;
+ old = notice.removed;
+ }
+ const uses = old.map(n => `\`icons/${n}/…\` SVG links or \`devicon-${n}-*\` classes`).join(', ');
+ await github.rest.issues.createComment({ ...issue, body: [
+ "Hi!", "",
+ `I'm the \`check-bot\`. ${what}`, "",
+ `Sites that use the old name (${uses}) can break, so this is a breaking change. ` +
+ "I've labelled this PR `release: major`: it will be part of the next major release. " +
+ "If it isn't breaking after all, a maintainer can replace the label.", "",
+ "Thanks for your help,", "SVG-Checker Bot :smile:"
+ ].join('\n') });
- Thanks for your help,
- SVG-Checker Bot :smile:
+ - name: Comment on the PR about the result - SVG Error
+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
+ env:
+ PR_NUM: ${{ steps.pr.outputs.number }}
with:
- type: create
- issue_number: ${{ steps.pr_num_reader.outputs.content }}
- token: ${{ secrets.GITHUB_TOKEN }}
- body: ${{ format(env.MESSAGE, steps.err_message_reader.outputs.content) }}
+ script: |
+ const fs = require('fs');
+ const file = './err_messages/err_messages.txt';
+ const errors = fs.existsSync(file) ? fs.readFileSync(file, 'utf8').trim() : '';
+ if (!errors) return;
+
+ await github.rest.issues.createComment({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: parseInt(process.env.PR_NUM, 10),
+ body: [
+ "Hi!", "",
+ "I'm the `check-bot` and we have some issues with your PR:", "",
+ "```", errors, "```", "",
+ "Check our [CONTRIBUTING guide](https://github.com/devicons/devicon/wiki/SVG-Standards) for more details regarding these errors.", "",
+ "Please address these issues. When you push new commits or edit the PR title, I will check your PR again.", "",
+ "Thanks for your help,", "SVG-Checker Bot :smile:"
+ ].join('\n')
+ });
+ # Only with a verified PR number: never comment on a PR named by an unverified artifact
- name: Comment on the PR about the result - Failure
- uses: jungwinter/comment@v1.1.0 # let us comment on a specific PR
- if: failure()
+ if: failure() && steps.pr.outputs.number != ''
+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
- MESSAGE: |
- Hi!
-
- I'm Devicons' SVG-Checker Bot and it seems we've ran into a problem. I'm supposed to check your svgs but I couldn't do my task due to an issue.
-
- Please let my maintainers know of the issues. They will take a look at my work and try to resolve the problem. Until then, please hang tight and sorry for the inconvenience.
-
- Cheers,
- SVG-Checker Bot :smile:
+ PR_NUM: ${{ steps.pr.outputs.number }}
with:
- type: create
- issue_number: ${{ steps.pr_num_reader.outputs.content }}
- token: ${{ secrets.GITHUB_TOKEN }}
- body: ${{ env.MESSAGE }}
+ script: |
+ await github.rest.issues.createComment({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: parseInt(process.env.PR_NUM, 10),
+ body: [
+ "Hi!", "",
+ "I'm Devicons' SVG-Checker Bot and it seems we've ran into a problem. I'm supposed to check your svgs but I couldn't do my task due to an issue.", "",
+ "Please let my maintainers know of the issues. They will take a look at my work and try to resolve the problem. Until then, please hang tight and sorry for the inconvenience.", "",
+ "Cheers,", "SVG-Checker Bot :smile:"
+ ].join('\n')
+ });
diff --git a/.github/workflows/post_peek_screenshot.yml b/.github/workflows/post_peek_screenshot.yml
index f52cf9ffa7..475d7a9710 100644
--- a/.github/workflows/post_peek_screenshot.yml
+++ b/.github/workflows/post_peek_screenshot.yml
@@ -4,23 +4,26 @@ on:
workflows: ['Peek Icons']
types:
- completed
+
+permissions:
+ contents: write
+ issues: write
+ pull-requests: write
+
jobs:
post_screenshots_in_comment:
name: Post the screenshot
runs-on: ubuntu-latest
if: github.event.action == 'completed' && github.event.workflow_run.conclusion != 'skipped'
env:
- # three possible values: 'skipped', 'success', 'failure'
- # have to print github.event to console to see these values
- # note: can't use this env variable up in the if statement above for some reason.
- # I don't think it's an ordering issue cause it seems 'if' is auto evaluate first
PEEK_STATUS: ${{ github.event.workflow_run.conclusion }}
+
steps:
- name: Check state of last run
- run: echo $PEEK_STATUS
+ run: echo "Peek status $PEEK_STATUS"
- - name: Download workflow artifact
- uses: dawidd6/action-download-artifact@v7
+ - name: Download workflow artifacts
+ uses: dawidd6/action-download-artifact@eab87c9830c39eff17e5a6eadb20bfb4bc880477 # v27
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
workflow: peek_icons.yml
@@ -28,156 +31,234 @@ jobs:
- name: Read the pr_num file
id: pr_num_reader
- uses: juliangruber/read-file-action@v1.1.6
- with:
- path: ./pr_num/pr_num.txt
+ run: |
+ PR_NUM=$(cat ./pr_num/pr_num.txt | tr -d '[:space:]')
+ echo "pr_num=$PR_NUM" >> $GITHUB_OUTPUT
- name: Read the err message file
- if: success()
id: err_message_reader
- uses: juliangruber/read-file-action@v1.1.6
- with:
- path: ./err_messages/err_messages.txt
-
- # using this trigger allowed us to access secrets
- - name: Upload screenshot of the SVGs gotten from the artifacts
- id: svgs_overview_img_step
- if: env.PEEK_STATUS == 'success' && success()
- uses: devicons/public-upload-to-imgur@v2.2.2
- with:
- path: ./screenshots/new_svgs.png
- client_id: ${{secrets.IMGUR_CLIENT_ID}}
-
- - name: Upload zoomed in screenshot of the SVGs gotten from the artifacts
- id: svgs_detailed_img_step
- uses: devicons/public-upload-to-imgur@v2.2.2
- if: env.PEEK_STATUS == 'success' && success()
- with:
- path: ./screenshots/new_svg_*.png
- client_id: ${{secrets.IMGUR_CLIENT_ID}}
+ run: |
+ if [ -f ./err_messages/err_messages.txt ]; then
+ ERR=$(cat ./err_messages/err_messages.txt)
+ else
+ ERR=""
+ fi
+ echo "err_message<> $GITHUB_OUTPUT
+ echo "$ERR" >> $GITHUB_OUTPUT
+ echo "EOF" >> $GITHUB_OUTPUT
- - name: Upload screenshot of the newly made icons gotten from the artifacts
- id: icons_overview_img_step
- if: env.PEEK_STATUS == 'success' && success()
- uses: devicons/public-upload-to-imgur@v2.2.2
+ - name: Upload screenshots to screenshots branch
+ if: env.PEEK_STATUS == 'success'
+ id: upload_screenshots
+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
- path: ./screenshots/new_icons.png
- client_id: ${{secrets.IMGUR_CLIENT_ID}}
+ script: |
+ const fs = require('fs');
+ const path = require('path');
+ const prNum = '${{ steps.pr_num_reader.outputs.pr_num }}';
+ const repo = context.repo;
+ const branch = 'screenshots';
+ const screenshotsDir = './screenshots';
- - name: Upload zoomed in screenshot of the newly made icons gotten from the artifacts
- id: icons_detailed_img_step
- uses: devicons/public-upload-to-imgur@v2.2.2
- if: env.PEEK_STATUS == 'success' && success()
- with:
- path: ./screenshots/new_icon_*.png
- client_id: ${{secrets.IMGUR_CLIENT_ID}}
+ // A successful peek without screenshots means the PR changed no icon
+ // SVGs (e.g. a devicon.json-only change), so there's nothing to post
+ const files = fs.existsSync(screenshotsDir)
+ ? fs.readdirSync(screenshotsDir).filter(f => f.endsWith('.png'))
+ : [];
+ if (files.length === 0) {
+ console.log('No screenshots — nothing to post');
+ core.setOutput('skipped', 'true');
+ return;
+ }
- - name: Upload zoomed in screenshot of the colored icons gotten from the artifacts
- id: colored_icons_detailed_img_step
- uses: devicons/public-upload-to-imgur@v2.2.2
- if: env.PEEK_STATUS == 'success' && success()
- with:
- path: ./screenshots/new_colored_icon_*.png
- client_id: ${{secrets.IMGUR_CLIENT_ID}}
+ // Get or create screenshots branch
+ let branchSha;
+ try {
+ const { data: ref } = await github.rest.git.getRef({
+ ...repo,
+ ref: `heads/${branch}`
+ });
+ branchSha = ref.object.sha;
+ } catch (e) {
+ const { data: master } = await github.rest.git.getRef({
+ ...repo,
+ ref: 'heads/master'
+ });
+ const { data: newBranch } = await github.rest.git.createRef({
+ ...repo,
+ ref: `refs/heads/${branch}`,
+ sha: master.object.sha
+ });
+ branchSha = newBranch.object.sha;
+ }
- - name: Comment on the PR about the result - Success
- uses: jungwinter/comment@v1.1.0 # let us comment on a specific PR
- if: env.PEEK_STATUS == 'success' && success()
- env:
- MESSAGE: |
- Hi there,
+ // Get current tree SHA
+ const { data: commit } = await github.rest.git.getCommit({
+ ...repo,
+ commit_sha: branchSha
+ });
- I'm Devicons' Peek Bot and I just peeked at the icons that you wanted to add using [icomoon.io](https://icomoon.io/app/#/select).
+ // Upload each screenshot as a blob
+ const blobs = await Promise.all(files.map(async f => {
+ const content = fs.readFileSync(path.join(screenshotsDir, f));
+ const { data: blob } = await github.rest.git.createBlob({
+ ...repo,
+ content: content.toString('base64'),
+ encoding: 'base64'
+ });
+ return { path: `pr-${prNum}/${f}`, sha: blob.sha, mode: '100644', type: 'blob' };
+ }));
- Here are the SVGs as intepreted by Icomoon when we upload the files:
- {0}
+ // Create new tree and commit
+ const { data: tree } = await github.rest.git.createTree({
+ ...repo,
+ base_tree: commit.tree.sha,
+ tree: blobs
+ });
- Here are the zoomed-in screenshots of the added icons as **SVGs**:
- {1}
+ const { data: newCommit } = await github.rest.git.createCommit({
+ ...repo,
+ message: `screenshots: add PR #${prNum} previews`,
+ tree: tree.sha,
+ parents: [branchSha]
+ });
- Here are the icons that will be generated by Icomoon:
- {2}
+ await github.rest.git.updateRef({
+ ...repo,
+ ref: `heads/${branch}`,
+ sha: newCommit.sha
+ });
- Here are the zoomed-in screenshots of the added icons as **icons**:
- {3}
+ const baseUrl = `https://raw.githubusercontent.com/${repo.owner}/${repo.repo}/${branch}/pr-${prNum}`;
+ core.setOutput('base_url', baseUrl);
+ core.setOutput('files', files.join(','));
+ console.log(`Uploaded ${files.length} screenshots to ${baseUrl}`);
- Here are the colored versions:
- {4}
- {5}
+ - name: Comment on the PR - Success
+ if: env.PEEK_STATUS == 'success' && success() && steps.upload_screenshots.outputs.skipped != 'true'
+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
+ env:
+ BASE_URL: ${{ steps.upload_screenshots.outputs.base_url }}
+ FILES: ${{ steps.upload_screenshots.outputs.files }}
+ ERR_MSG: ${{ steps.err_message_reader.outputs.err_message }}
+ with:
+ script: |
+ const prNum = parseInt('${{ steps.pr_num_reader.outputs.pr_num }}');
+ const baseUrl = process.env.BASE_URL;
+ const files = process.env.FILES.split(',');
+ const errMsg = process.env.ERR_MSG || '';
- The maintainers will now check for:
- 1. The number of Glyphs matches the number of SVGs that were selected.
- 2. The icons (second group of pictures) look the same as the SVGs (first group of pictures).
- 3. The icons are of high quality (legible, matches the official logo, etc.)
- 4. A new object is added in the `devicon.json` file at the correct alphabetic position as seen [here](https://github.com/devicons/devicon/wiki/Updating-%60devicon.json%60)
+ const img = (name) => files.includes(name)
+ ? ``
+ : '_not generated_';
- In case of font issues, it might be caused by Icomoon not accepting strokes in the SVGs. Check this [doc](https://icomoon.io/#faq/importing) for more details and fix the issues as instructed by Icomoon and update this PR once you are done.
+ const imgGroup = (prefix) => files
+ .filter(f => f.startsWith(prefix))
+ .map(f => ``)
+ .join(' \n');
- Thank you for contributing to Devicon! I hope that your icons are accepted into the repository.
+ const body = [
+ 'Hi there,',
+ '',
+ "I'm Devicons' Peek Bot and I just peeked at the icons that you wanted to add using [icomoon.io](https://icomoon.io/app/#/select).",
+ '',
+ 'Here are the zoomed-in screenshots of the added icons as **SVGs**:',
+ imgGroup('new_svg_'),
+ '',
+ 'Here are the zoomed-in screenshots of the added icons as **font icons**:',
+ imgGroup('new_icon_'),
+ '',
+ 'Here are the colored versions:',
+ imgGroup('new_colored_icon_'),
+ '',
+ errMsg ? errMsg : '',
+ '',
+ 'The maintainers will now check for:',
+ '1. The number of Glyphs matches the number of SVGs that were selected.',
+ '2. The icons (second group of pictures) look the same as the SVGs (first group of pictures).',
+ '3. The icons are of high quality (legible, matches the official logo, etc.)',
+ '4. A new object is added in the `devicon.json` file at the correct alphabetic position as seen [here](https://github.com/devicons/devicon/wiki/Updating-%60devicon.json%60)',
+ '',
+ 'In case of font issues, it might be caused by Icomoon not accepting strokes in the SVGs. Check this [doc](https://icomoon.io/#faq/importing) for more details.',
+ '',
+ 'Thank you for contributing to Devicon!',
+ '',
+ 'Cheers,',
+ 'Peek Bot 😊',
+ ].join('\n');
- Note: If the images don't show up, it has been autodeleted by Imgur after 6 months due to our API choice.
+ await github.rest.issues.createComment({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: prNum,
+ body
+ });
- Cheers,
- Peek Bot :blush:
- with:
- type: create
- issue_number: ${{ steps.pr_num_reader.outputs.content }}
- token: ${{ secrets.GITHUB_TOKEN }}
- body: >
- ${{
- format(
- env.MESSAGE,
- fromJSON(steps.svgs_overview_img_step.outputs.markdown_urls)[0],
- join(fromJSON(steps.svgs_detailed_img_step.outputs.markdown_urls), ' '),
- fromJSON(steps.icons_overview_img_step.outputs.markdown_urls)[0],
- join(fromJSON(steps.icons_detailed_img_step.outputs.markdown_urls), ' '),
- join(fromJSON(steps.colored_icons_detailed_img_step.outputs.markdown_urls), ' '),
- steps.err_message_reader.outputs.content
- )
- }}
-
- - name: Comment on the PR about the result - Failure
- if: env.PEEK_STATUS == 'failure'
- uses: jungwinter/comment@v1.1.0 # let us comment on a specific PR
+ - name: Comment on the PR - Peek failure
+ if: env.PEEK_STATUS == 'failure' && success()
+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
- MESSAGE: |
- Hi there,
-
- I'm Devicons' Peek Bot and it seems we've ran into a problem.
-
- ```
- {0}
- ```
-
- Make sure that:
+ ERR_MSG: ${{ steps.err_message_reader.outputs.err_message }}
+ with:
+ script: |
+ const prNum = parseInt('${{ steps.pr_num_reader.outputs.pr_num }}');
+ const errMsg = process.env.ERR_MSG || 'Unknown error';
- - Your SVGs are named and added correctly to the /icons folder as seen [here](https://github.com/devicons/devicon/wiki/Organizing-SVGs).
- - Your icon information has been added to the `devicon.json` as seen [here](https://github.com/devicons/devicon/wiki/Updating-%60devicon.json%60)
- - Your PR title follows the format seen [here](https://github.com/devicons/devicon/wiki/Overview-on-Submitting-Icons)
+ const body = [
+ 'Hi there,',
+ '',
+ "I'm Devicons' Peek Bot and it seems we've run into a problem.",
+ '',
+ '```',
+ errMsg,
+ '```',
+ '',
+ 'Make sure that:',
+ '',
+ '- Your SVGs are named and added correctly to the /icons folder as seen [here](https://github.com/devicons/devicon/wiki/Organizing-SVGs).',
+ '- Your icon information has been added to the `devicon.json` as seen [here](https://github.com/devicons/devicon/wiki/Updating-%60devicon.json%60)',
+ '- Your PR title follows the format seen [here](https://github.com/devicons/devicon/wiki/Overview-on-Submitting-Icons)',
+ '',
+ 'I will retry once everything is fixed. If I still fail, the maintainers will investigate.',
+ '',
+ 'Best of luck,',
+ 'Peek Bot 😊',
+ ].join('\n');
- I will retry once everything is fixed. If I still fail or there are other error, the maintainers will investigate.
+ await github.rest.issues.createComment({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: prNum,
+ body
+ });
- Best of luck,
- Peek Bot :relaxed:
- with:
- type: create
- issue_number: ${{ steps.pr_num_reader.outputs.content }}
- token: ${{ secrets.GITHUB_TOKEN }}
- body: ${{ format(env.MESSAGE, steps.err_message_reader.outputs.content) }}
- - name: Comment on the PR about the result - Failure
+ - name: Comment on the PR - Workflow error
if: failure()
- uses: jungwinter/comment@v1.1.0 # let us comment on a specific PR
- env:
- MESSAGE: |
- Hi there,
+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
+ with:
+ script: |
+ let prNum;
+ try {
+ prNum = parseInt('${{ steps.pr_num_reader.outputs.pr_num }}');
+ if (!prNum) throw new Error('no pr_num');
+ } catch (e) {
+ core.warning('Could not read PR number — skipping comment');
+ return;
+ }
- I'm Devicons' Peek Bot and we've ran into a problem with the `post_peek_screenshot` workflow.
- The maintainers will take a look and fix the issue. Please wait for further instructions.
+ const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
- Thank you,
- Peek Bot :relaxed:
- with:
- type: create
- issue_number: ${{ steps.pr_num_reader.outputs.content }}
- token: ${{ secrets.GITHUB_TOKEN }}
- body: env.MESSAGE
+ await github.rest.issues.createComment({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: prNum,
+ body: [
+ 'Hi there,',
+ '',
+ "I'm Devicons' Peek Bot and we've run into a problem with the `post_peek_screenshot` workflow.",
+ `The maintainers will take a look at the [workflow run](${runUrl}) and fix the issue.`,
+ '',
+ 'Thank you,',
+ 'Peek Bot 😊',
+ ].join('\n')
+ });
diff --git a/.gitignore b/.gitignore
index 1ac6e7678e..d9a842e9a8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,3 +8,4 @@ new_icons.png
screenshots/
release_message.txt
log.txt
+log-attempt-*.txt
diff --git a/AGENTS.md b/AGENTS.md
index e47b62ba15..0b5cff90ce 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -26,7 +26,9 @@ The [wiki](https://github.com/devicons/devicon/wiki) is the source of truth for
## Branches and releases
-See [Release strategy](https://github.com/devicons/devicon/wiki/Release-strategy,-conventions,-preparation-and-execution) for which branch PRs target and how releases are built. Fonts are built by the release workflow, not in PRs.
+- One branch, `master`. PRs target it and are squash-merged, so the PR title becomes the commit message and the release-notes line.
+- Fonts and CSS aren't built in PRs. `build_weekly.yml` builds them every Monday (or when run by hand) and then releases, after a maintainer approves the `production` environment. The version bump comes from the `release: major|minor|patch` labels of the PRs merged since the last release; the check-bot sets them on icon PRs.
+- Details: [Release strategy](https://github.com/devicons/devicon/wiki/Release-strategy,-conventions,-preparation-and-execution).
## Posting on GitHub
diff --git a/README.md b/README.md
index 1db0919412..0f50e41a5a 100644
--- a/README.md
+++ b/README.md
@@ -178,12 +178,7 @@ Join the [official Discord server](https://discord.gg/hScy8KWACQ) to request ico
## Branches
-All official releases live on `master`. Everything in between (icons, features, experiments) is kept on `develop`.
-
-| Branch | Contains |
-| --- | --- |
-| `master` | The latest official release with all SVGs and built icons. Official, tested changes only. |
-| `develop` | The latest non-optimized SVGs, with no built icons for them (these are built at each release, or manually, see [Building Devicon](#building-devicon)). Experimental changes. |
+There is one branch, `master`. Pull requests target it and are squash-merged. The icon font and CSS aren't built per pull request: a weekly workflow builds them and then publishes a release, so `master` can have SVGs that aren't in the font yet. Use a [release](https://github.com/devicons/devicon/releases) or the npm package for a stable version.
## Stale Pull Requests
@@ -268,7 +263,7 @@ Build the icons and website locally, or use Gitpod to skip the setup.
[Gitpod](https://www.gitpod.io) installs the required dependencies and builds the icons in one click. No extra setup is needed.
-[](https://gitpod.io/#https://github.com/devicons/devicon/tree/develop)
+[](https://gitpod.io/#https://github.com/devicons/devicon)
> [!NOTE]
> If a command doesn't run properly on Gitpod, follow the local steps below and run them in the Gitpod terminal.
diff --git a/package.json b/package.json
index aab7b26e70..f0df5fb26e 100644
--- a/package.json
+++ b/package.json
@@ -5,7 +5,7 @@
"main": "devicon.min.css",
"scripts": {
"build-css": "gulp updateCss && gulp clean",
- "peek-test": "python ./.github/scripts/icomoon_peek.py ./.github/scripts/build_assets/geckodriver-v0.32.2-linux64/geckodriver ./icomoon.json ./devicon.json ./icons ./ --pr_title \"$PR_TITLE\"",
+ "peek-test": "python ./.github/scripts/icomoon_peek.py ./.github/scripts/build_assets/geckodriver-v0.32.2-linux64/geckodriver ./icomoon.json ./devicon.json ./icons ./ --headless",
"optimize-svg": "gulp optimizeSvg",
"bump": "gulp bumpVersion",
"build-icons": "run-script-os",