Skip to content
Navigation Menu
{{ message }}
forked from andreax79/airflow-code-editor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.py
More file actions
264 lines (234 loc) · 8.52 KB
/
Copy pathgit.py
File metadata and controls
264 lines (234 loc) · 8.52 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#!/usr/bin/env python
#
# Copyright 2019 Andrea Bonomi <andrea.bonomi@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the Licens
import os
import logging
import subprocess
import threading
import shlex
from pathlib import Path
from typing import Dict, List, Tuple
from datetime import datetime
from flask import make_response, Response
from flask_login import current_user # type: ignore
from airflow_code_editor.commons import (
DEFAULT_GIT_BRANCH,
HTTP_200_OK,
HTTP_404_NOT_FOUND,
SUPPORTED_GIT_COMMANDS,
GitOutput,
)
from airflow_code_editor.utils import (
normalize_path,
get_plugin_config,
get_plugin_boolean_config,
get_root_folder,
read_mount_points_config,
prepare_api_response,
)
from airflow_code_editor.fs import RootFS
__all__ = [
'git_enabled',
'execute_git_command',
]
def git_enabled() -> bool:
"Return true if git is enabled in the configuration"
return get_plugin_boolean_config('git_enabled')
_execute_git_command_lock = threading.Lock()
class CompletedGitCommand:
def __init__(
self,
args: List[str],
returncode: int,
stdout: GitOutput = None,
stderr: GitOutput = None,
):
self.args = args
self.returncode = returncode
if self.git_cmd == 'cat-file':
self.stdout = stdout
self.stderr = stderr
else:
self.stdout = stdout.decode('utf-8') if isinstance(stdout, bytes) else stdout
self.stderr = stderr.decode('utf-8') if isinstance(stderr, bytes) else stderr
@property
def git_cmd(self):
return self.args[0] if self.args else None
def prepare_git_response(self) -> Response:
if self.git_cmd == 'cat-file':
response = make_response(
self.stdout or self.stderr,
HTTP_200_OK if self.returncode == 0 else HTTP_404_NOT_FOUND,
)
response.headers['Content-Type'] = 'text/plain'
else:
message = prepare_api_response(
data=self.stdout,
returncode=self.returncode,
error_message=self.stderr or None,
)
response = make_response(message)
return response
def execute_git_command(git_args: List[str]) -> CompletedGitCommand:
with _execute_git_command_lock:
logging.info(' '.join(git_args))
git_cmd = git_args[0] if git_args else None
stdout: GitOutput = None
stderr: GitOutput = None
returncode = 0
try:
# Init git repo
init_git_repo()
# Local commands
if git_cmd in LOCAL_COMMANDS:
handler = LOCAL_COMMANDS[git_cmd]
stdout = handler(git_args)
# Git commands
elif git_cmd in SUPPORTED_GIT_COMMANDS:
git_default_args = shlex.split(get_plugin_config('git_default_args'))
returncode, stdout, stderr = git_call(git_default_args + git_args, capture_output=True)
else:
stdout = None
stderr = 'Command not supported: git {0}'.format(' '.join(git_args))
returncode = 1
except OSError as ex:
logging.error(ex)
stdout = None
stderr = ex.strerror
returncode = ex.errno
except Exception as ex:
logging.error(ex)
stdout = None
stderr = ex.message if hasattr(ex, 'message') else str(ex)
returncode = 1
finally:
return CompletedGitCommand(git_args, returncode, stdout, stderr)
def git_ls_local(git_args: List[str]) -> str:
"'git ls-tree' like output for local folders"
long_ = False # long format
if '-l' in git_args or '--long' in git_args:
git_args = [arg for arg in git_args if arg not in ('-l', '--long')]
long_ = True
all_ = False # do not ignore entries
if '-a' in git_args:
git_args = [arg for arg in git_args if arg not in ('-a')]
all_ = True
path = git_args[1] if len(git_args) > 1 else ''
path = normalize_path(path.split('#', 1)[0])
result = []
root_fs = RootFS()
for item in root_fs.path(path).iterdir(show_ignored_entries=all_):
if item.is_dir():
type_ = 'tree'
else:
type_ = 'blob'
s = item.stat()
if long_:
mtime = datetime.utcfromtimestamp(s.st_mtime).isoformat()[:16]
result.append('%06o %s %s#%s %8s\t%s' % (s.st_mode, type_, str(item), mtime, item.size(), item.name))
else:
result.append('%06o %s %s\t%s' % (s.st_mode, type_, str(item), item.name))
return '\n'.join(result)
def git_mounts(git_args: List[str]) -> str:
"List mountpoints"
mount_points = read_mount_points_config()
return '\n'.join(sorted(k for k, v in mount_points.items() if not v.default))
def git_rm_local(git_args: List[str]) -> str:
"Delete local files/directories"
root_fs = RootFS()
for arg in git_args[1:]:
if arg:
root_fs.path(arg).delete()
return ''
def git_mv_local(git_args: List[str]) -> str:
"Rename/Move local files"
if len(git_args) < 3:
raise Exception('Missing source/destination args')
root_fs = RootFS()
target = git_args[-1]
for arg in git_args[1:-1]:
source = root_fs.path(arg)
source.move(target)
return ''
LOCAL_COMMANDS = {
'mounts': git_mounts,
'ls-local': git_ls_local,
'rm-local': git_rm_local,
'mv-local': git_mv_local,
}
def git_call(argv: List[str], capture_output: bool = False) -> Tuple[int, bytes, bytes]:
"Run git command. If capture_output is true, stdout and stderr will be captured."
if not git_enabled():
return 1, b'', b'git is disabled'
cmd: List[str] = [get_plugin_config('git_cmd')] + argv
cwd: Path = get_root_folder()
env: Dict[str, str] = prepare_git_env()
try:
completed = subprocess.run(
args=cmd,
stdin=subprocess.PIPE if capture_output else None,
stdout=subprocess.PIPE if capture_output else None,
stderr=subprocess.PIPE if capture_output else None,
cwd=cwd,
env=env,
)
return completed.returncode, completed.stdout, completed.stderr
except (FileNotFoundError, PermissionError):
return 127, b'', b'git command not found'
def get_default_branch() -> str:
stdout = git_call(['config', '--global', 'init.defaultBranch'], capture_output=True)[1]
default_branch = stdout.decode('utf8').strip('\n')
return default_branch or DEFAULT_GIT_BRANCH
def init_git_repo() -> None:
"Initialize the git repository in root folder"
cwd: Path = get_root_folder()
if git_enabled() and not (cwd / '.git').exists() and get_plugin_boolean_config('git_init_repo'):
git_call(['init', '-b', get_default_branch(), '.'])
gitignore = cwd / '.gitignore'
if not gitignore.exists():
with gitignore.open('w') as f:
f.write('__pycache__\n')
git_call(['add', '.gitignore'])
git_call(['commit', '-m', 'Initial commit'])
def prepare_git_env() -> Dict[str, str]:
"Prepare the environ for git"
env = dict(os.environ)
# Don't prompt on the terminal
env['GIT_TERMINAL_PROMPT'] = '0'
env['GIT_ASKPASS'] = '/bin/true'
# Author
git_author_name = get_plugin_config('git_author_name')
if not git_author_name:
try:
git_author_name = '%s %s' % (
current_user.first_name,
current_user.last_name,
)
except Exception:
pass
if git_author_name:
env['GIT_AUTHOR_NAME'] = git_author_name
env['GIT_COMMITTER_NAME'] = git_author_name
# Email
git_author_email = get_plugin_config('git_author_email')
if not git_author_email:
try:
git_author_email = current_user.email
except Exception:
pass
if git_author_email:
env['GIT_AUTHOR_EMAIL'] = git_author_email
env['GIT_COMMITTER_EMAIL'] = git_author_email
return env
You can’t perform that action at this time.
