#!/usr/bin/python
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""
This tool creates a tarball with all the sources, but without .svn directories.

It can also remove files which are not strictly required for build, so that
the resulting tarball can be reasonably small (last time it was ~110 MB).

Example usage (make sure gclient is in your PATH):

export_tarball.py /foo/bar

The above will create file /foo/bar.tar.bz2.
"""

from __future__ import with_statement

import contextlib
import optparse
import os
import shutil
import subprocess
import sys
import tarfile
import tempfile

def RunCommand(argv):
  """Runs the command with given argv and returns exit code."""
  try:
    proc = subprocess.Popen(argv, stdout=None)
  except OSError:
    return 1
  output = proc.communicate()[0]
  return proc.returncode

def main(argv):
  parser = optparse.OptionParser()
  parser.add_option("--remove-nonessential-files",
                    dest="remove_nonessential_files",
                    action="store_true", default=False)

  options, args = parser.parse_args(argv)

  if len(args) != 1:
    print 'You must provide only one argument: output file name'
    print '(without .tar.bz2 extension).'
    return 1

  output_fullname = args[0] + '.tar.bz2'
  output_basename = os.path.basename(args[0])
  target_dir = tempfile.mkdtemp()

  try:
    if RunCommand(['gclient', 'export', target_dir]) != 0:
      print 'gclient failed'
      return 1

    if options.remove_nonessential_files:
      nonessential_dirs = (
          'src/chrome/test/data',
          'src/chrome/tools/test/reference_build',
          'src/gears/binaries',
          'src/net/data/cache_tests',
          'src/o3d/documentation',
          'src/o3d/samples',
          'src/third_party/lighttpd',
          'src/third_party/WebKit/LayoutTests',
          'src/webkit/data/layout_tests',
          'src/webkit/tools/test/reference_build',
      )
      for dir in nonessential_dirs:
        path = os.path.join(target_dir, dir)
        try:
          print 'removing %s...' % dir
          shutil.rmtree(path)
        except OSError, e:
          print 'error while trying to remove %s, skipping' % dir

    with contextlib.closing(tarfile.open(output_fullname, 'w:bz2')) as archive:
      archive.add(os.path.join(target_dir, 'src'), arcname=output_basename)
  finally:
    shutil.rmtree(target_dir)

  return 0

if __name__ == "__main__":
  sys.exit(main(sys.argv[1:]))

@@ -431,44 +431,8 @@
 sage
- (make sure gclient is in your PATH)
 :%0A%0Ae
@@ -603,303 +603,472 @@
 rt s
-hutil%0Aimport subprocess%0Aimport sys%0Aimport tarfile%0Aimport tempfile%0A%0Adef RunCommand(argv):%0A  %22%22%22Runs the command with given argv and returns exit code.%22%22%22%0A  try:%0A    proc = subprocess.Popen(argv, stdout=None)%0A  except OSError:%0A    return 1%0A  output = proc.communicate()%5B0%5D%0A  return proc.returncode
+ys%0Aimport tarfile%0A%0ANONESSENTIAL_DIRS = (%0A    'chrome/test/data',%0A    'chrome/tools/test/reference_build',%0A    'gears/binaries',%0A    'net/data/cache_tests',%0A    'o3d/documentation',%0A    'o3d/samples',%0A    'third_party/lighttpd',%0A    'third_party/WebKit/LayoutTests',%0A    'webkit/data/layout_tests',%0A    'webkit/tools/test/reference_build',%0A)%0A%0Adef GetSourceDirectory():%0A  return os.path.realpath(%0A    os.path.join(os.path.dirname(__file__), '..', '..', '..', 'src'))
 %0A%0Ade
@@ -1463,16 +1463,120 @@
 turn 1%0A%0A
+  if not os.path.exists(GetSourceDirectory()):%0A    print 'Cannot find the src directory.'%0A    return 1%0A%0A
   output
@@ -1658,137 +1658,109 @@
 0%5D)%0A
+%0A
   
-target_dir = tempfile.mkdtemp()%0A%0A  try:%0A    if RunCommand(%5B'gclient', 'export', target_dir%5D) != 0:%0A      print 'gclient failed'
+def ShouldExcludePath(path):%0A    head, tail = os.path.split(path)%0A    if tail in ('.svn', '.git'):
 %0A   
@@ -1765,25 +1765,28 @@
      return 
-1
+True
 %0A%0A    if opt
@@ -1782,16 +1782,20 @@
 %0A    if 
+not 
 options.
@@ -1831,695 +1831,187 @@
     
-nonessential_dirs = (%0A          'src/chrome/test/data',%0A          'src/chrome/tools/test/reference_build',%0A          'src/gears/binaries',%0A          'src/net/data/cache_tests',%0A          'src/o3d/documentation',%0A          'src/o3d/samples',%0A          'src/third_party/lighttpd',%0A          'src/third_party/WebKit/LayoutTests',%0A          'src/webkit/data/layout_tests',%0A          'src/webkit/tools/test/reference_build',%0A      )%0A      for dir in nonessential_dirs:%0A        path = os.path.join(target_dir, dir)%0A        try:%0A          print 'removing %25s...' %25 dir%0A          shutil.rmtree(path)%0A        except OSError, e:%0A          print 'error while trying to remove %25s, skipping' %25 dir%0A%0A  
+return False%0A    for nonessential_dir in NONESSENTIAL_DIRS:%0A      if path.startswith(os.path.join(GetSourceDirectory(), nonessential_dir)):%0A        return True%0A%0A    return False%0A%0A
   wi
@@ -2084,18 +2084,16 @@
 rchive:%0A
-  
     arch
@@ -2104,38 +2104,27 @@
 add(
-os.path.join(target_dir, 'src'
+GetSourceDirectory(
 ), a
@@ -2149,49 +2149,51 @@
 name
-)%0A  finally:%0A    shutil.rmtree(target_dir
+,%0A                exclude=ShouldExcludePath
 )%0A%0A 

Make export_tarball.py more reliable and simplify it.