Class: ReactNativeUtil::Converter

Inherits:
Object
  • Object
show all
Includes:
Util
Defined in:
lib/react_native_util/converter.rb

Overview

Class to perform conversion operations.

Constant Summary collapse

DEFAULT_DEPENDENCIES =
Array<String>

Xcode projects from react-native that may be in the Libraries group

%w[
  ART
  React
  RCTActionSheet
  RCTAnimation
  RCTBlob
  RCTCameraRoll
  RCTGeolocation
  RCTImage
  RCTLinking
  RCTNetwork
  RCTPushNotification
  RCTSettings
  RCTTest
  RCTText
  RCTVibration
  RCTWebSocket
]
PODFILE_TEMPLATE_PATH =
String

Path to the Podfile template

File.expand_path '../assets/templates/Podfile.erb', __dir__

Instance Attribute Summary collapse

Attributes included from Util

#platform

Instance Method Summary collapse

Methods included from Util

#boolean_env_var?, #execute, #float_env_var, #log, #mac?

Constructor Details

#initialize(repo_update: nil) ⇒ Converter

Returns a new instance of Converter.



47
48
49
50
51
52
53
54
# File 'lib/react_native_util/converter.rb', line 47

def initialize(repo_update: nil)
  @options = {}
  if repo_update.nil?
    @options[:repo_update] = boolean_env_var?(:REACT_NATIVE_UTIL_REPO_UPDATE, default_value: true)
  else
    @options[:repo_update] = repo_update
  end
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



44
45
46
# File 'lib/react_native_util/converter.rb', line 44

def options
  @options
end

#package_jsonObject (readonly)

Hash

Contents of ./package.json



36
37
38
# File 'lib/react_native_util/converter.rb', line 36

def package_json
  @package_json
end

#react_podspecObject (readonly)

Returns the value of attribute react_podspec.



45
46
47
# File 'lib/react_native_util/converter.rb', line 45

def react_podspec
  @react_podspec
end

#xcodeprojObject (readonly)

Xcodeproj::Project

Contents of the project at xcodproj_path



42
43
44
# File 'lib/react_native_util/converter.rb', line 42

def xcodeproj
  @xcodeproj
end

#xcodeproj_pathObject (readonly)

String

Full path to Xcode project



39
40
41
# File 'lib/react_native_util/converter.rb', line 39

def xcodeproj_path
  @xcodeproj_path
end

Instance Method Details

#add_packager_scriptObject

Adds the Start Packager script from the React.xcodeproj under node_modules to the main application target before deleting React.xcodeproj from the Libraries group. Adjusts paths in the script to account for the different project location. If React.xcodeproj cannot be opened, or if the relevant build phase is not found, a warning is logged, and this step is skipped.

TODO: The build phase is added after all other build phases. Ideally it can be moved to the beginning. The packager is independent of the Xcode build process. It may be started at any time. Starting it early is an optimization that allows it to load while the build is in progress. Currently it’s possible to simply drag the build phase in Xcode to a higher position after running the react_pod command.



294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/react_native_util/converter.rb', line 294

def add_packager_script
  old_packager_phase = packager_phase_from_react_project
  unless old_packager_phase
    log 'Could not find packager build phase in React.xcodeproj. Skipping.'.yellow
    return
  end

  # location of project is different relative to packager script
  script = old_packager_phase.shell_script.gsub(%r{../scripts}, '../node_modules/react-native/scripts')

  # target can't be nil. Already validated earlier by #validate_app_target!
  target = xcodeproj.targets.find { |t| t.name == app_name }
  phase = target.new_shell_script_build_phase old_packager_phase.name
  phase.shell_script = script
end

#app_nameString

The name of the app as specified in package.json

Returns:



240
241
242
# File 'lib/react_native_util/converter.rb', line 240

def app_name
  @app_name ||= package_json['name']
end

#check_repo_status!Object

Raises:



264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/react_native_util/converter.rb', line 264

def check_repo_status!
  # If the git command is not installed, there's not much we can do.
  # Don't want to use verify_git here, which will insist on installing
  # the command. The logic of that method could change.
  return if `which git`.empty?

  unless Dir.exist? ".git"
    `git rev-parse --git-dir > /dev/null 2>&1`
    # Not a git repo
    return unless $?.success?
  end

  `git diff-index --quiet HEAD --`
  return if $?.success?

  raise ConversionError, 'Uncommitted changes in repo. Please commit or stash before continuing.'
end

#convert_to_react_pod!Object

Convert project to use React pod

Raises:

  • ConversionError on failure



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
# File 'lib/react_native_util/converter.rb', line 58

