Skip to content

Commit

Permalink
修复错误,优化代码
Browse files Browse the repository at this point in the history
  • Loading branch information
chenmozhijin committed Sep 22, 2024
1 parent 91bfaf2 commit b109d75
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 26 deletions.
11 changes: 5 additions & 6 deletions build_helper/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from actions_toolkit import core

from .utils.error import ConfigParseError, PrePareError
from .utils.logger import debug, logger
from .utils.upload import uploader
from .utils.utils import setup_env
Expand All @@ -28,17 +29,15 @@ def main() -> None:
setup_env()
try:
configs = parse_configs()
if not configs:
core.set_failed("未找到任何可用的配置")
except Exception as e:
logger.exception("解析配置时出错")
core.set_failed(f"解析配置时出错: {e.__class__.__name__}: {e!s}")
msg = f"解析配置时出错: {e.__class__.__name__}: {e!s}"
raise ConfigParseError(msg) from e
try:
prepare(configs)
core.set_output("matrix", get_matrix(configs))
except Exception as e:
logger.exception("准备时出错")
core.set_failed(f"准备时出错: {e.__class__.__name__}: {e!s}")
msg = f"准备时出错: {e.__class__.__name__}: {e!s}"
raise PrePareError(msg) from e
case "build-prepare":
from .build import prepare
prepare(config)
Expand Down
6 changes: 3 additions & 3 deletions build_helper/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def base_builds(cfg: dict) -> None:
tmp_ccache_path = None
if os.path.exists(ccache_path):
tmp_ccache_path = paths.get_tmpdir()
shutil.move(ccache_path, tmp_ccache_path.name)
os.replace(ccache_path, tmp_ccache_path.name)

logger.info("修改配置(设置编译所有kmod)...")
openwrt.enable_kmods(cfg["compile"]["kmod_compile_exclude_list"])
Expand All @@ -123,9 +123,9 @@ def base_builds(cfg: dict) -> None:
openwrt.make("toolchain/install")

logger.info("开始编译内核...")
openwrt.make("clean")
if tmp_ccache_path:
shutil.move(tmp_ccache_path.name, ccache_path)
os.replace(tmp_ccache_path.name, ccache_path)
tmp_ccache_path.cleanup()
openwrt.make("target/compile")

logger.info("归档文件...")
Expand Down
14 changes: 10 additions & 4 deletions build_helper/prepare.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
from typing import TYPE_CHECKING, Any

import pygit2
from actions_toolkit import core

from .utils.error import ConfigError, ConfigParseError
from .utils.logger import logger
from .utils.network import dl2, get_gh_repo_last_releases, request_get, wait_dl_tasks
from .utils.openwrt import OpenWrt
Expand All @@ -33,7 +33,8 @@ def parse_configs() -> dict[str, dict[str, Any]]:
configs[name] = {"path": path}
k_config_path = os.path.join(path, "OpenWrt-K")
if not os.path.isdir(k_config_path):
core.set_failed(f"未找到配置{name}的openwrt文件夹: {k_config_path}")
msg = f"未找到配置{name}的openwrt文件夹: {k_config_path}"
raise NotADirectoryError(msg)

configs[name]["compile"] = parse_config(os.path.join(k_config_path, "compile.config"),
("openwrt_tag/branch", "kmod_compile_exclude_list", "use_cache"))
Expand All @@ -55,12 +56,14 @@ def parse_configs() -> dict[str, dict[str, Any]]:
keys = ("NAME", "PATH", "REPOSITORIE", "BRANCH")
for key in keys:
if key not in pkg:
core.set_failed(f"配置{name}的extpackages{i}缺少{key}")
msg = f"配置{name}的extpackages{i}缺少{key}"
raise ConfigParseError(msg)
pkg_name = pkg["NAME"]
if name not in configs[name]["extpackages"]:
configs[name]["extpackages"][pkg["NAME"]] = {k:v for k, v in pkg.items() if k != "NAME"}
else:
core.set_failed(f"配置{name}的extpackages中存在重复的包名: {pkg_name}")
msg = f"配置{name}的extpackages中存在重复的包名: {pkg_name}"
raise ConfigParseError(msg)

configs[name]["openwrt"] = ""
for file in os.listdir(path):
Expand All @@ -69,6 +72,9 @@ def parse_configs() -> dict[str, dict[str, Any]]:
configs[name]["openwrt"] += f.read() + "\n"
if configs[name]["compile"]["use_cache"] is True:
configs[name]["openwrt"] += "CONFIG_DEVEL=y\nCONFIG_CCACHE=y"
if not configs:
msg = "没有找到任何可用配置文件"
raise ConfigError(msg)
return configs

