/usr/src/kernel is very RHEL specific.
Agreed, which is why I put it at the end of the search list.
Would this break non-RHEL systems?
None that I am aware of. I don't know of any other systems using /usr/src/kernels/. If there were, and they were doing it in an incompatible way, of course we could make this search dependent on the distro configure is being run on. That just doesn't seem necessary at this point so the complexity seems unnecessary at this point also.
On a system we could also end up with variants like PAE or XEN so it can be even more complex.
I'm not sure this is very likely. /usr/src/kernels/ is at the end of the search list and so only applies to a system that doesn't actually have a kernel matching $(uname -r) installed and as such the /lib/modules/$(uname -r)/{source,build} links are missing. – hence the need to keep looking for some kernel source. I can't imagine a system that this would be true on other than a mock-style (i.e. chroot) build environment and in such an environment, you would only populate it with the kernel-devel of the kernel you are wishing to build for.
Maybe there are cases I am not thinking of?
Don't think this particular patch is good or useful. In the common case where links in /lib/modules are missing and it would go to picking one from /usr/src/kernels, the one it picks is fairly arbitrary. It isn't the case that there is only one most of the time.
If you must pick from there it would be better to first look for a match on 'uname -r', first an exact match and then a close match if no exact match.
In general I think putting in appropriate symlinks in /lib/modules as Dmitry suggests even if the correct kernel-devel isn't installed would be better.
btw, kernel-devel of pristine, unpatched upstream linux is insufficient for building ldiskfs. In RHEL distros it doesn't include ext4 sources, needed for building ldiskfs. kernel source or debuginfo is needed