__init__.py 26.5 KB
Newer Older
Nicolas Chauvat's avatar
Nicolas Chauvat committed
1
import os
2
import json
Nicolas Chauvat's avatar
Nicolas Chauvat committed
3
4
5
6
7
import gitlab
import tempfile
import subprocess

from time import sleep
Laurent Peuch's avatar
Laurent Peuch committed
8
from loguru import logger
Nicolas Chauvat's avatar
Nicolas Chauvat committed
9
10
from rdflib import ConjunctiveGraph
from pathlib import Path
11
from heptalab import download_heptapod_trig, download_logigraphe_trig
Nicolas Chauvat's avatar
Nicolas Chauvat committed
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

FORGE_HEPTAPOD = "https://forge.extranet.logilab.fr/"


class EmptyCubeQueryResult(Exception):
    ...


def check_if_python_script(filename):
    if os.path.isdir(filename):
        return False

    if filename.endswith(".py"):
        return True

    # I have other extension than ".py"
    if "." in filename and filename.split(".")[-1] not in ".py":
        return False

    try:
        is_python = (
            "python script"
            in subprocess.check_output(["file", filename]).decode().lower()
        )
    except Exception as exc:
        print(
            "Warning: 'file' command not found, cannot check file type because of %s"
            % exc
        )
        raise

    return is_python


def get_all_cubes(query):
    cnx = gitlab.Gitlab(FORGE_HEPTAPOD, os.environ["GITLAB_TOKEN"])

    if query:
50
        download_heptapod_trig(cnx)
Nicolas Chauvat's avatar
Nicolas Chauvat committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
        g = ConjunctiveGraph()
        g.parse("./heptapod.trig", format="trig")

        query = (
            """
        prefix lgg: <http://data.logilab.fr/logigraphe/>
        prefix lon: <http://data.logilab.fr/ontology/network/>
        prefix dep: <http://ontologi.es/doap-deps#>
        prefix doap: <http://usefulinc.com/ns/doap#>

        SELECT ?projectId

        WHERE {
          ?project a doap:Project .
          ?project doap:name ?projectName .
          ?project lgg:heptapod_id ?projectId .
          ?project doap:category "project-dependency" .
68
          ?project lgg:is_cube true .
Nicolas Chauvat's avatar
Nicolas Chauvat committed
69
70
71
72
73
74
          %s
        } ORDER BY ?projectName
        """
            % query
        )

75
        logger.info(f"sparql query:\n{query}")
Nicolas Chauvat's avatar
Nicolas Chauvat committed
76
77
78
79
80
81
82
83
84
85
        query_result = g.query(query)

        if len(query_result) == 0:
            raise EmptyCubeQueryResult(
                f"ERROR: query failed to find any cube. Query:\n\n{query}"
            )

        for (project_id,) in query_result:
            yield cnx.projects.get(id=project_id)
    else:
86
87
88
        logger.info(
            "no custom query, parsing all projects in /cubes/ tagged 'project-dependency'"
        )
Nicolas Chauvat's avatar
Nicolas Chauvat committed
89
90
91
92
93
94
95
        # for project in cnx.projects.list(all=True, as_list=False):
        all_cubes = (
            x
            for x in cnx.projects.list(all=True, as_list=False)
            if x.namespace["name"] == "cubes" and "project-dependency" in x.tag_list
        )

Nicolas Chauvat's avatar
Nicolas Chauvat committed
96
        yield from all_cubes
Nicolas Chauvat's avatar
Nicolas Chauvat committed
97
98


Laurent Peuch's avatar
Laurent Peuch committed
99
100
def get_all_clients(query):
    cnx = gitlab.Gitlab(FORGE_HEPTAPOD, os.environ["GITLAB_TOKEN"])
101
102
    # needed to get access to cnx.user.id
    cnx.auth()
