text:
  clippy::all,
  clippy::default_trait_access,
  clippy::expl_impl_clone_on_copy,
  clippy::if_not_else,
  clippy::needless_continue,
  clippy::unseparated_literal_suffix,
  clippy::used_underscore_binding
)]
// It is often more clear to show that nothing is being moved.
#![allow(clippy::match_ref_pats)]
// Subjective style.
#![allow(
  clippy::len_without_is_empty,
  clippy::redundant_field_names,
  clippy::too_many_arguments
)]
// Default isn't as big a deal as people seem to think it is.
#![allow(clippy::new_without_default, clippy::new_ret_no_self)]
// Arc<Mutex> can be more clear than needing to grok Orderings:
#![allow(clippy::mutex_atomic)]
#[macro_use]
extern crate derivative;

use std::collections::{BTreeMap, BTreeSet};
use std::convert::TryFrom;
use std::path::PathBuf;
use std::sync::Arc;

pub use log::Level;

use async_semaphore::AsyncSemaphore;
use async_trait::async_trait;
use bazel_protos::gen::build::bazel::remote::execution::v2 as remexec;
use hashing::{Digest, EMPTY_FINGERPRINT};
use remexec::ExecutedActionMetadata;
use serde::{Deserialize, Serialize};
use workunit_store::{in_workunit, RunningWorkunit, WorkunitMetadata, WorkunitStore};

pub mod cache;
#[cfg(test)]
mod cache_tests;

pub mod local;
#[cfg(test)]
mod local_tests;

pub mod remote;
#[cfg(test)]
pub mod remote_tests;

pub mod remote_cache;
#[cfg(test)]
mod remote_cache_tests;

pub mod nailgun;

pub mod named_caches;

extern crate uname;

pub use crate::named_caches::{CacheDest, CacheName, NamedCaches};
use concrete_time::{Duration, TimeSpan};
use fs::RelativePath;

#[derive(PartialOrd, Ord, Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[allow(non_camel_case_types)]
pub enum Platform {
  Macos_x86_64,
  Macos_arm64,
  Linux_x86_64,
}

impl Platform {
  pub fn current() -> Result<Platform, String> {
    let platform_info =
      uname::uname().map_err(|_| "Failed to get local platform info!".to_string())?;
    match platform_info {
      uname::Info {
        ref sysname,
        ref machine,
        ..
      } if sysname.to_lowercase() == "linux" && machine.to_lowercase() == "x86_64" => {
        Ok(Platform::Linux_x86_64)
      }
      uname::Info {
        ref sysname,
        ref machine,
        ..
      } if sysname.to_lowercase() == "darwin" && machine.to_lowercase() == "arm64" => {
        Ok(Platform::Macos_arm64)
      }
      uname::Info {
        ref sysname,
        ref machine,
        ..
      } if sysname.to_lowercase() == "darwin" && machine.to_lowercase() == "x86_64" => {
        Ok(Platform::Macos_x86_64)
      }
      uname::Info {
        ref sysname,
        ref machine,
        ..
      } => Err(format!(
        "Found unknown system/arch name pair {} {}",
        sysname, machine
      )),
    }
  }
}

impl From<Platform> for String {
  fn from(platform: Platform) -> String {
    match platform {
      Platform::Linux_x86_64 => "linux_x86_64".to_string(),
      Platform::Macos_arm64 => "macos_arm64".to_string(),
      Platform::Macos_x86_64 => "macos_x86_64".to_string(),
    }
  }
}

impl TryFrom<String> for Platform {
  type Error = String;
  fn try_from(variant_candidate: String) -> Result<Self, Self::Error> {
    match variant_candidate.as_ref() {
      "macos_arm64" => Ok(Platform::Macos_arm64),
      "macos_x86_64" => Ok(Platform::Macos_x86_64),
      "linux_x86_64" => Ok(Platform::Linux_x86_64),
      other => Err(format!(
        "Unknown platform {:?} encountered in parsing",
        other
      )),
    }
  }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize)]
pub enum ProcessCacheScope {
  // Cached in all locations, regardless of success or failure.
  Always,
  // Cached in all locations, but only if the process exits successfully.
  Successful,
  // Cached only in memory (i.e. memoized in pantsd), but never persistently, regardless of
  // success vs. failure.
  PerRestartAlways,
  // Cached only in memory (i.e. memoized in pantsd), but never persistently, and only if
  // successful.
  PerRestartSuccessful,
  // Will run once per Session, i.e. once per run of Pants. This happens because the engine
  // de-duplicates identical work; the process is neither memoized in memory nor cached to disk.
  PerSession,
}

impl TryFrom<String> for ProcessCacheScope {
  type Error = String;
  fn try_from(variant_candidate: String) -> Result<Self, Self::Error> {
    match variant_candidate.to_lowercase().as_ref() {
      "always" => Ok(ProcessCacheScope::Always),
      "successful" => Ok(ProcessCacheScope::Successful),
      "per_restart_always" => Ok(ProcessCacheScope::PerRestartAlways),
      "per_restart_successful" => Ok(ProcessCacheScope::PerRestartSuccessful),
      "per_session" => Ok(ProcessCacheScope::PerSession),
      other => Err(format!("Unknown Process cache scope: {:?}", other)),
    }
  }
}

fn serialize_level<S: serde::Serializer>(level: &log::Level, s: S) -> Result<S::Ok, S::Error> {
  s.serialize_str(&level.to_string())
}

///
/// A process to be executed.
///
#[derive(Derivative, Clone, Debug, Eq, Serialize)]
#[derivative(PartialEq, Hash)]
pub struct Process {
  ///
  /// The arguments to execute.
  ///
  /// The first argument should be an absolute or relative path to the binary to execute.
  ///
  /// No PATH lookup will be performed unless a PATH environment variable is specified.
  ///
  /// No shell expansion will take place.
  ///
  pub argv: Vec<String>,
  ///
  /// The environment variables to set for the execution.
  ///
  /// No other environment variables will be set (except possibly for an empty PATH variable).
  ///
  pub env: BTreeMap<String, String>,

  ///
  /// A relative path to a directory existing in the `input_files` digest to execute the process
  /// from. Defaults to the `input_files` root.
  ///
  pub working_directory: Option<RelativePath>,

  pub input_files: hashing::Digest,

  pub output_files: BTreeSet<RelativePath>,

  pub output_directories: BTreeSet<RelativePath>,

  pub timeout: Option<std::time::Duration>,

  /// If not None, then if a BoundedCommandRunner executes this Process
  pub execution_slot_variable: Option<String>,

  #[derivative(PartialEq = "ignore", Hash = "ignore")]
  pub description: String,

  // NB: We serialize with a function to avoid adding a serde dep to the logging crate.
  #[serde(serialize_with = "serialize_level")]
  pub level: log::Level,

  ///
  /// Declares that this process uses the given named caches (which might have associated config
  /// in the future) at the associated relative paths within its workspace. Cache names must
  /// contain only lowercase ascii characters or underscores.
  ///
  /// Caches are exposed to processes within their workspaces at the relative paths represented
  /// by the values of the dict. A process may optionally check for the existence of the relevant
  /// directory, and disable use of that cache if it has not been created by the executor
  /// (indicating a lack of support for this feature).
  ///
  /// These caches are globally shared and so must be concurrency safe: a consumer of the cache
  /// must never assume that it has exclusive access to the provided directory.
  ///
  pub append_only_caches: BTreeMap<CacheName, CacheDest>,

  ///
  /// If present, a symlink will be created at .jdk which points to this directory for local
  /// execution, or a system-installed JDK (ignoring the value of the present Some) for remote
  /// execution.
  ///
  /// This is some technical debt we should clean up;
  /// see https://github.com/pantsbuild/pants/issues/6416.
  ///
  pub jdk_home: Option<PathBuf>,

  pub platform_constraint: Option<Platform>,

  ///
  /// If non-empty, the Digest of a nailgun server to use to attempt to spawn the Process.
  ///
  /// TODO: Currently this Digest must be a subset of the `input_digest`, but we should consider
  /// making it disjoint, and then automatically merging it.
  ///
  pub use_nailgun: Digest,

  pub cache_scope: ProcessCacheScope,
}

impl Process {
  ///
  /// Constructs a Process with default values for most fields, after which the builder pattern can
  /// be used to set values.
  ///
  /// We use the more ergonomic (but possibly slightly slower) "move self for each builder method"
  /// pattern, so this method is only enabled for test usage: production usage should construct the
  /// Process struct wholesale. We can reconsider this if we end up with more production callsites
  /// that require partial options.
  ///
  #[cfg(test)]
  pub fn new(argv: Vec<String>) -> Process {
    Process {
      argv,
      env: BTreeMap::new(),
      working_directory: None,
      input_files: hashing::EMPTY_DIGEST,
      output_files: BTreeSet::new(),
      output_directories: BTreeSet::new(),
      timeout: None,
      description: "".to_string(),
      level: log::Level::Info,
      append_only_caches: BTreeMap::new(),
      jdk_home: None,
      platform_constraint: None,
      use_nailgun: hashing::EMPTY_DIGEST,
      execution_slot_variable: None,
      cache_scope: ProcessCacheScope::Successful,
    }
  }

  ///
  /// Replaces the environment for this process.
  ///
  pub fn env(mut self, env: BTreeMap<String, String>) -> Process {
    self.env = env;
    self
  }

  ///
  /// Replaces the output files for this process.
  ///
  pub fn output_files(mut self, output_files: BTreeSet<RelativePath>) -> Process {
    self.output_files = output_files;
    self
  }

  ///
  /// Replaces the output directories for this process.
  ///
  pub fn output_directories(mut self, output_directories: BTreeSet<RelativePath>) -> Process {
    self.output_directories = output_directories;
    self
  }

  ///
  /// Replaces the append only caches for this process.
  ///
  pub fn append_only_caches(
    mut self,
    append_only_caches: BTreeMap<CacheName, CacheDest>,
  ) -> Process {
    self.append_only_caches = append_only_caches;
    self
  }
}

impl TryFrom<MultiPlatformProcess> for Process {
  type Error = String;

  fn try_from(req: MultiPlatformProcess) -> Result<Self, Self::Error> {
    match req.0.get(&None) {
      Some(crossplatform_req) => Ok(crossplatform_req.clone()),
      None => Err(String::from(
        "Cannot coerce to a simple Process, no cross platform request exists.",
      )),
    }
  }
}

///
/// A container of platform constrained processes.
///
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct MultiPlatformProcess(pub BTreeMap<Option<Platform>, Process>);

impl MultiPlatformProcess {
  pub fn user_facing_name(&self) -> String {
    self
      .0
      .iter()
      .next()
      .map(|(_platforms, process)| process.description.clone())
      .unwrap_or_else(|| "<Unnamed process>".to_string())
  }

  pub fn workunit_level(&self) -> log::Level {
    self
      .0
      .iter()
      .next()
      .map(|(_platforms, process)| process.level)
      .unwrap_or(Level::Info)
  }
}

impl From<Process> for MultiPlatformProcess {
  fn from(proc: Process) -> Self {
    MultiPlatformProcess(vec![(None, proc)].into_iter().collect())
  }
}

///
/// Metadata surrounding an Process which factors into its cache key when cached
/// externally from the engine graph (e.g. when using remote execution or an external process
/// cache).
///
#[derive(Clone, Debug, Default)]
pub struct ProcessMetadata {
  pub instance_name: Option<String>,
  pub cache_key_gen_version: Option<String>,
  pub platform_properties: Vec<(String, String)>,
}

///
/// The result of running a process.
///
#[derive(Derivative, Clone, Debug, Eq)]
#[derivative(PartialEq, Hash)]
pub struct FallibleProcessResultWithPlatform {
  pub stdout_digest: Digest,
  pub stderr_digest: Digest,
  pub exit_code: i32,
  pub output_directory: hashing::Digest,
  pub platform: Platform,
  #[derivative(PartialEq = "ignore", Hash = "ignore")]
  pub metadata: ProcessResultMetadata,
}

/// Metadata for a ProcessResult corresponding to the REAPI `ExecutedActionMetadata` proto. This
/// conversion is lossy, but the interesting parts are preserved.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProcessResultMetadata {
  /// The time from starting to completion, including preparing the chroot and cleanup.
  /// Corresponds to `worker_start_timestamp` and `worker_completed_timestamp` from
  /// `ExecutedActionMetadata`.
  ///
  /// NB: This is optional because the REAPI does not guarantee that it is returned.
  pub total_elapsed: Option<Duration>,
  /// The source of the result.
  pub source: ProcessResultSource,
}

impl ProcessResultMetadata {
  pub fn new(total_elapsed: Option<Duration>, source: ProcessResultSource) -> Self {
    ProcessResultMetadata {
      total_elapsed,
      source,
    }
  }

