iT邦幫忙

2024 iThome 鐵人賽

DAY 4
0
DevOps

將 AI Code Review 整進 CICD系列 第 4

將 AI Code Review 整進 CICD Day4

  • 分享至 

  • xImage
  •  

當工程師就是會有撞牆 debug 的時候Q

我設定 cicd variables

https://ithelp.ithome.com.tw/upload/images/20240818/20118525Tp1PhXbJDO.png


[gitlab]
# Gitlab personal access token
personal_access_token = ${PERSONAL_ACCESS_KEY}

[openai]
key = "$OPEN_AI_TOKEN" 

引用的方式

  • gitlab_provider.py
from ..config_loader import get_settings

gitlab_access_token = get_settings().get("GITLAB.PERSONAL_ACCESS_TOKEN", None)-
  • config_loader
def get_settings():
    """
    Retrieves the current settings.

    This function attempts to fetch the settings from the starlette_context's context object. If it fails,
    it defaults to the global settings defined outside of this function.

    Returns:
        Dynaconf: The current settings object, either from the context or the global default.
    """
    try:
        return context["settings"]
    except Exception:
        return global_settings
  • global_settings
current_dir = dirname(abspath(__file__))
global_settings = Dynaconf(
    envvar_prefix=False,
    merge_enabled=True,
    settings_files=[join(current_dir, f) for f in [
        "settings/.secrets.toml",
        "settings/configuration.toml",
        "settings/ignore.toml",
        "settings/language_extensions.toml",
        "settings/pr_reviewer_prompts.toml",
        "settings/pr_questions_prompts.toml",
        "settings/pr_line_questions_prompts.toml",
        "settings/pr_description_prompts.toml",
        "settings/pr_code_suggestions_prompts.toml",
        "settings/pr_code_suggestions_reflect_prompts.toml",
        "settings/pr_sort_code_suggestions_prompts.toml",
        "settings/pr_information_from_user_prompts.toml",
        "settings/pr_update_changelog_prompts.toml",
        "settings/pr_custom_labels.toml",
        "settings/pr_add_docs.toml",
        "settings_prod/.secrets.toml",
        "settings/custom_labels.toml"
    ]]
)

實際做個小實驗

a = "$TEST1"
b = "$TEST2"
c = "$PERSONAL_ACCESS_KEY"
import os
import toml
from os.path import abspath, dirname, join

from dynaconf import Dynaconf
current_dir = dirname(abspath(__file__))

global_settings = Dynaconf(
    envvar_prefix=False,
    merge_enabled=True,
    settings_files=[join(current_dir, f) for f in [
        "test.toml"
    ]]
)

# 打印設置內容
print("配置內容:")
for key in global_settings.keys():
    print(f"{key}: {global_settings.get(key)}")

我們發現印出來是失敗的

A: $TEST1
B: $TEST2
C: $PERSONAL_ACCESS_KEY

但如果使用 toml 的解析

import os
import toml
from os.path import abspath, dirname, join

current_dir = dirname(abspath(__file__))

# 讀取 test.toml 文件
test_toml_path = join(current_dir, "test.toml")
try:
    with open(test_toml_path, 'r') as f:
        test_config = toml.load(f)

    # 解析環境變數
    for key, value in test_config.items():
        if isinstance(value, str) and value.startswith('$'):
            test_config[key] = os.getenv(value[1:], value)  # 如果環境變數不存在,保留原值

    # 打印解析後的配置
    print("test.toml 配置:")
    print(test_config)
except FileNotFoundError:
    print(f"找不到 test.toml 文件: {test_toml_path}")
except Exception as e:
    print(f"讀取 test.toml 時發生錯誤: {str(e)}")

卻可以得到值,原因是使用 Dynaconf 的方法: Dynaconf 是一個更高級的配置管理工具。默認情況下,它不會自動替換以 $ 開頭的值為環境變量。這是為了安全性和靈活性考慮的。而直接使用 toml 庫的方法: 在這種方法中,您手動讀取 TOML 文件,然後顯式地使用 os.getenv() 來替換環境變量。這種方法直接且靈活,允許您完全控制環境變量的解析和替換過程。

  1. 直接使用 toml 庫的方法更直接,但需要您手動處理環境變量。

  2. Dynaconf 提供了更強大和靈活的配置管理,但需要特定的語法和設置來處理環境變量。

  3. 通過自定義加載器,您可以讓 Dynaconf 的行為更接近於直接使用 toml 庫的方法。

選擇哪種方法取決於您的具體需求和項目的複雜度。如果您的配置需求相對簡單,直接使用 toml 可能更直接。如果您需要更複雜的配置管理(如多環境支持、動態重載等),Dynaconf 可能是更好的選擇。

我們有兩種方式將變數帶入,比較簡單的一種是變數加上 format

a = "@format {env[TEST1]}"

上一篇
將 AI Code Review 整進 CICD Day3
下一篇
將 AI Code Review 整進 CICD Day5
系列文
將 AI Code Review 整進 CICD24
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言