or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

commit-pipeline.mdfile-copy.mdfile-management.mdfile-reading.mdfile-writing.mdindex.mdstate-management.mdtemplate-processing.mdtransform.md

file-management.mddocs/

0

# File Management

1

2

File management operations including moving, deleting, and bulk operations with glob pattern support for reorganizing and cleaning up file structures.

3

4

## Capabilities

5

6

### Move Files

7

8

Move files or directories by copying to the destination and deleting the source, with support for pattern matching and options.

9

10

```typescript { .api }

11

/**

12

* Move file or directory (copy + delete)

13

* @param from - Source path

14

* @param to - Destination path

15

* @param options - Copy options applied during move

16

*/

17

function move(from: string, to: string, options?: CopyOptions): void;

18

19

interface CopyOptions {

20

/** Disable glob pattern matching (default: false) */

21

noGlob?: boolean;

22

/** Options passed to glob library */

23

globOptions?: GlobOptions;

24

/** Don't throw error if no files match pattern (default: false) */

25

ignoreNoMatch?: boolean;

26

/** Base path for relative source paths */

27

fromBasePath?: string;

28

/** Transform destination paths */

29

processDestinationPath?: (path: string) => string;

30

/** Append to destination files instead of overwriting */

31

append?: boolean;

32

/** Process file contents during move */

33

process?: (contents: string | Buffer, filepath: string, destination: string) => string | Buffer;

34

}

35

```

36

37

**Usage Examples:**

38

39

```typescript

40

import { create as createMemFs } from "mem-fs";

41

import { create as createEditor } from "mem-fs-editor";

42

43

const store = createMemFs();

44

const fs = createEditor(store);

45

46

// Move single file

47

fs.move("old-location/file.txt", "new-location/file.txt");

48

49

// Move and rename

50

fs.move("temp/draft.md", "docs/final.md");

51

52

// Move with directory creation

53

fs.move("src/components/Button.tsx", "src/ui/components/Button.tsx");

54

55

// Move with path transformation

56

fs.move("legacy/old-config.json", "config/app-config.json", {

57

process: (contents) => {

58

// Update config format during move

59

const config = JSON.parse(contents.toString());

60

return JSON.stringify({

61

version: "2.0",

62

...config,

63

migrated: true

64

}, null, 2);

65

}

66

});

67

```

68

69

### Delete Files

70

71

Delete files using glob patterns with support for batch operations and selective deletion.

72

73

```typescript { .api }

74

/**

75

* Delete files using glob patterns

76

* @param paths - File paths or glob patterns to delete

77

* @param options - Deletion configuration options

78

*/

79

function delete(paths: string | string[], options?: DeleteOptions): void;

80

81

interface DeleteOptions {

82

/** Options passed to glob library for pattern matching */

83

globOptions?: GlobOptions;

84

}

85

86

interface GlobOptions {

87

/** Exclude directories from results */

88

nodir?: boolean;

89

/** Patterns to ignore during deletion */

90

ignore?: string | string[];

91

/** Additional glob options */

92

[key: string]: any;

93

}

94

```

95

96

**Usage Examples:**

97

98

```typescript

99

// Delete single file

100

fs.delete("temp/cache.txt");

101

102

// Delete multiple specific files

103

fs.delete(["temp/file1.txt", "temp/file2.txt"]);

104

105

// Delete with glob pattern

106

fs.delete("temp/**/*.tmp");

107

108

// Delete all files in directory

109

fs.delete("logs/*");

110

111

// Delete with exclusions

112

fs.delete("dist/**/*", {

113

globOptions: {

114

ignore: ["dist/important/**", "dist/*.config.js"]

115

}

116

});

117

118

// Delete only files, not directories

119

fs.delete("cleanup/**/*", {

120

globOptions: {

121

nodir: true

122

}

123

});

124

```

125

126

## Advanced File Management Patterns

127

128

### Bulk File Operations

129

130

```typescript

131

// Reorganize project structure

132

const moveOperations = [

133

{ from: "old-src/**/*.js", to: "src/js/" },

134

{ from: "old-styles/**/*.css", to: "src/styles/" },

135

{ from: "old-assets/**/*.{png,jpg}", to: "src/assets/images/" }

136

];

137

138

moveOperations.forEach(({ from, to }) => {

139

fs.move(from, to, {

140

processDestinationPath: (path) => {

141

// Maintain filename, change directory structure

142

const filename = path.split("/").pop();

143

return `${to}${filename}`;

144

}

145

});

146

});

147

148

// Clean up after reorganization

149

fs.delete(["old-src/**/*", "old-styles/**/*", "old-assets/**/*"]);

150

```

151

152

### Conditional File Management

153

154