  pub fn new_from_metadata(metadata: ExecutedActionMetadata, source: ProcessResultSource) -> Self {
    let total_elapsed = match (
      metadata.worker_start_timestamp,
      metadata.worker_completed_timestamp,
    ) {
      (Some(started), Some(completed)) => TimeSpan::from_start_and_end(&started, &completed, "")
        .map(|span| span.duration)
        .ok(),
      _ => None,
    };
    Self {
      total_elapsed,
      source,
    }
  }

  /// How much faster a cache hit was than running the process again.
  ///
  /// This includes the overhead of setting up and cleaning up the process for execution, and it
  /// should include all overhead for the cache lookup.
  ///
  /// If the cache hit was slower than the original process, we return 0. Note that the cache hit
  /// may still have been faster than rerunning the process a second time, e.g. if speculation
  /// is used and the cache hit completed before the rerun; still, we cannot know how long the
  /// second run would have taken, so the best we can do is report 0.
  ///
  /// If the original process's execution time was not recorded, we return None because we
  /// cannot make a meaningful comparison.
  pub fn time_saved_from_cache(
    &self,
    cache_lookup: std::time::Duration,
  ) -> Option<std::time::Duration> {
    self.total_elapsed.and_then(|original_process| {
      let original_process: std::time::Duration = original_process.into();
      original_process
        .checked_sub(cache_lookup)
        .or_else(|| Some(std::time::Duration::new(0, 0)))
    })
  }
}

impl From<ProcessResultMetadata> for ExecutedActionMetadata {
  fn from(metadata: ProcessResultMetadata) -> ExecutedActionMetadata {
    let (total_start, total_end) = match metadata.total_elapsed {
      Some(elapsed) => {
        // Because we do not have the precise start time, we hardcode to starting at UNIX_EPOCH. We
        // only care about accurately preserving the duration.
        let start = prost_types::Timestamp {
          seconds: 0,
          nanos: 0,
        };
        let end = prost_types::Timestamp {
          seconds: elapsed.secs as i64,
          nanos: elapsed.nanos as i32,
        };
        (Some(start), Some(end))
      }
      None => (None, None),
    };
    ExecutedActionMetadata {
      worker_start_timestamp: total_start,
      worker_completed_timestamp: total_end,
      ..ExecutedActionMetadata::default()
    }
  }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ProcessResultSource {
  RanLocally,
  RanRemotely,
  HitLocally,
  HitRemotely,
}

#[derive(Clone)]
pub struct Context {
  workunit_store: WorkunitStore,
  build_id: String,
}

impl Default for Context {
  fn default() -> Self {
    Context {
      workunit_store: WorkunitStore::new(false),
      build_id: String::default(),
    }
  }
}

impl Context {
  pub fn new(workunit_store: WorkunitStore, build_id: String) -> Context {
    Context {
      workunit_store,
      build_id,
    }
  }
}

#[async_trait]
pub trait CommandRunner: Send + Sync {
  ///
  /// Submit a request for execution on the underlying runtime, and return
  /// a future for it.
  ///
  async fn run(
    &self,
    context: Context,
    workunit: &mut RunningWorkunit,
    req: MultiPlatformProcess,
  ) -> Result<FallibleProcessResultWithPlatform, String>;

  ///
  /// Given a multi platform request which may have some platform
  /// constraints determine if any of the requests contained within are compatible
  /// with the current command runners platform configuration. If so return the
  /// first candidate that will be run if the multi platform request is submitted to
  /// `fn run(..)`
  fn extract_compatible_request(&self, req: &MultiPlatformProcess) -> Option<Process>;
}

// TODO(#8513) possibly move to the MEPR struct, or to the hashing crate?
pub fn digest(req: MultiPlatformProcess, metadata: &ProcessMetadata) -> Digest {
  let mut hashes: Vec<String> = req
    .0
    .values()
    .map(|process| crate::remote::make_execute_request(process, metadata.clone()).unwrap())
    .map(|(_a, _b, er)| {
      er.action_digest
        .map(|d| d.hash)
        .unwrap_or_else(|| EMPTY_FINGERPRINT.to_hex())
    })
    .collect();
  hashes.sort();
  Digest::of_bytes(
    hashes
      .iter()
      .fold(String::new(), |mut acc, hash| {
        acc.push_str(hash);
        acc
      })
      .as_bytes(),
  )
}

///
/// A CommandRunner wrapper that limits the number of concurrent requests.
///
#[derive(Clone)]
pub struct BoundedCommandRunner {
  inner: Arc<(Box<dyn CommandRunner>, AsyncSemaphore)>,
}

impl BoundedCommandRunner {
  pub fn new(inner: Box<dyn CommandRunner>, bound: usize) -> BoundedCommandRunner {
    BoundedCommandRunner {
      inner: Arc::new((inner, AsyncSemaphore::new(bound))),
    }
  }
}

#[async_trait]
impl CommandRunner for BoundedCommandRunner {
  async fn run(
    &self,
    context: Context,
    workunit: &mut RunningWorkunit,
    mut req: MultiPlatformProcess,
  ) -> Result<FallibleProcessResultWithPlatform, String> {
    let semaphore_acquisition = self.inner.1.acquire();
    let permit = in_workunit!(
      context.workunit_store.clone(),
      "acquire_command_runner_slot".to_owned(),
      WorkunitMetadata {
        level: Level::Trace,
        ..WorkunitMetadata::default()
      },
      |workunit| async move {
        let _blocking_token = workunit.blocking();
        semaphore_acquisition.await
      }
    )
    .await;

    log::debug!(
      "Running {} under semaphore with concurrency id: {}",
      req.user_facing_name(),
      permit.concurrency_slot()
    );

    for (_, process) in req.0.iter_mut() {
      if let Some(ref execution_slot_env_var) = process.execution_slot_variable {
        process.env.insert(
          execution_slot_env_var.clone(),
          format!("{}", permit.concurrency_slot()),
        );
      }
    }

    self.inner.0.run(context, workunit, req).await
  }

  fn extract_compatible_request(&self, req: &MultiPlatformProcess) -> Option<Process> {
    self.inner.0.extract_compatible_request(req)
  }
}

impl From<Box<BoundedCommandRunner>> for Arc<dyn CommandRunner> {
  fn from(command_runner: Box<BoundedCommandRunner>) -> Arc<dyn CommandRunner> {
    Arc::new(*command_runner)
  }
}

#[derive(Clone, Copy, Debug, PartialEq, strum_macros::EnumString)]
#[strum(serialize_all = "snake_case")]
pub enum RemoteCacheWarningsBehavior {
  Ignore,
  FirstOnly,
  Backoff,
}

#[cfg(test)]
mod tests;


text:
class Subregion < ActiveRecord::Base
  self.table_name  = 'new_mapcsubregionExtensionBase'
  self.primary_key = 'new_mapcsubregionId'

  alias_attribute :name, :new_FullName
  alias_attribute :abbv, :new_MAPC_Subregion

  default_scope {
    where.not("new_MAPC_Subregion" => "Not applicable")
      .where.not("new_MAPC_Subregion" => "All subregions")
  }

  def self.simple(boolean=true)
    boolean.to_b ? where("new_Organization" => nil) : all
  end

  def to_param
    "#{abbv}--#{id}"
  end

  has_many :municipalities, foreign_key: "new_MAPCSubregionId"
  has_many :projects, through: :municipalities

  def project_count
    @count ||= ProjectCounter.new(self).value
  end

  def to_geojson
    # TODO This logic should be moved to the resource,
    #   since it is presentation logic.
    @geojson ||= JSON.parse( SubregionGeojsonCacher.new(self).value )
    props = @geojson["properties"]
    props["id"] = self.id # TODO with Friendly URLs self.to_param
    props["project_count"] = project_count
    props["simple_name"] = name
    @geojson
  end
end

redpajama_set_name: RedPajamaGithub


text:
/*
 * Builtin "git am"
 *
 * Based on git-am.sh by Junio C Hamano.
 */
#include "cache.h"
#include "builtin.h"
#include "exec_cmd.h"
#include "parse-options.h"
#include "dir.h"
#include "run-command.h"
#include "quote.h"
#include "tempfile.h"
#include "lockfile.h"
#include "cache-tree.h"
#include "refs.h"
#include "commit.h"
#include "diff.h"
#include "diffcore.h"
#include "unpack-trees.h"
#include "branch.h"
#include "sequencer.h"
#include "revision.h"
#include "merge-recursive.h"
#include "revision.h"
#include "log-tree.h"
#include "notes-utils.h"
#include "rerere.h"
#include "prompt.h"

/**
 * Returns 1 if the file is empty or does not exist, 0 otherwise.
 */
static int is_empty_file(const char *filename)
{
	struct stat st;

	if (stat(filename, &st) < 0) {
		if (errno == ENOENT)
			return 1;
		die_errno(_("could not stat %s"), filename);
	}

	return !st.st_size;
}

/**
 * Like strbuf_getline(), but treats both '\n' and "\r\n" as line terminators.
 */
static int strbuf_getline_crlf(struct strbuf *sb, FILE *fp)
{
	if (strbuf_getwholeline(sb, fp, '\n'))
		return EOF;
	if (sb->buf[sb->len - 1] == '\n') {
		strbuf_setlen(sb, sb->len - 1);
		if (sb->len > 0 && sb->buf[sb->len - 1] == '\r')
			strbuf_setlen(sb, sb->len - 1);
	}
	return 0;
}

/**
 * Returns the length of the first line of msg.
 */
static int linelen(const char *msg)
{
	return strchrnul(msg, '\n') - msg;
}

/**
 * Returns true if `str` consists of only whitespace, false otherwise.
 */
static int str_isspace(const char *str)
{
	for (; *str; str++)
		if (!isspace(*str))
			return 0;

	return 1;
}

enum patch_format {
	PATCH_FORMAT_UNKNOWN = 0,
	PATCH_FORMAT_MBOX,
	PATCH_FORMAT_STGIT,
	PATCH_FORMAT_STGIT_SERIES,
	PATCH_FORMAT_HG
};

enum keep_type {
	KEEP_FALSE = 0,
	KEEP_TRUE,      /* pass -k flag to git-mailinfo */
	KEEP_NON_PATCH  /* pass -b flag to git-mailinfo */
};

enum scissors_type {
	SCISSORS_UNSET = -1,
	SCISSORS_FALSE = 0,  /* pass --no-scissors to git-mailinfo */
	SCISSORS_TRUE        /* pass --scissors to git-mailinfo */
};

enum signoff_type {
	SIGNOFF_FALSE = 0,
	SIGNOFF_TRUE = 1,
	SIGNOFF_EXPLICIT /* --signoff was set on the command-line */
};

struct am_state {
	/* state directory path */
	char *dir;

	/* current and last patch numbers, 1-indexed */
	int cur;
	int last;

	/* commit metadata and message */
	char *author_name;
	char *author_email;
	char *author_date;
	char *msg;
	size_t msg_len;

	/* when --rebasing, records the original commit the patch came from */
	unsigned char orig_commit[GIT_SHA1_RAWSZ];

	/* number of digits in patch filename */
	int prec;

	/* various operating modes and command line options */
	int interactive;
	int threeway;
	int quiet;
	int signoff; /* enum signoff_type */
	int utf8;
	int keep; /* enum keep_type */
	int message_id;
	int scissors; /* enum scissors_type */
	struct argv_array git_apply_opts;
	const char *resolvemsg;
	int committer_date_is_author_date;
	int ignore_date;
	int allow_rerere_autoupdate;
	const char *sign_commit;
	int rebasing;
};

/**
 * Initializes am_state with the default values. The state directory is set to
 * dir.
 */
static void am_state_init(struct am_state *state, const char *dir)
{
	int gpgsign;

	memset(state, 0, sizeof(*state));

	assert(dir);
	state->dir = xstrdup(dir);

	state->prec = 4;

	git_config_get_bool("am.threeway", &state->threeway);

	state->utf8 = 1;

	git_config_get_bool("am.messageid", &state->message_id);

	state->scissors = SCISSORS_UNSET;

	argv_array_init(&state->git_apply_opts);

	if (!git_config_get_bool("commit.gpgsign", &gpgsign))
		state->sign_commit = gpgsign ? "" : NULL;
}

/**
 * Releases memory allocated by an am_state.
 */
static void am_state_release(struct am_state *state)
{
	free(state->dir);
	free(state->author_name);
	free(state->author_email);
	free(state->author_date);
	free(state->msg);
	argv_array_clear(&state->git_apply_opts);
}

/**
 * Returns path relative to the am_state directory.
 */
static inline const char *am_path(const struct am_state *state, const char *path)
{
	return mkpath("%s/%s", state->dir, path);
}

/**
 * For convenience to call write_file()
 */
static int write_state_text(const struct am_state *state,
			    const char *name, const char *string)
{
	return write_file(am_path(state, name), "%s", string);
}

static int write_state_count(const struct am_state *state,
			     const char *name, int value)
{
	return write_file(am_path(state, name), "%d", value);
}

static int write_state_bool(const struct am_state *state,
			    const char *name, int value)
{
	return write_state_text(state, name, value ? "t" : "f");
}

/**
 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
 * at the end.
 */
static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	if (!state->quiet) {
		vfprintf(fp, fmt, ap);
		putc('\n', fp);
	}
	va_end(ap);
}

