I am wondering if this can be done in the terminal or any simple programs.
In my project folder, i have files like:
my-component.ts
my-component.spec.ts
my-component-without-spec.ts
Most component files will have a matching spec file. But some don't. I want to find the ones that don't have matching spec file.
In Mac OS, I tried:
find -E . -regex '. (?<!spec\.ts)'
I got:
find: -regex: . (?<!spec\.ts): repetition-operator operand invalid
How can I do this?
CodePudding user response:
You can't use PCRE regex with find. The (?<!spec\.ts) negative lookbehind matches a location that is not immediately preceded by spec.ts, and you mist probably wanted to just match all files ending with .ts but not ending with spec.ts.
So you can use
find . -iname '*spec.ts' -not -iname '*.spec.ts'
Here,
-iname '*spec.ts'- searches for all files ending withspec.ts(case insensitive)-not -iname '*.spec.ts'- and NOT ending with.spec.ts(case insensitive).
CodePudding user response:
The requirement is a simple program running under macOS that prints all .ts files without an associated spec file.
Obviously there are many possibilities, one would be a simple Python3 script:
- collects all .ts files recursively in a given directory with
glob.glob. - for each file not ending in spec.ts, construct the corresponding spec filename
- if this spec file is not in the collection, it will be output as missing
Code-wise, this could then look like this:
import glob
import os.path
import sys
from pathlib import Path
def find_unmatched(root_dir):
all_ts_files = glob.glob(os.path.join(root_dir, '**/*.ts'), recursive=True)
for ts_file in all_ts_files:
if not ts_file.endswith('.spec.ts'):
p = Path(ts_file)
folder = os.path.split(ts_file)[0]
corresponding_spec = os.path.join(folder, (p.stem '.spec' p.suffix))
if corresponding_spec not in all_ts_files:
print(f"missing: {corresponding_spec}")
if __name__ == '__main__':
if len(sys.argv) != 2:
print("usage: find_unmatched <dir>")
else:
find_unmatched(sys.argv[1])
Notes: The code was written for readability rather than performance, but should not be a problem for this use case. Above script works with Python 3.8.2 installed e.g. with XCode command line tools.
You would call it like this:
python3 find_unmatched.py .
For the given example case, the output would look like this:
missing: my-component-without-spec.spec.ts
