cli.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 
4 import os
5 import shlex
6 import subprocess
7 import sys
8 
9 import click
10 from jsk_tools.cltool import percol_select
11 
12 from jsk_data.gdrive import delete_gdrive
13 from jsk_data.gdrive import download_gdrive
14 from jsk_data.gdrive import info_gdrive
15 from jsk_data.gdrive import list_gdrive
16 from jsk_data.gdrive import open_gdrive
17 from jsk_data.gdrive import upload_gdrive
18 from jsk_data.ssh import connect_ssh
19 from jsk_data.ssh import get_user_by_hostname
20 from jsk_data.util import filename_with_timestamp
21 from jsk_data.util import google_drive_file_url
22 
23 
24 __all__ = ('cli', 'cmd_get', 'cmd_ls', 'cmd_put', 'cmd_pubinfo')
25 
26 
27 def _get_login_user(host):
28  username = get_user_by_hostname(host)
29  username = username or os.environ.get('SSH_USER')
30  username = username or os.environ['USER']
31  return username
32 
33 
34 HOST = 'aries.jsk.t.u-tokyo.ac.jp'
35 DATA_DIR = '/home/jsk/ros/data'
36 LOGIN_USER = _get_login_user(host=HOST)
37 
38 
39 CONTEXT_SETTINGS = dict(
40  help_option_names=['-h', '--help'],
41 )
42 
43 
44 @click.group(context_settings=CONTEXT_SETTINGS)
45 def cli():
46  pass
47 
48 
49 @cli.command(name='get', help='Download specified file.')
50 @click.option('-p', '--public', is_flag=True, help='Handle public files.')
51 @click.argument('query', default='')
52 def cmd_get(public, query):
53  """Download specified file."""
54  if not query:
55  if public:
56  lines = list_gdrive().splitlines()
57  candidates = [l.split()[1] for l in lines]
58  else:
59  candidates = _list_aries_files()
60  selected = percol_select(candidates)
61  if len(selected) != 1:
62  sys.stderr.write('Please select 1 filename.\n')
63  sys.exit(1)
64  query = selected[0]
65  sys.stderr.write('Selected: {0}\n'.format(query))
66 
67  if public:
68  download_gdrive(filename=query)
69  else:
70  cmd = 'rsync -avz --progress -e "ssh -o StrictHostKeyChecking=no"\
71  --bwlimit=100000 {usr}@{host}:{dir}/private/{q} .'
72  cmd = cmd.format(usr=LOGIN_USER, host=HOST, dir=DATA_DIR, q=query)
73  subprocess.call(shlex.split(cmd))
74 
75 
76 def _list_aries_files(query=None, ls_options=None):
77  query = query or ''
78  ls_options = ls_options or []
79  with connect_ssh(HOST, LOGIN_USER) as ssh:
80  cmd = 'ls {opt} {dir}/private/{q}'
81  cmd = cmd.format(opt=' '.join(ls_options), dir=DATA_DIR, q=query)
82  _, stdout, _ = ssh.exec_command(cmd)
83  files = stdout.read().splitlines()
84  return files
85 
86 
87 @cli.command(name='ls', help='Get list of files.')
88 @click.option('-p', '--public', is_flag=True, help='Handle public files.')
89 @click.argument('query', required=False)
90 @click.option('-s', '--show-size', is_flag=True, help='Display size.')
91 @click.option('--sort', help='Sort by ..',
92  type=click.Choice(['time', 'size', 'extension', 'version']))
93 @click.option('-r', '--reverse', is_flag=True, help='Reverse the order.')
94 def cmd_ls(public, query, show_size, sort, reverse):
95  """Get list of files."""
96  if query is None:
97  query = ''
98 
99  ls_options = []
100  if show_size:
101  ls_options.append('--size')
102  ls_options.append('--human-readable')
103  if sort is not None:
104  ls_options.append('--sort={0}'.format(sort))
105  if reverse:
106  ls_options.append('--reverse')
107 
108  if public:
109  if ls_options:
110  sys.stderr.write(
111  'WARNING: if public=True, ignores all ls options\n')
112  sys.stdout.write(list_gdrive())
113  else:
114  print('\n'.join(_list_aries_files(query, ls_options)))
115 
116 
117 @cli.command(name='put', help='Upload file to aries.')
118 @click.argument('filename', required=True, type=click.Path(exists=True))
119 @click.option(
120  '-p', '--public', is_flag=True,
121  help=('Handle public files. It will be uploaded to Google Drive. '
122  'Go https://drive.google.com/open?id=0B9P1L--7Wd2vUGplQkVLTFBWcFE'))
123 @click.option(
124  '--stamped', is_flag=True,
125  help='Rename file to with prefix of timestamp')
126 def cmd_put(filename, public, stamped):
127  """Upload file to aries."""
128  if stamped:
129  filename_org = filename
130  filename = filename_with_timestamp(filename)
131  if filename_org != filename:
132  print('Filename is being changed: {0} -> {1}'
133  .format(filename_org, filename))
134  yn = raw_input('Are you sure?[Y/n]: ')
135  if yn not in 'yY':
136  sys.stderr.write('Aborted!')
137  sys.exit(1)
138  os.rename(filename_org, filename)
139 
140  if public:
141  print('Uploading to Google Drive...')
142  stdout = upload_gdrive(filename)
143  for line in stdout.splitlines():
144  if line.startswith('Title:'):
145  filename = line.split(' ')[-1].strip()
146  elif line.startswith('Id:'):
147  file_id = line.split(' ')[-1].strip()
148  print('Done.')
149  print('You can download it by:')
150  dl_url = google_drive_file_url(file_id, download=True)
151  print('$ wget {url} -O {file}'.format(url=dl_url, file=filename))
152  else:
153  print('Uploading to aries...')
154  cmd = 'rsync -avz --progress -e "ssh -o StrictHostKeyChecking=no"\
155  --bwlimit=100000 {file} {usr}@{host}:{dir}/private/'
156  cmd = cmd.format(file=filename, usr=LOGIN_USER, host=HOST,
157  dir=DATA_DIR)
158  subprocess.call(shlex.split(cmd))
159  print('Done.')
160 
161 
162 @cli.command(name='pubinfo', help='Show public data info.')
163 @click.argument('filename', default='')
164 @click.option('-d', '--download-cmd', 'show_dl_cmd', is_flag=True,
165  help='Print out download command')
166 def cmd_pubinfo(filename, show_dl_cmd):
167  if not filename:
168  candidates = list_gdrive().splitlines()
169  selected = percol_select(candidates)
170  if len(selected) != 1:
171  sys.stderr.write('Please select 1 filename.\n')
172  sys.exit(1)
173  filename = selected[0].split()[1]
174 
175  # FIXME: gdrive does not return full title if it is longer than 40
176  if len(filename) > 40:
177  filename = filename[:19] + '...' + filename[-18:]
178 
179  stdout = list_gdrive()
180  for line in stdout.splitlines():
181  file_id, title = line.split()[:2]
182  if filename == title:
183  filename = info_gdrive(id=file_id, only_filename=True)
184  break
185  else:
186  sys.stderr.write('file not found: {0}\n'.format(filename))
187  sys.stderr.write('Run `jsk_data ls --public` to find files.\n')
188  return
189 
190  dl_url = google_drive_file_url(file_id, download=True)
191  if show_dl_cmd:
192  info = 'wget {url} -O {file}'.format(url=dl_url, file=filename)
193  sys.stdout.write(info) # no new line for copy with pipe
194  else:
195  view_url = google_drive_file_url(file_id)
196  info = '''\
197 Id: {id}
198 Filename: {file}
199 View URL: {view_url}
200 Download URL: {dl_url}'''.format(id=file_id, file=filename,
201  view_url=view_url, dl_url=dl_url)
202  print(info)
203 
204 
205 @cli.command(name='delete', help='Delete specified file.')
206 @click.option('-p', '--public', is_flag=True, help='Handle public files.')
207 @click.argument('filename', default='')
208 def cmd_delete(public, filename):
209  """Delete specified file."""
210  if not public:
211  sys.stderr.write('ERROR: public=False is not supported\n')
212  sys.exit(1)
213 
214  if not filename:
215  # FIXME: gdrive does not return full title if it is longer than 40
216  candidates = list_gdrive().splitlines()
217  selected = percol_select(candidates)
218  if len(selected) != 1:
219  sys.stderr.write('Please select 1 filename.\n')
220  sys.exit(1)
221  filename = selected[0].split()[1]
222 
223  delete_gdrive(filename=filename)
224 
225 
226 @cli.command(name='pubopen', help='Go to see files on browser')
228  open_gdrive()
def connect_ssh(host, username=None, password=None)
Definition: ssh.py:10
def cmd_pubopen()
Definition: cli.py:227
def _list_aries_files(query=None, ls_options=None)
Definition: cli.py:76
def cli()
Definition: cli.py:45
def list_gdrive()
Definition: gdrive.py:47
def open_gdrive()
Definition: gdrive.py:15
def cmd_ls(public, query, show_size, sort, reverse)
Definition: cli.py:94
def filename_with_timestamp(filename, sep=None)
Definition: util.py:8
def cmd_delete(public, filename)
Definition: cli.py:208
def cmd_put(filename, public, stamped)
Definition: cli.py:126
def info_gdrive(id, only_filename=False)
Definition: gdrive.py:53
def delete_gdrive(filename)
Definition: gdrive.py:95
def cmd_pubinfo(filename, show_dl_cmd)
Definition: cli.py:166
def google_drive_file_url(id, download=False)
Definition: util.py:31
def _get_login_user(host)
Definition: cli.py:27
def get_user_by_hostname(hostname)
Definition: ssh.py:25
def download_gdrive(filename)
Definition: gdrive.py:88
def cmd_get(public, query)
Definition: cli.py:52
def upload_gdrive(filename)
Definition: gdrive.py:68


jsk_data
Author(s):
autogenerated on Tue Feb 6 2018 03:45:36