Skip to content

Commit

Permalink
Format according to black standard
Browse files Browse the repository at this point in the history
  • Loading branch information
Serene-Arc committed Jan 4, 2023
1 parent 8c2b0cd commit e8e4265
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 46 deletions.
26 changes: 13 additions & 13 deletions tests/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,35 +16,35 @@ def args(tmp_path: Path) -> Namespace:
args.include_folders = False
args.no_act = False
args.recursive = False
args.regex = ''
args.timeformat = ''
args.regex = ""
args.timeformat = ""
args.verbose = 1
return args


def test_rename_files(args: Namespace, capsys: pytest.CaptureFixture):
args.timeformat = '%Y-%m-%d_%H-%M'
args.regex = r'(\d{4}-\d{2}-\d{2}_\d{2}-\d{2})'
args.timeformat = "%Y-%m-%d_%H-%M"
args.regex = r"(\d{4}-\d{2}-\d{2}_\d{2}-\d{2})"
for i in range(0, 4):
Path(args.destination, f'2021-04-20_17-49_test_{i}.png').touch()
Path(args.destination, f"2021-04-20_17-49_test_{i}.png").touch()
main.main(args)
output = capsys.readouterr()
assert all([Path(args.destination, f'2021-04-20T17:49:00_test_{i}.png').exists() for i in range(0, 4)])
assert 'Renamed' in output.out
assert all([Path(args.destination, f"2021-04-20T17:49:00_test_{i}.png").exists() for i in range(0, 4)])
assert "Renamed" in output.out


def test_rename_files_no_act(args: Namespace, capsys: pytest.CaptureFixture):
args.no_act = True
args.timeformat = '%Y-%m-%d_%H-%M'
args.regex = r'^(\d{4}-\d{2}-\d{2}_\d{2}-\d{2})'
args.timeformat = "%Y-%m-%d_%H-%M"
args.regex = r"^(\d{4}-\d{2}-\d{2}_\d{2}-\d{2})"
create_test_files(args)
main.main(args)
output = capsys.readouterr()
assert all([Path(args.destination, f'2021-04-20_17-49_test_{i}.png').exists() for i in range(0, 4)])
assert 'Renamed' not in output.out
assert '.png ->' in output.out
assert all([Path(args.destination, f"2021-04-20_17-49_test_{i}.png").exists() for i in range(0, 4)])
assert "Renamed" not in output.out
assert ".png ->" in output.out


def create_test_files(args):
for i in range(0, 4):
Path(args.destination, f'2021-04-20_17-49_test_{i}.png').touch()
Path(args.destination, f"2021-04-20_17-49_test_{i}.png").touch()
41 changes: 24 additions & 17 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,35 +11,42 @@
import timestampconverter.__main__ as main


@pytest.mark.parametrize(('test_name', 'test_regex_pattern', 'expected'), (
('test', r'(\d)', None),
('2020', r'(\d*)', '2020'),
('2021_test', r'(\d*)', '2021'),
))
@pytest.mark.parametrize(
("test_name", "test_regex_pattern", "expected"),
(
("test", r"(\d)", None),
("2020", r"(\d*)", "2020"),
("2021_test", r"(\d*)", "2021"),
),
)
def test_extract_timestamp(test_name: str, test_regex_pattern: str, expected: Optional[str]):
pattern = re.compile(test_regex_pattern)
result = main.find_match_in_name(test_name, pattern)
assert result == expected


@pytest.mark.parametrize(('test_format_string', 'test_time_string', 'expected'), (
('%Y-%m-%d', '2021-04-22', datetime(2021, 4, 22)),
('%Y-%m-%d_%H-%M', '2021-04-22_10-20', datetime(2021, 4, 22, 10, 20)),
))
@pytest.mark.parametrize(
("test_format_string", "test_time_string", "expected"),
(
("%Y-%m-%d", "2021-04-22", datetime(2021, 4, 22)),
("%Y-%m-%d_%H-%M", "2021-04-22_10-20", datetime(2021, 4, 22, 10, 20)),
),
)
def test_convert_string_to_datetime(test_format_string: str, test_time_string: str, expected: datetime):
result = main.convert_string_to_datetime(test_format_string, test_time_string)
assert result == expected


