iosswiftxcodeproj

Add file to native target programmatically via tuist/XcodeProj


I am using https://github.com/tuist/XcodeProj in an attempt to add a file to a specific target. Basically I'd like to do the following thing done via ruby mirror using Swift:

require 'xcodeproj'
source_root = '/path/to/xcodeproj'
project = Xcodeproj::Project.open(source_root)

group = project.main_group['TestProject']['TestGroup']
file = group.new_file('TestFile.swift')

target = project.targets.first
target.add_file_references([file])

project.save

So far, I've managed to add the actual file to project but couldn't manage to add it to a specific target:

let sourceRoot = Path("/path/to/xcodeproj")
let project = try XcodeProj(path: sourceRoot)

let target = project.pbxproj.targets(named: "some target name").first!
let group = project.pbxproj.groups.first!

let fileReference = try group.addFile(
  at: Path("TestFile.swift"),
  sourceTree: .group,
  sourceRoot: sourceRoot
)

try project.write(path: Path(sourceRoot))

My question is, how can I add a file reference fileReference added to the project into a specific target programmatically using the library I mentioned above?


Solution

  • Try something like the following (also review Target Object API for details)

    try target.sourcesBuildPhase().add(file: fileReference)