-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitdrive
More file actions
executable file
·199 lines (161 loc) · 7.86 KB
/
gitdrive
File metadata and controls
executable file
·199 lines (161 loc) · 7.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#!/usr/bin/env python3
import sys
import argparse
import subprocess
import os
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
class GitDriveHandler(BaseHTTPRequestHandler):
def do_GET(self):
print('Get request received')
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
return
def do_POST(self):
print('Get request received')
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
if self.path == "/" + self.server.data:
update_drive_repo(self.server.data)
return
class HttpServer:
def __init__(self, data: any, port: int):
self.server = HTTPServer(('', port), GitDriveHandler)
self.server.data = data
print(self.server.server_address)
print("/" + self.server.data)
self.server.serve_forever()
def __del__(self):
self.server.server_close()
INIT_USAGE = "usage: gitdrive init [-h] (--link LINK | --path PATH) [--json JSON]"
AUTO_USAGE = "gitdrive auto [-h] (--link LINK | --path PATH) [--json JSON] [--hook]"
def paser_init() -> argparse:
parser = argparse.ArgumentParser(description="Service who connect every update to a git branch into a Google drive")
subparsers = parser.add_subparsers(help='', dest='mode')
subparsers.required = True
parser_credential = subparsers.add_parser("credential", help='getting json credential for GoogleDrive')
parser_credential.add_argument('--path', type=str, help='path of the credential file (by default it\'s .)', default=None, metavar='PATH')
parser_init = subparsers.add_parser('init', help='init the drive directory and pull the repo', usage=INIT_USAGE)
parser_init_group = parser_init.add_argument_group('repository')
parser_init_group.add_argument('--link', type=str, nargs=1, metavar='LINK', help='link of the git repository', default=[''])
parser_init_group.add_argument('--path', type=str, nargs=1, metavar='PATH', help='path of the repository or where it will be cloned', default=[''])
parser_init.add_argument('--json', type=str, nargs=1, metavar='JSON', required=False, help='credential json file', default=[''])
parser_start = subparsers.add_parser('start', help='start the GitToDrive" service/server on the directory')
parser_start.add_argument('DIR', type=str, default='.', help='directory to start the git drive service')
parser_start.add_argument('--hook', help='use web hook to update', action='store_true')
parser_start.add_argument('--port', help='set the port for --hook option (8080 by default)', type=int, metavar='PORT', default=8080)
parser_auto = subparsers.add_parser('auto', help='init and start the GitToDrive service/server', usage=AUTO_USAGE)
parser_auto_group = parser_auto.add_argument_group('repository')
parser_auto_group.add_argument('--link', type=str, nargs=1, metavar='LINK', help='link of the git repository', default=[''])
parser_auto_group.add_argument('--path', type=str, nargs=1, metavar='PATH', help='path of the repository or where it will be cloned', default=[''])
parser_auto.add_argument('--json', type=str, nargs=1, metavar='JSON', required=False, help='credential json file', default=[''])
parser_auto.add_argument('--hook', help='use web hook to update', action='store_true')
parser_auto.add_argument('--port', help='set the port for --hook option (8080 by default)', type=int, metavar='PORT', default=8080)
return parser
def update_drive_repo(folder: str) -> None:
print('pull !')
subprocess.run(['git', 'pull'])
subprocess.run(['drive push -no-prompt -ignore-conflict -destination ' + folder + ' *'], shell=True)
def check_and_push(repo: str) -> None:
os.chdir(repo)
folder = os.path.basename(os.getcwd())
try:
while 666:
subprocess.run(['git', 'fetch'])
upstream = subprocess.run(['echo ${1:-\'@{u}\'}'], shell=True, stdout=subprocess.PIPE).stdout.decode('utf-8')[:-1]
local = subprocess.run(['echo $(git rev-parse @)'], shell=True, stdout=subprocess.PIPE).stdout.decode('utf-8')[:-1]
remote = subprocess.run(['echo $(git rev-parse "' + upstream + '")'], shell=True, stdout=subprocess.PIPE).stdout.decode('utf-8')[:-1]
base = subprocess.run(['echo $(git merge-base @ "' + upstream + '")'], shell=True, stdout=subprocess.PIPE).stdout.decode('utf-8')[:-1]
if local == base and local != remote:
update_drive_repo(folder)
time.sleep(5)
except KeyboardInterrupt:
print(': received, shutting down the service')
exit(2)
def get_path_last_name(path: str) -> str:
if path[-1] == os.sep:
path = path[:-1]
return path.split(os.sep)[-1]
def hook_and_push(repo: str, port: int) -> None:
os.chdir(repo)
folder = os.path.basename(os.getcwd())
server = None
try:
server = HttpServer(data=repo, port=port)
except KeyboardInterrupt:
print(': received, shutting down the web server')
exit(2)
def clone_repo(link: str, path: str) -> str:
if not path:
path = os.path.splitext(os.path.basename(link))[0]
if os.path.isdir(path):
return path
ret = subprocess.run(['git', 'clone', link, path])
if ret.returncode != 0:
exit(128)
return path
def check_repo(path: str) -> None:
if not os.path.isdir(path + '/.git'):
print("gitdrive error: " + path + "/.git does not exist")
exit(128)
if not os.path.isdir(path + '/.gd'):
print("gitdrive error: " + path + " has allready been initialized by drive")
exit(128)
def init_git_drive(link: str, path: str, json: str) -> None:
if link:
folder = clone_repo(link, path)
else:
check_repo(path)
folder = path
if json:
subprocess.run(['mkdir ' + folder + '/.gd'], shell=True)
subprocess.run(['cp ' + json + ' ' + folder + '/.gd/credentials.json'], shell=True)
os.chdir(folder)
if not json:
subprocess.run(['drive', 'init'])
folder_name = get_path_last_name(folder)
ret = subprocess.run(['drive list | grep ' + folder_name], shell=True)
if ret.returncode != 0:
subprocess.run(['drive', 'new', '-folder', folder_name])
subprocess.run(['drive push -no-prompt -destination ' + folder_name + ' *'], shell=True)
def auto_git_drive(link: str, path: str, json: str, hook: bool, port: int) -> None:
folder = os.path.splitext(os.path.basename(link))[0]
init_git_drive(link, path, json)
os.chdir("..")
if not hook:
check_and_push(folder)
else:
hook_and_push(folder, port)
def link_path_args_check(arg: argparse, cmd: str) -> bool:
if not arg.link[0] and not arg.path[0]:
if cmd == "init":
print(INIT_USAGE)
print("gitdrive init: error: the following arguments are required: --link OR --path")
if cmd == "auto":
print(AUTO_USAGE)
print("gitdrive auto: error: the following arguments are required: --link OR --path")
return False
return True
if __name__ == "__main__":
args = paser_init().parse_args()
# print(vars(args))
if args.mode == 'init' and link_path_args_check(args, "init"):
init_git_drive(args.link[0], args.path[0], args.json[0])
elif args.mode == 'start':
if not args.hook:
check_and_push(args.DIR)
else:
hook_and_push(args.DIR, args.port)
elif args.mode == 'auto' and link_path_args_check(args, "auto"):
auto_git_drive(args.link[0], args.path[0], args.json[0], args.hook, args.port)
elif args.mode == 'credential':
subprocess.run(['drive', 'init'])
if not args.path:
args.path = '.'
subprocess.run(['mv .gd/credentials.json ' + args.path], shell=True)
subprocess.run(['rmdir .gd'], shell=True)
else:
exit(1)
exit(0)