/**
 * Returns 1 if there is an am session in progress, 0 otherwise.
 */
static int am_in_progress(const struct am_state *state)
{
	struct stat st;

	if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
		return 0;
	if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
		return 0;
	if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
		return 0;
	return 1;
}

/**
 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
 * number of bytes read on success, -1 if the file does not exist. If `trim` is
 * set, trailing whitespace will be removed.
 */
static int read_state_file(struct strbuf *sb, const struct am_state *state,
			const char *file, int trim)
{
	strbuf_reset(sb);

	if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
		if (trim)
			strbuf_trim(sb);

		return sb->len;
	}

	if (errno == ENOENT)
		return -1;

	die_errno(_("could not read '%s'"), am_path(state, file));
}

/**
 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
 * match `key`. Returns NULL on failure.
 *
 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
 * the author-script.
 */
static char *read_shell_var(FILE *fp, const char *key)
{
	struct strbuf sb = STRBUF_INIT;
	const char *str;

	if (strbuf_getline(&sb, fp, '\n'))
		goto fail;

	if (!skip_prefix(sb.buf, key, &str))
		goto fail;

	if (!skip_prefix(str, "=", &str))
		goto fail;

	strbuf_remove(&sb, 0, str - sb.buf);

	str = sq_dequote(sb.buf);
	if (!str)
		goto fail;

	return strbuf_detach(&sb, NULL);

fail:
	strbuf_release(&sb);
	return NULL;
}

/**
 * Reads and parses the state directory's "author-script" file, and sets
 * state->author_name, state->author_email and state->author_date accordingly.
 * Returns 0 on success, -1 if the file could not be parsed.
 *
 * The author script is of the format:
 *
 *	GIT_AUTHOR_NAME='$author_name'
 *	GIT_AUTHOR_EMAIL='$author_email'
 *	GIT_AUTHOR_DATE='$author_date'
 *
 * where $author_name, $author_email and $author_date are quoted. We are strict
 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
 * script, and thus if the file differs from what this function expects, it is
 * better to bail out than to do something that the user does not expect.
 */
static int read_author_script(struct am_state *state)
{
	const char *filename = am_path(state, "author-script");
	FILE *fp;

	assert(!state->author_name);
	assert(!state->author_email);
	assert(!state->author_date);

	fp = fopen(filename, "r");
	if (!fp) {
		if (errno == ENOENT)
			return 0;
		die_errno(_("could not open '%s' for reading"), filename);
	}

	state->author_name = read_shell_var(fp, "GIT_AUTHOR_NAME");
	if (!state->author_name) {
		fclose(fp);
		return -1;
	}

	state->author_email = read_shell_var(fp, "GIT_AUTHOR_EMAIL");
	if (!state->author_email) {
		fclose(fp);
		return -1;
	}

	state->author_date = read_shell_var(fp, "GIT_AUTHOR_DATE");
	if (!state->author_date) {
		fclose(fp);
		return -1;
	}

	if (fgetc(fp) != EOF) {
		fclose(fp);
		return -1;
	}

	fclose(fp);
	return 0;
}

/**
 * Saves state->author_name, state->author_email and state->author_date in the
 * state directory's "author-script" file.
 */
static void write_author_script(const struct am_state *state)
{
	struct strbuf sb = STRBUF_INIT;

	strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
	sq_quote_buf(&sb, state->author_name);
	strbuf_addch(&sb, '\n');

	strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
	sq_quote_buf(&sb, state->author_email);
	strbuf_addch(&sb, '\n');

	strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
	sq_quote_buf(&sb, state->author_date);
	strbuf_addch(&sb, '\n');

	write_state_text(state, "author-script", sb.buf);

	strbuf_release(&sb);
}

/**
 * Reads the commit message from the state directory's "final-commit" file,
 * setting state->msg to its contents and state->msg_len to the length of its
 * contents in bytes.
 *
 * Returns 0 on success, -1 if the file does not exist.
 */
static int read_commit_msg(struct am_state *state)
{
	struct strbuf sb = STRBUF_INIT;

	assert(!state->msg);

	if (read_state_file(&sb, state, "final-commit", 0) < 0) {
		strbuf_release(&sb);
		return -1;
	}

	state->msg = strbuf_detach(&sb, &state->msg_len);
	return 0;
}

/**
 * Saves state->msg in the state directory's "final-commit" file.
 */
static void write_commit_msg(const struct am_state *state)
{
	int fd;
	const char *filename = am_path(state, "final-commit");

	fd = xopen(filename, O_WRONLY | O_CREAT, 0666);
	if (write_in_full(fd, state->msg, state->msg_len) < 0)
		die_errno(_("could not write to %s"), filename);
	close(fd);
}

/**
 * Loads state from disk.
 */
static void am_load(struct am_state *state)
{
	struct strbuf sb = STRBUF_INIT;

	if (read_state_file(&sb, state, "next", 1) < 0)
		die("BUG: state file 'next' does not exist");
	state->cur = strtol(sb.buf, NULL, 10);

	if (read_state_file(&sb, state, "last", 1) < 0)
		die("BUG: state file 'last' does not exist");
	state->last = strtol(sb.buf, NULL, 10);

	if (read_author_script(state) < 0)
		die(_("could not parse author script"));

	read_commit_msg(state);

	if (read_state_file(&sb, state, "original-commit", 1) < 0)
		hashclr(state->orig_commit);
	else if (get_sha1_hex(sb.buf, state->orig_commit) < 0)
		die(_("could not parse %s"), am_path(state, "original-commit"));

	read_state_file(&sb, state, "threeway", 1);
	state->threeway = !strcmp(sb.buf, "t");

	read_state_file(&sb, state, "quiet", 1);
	state->quiet = !strcmp(sb.buf, "t");

	read_state_file(&sb, state, "sign", 1);
	state->signoff = !strcmp(sb.buf, "t");

	read_state_file(&sb, state, "utf8", 1);
	state->utf8 = !strcmp(sb.buf, "t");

	read_state_file(&sb, state, "keep", 1);
	if (!strcmp(sb.buf, "t"))
		state->keep = KEEP_TRUE;
	else if (!strcmp(sb.buf, "b"))
		state->keep = KEEP_NON_PATCH;
	else
		state->keep = KEEP_FALSE;

	read_state_file(&sb, state, "messageid", 1);
	state->message_id = !strcmp(sb.buf, "t");

	read_state_file(&sb, state, "scissors", 1);
	if (!strcmp(sb.buf, "t"))
		state->scissors = SCISSORS_TRUE;
	else if (!strcmp(sb.buf, "f"))
		state->scissors = SCISSORS_FALSE;
	else
		state->scissors = SCISSORS_UNSET;

	read_state_file(&sb, state, "apply-opt", 1);
	argv_array_clear(&state->git_apply_opts);
	if (sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) < 0)
		die(_("could not parse %s"), am_path(state, "apply-opt"));

	state->rebasing = !!file_exists(am_path(state, "rebasing"));

	strbuf_release(&sb);
}

/**
 * Removes the am_state directory, forcefully terminating the current am
 * session.
 */
static void am_destroy(const struct am_state *state)
{
	struct strbuf sb = STRBUF_INIT;

	strbuf_addstr(&sb, state->dir);
	remove_dir_recursively(&sb, 0);
	strbuf_release(&sb);
}

/**
 * Runs applypatch-msg hook. Returns its exit code.
 */
static int run_applypatch_msg_hook(struct am_state *state)
{
	int ret;

	assert(state->msg);
	ret = run_hook_le(NULL, "applypatch-msg", am_path(state, "final-commit"), NULL);

	if (!ret) {
		free(state->msg);
		state->msg = NULL;
		if (read_commit_msg(state) < 0)
			die(_("'%s' was deleted by the applypatch-msg hook"),
				am_path(state, "final-commit"));
	}

	return ret;
}

/**
 * Runs post-rewrite hook. Returns it exit code.
 */
static int run_post_rewrite_hook(const struct am_state *state)
{
	struct child_process cp = CHILD_PROCESS_INIT;
	const char *hook = find_hook("post-rewrite");
	int ret;

	if (!hook)
		return 0;

	argv_array_push(&cp.args, hook);
	argv_array_push(&cp.args, "rebase");

	cp.in = xopen(am_path(state, "rewritten"), O_RDONLY);
	cp.stdout_to_stderr = 1;

	ret = run_command(&cp);

	close(cp.in);
	return ret;
}

/**
 * Reads the state directory's "rewritten" file, and copies notes from the old
 * commits listed in the file to their rewritten commits.
 *
 * Returns 0 on success, -1 on failure.
 */
static int copy_notes_for_rebase(const struct am_state *state)
{
	struct notes_rewrite_cfg *c;
	struct strbuf sb = STRBUF_INIT;
	const char *invalid_line = _("Malformed input line: '%s'.");
	const char *msg = "Notes added by 'git rebase'";
	FILE *fp;
	int ret = 0;

	assert(state->rebasing);

	c = init_copy_notes_for_rewrite("rebase");
	if (!c)
		return 0;

	fp = xfopen(am_path(state, "rewritten"), "r");

	while (!strbuf_getline(&sb, fp, '\n')) {
		unsigned char from_obj[GIT_SHA1_RAWSZ], to_obj[GIT_SHA1_RAWSZ];

		if (sb.len != GIT_SHA1_HEXSZ * 2 + 1) {
			ret = error(invalid_line, sb.buf);
			goto finish;
		}

		if (get_sha1_hex(sb.buf, from_obj)) {
			ret = error(invalid_line, sb.buf);
			goto finish;
		}

		if (sb.buf[GIT_SHA1_HEXSZ] != ' ') {
			ret = error(invalid_line, sb.buf);
			goto finish;
		}

		if (get_sha1_hex(sb.buf + GIT_SHA1_HEXSZ + 1, to_obj)) {
			ret = error(invalid_line, sb.buf);
			goto finish;
		}

		if (copy_note_for_rewrite(c, from_obj, to_obj))
			ret = error(_("Failed to copy notes from '%s' to '%s'"),
					sha1_to_hex(from_obj), sha1_to_hex(to_obj));
	}

finish:
	finish_copy_notes_for_rewrite(c, msg);
	fclose(fp);
	strbuf_release(&sb);
	return ret;
}

/**
 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
 * non-indented lines and checking if they look like they begin with valid
 * header field names.
 *
 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
 */
static int is_mail(FILE *fp)
{
	const char *header_regex = "^[!-9;-~]+:";
	struct strbuf sb = STRBUF_INIT;
	regex_t regex;
	int ret = 1;

	if (fseek(fp, 0L, SEEK_SET))
		die_errno(_("fseek failed"));

	if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
		die("invalid pattern: %s", header_regex);

	while (!strbuf_getline_crlf(&sb, fp)) {
		if (!sb.len)
			break; /* End of header */

		/* Ignore indented folded lines */
		if (*sb.buf == '\t' || *sb.buf == ' ')
			continue;

		/* It's a header if it matches header_regex */
		if (regexec(&regex, sb.buf, 0, NULL, 0)) {
			ret = 0;
			goto done;
		}
	}

done:
	regfree(&regex);
	strbuf_release(&sb);
	return ret;
}

/**
 * Attempts to detect the patch_format of the patches contained in `paths`,
 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
 * detection fails.
 */
