func tryClearRegexMatchingFiles()

in pkg/linuxutils/linuxutils.go [62:105]


func tryClearRegexMatchingFiles(ctx *log.Context, directory string, regexFileNamePattern string, deleteFiles bool) error {
	if regexFileNamePattern == "" {
		return errors.New("empty regexFileNamePattern argument")
	}

	// Check if the directory exists
	directoryFDRef, err := os.Open(directory)
	if err != nil {
		return errors.Wrap(err, "could not open directory")
	}

	regex, err := regexp.Compile(regexFileNamePattern)
	if err != nil {
		return errors.Wrap(err, "could not parse given regular expression")
	}

	dirEntries, err := directoryFDRef.ReadDir(0)
	if err != nil {
		return errors.Wrap(err, "could not read contents from directory")
	}

	for _, dirEntry := range dirEntries {
		fileName := dirEntry.Name()

		if regex.MatchString(fileName) {
			fullFilePath := filepath.Join(directory, fileName)
			if deleteFiles {
				ctx.Log("message", "deleting file "+fullFilePath)
				err = os.Remove(fullFilePath)
				if err != nil {
					ctx.Log("warning", "could not delete file", "error", err)
				}
			} else {
				ctx.Log("message", "cleaning file "+fullFilePath)
				err = os.Truncate(fullFilePath, 0) // Calling create on existing file truncates file
				if err != nil {
					ctx.Log("warning", "could not truncate file", "error", err)
				}
			}
		}
	}

	return nil
}