Move more string_util functions to base namespace.
[chromium-blink-merge.git] / gin / test / file.cc
blob38efbb434f915381884fc9643e267598e44e0ff7
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "gin/test/file.h"
7 #include <iostream>
9 #include "base/bind.h"
10 #include "base/files/file_enumerator.h"
11 #include "base/files/file_path.h"
12 #include "base/files/file_util.h"
13 #include "base/path_service.h"
14 #include "gin/arguments.h"
15 #include "gin/converter.h"
16 #include "gin/object_template_builder.h"
17 #include "gin/per_isolate_data.h"
18 #include "gin/public/wrapper_info.h"
20 using v8::ObjectTemplate;
22 namespace gin {
24 namespace {
26 v8::Local<v8::Value> ReadFileToString(gin::Arguments* args) {
27 std::string filename;
28 if (!args->GetNext(&filename))
29 return v8::Null(args->isolate());
31 const base::FilePath& path = base::FilePath::FromUTF8Unsafe(filename);
32 std::string contents;
33 if (!ReadFileToString(path, &contents))
34 return v8::Null(args->isolate());
36 return gin::Converter<std::string>::ToV8(args->isolate(), contents);
39 v8::Local<v8::Value> GetSourceRootDirectory(gin::Arguments* args) {
40 base::FilePath path;
41 if (!PathService::Get(base::DIR_SOURCE_ROOT, &path))
42 return v8::Null(args->isolate());
43 return gin::Converter<std::string>::ToV8(args->isolate(),
44 path.AsUTF8Unsafe());
47 v8::Local<v8::Value> GetFilesInDirectory(gin::Arguments* args) {
48 std::string filename;
49 if (!args->GetNext(&filename))
50 return v8::Null(args->isolate());
52 const base::FilePath& path = base::FilePath::FromUTF8Unsafe(filename);
53 if (!base::DirectoryExists(path))
54 return v8::Null(args->isolate());
56 std::vector<std::string> names;
57 base::FileEnumerator e(path, false, base::FileEnumerator::FILES);
58 for (base::FilePath name = e.Next(); !name.empty(); name = e.Next()) {
59 names.push_back(name.BaseName().AsUTF8Unsafe());
62 v8::Local<v8::Value> v8_names;
63 if (!TryConvertToV8(args->isolate(), names, &v8_names))
64 return v8::Null(args->isolate());
65 return v8_names;
68 gin::WrapperInfo g_wrapper_info = { gin::kEmbedderNativeGin };
70 } // namespace
72 const char File::kModuleName[] = "file";
74 v8::Local<v8::Value> File::GetModule(v8::Isolate* isolate) {
75 gin::PerIsolateData* data = gin::PerIsolateData::From(isolate);
76 v8::Local<ObjectTemplate> templ = data->GetObjectTemplate(&g_wrapper_info);
77 if (templ.IsEmpty()) {
78 templ = gin::ObjectTemplateBuilder(isolate)
79 .SetMethod("readFileToString", ReadFileToString)
80 .SetMethod("getFilesInDirectory", GetFilesInDirectory)
81 .SetMethod("getSourceRootDirectory", GetSourceRootDirectory)
82 .Build();
83 data->SetObjectTemplate(&g_wrapper_info, templ);
85 return templ->NewInstance();
88 } // namespace gin