Fixed and Added.

This commit is contained in:
Saturneric 2019-03-11 11:18:02 +08:00
parent cae87b36d3
commit 32e304e8ad
10 changed files with 370 additions and 355 deletions

4
.idea/encodings.xml generated Normal file
View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" addBOMForNewFiles="with NO BOM" />
</project>

6
.idea/giteasy.iml generated
View File

@ -1,8 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="jdk" jdkName="Python 3.7 (giteasy)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TestRunnerService">

6
.idea/vcs.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

196
.idea/workspace.xml generated
View File

@ -1,7 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="d703f139-38f3-455d-a086-a2da561870b5" name="Default Changelist" comment="" />
<list default="true" id="d703f139-38f3-455d-a086-a2da561870b5" name="Default Changelist" comment="">
<change afterPath="$PROJECT_DIR$/.idea/encodings.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/vcs.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/keygen.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/giteasy.iml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/giteasy.iml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/bin/python" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/bin/python3" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/server.py" beforeDir="false" afterPath="$PROJECT_DIR$/server.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ssh.py" beforeDir="false" afterPath="$PROJECT_DIR$/ssh.py" afterDir="false" />
</list>
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -9,52 +19,32 @@
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="CoverageDataManager">
<SUITE FILE_PATH="coverage/giteasy$Debug.coverage" NAME="Debug Coverage Results" MODIFIED="1552200896901" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="true" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
<SUITE FILE_PATH="coverage/giteasy$ssh.coverage" NAME="ssh Coverage Results" MODIFIED="1552191792390" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="true" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
<SUITE FILE_PATH="coverage/giteasy$Debug.coverage" NAME="Debug Coverage Results" MODIFIED="1552274220071" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="true" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
</component>
<component name="FUSProjectUsageTrigger">
<session id="46200952">
<usages-collector id="statistics.lifecycle.project">
<counts>
<entry key="project.closed" value="2" />
<entry key="project.open.time.11" value="2" />
<entry key="project.opened" value="2" />
</counts>
</usages-collector>
<usages-collector id="statistics.file.extensions.open">
<counts>
<entry key="py" value="2" />
</counts>
</usages-collector>
<usages-collector id="statistics.file.types.open">
<counts>
<entry key="Python" value="2" />
</counts>
</usages-collector>
<usages-collector id="statistics.file.extensions.edit">
<counts>
<entry key="dummy" value="6" />
<entry key="py" value="6153" />
</counts>
</usages-collector>
<usages-collector id="statistics.file.types.edit">
<counts>
<entry key="PLAIN_TEXT" value="6" />
<entry key="Python" value="6153" />
</counts>
</usages-collector>
</session>
<component name="DatabaseView">
<option name="SHOW_INTERMEDIATE" value="true" />
<option name="GROUP_DATA_SOURCES" value="true" />
<option name="GROUP_SCHEMA" value="true" />
<option name="GROUP_CONTENTS" value="false" />
<option name="SORT_POSITIONED" value="false" />
<option name="SHOW_EMPTY_GROUPS" value="false" />
<option name="AUTO_SCROLL_FROM_SOURCE" value="false" />
<option name="HIDDEN_KINDS">
<set />
</option>
<expand />
<select />
</component>
<component name="FileEditorManager">
<leaf SIDE_TABS_SIZE_LIMIT_KEY="300">
<file pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/server.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="79">
<caret line="122" column="43" selection-start-line="122" selection-start-column="43" selection-end-line="122" selection-end-column="43" />
<state relative-caret-position="436">
<caret line="191" column="58" selection-start-line="191" selection-start-column="58" selection-end-line="191" selection-end-column="58" />
<folding>
<element signature="e#0#15#0" expanded="true" />
<marker date="1552200895581" expanded="true" signature="87:92" ph="..." />
<element signature="e#1#10#0" expanded="true" />
</folding>
</state>
</provider>
@ -63,13 +53,19 @@
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/ssh.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="345">
<caret line="25" column="1" selection-start-line="25" selection-start-column="1" selection-end-line="25" selection-end-column="1" />
<state relative-caret-position="875">
<caret line="35" column="13" lean-forward="true" selection-start-line="35" selection-start-column="13" selection-end-line="35" selection-end-column="13" />
</state>
</provider>
</entry>
</file>
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/keygen.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="300">
<caret line="12" lean-forward="true" selection-start-line="12" selection-end-line="12" />
<folding>
<element signature="e#0#13#0" expanded="true" />
<marker date="1552191914094" expanded="true" signature="65:70" ph="..." />
<marker date="1552191914094" expanded="true" signature="137:264" ph="..." />
<marker date="1552191914094" expanded="true" signature="389:594" ph="..." />
</folding>
</state>
</provider>
@ -89,23 +85,22 @@
<find>self.remotes</find>
</findStrings>
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="IdeDocumentHistory">
<option name="CHANGED_PATHS">
<list>
<option value="$PROJECT_DIR$/main.py" />
<option value="$PROJECT_DIR$/lib/ssh.py" />
<option value="$PROJECT_DIR$/venv/ssh.py" />
<option value="$PROJECT_DIR$/ssh.py" />
<option value="$PROJECT_DIR$/keygen.py" />
<option value="$PROJECT_DIR$/server.py" />
</list>
</option>
</component>
<component name="JsBuildToolGruntFileManager" detection-done="true" sorting="DEFINITION_ORDER" />
<component name="JsBuildToolPackageJson" detection-done="true" sorting="DEFINITION_ORDER" />
<component name="JsGulpfileManager">
<detection-done>true</detection-done>
<sorting>DEFINITION_ORDER</sorting>
</component>
<component name="ProjectFrameBounds">
<component name="ProjectFrameBounds" extendedState="6">
<option name="y" value="30" />
<option name="width" value="1440" />
<option name="height" value="804" />
@ -115,7 +110,6 @@
<foldersAlwaysOnTop value="true" />
</navigator>
<panes>
<pane id="Scope" />
<pane id="ProjectPane">
<subPane>
<expand>
@ -123,13 +117,19 @@
<item name="giteasy" type="b2602c69:ProjectViewProjectNode" />
<item name="giteasy" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="giteasy" type="b2602c69:ProjectViewProjectNode" />
<item name="External Libraries" type="cb654da1:ExternalLibrariesNode" />
</path>
</expand>
<select />
</subPane>
</pane>
<pane id="Scope" />
</panes>
</component>
<component name="PropertiesComponent">
<property name="DatabaseDriversLRU" value="sqlite" />
<property name="WebServerToolWindowFactoryState" value="false" />
<property name="nodejs_interpreter_path.stuck_in_default_project" value="undefined stuck path" />
<property name="nodejs_npm_path_reset_for_default_project" value="true" />
@ -137,6 +137,8 @@
</component>
<component name="RecentsManager">
<key name="MoveFile.RECENT_KEYS">
<recent name="C:\Users\Saturneric\PycharmProjects\giteasy" />
<recent name="C:\Users\Saturneric\PycharmProjects\giteasy\bin" />
<recent name="$PROJECT_DIR$" />
</key>
</component>
@ -152,7 +154,7 @@
</list>
</option>
</component>
<component name="RunManager" selected="Python.Debug">
<component name="RunManager">
<configuration name="Debug" type="PythonConfigurationType" factoryName="Python">
<module name="giteasy" />
<option name="INTERPRETER_OPTIONS" value="" />
@ -160,13 +162,13 @@
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="/usr/local/bin/python3.7" />
<option name="SDK_HOME" value="C:\Users\Saturneric\PycharmProjects\giteasy\venv\Scripts\python.exe" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/server.py" />
<option name="SCRIPT_NAME" value="C:\Users\Saturneric\PycharmProjects\giteasy\git.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
@ -197,37 +199,6 @@
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
<configuration name="ssh" type="PythonConfigurationType" factoryName="Python" temporary="true">
<module name="giteasy" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="/usr/local/bin/python3.7" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/ssh.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="false" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
<list>
<item itemvalue="Python.Debug" />
<item itemvalue="Python.ssh" />
</list>
<recent_temporary>
<list>
<item itemvalue="Python.ssh" />
</list>
</recent_temporary>
</component>
<component name="SvnConfiguration">
<configuration />
@ -239,31 +210,36 @@
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1552027430305</updated>
<workItem from="1552263509381" duration="3100000" />
</task>
<servers />
</component>
<component name="TimeTrackingManager">
<option name="totallyTimeSpent" value="3100000" />
</component>
<component name="ToolWindowManager">
<frame x="0" y="30" width="1440" height="804" extended-state="0" />
<frame x="-8" y="-8" width="1936" height="1056" extended-state="6" />
<editor active="true" />
<layout>
<window_info id="Favorites" order="0" side_tool="true" />
<window_info content_ui="combo" id="Project" order="1" visible="true" weight="0.19170243" />
<window_info content_ui="combo" id="Project" order="1" visible="true" weight="0.14285715" />
<window_info id="Structure" order="2" side_tool="true" weight="0.25" />
<window_info anchor="bottom" id="Database Changes" order="0" show_stripe_button="false" />
<window_info anchor="bottom" id="Terminal" order="1" />
<window_info anchor="bottom" id="Event Log" order="2" sideWeight="0.5007153" side_tool="true" weight="0.26404494" />
<window_info anchor="bottom" id="Version Control" order="3" show_stripe_button="false" />
<window_info anchor="bottom" id="Event Log" order="2" sideWeight="0.5010661" side_tool="true" weight="0.2635575" />
<window_info anchor="bottom" id="Version Control" order="3" />
<window_info anchor="bottom" id="Python Console" order="4" weight="0.3286517" />
<window_info anchor="bottom" id="Docker" order="5" show_stripe_button="false" />
<window_info anchor="bottom" id="Message" order="6" />
<window_info anchor="bottom" id="Find" order="7" />
<window_info anchor="bottom" id="Run" order="8" sideWeight="0.49928468" weight="0.26404494" />
<window_info anchor="bottom" id="Find" order="7" weight="0.329718" />
<window_info active="true" anchor="bottom" id="Run" order="8" sideWeight="0.4989339" visible="true" weight="0.2635575" />
<window_info anchor="bottom" id="Debug" order="9" weight="0.30758426" />
<window_info anchor="bottom" id="Cvs" order="10" weight="0.25" />
<window_info anchor="bottom" id="Inspection" order="11" weight="0.4" />
<window_info anchor="bottom" id="TODO" order="12" />
<window_info anchor="right" id="Database" order="0" />
<window_info anchor="right" id="Database" order="0" weight="0.21588486" />
<window_info anchor="right" id="Commander" internal_type="SLIDING" order="1" type="SLIDING" weight="0.4" />
<window_info anchor="right" id="SciView" order="2" />
<window_info anchor="right" id="SciView" order="2" weight="0.21695095" />
<window_info anchor="right" id="Ant Build" order="3" weight="0.25" />
<window_info anchor="right" content_ui="combo" id="Hierarchy" order="4" weight="0.25" />
</layout>
@ -271,9 +247,6 @@
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="1" />
</component>
<component name="VcsContentAnnotationSettings">
<option name="myLimit" value="2678400000" />
</component>
<component name="XDebuggerManager">
<breakpoint-manager>
<default-breakpoints>
@ -286,30 +259,29 @@
</breakpoint-manager>
</component>
<component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/server.py">
<entry file="file://$PROJECT_DIR$/ssh.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="79">
<caret line="122" column="43" selection-start-line="122" selection-start-column="43" selection-end-line="122" selection-end-column="43" />
<state relative-caret-position="875">
<caret line="35" column="13" lean-forward="true" selection-start-line="35" selection-start-column="13" selection-end-line="35" selection-end-column="13" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/keygen.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="300">
<caret line="12" lean-forward="true" selection-start-line="12" selection-end-line="12" />
<folding>
<element signature="e#0#15#0" expanded="true" />
<marker date="1552200895581" expanded="true" signature="87:92" ph="..." />
<marker date="1552200895581" expanded="true" signature="1551:7243" ph="..." />
<marker date="1552200895581" expanded="true" signature="1596:1605" ph="..." />
<marker date="1552200895581" expanded="true" signature="4928:5204" ph="..." />
<marker date="1552200895581" expanded="true" signature="5502:5669" ph="..." />
<element signature="e#0#13#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/ssh.py">
<entry file="file://$PROJECT_DIR$/server.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="345">
<caret line="25" column="1" selection-start-line="25" selection-start-column="1" selection-end-line="25" selection-end-column="1" />
<state relative-caret-position="436">
<caret line="191" column="58" selection-start-line="191" selection-start-column="58" selection-end-line="191" selection-end-column="58" />
<folding>
<element signature="e#0#13#0" expanded="true" />
<marker date="1552191914094" expanded="true" signature="65:70" ph="..." />
<marker date="1552191914094" expanded="true" signature="137:264" ph="..." />
<marker date="1552191914094" expanded="true" signature="389:594" ph="..." />
<element signature="e#1#10#0" expanded="true" />
</folding>
</state>
</provider>