static int detect_patch_format(const char **paths)
{
	enum patch_format ret = PATCH_FORMAT_UNKNOWN;
	struct strbuf l1 = STRBUF_INIT;
	struct strbuf l2 = STRBUF_INIT;
	struct strbuf l3 = STRBUF_INIT;
	FILE *fp;

	/*
	 * We default to mbox format if input is from stdin and for directories
	 */
	if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
		return PATCH_FORMAT_MBOX;

	/*
	 * Otherwise, check the first few lines of the first patch, starting
	 * from the first non-blank line, to try to detect its format.
	 */

	fp = xfopen(*paths, "r");

	while (!strbuf_getline_crlf(&l1, fp)) {
		if (l1.len)
			break;
	}

	if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
		ret = PATCH_FORMAT_MBOX;
		goto done;
	}

	if (starts_with(l1.buf, "# This series applies on GIT commit")) {
		ret = PATCH_FORMAT_STGIT_SERIES;
		goto done;
	}

	if (!strcmp(l1.buf, "# HG changeset patch")) {
		ret = PATCH_FORMAT_HG;
		goto done;
	}

	strbuf_reset(&l2);
	strbuf_getline_crlf(&l2, fp);
	strbuf_reset(&l3);
	strbuf_getline_crlf(&l3, fp);

	/*
	 * If the second line is empty and the third is a From, Author or Date
	 * entry, this is likely an StGit patch.
	 */
	if (l1.len && !l2.len &&
		(starts_with(l3.buf, "From:") ||
		 starts_with(l3.buf, "Author:") ||
		 starts_with(l3.buf, "Date:"))) {
		ret = PATCH_FORMAT_STGIT;
		goto done;
	}

	if (l1.len && is_mail(fp)) {
		ret = PATCH_FORMAT_MBOX;
		goto done;
	}

done:
	fclose(fp);
	strbuf_release(&l1);
	return ret;
}

/**
 * Splits out individual email patches from `paths`, where each path is either
 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
 */
static int split_mail_mbox(struct am_state *state, const char **paths, int keep_cr)
{
	struct child_process cp = CHILD_PROCESS_INIT;
	struct strbuf last = STRBUF_INIT;

	cp.git_cmd = 1;
	argv_array_push(&cp.args, "mailsplit");
	argv_array_pushf(&cp.args, "-d%d", state->prec);
	argv_array_pushf(&cp.args, "-o%s", state->dir);
	argv_array_push(&cp.args, "-b");
	if (keep_cr)
		argv_array_push(&cp.args, "--keep-cr");
	argv_array_push(&cp.args, "--");
	argv_array_pushv(&cp.args, paths);

	if (capture_command(&cp, &last, 8))
		return -1;

	state->cur = 1;
	state->last = strtol(last.buf, NULL, 10);

	return 0;
}

/**
 * Callback signature for split_mail_conv(). The foreign patch should be
 * read from `in`, and the converted patch (in RFC2822 mail format) should be
 * written to `out`. Return 0 on success, or -1 on failure.
 */
typedef int (*mail_conv_fn)(FILE *out, FILE *in, int keep_cr);

/**
 * Calls `fn` for each file in `paths` to convert the foreign patch to the
 * RFC2822 mail format suitable for parsing with git-mailinfo.
 *
 * Returns 0 on success, -1 on failure.
 */
static int split_mail_conv(mail_conv_fn fn, struct am_state *state,
			const char **paths, int keep_cr)
{
	static const char *stdin_only[] = {"-", NULL};
	int i;

	if (!*paths)
		paths = stdin_only;

	for (i = 0; *paths; paths++, i++) {
		FILE *in, *out;
		const char *mail;
		int ret;

		if (!strcmp(*paths, "-"))
			in = stdin;
		else
			in = fopen(*paths, "r");

		if (!in)
			return error(_("could not open '%s' for reading: %s"),
					*paths, strerror(errno));

		mail = mkpath("%s/%0*d", state->dir, state->prec, i + 1);

		out = fopen(mail, "w");
		if (!out)
			return error(_("could not open '%s' for writing: %s"),
					mail, strerror(errno));

		ret = fn(out, in, keep_cr);

		fclose(out);
		fclose(in);

		if (ret)
			return error(_("could not parse patch '%s'"), *paths);
	}

	state->cur = 1;
	state->last = i;
	return 0;
}

/**
 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
 * message suitable for parsing with git-mailinfo.
 */
static int stgit_patch_to_mail(FILE *out, FILE *in, int keep_cr)
{
	struct strbuf sb = STRBUF_INIT;
	int subject_printed = 0;

	while (!strbuf_getline(&sb, in, '\n')) {
		const char *str;

		if (str_isspace(sb.buf))
			continue;
		else if (skip_prefix(sb.buf, "Author:", &str))
			fprintf(out, "From:%s\n", str);
		else if (starts_with(sb.buf, "From") || starts_with(sb.buf, "Date"))
			fprintf(out, "%s\n", sb.buf);
		else if (!subject_printed) {
			fprintf(out, "Subject: %s\n", sb.buf);
			subject_printed = 1;
		} else {
			fprintf(out, "\n%s\n", sb.buf);
			break;
		}
	}

	strbuf_reset(&sb);
	while (strbuf_fread(&sb, 8192, in) > 0) {
		fwrite(sb.buf, 1, sb.len, out);
		strbuf_reset(&sb);
	}

	strbuf_release(&sb);
	return 0;
}

/**
 * This function only supports a single StGit series file in `paths`.
 *
 * Given an StGit series file, converts the StGit patches in the series into
 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
 * the state directory.
 *
 * Returns 0 on success, -1 on failure.
 */
static int split_mail_stgit_series(struct am_state *state, const char **paths,
					int keep_cr)
{
	const char *series_dir;
	char *series_dir_buf;
	FILE *fp;
	struct argv_array patches = ARGV_ARRAY_INIT;
	struct strbuf sb = STRBUF_INIT;
	int ret;

	if (!paths[0] || paths[1])
		return error(_("Only one StGIT patch series can be applied at once"));

	series_dir_buf = xstrdup(*paths);
	series_dir = dirname(series_dir_buf);

	fp = fopen(*paths, "r");
	if (!fp)
		return error(_("could not open '%s' for reading: %s"), *paths,
				strerror(errno));

	while (!strbuf_getline(&sb, fp, '\n')) {
		if (*sb.buf == '#')
			continue; /* skip comment lines */

		argv_array_push(&patches, mkpath("%s/%s", series_dir, sb.buf));
	}

	fclose(fp);
	strbuf_release(&sb);
	free(series_dir_buf);

	ret = split_mail_conv(stgit_patch_to_mail, state, patches.argv, keep_cr);

	argv_array_clear(&patches);
	return ret;
}

/**
 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
 * message suitable for parsing with git-mailinfo.
 */
static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr)
{
	struct strbuf sb = STRBUF_INIT;

	while (!strbuf_getline(&sb, in, '\n')) {
		const char *str;

		if (skip_prefix(sb.buf, "# User ", &str))
			fprintf(out, "From: %s\n", str);
		else if (skip_prefix(sb.buf, "# Date ", &str)) {
			unsigned long timestamp;
			long tz, tz2;
			char *end;

			errno = 0;
			timestamp = strtoul(str, &end, 10);
			if (errno)
				return error(_("invalid timestamp"));

			if (!skip_prefix(end, " ", &str))
				return error(_("invalid Date line"));

			errno = 0;
			tz = strtol(str, &end, 10);
			if (errno)
				return error(_("invalid timezone offset"));

			if (*end)
				return error(_("invalid Date line"));

			/*
			 * mercurial's timezone is in seconds west of UTC,
			 * however git's timezone is in hours + minutes east of
			 * UTC. Convert it.
			 */
			tz2 = labs(tz) / 3600 * 100 + labs(tz) % 3600 / 60;
			if (tz > 0)
				tz2 = -tz2;

			fprintf(out, "Date: %s\n", show_date(timestamp, tz2, DATE_MODE(RFC2822)));
		} else if (starts_with(sb.buf, "# ")) {
			continue;
		} else {
			fprintf(out, "\n%s\n", sb.buf);
			break;
		}
	}

	strbuf_reset(&sb);
	while (strbuf_fread(&sb, 8192, in) > 0) {
		fwrite(sb.buf, 1, sb.len, out);
		strbuf_reset(&sb);
	}

	strbuf_release(&sb);
	return 0;
}

/**
 * Splits a list of files/directories into individual email patches. Each path
 * in `paths` must be a file/directory that is formatted according to
 * `patch_format`.
 *
 * Once split out, the individual email patches will be stored in the state
 * directory, with each patch's filename being its index, padded to state->prec
 * digits.
 *
 * state->cur will be set to the index of the first mail, and state->last will
 * be set to the index of the last mail.
 *
 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
 * to disable this behavior, -1 to use the default configured setting.
 *
 * Returns 0 on success, -1 on failure.
 */
static int split_mail(struct am_state *state, enum patch_format patch_format,
			const char **paths, int keep_cr)
{
	if (keep_cr < 0) {
		keep_cr = 0;
		git_config_get_bool("am.keepcr", &keep_cr);
	}

	switch (patch_format) {
	case PATCH_FORMAT_MBOX:
		return split_mail_mbox(state, paths, keep_cr);
	case PATCH_FORMAT_STGIT:
		return split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);
	case PATCH_FORMAT_STGIT_SERIES:
		return split_mail_stgit_series(state, paths, keep_cr);
	case PATCH_FORMAT_HG:
		return split_mail_conv(hg_patch_to_mail, state, paths, keep_cr);
	default:
		die("BUG: invalid patch_format");
	}
	return -1;
}

/**
 * Setup a new am session for applying patches
 */
static void am_setup(struct am_state *state, enum patch_format patch_format,
			const char **paths, int keep_cr)
{
	unsigned char curr_head[GIT_SHA1_RAWSZ];
	const char *str;
	struct strbuf sb = STRBUF_INIT;

	if (!patch_format)
		patch_format = detect_patch_format(paths);

	if (!patch_format) {
		fprintf_ln(stderr, _("Patch format detection failed."));
		exit(128);
	}

	if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
		die_errno(_("failed to create directory '%s'"), state->dir);

	if (split_mail(state, patch_format, paths, keep_cr) < 0) {
		am_destroy(state);
		die(_("Failed to split patches."));
	}

	if (state->rebasing)
		state->threeway = 1;

	write_state_bool(state, "threeway", state->threeway);
	write_state_bool(state, "quiet", state->quiet);
	write_state_bool(state, "sign", state->signoff);
	write_state_bool(state, "utf8", state->utf8);

	switch (state->keep) {
	case KEEP_FALSE:
		str = "f";
		break;
	case KEEP_TRUE:
		str = "t";
		break;
	case KEEP_NON_PATCH:
		str = "b";
		break;
	default:
		die("BUG: invalid value for state->keep");
	}

	write_state_text(state, "keep", str);
	write_state_bool(state, "messageid", state->message_id);

	switch (state->scissors) {
	case SCISSORS_UNSET:
		str = "";
		break;
	case SCISSORS_FALSE:
		str = "f";
		break;
	case SCISSORS_TRUE:
		str = "t";
		break;
	default:
		die("BUG: invalid value for state->scissors");
	}
	write_state_text(state, "scissors", str);

	sq_quote_argv(&sb, state->git_apply_opts.argv, 0);
	write_state_text(state, "apply-opt", sb.buf);

	if (state->rebasing)
		write_state_text(state, "rebasing", "");
	else
		write_state_text(state, "applying", "");

	if (!get_sha1("HEAD", curr_head)) {
		write_state_text(state, "abort-safety", sha1_to_hex(curr_head));
		if (!state->rebasing)
			update_ref("am", "ORIG_HEAD", curr_head, NULL, 0,
					UPDATE_REFS_DIE_ON_ERR);
	} else {
		write_state_text(state, "abort-safety", "");
		if (!state->rebasing)
			delete_ref("ORIG_HEAD", NULL, 0);
	}

	/*
	 * NOTE: Since the "next" and "last" files determine if an am_state
	 * session is in progress, they should be written last.
	 */

	write_state_count(state, "next", state->cur);
	write_state_count(state, "last", state->last);

	strbuf_release(&sb);
}

/**
 * Increments the patch pointer, and cleans am_state for the application of the
 * next patch.
 */
static void am_next(struct am_state *state)
{
	unsigned char head[GIT_SHA1_RAWSZ];

	free(state->author_name);
	state->author_name = NULL;

	free(state->author_email);
	state->author_email = NULL;

	free(state->author_date);
	state->author_date = NULL;

	free(state->msg);
	state->msg = NULL;
	state->msg_len = 0;

	unlink(am_path(state, "author-script"));
	unlink(am_path(state, "final-commit"));

	hashclr(state->orig_commit);
	unlink(am_path(state, "original-commit"));

	if (!get_sha1("HEAD", head))
		write_state_text(state, "abort-safety", sha1_to_hex(head));
	else
		write_state_text(state, "abort-safety", "");

	state->cur++;
	write_state_count(state, "next", state->cur);
}

/**
 * Returns the filename of the current patch email.
 */
static const char *msgnum(const struct am_state *state)
{
	static struct strbuf sb = STRBUF_INIT;

	strbuf_reset(&sb);
	strbuf_addf(&sb, "%0*d", state->prec, state->cur);

	return sb.buf;
}

/**
 * Refresh and write index.
 */
static void refresh_and_write_cache(void)
{
	struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));

	hold_locked_index(lock_file, 1);
	refresh_cache(REFRESH_QUIET);
	if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
		die(_("unable to write index file"));
}

