Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_ops.py
More file actions
Latest commit
285 lines (234 loc) · 12.1 KB
/
Copy pathfile_ops.py
File metadata and controls
285 lines (234 loc) · 12.1 KB
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
frompathlibimportPath
importplatform
importjson
importos
importglob
importshutil
importdatetime
public_description="Handle file operations with smart path resolution."
PLATFORM=platform.system().lower()
asyncdeffunction(args):
try:
operation=args.get("operation")
source=args.get("source", "")
destination=args.get("destination", "")
filename=args.get("filename", "")
content=args.get("content", "")
pattern=args.get("pattern", "*")
ifsource:
ifsource.startswith('~'):
source=os.path.join(os.path.expanduser('~'), source[2:] ifsource.startswith('~/') orsource.startswith('~\\') elsesource[1:])
source=os.path.normpath(source)
ifdestination:
ifdestination.startswith('~'):
destination=os.path.join(os.path.expanduser('~'), destination[2:] ifdestination.startswith('~/') ordestination.startswith('~\\') elsedestination[1:])
destination=os.path.normpath(destination)
# Operation-specific validations
ifoperationin ["move", "copy", "latest", "read", "file_info", "search"]:
ifnotsourceornotos.path.exists(source):
returnjson.dumps({"error": f"Source not found: {source}"})
ifoperationin ["move", "copy", "write", "create_directory"]:
ifnotdestination:
returnjson.dumps({"error": f"Destination required for {operation}"})
# Create parent directories if they don't exist for certain operations
ifoperationin ["write", "create_directory"]:
os.makedirs(os.path.dirname(destination), exist_ok=True)
# Handle different operations
ifoperation=="move":
iffilename:
matches=list(Path(source).glob(f"{filename}*"))
ifnotmatches:
returnjson.dumps({"error": f"No file matching '{filename}' found"})
src_file=matches[0]
dst_file=Path(destination) /src_file.name
try:
ifnotsrc_file.is_file():
returnjson.dumps({"error": "Source is not a file"})
dst_file.parent.mkdir(parents=True, exist_ok=True)
os.replace(str(src_file), str(dst_file))
ifnotdst_file.exists():
returnjson.dumps({"error": "Move operation failed"})
exceptPermissionError:
returnjson.dumps({"error": "Permission denied"})
exceptExceptionase:
returnjson.dumps({"error": f"Move failed: {str(e)}"})
else:
returnjson.dumps({"error": "Filename required for move operation"})
elifoperation=="latest":
try:
files= [(f, os.path.getmtime(f)) forfinPath(source).iterdir() iff.is_file()]
ifnotfiles:
returnjson.dumps({"error": f"No files found in {source}"})
latest=max(files, key=lambdax: x[1])[0]
dst_file=Path(destination) /latest.name
os.replace(str(latest), str(dst_file))
ifnotdst_file.exists():
returnjson.dumps({"error": "Move operation failed"})
exceptExceptionase:
returnjson.dumps({"error": f"Latest operation failed: {str(e)}"})
elifoperation=="read":
try:
ifos.path.isdir(source):
returnjson.dumps({"error": f"Cannot read a directory: {source}"})
withopen(source, 'r', encoding='utf-8', errors='replace') asf:
content=f.read()
returnjson.dumps({"content": content})
exceptUnicodeDecodeError:
returnjson.dumps({"error": "File appears to be binary and cannot be read as text"})
exceptExceptionase:
returnjson.dumps({"error": f"Read failed: {str(e)}"})
elifoperation=="write":
try:
withopen(destination, 'w', encoding='utf-8') asf:
f.write(content)
returnjson.dumps({"message": f"Successfully wrote to {destination}"})
exceptExceptionase:
returnjson.dumps({"error": f"Write failed: {str(e)}"})
elifoperation=="list_directory":
try:
ifnotos.path.isdir(source):
returnjson.dumps({"error": f"Not a directory: {source}"})
items= []
foriteminos.listdir(source):
full_path=os.path.join(source, item)
is_dir=os.path.isdir(full_path)
items.append({
"name": item,
"type": "directory"ifis_direlse"file",
"path": full_path
})
returnjson.dumps({"items": items})
exceptExceptionase:
returnjson.dumps({"error": f"List directory failed: {str(e)}"})
elifoperation=="directory_tree":
try:
ifnotos.path.isdir(source):
returnjson.dumps({"error": f"Not a directory: {source}"})
defbuild_tree(path, max_depth=3, current_depth=0):
ifcurrent_depth>max_depth:
return {"name": os.path.basename(path), "type": "directory", "children": [{"name": "...", "type": "more"}]}
result= {"name": os.path.basename(path), "type": "directory", "children": []}
try:
foriteminos.listdir(path):
full_path=os.path.join(path, item)
ifos.path.isdir(full_path):
result["children"].append(build_tree(full_path, max_depth, current_depth+1))
else:
result["children"].append({"name": item, "type": "file"})
exceptPermissionError:
result["children"].append({"name": "Permission denied", "type": "error"})
returnresult
tree=build_tree(source)
returnjson.dumps({"tree": tree})
exceptExceptionase:
returnjson.dumps({"error": f"Directory tree failed: {str(e)}"})
elifoperation=="file_info":
try:
ifnotos.path.exists(source):
returnjson.dumps({"error": f"File not found: {source}"})
stat=os.stat(source)
info= {
"name": os.path.basename(source),
"path": source,
"size": stat.st_size,
"created": datetime.datetime.fromtimestamp(stat.st_ctime).isoformat(),
"modified": datetime.datetime.fromtimestamp(stat.st_mtime).isoformat(),
"accessed": datetime.datetime.fromtimestamp(stat.st_atime).isoformat(),
"is_directory": os.path.isdir(source),
"is_file": os.path.isfile(source),
"permissions": oct(stat.st_mode)[-3:]
}
returnjson.dumps({"info": info})
exceptExceptionase:
returnjson.dumps({"error": f"File info failed: {str(e)}"})
elifoperation=="search":
try:
ifnotos.path.isdir(source):
returnjson.dumps({"error": f"Not a directory: {source}"})
matches= []
foriteminglob.glob(f"{source}/**/{pattern}", recursive=True):
ifos.path.exists(item): # Check in case it was deleted during search
matches.append({
"path": item,
"name": os.path.basename(item),
"is_directory": os.path.isdir(item)
})
returnjson.dumps({"matches": matches})
exceptExceptionase:
returnjson.dumps({"error": f"Search failed: {str(e)}"})
elifoperation=="create_directory":
try:
os.makedirs(destination, exist_ok=True)
returnjson.dumps({"message": f"Successfully created directory: {destination}"})
exceptExceptionase:
returnjson.dumps({"error": f"Create directory failed: {str(e)}"})
elifoperation=="copy":
try:
iffilename:
matches=list(Path(source).glob(f"{filename}*"))
ifnotmatches:
returnjson.dumps({"error": f"No file matching '{filename}' found"})
src_file=matches[0]
dst_file=Path(destination) /src_file.name
ifos.path.isdir(src_file):
shutil.copytree(src_file, dst_file)
else:
shutil.copy2(src_file, dst_file)
returnjson.dumps({"message": f"Successfully copied {src_file} to {dst_file}"})
else:
returnjson.dumps({"error": "Filename required for copy operation"})
exceptExceptionase:
returnjson.dumps({"error": f"Copy failed: {str(e)}"})
else:
returnjson.dumps({"error": "Invalid operation"})
returnjson.dumps({"message": "File operation completed successfully"})
exceptExceptionase:
returnjson.dumps({"error": str(e)})
object= {
"name": "file_ops",
"description": """Handle file operations with smart path resolution.
Examples:
"move report from downloads to documents"
→ {"operation": "move", "source": "~/Downloads", "destination": "~/Documents", "filename": "report"}
"move latest download to Documents"
→ {"operation": "latest", "source": "~/Downloads", "destination": "~/Documents"}
"read my notes.txt file"
→ {"operation": "read", "source": "~/notes.txt"}
"list files in Downloads folder"
→ {"operation": "list_directory", "source": "~/Downloads"}
"get info about my resume.pdf"
→ {"operation": "file_info", "source": "~/Documents/resume.pdf"}
"search for python files in my projects folder"
→ {"operation": "search", "source": "~/Projects", "pattern": "*.py"}""",
"parameters": {
"type": "object",
"properties": {
"operation": {
"type": "string",
"enum": ["move", "latest", "read", "write", "list_directory", "directory_tree", "file_info", "search", "create_directory", "copy"],
"description": "Type of file operation"
},
"source": {
"type": "string",
"description": "Source path (use ~ for home directory)"
},
"destination": {
"type": "string",
"description": "Destination path (use ~ for home directory)"
},
"filename": {
"type": "string",
"description": "Filename without extension (optional)"
},
"content": {
"type": "string",
"description": "Content to write to a file"
},
"pattern": {
"type": "string",
"description": "Search pattern (e.g., *.txt for text files)"
}
},
"required": ["operation"]
}
}