介绍
作为一名开发人员,我最近发现自己面临着一个令人兴奋的挑战:对仍在使用 bootstrap 3 的旧版 c# .net 代码库进行现代化改造。目标很明确 - 使用最新的 bootstrap 5 加快项目速度。但是,我很快就意识到实现如此重大的飞跃可能会充满风险且耗时。
就在那时我决定采取分阶段的方法:
- 首先,从 bootstrap 3 迁移到 bootstrap 4
- 然后,一旦稳定,就从 bootstrap 4 跳转到 bootstrap 5
此策略将允许更易于管理的转换、更容易的调试以及更流畅的整体过程。今天,我很高兴分享这个旅程的第一部分 - 使用 python 脚本自动从 bootstrap 3 迁移到 4。
关于代码的注释
在深入研究之前,请务必注意,此处提供的代码是项目中使用的实际脚本的简化版本。出于明显的原因,例如专有信息和特定项目要求,我简化了这篇博文的代码。然而,该方法和核心功能仍然与现实场景中实现的非常相似。
立即学习“Python免费学习笔记(深入)”;
挑战
从 bootstrap 3 迁移到 4 涉及大量类名更改和弃用的组件。在整个项目中手动更新这些内容可能非常耗时且容易出错。这就是我们的 python 脚本的用武之地。
解决方案
我们的脚本(我们将其称为 bootstrap_migrator.py)旨在扫描您的项目文件并自动将 bootstrap 3 类名称更新为 bootstrap 4 的等效名称。它可以处理 html、razor (cshtml) 甚至 javascript 文件,使其成为满足您的迁移需求的全面解决方案。
分解代码
让我们深入了解迁移脚本的详细信息并解释每个部分。
导入所需的模块
import os
import re
我们首先导入两个基本的 python 模块:
- os:此模块提供了一种使用操作系统相关功能的方法,例如导航文件系统。
- re: 该模块提供了对python中正则表达式的支持。
主要迁移功能
def update_bootstrap_classes(content, file_type):
class_mappings = {
r'bcol-xs-(d+)b': r'col-1',
r'bcol-sm-(d+)b': r'col-sm-1',
r'bcol-md-(d+)b': r'col-md-1',
r'bcol-lg-(d+)b': r'col-lg-1',
r'bcol-xl-(d+)b': r'col-xl-1',
r'bbtn-defaultb': 'btn-secondary',
r'bimg-responsiveb': 'img-fluid',
r'bimg-circleb': 'rounded-circle',
r'bimg-roundedb': 'rounded',
r'bpanelb': 'card',
r'bpanel-headingb': 'card-header',
r'bpanel-titleb': 'card-title',
r'bpanel-bodyb': 'card-body',
r'bpanel-footerb': 'card-footer',
r'bpanel-primaryb': 'card bg-primary text-white',
r'bpanel-successb': 'card bg-success text-white',
r'bpanel-infob': 'card text-white bg-info',
r'bpanel-warningb': 'card bg-warning',
r'bpanel-dangerb': 'card bg-danger text-white',
r'bwellb': 'card card-body',
r'bthumbnailb': 'card card-body',
r'blist-inlines*>s*lib': 'list-inline-item',
r'bdropdown-menus*>s*lib': 'dropdown-item',
r'bnavs+navbars*>s*lib': 'nav-item',
r'bnavs+navbars*>s*lis*>s*ab': 'nav-link',
r'bnavbar-rightb': 'ml-auto',
r'bnavbar-btnb': 'nav-item',
r'bnavbar-fixed-topb': 'fixed-top',
r'bnav-stackedb': 'flex-column',
r'bhidden-xsb': 'd-none',
r'bhidden-smb': 'd-sm-none',
r'bhidden-mdb': 'd-md-none',
r'bhidden-lgb': 'd-lg-none',
r'bvisible-xsb': 'd-block d-sm-none',
r'bvisible-smb': 'd-none d-sm-block d-md-none',
r'bvisible-mdb': 'd-none d-md-block d-lg-none',
r'bvisible-lgb': 'd-none d-lg-block d-xl-none',
r'bpull-rightb': 'float-right',
r'bpull-leftb': 'float-left',
r'bcenter-blockb': 'mx-auto d-block',
r'binput-lgb': 'form-control-lg',
r'binput-smb': 'form-control-sm',
r'bcontrol-labelb': 'col-form-label',
r'btable-condensedb': 'table-sm',
r'bpaginations*>s*lib': 'page-item',
r'bpaginations*>s*lis*>s*ab': 'page-link',
r'bitemb': 'carousel-item',
r'bhelp-blockb': 'form-text',
r'blabelb': 'badge',
r'bbadgeb': 'badge badge-pill'
}
这个函数是我们脚本的核心。它需要两个参数:
- content:我们正在更新的文件的内容。
- file_type:我们正在处理的文件类型(html、js 等)。
class_mappings 字典至关重要。它将 bootstrap 3 类模式(作为正则表达式)映射到 bootstrap 4 的等效项。例如,col-xs-* 在 bootstrap 4 中变成了 col-*。
替换 html 和 razor 文件中的类
def replace_class(match):
classes = match.group(1).split()
updated_classes = []
for cls in classes:
replaced = false
for pattern, replacement in class_mappings.items():
if re.fullmatch(pattern, cls):
updated_cls = re.sub(pattern, replacement, cls)
updated_classes.append(updated_cls)
replaced = true
break
if not replaced:
updated_classes.append(cls)
return f'class="{" ".join(updated_classes)}"'
if file_type in ['cshtml', 'html']:
return re.sub(r'class="([^"]*)"', replace_class, content)
这部分处理 html 和 razor 文件中类的替换:
- 它找到 html 中的所有类属性。
- 对于找到的每个类,它会检查它是否与我们的 bootstrap 3 模式中的任何一个匹配。
- 如果找到匹配项,它将用 bootstrap 4 的等效类替换该类。
- 不匹配任何模式的类保持不变。
更新 javascript 选择器
def replace_js_selectors(match):
full_match = match.group(0)
method = match.group(1)
selector = match.group(2)
classes = re.findall(r'.[-w]+', selector)
for i, cls in enumerate(classes):
cls = cls[1:]
for pattern, replacement in class_mappings.items():
if re.fullmatch(pattern, cls):
new_cls = re.sub(pattern, replacement, cls)
classes[i] = f'.{new_cls}'
break
updated_selector = selector
for old_cls, new_cls in zip(re.findall(r'.[-w]+', selector), classes):
updated_selector = updated_selector.replace(old_cls, new_cls)
return f"{method}('{updated_selector}')"
if file_type == 'js':
js_jquery_methods = [
'queryselector', 'queryselectorall', 'getelementbyid', 'getelementsbyclassname',
'$', 'jquery', 'find', 'children', 'siblings', 'parent', 'closest', 'next', 'prev',
'addclass', 'removeclass', 'toggleclass', 'hasclass'
]
method_pattern = '|'.join(map(re.escape, js_jquery_methods))
content = re.sub(rf"({method_pattern})s*(s*['"]([^'"]+)['"]s*)", replace_js_selectors, content)
return content
本节处理更新 javascript 文件中的类名:
- 它定义了可能使用类选择器的常见 javascript 和 jquery 方法的列表。
- 然后使用正则表达式查找这些方法调用并更新其选择器中的类名称。
- 它还更新了 jquery 的 .css() 方法调用中使用的类名。
处理单个文件
def process_file(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
file_type = file_path.split('.')[-1].lower()
updated_content = update_bootstrap_classes(content, file_type)
if content != updated_content:
with open(file_path, 'w', encoding='utf-8') as file:
file.write(updated_content)
print(f"updated: {file_path}")
else:
print(f"no changes: {file_path}")
except exception as e:
print(f"error processing {file_path}: {str(e)}")
此函数处理单个文件的处理:
- 它读取文件的内容。
- 根据扩展名确定文件类型。
- 调用update_bootstrap_classes更新内容。
- 如果进行了更改,它将更新的内容写回到文件中。
- 它还处理异常并提供流程反馈。
主要功能
def main():
project_dir = input("enter the path to your project directory: ")
print(f"scanning directory: {project_dir}")
if not os.path.exists(project_dir):
print(f"the directory {project_dir} does not exist.")
return
files_found = false
for root, dirs, files in os.walk(project_dir):
for file in files:
if file.endswith(('.cshtml', '.html', '.js')):
files_found = true
file_path = os.path.join(root, file)
print(f"processing file: {file_path}")
process_file(file_path)
if not files_found:
print("no .cshtml, .html, or .js files found in the specified directory.")
if __name__ == "__main__":
main()
主要功能将所有内容联系在一起:
- 它提示用户输入项目目录。
- 然后它会遍历目录,查找所有相关文件(.cshtml、.html、.js)。
- 对于找到的每个文件,它都会调用 process_file 来更新其内容。
- 它提供有关过程的反馈,包括是否未找到相关文件。
主要特征
- 全面的类更新:从网格类到特定于组件的类,脚本涵盖了广泛的 bootstrap 更改。
- javascript 支持:它更新各种 javascript 和 jquery 选择器中的类名称,确保您的动态内容不会中断。
- 灵活性:脚本可以轻松扩展以包含更多类映射或文件类型。
- 非破坏性:它只修改需要更改的文件,而不影响其他文件。
使用脚本
要使用该脚本,只需运行它并在出现提示时提供项目目录的路径即可。然后它将处理所有相关文件,并根据需要更新它们。
python bootstrap_migrator.py
限制和注意事项
虽然此脚本自动执行了迁移过程的很大一部分,但值得注意的是,它不是一个完整的解决方案。你仍然应该:
- 运行脚本后彻底测试您的应用程序。
- 注意 bootstrap 4 可能需要手动实现的新组件和功能。
- 检查可能与 bootstrap 类交互的自定义 css 和 javascript。
结论
此脚本提供了一种强大的自动化方法来处理 bootstrap 3 到 4 迁移过程的大部分,从而节省开发人员大量时间并减少手动错误的机会。它代表了我们对遗留 c# .net 代码库进行现代化改造的第一步。一旦我们成功迁移到 bootstrap 4 并确保稳定性,我们将处理下一阶段:从 bootstrap 4 迁移到 5。
请记住,虽然自动化非常有用,但它并不能替代理解 bootstrap 版本之间的变化。使用此脚本作为迁移过程中的强大帮助,但始终将其与您的专业知识和彻底的测试结合起来。
迁移快乐!