Follow upstream's disentangling of BUCK caches

In 6f6de0d32cc9b9e1adf65bde3fa0854e6bd26db9, Gerrit moved downloaded
artifacts from

  ~/.gerritcodereview/buck-cache

to

  ~/.gerritcodereview/buck-cache/downloaded-artifacts

. To avoid unnecessarily downloading artifacts, we reflect this move
also for bucklets.
(Note that we do not reflect the above commit's move of the cache for
BUCK built artifacts, as for bucklets builds, those artifacts reside
outside of ~/.gerritcodereview anyways)

Change-Id: I7327ff6c1736f9af8ea15450949dc6a4bc10b684
diff --git a/tools/download_file.py b/tools/download_file.py
index 061d67c..49f6c4d 100755
--- a/tools/download_file.py
+++ b/tools/download_file.py
@@ -25,7 +25,11 @@
 from zipfile import ZipFile, BadZipfile, LargeZipFile
 
 GERRIT_HOME = path.expanduser('~/.gerritcodereview')
-CACHE_DIR = path.join(GERRIT_HOME, 'buck-cache')
+CACHE_DIR = path.join(GERRIT_HOME, 'buck-cache', 'downloaded-artifacts')
+# LEGACY_CACHE_DIR is only used to allow existing workspaces to move already
+# downloaded files to the new cache directory.
+# Please remove after 3 months (2015-10-07).
+LEGACY_CACHE_DIR = path.join(GERRIT_HOME, 'buck-cache')
 LOCAL_PROPERTIES = 'local.properties'
 
 
@@ -86,6 +90,16 @@
   return path.join(CACHE_DIR, name)
 
 
+# Please remove after 3 months (2015-10-07). See LEGACY_CACHE_DIR above.
+def legacy_cache_entry(args):
+  if args.v:
+    h = args.v
+  else:
+    h = sha1(args.u.encode('utf-8')).hexdigest()
+  name = '%s-%s' % (path.basename(args.o), h)
+  return path.join(LEGACY_CACHE_DIR, name)
+
+
 opts = OptionParser()
 opts.add_option('-o', help='local output file')
 opts.add_option('-u', help='URL to download')
@@ -103,8 +117,19 @@
 
 redirects = download_properties(root_dir)
 cache_ent = cache_entry(args)
+legacy_cache_ent = legacy_cache_entry(args)
 src_url = resolve_url(args.u, redirects)
 
+# Please remove after 3 months (2015-10-07). See LEGACY_CACHE_DIR above.
+if not path.exists(cache_ent) and path.exists(legacy_cache_ent):
+  try:
+    safe_mkdirs(path.dirname(cache_ent))
+  except OSError as err:
+    print('error creating directory %s: %s' %
+          (path.dirname(cache_ent), err), file=stderr)
+    exit(1)
+  shutil.move(legacy_cache_ent, cache_ent)
+
 if not path.exists(cache_ent):
   try:
     safe_mkdirs(path.dirname(cache_ent))