summaryrefslogtreecommitdiff
path: root/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/DirectoryBasedStorage.java
blob: 912c239cffcbf0259b1fc829608b99b02e2313f8 (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
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
/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.openapi.components.impl.stores;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.tracker.VirtualFileTracker;
import com.intellij.util.SmartList;
import com.intellij.util.containers.SmartHashSet;
import com.intellij.util.messages.MessageBus;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.picocontainer.PicoContainer;

import java.io.File;
import java.io.IOException;
import java.util.*;

//todo: support missing plugins
//todo: support storage data
public class DirectoryBasedStorage implements StateStorage, Disposable {
  private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.components.impl.stores.DirectoryBasedStorage");

  private final TrackingPathMacroSubstitutor myPathMacroSubstitutor;
  private final File myDir;
  private final StateSplitter mySplitter;
  private final FileTypeManager myFileTypeManager;

  private Object mySession;
  private DirectoryStorageData myStorageData = null;

  public DirectoryBasedStorage(@Nullable TrackingPathMacroSubstitutor pathMacroSubstitutor,
                               @NotNull String dir,
                               @NotNull StateSplitter splitter,
                               @NotNull Disposable parentDisposable,
                               @NotNull PicoContainer picoContainer) {
    myPathMacroSubstitutor = pathMacroSubstitutor;
    myDir = new File(dir);
    mySplitter = splitter;
    Disposer.register(parentDisposable, this);

    VirtualFileTracker virtualFileTracker = (VirtualFileTracker)picoContainer.getComponentInstanceOfType(VirtualFileTracker.class);
    MessageBus messageBus = (MessageBus)picoContainer.getComponentInstanceOfType(MessageBus.class);

    if (virtualFileTracker != null && messageBus != null) {
      final String path = myDir.getAbsolutePath();
      final String fileUrl = LocalFileSystem.PROTOCOL_PREFIX + path.replace(File.separatorChar, '/');
      final Listener listener = messageBus.syncPublisher(STORAGE_TOPIC);
      virtualFileTracker.addTracker(fileUrl, new VirtualFileAdapter() {
        @Override
        public void contentsChanged(@NotNull final VirtualFileEvent event) {
          if (!StringUtil.endsWithIgnoreCase(event.getFile().getName(), ".xml")) return;
          listener.storageFileChanged(event, DirectoryBasedStorage.this);
        }

        @Override
        public void fileDeleted(@NotNull final VirtualFileEvent event) {
          if (!StringUtil.endsWithIgnoreCase(event.getFile().getName(), ".xml")) return;
          listener.storageFileChanged(event, DirectoryBasedStorage.this);
        }

        @Override
        public void fileCreated(@NotNull final VirtualFileEvent event) {
          if (!StringUtil.endsWithIgnoreCase(event.getFile().getName(), ".xml")) return;
          listener.storageFileChanged(event, DirectoryBasedStorage.this);
        }
      }, false, this);
    }

    myFileTypeManager = FileTypeManager.getInstance();
  }

  @Override
  @Nullable
  public <T> T getState(final Object component, @NotNull final String componentName, Class<T> stateClass, @Nullable T mergeInto)
    throws StateStorageException {
    if (myStorageData == null) myStorageData = loadState();


    if (!myStorageData.containsComponent(componentName)) {
      return DefaultStateSerializer.deserializeState(new Element(StorageData.COMPONENT), stateClass, mergeInto);
    }

    return myStorageData.getMergedState(componentName, stateClass, mySplitter, mergeInto);
  }

  private DirectoryStorageData loadState() throws StateStorageException {
    DirectoryStorageData storageData = new DirectoryStorageData();
    storageData.loadFrom(LocalFileSystem.getInstance().findFileByIoFile(myDir), myPathMacroSubstitutor);
    return storageData;
  }


  @Override
  public boolean hasState(final Object component, @NotNull String componentName, final Class<?> aClass, final boolean reloadData) throws StateStorageException {
    if (!myDir.exists()) return false;
    if (reloadData) myStorageData = null;
    return true;
  }

  @Override
  @NotNull
  public ExternalizationSession startExternalization() {
    if (myStorageData == null) {
      try {
        myStorageData = loadState();
      }
      catch (StateStorageException e) {
        LOG.error(e);
      }
    }
    final ExternalizationSession session = new MyExternalizationSession(myStorageData.clone());

    mySession = session;
    return session;
  }

  @Override
  @NotNull
  public SaveSession startSave(@NotNull final ExternalizationSession externalizationSession) {
    assert mySession == externalizationSession;

    final MySaveSession session =
      new MySaveSession(((MyExternalizationSession)externalizationSession).myStorageData, myPathMacroSubstitutor);
    mySession = session;
    return session;
  }

  @Override
  public void finishSave(@NotNull final SaveSession saveSession) {
    try {
      LOG.assertTrue(mySession == saveSession);
    } finally {
      mySession = null;
    }
  }

  @Override
  public void reload(@NotNull final Set<String> changedComponents) throws StateStorageException {
    myStorageData = loadState();
  }

  @Override
  public void dispose() {
  }

  private class MySaveSession implements SaveSession, SafeWriteRequestor {
    private final DirectoryStorageData myStorageData;
    private final TrackingPathMacroSubstitutor myPathMacroSubstitutor;

    private MySaveSession(final DirectoryStorageData storageData, final TrackingPathMacroSubstitutor pathMacroSubstitutor) {
      myStorageData = storageData;
      myPathMacroSubstitutor = pathMacroSubstitutor;
    }

    @Override
    public void save() throws StateStorageException {
      assert mySession == this;
      final Set<String> currentNames = new SmartHashSet<String>();
      File[] children = myDir.listFiles();
      if (children != null) {
        for (File child : children) {
          final String fileName = child.getName();
          if (!myFileTypeManager.isFileIgnored(fileName) && StringUtil.endsWithIgnoreCase(fileName, ".xml")) {
            currentNames.add(fileName);
          }
        }
      }

      myStorageData.process(new DirectoryStorageData.StorageDataProcessor() {
        @Override
        public void process(final String componentName, final File file, final Element element) {
          currentNames.remove(file.getName());

          if (myPathMacroSubstitutor != null) {
            myPathMacroSubstitutor.collapsePaths(element);
          }

          if (file.lastModified() <= myStorageData.getLastTimeStamp()) {
            StorageUtil.save(file, element, MySaveSession.this, false, null);
            myStorageData.updateLastTimestamp(file);
          }
        }
      });

      if (myDir.exists() && !currentNames.isEmpty()) {
      ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
          if (myDir.exists()) {
            for (String name : currentNames) {
              File child = new File(myDir, name);
              if (child.lastModified() > myStorageData.getLastTimeStamp()) {
                // do not touch new files during VC update (which aren't read yet)
                // now got an opposite problem: file is recreated if was removed by VC during update.
                return;
              }

              final VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByIoFile(child);
              if (virtualFile != null) {
                try {
                  LOG.debug("Removing configuration file: " + virtualFile.getPresentableUrl());
                  virtualFile.delete(MySaveSession.this);
                }
                catch (IOException e) {
                  LOG.error(e);
                }
              }
            }
          }
        }
      });
      }

      myStorageData.clear();
    }

    @Override
    @Nullable
    public Set<String> analyzeExternalChanges(@NotNull final Set<Pair<VirtualFile, StateStorage>> changedFiles) {
      boolean containsSelf = false;

      for (Pair<VirtualFile, StateStorage> pair : changedFiles) {
        if (pair.second == DirectoryBasedStorage.this) {
          VirtualFile file = pair.first;
          if ("xml".equalsIgnoreCase(file.getExtension())) {
            containsSelf = true;
            break;
          }
        }
      }

      if (!containsSelf) return Collections.emptySet();

      if (myStorageData.getComponentNames().size() == 0) {
        // no state yet, so try to initialize it now
        final DirectoryStorageData storageData = loadState();
        return new HashSet<String>(storageData.getComponentNames());
      }

      return new HashSet<String>(myStorageData.getComponentNames());
    }

    @Override
    @NotNull
    public Collection<File> getStorageFilesToSave() throws StateStorageException {
      assert mySession == this;

      if (!myDir.exists()) return getAllStorageFiles();
      assert myDir.isDirectory() : myDir.getPath();

      final List<File> filesToSave = new ArrayList<File>();
      final Set<String> currentChildNames = new SmartHashSet<String>();
      File[] children = myDir.listFiles();
      if (children != null) {
        for (File child : children) {
          if (!myFileTypeManager.isFileIgnored(child.getName())) {
            currentChildNames.add(child.getName());
          }
        }
      }

      myStorageData.process(new DirectoryStorageData.StorageDataProcessor() {
        @Override
        public void process(final String componentName, final File file, final Element element) {
          if (currentChildNames.contains(file.getName())) {
            currentChildNames.remove(file.getName());

            if (myPathMacroSubstitutor != null) {
              myPathMacroSubstitutor.collapsePaths(element);
            }

            VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByIoFile(file);
            if (virtualFile == null || !StorageUtil.contentEquals(element, virtualFile)) {
              filesToSave.add(file);
            }
          }
        }
      });

      for (String childName : currentChildNames) {
        filesToSave.add(new File(myDir, childName));
      }

      return filesToSave;
    }

    @Override
    @NotNull
    public List<File> getAllStorageFiles() {
      return new SmartList<File>(myStorageData.getAllStorageFiles().keySet());
    }
  }

  private class MyExternalizationSession implements ExternalizationSession {
    private final DirectoryStorageData myStorageData;

    private MyExternalizationSession(final DirectoryStorageData storageData) {
      myStorageData = storageData;
    }

    @Override
    public void setState(@NotNull final Object component, final String componentName, @NotNull final Object state, final Storage storageSpec) {
      assert mySession == this;
      setState(componentName, state, storageSpec);
    }

    private void setState(final String componentName, @NotNull Object state, final Storage storageSpec) {
      try {
        final Element element = DefaultStateSerializer.serializeState(state, storageSpec);
        if (element != null) {
          for (Pair<Element, String> pair : mySplitter.splitState(element)) {
            Element e = pair.first;
            String name = pair.second;

            Element statePart = new Element(StorageData.COMPONENT);
            statePart.setAttribute(StorageData.NAME, componentName);
            statePart.addContent(e.detach());

            myStorageData.put(componentName, new File(myDir, name), statePart, false);
          }
        }
      }
      catch (WriteExternalException e) {
        throw new StateStorageException(e);
      }
    }
  }
}