Reconnecting with lost animation

Occasionally an animator will be working away in their scene, when a new rig is published. Usually this isn’t an issue and the animator will reload the rig and have it available in their scene.
But every now and then, someone doesn’t have their coffee in the morning and instead will load in the new rig, unload the old, save their work and -shock!- their animation is gone! having saved their work they cannot see a way to retrieve it.
At this point I tend the hear “Aaall, my animation has broken!”
Talking to them and having a look at their scene it is apparent what has happened.
Upon loading a new rig, the animation is not connected to it, and when unloading the old rig the animCurve nodes are disconnected from the rig controls.
Fortunately the solution to this is simple.

1. find all animCurve nodes.
2. discern what control node it was connected to.
3. reconnect the animCurve node to the newly discerned control node.

I’ve attached some simple code below that demonstrates this process.

import maya.cmds as cmds

animCurves = cmds.ls(type='animCurve')
nameSpace = 'CH'

for animCurve in animCurves:
    attr = animCurve.split('_')[-1]
    control = (animCurve.replace(attr,''))[0:-1]
    try:
        if nameSpace:
            cmds.connectAttr('%s.output' % animCurve, '%s:%s.%s' % (nameSpace, control, attr))
        if not nameSpace:
            cmds.connectAttr('%s.output' % animCurve, '%s.%s' % (control, attr))
    except:
        print 'could not connect %s' % animCurve