Build one 1-course backup
335557
static protected function build_course_plan($controller, $id) {

        $plan = $controller->get_plan();

        // Add the course task, responsible for outputting
        // all the course related information
        $plan->add_task(backup_factory::get_backup_course_task($controller->get_format(), $id));

        // For the given course, add as many section tasks as necessary
        $sections = backup_plan_dbops::get_sections_from_courseid($id);
        foreach ($sections as $section) {
            self::build_section_plan($controller, $section);
        }

        // For the given course, add as many block tasks as necessary
        $blockids = backup_plan_dbops::get_blockids_from_courseid($id);
        foreach ($blockids as $blockid) {
            $plan->add_task(backup_factory::get_backup_block_task($controller->get_format(), $blockid));
        }
    }
617784
def backup_db(release=None, limit=5):
    

    assert "mysql_user" in env, "Missing mysqL_user in env"
    assert "mysql_password" in env, "Missing mysql_password in env"
    assert "mysql_host" in env, "Missing mysql_host in env"
    assert "mysql_db" in env, "Missing mysql_db in env"

    if not release:
        release = paths.get_current_release_name()

    max_versions = limit+1

    if not release:
        return

    env.run("mkdir -p %s" % paths.get_backup_path("mysql"))

    backup_file = "mysql/%s.sql.gz" % release
    backup_path = paths.get_backup_path(backup_file)

    env.run("mysqldump -u %s -p%s -h %s %s | gzip -c > %s" %
            (env.mysql_user, env.mysql_password, env.mysql_host, env.mysql_db,
             backup_path))

    # Remove older releases
    env.run("ls -dt %s/* | tail -n +%s | xargs rm -rf" % (
        paths.get_backup_path("mysql"),
        max_versions)
    )
139971
protected static function remove_excess_backups_from_directory($course, $now) {
        $config = get_config('backup');
        $dir = $config->backup_auto_destination;

        $isnotvaliddir = !file_exists($dir) || !is_dir($dir) || !is_writable($dir);
        if ($isnotvaliddir) {
            mtrace('Error: ' . $dir . ' does not appear to be a valid directory');
            return false;
        }

        // Calculate backup filename regex, ignoring the date/time/info parts that can be
        // variable, depending of languages, formats and automated backup settings.
        $filename = backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-' . $course->id . '-';
        $regex = '#' . preg_quote($filename, '#') . '.*\.mbz$#';

        // Store all the matching files into filename => timemodified array.
        $backupfiles = array();
        foreach (scandir($dir) as $backupfile) {
            // Skip files not matching the naming convention.
            if (!preg_match($regex, $backupfile)) {
                continue;
            }

            // Read the information contained in the backup itself.
            try {
                $bcinfo = backup_general_helper::get_backup_information_from_mbz($dir . '/' . $backupfile);
            } catch (backup_helper_exception $e) {
                mtrace('Error: ' . $backupfile . ' does not appear to be a valid backup (' . $e->errorcode . ')');
                continue;
            }

            // Make sure this backup concerns the course and site we are looking for.
            if ($bcinfo->format === backup::FORMAT_MOODLE &&
                    $bcinfo->type === backup::TYPE_1COURSE &&
                    $bcinfo->original_course_id == $course->id &&
                    backup_general_helper::backup_is_samesite($bcinfo)) {
                $backupfiles[$bcinfo->backup_date] = $backupfile;
            }
        }

        $backupstodelete = self::get_backups_to_delete($backupfiles, $now);
        if ($backupstodelete) {
            foreach ($backupstodelete as $backuptodelete) {
                unlink($dir . '/' . $backuptodelete);
            }
            mtrace('Deleted ' . count($backupstodelete) . ' old backup file(s) from external directory');
            return true;
        } else {
            return false;
        }
    }
