pcdshub / engineering_tools

A repository of scripts, configuration useful for the PCDS team
Other
4 stars 26 forks source link

ENH: Add no-color option to search sub-cmd in grep_more_ioc #192

Closed aberges-SLAC closed 4 days ago

aberges-SLAC commented 3 months ago

Expected Behavior

An optional flag where the text printed to terminal has no ANSI color wrapping would be nice for piping into other commands. E.g. image image (which can then be piped for other fun activities ;])

Current Behavior

Currently the search sub-cmd wraps the Fore.LIGHTRED_EX object around the text, but could just as easily be specified to be None to bypass this.

Possible Solution

Add a new optional flag to search:

search.add_argument('-n', '--no_color', action='store_true',
                        default=False,
                        help="Don't wrap the search results with a color.")
...
        _color = None
        if not args.no_color:
            _color = Fore.LIGHTRED_EX
        for ioc, d in df.loc[:, ['id', 'dir']].values:
            target_dir = fix_dir(d)
            # Search for pattern after moving into the directory
            if args.search is not None:
                search_result = (search_file(file=f'{target_dir}{ioc}.cfg',
                                             patt=args.search,
                                             color_wrap=_color,
                                             quiet=args.quiet)
                                 .strip()
                                 )
                if len(search_result) > 0:
                    print(f'{Fore.LIGHTYELLOW_EX}{ioc}:{Style.RESET_ALL}')
                    print(''.join(search_result.strip()))
                    check_search.append(len(search_result))

Context

This is mostly a selfish request for wanting to use grep_more_ioc to do the legwork for me when trying to ping multiple devices in MODS for checking health/connectivity after planned outages. Right now I have this hacky approach:

grep_more_ioc -d "$patt" "$hutch" search -qo "$delim" | grep -Po --color=never '(?<=[[:ascii:]]")[- a-z A-Z 0-9]*' | xargs -I {} \
bash -c 'if ping -q -c 1 {} &> /dev/null; then echo "{} is OK"; else echo "{} is not reachable"; fi'

Which only works if the IOC defines the device IP as IP="FOO" and this is not always the case cough smaract cough

Might also be useful for others if I have a version that just dumps the search results, but at that point why not just grep normally?