TODO:
    * Add a random string to the backup file.
    * Restore permissions after copy.
173819
def prepend_to_file(path, data, bufsize=1<<15):
    
    # Backup the file #
    backupname = path + os.extsep + 'bak'
    # Remove previous backup if it exists #
    try: os.unlink(backupname)
    except OSError: pass
    os.rename(path, backupname)
    # Open input/output files,  note: outputfile's permissions lost #
    with open(backupname) as inputfile:
        with open(path, 'w') as outputfile:
            outputfile.write(data)
            buf = inputfile.read(bufsize)
            while buf:
                outputfile.write(buf)
                buf = inputfile.read(bufsize)
    # Remove backup on success #
    os.remove(backupname)
47689
def restoredata(filename=None):
    """"""
    if filename is None:
        filename = 'credolib_state.pickle'
    ns = get_ipython().user_ns
    with open(filename, 'rb') as f:
        d = pickle.load(f)
    for k in d.keys():
        ns[k] = d[k]
352099
def restore(backup_file):
    '''
        
    '''
    if not os.path.isfile(backup_file) and not os.path.islink(backup_file):
        print 'Missing backup file: {}'.format(backup_file)
    else:
        couchdb_path = _get_couchdb_path()

        print 'Restore Cozy:'
        cmd = 'supervisorctl stop cozy-controller ; sleep 10'
        cmd += ' ; service couchdb stop ; service nginx stop'
        cmd += ' ; rm -rf {couchdb_path}/.cozy_design'
        cmd += ' {couchdb_path}/_replicator.couch'
        cmd += ' ; tar xvzf {backup_file} -C /'
        cmd += ' ; service couchdb start ; service nginx start'
        cmd = cmd.format(backup_file=backup_file, couchdb_path=couchdb_path)
        helpers.cmd_exec(cmd, show_output=True)
        helpers.wait_couchdb(10)
        cmd = 'supervisorctl start cozy-controller'
        helpers.cmd_exec(cmd, show_output=True)
80803
def verify(backup_path, fast):
    """"""
    from PyHardLinkBackup.phlb.verify import verify_backup

    verify_backup(backup_path, fast)
1129242
def put_str(content, path, share='C$', conn=None, host=None, username=None, password=None):
    '''
    
    '''
    if HAS_SMBPROTOCOL:
        return _put_str_smbprotocol(
            content, path, share, conn=conn, host=host,
            username=username, password=password
        )
    elif HAS_IMPACKET:
        return _put_str_impacket(
            content, path, share, conn=conn, host=host, username=username, password=password
        )
    raise MissingSmb("SMB library required (impacket or smbprotocol)")
266186
function copyFile(srcPath: string, destPath: string) {
  if (fs.lstatSync(srcPath).isDirectory()) {
    if (!fs.existsSync(destPath)) {
      fs.mkdirSync(destPath);
    }
    // Not recursive
    return;
  }

  return new Promise((resolve, reject) => {
    copyBinaryFile(srcPath, destPath, err => {
      if (err) {
        reject(err);
      }
      resolve(destPath);
    });
  });
}
173255
private void restore() {
    Preferences pref = Preferences
        .userNodeForPackage(ConnectionDialog.class);

    getHostField().setText(pref.get("host", "localhost"));
    getUserField().setText(pref.get("user", "guest"));

    boolean remember = pref.getBoolean("remember", false);
    boolean passwordSet = false;
    getRememberPasswordCheckBox().setSelected(remember);
    if (remember) {
      byte[] cipherText = pref.getByteArray("password", null);
      if (cipherText != null) {
        try {
          Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
          KeyGenerator keygen = KeyGenerator.getInstance("AES");
          SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
          random.setSeed(new byte[]{
            0x60, (byte) 0xFD, 0x28, 0x07, 0x35, 0x4A, 0x0D, 0x3B
          });
          byte[] iv = new byte[16];
          random.nextBytes(iv);
          IvParameterSpec spec = new IvParameterSpec(iv);
          keygen.init(128, random);
          cipher.init(Cipher.DECRYPT_MODE, keygen.generateKey(), spec);
          byte[] clearText = cipher.doFinal(cipherText);
          String password = new String(clearText);
          getPasswordField().setText(password);
          passwordSet = true;
        } catch (Exception e) {
          logger.error("Could not decrypt password", e);
        }
      }
    }
    if (!passwordSet) {
      getPasswordField().setText("");
    }
  }
859714
protected void doBackup(File backupFile) throws BackupException
   {
      ZipObjectWriter out = null;
      try
      {
         out = new ZipObjectWriter(PrivilegedFileHelper.zipOutputStream(backupFile));
         quotaPersister.backupWorkspaceData(rName, wsName, out);
      }
      catch (IOException e)
      {
         throw new BackupException(e);
      }
      finally
      {
         if (out != null)
         {
            try
            {
               out.close();
            }
            catch (IOException e)
            {
               LOG.error("Can't close output stream", e);
            }
         }
      }
   }
