python實(shí)現(xiàn)對svn操作及信息獲取
一、實(shí)現(xiàn)效果
1、通過python獲取路徑下所有文件的svn狀態(tài)
2、通過python對svn進(jìn)行“提交、刪除、鎖、解鎖、刪除等操作”
3、通過svn打開小烏龜界面
二、完整代碼
""" SVN狀態(tài)對照表 """ class FileState: Normal = 0 # 000000 正常在svn管理下的最新的文件 RemoteLocked = 1 # 000001 云端鎖定態(tài) LocalLocked = 2 # 000010 本地鎖定態(tài) Locked = 3 # 000011 已鎖定 state and Locked == True LocalMod = 4 # 000100 本地有修改需提交 RemoteMod = 8 # 001000 遠(yuǎn)程有修改需要更新 Conflicked = 12 # 001100 沖突 state and Conflicked == Conflicked UnVersioned = 16 # 010000 未提交到庫 Error = 32 # 100000 錯誤狀態(tài)
"""
具體實(shí)現(xiàn)邏輯
"""
# -*- coding: utf-8 -*-
import os
import pprint
import subprocess
import time
from threading import Thread
from xmltodict import parse as xmlParse
def _doSvnCommandSync(args):
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
p = subprocess.Popen(
args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
startupinfo=startupinfo,
shell=True
)
rst, err = p.communicate()
try:
rst = str(rst, 'utf-8')
except:
rst = str(rst, 'gbk', errors="-ignore")
try:
err = str(err, 'utf-8')
except:
err = str(err, 'gbk', errors="-ignore")
return rst, err
def svnCommitNoUnlockSync(path, comment=""):
rst, err = _doSvnCommandSync("svn commit " + path + " -m \"" + comment + "\"" + " --no-unlock")
return rst, err
def svnCommitSync(path, comment=""):
rst, err = _doSvnCommandSync("svn commit " + path + " -m \"" + comment + "\"")
return rst, err
def _svnStatusSync(path):
rst, err = _doSvnCommandSync("svn status " + path)
if err:
return None, err
data = rst
return data, None
def svnLockSync(path):
rst, err = _doSvnCommandSync("svn lock -m '哈哈哈哈哈哈' " + path)
return rst, err
def svnAddSync(path):
data, err = _doSvnCommandSync("svn add " + path)
return data, err
def svnUnLockSync(path):
rst, err = _doSvnCommandSync("svn unlock " + path)
return rst, err
def svnDeleteSync(path):
return _doSvnCommandSync("svn delete " + path)
def _svnStatusXMLSync(path):
rst, err = _doSvnCommandSync("svn status " + path + " -u --xml")
if err:
return None, err
data = rst
data = xmlParse(data)
return data, None
def syncGetAllFileStatus(rootPath):
data, info = _svnStatusXMLSync(rootPath)
returnDict = {}
lockRole = ""
state = FileState.Normal
if info:
if data is None:
state = state | FileState.UnVersioned
else:
state = state | FileState.Error
return returnDict
target = data["status"]["target"]
if target and "entry" in target:
iterList = []
if not isinstance(target["entry"], list):
iterList.append(target["entry"])
else:
iterList = target["entry"]
for fileStatusItem in iterList:
state = FileState.Normal
filePath = fileStatusItem["@path"]
wc_status = fileStatusItem["wc-status"]
if "unversioned" == wc_status["@item"]:
state = state | FileState.UnVersioned
elif "modified" == wc_status["@item"]:
state = state | FileState.LocalMod
elif "repos-status" in fileStatusItem:
repos_status = fileStatusItem["repos-status"]
if "lock" in repos_status and "lock" not in wc_status:
info = repos_status["lock"]["owner"]
lockRole = info
state = state | FileState.RemoteLocked
elif "lock" in wc_status:
info = wc_status["lock"]["owner"]
lockRole = info
state = state | FileState.LocalLocked
elif "modified" == repos_status["@item"]:
state = state | FileState.RemoteMod
info = "%s is modified on remote, you need update first" % filePath
if "modified" == wc_status["@item"]:
state = state | FileState.LocalMod
info = "%s is modified on local, you need commit first" % filePath
returnDict[os.path.normcase(filePath)] = [state, info, lockRole]
return returnDict
def openTortoise():
pathsStr = "".join("G:\SVNCheckOut\Txt2")
cmd = "TortoiseProc.exe /command:commit /path %s" % pathsStr
p = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
shell=True
)
# class Process(subprocess.Popen):
# def register_callback(self, callback, *args, **kwargs):
#Thread(target=self._poll_completion, args=(callback, args, kwargs)).start()
#
# def _poll_completion(self, callback, args, kwargs):
#while self.poll() is None:
# time.sleep(0.1)
#callback(*args, **kwargs)
# def openTortoise():
# pathsStr = "".join("G:\SVNCheckOut\Version1")
# cmd = "TortoiseProc.exe /command:commit /path %s" % pathsStr
# handle = Process(cmd)
# handle.register_callback(MyPrint)
# def MyPrint():
# print("~~~~~~~~~~~~~~~~~")
openTortoise()
data = syncGetAllFileStatus(r"G:\SVNCheckOut\Txt2")
pprint.pprint(data)
os.system("Pause")
三、結(jié)果展示、代碼解析
1、上述代碼最終會有兩個輸出展示
a、打開小烏龜提交界面

這里對應(yīng)的其實(shí)就是 “TortoiseProc.exe /command:commit /path %s” % pathsStr" 這句命令行的運(yùn)行
b、展示SVN 文件狀態(tài)


我們需要查看上述 “svn狀態(tài)對照表”,可以發(fā)現(xiàn)狀態(tài)碼 “2、4、16” 分別對應(yīng)的就是 “本地鎖定、本地有修改、未提交到庫”,并且到文件夾中查看可知是一一對應(yīng)的
2、代碼解析
首先,我們看 “_doSvnCommandSync” 該函數(shù)的實(shí)質(zhì)就是運(yùn)行命令行
我們將svn的各種命令行傳入上述函數(shù) “_doSvnCommandSync”,以此構(gòu)造了python內(nèi)的 "提交、刪除、鎖、解鎖 等函數(shù)"
比較特殊的是 “_svnStatusXMLSync” 這個獲取svn狀態(tài)的函數(shù),因?yàn)槲覀兪菍⑵湟詘ml的格式輸出,因此要對其結(jié)構(gòu)進(jìn)行解析,“svn status " + path + " -u --xml” 這條指令能夠獲取 path路徑下所有文件的svn狀態(tài),我們在 “syncGetAllFileStatus” 函數(shù)中對其解析便可以得到我們想要的信息,包括 鎖的相關(guān)信息、提交信息、文件狀態(tài)等
以上就是python實(shí)現(xiàn)對svn操作及信息獲取的詳細(xì)內(nèi)容,更多關(guān)于python操作svn信息獲取的資料請關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信