Binary file not shown.

Binary file not shown.

198
git.py Normal file
View File

@ -0,0 +1,198 @@
import re
import os
import ssh
class Git(ssh.SSH):
projects = {}
projects_list = []
remotes = {}
def __init__(self, hostname, path, user, passwd):
super().__init__(hostname, path, user, passwd)
self.base_path = [False]
self.connect(5)
self.local_path = None
self.fix_cmd = None
self.fix_name = None
self.git_user = None
self.git_email = None
def global_init(self, git_user, git_email):
self.git_user = git_user
self.git_email = git_email
cmd = "git config --global user.email \"{0}\";".format(git_email)
cmd += "git config --global user.name \"{0}\";".format(git_user)
stdout, stderr = self.run(cmd)
if self.check_error(stderr):
print("Global setting successful.")
else:
print(stderr)
raise ValueError("Args Abnormal")
def base_init(self):
stdout, stderr = self.run("ls {}".format(self.path))
if self.check_error(stderr):
if "giteasy\n" in stdout:
print("Directory already found.")
else:
stdout, stderr = self.run("mkdir {0}/{1}".format(self.path, "giteasy"))
if self.check_error(stderr):
print("Create directory.")
else:
raise ValueError(stderr)
self.base_path = [True, "{0}/{1}".format(self.path, "giteasy")]
else:
raise ValueError("Home Path Abnormal")
def create_project(self, name):
if self.base_path[0]:
stdout, stderr = self.run("mkdir {0}/{1}".format(self.base_path[1], name))
if self.check_error(stderr):
print("Succeed In Making Directory.")
self.projects[name] = {"path": "{0}/{1}".format(self.base_path[1], name), "branch": []}
cmd = "cd {0};".format(self.projects[name]["path"])
cmd += "git init;"
cmd += "touch ReadME.md;"
cmd += "git add *;"
cmd += "git commit --message=init;"
stdout, stderr = self.run(cmd)
if self.check_error(stderr):
print("Succeed In Getting Repository.")
else:
print(stderr)
raise ValueError("Target Path Abnormal")
else:
raise ValueError("Base Path Abnormal")
else:
raise UnboundLocalError("Init Base First")
def init_project_local(self, name):
cmd = self.fix_cmd
cmd += "mkdir {0};".format(name)
cmd += "git init;"
cmd = "git config --global user.email \"{0}\";".format(self.git_email)
cmd += "git config --global user.name \"{0}\";".format(self.git_user)
os.popen(cmd)
def update_projects(self):
if self.base_path[0]:
stdout, stderr = self.run("ls {0}".format(self.base_path[1]))
if self.check_error(stderr):
reform = re.compile("\w+")
for project in stdout:
print("PROJECT", project)
project_name = reform.match(project).string.strip('\n')
self.projects[project_name] = {"path": "{0}/{1}".format(self.base_path[1], project_name),
"branch": []}
else:
raise ValueError("Base Path Abnormal")
self.list_projects()
else:
raise UnboundLocalError("Init Base First")
def list_projects(self):
for project in self.projects.keys():
self.projects_list.append(project)
print(project)
def set_local(self, path):
self.remotes = {}
self.local_path = path
os.chdir(self.local_path)
def add_remote(self, name="origin"):
os.popen(
"git remote add {3} ssh://{0}@{1}:{2}/{4}/.git".format(self.user, self.hostname, self.base_path[1], name,
self.fix_name))
self.remotes[name] = {"name": name,
"url": "ssh://{0}@{1}:{2}/{3}/.git".format(self.user, self.hostname, self.base_path[1],
self.fix_name)}
def fetch_remote(self, name):
if name in self.remotes.keys():
os.popen("git fetch {0}".format(name))
def get_remote(self):
ret_code = re.compile(r"[\t, ]")
for remote in os.popen("git remote -v").readlines():
results = ret_code.split(remote)
for item in results:
if item[0] not in self.remotes.keys():
self.remotes[item[0]] = {"name": item[0], "url": item[1]}
def push_remote(self, name, branch):
if branch in self.projects[self.fix_name]["branch"] and name in self.remotes.keys():
os.popen("git push {0} {1}".format(name, branch))
else:
raise ValueError("Branch or Name Abnormal")
def pull_remote(self, name, branch):
if name in self.remotes.keys():
os.popen("git pull {0} {1}".format(name, branch))
else:
raise ValueError("Remote Error")
def fix(self, name):
if name in self.projects_list:
self.fix_name = name
stdout, stderr = self.run("cd {0}".format(self.projects[name]["path"]))
if self.check_error(stderr):
print("Fixed.")
self.fix_cmd = "cd {0}".format(self.projects[name]["path"]) + ";"
else:
raise ValueError("Project Path Abnormal")
def commit(self, message):
if self.base_path[0]:
stdout, stderr = self.run(self.fix_cmd + "git commit --message={0}".format(message))
if self.check_error(stderr):
print(stdout)
else:
raise ValueError(stderr)
else:
raise UnboundLocalError("Init Base First")
def get_branch(self):
if self.base_path[0] and self.fix_name is None:
stdout, stderr = self.run(self.fix_cmd + "git branch")
if self.check_error(stderr):
reform = re.compile("\w+")
for branch in stdout:
branch_name = reform.search("*master").group().strip('\n')
self.projects[self.fix_name]["branch"].append(branch_name)
if '*' in str(branch):
self.projects[self.fix_name]["active_branch"] = branch_name
else:
print(stderr)
raise ValueError("Command Error")
def list_branch(self):
for project in self.projects.items():
for branch in project[1]["branch"]:
if branch == project[1]["active_branch"]:
print("(*)", branch)
else:
print(" ", branch)
if __name__ == "__main__":
compute = Git("compute.bktus.com", "/home/git", "git", "123456")
compute.global_init(git_user="saturneric", git_email="eric.bktu@gmail.com")
compute.base_init()
# compute.create_project("lcs")
compute.update_projects()
compute.list_projects()
compute.fix("lcs")
# compute.get_branch("lcs")
compute.set_local("C:/Users/Saturneric/Documents/Code/")
compute.init_project_local("test")
# compute.add_remote();
# compute.get_remote()
# compute.get_branch()
# compute.list_branch()
print(compute.projects)

