summaryrefslogtreecommitdiffstats
path: root/devtools/client/projecteditor/lib/stores/local.js
blob: 1f782dadf16c6d7dbaf00b7f5266b1789f00cc18 (plain)
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
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const { Cc, Ci, Cu, ChromeWorker } = require("chrome");
const { Class } = require("sdk/core/heritage");
const { OS } = require("resource://gre/modules/osfile.jsm");
const { emit } = require("sdk/event/core");
const { Store } = require("devtools/client/projecteditor/lib/stores/base");
const { Task } = require("devtools/shared/task");
const promise = require("promise");
const Services = require("Services");
const { on, forget } = require("devtools/client/projecteditor/lib/helpers/event");
const { FileResource } = require("devtools/client/projecteditor/lib/stores/resource");

const CHECK_LINKED_DIRECTORY_DELAY = 5000;
const SHOULD_LIVE_REFRESH = true;
// XXX: Ignores should be customizable
const IGNORE_REGEX = /(^\.)|(\~$)|(^node_modules$)/;

/**
 * A LocalStore object maintains a collection of Resource objects
 * from the file system.
 *
 * This object emits the following events:
 *   - "resource-added": When a resource is added
 *   - "resource-removed": When a resource is removed
 */
var LocalStore = Class({
  extends: Store,

  defaultCategory: "js",

  initialize: function(path) {
    this.initStore();
    this.path = OS.Path.normalize(path);
    this.rootPath = this.path;
    this.displayName = this.path;
    this.root = this._forPath(this.path);
    this.notifyAdd(this.root);
    this.refreshLoop = this.refreshLoop.bind(this);
    this.refreshLoop();
  },

  destroy: function() {
    clearTimeout(this._refreshTimeout);

    if (this._refreshDeferred) {
      this._refreshDeferred.reject("destroy");
    }
    if (this.worker) {
      this.worker.terminate();
    }

    this._refreshTimeout = null;
    this._refreshDeferred = null;
    this.worker = null;

    if (this.root) {
      forget(this, this.root);
      this.root.destroy();
    }
  },

  toString: function() { return "[LocalStore:" + this.path + "]" },

  /**
   * Return a FileResource object for the given path.  If a FileInfo
   * is provided the resource will use it, otherwise the FileResource
   * might not have full information until the next refresh.
   *
   * The following parameters are passed into the FileResource constructor
   * See resource.js for information about them
   *
   * @param String path
   * @param FileInfo info
   * @returns Resource
   */
  _forPath: function(path, info=null) {
    if (this.resources.has(path)) {
      return this.resources.get(path);
    }

    let resource = FileResource(this, path, info);
    this.resources.set(path, resource);
    return resource;
  },

  /**
   * Return a promise that resolves to a fully-functional FileResource
   * within this project.  This will hit the disk for stat info.
   * options:
   *
   *   create: If true, a resource will be created even if the underlying
   *     file doesn't exist.
   */
  resourceFor: function(path, options) {
    path = OS.Path.normalize(path);

    if (this.resources.has(path)) {
      return promise.resolve(this.resources.get(path));
    }

    if (!this.contains(path)) {
      return promise.reject(new Error(path + " does not belong to " + this.path));
    }

    return Task.spawn(function*() {
      let parent = yield this.resourceFor(OS.Path.dirname(path));

      let info;
      try {
        info = yield OS.File.stat(path);
      } catch (ex if ex instanceof OS.File.Error && ex.becauseNoSuchFile) {
        if (!options.create) {
          throw ex;
        }
      }

      let resource = this._forPath(path, info);
      parent.addChild(resource);
      return resource;
    }.bind(this));
  },

  refreshLoop: function() {
    // XXX: Once Bug 958280 adds a watch function, will not need to forever loop here.
    this.refresh().then(() => {
      if (SHOULD_LIVE_REFRESH) {
        this._refreshTimeout = setTimeout(this.refreshLoop,
          CHECK_LINKED_DIRECTORY_DELAY);
      }
    });
  },

  _refreshTimeout: null,
  _refreshDeferred: null,

  /**
   * Refresh the directory structure.
   */
  refresh: function(path=this.rootPath) {
    if (this._refreshDeferred) {
      return this._refreshDeferred.promise;
    }
    this._refreshDeferred = promise.defer();

    let worker = this.worker = new ChromeWorker("chrome://devtools/content/projecteditor/lib/helpers/readdir.js");
    let start = Date.now();

    worker.onmessage = evt => {
      // console.log("Directory read finished in " + ( Date.now() - start ) +"ms", evt);
      for (path in evt.data) {
        let info = evt.data[path];
        info.path = path;

        let resource = this._forPath(path, info);
        resource.info = info;
        if (info.isDir) {
          let newChildren = new Set();
          for (let childPath of info.children) {
            childInfo = evt.data[childPath];
            newChildren.add(this._forPath(childPath, childInfo));
          }
          resource.setChildren(newChildren);
        }
        resource.info.children = null;
      }

      worker = null;
      this._refreshDeferred.resolve();
      this._refreshDeferred = null;
    };
    worker.onerror = ex => {
      console.error(ex);
      worker = null;
      this._refreshDeferred.reject(ex);
      this._refreshDeferred = null;
    }
    worker.postMessage({ path: this.rootPath, ignore: IGNORE_REGEX });
    return this._refreshDeferred.promise;
  },

  /**
   * Returns true if the given path would be a child of the store's
   * root directory.
   */
  contains: function(path) {
    path = OS.Path.normalize(path);
    let thisPath = OS.Path.split(this.rootPath);
    let thatPath = OS.Path.split(path)

    if (!(thisPath.absolute && thatPath.absolute)) {
      throw new Error("Contains only works with absolute paths.");
    }

    if (thisPath.winDrive && (thisPath.winDrive != thatPath.winDrive)) {
      return false;
    }

    if (thatPath.components.length <= thisPath.components.length) {
      return false;
    }

    for (let i = 0; i < thisPath.components.length; i++) {
      if (thisPath.components[i] != thatPath.components[i]) {
        return false;
      }
    }
    return true;
  }
});
exports.LocalStore = LocalStore;