blimp.nim 17.2 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 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
import md5, os, osproc, parseopt2, strutils, parsecfg, streams, lapp, subexes, tables

# 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.
# It is a single binary without any dependencies.
#
# 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:
#   "blimphash:" <filename> + <an md5sum>
# ...inside it.
#
# The file is copied over to a local dir:
#  <blimpstore>/<filename>-<md5sum>
#
# Configuration is in these locations in order:
#
#   ./.blimp.conf
#   <gitroot>/.blimp.conf
#   ~/<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.

const 
  versionMajor* = 0
  versionMinor* = 3
  versionPatch* = 0
  versionAsString* = $versionMajor & "." & $versionMinor & "." & $versionPatch

var
  blimpStore, remoteBlimpStore, uploadCommandFormat, downloadCommandFormat, deleteCommandFormat, rsyncPassword, blimpVersion: string = nil
  homeDir, currentDir, gitRootDir: string
  verbose, stdio, onAllDeflated, onAllFiltered: bool
  stdinContent: string = nil

let
  defaultConfig = """
[rsync]
# Set your local blimpstore directory. You can use %home%, %cwd% and %gitroot% in paths, works cross platform.
# 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
remote = "blimpuser@some-rsync-server.com::blimpstore"
# Set this to your rsync password, it will be written out as a password-file called .blimp.pass on every rsync.
password = "some-good-rsync-password-for-blimpuser"

# 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.
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. Yeah... insane! But it works.
delete = "rsync --password-file $3/.blimp.pass -dv --delete --existing --ignore-existing --include '$1' --exclude '*' $3/ $2"

[blimp]
# Minimal version, otherwise stop
# version = """ & versionAsString


proc cmd(cmd: string): string =
  try:
    let tup = execCmdEx(cmd)
    if tup[1] == 0:
      result = strip(tup[0])
    else:
      result = nil
  except:
    result = nil

# 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()


# 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)

# 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 = expandDirs(e.value)
        of "remote":
          if remoteBlimpStore.isNil: remoteBlimpStore = expandDirs(e.value)
        of "password":
          if rsyncPassword.isNil: rsyncPassword = e.value
        of "upload":
          if uploadCommandFormat.isNil: uploadCommandFormat = expandDirs(e.value)
        of "download":
          if downloadCommandFormat.isNil: downloadCommandFormat = expandDirs(e.value)
        of "delete":
          if deleteCommandFormat.isNil: deleteCommandFormat = expandDirs(e.value)
        of "version":
          if blimpVersion.isNil: blimpVersion = 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 =
  if not rsyncPassword.isNil:
    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):
    if stdio:
      try:
        writeFile(blimpStore / blimpFilename, stdinContent)
      except:
        quit("Failed writing file: " & blimpStore / blimpFilename & " from stdin", 1)
    else:
      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)
  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)

# Delete from blimpStore and remote.
proc deleteFromBlimpStore(blimpFilename, filename: string) =
  if existsFile(blimpStore / blimpFilename):
    removeFile(blimpStore / blimpFilename)
  remoteDeleteFile(blimpFilename)

proc blimpFileNameFromString(line: string): string =
  let hashline = split(strip(line), ':')
  if hashline[0] == "blimphash":
    result = hashline[1]
  else:
    result = nil

# Pick out blimpFilename (filename & "-" & hash)
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)))  

# 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 = extractFilename(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)
    if stdio:
      write(stdout, "blimphash:" & blimpFilename)
    else:
      writeFile(filename, "blimphash:" & blimpFilename)
    if verbose: echo("\t" & filename & " deflated.")

# Iterator over all deflated files in the git clone
iterator allDeflated() =
  let filenames = cmd("git ls-files " & gitRootDir).split('\l')
  for fn in filenames:
    if not blimpFilename(fn).isNil:
      yield fn
      
# Iterator over all files matching the blimp filter in the git clone
iterator allFiltered() =
  let lines = cmd("git ls-files | git check-attr --stdin filter").split('\l')
  for line in lines:
    let status = line.split(':')
    if strip(status[2]) == "blimp":
      yield status[0]

