Tuesday, August 19, 2014

Writing a MacPorts Portfile (and Testing It on a Local Repository)

As a MacPorts user, it is maybe funny that fswatch is available on Homebrew and not on MacPorts. Today I put an end to this idiosyncrasy of mine and submitted my first MacPorts port file.

I was pleasantly surprised to discover that, although a deceiving initial impression, setting up my first port file was way easier than I first believed. Furthermore, the MacPorts guys have been very supportive and provided many insights that helped me improve the port file and my understanding of the MacPorts port system (beyond what is described in the nice MacPorts Guide).

The Basic Portfile

The basic Portfile for a source tarball generated by the GNU Build System, that is a package which is built and installed with the now classic:

$ ./configure
$ make
$ make install

is typically very simple, since these two operations are performed out of the box by the Configure, Build and Destroot phases of a port installation life cycle.

In this case, the basic Portfile includes:
  • The modeline (optional).
  • The Subversion ID tag: placeholder string automatically expanded by the MacPorts infrastructure.
  • The PortSystem line: required by all ports.
  • The port name and version: many other port variables (including the source tarball name) depend on these values.
  • The category line: one or more port categories.
  • The platform: darwin most of the times.
  • The maintainers.
  • The short and long description.
  • The homepage.
  • The download URLs.
  • The checksums (used to verify the integrity of the downloaded files).
  • The dependencies (optional).
  • The configure arguments (optional).
A fully working, basic port is the following:

In this example you can see how the download URL is split in two pieces: the master_sites and the distfiles (or distnames). The rationale behind this choice is the fact that a package may typically be hosted by multiple master sites (such as mirrors).

In this example, distfiles is specified. This variable contains the full distribution file name, including the suffix (the file extension). By default this value is set to ${distname}${extract.suffix}. You may as well define the distname (which defaults to ${name}-${version}) and the extract.suffix separately. These parameters, in the example above, are redundant, since they simply set the corresponding default value (and use_zip is used as a shortcut to set extract.suffix and other variables related to processing zip files).

A Portfile for a GitHub-Hosted Project

fswatch, such as many other projects nowadays, is hosted at GitHub.  Although not yet documented on the MacPorts Guide, a recently added PortGroup called github greatly simplifies  the Portfile for such projects. The only existing documentation, at the moment, is this port group source code.

Many of the aforementioned configuration variables are inferred by a much simpler GitHub configuration such as:

github.setup        emcrisostomo fswatch 1.3.9
github.tarball_from releases

This expands to:
  • name is set as the GitHub project name (fswatch in this case).
  • version is set as the GitHub version tag (1.3.9 in this case).
  • The download URL and the distribution file name is inferred from the repository configuration and the corresponding release URL. If the distribution file name is different than the default (${name}-${version}) then you still have to configure it as described in the previous section.
The resulting Portfile is the following:


Checking Your Portfile

The port utility can check whether a Portfile conforms to the MacPorts guidelines using the lint command:

$ port lint --nitpick fswatch
--->  Verifying Portfile for fswatch
--->  0 errors and 0 warnings found.

In the example above the fswatch Portfile passes verification with no errors nor warnings. Be sure to check your Portfile before submitting it to the MacPorts repository.

Testing Your Portfile With a Local Repository

You can test and store your Portfiles in a local repository before submitting them to a public repository in a private repository. Furthermore, you can take advantage of the MacPorts package management features to maintain your own local packages.

Adding a Portfile to a local repository is very simple:
  • Create the local repository directory somewhere (if it does not exist).
  • Create a subdirectory (if it does not exist) named after the primary category of the port you are adding.
  • Create a subdirectory named after the port.
  • Move the Portfile into this directory.
  • Make sure the user macports has sufficient privileges to read the repository (I usually give him ownership of the port directory).
  • Update the port repository indexes running portindex from the repository root.

If you have not done it yet, you have to configure MacPorts to use your local repository, adding a line in $MACPORTS_HOME/etc/macports/sources.conf:

file:///ports

right above any other repository so that ports in the local one take precedence over ports in the public repository.

If everything is setup correctly, you will be able to query and install ports from your local repository.

Further Readings

A basic Portfile such as what I described in this blog post is just the beginning: we only scratched the surface of what MacPorts can offer you. If you want to get further information about MacPorts and the facilities it provides (either from an user or a developer standpoint), start from the MacPorts Guide.

Public Domain Flags Archive (in Vector Image Format)

Some time ago, when I was implementing the EMCCountryPickerController component I described in some earlier posts (such as this one), I soon realised I needed high quality images of the flags of all the countries listed in the ISO 3166-1 standard. And since the EMCCountryPickerController library is GPL-licensed, I needed images whose license was compatible with it in order to distribute them together with the component.

I found decent collections of flags in the internet but at the end I decided to build my own, especially in order to overcome problems that arose from the limited resolution of many image collections.

I picked the flags from Wikimedia Commons since they're available in SVG format (a widely used vector image format). This way, if I need to, I can render a flag at any resolution.