Laurent Peuch's avatar
Laurent Peuch committed
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120

    if query:
        download_logigraphe_trig(cnx)
        g = ConjunctiveGraph()
        g.parse("./logigraphe.trig", format="trig")

        query = (
            """
        prefix lgg: <http://data.logilab.fr/logigraphe/>
        prefix lon: <http://data.logilab.fr/ontology/network/>
        prefix dep: <http://ontologi.es/doap-deps#>
        prefix doap: <http://usefulinc.com/ns/doap#>

        SELECT ?projectId

        WHERE {
          ?project a doap:Project .
          ?project doap:name ?projectName .
121
122
          ?project doap:category ?projectCategory .
          FILTER (?projectCategory IN ("client-project", "logilab-project")) .
Laurent Peuch's avatar
Laurent Peuch committed
123
124
125
126
127
128
          %s
        } ORDER BY ?projectName
        """
            % query
        )

129
        logger.info(f"sparql query:\n{query}")
Laurent Peuch's avatar
Laurent Peuch committed
130
131
132
133
134
135
136
137
        query_result = g.query(query)

        if len(query_result) == 0:
            raise EmptyCubeQueryResult(
                f"ERROR: query failed to find any cube. Query:\n\n{query}"
            )

        for (project_id,) in query_result:
138
139
140
            project = cnx.projects.get(id=project_id)
            if cnx.user.id in {member.id for member in project.members.all(all=True)}:
                yield project
Laurent Peuch's avatar
Laurent Peuch committed
141
    else:
142
143
144
145
        logger.info(
            "no custom query, parsing all projects tagged 'project-dependency' or "
            "'logilab-project' and in which I'm a user"
        )
Laurent Peuch's avatar
Laurent Peuch committed
146
        # for project in cnx.projects.list(all=True, as_list=False):
147
        all_projects = (
Laurent Peuch's avatar
Laurent Peuch committed
148
149
            x
            for x in cnx.projects.list(all=True, as_list=False)
150
            if "client-project" in x.tag_list
151
            or "logilab-project" in x.tag_list
152
            and cnx.user.id in {member.id for member in x.members.all(all=True)}
Laurent Peuch's avatar
Laurent Peuch committed
153
154
        )

155
        yield from all_projects
Laurent Peuch's avatar
Laurent Peuch committed
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
def get_all_core_projects(query):
    cnx = gitlab.Gitlab(FORGE_HEPTAPOD, os.environ["GITLAB_TOKEN"])

    if query:
        download_logigraphe_trig(cnx)
        g = ConjunctiveGraph()
        g.parse("./logigraphe.trig", format="trig")

        query = (
            """
        prefix lgg: <http://data.logilab.fr/logigraphe/>
        prefix lon: <http://data.logilab.fr/ontology/network/>
        prefix dep: <http://ontologi.es/doap-deps#>
        prefix doap: <http://usefulinc.com/ns/doap#>

        SELECT ?projectId

        WHERE {
          ?project a doap:Project .
          ?project doap:name ?projectName .
          ?project lgg:heptapod_id ?projectId .
          ?project doap:category "cw-core" .
          %s
        } ORDER BY ?projectName
        """
            % query
        )

186
        logger.info(f"sparql query:\n{query}")
187
188
189
190
191
192
193
194
195
196
        query_result = g.query(query)

        if len(query_result) == 0:
            raise EmptyCubeQueryResult(
                f"ERROR: query failed to find any cube. Query:\n\n{query}"
            )

        for (project_id,) in query_result:
            yield cnx.projects.get(id=project_id)
    else:
197
        logger.info("no custom query, parsing all projects tagged 'cw-core'")
198
199
200
201
202
203
204
205
206
207
        # for project in cnx.projects.list(all=True, as_list=False):
        all_cubes = (
            x
            for x in cnx.projects.list(all=True, as_list=False)
            if "cw-core" in x.tag_list
        )

        yield from all_cubes


208
209
210
def get_project(project):
    cnx = gitlab.Gitlab(FORGE_HEPTAPOD, os.environ["GITLAB_TOKEN"])

