Commits

mickael9 committed f244e96

- Added list command
- Code cleanup

Comments (0)

Files changed (2)

 
 url_re = re.compile(r'^(?:http://ge\.tt/|/)?(\w+)(?:/(?:v/(\d+)))?$')
 
-signal.signal(signal.SIGINT, signal.SIG_DFL)
+def humanize(nbytes):
+    for (exp, unit) in ((9, 'GB'), (6, 'MB'), (3, 'KB')):
+       if nbytes >= 10**exp:
+           return '%.2f %s' % (nbytes / 10**exp, unit)
 
-home = os.getenv('USERPROFILE') or os.getenv('HOME')
+    return '%.2f B' % nbytes
 
-parser = argparse.ArgumentParser(description="A simple ge.tt uploader")
-parser.add_argument('file', nargs='*', type=argparse.FileType('rb'), help="Name of a file to upload")
-parser.add_argument('-t', dest='title', help='Title of the share (defaults to first file name)')
-parser.add_argument('-s', dest='share', help='Name of the share to upload to (defaults to a newly created one)')
-parser.add_argument('-D', dest='debug', action='store_true', help='Debug API calls')
-parser.add_argument('-S', dest='seq', action='store_true', help='Force sequential upload of files in order (by default, files are uploaded in parallel although the progress bars are displayed in ascending file size order)')
-
-parser.add_argument('--delete', nargs=1, dest='share_or_file', help='Delete a share or a file (url or path)')
-
-auth_group = parser.add_argument_group('Authentification (optional)')
-auth_group.add_argument('-e', dest='email', help='Email to login with')
-auth_group.add_argument('-p', dest='password', help='Password to login with')
-auth_group.add_argument('-k', dest='tokenfile', help='Ge.tt token file path (~/.gett-token)', default=os.path.join(home, '.gett-token'))
-
-args = parser.parse_args()
-
-if args.debug:
-    import gett
-    gett.DEBUG = True
-
-user = User()
-try:
-    # Try to log-in with the token
-
-    token = open(args.tokenfile, 'r').read()
-    user.login_token(token)
-except:
-    # If it doesn't work, ask the user its email and password
-
-    if not args.email:
-        args.email = input('Please enter your Ge.tt email: ')
-
-    if not args.password:
-        import getpass
-        args.password = getpass.getpass('Please enter your Ge.tt password: ')
-
-    try:
-        user.login_auth(args.email, args.password)
-    except Exception as ex:
-        print('Unable to login: %s' % ex.args[0])
-        sys.exit(1)
-
-with open(args.tokenfile, 'w') as file:
-    file.write(user.rtoken)
-
-if not args.share_or_file:
-    args.share_or_file = []
-
-for item in args.share_or_file:
-    match = url_re.match(item)
-
-    if not match:
-        parser.error('argument --delete: invalid format, please supply file/share url or path')
-
-    share = user.get_share(match.group(1))
-
-    if match.group(2):
-        id = match.group(2)
-        file = share.files[id]
-        file.destroy()
-    else:
-        share.destroy()
-
-if args.file:
-    if args.share:
-        share = user.get_share(args.share)
-    else:
-        if args.title:
-            share = user.create_share(args.title)
-        else:
-            share = user.create_share(os.path.basename(args.file[0].name))
-
-
-    uploads = []
-
-    for fp in args.file:
-        name = os.path.basename(fp.name)
-        file = share.create_file(name)
-
-        print('%s: %s' % (name, file.url))
-
-        upload = FileUpload(file, fp)
-
-        if not args.seq:
-            upload.start()
-
-        uploads.append(upload)
-
-    print()
-
-    if not args.seq:
-        uploads.sort(key=lambda item: item.file_size)
-
-    def print_status(upload, index, count):
+def print_status(upload, index, count):
         name = upload.file.name
 
         if len(name) > 15:
 
         sys.stderr.write('\r%s (%d/%d) %s %d %%' % (name, index, count, bar, upload.percent_done))
 
-    for i, upload in enumerate(uploads):
-        if args.seq:
-            upload.start()
+def show_share(share):
+    print('Share %s : %d file(s)' % (share.name, len(share.files)))
 
-        while True:
-            print_status(upload, i + 1, len(uploads))
-            upload.join(0.5)
+    for file in share.files.values():
+        size = ''
+        if file.size is not None:
+            size = '[%s]' % humanize(file.size)
 
-            if not upload.is_alive():
+        print('--- %-20s %s [%s]' % (file.name, size, file.url))
+    print()
+
+
+def main():
+    signal.signal(signal.SIGINT, signal.SIG_DFL)
+
+    home = os.getenv('USERPROFILE') or os.getenv('HOME')
+
+    parser = argparse.ArgumentParser(description="A command-line Ge.tt uploader and manager")
+    parser.add_argument('-D', dest='debug', action='store_true', help='Debug API calls')
+
+    upload_group = parser.add_argument_group('Upload options')
+    upload_group.add_argument('file', nargs='*', type=argparse.FileType('rb'), help="Name of a file to upload")
+    upload_group.add_argument('-t', dest='title', help='Title of the share (defaults to first file name)')
+    upload_group.add_argument('-s', dest='share', help='Name or URL of the share to upload to (defaults to a newly created one)')
+    upload_group.add_argument('-S', dest='sequential_upload', action='store_true', help='Force sequential upload of files in order (by default, files are uploaded in parallel although the progress bars are displayed in ascending file size order)')
+
+    other_group = parser.add_argument_group('Other actions')
+    other_group.add_argument('--delete', nargs='+', dest='delete', metavar='SHARE_OR_FILE', help='Delete a share or a file (url or path)')
+    other_group.add_argument('--list', nargs='*', dest='list', metavar='SHARE_NAME', help='List the files in the specified share. If no share is specified, list all your shares.')
+
+    auth_group = parser.add_argument_group('Authentification')
+    auth_group.add_argument('-e', dest='email', help='Email to login with')
+    auth_group.add_argument('-p', dest='password', help='Password to login with')
+    auth_group.add_argument('-k', dest='tokenfile', help='Ge.tt token file path (~/.gett-token)', default=os.path.join(home, '.gett-token'))
+
+    args = parser.parse_args()
+
+    if args.debug:
+        import gett
+        gett.DEBUG = True
+
+    user = User()
+
+    try:
+        # Try to log-in with the token
+
+        token = open(args.tokenfile, 'r').read()
+        user.login_token(token)
+    except:
+        # If it doesn't work, ask the user his email and password
+
+        if not args.email:
+            args.email = input('Please enter your Ge.tt email: ')
+
+        if not args.password:
+            import getpass
+            args.password = getpass.getpass('Please enter your Ge.tt password: ')
+
+        try:
+            user.login_auth(args.email, args.password)
+        except Exception as ex:
+            print('Unable to login: %s' % ex.args[0])
+            sys.exit(1)
+
+    # Save the refreshtoken to the user's home directory
+
+    with open(args.tokenfile, 'w') as file:
+        file.write(user.rtoken)
+
+
+    # --list command
+
+    if args.list is not None:
+        for name in args.list:
+            share = Share(name)
+            show_share(share)
+
+        if not args.list:
+            for share in user.list_shares():
+                show_share(share)
+
+    # --delete command
+
+    if args.delete:
+        for item in args.delete:
+            match = url_re.match(item)
+
+            if not match:
+                parser.error('argument --delete: invalid format, please supply either file/share url or path')
+
+            share = user.get_share(match.group(1))
+
+            if match.group(2):
+                id = match.group(2)
+                file = share.files[id]
+                file.destroy()
+
+                print('Deleted file %s [%s]' % (file.name, file.url))
+            else:
+                print('Deleted share %s' % share.name)
+                share.destroy()
+
+    # File uploads
+
+    if args.file:
+        if args.share:
+            # Upload to existing share
+
+            match = url_re.match(args.share)
+
+            if match:
+                share = user.get_share(match.group(1))
+            else:
+                parser.error('argument --list: invalid share name, please supply either URL or name')
+        else:
+            # Upload to a new share
+
+            if args.title:
+                share = user.create_share(args.title)
+            else:
+                share = user.create_share(os.path.basename(args.file[0].name))
+
+        uploads = []
+
+        # Create the file URLs
+
+        for fp in args.file:
+            name = os.path.basename(fp.name)
+            file = share.create_file(name)
+
+            print('%s: %s' % (name, file.url))
+
+            upload = FileUpload(file, fp)
+
+            if not args.sequential_upload:
+                upload.start()
+
+            uploads.append(upload)
+
+        print()
+
+        if not args.sequential_upload:
+            uploads.sort(key=lambda item: item.file_size)
+
+        for i, upload in enumerate(uploads):
+            if args.sequential_upload:
+                upload.start()
+
+            while True:
                 print_status(upload, i + 1, len(uploads))
+                upload.join(0.5)
 
-                if upload.ex:
-                    sys.stderr.write(('\rError uploading %s: %s' % (upload.file.name, upload.ex)).ljust(80))
+                if not upload.is_alive():
+                    print_status(upload, i + 1, len(uploads))
 
-                sys.stderr.write('\n')
-                break
+                    if upload.ex:
+                        sys.stderr.write(('\rError uploading %s: %s' % (upload.file.name, upload.ex)).ljust(80))
 
-user.refresh()
+                    sys.stderr.write('\n')
+                    break
 
-def humanize(nbytes):
-    for (exp, unit) in ((9, 'GB'), (6, 'MB'), (3, 'KB')):
-       if nbytes >= 10**exp:
-           return '%.2f %s' % (nbytes / 10**exp, unit)
+    user.refresh()
 
-    return '%.2f B' % nbytes
+    print('Storage used : %s out of %s (%d %%)' % (
+            humanize(user.storage_used),
+            humanize(user.storage_limit),
+            int(100 * user.storage_used / user.storage_limit)))
 
 
-print('Storage used : %s out of %s (%d %%)' % (
-        humanize(user.storage_used),
-        humanize(user.storage_limit),
-        int(100 * user.storage_used / user.storage_limit)))
+if __name__ == '__main__':
+    main()
+
 
 setup(name='Ge.tt uploader',
       version='0.0',
-      description='A command-line uploader for Ge.tt',
+      description='A command-line Ge.tt uploader and manager',
       author='Mickaël THOMAS',
       author_email='mickael9@gmail.com',
       url='https://bitbucket.org/mickael9/gett-cli/',
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.