Blame view

blimp.nim 9.05 KB
b9ad52ff   Göran Krampe   Added default con...
1
  import md5, os, osproc, parseopt2, strutils, parsecfg, streams, lapp, subexes
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
5fc367ad   Göran Krampe   Renamed to blimp,...
5
6
  # 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.
74272cdb   Göran Krampe   First commit
7
  #
5fc367ad   Göran Krampe   Renamed to blimp,...
8
9
10
11
  # Manual use:
  #
  # Use "blimp d mybigfile" to deflate it before commit.
  # Use "blimp i mybigfile" to inflate it back to original size.
74272cdb   Göran Krampe   First commit
12
13
14
15
  #
  # When deflated the file only has an md5sum string inside it.
  #
  # The file is copied over into:
5fc367ad   Göran Krampe   Renamed to blimp,...
16
17
18
19
20
  #  <homedir>/blimpStore/<originalfilename>-<md5sum>
  #
  # Configuration is in:
  #   <gitroot>/.blimp.conf
  #   ~/blimpstore/.blimp.conf
74272cdb   Göran Krampe   First commit
21
  
b9ad52ff   Göran Krampe   Added default con...
22
  var
ed979253   Göran Krampe   Fixed #1, rsync p...
23
    blimpStore, uploadCommandFormat, downloadCommandFormat, deleteCommandFormat, rsyncPassword: string
b9ad52ff   Göran Krampe   Added default con...
24
25
    remoteBlimpStore: string = nil
    verbose: bool
74272cdb   Göran Krampe   First commit
26
  
b9ad52ff   Göran Krampe   Added default con...
27
28
29
  let
    defaultConfig = """
  [rsync]
e914743a   Göran Krampe   Added remove comm...
30
  # Set this to your remote rsync daemon area
ed979253   Göran Krampe   Fixed #1, rsync p...
31
32
  remote = "blimpuser@some-rsync-server.com::blimpstore"
  password = some-good-rsync-password-for-blimpuser
e914743a   Göran Krampe   Added remove comm...
33
34
  
  # The following three formats should not need editing
b9ad52ff   Göran Krampe   Added default con...
35
  # $1 is filename, $2 is remote and $3 is the local blimpstore
ed979253   Göran Krampe   Fixed #1, rsync p...
36
37
  upload = "rsync --password-file $3/.blimp.pass -avzP $3/$1 $2/"
  download = "rsync --password-file $3/.blimp.pass -avzP $2/$1 $3/"
e914743a   Göran Krampe   Added remove comm...
38
  # This deletes a single file from destination, that is already deleted in source
ed979253   Göran Krampe   Fixed #1, rsync p...
39
  delete = "rsync --password-file $3/.blimp.pass -dv --delete --existing --ignore-existing --include '$1' --exclude '*' $3/ $2"
b9ad52ff   Göran Krampe   Added default con...
40
  """
74272cdb   Göran Krampe   First commit
41
  
5fc367ad   Göran Krampe   Renamed to blimp,...
42
  # Load blimp.conf file, overkill for now but...
74272cdb   Göran Krampe   First commit
43
  proc parseConfFile(filename: string) =
74272cdb   Göran Krampe   First commit
44
45
46
47
48
49
50
51
52
53
54
55
    var f = newFileStream(filename, fmRead)
    if f != nil:
      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:
b9ad52ff   Göran Krampe   Added default con...
56
57
          case e.key
          of "remote":
5fc367ad   Göran Krampe   Renamed to blimp,...
58
            remoteBlimpStore = e.value
b9ad52ff   Göran Krampe   Added default con...
59
60
61
62
          of "upload":
            uploadCommandFormat = e.value
          of "download":
            downloadCommandFormat = e.value
e914743a   Göran Krampe   Added remove comm...
63
64
          of "delete":
            deleteCommandFormat = e.value
ed979253   Göran Krampe   Fixed #1, rsync p...
65
66
          of "password":
            rsyncPassword = e.value
74272cdb   Göran Krampe   First commit
67
68
69
70
71
72
73
74
          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...
75
76
77
78
  # Trivial helper to enable verbose
  proc run(cmd: string): auto =
    if verbose: echo(cmd)
    execCmd(cmd)
74272cdb   Göran Krampe   First commit
79
  
ed979253   Göran Krampe   Fixed #1, rsync p...
80
81
82
83
84
85
86
  # 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)
  
