/
command.py
2035 lines (1795 loc) · 108 KB
/
command.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
import inspect
import json
import os
import sys
import argparse
import six
from argparse import ArgumentError
from difflib import get_close_matches
from conans import __version__ as client_version
from conans.client.cmd.uploader import UPLOAD_POLICY_FORCE, \
UPLOAD_POLICY_NO_OVERWRITE, UPLOAD_POLICY_NO_OVERWRITE_RECIPE, UPLOAD_POLICY_SKIP
from conans.client.conan_api import (Conan, default_manifest_folder, _make_abs_path)
from conans.client.conan_command_output import CommandOutputer
from conans.client.output import Color
from conans.client.printer import Printer
from conans.errors import ConanException, ConanInvalidConfiguration, NoRemoteAvailable, \
ConanMigrationError
from conans.model.ref import ConanFileReference, PackageReference, get_reference_fields, \
check_valid_ref
from conans.unicode import get_cwd
from conans.util.config_parser import get_bool_from_text
from conans.util.files import exception_message_safe
from conans.util.files import save
from conans.util.log import logger
# Exit codes for conan command:
SUCCESS = 0 # 0: Success (done)
ERROR_GENERAL = 1 # 1: General ConanException error (done)
ERROR_MIGRATION = 2 # 2: Migration error
USER_CTRL_C = 3 # 3: Ctrl+C
USER_CTRL_BREAK = 4 # 4: Ctrl+Break
ERROR_SIGTERM = 5 # 5: SIGTERM
ERROR_INVALID_CONFIGURATION = 6 # 6: Invalid configuration (done)
class Extender(argparse.Action):
"""Allows to use the same flag several times in a command and creates a list with the values.
For example:
conan install MyPackage/1.2@user/channel -o qt:value -o mode:2 -s cucumber:true
It creates:
options = ['qt:value', 'mode:2']
settings = ['cucumber:true']
"""
def __call__(self, parser, namespace, values, option_strings=None): # @UnusedVariable
# Need None here incase `argparse.SUPPRESS` was supplied for `dest`
dest = getattr(namespace, self.dest, None)
if not hasattr(dest, 'extend') or dest == self.default:
dest = []
setattr(namespace, self.dest, dest)
# if default isn't set to None, this method might be called
# with the default as `values` for other arguments which
# share this destination.
parser.set_defaults(**{self.dest: None})
if isinstance(values, str):
dest.append(values)
elif values:
try:
dest.extend(values)
except ValueError:
dest.append(values)
class OnceArgument(argparse.Action):
"""Allows to declare a parameter that can have only one value, by default argparse takes the
latest declared and it's very confusing.
"""
def __call__(self, parser, namespace, values, option_string=None):
if getattr(namespace, self.dest) is not None and self.default is None:
msg = '{o} can only be specified once'.format(o=option_string)
raise argparse.ArgumentError(None, msg)
setattr(namespace, self.dest, values)
class SmartFormatter(argparse.HelpFormatter):
def _fill_text(self, text, width, indent):
import textwrap
text = textwrap.dedent(text)
return ''.join(indent + line for line in text.splitlines(True))
_QUERY_EXAMPLE = ("os=Windows AND (arch=x86 OR compiler=gcc)")
_PATTERN_EXAMPLE = ("boost/*")
_REFERENCE_EXAMPLE = ("MyPackage/1.2@user/channel")
_PREF_EXAMPLE = ("MyPackage/1.2@user/channel:af7901d8bdfde621d086181aa1c495c25a17b137")
_BUILD_FOLDER_HELP = ("Directory for the build process. Defaulted to the current directory. A "
"relative path to current directory can also be specified")
_INSTALL_FOLDER_HELP = ("Directory containing the conaninfo.txt and conanbuildinfo.txt files "
"(from previous 'conan install'). Defaulted to --build-folder")
_KEEP_SOURCE_HELP = ("Do not remove the source folder in local cache, even if the recipe changed. "
"Use this for testing purposes only")
_PATTERN_OR_REFERENCE_HELP = ("Pattern or package recipe reference, e.g., '%s', "
"'%s'" % (_PATTERN_EXAMPLE, _REFERENCE_EXAMPLE))
_PATTERN_REF_OR_PREF_HELP = ("Pattern, recipe reference or package reference e.g., '%s', "
"'%s', '%s'" % (_PATTERN_EXAMPLE, _REFERENCE_EXAMPLE, _PREF_EXAMPLE))
_REF_OR_PREF_HELP = ("Recipe reference or package reference e.g., '%s', "
"'%s'" % (_REFERENCE_EXAMPLE, _PREF_EXAMPLE))
_PATH_HELP = ("Path to a folder containing a conanfile.py or to a recipe file "
"e.g., my_folder/conanfile.py")
_QUERY_HELP = ("Packages query: '%s'. The 'pattern_or_reference' parameter has "
"to be a reference: %s" % (_QUERY_EXAMPLE, _REFERENCE_EXAMPLE))
_SOURCE_FOLDER_HELP = ("Directory containing the sources. Defaulted to the conanfile's directory. A"
" relative path to current directory can also be specified")
class Command(object):
"""A single command of the conan application, with all the first level commands. Manages the
parsing of parameters and delegates functionality in collaborators. It can also show help of the
tool.
"""
def __init__(self, conan_api):
assert isinstance(conan_api, Conan)
self._conan = conan_api
self._out = conan_api.out
@property
def _outputer(self):
# FIXME, this access to the cache for output is ugly, should be removed
return CommandOutputer(self._out, self._conan.app.cache)
def help(self, *args):
"""
Shows help for a specific command.
"""
parser = argparse.ArgumentParser(description=self.help.__doc__,
prog="conan help",
formatter_class=SmartFormatter)
parser.add_argument("command", help='command', nargs="?")
args = parser.parse_args(*args)
if not args.command:
self._show_help()
return
try:
commands = self._commands()
method = commands[args.command]
self._warn_python2()
method(["--help"])
except KeyError:
raise ConanException("Unknown command '%s'" % args.command)
def new(self, *args):
"""
Creates a new package recipe template with a 'conanfile.py' and optionally,
'test_package' testing files.
"""
parser = argparse.ArgumentParser(description=self.new.__doc__,
prog="conan new",
formatter_class=SmartFormatter)
parser.add_argument("name", help='Package name, e.g.: "Poco/1.7.3" or complete reference'
' for CI scripts: "Poco/1.7.3@conan/stable"')
parser.add_argument("-t", "--test", action='store_true', default=False,
help='Create test_package skeleton to test package')
parser.add_argument("-i", "--header", action='store_true', default=False,
help='Create a headers only package template')
parser.add_argument("-c", "--pure-c", action='store_true', default=False,
help='Create a C language package only package, '
'deleting "self.settings.compiler.libcxx" setting '
'in the configure method')
parser.add_argument("-s", "--sources", action='store_true', default=False,
help='Create a package with embedded sources in "src" folder, '
'using "exports_sources" instead of retrieving external code with '
'the "source()" method')
parser.add_argument("-b", "--bare", action='store_true', default=False,
help='Create the minimum package recipe, without build() method. '
'Useful in combination with "export-pkg" command')
parser.add_argument("-m", "--template",
help='Use the given template from the local cache for conanfile.py')
parser.add_argument("-cis", "--ci-shared", action='store_true',
default=False,
help='Package will have a "shared" option to be used in CI')
parser.add_argument("-cilg", "--ci-travis-gcc", action='store_true',
default=False,
help='Generate travis-ci files for linux gcc')
parser.add_argument("-cilc", "--ci-travis-clang", action='store_true',
default=False,
help='Generate travis-ci files for linux clang')
parser.add_argument("-cio", "--ci-travis-osx", action='store_true',
default=False,
help='Generate travis-ci files for OSX apple-clang')
parser.add_argument("-ciw", "--ci-appveyor-win", action='store_true',
default=False, help='Generate appveyor files for Appveyor '
'Visual Studio')
parser.add_argument("-ciglg", "--ci-gitlab-gcc", action='store_true',
default=False,
help='Generate GitLab files for linux gcc')
parser.add_argument("-ciglc", "--ci-gitlab-clang", action='store_true',
default=False,
help='Generate GitLab files for linux clang')
parser.add_argument("-ciccg", "--ci-circleci-gcc", action='store_true',
default=False,
help='Generate CircleCI files for linux gcc')
parser.add_argument("-ciccc", "--ci-circleci-clang", action='store_true',
default=False,
help='Generate CircleCI files for linux clang')
parser.add_argument("-cicco", "--ci-circleci-osx", action='store_true',
default=False,
help='Generate CircleCI files for OSX apple-clang')
parser.add_argument("-gi", "--gitignore", action='store_true', default=False,
help='Generate a .gitignore with the known patterns to excluded')
parser.add_argument("-ciu", "--ci-upload-url",
help='Define URL of the repository to upload')
args = parser.parse_args(*args)
self._warn_python2()
self._conan.new(args.name, header=args.header, pure_c=args.pure_c, test=args.test,
exports_sources=args.sources, bare=args.bare,
visual_versions=args.ci_appveyor_win,
linux_gcc_versions=args.ci_travis_gcc,
linux_clang_versions=args.ci_travis_clang,
gitignore=args.gitignore,
osx_clang_versions=args.ci_travis_osx, shared=args.ci_shared,
upload_url=args.ci_upload_url,
gitlab_gcc_versions=args.ci_gitlab_gcc,
gitlab_clang_versions=args.ci_gitlab_clang,
circleci_gcc_versions=args.ci_circleci_gcc,
circleci_clang_versions=args.ci_circleci_clang,
circleci_osx_versions=args.ci_circleci_osx,
template=args.template)
def inspect(self, *args):
"""
Displays conanfile attributes, like name, version and options. Works locally,
in local cache and remote.
"""
parser = argparse.ArgumentParser(description=self.inspect.__doc__,
prog="conan inspect",
formatter_class=SmartFormatter)
parser.add_argument("path_or_reference", help="Path to a folder containing a recipe"
" (conanfile.py) or to a recipe file. e.g., "
"./my_project/conanfile.py. It could also be a reference")
parser.add_argument("-a", "--attribute", help='The attribute to be displayed, e.g "name"',
nargs="?", action=Extender)
parser.add_argument("-r", "--remote", help='look in the specified remote server',
action=OnceArgument)
parser.add_argument("-j", "--json", default=None, action=OnceArgument,
help='json output file')
parser.add_argument('--raw', default=None, action=OnceArgument,
help='Print just the value of the requested attribute')
args = parser.parse_args(*args)
if args.raw and args.attribute:
raise ConanException("Argument '--raw' is incompatible with '-a'")
if args.raw and args.json:
raise ConanException("Argument '--raw' is incompatible with '--json'")
attributes = [args.raw, ] if args.raw else args.attribute
result = self._conan.inspect(args.path_or_reference, attributes, args.remote)
Printer(self._out).print_inspect(result, raw=args.raw)
if args.json:
json_output = json.dumps(result)
if not os.path.isabs(args.json):
json_output_file = os.path.join(get_cwd(), args.json)
else:
json_output_file = args.json
save(json_output_file, json_output)
def test(self, *args):
"""
Tests a package consuming it from a conanfile.py with a test() method.
This command installs the conanfile dependencies (including the tested
package), calls a 'conan build' to build test apps and finally executes
the test() method. The testing recipe does not require name or version,
neither definition of package() or package_info() methods. The package
to be tested must exist in the local cache or in any configured remote.
"""
parser = argparse.ArgumentParser(description=self.test.__doc__,
prog="conan test",
formatter_class=SmartFormatter)
parser.add_argument("path", help='Path to the "testing" folder containing a conanfile.py or'
' to a recipe file with test() method'
'e.g. conan test_package/conanfile.py pkg/version@user/channel')
parser.add_argument("reference",
help='pkg/version@user/channel of the package to be tested')
parser.add_argument("-tbf", "--test-build-folder", action=OnceArgument,
help="Working directory of the build process.")
_add_common_install_arguments(parser, build_help=_help_build_policies)
args = parser.parse_args(*args)
self._warn_python2()
return self._conan.test(args.path, args.reference, args.profile, args.settings,
args.options, args.env, args.remote, args.update,
build_modes=args.build, test_build_folder=args.test_build_folder,
lockfile=args.lockfile)
def create(self, *args):
"""
Builds a binary package for a recipe (conanfile.py).
Uses the specified configuration in a profile or in -s settings, -o
options etc. If a 'test_package' folder (the name can be configured
with -tf) is found, the command will run the consumer project to ensure
that the package has been created correctly. Check 'conan test' command
to know more about 'test_folder' project.
"""
parser = argparse.ArgumentParser(description=self.create.__doc__,
prog="conan create",
formatter_class=SmartFormatter)
parser.add_argument("path", help=_PATH_HELP)
parser.add_argument("reference", nargs='?', default=None,
help='user/channel, version@user/channel or pkg/version@user/channel '
'(if name or version declared in conanfile.py, they should match)')
parser.add_argument("-j", "--json", default=None, action=OnceArgument,
help='json file path where the install information will be written to')
parser.add_argument('-k', '-ks', '--keep-source', default=False, action='store_true',
help=_KEEP_SOURCE_HELP)
parser.add_argument('-kb', '--keep-build', default=False, action='store_true',
help='Do not remove the build folder in local cache. '
'Implies --keep-source. '
'Use this for testing purposes only')
parser.add_argument("-ne", "--not-export", default=False, action='store_true',
help='Do not export the conanfile.py')
parser.add_argument("-tbf", "--test-build-folder", action=OnceArgument,
help='Working directory for the build of the test project.')
parser.add_argument("-tf", "--test-folder", action=OnceArgument,
help='Alternative test folder name. By default it is "test_package". '
'Use "None" to skip the test stage')
_add_manifests_arguments(parser)
_add_common_install_arguments(parser, build_help=_help_build_policies)
args = parser.parse_args(*args)
self._warn_python2()
name, version, user, channel, _ = get_reference_fields(args.reference,
user_channel_input=True)
if any([user, channel]) and not all([user, channel]):
# Or user/channel or nothing, but not partial
raise ConanException("Invalid parameter '%s', "
"specify the full reference or user/channel" % args.reference)
if args.test_folder == "None":
# Now if parameter --test-folder=None (string None) we have to skip tests
args.test_folder = False
cwd = get_cwd()
info = None
try:
info = self._conan.create(args.path, name, version, user, channel,
args.profile, args.settings, args.options,
args.env, args.test_folder, args.not_export,
args.build, args.keep_source, args.keep_build, args.verify,
args.manifests, args.manifests_interactive,
args.remote, args.update,
test_build_folder=args.test_build_folder,
lockfile=args.lockfile)
except ConanException as exc:
info = exc.info
raise
finally:
if args.json and info:
self._outputer.json_output(info, args.json, cwd)
def download(self, *args):
"""
Downloads recipe and binaries to the local cache, without using settings.
It works specifying the recipe reference and package ID to be
installed. Not transitive, requirements of the specified reference will
NOT be retrieved. Useful together with 'conan copy' to automate the
promotion of packages to a different user/channel. Only if a reference
is specified, it will download all packages from the specified remote.
If no remote is specified, it will use the default remote.
"""
parser = argparse.ArgumentParser(description=self.download.__doc__,
prog="conan download",
formatter_class=SmartFormatter)
parser.add_argument("reference",
help='pkg/version@user/channel')
parser.add_argument("-p", "--package", nargs=1, action=Extender,
help='Force install specified package ID (ignore settings/options)'
' [DEPRECATED: use full reference instead]')
parser.add_argument("-r", "--remote", help='look in the specified remote server',
action=OnceArgument)
parser.add_argument("-re", "--recipe", help='Downloads only the recipe', default=False,
action="store_true")
args = parser.parse_args(*args)
try:
pref = PackageReference.loads(args.reference, validate=True)
except ConanException:
reference = args.reference
packages_list = args.package
if packages_list:
self._out.warn("Usage of `--package` argument is deprecated."
" Use a full reference instead: "
"`conan download [...] {}:{}`".format(reference, packages_list[0]))
else:
reference = repr(pref.ref)
packages_list = [pref.id]
if args.package:
raise ConanException("Use a full package reference (preferred) or the `--package`"
" command argument, but not both.")
self._warn_python2()
return self._conan.download(reference=reference, packages=packages_list,
remote_name=args.remote, recipe=args.recipe)
def install(self, *args):
"""
Installs the requirements specified in a recipe (conanfile.py or conanfile.txt).
It can also be used to install a concrete package specifying a
reference. If any requirement is not found in the local cache, it will
retrieve the recipe from a remote, looking for it sequentially in the
configured remotes. When the recipes have been downloaded it will try
to download a binary package matching the specified settings, only from
the remote from which the recipe was retrieved. If no binary package is
found, it can be build from sources using the '--build' option. When
the package is installed, Conan will write the files for the specified
generators.
"""
parser = argparse.ArgumentParser(description=self.install.__doc__,
prog="conan install",
formatter_class=SmartFormatter)
parser.add_argument("path_or_reference", help="Path to a folder containing a recipe"
" (conanfile.py or conanfile.txt) or to a recipe file. e.g., "
"./my_project/conanfile.txt. It could also be a reference")
parser.add_argument("reference", nargs="?",
help='Reference for the conanfile path of the first argument: '
'user/channel, version@user/channel or pkg/version@user/channel'
'(if name or version declared in conanfile.py, they should match)')
parser.add_argument("-g", "--generator", nargs=1, action=Extender,
help='Generators to use')
parser.add_argument("-if", "--install-folder", action=OnceArgument,
help='Use this directory as the directory where to put the generator'
'files. e.g., conaninfo/conanbuildinfo.txt')
_add_manifests_arguments(parser)
parser.add_argument("--no-imports", action='store_true', default=False,
help='Install specified packages but avoid running imports')
parser.add_argument("-j", "--json", default=None, action=OnceArgument,
help='Path to a json file where the install information will be '
'written')
_add_common_install_arguments(parser, build_help=_help_build_policies)
args = parser.parse_args(*args)
cwd = get_cwd()
# We need @ otherwise it could be a path, so check strict
path_is_reference = check_valid_ref(args.path_or_reference)
info = None
try:
if not path_is_reference:
name, version, user, channel, _ = get_reference_fields(args.reference,
user_channel_input=True)
info = self._conan.install(path=args.path_or_reference,
name=name, version=version, user=user, channel=channel,
settings=args.settings, options=args.options,
env=args.env,
remote_name=args.remote,
verify=args.verify, manifests=args.manifests,
manifests_interactive=args.manifests_interactive,
build=args.build, profile_names=args.profile,
update=args.update, generators=args.generator,
no_imports=args.no_imports,
install_folder=args.install_folder,
lockfile=args.lockfile)
else:
if args.reference:
raise ConanException("A full reference was provided as first argument, second "
"argument not allowed")
ref = ConanFileReference.loads(args.path_or_reference, validate=False)
manifest_interactive = args.manifests_interactive
info = self._conan.install_reference(ref, settings=args.settings,
options=args.options,
env=args.env,
remote_name=args.remote,
verify=args.verify, manifests=args.manifests,
manifests_interactive=manifest_interactive,
build=args.build, profile_names=args.profile,
update=args.update,
generators=args.generator,
install_folder=args.install_folder,
lockfile=args.lockfile)
except ConanException as exc:
info = exc.info
raise
finally:
if args.json and info:
self._outputer.json_output(info, args.json, cwd)
def config(self, *args):
"""
Manages Conan configuration.
Used to edit conan.conf, or install config files.
"""
parser = argparse.ArgumentParser(description=self.config.__doc__,
prog="conan config",
formatter_class=SmartFormatter)
subparsers = parser.add_subparsers(dest='subcommand', help='sub-command help')
subparsers.required = True
get_subparser = subparsers.add_parser('get', help='Get the value of configuration item')
subparsers.add_parser('home', help='Retrieve the Conan home directory')
install_subparser = subparsers.add_parser('install', help='Install a full configuration '
'from a local or remote zip file')
rm_subparser = subparsers.add_parser('rm', help='Remove an existing config element')
set_subparser = subparsers.add_parser('set', help='Set a value for a configuration item')
rm_subparser.add_argument("item", help="Item to remove")
get_subparser.add_argument("item", nargs="?", help="Item to print")
set_subparser.add_argument("item", help="'item=value' to set")
install_subparser.add_argument("item", nargs="?",
help="git repository, local folder or zip file (local or "
"http) where the configuration is stored")
install_subparser.add_argument("--verify-ssl", nargs="?", default="True",
help='Verify SSL connection when downloading file')
install_subparser.add_argument("--type", "-t", choices=["git"],
help='Type of remote config')
install_subparser.add_argument("--args", "-a",
help='String with extra arguments for "git clone"')
install_subparser.add_argument("-sf", "--source-folder",
help='Install files only from a source subfolder from the '
'specified origin')
install_subparser.add_argument("-tf", "--target-folder",
help='Install to that path in the conan cache')
args = parser.parse_args(*args)
if args.subcommand == "set":
try:
key, value = args.item.split("=", 1)
except ValueError:
if "hooks." in args.item:
key, value = args.item.split("=", 1)[0], None
else:
raise ConanException("Please specify 'key=value'")
return self._conan.config_set(key, value)
elif args.subcommand == "get":
return self._conan.config_get(args.item)
elif args.subcommand == "rm":
return self._conan.config_rm(args.item)
elif args.subcommand == "home":
conan_home = self._conan.config_home()
self._out.info(conan_home)
return conan_home
elif args.subcommand == "install":
verify_ssl = get_bool_from_text(args.verify_ssl)
return self._conan.config_install(args.item, verify_ssl, args.type, args.args,
source_folder=args.source_folder,
target_folder=args.target_folder)
def info(self, *args):
"""
Gets information about the dependency graph of a recipe.
It can be used with a recipe or a reference for any existing package in
your local cache.
"""
info_only_options = ["id", "build_id", "remote", "url", "license", "requires", "update",
"required", "date", "author", "None"]
path_only_options = ["export_folder", "build_folder", "package_folder", "source_folder"]
str_path_only_options = ", ".join(['"%s"' % field for field in path_only_options])
str_only_options = ", ".join(['"%s"' % field for field in info_only_options])
parser = argparse.ArgumentParser(description=self.info.__doc__,
prog="conan info",
formatter_class=SmartFormatter)
parser.add_argument("path_or_reference", help="Path to a folder containing a recipe"
" (conanfile.py or conanfile.txt) or to a recipe file. e.g., "
"./my_project/conanfile.txt. It could also be a reference")
parser.add_argument("--paths", action='store_true', default=False,
help='Show package paths in local cache')
parser.add_argument("-bo", "--build-order",
help='given a modified reference, return an ordered list to build (CI)',
nargs=1, action=Extender)
parser.add_argument("-g", "--graph", action=OnceArgument,
help='Creates file with project dependencies graph. It will generate '
'a DOT or HTML file depending on the filename extension')
parser.add_argument("-if", "--install-folder", action=OnceArgument,
help="local folder containing the conaninfo.txt and conanbuildinfo.txt "
"files (from a previous conan install execution). Defaulted to "
"current folder, unless --profile, -s or -o is specified. If you "
"specify both install-folder and any setting/option "
"it will raise an error.")
parser.add_argument("-j", "--json", nargs='?', const="1", type=str,
help='Path to a json file where the information will be written')
parser.add_argument("-n", "--only", nargs=1, action=Extender,
help="Show only the specified fields: %s. '--paths' information can "
"also be filtered with options %s. Use '--only None' to show only "
"references." % (str_only_options, str_path_only_options))
parser.add_argument("--package-filter", nargs='?',
help='Print information only for packages that match the filter pattern'
' e.g., MyPackage/1.2@user/channel or MyPackage*')
dry_build_help = ("Apply the --build argument to output the information, "
"as it would be done by the install command")
parser.add_argument("-db", "--dry-build", action=Extender, nargs="?", help=dry_build_help)
build_help = ("Given a build policy, return an ordered list of packages that would be built"
" from sources during the install command")
_add_common_install_arguments(parser, build_help=build_help)
args = parser.parse_args(*args)
if args.install_folder and (args.profile or args.settings or args.options or args.env):
raise ArgumentError(None,
"--install-folder cannot be used together with -s, -o, -e or -pr")
if args.build_order and args.graph:
raise ArgumentError(None,
"--build-order cannot be used together with --graph")
# BUILD ORDER ONLY
if args.build_order:
ret = self._conan.info_build_order(args.path_or_reference,
settings=args.settings,
options=args.options,
env=args.env,
profile_names=args.profile,
remote_name=args.remote,
build_order=args.build_order,
check_updates=args.update,
install_folder=args.install_folder)
if args.json:
json_arg = True if args.json == "1" else args.json
self._outputer.json_build_order(ret, json_arg, get_cwd())
else:
self._outputer.build_order(ret)
# INSTALL SIMULATION, NODES TO INSTALL
elif args.build is not None:
nodes, _ = self._conan.info_nodes_to_build(args.path_or_reference,
build_modes=args.build,
settings=args.settings,
options=args.options,
env=args.env,
profile_names=args.profile,
remote_name=args.remote,
check_updates=args.update,
install_folder=args.install_folder)
if args.json:
json_arg = True if args.json == "1" else args.json
self._outputer.json_nodes_to_build(nodes, json_arg, get_cwd())
else:
self._outputer.nodes_to_build(nodes)
# INFO ABOUT DEPS OF CURRENT PROJECT OR REFERENCE
else:
data = self._conan.info(args.path_or_reference,
remote_name=args.remote,
settings=args.settings,
options=args.options,
env=args.env,
profile_names=args.profile,
update=args.update,
install_folder=args.install_folder,
build=args.dry_build,
lockfile=args.lockfile)
deps_graph, _ = data
only = args.only
if args.only == ["None"]:
only = []
if only and args.paths and (set(only) - set(path_only_options)):
raise ConanException("Invalid --only value '%s' with --path specified, allowed "
"values: [%s]." % (only, str_path_only_options))
elif only and not args.paths and (set(only) - set(info_only_options)):
raise ConanException("Invalid --only value '%s', allowed values: [%s].\n"
"Use --only=None to show only the references."
% (only, str_only_options))
if args.graph:
self._outputer.info_graph(args.graph, deps_graph, get_cwd())
if args.json:
json_arg = True if args.json == "1" else args.json
self._outputer.json_info(deps_graph, json_arg, get_cwd(), show_paths=args.paths)
if not args.graph and not args.json:
self._outputer.info(deps_graph, only, args.package_filter, args.paths)
def source(self, *args):
"""
Calls your local conanfile.py 'source()' method.
Usually downloads and uncompresses the package sources.
"""
parser = argparse.ArgumentParser(description=self.source.__doc__,
prog="conan source",
formatter_class=SmartFormatter)
parser.add_argument("path", help=_PATH_HELP)
parser.add_argument("-sf", "--source-folder", action=OnceArgument,
help='Destination directory. Defaulted to current directory')
parser.add_argument("-if", "--install-folder", action=OnceArgument,
help=_INSTALL_FOLDER_HELP + " Optional, source method will run without "
"the information retrieved from the conaninfo.txt and "
"conanbuildinfo.txt, only required when using conditional source() "
"based on settings, options, env_info and user_info")
args = parser.parse_args(*args)
try:
if "@" in args.path and ConanFileReference.loads(args.path):
raise ArgumentError(None,
"'conan source' doesn't accept a reference anymore. "
"If you were using it as a concurrency workaround, "
"you can call 'conan install' simultaneously from several "
"different processes, the concurrency is now natively supported"
". The path parameter should be a folder containing a "
"conanfile.py file.")
except ConanException:
pass
self._warn_python2()
return self._conan.source(args.path, args.source_folder, args.install_folder)
def build(self, *args):
"""
Calls your local conanfile.py 'build()' method.
The recipe will be built in the local directory specified by
--build-folder, reading the sources from --source-folder. If you are
using a build helper, like CMake(), the --package-folder will be
configured as destination folder for the install step.
"""
parser = argparse.ArgumentParser(description=self.build.__doc__,
prog="conan build",
formatter_class=SmartFormatter)
parser.add_argument("path", help=_PATH_HELP)
parser.add_argument("-b", "--build", default=None, action="store_true",
help="Execute the build step (variable should_build=True). When "
"specified, configure/install/test won't run unless "
"--configure/--install/--test specified")
parser.add_argument("-bf", "--build-folder", action=OnceArgument, help=_BUILD_FOLDER_HELP)
parser.add_argument("-c", "--configure", default=None, action="store_true",
help="Execute the configuration step (variable should_configure=True). "
"When specified, build/install/test won't run unless "
"--build/--install/--test specified")
parser.add_argument("-i", "--install", default=None, action="store_true",
help="Execute the install step (variable should_install=True). When "
"specified, configure/build/test won't run unless "
"--configure/--build/--test specified")
parser.add_argument("-t", "--test", default=None, action="store_true",
help="Execute the test step (variable should_test=True). When "
"specified, configure/build/install won't run unless "
"--configure/--build/--install specified")
parser.add_argument("-if", "--install-folder", action=OnceArgument,
help=_INSTALL_FOLDER_HELP)
parser.add_argument("-pf", "--package-folder", action=OnceArgument,
help="Directory to install the package (when the build system or "
"build() method does it). Defaulted to the '{build_folder}/package' "
"folder. A relative path can be specified, relative to the current "
"folder. Also an absolute path is allowed.")
parser.add_argument("-sf", "--source-folder", action=OnceArgument, help=_SOURCE_FOLDER_HELP)
args = parser.parse_args(*args)
self._warn_python2()
if args.build or args.configure or args.install or args.test:
build, config, install, test = (bool(args.build), bool(args.configure),
bool(args.install), bool(args.test))
else:
build = config = install = test = True
return self._conan.build(conanfile_path=args.path,
source_folder=args.source_folder,
package_folder=args.package_folder,
build_folder=args.build_folder,
install_folder=args.install_folder,
should_configure=config,
should_build=build,
should_install=install,
should_test=test)
def package(self, *args):
"""
Calls your local conanfile.py 'package()' method.
This command works in the user space and it will copy artifacts from
the --build-folder and --source-folder folder to the --package-folder
one. It won't create a new package in the local cache, if you want to
do it, use 'conan create' or 'conan export-pkg' after a 'conan build'
command.
"""
parser = argparse.ArgumentParser(description=self.package.__doc__,
prog="conan package",
formatter_class=SmartFormatter)
parser.add_argument("path", help=_PATH_HELP)
parser.add_argument("-bf", "--build-folder", action=OnceArgument, help=_BUILD_FOLDER_HELP)
parser.add_argument("-if", "--install-folder", action=OnceArgument,
help=_INSTALL_FOLDER_HELP)
parser.add_argument("-pf", "--package-folder", action=OnceArgument,
help="folder to install the package. Defaulted to the "
"'{build_folder}/package' folder. A relative path can be specified"
" (relative to the current directory). Also an absolute path"
" is allowed.")
parser.add_argument("-sf", "--source-folder", action=OnceArgument, help=_SOURCE_FOLDER_HELP)
args = parser.parse_args(*args)
try:
if "@" in args.path and ConanFileReference.loads(args.path):
raise ArgumentError(None,
"'conan package' doesn't accept a reference anymore. "
"The path parameter should be a conanfile.py or a folder "
"containing one. If you were using the 'conan package' "
"command for development purposes we recommend to use "
"the local development commands: 'conan build' + "
"'conan package' and finally 'conan create' to regenerate the "
"package, or 'conan export_package' to store the already built "
"binaries in the local cache without rebuilding them.")
except ConanException:
pass
self._warn_python2()
return self._conan.package(path=args.path,
build_folder=args.build_folder,
package_folder=args.package_folder,
source_folder=args.source_folder,
install_folder=args.install_folder)
def imports(self, *args):
"""
Calls your local conanfile.py or conanfile.txt 'imports' method.
It requires to have been previously installed and have a
conanbuildinfo.txt generated file in the --install-folder (defaulted to
current directory).
"""
parser = argparse.ArgumentParser(description=self.imports.__doc__,
prog="conan imports",
formatter_class=SmartFormatter)
parser.add_argument("path",
help=_PATH_HELP + " With --undo option, this parameter is the folder "
"containing the conan_imports_manifest.txt file generated in a previous"
" execution. e.g.: conan imports ./imported_files --undo ")
parser.add_argument("-if", "--install-folder", action=OnceArgument,
help=_INSTALL_FOLDER_HELP)
parser.add_argument("-imf", "--import-folder", action=OnceArgument,
help="Directory to copy the artifacts to. By default it will be the"
" current directory")
parser.add_argument("-u", "--undo", default=False, action="store_true",
help="Undo imports. Remove imported files")
args = parser.parse_args(*args)
if args.undo:
return self._conan.imports_undo(args.path)
try:
if "@" in args.path and ConanFileReference.loads(args.path):
raise ArgumentError(None, "Parameter 'path' cannot be a reference. Use a folder "
"containing a conanfile.py or conanfile.txt file.")
except ConanException:
pass
self._warn_python2()
return self._conan.imports(args.path, args.import_folder, args.install_folder)
def export_pkg(self, *args):
"""
Exports a recipe, then creates a package from local source and build folders.
If '--package-folder' is provided it will copy the files from there, otherwise it
will execute package() method over '--source-folder' and '--build-folder' to create
the binary package.
"""
parser = argparse.ArgumentParser(description=self.export_pkg.__doc__,
prog="conan export-pkg",
formatter_class=SmartFormatter)
parser.add_argument("path", help=_PATH_HELP)
parser.add_argument("reference", nargs='?', default=None,
help="user/channel or pkg/version@user/channel "
"(if name and version are not declared in the "
"conanfile.py)")
parser.add_argument("-bf", "--build-folder", action=OnceArgument, help=_BUILD_FOLDER_HELP)
parser.add_argument("-e", "--env", nargs=1, action=Extender,
help='Environment variables that will be set during the package build, '
'-e CXX=/usr/bin/clang++')
parser.add_argument('-f', '--force', default=False, action='store_true',
help='Overwrite existing package if existing')
parser.add_argument("-if", "--install-folder", action=OnceArgument,
help=_INSTALL_FOLDER_HELP + " If these files are found in the specified"
" folder and any of '-e', '-o', '-pr' or '-s' arguments are used, it "
"will raise an error.")
parser.add_argument("-o", "--options", nargs=1, action=Extender,
help='Define options values, e.g., -o pkg:with_qt=true')
parser.add_argument("-pr", "--profile", action=Extender,
help='Profile for this package')
parser.add_argument("-pf", "--package-folder", action=OnceArgument,
help="folder containing a locally created package. If a value is given,"
" it won't call the recipe 'package()' method, and will run a copy"
" of the provided folder.")
parser.add_argument("-s", "--settings", nargs=1, action=Extender,
help='Define settings values, e.g., -s compiler=gcc')
parser.add_argument("-sf", "--source-folder", action=OnceArgument, help=_SOURCE_FOLDER_HELP)
parser.add_argument("-j", "--json", default=None, action=OnceArgument,
help='Path to a json file where the install information will be '
'written')
parser.add_argument("-l", "--lockfile", action=OnceArgument, nargs='?', const=".",
help="Path to a lockfile or folder containing 'conan.lock' file. "
"Lockfile will be updated with the exported package")
args = parser.parse_args(*args)
self._warn_python2()
name, version, user, channel, _ = get_reference_fields(args.reference,
user_channel_input=True)
cwd = os.getcwd()
info = None
try:
info = self._conan.export_pkg(conanfile_path=args.path,
name=name,
version=version,
source_folder=args.source_folder,
build_folder=args.build_folder,
package_folder=args.package_folder,
install_folder=args.install_folder,
profile_names=args.profile,
env=args.env,
settings=args.settings,
options=args.options,
force=args.force,
user=user,
channel=channel,
lockfile=args.lockfile)
except ConanException as exc:
info = exc.info
raise
finally:
if args.json and info:
self._outputer.json_output(info, args.json, cwd)
def export(self, *args):
"""
Copies the recipe (conanfile.py & associated files) to your local cache.
Use the 'reference' param to specify a user and channel where to export
it. Once the recipe is in the local cache it can be shared, reused and
to any remote with the 'conan upload' command.
"""
parser = argparse.ArgumentParser(description=self.export.__doc__,
prog="conan export",
formatter_class=SmartFormatter)
parser.add_argument("path", help=_PATH_HELP)
parser.add_argument("reference", nargs='?', default=None,
help="user/channel, or Pkg/version@user/channel (if name "
"and version are not declared in the conanfile.py")
parser.add_argument('-k', '-ks', '--keep-source', default=False, action='store_true',
help=_KEEP_SOURCE_HELP)
parser.add_argument("-l", "--lockfile", action=OnceArgument, nargs='?', const=".",
help="Path to a lockfile or folder containing 'conan.lock' file. "
"Lockfile will be updated with the exported package")
args = parser.parse_args(*args)
self._warn_python2()
name, version, user, channel, _ = get_reference_fields(args.reference,
user_channel_input=True)
if any([user, channel]) and not all([user, channel]):
# Or user/channel or nothing, but not partial
raise ConanException("Invalid parameter '%s', "
"specify the full reference or user/channel" % args.reference)
return self._conan.export(path=args.path,
name=name, version=version, user=user, channel=channel,
keep_source=args.keep_source, lockfile=args.lockfile)
def remove(self, *args):
"""
Removes packages or binaries matching pattern from local cache or remote.
It can also be used to remove temporary source or build folders in the
local conan cache. If no remote is specified, the removal will be done
by default in the local conan cache.
"""
parser = argparse.ArgumentParser(description=self.remove.__doc__,
prog="conan remove",
formatter_class=SmartFormatter)
parser.add_argument('pattern_or_reference', nargs="?", help=_PATTERN_OR_REFERENCE_HELP)
parser.add_argument('-b', '--builds', nargs="*", action=Extender,
help=("By default, remove all the build folders or select one, "
"specifying the package ID"))
parser.add_argument('-f', '--force', default=False, action='store_true',
help='Remove without requesting a confirmation')
parser.add_argument("-l", "--locks", default=False, action="store_true",
help="Remove locks")
parser.add_argument("-o", "--outdated", default=False, action="store_true",
help="Remove only outdated from recipe packages. "
"This flag can only be used with a reference")
parser.add_argument('-p', '--packages', nargs="*", action=Extender,
help="Select package to remove specifying the package ID")
parser.add_argument('-q', '--query', default=None, action=OnceArgument, help=_QUERY_HELP)
parser.add_argument('-r', '--remote', action=OnceArgument,
help='Will remove from the specified remote')