Quantcast
Channel: taichino.com » programming
Viewing all articles
Browse latest Browse all 6

Xcodeプロジェクト内の使われてないリソースを探す

$
0
0

iOS7以降、主なアプリはほぼフラットなスタイルに移行していますね。iHeartRadioでもフラット+iOS7対応は一旦完了しているものの、まだ試行錯誤の途中でバージョンアップ毎に結構デザインを変更しています。

そこで問題になるのがリソースの管理です。プロジェクトの体制にもよると思いますが、一般に新しいファイルの追加は簡単でも、古いファイルを削除するのは本当に使われてないか確認するコストが高くて面倒です。そうして気がついたらプロジェクトの中が古い画像ファイルだらけになっていて、これは良くないなというので使われてない(かもしれない)画像ファイルを列挙するスクリプトを書きました。

RubyにはXcodeprojというXcodeのプロジェクトファイルを色々弄れる便利なRubyGemがあります。Cocoa Podsでも使われているモジュールで、最初はPythonにポートして使おうと思っていたのですが、結構規模がデカいので諦めてRubyを覚える事にしました。最近Rubyを学習しはじめた直接的な要員はこのモジュールです。でこのモジュール使ってプロジェクト内のファイルからリソース名でひたすら全文検索をかけるという、原始的なやつです。

def search_unused_images
  sources = ""
  for file in @target.source_build_phase.files_references
    sources += File.read file.real_path
  end
  for file in @proj.files
    if file.path.end_with? ".h"
      sources += File.read file.real_path
    end
  end
  for file in @target.resources_build_phase.files_references
    type = file.last_known_file_type
    next unless type
    if type == 'file.xib' or type == 'text.plist.xml'
      sources += File.read file.real_path
    end
  end

  images = []
  for file in @target.resources_build_phase.files_references
    type = file.last_known_file_type
    if not type or not type.match /^image/
      next
    end

    name = File.basename(file.display_name, '.*')
    name = name.split('@').first.strip

    if name == 'Default' or name == 'Default-568h'
      next
    end

    if sources.scan(name).count == 0
      images << file
    end
  end

  images.sort {|x,y| x.display_name <=> y.display_name}
end

先日書いたxcodeproj_utilsに追加したので、下記のようにして使います。まぁUIImage::imageNamedとかでファイル名をコードで組み立ててると、誤って検出されるので確実なリストではないんですけど、僕らの場合は割と上手くいきました。あと–htmlオプションで使われてない画像一覧をHTMLに吐き出せます。

$ gem install xcodeproj_utils # インストール
$ xcp_utils unused_images <path/to/xcodeproj> <target> # 一覧取得
$ xcp_utils unused_images --html <path/to/xcodeproj> <target> > /tmp/list.html # HTML出力

一覧は正確には使われていない画像ファイルの一覧ではなく、あくまでソースコード内に名前が出てこない画像なので、削除の際は一点一点やはり目で確認してください。

やっつけの割には結構便利な気がするんですけど、どうでしょうか。


Viewing all articles
Browse latest Browse all 6

Trending Articles