464344
public function after_restore_course() {
        global $DB;

        if (!$this->need_restore_numsections()) {
            // Backup file was made in Moodle 3.3 or later, we don't need to process 'numsecitons'.
            return;
        }

        $data = $this->connectionpoint->get_data();
        $backupinfo = $this->step->get_task()->get_info();
        if ($backupinfo->original_course_format !== 'topics' || !isset($data['tags']['numsections'])) {
            // Backup from another course format or backup file does not even have 'numsections'.
            return;
        }

        $numsections = (int)$data['tags']['numsections'];
        foreach ($backupinfo->sections as $key => $section) {
            // For each section from the backup file check if it was restored and if was "orphaned" in the original
            // course and mark it as hidden. This will leave all activities in it visible and available just as it was
            // in the original course.
            // Exception is when we restore with merging and the course already had a section with this section number,
            // in this case we don't modify the visibility.
            if ($this->step->get_task()->get_setting_value($key . '_included')) {
                $sectionnum = (int)$section->title;
                if ($sectionnum > $numsections && $sectionnum > $this->originalnumsections) {
                    $DB->execute("UPDATE {course_sections} SET visible = 0 WHERE course = ? AND section = ?",
                        [$this->step->get_task()->get_courseid(), $sectionnum]);
                }
            }
        }
    }
1273299
public function backupDatabase(): TempFile
	{
		$this->check();
		$backup = new TempFile('database.sql', true);
		$tables = $this->driver->getTables();

		$backup->write("SET NAMES utf8;\n");
		$backup->write("SET time_zone = '+00:00';\n");
		$backup->write("SET foreign_key_checks = 0;\n");
		$backup->write("SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';\n\n\n");

		foreach ($tables as $table) {
			if (in_array($table, $this->excludeTables)) {
				continue;
			}
			$backup->write("DROP TABLE IF EXISTS `$table`;\n");

			$createTable = $this->driver->getCreateTable($table);
			$backup->write("$createTable;\n\n");

			$rows = $this->driver->getRows($table);
			$insert = [];
			$columns = null;
			$counter = 0;
			foreach ($rows as $row) {
				$counter++;
				if ($columns === null) {
					$colName = [];
					foreach ($row as $key => $value) {
						$colName[] = "`$key`";
					}
					$columns = implode(', ', $colName);
				}
				$cols = [];
				foreach ($row as $column) {
					if (is_string($column)) {
						$column = addslashes($column);
						$column = preg_replace("/\n/", "\\n", $column);
					} elseif ($column === null) {
						$cols[] = 'NULL';
						continue;
					}
					$cols[] = '"' . $column . '"';
				}
				$insert[] = implode(', ', $cols);

				if ($this->maxRows && $counter >= $this->maxRows) {
					$this->writeInsert($backup, $table, $columns, $insert);
					$counter = 0;
					$insert = [];
				}
			}
			$this->writeInsert($backup, $table, $columns, $insert);
			$backup->write("\n\n");
		}

		return $backup;
	}
1114908
public function backup() {
        $dbConfigParams     = $this->getDbConfigParams();
        $backupDir          = $this->getBackupDir();
        $environment        = $this->getEnvironment();

        if (!$this->databaseExists()) {
            return;
        }

        $createBackupDir    = new Garp_Shell_Command_CreateDir($backupDir);
        $dumpToFile         = new Garp_Shell_Command_DumpDatabaseToFile($dbConfigParams, $backupDir, $environment);

        $this->shellExec($createBackupDir);
        $this->shellExec($dumpToFile);

        /**
         * @todo: verifiëren of:
         *          - backupbestand bestaat
         *          - backupbestand meer dan 0 bytes heeft
         */
    }
968197
def backUpDB() :
    """"""
    st = time.ctime().replace(' ', '_')
    fn = conf.pyGeno_RABA_DBFILE.replace('.db', '_%s-bck.db' % st)
    shutil.copy2(conf.pyGeno_RABA_DBFILE, fn)

    return fn
1287259
def backup_db():
    
    if not os.path.exists('backups'):
        os.makedirs('backups')
    local('python manage.py dump_database | gzip > backups/' + _sql_paths('local', datetime.now()))
769932
def _backup_previous_version(func: Callable = None):
    """"""

    @wraps(func)
    def wrapper(self, *args, **kwargs):
        self.old_path = None
        if self.is_local:
            self.old_path = join(gettempdir(), self.name)
            if exists(self.old_path):
                rmtree(self.old_path)
            shutil.copytree(self.path, self.old_path)
        try:
            func(self, *args, **kwargs)

        # Modified skill or GitError should not restore working copy
        except (SkillModified, GitError, GitException):
            raise
        except Exception:
            LOG.info('Problem performing action. Restoring skill to '
                     'previous state...')
            if exists(self.path):
                rmtree(self.path)
            if self.old_path and exists(self.old_path):
                shutil.copytree(self.old_path, self.path)
            self.is_local = exists(self.path)
            raise

    return wrapper
