file_system.dart 2.11 KB
Newer Older
1 2 3 4
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:io' as dart_io;
6

yjbanov's avatar
yjbanov committed
7 8
import 'package:file/io.dart';
import 'package:file/sync_io.dart';
9 10
import 'package:path/path.dart' as path;

yjbanov's avatar
yjbanov committed
11 12 13 14 15 16 17 18 19 20
export 'package:file/io.dart';
export 'package:file/sync_io.dart';

/// Currently active implmenetation of the file system.
///
/// By default it uses local disk-based implementation. Override this in tests
/// with [MemoryFileSystem].
FileSystem fs = new LocalFileSystem();
SyncFileSystem syncFs = new SyncLocalFileSystem();

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
typedef String CurrentDirectoryGetter();

final CurrentDirectoryGetter _defaultCurrentDirectoryGetter = () {
  return dart_io.Directory.current.path;
};

/// Points to the current working directory (like `pwd`).
CurrentDirectoryGetter getCurrentDirectory = _defaultCurrentDirectoryGetter;

/// Exits the process with the given [exitCode].
typedef void ExitFunction([int exitCode]);

final ExitFunction _defaultExitFunction = ([int exitCode]) {
  dart_io.exit(exitCode);
};

/// Exits the process.
ExitFunction exit = _defaultExitFunction;

yjbanov's avatar
yjbanov committed
40 41 42 43
/// Restores [fs] and [syncFs] to the default local disk-based implementation.
void restoreFileSystem() {
  fs = new LocalFileSystem();
  syncFs = new SyncLocalFileSystem();
44 45
  getCurrentDirectory = _defaultCurrentDirectoryGetter;
  exit = _defaultExitFunction;
yjbanov's avatar
yjbanov committed
46 47
}

48
/// Uses in-memory replacments for `dart:io` functionality. Useful in tests.
Ian Hickson's avatar
Ian Hickson committed
49
void useInMemoryFileSystem({ String cwd: '/', ExitFunction exitFunction }) {
yjbanov's avatar
yjbanov committed
50 51 52
  MemoryFileSystem memFs = new MemoryFileSystem();
  fs = memFs;
  syncFs = new SyncMemoryFileSystem(backedBy: memFs.storage);
53 54 55 56
  getCurrentDirectory = () => cwd;
  exit = exitFunction ?? ([int exitCode]) {
    throw new Exception('Exited with code $exitCode');
  };
yjbanov's avatar
yjbanov committed
57 58
}

59 60 61
/// Create the ancestor directories of a file path if they do not already exist.
void ensureDirectoryExists(String filePath) {
  String dirPath = path.dirname(filePath);
yjbanov's avatar
yjbanov committed
62 63

  if (syncFs.type(dirPath) == FileSystemEntityType.DIRECTORY)
64
    return;
yjbanov's avatar
yjbanov committed
65
  syncFs.directory(dirPath).create(recursive: true);
66
}