<commit_before>/*
 * Copyright 2010 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.twitter.logging

import java.io.{File, FileOutputStream, FilenameFilter, OutputStream}
import java.nio.charset.Charset
import java.util.{Calendar, Date, logging => javalog}

import com.twitter.util.{TwitterDateFormat, HandleSignal, Return, StorageUnit, Time, Try}

sealed abstract class Policy
object Policy {
  case object Never extends Policy
  case object Hourly extends Policy
  case object Daily extends Policy
  case class Weekly(dayOfWeek: Int) extends Policy
  case object SigHup extends Policy
  case class MaxSize(size: StorageUnit) extends Policy


  private[this] val singletonPolicyNames: Map[String, Policy] =
    Map("never" -> Never, "hourly" -> Hourly, "daily" -> Daily, "sighup" -> SigHup)

  // Regex object that matches "Weekly(n)" and extracts the `dayOfWeek` number.
  private[this] val weeklyRegex = """(?i)weekly\(([1-7]+)\)""".r

  /**
   * Parse a string into a Policy object. Parsing rules are as follows:
   *
   * - Case-insensitive names of singleton Policy objects (e.g. Never, Hourly,
   *   Daily) are parsed into their corresponding objects.
   * - "Weekly(n)" is parsed into `Weekly` objects with `n` as the day-of-week
   *   integer.
   * - util-style data size strings (e.g. 3.megabytes, 1.gigabyte) are
   *   parsed into `StorageUnit` objects and used to produce `MaxSize` policies.
   *   See `StorageUnit.parse(String)` for more details.
   */
  def parse(s: String): Policy =
    (s, singletonPolicyNames.get(s.toLowerCase), Try(StorageUnit.parse(s.toLowerCase))) match {
      case (weeklyRegex(dayOfWeek), _, _) => Weekly(dayOfWeek.toInt)
      case (_, Some(singleton), _) => singleton
      case (_, _, Return(storageUnit)) => MaxSize(storageUnit)
      case _ => throw new Exception("Invalid log roll policy: " + s)
    }
}

object FileHandler {
  val UTF8 = Charset.forName("UTF-8")

  /**
   * Generates a HandlerFactory that returns a FileHandler
   *
   * @param filename
   * Filename to log to.
   *
   * @param rollPolicy
   * When to roll the logfile.
   *
   * @param append
   * Append to an existing logfile, or truncate it?
   *<commit_msg>util-logging: fix infinite loop in Weekly rotation policy<commit_after>/*
 * Copyright 2010 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.twitter.logging

import java.io.{File, FileOutputStream, FilenameFilter, OutputStream}
import java.nio.charset.Charset
import java.util.{Calendar, Date, logging => javalog}

import com.twitter.util.{TwitterDateFormat, HandleSignal, Return, StorageUnit, Time, Try}

sealed abstract class Policy
object Policy {
  case object Never extends Policy
  case object Hourly extends Policy
  case object Daily extends Policy
  case class Weekly(dayOfWeek: Int) extends Policy {
    assert(dayOfWeek >= Calendar.SUNDAY && dayOfWeek <= Calendar.SATURDAY)
  }
  case object SigHup extends Policy
  case class MaxSize(size: StorageUnit) extends Policy


  private[this] val singletonPolicyNames: Map[String, Policy] =
    Map("never" -> Never, "hourly" -> Hourly, "daily" -> Daily, "sighup" -> SigHup)

  // Regex object that matches "Weekly(n)" and extracts the `dayOfWeek` number.
  private[this] val weeklyRegex = """(?i)weekly\(([1-7]+)\)""".r

  /**
   * Parse a string into a Policy object. Parsing rules are as follows:
   *
   * - Case-insensitive names of singleton Policy objects (e.g. Never, Hourly,
   *   Daily) are parsed into their corresponding objects.
   * - "Weekly(n)" is parsed into `Weekly` objects with `n` as the day-of-week
   *   integer, as defined by the constants in java.util.Calendar.
   * - util-style data size strings (e.g. 3.megabytes, 1.gigabyte) are
   *   parsed into `StorageUnit` objects and used to produce `MaxSize` policies.
   *   See `StorageUnit.parse(String)` for more details.
   */
  def parse(s: String): Policy =
    (s, singletonPolicyNames.get(s.toLowerCase), Try(StorageUnit.parse(s.toLowerCase))) match {
      case (weeklyRegex(dayOfWeek), _, _) => Weekly(dayOfWeek.toInt)
      case (_, Some(singleton), _) => singleton
      case (_, _, Return(storageUnit)) => MaxSize(storageUnit)
      case _ => throw new Exception("Invalid log roll policy: " + s)
    }
}

object FileHandler {
  val UTF8 = Charset.forName("UTF-8")

  /**
   * Generates a HandlerFactory that returns a FileHandler
   *
   * @param filename
   * Filename to log to.
   *
   * @param rollPolicy
   * When to roll the logfile.
   *
   * @param append
   * Append to an existing logfile, or truncate it?
   *
{'fraction_non_alphanumeric': 0.10540348382509776, 'fraction_numerical': 0.004976892996800568, 'mean_word_length': 3.638911788953009, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 22, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6743685', 'n_tokens_mistral': 1697, 'n_tokens_neox': 1649, 'n_words': 602}