Giter VIP home page Giter VIP logo

xcres's Introduction

xcres

Twitter: @mrackwitz Gem Build Status Code Climate Inline Docs

xcres searches your Xcode project for resources and generates an index as struct constants. So you will never have to reference a resource, without knowing already at compile time if it exists or not.

It includes loose images, .bundles, asset catalogs (.xcasset) and even .strings in the index.

It gives you code autocompletion for resources and localized string keys, without the need of an Xcode plugin.

Especially if your app is a bit more complex, this will greatly improve your workflow. It ensures a better quality and gives you more safety. You will see directly when a resource is missing, when you renamed it, or you moved it around.

Furthermore it won't even bother you for trivial name changes like change capitalization or converting name scheme from train-case or snake_case to camelCase and vice versa.

It will warn you in Xcode on build, if certain resources or string keys can't be referenced, because their name contain invalid chars, duplicates in the camelCase variant with another key, or would be equal to a protected compiler keyword.

The generated index could look like below.

xcres can generate code both as Swift or Objective-C. If you are using both in your project choose Objective-C and add an import to the generated header to your project's bridging header.

Swift

public class R {
    public enum Images: String {
        /// doge.jpeg
        case doge = "doge.jpeg"
    }
    public enum ImagesAssets: String {
        /// AppIcon
        case app = "AppIcon"
        /// LaunchImage
        case launch = "LaunchImage"
        /// DefaultAvatar
        case defaultAvatar = "DefaultAvatar"
    }
    public enum Strings: String {
        /// Title shown if a wrong password was entered.
        case errorTitleWrongPassword = "error_title_wrong_password"
        /// Message shown if a wrong password was entered.
        case errorMessageWrongPassword = "error_message_wrong_password"
    }
}

Objective-C

FOUNDATION_EXTERN const struct R {
    struct Images {
        /// doge.jpeg
        __unsafe_unretained NSString *doge;
    } Images;
    struct ImagesAssets {
        /// AppIcon
        __unsafe_unretained NSString *app;
        /// LaunchImage
        __unsafe_unretained NSString *launch;
        /// DefaultAvatar
        __unsafe_unretained NSString *defaultAvatar;
    } ImagesAssets;
    struct Strings {
        /// Password wrong!
        __unsafe_unretained NSString *errorTitleWrongPassword;
        /// Please enter the correct password.
        __unsafe_unretained NSString *errorMessageWrongPassword;
    } Strings;
} R;

Installation

xcres is built with Ruby and it will be installable with the default Ruby available on OS X. You can use a Ruby Version manager, if you know what you're doing. Using the default Ruby install will require you to use sudo when installing gems. (This is only an issue for the duration of the gem installation, though.)

Install the gem on your machine:

$ [sudo] gem install xcres

Use the automatic integration to add a build phase to your project, by executing the following command:

Swift

$ xcres install --swift

Objective-C

$ xcres install

Usage

Reference your resources safely with the generated constants.

Asset Catalogs

Assuming your asset catalog is named Images.xcassets.
xcres supports multiple bundles in one project.

Instead of:

[UIImage imageNamed:@"PersonDefaultAvatar"]

Just write:

[UIImage imageNamed:R.ImagesAssets.personDefaultAvatar]
How to Add a New Resource
  1. Add it to your asset catalog.
  • Trigger a build. (⌘ + B)
  • The new key will be available under R.${catalogName}Assets.${keyName:camelCase} and is ready for use in your code now.

Loose Images

Instead of:

[UIImage imageNamed:@"table_header_background_image"]

Just write:

[UIImage imageNamed:R.Images.tableHeaderBackgroundImage]
How to Add a New Loose Image
  1. Drop the image in your project.
  • Trigger a build. (⌘ + B)
  • The new key will be available under R.Images.${keyName:camelCase} and is ready for use in your code now.

Strings

Instead of:

NSLocalizedString(@"error_message_wrong_password", @"Message shown if a wrong password was entered.")

Just write:

Swift

R.Strings.errorMessageWrongPassword.localizedValue

Objective-C

NSLocalizedString(R.Strings.errorMessageWrongPassword, @"Message shown if a wrong password was entered.")
How to Add a New String

