Archive for category cocoa

Sharpening the code coverage saw

Here’s a quick followup to my Hudson – Cocoa – Coverage Reporting blog post from the other day.

I didn’t show the summary output that Cobertura displays in Hudson.  It looked like this:

Coverage before cleanup

You’ll note (or I will do so for you) that there’s a variety of packages here (in the cocoa case, these are just subdirectories of the current workspace).

Notwithstanding the anemic percentages of coverage overall, outside of the <default> and CDGenerated packages, these are all third party components.  While I’m extremely interested in knowing that they work correctly, it’s not on my radar to build out test coverage for each of these. 

What I want is accurate reporting for the code that I write.

When we setup the gcovr build step in Hudson, the command looked like this:

/usr/local/bin/gcovr -r . -x -b -e /Developer  1> html/coverage.xml 2>/dev/null

The -e /Developer command line argument instructs gcovr to exclude any files with names that match /Developer.  The final config that I’m now working with is:

/usr/local/bin/gcovr -r . -x -b -e /Developer -e ‘.*/UKKQueue/’ -e ‘.*/DebugUtils/’ -e ‘.*/Foundation/’ -e ‘.*/UnitTesting/*’ -e ‘.*/Third Party Sources/’ -e ‘.*/ShortcutRecorder.framework/’ 1> html/coverage.xml 2>/dev/null

Which is obtuse at best, but works.  The ‘.*/xxx/’ is necessary because the fully qualified path is processed by gcovr.  In my case it would be /Users/jschilli/.hudson/jobs/Tickets-MASTER/workspace/…

The results now look like this:

coverage chart after tweaks

The absolute measure of coverage for each of the two remaining packages has not changed, but the information is now focused on the data that is most important to me.

With all of that said, the exclusions you choose to add are project specific.  Hopefully this will help you hone the reporting to your liking.

No Comments

That feels better – Cocoa, Hudson and running green

 

Continuous Integration

Continuous Integration (CI) has been around for a while now. Popularized in the java/ruby/[*lang*] communities, CI, when properly implemented promotes good code practices.  CI alone won’t guarantee great code, but it helps support good behavior and in fact rewards users routinely and reliably.

 

I’ve used Continuous Integration in many former lives – CI was essential on large geographically distributed teams – driving out incompatibilities in interface and implementation early and often.

My definition of a successful CI system and implementation are:

  1. Automated and unattended application build
  2. Automated and unattended test execution

Everything beyond that is gravy (or sugar).

CI & the indie

When I released my first iPhone app, I was building the project in Xcode, switching to Finder and/or Terminal.app, compressing, copying and generally screwing up at every possible step.  Although I’ve seen the benefits of automation multiple times, I was so busy getting this app out that I couldn’t see how I could take the time to write scripts.  That airlock of paradox didn’t last long.  I wrote a few scripts and every aspect of my build/sign/archive workflow was automated – when I ran the script.

 

I repeated this exercise for my first Mac product – this time a hodge-podge of scripts to build the app, generate the help files, generate the sparkle appcast, release notes, upload, etc.  I still use this script and it works great – when I run the script.

Although I’ve had great success with CI in the past, I wasn’t convinced that my one workunit indie shop could or would benefit from implementing CI.  There were a few things that helped turn me around on this:

  1. The weakness of my script based build system continues to be the user centered part – me running the scripts.  As I bounce from machine to machine, branch to branch, tucking frameworks away on one machine and not replicating them to another, [insert favorite 'in the heat of the battle' screwup here], issues might not emerge for some time.
  2. Increased desire to capture metrics and data about my personal development process.  I’m not implementing heavy weight metrics, but I understand absolutely that data can empower me to make decisions – test data, build data, coverage data.
  3. Renewed belief that removing rote non value-adding activities from my routine will increase my effectiveness and throughput

Rule #1 of CI – Automated and Unattended Build

