blimp.nim
10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import md5, os, osproc, parseopt2, strutils, parsecfg, streams, lapp, subexes
# blimp is a little utility program for handling large files
# in git repositories. Its inspired by git-fat and s3annex
# but doesn't rely on S3 for storage, is a single binary without
# need for Python, and has less features than git-fat. So far.
#
# Manual use:
#
# Use "blimp d mybigfile" to deflate it before commit.
# Use "blimp i mybigfile" to inflate it back to original size.
#
# When deflated the file only has an md5sum string inside it.
#
# The file is copied over into:
# <homedir>/blimpStore/<originalfilename>-<md5sum>
#
# Configuration is in these locations in order:
# ./.blimp.conf
# <gitroot>/.blimp.conf
# ~/blimpstore/.blimp.conf
# ~/.blimp.conf
const
versionMajor* = 0
versionMinor* = 2
versionPatch* = 1
versionAsString* = $versionMajor & "." & $versionMinor & "." & $versionPatch
var
blimpStore, remoteBlimpStore, uploadCommandFormat, downloadCommandFormat, deleteCommandFormat, rsyncPassword: string = nil
verbose: bool
let
defaultConfig = """
[rsync]
# Set this to your remote rsync daemon area
remote = "blimpuser@some-rsync-server.com::blimpstore"
password = "some-good-rsync-password-for-blimpuser"
# The following three formats should not need editing
# $1 is filename, $2 is remote and $3 is the local blimpstore
upload = "rsync --password-file $3/.blimp.pass -avzP $3/$1 $2/"
download = "rsync --password-file $3/.blimp.pass -avzP $2/$1 $3/"
# This deletes a single file from destination, that is already deleted in source
delete = "rsync --password-file $3/.blimp.pass -dv --delete --existing --ignore-existing --include '$1' --exclude '*' $3/ $2"
"""
# Load a blimp.conf file
proc parseConfFile(filename: string) =
var f = newFileStream(filename, fmRead)
if f != nil:
if verbose: echo "Reading config: " & filename
var p: CfgParser
open(p, f, filename)
while true:
var e = next(p)
case e.kind
of cfgEof:
break
of cfgSectionStart:
continue # Ignore
of cfgKeyValuePair:
case e.key
of "blimpstore":
if blimpStore.isNil: blimpStore = e.value
of "remote":
if remoteBlimpStore.isNil: remoteBlimpStore = e.value
of "password":
if rsyncPassword.isNil: rsyncPassword = e.value
of "upload":
if uploadCommandFormat.isNil: uploadCommandFormat = e.value
of "download":
if downloadCommandFormat.isNil: downloadCommandFormat = e.value
of "delete":
if deleteCommandFormat.isNil: deleteCommandFormat = e.value
else:
quit("Unknown configuration: " & e.key)
of cfgOption:
quit("Unknown configuration: " & e.key)
of cfgError:
quit("Parsing " & filename & ": " & e.msg)
close(p)
# Trivial helper to enable verbose
proc run(cmd: string): auto =
if verbose: echo(cmd)
execCmd(cmd)
# Every rsync command, make sure we have a password file
proc rsyncRun(cmd: string): auto =
writeFile(blimpStore / ".blimp.pass", rsyncPassword)
if execCmd("chmod 600 " & blimpStore / ".blimp.pass") != 0:
quit("Failed to chmod 600 " & blimpStore / ".blimp.pass")
run(cmd)
# Upload a file to the remote master blimpStore
proc uploadFile(blimpFilename: string) =
if remoteBlimpStore.isNil:
echo("Remote blimpstore not set in configuration file, skipping uploading content:\n\t" & blimpFilename)
return
let errorCode = rsyncRun(format(uploadCommandFormat, blimpFilename, remoteBlimpStore, blimpStore))
if errorCode != 0:
quit("Something went wrong uploading " & blimpFilename & " to " & remoteBlimpStore, 2)
# Download a file to the remote master blimpStore
proc downloadFile(blimpFilename: string) =
if remoteBlimpStore.isNil:
quit("Remote blimpstore not set in configuration file, can not download content:\n\t" & blimpFilename)
let errorCode = rsyncRun(format(downloadCommandFormat, blimpFilename, remoteBlimpStore, blimpStore))
if errorCode != 0:
quit("Something went wrong downloading " & blimpFilename & " from " & remoteBlimpStore, 3)
# Delete a file from the remote master blimpStore
proc remoteDeleteFile(blimpFilename: string) =
if remoteBlimpStore.isNil:
return
let errorCode = rsyncRun(format(deleteCommandFormat, blimpFilename, remoteBlimpStore, blimpStore))
if errorCode != 0:
quit("Something went wrong deleting " & blimpFilename & " from " & remoteBlimpStore, 3)
# Copy content to blimpStore, no upload yet.
proc copyToBlimpStore(filename, blimpFilename: string) =
if not existsFile(blimpStore / blimpFilename):
copyFile(filename, blimpStore / blimpFilename)
uploadFile(blimpFilename)
# Copy content from blimpStore, and downloading first if needed
proc copyFromBlimpStore(blimpFilename, filename: string) =
if not existsFile(blimpStore / blimpFilename):
downloadFile(blimpFilename)
copyFile(blimpStore / blimpFilename, filename)
# Delete from blimpStore and remote.
proc deleteFromBlimpStore(blimpFilename, filename: string) =
if existsFile(blimpStore / blimpFilename):
removeFile(blimpStore / blimpFilename)
remoteDeleteFile(blimpFilename)
# Pick out blimpFilename (filename & "-" & hash)
proc blimpFileName(filename: string): string=
var hashfile: File
if not open(hashfile, filename):
quit("Failed opening file: " & filename, 4)
let hashline = split(string(readLine(hashfile)), {':'})
if hashline[0] == "hash":
result = hashline[1]
else:
result = nil
# Get hash and compute blimpFilename
proc computeBlimpFilename(filename: string): string =
var content: string
try:
content = readFile(filename)
except:
quit("Failed opening file: " & filename, 1)
let hash = getMD5(content)
result = filename & "-" & hash
# Copy original file to blimpStore and replace with hash stub in git.
proc deflate(filename: string) =
if verbose: echo "Deflating " & filename
var blimpFilename = blimpFilename(filename)
if not blimpFilename.isNil:
echo("\t" & filename & " is already deflated, skipping.")
else:
blimpFilename = computeBlimpFilename(filename)
copyToBlimpStore(filename, blimpFilename)
writeFile(filename, "hash:" & blimpFilename)
if verbose: echo("\t" & filename & " deflated.")
# Parse out hash from hash stub and copy back original content from blimpStore.
proc inflate(filename: string) =
if verbose: echo "Inflating " & filename
let blimpFilename = blimpFilename(filename)
if blimpFilename.isNil:
echo("\t" & filename & " is not deflated, skipping.")
else:
copyFromBlimpStore(blimpfilename, filename)
if verbose: echo("\t" & filename & " inflated.")
# Inflates file first (if deflated) and then removes current content for it,
# both locally and in remote.
proc remove(filename: string) =
var blimpFilename = blimpFilename(filename)
if not blimpFilename.isNil:
copyFromBlimpStore(blimpfilename, filename)
else:
blimpFilename = computeBlimpFilename(filename)
deleteFromBlimpStore(blimpfilename, filename)
echo("\t" & filename & " content removed from blimpstore locally and remotely.")
# Find git root dir or nil
proc gitRoot(): string =
try:
let tup = execCmdEx("git rev-parse --show-toplevel")
if tup[1] == 0:
result = strip(tup[0])
else:
result = nil
except:
result = nil
proc setupBlimpStore() =
try:
if not existsDir(blimpStore):
createDir(blimpStore)
except:
quit("Could not create " & blimpStore & " directory.", 1)
try:
if not existsFile(blimpStore / ".blimp.conf"):
writeFile(blimpStore / ".blimp.conf", defaultConfig)
except:
quit("Could not create .blimp.conf config file in " & blimpStore & " directory.", 1)
proc dumpConfig() =
echo "\nDump of configuration:"
echo "\tblimpStore: " & blimpStore
echo "\tremoteBlimpStore: " & remoteBlimpStore
echo "\tuploadCommandFormat: " & uploadCommandFormat
echo "\tdownloadCommandFormat: " & downloadCommandFormat
echo "\tdeleteCommandFormat: " & deleteCommandFormat
echo "\trsyncPassword: " & rsyncPassword
echo "\n"
let help = """
blimp [options] <command> <filenames...>
-h,--help Show this
--version Show version of blimp
-v,--verbose Verbosity
<command> (string) (d)eflate, (i)nflate, remove
<filenames> (string...) One or more filepaths to inflate/deflate
Edit ~/blimpstore/.blimp.conf or <gitroot>/.blimp.conf and set a proper
remote and the proper rsync password to use.
Deflate is run before you add the big file to the index for committing.
Deflate will replace the file contents with a hash, and copy the
real content to your local blimpstore, and if configured also upload it to
remote, using rsync.
Inflate will bring back the original content by copying from
your local blimpstore, and if its not there, first downloading from the remote.
Use this whenever you need to work/edit the big file - in order to get
its real content.
Remove (no single character shortcut) will remove the file(s) content
both from the local blimpstore and from the remote. This only removes
the current content version, not older versions. The file itself is first
inflated, if needed, and not deleted. This only "unblimps" the file.
"""
################################ main #####################################
# Using lapp to get args, on parsing failure this will show usage automatically
var args = parse(help)
verbose = args["verbose"].asBool
# Parse configuration files, may shadow and override each other
parseConfFile(getCurrentDir() / ".blimp.conf")
if not gitRoot().isNil:
parseConfFile(gitRoot() / ".blimp.conf")
# If we haven't gotten a blimpstore yet, we set a default one
if blimpStore.isNil:
blimpStore = getHomeDir() / "blimpstore"
if existsDir(blimpStore):
parseConfFile(blimpStore / ".blimp.conf")
parseConfFile(getHomeDir() / ".blimp.conf")
if verbose: dumpConfig()
# These two are special, they short out
if args.showHelp: quit(help)
if args.showVersion: quit("blimp version: " & versionAsString)
let command = args["command"].asString
let filenames = args["filenames"].asSeq
# Make sure the local blimpstore is setup.
setupBlimpStore()
# Do the deed
if command == "d" or command == "deflate":
for fn in filenames:
deflate(fn.asString)
elif command == "i" or command == "inflate":
for fn in filenames:
inflate(fn.asString)
elif command == "remove":
for fn in filenames:
remove(fn.asString)
else:
quit("Unknown command, only (d)eflate or (i)inflate are valid.", 6)
# All good
quit(0)