-
Notifications
You must be signed in to change notification settings - Fork 6
/
abf.py
executable file
·1829 lines (1563 loc) · 81.1 KB
/
abf.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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import warnings
import importlib
warnings.filterwarnings('ignore', 'Module argparse was already imported')
import sys
import argparse
from argparse import RawDescriptionHelpFormatter
import os
import shutil
import platform
from glob import glob
import shlex
from subprocess import Popen, PIPE
import tempfile
import gettext
gettext.install('abf-console-client')
from abf.console.config import Config, mkdirs
from abf.console.log import Log
from abf.model import *
configs_dir = '/etc/abf/mock/configs/'
def test():
log.debug(_('TEST started'))
pls_import_personal = Platform.search(models, 'import_personal')
grs_import = Group.search(models, 'import')
prs_abfcc = Project.search(models, 'abf-console-client')
uss_akirilenko = User.search(models, 'akirilenko')
assert pls_import_personal
assert grs_import
assert prs_abfcc
assert uss_akirilenko
assert pls_import_personal[0].repositories[0].platform == pls_import_personal[0]
# check last items
assert Platform(models, ID=pls_import_personal[0].id).name == pls_import_personal[0].name
assert Group(models, ID=grs_import[0].id).uname == grs_import[0].uname
assert Project(models, ID=prs_abfcc[0].id).name == prs_abfcc[0].name
assert User(models, ID=uss_akirilenko[0].id).uname == uss_akirilenko[0].uname
# make models load the whole object
pls_import_personal[0].description
grs_import[0].description
prs_abfcc[0].description
uss_akirilenko[0].professional_experience
pr_abfcc = Project.get_by_name(models, 'akirilenko/abf-console-client')
assert pr_abfcc in prs_abfcc
# bl = BuildList(models, ID=750988)
Platform.get_user_platforms_main(models)
Platform.get_user_platforms_personal(models)
Platform.get_build_platforms(models)
arches = Arch.get_arches(models)
arch_x86_64 = Arch.get_arch_by_name(models, 'x86_64')
assert arch_x86_64 in arches
log.info(_('Datamodel seems to work fine'))
def apply_aliases():
# check if the current command is 'alias'
if 'alias' in sys.argv:
ind = sys.argv.index('alias')
found = False
for i in range(1, ind):
if sys.argv[i] not in ['-h', '-v', '--help', '--verbose', 'help']:
found = True
if not found:
return
for alias_name in cfg['alias']:
alias = shlex.split(cfg['alias'][alias_name])
if alias_name in sys.argv:
ind = sys.argv.index(alias_name)
del sys.argv[ind]
for item in alias:
sys.argv.insert(ind, item)
ind += 1
def parse_command_line():
global command_line
parser = argparse.ArgumentParser(description=_('ABF Console Client'))
parser.add_argument('-v', '--verbose', action='store_true', help=_('be verbose, display even debug messages'))
parser.add_argument('-c', '--clear-cache', action='store_true', help=_('clear cached information about repositories, platforms, projects, etc.'))
parser.add_argument('-q', '--quiet', action='store_true', help=_('Do not display info messages'))
parser.add_argument('-C', '--config', action='store', help=_('config file to be used'))
subparsers = parser.add_subparsers(title='command', dest='help')
subparsers.required = True
# help
subparser = subparsers.add_parser('help', help=_('show a help for command'))
subparser.add_argument('command', action='store', nargs='?', help=_('a command to show help for'))
subparser.set_defaults(func=help)
# alias
subparser = subparsers.add_parser('alias', help=_('Manage aliases'))
alias_commands = ['list', 'add', 'remove']
subparser.add_argument('command', action='store', choices=alias_commands)
subparser.add_argument('options', action='store', nargs='*', help=_('name and alias (not quoted, e. g. "abf alias add sg search groups") for adding, only name for removing.'))
subparser.set_defaults(func=alias)
# get
subparser = subparsers.add_parser('get', help=_('clone a project from ABF'))
subparser.add_argument('project', action='store', help=_('project name. ([group/]project). If no group specified, '
'it\'s assumed to be your default group.'))
subparser.add_argument('-b', '--branch', action='store', help=_('branch to checkout'))
subparser.add_argument('--skip-proj-cfg-update', action='store_true', help=_('Do not update cache with information about project builds.'))
subparser.set_defaults(func=get)
# put
subparser = subparsers.add_parser('put', help=_('Upload large binary files to File-Store and update (or create) .abf.yml file. Can also commit and push changes.'))
subparser.add_argument('-m', '--message', action='store', help=_('With this option specified, "git add" for every file, "git commit -m MSG" and "git push" will be executed.'))
subparser.add_argument('-f', '--add-folders', action='store_true', help=_('By default, the client does not add new folders to Git. This option will force it to add all new directories.'))
subparser.add_argument('-b', '--add-binaries', action='store_true', help=_('By default, the client does not add new binary files to Git. This option will force it to add all new binaries (unless they are uploaded to file store - see below).'))
subparser.add_argument('-s', '--minimal-file-size', default='0', action='store', help=_('The minimal file size to upload to File-Store. '
'Default is 0B.'))
subparser.add_argument('-n', '--do-not-remove-files', action='store_true', help=_('By default files are being removed on uploading. Override this behavior.'))
subparser.add_argument('-a', '--upload-all', action='store_true', help=_('By default, console client analyzes spec file and tries to detect which files located in the '
'current folder are really used by the project and uploads only these files to file store. '
'With this option, console client will upload all binary files located in the current folder.'))
subparser.set_defaults(func=put)
# store
subparser = subparsers.add_parser('store', help=_('Upload a given file to File-Store. Prints a sha1 hash or error message (with non-zero return code).'))
subparser.add_argument('path', action='store', help=_('Path to file'))
subparser.set_defaults(func=store)
# update
subparser = subparsers.add_parser('update', help=_('Update project settings.'))
subparser.add_argument('-p', '--project', action='store', help=_('Project to show information for (if needed). Format: '
'"[group/]name". If no group specified, default group will be used.'))
subparser.add_argument('--name', nargs='?', action='store', help=_('New project name.'))
subparser.add_argument('--desc', nargs='?', action='store', help=_('Project description.'))
subparser.add_argument('--visibility', nargs='?', action='store', help=_('Project visibility. Please specify "open" or "hidden".'))
subparser.add_argument('--is_pkg', nargs='?', action='store', help=_('Is project a package. Please specify "true" or "false".'))
subparser.add_argument('--maintainer', nargs='?', action='store', help=_('Project maintainer. You can specify either maintainer id or login.'))
subparser.add_argument('--branch', nargs='?', action='store', help=_('Default branch for the project Git repository.'))
subparser.add_argument('--issues', nargs='?', action='store', help=_('Should project issue tracker be enabled. Please specify "true" or "false".'))
subparser.add_argument('--wiki', nargs='?', action='store', help=_('Should project wiki be enabled. Please specify "true" or "false".'))
subparser.add_argument('--biarch', nargs='?', action='store', help=_('Enable/disable publishing 32bit packages into 64bit repository. Please specify "true" or "false".'))
subparser.set_defaults(func=update)
# fetch
subparser = subparsers.add_parser('fetch', help=_('Download all the files listed in .abf.yml or file with given hash from File-Store to local directory.'))
subparser.add_argument('filehash', nargs='*', action='store', help=_('Download file with given hash'))
subparser.add_argument('-o', '--only', action='append', help=_('Limit the list of downloaded files to this file name(s). This option can be specified more than once.'))
subparser.set_defaults(func=fetch)
# remote
subparser = subparsers.add_parser('remote', help=_('Add remote Git repository and fetch it.'))
subparser.add_argument('remote_group', action='store', help=_('ABF group to fetch from. This value will be also used as the name of remote repository.'))
subparser.add_argument('remote_name', nargs='?', action='store', help=_('Project to fetch (by default the same project name is used as the current one).'))
subparser.set_defaults(func=remote)
# show
subparser = subparsers.add_parser('show', help=_('show some general information. Bash autocomplete uses it.'))
show_choices = ['buildlists', 'build-repos', 'build-platforms', 'save-to-repos', 'save-to-platforms']
subparser.add_argument('type', action='store', nargs='?', choices=show_choices,help=_('The type of information to show'))
subparser.add_argument('-p', '--project', action='store', help=_('Project to show information for (if needed). Format: '
'"[group/]name". If no group specified, default group will be used.'))
subparser.set_defaults(func=show)
# locate
subparser = subparsers.add_parser('locate', help=_('tool can remember the project location and use it for some reasons (abfcd, etc.).'),
epilog=_('Every interaction with git repository (build, get, put, etc.) updates the cached location of the project (overriding '
'an existing one if needed). For any cached project you can execute "abfcd <project>" and you will cd to the project directory.'))
locate_choices = ['update', 'update-recursive']
subparser.add_argument('action', action='store', choices=locate_choices, nargs='?', help=_('The type of information to show'))
subparser.add_argument('-p', '--project', action='store', help=_('Project to show information for (if needed). Format: '
'"[group/]name". If no group specified, default group will be used.'))
subparser.add_argument('-d', '--directory', action='store', help=_('Directory to update locations for. It should be a '
'git repository for "update" and any directory for "update-recursive". If not specified - the current directory will be used'))
subparser.set_defaults(func=locate)
# build
subparser = subparsers.add_parser('build', help=_('Initiate a build task on ABF.'), formatter_class=RawDescriptionHelpFormatter,
epilog=_('NOTES:\n'
'API takes git commit hash to build. So client have to resolve it.\n'
'1) If you\'ve specified commit hash - it will be used "as is".\n'
'2) If you\'ve specified branch or tag name - it will be resolved automatically\n'
'using ABF API. (the hash of top commit will be used for branch)\n'
'3) If you\'ve specified no git commit related options and you\'ve\n'
' specified a project name - this project\'s default branch will be used.\n'
'4) If you\'ve specified no git commit related options and you\'ve\n'
'not specified a project name (you have to be in a git repository) -\n'
'the top remote commit of your current branch will be used.\n'))
subparser.add_argument('-p', '--project', action='store', help=_('project name ([group/]project). If no group '
'specified, it is assumed to be your default group. If the option is not specified and you are in a git '
'repository directory - resolve a project name from it.'))
g = subparser.add_mutually_exclusive_group()
g.add_argument('-b', '--branch', action='store', help=_('branch to build.'))
g.add_argument('-t', '--tag', action='store', help=_('tag to build.'))
g.add_argument('-c', '--commit', action='store', help=_('commit sha hash to build.'))
subparser.add_argument('-s', '--save-to-repository', action='store', help=_('repository to save results to '
'([platform/]repository). If no platform part specified, it is assumed to be "<default_group>_personal". '
'If this option is not specified at all, "<default_group>_personal/main" will be used.'))
subparser.add_argument('-a', '--arch', action='append', help=_('architectures to build, '
'can be set more than once. If not set - use all the available architectures.'))
subparser.add_argument('-r', '--repository', action='append', help=_('repositories to build with ([platform/]repository). '
'Can be set more than once. If no platform part specified, it is assumed to be your "<default_build_platform>".'
' If no repositories were specified at all, use the "main" repository from save-to platform.'))
subparser.add_argument('-l', '--build-list', action='append', help=_('build list whose container should be used during the build. Can be specified more than once.'))
subparser.add_argument('--auto-publish', action='store_true', help=_('deprecated synonym for --auto-publish-status=default.'))
subparser.add_argument('--auto-publish-status', action='store', choices=BuildList.auto_publish_statuses, help=_('enable automatic publishing. Default is "%s".') %
(BuildList.auto_publish_statuses[0]))
subparser.add_argument('--skip-personal', action='store_true', help=_('do not use personal repository to resolve dependencies.'))
subparser.add_argument('--testing', action='store_true', help=_('Include "testing" subrepository.'))
subparser.add_argument('--no-extra-tests', action='store_true', help=_('Do not launch comprehensive tests.'))
subparser.add_argument('--auto-create-container', action='store_true', help=_('enable automatic creation of container'))
subparser.add_argument('--no-cached-chroot', action='store_true', help=_('do NOT use cached chroot for the build'))
subparser.add_argument('--save-chroot', action='store_true', help=_('save build chroot in case of failure'))
subparser.add_argument('--update-type', action='store', choices=BuildList.update_types, help=_('Update type. Default is "%s".') %
(BuildList.update_types[0]) )
subparser.add_argument('--external-nodes', action='store', choices=BuildList.external_nodes_vals, help=_('Use any external ABF node or own external ABF node. Default is "%s".') %
(BuildList.external_nodes_vals[0]) )
subparser.add_argument('--skip-spec-check', action='store_true', help=_('Do not check spec file.'))
subparser.add_argument('--skip-proj-cfg-update', action='store_true', help=_('Do not update cache with information about project builds.'))
subparser.set_defaults(func=build)
# chain-build
subparser = subparsers.add_parser('chain_build', help=_('Initiate a chain of build tasks on ABF.'), formatter_class=RawDescriptionHelpFormatter)
subparser.add_argument('project', nargs='*', action='store', help=_('Project name ([group/]project). If no group '
'specified, it is assumed to be your default group. You can specify several projects to be built one after another. '
'You can also group projects with ":" to indicate that they can be built in parallel. For example, '
'"abf chain_build a b:c d" will build project "a", then (after "a" is built) will launch builds of "b" and "c" '
'in parallel and after both of these projects are built, the build of "d" will be initiated. '
'If automated publishing is set, then console client waits for every build to be published before starting the next build in the chain. '
'If automated container creation is set, then console client waits for container to be ready and when the next build is started, containers '
'from all previous builds are used as extra repositories.' ))
subparser.add_argument('-i', '--infile', action='store', help=_('File with project names. You can omit project names in command line '
'and provide a file with project names instead. The file will be read line by line. All projects specified at the same line '
'will be built in parallel; the next line will be processed only after all the build from the previous line are completed successfully. '
'Project name in a line can be separated by colon (":") or by space symbols.'))
g = subparser.add_mutually_exclusive_group()
g.add_argument('-b', '--branch', action='store', help=_('branch to build.'))
g.add_argument('-t', '--tag', action='store', help=_('tag to build.'))
g.add_argument('-c', '--commit', action='store', help=_('commit sha hash to build.'))
subparser.add_argument('-u', '--timeout', action='store', help=_('number of seconds to sleep between successive checks of build status.'))
subparser.add_argument('-s', '--save-to-repository', action='store', help=_('repository to save results to '
'([platform/]repository). If no platform part specified, it is assumed to be "<default_group>_personal". '
'If this option is not specified at all, "<default_group>_personal/main" will be used.'))
subparser.add_argument('-a', '--arch', action='append', help=_('architectures to build, '
'can be set more than once. If not set - use all the available architectures.'))
subparser.add_argument('-r', '--repository', action='append', help=_('repositories to build with ([platform/]repository). '
'Can be set more than once. If no platform part specified, it is assumed to be your "<default_build_platform>".'
' If no repositories were specified at all, use the "main" repository from save-to platform.'))
subparser.add_argument('-l', '--build-list', action='append', help=_('build list whose container should be used during the build. Can be specified more than once.'))
subparser.add_argument('--auto-publish', action='store_true', help=_('deprecated synonym for --auto-publish-status=default.'))
subparser.add_argument('--auto-publish-status', action='store', choices=BuildList.auto_publish_statuses, help=_('enable automatic publishing. Default is "%s".') %
(BuildList.auto_publish_statuses[0]))
subparser.add_argument('--skip-personal', action='store_true', help=_('do not use personal repository to resolve dependencies.'))
subparser.add_argument('--testing', action='store_true', help=_('Include "testing" subrepository.'))
subparser.add_argument('--no-extra-tests', action='store_true', help=_('Do not launch comprehensive tests.'))
subparser.add_argument('--auto-create-container', action='store_true', help=_('enable automatic creation of container'))
subparser.add_argument('--no-cached-chroot', action='store_true', help=_('do NOT use cached chroot for the build'))
subparser.add_argument('--save-chroot', action='store_true', help=_('save build chroot in case of failure'))
subparser.add_argument('--update-type', action='store', choices=BuildList.update_types, help=_('Update type. Default is "%s".') %
(BuildList.update_types[0]) )
subparser.add_argument('--external-nodes', action='store', choices=BuildList.external_nodes_vals, help=_('Use any external ABF node or own external ABF node. Default is "%s".') %
(BuildList.external_nodes_vals[0]) )
subparser.add_argument('--skip-proj-cfg-update', action='store_true', help=_('Do not update cache with information about project builds.'))
subparser.set_defaults(func=chain_build)
# mock
subparser = subparsers.add_parser('mock', help=_('Build a project locally using mock.'), epilog=_('No checkouts will be made,'
'the current git repository state will be used'))
subparser.add_argument('-c', '--config', action='store', help=_('A config template to use. Specify one of the config names '
'from %s. Directory path should be omitted. If no config specified, "default.cfg" will be used') % configs_dir)
subparser.set_defaults(func=localbuild_mock_urpm)
# rpmbuild
subparser = subparsers.add_parser('rpmbuild', help=_('Build a project locally using rpmbuild.'), epilog=_('No checkouts will be made,'
'the current git repository state will be used'))
subparser.add_argument('-b', '--build', action='store', choices=['b', 's', 'a', 'p'], default='a', help=_('Build src.rpm (s), rpm (b), both (a) or only %%prep(p)'))
subparser.add_argument('-s', '--save-rpmbuild-folder', action='store_true', help=_('Copy the whole rpmbuild folder into the current folder after the build'))
subparser.set_defaults(func=localbuild_rpmbuild)
# publish
subparser = subparsers.add_parser('publish', help=_('Publish the task that have already been built.'))
subparser.add_argument('task_ids', action='store', nargs="+", help=_('The IDs of tasks to publish.'))
subparser.set_defaults(func=publish)
# copy
subparser = subparsers.add_parser('copy', help=_('Copy all the files from SRC_BRANCH to DST_BRANCH'))
subparser.add_argument('src_branch', action='store', help=_('source branch'))
subparser.add_argument('dst_branch', action='store', nargs='?', help=_('destination branch. If not specified, it\'s assumed to be the current branch'))
subparser.add_argument('-p', '--pack', action='store_true', help=_('Create a tar.gz from the src_branch and put this archive and spec file to dst_branch'))
subparser.set_defaults(func=copy)
# pull request
subparser = subparsers.add_parser('pullrequest', help=_('Send a pull request from SRC_BRANCH to DST_BRANCH'))
subparser.add_argument('from_ref', action='store', help=_('source ref or branch'))
subparser.add_argument('to_ref', action='store', help=_('destination ref or branch'))
subparser.add_argument('title', action='store', help=_('Request title'))
subparser.add_argument('body', action='store', help=_('Request body'))
subparser.add_argument('-p', '--project', action='store', help=_('Source project name (group/project).'))
subparser.add_argument('-d', '--dest', action='store', help=_('Destination project name (group/project). If not specified, the source project is used (this can be used to send requests from one project branch to another).'))
subparser.set_defaults(func=pull_request)
# fork project
subparser = subparsers.add_parser('fork', help=_('Fork existing project'))
subparser.add_argument('source_project', action='store', help=_('project to fork (group/project)'))
subparser.add_argument('target_project', action='store', nargs='?', help=_('target project group and name (group/project)'))
subparser.set_defaults(func=fork_project)
# alias project
subparser = subparsers.add_parser('proj_alias', help=_('Create alias of existing project'))
subparser.add_argument('source_project', action='store', help=_('project to fork (group/project)'))
subparser.add_argument('target_project', action='store', help=_('target project group and name (group/project)'))
subparser.set_defaults(func=alias_project)
# create empty project
subparser = subparsers.add_parser('create_empty', help=_('Create empty project'))
subparser.add_argument('name', action='store', help=_('project name'))
subparser.add_argument('owner', action='store', nargs='?', help=_('who will own the project; default_owner is used by default'))
subparser.add_argument('--description', action='store', help=_('project description'))
subparser.add_argument('--visibility', action='store', choices=['public', 'private'], default='public', help=_('project visibility'))
subparser.set_defaults(func=create_empty)
# create project from SRPM
subparser = subparsers.add_parser('create', help=_('Create project from SRPM'))
subparser.add_argument('srpm', action='store', help=_('srpm file'))
subparser.add_argument('owner', action='store', nargs='?', help=_('who will own the project; default_owner is used by default'))
subparser.add_argument('-b', '--branch', action='append', help=_('create additional branch; can be set more than once.'))
subparser.add_argument('--no-def-branch', action='store_true', help=_('Do not automatically create branch set as default in user config (if it is set to smth different from "master").'))
subparser.add_argument('--visibility', action='store', choices=['public', 'private'], default='public', help=_('project visibility'))
subparser.set_defaults(func=create)
# destroy project
subparser = subparsers.add_parser('destroy', help=_('Destroy project'))
subparser.add_argument('project', action='store', help=_('project name. ([group/]project). If no group specified, '
'it\'s assumed to be your default group.'))
subparser.set_defaults(func=destroy)
# add project to repository
subparser = subparsers.add_parser('add', help=_('Add project to specified repository'))
subparser.add_argument('repository', action='store', help=_('target repository ([platform/]repository)'))
subparser.add_argument('-p', '--project', action='store', help=_('project name (group/project).'))
subparser.set_defaults(func=add_project_to_repository)
# remove project from repository
subparser = subparsers.add_parser('remove', help=_('Remove project from specified repository'))
subparser.add_argument('repository', action='store', help=_('target repository ([platform/]repository)'))
subparser.add_argument('-p', '--project', action='store', help=_('project name (group/project).'))
subparser.set_defaults(func=remove_project_from_repository)
# status
subparser = subparsers.add_parser('status', help=_('get a build-task status'), epilog=_('If a project specified '
' or you are in a git repository - try to get the IDs from the last build task sent for this project. If you are not'
' in a git repository directory and project is not specified - try to get build IDs from the last build you\'ve done '
'with console client.'))
subparser.add_argument('ID', action='store', nargs='*', help=_('build list ID'))
subparser.add_argument('-p', '--project', action='store', help=_('Project. If last IDs for this project can be found - use them'))
subparser.add_argument('-s', '--short', action='store_true', help=_('Show one-line information including id, project, '
'arch and status'))
subparser.set_defaults(func=status)
# clean
subparser = subparsers.add_parser('clean', help=_('Analyze spec file and show missing and unnecessary files from '
'the current git repository directory.'))
subparser.add_argument('--auto-remove', action='store_true', help=_('automatically remove all the unnecessary files'))
subparser.set_defaults(func=clean)
# search
subparser = subparsers.add_parser('search', help=_('Search for something on ABF.'), epilog=_('NOTE: only first 100 results of any request will be shown'))
search_choices = ['users', 'groups', 'platforms', 'projects']
subparser.add_argument('type', action='store', choices=search_choices, help=_('what to search for'))
subparser.add_argument('query', action='store', help=_('a string to search for'))
subparser.set_defaults(func=search)
#list
# info
subparser = subparsers.add_parser('info', help=_('get information about single instance'))
info_choices = ['platforms', 'repositories', 'projects']
subparser.add_argument('type', action='store', choices=info_choices, help=_('type of the instance'))
subparser.add_argument('-f', '--filter', action='store', help=_('The filter may be specified by defining multiple pairs <type>.<attribute>=<value> or <attribute>=<value>, where <type> is one of the following positional arguments: %s, <attribute> is the one of the instance fields or special attribute (page - using for pagination) and <value> - string, that can take asterisk (*) or anything else... Example: abf info projects -f platforms.name=rosa2012lts page=*') % info_choices, nargs='*')
subparser.add_argument('-o', '--output', action='store', help=_('output format '), nargs='*')
subparser.set_defaults(func=info_single)
# test
subparser = subparsers.add_parser('test', help=_('Execute a set of internal datamodel tests'))
subparser.set_defaults(func=test)
for s in subparsers._name_parser_map:
subparsers._name_parser_map[s].add_argument('-v', '--verbose', action='store_true', help=_('be verbose, display even debug messages'))
command_line = parser.parse_args(sys.argv[1:])
def info_single():
st = command_line.type
cl = {'platforms': Platform, 'repositories': Repository, 'projects': Project}
if not command_line.filter:
log.debug(_('Filter can be specified with the following parameters:\n %s' % cl[st].filter_dict))
sf = None
else:
for param in command_line.filter:
try:
st, param = list(map(str, param.split('.')))
except:
pass
attr, value = list(map(str, param.split('=')))
cl[st].filter_dict[attr]=value
log.debug(_('Filter setup for instance %s ') % st)
st = command_line.type
if not command_line.output:
log.debug(_('Output format can be specified with the following parameters:\n %s') % cl[st].required_fields)
so = [cl[st].required_fields[1]]
log.debug(_('Using default query format: %s') % so)
else:
so = command_line.output
res = cl[st].info(models)
info_out = []
for inst in res:
for param in so:
try:
print(param + ':\t' + str(inst.params_dict[param]))
except:
log.debug(_("Parameter %s not available:") % param)
def fix_default_config():
if not os.path.exists('/etc/abf/mock/configs/default.cfg'):
if os.getuid() != 0:
print(_("To set up a default configuration file, symbolic link in /etc/abf/mock/configs have to be created. I need sudo rights to do it."))
exit(1)
files = os.listdir('/etc/abf/mock/configs')
print(_('Avaliable configurations: '))
out = []
for f in files:
if not f.endswith('.cfg'):
continue
if f == 'site-defaults.cfg':
continue
out.append(f[:-4])
print(', '.join(out))
res = None
while res not in out:
if res is not None:
print(_('"%s" is not a valid configuration.') % res)
res = input(_('Select one (it will be remembered): '))
os.symlink('/etc/abf/mock/configs/%s.cfg' % res, '/etc/abf/mock/configs/default.cfg')
def run_mock_urpm(binary=True):
fix_default_config()
if not command_line.config:
command_line.config = 'default.cfg'
if command_line.config.endswith('.cfg'):
command_line.config = command_line.config[:-4]
config_path = os.path.join(configs_dir, command_line.config + '.cfg')
if not os.path.exists(config_path):
log.error(_("Config file %s can not be found.") % config_path)
if os.path.basename(config_path) == 'default.cfg':
log.error(_("You should create this file or a symbolic link to another config in order to execute 'abf mock' without --config"))
exit(1)
config_opts = {'plugins': [], 'scm_opts': {}}
config_opts['plugin_conf'] = {'ccache_opts': {}, 'root_cache_opts': {}, 'bind_mount_opts': {'dirs': []}, 'tmpfs_opts': {}, 'selinux_opts': {}}
try:
exec(compile(open(config_path).read(), config_path, 'exec'))
except Exception as ex:
log.error(_("Could not read the contents of '%(path)s': %(exception)s") % {'path': config_path, 'exception': str(ex)})
exit(2)
basedir = ('basedir' in config_opts and config_opts['basedir']) or '/var/lib/abf/mock'
root = config_opts['root']
resultsdir = ('resultdir' in config_opts and config_opts['resultdir']) or '%s/%s/result' % (basedir, root)
src_dir = basedir + '/src'
if os.path.exists(src_dir):
shutil.rmtree(src_dir)
src = get_root_git_dir()
if os.path.exists(os.path.join(src, '.abf.yml')):
cmd = ['abf', 'fetch']
if command_line.verbose:
cmd.append('-v')
execute_command(cmd, print_to_stdout=True, exit_on_error=True, cwd=src)
shutil.copytree(src, src_dir, symlinks=True)
spec_path = find_spec(src_dir)
if not spec_path:
log.error(_('Can not locate a spec file in %s') % src_dir)
exit(1)
spec_path = os.path.join(src_dir, spec_path)
cmd = ['mock', '-r', command_line.config, '--buildsrpm', '--spec', spec_path, '--sources', src_dir, '--configdir', configs_dir ]
if command_line.verbose:
cmd.append('-v')
log.info(_('Executing mock...'))
try:
res = execute_command(cmd, print_to_stdout=True, exit_on_error=False, shell=False)
except OSError as ex:
log.error(_("Can not execute mock (%s). Maybe it is not installed?") % str(ex))
exit(1)
finally:
shutil.rmtree(src_dir)
srpm_path = glob(os.path.join(resultsdir, '*.src.rpm'))
if len (srpm_path) != 1:
log.error(_('Could not find a single src.rpm file in %s') % resultsdir)
exit(1)
srpm_path = srpm_path[0]
srpm_path_new = os.path.join(os.getcwd(), os.path.basename(srpm_path))
if os.path.exists(srpm_path_new):
os.remove(srpm_path_new)
shutil.move(srpm_path, os.getcwd())
log.info(_('\nSRPM: %s\n') % srpm_path_new)
if binary:
cmd = ['mock', '-r', command_line.config, '--configdir', configs_dir, srpm_path_new]
if command_line.verbose:
cmd.append('-v')
log.info(_('Executing mock...'))
res = execute_command(cmd, print_to_stdout=True, exit_on_error=False, shell=False)
os.remove(srpm_path)
rpms = glob(os.path.join(resultsdir, '*.rpm'))
print('')
for rpm in rpms:
new_path = os.path.join(os.getcwd(), os.path.basename(rpm))
if os.path.exists(new_path):
os.remove(new_path)
shutil.move(rpm, os.getcwd())
print(_('RPM: ' + os.path.join(os.getcwd(), os.path.basename(rpm))))
def localbuild_mock_urpm():
# get project
proj = get_project(models, must_exist=True)
find_spec_problems()
try:
run_mock_urpm(binary=True)
except OSError as ex:
log.error(str(ex))
exit(1)
def alias():
log.debug('ALIAS started')
if command_line.command == 'list':
if not cfg['alias']:
log.info(_('No aliases found'))
return
for al_name in cfg['alias']:
print('%10s: %s' % (al_name, cfg['alias'][al_name]))
elif command_line.command == 'add':
if len(command_line.options) < 2:
log.error(_('Not enough options. Use it like "abf alias add <alias_name> opt1 [opt2 ...]"'))
exit(1)
al_name = command_line.options[0]
if ' ' in al_name or '=' in al_name:
log.error(_('Do not use " " or "=" for alias name!'))
exit(1)
alias = ''
for al in command_line.options[1:]:
if ' ' in al:
alias += '"%s" ' % al
else:
alias += al + ' '
if al_name in cfg['alias']:
log.warning(_('Alias "%s" already exists and will be overwritten.') % al_name)
cfg['alias'][al_name] = alias
log.info('Done')
elif command_line.command == 'remove':
if not command_line.options:
log.error(_("Enter the alias name!"))
exit(1)
al_name = command_line.options[0]
if al_name not in cfg['alias']:
log.error(_('Alias "%s" not found') % al_name)
exit(1)
cfg['alias'].pop(al_name)
log.info('Done')
def localbuild_rpmbuild():
log.debug(_('RPMBUILD started'))
src_dir = '/tmp/abf/rpmbuild'
mkdirs('/tmp/abf')
if os.path.exists(src_dir):
shutil.rmtree(src_dir)
src = get_root_git_dir()
if os.path.isfile(".abf.yml"):
cmd = ['abf', 'fetch']
if command_line.verbose:
cmd.append('-v')
execute_command(cmd, print_to_stdout=True, exit_on_error=True)
shutil.copytree(src, src_dir, symlinks=True)
spec_path = find_spec(src_dir)
if not spec_path:
log.error(_('Can not locate a spec file in %s') % src_dir)
exit(1)
spec_path = os.path.join(src_dir, spec_path)
spec_lines = open(spec_path, 'r').readlines()
if default_changelog == 'enabled':
if '%changelog' not in [line.strip() for line in spec_lines]:
log_lines = subprocess.run(f'cd "{src_dir}" && LC_ALL=C.UTF-8 git log --decorate=short', shell=True, capture_output=True).stdout.decode().split('\n')
branch = subprocess.run(f'cd "{src_dir}" && LC_ALL=C.UTF-8 git branch --show-current', shell=True, capture_output=True).stdout.decode().strip()
changelog_lines = create_changelog_from_log(log_lines, branch)
with open(spec_path, 'a') as out:
print(*changelog_lines, sep='\n', file=out)
cmd = ['rpmbuild', '-b'+command_line.build, '--define', '_topdir '+src_dir, '--define', '_sourcedir '+src_dir, spec_path]
if command_line.verbose:
cmd.append('-v')
log.info(_('Executing rpmbuild...'))
try:
res = execute_command(cmd, print_to_stdout=True, exit_on_error=False, shell=False)
except OSError as ex:
log.error(_("Can not execute rpmbuild (%s). Maybe it is not installed?") % str(ex))
exit(1)
except ReturnCodeNotZero:
log.info(_('Saving build folders to current directory...'))
if os.path.exists(src + "/BUILD"):
shutil.rmtree(src + "/BUILD")
if os.path.exists(src + "/BUILDROOT"):
shutil.rmtree(src + "/BUILDROOT")
if os.path.exists(src_dir + "/BUILD"):
shutil.copytree(src_dir + "/BUILD", src + "/BUILD", symlinks=True)
if os.path.exists(src_dir + "/BUILDROOT"):
shutil.copytree(src_dir + "/BUILDROOT", src + "/BUILDROOT", symlinks=True)
log.info(_('Moving files to the current directory...'))
if command_line.save_rpmbuild_folder:
shutil.copytree(src_dir, src + "/rpmbuild", symlinks=True)
else:
for item in os.listdir(src_dir):
if os.path.isfile(item) and not item.endswith('.spec') and item != ".abf.yml":
log.info(_('SOURCE: ') + item)
new_ff = os.path.join(os.getcwd(), item)
if os.path.exists(new_ff):
os.remove(new_ff)
shutil.move(src_dir + "/" + item, os.getcwd())
items = [x for x in os.walk(src_dir+'/SRPMS')] + [x for x in os.walk(src_dir+'/RPMS')]
for item in items:
path, dirs, files = item
for f in files:
if not f.endswith('.rpm'):
continue
ff = os.path.join(path, f)
new_ff = os.path.join(os.getcwd(), f)
if os.path.exists(new_ff):
os.remove(new_ff)
shutil.move(ff, os.getcwd())
if new_ff.endswith('.src.rpm'):
log.info(_('SRPM: ') + new_ff)
else:
log.info(_('RPM: ') + new_ff)
shutil.rmtree(src_dir)
def help():
if command_line.command:
sys.argv = [sys.argv[0], command_line.command, '-h']
else:
sys.argv = [sys.argv[0], '-h']
parse_command_line()
def search():
log.debug(_('SEARCH started'))
st = command_line.type
sq = command_line.query
cl = {'groups': Group, 'users': User, 'platforms': Platform, 'projects': Project}
items = cl[st].search(models, sq)
for item in items:
print(item)
def get_project_name_only(must_exist=True, name=None):
if name:
tmp = name.rstrip('/').split('/')
if len(tmp) > 2:
log.error(_('The project format is "[owner_name/]project_name"'))
exit(1)
elif len(tmp) == 1:
project_name = tmp[0]
log.info(_("The project group is assumed to be ") + default_group)
owner_name = default_group
else: # len == 2
owner_name = tmp[0]
project_name = tmp[1]
else:
owner_name, project_name = get_project_name()
if not project_name:
if must_exist:
log.error(_('You are not in a git repository directory. Specify the project name please!'))
exit(1)
else:
return None
_update_location()
return (owner_name, project_name)
def get_project(models, must_exist=True, name=None):
owner_name, project_name = get_project_name_only(must_exist, name)
try:
proj = Project.get_by_name(models, '%s/%s' % (owner_name, project_name))
except PageNotFoundError:
log.error(_('The project %(owner)s/%(project)s does not exist!') % {'owner': owner_name, 'project': project_name})
exit(1)
except ForbiddenError:
log.error(_('You do not have acces to the project %(owner)s/%(project)s!') % {'owner': owner_name, 'project': project_name})
exit(1)
log.debug(_('Project: %s') % proj)
return proj
def get_maintainer_id(models, name):
user_id = 0
try:
user_data = models.jsn.get_user_id(name)
user_id = user_data['user']['id']
except:
log.error(_('Failed to get ID for user ') + name)
exit(1)
return user_id
def split_repo_name(fullname):
items = fullname.rstrip('/').split('/')
if len(items) == 2:
repo_name = items[1]
pl_name = items[0]
elif len(items) == 1:
repo_name = items[0]
pl_name = default_build_platform
log.info(_("Platform is assumed to be ") + pl_name)
else:
log.error(_("repository argument format: [platform/]repository"))
exit(1)
return [repo_name, pl_name]
def get_repo_id(repo_name, pl_name):
# TODO: better to just get plaform by name...
platforms = Platform.search(models, pl_name)
plat_found = False
for plat in platforms:
if plat.name == pl_name:
plat_found = True
break
if not plat_found:
log.error(_("Platform %s doesn't exists!") % (pl_name))
exit(1)
repo_found = False
for repo in plat.repositories:
if repo.name == repo_name:
repo_found = True
break
if not repo_found:
log.error(_("Repository %s doesn't exists!") % (repo_name))
exit(1)
return repo.id
def get():
log.debug(_('GET started'))
proj = command_line.project.strip('/')
tmp = proj.split('/')
if len(tmp) > 2:
log.error(_('Specify a project name as "group_name/project_name" or just "project_name"'))
exit(1)
elif len(tmp) == 1:
project_name = tmp[0]
if 'openmandriva' in cfg['user']['default_group']:
proj = project_name
else:
proj = '%s/%s' % (cfg['user']['default_group'], proj)
elif len(tmp) == 2:
project_name = tmp[1]
if cfg['user']['git_uri'].startswith('git@'):
uri = "%s:%s.git" % (cfg['user']['git_uri'].rstrip(':'), proj)
else:
uri = "%s/%s.git" % (cfg['user']['git_uri'].rstrip('/'), proj)
cmd = ['git', 'clone', uri]
if command_line.branch:
cmd += ['-b', command_line.branch]
execute_command(cmd, print_to_stdout=True, exit_on_error=True)
if (not command_line.branch) and default_branch > '' and default_branch != 'master':
os.chdir(project_name)
check_branch = Popen(["git", "checkout", default_branch], stdout=PIPE, stderr=PIPE)
(output, err) = check_branch.communicate()
branch_missing = check_branch.wait()
if branch_missing != 0:
log.info(_("Branch " + default_branch + " is missing, will use HEAD"))
os.chdir("..")
if 'projects_cfg' in globals():
projects_cfg[proj]['location'] = os.path.join(os.getcwd(), project_name)
def destroy():
log.debug(_('DESTROY started'))
proj = get_project(models, must_exist=True, name=command_line.project)
ProjectCreator.destroy_project(models, proj.id)
def put():
log.debug(_('PUT started'))
path = get_root_git_dir()
if not path:
log.error(_("You have to be in a git repository directory"))
exit(1)
yaml_path = os.path.join(path, '.abf.yml')
_update_location()
try:
min_size = human2bytes(command_line.minimal_file_size)
except ValueError as ex:
log.error(_('Incorrect "--minimal-file-size" value: %s') % command_line.minimal_file_size)
exit(1)
error_count = upload_files(models, min_size, remove_files=not command_line.do_not_remove_files, path=path, upload_all=command_line.upload_all)
if error_count:
log.info(_('There were errors while uploading, stopping.'))
exit(1)
if not command_line.message:
return
if not command_line.add_folders:
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
if not is_text_file(f) and not command_line.add_binaries:
continue
cmd = ['git', 'add', f]
execute_command(cmd, print_to_stdout=True, exit_on_error=True)
else:
cmd = ['git', 'add', '--all']
execute_command(cmd, print_to_stdout=True, exit_on_error=True)
if os.path.isfile(yaml_path):
cmd = ['git', 'add', '-f', yaml_path]
execute_command(cmd, print_to_stdout=True, exit_on_error=True)
cmd = ['git', 'commit', '-m', command_line.message]
execute_command(cmd, print_to_stdout=True, exit_on_error=True)
log.info(_('Commited.'))
cmd = ['git', 'push']
execute_command(cmd, print_to_stdout=True, exit_on_error=True)
log.info(_('Pushed'))
def fetch():
log.debug(_('FETCH started'))
if command_line.filehash:
for filehash in command_line.filehash:
log.info(_("Fetching file with hash ") + filehash)
os.system("wget -c --content-disposition " + file_store_url + "/api/v1/file_stores/" + filehash)
exit(0)
path = get_root_git_dir()
if not path:
log.error(_("You have to be in a git repository directory"))
exit(1)
path = os.path.join(path, '.abf.yml')
if not os.path.isfile(path):
log.error(_('File "%s" can not be found') % path)
exit(1)
try:
fetch_files(models, path, command_line.only)
except yaml.scanner.ScannerError as ex:
log.error(_('Invalid yml file %(filename)s!\nProblem in line %(line)d column %(column)d: %(problem)s') % {'filename': path, 'line': ex.problem_mark.line, 'column': ex.problem_mark.column, 'problem': ex.problem})
except yaml.composer.ComposerError as ex:
log.error(_('Invalid yml file %(filename)s!\n%(exception)s') % {'filename': path, 'exception': ex})
def remote():
log.debug(_('REMOTE started'))
path = get_root_git_dir()
if not path:
log.error(_("You have to be in a git repository directory"))
exit(1)
owner_name, project_name = get_project_name()
if project_name is None:
log.error(_("Fail to detect project name"))
exit(1)
remote_group = command_line.remote_group
if command_line.remote_name:
project_name = command_line.remote_name
if cfg['user']['git_uri'].startswith('git@'):
uri = "%s:%s.git" % (cfg['user']['git_uri'].rstrip(':'), remote_group + "/" + project_name)
else:
uri = "%s/%s.git" % (cfg['user']['git_uri'].rstrip('/'), remote_group + "/" + project_name)
cmd = ['git', 'remote', 'add', remote_group, uri]
execute_command(cmd, print_to_stdout=True, exit_on_error=True)
cmd = ['git', 'fetch', remote_group]
execute_command(cmd, print_to_stdout=True, exit_on_error=True)
def store():
log.debug(_('STORE started'))
p = os.path.expanduser(command_line.path)
if not os.path.exists(p):
log.error(_('File "%s" does not exist!') % p)
exit(1)
if not os.path.isfile(p):
log.error(_('"%s" is not a regular file!') % p)
exit(1)
res = models.jsn.upload_file(p, silent=True)
print(p + ":", res)
def copy():
log.debug(_('COPY started'))
sbrn = command_line.src_branch
start_branch = get_branch_name()
if not start_branch:
log.error(_("You are not in a git directory"))
exit(1)
log.debug(_("Current branch is ") + start_branch)
if command_line.dst_branch:
dbrn = command_line.dst_branch
else:
dbrn = start_branch
if sbrn == dbrn:
log.error(_("Source and destination branches shold be different branches!"))
exit(1)
path = get_root_git_dir()
log.debug(_("Repository root folder is ") + path)
_update_location(path=path)
stage = 0
try:
if start_branch != dbrn:
cmd = ['git', 'checkout', dbrn]
execute_command(cmd, print_to_stdout=True, cwd=path)
stage = 1
cmd = ['rm', '-rf', './*']
execute_command(cmd, print_to_stdout=True, cwd=path)
stage = 2
cmd = ['git', 'checkout', sbrn, '*']
execute_command(cmd, print_to_stdout=True, cwd=path)
stage = 3
if command_line.pack:
pack_project(path)
cmd = ['git', 'reset']
execute_command(cmd, print_to_stdout=True, cwd=path)
except Exception as ex:
if type(ex) == ReturnCodeNotZero:
log.error(str(ex))
else:
log.exception(ex)
if stage == 1 or stage == 2:
log.info(_("Checking out the initial branch (%s)") % start_branch)
cmd = ['git', 'reset', '--hard', start_branch]
execute_command(cmd, print_to_stdout=True, cwd=path)
log.info('Done')
def pull_request():
log.debug(_('PULL REQUEST started'))
proj = get_project(models, must_exist=True, name=command_line.project)
if command_line.dest:
dest_proj = get_project(models, must_exist=True, name=command_line.dest)
else:
dest_proj = get_project(models, must_exist=True, name=command_line.project)
PullRequest.new_pull_request(models, proj, dest_proj, command_line.title, command_line.body, command_line.to_ref, command_line.from_ref)
def fork_project():
log.debug(_('FORK PROJECT started'))
source_proj = get_project(models, must_exist=True, name=command_line.source_project)
if command_line.target_project:
tmp = get_project_name_only(True, command_line.target_project)
target_group = tmp[0]
target_name = tmp[1]
else:
target_group = default_group
target_name = source_proj.name