Blame view

blimp.nim 17.6 KB
3e2f4c14   Göran Krampe   Added upload comm...
1
  import md5, os, osproc, parseopt2, strutils, parsecfg, streams, lapp, subexes, tables, sets
74272cdb   Göran Krampe   First commit
2
  
5fc367ad   Göran Krampe   Renamed to blimp,...
3
  # blimp is a little utility program for handling large files
74272cdb   Göran Krampe   First commit
4
  # in git repositories. Its inspired by git-fat and s3annex
aaf9bcef   Göran Krampe   Upped to version ...
5
6
  # but doesn't rely on S3 for storage - it uses rsync like git-fat.
  # It is a single binary without any dependencies.
74272cdb   Göran Krampe   First commit
7
  #
3e2f4c14   Göran Krampe   Added upload comm...
8
  # Just run blimp --help for detailed help.
dab0c5b0   Göran Krampe   Added --version, ...
9
10
11
  
  const 
    versionMajor* = 0
386557e6   Göran Krampe   Added support for...
12
13
    versionMinor* = 3
    versionPatch* = 0
dab0c5b0   Göran Krampe   Added --version, ...
14
    versionAsString* = $versionMajor & "." & $versionMinor & "." & $versionPatch
74272cdb   Göran Krampe   First commit
15
  
b9ad52ff   Göran Krampe   Added default con...
16
  var
aaf9bcef   Göran Krampe   Upped to version ...
17
    blimpStore, remoteBlimpStore, uploadCommandFormat, downloadCommandFormat, deleteCommandFormat, rsyncPassword, blimpVersion: string = nil
78569137   Göran Krampe   Added directory e...
18
    homeDir, currentDir, gitRootDir: string
ec7d9613   Göran Krampe   Added option --fi...
19
    verbose, stdio, onAllDeflated, onAllFiltered: bool
aaf9bcef   Göran Krampe   Upped to version ...
20
    stdinContent: string = nil
74272cdb   Göran Krampe   First commit
21
  
b9ad52ff   Göran Krampe   Added default con...
22
23
24
  let
    defaultConfig = """
  [rsync]
aaf9bcef   Göran Krampe   Upped to version ...
25
  # Set your local blimpstore directory. You can use %home%, %cwd% and %gitroot% in paths, works cross platform.
78569137   Göran Krampe   Added directory e...
26
27
28
29
30
31
32
33
34
35
36
  # Example:
  #   # Place it inside the git clone
  #   blimpstore = "%gitroot%/.git/blimpstore"
  #   # Place it in current working directory (not very useful)
  #   blimpstore = "%cwd%/blimpstore"
  #
  # Default:
  #   # Place it in the users home directory
  #   blimpstore = "%home%/blimpstore"
  
  # Set this to your remote rsync location
dab0c5b0   Göran Krampe   Added --version, ...
37
  remote = "blimpuser@some-rsync-server.com::blimpstore"
aaf9bcef   Göran Krampe   Upped to version ...
38
  # Set this to your rsync password, it will be written out as a password-file called .blimp.pass on every rsync.
dab0c5b0   Göran Krampe   Added --version, ...
39
  password = "some-good-rsync-password-for-blimpuser"
e914743a   Göran Krampe   Added remove comm...
40
  
aaf9bcef   Göran Krampe   Upped to version ...
41
42
43
  # The following three formats should not need editing.
  # $1 is the blimp filename, $2 is remote location and $3 is the local blimpstore directory set above.
  # NOTE: The password-file .blimp.pass will be created by blimp on every command, do not remove that option.
7e507b62   Göran Krampe   Fixes discovered ...
44
45
  upload = "rsync --password-file $3/.blimp.pass -azP $3/$1 $2/"
  download = "rsync --password-file $3/.blimp.pass -azP $2/$1 $3/"
78569137   Göran Krampe   Added directory e...
46
  # This deletes a single file from destination, that is already deleted in source. Yeah... insane! But it works.
7e507b62   Göran Krampe   Fixes discovered ...
47
  delete = "rsync --password-file $3/.blimp.pass -d --delete --existing --ignore-existing --include '$1' --exclude '*' $3/ $2"
aaf9bcef   Göran Krampe   Upped to version ...
48
49
50
  
  [blimp]
  # Minimal version, otherwise stop
ec7d9613   Göran Krampe   Added option --fi...
51
  # version = """ & versionAsString
