git-remote-dropbox 2.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ # Copyright (c) Anish Athalye (me@anishathalye.com)
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ # of this software and associated documentation files (the "Software"), to deal
5
+ # in the Software without restriction, including without limitation the rights
6
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ # copies of the Software, and to permit persons to whom the Software is
8
+ # furnished to do so, subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in
11
+ # all copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ # SOFTWARE.
20
+
21
+ __version__ = "2.0.1"
File without changes
@@ -0,0 +1,96 @@
1
+ from git_remote_dropbox.util import (
2
+ Config,
3
+ stderr,
4
+ Token,
5
+ LongLivedToken,
6
+ )
7
+ from git_remote_dropbox.helper import Helper
8
+
9
+ import dropbox # type: ignore
10
+
11
+ import sys
12
+ import os
13
+ from typing import NoReturn
14
+ from urllib.parse import urlparse
15
+
16
+
17
+ def error(msg: str) -> NoReturn:
18
+ stderr("error: %s\n" % msg)
19
+ sys.exit(1)
20
+
21
+
22
+ def get_config() -> Config:
23
+ config_files = [
24
+ os.path.join(
25
+ os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")),
26
+ "git",
27
+ "git-remote-dropbox.json",
28
+ ),
29
+ os.path.expanduser("~/.git-remote-dropbox.json"),
30
+ ]
31
+ for path in config_files:
32
+ if os.path.exists(path):
33
+ return Config(path)
34
+ path = config_files[0]
35
+ os.makedirs(os.path.dirname(path), exist_ok=True)
36
+ return Config(path, create=True)
37
+
38
+
39
+ def check_connection(dbx: dropbox.Dropbox) -> None:
40
+ dbx.users_get_current_account()
41
+
42
+
43
+ def get_helper(url: str) -> Helper:
44
+ """
45
+ Return a Helper configured to point at the given URL.
46
+
47
+ URLs must be formatted as:
48
+ dropbox:///path/to/repo
49
+ dropbox://username@/path/to/repo
50
+ dropbox://:token@/path/to/repo
51
+ """
52
+ parsed = urlparse(url)
53
+ if parsed.scheme != "dropbox":
54
+ error('URL must start with the "dropbox://" scheme')
55
+ if parsed.netloc:
56
+ if not parsed.username and not parsed.password:
57
+ # user probably put in something like "dropbox://path/to/repo"
58
+ # missing the third "/"
59
+ error('URL with no username or token must start with "dropbox:///"')
60
+ if parsed.username and parsed.password:
61
+ # user supplied both username and token
62
+ error("URL must not specify both username and token")
63
+ path = parsed.path.lower() # dropbox is case insensitive, so we must canonicalize
64
+ if path.endswith("/"):
65
+ error("URL path must not have trailing slash")
66
+
67
+ config = get_config()
68
+ token: Token
69
+ if parsed.password:
70
+ token = LongLivedToken(parsed.password)
71
+ elif parsed.username:
72
+ t = config.get_named_token(parsed.username)
73
+ if not t:
74
+ error("you must log in first with 'git dropbox login %s'" % parsed.username)
75
+ token = t
76
+ else:
77
+ t = config.get_default_token()
78
+ if not t:
79
+ error("you must log in first with 'git dropbox login'")
80
+ token = t
81
+ try:
82
+ check_connection(token.connect())
83
+ except dropbox.exceptions.DropboxException:
84
+ if parsed.password:
85
+ error(
86
+ "invalid inline legacy access token, try switching to short-lived access tokens with 'git dropbox login'"
87
+ )
88
+ elif parsed.username:
89
+ error(
90
+ "invalid access token, try logging in again with 'git dropbox login %s'"
91
+ % parsed.username
92
+ )
93
+ else:
94
+ error("invalid access token, try logging in again with 'git dropbox login'")
95
+
96
+ return Helper(token, path)
@@ -0,0 +1,31 @@
1
+ from git_remote_dropbox.util import (
2
+ Level,
3
+ stdout_to_binary,
4
+ )
5
+ from git_remote_dropbox.cli.common import (
6
+ error,
7
+ get_helper,
8
+ )
9
+
10
+ import sys
11
+
12
+
13
+ def main() -> None:
14
+ """
15
+ Main entry point for git-remote-dropbox Git remote helper.
16
+ """
17
+ # configure system
18
+ stdout_to_binary()
19
+
20
+ url = sys.argv[2]
21
+ helper = get_helper(url)
22
+ try:
23
+ helper.run()
24
+ except Exception:
25
+ if helper.verbosity >= Level.DEBUG:
26
+ raise # re-raise exception so it prints out a stack trace
27
+ else:
28
+ error("unexpected exception (run with -v for details)")
29
+ except KeyboardInterrupt:
30
+ # exit silently with an error code
31
+ sys.exit(1)
@@ -0,0 +1,164 @@
1
+ import git_remote_dropbox
2
+ from git_remote_dropbox import constants
3
+ from git_remote_dropbox import git
4
+ from git_remote_dropbox.util import RefreshToken, LongLivedToken
5
+ from git_remote_dropbox.cli.common import (
6
+ error,
7
+ get_helper,
8
+ get_config,
9
+ )
10
+
11
+ import dropbox # type: ignore
12
+
13
+ import argparse
14
+ import subprocess
15
+ import sys
16
+ from typing import Optional
17
+
18
+
19
+ def main() -> None:
20
+ """
21
+ Main entry point for git-dropbox program.
22
+ """
23
+ parser = argparse.ArgumentParser()
24
+ subparsers = parser.add_subparsers()
25
+ subparsers.required = True
26
+ subparsers.dest = "command"
27
+
28
+ parser_set_head = subparsers.add_parser("set-head", help="set the default branch on the remote")
29
+ parser_set_head.add_argument("remote", type=str, help="name of the remote")
30
+ parser_set_head.add_argument("branch", type=str, help="name of the branch on the remote")
31
+
32
+ parser_version = subparsers.add_parser(
33
+ "version", help="print the version of git-remote-dropbox"
34
+ )
35
+
36
+ parser_login = subparsers.add_parser("login", help="log in to Dropbox")
37
+ parser_login.add_argument("username", type=str, help="username/tag", nargs="?", default=None)
38
+
39
+ parser_logout = subparsers.add_parser("logout", help="log out from Dropbox")
40
+ parser_logout.add_argument("username", type=str, help="username/tag", nargs="?", default=None)
41
+
42
+ parser_show_logins = subparsers.add_parser(
43
+ "show-logins", help="show logged-in accounts and their usernames/tags"
44
+ )
45
+
46
+ args = parser.parse_args()
47
+
48
+ if args.command == "set-head":
49
+ set_head(args.remote, args.branch)
50
+ elif args.command == "version":
51
+ version()
52
+ elif args.command == "login":
53
+ login(args.username)
54
+ elif args.command == "logout":
55
+ logout(args.username)
56
+ elif args.command == "show-logins":
57
+ show_logins()
58
+
59
+
60
+ def set_head(remote: str, branch: str) -> None:
61
+ """
62
+ Set the default branch on the remote to point to branch.
63
+
64
+ While almost all git-remote-dropbox functionality is fully safe under
65
+ concurrent operation, this particular functionality is not safe under a
66
+ particular kind of concurrent modification. In particular, if set-head is
67
+ called with a branch that is concurrently deleted, then the operation fails
68
+ (and notifies the user).
69
+ """
70
+ try:
71
+ url = git.get_remote_url(remote)
72
+ except subprocess.CalledProcessError:
73
+ error("no such remote '%s'" % remote)
74
+ sys.exit(1)
75
+ helper = get_helper(url)
76
+
77
+ remote_ref = "refs/heads/%s" % branch
78
+
79
+ def branch_exists() -> bool:
80
+ refs = helper.get_refs(False)
81
+ for _, name in refs:
82
+ if name == remote_ref:
83
+ return True
84
+ return False
85
+
86
+ # check if target branch exists
87
+ if not branch_exists():
88
+ error("remote has no such ref '%s'" % remote_ref)
89
+ # get current head
90
+ old_head = helper.read_symbolic_ref("HEAD")
91
+ if old_head and old_head[1] == remote_ref:
92
+ error("remote HEAD is already '%s'" % remote_ref)
93
+ rev = old_head[0] if old_head else None
94
+ # write new head
95
+ ok = helper.write_symbolic_ref("HEAD", remote_ref, rev=rev)
96
+ if not ok:
97
+ error("concurrent modification of remote HEAD detected (try again)")
98
+ # ensure that target branch still exists
99
+ if not branch_exists():
100
+ # this should be a really rare occurrence: have the user fix it up if
101
+ # it happens
102
+ error("remote ref '%s' was concurrently deleted: remote HEAD needs to be fixed (try again)")
103
+ print("Updated remote HEAD to '%s'." % remote_ref)
104
+
105
+
106
+ def login(username: Optional[str]) -> None:
107
+ auth_flow = dropbox.DropboxOAuth2FlowNoRedirect(
108
+ constants.APP_KEY, use_pkce=True, token_access_type="offline"
109
+ )
110
+ authorize_url = auth_flow.start()
111
+ print("Logging in to Dropbox using OAuth...")
112
+ print("1. Go to: %s" % authorize_url)
113
+ print('2. Click "Allow" (you might have to log in first)')
114
+ print("3. Copy the authorization code")
115
+ auth_code = input("Enter authorization code: ").strip()
116
+ try:
117
+ oauth_result = auth_flow.finish(auth_code)
118
+ token = RefreshToken(oauth_result.refresh_token)
119
+ except Exception:
120
+ error("failed to log in; did you copy the code correctly?")
121
+
122
+ config = get_config()
123
+ if username is None:
124
+ config.set_default_token(token)
125
+ else:
126
+ config.set_named_token(username, token)
127
+ config.save()
128
+
129
+ if username is None:
130
+ example = "dropbox:///path/to/repo"
131
+ else:
132
+ example = "dropbox://%s@/path/to/repo" % username
133
+ print("Successfully logged in! You can now add Dropbox remotes like '%s'" % example)
134
+
135
+
136
+ def logout(username: Optional[str]) -> None:
137
+ config = get_config()
138
+ if username is None:
139
+ config.delete_default_token()
140
+ config.save()
141
+ print("Logged out!")
142
+ else:
143
+ config.delete_named_token(username)
144
+ config.save()
145
+ print("Logged out %s!" % username)
146
+
147
+
148
+ def show_logins() -> None:
149
+ config = get_config()
150
+ token = config.get_default_token()
151
+ if token is not None:
152
+ deprecated = ""
153
+ if isinstance(token, LongLivedToken):
154
+ deprecated = " [deprecated long-lived token]"
155
+ print("(default user)%s" % deprecated)
156
+ for username, token in config.named_tokens().items():
157
+ deprecated = ""
158
+ if isinstance(token, LongLivedToken):
159
+ deprecated = " [deprecated long-lived token]"
160
+ print("%s%s" % (username, deprecated))
161
+
162
+
163
+ def version() -> None:
164
+ print("git-remote-dropbox %s" % git_remote_dropbox.__version__)
@@ -0,0 +1,9 @@
1
+ import os
2
+ from typing import TextIO
3
+
4
+
5
+ APP_KEY: str = "h7d8z1irmz0r7lp"
6
+ DEVNULL: TextIO = open(os.devnull, "w")
7
+ PROCESSES: int = 20
8
+ MAX_RETRIES: int = 3
9
+ CHUNK_SIZE: int = 50 * 1024 * 1024 # 50 megabytes
@@ -0,0 +1,184 @@
1
+ from git_remote_dropbox.constants import DEVNULL
2
+
3
+ import subprocess
4
+ import zlib
5
+ from typing import Optional, List
6
+
7
+
8
+ EMPTY_TREE_HASH: str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
9
+
10
+
11
+ def command_output_raw(*args: str) -> bytes:
12
+ """
13
+ Return the raw result of running a git command.
14
+ """
15
+ args = ("git",) + args
16
+ output = subprocess.check_output(args, stderr=DEVNULL)
17
+ return output
18
+
19
+
20
+ def command_output(*args: str) -> str:
21
+ """
22
+ Return the raw result of running a git command.
23
+ """
24
+ return command_output_raw(*args).decode("utf8").strip()
25
+
26
+
27
+ def command_ok(*args: str) -> bool:
28
+ """
29
+ Return whether a git command runs successfully.
30
+ """
31
+ args = ("git",) + args
32
+ return subprocess.call(args, stdout=DEVNULL, stderr=DEVNULL) == 0
33
+
34
+
35
+ def is_ancestor(ancestor: str, ref: str) -> bool:
36
+ """
37
+ Return whether ancestor is an ancestor of ref.
38
+
39
+ This returns true when it is possible to fast-forward from ancestor to ref.
40
+ """
41
+ return command_ok("merge-base", "--is-ancestor", ancestor, ref)
42
+
43
+
44
+ def object_exists(sha: str) -> bool:
45
+ """
46
+ Return whether the object exists in the repository.
47
+ """
48
+ return command_ok("cat-file", "-e", sha)
49
+
50
+
51
+ def history_exists(sha: str) -> bool:
52
+ """
53
+ Return whether the object, along with its history, exists in the
54
+ repository.
55
+ """
56
+ return command_ok("rev-list", "--objects", sha)
57
+
58
+
59
+ def ref_value(ref: str) -> str:
60
+ """
61
+ Return the hash of the ref.
62
+ """
63
+ return command_output("rev-parse", ref)
64
+
65
+
66
+ def symbolic_ref_value(name: str) -> str:
67
+ """
68
+ Return the branch head to which the symbolic ref refers.
69
+ """
70
+ return command_output("symbolic-ref", name)
71
+
72
+
73
+ def object_kind(sha: str) -> str:
74
+ """
75
+ Return the type of the object.
76
+ """
77
+ return command_output("cat-file", "-t", sha)
78
+
79
+
80
+ def object_data(sha: str, kind: Optional[str] = None) -> bytes:
81
+ """
82
+ Return the contents of the object.
83
+
84
+ If kind is None, return a pretty-printed representation of the object.
85
+ """
86
+ if kind is not None:
87
+ return command_output_raw("cat-file", kind, sha)
88
+ else:
89
+ return command_output_raw("cat-file", "-p", sha)
90
+
91
+
92
+ def encode_object(sha: str) -> bytes:
93
+ """
94
+ Return the encoded contents of the object.
95
+
96
+ The encoding is identical to the encoding git uses for loose objects.
97
+
98
+ This operation is the inverse of `decode_object`.
99
+ """
100
+ kind = object_kind(sha)
101
+ size = command_output("cat-file", "-s", sha)
102
+ contents = object_data(sha, kind)
103
+ data = kind.encode("utf8") + b" " + size.encode("utf8") + b"\0" + contents
104
+ compressed = zlib.compress(data)
105
+ return compressed
106
+
107
+
108
+ def decode_object(data: bytes) -> str:
109
+ """
110
+ Decode the object, write it, and return the computed hash.
111
+
112
+ This operation is the inverse of `encode_object`.
113
+ """
114
+ decompressed = zlib.decompress(data)
115
+ header, contents = decompressed.split(b"\0", 1)
116
+ kind = header.split()[0]
117
+ return write_object(kind.decode("utf8"), contents)
118
+
119
+
120
+ def write_object(kind: str, contents: bytes) -> str:
121
+ with subprocess.Popen(
122
+ ["git", "hash-object", "-w", "--stdin", "-t", kind],
123
+ stdin=subprocess.PIPE,
124
+ stdout=subprocess.PIPE,
125
+ stderr=DEVNULL,
126
+ ) as p:
127
+ sha = p.communicate(contents)[0].decode("utf8").strip()
128
+ return sha
129
+
130
+
131
+ def list_objects(ref: str, exclude: List[str]) -> List[str]:
132
+ """
133
+ Return the objects reachable from ref excluding the objects reachable from
134
+ exclude.
135
+ """
136
+ exclude = ["^%s" % obj for obj in exclude if object_exists(obj)]
137
+ objects = command_output("rev-list", "--objects", ref, *exclude)
138
+ if not objects:
139
+ return []
140
+ return [i.split()[0] for i in objects.split("\n")]
141
+
142
+
143
+ def referenced_objects(sha: str) -> List[str]:
144
+ """
145
+ Return the objects directly referenced by the object.
146
+ """
147
+ kind = object_kind(sha)
148
+ if kind == "blob":
149
+ # blob objects do not reference any other objects
150
+ return []
151
+ data = object_data(sha).decode("utf8").strip()
152
+ if kind == "tag":
153
+ # tag objects reference a single object
154
+ obj = data.split("\n", maxsplit=1)[0].split()[1]
155
+ return [obj]
156
+ elif kind == "commit":
157
+ # commit objects reference a tree and zero or more parents
158
+ lines = data.split("\n")
159
+ tree = lines[0].split()[1]
160
+ objs = [tree]
161
+ for line in lines[1:]:
162
+ if line.startswith("parent "):
163
+ objs.append(line.split()[1])
164
+ else:
165
+ break
166
+ return objs
167
+ elif kind == "tree":
168
+ # tree objects reference zero or more trees and blobs, or submodules
169
+ if not data:
170
+ # empty tree
171
+ return []
172
+ lines = data.split("\n")
173
+ # submodules have the mode '160000' and the kind 'commit', we filter them out because
174
+ # there is nothing to download and this causes errors
175
+ return [line.split()[2] for line in lines if not line.startswith("160000 commit ")]
176
+ else:
177
+ raise Exception("unexpected git object type: %s" % kind)
178
+
179
+
180
+ def get_remote_url(name: str) -> str:
181
+ """
182
+ Return the URL of the given remote.
183
+ """
184
+ return command_output("remote", "get-url", name)