From nobody Fri May 3 09:26:17 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of groups.io designates 66.175.222.12 as permitted sender) client-ip=66.175.222.12; envelope-from=bounce+27952+56877+1787277+3901457@groups.io; helo=web01.groups.io; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of groups.io designates 66.175.222.12 as permitted sender) smtp.mailfrom=bounce+27952+56877+1787277+3901457@groups.io; dmarc=fail(p=none dis=none) header.from=intel.com ARC-Seal: i=1; a=rsa-sha256; t=1585780506; cv=none; d=zohomail.com; s=zohoarc; b=ahSocn6E3ZXWUAXucRd9DThdthXhGHFmltZO9uRNi+RCcvAFxeBdBAG1NW62L5/L6iU4/Twxy6Beb89DldE263o9V2m7r9VKd8IUF7jDFZ5IiwPngBJtX0mEwzjhAz+5ue+2UMZmJ6pcY/ZoTE3HmgXAZx0Sug0RODg7rr+8jIk= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1585780506; h=Content-Transfer-Encoding:Cc:Date:From:In-Reply-To:List-Id:List-Unsubscribe:MIME-Version:Message-ID:Reply-To:References:Sender:Subject:To; bh=pg5uGSP9FvmSV58HxyzsO3ENQt+LXJa9oD6pxA5/8AQ=; b=mjrULNQ5WbkTvgOy/bLfZpriKtgWNldm5ExYb0HdKmzZXht4R7oGINbJHbmpjas2OvwEUYqJ0bbUbVROxCeYc/7wXrAPm82mvOtSGA5gWZM3/PHU8KYf2eQ7GPdKKGsMNsAQAHHGKp9b2nMG2iNryf87tQacBWbhIrbu4GKlo9o= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of groups.io designates 66.175.222.12 as permitted sender) smtp.mailfrom=bounce+27952+56877+1787277+3901457@groups.io; dmarc=fail header.from= (p=none dis=none) header.from= Received: from web01.groups.io (web01.groups.io [66.175.222.12]) by mx.zohomail.com with SMTPS id 1585780506737735.6687821942105; Wed, 1 Apr 2020 15:35:06 -0700 (PDT) Return-Path: X-Received: by 127.0.0.2 with SMTP id CZFCYY1788612xOTwRgy6APO; Wed, 01 Apr 2020 15:35:06 -0700 X-Received: from mga05.intel.com (mga05.intel.com []) by mx.groups.io with SMTP id smtpd.web12.1673.1585780505388364153 for ; Wed, 01 Apr 2020 15:35:05 -0700 IronPort-SDR: j5EmcYteV+qF1twdpLiGizupvL2Vds87pDQOYvJdRTkPkO5UxurWGA1tQIaAUgf1j0/vfUVmjw +QmKzEQ8bUXw== X-Amp-Result: SKIPPED(no attachment in message) X-Amp-File-Uploaded: False X-Received: from orsmga003.jf.intel.com ([10.7.209.27]) by fmsmga105.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 01 Apr 2020 15:35:05 -0700 IronPort-SDR: iy1WYjC6yuuhdxQ/3eyjSlz4rrY7Bh/uRm+5PelZPnfAGJioMaMQ/oILw/lwuj1p5iHUP/2Fdf TQGNJmc+kiZA== X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.72,333,1580803200"; d="scan'208";a="249615992" X-Received: from nldesimo-desk1.amr.corp.intel.com ([10.7.159.63]) by orsmga003.jf.intel.com with ESMTP; 01 Apr 2020 15:35:04 -0700 From: "Nate DeSimone" To: devel@edk2.groups.io Cc: Ashley DeSimone , Puja Pandya , Erik Bjorge , Prince Agyeman , Bret Barkelew , Philippe Mathieu-Daude Subject: [edk2-devel] [edk2-staging/EdkRepo] [PATCH V1 1/3] EdkRepo: Generate command completion scripts Date: Wed, 1 Apr 2020 15:34:50 -0700 Message-Id: <20200401223452.4805-2-nathaniel.l.desimone@intel.com> In-Reply-To: <20200401223452.4805-1-nathaniel.l.desimone@intel.com> References: <20200401223452.4805-1-nathaniel.l.desimone@intel.com> MIME-Version: 1.0 Precedence: Bulk List-Unsubscribe: Sender: devel@edk2.groups.io List-Id: Mailing-List: list devel@edk2.groups.io; contact devel+owner@edk2.groups.io Reply-To: devel@edk2.groups.io,nathaniel.l.desimone@intel.com X-Gm-Message-State: Ds1UtkNfntwWpQFtCOyWNXGFx1787277AA= Content-Transfer-Encoding: quoted-printable DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=groups.io; q=dns/txt; s=20140610; t=1585780506; bh=tfK09WxLk268JVgAm2/JUZnzI7HftyAIwvwGbDokfmE=; h=Cc:Date:From:Reply-To:Subject:To; b=RXQCEery+MU076vOzFNWS5H2PMMpqL42198kX1Sd+3OoDsSDjzytIiLx/EFyfdtbFrc H1Vbl6shQLCAcIwQ45ijZn/F+Z1/s7c4jGMaU7YmJ9ksvuGfG6+TQCn/JSSpp3eF9wqLf /z/AXfVCozQqxlpealdG36v0XUMU9P0EFcw= X-ZohoMail-DKIM: pass (identity @groups.io) Content-Type: text/plain; charset="utf-8" Adds code to edkrepo_cli.py to generate a bash/zsh compatible command completion script. Add a new command_completion_edkrepo.py script which is callable by the shell when needed for dynamic completion data. For example, providing completion for "edkrepo checkout" requires the shell to know the list of possible branch combinations, this requires parsing the manifest XML. command_completion_edkrepo.py provides a means for the shell to get that type of data. Cc: Ashley DeSimone Cc: Puja Pandya Cc: Erik Bjorge Cc: Prince Agyeman Cc: Bret Barkelew Cc: Philippe Mathieu-Daude Signed-off-by: Nate DeSimone --- edkrepo/command_completion_edkrepo.py | 86 +++++++++++++++++++++++++++ edkrepo/edkrepo_cli.py | 61 ++++++++++++++++++- setup.py | 8 +-- 3 files changed, 150 insertions(+), 5 deletions(-) create mode 100644 edkrepo/command_completion_edkrepo.py diff --git a/edkrepo/command_completion_edkrepo.py b/edkrepo/command_comple= tion_edkrepo.py new file mode 100644 index 0000000..05de9ca --- /dev/null +++ b/edkrepo/command_completion_edkrepo.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +# +## @file +# command_completion_edkrepo.py +# +# Copyright (c) 2020, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# + +import argparse +import io +import os +import sys +import traceback + +from edkrepo_manifest_parser.edk_manifest import ManifestXml +from edkrepo.config import config_factory +from edkrepo.config.config_factory import get_workspace_manifest + +def checkout(parsed_args, config): + manifest =3D get_workspace_manifest() + print(' '.join([c.name for c in manifest.combinations])) + +def current_combo(parsed_args, config): + manifest =3D get_workspace_manifest() + print(" [{}]".format(manifest.general_config.current_combo)) + +def checkout_pin(parsed_args, config): + pins =3D [] + manifest_directory =3D config['cfg_file'].manifest_repo_abs_local_path + manifest =3D get_workspace_manifest() + pin_folder =3D os.path.normpath(os.path.join(manifest_directory, manif= est.general_config.pin_path)) + for dirpath, _, filenames in os.walk(pin_folder): + for file in filenames: + pin_file =3D os.path.join(dirpath, file) + # Capture error output from manifest parser stdout so it is hi= dden unless verbose is enabled + stdout =3D sys.stdout + sys.stdout =3D io.StringIO() + pin =3D ManifestXml(pin_file) + parse_output =3D sys.stdout.getvalue() + sys.stdout =3D stdout + if parsed_args.verbose and parse_output.strip() !=3D '': + print('Pin {} Parsing Errors: {}\n'.format(file, parse_out= put.strip())) + if pin.project_info.codename =3D=3D manifest.project_info.code= name: + pins.append(file) + print(' '.join(pins)) + +# To add command completions for a new command, add an entry to this dicti= onary. +command_completions =3D { + 'current-combo': current_combo, + 'checkout': checkout, + 'checkout-pin': checkout_pin, + 'chp': checkout_pin +} + +def main(): + parser =3D argparse.ArgumentParser() + parser.add_argument("-v", "--verbose", action=3D"store_true", help=3D'= Increases command verbosity') + subparsers =3D parser.add_subparsers(dest=3D'subparser_name') + for command_completion in command_completions: + subparsers.add_parser(command_completion, formatter_class=3Dargpar= se.RawTextHelpFormatter) + if len(sys.argv) <=3D 1: + return 0 + parsed_args =3D parser.parse_args() + try: + command_name =3D parsed_args.subparser_name + config =3D {} + config["cfg_file"] =3D config_factory.GlobalConfig() + config["user_cfg_file"] =3D config_factory.GlobalUserConfig() + if command_name not in command_completions: + return 1 + command_completions[command_name](parsed_args, config) + return 0 + except Exception as e: + if parsed_args.verbose: + traceback.print_exc() + print("Error: {}".format(str(e))) + return 1 + return 0 + +if __name__ =3D=3D "__main__": + try: + sys.exit(main()) + except Exception as e: + traceback.print_exc() + sys.exit(1) diff --git a/edkrepo/edkrepo_cli.py b/edkrepo/edkrepo_cli.py index 0b69860..03061c9 100644 --- a/edkrepo/edkrepo_cli.py +++ b/edkrepo/edkrepo_cli.py @@ -3,7 +3,7 @@ ## @file # edkrepo_cli.py # -# Copyright (c) 2017- 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2017 - 2020, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # =20 @@ -29,6 +29,7 @@ from edkrepo.common.edkrepo_exception import EdkrepoExcep= tion, EdkrepoGlobalConf from edkrepo.common.edkrepo_exception import EdkrepoWarningException from edkrepo.common.edkrepo_exception import EdkrepoConfigFileInvalidExcep= tion from edkrepo.common.humble import KEYBOARD_INTERRUPT, GIT_CMD_ERROR +from edkrepo.common.pathfix import get_actual_path =20 def generate_command_line(command): parser =3D argparse.ArgumentParser() @@ -100,6 +101,61 @@ def generate_command_line(command): subparser_name.add_argument(('--' + arg.get('name')), acti= on=3Darg_action, help=3Darg.get('help-text')) return parser =20 +command_completion_script_header=3D'''#!/usr/bin/env bash +# +## @file edkrepo_completions.sh +# +# Automatically generated please DO NOT modify !!! +# + +''' +def generate_command_completion_script(script_filename, parser): + import edkrepo.command_completion_edkrepo as completion + commands =3D [] + for action in parser._positionals._group_actions: + if action.choices is not None: + commands =3D [c for c in action.choices] + break + commands =3D sorted(commands) + commands_with_3rd_param_completion =3D [c for c in completion.command_= completions if c in commands] + commands_with_3rd_param_completion =3D sorted(commands_with_3rd_param_= completion) + with open(script_filename, 'w') as f: + f.write(command_completion_script_header) + if sys.platform =3D=3D "win32": + command_completion_path =3D os.path.dirname(sys.executable) + command_completion_path =3D os.path.join(command_completion_pa= th, 'Scripts', "command_completion_edkrepo.exe") + if not os.path.isfile(command_completion_path): + print('command_completion_edkrepo.exe not found') + return + command_completion_path =3D get_actual_path(command_completion= _path) + (drive, path) =3D os.path.splitdrive(command_completion_path) + command_completion_path =3D '/{}{}'.format(drive.replace(':','= ').lower(), path.replace('\\','/')) + f.write("export command_completion_edkrepo_file=3D'{}'\n".form= at(command_completion_path)) + f.write('alias command_completion_edkrepo=3D"$command_completi= on_edkrepo_file"\n') + f.write('_edkrepo_completions() {\n if [ "${#COMP_WORDS[@]}" -e= q "2" ]; then\n') + f.write(' COMPREPLY=3D($(compgen -W "{}" -- "${{COMP_WORDS[= 1]}}"))\n'.format(' '.join(commands))) + if len(commands_with_3rd_param_completion) > 0: + f.write(' elif [ "${#COMP_WORDS[@]}" -eq "3" ]; then\n') + first_loop =3D True + for command in commands_with_3rd_param_completion: + if first_loop: + f.write(' if [ "${{COMP_WORDS[1]}}" =3D=3D "{}" ]; = then\n'.format(command)) + first_loop =3D False + else: + f.write(' elif [ "${{COMP_WORDS[1]}}" =3D=3D "{}" ]= ; then\n'.format(command)) + f.write(' COMPREPLY=3D($(compgen -W "$(command_comp= letion_edkrepo ${COMP_WORDS[1]})" -- "${COMP_WORDS[2]}"))\n') + if len(commands_with_3rd_param_completion) > 0: + f.write(' fi\n') + f.write(' fi\n}\n\n') + if len(commands_with_3rd_param_completion) > 0: + if sys.platform =3D=3D "win32": + f.write('if [ -x "$(command -v edkrepo)" ] && [ -x "$(comm= and -v $command_completion_edkrepo_file)" ]; then\n') + else: + f.write('if [ -x "$(command -v edkrepo)" ] && [ -x "$(comm= and -v command_completion_edkrepo)" ]; then\n') + else: + f.write('if [ -x "$(command -v edkrepo)" ]; then\n') + f.write(' complete -F _edkrepo_completions edkrepo\nfi\n') + def main(): command =3D command_factory.create_composite_command() config =3D {} @@ -117,6 +173,9 @@ def main(): if len(sys.argv) <=3D 1: parser.print_help() return 1 + if sys.argv[1] =3D=3D 'generate-command-completion-script' and len(sys= .argv) >=3D 3: + generate_command_completion_script(sys.argv[2], parser) + return 0 parsed_args =3D parser.parse_args() command_name =3D parsed_args.subparser_name try: diff --git a/setup.py b/setup.py index e14aed1..e7e6ce8 100755 --- a/setup.py +++ b/setup.py @@ -1,9 +1,8 @@ #!/usr/bin/env python3 # -## @file -# setup.py +## @file setup.py # -# Copyright (c) 2017 - 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2017 - 2020, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # =20 @@ -20,7 +19,8 @@ setup(name=3D'edkrepo', include_package_data=3DTrue, entry_points=3D{ 'console_scripts': [ - 'edkrepo =3D edkrepo.edkrepo_entry_point:main' + 'edkrepo =3D edkrepo.edkrepo_entry_point:main', + 'command_completion_edkrepo =3D edkrepo.command_completion_e= dkrepo:main' ] } ) --=20 2.24.0.windows.2 -=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D- Groups.io Links: You receive all messages sent to this group. View/Reply Online (#56877): https://edk2.groups.io/g/devel/message/56877 Mute This Topic: https://groups.io/mt/72713333/1787277 Group Owner: devel+owner@edk2.groups.io Unsubscribe: https://edk2.groups.io/g/devel/unsub [importer@patchew.org] -=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D- From nobody Fri May 3 09:26:17 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of groups.io designates 66.175.222.12 as permitted sender) client-ip=66.175.222.12; envelope-from=bounce+27952+56878+1787277+3901457@groups.io; helo=web01.groups.io; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of groups.io designates 66.175.222.12 as permitted sender) smtp.mailfrom=bounce+27952+56878+1787277+3901457@groups.io; dmarc=fail(p=none dis=none) header.from=intel.com ARC-Seal: i=1; a=rsa-sha256; t=1585780506; cv=none; d=zohomail.com; s=zohoarc; b=bckQMoBlY80qUsdsrycLbawoNvqn0r37OQ0N8d9vnePDANqzUo9vul7uC77h8z/uzYgtgpMey6ujuGeqyeRjLHvJzR19uUZmsmR7HmAyaWFdVBQZpcqzAx2PSR7Xh2/HEbOWTajQkoxJJ8L3Edc8lxKJcUX9jzhq38afHUdKgQE= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1585780506; h=Content-Transfer-Encoding:Cc:Date:From:In-Reply-To:List-Id:List-Unsubscribe:MIME-Version:Message-ID:Reply-To:References:Sender:Subject:To; bh=ETB2m1FCBpIx4nuSGsE1lcgCs1glSqW7wXpngCcK4eA=; b=a9KFDsAYf2jdRCFyQ7tdIf0fy67jG4nuqL6yllmSQS0Vgo5nqmyBuLYg4sQ9ABcWXAPM4bk0YbfEPb1TbCxPKbftRZ3jgmIZyghUIc75BIEK2BEjMGZMShgE9tdajv2YbX9CfhgBeMzig+bKJqtW40gVOcUD3Y1+KswwiamoavM= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of groups.io designates 66.175.222.12 as permitted sender) smtp.mailfrom=bounce+27952+56878+1787277+3901457@groups.io; dmarc=fail header.from= (p=none dis=none) header.from= Received: from web01.groups.io (web01.groups.io [66.175.222.12]) by mx.zohomail.com with SMTPS id 1585780506856483.4097739800527; Wed, 1 Apr 2020 15:35:06 -0700 (PDT) Return-Path: X-Received: by 127.0.0.2 with SMTP id OsTcYY1788612xrsvPMiiC7z; Wed, 01 Apr 2020 15:35:06 -0700 X-Received: from mga05.intel.com (mga05.intel.com []) by mx.groups.io with SMTP id smtpd.web12.1673.1585780505388364153 for ; Wed, 01 Apr 2020 15:35:06 -0700 IronPort-SDR: Z1NPGWh7ereU3JibeP56UTGO2QLC/0wBqKcuiUvJhYtgkGvsRMojbaE4FPNtIg4FkgL226/IfJ NVfzxdCrWWBg== X-Amp-Result: SKIPPED(no attachment in message) X-Amp-File-Uploaded: False X-Received: from orsmga003.jf.intel.com ([10.7.209.27]) by fmsmga105.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 01 Apr 2020 15:35:05 -0700 IronPort-SDR: yz+6UC0KVgwgi0jHMTeUeWzepL4kxacJFCuRbPJTFiScRgexx7TO5Y+fEoVVlww/c5ZfXgD4+t 33zgN4tt1rXA== X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.72,333,1580803200"; d="scan'208";a="249615993" X-Received: from nldesimo-desk1.amr.corp.intel.com ([10.7.159.63]) by orsmga003.jf.intel.com with ESMTP; 01 Apr 2020 15:35:04 -0700 From: "Nate DeSimone" To: devel@edk2.groups.io Cc: Ashley DeSimone , Puja Pandya , Erik Bjorge , Prince Agyeman , Bret Barkelew , Philippe Mathieu-Daude Subject: [edk2-devel] [edk2-staging/EdkRepo] [PATCH V1 2/3] EdkRepo: Add command completion setup to install.py Date: Wed, 1 Apr 2020 15:34:51 -0700 Message-Id: <20200401223452.4805-3-nathaniel.l.desimone@intel.com> In-Reply-To: <20200401223452.4805-1-nathaniel.l.desimone@intel.com> References: <20200401223452.4805-1-nathaniel.l.desimone@intel.com> MIME-Version: 1.0 Precedence: Bulk List-Unsubscribe: Sender: devel@edk2.groups.io List-Id: Mailing-List: list devel@edk2.groups.io; contact devel+owner@edk2.groups.io Reply-To: devel@edk2.groups.io,nathaniel.l.desimone@intel.com X-Gm-Message-State: sjaZ3AUv4Wqv5eBSPv81fxRHx1787277AA= Content-Transfer-Encoding: quoted-printable DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=groups.io; q=dns/txt; s=20140610; t=1585780506; bh=NfyM/cCA7wx+E6AV4rJ65GMJs6NI2bCZkRdoDeIc1NQ=; h=Cc:Date:From:Reply-To:Subject:To; b=HFMwcUVP2k4ZM9VqvqgYDxw0P5r6Dd8BnISVEUxPFzKcldASKijQUDSx6SwJnbwPlju ajD7yeia2vl0wObrReLL12LwAkyAsSHg2MaiQhP5Pw8auvuVFJiAosPG4rmkKQlac/jRr d8tBw/NcjdOpguQgWOUurQ35UMUWpwpXjlA= X-ZohoMail-DKIM: pass (identity @groups.io) Content-Type: text/plain; charset="utf-8" Add configuration of command completion scripts to install.py This enables edkrepo command completions to work "out of box" on most Linux systems by appending to the user's .bashrc and .zshrc startup scripts inclusion of the EdkRepo command completion scripts. Cc: Ashley DeSimone Cc: Puja Pandya Cc: Erik Bjorge Cc: Prince Agyeman Cc: Bret Barkelew Cc: Philippe Mathieu-Daude Signed-off-by: Nate DeSimone Reviewed-by: Ashley DeSimone --- edkrepo_installer/linux-scripts/install.py | 285 ++++++++++++++++++++- 1 file changed, 283 insertions(+), 2 deletions(-) diff --git a/edkrepo_installer/linux-scripts/install.py b/edkrepo_installer= /linux-scripts/install.py index b2cdfed..52f0c52 100755 --- a/edkrepo_installer/linux-scripts/install.py +++ b/edkrepo_installer/linux-scripts/install.py @@ -15,6 +15,7 @@ import importlib.util import logging import os import platform +import re import stat import shutil import subprocess @@ -22,7 +23,7 @@ import sys import traceback import xml.etree.ElementTree as et =20 -tool_sign_on =3D 'Installer for edkrepo version {}\nCopyright(c) Intel Cor= poration, 2019' +tool_sign_on =3D 'Installer for edkrepo version {}\nCopyright(c) Intel Cor= poration, 2020' =20 # Data here should be maintained in a configuration file cfg_dir =3D '.edkrepo' @@ -31,6 +32,21 @@ cfg_src_dir =3D os.path.abspath('config') whl_src_dir =3D os.path.abspath('wheels') def_python =3D 'python3' =20 +# ZSH Configuration options +prompt_regex =3D re.compile(r"#\s+[Aa][Dd][Dd]\s+[Ee][Dd][Kk][Rr][Ee][Pp][= Oo]\s+&\s+[Gg][Ii][Tt]\s+[Tt][Oo]\s+[Tt][Hh][Ee]\s+[Pp][Rr][Oo][Mm][Pp][Tt]= ") +zsh_autoload_compinit_regex =3D re.compile(r"autoload\s+-U\s+compinit") +zsh_autoload_bashcompinit_regex =3D re.compile(r"autoload\s+-U\s+bashcompi= nit") +zsh_autoload_colors_regex =3D re.compile(r"autoload\s+-U\s+colors") +zsh_colors_regex =3D re.compile(r"\n\s*colors\n") +zsh_compinit_regex =3D re.compile(r"compinit\s+-u") +zsh_bashcompinit_regex =3D re.compile(r"\n\s*bashcompinit\n") +zsh_autoload_compinit =3D 'autoload -U compinit' +zsh_autoload_bashcompinit =3D 'autoload -U bashcompinit' +zsh_autoload_colors =3D 'autoload -U colors' +zsh_colors =3D 'colors' +zsh_compinit =3D 'compinit -u' +zsh_bashcompinit =3D 'bashcompinit' + def default_run(cmd): return subprocess.run(cmd, universal_newlines=3DTrue, stdout=3Dsubproc= ess.PIPE, stderr=3Dsubprocess.STDOUT, check=3DTrue) =20 @@ -51,8 +67,85 @@ def get_args(): parser.add_argument('-p', '--py', action=3D'store', default=3DNone, he= lp=3D'Specify the python command to use when installing') parser.add_argument('-u', '--user', action=3D'store', default=3DNone, = help=3D'Specify user account to install edkrepo support on') parser.add_argument('-v', '--verbose', action=3D'store_true', default= =3DFalse, help=3D'Enables verbose output') + parser.add_argument('--no-prompt', action=3D'store_true', default=3DFa= lse, help=3D'Do NOT add EdkRepo combo and git branch to the shell prompt') + parser.add_argument('--prompt', action=3D'store_true', default=3DFalse= , help=3D'Add EdkRepo combo and git branch to the shell prompt') return parser.parse_args() =20 +def is_prompt_customization_installed(user_home_dir): + script_files =3D [os.path.join(user_home_dir, '.bashrc'), os.path.join= (user_home_dir, '.zshrc')] + customization_installed =3D True + for script_file in script_files: + if os.path.isfile(script_file): + with open(script_file, 'r') as f: + script =3D f.read().strip() + data =3D prompt_regex.search(script) + if not data: + customization_installed =3D False + break + return customization_installed + +__add_prompt_customization =3D None +def get_add_prompt_customization(args, user_home_dir): + global __add_prompt_customization + if __add_prompt_customization is not None: + return __add_prompt_customization + if args.no_prompt: + __add_prompt_customization =3D False + return False + elif args.prompt: + __add_prompt_customization =3D True + return True + #Check if the prompt customization has already been installed + if is_prompt_customization_installed(user_home_dir): + __add_prompt_customization =3D False + return False + #If the prompt has not been installed and EdkRepo >=3D 2.0.0 is instal= led, then don't install the prompt customization + if shutil.which('edkrepo') is not None: + res =3D default_run(['edkrepo', '--version']) + if _check_version(res.stdout.replace('edkrepo ', '').strip(), '2.0= .0') >=3D 0: + __add_prompt_customization =3D False + return False + #Show the user an advertisement to see if they want the prompt customi= zation + from select import select + import termios + import tty + def get_key(timeout=3D-1): + key =3D None + old_settings =3D termios.tcgetattr(sys.stdin.fileno()) + try: + tty.setraw(sys.stdin.fileno()) + if timeout !=3D -1: + rlist, _, _ =3D select([sys.stdin], [], [], timeout) + if rlist: + key =3D sys.stdin.read(1) + else: + key =3D sys.stdin.read(1) + finally: + termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, old_s= ettings) + return key + print('\nEdkRepo can show the checked out \033[32mcombo\033[00m and \0= 33[36mbranch\033[00m as part of the command prompt') + print('For example, instead of:\n') + print('\033[01;32muser@machine\033[00m:\033[01;34mEdk2\033[00m$ ') + print('\nThe command prompt would look like:\n') + print('\033[01;32muser@machine\033[00m:\033[01;34mEdk2\033[00m \033[32= m[Edk2Master]\033[36m (master)\033[00m$ ') + print('') + while True: + print('Would you like the combo and branch shown on the command pr= ompt? [y/N] ') + key =3D get_key(120) + if key: + if key =3D=3D 'y' or key =3D=3D 'Y': + print('Y') + __add_prompt_customization =3D True + return True + if key =3D=3D 'n' or key =3D=3D 'N': + print('N') + __add_prompt_customization =3D False + return False + else: + print('No response after 2min... assuming no.') + __add_prompt_customization =3D False + return False + def get_installed_packages(python_command): pip_cmd =3D [def_python, '-m', 'pip', 'list', '--legacy'] try: @@ -146,6 +239,176 @@ def set_execute_permissions(): stat_data =3D os.stat(py_file) os.chmod(py_file, stat_data.st_mode | stat.S_IEXEC) =20 +bash_prompt_customization =3D r''' +# Add EdkRepo & git to the prompt +ps1len=3D"${#PS1}" +let "pos3 =3D ps1len - 3" +let "pos2 =3D ps1len - 2" +if [ "${PS1:pos3}" =3D=3D "\\$ " ]; then + newps1=3D"${PS1:0:pos3}" + prompt_suffix=3D"\\$ " +elif [ "${PS1:pos3}" =3D=3D " $ " ]; then + newps1=3D"${PS1:0:pos3}" + prompt_suffix=3D" $ " +elif [ "${PS1:pos2}" =3D=3D "$ " ]; then + newps1=3D"${PS1:0:pos2}" + prompt_suffix=3D"$ " +else + newps1=3D"$PS1" + prompt_suffix=3D"" +fi + +# EdkRepo combo in prompt. +if [ -x "$(command -v edkrepo)" ] && [ -x "$(command -v command_completion= _edkrepo)" ]; then + newps1=3D"$newps1\[\033[32m\]\$current_edkrepo_combo" + current_edkrepo_combo=3D$(command_completion_edkrepo current-combo) + + # Determining the current Edkrepo combo requires invoking Python and par= sing + # manifest XML, which is a relatively expensive operation to do every ti= me + # the user presses . + # As a performance optimization, only do this if the present working dir= ectory + # changed + if [[ ! -z ${PROMPT_COMMAND+x} ]] && [[ "$PROMPT_COMMAND" !=3D "edkrepo_= combo_chpwd" ]]; then + old_prompt_command=3D$PROMPT_COMMAND + fi + old_pwd=3D$(pwd) + edkrepo_combo_chpwd() { + if [[ "$(pwd)" !=3D "$old_pwd" ]]; then + old_pwd=3D$(pwd) + current_edkrepo_combo=3D$(command_completion_edkrepo current-combo) + fi + if [[ ! -z ${PROMPT_COMMAND+x} ]]; then + eval $old_prompt_command + fi + } + PROMPT_COMMAND=3Dedkrepo_combo_chpwd +fi + +# Git branch in prompt. +parse_git_branch() { + git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/' +} + +PS1=3D"$newps1\[\033[36m\]\$(parse_git_branch)\[\033[00m\]$prompt_suffix" +''' + +zsh_prompt_customization =3D r''' +# Add EdkRepo & git to the prompt +prompt_length=3D"${#PROMPT}" +let "pos4 =3D prompt_length - 3" +let "pos3 =3D prompt_length - 2" +if [ "${PROMPT[$pos4,$prompt_length]}" =3D ' %# ' ]; then + new_prompt=3D"${PROMPT[1,$pos4-1]}" + prompt_suffix=3D" %# " +elif [ "${PROMPT[$pos3,$prompt_length]}" =3D "%# " ]; then + new_prompt=3D"${PROMPT[1,$pos3-1]}" + prompt_suffix=3D"%# " +else + new_prompt=3D"$PROMPT" + prompt_suffix=3D"" +fi + +# EdkRepo combo in prompt. +if [ -x "$(command -v edkrepo)" ] && [ -x "$(command -v command_completion= _edkrepo)" ]; then + new_prompt=3D"$new_prompt%{$fg[green]%}\$current_edkrepo_combo%{$reset_c= olor%}" + current_edkrepo_combo=3D$(command_completion_edkrepo current-combo) + + # Determining the current Edkrepo combo requires invoking Python and par= sing + # manifest XML, which is a relatively expensive operation to do every ti= me + # the user presses . + # As a performance optimization, only do this if the present working dir= ectory + # changed + function edkrepo_combo_chpwd() { + current_edkrepo_combo=3D$(command_completion_edkrepo current-combo) + } + chpwd_functions=3D(${chpwd_functions[@]} "edkrepo_combo_chpwd") +fi + +# Load version control information +autoload -Uz vcs_info +precmd() { vcs_info } + +# Format the vcs_info_msg_0_ variable +zstyle ':vcs_info:git:*' formats " %{$fg[cyan]%}(%b)%{$reset_color%}" + +# Set up the prompt (with git branch name) +setopt PROMPT_SUBST +eval "PROMPT=3D'$new_prompt\${vcs_info_msg_0_}\$prompt_suffix'" +''' + +def add_command_to_startup_script(script_file, regex, command, username): + script =3D '' + if os.path.isfile(script_file): + with open(script_file, 'r') as f: + script =3D f.read().strip() + data =3D regex.search(script) + if not data: + if script =3D=3D '': + script =3D command + else: + script =3D '{}\n{}'.format(script, command) + with open(script_file, 'w') as f: + f.write(script) + +def add_command_comment_to_startup_script(script_file, regex, command, com= ment, username): + script =3D '' + if os.path.isfile(script_file): + with open(script_file, 'r') as f: + script =3D f.read().strip() + (new_script, subs) =3D re.subn(regex, command, script) + if subs =3D=3D 0: + command =3D '\n{1}\n{0}\n'.format(command, comment) + if script =3D=3D '': + new_script =3D command + else: + new_script =3D '{}\n{}'.format(script, command) + if new_script !=3D script: + with open(script_file, 'w') as f: + f.write(new_script) + shutil.chown(script_file, user=3Dusername) + os.chmod(script_file, 0o644) + +def add_command_completions_to_shell(command_completion_script, args, user= name, user_home_dir): + # Add "source ~/.bashrc" to ~/.bash_profile if it does not have it alr= eady + bash_profile_file =3D os.path.join(user_home_dir, '.bash_profile') + bash_profile =3D '' + if os.path.isfile(bash_profile_file): + with open(bash_profile_file, 'r') as f: + bash_profile =3D f.read().strip() + profile_source_regex =3D re.compile(r"source\s+~/\.bashrc") + profile_source_regex2 =3D re.compile(r".\s+~/\.bashrc") + data =3D profile_source_regex.search(bash_profile) + if not data: + data =3D profile_source_regex2.search(bash_profile) + if not data: + if bash_profile =3D=3D '': + bash_profile =3D 'source ~/.bashrc\n' + else: + bash_profile =3D '{}\nsource ~/.bashrc\n'.format(bash_prof= ile) + with open(bash_profile_file, 'w') as f: + f.write(bash_profile) + shutil.chown(bash_profile_file, user=3Dusername) + os.chmod(bash_profile_file, 0o644) + + # Add edkrepo command completion to ~/.bashrc if it does not have it a= lready + regex =3D r"\[\[\s+-r\s+\"\S*edkrepo_completions.sh\"\s+\]\]\s+&&\s+.\= s+\"\S*edkrepo_completions.sh\"" + new_source_line =3D '[[ -r "{0}" ]] && . "{0}"'.format(command_complet= ion_script) + comment =3D '\n# Add EdkRepo command completions' + bash_rc_file =3D os.path.join(user_home_dir, '.bashrc') + add_command_comment_to_startup_script(bash_rc_file, regex, new_source_= line, comment, username) + if get_add_prompt_customization(args, user_home_dir): + add_command_to_startup_script(bash_rc_file, prompt_regex, bash_pro= mpt_customization, username) + zsh_rc_file =3D os.path.join(user_home_dir, '.zshrc') + add_command_to_startup_script(zsh_rc_file, zsh_autoload_compinit_regex= , zsh_autoload_compinit, username) + add_command_to_startup_script(zsh_rc_file, zsh_autoload_bashcompinit_r= egex, zsh_autoload_bashcompinit, username) + add_command_to_startup_script(zsh_rc_file, zsh_autoload_colors_regex, = zsh_autoload_colors, username) + add_command_to_startup_script(zsh_rc_file, zsh_colors_regex, zsh_color= s, username) + add_command_to_startup_script(zsh_rc_file, zsh_compinit_regex, zsh_com= pinit, username) + add_command_to_startup_script(zsh_rc_file, zsh_bashcompinit_regex, zsh= _bashcompinit, username) + add_command_comment_to_startup_script(zsh_rc_file, regex, new_source_l= ine, comment, username) + if get_add_prompt_customization(args, user_home_dir): + add_command_to_startup_script(zsh_rc_file, prompt_regex, zsh_promp= t_customization, username) + def do_install(): global def_python org_python =3D None @@ -209,6 +472,7 @@ def do_install(): log.info('- Unable to determine users home directory') return 1 default_cfg_dir =3D os.path.join(user_home_dir, cfg_dir) + get_add_prompt_customization(args, user_home_dir) log.info('+ System information collected') =20 # Display current system information. @@ -348,7 +612,7 @@ def do_install(): #Delete obsolete dependencies if updating_edkrepo: installed_packages =3D get_installed_packages(def_python) - for whl_name in ['smmap2', 'gitdb2']: + for whl_name in ['smmap2', 'gitdb2', 'edkrepo-internal']: if whl_name in installed_packages: try: res =3D default_run([def_python, '-m', 'pip', 'uni= nstall', '--yes', whl_name]) @@ -375,6 +639,23 @@ def do_install(): set_execute_permissions() log.info('+ Marked scripts as executable') =20 + + #Install the command completion script + if shutil.which('edkrepo') is not None: + if args.local: + command_completion_script =3D os.path.join(default_cfg_dir, 'e= dkrepo_completions.sh') + else: + command_completion_script =3D os.path.join('/', 'etc', 'profil= e.d', 'edkrepo_completions.sh') + try: + res =3D default_run(['edkrepo', 'generate-command-completion-s= cript', command_completion_script]) + if args.local: + shutil.chown(command_completion_script, user=3Dusername) + os.chmod(command_completion_script, 0o644) + add_command_completions_to_shell(command_completion_script, ar= gs, username, user_home_dir) + except: + log.info('- Failed to configure edkrepo command completion') + if args.verbose: + traceback.print_exc() log.log(logging.PRINT, '\nInstallation complete\n') =20 return 0 --=20 2.24.0.windows.2 -=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D- Groups.io Links: You receive all messages sent to this group. View/Reply Online (#56878): https://edk2.groups.io/g/devel/message/56878 Mute This Topic: https://groups.io/mt/72713334/1787277 Group Owner: devel+owner@edk2.groups.io Unsubscribe: https://edk2.groups.io/g/devel/unsub [importer@patchew.org] -=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D- From nobody Fri May 3 09:26:17 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of groups.io designates 66.175.222.12 as permitted sender) client-ip=66.175.222.12; envelope-from=bounce+27952+56879+1787277+3901457@groups.io; helo=web01.groups.io; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of groups.io designates 66.175.222.12 as permitted sender) smtp.mailfrom=bounce+27952+56879+1787277+3901457@groups.io; dmarc=fail(p=none dis=none) header.from=intel.com ARC-Seal: i=1; a=rsa-sha256; t=1585780507; cv=none; d=zohomail.com; s=zohoarc; b=J+YtKKYGFygYKh9ZwZp48GR8iGoZX1wKwYX7V7bdFOgBS4A0cwyhf/c5uQPL2JlYA0SU0U3ZAfAptBBRYvl0QIO5dTfDRuY1LWhUdtlOsVIMzwjjDqVVgMyHDslBuDpA0lfJBnzCcXogA3sX5AfeyNqvLwkaE3L0LWELzUofyz8= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1585780507; h=Content-Transfer-Encoding:Cc:Date:From:In-Reply-To:List-Id:List-Unsubscribe:MIME-Version:Message-ID:Reply-To:References:Sender:Subject:To; bh=2OcJ8lO7UJPSH/hfy5Hvwl7OhEnHwYYjFJCWIVzcTE8=; b=TdWlE4IARmlvo4zMXR0y3J9z68UHvbvJM2jxPtWab3EzD5TMNiZe1n7ejMK8gui+Wq4DOud4xUEuMn66jQUiveyxdMwXERBD/2SRMEC/f/4rPrDutCSmlGy3YATxFmxBGmhuUOZ7+tuRssSYqb7HXrBO/a2648rxQS0KgILRNSc= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of groups.io designates 66.175.222.12 as permitted sender) smtp.mailfrom=bounce+27952+56879+1787277+3901457@groups.io; dmarc=fail header.from= (p=none dis=none) header.from= Received: from web01.groups.io (web01.groups.io [66.175.222.12]) by mx.zohomail.com with SMTPS id 1585780507078917.3097759643329; Wed, 1 Apr 2020 15:35:07 -0700 (PDT) Return-Path: X-Received: by 127.0.0.2 with SMTP id NDcbYY1788612xa5Mk0yMiin; Wed, 01 Apr 2020 15:35:06 -0700 X-Received: from mga05.intel.com (mga05.intel.com []) by mx.groups.io with SMTP id smtpd.web12.1673.1585780505388364153 for ; Wed, 01 Apr 2020 15:35:06 -0700 IronPort-SDR: 8/wdyzSpvfbvPg/9wpZ4FozCnzarV2+2AtbeOSrL2olFzWrdKYTqamlA1N/wimKq5U98fmyI2S xSQU/LCA8EUg== X-Amp-Result: SKIPPED(no attachment in message) X-Amp-File-Uploaded: False X-Received: from orsmga003.jf.intel.com ([10.7.209.27]) by fmsmga105.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 01 Apr 2020 15:35:05 -0700 IronPort-SDR: 7uyFzY15Gb1Ovd17rGdaGdB4mVxve3NYSh9PT9IXZ7LIuiGMmnB+SNpZEwGfF2oRza9vX3RlvH 1Qq8iFy6b6Sg== X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.72,333,1580803200"; d="scan'208";a="249615996" X-Received: from nldesimo-desk1.amr.corp.intel.com ([10.7.159.63]) by orsmga003.jf.intel.com with ESMTP; 01 Apr 2020 15:35:04 -0700 From: "Nate DeSimone" To: devel@edk2.groups.io Cc: Ashley DeSimone , Puja Pandya , Erik Bjorge , Prince Agyeman , Bret Barkelew , Philippe Mathieu-Daude Subject: [edk2-devel] [edk2-staging/EdkRepo] [PATCH V1 3/3] EdkRepo: Add command completion setup to Windows installer Date: Wed, 1 Apr 2020 15:34:52 -0700 Message-Id: <20200401223452.4805-4-nathaniel.l.desimone@intel.com> In-Reply-To: <20200401223452.4805-1-nathaniel.l.desimone@intel.com> References: <20200401223452.4805-1-nathaniel.l.desimone@intel.com> MIME-Version: 1.0 Precedence: Bulk List-Unsubscribe: Sender: devel@edk2.groups.io List-Id: Mailing-List: list devel@edk2.groups.io; contact devel+owner@edk2.groups.io Reply-To: devel@edk2.groups.io,nathaniel.l.desimone@intel.com X-Gm-Message-State: RT16QEhRhvhheAIl0Mj6tnzjx1787277AA= Content-Transfer-Encoding: quoted-printable DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=groups.io; q=dns/txt; s=20140610; t=1585780506; bh=qP0vevtI5jcZBYARlgS8i45cMUCnm3yXh6FKkXUny9s=; h=Cc:Date:From:Reply-To:Subject:To; b=lD/fcHN+Mr39v8GTF7yYu3hrwF6ckMWrRAaim74YsAUuSPYbiCEu7havOBuf2qvuLC7 YfeLBzEmsdMwceNMCdYLSd1fwfCI4uO4AnB+pnTtvjZchuk54tnRFqwphyCAq/HX6sL5C Ba03y6HsAg+Wsn+6AqlCL+jMLV2hefT2X58= X-ZohoMail-DKIM: pass (identity @groups.io) Content-Type: text/plain; charset="utf-8" Add configuration of command completion scripts to the Windows installer. This enables edkrepo command completions to work "out of box" on Git for Windows by adding the edkrepo command completions scripts to the Git for Windows /etc/profile.d directory Cc: Ashley DeSimone Cc: Puja Pandya Cc: Erik Bjorge Cc: Prince Agyeman Cc: Bret Barkelew Cc: Philippe Mathieu-Daude Signed-off-by: Nate DeSimone Reviewed-by: Ashley DeSimone --- .../EdkRepoInstaller/InstallWorker.cs | 212 ++++++++++++++++-- .../EdkRepoInstaller/InstallerStrings.cs | 44 +++- .../Vendor/win_edkrepo_prompt.sh | 60 +++++ 3 files changed, 296 insertions(+), 20 deletions(-) create mode 100644 edkrepo_installer/Vendor/win_edkrepo_prompt.sh diff --git a/edkrepo_installer/EdkRepoInstaller/InstallWorker.cs b/edkrepo_= installer/EdkRepoInstaller/InstallWorker.cs index 472a6c8..679b4f4 100644 --- a/edkrepo_installer/EdkRepoInstaller/InstallWorker.cs +++ b/edkrepo_installer/EdkRepoInstaller/InstallWorker.cs @@ -19,6 +19,7 @@ using System.Security.AccessControl; using System.Security.Cryptography; using System.Security.Principal; using System.Text; +using System.Text.RegularExpressions; using System.Threading; =20 namespace TianoCore.EdkRepoInstaller @@ -611,7 +612,7 @@ namespace TianoCore.EdkRepoInstaller SilentProcess process =3D SilentProcess.StartConsoleProcessSil= ently(GitPath, "--version", dataCapture.DataReceivedHandler); process.WaitForExit(); PythonVersion gitVersion =3D new PythonVersion(dataCapture.Get= Data().Trim()); - if (gitVersion < new PythonVersion(2,13,0)) + if (gitVersion < new PythonVersion(2, 13, 0)) { InstallLogger.Log(string.Format("Git Version 2.13 or later= is required. You have version {0}, please upgrade to a newer version of Gi= t.", gitVersion)); ReportComplete(false, false); @@ -624,7 +625,7 @@ namespace TianoCore.EdkRepoInstaller List> ExclusivePackages =3D new L= ist>(); foreach (PythonInstance PyInstance in PythonWheelsToInstall) { - foreach(PythonWheel Wheel in PyInstance.Wheels) + foreach (PythonWheel Wheel in PyInstance.Wheels) { if (Wheel.UninstallAllOtherCopies) { @@ -668,13 +669,13 @@ namespace TianoCore.EdkRepoInstaller // foreach (PythonVersion Obsolete in ObsoletedPythonVersions) { - if(ExistingEdkRepoPaths.Select(p =3D> p.Item2).Contains(Ob= solete)) + if (ExistingEdkRepoPaths.Select(p =3D> p.Item2).Contains(O= bsolete)) { foreach (string ExistingEdkrepoPythonPath in ExistingE= dkRepoPaths.Where(p =3D> p.Item2 =3D=3D Obsolete).Select(p =3D> p.Item1)) { string UninstallerPath =3D Path.Combine(Path.GetDi= rectoryName(ExistingEdkrepoPythonPath), "Lib", "site-packages"); UninstallerPath =3D Path.Combine(UninstallerPath, = Path.GetFileName(WindowsHelpers.GetApplicationPath())); - if(File.Exists(UninstallerPath)) + if (File.Exists(UninstallerPath)) { InstallLogger.Log(string.Format("Uninstalling = {0}...", UninstallerPath)); string UninstallString =3D string.Format("\"{0= }\" /Uninstall /Passive", UninstallerPath); @@ -788,14 +789,15 @@ namespace TianoCore.EdkRepoInstaller // // Step 10 - Setup symlink to edkrepo and bash script to launc= h edkrepo from git bash // + string EdkrepoSymlinkPath =3D null; if (!string.IsNullOrEmpty(EdkrepoPythonPath)) { string EdkrepoScriptPath =3D Path.Combine(Path.GetDirector= yName(EdkrepoPythonPath), "Scripts", InstallerStrings.EdkrepoCliExecutable); - string EdkrepoSymlinkPath =3D Path.Combine(Environment.Get= FolderPath(Environment.SpecialFolder.Windows), InstallerStrings.EdkrepoCliE= xecutable); + EdkrepoSymlinkPath =3D Path.Combine(Environment.GetFolderP= ath(Environment.SpecialFolder.Windows), InstallerStrings.EdkrepoCliExecutab= le); if (File.Exists(EdkrepoScriptPath)) { bool CreateSymlink =3D true; - if(File.Exists(EdkrepoSymlinkPath)) + if (File.Exists(EdkrepoSymlinkPath)) { try { @@ -805,22 +807,22 @@ namespace TianoCore.EdkRepoInstaller } } catch (NotASymlinkException) { } - if(CreateSymlink) + if (CreateSymlink) { File.Delete(EdkrepoSymlinkPath); } } - if(CreateSymlink) + if (CreateSymlink) { InstallLogger.Log("Creating Symbolic Link for edkr= epo.exe..."); WindowsHelpers.CreateSymbolicLink(EdkrepoSymlinkPa= th, EdkrepoScriptPath, WindowsHelpers.SYMBOLIC_LINK_FLAG.File); } string GitBashBinPath =3D Path.Combine(Path.GetDirecto= ryName(Path.GetDirectoryName(GitPath)), "usr", "bin"); - if(Directory.Exists(GitBashBinPath)) + if (Directory.Exists(GitBashBinPath)) { InstallLogger.Log("Creating edkrepo launcher in Gi= t Bash..."); string EdkrepoBashScriptPath =3D Path.Combine(GitB= ashBinPath, InstallerStrings.EdkrepoBashLauncherScript); - if(File.Exists(EdkrepoBashScriptPath)) + if (File.Exists(EdkrepoBashScriptPath)) { File.Delete(EdkrepoBashScriptPath); } @@ -838,7 +840,7 @@ namespace TianoCore.EdkRepoInstaller // Step 11 - Copy edkrepo config file to the edkrepo global da= ta directory // string EdkrepoCfg =3D Path.Combine(Path.GetDirectoryName(Windo= wsHelpers.GetApplicationPath()), InstallerStrings.EdkrepoCfg); - if(File.Exists(EdkrepoCfg)) + if (File.Exists(EdkrepoCfg)) { CreateEdkrepoGlobalDataDirectory(); string EdkrepoCfgDir =3D Path.Combine(WindowsHelpers.GetAl= lUsersAppDataPath(), InstallerStrings.EdkrepoGlobalDirectoryName); @@ -853,7 +855,7 @@ namespace TianoCore.EdkRepoInstaller { string NewCfgHash =3D ComputeSha256(ReadFile(EdkrepoCf= g)); string OldCfgHash =3D ComputeSha256(ReadFile(EdkrepoCf= gTarget)); - if(NewCfgHash !=3D OldCfgHash) + if (NewCfgHash !=3D OldCfgHash) { if (GetPreviousEdkrepoCfgFileHashes().Contains(Old= CfgHash)) { @@ -908,7 +910,119 @@ namespace TianoCore.EdkRepoInstaller } =20 // - // Step 13 - Create Programs and Features uninstall links + // Step 13 - Copy win_edkrepo_prompt.sh and generate edkrepo_c= ompletions.sh + // + string edkrepoPromptSource =3D Path.Combine(Path.GetDirectoryN= ame(WindowsHelpers.GetApplicationPath()), InstallerStrings.EdkrepoPrompt); + + if (File.Exists(edkrepoPromptSource) && !string.IsNullOrEmpty(= EdkrepoSymlinkPath)) + { + string gitBashEtcPath =3D Path.Combine(Path.GetDirectoryNa= me(Path.GetDirectoryName(GitPath)), "etc"); + string gitBashEtcProfileDPath =3D Path.Combine(gitBashEtcP= ath, "profile.d"); + if (Directory.Exists(gitBashEtcPath) && Directory.Exists(g= itBashEtcProfileDPath)) + { + InstallLogger.Log("Installing EdkRepo command completi= on..."); + + //Copy win_edkrepo_prompt.sh + string edkrepoPromptDest =3D Path.Combine(gitBashEtcPr= ofileDPath, InstallerStrings.EdkrepoPrompt); + if (File.Exists(edkrepoPromptDest)) + { + File.Delete(edkrepoPromptDest); + } + File.Copy(edkrepoPromptSource, edkrepoPromptDest); + DirectoryInfo info =3D new DirectoryInfo(edkrepoPrompt= Dest); + DirectorySecurity security =3D info.GetAccessControl(); + security.AddAccessRule(new FileSystemAccessRule( + new SecurityIdentifier(WellKnownSidType.BuiltinUse= rsSid, null), + FileSystemRights.FullControl, + InheritanceFlags.ContainerInherit | InheritanceFla= gs.ObjectInherit, + PropagationFlags.NoPropagateInherit, + AccessControlType.Allow + )); + info.SetAccessControl(security); + InstallLogger.Log(string.Format("Copied {0}", Installe= rStrings.EdkrepoPrompt)); + + //Generate edkrepo_completions.sh + string edkrepoCompletionDest =3D Path.Combine(gitBashE= tcProfileDPath, InstallerStrings.EdkrepoCompletion); + if (File.Exists(edkrepoCompletionDest)) + { + File.Delete(edkrepoCompletionDest); + } + dataCapture =3D new SilentProcess.StdoutDataCapture(); + process =3D SilentProcess.StartConsoleProcessSilently( + EdkrepoSymlinkPath, + string.Format( + "generate-command-completion-script \"{0}\"", + edkrepoCompletionDest), + dataCapture.DataReceivedHandler); + process.WaitForExit(); + InstallLogger.Log(EdkrepoSymlinkPath); + InstallLogger.Log(edkrepoCompletionDest); + InstallLogger.Log(dataCapture.GetData().Trim()); + if (process.ExitCode !=3D 0) + { + throw new InvalidOperationException(string.Format(= "generate-command-completion-script failed with status {0}", process.ExitCo= de)); + } + if (!File.Exists(edkrepoCompletionDest)) + { + throw new InvalidOperationException(string.Format(= "generate-command-completion-script did not create {0}", InstallerStrings.E= dkrepoCompletion)); + } + info =3D new DirectoryInfo(edkrepoCompletionDest); + security =3D info.GetAccessControl(); + security.AddAccessRule(new FileSystemAccessRule( + new SecurityIdentifier(WellKnownSidType.BuiltinUse= rsSid, null), + FileSystemRights.FullControl, + InheritanceFlags.ContainerInherit | InheritanceFla= gs.ObjectInherit, + PropagationFlags.NoPropagateInherit, + AccessControlType.Allow + )); + info.SetAccessControl(security); + InstallLogger.Log(string.Format("Generated {0}", Insta= llerStrings.EdkrepoCompletion)); + + //Call win_edkrepo_prompt.sh from bash.bashrc so edkre= po completions are available for "interactive non-login" bash shells + string bashrcPath =3D Path.Combine(gitBashEtcPath, "ba= sh.bashrc"); + if (File.Exists(bashrcPath)) + { + string bashrc =3D Encoding.UTF8.GetString(ReadFile= (bashrcPath)); + Match match =3D Regex.Match(bashrc, InstallerStrin= gs.BashrcEdkrepoPromptCallPattern); + if (match.Success) + { + InstallLogger.Log("EdkRepo prompt is already i= n bash.bashrc"); + } + else + { + bashrc =3D string.Format("{0}{1}", bashrc, Ins= tallerStrings.BashrcEdkRepoPromptCall); + using (BinaryWriter writer =3D new BinaryWrite= r(File.Open(bashrcPath, FileMode.Truncate, FileAccess.Write))) + { + string sanitized =3D bashrc.Replace("\r\n"= , "\n"); + writer.Write(Encoding.UTF8.GetBytes(saniti= zed)); + } + InstallLogger.Log("EdkRepo prompt added to bas= h.bashrc"); + } + } + else + { + InstallLogger.Log(string.Format("{0} not found", b= ashrcPath)); + } + } + else + { + InstallLogger.Log("Git for Windows /etc/profile.d not = found"); + } + } + else + { + if (string.IsNullOrEmpty(EdkrepoSymlinkPath)) + { + InstallLogger.Log("EdkRepo symlink not found"); + } + if (!File.Exists(edkrepoPromptSource)) + { + InstallLogger.Log(string.Format("{0} not found", Insta= llerStrings.EdkrepoPrompt)); + } + } + + // + // Step 14 - Create Programs and Features uninstall links // if (!string.IsNullOrEmpty(EdkrepoPythonPath)) { @@ -977,7 +1091,7 @@ namespace TianoCore.EdkRepoInstaller string GitPath =3D PythonOperations.GetFullPath("git.exe"); =20 // - // Step 2 - Delete symlink to edkrepo and bash script to launc= h it from git bash + // Step 2 - Delete symlink to edkrepo // string EdkrepoSymlinkPath =3D Path.Combine(Environment.GetFold= erPath(Environment.SpecialFolder.Windows), InstallerStrings.EdkrepoCliExecu= table); if (File.Exists(EdkrepoSymlinkPath)) @@ -1003,7 +1117,11 @@ namespace TianoCore.EdkRepoInstaller File.Delete(EdkrepoSymlinkPath); } } - if (GitPath !=3D null) + + // + // Step 3 - Delete scripts to launch edkrepo and Python from g= it bash, and edkrepo command completion scripts + // + if (!string.IsNullOrWhiteSpace(GitPath)) { string GitBashBinPath =3D Path.Combine(Path.GetDirectoryNa= me(Path.GetDirectoryName(GitPath)), "usr", "bin"); if (Directory.Exists(GitBashBinPath)) @@ -1057,10 +1175,68 @@ namespace TianoCore.EdkRepoInstaller File.Delete(EdkrepoPython2ScriptPath); } } + string gitBashEtcPath =3D Path.Combine(Path.GetDirectoryNa= me(Path.GetDirectoryName(GitPath)), "etc"); + string gitBashEtcProfileDPath =3D Path.Combine(gitBashEtcP= ath, "profile.d"); + if (Directory.Exists(gitBashEtcPath) && Directory.Exists(g= itBashEtcProfileDPath)) + { + string edkrepoPromptDest =3D Path.Combine(gitBashEtcPr= ofileDPath, InstallerStrings.EdkrepoPrompt); + if (File.Exists(edkrepoPromptDest)) + { + AllowCancel(false); + if (CancelPending()) + { + ReportComplete(true, true); + return; + } + InstallLogger.Log(string.Format("Deleting {0}...",= InstallerStrings.EdkrepoPrompt)); + File.Delete(edkrepoPromptDest); + } + + string edkrepoCompletionDest =3D Path.Combine(gitBashE= tcProfileDPath, InstallerStrings.EdkrepoCompletion); + if (File.Exists(edkrepoCompletionDest)) + { + AllowCancel(false); + if (CancelPending()) + { + ReportComplete(true, true); + return; + } + InstallLogger.Log(string.Format("Deleting {0}...",= InstallerStrings.EdkrepoCompletion)); + File.Delete(edkrepoCompletionDest); + } + + //Remove call win_edkrepo_prompt.sh from bash.bashrc + string bashrcPath =3D Path.Combine(gitBashEtcPath, "ba= sh.bashrc"); + if (File.Exists(bashrcPath)) + { + string original_bashrc =3D Encoding.UTF8.GetString= (ReadFile(bashrcPath)); + + string new_bashrc =3D Regex.Replace(original_bashr= c, InstallerStrings.BashrcEdkrepoPromptCommentPattern, ""); + new_bashrc =3D Regex.Replace(new_bashrc, Installer= Strings.BashrcEdkrepoPromptCallPattern, ""); + if (new_bashrc =3D=3D original_bashrc) + { + InstallLogger.Log("EdkRepo not found in bash.b= ashrc"); + } + else + { + new_bashrc =3D new_bashrc.TrimEnd(); + using (BinaryWriter writer =3D new BinaryWrite= r(File.Open(bashrcPath, FileMode.Truncate, FileAccess.Write))) + { + string sanitized =3D new_bashrc.Replace("\= r\n", "\n"); + writer.Write(Encoding.UTF8.GetBytes(saniti= zed)); + } + InstallLogger.Log("EdkRepo prompt removed from= bash.bashrc"); + } + } + else + { + InstallLogger.Log(string.Format("{0} not found", b= ashrcPath)); + } + } } =20 // - // Step 3 - Uninstall any instances of edkrepo + // Step 4 - Uninstall any instances of edkrepo // IEnumerable PackagesToUninstall =3D GetPythonWheelsToU= ninstall(); InstallLogger.Log("Determining currently installed Python pack= ages..."); @@ -1109,7 +1285,7 @@ namespace TianoCore.EdkRepoInstaller } =20 // - // Step 4 - Invoke the Finish Uninstall Event + // Step 5 - Invoke the Finish Uninstall Event // if (VendorCustomizer.Instance !=3D null) { @@ -1122,7 +1298,7 @@ namespace TianoCore.EdkRepoInstaller } =20 // - // Step 5 - Delete Programs and Feature uninstall link + // Step 6 - Delete Programs and Feature uninstall link // RegistryKey hklm =3D RegistryKey.OpenBaseKey(RegistryHive.Loca= lMachine, RegistryView.Registry64); RegistryKey winUninstallRegistryKey =3D hklm.OpenSubKey(@"SOFT= WARE\Microsoft\Windows\CurrentVersion\Uninstall", true); diff --git a/edkrepo_installer/EdkRepoInstaller/InstallerStrings.cs b/edkre= po_installer/EdkRepoInstaller/InstallerStrings.cs index 6aa90ee..1542641 100644 --- a/edkrepo_installer/EdkRepoInstaller/InstallerStrings.cs +++ b/edkrepo_installer/EdkRepoInstaller/InstallerStrings.cs @@ -2,7 +2,7 @@ InstallerStrings.cs =20 @copyright - Copyright 2016 - 2019 Intel Corporation. All rights reserved.
+ Copyright 2016 - 2020 Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent =20 @par Specification Reference: @@ -43,7 +43,7 @@ namespace TianoCore.EdkRepoInstaller } =20 public static string EdkrepoPackageName - {=20 + { get { return "edkrepo"; @@ -113,6 +113,46 @@ namespace TianoCore.EdkRepoInstaller } } =20 + public static string EdkrepoPrompt + { + get + { + return "win_edkrepo_prompt.sh"; + } + } + + public static string EdkrepoCompletion + { + get + { + return "edkrepo_completions.sh"; + } + } + + public static string BashrcEdkrepoPromptCommentPattern + { + get + { + return @"#\s+Install\s+EdkRepo\s+command\s+completions"; + } + } + + public static string BashrcEdkrepoPromptCallPattern + { + get + { + return @"shopt\s+-q\s+login_shell\s+\|\|\s+\.\s+/etc/profi= le\.d/win_edkrepo_prompt\.sh"; + } + } + + public static string BashrcEdkRepoPromptCall + { + get + { + return "\n\n# Install EdkRepo command completions\nshopt -= q login_shell || . /etc/profile.d/win_edkrepo_prompt.sh"; + } + } + public static string InstallerName { get diff --git a/edkrepo_installer/Vendor/win_edkrepo_prompt.sh b/edkrepo_insta= ller/Vendor/win_edkrepo_prompt.sh new file mode 100644 index 0000000..5404175 --- /dev/null +++ b/edkrepo_installer/Vendor/win_edkrepo_prompt.sh @@ -0,0 +1,60 @@ +## @file win_edkrepo_prompt.sh +# Note: For use on Git for Windows/MSYS2 ONLY. +# UNIX version is in install.py +# +# Copyright (c) 2020, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# + +# Add EdkRepo command completions +[[ -r "/etc/profile.d/edkrepo_completions.sh" ]] && . "/etc/profile.d/edkr= epo_completions.sh" + +# Add EdkRepo to the prompt +ps1len=3D"${#PS1}" +let "pos38 =3D ps1len - 38" +let "pos3 =3D ps1len - 3" +let "pos2 =3D ps1len - 2" +if [ "${PS1:pos38}" =3D=3D '\[\033[36m\]`__git_ps1`\[\033[0m\]\n$ ' ]; then + newps1=3D"${PS1:0:pos38}" + prompt_suffix=3D'\[\033[36m\]`__git_ps1`\[\033[0m\]\n$ ' +elif [ "${PS1:pos3}" =3D=3D "\\$ " ]; then + newps1=3D"${PS1:0:pos3}" + prompt_suffix=3D"\\$ " +elif [ "${PS1:pos3}" =3D=3D " $ " ]; then + newps1=3D"${PS1:0:pos3}" + prompt_suffix=3D" $ " +elif [ "${PS1:pos2}" =3D=3D "$ " ]; then + newps1=3D"${PS1:0:pos2}" + prompt_suffix=3D"$ " +else + newps1=3D"$PS1" + prompt_suffix=3D"" +fi + +if [ -x "$(command -v edkrepo)" ] && [ -x "$(command -v $command_completio= n_edkrepo_file)" ]; then + newps1=3D"$newps1\[\033[32m\]\$current_edkrepo_combo\[\033[00m\]" + current_edkrepo_combo=3D$(command_completion_edkrepo current-combo) + + # Determining the current Edkrepo combo requires invoking Python and par= sing + # manifest XML, which is a relatively expensive operation to do every ti= me + # the user presses . + # As a performance optimization, only do this if the present working dir= ectory + # changed + if [[ ! -z ${PROMPT_COMMAND+x} ]] && [[ "$PROMPT_COMMAND" !=3D "edkrepo_= combo_chpwd" ]]; then + old_prompt_command=3D$PROMPT_COMMAND + fi + old_pwd=3D$(pwd) + edkrepo_combo_chpwd() { + if [[ "$(pwd)" !=3D "$old_pwd" ]]; then + old_pwd=3D$(pwd) + current_edkrepo_combo=3D$(command_completion_edkrepo current-combo) + fi + if [[ ! -z ${PROMPT_COMMAND+x} ]]; then + eval $old_prompt_command + fi + } + PROMPT_COMMAND=3Dedkrepo_combo_chpwd +fi + +PS1=3D"$newps1$prompt_suffix" +MSYS2_PS1=3D"$PS1" # for detection by MSYS2 SDK's bash.basrc --=20 2.24.0.windows.2 -=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D- Groups.io Links: You receive all messages sent to this group. View/Reply Online (#56879): https://edk2.groups.io/g/devel/message/56879 Mute This Topic: https://groups.io/mt/72713335/1787277 Group Owner: devel+owner@edk2.groups.io Unsubscribe: https://edk2.groups.io/g/devel/unsub [importer@patchew.org] -=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-