665366
function writeFiles(privKey, file, keyMode, cb) {
  // No file name - generate a random one under the system temp dir
  if (!file) {
    file = mkTempFile("_gitane", ".sh")
  }

  if (typeof(keyMode) === 'function') {
    cb = keyMode
    keyMode = 0600
  }

  var keyfile = mkTempFile("_gitaneid", ".key")
  var keyfileName = keyfile
  if (isWindows) {
    keyfileName = "\"" + keyfile.replace(/\\/g,"\\\\") + "\"";
  }

  var data = GIT_SSH_TEMPLATE.replace('$key', keyfileName)
  Step(
      function() {
      fs.writeFile(file, data, this.parallel())
      fs.writeFile(keyfile, privKey, this.parallel())
    },
    function(err) {
      if (err) {
        return cb(err, null)
      }
      // make script executable
      fs.chmod(file, 0755, this.parallel())
      // make key secret
      fs.chmod(keyfile, keyMode, this.parallel())
    },
    function(err) {
      if (err) {
        return cb(err, null)
      }

      return cb(null, file, keyfile)
    }
  )
}
1146177
function restoreBackup(backupRecord, mongoUri) {
  var receipts = backupRecord.receipts;
  var handler = getHandler(backupRecord.type);

  var restorePromises = receipts.map(function (receipt) {
    var tmpfile = util.getTempFileName() + '.bson';
    return R.pPipe(
      handler.restore.bind(handler),
      R.curry(R.flip(mds.dump.fs.file))(tmpfile),
      R.curryN(4, mongoRestoreFromFile)(tmpfile, mongoUri, receipt.collection)
    )(receipt.data);
  });

  return q.all(restorePromises).thenResolve('done');
}
600908
def backup_file(*, file, host):
    
    log.msg("[{host}] Backing up file '{file}'".format(host=host, file=file))
362827
function(info, file, opts) {
  if (typeof opts == 'boolean') { // old arugment backup
    opts = {backup: opts};
  }
  opts = opts || {};
  var err = null;
  try {
    ensureDirectoryExists(path.dirname(file));
    if (opts.backup && fileExists(file)) {
      fs.renameSync(file, file + '.bak');
    }
    jsonfile.writeFileSync(file, info, { spaces: 2 });
  } catch (e) {
    err = e;
  }
  return err;
}
926034
def backup(self):
        """"""
        count = 0
        name = "{}.bkp".format(self.filename)
        backup = os.path.join(self.cwd, name)
        while os.path.exists(backup):
            count += 1
            name = "{}.bkp{}".format(self.filename, count)
            backup = os.path.join(self.cwd, name)
        self.hey("Moving existing {} to {}".format(self.filename, name))
        os.rename(os.path.join(self.cwd, self.filename), backup)
1165505
def clone(self, source_id, backup_id, size,
              volume_id=None, source_host=None):
        
        volume_id = volume_id or str(uuid.uuid4())
        return self.http_put('/volumes/%s' % volume_id,
                             params=self.unused({
                                 'source_host': source_host,
                                 'source_volume_id': source_id,
                                 'backup_id': backup_id,
                                 'size': size
                             }))
305655
private void recordBackupSet(File backupDir) throws IOException {
        String[] filesInEnv = env.getHome().list();
        SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd_kk_mm_ss");
        String recordFileName = "backupset-" + format.format(new Date());
        File recordFile = new File(backupDir, recordFileName);
        if(recordFile.exists()) {
            recordFile.renameTo(new File(backupDir, recordFileName + ".old"));
        }

        PrintStream backupRecord = new PrintStream(new FileOutputStream(recordFile));
        backupRecord.println("Lastfile:" + Long.toHexString(backupHelper.getLastFileInBackupSet()));
        if(filesInEnv != null) {
            for(String file: filesInEnv) {
                if(file.endsWith(BDB_EXT))
                    backupRecord.println(file);
            }
        }
        backupRecord.close();
    }
700139
private void backup(final FileObject _backup,
                        final int _number)
        throws FileSystemException
    {
        if (_number < this.numberBackup) {
            final FileObject backFile = this.manager.resolveFile(this.manager.getBaseFile(),
                    this.storeFileName + VFSStoreResource.EXTENSION_BACKUP + _number);
            if (backFile.exists()) {
                backup(backFile, _number + 1);
            }
            _backup.moveTo(backFile);
        } else {
            _backup.delete();
        }
    }
197367
def setup(self):
        
        if self.backup:
            shutil.copy(self.input_file, "{}.orig".format(self.input_file))