3

I'm attempting to write a Ruby script that will delete certain files from the Xcode project. I can find the files based on the absolute path and remove them from the project using the remove_from_project method of PBXFileReference. However this leaves source files (e.g. .m or .swift files) in the "Compile Sources" build phase of whatever target(s) it is a member of, but without a name.

enter image description here

I know I need to also remove the file from the target(s) but there seems to be no easy link between a PBXFileReference and a target (PBXNativeTarget).

From what I can make out I need to iterate through each of the project's targets, then iterate through the files or files_references of that target's source_build_phase looking for the PBXFileReference I already have.

Is this correct or am I missing some obvious link such e.g. file_ref.target_memberships?

Steve Wilford
  • 8,894
  • 5
  • 42
  • 66
  • did you ever figure this out? – lemon lime pomelo Dec 18 '15 at 02:04
  • @lemonlimepomelo unfortunately not, I ended up working around it by iterating over each target's files and looking for a match. Dirty but it works. https://github.com/NxSoftware/stronglyboards/blob/master/lib/stronglyboards.rb#L105 – Steve Wilford Dec 18 '15 at 07:15

2 Answers2

0
if (object.is_a?(Xcodeproj::Project::Object::PBXFileReference))
    if (!object.real_path.exist?)
        object.remove_from_project
    end
end

project.save(project_path)
Nikita
  • 1,811
  • 1
  • 20
  • 41
  • 3
    Code only answers become tremendously more useful if you add an explanation about how your code answers the question. – K Erlandsson Jan 07 '17 at 18:53
0

Not sure when this was introduced, but as of xcodeproj version 1.15.0, you can can get the build files associated with a file reference with:

file_ref.build_files

From the documentation:

Method: Xcodeproj::Project::Object::PBXFileReference#build_files

#build_files ⇒ Array<PBXBuildFile>

Returns the build files associated with the current file reference.

Returns: (Array<PBXBuildFile>) — the build files associated with the current file reference.

Seems like this should do the trick:

file_ref.build_files.each { |file| file.remove_from_project }
Clay Bridges
  • 11,602
  • 10
  • 68
  • 118