def get_matrix(configs: dict[str, dict]) -> str:
Expand Down
13 changes: 13 additions & 0 deletions build_helper/utils/error.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# SPDX-FileCopyrightText: Copyright (c) 2024 沉默の金 <cmzj@cmzj.org>
# SPDX-License-Identifier: MIT
class ConfigError(Exception):
pass

class ConfigParseError(ConfigError):
pass

class ConfigNotFoundError(ConfigError):
pass

class PrePareError(Exception):
pass
14 changes: 7 additions & 7 deletions build_helper/utils/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from actions_toolkit import core
import tempfile

from .error import ConfigError
class Paths:

def __init__(self) -> None:
Expand All @@ -27,15 +27,15 @@ def configs(self) -> dict[str, str]:
from .utils import parse_config
config_names = parse_config(self.global_config, ["config"])['config']
if not isinstance(config_names, list) or len(config_names) == 0:
core.set_failed("没有获取到任何配置")
raise ConfigError("没有获取到任何配置")
for config in config_names:
path = os.path.join(self.root, "config", config)
if os.path.isdir(path):
configs[config] = os.path.join(self.root, "config", config)
else:
core.warning(f"配置 {config} 不存在")
except Exception as e:
core.set_failed(f"获取配置时出错: {e.__class__.__name__}: {e!s}")
raise ConfigError(f"获取配置时出错: {e.__class__.__name__}: {e!s}") from e
return configs

@property
Expand All @@ -44,7 +44,7 @@ def workdir(self) -> str:
if not os.path.exists(workdir):
os.makedirs(workdir)
elif not os.path.isdir(workdir):
core.set_failed(f"工作区路径 {workdir} 不是一个目录")
raise NotADirectoryError(f"工作区路径 {workdir} 不是一个目录")
return workdir

@property
Expand All @@ -53,7 +53,7 @@ def uploads(self) -> str:
if not os.path.exists(uploads):
os.makedirs(uploads)
elif not os.path.isdir(uploads):
core.set_failed(f"上传区路径 {uploads} 不是一个目录")
raise NotADirectoryError(f"上传区路径 {uploads} 不是一个目录")
return uploads

@property
Expand All @@ -66,15 +66,15 @@ def errorinfo(self) -> str:
if not os.path.exists(errorinfo):
os.makedirs(errorinfo)
elif not os.path.isdir(errorinfo):
core.set_failed(f"错误信息路径 {errorinfo} 不是一个目录")
raise NotADirectoryError(f"错误信息路径 {errorinfo} 不是一个目录")
return errorinfo

def get_tmpdir(self) -> tempfile.TemporaryDirectory:
tmpdir = os.path.join(self.root, "tmp")
if not os.path.exists(tmpdir):
os.makedirs(tmpdir)
elif not os.path.isdir(tmpdir):
core.set_failed(f"临时目录 {tmpdir} 不是一个目录")
raise NotADirectoryError(f"临时目录 {tmpdir} 不是一个目录")
return tempfile.TemporaryDirectory(dir=tmpdir)


Expand Down
2 changes: 1 addition & 1 deletion build_helper/utils/upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def add(self,

def save(self) -> None:
if self.action['runs']['steps']:
logger.debug("Save UpLoad Action file to %s0", self.action_file)
logger.debug("Save UpLoad Action file to %s", self.action_file)
with open(self.action_file, 'w', encoding='utf-8') as file:
yaml.dump(self.action, file, allow_unicode=True, sort_keys=False)

Expand Down
10 changes: 5 additions & 5 deletions build_helper/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@
import shutil
import subprocess

from actions_toolkit import core

from .error import ConfigParseError
from .logger import logger
from .paths import paths


def parse_config(path: str, prefixs: tuple[str,...]|list[str]) -> dict[str, str | list[str] | bool]:
if not os.path.isfile(path):
core.set_failed(f"配置文件 {path} 不存在")
msg = f"配置文件 {path} 不存在"
raise ConfigParseError(msg)

config = {}
with open(path, encoding="utf-8") as f:
Expand All @@ -33,7 +33,8 @@ def parse_config(path: str, prefixs: tuple[str,...]|list[str]) -> dict[str, str
config[prefix] = content
break
else:
core.set_failed(f"无法在配置文件 {path} 中找到配置项{prefix}")
msg = f"无法在配置文件 {path} 中找到配置项{prefix}"
raise ConfigParseError(msg)
return config


Expand Down Expand Up @@ -125,7 +126,6 @@ def apt(*args: str) -> None:
sudo("chown", "-R", "runner:runner", paths.root)

if not os.path.exists(os.path.join(paths.root, ".github")):
os.makedirs(os.path.join(paths.root, ".github"))
os.symlink(os.path.join(paths.openwrt_k, ".github"), os.path.join(paths.root, ".github"))
# 打印剩余空间
total, used, free = shutil.disk_usage(paths.root)
Expand Down

0 comments on commit b109d75

Please sign in to comment.