097. 编写一个函数,实现简单的版本控制工具
097. 编写一个函数,实现简单的版本控制工具
实现一个简单的版本控制工具可以让我们更好地理解版本控制系统的工作原理。虽然完整的版本控制系统(如 Git)非常复杂,但我们可以编写一个简化版的版本控制工具,实现基本的功能,例如:
- 初始化版本库:创建一个版本控制目录,用于存储版本信息。
- 添加文件到版本库:将文件的当前状态保存到版本库中。
- 提交更改:记录文件的更改并保存到版本库。
- 查看历史记录:显示文件的版本历史。
- 回滚到特定版本:将文件恢复到指定的版本。
示例代码
import os
import shutil
import datetime
import hashlib
class SimpleVersionControl:
def __init__(self, repo_path):
"""
初始化版本控制工具
:param repo_path: 版本库路径
"""
self.repo_path = repo_path
self.versions_path = os.path.join(repo_path, ".versions")
self.history_path = os.path.join(repo_path, ".history.txt")
if not os.path.exists(self.versions_path):
os.makedirs(self.versions_path)
if not os.path.exists(self.history_path):
with open(self.history_path, 'w') as history_file:
history_file.write("")
def add_file(self, file_path):
"""
添加文件到版本库
:param file_path: 文件路径
"""
if not os.path.exists(file_path):
print(f"Error: File '{
file_path}' does not exist.")
return
file_name = os.path.basename(file_path)
version_path = os.path.join(self.versions_path, file_name)
shutil.copy(file_path, version_path)
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
version_hash = self._calculate_hash(file_path)
with open(self.history_path, 'a') as history_file:
history_file.write(f"{
timestamp} | Added file: {
file_name} | Hash: {
version_hash}\n")
print(f"File '{
file_name}' added to version control.")
def commit(self, file_path, message=""):