Tesla Motors said it would buy solar panel installer SolarCity for $2.6 billion in shares to form a one-stop clean energy shop.