-
Notifications
You must be signed in to change notification settings - Fork 324
/
handlers.py
781 lines (644 loc) · 23.8 KB
/
handlers.py
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
"""
Module with all the individual handlers, which execute git commands and return the results to the frontend.
"""
import json
import os
from pathlib import Path
from tornado import web
from notebook.base.handlers import APIHandler
from notebook.utils import url_path_join as ujoin, url2path
from packaging.version import parse
from ._version import __version__
from .git import DEFAULT_REMOTE_NAME
# Git configuration options exposed through the REST API
ALLOWED_OPTIONS = ["user.name", "user.email"]
class GitHandler(APIHandler):
"""
Top-level parent class.
"""
@property
def git(self):
return self.settings["git"]
class GitCloneHandler(GitHandler):
@web.authenticated
async def post(self):
"""
Handler for the `git clone`
Input format:
{
'current_path': 'current_file_browser_path',
'repo_url': 'https://github.com/path/to/myrepo',
OPTIONAL 'auth': '{ 'username': '<username>',
'password': '<password>'
}'
}
"""
data = self.get_json_body()
response = await self.git.clone(
data["current_path"], data["clone_url"], data.get("auth", None)
)
if response["code"] != 0:
self.set_status(500)
self.finish(json.dumps(response))
class GitAllHistoryHandler(GitHandler):
"""
Parent handler for all four history/status git commands:
1. git show_top_level
2. git branch
3. git log
4. git status
Called on refresh of extension's widget
"""
@web.authenticated
async def post(self):
"""
POST request handler, calls individual handlers for
'git show_top_level', 'git branch', 'git log', and 'git status'
"""
body = self.get_json_body()
current_path = body["current_path"]
history_count = body["history_count"]
show_top_level = await self.git.show_top_level(current_path)
if show_top_level["code"] != 0:
self.set_status(500)
self.finish(json.dumps(show_top_level))
else:
branch = await self.git.branch(current_path)
log = await self.git.log(current_path, history_count)
status = await self.git.status(current_path)
result = {
"code": show_top_level["code"],
"data": {
"show_top_level": show_top_level,
"branch": branch,
"log": log,
"status": status,
},
}
self.finish(json.dumps(result))
class GitShowTopLevelHandler(GitHandler):
"""
Handler for 'git rev-parse --show-toplevel'.
Displays the git root directory inside a repository.
"""
@web.authenticated
async def post(self):
"""
POST request handler, displays the git root directory inside a repository.
"""
current_path = self.get_json_body()["current_path"]
result = await self.git.show_top_level(current_path)
if result["code"] != 0:
self.set_status(500)
self.finish(json.dumps(result))
class GitShowPrefixHandler(GitHandler):
"""
Handler for 'git rev-parse --show-prefix'.
Displays the prefix path of a directory in a repository,
with respect to the root directory.
"""
@web.authenticated
async def post(self):
"""
POST request handler, displays the prefix path of a directory in a repository,
with respect to the root directory.
"""
current_path = self.get_json_body()["current_path"]
result = await self.git.show_prefix(current_path)
if result["code"] != 0:
self.set_status(500)
self.finish(json.dumps(result))
class GitStatusHandler(GitHandler):
"""
Handler for 'git status --porcelain', fetches the git status.
"""
@web.authenticated
async def post(self):
"""
POST request handler, fetches the git status.
"""
current_path = self.get_json_body()["current_path"]
result = await self.git.status(current_path)
if result["code"] != 0:
self.set_status(500)
self.finish(json.dumps(result))
class GitLogHandler(GitHandler):
"""
Handler for 'git log --pretty=format:%H-%an-%ar-%s'.
Fetches Commit SHA, Author Name, Commit Date & Commit Message.
"""
@web.authenticated
async def post(self):
"""
POST request handler,
fetches Commit SHA, Author Name, Commit Date & Commit Message.
"""
body = self.get_json_body()
current_path = body["current_path"]
history_count = body.get("history_count", 25)
result = await self.git.log(current_path, history_count)
if result["code"] != 0:
self.set_status(500)
self.finish(json.dumps(result))
class GitDetailedLogHandler(GitHandler):
"""
Handler for 'git log -1 --stat --numstat --oneline' command.
Fetches file names of committed files, Number of insertions &
deletions in that commit.
"""
@web.authenticated
async def post(self):
"""
POST request handler, fetches file names of committed files, Number of
insertions & deletions in that commit.
"""
data = self.get_json_body()
selected_hash = data["selected_hash"]
current_path = data["current_path"]
result = await self.git.detailed_log(selected_hash, current_path)
if result["code"] != 0:
self.set_status(500)
self.finish(json.dumps(result))
class GitDiffHandler(GitHandler):
"""
Handler for 'git diff --numstat'. Fetches changes between commits & working tree.
"""
@web.authenticated
async def post(self):
"""
POST request handler, fetches differences between commits & current working
tree.
"""
top_repo_path = self.get_json_body()["top_repo_path"]
my_output = await self.git.diff(top_repo_path)
if my_output["code"] != 0:
self.set_status(500)
self.finish(my_output)
class GitBranchHandler(GitHandler):
"""
Handler for 'git branch -a'. Fetches list of all branches in current repository
"""
@web.authenticated
async def post(self):
"""
POST request handler, fetches all branches in current repository.
"""
current_path = self.get_json_body()["current_path"]
result = await self.git.branch(current_path)
if result["code"] != 0:
self.set_status(500)
self.finish(json.dumps(result))
class GitAddHandler(GitHandler):
"""
Handler for git add <filename>'.
Adds one or all files to the staging area.
"""
@web.authenticated
async def post(self):
"""
POST request handler, adds one or all files into the staging area.
"""
data = self.get_json_body()
top_repo_path = data["top_repo_path"]
if data["add_all"]:
body = await self.git.add_all(top_repo_path)
else:
filename = data["filename"]
body = await self.git.add(filename, top_repo_path)
if body["code"] != 0:
self.set_status(500)
self.finish(json.dumps(body))
class GitAddAllUnstagedHandler(GitHandler):
"""
Handler for 'git add -u'. Adds ONLY all unstaged files, does not touch
untracked or staged files.
"""
@web.authenticated
async def post(self):
"""
POST request handler, adds all the changed files.
"""
body = await self.git.add_all_unstaged(self.get_json_body()["top_repo_path"])
if body["code"] != 0:
self.set_status(500)
self.finish(json.dumps(body))
class GitAddAllUntrackedHandler(GitHandler):
"""
Handler for 'echo "a\n*\nq\n" | git add -i'. Adds ONLY all
untracked files, does not touch unstaged or staged files.
"""
@web.authenticated
async def post(self):
"""
POST request handler, adds all the untracked files.
"""
body = await self.git.add_all_untracked(self.get_json_body()["top_repo_path"])
if body["code"] != 0:
self.set_status(500)
self.finish(json.dumps(body))
class GitRemoteAddHandler(GitHandler):
"""Handler for 'git remote add <name> <url>'."""
@web.authenticated
async def post(self):
"""POST request handler to add a remote."""
data = self.get_json_body()
top_repo_path = data["top_repo_path"]
name = data.get("name", DEFAULT_REMOTE_NAME)
url = data["url"]
output = await self.git.remote_add(top_repo_path, url, name)
if output["code"] == 0:
self.set_status(201)
else:
self.set_status(500)
self.finish(json.dumps(output))
class GitResetHandler(GitHandler):
"""
Handler for 'git reset <filename>'.
Moves one or all files from the staged to the unstaged area.
"""
@web.authenticated
async def post(self):
"""
POST request handler,
moves one or all files from the staged to the unstaged area.
"""
data = self.get_json_body()
top_repo_path = data["top_repo_path"]
if data["reset_all"]:
body = await self.git.reset_all(top_repo_path)
else:
filename = data["filename"]
body = await self.git.reset(filename, top_repo_path)
if body["code"] != 0:
self.set_status(500)
self.finish(json.dumps(body))
class GitDeleteCommitHandler(GitHandler):
"""
Handler for 'git revert --no-commit <SHA>'.
Deletes the specified commit from the repository, leaving history intact.
"""
@web.authenticated
async def post(self):
data = self.get_json_body()
top_repo_path = data["top_repo_path"]
commit_id = data["commit_id"]
body = await self.git.delete_commit(commit_id, top_repo_path)
if body["code"] != 0:
self.set_status(500)
self.finish(json.dumps(body))
class GitResetToCommitHandler(GitHandler):
"""
Handler for 'git reset --hard <SHA>'.
Deletes all commits from head to the specified commit, making the specified commit the new head.
"""
@web.authenticated
async def post(self):
data = self.get_json_body()
top_repo_path = data["top_repo_path"]
commit_id = data["commit_id"]
body = await self.git.reset_to_commit(commit_id, top_repo_path)
if body["code"] != 0:
self.set_status(500)
self.finish(json.dumps(body))
class GitCheckoutHandler(GitHandler):
"""
Handler for 'git checkout <branchname>'. Changes the current working branch.
"""
@web.authenticated
async def post(self):
"""
POST request handler, changes between branches.
"""
data = self.get_json_body()
top_repo_path = data["top_repo_path"]
if data["checkout_branch"]:
if data["new_check"]:
body = await self.git.checkout_new_branch(
data["branchname"], data["startpoint"], top_repo_path
)
else:
body = await self.git.checkout_branch(data["branchname"], top_repo_path)
elif data["checkout_all"]:
body = await self.git.checkout_all(top_repo_path)
else:
body = await self.git.checkout(data["filename"], top_repo_path)
if body["code"] != 0:
self.set_status(500)
self.finish(json.dumps(body))
class GitCommitHandler(GitHandler):
"""
Handler for 'git commit -m <message>'. Commits files.
"""
@web.authenticated
async def post(self):
"""
POST request handler, commits files.
"""
data = self.get_json_body()
top_repo_path = data["top_repo_path"]
commit_msg = data["commit_msg"]
body = await self.git.commit(commit_msg, top_repo_path)
if body["code"] != 0:
self.set_status(500)
self.finish(json.dumps(body))
class GitUpstreamHandler(GitHandler):
@web.authenticated
async def post(self):
"""
Handler for the `git rev-parse --abbrev-ref $CURRENT_BRANCH_NAME@{upstream}` on the repo. Used to check if there
is a upstream branch defined for the current Git repo (and a side-effect is disabling the Git push/pull actions)
Input format:
{
'current_path': 'current_file_browser_path',
}
"""
current_path = self.get_json_body()["current_path"]
current_branch = await self.git.get_current_branch(current_path)
response = await self.git.get_upstream_branch(current_path, current_branch)
if response["code"] != 0:
self.set_status(500)
self.finish(json.dumps(response))
class GitPullHandler(GitHandler):
"""
Handler for 'git pull'. Pulls files from a remote branch.
"""
@web.authenticated
async def post(self):
"""
POST request handler, pulls files from a remote branch to your current branch.
"""
data = self.get_json_body()
response = await self.git.pull(
data["current_path"],
data.get("auth", None),
data.get("cancel_on_conflict", False),
)
if response["code"] != 0:
self.set_status(500)
self.finish(json.dumps(response))
class GitPushHandler(GitHandler):
"""
Handler for 'git push <first-branch> <second-branch>.
Pushes committed files to a remote branch.
"""
@web.authenticated
async def post(self):
"""
POST request handler,
pushes committed files from your current branch to a remote branch
Request body:
{
current_path: string, # Git repository path
remote?: string # Remote to push to; i.e. <remote_name> or <remote_name>/<branch>
}
"""
data = self.get_json_body()
current_path = data["current_path"]
known_remote = data.get("remote")
current_local_branch = await self.git.get_current_branch(current_path)
set_upstream = False
current_upstream_branch = await self.git.get_upstream_branch(
current_path, current_local_branch
)
if known_remote is not None:
set_upstream = current_upstream_branch["code"] != 0
remote_name, _, remote_branch = known_remote.partition("/")
current_upstream_branch = {
"code": 0,
"remote_branch": remote_branch or current_local_branch,
"remote_short_name": remote_name,
}
if current_upstream_branch["code"] == 0:
branch = ":".join(["HEAD", current_upstream_branch["remote_branch"]])
response = await self.git.push(
current_upstream_branch["remote_short_name"],
branch,
current_path,
data.get("auth", None),
set_upstream,
)
else:
# Allow users to specify upstream through their configuration
# https://git-scm.com/docs/git-config#Documentation/git-config.txt-pushdefault
# Or use the remote defined if only one remote exists
config = await self.git.config(current_path)
config_options = config["options"]
list_remotes = await self.git.remote_show(current_path)
remotes = list_remotes.get("remotes", list())
push_default = config_options.get("remote.pushdefault")
default_remote = None
if push_default is not None and push_default in remotes:
default_remote = push_default
elif len(remotes) == 1:
default_remote = remotes[0]
if default_remote is not None:
response = await self.git.push(
default_remote,
current_local_branch,
current_path,
data.get("auth", None),
set_upstream=True,
)
else:
response = {
"code": 128,
"message": "fatal: The current branch {} has no upstream branch.".format(
current_local_branch
),
"remotes": remotes, # Returns the list of known remotes
}
if response["code"] != 0:
self.set_status(500)
self.finish(json.dumps(response))
class GitInitHandler(GitHandler):
"""
Handler for 'git init'. Initializes a repository.
"""
@web.authenticated
async def post(self):
"""
POST request handler, initializes a repository.
"""
current_path = self.get_json_body()["current_path"]
body = await self.git.init(current_path)
if body["code"] != 0:
self.set_status(500)
self.finish(json.dumps(body))
class GitChangedFilesHandler(GitHandler):
@web.authenticated
async def post(self):
body = await self.git.changed_files(**self.get_json_body())
if body["code"] != 0:
self.set_status(500)
self.finish(json.dumps(body))
class GitConfigHandler(GitHandler):
"""
Handler for 'git config' commands
"""
@web.authenticated
async def post(self):
"""
POST get (if no options are passed) or set configuration options
"""
data = self.get_json_body()
top_repo_path = data["path"]
options = data.get("options", {})
filtered_options = {k: v for k, v in options.items() if k in ALLOWED_OPTIONS}
response = await self.git.config(top_repo_path, **filtered_options)
if "options" in response:
response["options"] = {
k: v for k, v in response["options"].items() if k in ALLOWED_OPTIONS
}
if response["code"] != 0:
self.set_status(500)
else:
self.set_status(201)
self.finish(json.dumps(response))
class GitDiffContentHandler(GitHandler):
"""
Handler for plain text diffs. Uses git show $REF:$FILE
Returns `prev_content` and `curr_content` with content of given file.
"""
@web.authenticated
async def post(self):
cm = self.contents_manager
data = self.get_json_body()
filename = data["filename"]
prev_ref = data["prev_ref"]
curr_ref = data["curr_ref"]
top_repo_path = os.path.join(cm.root_dir, url2path(data["top_repo_path"]))
response = await self.git.diff_content(
filename, prev_ref, curr_ref, top_repo_path
)
self.finish(json.dumps(response))
class GitIgnoreHandler(GitHandler):
"""
Handler to manage .gitignore
"""
@web.authenticated
async def post(self):
"""
POST add entry in .gitignore
"""
data = self.get_json_body()
top_repo_path = data["top_repo_path"]
file_path = data.get("file_path", None)
use_extension = data.get("use_extension", False)
if file_path:
if use_extension:
suffixes = Path(file_path).suffixes
if len(suffixes) > 0:
file_path = "**/*" + ".".join(suffixes)
body = await self.git.ignore(top_repo_path, file_path)
else:
body = await self.git.ensure_gitignore(top_repo_path)
if body["code"] != 0:
self.set_status(500)
self.finish(json.dumps(body))
class GitSettingsHandler(GitHandler):
@web.authenticated
async def get(self):
jlab_version = self.get_query_argument("version", None)
if jlab_version is not None:
jlab_version = str(parse(jlab_version))
git_version = None
try:
git_version = await self.git.version()
except Exception as error:
self.log.debug(
"[jupyterlab_git] Failed to execute 'git' command: {!s}".format(error)
)
server_version = str(parse(__version__))
# Similar to https://github.com/jupyter/nbdime/blob/master/nbdime/webapp/nb_server_extension.py#L90-L91
root_dir = getattr(self.contents_manager, "root_dir", None)
server_root = None if root_dir is None else Path(root_dir).as_posix()
self.finish(
json.dumps(
{
"frontendVersion": jlab_version,
"gitVersion": git_version,
"serverRoot": server_root,
"serverVersion": server_version,
}
)
)
class GitTagHandler(GitHandler):
"""
Handler for 'git tag '. Fetches list of all tags in current repository
"""
@web.authenticated
async def post(self):
"""
POST request handler, fetches all tags in current repository.
"""
current_path = self.get_json_body()["current_path"]
result = await self.git.tags(current_path)
if result["code"] != 0:
self.set_status(500)
self.finish(json.dumps(result))
class GitTagCheckoutHandler(GitHandler):
"""
Handler for 'git tag checkout '. Checkout the tag version of repo
"""
@web.authenticated
async def post(self):
"""
POST request handler, checkout the tag version to a branch.
"""
data = self.get_json_body()
current_path = data["current_path"]
tag = data["tag_id"]
result = await self.git.tag_checkout(current_path, tag)
if result["code"] != 0:
self.set_status(500)
self.finish(json.dumps(result))
# FIXME remove for 0.22 release - this avoid error when upgrading from 0.20 to 0.21 if the frontend
# has not been rebuilt yet.
class GitServerRootHandler(GitHandler):
@web.authenticated
async def get(self):
# Similar to https://github.com/jupyter/nbdime/blob/master/nbdime/webapp/nb_server_extension.py#L90-L91
root_dir = getattr(self.contents_manager, "root_dir", None)
server_root = None if root_dir is None else Path(root_dir).as_posix()
self.finish(json.dumps({"server_root": server_root}))
def setup_handlers(web_app):
"""
Setups all of the git command handlers.
Every handler is defined here, to be used in git.py file.
"""
git_handlers = [
("/git/add", GitAddHandler),
("/git/add_all_unstaged", GitAddAllUnstagedHandler),
("/git/add_all_untracked", GitAddAllUntrackedHandler),
("/git/all_history", GitAllHistoryHandler),
("/git/branch", GitBranchHandler),
("/git/changed_files", GitChangedFilesHandler),
("/git/checkout", GitCheckoutHandler),
("/git/clone", GitCloneHandler),
("/git/commit", GitCommitHandler),
("/git/config", GitConfigHandler),
("/git/delete_commit", GitDeleteCommitHandler),
("/git/detailed_log", GitDetailedLogHandler),
("/git/diff", GitDiffHandler),
("/git/diffcontent", GitDiffContentHandler),
("/git/init", GitInitHandler),
("/git/log", GitLogHandler),
("/git/pull", GitPullHandler),
("/git/push", GitPushHandler),
("/git/remote/add", GitRemoteAddHandler),
("/git/reset", GitResetHandler),
("/git/reset_to_commit", GitResetToCommitHandler),
("/git/server_root", GitServerRootHandler),
("/git/settings", GitSettingsHandler),
("/git/show_prefix", GitShowPrefixHandler),
("/git/show_top_level", GitShowTopLevelHandler),
("/git/status", GitStatusHandler),
("/git/upstream", GitUpstreamHandler),
("/git/ignore", GitIgnoreHandler),
("/git/tags", GitTagHandler),
("/git/tag_checkout", GitTagCheckoutHandler),
]
# add the baseurl to our paths
base_url = web_app.settings["base_url"]
git_handlers = [(ujoin(base_url, x[0]), x[1]) for x in git_handlers]
web_app.add_handlers(".*", git_handlers)