5
5
import difflib
6
6
import sys
7
7
8
- def get_tree_output ():
8
+ def get_tree_structure ():
9
9
# Get the current tree structure as a string
10
10
result = subprocess .run (['tree' ], stdout = subprocess .PIPE )
11
11
return result .stdout .decode ('utf-8' )
12
12
13
- def print_diff (old_tree , new_tree ):
13
+ def generate_diff (old_tree , new_tree ):
14
14
# Use difflib to print a diff of the two tree outputs
15
15
diff = difflib .unified_diff (
16
16
old_tree .splitlines (keepends = True ),
17
17
new_tree .splitlines (keepends = True ),
18
18
fromfile = 'Before changes' ,
19
19
tofile = 'After changes' ,
20
20
)
21
- print ( '' .join (diff ), end = "" )
21
+ return '' .join (diff )
22
22
23
23
# 1. Traverse the current directory and build a dictionary mapping step numbers to paths
24
- def get_current_steps_dict ():
24
+ def get_current_steps_dict (directory_items ):
25
25
steps_dict = {}
26
- for item in os . listdir ( '.' ) :
26
+ for item in directory_items :
27
27
if item .startswith ('step' ) and (os .path .isdir (item ) or item .endswith ('.md' )):
28
28
# Extract the step number from the name
29
29
try :
@@ -34,20 +34,17 @@ def get_current_steps_dict():
34
34
return steps_dict
35
35
36
36
# 2. Take input from the user for the new step's name and the desired step number
37
- def get_user_input (steps_dict ):
38
- step_title = input ( "Enter the title for the new step: " )
37
+ def get_user_input (steps_dict , step_title_input , step_number_input ):
38
+ step_title = step_title_input
39
39
highest_step_num = max (steps_dict .keys (), default = 0 )
40
40
41
41
while True :
42
- try :
43
- step_number = int (input (f"Enter the step number to insert the new step at (1-{ highest_step_num + 1 } ): " ))
44
- if 1 <= step_number <= highest_step_num + 1 :
45
- break
46
- else :
47
- print (f"Please enter a valid step number between 1 and { highest_step_num + 1 } ." )
48
- except ValueError :
49
- print ("That's not a valid number. Please try again." )
50
-
42
+ step_number = int (step_number_input )
43
+ if 1 <= step_number <= highest_step_num + 1 :
44
+ break
45
+ else :
46
+ raise ValueError (f"Invalid step number: { step_number_input } . Please enter a valid step number between 1 and { highest_step_num + 1 } ." )
47
+
51
48
return step_title , step_number
52
49
53
50
# 3. Determine the renaming and shifting required based on user input
@@ -65,61 +62,61 @@ def plan_renaming(steps_dict, insert_step_num):
65
62
renaming_plan .reverse ()
66
63
return renaming_plan
67
64
68
- def execute_renaming_plan (renaming_plan ):
65
+ def calculate_renaming_operations (renaming_plan ):
69
66
# Execute the renaming plan
67
+ file_operations = []
70
68
for old_name , new_name in renaming_plan :
71
69
# Make the new directory if it doesn't exist
72
- os . makedirs ( new_name , exist_ok = True )
70
+ file_operations . append (( 'makedirs' , new_name ) )
73
71
# If it's a directory, we need to check for background.sh and foreground.sh
74
72
if os .path .isdir (old_name ):
75
73
# Check and move background.sh if it exists
76
74
old_background = f"{ old_name } /background.sh"
77
75
new_background = f"{ new_name } /background.sh"
78
76
if os .path .isfile (old_background ):
79
- os . rename ( old_background , new_background )
77
+ file_operations . append (( 'rename' , old_background , new_background ) )
80
78
# Check and move foreground.sh if it exists
81
79
old_foreground = f"{ old_name } /foreground.sh"
82
80
new_foreground = f"{ new_name } /foreground.sh"
83
81
if os .path .isfile (old_foreground ):
84
- os . rename ( old_foreground , new_foreground )
82
+ file_operations . append (( 'rename' , old_foreground , new_foreground ) )
85
83
# Rename the step markdown file
86
84
old_step_md = f"{ old_name } /step{ old_name .replace ('step' , '' )} .md"
87
85
new_step_md = f"{ new_name } /step{ new_name .replace ('step' , '' )} .md"
88
86
if os .path .isfile (old_step_md ):
89
- os . rename ( old_step_md , new_step_md )
87
+ file_operations . append (( 'rename' , old_step_md , new_step_md ) )
90
88
else :
91
89
# If it's just a markdown file without a directory
92
90
new_step_md = f"{ new_name } .md"
93
- os .rename (old_name , new_step_md )
91
+ file_operations .append (('rename' , old_name , new_step_md ))
92
+ return file_operations
94
93
95
- def add_new_step_file (insert_step_num , step_title ):
94
+ def calculate_new_step_file_operations (insert_step_num , step_title ):
96
95
# Add the new step folder and files
97
96
new_step_folder = f"step{ insert_step_num } "
98
97
new_step_md = f"{ new_step_folder } /step{ insert_step_num } .md"
99
98
new_step_background = f"{ new_step_folder } /background.sh"
100
99
new_step_foreground = f"{ new_step_folder } /foreground.sh"
101
100
102
- os . makedirs ( new_step_folder , exist_ok = True )
101
+ file_operations = [( 'makedirs' , new_step_folder )]
103
102
104
103
# Write the step markdown file
105
- with open (new_step_md , 'w' ) as md_file :
106
- md_file .write (f"# { step_title } \n " )
104
+ file_operations .append (('write_file' , new_step_md , f"# { step_title } \n " ))
107
105
108
106
# Write a simple echo command to the background and foreground scripts
109
107
script_content = f"#!/bin/sh\n echo \" { step_title } script\" \n "
110
108
111
- with open (new_step_background , 'w' ) as bg_file :
112
- bg_file .write (script_content )
113
- with open (new_step_foreground , 'w' ) as fg_file :
114
- fg_file .write (script_content )
109
+ file_operations .append (('write_file' , new_step_background , script_content ))
110
+ file_operations .append (('write_file' , new_step_foreground , script_content ))
115
111
116
- os . chmod ( new_step_background , 0o755 )
117
- os . chmod ( new_step_foreground , 0o755 )
112
+ file_operations . append (( 'chmod' , new_step_background , 0o755 ) )
113
+ file_operations . append (( 'chmod' , new_step_foreground , 0o755 ) )
118
114
119
- def update_index_json (steps_dict , insert_step_num , step_title , index_file ):
115
+ return file_operations
116
+
117
+ def calculate_index_json_updates (steps_dict , insert_step_num , step_title , current_index_data ):
120
118
# Load the index.json file
121
- with open (index_file , 'r' ) as file :
122
- data = json .load (file )
119
+ data = current_index_data
123
120
124
121
# Create new step entry
125
122
new_step_data = {
@@ -136,11 +133,10 @@ def update_index_json(steps_dict, insert_step_num, step_title, index_file):
136
133
step = data ['details' ]['steps' ][i ]
137
134
step_number = i + 1 # Convert to 1-based index
138
135
step ["text" ] = f"step{ step_number } /step{ step_number } .md"
139
- step ["background" ] = f"step{ step_number } /background{ step_number } .sh"
136
+ step ["background" ] = f"step{ step_number } /background.sh"
140
137
141
138
# Write the updated data back to index.json
142
- with open (index_file , 'w' ) as file :
143
- json .dump (data , file , ensure_ascii = False , indent = 4 )
139
+ return data
144
140
145
141
def display_help ():
146
142
help_text = """
@@ -168,27 +164,64 @@ def main():
168
164
if len (sys .argv ) > 1 and sys .argv [1 ] in ['-h' , '--help' ]:
169
165
display_help ()
170
166
sys .exit ()
171
- old_tree_output = get_tree_output ()
172
- steps_dict = get_current_steps_dict ()
167
+ old_tree_structure = get_tree_structure ()
168
+ directory_items = os .listdir ('.' )
169
+ steps_dict = get_current_steps_dict (directory_items )
173
170
if not steps_dict :
174
171
print ("No step files or directories found. Please run this command in a directory containing step files or directories." )
175
172
sys .exit (1 )
176
- step_title , insert_step_num = get_user_input (steps_dict )
173
+ step_title_input = input ("Enter the title for the new step: " )
174
+ highest_step_num = max (steps_dict .keys (), default = 0 )
175
+ while True :
176
+ try :
177
+ step_number_input = input (f"Enter the step number to insert the new step at (1-{ highest_step_num + 1 } ): " )
178
+ insert_step_num = int (step_number_input )
179
+ if 1 <= insert_step_num <= highest_step_num + 1 :
180
+ break
181
+ else :
182
+ print (f"Please enter a valid step number between 1 and { highest_step_num + 1 } ." )
183
+ except ValueError :
184
+ print ("That's not a valid number. Please try again." )
185
+ step_title , insert_step_num = get_user_input (steps_dict , step_title_input , step_number_input )
177
186
renaming_plan = plan_renaming (steps_dict , insert_step_num )
178
187
179
- # Execute the renaming plan
180
- execute_renaming_plan (renaming_plan )
181
-
182
- # Add the new step
183
- add_new_step_file (insert_step_num , step_title )
184
-
185
- # Update the index.json
186
- index_file = 'index.json'
187
- update_index_json (steps_dict , insert_step_num , step_title , index_file )
188
- new_tree_output = get_tree_output ()
188
+ # Calculate the file operations for the renaming plan
189
+ file_operations = calculate_renaming_operations (renaming_plan )
190
+ # Execute the file operations
191
+ for operation in file_operations :
192
+ if operation [0 ] == 'makedirs' :
193
+ os .makedirs (operation [1 ], exist_ok = True )
194
+ elif operation [0 ] == 'rename' :
195
+ os .rename (operation [1 ], operation [2 ])
196
+
197
+ # Calculate the file operations for the new step
198
+ new_step_operations = calculate_new_step_file_operations (insert_step_num , step_title )
199
+ # Execute the file operations for the new step
200
+ for operation in new_step_operations :
201
+ if operation [0 ] == 'makedirs' :
202
+ os .makedirs (operation [1 ], exist_ok = True )
203
+ elif operation [0 ] == 'write_file' :
204
+ with open (operation [1 ], 'w' ) as file :
205
+ file .write (operation [2 ])
206
+ elif operation [0 ] == 'chmod' :
207
+ os .chmod (operation [1 ], operation [2 ])
208
+
209
+ # Read the current index.json data
210
+ index_file_path = 'index.json'
211
+ with open (index_file_path , 'r' ) as index_file :
212
+ current_index_data = json .load (index_file )
213
+
214
+ # Calculate the updates to the index.json data
215
+ updated_index_data = calculate_index_json_updates (steps_dict , insert_step_num , step_title , current_index_data )
216
+
217
+ # Write the updated index.json data back to the file
218
+ with open (index_file_path , 'w' ) as index_file :
219
+ json .dump (updated_index_data , index_file , ensure_ascii = False , indent = 4 )
220
+ new_tree_structure = get_tree_structure ()
189
221
# Print out the new file structure for confirmation
190
- print ("\n New file structure:" )
191
- print_diff (old_tree_output , new_tree_output )
222
+ tree_diff = generate_diff (old_tree_structure , new_tree_structure )
223
+ print ("\n File structure changes:" )
224
+ print (tree_diff , end = "" )
192
225
193
226
if __name__ == "__main__" :
194
227
main ()
0 commit comments