I then assembled a GitHub repository where you can find:
  • All the flags in SVG format.
  • All the flags in PNG format scaled to a width of 256 pixels.
  • All the flags in PNG format, scaled to a width of 512 pixels.

The following is a shell script that can be used to render the flags archive at the desired widths.

The script requires librsvg to be installed.

Friday, June 20, 2014

Installing Logstash v 1.4 (and Greater) on FreeBSD

In a previous post I described how to install Logstash (v. 1.3 and previous) on FreeBSD and in this post I will describe how to install Logstash v. 1.4 and greater.

Until version 1.3 included, Logstash was distributed as a single JAR file, and when version 1.4 was released a new packaging style was introduced. As a consequence, new instructions are required to properly setup Logstash in FreeBSD and registering it as a service. Further information about the new    distribution layout can be found in the Logstash release notes.

As seen in the previous post, a Logstash FreeBSD port exists, but it is currently outdated since it bundles Logstash v. 1.2. But while this could be used as a starting point for JAR-based Logstash installations (as we have seen, the update process only required updating the Logstash JAR), this is not possible with the new Logstash distribution because the included rc script will fail to work.

Skimming through the original post is recommended because it provides general information about Logstash and FreeBSD which is required to properly plan and execute a Logstash setup.

Prerequisites

The essential prerequisites required to execute Logstash are:
The former is required because LogStash is a JRuby application while the latter, although not technically a requirement, is the recommended output for Logstash.

Installing Java

To install OpenJDK on FreeBSD you can use pkg to install a ready-to-use binary package:

# pkg install openjdk

Currently, this command will install an instance of OpenJDK v. 7 in both FreeBSD 9 and 10. If you'd rather install a different version, you can search the available packages and pick the one you prefer (command output has been filtered for brevity):

# pkg search openjdk
openjdk-7.60.19,1
openjdk6-b31_3,1
openjdk8-8.5.13_7
# pkg install openjdk8-8.5.13_7

Installing ElasticSearch

Logstash includes an embedded ElasticSearch instance you can use for standalone installations (see my previous post for an introductory view on Logstash operation modes). The required configuration to bootstrap the embedded ElasticSearch instance and to have Logstash use it as its outputs is described in the following sections.

Although simpler from the standpoint of the configuration, Logstash installations using separate ElasticSearch instances are out of the scope of this post.

Installing Logstash

Logstash installation procedure is fairly simple since it is distributed as a tarball:
  • Download Logstash from the official website.
  • Extract the tarball in the designated installation directory (my personal suggestion is to avoid /usr/local because it is used by ports and to use /opt instead).

Creating an rc.d Script

An rc.d script is required in a BSD system to register a service, define its configuration and have the rc framework manage its lifetime. The following script can be used as is or as a starting point to customise your own. If used as is, be aware that the script uses the following default values:
  • Installation directory: ${logstash14_home="/opt/logstash-1.4.1"}
  • Configuration file path: ${logstash14_config="/usr/local/etc/${name}/${name}.conf"}
  • ElasticSearch data directory: ${logstash14_elastic_datadir="/var/db/logstash14"}
  • Java home: ${logstash14_java_home="/usr/local/openjdk6"}
You can override any of the supported configuration values in the /etc/rc.conf file. If, for example, you want to use an alternate Java home path, just add the following line to /etc/rc.conf setting the desired value:

logstash14_java_home="/usr/local/openjdk7"

Testing the Service

To test the Logstash service, the following command can be used:

# service logstash14 onestart

To stop it, use:

# service logstash14 onestop

To help troubleshooting any problem you might find you can enable the Logstash log, setting the logstash14_log variable to YES in the /etc/rc.conf file:

logstash14_log="YES"

The log file location is specified by the logstash14_log_file variable, whose default value is set by the service rc file (only the relevant lines are shown):

name=logstash14
logdir="/var/log"
: ${logstash14_log_file="${logdir}/${name}.log"}

The log file location can be overridden setting the logstash14_log_file variable in the /etc/rc.conf file.

Enabling the Service

Note that the rc script described above does not enable the Logstash service:

: ${logstash14_enable="NO"}

If everything works, you can enable the Logstash service just adding the following line to /etc/rc.conf:

logstash14_enable="YES"

Wednesday, June 18, 2014

Pkg Update Fails in FreeBSD 9.2 Because of a Python Setuptools Conflict

Today I launched pkg to upgrade some binary packages installed in a FreeBSD 9.2 instance but suddenly pkg failed complaining about a locally installed python package (py27-setuptools-2.0.1) conflicting with the version required by it. The error began with the following statement, followed by a long list of repetitions of the same warning message:

WARNING: locally installed py27-setuptools-2.0.1 conflicts on /usr/local/bin/easy_install with:
- py27-setuptools27-2.0.1

All the software in this box was installed using pkg binary packages, so that at first this error sounded really strange to me.

