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,279 @@
1
+ from git_remote_dropbox.constants import APP_KEY
2
+
3
+ import dropbox # type: ignore
4
+
5
+ import json
6
+ import os
7
+ import sys
8
+ import tempfile
9
+ from typing import Optional, Any, Dict
10
+ from abc import ABC, abstractmethod
11
+ from enum import IntEnum
12
+
13
+
14
+ def stdout(line: str) -> None:
15
+ """
16
+ Write line to standard output.
17
+ """
18
+ sys.stdout.write(line)
19
+ sys.stdout.flush()
20
+
21
+
22
+ def stderr(line: str) -> None:
23
+ """
24
+ Write line to standard error.
25
+ """
26
+ sys.stderr.write(line)
27
+ sys.stderr.flush()
28
+
29
+
30
+ def readline() -> str:
31
+ """
32
+ Read a line from standard input.
33
+ """
34
+ return sys.stdin.readline().strip() # remove trailing newline
35
+
36
+
37
+ def stdout_to_binary() -> None:
38
+ """
39
+ Ensure that stdout is in binary mode on windows
40
+ """
41
+ if sys.platform == "win32":
42
+ import msvcrt
43
+
44
+ msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
45
+
46
+
47
+ class Level(IntEnum):
48
+ """
49
+ A class for severity levels.
50
+ """
51
+
52
+ ERROR = 0
53
+ INFO = 1
54
+ DEBUG = 2
55
+
56
+
57
+ class Poison:
58
+ """
59
+ A poison pill.
60
+
61
+ Instances of this class can be used as sentinel objects to communicate
62
+ termination requests to processes.
63
+ """
64
+
65
+ def __init__(self, message: Optional[str] = None) -> None:
66
+ self.message = message
67
+
68
+
69
+ class Binder:
70
+ """
71
+ A class to bind a method to an object.
72
+
73
+ Python's built-in pickling does not work on bound methods or lambdas. This
74
+ class is designed to work around that restriction. In addition, it provides
75
+ the ability to partially apply a function.
76
+
77
+ For example, Binder can be used as follows:
78
+
79
+ >>> class A(object):
80
+ ... def __init__(self, x):
81
+ ... self.x = x
82
+ ... def add(self, y, z):
83
+ ... return self.x + y + z
84
+ ...
85
+ >>> b = Binder(A(1), 'add', 2)
86
+ >>> b(3)
87
+ 6
88
+
89
+ In the above example, it is possible to pickle the `b` object.
90
+ """
91
+
92
+ def __init__(self, obj: Any, func_name: str, *args: Any) -> None:
93
+ """
94
+ Initialize a Binder with an object and a function by its name.
95
+
96
+ Partially apply the function with args.
97
+ """
98
+ self._obj = obj
99
+ self._func_name = func_name
100
+ self._args = args
101
+
102
+ def __call__(self, *args: Any) -> Any:
103
+ """
104
+ Call the function bound to the object, passing args if given.
105
+ """
106
+ # we cannot pickle an instance method, but we can pickle the instance
107
+ # itself along with the method name, and then we can dynamically
108
+ # retrieve the unbound method and call it with the instance and
109
+ # arguments
110
+ method = getattr(type(self._obj), self._func_name)
111
+ args = self._args + args
112
+ return method(self._obj, *args)
113
+
114
+
115
+ class Token(ABC):
116
+ @abstractmethod
117
+ def connect(self) -> dropbox.Dropbox:
118
+ raise NotImplementedError
119
+
120
+ @abstractmethod
121
+ def serialize(self) -> Any:
122
+ raise NotImplementedError
123
+
124
+ @classmethod
125
+ @abstractmethod
126
+ def parse(cls, rep: Any) -> "Token":
127
+ raise NotImplementedError
128
+
129
+
130
+ class RefreshToken(Token):
131
+ _value: str
132
+
133
+ def __init__(self, value: str) -> None:
134
+ self._value = value
135
+
136
+ def serialize(self) -> Any:
137
+ return ["refresh", self._value]
138
+
139
+ @classmethod
140
+ def parse(cls, rep: Any) -> "RefreshToken":
141
+ if (
142
+ not isinstance(rep, list)
143
+ or not len(rep) == 2
144
+ or not rep[0] == "refresh"
145
+ or not isinstance(rep[1], str)
146
+ ):
147
+ raise ValueError("cannot parse as RefreshToken")
148
+ return RefreshToken(rep[1])
149
+
150
+ def connect(self) -> dropbox.Dropbox:
151
+ return dropbox.Dropbox(oauth2_refresh_token=self._value, app_key=APP_KEY)
152
+
153
+
154
+ class LongLivedToken(Token):
155
+ _value: str
156
+
157
+ def __init__(self, value: str) -> None:
158
+ self._value = value
159
+
160
+ def serialize(self) -> Any:
161
+ return ["long-lived", self._value]
162
+
163
+ @classmethod
164
+ def parse(cls, rep: Any) -> "LongLivedToken":
165
+ if (
166
+ not isinstance(rep, list)
167
+ or not len(rep) == 2
168
+ or not rep[0] == "long-lived"
169
+ or not isinstance(rep[1], str)
170
+ ):
171
+ raise ValueError("cannot parse as LongLivedToken")
172
+ return LongLivedToken(rep[1])
173
+
174
+ def connect(self) -> dropbox.Dropbox:
175
+ return dropbox.Dropbox(self._value)
176
+
177
+
178
+ def parse_token(rep: Any) -> Token:
179
+ for TokenType in [RefreshToken, LongLivedToken]:
180
+ try:
181
+ token = TokenType.parse(rep)
182
+ return token
183
+ except ValueError:
184
+ continue
185
+ raise ValueError('cannot parse "%s" as a token' % rep)
186
+
187
+
188
+ class Config:
189
+ """
190
+ A class to manage configuration data.
191
+ """
192
+
193
+ _VERSION: int = 2
194
+
195
+ _filename: str
196
+ _default_token: Optional[Token]
197
+ _named_tokens: Dict[str, Token]
198
+
199
+ def __init__(self, filename: str, create: bool = False) -> None:
200
+ self._filename = filename
201
+ self._default_token = None
202
+ self._named_tokens = {}
203
+ if create:
204
+ self.save()
205
+ else:
206
+ self.load()
207
+
208
+ def save(self) -> None:
209
+ rep: Dict[str, Any] = {}
210
+ rep["version"] = self._VERSION
211
+ named_tokens = {name: token.serialize() for name, token in self._named_tokens.items()}
212
+ default_token = self._default_token.serialize() if self._default_token else None
213
+ rep["tokens"] = {"default": default_token, "named": named_tokens}
214
+ contents = json.dumps(rep, indent=2).encode("utf8")
215
+ atomic_write(contents, self._filename)
216
+
217
+ def load(self) -> None:
218
+ with open(self._filename) as f:
219
+ rep = json.load(f)
220
+ version = rep.get("version")
221
+ # try to migrate if necessary
222
+ if version is None:
223
+ # v1 style config, before we had versions
224
+ for username, token_rep in rep.items():
225
+ token = LongLivedToken(token_rep)
226
+ if username == "default":
227
+ self._default_token = token
228
+ else:
229
+ self._named_tokens[username] = token
230
+ self.save()
231
+ elif version != self._VERSION:
232
+ raise ValueError(
233
+ 'expected config version %d, got %s; delete the config file "%s" to re-initialize'
234
+ % (self._VERSION, version, self._filename)
235
+ )
236
+ else:
237
+ # version is correct, parse
238
+ default_token_rep = rep["tokens"]["default"]
239
+ if default_token_rep:
240
+ self._default_token = parse_token(default_token_rep)
241
+ for username, token_rep in rep["tokens"]["named"].items():
242
+ self._named_tokens[username] = parse_token(token_rep)
243
+
244
+ def get_default_token(self) -> Optional[Token]:
245
+ return self._default_token
246
+
247
+ def set_default_token(self, token: Token) -> None:
248
+ self._default_token = token
249
+
250
+ def delete_default_token(self) -> None:
251
+ self._default_token = None
252
+
253
+ def named_tokens(self) -> Dict[str, Token]:
254
+ return self._named_tokens
255
+
256
+ def get_named_token(self, name: str) -> Optional[Token]:
257
+ return self._named_tokens.get(name)
258
+
259
+ def set_named_token(self, name: str, token: Token) -> None:
260
+ self._named_tokens[name] = token
261
+
262
+ def delete_named_token(self, name: str) -> None:
263
+ self._named_tokens.pop(name, None) # ignore nonexistent
264
+
265
+
266
+ def atomic_write(contents: bytes, path: str) -> None:
267
+ # same directory as path to avoid being on a different filesystem
268
+ try:
269
+ temp_file = tempfile.NamedTemporaryFile(dir=os.path.dirname(path), delete=False)
270
+ temp_file.write(contents)
271
+ temp_file.flush()
272
+ os.fsync(temp_file.fileno())
273
+ temp_file.close() # necessary on Windows because we can't move an open file
274
+ os.replace(temp_file.name, path)
275
+ finally:
276
+ try:
277
+ os.unlink(temp_file.name)
278
+ except Exception:
279
+ pass
@@ -0,0 +1,22 @@
1
+ The MIT License (MIT)
2
+ =====================
3
+
4
+ **Copyright (c) Anish Athalye (me@anishathalye.com)**
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
7
+ this software and associated documentation files (the "Software"), to deal in
8
+ the Software without restriction, including without limitation the rights to
9
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10
+ of the Software, and to permit persons to whom the Software is furnished to do
11
+ so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,199 @@
1
+ Metadata-Version: 2.1
2
+ Name: git-remote-dropbox
3
+ Version: 2.0.1
4
+ Summary: A transparent bidirectional bridge between Git and Dropbox
5
+ Home-page: https://github.com/anishathalye/git-remote-dropbox
6
+ Author: Anish Athalye
7
+ Author-email: me@anishathalye.com
8
+ License: MIT
9
+ Keywords: git dropbox
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Topic :: Software Development :: Version Control
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.6
16
+ Classifier: Programming Language :: Python :: 3.7
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE.md
22
+ Requires-Dist: dropbox <12,>=11
23
+ Requires-Dist: setuptools <70,>=69
24
+
25
+ # git-remote-dropbox [![Build Status](https://github.com/anishathalye/git-remote-dropbox/workflows/CI/badge.svg)](https://github.com/anishathalye/git-remote-dropbox/actions?query=workflow%3ACI) [![pypi](https://img.shields.io/pypi/v/git-remote-dropbox.svg)](https://pypi.org/pypi/git-remote-dropbox/)
26
+
27
+ git-remote-dropbox is a transparent bidirectional bridge between Git and
28
+ Dropbox. It lets you use a Dropbox folder or a shared folder as a Git remote!
29
+
30
+ ---
31
+
32
+ This Git remote helper makes Dropbox act like a _true Git remote_. It maintains
33
+ _all guarantees_ that are provided by a traditional Git remote while using
34
+ Dropbox as a backing store. This means that it works correctly even when there
35
+ are multiple people operating on the repository at once, making it possible to
36
+ use a Dropbox shared folder as a Git remote for collaboration.
37
+
38
+ Once the helper is installed, using it is as simple as adding a remote like
39
+ `dropbox:///path/to/repo`.
40
+
41
+ To clone repositories in folders or shared folders mounted in your Dropbox, you
42
+ can run:
43
+
44
+ ```bash
45
+ git clone "dropbox:///path/to/repo"
46
+ ```
47
+
48
+ To add a remote to an existing local repository, you can run:
49
+
50
+ ```bash
51
+ git remote add origin "dropbox:///path/to/repo"
52
+ ```
53
+
54
+ The repository directory will be created automatically the first time you push.
55
+
56
+ After adding the remote, you can treat it just like a regular Git remote. The
57
+ Dropbox-backed remote supports all operations that regular remotes support, and
58
+ it provides identical guarantees in terms of atomicity even when there are
59
+ concurrent operations, even when using a shared folder.
60
+
61
+ ## Setup
62
+
63
+ ### Install git-remote-dropbox
64
+
65
+ 1. Prerequisites:
66
+ 1. `python` and matching `pip`
67
+ 2. `git`
68
+ 2. Install this package with `pip install git-remote-dropbox`. Use `which git-remote-dropbox` to make sure it's available via `$PATH`. If not, edit `$PATH` appropriately.
69
+
70
+ ### Log in to Dropbox
71
+
72
+ Run `git dropbox login` and follow the instructions to authenticate with OAuth
73
+ and log in to your Dropbox account.
74
+
75
+ ## Sharing
76
+
77
+ The above gives you a way to create a Git repository on Dropbox and use it from multiple machines that you own. In other words, it's a convenient way to share a remote with your laptop and your desktop.
78
+
79
+ If you want to share with other people, you should explicitly share (e.g. via the Dropbox website) the root folder of the repo with your collaborators. Then they should also install git-remote-dropbox and log in *with their own account*.
80
+
81
+ ## Multiple Accounts
82
+
83
+ git-remote-dropbox supports using multiple Dropbox accounts. You can have named
84
+ accounts with `git dropbox login <username>`. **These usernames are unrelated
85
+ to your Dropbox login; you can choose whatever names you want to organize your
86
+ accounts, e.g. "work".**
87
+
88
+ You can tell git-remote-dropbox to use a particular account by setting the git
89
+ remote URL appropriately, specifying a username like:
90
+ `dropbox://username@/path/to/repo`.
91
+
92
+ ## Repository Manager
93
+
94
+ In addition to the git remote helper, git-remote-dropbox comes with an
95
+ additional tool to manage your logins and repositories on Dropbox. This tool
96
+ can be invoked as `git dropbox`.
97
+
98
+ The tool supports the following commands:
99
+
100
+ - `git dropbox login [username]`: log in, either with the default account (no
101
+ need to specify a username in remote), or with an alias (for multi-account
102
+ support)
103
+ - `git dropbox logout [username]`: log out
104
+ - `git dropbox show-logins`: list logged-in accounts
105
+ - `git dropbox set-head <remote> <branch>`: set default branch on the remote
106
+ - `git dropbox version`: show version
107
+
108
+ ## Notes
109
+
110
+ - Do not directly interact with Git repositories in your Dropbox folder -always
111
+ use git-remote-dropbox. If you're using the Dropbox client to sync files,
112
+ it's a good idea to use [selective
113
+ sync](https://help.dropbox.com/installs-integrations/sync-uploads/selective-sync-overview)
114
+ and disable syncing of the folder containing the repository to avoid any
115
+ unexpected conflicts, just in case.
116
+
117
+ - git-remote-dropbox does not use the Dropbox desktop client - it uses the API
118
+ directly. It does not require that the desktop client is installed.
119
+
120
+ - The remote helper does not support shallow cloning.
121
+
122
+ - Cloning a repository or fetching a lot of objects produces lots of loose
123
+ objects. To save space in the local repository, run `git gc --aggressive`.
124
+
125
+ - If the remote HEAD (default branch on the remote) is not set, after cloning a
126
+ repository from Dropbox, Git will not automatically check out a branch. To
127
+ check out a branch, run `git checkout <branch>`. To set the default branch on
128
+ the remote, use the [`git dropbox`](#repository-manager) command.
129
+
130
+ ## FAQ
131
+
132
+ **Why shouldn't I keep my Git repository in Dropbox and let the client sync
133
+ it?**
134
+
135
+ There seem to be a lot of articles on the Internet recommending this as a good
136
+ workflow. However, this is *not a good idea*! The desktop client is not aware
137
+ of how Git manages it's on-disk format, so if there are concurrent changes or
138
+ delays in syncing, it's possible to have conflicts that result in a corrupted
139
+ Git repository. This may be uncommon with the way the timing works out in the
140
+ single user case, but it's still not safe!
141
+
142
+ **Why shouldn't I keep a bare Git repository in a Dropbox shared folder, use it
143
+ as a folder-based Git remote, and sync it with the desktop client?**
144
+
145
+ There seem to be some articles on the Internet suggesting that this is a good
146
+ idea. It's not. Using the desktop client to sync a bare Git repository is not
147
+ safe. Concurrent changes or delays in syncing can result in a corrupted Git
148
+ repository.
149
+
150
+ **How can I access / recover my repository from Dropbox without using the
151
+ git-remote-dropbox helper?**
152
+
153
+ Because git-remote-dropbox uses an on-disk format that's compatible with Git,
154
+ accessing your repository without using the helper is easy:
155
+
156
+ 1. Download the repository data (a directory containing the `objects` and
157
+ `refs` directories) from Dropbox.
158
+ 2. Make a new directory and initialize an empty Git repository in the
159
+ directory.
160
+ 3. Overwrite `.git/refs` and `.git/objects` in your newly initialized
161
+ repository with the data downloaded from Dropbox (using a command like `rm
162
+ -rf .git/{refs,objects} && cp -r /path/to/data/{refs,objects} .git/`).
163
+ 4. Check out a branch (using a command like `git checkout -f master`).
164
+ 5. Optionally, run `git gc --aggressive` to save disk space in your local
165
+ repository.
166
+
167
+ **How do I use git-remote-dropbox from behind a proxy server?**
168
+
169
+ You can use git-remote-dropbox from behind a proxy server by setting the
170
+ `HTTP_PROXY` and `HTTPS_PROXY` environment variables. See
171
+ [here](http://docs.python-requests.org/en/latest/user/advanced/#proxies) for
172
+ more details.
173
+
174
+ **How do I use git-remote-dropbox with submodules?**
175
+
176
+ You can allow this by setting
177
+ [`protocol.dropbox.allow`](https://git-scm.com/docs/git-config#Documentation/git-config.txt-protocolltnamegtallow)
178
+ to `always`:
179
+
180
+ ```bash
181
+ git config --global --add protocol.dropbox.allow always
182
+ ```
183
+
184
+ ## Design
185
+
186
+ To read about the design of git-remote-dropbox, see [DESIGN.md](DESIGN.md).
187
+ This could be especially useful if you're thinking about contributing to the
188
+ project.
189
+
190
+ ## Contributing
191
+
192
+ Do you have ideas on how to improve git-remote-dropbox? Have a feature request,
193
+ bug report, or patch? Great! See [CONTRIBUTING.md](CONTRIBUTING.md) for
194
+ information on what you can do about that.
195
+
196
+ ## License
197
+
198
+ Copyright (c) Anish Athalye. Released under the MIT License. See
199
+ [LICENSE.md](LICENSE.md) for details.
@@ -0,0 +1,15 @@
1
+ git_remote_dropbox/__init__.py,sha256=2hNPya2i_kbDmnI7lhL5z7qj20bcXVWVVyBAOGg6gOY,1132
2
+ git_remote_dropbox/constants.py,sha256=6PJRRi10Y3dkOFcpImIns6pnrmLRYJLvKXx58dzVdEI,203
3
+ git_remote_dropbox/git.py,sha256=dfFWY_JaOqmRbS6R7l5hGK2Maha591HsuGq25UCelLY,5215
4
+ git_remote_dropbox/helper.py,sha256=kvzOOsRNYytWPwn7naV6q554TUtSiIJuGE6_NWo_pNQ,21023
5
+ git_remote_dropbox/util.py,sha256=JbKBLKbGLy1QyV7L7C01n887lNMPjBKPnJnSjsQoU6k,7855
6
+ git_remote_dropbox/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ git_remote_dropbox/cli/common.py,sha256=rKVePLxiJH24Ig7r-RKw9I7qt_jxocIDNhMtb_AAS48,2987
8
+ git_remote_dropbox/cli/helper.py,sha256=jTODsZ6CMWrqGJ1R4HIQco4wYuZlSo7eK2_-lUwaY9w,699
9
+ git_remote_dropbox/cli/manage.py,sha256=0mffOuEVCL4wUN-PMDzCoQq6Ynj45WQEbKvHRQh2rq0,5556
10
+ git_remote_dropbox-2.0.1.dist-info/LICENSE.md,sha256=oBfBawvq3WaGZwrTYJoBMFcOAv2L1PLQrRj0bO33bRw,1123
11
+ git_remote_dropbox-2.0.1.dist-info/METADATA,sha256=93lHYM-GVC2-aeuQOffhtHZ77E9vnLLCLlp87NDQ_Jw,8342
12
+ git_remote_dropbox-2.0.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
13
+ git_remote_dropbox-2.0.1.dist-info/entry_points.txt,sha256=pNACZhcUteKqLnrlUO4tFMbMFLgGMyAZ-oJd1L5vzic,179
14
+ git_remote_dropbox-2.0.1.dist-info/top_level.txt,sha256=aVkzNnRNi-Qo6IyhJzxBuUHWBuEDEvFanWys7E4c9YY,19
15
+ git_remote_dropbox-2.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.43.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,4 @@
1
+ [console_scripts]
2
+ git-dropbox = git_remote_dropbox.cli.manage:main
3
+ git-dropbox-manage = git_remote_dropbox.cli.manage:main
4
+ git-remote-dropbox = git_remote_dropbox.cli.helper:main
@@ -0,0 +1 @@
1
+ git_remote_dropbox