211
212
213
214
215
216
217
218
219
220
221
222
223
224
    if os.path.exists("projects_to_id.json"):
        question_to_id = json.load(open("projects_to_id.json"))
    else:
        download_logigraphe_trig(cnx)  # operate of the whole forge
        g = ConjunctiveGraph()
        g.parse("./logigraphe.trig", format="trig")

        query = """
        prefix lgg: <http://data.logilab.fr/logigraphe/>
        prefix lon: <http://data.logilab.fr/ontology/network/>
        prefix dep: <http://ontologi.es/doap-deps#>
        prefix doap: <http://usefulinc.com/ns/doap#>

        SELECT ?projectId ?project ?projectName ?projectDescription
225

226
227
228
229
230
231
        WHERE {
          ?project a doap:Project .
          ?project doap:name ?projectName .
          ?project lgg:heptapod_id ?projectId .
          ?project dc:description ?projectDescription .
        }
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
        query_result = g.query(query)

        if len(query_result) == 0:
            raise EmptyCubeQueryResult(
                f"ERROR: query failed to find any cube. Query:\n\n{query}"
            )

        question_to_id = {}
        for (
            project_id,
            project_url,
            project_name,
            project_description,
        ) in query_result:
            question_to_id[str(project_url).lower()] = project_id
            question_to_id[str(project_name).lower()] = project_id
            question_to_id[
                str(project_name).replace("cubicweb-", "").lower()
            ] = project_id
            question_to_id[
                str(project_description).replace(" ", "").lower()
            ] = project_id

    project_id = None
258
259

    if project.isdigit():
260
261
262
263
264
265
266
267
268
269
270
271
272
273
        project_id = int(project)
    elif project.lower() in question_to_id:
        project_id = int(question_to_id[project.lower()])
    elif os.path.exists("projects_to_id.json"):
        # prune cache and restart
        os.remove("projects_to_id.json")
        return get_project(project)
    else:
        raise Exception(f"Failed to find project: {project}")

    if not os.path.exists("projects_to_id.json"):
        open("projects_to_id.json", "w").write(
            json.dumps(question_to_id, indent=4, sort_keys=True)
        )
274

275
    return cnx.projects.get(project_id)
276
277


Nicolas Chauvat's avatar
Nicolas Chauvat committed
278
279
280
281
282
283
284
class Repository:
    def __init__(self, url):
        self.url = url

    def __enter__(self):
        self.temporary_directory = tempfile.TemporaryDirectory()
        self.path = Path(self.temporary_directory.name)
285
        self.run_command(f"hg clone {self.url} {self.temporary_directory.name}")
Nicolas Chauvat's avatar
Nicolas Chauvat committed
286
287
288
289
290
291
292
293
294

        return self

    def run_command(self, command, capture_output=False):
        if capture_output:
            return subprocess.check_output(
                f"cd {self.path} && {command}", shell=True
            ).decode()
        else:
295
            print(f"\033[1;31m>>\033[0m \033[0;34m{command}\033[0m")
296
            return subprocess.check_call(f"cd {self.path} && {command}", shell=True)
Nicolas Chauvat's avatar
Nicolas Chauvat committed
297
298
299
300
301
302
303

    def read_file(self, file_name):
        return open(self.path / file_name, "r").read()

    def write_file(self, file_name, content):
        open(self.path / file_name, "w").write(content)

Laurent Peuch's avatar
Laurent Peuch committed
304
305
306
    def remove_file(self, file_name):
        os.remove(self.path / file_name)

Nicolas Chauvat's avatar
Nicolas Chauvat committed
307
308
309
310
311
312
313
314
315
316
317
318
319
    def append_to_file(self, file_name, content):
        open(self.path / file_name, "a").write(content)

    def all_python_files(self):
        repo_files = (f.as_posix() for f in self.path.glob("**/*"))
        yield from (f for f in repo_files if check_if_python_script(f))

    def __exit__(self, *args, **kwargs):
        del self.temporary_directory


class Command:
    BRANCH_NAME = None
320
    commit_message = None
Nicolas Chauvat's avatar
Nicolas Chauvat committed
321
322
    base_query = None
    AUTO_MR_AUTO_MERGE = True
323
    NO_AUTO_MR = False
324
    TARGETS = ("cubes", "clients")
Nicolas Chauvat's avatar
Nicolas Chauvat committed
325

326
327
328
329
330
331
332
    merge_request_description = (
        "Hello dear contributors,\n\nThis is an auto generated modification to help you improve the"
        " code base of logilab. If this commit is bad don't hesitate to close this MR and report it"
        " here https://forge.extranet.logilab.fr/cubicweb/cube-doctor/-/issues."
        "\n\nKind regards,"
    )

Nicolas Chauvat's avatar
Nicolas Chauvat committed
333
334
335
    def pre_check(self, root_files):
        return

336
    def modify_code(self, cube, repo, root_files, branches, other_args):
Nicolas Chauvat's avatar
Nicolas Chauvat committed
337
338
339
340
341
342
343
344
345
346
        raise NotImplementedError()

    def workflow(
        self,
        apply=False,
        query="",
        interactif=False,
        merge_when_pipeline_succeeds=False,
        number=None,
        additional_checks=None,
347
        project=None,
348
        target="cubes",
349
350
        branch_name=None,
        commit_message=None,
351
        update_mr=False,
352
        other_args=None,
Nicolas Chauvat's avatar
Nicolas Chauvat committed
353
    ):
354
355
        forced_branch_name = branch_name
        forced_commit_message = commit_message
Nicolas Chauvat's avatar
Nicolas Chauvat committed
356
357
358
359
360
361
362
363

        if self.base_query:
            if query:
                query += " . " + self.base_query
            else:
                query = self.base_query

        if merge_when_pipeline_succeeds and "lgg:has_gitlab_ci" not in query:
364
            query += " ?project lgg:has_gitlab_ci true ."
Nicolas Chauvat's avatar
Nicolas Chauvat committed
365

Laurent Peuch's avatar
Laurent Peuch committed
366
367
368
        if project:
            cubes = [get_project(project)]
        else:
369
370
371
372
373
374
            targets = {
                "cubes": get_all_cubes,
                "clients": get_all_clients,
                "core": get_all_core_projects,
            }
            cubes = targets[target](query)
Laurent Peuch's avatar
Laurent Peuch committed
375

Nicolas Chauvat's avatar
Nicolas Chauvat committed
376
377
        number = int(number) if number is not None else None
        cube_number_x = 0
Laurent Peuch's avatar
Laurent Peuch committed
378
        for cube in cubes:
Nicolas Chauvat's avatar
Nicolas Chauvat committed
379
380
381
382
383
384
385
386
387
388
389
390
            if number is not None and cube_number_x >= number:
                return

            try:
                root_files = {
                    x["name"]
                    for x in cube.repository_tree(all=True, ref="branch/default")
                }
            except gitlab.exceptions.GitlabGetError:
                print(f"ERROR: {cube.name} is EMPTY, skip it")
                continue

391
392
393
394
395
396
397
398
399
            if forced_branch_name is not None:
                if not forced_branch_name.startswith("topic/default/"):
                    forced_branch_name = "topic/default/" + forced_branch_name
                target_branch = branch_name
            elif self.BRANCH_NAME is not None:
                target_branch = self.BRANCH_NAME
            else:
                target_branch = None

400
401
            branches = [x.name for x in cube.branches.list(all=True)]

Nicolas Chauvat's avatar
Nicolas Chauvat committed
402
            # we already sent the MR
403
404
405
406
407
            if (
                not update_mr
                and target_branch is not None
                and target_branch in branches
            ):
Simon Chabot's avatar
Simon Chabot committed
408
                logger.info(f"{cube.name} already has a topic {target_branch}, skip")
Nicolas Chauvat's avatar
Nicolas Chauvat committed
409
410
411
412
413
414
415
416
417
418
                continue

            if self.pre_check(root_files) == "continue":
                continue

            if additional_checks:
                for check in additional_checks:
                    if check(cube=cube) == "continue":
                        continue

419
            logger.info(f'cloning {cube.attributes["web_url"]}')
Nicolas Chauvat's avatar
Nicolas Chauvat committed
420
421
            # hg clone
            with Repository(url=cube.attributes["web_url"]) as repo:
422
423
424
                modifications = self.modify_code(
                    cube, repo, root_files, branches, other_args
                )
Nicolas Chauvat's avatar
Nicolas Chauvat committed
425
                while True:
426
427
428
429
430
431
432
433
434
435
436
437
438
                    try:
                        repo.run_command(
                            'hg up -C -r "last(public() and branch(default))"',
                            capture_output=True,
                        )
                    except Exception:
                        import traceback

                        traceback.print_exc()
                        logger.error(
                            "failed to 'hg up', the repository is probably broken, skip it"
                        )
                        return
Nicolas Chauvat's avatar
Nicolas Chauvat committed
439
440
                    try:
                        # {"branch_name": ..., "commit_message": ...}
Laurent Peuch's avatar
Laurent Peuch committed
441
                        logger.info(f"run modification command for {self}")
Nicolas Chauvat's avatar
Nicolas Chauvat committed
442
443
444
445
                        metadata = next(modifications)
                    except StopIteration:
                        break

446
447
448
449
450
                    if forced_branch_name:
                        branch_name = forced_branch_name
                    else:
                        branch_name = metadata["branch_name"]

451
                    assert branch_name.startswith("topic/default/"), branch_name
452
453
454
455
456

                    if forced_commit_message:
                        commit_message = forced_commit_message
                    else:
                        commit_message = metadata["commit_message"]
457

458
459
460
461
462
463
464
                    if "merge_request_description" in metadata:
                        merge_request_description = metadata[
                            "merge_request_description"
                        ]
                    else:
                        merge_request_description = self.merge_request_description

Nicolas Chauvat's avatar
Nicolas Chauvat committed
465
466
                    # if nothing has changed, continue
                    if not repo.run_command("hg status", capture_output=True):
467
                        logger.info("nothing has changed, skip")
Nicolas Chauvat's avatar
Nicolas Chauvat committed
468
469
                        continue

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
                    needs_amend = False
                    branches = [x.name for x in cube.branches.list(all=True)]
                    if branch_name in branches:
                        topic = branch_name.split("/", -1)[-1]
                        if not update_mr:
                            logger.info(f"branch '{branch_name}' already exists, skip")
                            continue

                        logger.info(
                            f"branch '{branch_name}' already exists but --update-mr is used, will "
                            "update it"
                        )

                        try:
                            logger.info(f"see if I need to rebase topic '{topic}'")
                            repo.run_command("hg shelve")
                            repo.run_command(
                                f"hg rebase -d 'max(branch(default) and public())' "
                                f"-s 'min(topic({topic}))' --dry-run"
                            )
                        except subprocess.CalledProcessError as e:
                            if e.returncode == 255:
                                logger.info(f"no rebase needed on topic '{topic}'")
                            else:
                                logger.warning(
                                    f"merge conflict when trying to rebase topic '{topic}', let's "
                                    "prune it"
                                )
                                repo.run_command(f"hg update {topic}")
                                repo.run_command("hg prune -r .")
                                if apply:
                                    repo.run_command("hg push -r .")
                                repo.run_command(
                                    'hg up -C -r "last(public() and branch(default))"',
                                )
                        else:
                            logger.warning(f"rebasing topic '{topic}'...")
                            repo.run_command(
                                f"hg rebase -d 'max(branch(default) and public())' "
                                f"-s 'min(topic({topic}))'"
                            )
                        finally:
                            repo.run_command("hg unshelve")

                        repo.run_command(f"hg diff -r {branch_name.split('/')[-1]}")
                        if not repo.run_command(
                            f"hg diff -r {branch_name.split('/')[-1]}",
                            capture_output=True,
                        ).strip():
                            logger.info(
                                "actually no need to update because the existing branch won't be "
                                "changed"
                            )
                            continue

                        needs_amend = True
                        repo.run_command("hg shelve")
                        repo.run_command(f"hg update {branch_name.split('/')[-1]}")
                        try:
                            repo.run_command("hg uncommit -a")
                        except subprocess.CalledProcessError as e:
                            # 255 means nothing to do
                            if e.returncode != 255:
                                raise
                        else:
                            repo.run_command("hg revert -a")
                        repo.run_command("hg unshelve")

Nicolas Chauvat's avatar
Nicolas Chauvat committed
538
539
540
541
                    print()
                    message = f"{cube.name} {cube.web_url}"
                    print(message)
                    print("=" * len(message))
542
543
                    if not needs_amend:
                        repo.run_command(f"hg topic '{branch_name.split('/')[-1]}'")
Nicolas Chauvat's avatar
Nicolas Chauvat committed
544
545
                    repo.run_command("hg status")
                    repo.run_command("hg diff")
546
547
548
549
                    if not needs_amend:
                        repo.run_command(f"hg commit -m '{commit_message}'")
                    else:
                        repo.run_command("hg amend")
Nicolas Chauvat's avatar
Nicolas Chauvat committed
550
551
552
553
554

                    cube_number_x += 1

                    if apply or (
                        interactif
555
556
557
                        and input(
                            f"{'Apply to' if not update_mr else 'Update on'} {cube.name}? [Y/n] "
                        ).lower()[:1]
Nicolas Chauvat's avatar
Nicolas Chauvat committed
558
559
560
561
                        in ("y", "")
                    ):
                        repo.run_command("hg push -r tip")

562
563
564
565
566
567
568
569
                        if update_mr and cube.mergerequests.list(
                            state="opened", source_branch=branch_name
                        ):
                            logger.info(
                                f"mr for branch '{branch_name}' already exist, don't recreate it"
                            )
                            continue

Nicolas Chauvat's avatar
Nicolas Chauvat committed
570
571
572
573
                        print("Creating MR...")
                        mr = cube.mergerequests.create(
                            {
                                "target_branch": "branch/default",
574
                                "source_branch": branch_name,
575
                                "title": commit_message[:254],
Nicolas Chauvat's avatar
Nicolas Chauvat committed
576
                                "labels": ["To Review"],
577
                                "description": merge_request_description,
Nicolas Chauvat's avatar
Nicolas Chauvat committed
578
579
                            }
                        )
580
                        print(f"\n=> MR created at {mr.attributes['web_url']} \\o/\n")
Nicolas Chauvat's avatar
Nicolas Chauvat committed
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599

                        if merge_when_pipeline_succeeds:
                            # here "mr" is a ProjectMergeRequest and not the real MR somehow?
                            # so we need to use the real MR id to get it which is "mr.iid"
                            # and NOT mr.id... for whatever reason this weird API is like that!
                            for i in range(5):
                                try:
                                    cube.mergerequests.get(mr.iid).merge(
                                        merge_when_pipeline_succeeds=True
                                    )
                                    break
                                except gitlab.exceptions.GitlabMRClosedError:
                                    # we need to sleep because heptapod lags sometime and fails
                                    # to create the MR on time
                                    sleep(i * 2)
                                except gitlab.exceptions.GitlabAuthenticationError:
                                    print("ERROR: you aren't allowed to merge this MR")
                                    break
                            else:
600
601
602
603
604
605
606
607
608
                                try:
                                    cube.mergerequests.get(mr.iid).merge(
                                        merge_when_pipeline_succeeds=True
                                    )
                                except gitlab.exceptions.GitlabMRClosedError:
                                    import traceback

                                    traceback.print_exc()
                                    logger.error(
Laurent Peuch's avatar
Laurent Peuch committed
609
610
                                        f"failed to mark MR {mr} on {cube.name} as "
                                        "merge_when_pipeline_succeeds"
611
                                    )
Nicolas Chauvat's avatar
Nicolas Chauvat committed
612
613

                        open("created_mr.log", "a").write(
614
                            f"{branch_name.split('/')[-1]}: {mr.attributes['web_url']}\n"
Nicolas Chauvat's avatar
Nicolas Chauvat committed
615
616
617
                        )
                    elif not interactif:
                        print(f"would work on {cube.name}")
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

    def add_env_to_tox_envlist(self, repo, env):
        """
        This function will had the new env given as a string to the tox.ini
        file of a repo.

        Usage:

           self.add_env_to_tox_envlist(repo, "yamllint")

        This will transform:

           [tox]
           envlist = py3

        Into:

           [tox]
           envlist = py3,yamllint

        For now multiline envlist aren't handled. This will be added once needed.
        """

        tox_content = repo.read_file("tox.ini")
        result = ""

        for line in tox_content.split("\n"):
            # envlist = a,b,c...
            if line.startswith("envlist"):
                if ", " in line:
                    line += ", " + env
                elif "," in line:
                    line += "," + env
                else:  # no comma on line
                    line += "," + env

            result += line
            result += "\n"

        repo.write_file("tox.ini", result)
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

    def add_stage_to_gitlab_ci(self, repo, stage):
        """
        This function will add a stage (in first place for now) in the
        "stages:" list of a .gitlab-ci.yml

        Usage:

            self.add_stage_to_gitlab_ci(repo, "lint")

        For now this only add it in the first position since this is used for
        added lint at the beginning. More options will be added once the need
        is here.
        """

        gitlab_ci_content = repo.read_file(".gitlab-ci.yml")
        result = []

        for line in gitlab_ci_content.split("\n"):
            if line.strip() == "stages:":
                result.append(line)
                # assume correct indentation
                result.append("  - lint")
            else:
                result.append(line)

        repo.write_file(".gitlab-ci.yml", "\n".join(result) + "\n")
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699


class NoMRCommand(Command):
    def workflow(
        self,
        apply=False,
        query="",
        interactif=False,
        merge_when_pipeline_succeeds=False,
        number=None,
        additional_checks=None,
        project=None,
        target="cubes",
        branch_name=None,
        commit_message=None,
700
        update_mr=False,
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
        other_args=None,
    ):
        if self.base_query:
            if query:
                query += " . " + self.base_query
            else:
                query = self.base_query

        if project:
            cubes = [get_project(project)]
        else:
            targets = {
                "cubes": get_all_cubes,
                "clients": get_all_clients,
                "core": get_all_core_projects,
            }
            cubes = targets[target](query)

        number = int(number) if number is not None else None
        cube_number_x = 0
        for cube in cubes:
            if number is not None and cube_number_x >= number:
                return

            try:
                root_files = {
                    x["name"]
                    for x in cube.repository_tree(all=True, ref="branch/default")
                }
            except gitlab.exceptions.GitlabGetError:
                print(f"ERROR: {cube.name} is EMPTY, skip it")
                continue

            branches = [x.name for x in cube.branches.list(all=True)]

            if self.pre_check(root_files) == "continue":
                continue

            if additional_checks:
                for check in additional_checks:
                    if check(cube=cube) == "continue":
                        continue

            print()
            message = f"{cube.name} {cube.web_url}"
            print(message)
            print("=" * len(message))

            logger.info(f'cloning {cube.attributes["web_url"]}')
            # hg clone
            with Repository(url=cube.attributes["web_url"]) as repo:
                modifications = self.modify_code(
753
754
755
756
757
758
                    cube,
                    repo,
                    root_files,
                    branches=branches,
                    other_args=other_args,
                    apply=apply,
759
760
761
762
763
764
765
766
767
768
769
770
771
772
                )
                while True:
                    repo.run_command(
                        'hg up -C -r "last(public() and branch(default))"',
                        capture_output=True,
                    )

                    try:
                        # {"branch_name": ..., "commit_message": ...}
                        next(modifications)
                    except StopIteration:
                        break

                    cube_number_x += 1