74272cdb   Göran Krampe   First commit
52
  
386557e6   Göran Krampe   Added support for...
53
54
  
  proc cmd(cmd: string): string =
78569137   Göran Krampe   Added directory e...
55
    try:
7e507b62   Göran Krampe   Fixes discovered ...
56
57
58
59
60
61
      # Otherwise pipes will not work for git commands etc
      when defined(windows):
        let tup = execCmdEx("cmd /c \"" & cmd & "\"")
      else:
        let tup = execCmdEx(cmd) 
      #echo "cmd: " & $cmd & "err:" & $tup[1]
78569137   Göran Krampe   Added directory e...
62
63
64
65
66
67
68
      if tup[1] == 0:
        result = strip(tup[0])
      else:
        result = nil
    except:
      result = nil
  
386557e6   Göran Krampe   Added support for...
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
  # Find git root dir or nil
  proc gitRoot(): string =
    cmd("git rev-parse --show-toplevel")
  
  # Git config
  proc gitConfigSet(key, val: string) =
    discard cmd("git config " & $key & " " & $val)
  
  proc gitConfigGet(key: string): string =
    cmd("git config --get " & $key)
  
  # Set blimp filter
  proc setBlimpFilter() =
    gitConfigSet("filter.blimp.clean", "\"blimp -s d %f\"")
    gitConfigSet("filter.blimp.smudge", "\"blimp -s i %f\"")
  
  
  # Ensure the filter is set
  proc ensureBlimpFilter() =
    if gitConfigGet("filter.blimp.clean") != "":
      setBlimpFilter()
  
  
78569137   Göran Krampe   Added directory e...
92
93
94
95
96
97
98
99
  # Simple expansion of %home%, %cwd% and %gitroot%
  proc expandDirs(templ: string): string =
    result = templ.replace("%home%", homeDir)
    result = result.replace("%cwd%", currentDir)
    if result.contains("%gitroot%"):
      if gitRootDir.isNil: quit("Not in a git clone, can not expand %gitroot% in '" & templ & "'") 
      result = result.replace("%gitroot%", gitRootDir)
  
dab0c5b0   Göran Krampe   Added --version, ...
100
  # Load a blimp.conf file
74272cdb   Göran Krampe   First commit
101
  proc parseConfFile(filename: string) =
74272cdb   Göran Krampe   First commit
102
103
    var f = newFileStream(filename, fmRead)
    if f != nil:
dab0c5b0   Göran Krampe   Added --version, ...
104
      if verbose: echo "Reading config: " & filename
386557e6   Göran Krampe   Added support for...
105
      var p: CfgParser  
74272cdb   Göran Krampe   First commit
106
107
108
109
110
111
112
113
114
      open(p, f, filename)
      while true:
        var e = next(p)
        case e.kind
        of cfgEof: 
          break
        of cfgSectionStart:
          continue # Ignore
        of cfgKeyValuePair:
b9ad52ff   Göran Krampe   Added default con...
115
          case e.key
dab0c5b0   Göran Krampe   Added --version, ...
116
          of "blimpstore":
78569137   Göran Krampe   Added directory e...
117
            if blimpStore.isNil: blimpStore = expandDirs(e.value)
b9ad52ff   Göran Krampe   Added default con...
118
          of "remote":
78569137   Göran Krampe   Added directory e...
119
            if remoteBlimpStore.isNil: remoteBlimpStore = expandDirs(e.value)
dab0c5b0   Göran Krampe   Added --version, ...
120
121
          of "password":
            if rsyncPassword.isNil: rsyncPassword = e.value
b9ad52ff   Göran Krampe   Added default con...
122
          of "upload":
78569137   Göran Krampe   Added directory e...
123
            if uploadCommandFormat.isNil: uploadCommandFormat = expandDirs(e.value)