With xcres your workflow for adding new strings will change slightly.

  1. Create a new string (at least) in your project's native development language in one of the strings files included in your target. (By default this will be en.lproj/Localizable.strings)
  • Trigger a build. (⌘ + B)
  • The new key will be available under R.Strings.${keyName:camelCase} and is ready for use in your code now.

Known Issues & Tips

One minor drawback is that genstrings will not be helpful anymore. But this tool is mostly useful in the first step, when bootstrapping your project, until you care about internationalization and want to provide translations.

xcres generally assumes that you don't use natural language for keys, as this will led very fast to ambiguities. It will filter out unwanted chars when transforming your keys to camel case notation, but it will also warn you about those. It can be a help, if you want to migrate your project to non-natural language keys.

Credits

The logo was designed by @kuchengnom. Swift support was implemented by @timbodeit.

License

xcres is available under MIT License. See the LICENSE file for more info.

xcres's People

Contributors

dukeflyheli avatar lagubull avatar loddan avatar mrackwitz avatar pietbrauer avatar simonseyer avatar timbodeit avatar tonyxiao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

xcres's Issues

Define output directory

When using the "xcres install" command the generated files are put into a Resources folder.
When using the "xcres build" command the generated files are put into a root folder of the project.

Strings with punctuation

Hello!

I've just started using your tool, It really cleans up my code, thanks for that.

I'm facing an issue with punctuation. I'm using strings with and without punctuation, for example :

"Password" = "Mot de passe";
"Password:" = "Mot de passe :";

In my Strings resources, I only get the last one. Is there a way to get the two?

Analyze Storyboards / XIBs

Find the following info:

  • Storyboard identifiers
  • identifier of segues
  • reuseIdentifier of table view and collection view cells
  • restorationIdentifier of views

Question (not issue)

Hi

I found this little gem by Cocoacontrols and have, so far, found it great, cool job man!
But a little question about the unsafe_unretained strings in a struct... if you declare them this way, shouldn't R.m be specified as -fno_objc_arc? After all we can't use ARC in structs, but I don'^t really know about the lifetime of an object that is declared statically and unsafe_unretained. IN the old memory model it would be autoreleased (which would be, well, soon), but within ARC.. or what do you think?

Gem conflict with Cocoapods

