init.py 8.82 KB
Newer Older
Alan Marchiori's avatar
initial  
Alan Marchiori committed
1
import click
Alan Marchiori's avatar
Alan Marchiori committed
2
import time
Alan Marchiori's avatar
initial  
Alan Marchiori committed
3
4
5
6
import os
import os.path
import config
import config.validation as validation
Alan Marchiori's avatar
Alan Marchiori committed
7
8
import shutil
from config.echo import *
Alan Marchiori's avatar
initial  
Alan Marchiori committed
9
from utils.gitlab import GitLab
Alan Marchiori's avatar
Alan Marchiori committed
10
from utils.git import Git
Alan Marchiori's avatar
Alan Marchiori committed
11
from utils.shell import run
Alan Marchiori's avatar
Alan Marchiori committed
12

Alan Marchiori's avatar
Alan Marchiori committed
13
import courses
Alan Marchiori's avatar
Alan Marchiori committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def init_ta(coursename, localpath):
    "called when init sees the ta flag set."
    localpath += "-TA"
    if confirm("Initialize {} into {} as a TA?".format(coursename, localpath)):
        if os.path.exists(localpath):
            # prompt to wipe it.
            warn("The path already exists!")
            if warn_confirm("Would you like me to WIPE {} and re-create (this will DELETE ALL files)".format(localpath)):
                shutil.rmtree(localpath)
                success("Deleted {}".format(localpath))

        if os.path.exists(localpath):
            error("ABORT: Cannot initialize since the path {} already exists!".format(
                localpath))
            return
Alan Marchiori's avatar
Alan Marchiori committed
29
        os.makedirs(localpath, mode=0o700)
Alan Marchiori's avatar
Alan Marchiori committed
30
31
32
33
        with config.UserConfig() as uc:
            uc.add_ta(
                name=coursename,
                path=localpath)
Alan Marchiori's avatar
Alan Marchiori committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47

            gl = GitLab()

            while not 'api_token' in uc.cfg or not gl.check_token():
                api_token = prompt("Got to {} and create a personal access token with the \"api scope\" checked. Copy-paste the value here".format(
                    config.gitlab_api_token_url
                ))
                uc.add_string(
                    name='api_token',
                    value=api_token
                )
                # needed to refresh the new token cached in the GitLab module
                gl = GitLab()

Alan Marchiori's avatar
Alan Marchiori committed
48
        success("Done.")
Alan Marchiori's avatar
initial  
Alan Marchiori committed
49

Alan Marchiori's avatar
Alan Marchiori committed
50
@click.command(short_help='Initialize a course.')
Alan Marchiori's avatar
initial  
Alan Marchiori committed
51
52
53
@click.argument('course', callback=validation.course)
@click.argument('section', callback=validation.section)
@click.argument('semester', callback=validation.semester)
Alan Marchiori's avatar
Alan Marchiori committed
54
@click.option('--prefix', default="~/",
Alan Marchiori's avatar
Alan Marchiori committed
55
    help="Override the default path prefix (~/)")
Alan Marchiori's avatar
Alan Marchiori committed
56
57
58
59
@click.option("--ta", default=False,
              help = "Set if you are a course TA or instructor.",
              is_flag = True)
def init(course, semester, section, prefix, ta):
Alan Marchiori's avatar
initial  
Alan Marchiori committed
60
61
62
63
64
65
66
67
68
    """Initializes the lab tool structure on your local system
    and on gitlab for a given COURSE, SECTION, and SEMESTER. Example: init CSCI206 S20 61.
    """

    coursename = config.course_name_fmt.format(
                course=course,
                semester=semester,
                section=section)

Alan Marchiori's avatar
Alan Marchiori committed
69
70
71
72
73
74
    if coursename not in courses.all:
        error("That course name/section/semester combination is not valid!")
        return

    coursedef = courses.all[coursename]

Alan Marchiori's avatar
Alan Marchiori committed
75
76
77
78
79
80
81
82
83
84
85
86
87
    if prefix == None:
        lp = os.path.expanduser(config.local_home.format(
                    course=course,
                    semester=semester,
                    section=section))
    else:
        lp = os.path.expanduser(
                os.path.join(
                    prefix,
                    config.course_name_fmt.format(
                            course=course,
                            semester=semester,
                            section=section)))
Alan Marchiori's avatar
Alan Marchiori committed
88
89
90
    if ta:
        init_ta(coursename, lp)
        return
Alan Marchiori's avatar
Alan Marchiori committed
91
92
93
94
95
96
97
98
99
    if confirm("Initialize {} into {}?".format(coursename, lp)):

        if os.path.exists(lp):
            # prompt to wipe it.
            warn("The path already exists!")
            if warn_confirm("Would you like me to WIPE {} and re-create (this will DELETE ALL files)".format(lp)):
                shutil.rmtree(lp)
                success("Deleted {}".format(lp))

Alan Marchiori's avatar
Alan Marchiori committed
100
        if os.path.exists(lp):
Alan Marchiori's avatar
Alan Marchiori committed
101
            error("ABORT: Cannot initialize since the path {} already exists!".format(
Alan Marchiori's avatar
Alan Marchiori committed
102
103
                lp))
            return
Alan Marchiori's avatar
initial  
Alan Marchiori committed
104
105
106
107

        with config.UserConfig() as uc:
            uc.add_course(
                name=coursename,
Alan Marchiori's avatar
Alan Marchiori committed
108
                path=lp)
Alan Marchiori's avatar
initial  
Alan Marchiori committed
109
110

            gl = GitLab()
Alan Marchiori's avatar
Alan Marchiori committed
111

Alan Marchiori's avatar
initial  
Alan Marchiori committed
112
            while not 'api_token' in uc.cfg or not gl.check_token():
