Skip to content

Commit

Permalink
feat/intial-v extra features
Browse files Browse the repository at this point in the history
  • Loading branch information
hminaee-tc committed Jun 18, 2024
1 parent 3521521 commit fe65bc7
Show file tree
Hide file tree
Showing 4 changed files with 121 additions and 86 deletions.
9 changes: 9 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,12 @@ repos:
language: system
files: 'e2e/.*\.test$'
verbose: true

- repo: local
hooks:
- id: unittest
name: Run unit tests
entry: python -m unittest tests.test_main
language: system
pass_filenames: false
always_run: true
97 changes: 76 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,23 @@ files: .

In this configuration, the find-and-replace hook is set to read search and replacement strings from a file (.project-properties.json by default which should be defined in the root of the project you want to use this package). You can also specify the search and replacement strings directly in the args field (which is not a suggested way).

## Usage as a python package
python -m find_and_replace_strings --usage
or
find-and-replace-strings --usage

shows some usage examples.
```
python -m find_and_replace_strings --usage
Example usages:
python -m find_and_replace_strings --config e2e/.find-and-replace.json e2e/precommit-e2e.test --dry-run --verbose
python -m find_and_replace_strings --config e2e/.find-and-replace.json e2e/precommit-e2e.test --dry-run --log-level=DEBUG
python -m find_and_replace_strings --find 'old_string' --replacement 'new_string' example.txt --verbose
python -m find_and_replace_strings --find 'old_string' --replacement 'new_string' example1.txt example2.txt --verbose
python -m find_and_replace_strings --config my_config.json example.txt --dry-run --verbose
python -m find_and_replace_strings --config e2e/.find-and-replace.json e2e/precommit-e2e.test --dry-run --log-level=INFO
```

## Run tests

```
Expand All @@ -88,7 +105,7 @@ python -m unittest tests.test_main

```
pip install find-and-replace-strings
find-and-replace --config .find-and-replace.json README1.md README2.md
find-and-replace --config .find-and-replace.json README1.md README2.md
```

also if you prefer to use a direct mod
Expand All @@ -97,29 +114,74 @@ also if you prefer to use a direct mod
find-and-replace-strings --find "old_string" --replacement "new_string" README1.md README2.md
```

## If you need more help with the flags and usage of them
## Dry run

Inside the project

python -m find_and_replace_strings --config ./.find-and-replace.json ./README.md READMEtest.md --dry-run

or using the deployed package

find-and-replace-strings --config ./.find-and-replace.json ./README.md READ
MEtest.md --dry-run

More example:


python -m find_and_replace_strings --config e2e/.find-and-replace.json e2e/precommit-e2e.test --dry-run --verbose

python -m find_and_replace_strings --config e2e/.find-and-replace.json e2e/precommit-e2e.test --dry-run --log-level=DEBUG

```
python -m find_and_replace_strings --config e2e/.find-and-replace.json e2e/precommit-e2e.test --dry-run --verbose
INFO:root:Running in default config file mode
INFO:root:Replacing {{BUSINESS_UNIT}} with examp"lebu in e2e/precommit-e2e.test
INFO:root:Replacing {{PROJECT_NAME}} with exampleproject in e2e/precommit-e2e.test
INFO:root:{{PROJECT_NAME}} would be replaced with exampleproject in e2e/precommit-e2e.test
INFO:root:Replacing {{GITHUB_REPO_URL}} with https://github.com/examplebu/exampleproject in e2e/precommit-e2e.test
INFO:root:Replacing {{PROJECT_DESCRIPTION_SLUG}} with Example project used to demonstrate all aspects of a project development and deployment in e2e/precommit-e2e.test
INFO:root:Replacing tucowsinc/iaascloudenablement with tucowsinc/example-github-team-name in e2e/precommit-e2e.test
INFO:root:Replacing {{PROJECT_CONTRIBUTORS}} with * [Andre Ouellet](mailto:aouellet@tucowsinc.com) in e2e/precommit-e2e.test
```

## If you need more help with the available flags

```
find-and-replace-strings -h
usage: find-and-replace-strings [-h] [--config CONFIG] [--find] [--replacement]
[files ...]
python -m find_and_replace_strings -h
usage: __main__.py [-h] [--config CONFIG] [--find] [--replacement] [--dry-run]
[--log-level LOG_LEVEL] [--verbose] [--usage]
[files ...]
Perform find and replace operations on one or more target files. By default, the script
reads the search and replacement entries (strings) from a JSON file. You can also
specify the search and replacement strings directly as command line args by setting the
--find "search_string" and --replacement "replacement_string" argument options.
Perform find and replace operations on one or more target files. By default, the script reads the
search and replacement entries (strings) from a JSON file. You can also specify the search and
replacement strings directly as command line args by setting the --find "search_string" and
--replacement "replacement_string" argument options.
positional arguments:
files File(s) on which to perform search and replace
files File(s) on which to perform search and replace
options:
-h, --help show this help message and exit
--config CONFIG PATH to JSON config file containing find and replacement entries
--find String to find in files
--replacement String to replace with in files
-h, --help show this help message and exit
--config CONFIG PATH to JSON config file containing find and replacement entries
--find String to find in files
--replacement String to replace with in files
--dry-run Perform a dry run without making any changes
--log-level LOG_LEVEL
Set the logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
--verbose Print debug and info messages
--usage Print example usages
```

## Building and Publishing

To build and publish it to pypi run with proper token