31
keygen.py Normal file
View File

@ -0,0 +1,31 @@
import git
import subprocess
import os
import ssh
class Key(ssh.SSH):
def __init__(self,hostname, path, user, password=None, ssh_key=False):
super().__init__(hostname=hostname, path=path, user=user, passwd=password, ssh_key=ssh_key)
self.connect(5)
self.pub_key = None
self.keygen = None
def add_key(self):
self.run("echo \"{0}\" >> ~/.ssh/authorized_keys".format(self.pub_key))
def create_key(self):
ret_code = subprocess.Popen(["ssh-keygen", "-b 4096", "-t rsa"], shell=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = ret_code.communicate(input=b"\ny \n \n \n")
self.get_key()
def get_key(self):
self.pub_key = os.popen("cat ~/.ssh/id_rsa.pub").read()
if __name__ == "__main__":
new_key = Key("compute.bktus.com", "/home/git", "git", "123456", ssh_key=False)
# new_key.create_key()
# new_key.get_key()
# new_key.add_key()

219
server.py
View File

@ -1,219 +0,0 @@
import paramiko
import re
import os
class ssh(object):
ssh = paramiko.SSHClient();
def __init__(self, hostname, path, user, passwd=None, sshkey=False):
self.hostname = hostname;
self.path = path;
self.user = user;
self.sshkey = sshkey;
if sshkey == True:
self.passwd = None;
self.key = paramiko.RSAKey.from_private_key_file('/Users/huyibing/.ssh/id_rsa')
else:
self.passwd = passwd;
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def close(self):
self.ssh.close();
def run(self, cmd):
print("CMD:", cmd)
stdin, stdout, stderr = self.ssh.exec_command(cmd)
stdout = list(stdout);
stderr = list(stderr);
return stdout, stderr;
def check_error(self, stderr):
if len(stderr) == 0:
return True
else:
return False
def connect(self,timeout):
if self.sshkey:
self.ssh.connect(hostname=self.hostname, port=22, username=self.user, pkey=self.key, timeout=timeout);
else:
self.ssh.connect(hostname=self.hostname, port=22, username=self.user, password=self.passwd, timeout=timeout);
def __del__(self):
self.close();
class git(ssh):
projects = {}
projects_list = []
remotes = {}
fix_name = None;
def __init__(self, hostname, path, user, passwd):
super().__init__(hostname, path, user, passwd);
self.base_path = [False];
self.connect(5);
def globalinit(self,git_user,git_email):
cmd = "git config --global user.email \"{0}\";".format(git_email);
cmd += "git config --global user.name \"{0}\";".format(git_user);
stdout, stderr = self.run(cmd)
if self.check_error(stderr):
print("Global setting successful.")
else:
print(stderr)
raise ValueError("Args Abnormal")
def baseinit(self):
stdout, stderr = self.run("ls {}".format(self.path))
if self.check_error(stderr):
if "giteasy\n" in stdout:
print("Directory already found.")
else:
stdout, stderr = self.run("mkdir {0}/{1}".format(self.path, "giteasy"))
print("Create directory.")
self.base_path = [True,"{0}/{1}".format(self.path, "giteasy")]
else:
raise ValueError("Home Path Abnormal")
def create_project(self,name):
if self.base_path[0]:
stdout, stderr = self.run("mkdir {0}/{1}".format(self.base_path[1],name))
if self.check_error(stderr):
print("Succeed In Making Directory.")
self.projects[name] = {"path" : "{0}/{1}".format(self.base_path[1],name), "branch" : []}
cmd = "cd {0};".format(self.projects[name]["path"]);
cmd += "git init;";
cmd += "touch ReadME.md;";
cmd += "git add *;"
cmd += "git commit --message=init;";
stdout, stderr = self.run(cmd)
if self.check_error(stderr):
print("Succeed In Getting Repository.")
else:
print(stderr)
raise ValueError("Target Path Abnormal")
else:
raise ValueError("Base Path Abnormal")
else:
raise UnboundLocalError("Init Base First")
def update_projects(self):
if self.base_path[0]:
stdout, stderr = self.run("ls {0}".format(self.base_path[1]))
if self.check_error(stderr):
reform = re.compile("\w+")
for project in stdout:
print("PROJECT",project)
project_name = reform.match(project).string.strip('\n')
self.projects[project_name] = {"path" : "{0}/{1}".format(self.base_path[1],project_name), "branch" : []}
else:
raise ValueError("Base Path Abnormal")
self.list_projects();
else:
raise UnboundLocalError("Init Base First")
def list_projects(self):
for project in self.projects.keys():
self.projects_list.append(project)
print(project)
def set_local(self,path):
self.remotes = {};
self.local_path = path;
os.chdir(self.local_path);
def add_remote(self,name="origin"):
os.popen("git remote add {3} ssh://{0}@{1}:{2}/{4}/.git".format(self.user,self.hostname,self.base_path[1],name,self.fix_name))
self.remotes[name] = {"name" : name, "url" : "ssh://{0}@{1}:{2}/{3}/.git".format(self.user,self.hostname,self.base_path[1],self.fix_name)}
def fetch_remote(self,name):
if name in self.remotes.keys():
os.popen("git fetch {0}".format(name))
def get_remote(self):
retcode = re.compile(r"[\t, ]")
for remote in os.popen("git remote -v").readlines():
results = retcode.split(remote)
for item in results:
if item[0] not in self.remotes.keys():
self.remotes[item[0]] = {"name":item[0],"url":item[1]}
def push_remote(self,name,branch):
if branch in self.projects[self.fix_name]["branch"] and name in self.remotes.keys():
os.popen("git push {0} {1}".format(name,branch))
else:
raise ValueError("Branch or Name Abnormal")
def pull_remote(self,name,branch):
if name in self.remotes.keys():
os.popen("git pull {0} {1}".format(name,branch))
else:
raise ValueError("Remote Error")
def fix(self,name):
if name in self.projects_list:
self.fix_name = name;
stdout, stderr = self.run("cd {0}".format(self.projects[name]["path"]))
if self.check_error(stderr):
print("Fixed.")
self.fix_cmd = "cd {0}".format(self.projects[name]["path"]) + ";";
else:
raise ValueError("Project Path Abnormal")
def commit(self,message):
if self.base_path[0]:
stdout, stderr = self.run(self.fix_cmd+"git commit --message={0}".format(message))
else:
raise UnboundLocalError("Init Base First")
def get_branch(self):
if self.base_path[0] and self.fix_name != None:
stdout, stderr = self.run(self.fix_cmd+"git branch")
if self.check_error(stderr):
reform = re.compile("\w+",)
for branch in stdout:
branch_name = reform.search("*master").group().strip('\n')
self.projects[self.fix_name]["branch"].append(branch_name)
if '*' in str(branch):
self.projects[self.fix_name]["active_branch"] = branch_name
else:
print(stderr)
raise ValueError("Command Error")
def list_branch(self):
for project in self.projects.items():
for branch in project[1]["branch"]:
if branch == project[1]["active_branch"]:
print("(*)",branch)
else:
print(" ",branch)
if __name__ == "__main__":
compute = git("compute.bktus.com", "/home/git", "git", "123456")
compute.globalinit(git_user = "saturneric", git_email = "eric.bktu@gmail.com")
compute.baseinit();
#compute.create_project("lcs")
compute.update_projects();
compute.list_projects();
compute.fix("lcs");
#compute.get_branch("lcs")
compute.set_local("/Users/huyibing/Documents/code/test")
#compute.add_remote();
#compute.get_remote()
compute.get_branch();
compute.list_branch();
print(compute.projects)

65
ssh.py
View File

@ -1,26 +1,47 @@
import server
import subprocess
import os
class key(server.ssh):
def __init__(self,hostname, path, user, passwd=None, sshkey=False):
super().__init__(hostname=hostname, path=path, user=user, passwd=passwd, sshkey=sshkey)
self.connect(5);
def add_key(self):
self.run("echo \"{0}\" >> ~/.ssh/authorized_keys".format(self.pub_key))
def create_key(self):
retcode = subprocess.Popen(["ssh-keygen", "-b 4096", "-t rsa"], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = retcode.communicate(input=b"\ny \n \n \n")
def get_key(self):
self.pub_key = os.popen("cat ~/.ssh/id_rsa.pub").read()
import paramiko
class SSH(object):
ssh = paramiko.SSHClient();
def __init__(self, hostname, path, user, passwd=None, ssh_key=False):
self.hostname = hostname
self.path = path
self.user = user
self.ssh_key = ssh_key
newkey = key("compute.bktus.com", "/home/git", "git", "123456",sshkey=False);
#newkey.create_key();
#newkey.get_key();
#newkey.add_key();
if ssh_key:
self.passwd = None
self.key = paramiko.RSAKey.from_private_key_file('/Users/huyibing/.ssh/id_rsa')
else:
self.passwd = passwd
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def close(self):
self.ssh.close()
def run(self, cmd):
print("CMD:", cmd)
stdin, stdout, stderr = self.ssh.exec_command(cmd)
stdout = list(stdout)
stderr = list(stderr)
return stdout, stderr
@staticmethod
def check_error(stderr):
if len(stderr) == 0:
return True
else:
return False
def connect(self, timeout):
if self.ssh_key:
self.ssh.connect(hostname=self.hostname, port=22, username=self.user, pkey=self.key, timeout=timeout)
else:
self.ssh.connect(hostname=self.hostname, port=22, username=self.user, password=self.passwd,
timeout=timeout)
def __del__(self):
self.close()