/**
 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
 * strbuf is provided, the space-separated list of files that differ will be
 * appended to it.
 */
static int index_has_changes(struct strbuf *sb)
{
	unsigned char head[GIT_SHA1_RAWSZ];
	int i;

	if (!get_sha1_tree("HEAD", head)) {
		struct diff_options opt;

		diff_setup(&opt);
		DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
		if (!sb)
			DIFF_OPT_SET(&opt, QUICK);
		do_diff_cache(head, &opt);
		diffcore_std(&opt);
		for (i = 0; sb && i < diff_queued_diff.nr; i++) {
			if (i)
				strbuf_addch(sb, ' ');
			strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
		}
		diff_flush(&opt);
		return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
	} else {
		for (i = 0; sb && i < active_nr; i++) {
			if (i)
				strbuf_addch(sb, ' ');
			strbuf_addstr(sb, active_cache[i]->name);
		}
		return !!active_nr;
	}
}

/**
 * Dies with a user-friendly message on how to proceed after resolving the
 * problem. This message can be overridden with state->resolvemsg.
 */
static void NORETURN die_user_resolve(const struct am_state *state)
{
	if (state->resolvemsg) {
		printf_ln("%s", state->resolvemsg);
	} else {
		const char *cmdline = state->interactive ? "git am -i" : "git am";

		printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
		printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
		printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
	}

	exit(128);
}

static void am_signoff(struct strbuf *sb)
{
	char *cp;
	struct strbuf mine = STRBUF_INIT;

	/* Does it end with our own sign-off? */
	strbuf_addf(&mine, "\n%s%s\n",
		    sign_off_header,
		    fmt_name(getenv("GIT_COMMITTER_NAME"),
			     getenv("GIT_COMMITTER_EMAIL")));
	if (mine.len < sb->len &&
	    !strcmp(mine.buf, sb->buf + sb->len - mine.len))
		goto exit; /* no need to duplicate */

	/* Does it have any Signed-off-by: in the text */
	for (cp = sb->buf;
	     cp && *cp && (cp = strstr(cp, sign_off_header)) != NULL;
	     cp = strchr(cp, '\n')) {
		if (sb->buf == cp || cp[-1] == '\n')
			break;
	}

	strbuf_addstr(sb, mine.buf + !!cp);
exit:
	strbuf_release(&mine);
}

/**
 * Appends signoff to the "msg" field of the am_state.
 */
static void am_append_signoff(struct am_state *state)
{
	struct strbuf sb = STRBUF_INIT;

	strbuf_attach(&sb, state->msg, state->msg_len, state->msg_len);
	am_signoff(&sb);
	state->msg = strbuf_detach(&sb, &state->msg_len);
}

/**
 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
 * state->msg will be set to the patch message. state->author_name,
 * state->author_email and state->author_date will be set to the patch author's
 * name, email and date respectively. The patch body will be written to the
 * state directory's "patch" file.
 *
 * Returns 1 if the patch should be skipped, 0 otherwise.
 */
static int parse_mail(struct am_state *state, const char *mail)
{
	FILE *fp;
	struct child_process cp = CHILD_PROCESS_INIT;
	struct strbuf sb = STRBUF_INIT;
	struct strbuf msg = STRBUF_INIT;
	struct strbuf author_name = STRBUF_INIT;
	struct strbuf author_date = STRBUF_INIT;
	struct strbuf author_email = STRBUF_INIT;
	int ret = 0;

	cp.git_cmd = 1;
	cp.in = xopen(mail, O_RDONLY, 0);
	cp.out = xopen(am_path(state, "info"), O_WRONLY | O_CREAT, 0777);

	argv_array_push(&cp.args, "mailinfo");
	argv_array_push(&cp.args, state->utf8 ? "-u" : "-n");

	switch (state->keep) {
	case KEEP_FALSE:
		break;
	case KEEP_TRUE:
		argv_array_push(&cp.args, "-k");
		break;
	case KEEP_NON_PATCH:
		argv_array_push(&cp.args, "-b");
		break;
	default:
		die("BUG: invalid value for state->keep");
	}

	if (state->message_id)
		argv_array_push(&cp.args, "-m");

	switch (state->scissors) {
	case SCISSORS_UNSET:
		break;
	case SCISSORS_FALSE:
		argv_array_push(&cp.args, "--no-scissors");
		break;
	case SCISSORS_TRUE:
		argv_array_push(&cp.args, "--scissors");
		break;
	default:
		die("BUG: invalid value for state->scissors");
	}

	argv_array_push(&cp.args, am_path(state, "msg"));
	argv_array_push(&cp.args, am_path(state, "patch"));

	if (run_command(&cp) < 0)
		die("could not parse patch");

	close(cp.in);
	close(cp.out);

	/* Extract message and author information */
	fp = xfopen(am_path(state, "info"), "r");
	while (!strbuf_getline(&sb, fp, '\n')) {
		const char *x;

		if (skip_prefix(sb.buf, "Subject: ", &x)) {
			if (msg.len)
				strbuf_addch(&msg, '\n');
			strbuf_addstr(&msg, x);
		} else if (skip_prefix(sb.buf, "Author: ", &x))
			strbuf_addstr(&author_name, x);
		else if (skip_prefix(sb.buf, "Email: ", &x))
			strbuf_addstr(&author_email, x);
		else if (skip_prefix(sb.buf, "Date: ", &x))
			strbuf_addstr(&author_date, x);
	}
	fclose(fp);

	/* Skip pine's internal folder data */
	if (!strcmp(author_name.buf, "Mail System Internal Data")) {
		ret = 1;
		goto finish;
	}

	if (is_empty_file(am_path(state, "patch"))) {
		printf_ln(_("Patch is empty. Was it split wrong?"));
		die_user_resolve(state);
	}

	strbuf_addstr(&msg, "\n\n");
	if (strbuf_read_file(&msg, am_path(state, "msg"), 0) < 0)
		die_errno(_("could not read '%s'"), am_path(state, "msg"));
	strbuf_stripspace(&msg, 0);

	if (state->signoff)
		am_signoff(&msg);

	assert(!state->author_name);
	state->author_name = strbuf_detach(&author_name, NULL);

	assert(!state->author_email);
	state->author_email = strbuf_detach(&author_email, NULL);

	assert(!state->author_date);
	state->author_date = strbuf_detach(&author_date, NULL);

	assert(!state->msg);
	state->msg = strbuf_detach(&msg, &state->msg_len);

finish:
	strbuf_release(&msg);
	strbuf_release(&author_date);
	strbuf_release(&author_email);
	strbuf_release(&author_name);
	strbuf_release(&sb);
	return ret;
}

/**
 * Sets commit_id to the commit hash where the mail was generated from.
 * Returns 0 on success, -1 on failure.
 */
static int get_mail_commit_sha1(unsigned char *commit_id, const char *mail)
{
	struct strbuf sb = STRBUF_INIT;
	FILE *fp = xfopen(mail, "r");
	const char *x;

	if (strbuf_getline(&sb, fp, '\n'))
		return -1;

	if (!skip_prefix(sb.buf, "From ", &x))
		return -1;

	if (get_sha1_hex(x, commit_id) < 0)
		return -1;

	strbuf_release(&sb);
	fclose(fp);
	return 0;
}

/**
 * Sets state->msg, state->author_name, state->author_email, state->author_date
 * to the commit's respective info.
 */
static void get_commit_info(struct am_state *state, struct commit *commit)
{
	const char *buffer, *ident_line, *author_date, *msg;
	size_t ident_len;
	struct ident_split ident_split;
	struct strbuf sb = STRBUF_INIT;

	buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());

	ident_line = find_commit_header(buffer, "author", &ident_len);

	if (split_ident_line(&ident_split, ident_line, ident_len) < 0) {
		strbuf_add(&sb, ident_line, ident_len);
		die(_("invalid ident line: %s"), sb.buf);
	}

	assert(!state->author_name);
	if (ident_split.name_begin) {
		strbuf_add(&sb, ident_split.name_begin,
			ident_split.name_end - ident_split.name_begin);
		state->author_name = strbuf_detach(&sb, NULL);
	} else
		state->author_name = xstrdup("");

	assert(!state->author_email);
	if (ident_split.mail_begin) {
		strbuf_add(&sb, ident_split.mail_begin,
			ident_split.mail_end - ident_split.mail_begin);
		state->author_email = strbuf_detach(&sb, NULL);
	} else
		state->author_email = xstrdup("");

	author_date = show_ident_date(&ident_split, DATE_MODE(NORMAL));
	strbuf_addstr(&sb, author_date);
	assert(!state->author_date);
	state->author_date = strbuf_detach(&sb, NULL);

	assert(!state->msg);
	msg = strstr(buffer, "\n\n");
	if (!msg)
		die(_("unable to parse commit %s"), sha1_to_hex(commit->object.sha1));
	state->msg = xstrdup(msg + 2);
	state->msg_len = strlen(state->msg);
}

/**
 * Writes `commit` as a patch to the state directory's "patch" file.
 */
static void write_commit_patch(const struct am_state *state, struct commit *commit)
{
	struct rev_info rev_info;
	FILE *fp;

	fp = xfopen(am_path(state, "patch"), "w");
	init_revisions(&rev_info, NULL);
	rev_info.diff = 1;
	rev_info.abbrev = 0;
	rev_info.disable_stdin = 1;
	rev_info.show_root_diff = 1;
	rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
	rev_info.no_commit_id = 1;
	DIFF_OPT_SET(&rev_info.diffopt, BINARY);
	DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);
	rev_info.diffopt.use_color = 0;
	rev_info.diffopt.file = fp;
	rev_info.diffopt.close_file = 1;
	add_pending_object(&rev_info, &commit->object, "");
	diff_setup_done(&rev_info.diffopt);
	log_tree_commit(&rev_info, commit);
}

/**
 * Writes the diff of the index against HEAD as a patch to the state
 * directory's "patch" file.
 */
static void write_index_patch(const struct am_state *state)
{
	struct tree *tree;
	unsigned char head[GIT_SHA1_RAWSZ];
	struct rev_info rev_info;
	FILE *fp;

	if (!get_sha1_tree("HEAD", head))
		tree = lookup_tree(head);
	else
		tree = lookup_tree(EMPTY_TREE_SHA1_BIN);

	fp = xfopen(am_path(state, "patch"), "w");
	init_revisions(&rev_info, NULL);
	rev_info.diff = 1;
	rev_info.disable_stdin = 1;
	rev_info.no_commit_id = 1;
	rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
	rev_info.diffopt.use_color = 0;
	rev_info.diffopt.file = fp;
	rev_info.diffopt.close_file = 1;
	add_pending_object(&rev_info, &tree->object, "");
	diff_setup_done(&rev_info.diffopt);
	run_diff_index(&rev_info, 1);
}

/**
 * Like parse_mail(), but parses the mail by looking up its commit ID
 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
 * of patches.
 *
 * state->orig_commit will be set to the original commit ID.
 *
 * Will always return 0 as the patch should never be skipped.
 */
static int parse_mail_rebase(struct am_state *state, const char *mail)
{
	struct commit *commit;
	unsigned char commit_sha1[GIT_SHA1_RAWSZ];

	if (get_mail_commit_sha1(commit_sha1, mail) < 0)
		die(_("could not parse %s"), mail);

	commit = lookup_commit_or_die(commit_sha1, mail);

	get_commit_info(state, commit);

	write_commit_patch(state, commit);

	hashcpy(state->orig_commit, commit_sha1);
	write_state_text(state, "original-commit", sha1_to_hex(commit_sha1));

	return 0;
}

/**
 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
 * `index_file` is not NULL, the patch will be applied to that index.
 */
static int run_apply(const struct am_state *state, const char *index_file)
{
	struct child_process cp = CHILD_PROCESS_INIT;

	cp.git_cmd = 1;

	if (index_file)
		argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s", index_file);

	/*
	 * If we are allowed to fall back on 3-way merge, don't give false
	 * errors during the initial attempt.
	 */
	if (state->threeway && !index_file) {
		cp.no_stdout = 1;
		cp.no_stderr = 1;
	}

	argv_array_push(&cp.args, "apply");

	argv_array_pushv(&cp.args, state->git_apply_opts.argv);

	if (index_file)
		argv_array_push(&cp.args, "--cached");
	else
		argv_array_push(&cp.args, "--index");

	argv_array_push(&cp.args, am_path(state, "patch"));

	if (run_command(&cp))
		return -1;

	/* Reload index as git-apply will have modified it. */
	discard_cache();
	read_cache_from(index_file ? index_file : get_index_file());

	return 0;
}

/**
 * Builds an index that contains just the blobs needed for a 3way merge.
 */
