Skip to content

Commit cb15d94

Browse files
author
HR
committed
Fix cloning of the entire directory tree
1 parent 567197c commit cb15d94

1 file changed

Lines changed: 23 additions & 17 deletions

File tree

ghclone.py

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@
3131

3232
__version__ = '1.1.0'
3333
GH_API_BASE_URL = 'https://api.github.com'
34-
GH_REPO_ENDPOINT = GH_API_BASE_URL + '/repos/{}/{}'
3534
GH_REPO_CONTENTS_ENDPOINT = GH_API_BASE_URL + '/repos/{}/{}/contents'
3635
BASE_NORMALIZE_REGEX = re.compile(r'.*github\.com\/')
3736

@@ -69,16 +68,11 @@ def clone_file(download_url, file_path):
6968
fd.write(chunk)
7069

7170

72-
def clone(base_url, path=None, ref=None):
71+
def clone(base_url, rel_url=None, path=None, ref=None):
7372
"""
7473
Recursively clones the path
7574
"""
76-
if path:
77-
req_url = os.path.join(base_url, path)
78-
# Create path locally
79-
mkdir_p(path)
80-
else:
81-
req_url = base_url
75+
req_url = os.path.join(base_url, rel_url) if rel_url else base_url
8276

8377
# Get path metadata
8478
r = req.get(req_url) if not ref else req.get(req_url, params={'ref': ref})
@@ -92,13 +86,26 @@ def clone(base_url, path=None, ref=None):
9286
for item in repo_data:
9387
if item['type'] == 'dir':
9488
# Fetch dir recursively
95-
clone(base_url, item['path'], ref)
89+
clone(base_url, item['path'], path, ref)
9690
else:
9791
# Fetch the file
98-
clone_file(item['download_url'], item['path'])
92+
new_file_path = resolve_path(item['path'], path)
93+
new_path = os.path.dirname(new_file_path)
94+
# Create path locally
95+
mkdir_p(new_path)
96+
# Download the file
97+
clone_file(item['download_url'], new_file_path)
9998
# print('Cloned', item['path'])
10099

101100

101+
def resolve_path(path, dir):
102+
index = path.find(dir)
103+
if index is -1:
104+
return os.path.join(dir, path)
105+
else:
106+
return path[index:]
107+
108+
102109
###
103110
# Main
104111
###
@@ -122,19 +129,18 @@ def main():
122129
if len(gh_args) > 2:
123130
# Clone subdirectory
124131
ref = gh_args[2]
125-
path = os.path.join(*gh_args[3:])
126-
print("Cloning into '%s'..." % path)
132+
rel_url = os.path.join(*gh_args[3:])
133+
path = gh_args[-1]
127134
else:
128135
# Clone entire repo
129-
mkdir_p(repo)
130-
os.chdir(repo)
131136
ref = None
132-
path = None
133-
print("Cloning into '%s'..." % repo)
137+
rel_url = None
138+
path = repo
134139

135140
api_req_url = GH_REPO_CONTENTS_ENDPOINT.format(user, repo)
136141

137-
clone(api_req_url, path, ref)
142+
print("Cloning into '%s'..." % path)
143+
clone(api_req_url, rel_url, path, ref)
138144
print("done.")
139145

140146

0 commit comments

Comments
 (0)