« index

Coverage for /Users/kris/q-io/fs-common.js : 90%

436 lines | 395 run | 41 missing | 1 partial | 119 blocks | 91 blocks run | 28 blocks missing

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

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

  var Q = require("q");
  var Boot = require("./fs-boot");
  var RootFs = require("./fs-root");
  var MockFs = require("./fs-mock");
  
  // TODO patternToRegExp
  // TODO glob
  // TODO match
  
  var concat = function (arrays) {
      return Array.prototype.concat.apply([], arrays);
  };
  
  exports.update = function (exports, workingDirectory) {
  
      for (var name in Boot) {
          exports[name] = Boot[name];
      }
  
      /**
       * Read a complete file.
       * @param {String} path    Path to the file.
       * @param {Object} [options]   An object with options.
       * @param {String} [options.flags]  The mode to open the file with.
       * @param {String} [options.charset]  The charset to open the file with.
       * second argument.
       * @returns {Promise * (String || Buffer)}
       */
      exports.read = function (path, flags, charset, options) {
          if (typeof flags == "object") {
              options = flags;
          } else {
              options = options || {};
              options.flags = flags;
              options.charset = charset;
          }
          options.flags = "r" + (options.flags || "").replace(/r/g, "");
          return Q.when(this.open(path, options), function (stream) {
              return stream.read();
          }, function (error) {
              error.message = "Can't read " + path + " because " + error.message;
              error.path = path;
              error.flags = flags;
              error.charset = charset;
              throw error;
          });
      };
  
      /**
       * Write content to a file, overwriting the existing content.
       * @param {String} path    Path to the file.
       * @param {String || Buffer} content
       * @param {Object} [options]   An object with options.
       * @param {String} [options.flags]  The mode to open the file with.
       * @param {String} [options.charset]  The charset to open the file with.
       * @returns {Promise * Undefined} a promise that resolves
       * when the writing is complete.
       */
      exports.write = function (path, content, flags, charset, options) {
          var self = this;
          if (typeof flags == "object") {
              options = flags;
          } else {
              options = options || {};
              options.flags = flags;
              options.charset = charset;
          }
          flags = "w" + (options.flags || "").replace(/[w]/g, "");
          if (flags.indexOf("b") !== -1) {
              if (!(content instanceof Buffer)) {
                  content = new Buffer(content);
              }
          } else if (content instanceof Buffer) {
              flags += "b";
          }
          options.flags = flags;
          return Q.when(self.open(path, options), function (stream) {
              return Q.when(stream.write(content), function () {
                  return stream.close();
              });
          });
      };
  
      /**
       * Append content to the end of a file.
       * @param {String} path    Path to the file.
       * @param {String || Buffer} content
       * @param {Object} [options]   An object with options.
       * @param {String} [options.flags]  The mode to open the file with.
       * @param {String} [options.charset]  The charset to open the file with.
       * @returns {Promise * Undefined} a promise that resolves
       * when the writing is complete.
       */
      exports.append = function (path, content, flags, charset, options) {
          var self = this;
          if (typeof flags == "object") {
              options = flags;
          } else {
              options = options || {};
              options.flags = flags;
              options.charset = charset;
          }
          flags = "w+" + (options.flags || "").replace(/[w\+]/g, "");
          if (content instanceof Buffer) {
              flags += "b";
          }
          options.flags = flags;
          return Q.when(self.open(path, options), function (stream) {
              return Q.when(stream.write(content), function () {
                  return stream.close();
              });
          });
      };
  
      exports.copy = function (source, target) {
          var self = this;
          return Q.spread([
              self.open(source, {flags: "rb"}),
              self.open(target, {flags: "wb"})
          ], function (reader, writer) {
              return Q.when(reader.forEach(function (block) {
                  return writer.write(block);
              }), function () {
                  return Q.all([
                      reader.close(),
                      writer.close()
                  ]);
              });
          });
      };
  
      exports.copyTree = function (source, target) {
          var self = this;
          return Q.when(self.stat(source), function (stat) {
              if (stat.isFile()) {
                  return self.copy(source, target);
              } else if (stat.isDirectory()) {
                  return Q.when(self.makeDirectory(target), function () {
                      return Q.when(self.list(source), function (list) {
                          return Q.all(list.map(function (child) {
                              return self.copyTree(
                                  self.join(source, child),
                                  self.join(target, child)
                              );
                          }));
                      });
                  });
              } else if (stat.isSymbolicLink()) {
                  // TODO copy the link and type with readPath (but what about
                  // Windows junction type?)
                  return self.symbolicCopy(source, target);
              }
          });
      };
  
      exports.listTree = function (basePath, guard) {
          var self = this;
          basePath = String(basePath || '');
          if (!basePath)
              basePath = ".";
          guard = guard || function () {
              return true;
          };
          var stat = self.stat(basePath);
          return Q.when(stat, function (stat) {
              var paths = [];
              var mode; // true:include, false:exclude, null:no-recur
              try {
                  var include = guard(basePath, stat);
              } catch (exception) {
                  return Q.reject(exception);
              }
              return Q.when(include, function (include) {
                  if (include) {
                      paths.push([basePath]);
                  }
                  if (include !== null && stat.isDirectory()) {
                      return Q.when(self.list(basePath), function (children) {
                          paths.push.apply(paths, children.map(function (child) {
                              var path = self.join(basePath, child);
                              return self.listTree(path, guard);
                          }));
                          return paths;
                      });
                  } else {
                      return paths;
                  }
              });
          }, function noSuchFile(reason) {
              return [];
          }).then(Q.all).then(concat);
      };
  
      exports.listDirectoryTree = function (path) {
          return this.listTree(path, function (path, stat) {
              return stat.isDirectory();
          });
      };
  
      exports.makeTree = function (path, mode) {
          var self = this;
          var parts = self.split(path);
          var at = [];
          if (self.isAbsolute(path)) {
              // On Windows use the root drive (e.g. "C:"), on *nix the first
              // part is the falsey "", and so use the ROOT ("/")
              at.push(parts.shift() || self.ROOT);
          }
          return parts.reduce(function (parent, part) {
              return Q.when(parent, function () {
                  at.push(part);
                  var parts = self.join(at);
                  var made = self.makeDirectory(parts, mode);
                  return Q.when(made, null, function rejected(error) {
                      // throw away errors for already made directories
                      if (error.exists) {
                          return;
                      } else {
                          throw error;
                      }
                  });
              });
          }, undefined);
      };
  
      exports.removeTree = function (path) {
          var self = this;
          return Q.when(self.stat(path), function (stat) {
              if (stat.isSymbolicLink()) {
                  return self.remove(path);
              } else if (stat.isDirectory()) {
                  return self.list(path)
                  .then(function (list) {
                      // asynchronously remove every subtree
                      return Q.all(list.map(function (name) {
                          return self.removeTree(self.join(path, name));
                      }))
                      .then(function () {
                          return self.removeDirectory(path);
                      });
                  });
              } else {
                  return self.remove(path);
              }
          });
      };
  
      exports.symbolicCopy = function (source, target, type) {
          var self = this;
          return Q.when(self.relative(target, source), function (relative) {
              return self.symbolicLink(target, relative, type || "file");
          });
      };
  
      exports.exists = function (path) {
          return Q.when(this.stat(path), function () {
              return true;
          }, function () {
              return false;
          });
      };
  
      exports.isFile = function (path) {
          return Q.when(this.stat(path), function (stat) {
              return stat.isFile();
          }, function (reason) {
              return false;
          });
      };
  
      exports.isDirectory = function (path) {
          return Q.when(this.stat(path), function (stat) {
              return stat.isDirectory();
          }, function (reason) {
              return false;
          });
      };
  
      exports.isSymbolicLink = function (path) {
          return Q.when(this.statLink(path), function (stat) {
              return stat.isSymbolicLink();
          }, function (reason) {
              return false;
          });
      };
  
      exports.lastModified = function (path) {
          var self = this;
          return self.stat(path).invoke('lastModified');
      };
  
      exports.lastAccessed = function (path) {
          var self = this;
          return self.stat(path).invoke('lastAccessed');
      };
  
      exports.absolute = function (path) {
          if (this.isAbsolute(path))
              return this.normal(path);
          return this.join(workingDirectory(), path);
      };
  
      exports.relative = function (source, target) {
          var self = this;
          return Q.when(this.isDirectory(source), function (isDirectory) {
              if (isDirectory) {
                  return self.relativeFromDirectory(source, target);
              } else {
                  return self.relativeFromFile(source, target);
              }
          });
      };
  
      exports.relativeFromFile = function (source, target) {
          var self = this;
          source = self.absolute(source);
          target = self.absolute(target);
          source = source.split(self.SEPARATORS_RE());
          target = target.split(self.SEPARATORS_RE());
          source.pop();
          while (
              source.length &&
              target.length &&
              target[0] == source[0]
          ) {
              source.shift();
              target.shift();
          }
          while (source.length) {
              source.shift();
              target.unshift("..");
          }
          return target.join(self.SEPARATOR);
      };
  
      exports.relativeFromDirectory = function (source, target) {
          if (!target) {
              target = source;
              source = workingDirectory();
          }
          source = this.absolute(source);
          target = this.absolute(target);
          source = source.split(this.SEPARATORS_RE());
          target = target.split(this.SEPARATORS_RE());
          if (source.length === 2 && source[1] === "")
              source.pop();
          while (
              source.length &&
              target.length &&
              target[0] == source[0]
          ) {
              source.shift();
              target.shift();
          }
          while (source.length) {
              source.shift();
              target.unshift("..");
          }
          return target.join(this.SEPARATOR);
      };
  
      exports.contains = function (parent, child) {
          var i, ii;
          parent = this.absolute(parent);
          child = this.absolute(child);
          parent = parent.split(this.SEPARATORS_RE());
          child = child.split(this.SEPARATORS_RE());
          if (parent.length === 2 && parent[1] === "")
              parent.pop();
          if (parent.length > child.length)
              return false;
          for (i = 0, ii = parent.length; i < ii; i++) {
              if (parent[i] !== child[i])
                  break;
          }
          return i == ii;
      };
  
      exports.reroot = reroot;
      function reroot(path) {
          var self = this;
          path = path || this.ROOT;
          return Q.when(this.list(path), function (list) {
              if (list.length !== 1)
                  return RootFs(self, path);
              var nextPath = self.join(path, list[0]);
              return Q.when(self.stat(nextPath), function (stat) {
                  if (stat.isDirectory()) {
                      return reroot(nextPath);
                  } else {
                      return RootFs(self, path);
                  }
              });
          });
      }
  
      exports.toObject = function (path) {
          var self = this;
          var list = self.listTree(path || "", function (path, stat) {
              return stat.isFile();
          });
          return Q.when(list, function (list) {
              var tree = {};
              return Q.all(list.map(function (path) {
                  return Q.when(self.read(path, "rb"), function (content) {
                      tree[path] = content;
                  });
              })).then(function () {
                  return tree;
              });
          });
      };
  
      exports.merge = function (fss) {
          var tree = {};
          var done;
          fss.forEach(function (fs) {
              done = Q.when(done, function () {
                  return fs.listTree("", function (path, stat) {
                      return stat.isFile();
                  })
                  .then(function (list) {
                      return Q.all(list.map(function (path) {
                          return Q.when(fs.read(path, "rb"), function (content) {
                              tree[path] = content;
                          });
                      }));
                  });
              });
          })
          return Q.when(done, function () {
              return MockFs(tree);
          });
      };
  
  }
« index | cover.io