Hey... Unsure if this is the right place for this (forgive me Marius if that's the case) but I'm getting this gem conflict with Active Support and Xcodeproj... wondering if anyone else solved it?

Bundler could not find compatible versions for gem "activesupport":
  In Gemfile:
    cocoapods (= 1.0.0) was resolved to 1.0.0, which depends on
      activesupport (>= 4.0.2)

    cocoapods (= 1.0.0) was resolved to 1.0.0, which depends on
      activesupport (>= 4.0.2)

    cocoapods (= 1.0.0) was resolved to 1.0.0, which depends on
      xcodeproj (< 2.0, >= 1.0.0) was resolved to 1.0.0, which depends on
        activesupport (>= 3)

    cocoapods (= 1.0.0) was resolved to 1.0.0, which depends on
      xcodeproj (< 2.0, >= 1.0.0) was resolved to 1.0.0, which depends on
        activesupport (>= 3)

    xcres (= 0.6.0) was resolved to 0.6.0, which depends on
      activesupport (< 4, >= 3.2.15)

Compile error when generated string begins with number

I'm using ibtool to generate .strings files which are extracted from my .xib/.storyboard file. Now ibtool will create strings like this:

"8ie-xW-0ye.text" = "Hello World";

Then the issue with xcres is that it creates the below variable with the same name which starts with the number 8, which in turn is not a valid variable or constant name – which causes a compile error.

struct Strings {
__unsafe_unretained NSString *8ieXW0yetext;

Error running --swift

First of all let me say that this is a great tool.

I created a new Swift project to test the tool:
I also added 2 images to Assets.xcassets

$ cd [project folder]
$ rvm use system
$ sudo gem install xcres
$ xcres install --swift --verbose

Ⓥ Verbose mode is enabled.
⚠ Argument XCODEPROJ is not set. Using the current directory.
✓ Use ./xcres_test_swift.xcodeproj as XCODEPROJ.
Ⓥ Found target group, will use its path as base output path.
⚠ Didn't find support files group
Execute build first:
Ⓥ Verbose mode is enabled.
✓ Use xcres_test_swift.xcodeproj as XCODEPROJ.
Ⓥ Found #0 resource bundles in project.
Ⓥ Found #0 image files in project.
Ⓥ Found #1 asset catalogs in project.
Ⓥ Found asset catalog Assets.xcassets with #4 image files.
Ⓥ Add section for AssetsAssets with 4 elements
Ⓥ Strings files in project: []
Ⓥ Native development languages: ["en"]
Ⓥ Used languages for .strings files: []
Ⓥ Preferred languages: []
Ⓥ Strings files after language selection: []
Ⓥ Non-ignored .strings files: []
⚠ Skip invalid key: '.'. (Was transformed to empty text)
✓ Directory did not exist. Will be created.
✓ Successfully updated: /Users/Gabriel/Desktop/xcres_test_swift/xcres_test_swift/Resources/R.swift
✓ Successfully integrated into xcres_test_swift.xcodeproj

I've got now an R.swift file into the project. Great!

The problem is the content of the file:

// generated by xcres
//
// DO NOT EDIT. This file is machine-generated and constantly overwritten.
// See https://github.com/mrackwitz/xcres for more info.
//

public class R {
    public enum AssetsAssets: String {
        /// AppIcon
        case app = "AppIcon"
        /// earth
        case earth = "earth"
        /// sun
        case sun = "sun"
    }
}

public extension R.Strings {
    public var localizedValue: String {
        return NSLocalizedString(self.rawValue,
                                 bundle: NSBundle(forClass: R.self),
                                 comment: "")
    }
}

Xcode is complaining:
'Strings' is not a member type of 'R'

So this line is wrong:

public extension R.Strings {

changing it to this, stops complaining:

public extension AssetsAssets {

I think then the file needs to import UIKit.

Erroneous variable names

When using xcres in a project, it generates a file with some erroneous variable names

Example:

extern const struct R {
struct Images {
/// Icon-100.png
__unsafe_unretained NSString *100;

Install issues

I've installed xcres $ [sudo] gem install xcres

then I ran $ xcres install – but no build phase was added to my project...?
So I tried to add a build phase my self to run the script xcres -v build – and hit cmd+b, but then Xcode complains that the command xcres could not be found ?

Chinese characters in assets folder has been skipped

✓ Use ./zsh.xcodeproj as XCODEPROJ.
Execute build first:
✓ Use zsh.xcodeproj as XCODEPROJ.
⚠ Skip invalid key: '会员等级'. (Was transformed to empty text)
⚠ Skip invalid key: '便利店'. (Was transformed to empty text)
⚠ Skip invalid key: '关于'. (Was transformed to empty text)
⚠ Skip invalid key: '出差模式'. (Was transformed to empty text)
⚠ Skip invalid key: '占位图'. (Was transformed to empty text)
⚠ Skip invalid key: '回收记录'. (Was transformed to empty text)
⚠ Skip invalid key: '导航'. (Was transformed to empty text)
⚠ Skip invalid key: '小区雾霾指数'. (Was transformed to empty text)
⚠ Skip invalid key: '我'. (Was transformed to empty text)
⚠ Skip invalid key: '新手引导'. (Was transformed to empty text)
⚠ Skip invalid key: '注册'. (Was transformed to empty text)
⚠ Skip invalid key: '消息'. (Was transformed to empty text)
⚠ Skip invalid key: '等待'. (Was transformed to empty text)
⚠ Skip invalid key: '账户余额'. (Was transformed to empty text)
⚠ Skip invalid key: '首页'. (Was transformed to empty text)
✓ Directory did not exist. Will been created.

crash on no pch file

I have a vanilla swift project. The script crashes because it is expecting a GCC_PREFIX_HEADER key in settings which does not exist for swift projects. Work around is to set it to something bogus. Fix is to check the key exists before passing to pathname function.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.