b9ad52ff   Göran Krampe   Added default con...
124
          of "download":
78569137   Göran Krampe   Added directory e...
125
            if downloadCommandFormat.isNil: downloadCommandFormat = expandDirs(e.value)
e914743a   Göran Krampe   Added remove comm...
126
          of "delete":
78569137   Göran Krampe   Added directory e...
127
            if deleteCommandFormat.isNil: deleteCommandFormat = expandDirs(e.value)
aaf9bcef   Göran Krampe   Upped to version ...
128
129
          of "version":
            if blimpVersion.isNil: blimpVersion = e.value
74272cdb   Göran Krampe   First commit
130
131
132
133
134
135
136
137
          else:
            quit("Unknown configuration: " & e.key)
        of cfgOption:
          quit("Unknown configuration: " & e.key)
        of cfgError:
          quit("Parsing " & filename & ": " & e.msg)
      close(p)
  
db95b901   Göran Krampe   Various fixes, mo...
138
139
140
141
  # Trivial helper to enable verbose
  proc run(cmd: string): auto =
    if verbose: echo(cmd)
    execCmd(cmd)
74272cdb   Göran Krampe   First commit
142
  
dab0c5b0   Göran Krampe   Added --version, ...
143
144
  # Every rsync command, make sure we have a password file
  proc rsyncRun(cmd: string): auto =
78569137   Göran Krampe   Added directory e...
145
146
    if not rsyncPassword.isNil:
      writeFile(blimpStore / ".blimp.pass", rsyncPassword)
7e507b62   Göran Krampe   Fixes discovered ...
147
      if execCmd("chmod 600 \"" & blimpStore / ".blimp.pass\"") != 0:
78569137   Göran Krampe   Added directory e...
148
        quit("Failed to chmod 600 " & blimpStore / ".blimp.pass")
dab0c5b0   Göran Krampe   Added --version, ...
149
150
    run(cmd)
  
5fc367ad   Göran Krampe   Renamed to blimp,...
151
152
153
  # Upload a file to the remote master blimpStore
  proc uploadFile(blimpFilename: string) =
    if remoteBlimpStore.isNil:
e914743a   Göran Krampe   Added remove comm...
154
      echo("Remote blimpstore not set in configuration file, skipping uploading content:\n\t" & blimpFilename)
74272cdb   Göran Krampe   First commit
155
      return
dab0c5b0   Göran Krampe   Added --version, ...
156
    let errorCode = rsyncRun(format(uploadCommandFormat, blimpFilename, remoteBlimpStore, blimpStore))
b9ad52ff   Göran Krampe   Added default con...
157
158
    if errorCode != 0:
      quit("Something went wrong uploading " & blimpFilename & " to " & remoteBlimpStore, 2)
74272cdb   Göran Krampe   First commit
159
    
5fc367ad   Göran Krampe   Renamed to blimp,...
160
161
162
163
  # 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)
dab0c5b0   Göran Krampe   Added --version, ...
164
    let errorCode = rsyncRun(format(downloadCommandFormat, blimpFilename, remoteBlimpStore, blimpStore))
b9ad52ff   Göran Krampe   Added default con...
165
166
    if errorCode != 0:
      quit("Something went wrong downloading " & blimpFilename & " from " & remoteBlimpStore, 3)
5fc367ad   Göran Krampe   Renamed to blimp,...
167
  
e914743a   Göran Krampe   Added remove comm...
168
169
170
171
  # Delete a file from the remote master blimpStore
  proc remoteDeleteFile(blimpFilename: string) =
    if remoteBlimpStore.isNil:
      return
dab0c5b0   Göran Krampe   Added --version, ...
172
    let errorCode = rsyncRun(format(deleteCommandFormat, blimpFilename, remoteBlimpStore, blimpStore))
e914743a   Göran Krampe   Added remove comm...
173
174
    if errorCode != 0:
      quit("Something went wrong deleting " & blimpFilename & " from " & remoteBlimpStore, 3)
5fc367ad   Göran Krampe   Renamed to blimp,...
175
  