```typescript

155

// Move files based on content

156

fs.copy("mixed/**/*.js", "temp/"); // Copy to analyze first

157

158

// Process each file and move based on content

159

const filesToMove = fs.dump("temp/");

160

Object.keys(filesToMove).forEach(filepath => {

161

const contents = fs.read(filepath);

162

163

if (contents.includes("import React")) {

164

fs.move(filepath, `src/components/${filepath.split("/").pop()}`);

165

} else if (contents.includes("export default")) {

166

fs.move(filepath, `src/utils/${filepath.split("/").pop()}`);

167

} else {

168

fs.move(filepath, `src/misc/${filepath.split("/").pop()}`);

169

}

170

});

171

172

// Clean up temp directory

173

fs.delete("temp/**/*");

174

```

175

176

### Safe File Operations

177

178

```typescript

179

// Create backup before moving important files

180

fs.copy("config/**/*", "backup/config/");

181

fs.move("config/production.json", "config/prod.config.json");

182

183

// Move with validation

184

const moveWithValidation = (from, to) => {

185

if (fs.exists(from)) {

186

const contents = fs.read(from);

187

if (contents && contents.length > 0) {

188

fs.move(from, to);

189

console.log(`Moved ${from} to ${to}`);

190

} else {

191

console.warn(`Skipping empty file: ${from}`);

192

}

193

} else {

194

console.warn(`Source file not found: ${from}`);

195

}

196

};

197

198

moveWithValidation("data/temp.json", "data/processed.json");

199

```

200

201

### File Cleanup Patterns

202

203

```typescript

204

// Clean up generated files

205

fs.delete([

206

"**/*.tmp",

207

"**/.DS_Store",

208

"**/Thumbs.db",

209

"**/*.log",

210

"**/node_modules/.cache/**/*"

211

]);

212

213

// Clean up by file age (using custom logic)

214

const oldFiles = fs.dump();

215

Object.keys(oldFiles).forEach(filepath => {

216

// Custom logic for old file detection would go here

217

if (filepath.includes("temp-") && filepath.includes("2023")) {

218

fs.delete(filepath);

219

}

220

});

221

222

// Clean up empty directories (directories without files)

223

fs.delete("**/*/", {

224

globOptions: {

225

// This would need custom implementation as mem-fs-editor

226

// doesn't directly support empty directory detection

227

}

228

});

229

```

230

231

### Batch Rename Operations

232

233

```typescript

234

// Rename files with pattern

235

const renamePattern = (oldPath, newPattern) => {

236

const filename = oldPath.split("/").pop();

237

const directory = oldPath.substring(0, oldPath.lastIndexOf("/"));

238

const newFilename = filename.replace(/old-prefix-/, newPattern);

239

return `${directory}/${newFilename}`;

240

};

241

242

// Apply rename pattern

243

const filesToRename = fs.dump("src/components/");

244

Object.keys(filesToRename).forEach(filepath => {

245

if (filepath.includes("old-prefix-")) {

246

const newPath = renamePattern(filepath, "new-prefix-");

247

fs.move(filepath, newPath);

248

}

249

});

250

251

// Convert file extensions during move

252

fs.move("typescript/**/*.ts", "javascript/", {

253

processDestinationPath: (path) => {

254

return path.replace(/\.ts$/, ".js").replace("typescript/", "javascript/");

255

},

256

process: (contents) => {

257

// Basic TypeScript to JavaScript conversion

258

return contents

259

.toString()

260

.replace(/: \w+/g, "") // Remove type annotations

261

.replace(/interface \w+.*?{.*?}/gs, ""); // Remove interfaces

262

}

263

});

264

```

265

266

## Error Handling

267

268

```typescript

269

// Safe delete with error handling

270

const safeDelete = (patterns) => {

271

try {

272

fs.delete(patterns, { globOptions: { nodir: true } });

273

console.log(`Deleted files matching: ${patterns}`);

274

} catch (error) {

275

if (error.message.includes("no files found")) {

276

console.log(`No files found for pattern: ${patterns}`);

277

} else {

278

console.error(`Delete failed: ${error.message}`);

279

}

280

}

281

};

282

283

safeDelete("temp/**/*.tmp");

284

285

// Safe move with existence check

286

const safeMove = (from, to) => {

287

if (fs.exists(from)) {

288

try {

289

fs.move(from, to);

290

console.log(`Moved ${from} to ${to}`);

291

} catch (error) {

292

console.error(`Failed to move ${from} to ${to}: ${error.message}`);

293

}

294

} else {

295

console.warn(`Source file does not exist: ${from}`);

296

}

297

};

298

299

safeMove("old/location.txt", "new/location.txt");

300

301

// Bulk operation with error collection

302

const errors = [];

303

const moveOperations = [

304

{ from: "src/old1.js", to: "dist/new1.js" },

305

{ from: "src/old2.js", to: "dist/new2.js" }

306

];

307

308

moveOperations.forEach(({ from, to }) => {

309

try {

310

fs.move(from, to);

311

} catch (error) {

312

errors.push({ operation: "move", from, to, error: error.message });

313

}

314

});

315

316

if (errors.length > 0) {

317

console.error("Some operations failed:", errors);

318

}

319

```