def convert_to_react_pod!
  raise ConversionError, "macOS required." unless mac?

  # Make sure no uncommitted changes
  check_repo_status!

  load_package_json!
  log 'package.json:'
  log " app name: #{app_name.inspect}"

  # 1. Detect project. TODO: Add an option to override.
  @xcodeproj_path = File.expand_path "ios/#{app_name}.xcodeproj"
  load_xcodeproj!
  log "Found Xcode project at #{xcodeproj_path}"

  if libraries_group.nil?
    log "Libraries group not found in #{xcodeproj_path}. No conversion necessary."
    exit 0
  end

  # Don't run yarn until we're sure we're proceeding,
  log 'Installing NPM dependencies with yarn'
  execute 'yarn'

  # Unused, but should be there and parseable
  load_react_podspec!

  # 2. Detect native dependencies in Libraries group.
  log 'Dependencies:'
  dependencies.each { |d| log " #{d}" }

  # Save for after Libraries removed.
  deps_to_add = dependencies

  # 3. Run react-native unlink for each one.
  dependencies.each do |dep|
    execute 'react-native', 'unlink', dep
  end

  # reload after react-native unlink
  load_xcodeproj!

  # 4a. Add Start Packager script
  validate_app_target!
  add_packager_script

  # Make a note of pod subspecs to replace Libraries group
  load_subspecs_from_libraries

  # 4b. Remove Libraries group from Xcode project.
  remove_libraries_group_from_project!

  xcodeproj.save

  # 5. Generate boilerplate Podfile.
  generate_podfile!

  # 6. Run react-native link for each dependency.
  deps_to_add.each do |dep|
    execute 'react-native', 'link', dep
  end

  # 7. pod install
  command = %w[pod install --silent]
  command << '--repo-update' if options[:repo_update]
  execute(*command, chdir: 'ios')

  # 8. SCM/git (add, commit - optional)

  # 9. Open workspace/build
  execute 'open', File.join('ios', "#{app_name}.xcworkspace")
end

#dependenciesArray<String>

A list of external dependencies from NPM requiring react-native link.

Returns:

  • (Array<String>)

    a list of NPM package names



195
196
197
198
199
200
201
202
203
# File 'lib/react_native_util/converter.rb', line 195

def dependencies
  return [] if libraries_group.nil?

  dependency_paths.map do |path|
    # Find the root above the ios/*.xcodeproj under node_modules
    root = File.expand_path '../..', path
    File.basename root
  end
end

#dependency_pathsArray<String>

Paths to Xcode projects in the Libraries group from external deps.

Returns:

  • (Array<String>)

    a list of absolute paths to Xcode projects



207
208
209
210
211
212
# File 'lib/react_native_util/converter.rb', line 207

def dependency_paths
  return [] if libraries_group.nil?

  paths = libraries_group.children.reject { |c| DEFAULT_DEPENDENCIES.include?(c.name.sub(/\.xcodeproj$/, '')) }.map(&:path)
  paths.map { |p| File.expand_path p, File.join(Dir.pwd, 'ios') }
end

#generate_podfile!Object

Generate a Podfile from a template.



257
258
259
260
261
262
# File 'lib/react_native_util/converter.rb', line 257

def generate_podfile!
  podfile_contents = ERB.new(File.read(PODFILE_TEMPLATE_PATH)).result binding
  File.open 'ios/Podfile', 'w' do |file|
    file.write podfile_contents
  end
end

#libraries_groupObject

A representation of the Libraries group (if any) from the Xcode project.

Returns:

  • the Libraries group



165
166
167
# File 'lib/react_native_util/converter.rb', line 165

def libraries_group
  xcodeproj['Libraries']
end

#library_rootsObject



214
215
216
217
218
# File 'lib/react_native_util/converter.rb', line 214

def library_roots
  libraries_group.children.map do |library|
    File.basename(library.path).sub(/\.xcodeproj$/, '')
  end
end

#load_package_json!Object

Read the contents of ./package.json into @package_json

Raises:

  • ConversionError on failure



133
134
135
136
137
138
139
# File 'lib/react_native_util/converter.rb', line 133

def load_package_json!
  @package_json = File.open('package.json') { |f| JSON.parse f.read }
rescue Errno::ENOENT
  raise ConversionError, 'Failed to load package.json. File not found. Please run from the project root.'
rescue JSON::ParserError => e
  raise ConversionError, "Failed to parse package.json: #{e.message}"
end

#load_react_podspec!Object



152
153
154
155
156
157
158
159
160
161
# File 'lib/react_native_util/converter.rb', line 152