3e2f4c14   Göran Krampe   Added upload comm...
176
  # Copy content to blimpStore and upload if it was a new file or upload == true.
5fc367ad   Göran Krampe   Renamed to blimp,...
177
178
  proc copyToBlimpStore(filename, blimpFilename: string) =
    if not existsFile(blimpStore / blimpFilename):
aaf9bcef   Göran Krampe   Upped to version ...
179
180
181
182
183
184
185
      if stdio:
        try:
          writeFile(blimpStore / blimpFilename, stdinContent)
        except:
          quit("Failed writing file: " & blimpStore / blimpFilename & " from stdin", 1)
      else:
        copyFile(filename, blimpStore / blimpFilename)
ec7d9613   Göran Krampe   Added option --fi...
186
      uploadFile(blimpFilename)
3e2f4c14   Göran Krampe   Added upload comm...
187
    
5fc367ad   Göran Krampe   Renamed to blimp,...
188
189
  
  # Copy content from blimpStore, and downloading first if needed
e914743a   Göran Krampe   Added remove comm...
190
  proc copyFromBlimpStore(blimpFilename, filename: string) =
5fc367ad   Göran Krampe   Renamed to blimp,...
191
192
    if not existsFile(blimpStore / blimpFilename):
      downloadFile(blimpFilename)
aaf9bcef   Göran Krampe   Upped to version ...
193
194
195
196
197
198
199
200
    if stdio:
      try:
        var content = readFile(blimpStore / blimpFilename)
        write(stdout, content)
      except:
        quit("Failed reading file: " & blimpStore / blimpFilename & " to stdout", 1)
    else:
      copyFile(blimpStore / blimpFilename, filename)
74272cdb   Göran Krampe   First commit
201
  
e914743a   Göran Krampe   Added remove comm...
202
203
204
205
206
207
  # Delete from blimpStore and remote.
  proc deleteFromBlimpStore(blimpFilename, filename: string) =
    if existsFile(blimpStore / blimpFilename):
      removeFile(blimpStore / blimpFilename)
    remoteDeleteFile(blimpFilename)
  
aaf9bcef   Göran Krampe   Upped to version ...
208
  proc blimpFileNameFromString(line: string): string =
386557e6   Göran Krampe   Added support for...
209
210
    let hashline = split(strip(line), ':')
    if hashline[0] == "blimphash":
e914743a   Göran Krampe   Added remove comm...
211
212
213
214
      result = hashline[1]
    else:
      result = nil
  
3e2f4c14   Göran Krampe   Added upload comm...
215
  # Pick out blimpFilename (filename & "-" & hash) or nil
aaf9bcef   Göran Krampe   Upped to version ...
216
217
218
219
220
221
222
223
224
  proc blimpFileName(filename: string): string =
    if stdio:
      blimpFileNameFromString(stdinContent)
    else:
      var hashfile: File
      if not open(hashfile, filename):
        quit("Failed opening file: " & filename, 4)
      blimpFileNameFromString(string(readLine(hashfile)))  
  
e914743a   Göran Krampe   Added remove comm...
225
226
  # Get hash and compute blimpFilename
  proc computeBlimpFilename(filename: string): string =
dab0c5b0   Göran Krampe   Added --version, ...
227
228
229
230
231
232
    var content: string
    try:
      content = readFile(filename)
    except:
      quit("Failed opening file: " & filename, 1)
    let hash = getMD5(content)
14d16aa7   Göran Krampe   Now the git filte...
233
    result = extractFilename(filename) & "-" & hash
e914743a   Göran Krampe   Added remove comm...
234
   
5fc367ad   Göran Krampe   Renamed to blimp,...
235
  # Copy original file to blimpStore and replace with hash stub in git.
74272cdb   Göran Krampe   First commit
236
  proc deflate(filename: string) =
dab0c5b0   Göran Krampe   Added --version, ...
237
238
239
240
241
242
243
    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)
aaf9bcef   Göran Krampe   Upped to version ...
244
      if stdio:
386557e6   Göran Krampe   Added support for...
245
        write(stdout, "blimphash:" & blimpFilename)
aaf9bcef   Göran Krampe   Upped to version ...
246
      else:
386557e6   Göran Krampe   Added support for...
247
        writeFile(filename, "blimphash:" & blimpFilename)
dab0c5b0   Göran Krampe   Added --version, ...
248
      if verbose: echo("\t" & filename & " deflated.")
e914743a   Göran Krampe   Added remove comm...
249
  
386557e6   Göran Krampe   Added support for...
250
251
  # Iterator over all deflated files in the git clone
  iterator allDeflated() =
7e507b62   Göran Krampe   Fixes discovered ...
252
    let filenames = cmd("git ls-files " & gitRootDir).split({'\l', '\c'})
386557e6   Göran Krampe   Added support for...
253
254
255
    for fn in filenames:
      if not blimpFilename(fn).isNil:
        yield fn
ec7d9613   Göran Krampe   Added option --fi...
256
257
258
        
  # Iterator over all files matching the blimp filter in the git clone
  iterator allFiltered() =
7e507b62   Göran Krampe   Fixes discovered ...
259
    let lines = cmd("git ls-files | git check-attr --stdin filter").split({'\l', '\c'})
ec7d9613   Göran Krampe   Added option --fi...
260
261
262
263
    for line in lines:
      let status = line.split(':')
      if strip(status[2]) == "blimp":
        yield status[0]
386557e6   Göran Krampe   Added support for...
264
  
5fc367ad   Göran Krampe   Renamed to blimp,...
265
  # Parse out hash from hash stub and copy back original content from blimpStore.
74272cdb   Göran Krampe   First commit
266
  proc inflate(filename: string) =
dab0c5b0   Göran Krampe   Added --version, ...
267
    if verbose: echo "Inflating " & filename
e914743a   Göran Krampe   Added remove comm...
268
269
    let blimpFilename = blimpFilename(filename)
    if blimpFilename.isNil:
dab0c5b0   Göran Krampe   Added --version, ...
270
      echo("\t" & filename & " is not deflated, skipping.")
e914743a   Göran Krampe   Added remove comm...
271
272
    else:
      copyFromBlimpStore(blimpfilename, filename)
dab0c5b0   Göran Krampe   Added --version, ...
273
      if verbose: echo("\t" & filename & " inflated.")
e914743a   Göran Krampe   Added remove comm...
274
275
276
277
278
279
280
  
  # 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)
74272cdb   Göran Krampe   First commit
281
    else:
e914743a   Göran Krampe   Added remove comm...
282
283
284
      blimpFilename = computeBlimpFilename(filename)
    deleteFromBlimpStore(blimpfilename, filename)
    echo("\t" & filename & " content removed from blimpstore locally and remotely.")
5fc367ad   Göran Krampe   Renamed to blimp,...
285
  
dab0c5b0   Göran Krampe   Added --version, ...
286
  
3e2f4c14   Göran Krampe   Added upload comm...
287
288
289
290
291
292
293
294
295
296
297
298
299
  # Copy original file to blimpStore and replace with hash stub in git.
  proc upload(filename: string) =
    if verbose: echo "Uploading " & filename
    var blimpFilename = blimpFilename(filename)
    if blimpFilename.isNil:
      blimpFilename = computeBlimpFilename(filename)
    if existsFile(blimpStore / blimpFilename):
      uploadFile(blimpFilename)
      if verbose: echo("\t" & filename & " uploaded.")
    else:
      if verbose: echo("\t" & filename & " is not in blimpstore, skipping.")
  
  
dab0c5b0   Göran Krampe   Added --version, ...
300
301
302
303
304
305
306
307
308
309
310
311
312
  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)
  
78569137   Göran Krampe   Added directory e...
313
314
315
  proc `$`(x: string): string =
    if x.isNil: "nil" else: x
  
dab0c5b0   Göran Krampe   Added --version, ...
316
317
  proc dumpConfig() =
    echo "\nDump of configuration:"
