1# Copyright 2017 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""This module contains Google Storage utilities.
6
7TODO(ayatane): This should be merged into chromite.lib.gs
8"""
9
10import re
11
12# See https://cloud.google.com/storage/docs/bucket-naming#objectnames
13# Banned characters: []*?#
14# and control characters (hex): 00-1f, 7f-84, 86-ff
15_INVALID_GS_PATTERN = r'[[\]*?#\x00-\x1f\x7f-\x84\x86-\xff]'
16
17
18def escape(name):
19    """Escape GS object name.
20
21    @param name: Name string.
22    @return: Escaped name string.
23    """
24    return re.sub(_INVALID_GS_PATTERN,
25                  lambda x: _percent_escape(x.group(0)), name)
26
27
28def _percent_escape(char):
29    """Percent escape a character.
30
31    @param char: character to escape.
32    @return: Escaped string.
33    """
34    return '%{:02x}'.format(ord(char))
35