@pytest.mark.parametrize(('test_path_name', 'test_old_str', 'test_replacement_datetime', 'expected'), (
('test_old', 'old', datetime(2021, 4, 22), 'test_2021-04-22T00:00:00'),
))
@pytest.mark.parametrize(
("test_path_name", "test_old_str", "test_replacement_datetime", "expected"),
(("test_old", "old", datetime(2021, 4, 22), "test_2021-04-22T00:00:00"),),
)
def test_calculate_new_name(
test_path_name: str,
test_old_str: str,
test_replacement_datetime: datetime,
expected: str,
tmp_path: Path,
test_path_name: str,
test_old_str: str,
test_replacement_datetime: datetime,
expected: str,
tmp_path: Path,
):
test_path = Path(tmp_path, test_path_name)
result = main.calculate_new_name(test_path, test_replacement_datetime, test_old_str)
Expand Down
32 changes: 16 additions & 16 deletions timestampconverter/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
def _setup_logging(verbosity: int):
logger.setLevel(1)
stream = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('[%(asctime)s - %(name)s - %(levelname)s] - %(message)s')
formatter = logging.Formatter("[%(asctime)s - %(name)s - %(levelname)s] - %(message)s")
stream.setFormatter(formatter)
logger.addHandler(stream)
if verbosity > 0:
Expand All @@ -27,15 +27,15 @@ def _setup_logging(verbosity: int):


def _add_arguments():
parser.add_argument('destination', type=str)
parser.add_argument('regex', type=str)
parser.add_argument('timeformat', type=str)
parser.add_argument("destination", type=str)
parser.add_argument("regex", type=str)
parser.add_argument("timeformat", type=str)
recursive = parser.add_mutually_exclusive_group()

recursive.add_argument('-r', '--recursive', action='store_true')
recursive.add_argument('--include-folders', action='store_true')
parser.add_argument('-n', '--no-act', action='store_true')
parser.add_argument('-v', '--verbose', action='count', default=0)
recursive.add_argument("-r", "--recursive", action="store_true")
recursive.add_argument("--include-folders", action="store_true")
parser.add_argument("-n", "--no-act", action="store_true")
parser.add_argument("-v", "--verbose", action="count", default=0)


def main(args: argparse.Namespace):
Expand All @@ -54,7 +54,7 @@ def main(args: argparse.Namespace):
if not args.include_folders:
directory_contents = list(filter(lambda f: f.is_file, directory_contents))

logger.info(f'{len(directory_contents)} files found')
logger.info(f"{len(directory_contents)} files found")
regex = re.compile(args.regex)
for file in directory_contents:
match_text = find_match_in_name(file.name, regex)
Expand All @@ -65,16 +65,16 @@ def main(args: argparse.Namespace):
continue
new_path = calculate_new_name(file, file_time, match_text)
if args.no_act:
print(f'{file} -> {new_path}')
print(f"{file} -> {new_path}")
else:
file.rename(new_path)
logger.info(f'Renamed {file} to {new_path}')
logger.info(f"Renamed {file} to {new_path}")


def calculate_new_name(file: Path, file_time: datetime, match_text: str) -> Path:
new_name = file.name.replace(match_text, file_time.isoformat())
if platform.system() == 'Windows':
new_name = new_name.replace(':', '')
if platform.system() == "Windows":
new_name = new_name.replace(":", "")
new_path = Path(file.parent, new_name)
return new_path

Expand All @@ -84,19 +84,19 @@ def convert_string_to_datetime(time_format: str, match_text: str) -> Optional[da
file_time = datetime.strptime(match_text, time_format)
return file_time
except ValueError:
logger.error(f'Regex match {match_text} was not compatible with given time format')
logger.error(f"Regex match {match_text} was not compatible with given time format")


def find_match_in_name(file_name: str, regex: re.Pattern) -> Optional[str]:
match = re.search(regex, file_name)
if not match:
logger.debug(f'No regex match found in {file_name}')
logger.debug(f"No regex match found in {file_name}")
return None
match_text = match.group()
return match_text


if __name__ == '__main__':
if __name__ == "__main__":
_add_arguments()
args = parser.parse_args()
main(args)

0 comments on commit e8e4265

Please sign in to comment.