Enhance Xcode snippets using Git

In a previous post we described how to combine xcresource and Xcode templates to create a distributed sample code database available right inside Xcode.

This time, we will see how to use xcresource to share and back Xcode codesnippets up!

Backing codesnippets up in a git repository

Xcode snippets are reusable blocks of code available in Xcode. You can browse them and create your own snippets in the Xcode snippets library.

Anytime you create a codesnippet, Xcode stores it in a local folder (~/Library/Developer/Xcode/UserData/CodeSnippets). You can use xcresource snippet open to browse them.

xcresourcecodesnippets storage directory
Xcode snippets directory

Thanks to xcresource, you can move your snippets to a git repository to back them up and install them again later locally. It is considered as a good pratice to rename them with explicit names.

Consider deleting your local snippets once copied, before installation, to avoid duplications:

> xcresource snippet remove
> xcresource snippet install --url url_to_git_repo --pointer branch_name

Installing snippets from different sources

When installing snippets, you can specify a namespace parameter:

> xcresource snippet install --url url_to_git_repo --pointer branch_name --namespace my_namespace

A namespace acts as an installation folder. The snippets will be installed inside it. If the namespace already exists, it is replaced. Thus, you can use namespace to install snippets from different sources:

> xcresource snippet install --url url_to_my_personal_git_repo --namespace personal_snippets

> xcresource snippet install --url url_to_my_company_git_repo --namespace company_snippets

> xcresource snippet list
# personal_snippets
- personal snippet 1
- personal snippet 2
# company_snippets
- company snippet 1
- company snippet 2

A word on the snippet namespace implementation

When installing snippets, xcresource stores the namespace you specified in the summary of your snippets:

The snippet namespace is stored in its summary
The snippet namespace is stored in its summary

Be careful to not override it when editing your snippets using Xcode.

What’s next?

Try to create your own Xcode snippets repository and display them in Xcode of course!

Discover how you can use xcresource to enhance your Xcode templates ;)