/*
Allow us to backup the storage directory before formatting.
556627
void backupDirs() throws IOException {
    File rootDir = sd.getRootDir();
    FileSystem localFs = FileSystem.getLocal(conf).getRaw();
    NNStorageDirectoryRetentionManager.backupFiles(localFs, rootDir, conf);
  }
852095
def __prepare(self, filestem, pos, neg, b):
        
        posFile = open('%s/%s.f' % (self.tmpdir, filestem), 'w')
        negFile = open('%s/%s.n' % (self.tmpdir, filestem), 'w')
        bFile = open('%s/%s.b' % (self.tmpdir, filestem), 'w')

        posFile.write(pos)
        negFile.write(neg)
        bFile.write(b)

        posFile.close()
        negFile.close()
        bFile.close()
1140802
function ensureLogDir(dir) {
    if (!dir) return;
    let mkdir = true;
    try {
        const stat = fs.statSync(dir);
        if (stat && !stat.isDirectory()) {
            mkdir = false;
            throw new Error(`'logDir' must be a directory`);
        }
    } catch (e) {
        if (mkdir) {
            fs.mkdirSync(dir);
        }
    }
}
525936
private static String formatPathToDir(Path path) {
    return path.toString().endsWith(Path.SEPARATOR) ? path.toString() : path.toString() + Path.SEPARATOR;
  }
244437
function(/**string*/ outDir, /**string*/ fileName, /**string*/ content) {
		fs.writeFileSync(outDir + "/" + fileName, content, IO.encoding);
	}
799749
def store_output_files(self, dir_path):
        """"""
        if self.last_result:
            for entry in os.listdir(self.last_result["output_dir"]):
                path = os.path.join(self.last_result["output_dir"], entry)
                if os.path.isfile(path):
                    shutil.copy(path, os.path.join(dir_path, entry))
            shutil.copy(
                self.get_path(OslomRunner.SEED_FILE),
                os.path.join(dir_path, OslomRunner.SEED_FILE))
            args_file = os.path.join(dir_path, OslomRunner.ARGS_FILE)
            with open(args_file, "w") as writer:
                writer.write("{}\n".format(" ".join(self.last_result["args"])))
            self.id_remapper.store_mapping(
                os.path.join(dir_path, OslomRunner.IDS_MAPPING_FILE))
1140983
public static void backupFiles(FileSystem fs, File dest, 
      Configuration conf) throws IOException {
    // check if we can still backup
    cleanUpAndCheckBackup(conf, dest);
    
    int MAX_ATTEMPT = 3;
    for (int i = 0; i < MAX_ATTEMPT; i++) {
      try {
        String mdate = dateForm.get().format(new Date(System.currentTimeMillis()));
        if (dest.exists()) {
          File tmp = new File (dest + File.pathSeparator + mdate);
          FLOG.info("Moving aside " + dest + " as " + tmp);
          if (!dest.renameTo(tmp)) {
            throw new IOException("Unable to rename " + dest +
                                  " to " +  tmp);
          }
          FLOG.info("Moved aside " + dest + " as " + tmp);
        }
        return;
      } catch (IOException e) {
        FLOG.error("Creating backup exception. Will retry ", e);
        try {
          Thread.sleep(1000);
        } catch (InterruptedException iex) {
          throw new IOException(iex);
        }
      }
    }
    throw new IOException("Cannot create backup for: " + dest);
  }
687976
function formatRepoUrl( dir ) {
	dir = path.resolve( dir );
	dir = dir.replace( /\\/g, '/' );
	return g_serverUser + '@127.0.0.1:' + dir;
	//return 'file:///' + dir;
}
1244842
def save(self, folder, format):
        
        try:
            mkdir(folder)
        except Exception:
            pass
        for document in self.documents:
            f = join(folder, document.id)
            content = u"\n".join(document.sentences)
            write(f, content)
1309077
def save_data(self, idx):
        """"""
        for name in self:
            actual = getattr(self, name)
            diskflag = getattr(self, '_%s_diskflag' % name)
            ramflag = getattr(self, '_%s_ramflag' % name)
            if diskflag:
                file_ = getattr(self, '_%s_file' % name)
                ndim = getattr(self, '_%s_ndim' % name)
                length_tot = 1
                for jdx in range(ndim):
                    length = getattr(self, '_%s_length_%s' % (name, jdx))
                    length_tot *= length
                if ndim:
                    raw = struct.pack(length_tot*'d', *actual.flatten())
                else:
                    raw = struct.pack('d', actual)
                file_.write(raw)
            elif ramflag:
                array = getattr(self, '_%s_array' % name)
                array[idx] = actual