Alan Marchiori's avatar
Alan Marchiori committed
113
                api_token = prompt("Got to {} and create a personal access token with the \"api scope\" checked. Copy-paste the value here".format(
Alan Marchiori's avatar
initial  
Alan Marchiori committed
114
115
116
117
118
119
120
121
                    config.gitlab_api_token_url
                ))
                uc.add_string(
                    name='api_token',
                    value=api_token
                )
                # needed to refresh the new token cached in the GitLab module
                gl = GitLab()
Alan Marchiori's avatar
Alan Marchiori committed
122

Alan Marchiori's avatar
Alan Marchiori committed
123
124
125
126
            # ensure they have an ssh key if needed
            # this needs the api token first!
            gl.ensure_key()

Alan Marchiori's avatar
Alan Marchiori committed
127
128
129
130
131
132
133
134
            # check if it already exists
            p = gl.search_for_project(coursename)
            if len(p) > 0:
                for prj in p:
                    if warn_confirm(
                        "Gitlab repo \"{}\" already exists--should I DELETE it?".format(
                            prj['name_with_namespace'])):
                        if gl.remove_project(prj['id']):
Alan Marchiori's avatar
Alan Marchiori committed
135
136
137
138
139
140
141
                            success("Removing \"{}\"".format(prj['name_with_namespace']))

                            # fake delay
                            with click.progressbar(range(10)) as bar:
                                for item in bar:
                                    time.sleep(0.1*item)

Alan Marchiori's avatar
Alan Marchiori committed
142
143
                        else:
                            error("Failed to remove \"{}\"".format(prj['name_with_namespace']))
Alan Marchiori's avatar
Alan Marchiori committed
144

Alan Marchiori's avatar
Alan Marchiori committed
145
146
147
                # try again
                p = gl.search_for_project(coursename)

Alan Marchiori's avatar
Alan Marchiori committed
148
            repo = None
Alan Marchiori's avatar
Alan Marchiori committed
149
150
151
152
153
154
155
156
157
158
159
            if len(p) == 0:
                repo = gl.create_project(coursename)
                if 'id' in repo:
                    success("Created gitlab repo \"{}\" at {}".format(
                        repo['name_with_namespace'],
                        repo['web_url']))

            # try again (2nd time)
            p = gl.search_for_project(coursename)
            if len(p) == 1:
                repo = p[0]
Alan Marchiori's avatar
Alan Marchiori committed
160
161
162
163

                curmembers = (gl.get(repo['_links']['members']).json())
                curmembers = [x['username'] for x in curmembers]

Alan Marchiori's avatar
Alan Marchiori committed
164
165
                # add members
                for name in coursedef['instructors'] + coursedef['tas']:
Alan Marchiori's avatar
Alan Marchiori committed
166

Alan Marchiori's avatar
Alan Marchiori committed
167
168
169
170
                    uobj = gl.get_users(username=name)
                    if len(uobj)==0:
                        warn('No gitlab user "{}" found!.'.format(name))
                    elif len(uobj)==1:
Alan Marchiori's avatar
Alan Marchiori committed
171
172
173
174
175
176
                        if name in curmembers:
                            success("{} ({}) is already a member".format(
                                uobj[0]['username'],
                                uobj[0]['name']))
                            continue

Alan Marchiori's avatar
Alan Marchiori committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
                        mem = gl.add_member_to_project(
                            repo['id'],
                            uobj[0]['id'],
                            40)
                        if mem:
                            success("Added {}, {} ({}) to \"{}\"".format(
                                mem['name'],
                                mem['username'],
                                mem['id'],
                                repo['name_with_namespace']
                            ))
                        else:
                            warn("Adding member {}, {} ({}) to \"{}\" failed.".format(
                                uobj[0]['name'],
                                uobj[0]['username'],
                                uobj[0]['id'],
                                repo['name_with_namespace']
                            ))
                    else: warn('Cannot add member -- multiple gitlab accounts for {}: {}'.format(
                        name, uobj))
            else:
                warn("Skipped repo creation and member addition.")
Alan Marchiori's avatar
Alan Marchiori committed
199
200
201
202

            # finally clone the repo

            git = Git()
Alan Marchiori's avatar
Alan Marchiori committed
203
204
205
206
            if git.do_clone(repo['ssh_url_to_repo'], localpath=lp):
                # copy cs206 gitignore and add to repo
                igf = os.path.join(lp, '.gitignore')

Alan Marchiori's avatar
push    
Alan Marchiori committed
207
208
209
210
211
212
213
                # src = "curl {} -o {}".format(
                #     "http://eg.bucknell.edu/~cs206/.gitignore", igf)
                # c,t = run(src)
                # if c == 0:
                #     success(src)

                if '.gitignore' in coursedef:
Alan Marchiori's avatar
Alan Marchiori committed
214
215
216
217
218
219
220
221
                    if os.path.exists(os.path.expanduser(coursedef['.gitignore'])):
                        src = os.path.expanduser(coursedef['.gitignore'])
                        dst = os.path.join(lp, '.gitignore')
                        debug("COPY {} --> {}".format(
                            src,
                            dst
                        ))
                        shutil.copyfile(src, dst)
Alan Marchiori's avatar
push    
Alan Marchiori committed
222
223
224
225
226
                        git.do_push(addfiles=['.gitignore'],
                            cwd=lp, message='Added by labtool')
                    else:
                        warn("Failed to initialize gitignore file.")
                        warn(coursedef['.gitignore'])
Alan Marchiori's avatar
Alan Marchiori committed
227

Alan Marchiori's avatar
Alan Marchiori committed
228
229
230
                success("Initialization complete!")
            else:
                error("Sorry, I was unable to clone the repo (did something go wrong earlier?)!")