1# Copyright 2016 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.
4
5import os
6import subprocess
7import sys
8
9import py_utils
10from py_utils import binary_manager
11from py_utils import dependency_util
12
13
14def _NodeBinariesConfigPath():
15  return os.path.realpath(os.path.join(
16      os.path.dirname(os.path.abspath(__file__)), 'node_binaries.json'))
17
18
19class _NodeManager(object):
20  def __init__(self):
21    self.bm = binary_manager.BinaryManager(
22        [_NodeBinariesConfigPath()])
23    self.os_name = dependency_util.GetOSNameForCurrentDesktopPlatform()
24    self.arch_name = dependency_util.GetArchForCurrentDesktopPlatform(
25        self.os_name)
26    self.node_path = self.bm.FetchPath('node', self.os_name, self.arch_name)
27    self.npm_path = self.bm.FetchPath('npm', self.os_name, self.arch_name)
28
29    self.node_initialized = False
30
31  def InitNode(self):
32    if self.node_initialized:
33      return  # So we only init once per run
34    self.node_initialized = True
35    old_dir = os.path.abspath(os.curdir)
36    os.chdir(os.path.join(os.path.abspath(
37        py_utils.GetCatapultDir()), 'common', 'node_runner', 'node_runner'))
38    subprocess.call([self.node_path, self.npm_path, 'install'])
39    os.chdir(old_dir)
40
41
42_NODE_MANAGER = _NodeManager()
43
44
45def InitNode():
46  _NODE_MANAGER.InitNode()
47
48
49def GetNodePath():
50  return _NODE_MANAGER.node_path
51
52
53def GetNodeModulesPath():
54  _NODE_MANAGER.InitNode()
55  path = os.path.abspath(os.path.join(os.path.dirname(__file__),
56                                      'node_modules'))
57  if sys.platform.startswith('win'):
58    # Escape path on Windows because it's very long and must be passed to NTFS.
59    path = u'\\\\?\\' + path
60  return path
61