1118674
def write_backup_meta_data(self):
        """"""
        auto_backup_meta_file = os.path.join(self._tmp_storage_path, FILE_NAME_AUTO_BACKUP)
        storage.storage_utils.write_dict_to_json(self.meta, auto_backup_meta_file)
711755
public function save()
    {
        $this->makeBackup();

        if (!is_dir(dirname($this->filename))) {
            mkdir(dirname($this->filename), 0700, true);
        }

        file_put_contents($this->filename, (string) $this);

        return $this;
    }
264180
function() {
      var i = 0;
      grunt.log.writeln( 'Ensuring directories:' );

      var ensureDir = function( dir ) {
        grunt.log.ok( options.remoteDir + dir );

        if ( directoriesChecked.indexOf( dir ) > -1 && ((i + 1) < dirs.length) ) {
          directoriesChecked.push( dir );
          i += 1;
          ensureDir( dirs[ i ] );
        } else if ( i >= dirs.length ) {
          uploadFiles();
        } else {
          directoriesChecked.push( dir );
          client
            .raw( 'mkdir -p "' + options.remoteDir + dir + '"' )
            .exec(function( err, res ) {
              if ( err ) {
                grunt.log.error( err );
              }

              if ( (i + 1) < dirs.length ) {
                 i += 1;
                ensureDir( dirs[ i ] );
              } else {
                uploadFiles();
              }
            });
        }
      };

      if ( dirs.length > 0 ) {
        ensureDir( dirs[0] );
      }
    }
57835
public static void copyDirectories(File[] directories, String storageFolder) throws IOException {
        storageFolder = checkFolder(storageFolder) + ValueConsts.SEPARATOR;
        for (File directory : directories) {
            copyDirectory(directory, new File(storageFolder + directory.getName()));
        }
    }
385572
def backup(schema, uuid, export_filter, export_format, filename, pretty, export_all, omit):
    """"""

    export_format = export_format.upper()

    if pretty:
        indent = 4
    else:
        indent = 0

    f = None

    if filename:
        try:
            f = open(filename, 'w')
        except (IOError, PermissionError) as e:
            backup_log('Could not open output file for writing:', exc=True, lvl=error)
            return

    def output(what, convert=False):
        """Output the backup in a specified format."""

        if convert:
            if export_format == 'JSON':
                data = json.dumps(what, indent=indent)
            else:
                data = ""
        else:
            data = what

        if not filename:
            print(data)
        else:
            f.write(data)

    if schema is None:
        if export_all is False:
            backup_log('No schema given.', lvl=warn)
            return
        else:
            schemata = objectmodels.keys()
    else:
        schemata = [schema]

    all_items = {}

    for schema_item in schemata:
        model = objectmodels[schema_item]

        if uuid:
            obj = model.find({'uuid': uuid})
        elif export_filter:
            obj = model.find(literal_eval(export_filter))
        else:
            obj = model.find()

        items = []
        for item in obj:
            fields = item.serializablefields()
            for field in omit:
                try:
                    fields.pop(field)
                except KeyError:
                    pass
            items.append(fields)

        all_items[schema_item] = items

        # if pretty is True:
        #    output('\n// Objectmodel: ' + schema_item + '\n\n')
        # output(schema_item + ' = [\n')

    output(all_items, convert=True)

    if f is not None:
        f.flush()
        f.close()
435281
def backup(outputdir):
    

    ecode = 0
    try:
        anchore_print('Backing up anchore system to directory '+str(outputdir)+' ...')
        backupfile = config.backup(outputdir)
        anchore_print({"anchore_backup_tarball":str(backupfile)}, do_formatting=True)
    except Exception as err:
        anchore_print_err('operation failed')
        ecode = 1

    sys.exit(ecode)
254993
def save_dir(key, dir_path, *refs):
    
    if not os.path.isdir(dir_path):
        return error(
            "Output '{}' set to a missing directory: '{}'.".format(key, dir_path)
        )

    result = {key: {"dir": dir_path}}

    if refs:
        missing_refs = [
            ref for ref in refs if not (os.path.isfile(ref) or os.path.isdir(ref))
        ]
        if len(missing_refs) > 0:
            return error(
                "Output '{}' set to missing references: '{}'.".format(
                    key, ', '.join(missing_refs)
                )
            )
        result[key]["refs"] = refs

    return json.dumps(result)