When something changes, your CI should build the system to ensure that nothing has broken.  If you’re in the zone and a failure pops up – easy to fix.  If you find an issue weeks later – well we’ve all been there.

 

CI is all about automating those rote tasks.  It is important to emphasize both the automated aspects as well as the unattended aspects of CI.  The only thing worse than no CI is CI that is broken and neglected.  We’ll come back to this point in a bit.

Hudson CI & Cocoa

There are several compelling CI solutions in the market - CruiseControlHudson and scores of others in the opensource space.  There are a spectrum of commercially available solutions as well including Bamboo.  To my knowledge, there are no CI solutions that focus on the Cocoa space [just found BuildFactory - haven't checked it out].  The good news is that most of these systems can run external processes – the by-product is good news for cocoa devs.

 

Hudson seems to be the leading choice – it’s really straight forward to get the basics working.  From there, incremental tweaks should get you up and running.

Preparing for the move

I screwed up more than a few times getting my apps to build in Hudson.  There are more than a few pages on the web that illustrate Cocoa/Hudson builds.

 

My suggestion is to ensure that you can take a fresh cut of your project from your SCM system, check it out to a new directory and build it clean.

I would encourage you to do this outside of your normal dev tree – it’s surprising how easily a relative path will find its way into your xcode build settings.

  1. cd /tmp
  2. checkout project to foobaz
  3. build
  4. if errors, rm -rf /tmp/foobaz, fix errors in main tree, checkin, goto #1

This process should rid you of (many of) those hidden dependencies that will prevent a clean build once you’re executing inside of Hudson.

 

Once you have a clean repeatable build – from your scm system – you should move on to getting hudson up and running.

Setting up Hudson

Installing Hudson is well documented on the net.  The Hudson site includes installation instructions that work well.  There are several examples of cocoa specific sites – I started here.

 

Because I have multiple targets setup in my Xcode project, I selected ‘This build is parameterized’ and added some targets to choose from.  Hudson will remember your last choice.

Parameterized Build Settings

Setting up SCM

If you use Git, Christian Hedin’s article covers that configuration as well.  The critical thing is to use either SCM polling or a post-commit-hook to invoke the build.  Hudson will allow you to setup a time based build e.g. build every thirty minutes.  The issue with that is that it will execute the build whether there are changes or not.  Polling or post-commit-hooks will ensure that builds are invoked when change occurs.

 

scm-config.png

You will note that I’ve elected to only build my master branch – by default, Hudson will checkout and build each branch that it finds in your Git repo.  While I see this as advantageous (forward dev on master, branches for production release and bug fix), my branches haven’t gotten the Hudson CI/gcov/unit testing love that master has.

SCM Polling

Setting up your project

In the interest of walking before I run, I want my Hudson build to checkout my updated code, compile my code, execute unit tests and capture any reporting output for test coverage and unit test failures.  It turns out that most of this is already performed when I build my UnitTests target in my Xcode projects.

 

Build Step

Click on build now – you can check the console to see the steps that Hudson is taking.

If the stars are aligned, you should have a successful build.  If not, you’ll need to crawl through the console logs to determine where the failure occurred.

It is critical that you go back to your Xcode project/standalone build directory and correct mistakes there.  Check in your changes and repeat.  No one has to know how many times you repeat this cycle, but it’s critical to meet the spirit and law of Rule #1!

Sugar

Once the basic build is working you should add unit test reporting.  If you have or are planning to run unit tests (Rule #2), download this ruby script, install it in /usr/local/bin or the directory of your choice and change your build step to look like this:

 

Safari.png

In the Post-build actions, configure Hudson to publish your test results.

Safari.png

Trigger a build and you’ll now see a chart with the build results.  As your test suite grows, you should see a trending graph with increased numbers of tests.

Code Coverage

Unit tests execution is what we’re after for Rule #2, but the number of tests as a key metric is easily misleading.  I’ve seen a lot of cases where the same code is tested over and over again.  Coverage is the key indicator!

 

Download and install gcovr and install it again in /usr/local/bin

Add the following as a new build step (after the xcodebuild step)

gcovr converts gcov data into a format parseable by Cobertura – a coverage analysis tool.

(See Tommy McLeod’s blog post here for some additional details)

Safari.png

Cobertura Configuration

Assuming you have gcov correctly working for your project (the subject of an as yet unwritten post), executing the build will result in some nice graphs.

You can now navigate through the coverage reports and see your annotated source code including what’s covered – and more importantly, what’s not.  (There’s a one-line patch to gcovr detailed here that allows Cobertura/Hudson to navigate into your code)

Safari.png

[Edit 3/2/2010 - new example showing a real miss]

This example illustrates the value of visualizing test coverage – I had ~15 valid operations on a model class – I wrote this code from the spec – I erroneously interpreted running green on my unit tests meant all good.  In fact, I had missed several cases – clearly identified here.

 

Safari.png

 

Finally

Make some changes in your project, commit them to your SCM system and monitor the build.  Make a test fail, introduce a compiler error and monitor the results.

 

You want to be able to rely on your CI system to accurately report failures.  If you have instability in the process, now is the time to grind through the issues.

You can install the Jabber notification plugin in Hudson, configure your jabber address (or that of a group chat if you’re working with multiple people) and Hudson will now inform you of build successes and failures.  You can also configure email.

The compelling aspect of the Jabber plugin is that Hudson has a jabber bot that you can use to get status, trigger builds and more.

Jabber Configuration

What’s left?  There are a lot of different directions you can take Hudson now that the basics are in hand.  I want to spend some more cycles getting better diagnostics when the build fails.  Unit test failures are clearly reported.  Compilation failures (forget to commit that new file to the build?) require spelunking through the console log.  I also plan on moving my production builds to Hudson, but for now, getting that jabber notification that the build is clean is totally worth the time I’ve invested in setting this up.

1 Comment

Logitech – I want my day back

Yesterday sucked from a productivity perspective.  I’m deep into the development on Tickets 2.0 and spending a lot of time generating new versions of my Core Data based data model.  This is a (normally) straight-forward exercise in Xcode – Design>Data Model>Add Model Version.  The rub here is that this works fine on my Mac Book Pro, but failed without error on my Mac Pro.  Yesterday, I’d had enough with git commit && git push -> switch to MBPro, make data model changes -> git commit && git push -> back to Mac Pro - 

I spent several hours trying to isolate the differences between the two setups – same project, different rev of Xcode.  I down leveled my Xcode install on the Mac Pro, same result – now things are weird.

I moved /Developer to /Developer.old – clean install.  No Love!

What I observed on the failing machine was that the versioned data model was being created in the .xcdatamodeld directory, but was not being added to the Xcode project.pbxproj file.  Very Frustrating.

I grabbed Activity Monitor to watch the open files for Xcode to see if I could determine what was going on.

I noticed that DefaultFolderX (DFX) had a scripting addition loaded into my Xcode process.  I disabled DefaultFolderX and voilà I was able to add my versioned data model file.

Were it that this is the end of the story.  I sent a note off to Jon Gotow at St. Clair Software with my observations.  Jon quickly replied and asked if I was by chance using a Logitech mouse.  I am.  He further suggested that I look to see if /Library/ScriptingAdditions/LCC Scroll Enhancer Loader.osax was being loaded.

I reenabled DFX and saw that indeed LCC Scroll enhancer was loaded, with errors.  I did a quick sudo rm /Library/ScriptingAdditions/LCC Scroll Enhancer Loader.osax, restarted Xcode and everything is working well again.

Many thanks to Jon for his quick and professional response.  Logitech – my bill has been remitted.

 

No Comments

Application Development Post Mortem

Were it that this was a post mortem for the recently released Tickets.app :-)

Rather, its a note that I need to do so.

Daniel Kennett of kennetnet software has put together a few nice post mortems, most recently this one detailing the development of an iPhone companion app.

Whether you put together a presentation, a video or simply scratch some notes in your moleskine, the act of analyzing your performance on a product development or contract development effort is a good one.

I keep a page in VoodooPad for each development release and capture notes about what I could do better or differently the next time around.

iPhone Companion Apps: New Project to App Store in Two Months | Daniel Kennett: “”

No Comments

Unraveling the mysteries of NSSplitView – part 2

In part 1 of the series, we covered the very basics of NSSplitView. We ended with a NSSplitView with two subviews. We were able to constrain the minimum size of each.

In this part of the series, we are going to add collapsible subviews.

Collapsible subviews

There are several ways to support collapsible subviews. The first is supported directly by NSSplitView. As the user drags a divider to its minimum position, if subviews are collapsible, additional movement will result in the subview snapping shut.

We can support this behavior by adding the canCollapseSubview method.

1
2
3
4
5
6
- (BOOL)splitView:(NSSplitView *)splitView canCollapseSubview:(NSView *)subview;
{
    NSView* rightView = [[splitView subviews] objectAtIndex:1];
    NSLog(@"%@:%s returning %@",[self class], _cmd, ([subview isEqual:rightView])?@"YES":@"NO");
    return ([subview isEqual:rightView]);
}

Dragging the divider to the right most edge of the window will result in the right subview snapping shut. The divider will still be show on the rightmost margin of the view. This collapsing behavior is our first bit of good news. When we collapse and uncollapse our right subviews, the layout is not munged as it was in part one when we effectively reduced the right subview width to zero. We’ll use the observation later when we add programmatic collapsing.

NSSplitView-Part1a.png
NSSplitView-Part1a.png
We can hide the divider when the right subview is collapsed.

1
2
3
4
5
- (BOOL)splitView:(NSSplitView *)splitView shouldHideDividerAtIndex:(NSInteger)dividerIndex;
{
    NSLog(@"%@:%s returning YES",[self class], _cmd);
    return YES;
}

NSSplitView-Part1a.png

If you keep you’re finger on the mouse while moving the divider, you can observe it collapse the right subview and then moving the divider back to the left – uncollapse it.

If you didn’t keep your finger on the mouse, the right view collapsed and there is no way now to get the view back. Hovering over the right edge of the window won’t do it. There aren’t any buttons to press, nothing to double click.

Before we fix this issue, change shouldHideDividerAtIndex back to returning NO.

We’ll add one more bit of goodness before we tackle programming collapsing.

Double Click to collapse

NSSplitViewDelegate includes an optional method shouldCollapseSubview:forDoubleClickOnDividerAtIndex: – it does its name suggests. If we answer YES, double-clicking on the divider will collapse the right subview. Double-clicking on the divider while the right subview is collapsed will uncollapse the right subview.

Here’s the implementation:

1
2
3
4
5
6
- (BOOL)splitView:(NSSplitView *)splitView shouldCollapseSubview:(NSView *)subview forDoubleClickOnDividerAtIndex:(NSInteger)dividerIndex;
{
    NSView* rightView = [[splitView subviews] objectAtIndex:1];
    NSLog(@"%@:%s returning %@",[self class], _cmd, ([subview isEqual:rightView])?@"YES":@"NO");
    return ([subview isEqual:rightView]);
}

Sweet!

Programmatic Double Click

Programmatic double-click will allow us to hook the action selector of a menu item, a toolbar button or other UI control to a method that will toggle the collapsed state of the collapsible subview.

First we’ll add a toolbar to our window to have a convenient place to put the toggle button.
Interface Builder.png

In MySplitViewController, we’ll add the logic to toggle right subview.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
-(IBAction)toggleRightView:(id)sender;
{
	BOOL rightViewCollapsed = [[self mySplitView] isSubviewCollapsed:[[[self mySplitView] subviews] objectAtIndex: 1]];
    NSLog(@"%@:%s toggleInspector isCollapsed: %@",[self class], _cmd, rightViewCollapsed?@"YES":@"NO");
	if (rightViewCollapsed) {
		[self uncollapseRightView];
	} else {
		[self collapseRightView];
	}
}
 
-(void)collapseRightView
{
 
	NSView *right = [[[self mySplitView] subviews] objectAtIndex:1];
	NSView *left  = [[[self mySplitView] subviews] objectAtIndex:0];
    NSRect leftFrame = [left frame];
    NSRect overallFrame = [[self mySplitView] frame]; //???
    [right setHidden:YES];
    [left setFrameSize:NSMakeSize(overallFrame.size.width,leftFrame.size.height)];
	[[self mySplitView] display];
}

toggleRightView: is the public method that we’ll connect UI elements to. It queries the NSSplitView to see if the right subview is collapsed. If not, it calls collapseRightView otherwise, we’ll uncollapseRightView:. The key element here is to ensure that the ‘collapsed’ status of the right view is set correctly. My first several attempts to make this work involved setting the frame width of the right view to 0. NSSplitView did not answer YES to isSubviewCollapsed: under those circumstances. Remember the observation earlier that when we snapped the right view closed and reopened it the view had not been mangled by autoresize logic? That suggests that the view was never shrunk to zero width, but rather hidden. I confirmed this with a F-Script session.

uncollapseRightView: is equally straight forward –

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
-(void)uncollapseRightView
{
	NSView *left  = [[[self mySplitView] subviews] objectAtIndex:0];
	NSView *right = [[[self mySplitView] subviews] objectAtIndex:1];
    [right setHidden:NO];
 
	CGFloat dividerThickness = [[self mySplitView] dividerThickness];
 
    // get the different frames
	NSRect leftFrame = [left frame];
	NSRect rightFrame = [right frame];
    // Adjust left frame size
	leftFrame.size.width = (leftFrame.size.width-rightFrame.size.width-dividerThickness);
	rightFrame.origin.x = leftFrame.size.width + dividerThickness;
	[left setFrameSize:leftFrame.size];
	[right setFrame:rightFrame];
	[[self mySplitView] display];
}

The cool thing about all of this is that we’re not saving frame rects or adding additional data structures to hold this state. I can assure you that my first several attempts to understand NSSplitView had loads of code to deal with view frames, collapse states, notifications to enable/disable view resizing etc. It is true, at least in this case, that if you’re fighting the frameworks, there may be a more enlightened path awaiting discovery.

We can now go back and hide the divider when the right subview is collapsed. The app should now look like this.

NSSplitView-Part2.png

Conclusion and Next Steps

We’ve accomplished quite a bit. I know, it’s hard coded to collapse only the right subview and only handles a single split, but the concepts at work are illustrated plainly. The next few topics for future posts will include adding animated adjustments, controlling the effective drag area, customizing dividers and generalizing the solution.

The code for this segment can be downloaded here: Part-2

1 Comment

Unraveling the mysteries of NSSplitView – part 1

There are many examples of Mac applications that leverage split views to great effect. Apple uses split views in many applications that we use every day – Mail.app, Preview.app, Xcode.app etc. Many third parties use NSSplitView as well. Gauging from the number of posts on the net, there is also a lot of confusion about how to accomplish the basics (or the expected) using the default NSSplitView class provided in the SDK. This point is accentuated by the presence of several third party frameworks that provide these expected behaviors.

Pre-leopard behavior of NSSplitView gave rise to several of the third party frameworks. In 10.5 Apple cleaned up the implementation of NSSplitView and ostensibly provides everything one needs to use split views effectively.

My experiences (and occasional frustrations) with third party frameworks led me to dig in and try to understand what Apple offers, how it works and how (if) I could package that up in a reusable form for use in my own applications.

Requirements

Everyone has there own pet list of requirements for a usable split view solution, but my list includes the following:

  • collapsible subviews – A common UI capability today is a button or key combination that hides a subview
  • Intelligent subview resizing – There are a lot of documented issues with autoresizing Cocoa views – we need a splitview solution that doesn’t trash subviews when they are collapsed
  • Ability to specify additional drag areas for splitters
  • Ability to specify custom divider visuals
  • Sexy animation when toggling the visibility of subviews

First, it’s worth looking at a few of the frameworks that are out there, what problems they solve and those that they don’t (from my perspective).

RBSplitView

The excellent RBSplitView emerged in 2004 in the pre-leopard days. In addition to providing the runtime framework, RBSplitView includes an Interface Builder palette that supports IB modification of most of the desired behaviors, including divider selection, collapsible views, and min and max settings for view sizes.

RBSplitView also includes support for animating view adjustments such as collapse/uncollapse.

There are a long list of applications that use RBSplitView .

RBSplitView is, from my experiments, very solid code. Capabilities such as toggling splits works, preserving subview layouts.

The primary issue with RBSplitView is that the animation used is pre Core Animation. Running on my 8 core mac pro, this is not an issue, but it gets a bit jumpy on my MacBook Pro. Further, by implementing the animations in the framework, RBSplitView limits ones ability to leverage a consistent CA based animation scheme throughout the application.

Bottom line – in a 10.6 world, is RBSplitView still the best solution?

BWSplitView

I have to say that I really want to like BWSplitView – Brandon Walkin’s framework that provides a modern NSSplitView based solution. On the surface, it meets all of the requirements outlined above. It is supported by a rich IB palette with a slew of conveniences. Brandon’s site includes some great screencasts illustrating the promise of BWSplitView.

That said, I struggled in real world usage of BWSplitView. Documented open issues around the splitter drag behavior created some showstopper issues for me.

In fact, it was my attempts to fix some of the BWSplitView issues that led me to explore how NSSplitView works.

Digging in

The canonical example of splitter view behavior is perhaps Mail.app. Two splitters, a vertical split for the Mailboxes and main view. The main view is horizontally split into the messages list and the message viewer.

To understand what NSSplitView offers out of the box, let’s build a sample app with a single splitter. If we can understand what is going on with a single split view, we can generalize that as we add additional split views.

In order to verify the subview resizing challenges, one of our subviews will have several standard cocoa controls with autoresizing turned on.

The app looks like this:

NSSplitView-Part1-initial.png

Dragging the divider all the way to the right and then back towards the middle quickly borks up the autoresizing behavior.

NSSplitView-Part1-borked.png

To end part 1 of this exploration, let’s add minimum sizes for our split view.

We instantiate a new controller class, we’ll call it MySplitViewController (as it stands now, its just a delegate but we’ll be adding other functionality to it as we move along).

Instantiate an instance of this class in the XIB and hook the delegate outlet of the NSSplitView outlet to the new class.

There are a bunch of optional methods declared in the NSSplitViewDelegate – we’ll implement only two. constrainMinCoordinate and constrainMaxCoordinate. The documentation is sparse on the functionality of these methods, but the header file for NSSplitView does a pretty good job of laying out the basics.

constrainMin… and constrainMax are called repeatedly while the divider is being dragged. In the example implementation, we’ll answer proposedMinimum+200 for the constrainMinCoordinate call, which in our example will have the effect of limiting the left subview to 200 pixels. Judicious use of NSLog will show that the proposedMinimum will be 0 — we’re adding 200 and hence the minimum position of the divider will be 200 pixels. When you begin having splitviews with more than two subviews, the concept is the same, but you are now responsible for determining which subview is being referenced. In our example there is only one divider and its index will always be zero.

The constrainMaxCoordinate method works in a similar fashion. The splitview sends in a proposedMaximumPosition that is the width of splitview – in this case, the entire width of the window. We’ll answer with that value – 100 resulting in a maximum divider position of the window width – 100 pixels.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@implementation MySplitViewController
 
/*
 * Controls the minimum size of the left subview (or top subview in a horizonal NSSplitView)
 */
- (CGFloat)splitView:(NSSplitView *)splitView constrainMinCoordinate:(CGFloat)proposedMinimumPosition ofSubviewAt:(NSInteger)dividerIndex;
{
    NSLog(@"%@:%s proposedMinimum: %f",[self class], _cmd, proposedMinimumPosition);
    return proposedMinimumPosition + 200;
}
 
/*
 * Controls the minimum size of the right subview (or lower subview in a horizonal NSSplitView)
 */
- (CGFloat)splitView:(NSSplitView *)splitView constrainMaxCoordinate:(CGFloat)proposedMaximumPosition ofSubviewAt:(NSInteger)dividerIndex;
{
    NSLog(@"%@:%s proposedMaximum: %f",[self class], _cmd, proposedMaximumPosition);
    return proposedMaximumPosition - 100;
}

left-size-constrained.png

right-size-constrained.png

After compiling and running, we can now see that both the left and right subview are indeed constrained. Although the 100 pixel extent of the right view does not prevent the view from looking terrible, it does prevent the autoresize funkiness of the first example.

Conclusion and Next Steps

We’ve only scratched the surface of NSSplitView. We limited the complexity of our NSSplitView example to the simplest possible case and illustrated some of the challenges in using NSSplitView. In the end, we were able to introduce a few delegate methods that exert additional control over the behavior of NSSplitView.

In the next article, we’ll add support for collapsible subviews and then add programatic collapsing. Additional topics for future posts will cover adding animated adjustments, controlling the effective drag area, customizing dividers and generalizing the solution.

The code for this segment can be downloaded here: Part 1 Sample Projects

No Comments

git clone from Safari

It is often the late night exploration of code in the wild that gives rise to these cute little hacks.

With my wrist tiring of flipping between safari and terminal, the following was born.

Goal

git clone the repository ref found in the system pasteboard

Scenario

When perusing gitHub, I’ll find something I want to check out. I click on the “clone” button which copies the git reference to the clipboard. I typically flip over to a terminal session, change directory to my favorite dumping grounds, and do a git clone Cmd-V enter.

Here’s a script that will do all of that. The secret sauce is teaming this up with something like FastScripts (an excellent status bar accessory).

1
2
3
4
5
6
7
8
9
10
11
#!/bin/sh
REPO=`pbpaste`
DUMPDIR=~/dev/extern
 
cd $DUMPDIR && /usr/local/git/bin/git clone $REPO
EXITCODE=$?
if [ "$EXITCODE" -ne "0" ]; then
	echo "Download of $REPO failed: $EXITCODE" | /usr/local/bin/growlnotify -p 1 "Clone Failed"
else
	echo "Download of $REPO successful" | /usr/local/bin/growlnotify "Clone Succeeded"
fi

What’s happening here?

First we grab the repo reference from the pasteboard using pbpaste. Then we cd to our dumping grounds, execute the git clone. If it fails (because it’s already there, no access, etc) we use growlnotify to throw up the appropriate message.

I bind this script in ~/Library/Scripts/Applications/Safari and then use Cmd-Shift-C – so click to copy, Cmd-Shift-C to clone.

No Comments

Defensive programming and the role of assertions

In Mike Ash’s excellent series “Friday Q&A”, he recently wrote about defensive programming.

I’ve been tightening the screws on my first commercial Mac desktop app and reviewing my code for potential errors is front and center. It’s fair to say that all developers should heed Mike’s advice. I think its even more important (and fodder for a subsequent post) that indie developers heed this advice. Programming solo in the echo chamber has its share of challenges – someone to look over your shoulder occasionally is not a bad thing.

One thing that has bitten me a few times as I’ve reswizzled my UI and cleaned up ivars is missing IB connections. In Uli Kusterer excellent article on Defensive coding in Objective-C there is an excellent point about using NSAssert in your -awakeFromNib method to verify IB connections.

We’re getting there. The issue is that I’ve been disappointed with the behavior of NSAssert in my work to date. I will say up front that I may be missing something with NSAssert, but when I’m writing code and using assertions – I want a strong indication that something’s amiss. Pouring through console logs to find a missing IB connection doesn’t do it for me.

Using the following in my awakeFromNib

1
2
3
4
5
-(void) awakeFromNib
{
    NSAssert(button,@"IB connection for button is missing");
    NSLog(@"I'm the next line, but you'll never see me");
}

results in

*** Assertion failure in -[VerifyIBConnectionAppDelegate awakeFromNib], ..../VerifyIBConnectionAppDelegate.m:24
2009-10-30 10:20:45.824 VerifyIBConnection[35323:903] An uncaught exception was raised
2009-10-30 10:20:45.824 VerifyIBConnection[35323:903] IB connection for button is missing
2009-10-30 10:20:45.850 VerifyIBConnection[35323:903] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'IB connection for button is missing'

This is great. The app is terminated, giving me strong feedback that something is amiss.

If however I move the assertions to -applicationDidFinishLaunching, I get

*** Assertion failure in -[VerifyIBConnectionAppDelegate applicationDidFinishLaunching:], .../VerifyIBConnectionAppDelegate.m:35
2009-10-30 10:23:28.746 VerifyIBConnection[35429:903] IB connection for button is missing

and – the app is still running. The same assertions, in the same class, called at different points in the lifecycle have dramatically different results. So now, in addition to coding defensively, I also need to ponder where I’m asserting what – or else.

Vincent Gable has a nice post on NSAssert considered harmful which brings out this and several other points.

So while you and I decide whether to use NSAssert or the more dramatic assert, I put together the following macro to reduce the verbosity of coding such assertions.

1
2
3
4
// NSAssert version
#define IBVERIFY(condition) NSAssert((condition), @"IB Connection not established for %s", #condition)
// assert version
#define IBVERIFY(condition) assert((condition)!=nil && "IB Connection not established for:" #condition)

The NSAssert version behaves as above. The assert version results in

Assertion failed: ((button)!=nil && "IB Connection not established for:" "button"), function -[VerifyIBConnectionAppDelegate awakeFromNib], file .../VerifyIBConnectionAppDelegate.m, line 25.
Program received signal:  “SIGABRT”.

Outside of the gratuitous additional double quotes (which I’m sure someone will point out how to eliminate) – this version has the comforting side effect of killing my app – wherever it’s invoked from. I take comfort in getting that kind of direct feedback.

Should my opinion of NSAssert change, IBVERIFY can be easily retargeted to use such.

No Comments

When DocSets disappear

I have two OS X development machines, a beefy Mac Pro and a Mac Book Pro (MBP).

I recently repaved the MBP and reestablished my development toolchain.

When looking at Documentation on the MBP, I noticed that the “Doc Sets” pane displayed (as expected).

On my Mac Pro, no love. I’m not sure how it disappeared, but after several minutes of clicking around with no luck, I got down to business.

A quick scan of defaults read com.apple.Xcode revealed a whole bunch of potential settings.

On my MBP I saved off a copy of my defaults and then resized the Doc Sets pane.

Another snapshot and a diff revealed a property with the geometry for the Doc Sets window.

1
2
3
4
5
quant:jschilli$ defaults read com.apple.Xcode "NSSplitView Subview Frames DocSetsAndSearchResultsSplitView"
(
    "0.000000, 0.000000, 0.000000, 1249.000000, NO",
    "0.000000, 0.000000, 1869.000000, 1249.000000, NO"
)

That’s an awful lot of zeros – and very different from the MBP.

I closed XCode on the Mac Pro, and deleted the key.

defaults delete com.apple.Xcode "NSSplitView Subview Frames DocSetsAndSearchResultsSplitView"

Fired up XCode and low and behold – Doc Sets now display again.

No Comments