示例#1
0
def main():
    """Main function."""
    parser = argparse.ArgumentParser(
        description=__doc__.strip(),
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('docid', action='store', help="Kix doc id to update")
    parser.add_argument('mapping_json',
                        nargs='?',
                        action='store',
                        help="Path to JSON list of pairs to replace")
    parser.add_argument(
        '--dry-run',
        '-n',
        action='store_true',
        help="Only print the existing links and replacments, do not run.")
    args = parser.parse_args()

    # Parse out the doc id, in case the user provided a full URL.
    if args.docid:
        match = re.match('https://docs.google.com/document/d/([^/]+)(/|$)',
                         args.docid)
        if match:
            args.docid = match.group(1)

    # Read a file of mappings to apply in JSON format. See docstring.
    if args.mapping_json:
        with open(args.mapping_json) as mapfile:
            mapping = json.load(mapfile)
    else:
        mapping = {}

    # Discover the service.
    creds = gapis.get_credentials(
        ['https://www.googleapis.com/auth/documents'], 'beancount-docs')
    service = discovery.build('docs', 'v1', credentials=creds)

    transform_links(service, args.docid, mapping, args.dry_run)
示例#2
0
def _main():
    parser = argparse.ArgumentParser(
        description=__doc__.strip(),
        formatter_class=argparse.RawTextHelpFormatter)

    parser.add_argument(
        'filenames',
        nargs='*',
        action='store',
        help=("CSV filenames[:name] to upload. "
              "If 'name' is not provided, infer from the filename."))

    parser.add_argument('--docid',
                        '--doc',
                        '--id',
                        '-d',
                        dest='docid',
                        action='store',
                        help="Spreadsheets doc id to update")

    parser.add_argument('--title',
                        '-t',
                        action='store',
                        dest='doctitle',
                        help="Set or update the spreadsheet's title")

    parser.add_argument('--verbose',
                        '-v',
                        action='store_true',
                        help="Print out the log")

    parser.add_argument(
        '--min-rows',
        action='store',
        type=int,
        default=0,
        help=("Minimum number rows to resize uploaded sheet to. "
              "This is useful when another sheet feeds from the uploaded "
              "one, which otherwise automatically renumbers its "
              "references to rows beyond it if they existed, to avoid "
              "most such resizing woes."))

    args = parser.parse_args()

    logging.basicConfig(
        level=logging.INFO if args.verbose else logging.WARNING,
        format='%(levelname)-8s: %(message)s')

    # Parse out the doc id, in case the user provided a full URL.
    if args.docid:
        match = re.match('https://docs.google.com/spreadsheets/d/([^/]+)(/|$)',
                         args.docid)
        if match:
            args.docid = match.group(1)

    # Discover the service.
    creds = gapis.get_credentials(
        ['https://www.googleapis.com/auth/spreadsheets'], 'upload-to-sheets')
    service = discovery.build('sheets', 'v4', credentials=creds)

    # Figure out what the name mappings should be, from the filenames (or
    # explicitly).
    new_sheets = []
    for filename in args.filenames:
        match = re.match('(.*):(.*)$', filename)
        if match:
            sheet_name, filename = (match.group(1), match.group(2))
            # Support inverted sheets name labels.
            if not path.exists(filename) and path.exists(sheet_name):
                sheet_name, filename = filename, sheet_name
        else:
            sheet_name = path.splitext(path.basename(filename))[0]
        new_sheets.append((sheet_name, filename))
    logging.info("Sheets to create or update: %s", new_sheets)

    # Get or create the spreadsheet.
    if args.docid:
        created = False
        docid = args.docid
    else:
        created = True
        docid = create_doc(service)
        logging.info("Created doc: https://docs.google.com/spreadsheets/d/%s/",
                     docid)

    match_names_and_upload_sheets(service, docid, new_sheets, args.min_rows)

    # Clean up temporary sheets created for new documents only.
    doc = Doc(service, docid, args.min_rows)
    if created:
        doc.delete_empty_sheets()

    # Set the document title (if requested).
    if args.doctitle:
        doc.set_title(args.doctitle)

    print("https://docs.google.com/spreadsheets/d/{}/".format(docid))
示例#3
0
def main():
    logging.basicConfig(level=logging.INFO,
                        format='%(levelname)-8s: %(message)s')
    parser = argparse.ArgumentParser(description=__doc__.strip())

    parser.add_argument('docid',
                        action='store',
                        help="Google Sheets document id")

    parser.add_argument(
        'inflows_account',
        action='store',
        help="Inflows account to use for the rewritten transactions")

    parser.add_argument('--sheet',
                        dest='sheet_re',
                        action='store',
                        help="Google Sheets sheets name regexp")

    parser.add_argument('--uncategorized_account',
                        action='store',
                        default='Expenses:Uncategorized',
                        help="Name of uncategorized account if missing")

    parser.add_argument('-t',
                        '--tag',
                        action='store',
                        help="Tag all entries with the given tag string")

    args = parser.parse_args()

    _, http = gapis.get_credentials(
        'https://www.googleapis.com/auth/spreadsheets', 'extract-sheets')
    url = 'https://sheets.googleapis.com/$discovery/rest?version=v4'
    service = discovery.build('sheets',
                              'v4',
                              http=http,
                              discoveryServiceUrl=url)

    # Select the sheet.
    sheet = select_sheet(service, args.docid, args.sheet_re)
    logging.info("Selected sheet: {.name}".format(sheet))

    # Read contents and categorize them.
    rows = list(iter_sheet(service, sheet))
    coltypes = infer_columns(rows)

    rowiter = iter(rows)
    next(rowiter)
    entries = []
    for index, row in enumerate(rowiter):
        if not list(filter(None, row)):
            continue
        entry = create_entry(row, coltypes, args.inflows_account, 'USD',
                             args.docid, index, args.uncategorized_account)
        if entry is not None:
            entries.append(entry)

    if args.tag:
        print('pushtag #{}'.format(args.tag))
        print()
    printer.print_entries(entries, file=sys.stdout)
    if args.tag:
        print()
        print('poptag #{}'.format(args.tag))