summaryrefslogtreecommitdiff
path: root/chromium/gin/modules/file_module_provider.cc
blob: 46939b123be878449e93b19b0811b462fcae2738 (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
// Copyright 2013 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.

#include "gin/modules/file_module_provider.h"

#include <stddef.h>

#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_split.h"
#include "base/threading/thread_task_runner_handle.h"
#include "gin/converter.h"

namespace gin {

namespace {

void AttempToLoadModule(const base::WeakPtr<Runner>& runner,
                        const std::vector<base::FilePath>& search_paths,
                        const std::string& id) {
  if (!runner)
    return;

  std::vector<std::string> components = base::SplitString(
      id, "/", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);

  base::FilePath path;
  for (size_t i = 0; i < components.size(); ++i) {
    // TODO(abarth): Technically the path components can be UTF-8. We don't
    // handle that case correctly yet.
    path = path.AppendASCII(components[i]);
  }
  path = path.AddExtension(FILE_PATH_LITERAL("js"));

  for (size_t i = 0; i < search_paths.size(); ++i) {
    std::string source;
    if (!ReadFileToString(search_paths[i].Append(path), &source))
      continue;

    Runner::Scope scope(runner.get());
    runner->Run(source, id);
    return;
  }
  LOG(ERROR) << "Failed to load module from disk: " << id;
}

}  // namespace

FileModuleProvider::FileModuleProvider(
    const std::vector<base::FilePath>& search_paths)
    : search_paths_(search_paths) {
}

FileModuleProvider::~FileModuleProvider() {
}

void FileModuleProvider::AttempToLoadModules(
    Runner* runner, const std::set<std::string>& ids) {
  std::set<std::string> modules = ids;
  for (std::set<std::string>::const_iterator it = modules.begin();
       it != modules.end(); ++it) {
    const std::string& id = *it;
    if (attempted_ids_.count(id))
      continue;
    attempted_ids_.insert(id);
    base::ThreadTaskRunnerHandle::Get()->PostTask(
        FROM_HERE, base::Bind(AttempToLoadModule, runner->GetWeakPtr(),
                              search_paths_, id));
  }
}

}  // namespace gin