static int build_fake_ancestor(const struct am_state *state, const char *index_file)
{
	struct child_process cp = CHILD_PROCESS_INIT;

	cp.git_cmd = 1;
	argv_array_push(&cp.args, "apply");
	argv_array_pushv(&cp.args, state->git_apply_opts.argv);
	argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
	argv_array_push(&cp.args, am_path(state, "patch"));

	if (run_command(&cp))
		return -1;

	return 0;
}

/**
 * Do the three-way merge using fake ancestor, his tree constructed
 * from the fake ancestor and the postimage of the patch, and our
 * state.
 */
static int run_fallback_merge_recursive(const struct am_state *state,
					unsigned char *orig_tree,
					unsigned char *our_tree,
					unsigned char *his_tree)
{
	struct child_process cp = CHILD_PROCESS_INIT;
	int status;

	cp.git_cmd = 1;

	argv_array_pushf(&cp.env_array, "GITHEAD_%s=%.*s",
			 sha1_to_hex(his_tree), linelen(state->msg), state->msg);
	if (state->quiet)
		argv_array_push(&cp.env_array, "GIT_MERGE_VERBOSITY=0");

	argv_array_push(&cp.args, "merge-recursive");
	argv_array_push(&cp.args, sha1_to_hex(orig_tree));
	argv_array_push(&cp.args, "--");
	argv_array_push(&cp.args, sha1_to_hex(our_tree));
	argv_array_push(&cp.args, sha1_to_hex(his_tree));

	status = run_command(&cp) ? (-1) : 0;
	discard_cache();
	read_cache();
	return status;
}

/**
 * Attempt a threeway merge, using index_path as the temporary index.
 */
static int fall_back_threeway(const struct am_state *state, const char *index_path)
{
	unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],
		      our_tree[GIT_SHA1_RAWSZ];

	if (get_sha1("HEAD", our_tree) < 0)
		hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);

	if (build_fake_ancestor(state, index_path))
		return error("could not build fake ancestor");

	discard_cache();
	read_cache_from(index_path);

	if (write_index_as_tree(orig_tree, &the_index, index_path, 0, NULL))
		return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));

	say(state, stdout, _("Using index info to reconstruct a base tree..."));

	if (!state->quiet) {
		/*
		 * List paths that needed 3-way fallback, so that the user can
		 * review them with extra care to spot mismerges.
		 */
		struct rev_info rev_info;
		const char *diff_filter_str = "--diff-filter=AM";

		init_revisions(&rev_info, NULL);
		rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
		diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1);
		add_pending_sha1(&rev_info, "HEAD", our_tree, 0);
		diff_setup_done(&rev_info.diffopt);
		run_diff_index(&rev_info, 1);
	}

	if (run_apply(state, index_path))
		return error(_("Did you hand edit your patch?\n"
				"It does not apply to blobs recorded in its index."));

	if (write_index_as_tree(his_tree, &the_index, index_path, 0, NULL))
		return error("could not write tree");

	say(state, stdout, _("Falling back to patching base and 3-way merge..."));

	discard_cache();
	read_cache();

	/*
	 * This is not so wrong. Depending on which base we picked, orig_tree
	 * may be wildly different from ours, but his_tree has the same set of
	 * wildly different changes in parts the patch did not touch, so
	 * recursive ends up canceling them, saying that we reverted all those
	 * changes.
	 */

	if (run_fallback_merge_recursive(state, orig_tree, our_tree, his_tree)) {
		rerere(state->allow_rerere_autoupdate);
		return error(_("Failed to merge in the changes."));
	}

	return 0;
}

/**
 * Commits the current index with state->msg as the commit message and
 * state->author_name, state->author_email and state->author_date as the author
 * information.
 */
static void do_commit(const struct am_state *state)
{
	unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],
		      commit[GIT_SHA1_RAWSZ];
	unsigned char *ptr;
	struct commit_list *parents = NULL;
	const char *reflog_msg, *author;
	struct strbuf sb = STRBUF_INIT;

	if (run_hook_le(NULL, "pre-applypatch", NULL))
		exit(1);

	if (write_cache_as_tree(tree, 0, NULL))
		die(_("git write-tree failed to write a tree"));

	if (!get_sha1_commit("HEAD", parent)) {
		ptr = parent;
		commit_list_insert(lookup_commit(parent), &parents);
	} else {
		ptr = NULL;
		say(state, stderr, _("applying to an empty history"));
	}

	author = fmt_ident(state->author_name, state->author_email,
			state->ignore_date ? NULL : state->author_date,
			IDENT_STRICT);

	if (state->committer_date_is_author_date)
		setenv("GIT_COMMITTER_DATE",
			state->ignore_date ? "" : state->author_date, 1);

	if (commit_tree(state->msg, state->msg_len, tree, parents, commit,
				author, state->sign_commit))
		die(_("failed to write commit object"));

	reflog_msg = getenv("GIT_REFLOG_ACTION");
	if (!reflog_msg)
		reflog_msg = "am";

	strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
			state->msg);

	update_ref(sb.buf, "HEAD", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);

	if (state->rebasing) {
		FILE *fp = xfopen(am_path(state, "rewritten"), "a");

		assert(!is_null_sha1(state->orig_commit));
		fprintf(fp, "%s ", sha1_to_hex(state->orig_commit));
		fprintf(fp, "%s\n", sha1_to_hex(commit));
		fclose(fp);
	}

	run_hook_le(NULL, "post-applypatch", NULL);

	strbuf_release(&sb);
}

/**
 * Validates the am_state for resuming -- the "msg" and authorship fields must
 * be filled up.
 */
static void validate_resume_state(const struct am_state *state)
{
	if (!state->msg)
		die(_("cannot resume: %s does not exist."),
			am_path(state, "final-commit"));

	if (!state->author_name || !state->author_email || !state->author_date)
		die(_("cannot resume: %s does not exist."),
			am_path(state, "author-script"));
}

/**
 * Interactively prompt the user on whether the current patch should be
 * applied.
 *
 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
 * skip it.
 */
static int do_interactive(struct am_state *state)
{
	assert(state->msg);

	if (!isatty(0))
		die(_("cannot be interactive without stdin connected to a terminal."));

	for (;;) {
		const char *reply;

		puts(_("Commit Body is:"));
		puts("--------------------------");
		printf("%s", state->msg);
		puts("--------------------------");

		/*
		 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
		 * in your translation. The program will only accept English
		 * input at this point.
		 */
		reply = git_prompt(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "), PROMPT_ECHO);

		if (!reply) {
			continue;
		} else if (*reply == 'y' || *reply == 'Y') {
			return 0;
		} else if (*reply == 'a' || *reply == 'A') {
			state->interactive = 0;
			return 0;
		} else if (*reply == 'n' || *reply == 'N') {
			return 1;
		} else if (*reply == 'e' || *reply == 'E') {
			struct strbuf msg = STRBUF_INIT;

			if (!launch_editor(am_path(state, "final-commit"), &msg, NULL)) {
				free(state->msg);
				state->msg = strbuf_detach(&msg, &state->msg_len);
			}
			strbuf_release(&msg);
		} else if (*reply == 'v' || *reply == 'V') {
			const char *pager = git_pager(1);
			struct child_process cp = CHILD_PROCESS_INIT;

			if (!pager)
				pager = "cat";
			argv_array_push(&cp.args, pager);
			argv_array_push(&cp.args, am_path(state, "patch"));
			run_command(&cp);
		}
	}
}

/**
 * Applies all queued mail.
 *
 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
 * well as the state directory's "patch" file is used as-is for applying the
 * patch and committing it.
 */
static void am_run(struct am_state *state, int resume)
{
	const char *argv_gc_auto[] = {"gc", "--auto", NULL};
	struct strbuf sb = STRBUF_INIT;

	unlink(am_path(state, "dirtyindex"));

	refresh_and_write_cache();

	if (index_has_changes(&sb)) {
		write_state_bool(state, "dirtyindex", 1);
		die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
	}

	strbuf_release(&sb);

	while (state->cur <= state->last) {
		const char *mail = am_path(state, msgnum(state));
		int apply_status;

		if (!file_exists(mail))
			goto next;

		if (resume) {
			validate_resume_state(state);
		} else {
			int skip;

			if (state->rebasing)
				skip = parse_mail_rebase(state, mail);
			else
				skip = parse_mail(state, mail);

			if (skip)
				goto next; /* mail should be skipped */

			write_author_script(state);
			write_commit_msg(state);
		}

		if (state->interactive && do_interactive(state))
			goto next;

		if (run_applypatch_msg_hook(state))
			exit(1);

		say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);

		apply_status = run_apply(state, NULL);

		if (apply_status && state->threeway) {
			struct strbuf sb = STRBUF_INIT;

			strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
			apply_status = fall_back_threeway(state, sb.buf);
			strbuf_release(&sb);

			/*
			 * Applying the patch to an earlier tree and merging
			 * the result may have produced the same tree as ours.
			 */
			if (!apply_status && !index_has_changes(NULL)) {
				say(state, stdout, _("No changes -- Patch already applied."));
				goto next;
			}
		}

		if (apply_status) {
			int advice_amworkdir = 1;

			printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
				linelen(state->msg), state->msg);

			git_config_get_bool("advice.amworkdir", &advice_amworkdir);

			if (advice_amworkdir)
				printf_ln(_("The copy of the patch that failed is found in: %s"),
						am_path(state, "patch"));

			die_user_resolve(state);
		}

		do_commit(state);

next:
		am_next(state);

		if (resume)
			am_load(state);
		resume = 0;
	}

	if (!is_empty_file(am_path(state, "rewritten"))) {
		assert(state->rebasing);
		copy_notes_for_rebase(state);
		run_post_rewrite_hook(state);
	}

	/*
	 * In rebasing mode, it's up to the caller to take care of
	 * housekeeping.
	 */
	if (!state->rebasing) {
		am_destroy(state);
		run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
	}
}

/**
 * Resume the current am session after patch application failure. The user did
 * all the hard work, and we do not have to do any patch application. Just
 * trust and commit what the user has in the index and working tree.
 */
static void am_resolve(struct am_state *state)
{
	validate_resume_state(state);

	say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);

	if (!index_has_changes(NULL)) {
		printf_ln(_("No changes - did you forget to use 'git add'?\n"
			"If there is nothing left to stage, chances are that something else\n"
			"already introduced the same changes; you might want to skip this patch."));
		die_user_resolve(state);
	}

	if (unmerged_cache()) {
		printf_ln(_("You still have unmerged paths in your index.\n"
			"Did you forget to use 'git add'?"));
		die_user_resolve(state);
	}

	if (state->interactive) {
		write_index_patch(state);
		if (do_interactive(state))
			goto next;
	}

	rerere(0);

	do_commit(state);

next:
	am_next(state);
	am_load(state);
	am_run(state, 0);
}

/**
 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
 * failure.
 */
static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
{
	struct lock_file *lock_file;
	struct unpack_trees_options opts;
	struct tree_desc t[2];

	if (parse_tree(head) || parse_tree(remote))
		return -1;

	lock_file = xcalloc(1, sizeof(struct lock_file));
	hold_locked_index(lock_file, 1);

	refresh_cache(REFRESH_QUIET);

	memset(&opts, 0, sizeof(opts));
	opts.head_idx = 1;
	opts.src_index = &the_index;
	opts.dst_index = &the_index;
	opts.update = 1;
	opts.merge = 1;
	opts.reset = reset;
	opts.fn = twoway_merge;
	init_tree_desc(&t[0], head->buffer, head->size);
	init_tree_desc(&t[1], remote->buffer, remote->size);

	if (unpack_trees(2, t, &opts)) {
		rollback_lock_file(lock_file);
		return -1;
	}

	if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
		die(_("unable to write new index file"));

	return 0;
}

/**
 * Merges a tree into the index. The index's stat info will take precedence
 * over the merged tree's. Returns 0 on success, -1 on failure.
 */
static int merge_tree(struct tree *tree)
{
	struct lock_file *lock_file;
	struct unpack_trees_options opts;
	struct tree_desc t[1];

	if (parse_tree(tree))
		return -1;

	lock_file = xcalloc(1, sizeof(struct lock_file));
	hold_locked_index(lock_file, 1);

	memset(&opts, 0, sizeof(opts));
	opts.head_idx = 1;
	opts.src_index = &the_index;
	opts.dst_index = &the_index;
	opts.merge = 1;
	opts.fn = oneway_merge;
	init_tree_desc(&t[0], tree->buffer, tree->size);

	if (unpack_trees(1, t, &opts)) {
		rollback_lock_file(lock_file);
		return -1;
	}

	if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
		die(_("unable to write new index file"));

	return 0;
}

/**
 * Clean the index without touching entries that are not modified between
 * `head` and `remote`.
 */