```
bash assets/publish.sh
```
or create a PR and after merge the changes will be published to the artifactory.

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.
Expand All @@ -128,13 +190,6 @@ Contributions are welcome! Please feel free to submit a Pull Request.

This project is licensed under the terms of the MIT license.

## Building and Publishing

To build and publish it to pypi run

```
bash assets/publish.sh
```

## Reference Info

Expand Down
Binary file modified assets/pypi-package.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
101 changes: 36 additions & 65 deletions find_and_replace_strings/main.py
Original file line number Diff line number Diff line change
@@ -1,80 +1,32 @@
# -*- coding: utf-8 -*-
# import os
# import argparse
# import fileinput
# import json
# import sys


# def replace_in_file(filename, search, replacement):
# with fileinput.FileInput(filename, inplace=True) as file:
# for line in file:
# print(line.replace(rf"{search}", rf"{replacement}"), end='')


# def main():
# parser = argparse.ArgumentParser(
# description="""Perform find and replace operations on one or more target files.
# By default, the script reads the search and replacement entries (strings) from a JSON file.
# You can also specify the search and replacement strings directly as command line args by setting the
# --find "search_string" and --replacement "replacement_string" argument options."""
# )
# parser.add_argument(
# '--config', default='.find-and-replace.json',
# help='PATH to JSON config file containing find and replacement entries'
# )
# parser.add_argument(
# '--find', dest='direct_mode', action='store_true', help='String to find in files'
# )
# parser.add_argument(
# '--replacement', dest='direct_mode', action='store_true', help='String to replace with in files'
# )
# parser.add_argument(
# 'files', nargs='*', help='File(s) on which to perform search and replace'
# )
# args = parser.parse_args()

# if args.direct_mode:
# # Arguments --find and --replacement have been specified - running in direct mode
# for filename in args.files:
# replace_in_file(filename, args.find, args.replacement)
# else:
# # Arguments --find and --replacement have not been specified - running in default config file mode
# try:
# with open(os.path.join(os.getcwd(), args.config), 'r') as f:
# replacements = json.load(f)
# except FileNotFoundError:
# print(f"Error: {args.config} file not found.")
# sys.exit(1)
# except json.JSONDecodeError:
# print(f"Error: {args.config} is not a valid JSON file.")
# sys.exit(1)

# for filename in args.files:
# for replacement in replacements:
# replace_in_file(filename, replacement['search'], replacement['replacement'])


# if __name__ == "__main__":
# main()

# -*- coding: utf-8 -*-
import os
import argparse
import fileinput
import json
import sys
import logging


def replace_in_file(filename, search, replacement, dry_run=False):
logging.info(f"Replacing {search} with {replacement} in {filename}")
with fileinput.FileInput(filename, inplace=not dry_run) as file:
for line in file:
if search in line and dry_run:
print(f"{search} would be replaced with {replacement} in {filename}")
logging.info(f"{search} would be replaced with {replacement} in {filename}")
elif not dry_run:
print(line.replace(rf"{search}", rf"{replacement}"), end='')


def print_usage():
print("Example usages:")
print("python -m find_and_replace_strings --config e2e/.find-and-replace.json e2e/precommit-e2e.test --dry-run --verbose")
print("python -m find_and_replace_strings --config e2e/.find-and-replace.json e2e/precommit-e2e.test --dry-run --log-level=DEBUG")
print("python -m find_and_replace_strings --find 'old_string' --replacement 'new_string' example.txt --verbose")
print("python -m find_and_replace_strings --find 'old_string' --replacement 'new_string' example1.txt example2.txt --verbose")
print("python -m find_and_replace_strings --config my_config.json example.txt --dry-run --verbose")
print("python -m find_and_replace_strings --config e2e/.find-and-replace.json e2e/precommit-e2e.test --dry-run --log-level=INFO")


def main():
parser = argparse.ArgumentParser(
description="""Perform find and replace operations on one or more target files.
Expand All @@ -98,22 +50,41 @@ def main():
parser.add_argument(
'--dry-run', action='store_true', help='Perform a dry run without making any changes'
)
parser.add_argument(
'--log-level', default='WARNING', help='Set the logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)'
)
parser.add_argument(
'--verbose', action='store_true', help='Print debug and info messages'
)
parser.add_argument(
'--usage', action='store_true', help='Print example usages'
)
args = parser.parse_args()

if args.usage:
print_usage()
sys.exit(0)

levels = {'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARNING': logging.WARNING, 'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL}
level = levels.get(args.log_level.upper(), logging.WARNING)
if args.verbose:
level = logging.DEBUG
logging.basicConfig(level=level)

if args.direct_mode:
# Arguments --find and --replacement have been specified - running in direct mode
logging.info("Running in direct mode")
for filename in args.files:
replace_in_file(filename, args.find, args.replacement, args.dry_run)
else:
# Arguments --find and --replacement have not been specified - running in default config file mode
logging.info("Running in default config file mode")
try:
with open(os.path.join(os.getcwd(), args.config), 'r') as f:
replacements = json.load(f)
except FileNotFoundError:
print(f"Error: {args.config} file not found.")
logging.error(f"Error: {args.config} file not found.")
sys.exit(1)
except json.JSONDecodeError:
print(f"Error: {args.config} is not a valid JSON file.")
logging.error(f"Error: {args.config} is not a valid JSON file.")
sys.exit(1)

for filename in args.files:
Expand Down

0 comments on commit fe65bc7

Please sign in to comment.