7e507b62   Göran Krampe   Fixes discovered ...
318
319
320
321
322
    echo "\tblimpStore: " & $blimpStore
    echo "\tremoteBlimpStore: " & $remoteBlimpStore
    echo "\tuploadCommandFormat: " & $uploadCommandFormat
    echo "\tdownloadCommandFormat: " & $downloadCommandFormat
    echo "\tdeleteCommandFormat: " & $deleteCommandFormat
78569137   Göran Krampe   Added directory e...
323
    echo "\trsyncPassword: " & $rsyncPassword
aaf9bcef   Göran Krampe   Upped to version ...
324
    echo "\tblimpVersion: " & $blimpVersion
dab0c5b0   Göran Krampe   Added --version, ...
325
    echo "\n"
74272cdb   Göran Krampe   First commit
326
  
386557e6   Göran Krampe   Added support for...
327
  let synopsis = """
db95b901   Göran Krampe   Various fixes, mo...
328
    blimp [options] <command> <filenames...>
dab0c5b0   Göran Krampe   Added --version, ...
329
330
      -h,--help                Show this
      --version                Show version of blimp
aaf9bcef   Göran Krampe   Upped to version ...
331
      -v,--verbose             Verbosity, only works without -s
386557e6   Göran Krampe   Added support for...
332
333
      -i,--init                Set blimp filter in git config
      ----------
3e2f4c14   Göran Krampe   Added upload comm...
334
      <command>   (string)     (d)eflate, (i)nflate, remove, upload
386557e6   Göran Krampe   Added support for...
335
      -a,--all                 Operate on all deflated files in clone
ec7d9613   Göran Krampe   Added option --fi...
336
      -f,--filter              Operate on all files matching blimp filter
386557e6   Göran Krampe   Added support for...
337
338
339
340
341
      ----------
      -s,--stdio               If given, use stdin/stdout for content.
      <filenames> (string...)  One or more filepaths to inflate/deflate
  """
  let help = """
3e2f4c14   Göran Krampe   Added upload comm...
342
  
aaf9bcef   Göran Krampe   Upped to version ...
343
344
345
    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 - it uses rsync like git-fat.
386557e6   Göran Krampe   Added support for...
346
347
    It is a single binary without any dependencies. Its not as advanced
    as git-fat but basically does the same thing.
aaf9bcef   Göran Krampe   Upped to version ...
348
349
350
  
    Manual use:
  
386557e6   Göran Krampe   Added support for...
351
352
    Use "blimp d mybigfile" to deflate a file, typically before commit.
    Use "blimp i mybigfile" to inflate it back to original content.
aaf9bcef   Göran Krampe   Upped to version ...
353
  
3e2f4c14   Göran Krampe   Added upload comm...
354
355
    When deflated the file only has this content:
    
386557e6   Göran Krampe   Added support for...
356
      "blimphash:" <filename> "-" <md5sum>
aaf9bcef   Göran Krampe   Upped to version ...
357
  
386557e6   Göran Krampe   Added support for...
358
    Deflate also copies the real content to your local blimpstore:
aaf9bcef   Göran Krampe   Upped to version ...
359
    
386557e6   Göran Krampe   Added support for...
360
      <blimpstore>/<filename>-<md5sum>
aaf9bcef   Göran Krampe   Upped to version ...
361
  
386557e6   Göran Krampe   Added support for...
362
    ...and if configured also uploads it to "remote", using rsync.
aaf9bcef   Göran Krampe   Upped to version ...
363
364
365
366
  
    Configuration is in these locations in order:
   
      ./.blimp.conf
386557e6   Göran Krampe   Added support for...
367
      <gitroot>/.blimp.conf
aaf9bcef   Göran Krampe   Upped to version ...
368
369
370
371
372
373
374
375
376
377
378
379
      ~/<blimpstore>/.blimp.conf
      ~/.blimp.conf
  
    This way you can have settings per directory, per git clone,
    per store and per user. A default blimpstore with a commented .blimp.conf
    is created in ~/blimpstore if you run blimp and no .blimp.conf is found.
  
    Edit ~/blimpstore/.blimp.conf (or in another location) and set a proper
    remote and the proper rsync password. This ensures that its also properly
    synced with a master rsync repository that is typically shared.
  
    Inflate will bring back the original content by copying from
386557e6   Göran Krampe   Added support for...
380
    your local blimpstore, and if its not there, first download from the remote.
aaf9bcef   Göran Krampe   Upped to version ...
381
382
383
384
385
    Use this whenever you need to work/edit the big file - in order to get
    its real content.
  
    The filenames given are all processed. If -s is used content is processed via
    stdin/stdout and only one filename can be passed. This is used when running blimp
386557e6   Göran Krampe   Added support for...
386
    via a git filter (smudge/clean), see below.
aaf9bcef   Göran Krampe   Upped to version ...
387
388
389
390
391
  
    The remove command (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.
386557e6   Göran Krampe   Added support for...
392
    
3e2f4c14   Göran Krampe   Added upload comm...
393
394
395
396
    The upload command (no single character shortcut) will upload the given file
    from the local blimpstore to the remote. This is normally done automatically,
    but this way you can make sure they are up on the remote.
    
386557e6   Göran Krampe   Added support for...
397
398
399
    In order to have blimp work automatically you can:
    
    * Create a .gitattributes file with lines like:
ec7d9613   Göran Krampe   Added option --fi...
400
      *.png filter=blimp binary
386557e6   Göran Krampe   Added support for...
401
402
403
404
405
406
407
408
409
410
411
412
413
      
    * Configure blimp as a filter by running:
      git config filter.blimp.clean "blimp -s d %f"
      git config filter.blimp.smudge "blimp -s i %f"
  
    The above git config can be done by running "blimp --init".
  
    When the above is done (per clone) git will automatically run blimp deflate
    just before committing and blimp inflate when operations are done.
    
    This means that if you clone a git repository that already has a .gitattributes
    file in it that uses the blimp filter, then you should do:
    
3e2f4c14   Göran Krampe   Added upload comm...
414
      blimp --init inflate --filter
386557e6   Göran Krampe   Added support for...
415
416
417
    
    This will configure the blimp filter and also find and inflate all deflated
    files throughout the clone.
aaf9bcef   Göran Krampe   Upped to version ...
418
  """