static int clean_index(const unsigned char *head, const unsigned char *remote)
{
	struct tree *head_tree, *remote_tree, *index_tree;
	unsigned char index[GIT_SHA1_RAWSZ];

	head_tree = parse_tree_indirect(head);
	if (!head_tree)
		return error(_("Could not parse object '%s'."), sha1_to_hex(head));

	remote_tree = parse_tree_indirect(remote);
	if (!remote_tree)
		return error(_("Could not parse object '%s'."), sha1_to_hex(remote));

	read_cache_unmerged();

	if (fast_forward_to(head_tree, head_tree, 1))
		return -1;

	if (write_cache_as_tree(index, 0, NULL))
		return -1;

	index_tree = parse_tree_indirect(index);
	if (!index_tree)
		return error(_("Could not parse object '%s'."), sha1_to_hex(index));

	if (fast_forward_to(index_tree, remote_tree, 0))
		return -1;

	if (merge_tree(remote_tree))
		return -1;

	remove_branch_state();

	return 0;
}

/**
 * Resets rerere's merge resolution metadata.
 */
static void am_rerere_clear(void)
{
	struct string_list merge_rr = STRING_LIST_INIT_DUP;
	rerere_clear(&merge_rr);
	string_list_clear(&merge_rr, 1);
}

/**
 * Resume the current am session by skipping the current patch.
 */
static void am_skip(struct am_state *state)
{
	unsigned char head[GIT_SHA1_RAWSZ];

	am_rerere_clear();

	if (get_sha1("HEAD", head))
		hashcpy(head, EMPTY_TREE_SHA1_BIN);

	if (clean_index(head, head))
		die(_("failed to clean index"));

	am_next(state);
	am_load(state);
	am_run(state, 0);
}

/**
 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
 *
 * It is not safe to reset HEAD when:
 * 1. git-am previously failed because the index was dirty.
 * 2. HEAD has moved since git-am previously failed.
 */
static int safe_to_abort(const struct am_state *state)
{
	struct strbuf sb = STRBUF_INIT;
	unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];

	if (file_exists(am_path(state, "dirtyindex")))
		return 0;

	if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
		if (get_sha1_hex(sb.buf, abort_safety))
			die(_("could not parse %s"), am_path(state, "abort_safety"));
	} else
		hashclr(abort_safety);

	if (get_sha1("HEAD", head))
		hashclr(head);

	if (!hashcmp(head, abort_safety))
		return 1;

	error(_("You seem to have moved HEAD since the last 'am' failure.\n"
		"Not rewinding to ORIG_HEAD"));

	return 0;
}

/**
 * Aborts the current am session if it is safe to do so.
 */
static void am_abort(struct am_state *state)
{
	unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];
	int has_curr_head, has_orig_head;
	char *curr_branch;

	if (!safe_to_abort(state)) {
		am_destroy(state);
		return;
	}

	am_rerere_clear();

	curr_branch = resolve_refdup("HEAD", 0, curr_head, NULL);
	has_curr_head = !is_null_sha1(curr_head);
	if (!has_curr_head)
		hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);

	has_orig_head = !get_sha1("ORIG_HEAD", orig_head);
	if (!has_orig_head)
		hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);

	clean_index(curr_head, orig_head);

	if (has_orig_head)
		update_ref("am --abort", "HEAD", orig_head,
				has_curr_head ? curr_head : NULL, 0,
				UPDATE_REFS_DIE_ON_ERR);
	else if (curr_branch)
		delete_ref(curr_branch, NULL, REF_NODEREF);

	free(curr_branch);
	am_destroy(state);
}

/**
 * parse_options() callback that validates and sets opt->value to the
 * PATCH_FORMAT_* enum value corresponding to `arg`.
 */
static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
{
	int *opt_value = opt->value;

	if (!strcmp(arg, "mbox"))
		*opt_value = PATCH_FORMAT_MBOX;
	else if (!strcmp(arg, "stgit"))
		*opt_value = PATCH_FORMAT_STGIT;
	else if (!strcmp(arg, "stgit-series"))
		*opt_value = PATCH_FORMAT_STGIT_SERIES;
	else if (!strcmp(arg, "hg"))
		*opt_value = PATCH_FORMAT_HG;
	else
		return error(_("Invalid value for --patch-format: %s"), arg);
	return 0;
}

enum resume_mode {
	RESUME_FALSE = 0,
	RESUME_APPLY,
	RESUME_RESOLVED,
	RESUME_SKIP,
	RESUME_ABORT
};

static int git_am_config(const char *k, const char *v, void *cb)
{
	int status;

	status = git_gpg_config(k, v, NULL);
	if (status)
		return status;

	return git_default_config(k, v, NULL);
}

int cmd_am(int argc, const char **argv, const char *prefix)
{
	struct am_state state;
	int binary = -1;
	int keep_cr = -1;
	int patch_format = PATCH_FORMAT_UNKNOWN;
	enum resume_mode resume = RESUME_FALSE;
	int in_progress;

	const char * const usage[] = {
		N_("git am [<options>] [(<mbox>|<Maildir>)...]"),
		N_("git am [<options>] (--continue | --skip | --abort)"),
		NULL
	};

	struct option options[] = {
		OPT_BOOL('i', "interactive", &state.interactive,
			N_("run interactively")),
		OPT_HIDDEN_BOOL('b', "binary", &binary,
			N_("historical option -- no-op")),
		OPT_BOOL('3', "3way", &state.threeway,
			N_("allow fall back on 3way merging if needed")),
		OPT__QUIET(&state.quiet, N_("be quiet")),
		OPT_SET_INT('s', "signoff", &state.signoff,
			N_("add a Signed-off-by line to the commit message"),
			SIGNOFF_EXPLICIT),
		OPT_BOOL('u', "utf8", &state.utf8,
			N_("recode into utf8 (default)")),
		OPT_SET_INT('k', "keep", &state.keep,
			N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
		OPT_SET_INT(0, "keep-non-patch", &state.keep,
			N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
		OPT_BOOL('m', "message-id", &state.message_id,
			N_("pass -m flag to git-mailinfo")),
		{ OPTION_SET_INT, 0, "keep-cr", &keep_cr, NULL,
		  N_("pass --keep-cr flag to git-mailsplit for mbox format"),
		  PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},
		{ OPTION_SET_INT, 0, "no-keep-cr", &keep_cr, NULL,
		  N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
		  PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
		OPT_BOOL('c', "scissors", &state.scissors,
			N_("strip everything before a scissors line")),
		OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
			N_("pass it through git-apply"),
			0),
		OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
			N_("pass it through git-apply"),
			PARSE_OPT_NOARG),
		OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
			N_("pass it through git-apply"),
			PARSE_OPT_NOARG),
		OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
			N_("pass it through git-apply"),
			0),
		OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
			N_("pass it through git-apply"),
			0),
		OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
			N_("pass it through git-apply"),
			0),
		OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
			N_("pass it through git-apply"),
			0),
		OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
			N_("pass it through git-apply"),
			0),
		OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
			N_("format the patch(es) are in"),
			parse_opt_patchformat),
		OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
			N_("pass it through git-apply"),
			PARSE_OPT_NOARG),
		OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
			N_("override error message when patch failure occurs")),
		OPT_CMDMODE(0, "continue", &resume,
			N_("continue applying patches after resolving a conflict"),
			RESUME_RESOLVED),
		OPT_CMDMODE('r', "resolved", &resume,
			N_("synonyms for --continue"),
			RESUME_RESOLVED),
		OPT_CMDMODE(0, "skip", &resume,
			N_("skip the current patch"),
			RESUME_SKIP),
		OPT_CMDMODE(0, "abort", &resume,
			N_("restore the original branch and abort the patching operation."),
			RESUME_ABORT),
		OPT_BOOL(0, "committer-date-is-author-date",
			&state.committer_date_is_author_date,
			N_("lie about committer date")),
		OPT_BOOL(0, "ignore-date", &state.ignore_date,
			N_("use current timestamp for author date")),
		OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),
		{ OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
		  N_("GPG-sign commits"),
		  PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
		OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
			N_("(internal use for git-rebase)")),
		OPT_END()
	};

	git_config(git_am_config, NULL);

	am_state_init(&state, git_path("rebase-apply"));

	in_progress = am_in_progress(&state);
	if (in_progress)
		am_load(&state);

	argc = parse_options(argc, argv, prefix, options, usage, 0);

	if (binary >= 0)
		fprintf_ln(stderr, _("The -b/--binary option has been a no-op for long time, and\n"
				"it will be removed. Please do not use it anymore."));

	/* Ensure a valid committer ident can be constructed */
	git_committer_info(IDENT_STRICT);

	if (read_index_preload(&the_index, NULL) < 0)
		die(_("failed to read the index"));

	if (in_progress) {
		/*
		 * Catch user error to feed us patches when there is a session
		 * in progress:
		 *
		 * 1. mbox path(s) are provided on the command-line.
		 * 2. stdin is not a tty: the user is trying to feed us a patch
		 *    from standard input. This is somewhat unreliable -- stdin
		 *    could be /dev/null for example and the caller did not
		 *    intend to feed us a patch but wanted to continue
		 *    unattended.
		 */
		if (argc || (resume == RESUME_FALSE && !isatty(0)))
			die(_("previous rebase directory %s still exists but mbox given."),
				state.dir);

		if (resume == RESUME_FALSE)
			resume = RESUME_APPLY;

		if (state.signoff == SIGNOFF_EXPLICIT)
			am_append_signoff(&state);
	} else {
		struct argv_array paths = ARGV_ARRAY_INIT;
		int i;

		/*
		 * Handle stray state directory in the independent-run case. In
		 * the --rebasing case, it is up to the caller to take care of
		 * stray directories.
		 */
		if (file_exists(state.dir) && !state.rebasing) {
			if (resume == RESUME_ABORT) {
				am_destroy(&state);
				am_state_release(&state);
				return 0;
			}

			die(_("Stray %s directory found.\n"
				"Use \"git am --abort\" to remove it."),
				state.dir);
		}

		if (resume)
			die(_("Resolve operation not in progress, we are not resuming."));

		for (i = 0; i < argc; i++) {
			if (is_absolute_path(argv[i]) || !prefix)
				argv_array_push(&paths, argv[i]);
			else
				argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
		}

		am_setup(&state, patch_format, paths.argv, keep_cr);

		argv_array_clear(&paths);
	}

	switch (resume) {
	case RESUME_FALSE:
		am_run(&state, 0);
		break;
	case RESUME_APPLY:
		am_run(&state, 1);
		break;
	case RESUME_RESOLVED:
		am_resolve(&state);
		break;
	case RESUME_SKIP:
		am_skip(&state);
		break;
	case RESUME_ABORT:
		am_abort(&state);
		break;
	default:
		die("BUG: invalid resume value");
	}

	am_state_release(&state);

	return 0;
}


text:
from util.UCFactory import UCFactory

__author__ = 'cansik'

class UCKeyboard(object):
    def __init__(self):
        self.__keyboard = UCFactory.get_keyboard()

    def key_down(self, key_code):
        self.__keyboard.key_down(key_code)

    def key_up(self, key_code):
        self.__keyboard.key_up(key_code)

    def send_key(self, key_code):
        self.key_down(key_code)
        self.key_up(key_code)


text:
=============
Notifications
=============

General info about plugin
=========================

Notifications is javascript/jquery plugin, which supports displaying info boxes for system users.

Implementation is based on:
 * jquery.midgardNotification plugin: http://createjs.org/guide/#notifications
 * Twitter.bootstrap: http://twitter.github.com/bootstrap/components.html#alerts

Init and usage
==============
Initialization of Notification plugin is realized in JavaScript/Init.js
To init and allow usage of notifications in project, inside other modules use requireJS

Usage::
define(['notification'], function(Notification) {
	Notification.initialize();
	Notification.showInfo('Notification message');
});

Types of notifications
======================
After initialization, Notifications enable to display several types of notifications:

Info
----
Can be used to display simple information for user.

Usage::

 App.Service.Notification.showInfo('Info text for user');

Success
-------
Can be used to display success information about action of user or system.

Usage::

 App.Service.Notification.showSuccess('Data is updated');

Warning
-----
Can be displayed to warn the user.

Usage::

 App.Service.Notification.showWarning('Your account is expiring!');

Error
-----
Should be displayed whe action of user/system was failed.

Usage::

 App.Service.Notification.showError('Saving a form failed');

Dialog
------
Dialog notification allow possibility to display more interactive, chained notifications.

It supports setting up second argument with actions.

Its possible to set multiple buttons, separately for each action and also combine them with callback function.
Inside callback function there can be another Notifications executed.

