manniru
12/6/2016 - 1:55 AM

Import & Export Script For Google Apps Script

Import & Export Script For Google Apps Script

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import json
import requests
import pprint
import warnings
warnings.filterwarnings('ignore', category=requests.packages.urllib3.exceptions.InsecurePlatformWarning)

import argparse


# create the top-level parser
parser = argparse.ArgumentParser(description='Google Apps Script ExImporter')
parser.add_argument('--token', required=True)
parser.add_argument('-d', dest='debug', action='store_true', help='debug')

subparsers = parser.add_subparsers(dest='command')

# list projects
parser_im = subparsers.add_parser('list')

# import
parser_im = subparsers.add_parser('import')
parser_im.add_argument('project')
parser_im.add_argument('directory')
parser_im.add_argument('--exported-file', required=False)

# export
parser_ex = subparsers.add_parser('export')
parser_ex.add_argument('project')
parser_ex.add_argument('file')

options = parser.parse_args()

if options.debug:
    print options


def request_get(url, headers, timeout=10):
    s = requests.Session()
    req = requests.Request(
        'GET',
        url,
        headers=headers if headers else dict(),
    )

    return s.send(
        req.prepare(),
        timeout=timeout,
    )


def request_put(url, headers, data, timeout=10):
    s = requests.Session()
    req = requests.Request(
        'PUT',
        url,
        data=data,
        headers=headers if headers else dict(),
    )

    return s.send(
        req.prepare(),
        timeout=timeout,
    )


def list_projects(token):
    url = 'https://www.googleapis.com/drive/v2/files?q=mimeType%3D\'application%2Fvnd.google-apps.script\'+and+\'me\'+in+owners'

    resp = request_get(
        url,
        headers={
            'Authorization': 'Bearer %s' % token,
        },
    )

    if resp.status_code not in (200,):
        print '[ee] failed to get list: %s' % resp.text
        sys.exit(1)

    projects = dict()
    data = json.loads(resp.text)
    for i in data.get('items'):
        print '>', i.get('title')
        print '  id: %s: ' % i.get('id')
        print 'link: %s' % i.get('selfLink')
        projects[i.get('title')] = i

    return projects


def get_project(project, token):
    projects = list_projects(token)

    if options.debug:
        print 'current projects'
        pprint.pprint(projects)

    project = project.decode('utf-8')
    if project not in projects:
        print '[ee] project not found: `%s`' % project
        sys.exit(1)

    return projects.get(project)


def export_project(project, token, filename=None):
    project = get_project(project, token)

    url = 'https://script.google.com/feeds/download/export?id=%(id)s&format=json'
    resp = request_get(
        url % project,
        headers={
            'Authorization': 'Bearer %s' % token,
        },
    )

    # save file
    if resp.status_code not in (200,):
        print '[ee] failed to export project: %s' % resp.text
        sys.exit(1)

    content = json.loads(resp.text),
    if not filename:
        return content

    with file(filename, 'wb') as f:
        json.dump(
            content,
            f,
            indent=2,
        )

    print 'exported to `%s`' % filename

    return


def import_project(project, token, directory, exported=None):
    if not os.path.exists(directory):
        print '[ee] file not found, `%s`' % directory
        sys.exit(1)

    if not exported:
        exported = export_project(project, token)
    else:
        exported = json.loads(file(exported).read())

    print 'current exported file are: %s' % exported

    file_ids = dict()
    if len(exported) > 0:
        for i in exported[0].get('files'):
            file_ids[i.get('name')] = i.get('id')

    files = list()
    for i in os.listdir(directory):
        name, ext = os.path.splitext(i)
        if ext not in ('.gs', '.html'):
            continue

        if ext in ('.gs',):
            file_type = 'server_js'
        elif ext in ('.html'):
            file_type = 'html'
        else:
            print '[ee] unknown file, `%s`' % i
            sys.exit(1)

        f = dict(
            source=file(os.path.join(directory, i)).read(),
            type=file_type,
            name=name,
        )
        if name in file_ids:
            f['id'] = file_ids.get(name)

        files.append(f)

    project = get_project(project, token)

    url = 'https://www.googleapis.com/upload/drive/v2/files/%(id)s'

    resp = request_put(
        url % project,
        data=json.dumps(dict(files=files)),
        headers={
            'Authorization': 'Bearer %s' % token,
            'Content-Type': 'application/vnd.google-apps.script+json',
        },
    )

    if resp.status_code not in (200,):
        print '[ee] failed to export project: %s' % resp.text
        sys.exit(1)

    print 'imported.'

    return


if options.command == 'list':
    pprint.pprint(list_projects(options.token))
elif options.command == 'export':
    export_project(options.project, options.token, options.file)
elif options.command == 'import':
    import_project(options.project, options.token, options.directory, exported=options.exported_file)


sys.exit(0)

Export & Import Google Apps Script

How To Use

Get the OAuth token

  1. Open OAuth 2.0 Playground
  2. Set the valid scopes, select all the scopes in Drive API
  3. Follow the steps
  4. Get the Access Token

Run

eximport_for_google_apps_script.py  -h
usage: eximport_for_google_apps_script.py [-h] --token TOKEN [-d]
                                          {list,import,export} ...

Google Apps Script ExImporter

positional arguments:
  {list,import,export}

optional arguments:
  -h, --help            show this help message and exit
  --token TOKEN
  -d                    debug
$ eximport_for_google_apps_script.py  --token ya29.eAFmrNSqR32D5ISbJ_YlnsZzjU8AUUmaI-G9H5NBr1i3EyFasfxR9tM1QD7JolCEsNxhhyTT8TkQiQ list