cros_gestures: Delete
There doesn't seem to be any reference to it and the last real CL was in
2012.
BUG=none
TEST=CQ passes
Change-Id: I90865159d95593dba74b7a77bb141467cc4c84ad
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/platform/crostestutils/+/1841526
Tested-by: Amin Hassani <ahassani@chromium.org>
Reviewed-by: Mike Frysinger <vapier@chromium.org>
Reviewed-by: Achuith Bhandarkar <achuith@chromium.org>
Reviewed-by: Katherine Threlkeld <kathrelkeld@chromium.org>
Reviewed-by: Harry Cutts <hcutts@chromium.org>
Commit-Queue: Amin Hassani <ahassani@chromium.org>
diff --git a/cros_gestures/README b/cros_gestures/README
deleted file mode 100644
index 48f95e5..0000000
--- a/cros_gestures/README
+++ /dev/null
@@ -1,46 +0,0 @@
-This directory contains Python code that allows Chrome OS developers and testers
-to make files available for touchpad gesture testing.
-
-The command line tool is modeled very closely on (and depends) on the Google
-Storage command line client (gsutil).
-
-CONTENTS:
- - cros_gestures is the command line tool
- - setup_cros_gestures.sh helps establish proper environment variables to find
- both gsutil and the needed .boto file for authentication.
- - run_remote_tool builds a bundle to install on a test machine (and can
- run it on a test machine).
- - remote/install_cros_gestures.py can setup a test machine from the public,
- untrusted bundle.
-
-FOR MORE INFORMATION ON INSTALLING AND USING GSUTIL, SEE:
-<http://code.google.com/apis/storage/docs/gsutil.html>.
-
-TO INSTALL GSUTILS:
- - cd ~
- - wget http://commondatastorage.googleapis.com/pub/gsutil.tar.gz
- - gzip -d gsutil.tar.gz
- - tar -xvf gsutil.tar
-
-TO BUILD A TRUSTED PACKAGE TO ./CROS_GESTURES.TAR.BZ2:
- - . ./setup_cros_gestures.sh trusted
- - ./run_remote_tool
-
-TO BUILD AN UNTRUSTED PACKAGE TO ./CROS_GESTURES.TAR.BZ2:
- - . ./setup_cros_gestures.sh untrusted
- - ./run_remote_tool
-
-TO DEPLOY THE BUNDLES:
- - gsutil cp /tmp/cros_gestures.tar.bz2 \
- gs://chromeos-gestures-valid/downloads/untrusted/cros_gestures.tar.bz2
- - gsutil cp /tmp/install_cros_gestures.py \
- gs://chromeos-gestures-valid/downloads/untrusted/install_cros_gestures.py
- - gsutil setacl public-read \
- gs://chromeos-gestures-valid/downloads/untrusted/cros_gestures.tar.bz2
- - gsutil setacl public-read \
- gs://chromeos-gestures-valid/downloads/untrusted/install_cros_gestures.py
-
-TO INSTALL CROS_GESTURES TO /USR/LOCAL/CROS_GESTURES (TEST MACHINES):
- - cd /tmp
- - wget http://chromeos-gestures-valid.commondatastorage.googleapis.com/downloads/untrusted/install_cros_gestures.py
- - python ./install_cros_gestures.py
diff --git a/cros_gestures/__init__.py b/cros_gestures/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/cros_gestures/__init__.py
+++ /dev/null
diff --git a/cros_gestures/cros_gestures b/cros_gestures/cros_gestures
deleted file mode 100755
index 7a2ffc3..0000000
--- a/cros_gestures/cros_gestures
+++ /dev/null
@@ -1,141 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Simple command line interface for chromeos gesture developers.
-
-This is heavily dependent/copied on the gsutil cli interface to Google Storage.
-http://code.google.com/apis/storage/docs/gsutil.html
-Think of it as a version of gsutil with assumptions for more guided use.
-
-Look here for documentation on Google Storage:
-http://code.google.com/apis/storage/docs/gsmanager.html
-"""
-
-import logging
-import pprint
-import signal
-import sys
-
-import cros_gestures_constants
-import cros_gestures_logging
-import cros_gestures_utils
-from exception import CrosGesturesException
-
-
-color = cros_gestures_utils.Color()
-LOG = logging.getLogger('cros_gestures')
-
-
-#------------------------------------------------------------------------------
-# Setup gslib and boto by identifying gsutil/boto dirs and .boto location.
-#------------------------------------------------------------------------------
-gsutil_bin_dir, boto_config = cros_gestures_utils.FindDependencies()
-
-import boto
-boto.UserAgent += '/cros_gestures'
-from boto.exception import GSResponseError
-from boto.exception import InvalidUriError
-
-# We don't use the oauth2 authentication plugin directly; importing it here
-# ensures that it's loaded and available by default.
-_HAVE_OAUTH2 = False
-try:
- from oauth2_plugin import oauth2_plugin
- _HAVE_OAUTH2 = True
-except ImportError:
- pass
-
-import cros_gestures_commands
-import cros_gestures_options
-
-
-#------------------------------------------------------------------------------
-# Declare custom commands.
-#------------------------------------------------------------------------------
-commands = {'cat': None, 'download': None, 'ls': None,
- 'rm': None, 'upload': None, 'ver': None}
-COMMANDS_STRING = ', '.join(sorted(commands.keys()))
-USAGE_STRING = (
- 'cros_gestures [options] %(command)s\n%(command)s from: %(commands)s.\n\n'
- 'The default behavior is to group uploaded files under '
- '%(gs_base)s/model/user/".\nCommon command examples include:\n\n'
- '%(cat)s gesture_file [emits contents of %(gs_base)s/user/gesture_file]\n'
- '%(download)s gesture_file [copies %(gs_base)s/user/gesture_file to '
- 'current dir]\n'
- '%(ls)s [show all files under %(gs_base)s/user]\n'
- '%(ls)s -L [show all files with attributes under %(gs_base)s/user]\n'
- '%(upload)s dir/gesture_file [strip dir & copy gesture_file to '
- '%(gs_base)s/user/gesture_file]\n'
- '%(ver)s [show tool version numbers]' % {
- 'command': color.Color(cros_gestures_utils.Color.BLUE, 'command'),
- 'commands': color.Color(cros_gestures_utils.Color.BOLD,
- COMMANDS_STRING),
- 'cat': color.Color(cros_gestures_utils.Color.BOLD, 'cat'),
- 'download': color.Color(cros_gestures_utils.Color.BOLD, 'download'),
- 'ls': color.Color(cros_gestures_utils.Color.BOLD, 'ls'),
- 'upload': color.Color(cros_gestures_utils.Color.BOLD, 'upload'),
- 'ver': color.Color(cros_gestures_utils.Color.BOLD, 'ver'),
- 'gs_base': 'gs://chromeos-gestures-trusted-dev'}
- )
-
-
-# If user enters no commands just print the usage info.
-if len(sys.argv) == 1:
- cros_gestures_utils.OutputAndExit(USAGE_STRING)
-options, args, command_string = cros_gestures_options.ParseArgs(USAGE_STRING,
- commands)
-cros_gestures_logging.SetupLogging(options)
-if cros_gestures_constants.debug > 1:
- LOG.debug('Using\n\tGSUTIL_BIN_DIR=%s\n\tBOTO_CONFIG=%s.', gsutil_bin_dir,
- boto_config)
- LOG.debug('Accepted funtionalities:\n%s.',
- pprint.pformat(options.config_options))
-
-#------------------------------------------------------------------------------
-# Define custom commands.
-#------------------------------------------------------------------------------
-_command_inst = cros_gestures_commands.GestureCommand(gsutil_bin_dir)
-
-
-NO_MAX = sys.maxint
-# [command_function, min # args, max # args, file_uri_ok, gs_uri_ok]
-commands.update({
- 'cat': [_command_inst.CatGestureCommand, 1, NO_MAX, True, True],
- 'download': [_command_inst.DownloadGestureCommand, 1, NO_MAX, True,
- False],
- 'ls': [_command_inst.ListGesturesCommand, 0, NO_MAX, True, True],
- 'rm': [_command_inst.RemoveGesturesCommand, 1, NO_MAX, True, True],
- 'upload': [_command_inst.UploadGestureCommand, 1, 1, True, False],
- 'ver': [_command_inst.VersionCommand, 0, 0, False, False]})
-
-
-#------------------------------------------------------------------------------
-# Main
-#------------------------------------------------------------------------------
-def main():
- """Gesture File Command Line Interface main code."""
- try:
- signal.signal(signal.SIGINT, cros_gestures_utils.HandleControlC)
- command, min_nargs, max_nargs, file_uri, gs_uri = commands[command_string]
- # General command validation.
- if len(args) < min_nargs or len(args) > max_nargs:
- raise CrosGesturesException(
- 'Wrong number of arguments for "%s" command.' % command_string)
- if not file_uri and cros_gestures_utils.HaveFileUris(args):
- raise CrosGesturesException(
- '"%s" command does not support "file://" URIs. '
- 'Did you mean to use a gs:// URI?' % command_string)
- if not gs_uri and cros_gestures_commands.GestureUri.HasGSUris(args):
- raise CrosGesturesException(
- '"%s" command does not support gs:// URIs.' % command_string)
- # Finally, run the command.
- sys.exit(command(cros_gestures_utils.StripFileUris(args), options))
- except CrosGesturesException, e:
- cros_gestures_utils.HandleCrosGesturesException(e)
-
-
-if __name__ == '__main__':
- main()
diff --git a/cros_gestures/cros_gestures_admin b/cros_gestures/cros_gestures_admin
deleted file mode 100755
index 9f09db6..0000000
--- a/cros_gestures/cros_gestures_admin
+++ /dev/null
@@ -1,129 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Simple command line interface for chromeos gesture admins.
-
-This is heavily dependent/copied on the gsutil cli interface to Google Storage.
-http://code.google.com/apis/storage/docs/gsutil.html
-Think of it as a version of gsutil with assumptions for more guided use.
-
-Look here for documentation on Google Storage:
-http://code.google.com/apis/storage/docs/gsmanager.html
-"""
-
-import logging
-import pprint
-import signal
-import sys
-
-import cros_gestures_constants
-import cros_gestures_logging
-import cros_gestures_utils
-from exception import CrosGesturesException
-
-
-color = cros_gestures_utils.Color()
-LOG = logging.getLogger('cros_gestures')
-
-
-#------------------------------------------------------------------------------
-# Setup gslib and boto by identifying gsutil/boto dirs and .boto location.
-#------------------------------------------------------------------------------
-gsutil_bin_dir, boto_config = cros_gestures_utils.FindDependencies(
- 'BOTO_VALIDATE_CONFIG')
-
-import boto
-boto.UserAgent += '/cros_gestures'
-from boto.exception import GSResponseError
-from boto.exception import InvalidUriError
-
-# We don't use the oauth2 authentication plugin directly; importing it here
-# ensures that it's loaded and available by default.
-_HAVE_OAUTH2 = False
-try:
- from oauth2_plugin import oauth2_plugin
- _HAVE_OAUTH2 = True
-except ImportError:
- pass
-
-import cros_gestures_commands
-import cros_gestures_options
-
-
-#------------------------------------------------------------------------------
-# Declare custom commands.
-#------------------------------------------------------------------------------
-commands = {'cat': None, 'download': None, 'ls': None, 'invalidate': None,
- 'validate': None, 'ver': None}
-COMMANDS_STRING = ', '.join(sorted(commands.keys()))
-USAGE_STRING = (
- 'cros_gestures_admin [options] %(command)s\n%(command)s from: '
- '%(commands)s.\n\nThis utility is used to validate and invalidate '
- 'files. Validated files may be included in test passes.' % {
- 'command': color.Color(cros_gestures_utils.Color.BLUE, 'command'),
- 'commands': color.Color(cros_gestures_utils.Color.BOLD,
- COMMANDS_STRING)})
-
-
-# If user enters no commands just print the usage info.
-if len(sys.argv) == 1:
- cros_gestures_utils.OutputAndExit(USAGE_STRING)
-options, args, command_string = cros_gestures_options.ParseArgs(USAGE_STRING,
- commands,
- admin=True)
-cros_gestures_logging.SetupLogging(options)
-if cros_gestures_constants.debug > 1:
- LOG.debug('Using\n\tGSUTIL_BIN_DIR=%s\n\tBOTO_CONFIG=%s.', gsutil_bin_dir,
- boto_config)
- LOG.debug('Accepted funtionalities:\n%s.',
- pprint.pformat(options.config_options))
-
-#------------------------------------------------------------------------------
-# Define custom commands.
-#------------------------------------------------------------------------------
-_command_inst = cros_gestures_commands.GestureCommand(gsutil_bin_dir)
-
-
-NO_MAX = sys.maxint
-# [command_function, min # args, max # args, file_uri_ok, gs_uri_ok]
-commands.update({
- 'cat': [_command_inst.CatGestureCommand, 1, NO_MAX, True, True],
- 'download': [_command_inst.DownloadGestureCommand, 1, NO_MAX, True,
- False],
- 'ls': [_command_inst.ListGesturesCommand, 0, NO_MAX, True, True],
- 'invalidate': [_command_inst.InvalidateGestureCommand, 1, 1, True,
- True],
- 'validate': [_command_inst.ValidateGestureCommand, 1, 1, True, True],
- 'ver': [_command_inst.VersionCommand, 0, 0, False, False]})
-
-
-#------------------------------------------------------------------------------
-# Main
-#------------------------------------------------------------------------------
-def main():
- """Gesture File Command Line Interface main code."""
- try:
- signal.signal(signal.SIGINT, cros_gestures_utils.HandleControlC)
- command, min_nargs, max_nargs, file_uri, gs_uri = commands[command_string]
- # General command validation.
- if len(args) < min_nargs or len(args) > max_nargs:
- raise CrosGesturesException(
- 'Wrong number of arguments for "%s" command.' % command_string)
- if not file_uri and cros_gestures_utils.HaveFileUris(args):
- raise CrosGesturesException(
- '"%s" command does not support "file://" URIs. '
- 'Did you mean to use a gs:// URI?' % command_string)
- if not gs_uri and cros_gestures_commands.GestureUri.HasGSUris(args):
- raise CrosGesturesException(
- '"%s" command does not support gs:// URIs.' % command_string)
- # Finally, run the command.
- sys.exit(command(cros_gestures_utils.StripFileUris(args), options))
- except CrosGesturesException, e:
- cros_gestures_utils.HandleCrosGesturesException(e)
-
-
-if __name__ == '__main__':
- main()
diff --git a/cros_gestures/cros_gestures_commands.py b/cros_gestures/cros_gestures_commands.py
deleted file mode 100644
index 6fc8819..0000000
--- a/cros_gestures/cros_gestures_commands.py
+++ /dev/null
@@ -1,402 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Commands to support cros_gestures
-
-This code is modeled after and derived from the Command class in
-gsutil/gslib/command.py for maximum re-use.
-"""
-
-__version__ = '1.0.0'
-
-import datetime
-import hashlib
-import logging
-import optparse
-import os
-import re
-import sys
-
-import cros_gestures_constants
-import cros_gestures_utils
-from exception import CrosGesturesException
-
-
-color = cros_gestures_utils.Color()
-
-LOG = logging.getLogger('cros_gestures_commands')
-# Mon, 25 Jul 2011 08:20:08
-DISPLAY_TIME_FORMAT = '%a, %d %b %Y %H:%M:%S'
-# 20110725_082008
-FILE_TIME_FORMAT = '%Y%m%d_%H%M%S'
-
-
-def AddOptions(parser, config_options, admin=False):
- """Add command line option group for cros_gestures_commands.
-
- Add helpful command line options related to commands defined
- in this file.
-
- -F, --force-rm: [invalidate/rm] confirmation of irreversible file removal.
- -L, --list-metadata: [ls] most verbose ls command.
- -U, --user-override: [all] substitute an alternate user tag in file namespace.
- --print-filenames: [cat] include filename (helps cat of multiple cat files).
- --download-dir: [download] place downloaded files out of current dir.
- --upload-functionality: [upload]: override filename functionality.
- --upload-fwversion: [upload]: override filename fwversion.
- --upload-tag: [upload] set a tag (to arbitrarily group files).
- """
- group = optparse.OptionGroup(parser, 'Command Options')
- group.add_option('-F', '--force-rm',
- help='Force %s of file [default: %s]' % (
- color.Color(cros_gestures_utils.Color.BOLD, 'rm'),
- '%default'),
- dest='forcerm',
- action='store_true',
- default=False)
- group.add_option('-L', '--list-metadata',
- help='Show file metadata with %s [default: %s]' % (
- color.Color(cros_gestures_utils.Color.BOLD, 'list'),
- '%default'),
- dest='listmetadata',
- action='store_true',
- default=False)
- group.add_option('-U', '--user-override',
- help='Override filename user of file [default: %s]' %
- '%default',
- dest='useroverride',
- action='store_true',
- default=False)
- group.add_option('', '--print-filenames',
- help='Show file names with %s output [default: %s]' % (
- color.Color(cros_gestures_utils.Color.BOLD, 'cat'),
- '%default'),
- dest='catfilenames',
- action='store_true',
- default=False)
- # Admin commands use different options.
- if not admin:
- group.add_option('', '--download-dir',
- help='Set %s directory [default: %s]' % (
- color.Color(cros_gestures_utils.Color.BOLD,
- 'download'),
- '%default'),
- dest='downloaddir',
- default=None)
- group.add_option('', '--upload-functionality',
- help='Set functionality during %s: %s [default: %s]' % (
- color.Color(cros_gestures_utils.Color.BOLD, 'upload'),
- ', '.join(sorted(config_options.keys())),
- '<from filename>'),
- dest='uploadfunctionality',
- default=None)
- group.add_option('', '--upload-fwversion',
- help='Set fwversion during %s [default: %s]' % (
- color.Color(cros_gestures_utils.Color.BOLD, 'upload'),
- '%default'),
- dest='uploadfwversion',
- default=None)
- group.add_option('', '--upload-tag',
- help='Supply %s tag for custom grouping [default: %s]' % (
- color.Color(cros_gestures_utils.Color.BOLD, 'upload'),
- '%default'),
- dest='uploadtag',
- default=None)
- parser.add_option_group(group)
-
-
-def FixupOptionsFromFilename(source_file, options):
- """Setup default options (metadata) from filename if possible.
-
- template filename:
- area-functionalitynamewithunderscores.subname-model-tester-timestamp.dat
- 0: area
- 1: functionality [optional subname(s) separated by period]
- 2: model
- 3: [fw version]
- 4: [optional attributes - each separated by hyphen]
- 5: tester
- 6: timestamp
- """
- options.uploadarea = None # Create nonexistent attributes
- options.uploadcreated = None
- filename_parse = re.compile(
- '([\w]+)-([\w]+)\.[\w.]+-([\w]+)-([\w]+)-([\w]+)')
- m = re.match(filename_parse, source_file)
- if not m or m.lastindex < 5:
- raise CrosGesturesException(
- 'This filename is not formatted properly. Expecting: '
- 'area-functionality.subname-model-tester-timestamp.dat. '
- 'Skipping %s.' % source_file)
- gs_area, gs_functionality, gs_model, gs_tester, gs_time = m.groups()
- if gs_area:
- options.uploadarea = gs_area
- if gs_functionality:
- options.uploadfunctionality = gs_functionality
- if gs_model:
- if not options.model:
- options.model = gs_model
- if gs_model != options.model:
- raise CrosGesturesException(
- '--model (%s) is different than file name model (%s).' %
- (options.model, gs_model))
- if gs_tester and gs_tester != options.userowner:
- LOG.warning(
- '--user (%s) is different than file name tester (%s).',
- options.userowner, gs_tester)
- if not options.useroverride:
- options.userowner = gs_tester
- if gs_time:
- options.uploadcreated = datetime.datetime.strptime(
- gs_time, FILE_TIME_FORMAT).strftime(DISPLAY_TIME_FORMAT)
- # Extra validations.
- if options.uploadfunctionality not in options.config_options:
- raise CrosGesturesException('The config file does not expect this '
- 'functionality: %s' %
- options.uploadfunctionality)
- if (options.uploadarea not in
- options.config_options[options.uploadfunctionality]):
- raise CrosGesturesException('The area %s is not expected with %s.' %
- (options.uploadarea,
- options.uploadfunctionality))
-
-
-class GestureUri(object):
- """Very thin wrapper around our gesture uri's."""
- def __init__(self, options):
- self.options = options
-
- @staticmethod
- def HasGSUri(uri_str):
- """Check one uri for our provider."""
- return uri_str.lower().startswith('gs://')
-
- @staticmethod
- def HasGSUris(args):
- """Checks whether args contains any provider URIs (like 'gs://').
-
- Args:
- args: command-line arguments
-
- Returns:
- True if args contains any provider URIs.
- """
- for uri_str in args:
- if GestureUri.HasGSUri(uri_str):
- return True
- return False
-
- def MakeGestureUri(self, uri_str=None):
- """Gesture files are prefaced by their ownername."""
- assert uri_str
- if uri_str == '*' and not self.options.model:
- self.options.model = '*'
- if not self.options.model:
- raise CrosGesturesException('Please supply a model to MakeGestureUri.')
- if not self.options.userowner:
- raise CrosGesturesException('Please supply a user to MakeGestureUri.')
- if not uri_str:
- raise CrosGesturesException('Unexpected empty uri.')
- if cros_gestures_constants.trusted:
- user_type = 'trusted-dev'
- else:
- user_type = 'untrusted-dev'
- return 'gs://chromeos-gestures-%s/%s/%s/%s' % (user_type,
- self.options.model,
- self.options.userowner,
- uri_str)
-
- @staticmethod
- def MakeValidUri(uri_str):
- """Gesture files headed to the valid bucket."""
- if not GestureUri.HasGSUri(uri_str):
- raise CrosGesturesException('Validate requires a gs:// uri.')
- return re.sub('gs://chromeos-gestures.*trusted-dev/',
- 'gs://chromeos-gestures-valid/', uri_str)
-
- def MakeGestureUris(self, args):
- """Fixup args to be valid gs uri's if needed."""
- new_args = []
- for uri_str in args:
- if GestureUri.HasGSUri(uri_str):
- new_arg = uri_str
- else:
- uri_str = os.path.basename(uri_str)
- FixupOptionsFromFilename(uri_str, self.options)
- new_arg = self.MakeGestureUri(uri_str)
- new_args.append(new_arg)
- return new_args
-
-
-class GestureCommand(object):
- """Class that contains all our Gesture command code."""
-
- def __init__(self, gsutil_bin_dir):
- """Instantiates GestureCommand class. Modeled after gslib/command/Command.
-
- Args:
- gsutil_bin_dir: bin dir from which gsutil is running.
- """
- self.gsutil_bin_dir = gsutil_bin_dir
-
- def _FileExists(self, file_name):
- """Helper to see if a fully path-included remote file exits."""
- return 0 == cros_gestures_utils.RunGSUtil(self.gsutil_bin_dir, LOG, 'ls',
- args=[file_name],
- show_output=False)
-
- def RunGSUtil(self, cmd, headers=None, sub_opts=None, args=None,
- show_output=True):
- """Executes common gsutil run command utility."""
- return cros_gestures_utils.RunGSUtil(self.gsutil_bin_dir, LOG, cmd,
- headers, sub_opts, args, show_output)
-
- def CatGestureCommand(self, args, options):
- """Cat a single gesture file from Google Storage."""
- guri = GestureUri(options)
- args = guri.MakeGestureUris(args)
-
- if options.catfilenames:
- sub_opts = ['-h']
- else:
- sub_opts = None
- return self.RunGSUtil(cmd='cat', sub_opts=sub_opts, args=args)
-
- def DownloadGestureCommand(self, args, options):
- """Download a single gesture file from Google Storage."""
- # TODO(Truty): add md5/md5 header and verify.
- local_files = args[:]
- guri = GestureUri(options)
- args = guri.MakeGestureUris(args)
- rc = 0
- for i in xrange(len(args)):
- remote_file = args[i]
- if not self._FileExists(remote_file):
- LOG.warning(color.Color(
- cros_gestures_utils.Color.RED, 'File %s not found.' % remote_file))
- continue
- local_file = local_files[i]
- if options.downloaddir:
- if not os.path.exists(options.downloaddir):
- os.makedirs(options.downloaddir)
- local_file = os.path.join(options.downloaddir, local_file)
- if os.path.isfile(local_file):
- raise CrosGesturesException('Local file %s already exists.' %
- local_file)
- rc += self.RunGSUtil(cmd='cp', args=[remote_file, local_file])
- return rc
-
- def InvalidateGestureCommand(self, args, options):
- """Allows a gesture file to be blocked to tests.
-
- See ValidateGestureCommand() for more detail.
- """
- if not options.forcerm:
- raise CrosGesturesException(
- 'invalidate requires -F to force file removal.')
- guri = GestureUri(options)
- source_file = guri.MakeGestureUris(args)[0]
- target_file = GestureUri.MakeValidUri(source_file)
- if not self._FileExists(target_file):
- raise CrosGesturesException('Validated file %s cannot be found.'
- % target_file)
- return self.RunGSUtil(cmd='rm', args=[target_file])
-
- def ListGesturesCommand(self, args, options):
- """List gestures (and metadata) in Google Storage."""
- guri = GestureUri(options)
- if not args:
- args = [guri.MakeGestureUri('*')]
- else:
- args = guri.MakeGestureUris(args)
-
- if options.listmetadata:
- sub_opts = ['-L']
- LOG.info('This can take a little longer to retrieve metadata.')
- else:
- sub_opts = None
- return self.RunGSUtil(cmd='ls', sub_opts=sub_opts, args=args)
-
- def RemoveGesturesCommand(self, args, options):
- """Remove gestures in Google Storage."""
- guri = GestureUri(options)
- args = guri.MakeGestureUris(args)
- if not options.forcerm:
- raise CrosGesturesException('rm requires -F to force file removal.')
- return self.RunGSUtil(cmd='rm', args=args)
-
- def UploadGestureCommand(self, args, options):
- """Upload a single gesture file to Google Storage."""
- local_file = args[0]
- guri = GestureUri(options)
- remote_file = guri.MakeGestureUris(args)[0]
- if self._FileExists(remote_file):
- raise CrosGesturesException('File %s already exists.' % remote_file,
- informational=True)
- if not os.path.isfile(local_file):
- raise CrosGesturesException('Cannot find source file: %s.' % local_file)
- if not options.uploadfunctionality:
- raise CrosGesturesException('upload requires '
- '--upload-functionality=functionality. '
- '\n\t\tfunctionality is one of:\n\t\t\t%s' %
- ('\n\t\t\t'.join(options.config_options)))
- if not options.uploadarea:
- raise CrosGesturesException('upload requires an upload area.')
- if not options.model:
- raise CrosGesturesException('upload requires --model=model#.')
- # uploadfwversion is NOT required.
-
- # If this is not project-private, then only the owner can mark the
- # file object public-read (we call that 'validation').
- sub_opts = ['-a', 'project-private']
- hprefix = 'x-goog-meta'
-
- f = open(local_file, 'r')
- file_contents = f.read()
- f.close()
- headers = ["'Content-MD5':%s" % hashlib.md5(file_contents).hexdigest(),
- '"%s-area:%s"' % (hprefix, options.uploadarea),
- '"%s-function:%s"' % (hprefix, options.uploadfunctionality),
- '"%s-fw_version:%s"' % (hprefix, options.uploadfwversion),
- '"%s-model:%s"' % (hprefix, options.model),
- '"%s-created:%s"' % (hprefix, options.uploadcreated)]
- if options.uploadtag:
- headers.append('"%s-tag:%s"' % (hprefix, options.uploadtag))
- return self.RunGSUtil(cmd='cp', headers=headers, sub_opts=sub_opts,
- args=[local_file, remote_file])
-
- def ValidateGestureCommand(self, args, options):
- """Allows a gesture file to be consumed by tests.
-
- Validate makes files available for unauthenticated access. Note that
- in copying the file to the valid bucket, the object's metadata is lost.
- It's metadata remains in the source folder, though, for filtering use.
- 1. 'Invalid' files are not accessible by unauthenticated-public.
- 2. It is desirable to know the date of the validation. The logic of
- interpreting 'date-validated is:
- If the file is 'valid', then 'Last mod' is the 'date-validated'.
- Public access of 'validated' files is through:
- http://chromeos-gestures-valid.commondatastorage.googleapis.com/
- """
- guri = GestureUri(options)
- source_file = guri.MakeGestureUris(args)[0]
- target_file = GestureUri.MakeValidUri(source_file)
- if not self._FileExists(source_file):
- raise CrosGesturesException('File %s cannot be found.' % source_file)
- if self._FileExists(target_file):
- raise CrosGesturesException('Validated file %s already exists.'
- % target_file)
- rc = self.RunGSUtil(cmd='cp', args=[source_file, target_file])
- if not rc:
- rc = self.RunGSUtil(cmd='setacl', args=['public-read', target_file])
- return rc
-
- def VersionCommand(self, args, options):
- """Print version information for gsutil."""
- msg = color.Color(cros_gestures_utils.Color.BOLD,
- 'cros_gestures version %s\n' % __version__)
- sys.stderr.write(msg)
- return self.RunGSUtil(cmd='ver')
diff --git a/cros_gestures/cros_gestures_constants.py b/cros_gestures/cros_gestures_constants.py
deleted file mode 100644
index e7abba1..0000000
--- a/cros_gestures/cros_gestures_constants.py
+++ /dev/null
@@ -1,7 +0,0 @@
-# -*- coding: utf-8 -*-
-# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-debug = 0
-trusted = True
diff --git a/cros_gestures/cros_gestures_logging.py b/cros_gestures/cros_gestures_logging.py
deleted file mode 100644
index 49632fd..0000000
--- a/cros_gestures/cros_gestures_logging.py
+++ /dev/null
@@ -1,39 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Logging optinos to support cros_gestures
-
-Setup logging options and global debug variable used by underlying
-gsutil and boto libraries.
-"""
-
-import logging
-
-import cros_gestures_constants
-
-
-class NoLoggingFilter(logging.Filter):
- """Used to filter logging messages. This completely blocks messages."""
- def filter(self, record):
- return False
-
-
-def SetupLogging(options):
- """Initialize logging options."""
-
- if options.detaileddebugout or options.debugout:
- logging_level = logging.DEBUG
- if options.detaileddebugout:
- cros_gestures_constants.debug = 3 # from gsutil show httplib headers
- else:
- cros_gestures_constants.debug = 2 # from gsutil
- else:
- logging_level = logging.INFO
- # Mute verbose oauth logging.
- oauth_log = logging.getLogger('oauth2_client')
- oauth_log.addFilter(NoLoggingFilter())
-
- logging.basicConfig(level=logging_level)
diff --git a/cros_gestures/cros_gestures_options.py b/cros_gestures/cros_gestures_options.py
deleted file mode 100644
index 4f1be6b..0000000
--- a/cros_gestures/cros_gestures_options.py
+++ /dev/null
@@ -1,103 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Command line options to support cros_gestures.py.
-
-This code assembles and parses options used by commands run
-by cros_gestures.
-"""
-
-import getpass
-import optparse
-import os
-import sys
-
-import cros_gestures_commands
-import cros_gestures_utils
-
-
-color = cros_gestures_utils.Color()
-
-
-# Find the hardware_Trackpad config file - we share it with the test.
-base_dir = os.path.dirname(os.path.dirname(__file__))
-trackpad_test_dir = os.path.join('/usr/local/autotest/tests/hardware_Trackpad')
-if os.path.isdir(trackpad_test_dir):
- os.environ['TRACKPAD_TEST_DIR'] = trackpad_test_dir
-else:
- trackpad_test_dir = os.environ.get('TRACKPAD_TEST_DIR')
- if not trackpad_test_dir or not os.path.isdir(trackpad_test_dir):
- cros_gestures_utils.OutputAndExit(
- 'Unable to determine where the hardware_Trackpad test resides.'
- '\nPlease check the TRACKPAD_TEST_DIR environment variable.')
-
-sys.path.insert(0, trackpad_test_dir)
-from trackpad_util import read_trackpad_test_conf
-from trackpad_util import trackpad_test_conf
-
-
-def GetConfigOptions(current_dir):
- """Helper to retrieve config details like area and functionality."""
- found = False
- for path in [current_dir, os.environ.get('TRACKPAD_TEST_DIR')]:
- trackpad_test_conf_path = os.path.join(path, trackpad_test_conf)
- if os.path.isfile(trackpad_test_conf_path):
- found = True
- break
- if not found:
- msg = 'Unable to find config file: %s.' % trackpad_test_conf
- cros_gestures_utils.OutputAndExit(msg, red=True)
-
- # 'dir':['mix'] is a custom config entry for a handmade manifest file
- # with an area of 'mix' and a functionality of 'dir'.
- # examples: 'mix-dir.all-alex-mary_tut1-20111215_233052'
- # 'mix-dir.all-alex-user_tut1-20111215_233052'
- config_options = {'dir': ['mix']}
- for f in read_trackpad_test_conf('functionality_list', path):
- if f.name in config_options.iteritems():
- msg = ('Found a repeated functionality. Please check the conf file '
- 'in %s' % path)
- cros_gestures_utils.OutputAndExit(msg, red=True)
- config_options[f.name] = f.area
-
- return config_options
-
-
-def ParseArgs(usage, commands, admin=False):
- """Common processing of command line options."""
- base_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
-
- parser = optparse.OptionParser(usage=usage)
- parser.add_option('-d', '--debug',
- help='Show more output [default: %default]',
- dest='debugout',
- action='store_true',
- default=False)
- parser.add_option('-D', '--detailed-debug',
- help='Show even more output [default: %default]',
- dest='detaileddebugout',
- action='store_true',
- default=False)
- parser.add_option('-m', '--model',
- help='Gesture file model [default: %default]',
- dest='model',
- default=None)
- parser.add_option('-u', '--user',
- help='Gesture file owner [default: %default]',
- dest='userowner',
- default=getpass.getuser())
- config_options = GetConfigOptions(base_dir)
- cros_gestures_commands.AddOptions(parser, config_options, admin=admin)
- options, args = parser.parse_args()
- options.config_options = config_options
-
- COMMANDS_STRING = ', '.join(sorted(commands.keys()))
- if len(args) < 1 or args[0].lower() not in commands:
- msg = 'Must supply 1 command from: %s.' % COMMANDS_STRING
- cros_gestures_utils.OutputAndExit(msg, red=True)
- command = args[0].lower()
-
- return options, args[1:], command
diff --git a/cros_gestures/cros_gestures_utils.py b/cros_gestures/cros_gestures_utils.py
deleted file mode 100644
index 59fe5ba..0000000
--- a/cros_gestures/cros_gestures_utils.py
+++ /dev/null
@@ -1,240 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Utility functions for cros_gestures cli.
-
-Utility functions shared by cros_gestures, cros_gestures_options and
-cros_gestures_commands.
-"""
-
-import os
-import re
-import subprocess
-import sys
-import traceback
-
-import cros_gestures_constants
-
-
-FILE_PREFIX = 'file://'
-
-
-#------------------------------------------------------------------------------
-# Common utilities
-#------------------------------------------------------------------------------
-class Color(object):
- """Conditionally wraps text in ANSI color escape sequences."""
- BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
- BOLD = -1
- COLOR_START = '\033[1;%dm'
- BOLD_START = '\033[1m'
- RESET = '\033[0m'
-
- def __init__(self, enabled=True):
- self._enabled = enabled
-
- def Color(self, color, text):
- """Returns text with conditionally added color escape sequences.
-
- Keyword arguments:
- color: Text color -- one of the color constants defined in this class.
- text: The text to color.
-
- Returns:
- If self._enabled is False, returns the original text. If it's True,
- returns text with color escape sequences based on the value of color.
- """
- if not self._enabled:
- return text
- if color == self.BOLD:
- start = self.BOLD_START
- else:
- start = self.COLOR_START % (color + 30)
- return start + text + self.RESET
-
-
-color = Color()
-
-
-def Output(message, red=False):
- """Common error printing - used for error importing required modules."""
- if red:
- message = color.Color(Color.RED, message)
- sys.stderr.write('%s\n' % message)
-
-
-def OutputAndExit(message, red=False):
- """Common error printing - used for error importing required modules."""
- Output(message, red)
- sys.exit(1)
-
-
-#------------------------------------------------------------------------------
-# Very important but confusing import of boto library with proper .boto file
-#------------------------------------------------------------------------------
-def FindDependencies(boto_environ_var='BOTO_CONFIG'):
- """Find boto and gslib."""
- base_dir = os.path.dirname(__file__)
- gsutil_bin_dir = os.environ.get('GSUTIL_BIN_DIR', os.path.join(base_dir,
- 'gsutil'))
- if gsutil_bin_dir and os.path.isdir(gsutil_bin_dir):
- os.environ['GSUTIL_BIN_DIR'] = os.path.realpath(gsutil_bin_dir)
- else:
- OutputAndExit('Unable to determine where gsutil is installed. '
- 'Please ensure the GSUTIL_BIN_DIR environment variable is '
- 'set to the gsutil directory.\nRetrieve gsutil from '
- 'http://commondatastorage.googleapis.com/pub/gsutil.tar.gz '
- 'if you do not have it.')
- found = False
- boto_list = (os.environ.get(boto_environ_var, None),
- os.path.join(base_dir, '.boto'),
- os.path.join(base_dir, 'untrusted',
- 'chromeos.gestures.untrusted.write.boto'))
- for boto_config in boto_list:
- if boto_config and os.path.isfile(boto_config):
- os.environ['BOTO_CONFIG'] = os.path.realpath(boto_config)
- found = True
- break
- if not found:
- OutputAndExit('Unable to determine where .boto is installed. Please ensure '
- 'the %s environment variable is set to the '
- 'full path of the .boto file.\n' % boto_environ_var)
-
- # .boto enforces the trustworthiness - this is just a hint.
- if boto_config.find('untrusted') > -1:
- cros_gestures_constants.trusted = False
-
- # Before importing boto, find where gsutil is installed and include its
- # boto sub-directory at the start of the PYTHONPATH, to ensure the versions of
- # gsutil and boto stay in sync after software updates. This also allows gsutil
- # to be used without explicitly adding it to the PYTHONPATH.
- boto_lib_dir = os.path.join(gsutil_bin_dir, 'boto')
- if not os.path.isdir(boto_lib_dir):
- OutputAndExit('There is no boto library under the gsutil install directory '
- '(%s).\nThe gsutil command cannot work properly when '
- 'installed this way.\nPlease re-install gsutil per the '
- 'installation instructions.' % gsutil_bin_dir)
- sys.path.insert(0, os.path.realpath(boto_lib_dir))
-
- # Needed so that cros_gestures_commands can import from gslib/commands and for
- # oauth2 import.
- sys.path.insert(0, os.path.realpath(gsutil_bin_dir))
-
- return gsutil_bin_dir, boto_config
-
-
-#------------------------------------------------------------------------------
-# Exception handlers
-#------------------------------------------------------------------------------
-def HandleUnknownFailure(e):
- """Called if we fall through all known/handled exceptions.
- Allows us to # print a stacktrace if -D option used.
- """
- if cros_gestures_constants.debug > 2:
- stack_trace = traceback.format_exc()
- prefix = color.Color(Color.RED, 'DEBUG: Exception stack trace:')
- OutputAndExit('%s\n %s\n' % (prefix, re.sub('\\n', '\n ',
- stack_trace)))
- else:
- OutputAndExit('Failure: %s.' % e)
-
-
-def HandleCrosGesturesException(e):
- """Commonly raised exception in command line processing."""
- if e.informational:
- Output(e.reason)
- else:
- prefix = color.Color(Color.RED, 'CrosGesturesException:')
- OutputAndExit('%s %s' % (prefix, e.reason))
-
-
-def HandleControlC(signal_num, cur_stack_frame):
- """Called when user hits ^C so we can print a brief message.
- This is instead of the normal Python stack trace (unless -D option is used).
- """
- if cros_gestures_constants.debug > 2:
- stack_trace = ''.join(traceback.format_list(traceback.extract_stack()))
- prefix = color.Color(Color.RED, 'DEBUG: Caught signal %d - '
- 'Exception stack trace:' % signal_num)
- OutputAndExit('%s\n %s' % (prefix, re.sub('\\n', '\n ', stack_trace)))
- else:
- OutputAndExit('Caught signal %d - exiting' % signal_num, red=True)
-
-
-#------------------------------------------------------------------------------
-# Command validation utility functions.
-#------------------------------------------------------------------------------
-def HaveFileUris(args):
- """Checks whether args contains any file URIs."""
- for uri_str in args:
- if uri_str.lower().startswith(FILE_PREFIX) or uri_str.find(':') == -1:
- return True
- return False
-
-
-def StripFileUris(args):
- """Removes file:// from any file URIs since we prefix our file URIs."""
- new_args = []
- file_prefix_len = len(FILE_PREFIX)
- for uri_str in args:
- if uri_str.lower().startswith(FILE_PREFIX):
- new_args.append(uri_str[file_prefix_len:])
- else:
- new_args.append(uri_str)
- return new_args
-
-
-#------------------------------------------------------------------------------
-# Wrap command-line gsutil.
-#------------------------------------------------------------------------------
-def RunGSUtil(bin_dir, logger, cmd, headers=None, sub_opts=None, args=None,
- show_output=True):
- """Executes gsutil with the provided command.
-
- Args:
- bin_dir: Location of gsutil
- logger: active logger
- cmd: Command to execute: ls, cat, rm, cp, setacl, getacl, ver
- headers: send optional headers with the command
- sub_options: optional command-specific flags
- args: cmd specific args (e.g. filenames)
-
- Returns:
- Returns the returncode (0=success, nonzero=failed)
- """
- debug_options = ('', '', '-d', '-D', '-DD')
- if not headers:
- headers = ''
- else:
- headers = ' -h ' + ' -h '.join(headers)
- if not sub_opts:
- sub_opts = ''
- else:
- sub_opts = ' '.join(sub_opts)
- if args:
- args = '"' + '" "'.join(args) + '"'
- else:
- args = ''
- cmd = ('%s %s %s %s %s %s' % (os.path.join(bin_dir, 'gsutil'),
- debug_options[cros_gestures_constants.debug],
- headers, cmd, sub_opts, args)).strip()
- logger.debug('Running command "%s"', cmd)
- try:
- p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT)
- stdout, _ = p.communicate()
- if show_output:
- print stdout.strip()
- return p.returncode
- except OSError, e:
- if not show_output:
- return e.errno
- if e.errno == 2:
- OutputAndExit('File not found: %s' % args)
- OutputAndExit('OSError: (%s) %s.' % (e.errno, e.strerror))
- except Exception, e:
- HandleUnknownFailure(e)
- return 1
diff --git a/cros_gestures/exception.py b/cros_gestures/exception.py
deleted file mode 100644
index 8d04115..0000000
--- a/cros_gestures/exception.py
+++ /dev/null
@@ -1,36 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Custom exceeptions for ChromeOS Gestures command line interface.
-
-This code is modeled after and derived from the Command class in
-gsutil/gslib/command.py.
-"""
-
-class CrosGesturesException(StandardError):
- """Exception raised when a problem is encountered running a gsutil command.
-
- This exception should be used to signal user errors or system failures
- (like timeouts), not bugs (like an incorrect param value). For the
- latter you should raise Exception so we can see where/how it happened
- via gsutil -D (which will include a stack trace for raised Exceptions).
- """
- def __init__(self, reason, informational=False):
- """Instantiate a CrosGesturesException.
-
- Args:
- reason: text describing the problem.
- informational: indicates reason should be printed as FYI, not a failure.
- """
- StandardError.__init__(self)
- self.reason = reason
- self.informational = informational
-
- def __repr__(self):
- return 'CrosGesturesException: %s' % self.reason
-
- def __str__(self):
- return 'CrosGesturesException: %s' % self.reason
diff --git a/cros_gestures/remote/install_cros_gestures.py b/cros_gestures/remote/install_cros_gestures.py
deleted file mode 100755
index 48fc92e..0000000
--- a/cros_gestures/remote/install_cros_gestures.py
+++ /dev/null
@@ -1,237 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Deploy cros_gestures command line interface to test machine for usage.
-
-Deploys the command line client and dependent libraries (gsutil and boto).
-Package download/extract code loosely based on Autotest packaging utils.
-"""
-
-__author__ = 'truty@chromium.org (Mike Truty)'
-__version__ = '1.0.0'
-
-
-import logging
-import optparse
-import os
-import shutil
-import subprocess
-import sys
-import tempfile
-import urlparse
-
-
-LOG = logging.getLogger('cros_gestures')
-
-GESTURES_INSTALL_DIR = '/usr/local/cros_gestures'
-GESTURE_SERVER_URL = (
- 'http://chromeos-gestures-valid.commondatastorage.googleapis.com/'
- 'downloads/untrusted')
-GESTURE_ARCHIVE = 'cros_gestures.tar.bz2'
-
-
-class GestureInstallError(Exception):
- """The parent of all errors."""
- def __str__(self):
- return Exception.__str__(self) + _context_message(self)
-
-
-class CmdError(GestureInstallError):
- """Raised when there is an error running a command"""
-
-
-class PackageFetchError(GestureInstallError):
- """Raised when there is an error fetching the package"""
-
-
-def RunCommand(cmd, dargs=None):
- """General command execution - based on replacing os.system()."""
- try:
- cmd = [cmd]
- if dargs:
- cmd += ['--%s=%s' % (k, v) for k, v in dargs.items()]
- logging.debug('Running command (%s)', cmd)
- retcode = subprocess.call(cmd, shell=True)
- if retcode < 0:
- LOG.error('Child command (%s) was terminated by signal -%s',
- cmd, retcode)
- elif retcode > 0:
- LOG.error('Child command (%s) returned %s', cmd, retcode)
- except OSError, e:
- LOG.error('Execution failed:', str(e))
- return retcode
-
-
-class HttpFetcher(object):
- """Downloads packages from a repository."""
- wget_cmd_pattern = 'wget --connect-timeout=15 -nv "%s" -O "%s"'
-
-
- def __init__(self, repository_url):
- """
- @param repository_url: The base URL of the http repository
- """
- self.url = repository_url
-
-
- def _QuickHttpTest(self):
- """ Run a simple 30 second wget on the repository to see if it is
- reachable. This avoids the need to wait for a full 10min timeout.
- """
- # just make a temp file to write a test fetch into
- temp_file = tempfile.NamedTemporaryFile()
- dest_file_path = temp_file.name
-
- try:
- # build up a wget command
- if self.url == GESTURE_SERVER_URL:
- parts = urlparse.urlparse(self.url)
- try_url = urlparse.urlunparse([parts.scheme, parts.netloc, '',
- None, None, None])
- else:
- try_url = self.url
- http_cmd = self.wget_cmd_pattern % (try_url, dest_file_path)
- try:
- if RunCommand(http_cmd, dargs={'timeout': 30}):
- raise CmdError('Command failed')
- except Exception, e:
- msg = 'HTTP test failed, unable to contact %s: %s'
- raise PackageFetchError(msg % (try_url, e))
- finally:
- temp_file.close()
-
-
- def FetchPkgFile(self, filename, dest_path):
- logging.info('Fetching %s from %s to %s', filename, self.url,
- dest_path)
-
- # do a quick test to verify the repo is reachable
- self._QuickHttpTest()
-
- # try to retrieve the package via http
- package_url = os.path.join(self.url, filename)
- try:
- cmd = self.wget_cmd_pattern % (package_url, os.path.join(dest_path,
- filename))
- result = RunCommand(cmd)
- if result or not os.path.isfile(os.path.join(dest_path, filename)):
- logging.error('wget failed: %s', result)
- raise CmdError('%s: %s', cmd, result)
- logging.debug('Successfully fetched %s from %s', filename,
- package_url)
- except CmdError:
- # remove whatever junk was retrieved when the get failed
- RunCommand('rm -f %s/*' % dest_path)
- raise PackageFetchError('%s not found in %s' % (filename,
- package_url))
-
-
-def OutputAndExit(message):
- """Common error printing."""
- sys.stderr.write('%s\n' % message)
- sys.exit(1)
-
-
-def UntarPkg(tarball_path, dest_dir):
- """Untar the downloaded package likely a .gz or .bz2."""
- RunCommand('tar xjf "%s" -C "%s"' % (tarball_path, dest_dir))
-
-
-def VerifyInstallDirectory(force_option, path):
- """Ensure the target install directory is properly available."""
- if os.path.isdir(path):
- if not force_option:
- OutputAndExit('Directory (%s) for cros_gestures already exists. '
- 'Please use -F to override.' % path)
- LOG.debug('Removing existing cros_gestures now.')
- shutil.rmtree(path)
-
-
-def CopyPackage(repo_url, package_name, install_dir):
- """Easy copy of package if it is already present."""
- source_file_name = os.path.join(repo_url, package_name)
- target_file_name = os.path.join(install_dir, package_name)
- if os.path.isfile(source_file_name):
- shutil.copyfile(source_file_name, target_file_name)
- return not os.path.isfile(target_file_name)
-
-
-def DownloadPackage(repo_url, package_name, install_dir):
- """Download a package."""
- fetcher = HttpFetcher(repo_url)
- fetcher.FetchPkgFile(package_name, install_dir)
-
-
-def InstallPackage(source_dir, package_name, install_dir):
- """Install our downloaded package."""
- UntarPkg(os.path.join(source_dir, package_name), source_dir)
- shutil.copytree(os.path.join(source_dir, 'cros_gestures'), install_dir)
-
-
-def DownloadAndInstall(repo_url, package_name, install_dir):
- """Download and install a package."""
- temp_dir = tempfile.mkdtemp()
- try:
- if CopyPackage(repo_url, package_name, temp_dir):
- DownloadPackage(repo_url, package_name, temp_dir)
- InstallPackage(temp_dir, package_name, install_dir)
- logging.info('Installed to %s', install_dir)
- result = 0
- except PackageFetchError:
- logging.debug('%s could not be fetched from %s', package_name, repo_url)
- result = -1
- shutil.rmtree(temp_dir)
- return result
-
-
-def parse_args(argv):
- """Process command line options."""
- usage_string = (
- 'install_cros_gestures [options]\n\n'
- 'Retrieves and installs all dependent packages for the cros_gestures '
- 'developer/tester command line client tool.\n'
- 'Run install_cros_gestures -h to see options.')
- parser = optparse.OptionParser(usage=usage_string)
- parser.add_option('-F', '--force',
- help='Force install by replacing [default: %default]',
- dest='forceoverwrite',
- action='store_true',
- default=False)
- parser.add_option('-D', '--detailed-debug',
- help='Show even more output [default: %default]',
- dest='detaileddebugout',
- action='store_true',
- default=False)
- parser.add_option('-s', '--server-url',
- help='url for server downloads dir [default: %default]',
- dest='serverurl',
- default=GESTURE_SERVER_URL)
- options, args = parser.parse_args()
- if options.detaileddebugout:
- logging_level = logging.DEBUG
- else:
- logging_level = logging.INFO
- logging.basicConfig(level=logging_level)
-
- if len(args) > 0:
- OutputAndExit('No arguments are expected to be passed.\n\n%s' %
- usage_string)
-
- return options
-
-
-def main():
- """Logic of install."""
- options = parse_args(sys.argv)
-
- VerifyInstallDirectory(options.forceoverwrite, GESTURES_INSTALL_DIR)
- if DownloadAndInstall(options.serverurl, GESTURE_ARCHIVE,
- GESTURES_INSTALL_DIR):
- LOG.info('Unable to find and install %s.', GESTURE_ARCHIVE)
-
-
-if __name__ == '__main__':
- main()
diff --git a/cros_gestures/run_remote_tool b/cros_gestures/run_remote_tool
deleted file mode 100755
index 717a0d8..0000000
--- a/cros_gestures/run_remote_tool
+++ /dev/null
@@ -1,133 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Create cros_gestures command line interface package for test machines.
-
-Assemble the cros_gestures command line tool and gsutil into a package and/or
-deploy it to a remote test machine for use.
-"""
-
-__version__ = '0.9.1'
-
-
-import logging
-import optparse
-import os
-import shutil
-import subprocess
-import sys
-import tempfile
-
-import cros_gestures_utils
-
-
-color = cros_gestures_utils.Color()
-LOG = logging.getLogger('create_install_package')
-
-GESTURE_ARCHIVE = 'cros_gestures.tar.bz2'
-
-
-def RunCommand(cmd):
- """Common command execution."""
- LOG.debug('Running command (%s)', cmd)
- rc = subprocess.call(cmd, shell=True)
- if rc:
- LOG.error('Command (%s) failed!', cmd)
- sys.exit(1)
- return rc
-
-
-def CopyFilesToTempDir(argv):
- """Copy all the files in the package to a temp dir."""
- gsutil_bin_dir, boto_config = cros_gestures_utils.FindDependencies()
- LOG.debug('Using GSUTIL_BIN_DIR=%s and BOTO_CONFIG=%s.', gsutil_bin_dir,
- boto_config)
- temp_dir = tempfile.mkdtemp()
- # Copy cros_gestures
- shutil.copytree(os.path.dirname(os.path.abspath(argv[0])),
- os.path.join(temp_dir, 'cros_gestures'))
- # Copy gsutil
- shutil.copytree(os.path.abspath(gsutil_bin_dir),
- os.path.join(temp_dir, 'cros_gestures', 'gsutil'))
- # Copy .boto if trusted - otherwise untrusted one already present.
- if os.environ['BOTO_CONFIG'].find('untrusted') == -1:
- shutil.copyfile(os.path.abspath(boto_config),
- os.path.join(temp_dir, 'cros_gestures', '.boto'))
- return temp_dir
-
-
-def TarPkg(temp_dir, pkg_path, relative_file_path):
- """Create a .tar.bz2 package of the cros_gestures files."""
- cmd = 'tar -j -C "%s" -cf "%s" "%s"' % (temp_dir, pkg_path,
- relative_file_path)
- rc = RunCommand(cmd)
- shutil.rmtree(temp_dir)
- return rc
-
-
-def RemoteCopyAndInstall(remote_machine, package_path):
- """Copy package and install script then run install script."""
- warning_msg = ('Accessing test machine (%s), you may be prompted for a '
- 'test machine password.' % remote_machine)
- print color.Color(cros_gestures_utils.Color.YELLOW, warning_msg)
- RunCommand('scp -q "%s" root@%s:/tmp' % (package_path, remote_machine))
- install_script = 'install_cros_gestures.py'
- print color.Color(cros_gestures_utils.Color.YELLOW, warning_msg)
- RunCommand('scp -q "%s" root@%s:/tmp' % (os.path.join(
- os.path.dirname(package_path), 'remote', install_script), remote_machine))
- print color.Color(cros_gestures_utils.Color.YELLOW, warning_msg)
- RunCommand('ssh root@%s "/tmp/%s -s /tmp"' % (remote_machine, install_script))
-
-
-def ParseArgs(argv):
- """Process command line options."""
- base_dir = os.path.dirname(os.path.abspath(argv[0]))
- usage_string = (
- 'run_remote_tool\n\n'
- 'Creates and/or deploys a package of cros_gestures suitable for '
- 'test machine usage.')
- parser = optparse.OptionParser(usage=usage_string)
- parser.add_option('-d', '--debug',
- help='Show output [default: %default]',
- dest='debugout',
- action='store_true',
- default=False)
- parser.add_option('-p', '--package-file',
- help='cros_gestures packagea file [default: %default]',
- dest='packagefile',
- default=os.path.join(base_dir, GESTURE_ARCHIVE))
- parser.add_option('', '--remote',
- help='Deploy to remote machine [default: %default]',
- dest='remoteip',
- default=None)
- options, args = parser.parse_args()
- # Setup logging.
- if options.debugout:
- logging_level = logging.DEBUG
- else:
- logging_level = logging.INFO
- logging.basicConfig(level=logging_level)
- # Simple parameter checking.
- if len(args) > 0:
- output_and_exit('No arguments are expected to be passed.\n\n%s' %
- usage_string)
- return options, base_dir
-
-
-def main(argv):
- """Create dir and then package in it."""
- options, base_dir = ParseArgs(argv)
- if not os.path.isfile(options.packagefile):
- output_dir = CopyFilesToTempDir(argv)
- TarPkg(output_dir, options.packagefile, 'cros_gestures')
- print '%s created.' % options.packagefile
- if options.remoteip:
- RemoteCopyAndInstall(options.remoteip, options.packagefile)
- print 'Deployed to %s.' % options.remoteip
-
-
-if __name__ == '__main__':
- main(sys.argv)
diff --git a/cros_gestures/setup_cros_gestures.sh b/cros_gestures/setup_cros_gestures.sh
deleted file mode 100755
index 6c4fd4f..0000000
--- a/cros_gestures/setup_cros_gestures.sh
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/bin/bash
-
-# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# Script to setup environment variables so that cros_gestures cli can
-# find .boto files for authentication and related gsutil files.
-
-declare SCRIPT_DIR="$(pwd)"
-declare GSUTIL_BASE="$HOME/gsutil"
-declare SRC_BASE="$HOME/cros"
-declare TESTBOTO=\
-"${SRC_BASE}/src/third_party/autotest-private/cros_gestures_boto"
-declare AUTOTEST_SRC="${SRC_BASE}/src/third_party/autotest/files"
-
-check_and_set_var() {
- local var_name=$1
- local var_value=$2
- local dir_or_file=$3
- if [[ ${dir_or_file} == dir && -d "${var_value}" ]] || \
- [[ ${dir_or_file} == file && -f "${var_value}" ]]; then
- echo Setting ${var_name}
- export ${var_name}="${var_value}"
- echo -e "\tto ${var_value}."
- fi
-}
-
-clear_vars() {
- for v in BOTO_CONFIG BOTO_VALIDATE_CONFIG GSUTIL_BIN_DIR TRACKPAD_TEST_DIR
- do
- unset $v
- done
-}
-
-echo ---------------------------------------------------------------------
-clear_vars
-if [[ $1 == trusted ]]; then
- echo "---Setting TRUSTED values"
- check_and_set_var BOTO_CONFIG \
- ${TESTBOTO}/trusted_dev/chromeos.gestures.trusted.write.boto file
- check_and_set_var BOTO_VALIDATE_CONFIG \
- ${TESTBOTO}/validator/chromeos.gestures.full.boto file
-else
- echo "---Setting UNTRUSTED values"
- check_and_set_var BOTO_CONFIG \
- ${SCRIPT_DIR}/untrusted/chromeos.gestures.untrusted.write.boto file
-fi
-
-check_and_set_var GSUTIL_BIN_DIR ${GSUTIL_BASE} dir
-check_and_set_var TRACKPAD_TEST_DIR \
- ${AUTOTEST_SRC}/client/site_tests/hardware_Trackpad dir
-
-echo Done.
-echo ---------------------------------------------------------------------
-echo "Do not forget to run this as . ./setup_cros_gestures.sh"
-echo ---------------------------------------------------------------------
diff --git a/cros_gestures/untrusted/chromeos.gestures.untrusted.write.boto b/cros_gestures/untrusted/chromeos.gestures.untrusted.write.boto
deleted file mode 100644
index 1ce3481..0000000
--- a/cros_gestures/untrusted/chromeos.gestures.untrusted.write.boto
+++ /dev/null
@@ -1,49 +0,0 @@
-# This file contains credentials and other configuration information needed
-# by the boto library, used by gsutil. You can edit this file (e.g., to add
-# credentials) but be careful not to mis-edit any of the variable names (like
-# "gs_access_key_id") or remove important markers (like the "[Credentials]" and
-# "[Boto]" section delimeters).
-#
-# This file was created by gsutil version "2011-09-06 15:34:49-07:00"
-# at 2011-09-27 14:43:20.
-#
-# You can create additional configuration files by running
-# gsutil config [options] [-o <config-file>]
-
-
-[Credentials]
-
-# Google OAuth2 credentials (for "gs://" URIs):
-# The following OAuth2 token is authorized for scope(s):
-# https://www.googleapis.com/auth/devstorage.read_write
-gs_oauth2_refresh_token = 1/7hB6K3lhWIqB04Sqjp-xWJPNBNYq370V96pwEFjTx9g
-
-
-[Boto]
-
-# Set 'https_validate_certificates' to False to disable server certificate
-# checking. This is useful if you want to capture/analyze traffic using an
-# intercepting proxy. This option should always be set to True in production
-# environments.
-# In gsutil, the default for this option is True. *However*, the default for
-# this option in the boto library itself is currently 'False'; it is therefore
-# recommended to always set this option explicitly to True in configuration
-# files.
-https_validate_certificates = True
-
-
-[GSUtil]
-
-# 'default_api_version' specifies the default Google Storage API version to
-# use use. If not set below gsutil defaults to API version 1.
-default_api_version = 2
-
-# 'default_project_id' specifies the default Google Storage project ID to use
-# with the 'mb' and 'ls' commands. If defined it overrides the default value
-# you set in the API Console. Either of these defaults can be overridden
-# by specifying the -p option to the 'mb' and 'ls' commands.
-default_project_id = 449962335547
-
-
-[OAuth2]
-# This section specifies options used with OAuth2 authentication.