def load_react_podspec!
  podspec_dir = 'node_modules/react-native'
  podspec_contents = File.read "#{podspec_dir}/React.podspec"
  podspec_contents.gsub!(/__dir__/, podspec_dir.inspect)

  require 'cocoapods-core'
  # rubocop: disable Security/Eval
  @react_podspec = eval(podspec_contents)
  # rubocop: enable Security/Eval
end

#load_subspecs_from_librariesObject



226
227
228
229
230
231
232
233
234
235
236
# File 'lib/react_native_util/converter.rb', line 226

def load_subspecs_from_libraries
  roots = library_roots - %w[React]
  @subspecs_from_libraries = roots.select { |r| DEFAULT_DEPENDENCIES.include?(r) }.map do |root|
    case root
    when 'RCTLinking'
      'RCTLinkingIOS'
    else
      root
    end
  end
end

#load_xcodeproj!Object

Load the project at @xcodeproj_path into @xcodeproj

Raises:

  • ConversionError on failure



143
144
145
146
147
148
149
150
# File 'lib/react_native_util/converter.rb', line 143

def load_xcodeproj!
  @xcodeproj = nil # in case of exception on reopen
  @xcodeproj = Xcodeproj::Project.open xcodeproj_path
rescue Errno::ENOENT
  raise ConversionError, "Failed to open #{xcodeproj_path}. File not found."
rescue Xcodeproj::PlainInformative => e
  raise ConversionError, "Failed to load #{xcodeproj_path}: #{e.message}"
end

#packager_phase_from_react_projectObject

Returns the original Start Packager build phase from the React.xcodeproj under node_modules. This contains the original script.

Returns:

  • the packager build phase if found

  • nil if not found or React.xcodeproj cannot be opened



325
326
327
328
329
330
331
332
333
# File 'lib/react_native_util/converter.rb', line 325

def packager_phase_from_react_project
  react_project!.targets.first.build_phases.find { |p| p.name =~ /packager/i }
rescue Errno::ENOENT
  log 'Could not open React.xcodeproj. File not found.'
  nil
rescue Xcodeproj::PlainInformative => e
  log "Could not open React.xcodeproj. #{e.message}"
  nil
end

#react_project!Xcodeproj::Project

Returns a Project object with the contents of the React.xcodeproj project from node_modules.

Returns:

  • (Xcodeproj::Project)

    a Project object with the contents of React.xcodeproj from node_modules

Raises:

  • Xcodeproj::PlainInformative in case of most failures



314
315
316
317
318
319
# File 'lib/react_native_util/converter.rb', line 314

def react_project!
  return @react_project if @react_project

  path = libraries_group.children.find { |c| c.path =~ /React.xcodeproj/ }.real_path
  @react_project = Xcodeproj::Project.open path
end

#remove_libraries_from_target(target) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
# File 'lib/react_native_util/converter.rb', line 181

def remove_libraries_from_target(target)
  log "Removing Libraries from #{target.name}"
  to_remove = target.frameworks_build_phase.files.select do |file|
    path = file.file_ref.pretty_print
    next false unless /^lib(.+)\.a$/.match?(path)

    static_libs.include?(path)
  end

  to_remove.each { |f| target.frameworks_build_phase.remove_build_file f }
end

#remove_libraries_group_from_project!Object

Remove the Libraries group from the xcodeproj in memory. Resets @libraries_group to nil as well.



171
172
173
174
175
176
177
178
179
# File 'lib/react_native_util/converter.rb', line 171

def remove_libraries_group_from_project!
  # Remove links against these static libraries
  xcodeproj.targets.reject { |t| t.name =~ /-tvOS/ }.each do |t|
    remove_libraries_from_target t
  end

  log 'Removing Libraries group'
  libraries_group.remove_from_project
end

#static_libsArray<String>

All static libraries from the Libraries group

Returns:

  • (Array<String>)

    an array of filenames



222
223
224
# File 'lib/react_native_util/converter.rb', line 222

def static_libs
  library_roots.map { |root| "lib#{root}.a" }
end

#test_targetObject



244
245
246
# File 'lib/react_native_util/converter.rb', line 244

def test_target
  xcodeproj.targets.select(&:test_target_type?).reject { |t| t.name =~ /tvOS/ }.first
end

#validate_app_target!Object

Validate an assumption about the project. TODO: Provide override option.

Raises:

  • ConversionError if an application target is not found with the same name as the project.



250
251
252
253
254
# File 'lib/react_native_util/converter.rb', line 250

def validate_app_target!
  app_target = xcodeproj.targets.find { |t| t.name = app_name }
  raise ConversionError, "Unable to find target #{app_name} in #{xcodeproj_path}." if app_target.nil?
  raise ConversionError, "Target #{app_name} is not an application target." unless app_target.product_type == 'com.apple.product-type.application'
end