-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathflatdirs.py
executable file
·174 lines (158 loc) · 7.22 KB
/
flatdirs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#!/usr/bin/env python
########################################################################
# flatdirs.py: Flatten Directories and Manipulate Files
#
# Description:
# This script flattens the directory structure by either moving, copying,
# or renaming files to the base directory. It supports deletion of empty
# directories and can operate in a quiet mode. If no options are specified,
# the script displays a help message and exits.
#
# When using the `-x` option to execute file operations, the script will
# display the current working directory and prompt the user for confirmation
# to prevent accidental execution. Make sure to review the displayed directory
# before proceeding.
#
# Author: id774 (More info: http://id774.net)
# Source Code: https://github.com/id774/scripts
# License: LGPLv3 (Details: https://www.gnu.org/licenses/lgpl-3.0.html)
# Contact: idnanashi@gmail.com
#
# Version History:
# v1.9 2024-12-15
# Added confirmation prompt for `-x` option to prevent unintended execution.
# v1.8 2024-03-22
# Updated to display a help message and exit if no options are specified.
# v1.7 2024-03-05
# Fixed issue with deleting directories containing subdirectories.
# v1.6 2024-01-20
# Refactored to encapsulate option parser configuration in a separate function.
# v1.5 2024-01-13
# Changed script name to flatdirs.py for simplicity.
# v1.4 2024-01-11
# Refactored handle_directory function to accept options as a parameter.
# v1.3 2023-12-08
# Removed f-strings for compatibility with Python versions below 3.6.
# Modified behavior to require at least one option and display help message otherwise.
# v1.2 2023-12-07
# Enhanced dry-run mode output for clarity.
# v1.1 2023-09-11
# Added rename-only mode.
# v1.0 2023-06-27
# Initial release.
#
# Usage:
# python flatdirs.py [options]
# Options:
# -m, --move Move files instead of copying (default if no option is provided)
# -c, --copy Copy files instead of moving
# -d, --delete Delete empty directories
# -q, --quiet Suppress operation info
# -x, --execute Execute file operations (default is dry run)
# Note: Displays a confirmation prompt showing the current
# directory. Review carefully before proceeding.
# -r, --rename-only Only rename files, without moving or copying
#
# Notes:
# - Use with caution as it can significantly modify directory contents.
# - When using `-x`, review the displayed current directory and confirm before proceeding.
# - It's recommended to backup data before executing with the --execute option.
#
########################################################################
import os
import shutil
from optparse import OptionParser
def setup_option_parser():
""" Set up command-line options using OptionParser. """
parser = OptionParser()
parser.add_option("-m", "--move", action="store_true", dest="move_mode", default=False,
help="move files instead of copying them")
parser.add_option("-c", "--copy", action="store_true", dest="copy_mode", default=False,
help="copy files instead of moving them")
parser.add_option("-d", "--delete", action="store_true", dest="delete_mode", default=False,
help="delete empty directories")
parser.add_option("-q", "--quiet", action="store_true", dest="quiet_mode", default=False,
help="suppress operation info")
parser.add_option("-x", "--execute", action="store_true", dest="execute_mode", default=False,
help="execute file operations (default is dry run)")
parser.add_option("-r", "--rename-only", action="store_true", dest="rename_only_mode", default=False,
help="only rename the files by adding directory name, without moving or copying")
return parser
def print_action(action, source, destination=None, options=None):
""" Prints the action being performed or simulated. """
action_message = "{} {}".format(action, source)
if destination:
action_message += " -> {}".format(destination)
if options and not options.execute_mode:
print("[DRY RUN] {}".format(action_message))
else:
print(action_message)
def handle_directory(path, options):
""" Recursively processes a directory. """
try:
entries = os.listdir(path)
except FileNotFoundError:
return
for entry in entries:
old_path = os.path.join(path, entry)
if os.path.isdir(old_path):
handle_directory(old_path, options)
try:
if options.delete_mode and not os.listdir(old_path):
if options.execute_mode:
os.rmdir(old_path)
if not options.quiet_mode:
print_action("Deleted empty directory", old_path, options=options)
except FileNotFoundError:
pass
else:
dir_empty = False
new_filename = "{}_{}".format(path.replace('/', '_'), entry)
new_path = os.path.join(path, new_filename)
if options.rename_only_mode:
if options.execute_mode:
os.rename(old_path, new_path)
if not options.quiet_mode:
print_action("Renamed", old_path, new_path, options)
elif options.copy_mode or (not options.move_mode and not options.copy_mode):
if options.execute_mode:
shutil.copy(old_path, new_filename)
if not options.quiet_mode:
print_action("Copied", old_path, new_filename, options)
elif options.move_mode:
if options.execute_mode:
shutil.move(old_path, new_filename)
if not options.quiet_mode:
print_action("Moved", old_path, new_filename, options)
try:
if options.delete_mode and not os.listdir(path):
if options.execute_mode:
os.rmdir(path)
if not options.quiet_mode:
print_action("Deleted empty directory", path, options=options)
except FileNotFoundError:
pass
def confirm_execution():
"""Prompt the user to confirm execution when the -x option is used."""
current_dir = os.getcwd()
print("Current directory: {}".format(current_dir))
confirmation = input("Are you sure you want to execute operations in this directory? (yes/no): ").strip().lower()
return confirmation in ('yes', 'y')
def main(options):
"""Main function to process directories. Check if any options are set; if not, display help."""
if options.execute_mode:
if not confirm_execution():
print("Execution cancelled.")
exit(0)
# Check if any option is set. If not, display help and exit.
if not any(vars(options).values()):
parser.print_help()
exit()
# Process each subdirectory in the current directory
subdirectories = [d for d in os.listdir('.') if os.path.isdir(d)]
for subdir in subdirectories:
handle_directory(subdir, options)
if __name__ == '__main__':
parser = setup_option_parser()
(options, args) = parser.parse_args()
main(options)