Even though you use pkg to simplify package installations instead of compiling software from the ports collection, there is a file you should be aware of, especially if you are experiencing installation problems:

/usr/ports/UPDATING

This file contains important information about the update procedure and since binary packages are built from the port tree, the information applies even when installing with pkg.

A quick search starting from approximately the date of the last update of the affected machine pointed me in the right direction:

20140307:
  AFFECTS: users of devel/py-setuptools dependent ports
  AUTHOR: sunpoet@FreeBSD.org

  devel/py-setuptools is being used for every python ports (if USE_PYDISTUTILS
  defined) since r336553. Due to PKGORIGIN limitation, we cannot build one
  python port with python27 and the other with python33 since they require
  different setuptools versions which have same PKGORIGIN. With the addition
  of py-setuptools{27,32,33}, we could now have py27-foo and py33-bar coexist
  in one system.
  [...]

The suggested solution for pkg users is:

# pkg set -o devel/py-setuptools:devel/py-setuptoolsXX

where XX is the affected Python version. After running

# pkg set -o devel/py-setuptools:devel/py-setuptools27

pkg upgrade went fine and the problem was solved.

Monday, June 16, 2014

NSControlTextEditingDelegate Methods Are Not Called on a the Delegate of a View-Based NSTableView

I was developing a OS X Cocoa application and the time came to validate the text input by the user while editing cells of an NSTableView. My Cocoa-fu immediately suggested me to take advantage of the NSControlTextEditingDelegate protocol that specifies the following two methods to hook exactly where I need to:
  • control:textShouldBeginEditing:
  • control:textShouldEndEditing:

These two protocol methods are invoked on the delegate object. Everyday's Interface Builder outlet connection stuff, I thought, unaware I'd lose the rest of the day trying to have those method called. I then selected the text field in the editable column whose editing I wanted to be notified of:


Then I selected the Connection Inspector and connected the delegate outlet to the target object:


Finally, I implemented the two aforementioned methods on the delegate object, ran the application and... nothing happened!

The Official Documentation

I'll won't tell about the frustration I felt trying to do one of the simplest and most paradigmatic tasks in Cocoa programming: setting a delegate and implementing the corresponding protocol. Suffice it to say, I felt like I had some evident bug in front my eyes but could not notice it. Not immediately, not after a cup of tea or two, not after a hour diving into the documentation I could find.

I revised the documentation, outlets and the code over and over again, but I could not detect the problem. Then I noticed that I was not the only one struggling with this issue, although no solution was provided.

To make a long story short, the documentation I checked seemed confirmed the it should have worked, until I found especially after reading an official Apple Technical Q&A, number QA1551, titled Detecting the start and end edit sessions of a cell in NSTableView, stating the following:

A: How do I detect start and end edit sessions of a cell in NSTableView
In order to detect when a user is about to start and end an edit session of a cell in NSTableView, you need to be set as the delegate of that table and implement the following NSControl delegate methods:
- (BOOL)control:(NSControl *)control textShouldBeginEditing:(NSText *)fieldEditor;
- (BOOL)control:(NSControl *)control textShouldEndEditing:(NSText *)fieldEditor;
The table forwards the delegate message it is getting from the text view on to your delegate object using the control:textShouldEndEditing: method. This way your delegate can be informed of which control the text view field editor is acting on its behalf.

So, you should not set the editable field delegate but the table one! Fortunately, that was easy to change. I removed the connection to the delegate outlet in the text field and set the table one instead. I started the application and... nothing happened again!

At this point I felt at a loss and started to wonder whether some code in my application was interfering with the editing notification path. I created a new Cocoa application and quickly replicated the solution suggested in the Apple documentation but the result was the same: the delegate methods were not being called.

The Solution

The solution was simple, and fortunately not very different from what a Cocoa programmer expects: setting a delegate and implementing a protocol. But while the protocol was the correct one (NSControlTextEditingDelegate), the delegate was not. Better yet: they were not.

In fact, after some of tests I reached the following conclusions:
  • A cell-based NSTableView instance works as expected: setting the table delegate causes the NSControlTextEditingDelegate protocol methods to be invoked on it.
  • A view-based NSTableView instance (such as mine and almost surely most of the new NSTableView instances out there) required both the table and the field delegates to be set for the NSControlTextEditingDelegate protocol methods to be invoked.

I suspected that the aforementioned Apple Technical Q&A QA1551 document only considers the case of cell-based tables despite its date of publication: view-based tables were introduced in OS X 10.6, shipped two months before this document was issued. To dispel my doubts I decided to experiment with both kinds of table and found the behaviour described above, one for each different kind of table.

Nevertheless, and even though I dedicated a lot of time to skimming through the documentation, I was unable to find a mention of this issue in any other guide, API documentation or technical article from Apple. Even the very good Table View Programming Guide for Mac makes no mention of this "peculiarity" despite being a fairly common use case.

I hope this post helps anybody falling into the same trap to quickly solve his issues with getting NSControlTextEditingDelegate notifications to his table delegate.