# 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.")


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 `$`(x: string): string =
  if x.isNil: "nil" else: x

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 "\tblimpVersion: " & $blimpVersion
  echo "\n"

let synopsis = """
  blimp [options] <command> <filenames...>
    -h,--help                Show this
    --version                Show version of blimp
    -v,--verbose             Verbosity, only works without -s
    -i,--init                Set blimp filter in git config
    ----------
    <command>   (string)     (d)eflate, (i)nflate, remove
    -a,--all                 Operate on all deflated files in clone
    -f,--filter              Operate on all files matching blimp filter
    ----------
    -s,--stdio               If given, use stdin/stdout for content.
    <filenames> (string...)  One or more filepaths to inflate/deflate
"""
let help = """
  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.
  It is a single binary without any dependencies. Its not as advanced
  as git-fat but basically does the same thing.

  Manual use:

  Use "blimp d mybigfile" to deflate a file, typically before commit.
  Use "blimp i mybigfile" to inflate it back to original content.

  When deflated the file only has:
    "blimphash:" <filename> "-" <md5sum>
  ...inside it.

  Deflate also copies the real content to your local blimpstore:
  
    <blimpstore>/<filename>-<md5sum>

  ...and if configured also uploads it to "remote", using rsync.

  Configuration is in these locations in order:
 
    ./.blimp.conf
    <gitroot>/.blimp.conf
    ~/<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
  your local blimpstore, and if its not there, first download from the remote.
  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
  via a git filter (smudge/clean), see below.

  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.
  
  In order to have blimp work automatically you can:
  
  * Create a .gitattributes file with lines like:
    *.png filter=blimp binary
    
  * 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:
  
    blimp --init inflate --all
  
  This will configure the blimp filter and also find and inflate all deflated
  files throughout the clone.
"""

################################ main #####################################
# Set some dirs
homeDir = getHomeDir()
homeDir = homeDir[0.. -2] # Not sure why it keeps a trailing "/" on Linux
currentDir = getCurrentDir()
gitRootDir = gitRoot()

# Using lapp to get args, on parsing failure this will show usage automatically
var args = parse(synopsis)
verbose = args["verbose"].asBool
stdio = args["stdio"].asBool
onAllDeflated = args["all"].asBool
onAllFiltered = args["filter"].asBool

# 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)


# Parse configuration files, may shadow and override each other
parseConfFile(currentDir / ".blimp.conf")
if not gitRootDir.isNil and gitRootDir != currentDir:
  parseConfFile(gitRootDir / ".blimp.conf")

# If we haven't gotten a blimpstore yet, we set a default one
if blimpStore.isNil:
  blimpStore = homeDir / "blimpstore"

if existsDir(blimpStore):
  parseConfFile(blimpStore / ".blimp.conf")
parseConfFile(homeDir / ".blimp.conf")

# Let's just show what we have :)
if verbose: dumpConfig()

# These two are special, they short out
if args.showHelp: quit(synopsis & help)
if args.showVersion: quit("blimp version: " & versionAsString)

# Check blimpVersion
if not blimpVersion.isNil and blimpVersion != versionAsString:
  quit("Wrong version of blimp, configuration wants: " & blimpVersion)

# Should we install the filter?
if args["init"].asBool:
  ensureBlimpFilter()
  if verbose: echo("Installed blimp filter")

let command = args["command"].asString
var filenames: seq[PValue]
if args.hasKey("filenames"):
  filenames = args["filenames"].asSeq

# Make sure the local blimpstore is setup.
setupBlimpStore()

# Do the deed
if command != "":
  if command == "d" or command == "deflate":
    if onAllFiltered:
      for fn in allFiltered():
        deflate(fn)
    else:
      for fn in filenames:
        deflate(fn.asString)
  elif command == "i" or command == "inflate":
    if onAllDeflated:
      for fn in allDeflated():
        inflate(fn)
    elif onAllFiltered:
      for fn in allFiltered():
        inflate(fn)
    else:
      for fn in filenames:
        inflate(fn.asString)
  elif command == "remove":
    for fn in filenames:
      remove(fn.asString)
  else:
    quit("Unknown command, only (d)eflate, (i)inflate or remove are valid.", 6)

# All good
quit(0)