Usage::

 var actions =
 [
	{
		name: 'yes', label: 'Yes',
		cb: function(e, notification) {
			App.Service.Notification.showSuccess('Record was deleted');
			notification.close();
		}
	},
	{
		name: 'no', label: 'No',
		cb: function(e, notification) {
			notification.close();
		}
	}
 ];

 App.Service.Notification.showDialog('Are you sure you want to delete this record?', 'Confirmation required!', actions);

Timeout settings
================
By default, timeout is set to 5 seconds.

The are some ways to manipulate time.

Global timeout
--------------

Function ``setTimeout`` allows to set/change default time of timeout::

 App.Service.Notification.setTimeout(2000); //2000 = 2 seconds

Timeout for one notification
----------------------------

Its possible to set timeout only for selected notification::

 App.Service.Notification.showInfo('I go home in one second', 'Info', 1000);

Sticky notification
-------------------

To make notification displayed until user reaction use ``0`` value for timeout::

 App.Service.Notification.showError('You made a BIG mistake', false, 0);


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <title>SFML - Simple and Fast Multimedia Library</title>
        <meta http-equiv="Content-Type" content="text/html;"/>
        <meta charset="utf-8"/>

        <link rel="stylesheet" type="text/css" href="doxygen.css" title="default" media="screen,print" />

                SFML 2.4.2

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Class List

Class Index

Class Hierarchy

Class Members

sf

OutputSoundFile

Public Member Functions |
List of all members

sf::OutputSoundFile Class Reference
Audio module

Provide write access to sound files.
 More...

#include <OutputSoundFile.hpp>

Inheritance diagram for sf::OutputSoundFile:

  <map id="sf::OutputSoundFile_map" name="sf::OutputSoundFile_map">
<area href="classsf_1_1NonCopyable.html" title="Utility class that makes any derived class non-copyable. " alt="sf::NonCopyable" shape="rect" coords="0,0,122,24"/>
</map>

Public Member Functions

 	OutputSoundFile ()

 	Default constructor.  More...

 	~OutputSoundFile ()

 	Destructor.  More...

bool 	openFromFile (const std::string &filename, unsigned int sampleRate, unsigned int channelCount)

 	Open the sound file from the disk for writing.  More...

void 	write (const Int16 *samples, Uint64 count)

 	Write audio samples to the file.  More...

Detailed Description

Provide write access to sound files.

This class encodes audio samples to a sound file.

It is used internally by higher-level classes such as sf::SoundBuffer, but can also be useful if you want to create audio files from custom data sources, like generated audio samples.

Usage example:

// Create a sound file, ogg/vorbis format, 44100 Hz, stereo

sf::OutputSoundFile file;

if (!file.openFromFile("music.ogg", 44100, 2))

    /* error */;

while (...)

{

    // Read or generate audio samples from your custom source

    std::vector<sf::Int16> samples = ...;

    // Write them to the file

    file.write(samples.data(), samples.size());

}

See also

sf::SoundFileWriter, sf::InputSoundFile

Definition at line 44 of file OutputSoundFile.hpp.

Constructor & Destructor Documentation

          sf::OutputSoundFile::OutputSoundFile
          (
          	)

Default constructor.

          sf::OutputSoundFile::~OutputSoundFile
          (
          	)

Destructor.

Closes the file if it was still open.

Member Function Documentation

          bool sf::OutputSoundFile::openFromFile
          (
          const std::string &
          filename,

          unsigned int
          sampleRate,

          unsigned int
          channelCount

          )

Open the sound file from the disk for writing.

The supported audio formats are: WAV, OGG/Vorbis, FLAC.

Parameters

filename	Path of the sound file to write

sampleRate	Sample rate of the sound

channelCount	Number of channels in the sound

Returns

True if the file was successfully opened

          void sf::OutputSoundFile::write
          (
          const Int16 *
          samples,

          Uint64
          count

          )

Write audio samples to the file.

Parameters

samples	Pointer to the sample array to write

count	Number of samples to write

The documentation for this class was generated from the following file:

OutputSoundFile.hpp

                SFML is licensed under the terms and conditions of the zlib/png license.

                Copyright © Laurent Gomila  ::
                Documentation generated by doxygen  ::


text:
//using System.Web.Mvc;
//using AbstractConfigurationManager;
//using Entities;
//using FluentAssertions;
//using ItsaWeb.Controllers;
//using ItsaWeb.Models;
//using ItsaWeb.Models.Users;
//using Logging;
//using Moq;
//using NUnit.Framework;
//using ServiceInterfaces;

//namespace ItsaWebTests.Controllers
//{
//    [TestFixture]
//    public class UserControllerTests : ControllerTestsBase
//    {
//        private Mock<IUserService> _userService;
//        private Mock<IConfigurationManager> _configurationManager;
//        private Mock<ILogger> _logger;

//        [SetUp]
//        public void Setup()
//        {
//            _userService = new Mock<IUserService>();
//            _configurationManager = new Mock<IConfigurationManager>();
//            _logger = new Mock<ILogger>();

//            _configurationManager.Setup(c => c.AppSetting("cookie")).Returns("anything");
//        }

//        [Test]
//        public void GivenARegisteredUser_WhenITryAndReRegister_ThenIAmRedirectedToLogin()
//        {
//            _userService.Setup(u => u.GetRegisteredUser()).Returns(new User());
//            var controller = new UserController(_userService.Object, null, _logger.Object);
//            var view = controller.New(new RegisterUserViewModel());
//            view.Should().BeOfType<RedirectToRouteResult>();
//        }

//        [Test]
//        public void GivenARegisteredUser_WhenITryAndReRegister_ThenTempDataContainsTheCorrectMessage()
//        {
//            _userService.Setup(u => u.GetRegisteredUser()).Returns(new User());
//            var controller = new UserController(_userService.Object, null, _logger.Object);
//            SetControllerContext(controller);
//            controller.New(new RegisterUserViewModel());
//            TempData["message"].Should().Be("User is already registered");
//        }

//        [Test]
//        public void GivenAnUnRegisteredUser_WhenITryAndReRegister_ThenIAmShowTheRegisterView()
//        {
//            _userService.Setup(u => u.GetRegisteredUser()).Returns((User) null);
//            var controller = new UserController(_userService.Object, null, _logger.Object);
//            var view = controller.New(new RegisterUserViewModel{Email = "user"});
//            view.Should().BeOfType<ViewResult>();
//        }

//        [Test]
//        public void GivenAValidUser_WhenTheUserIsCreated_ThenTheUserIsRegistered()
//        {
//            const string password = "password";
//            const string email = "email";
//            var controller = new UserController(_userService.Object, _configurationManager.Object, _logger.Object);

//            SetControllerContext(controller);

//            controller.Create(new RegisterUserViewModel{Email = email, Password = password});
//            _userService.Verify(u => u.Register(email, password), Times.Once());
//        }

//        [Test]
//        public void GivenAValidUser_WhenTheUserIsCreated_ThenIndexViewIsReturned()
//        {
//            const string password = "password";
//            const string email = "email";
//            var controller = new UserController(_userService.Object, _configurationManager.Object, _logger.Object);

//            SetControllerContext(controller);

//            var view = controller.Create(new RegisterUserViewModel { Email = email, Password = password });
//            view.Should().BeOfType<RedirectToRouteResult>();
//            view.As<RedirectToRouteResult>().RouteValues["controller"].Should().Be("Itsa");
//            view.As<RedirectToRouteResult>().RouteValues["action"].Should().Be("Index");
//        }

//        [Test]
//        public void GivenARegisteredUser_WhenITryAndDelete_ThenTempDataContainsTheCorrectMessage()
//        {
//            _userService.Setup(u => u.UnRegister()).Returns(true);
//            var controller = new UserController(_userService.Object, null, _logger.Object);
//            SetControllerContext(controller);
//            controller.Delete();
//            TempData["message"].Should().Be("User unregistered");
//        }

//        [Test]
//        public void GivenAnUnregisteredUser_WhenITryAndDelete_ThenTempDataContainsTheCorrectMessage()
//        {
//            _userService.Setup(u => u.UnRegister()).Returns(false);
//            var controller = new UserController(_userService.Object, null, _logger.Object);
//            SetControllerContext(controller);
//            controller.Delete();
//            TempData["message"].Should().Be("User already unregistered");
//        }

//        [Test]
//        public void WhenAUserIsDeleted_ThenTheControllerRedirectsToTheNewView()
//        {
//            _userService.Setup(u => u.UnRegister()).Returns(false);
//            var controller = new UserController(_userService.Object, null, _logger.Object);
//            SetControllerContext(controller);
//            var view = controller.Delete();
//            view.Should().BeOfType<RedirectToRouteResult>();
//            view.As<RedirectToRouteResult>().RouteValues["action"].Should().Be("New");
//        }
//    }
//}


text:
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>UBL 2.1 Tenderer Qualification UML diagram</title>
      <META HTTP-EQUIV="refresh" CONTENT="0 ; URL=EARoot/EA103.htm">

UML diagram for UBL 2.1 Tenderer Qualification

EARoot/EA103.htm.

         If your browser supports automatic redirection, this link will
         be automatically traversed.

         Otherwise, please click on the link above to proceed!


text:
package weifen.com.eclife.activity;

import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;
import weifen.com.common.app.BaseApplication;
import weifen.com.common.base.BaseActivity;
import weifen.com.common.utils.ActivityCollector;
import weifen.com.eclife.R;
import weifen.com.eclife.app.MyApplication;
import weifen.com.eclife.domain.URLUtil;

/**
 * Created by zhurencong on 2017/9/20.
 */
public class SettingActivity extends BaseActivity implements View.OnClickListener {

    private ImageView back;
    private LinearLayout personalData,accountSafe,infoAuthentication,contact_Us,agreement;
    private TextView exit;
    private CircleImageView image;

    @Override
    protected int setLayout() {
        return R.layout.setting_layout;
    }

    @Override
    protected void initView() {

        ActivityCollector.addActivity(this);

        back= (ImageView) findViewById(R.id.back);
        personalData= (LinearLayout) findViewById(R.id.personal_data);
        accountSafe= (LinearLayout) findViewById(R.id.account_safe);
        infoAuthentication= (LinearLayout) findViewById(R.id.info_authentication);
        contact_Us= (LinearLayout) findViewById(R.id.contact_us);
        agreement= (LinearLayout) findViewById(R.id.agreement);
        exit= (TextView) findViewById(R.id.exit);
        image= (CircleImageView) findViewById(R.id.image);

        back.setOnClickListener(this);
        personalData.setOnClickListener(this);
        accountSafe.setOnClickListener(this);
        infoAuthentication.setOnClickListener(this);
        contact_Us.setOnClickListener(this);
        agreement.setOnClickListener(this);
        exit.setOnClickListener(this);

    }

    @Override
    protected void onResume() {
        super.onResume();

        if(!"".equals(MyApplication.user.getTel()+"")){
            setUserInfo();
        }
    }

    public void setUserInfo(){

        Picasso.with(this).load(URLUtil.URL_PATH+ MyApplication.user.getImageUrl()).error(getResources().getDrawable(R.mipmap.person_iocn)).into(image);
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()){
            //返回
            case R.id.back:
                finish();
                break;
            //个人资料
            case R.id.personal_data:
                intent=new Intent(this,InfoActivity.class);
                startActivity(intent);
                break;
            //账户安全
            case R.id.account_safe:
                break;
            //信息认证
            case R.id.info_authentication:
                break;
            //联系我们
            case R.id.contact_us:
                intent=new Intent(this,ContactUsActivity.class);
                startActivity(intent);
                break;
            //协议
            case R.id.agreement:
                break;
            //退出登录
            case R.id.exit:
                ActivityCollector.finishAll();
                break;
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
ByteProcessor (Guava Libraries 2010.01.04)
</TITLE>

<META NAME="date" CONTENT="2010-01-04">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.google.common.io

Interface ByteProcessor<T>

public interface ByteProcessor<T>

A callback interface to process bytes from a stream.

processBytes(byte[], int, int) will be called for each line that is read, and
 should return false when you want to stop processing.

Since:

2009.09.15 tentative

Author:

Chris Nokleberg

Method Summary

 T
getResult()

          Return the result of processing all the bytes.

 boolean
processBytes(byte[] buf,
             int off,
             int len)

          This method will be called for each chunk of bytes in an
 input stream.

Method Detail

processBytes

boolean processBytes(byte[] buf,
                     int off,
                     int len)
                     throws IOException

This method will be called for each chunk of bytes in an
 input stream. The implementation should process the bytes
 from buf[off] through buf[off + len - 1]
 (inclusive).

Parameters:
buf - the byte array containing the data to process
off - the initial offset into the array
len - the length of data to be processed

Returns:
true to continue processing, false to stop

Throws:

IOException

getResult

T getResult()

Return the result of processing all the bytes.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD