forked from ehamiter/GitHubinator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithubinator.py
187 lines (146 loc) · 6.33 KB
/
githubinator.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
import codecs
import os
import re
import sublime
import sublime_plugin
# The urllib module has been split into parts and renamed in Python 3 to urllib.parse
try:
from urllib.parse import quote, quote_plus
except ImportError:
from urllib import quote, quote_plus
class GithubinatorCommand(sublime_plugin.TextCommand):
"""
This will allow you to highlight your code, activate the plugin, then see the
highlighted results on GitHub/Bitbucket.
"""
DEFAULT_GIT_REMOTE = "origin"
DEFAULT_HOST = "github.com"
def load_config(self):
s = sublime.load_settings("Githubinator.sublime-settings")
self.default_remote = s.get("default_remote") or self.DEFAULT_GIT_REMOTE
if not isinstance(self.default_remote, list):
self.default_remote = [self.default_remote]
self.default_host = s.get("default_host") or self.DEFAULT_HOST
def run(self, edit, copyonly=False, permalink=False, mode="blob", branch=None, open_repo=False):
self.load_config()
if not self.view.file_name():
return
# The current file
full_name = os.path.realpath(self.view.file_name())
folder_name, file_name = os.path.split(full_name)
# Try to find a git directory
git_path = self.recurse_dir(folder_name, ".git")
if not git_path:
sublime.status_message("Could not find .git directory.")
return
new_git_path = folder_name[len(git_path):]
# path names normalize for UNC styling
if os.name == "nt":
new_git_path = new_git_path.replace("\\", "/")
file_name = file_name.replace("\\", "/")
# Read the config file in .git
git_config_path = os.path.join(git_path, ".git", "config")
with codecs.open(git_config_path, "r", "utf-8") as git_config_file:
config = git_config_file.read()
# Figure out the host
scheme = "https"
result = re.search(r"url.*?=.*?((https?)://([^/]*)/)|(git@([^:]*):)", config)
if result:
matches = result.groups()
if matches[0]:
scheme = matches[1]
self.default_host = matches[2]
else:
self.default_host = matches[4]
re_host = re.escape(self.default_host)
sha, current_branch = self.get_git_status(git_path)
if not branch:
branch = current_branch
target = sha if permalink or branch is None else branch
target = quote_plus(target, safe="/")
detected_remote = None
# we can only do this search when we have a branch to work with.
if branch is not None:
regex = r".*\s.*(?:remote = )(\w+?)\r?\n"
result = re.search(branch + regex, config)
if result:
matches = result.groups()
detected_remote = [matches[0]]
for remote in (detected_remote or self.default_remote):
regex = r".*\s.*(?:https?://%s/|%s:|git://%s/)(.*)/(.*?)(?:\.git)?\r?\n" % (re_host, re_host, re_host)
result = re.search(remote + regex, config)
if not result:
continue
matches = result.groups()
username = matches[0]
project = matches[1]
lines = self.get_selected_line_nums()
repo_link = scheme + "://%s/%s/%s/" % (self.default_host, username, project)
if open_repo:
full_link = repo_link
else:
if "bitbucket" in self.default_host:
mode = "src" if mode == "blob" else "annotate"
lines = ":".join([str(l) for l in lines])
full_link = repo_link + "%s/%s%s/%s#cl-%s" % \
(mode, sha, new_git_path, file_name, lines)
else:
lines = "-".join("L%s" % line for line in lines)
full_link = repo_link + "%s/%s%s/%s#%s" % \
(mode, target, new_git_path, file_name, lines)
full_link = quote(full_link, safe=':/#@')
sublime.set_clipboard(full_link)
sublime.status_message("Copied %s to clipboard." % full_link)
if not copyonly:
self.view.window().run_command("open_url", {"url": full_link})
break
def get_selected_line_nums(self):
"""Get the line number of selections."""
sel = self.view.sel()[0]
begin_line = self.view.rowcol(sel.begin())[0] + 1
end_line = self.view.rowcol(sel.end())[0] + 1
if begin_line == end_line:
lines = [begin_line]
else:
lines = [begin_line, end_line]
return lines
@staticmethod
def get_git_status(git_path):
# type: (str) -> (str, Optional[str])
"""Get the current branch and SHA from git."""
with open(os.path.join(git_path, ".git", "HEAD"), "r") as f:
ref = f.read().replace("ref: ", "")[:-1]
sha = None
packed_ref_path = os.path.join(git_path, ".git", "packed-refs")
if os.path.isfile(packed_ref_path):
with codecs.open(packed_ref_path, "r", "utf-8") as f:
regex = r"\s{0}(\s.*)?$".format(ref)
try:
for line in f:
if re.search(regex, line):
sha = line.split(" ")[0]
except UnicodeDecodeError:
None
if not ref.startswith('refs/'):
# we are in detached head mode and ref will be
# `26e7c31036641177fa929e5a3ae925f214b23ed9`, instead of
# `ref/heads/master`. So we're returning the sha when we return ref.
return ref, None
if not sha:
with open(os.path.join(git_path, ".git", ref), "r") as f:
sha = f.read()[:-1]
branch = ref.replace("refs/heads/", "")
return sha, branch
def recurse_dir(self, path, folder):
items = os.listdir(path)
if folder in items and os.path.isdir(os.path.join(path, folder)):
return path
dirname = os.path.dirname(path)
if dirname == path:
return None
return self.recurse_dir(dirname, folder)
def is_enabled(self):
if self.view.file_name() and len(self.view.file_name()) > 0:
return True
else:
return False