5fc367ad   Göran Krampe   Renamed to blimp,...
87
88
89
  # Upload a file to the remote master blimpStore
  proc uploadFile(blimpFilename: string) =
    if remoteBlimpStore.isNil:
e914743a   Göran Krampe   Added remove comm...
90
      echo("Remote blimpstore not set in configuration file, skipping uploading content:\n\t" & blimpFilename)
74272cdb   Göran Krampe   First commit
91
      return
ed979253   Göran Krampe   Fixed #1, rsync p...
92
    let errorCode = rsyncRun(format(uploadCommandFormat, blimpFilename, remoteBlimpStore, blimpStore))
b9ad52ff   Göran Krampe   Added default con...
93
94
    if errorCode != 0:
      quit("Something went wrong uploading " & blimpFilename & " to " & remoteBlimpStore, 2)
74272cdb   Göran Krampe   First commit
95
    
5fc367ad   Göran Krampe   Renamed to blimp,...
96
97
98
99
  # 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)
ed979253   Göran Krampe   Fixed #1, rsync p...
100
    let errorCode = rsyncRun(format(downloadCommandFormat, blimpFilename, remoteBlimpStore, blimpStore))
b9ad52ff   Göran Krampe   Added default con...
101
102
    if errorCode != 0:
      quit("Something went wrong downloading " & blimpFilename & " from " & remoteBlimpStore, 3)
5fc367ad   Göran Krampe   Renamed to blimp,...
103
  
e914743a   Göran Krampe   Added remove comm...
104
105
106
107
  # Delete a file from the remote master blimpStore
  proc remoteDeleteFile(blimpFilename: string) =
    if remoteBlimpStore.isNil:
      return
ed979253   Göran Krampe   Fixed #1, rsync p...
108
    let errorCode = rsyncRun(format(deleteCommandFormat, blimpFilename, remoteBlimpStore, blimpStore))
e914743a   Göran Krampe   Added remove comm...
109
110
    if errorCode != 0:
      quit("Something went wrong deleting " & blimpFilename & " from " & remoteBlimpStore, 3)
5fc367ad   Göran Krampe   Renamed to blimp,...
111
112
113
114
115
116
117
118
  
  # 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
e914743a   Göran Krampe   Added remove comm...
119
  proc copyFromBlimpStore(blimpFilename, filename: string) =
5fc367ad   Göran Krampe   Renamed to blimp,...
120
121
122
    if not existsFile(blimpStore / blimpFilename):
      downloadFile(blimpFilename)
    copyFile(blimpStore / blimpFilename, filename)
74272cdb   Göran Krampe   First commit
123
  
e914743a   Göran Krampe   Added remove comm...
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
  # 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 =
    result = blimpFilename(filename)
    if result.isNil:
      var content: string
      try:
        content = readFile(filename)
      except:
        quit("Failed opening file: " & filename, 1)
      let hash = getMD5(content)
      result = filename & "-" & hash
   
5fc367ad   Göran Krampe   Renamed to blimp,...
153
  # Copy original file to blimpStore and replace with hash stub in git.
74272cdb   Göran Krampe   First commit
154
  proc deflate(filename: string) =
e914743a   Göran Krampe   Added remove comm...
155
    let blimpFilename = computeBlimpFilename(filename)
5fc367ad   Göran Krampe   Renamed to blimp,...
156
157
    copyToBlimpStore(filename, blimpFilename)
    writeFile(filename, "hash:" & blimpFilename)
db95b901   Göran Krampe   Various fixes, mo...
158
    echo("\t" & filename & " deflated.")
e914743a   Göran Krampe   Added remove comm...
159
160
161
162
163
  
  proc isInBlimpStore(filename: string): bool =
    let blimpFilename = blimpFilename(filename)
    if not blimpFilename.isNil:
      return true
db95b901   Göran Krampe   Various fixes, mo...
164
    
5fc367ad   Göran Krampe   Renamed to blimp,...
165
  # Parse out hash from hash stub and copy back original content from blimpStore.
74272cdb   Göran Krampe   First commit
166
  proc inflate(filename: string) =
e914743a   Göran Krampe   Added remove comm...
167
168
169
170
171
172
173
174
175
176
177
178
179
    let blimpFilename = blimpFilename(filename)
    if blimpFilename.isNil:
      echo("\t" & filename & " is not deflated, skipping.", 5)
    else:
      copyFromBlimpStore(blimpfilename, filename)
      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)
74272cdb   Göran Krampe   First commit
180
    else:
e914743a   Göran Krampe   Added remove comm...
181
182
183
      blimpFilename = computeBlimpFilename(filename)
    deleteFromBlimpStore(blimpfilename, filename)
    echo("\t" & filename & " content removed from blimpstore locally and remotely.")
5fc367ad   Göran Krampe   Renamed to blimp,...
184
185
186
187
188
189
190
191
192
193
194
  
  # Find git root dir or fall back on current dir
  proc gitRoot(): string =
    try:
      let tup = execCmdEx("git rev-parse --show-toplevel")
      if tup[1] == 0:
        result = tup[0]
      else:
        result = getCurrentDir()
    except:
      result = getCurrentDir()
74272cdb   Göran Krampe   First commit
195
  
db95b901   Göran Krampe   Various fixes, mo...
196
197
198
  let help = """
    blimp [options] <command> <filenames...>
      -v,--verbose             Verbosity
e914743a   Göran Krampe   Added remove comm...
199
      <command>   (string)     (d)eflate, (i)nflate, delete, (c)heck, (r)ecover
db95b901   Göran Krampe   Various fixes, mo...
200
      <filenames> (string...)  One or more filepaths to inflate/deflate
e914743a   Göran Krampe   Added remove comm...
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
      
      Edit ~/blimpstore/.blimp.conf or <gitroot>/.blimp.conf and set a proper
      remote and also create ~/blimp.pass with 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 ~/blimpstore, and if configured also upload it to
      remote, using rsync.
      
      Inflate will bring back the original content by copying from
      ~/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.
db95b901   Göran Krampe   Various fixes, mo...
219
220
    """
  
74272cdb   Göran Krampe   First commit
221
222
  ################################ main #####################################
  
5fc367ad   Göran Krampe   Renamed to blimp,...
223
224
  # Hardwired to "blimpstore" directory in home dir.
  blimpStore = getHomeDir() / "blimpstore"
74272cdb   Göran Krampe   First commit
225
226
227
  
  # Make sure we have the dir, or create it.
  try:
b9ad52ff   Göran Krampe   Added default con...
228
229
230
231
    if not existsDir(blimpStore):
      createDir(blimpStore)
    if not existsFile(blimpStore / ".blimp.conf"):
      writeFile(blimpStore / ".blimp.conf", defaultConfig)
74272cdb   Göran Krampe   First commit
232
  except:
5fc367ad   Göran Krampe   Renamed to blimp,...
233
    quit("Could not create " & blimpStore & " directory.", 1)
74272cdb   Göran Krampe   First commit
234
235
  
  
5fc367ad   Göran Krampe   Renamed to blimp,...
236
  # Parse configuration files if they exist
e914743a   Göran Krampe   Added remove comm...
237
  # The one in gitroot overrides settings from the store.
5fc367ad   Göran Krampe   Renamed to blimp,...
238
  parseConfFile(blimpStore / ".blimp.conf")
e914743a   Göran Krampe   Added remove comm...
239
240
  parseConfFile(gitRoot() / ".blimp.conf")
  
74272cdb   Göran Krampe   First commit
241
  
db95b901   Göran Krampe   Various fixes, mo...
242
243
244
245
246
  # Using lapp to get args
  let args = parse(help)
  let command = args["command"].asString
  let filenames = args["filenames"].asSeq
  verbose = args["verbose"].asBool
74272cdb   Göran Krampe   First commit
247
248
249
  
  # Do the deed
  if command == "d" or command == "deflate":
db95b901   Göran Krampe   Various fixes, mo...
250
251
    for fn in filenames:
      deflate(fn.asString)
74272cdb   Göran Krampe   First commit
252
  elif command == "i" or command == "inflate":
db95b901   Göran Krampe   Various fixes, mo...
253
254
    for fn in filenames:
      inflate(fn.asString)
e914743a   Göran Krampe   Added remove comm...
255
256
257
  elif command == "remove":
    for fn in filenames:
      remove(fn.asString)
74272cdb   Göran Krampe   First commit
258
259
260
261
262
  else:
    quit("Unknown command, only (d)eflate or (i)inflate are valid.", 6)
  
  # All good
  quit(0)