727950
def backup(self):
        

        LOGGER.debug("> Storing '{0}' file backup.".format(self.__source))

        foundations.common.path_exists(self.__destination) or foundations.io.set_directory(self.__destination)
        destination = os.path.join(self.__destination, os.path.basename(self.__source))
        for i in range(self.__count - 1, 0, -1):
            sfn = "{0}.{1}".format(destination, i)
            dfn = "{0}.{1}".format(destination, i + 1)
            if foundations.common.path_exists(sfn):
                if foundations.common.path_exists(dfn):
                    foundations.io.remove(dfn)
                os.renames(sfn, dfn)
        foundations.common.path_exists(destination) and os.rename(destination, destination + ".1")
        foundations.io.copy(self.__source, destination)
        return True
647541
def copy_helper(app_or_project, name, directory, dist, template_dir, noadmin):
    

    import shutil
    if not re.search(r'^[_a-zA-Z]\w*$', name): # If it's not a valid directory name.
        # Provide a smart error message, depending on the error.
        if not re.search(r'^[_a-zA-Z]', name):
            message = 'make sure the name begins with a letter or underscore'
        else:
            message = 'use only numbers, letters and underscores'
        raise CommandError("%r is not a valid project name. Please %s." % (name, message))
    top_dir = os.path.join(directory, dist)
    try:
        os.mkdir(top_dir)
    except OSError, e:
        raise CommandError(e)
        
    for d, subdirs, files in os.walk(template_dir):
        relative_dir = d[len(template_dir)+1:].replace('project_name', name)
        if relative_dir:
            os.mkdir(os.path.join(top_dir, relative_dir))
        for subdir in subdirs[:]:
            if subdir.startswith('.'):
                subdirs.remove(subdir)
        for f in files:
            if not f.endswith('.py'):
                # Ignore .pyc, .pyo, .py.class etc, as they cause various
                # breakages.
                continue
            path_old = os.path.join(d, f)
            path_new = os.path.join(top_dir, relative_dir, f.replace('project_name', name))
            fp_old = open(path_old, 'r')
            fp_new = open(path_new, 'w')
            if noadmin:
                fp_new.write(fp_old.read().replace('{{ project_name }}', name))
            else:
                fp_new.write(fp_old.read().replace('{{ project_name }}', name).replace('## ',''))
            fp_old.close()
            fp_new.close()
            try:
                shutil.copymode(path_old, path_new)
                _make_writeable(path_new)
            except OSError:
                sys.stderr.write(style.NOTICE("Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\n" % path_new))
1335805
def _backup_pb_gui(self, dirs):
        """"""
        import PySimpleGUI as sg
        # Legacy support
        with ZipFile(self.zip_filename, 'w') as backup_zip:
            for count, path in enumerate(dirs):
                backup_zip.write(path, path[len(self.source):len(path)])
                if not sg.OneLineProgressMeter('Writing Zip Files', count + 1, len(dirs) - 1, 'Files'):
                    break
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)
398304
def setup(self):
        
        decompress_dir('.')

        if self.backup:
            for f in FEFF_INPUT_FILES:
                shutil.copy(f, "{}.orig".format(f))

            for f in FEFF_BACKUP_FILES:
                if os.path.isfile(f):
                    shutil.copy(f, "{}.orig".format(f))
499342
public function define_course_plugin_structure() {
        global $DB;

        // Since this method is executed before the restore we can do some pre-checks here.
        // In case of merging backup into existing course find the current number of sections.
        $target = $this->step->get_task()->get_target();
        if (($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING) &&
                $this->is_pre_33_backup()) {
            $maxsection = $DB->get_field_sql(
                'SELECT max(section) FROM {course_sections} WHERE course = ?',
                [$this->step->get_task()->get_courseid()]);
            $this->originalnumsections = (int)$maxsection;
        }

        // Dummy path element is needed in order for after_restore_course() to be called.
        return [new restore_path_element('dummy_course', $this->get_pathfor('/dummycourse'))];
    }
466864
protected function backup()
    {
        $from = $this->configFile;
        $pathinfo = pathinfo($from);
        $to = $pathinfo['dirname'] . DIRECTORY_SEPARATOR . $pathinfo['filename'] . '.bak.php';
        $this->file->copy($from, $to);
    }