db95b901   Göran Krampe   Various fixes, mo...
419
  
74272cdb   Göran Krampe   First commit
420
  ################################ main #####################################
78569137   Göran Krampe   Added directory e...
421
422
423
424
425
  # Set some dirs
  homeDir = getHomeDir()
  homeDir = homeDir[0.. -2] # Not sure why it keeps a trailing "/" on Linux
  currentDir = getCurrentDir()
  gitRootDir = gitRoot()
7e507b62   Göran Krampe   Fixes discovered ...
426
  echo gitRootDir
74272cdb   Göran Krampe   First commit
427
  
dab0c5b0   Göran Krampe   Added --version, ...
428
  # Using lapp to get args, on parsing failure this will show usage automatically
386557e6   Göran Krampe   Added support for...
429
  var args = parse(synopsis)
dab0c5b0   Göran Krampe   Added --version, ...
430
  verbose = args["verbose"].asBool
aaf9bcef   Göran Krampe   Upped to version ...
431
  stdio = args["stdio"].asBool
ec7d9613   Göran Krampe   Added option --fi...
432
433
  onAllDeflated = args["all"].asBool
  onAllFiltered = args["filter"].asBool
aaf9bcef   Göran Krampe   Upped to version ...
434
435
436
437
438
439
440
441
442
443
444
  
  # Can't do verbose with -s, that messes up stdout,
  # read in all of stdin once and for all
  if stdio:
    verbose = false
    try:
      stdinContent = readAll(stdin)
      close(stdin)
    except:
      quit("Failed reading stdin", 1)
  
dab0c5b0   Göran Krampe   Added --version, ...
445
446
  
  # Parse configuration files, may shadow and override each other
78569137   Göran Krampe   Added directory e...
447
  parseConfFile(currentDir / ".blimp.conf")
386557e6   Göran Krampe   Added support for...
448
  if not gitRootDir.isNil and gitRootDir != currentDir:
78569137   Göran Krampe   Added directory e...
449
    parseConfFile(gitRootDir / ".blimp.conf")
74272cdb   Göran Krampe   First commit
450
  
7e507b62   Göran Krampe   Fixes discovered ...
451
452
453
454
455
  if existsDir(homeDir / "blimpstore"):
    parseConfFile(homeDir / "blimpstore" / ".blimp.conf")
  
  parseConfFile(homeDir / ".blimp.conf")
  
dab0c5b0   Göran Krampe   Added --version, ...
456
457
  # If we haven't gotten a blimpstore yet, we set a default one
  if blimpStore.isNil:
78569137   Göran Krampe   Added directory e...
458
    blimpStore = homeDir / "blimpstore"
74272cdb   Göran Krampe   First commit
459
  
74272cdb   Göran Krampe   First commit
460
  
386557e6   Göran Krampe   Added support for...
461
  # Let's just show what we have :)
dab0c5b0   Göran Krampe   Added --version, ...
462
  if verbose: dumpConfig()
e914743a   Göran Krampe   Added remove comm...
463
  
dab0c5b0   Göran Krampe   Added --version, ...
464
  # These two are special, they short out
386557e6   Göran Krampe   Added support for...
465
  if args.showHelp: quit(synopsis & help)
dab0c5b0   Göran Krampe   Added --version, ...
466
  if args.showVersion: quit("blimp version: " & versionAsString)
74272cdb   Göran Krampe   First commit
467
  
aaf9bcef   Göran Krampe   Upped to version ...
468
469
470
471
  # Check blimpVersion
  if not blimpVersion.isNil and blimpVersion != versionAsString:
    quit("Wrong version of blimp, configuration wants: " & blimpVersion)
  
386557e6   Göran Krampe   Added support for...
472
473
474
475
476
  # Should we install the filter?
  if args["init"].asBool:
    ensureBlimpFilter()
    if verbose: echo("Installed blimp filter")
  
db95b901   Göran Krampe   Various fixes, mo...
477
  let command = args["command"].asString
3e2f4c14   Göran Krampe   Added upload comm...
478
479
480
  var filenames = initSet[string]()
  
  # Add upp all files to operate on in a Set
386557e6   Göran Krampe   Added support for...
481
  if args.hasKey("filenames"):
3e2f4c14   Göran Krampe   Added upload comm...
482
483
484
485
486
487
488
489
490
    for f in args["filenames"].asSeq:
      if f.asString != "":
        filenames.incl(f.asString)
  if onAllDeflated:
    for fn in allDeflated():
      filenames.incl(fn)
  if onAllFiltered:
    for fn in allFiltered():
      filenames.incl(fn)
dab0c5b0   Göran Krampe   Added --version, ...
491
492
493
494
  
  # Make sure the local blimpstore is setup.
  setupBlimpStore()
  
74272cdb   Göran Krampe   First commit
495
  # Do the deed
386557e6   Göran Krampe   Added support for...
496
497
  if command != "":
    if command == "d" or command == "deflate":
3e2f4c14   Göran Krampe   Added upload comm...
498
499
      for fn in filenames:
        deflate(fn)
386557e6   Göran Krampe   Added support for...
500
    elif command == "i" or command == "inflate":
3e2f4c14   Göran Krampe   Added upload comm...
501
502
      for fn in filenames:
        inflate(fn)
386557e6   Göran Krampe   Added support for...
503
504
    elif command == "remove":
      for fn in filenames:
3e2f4c14   Göran Krampe   Added upload comm...
505
506
507
508
509
        remove(fn)
    elif command == "upload":
      echo repr(filenames)
      for fn in filenames.items:
        upload(fn)
386557e6   Göran Krampe   Added support for...
510
    else:
3e2f4c14   Göran Krampe   Added upload comm...
511
      quit("Unknown command: \"" & command & "\",  only (d)eflate, (i)inflate, remove or upload are valid.", 6)
74272cdb   Göran Krampe   First commit
512
513
514
  
  # All good
  quit(0)