text:
package models.transit;

import static java.util.Collections.sort;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderColumn;
import javax.persistence.Query;

import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonManagedReference;
import org.geotools.ows.bindings.UpdateSequenceTypeBinding;
import org.hibernate.annotations.Type;

import play.Logger;
import play.db.jpa.Model;
import models.gtfs.GtfsSnapshot;

@JsonIgnoreProperties({"entityId", "persistent"})
@Entity
public class TripPattern extends Model {

    public String name;
    public String headsign;

    @Column(length = 8000,columnDefinition="TEXT")
    public String encodedShape;

    @JsonIgnore
    @ManyToOne
    public TripShape shape;

    @ManyToOne
    public Route route;

    @JsonManagedReference
    @OneToMany(cascade = CascadeType.ALL)
    public List<TripPatternStop> patternStops;

    public Boolean longest;

    public Boolean weekday;
    public Boolean saturday;
    public Boolean sunday;

    public Boolean useFrequency;

    public Integer startTime;
    public Integer endTime;

    public Integer headway;

    @JsonCreator
    public static TripPattern factory(long id) {
      return TripPattern.findById(id);
    }

    @JsonCreator
    public static TripPattern factory(String id) {
      return TripPattern.findById(Long.parseLong(id));
    }

    public TripPattern()
    {

    }

    public TripPattern(String name, String headsign, TripShape shape, Route route)
    {
    	this.name = name;
    	this.headsign = headsign;
    	this.shape = shape;
    	this.route = route;
    }

    public TripPattern delete() {

    	this.patternStops = new ArrayList<TripPatternStop>();
    	this.save();

        List<TripPatternStop> patternStops = TripPatternStop.find("pattern = ?", this).fetch();
        for(TripPatternStop patternStop : patternStops)
        {
            patternStop.delete();
        }

        List<StopTime> stopTimes = StopTime.find("trip.pattern = ?", this).fetch();
        for(StopTime stopTime : stopTimes)
        {
            stopTime.delete();
        }

        List<Trip> trips = Trip.find("pattern = ?", this).fetch();

        for(Trip trip : trips)
        {
            trip.delete();
        }

        return super.delete();
    }

    public void resequenceTripStops()
    {
        List<TripPatternStop> stops = TripPatternStop.find("pattern = ? order by stopSequence", this).fetch();

        Integer sequence = 0;
        for(TripPatternStop stop : stops)
        {
                stop.stopSequence = sequence;
                stop.save();

                sequence++;
        }
    }

    /**
     * Sort a list of patternstops by stop_sequence
     */
    public static class PatternStopSequenceComparator implements Comparator<TripPatternStop> {
        public int compare(TripPatternStop o1, TripPatternStop o2) {

            // nulls last
            if (o1 == null && o2 == null)
                return 0;
            if (o1 == null)
                return 1;
            if (o2 == null)
                return -1;

            return o1.stopSequence - o2.stopSequence;
        }
    }

    /**
     * Sort a list of StopTimes by StopSequence
     */
    public static class StopTimeSequenceComparator implements Comparator<StopTime> {
        public int compare(StopTime o1, StopTime o2) {

            // nulls last
            if (o1 == null && o2 == null)
                return 0;
            if (o1 == null)
                return 1;
            if (o2 == null)
                return -1;

            return o1.stopSequence - o2.stopSequence;
        }
    }

    /**
     * update the trip pattern stops
     * see extensive discussion in ticket #102
     * basically, we assume only one stop has changed---either it's been removed, added or moved
     * this is consistent with the use of Backbone.save in the UI, and
     * also with the principle of least magic possible
     * of course, we check to ensure that that is the case and fail if it's not
     * this lets us easily detect what has happened simply by length
     * @param tripPattern the trip pattern containing the new patternstops
     */
    public void reconcilePatternStops(TripPattern tripPattern) {
        long[] originalStopIds = new long[this.patternStops.size()];
        long[] newStopIds = new long[tripPattern.patternStops.size()];

        // fill the arrays
        sort(this.patternStops, new PatternStopSequenceComparator());

        for (int i = 0; i < originalStopIds.length; i++) {
            originalStopIds[i] = this.patternStops.get(i).stop.id;
        }

        sort(tripPattern.patternStops, new PatternStopSequenceComparator());

        for (int i = 0; i < newStopIds.length; i++) {
            newStopIds[i] = tripPattern.patternStops.get(i).stop.id;
            // while we're at it, repack the patternstops so stop sequences monotonically increment by 1
            // we can't just use the function in tripPattern to do this, because it relies on stops having already been persisted to the database
            tripPattern.patternStops.get(i).stopSequence = i + 1;
        }

        /* ADDITIONS */
        if (originalStopIds.length == newStopIds.length - 1) {
            // we have an addition; find it

            int differenceLocation = -1;
            for (int i = 0; i < newStopIds.length; i++) {
                if (differenceLocation != -1) {
                    // we've already found the addition
                    if (i < originalStopIds.length && originalStopIds[i] != newStopIds[i + 1]) {
                        // there's another difference, which we weren't expecting
                        throw new IllegalStateException("Multiple differences found when trying to detect stop addition");
                    }
                }

                // if we've reached where one trip has an extra stop, or if the stops at this position differ
                else if (i == newStopIds.length - 1 || originalStopIds[i] != newStopIds[i]) {
                    // we have found the difference
                    differenceLocation = i;
                }
            }

            // repack stop times
            // this is super-easy; we don't need to remove or add anything, as we don't create stop times for
            // the new stop. We would have no way of knowing which trips stop at the new stop, or at what time.
            // Stop times can be manually created in the timetable editor.

            for (Object t : Trip.find("pattern = ?", this).fetch()) {
                Trip trip = (Trip) t;

                Iterator<TripPatternStop> pse = tripPattern.patternStops.listIterator();
                TripPatternStop current;

                // sort the stop times by stop sequence
                List<StopTime> stopTimes = trip.getStopTimes();
                sort(stopTimes, new StopTimeSequenceComparator());

                for (StopTime st : stopTimes) {
                    current = pse.next();

                    while (!current.stop.id.equals(st.stop.id))
                        current = pse.next();

                    st.stopSequence = current.stopSequence;
                    st.patternStop = current;
                    StopTime.em().merge(st).save();
                }
            }
        }

        /* DELETIONS */
        else if (originalStopIds.length == newStopIds.length + 1) {
            // we have an deletion; find it
            int differenceLocation = -1;
            for (int i = 0; i < originalStopIds.length; i++) {
                if (differenceLocation != -1) {
                    if (originalStopIds[i] != newStopIds[i - 1]) {
                        // there is another difference, which we were not expecting
                        throw new IllegalStateException("Multiple differences found when trying to detect stop removal");
                    }
                }

                // we've reacehd the end and the only difference is length (so the last stop is the different one)
                // or we've found the difference
                else if (i == originalStopIds.length -1 || originalStopIds[i] != newStopIds[i]) {
                    differenceLocation = i;
                }
            }

            // renumber the stop sequences
            int i = 1;
            for (TripPatternStop ps : tripPattern.patternStops) {
                ps.stopSequence = i++;
                TripPatternStop.em().merge(ps).save();
            }

            // repack stop times and remove stop times for removed pattern stop
            // this will NPE if the original trip pattern had a null stop sequence, but that's not supposed to happen
            int removedStopSeq = this.patternStops.get(differenceLocation).stopSequence;
            long removedStopId = originalStopIds[differenceLocation];

            for (Object t : Trip.find("pattern = ?", this).fetch()) {
                Trip trip = (Trip) t;

                // sort the stop times by stop sequence
                List<StopTime> stopTimes = trip.getStopTimes();
                sort(stopTimes, new StopTimeSequenceComparator());

                // remove the stop time we want to remove
                StopTime toRemove = null;

                // something to get patternStops
                Iterator<TripPatternStop> pse = tripPattern.patternStops.listIterator();

                TripPatternStop current;

                for (StopTime st : stopTimes) {
                    if (st.stop.id.equals(removedStopId) && st.stopSequence.equals(removedStopSeq)) {
                        toRemove = st;
                        continue;
                    }

                    // ensure this happens at least once per iteration, in case the same stop occurs twice in a row
                    // that is bad but does happen
                    current = pse.next();

                    // skip skipped patternstops
                    // not every trip has to stop at every stop in a pattern
                    while (!current.stop.id.equals(st.stop.id))
                        current = pse.next();

                    st.stopSequence = current.stopSequence;
                    st.patternStop = current;
                    StopTime.em().merge(st).save();
                }

                toRemove.delete();
            }
        }

        /* TRANSPOSITIONS */
        else if (originalStopIds.length == newStopIds.length) {
            // Imagine the trip patterns pictured below (where . is a stop, and lines indicate the same stop)
            // the original trip pattern is on top, the new below
            // . . . . . . . .
            // | |  \ \ \  | |
            // * * * * * * * *
            // also imagine that the two that are unmarked are the same
            // (the limitations of ascii art, this is prettier on my whiteboard)
            // There are three regions: the beginning and end, where stopSequences are the same, and the middle, where they are not
            // The same is true of trips where stops were moved backwards

            // find the left bound of the changed region
            int firstDifferentIndex = 0;
            while (true) {
                // we've found the first index where they differ
                if (originalStopIds[firstDifferentIndex] != newStopIds[firstDifferentIndex])
                    break;

                firstDifferentIndex++;

                if (firstDifferentIndex == originalStopIds.length)
                    // trip patterns do not differ at all, nothing to do
                    return;
            }

            // find the right bound of the changed region
            int lastDifferentIndex = originalStopIds.length - 1;
            while (true) {
                if (originalStopIds[lastDifferentIndex] != newStopIds[lastDifferentIndex])
                    break;

                lastDifferentIndex--;
            }

            // TODO: write a unit test for this
            if (firstDifferentIndex == lastDifferentIndex) {
                throw new IllegalStateException("stop substitutions are not supported, region of difference must have length > 1");
            }

            // figure out whether a stop was moved left or right
            // note that if the stop was only moved one position, it's impossible to tell, and also doesn't matter,
            // because the requisite operations are equivalent
            long movedStopId;
            int movedStopSeq;
            int newStopSeq;
            TripPatternStop newPattStop;

            // TODO: ensure that this is all that happened (i.e. verify stop ID map inside changed region)
            if (originalStopIds[firstDifferentIndex] == newStopIds[lastDifferentIndex]) {
                movedStopId = originalStopIds[firstDifferentIndex];
                movedStopSeq = this.patternStops.get(firstDifferentIndex).stopSequence;
                newStopSeq = tripPattern.patternStops.get(lastDifferentIndex).stopSequence;
                newPattStop = tripPattern.patternStops.get(lastDifferentIndex);
            }

            else if (newStopIds[firstDifferentIndex] == originalStopIds[lastDifferentIndex]) {
                // stop was moved left
                movedStopId = originalStopIds[lastDifferentIndex];
                movedStopSeq = this.patternStops.get(lastDifferentIndex).stopSequence;
                newStopSeq = tripPattern.patternStops.get(firstDifferentIndex).stopSequence;
                newPattStop = tripPattern.patternStops.get(firstDifferentIndex);
            }

            else {
                throw new IllegalStateException("not a simple, single move!");
            }

            for (Object t : Trip.find("pattern = ?", this).fetch()) {
                Trip trip = (Trip) t;

                List<StopTime> stopTimes = trip.getStopTimes();

                // sort
                sort(stopTimes, new StopTimeSequenceComparator());

                Iterator<TripPatternStop> psi = tripPattern.patternStops.iterator();

                TripPatternStop current;

                // record if there were stop times
                // if there were, invalidate the trip.
                boolean hadStopTimes = false;

                for (StopTime st : stopTimes) {
                    if (st.arrivalTime != null || st.departureTime != null)
                        hadStopTimes = true;

                    if (st.stop.id.equals(movedStopId) && st.stopSequence.equals(movedStopSeq)) {
                        // we are dealing with the moved stop
                        st.stopSequence = newStopSeq;
                        StopTime updated = StopTime.em().merge(st);
                        updated.patternStop = newPattStop;
                    }

                    else {
                        // we are not dealing with the moved stop
                        current = psi.next();

                        while (!current.stop.id.equals(st.stop.id) ||
                                // skip the moved stop, in case the same stop appears twice
                                (current.stop.id.equals(movedStopId) && current.stopSequence.equals(newStopSeq)))
                            current = psi.next();

                        st.stopSequence = current.stopSequence;
                        StopTime updated = StopTime.em().merge(st);
                        updated.patternStop = current;
                    }
                }

                if (hadStopTimes) {
                    trip.invalid = true;
                    trip.save();
                }

                trip.refresh();
            }
        }

        /* OTHER STUFF IS NOT SUPPORTED */
        else {
            throw new IllegalStateException("Changes to trip pattern stops must be made one at a time");
        }
    }

    public static BigInteger createFromTrip(EntityManager em, BigInteger tripId)
    {
    	Trip trip = Trip.findById(tripId.longValue());

    	Query idQuery = em.createNativeQuery("SELECT NEXTVAL('hibernate_sequence');");
		BigInteger tripPatternId = (BigInteger)idQuery.getSingleResult();

		Query q;

		if(trip.shape != null)
			q = em.createNativeQuery("INSERT INTO trippattern (id, name, route_id, headsign, shape_id)" +
	    	"  VALUES(?, ?, ?, ?, ?);");
		else
			q = em.createNativeQuery("INSERT INTO trippattern (id, name, route_id, headsign)" +
			    	"  VALUES(?, ?, ?, ?);");

	      q.setParameter(1,  tripPatternId.longValue())
	      .setParameter(2,  trip.route.routeShortName + "(" + trip.tripHeadsign + ")")
	      .setParameter(3,  trip.route.id)
	      .setParameter(4,  trip.tripHeadsign);

	      if(trip.shape != null)
	       q.setParameter(5,  trip.shape.id);

	      q.executeUpdate();

    	ArrayList<StopTime> stopTimes = trip.getStopTimes();

    	Integer previousDepartureTime = 0;
    	Double previousDistance = new Double(0);

    	Boolean firstStop = true;

    	String firstStopName = null;
    	String lastStopName = null;

    	for(StopTime stopTime : stopTimes)
    	{
    		BigInteger tripPatternStopId = (BigInteger)idQuery.getSingleResult();

    		q = em.createNativeQuery("INSERT INTO trippatternstop (id, pattern_id, stop_id, stopsequence, defaultdwelltime, defaultdistance, defaulttraveltime)" +
	    	"  VALUES(?, ?, ?, ?, ?, ?, ?);");

    		q.setParameter(1,  tripPatternStopId.longValue());
    		q.setParameter(2,  tripPatternId.longValue());
    		q.setParameter(3,  stopTime.stop.id);
    		q.setParameter(4,  stopTime.stopSequence);
    		q.setParameter(5,  stopTime.departureTime - stopTime.arrivalTime);

    		if(firstStop)
    		{
    			previousDepartureTime = stopTime.departureTime;

    			q.setParameter(6,  new Double(0));
    			q.setParameter(7,  0);

    			firstStop = false;

    			firstStopName = stopTime.stop.stopName;
    		}
    		else
    		{
    			q.setParameter(6,  stopTime.shapeDistTraveled - previousDistance);
    			q.setParameter(7,  stopTime.arrivalTime - previousDepartureTime);

    			previousDepartureTime = stopTime.departureTime;
    			previousDistance = stopTime.shapeDistTraveled;
    		}

    		lastStopName = stopTime.stop.stopName;

    		q.executeUpdate();

    		q = em.createNativeQuery("INSERT INTO trippattern_trippatternstop (trippattern_id, patternstops_id) VALUES (?, ?);");

    		q.setParameter(1,  tripPatternId.longValue());
    		q.setParameter(2,  tripPatternStopId.longValue());

    		q.executeUpdate();

    	}

    	trip.route.routeLongName = firstStopName + " - " + lastStopName;
    	trip.route.save();

    	Logger.info("Adding trip pattern: " + trip.route.routeShortName + " (" + trip.tripHeadsign + ")");

    	return tripPatternId;
    }
}


text:
import os.path
import tempfile

# Our testing module
import svntest
from svntest import wc

# (abbreviation)
Skip = svntest.testcase.Skip_deco
SkipUnless = svntest.testcase.SkipUnless_deco
XFail = svntest.testcase.XFail_deco
Issues = svntest.testcase.Issues_deco
Issue = svntest.testcase.Issue_deco
Wimp = svntest.testcase.Wimp_deco
Item = svntest.wc.StateItem

# Run svnauthz commands on commit
hook_template = """import sys,os,subprocess
svnauthz_bin=%s

fp = open(os.path.join(sys.argv[1], 'hooks.log'), 'wb')
def output_command(fp, cmd, opt):
  command = [svnauthz_bin, cmd, '-t', sys.argv[2], sys.argv[1]] + opt
  process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, bufsize=-1)
  (output, errors) = process.communicate()
  status = process.returncode
  fp.write(output)
  fp.write(errors)
  fp.write("Exit %%d\\n" %% status)
  return status

for (svnauthz_cmd, svnauthz_opt) in %s:
  output_command(fp, svnauthz_cmd, svnauthz_opt.split())
fp.close()"""

#----------------------------------------------------------------------
def verify_logfile(logfilename, expected_data, delete_log=True):
  if os.path.exists(logfilename):
    fp = open(logfilename)
  else:
    raise svntest.verify.SVNUnexpectedOutput("hook logfile %s not found"\
                                             % logfilename)

  actual_data = fp.readlines()
  fp.close()
  if delete_log:
    os.unlink(logfilename)
  svntest.verify.compare_and_display_lines('wrong hook logfile content',
                                           'HOOKLOG',
                                           expected_data, actual_data)

#----------------------------------------------------------------------

# Note we don't test various different validation failures, the
# validation is actually just done when the file is loaded and
# the library tests for the config file parser and the authz
# parser already validate various failures that return errors.

def svnauthz_validate_file_test(sbox):
  "test 'svnauthz validate' on files"

  # build an authz file
  (authz_fd, authz_path) = tempfile.mkstemp()
  authz_content = "[/]\n* = rw\n"
  svntest.main.file_write(authz_path, authz_content)

  # Valid authz file
  svntest.actions.run_and_verify_svnauthz("Valid authz file", None, None,
                                          0, False, "validate", authz_path)

  # Invalid authz file, expect exit code 1, we found the file loaded it
  # but found an error
  svntest.main.file_write(authz_path, 'x\n')
  svntest.actions.run_and_verify_svnauthz("Invalid authz file", None, None,
                                          1, False, "validate", authz_path)

  # Non-existant authz file
  # exit code 2, operational error since we can't test the file.
  os.close(authz_fd)
  os.remove(authz_path)
  svntest.actions.run_and_verify_svnauthz("Non-existant authz file", None,
                                          None, 2, False, "validate",
                                          authz_path)

@SkipUnless(svntest.main.is_ra_type_file)
def svnauthz_validate_repo_test(sbox):
  "test 'svnauthz validate' on urls"

  sbox.build()
  wc_dir = sbox.wc_dir
  repo_url = sbox.repo_url

  authz_content = "[/]\n* = rw\n"

  # build an authz file and commit it to the repo
  authz_path = os.path.join(wc_dir, 'A', 'authz')
  svntest.main.file_write(authz_path, authz_content)
  svntest.main.run_svn(None, 'add', authz_path)
  expected_output = wc.State(wc_dir, {'A/authz' : Item(verb='Adding')})
  expected_status = svntest.actions.get_virginal_state(wc_dir, 1)
  expected_status.add({
    'A/authz'            :  Item(status='  ', wc_rev=2),
  })
  if svntest.actions.run_and_verify_commit(wc_dir, expected_output,
                                           expected_status, None, wc_dir):
    raise svntest.Failure

  # Valid authz url (file stored in repo)
  authz_url = repo_url + '/A/authz'
  svntest.actions.run_and_verify_svnauthz("Valid authz url", None, None,
                                          0, False, "validate", authz_url)

  # Invalid authz url (again use the iota file in the repo)
  # expect exit code 1, we found the file loaded it but found an error
  iota_url = repo_url + '/iota'
  svntest.actions.run_and_verify_svnauthz("Invalid authz url", None, None,
                                          1, False, "validate", iota_url)

  # Non-existant authz url
  # exit code 2, operational error since we can't test the file.
  svntest.actions.run_and_verify_svnauthz("Non-existant authz file", None,
                                          None, 2, False, "validate",
                                          repo_url + "/zilch")

def svnauthz_validate_txn_test(sbox):
  "test 'svnauthz validate --transaction'"

  sbox.build()
  wc_dir = sbox.wc_dir
  repo_dir = sbox.repo_dir

  logfilepath = os.path.join(repo_dir, 'hooks.log')
  pre_commit_hook = svntest.main.get_pre_commit_hook_path(repo_dir)
  hook_instance = hook_template % (repr(svntest.main.svnauthz_binary),
                                   repr([('validate', 'A/authz')]))
  svntest.main.create_python_hook_script(pre_commit_hook, hook_instance)

  # Create an authz file
  authz_content = "[/]\n* = rw\n"
  authz_path = os.path.join(wc_dir, 'A/authz')
  svntest.main.file_write(authz_path, authz_content)
  svntest.main.run_svn(None, 'add', authz_path)

  # commit a valid authz file, and check the hook's logfile
  expected_output = wc.State(wc_dir, {'A/authz' : Item(verb='Adding')})
  expected_status = svntest.actions.get_virginal_state(wc_dir, 1)
  expected_status.add({
    'A/authz'            :  Item(status='  ', wc_rev=2),
  })
  if svntest.actions.run_and_verify_commit(wc_dir, expected_output,
                                           expected_status, None, wc_dir):
    raise svntest.Failure
  expected_data = ['Exit 0\n']
  verify_logfile(logfilepath, expected_data)

  # Add an invalid line to the authz file.
  svntest.main.file_append(authz_path, 'x')
  expected_output = wc.State(wc_dir, {'A/authz' : Item(verb='Sending')})
  expected_status.tweak('A/authz', status='  ', wc_rev=3)
  if svntest.actions.run_and_verify_commit(wc_dir, expected_output,
                                           expected_status, None, wc_dir):
    raise svntest.Failure
  expected_data = svntest.verify.RegexOutput(".*?Error parsing authz file: '.*?'",
                                             match_all=False)
  verify_logfile(logfilepath, expected_data, delete_log=False)
  # Check the logfile that our Exit was 1 too
  expected_data = svntest.verify.ExpectedOutput("Exit 1\n", match_all=False)
  verify_logfile(logfilepath, expected_data)

  # Validate a file that doesn't exist and make sure we're exiting with 2.
  hook_instance = hook_template % (repr(svntest.main.svnauthz_binary),
                                   repr([('validate', 'zilch')]))
  svntest.main.create_python_hook_script(pre_commit_hook, hook_instance)
  svntest.main.file_append(authz_path, 'x')
  expected_status.tweak('A/authz', status='  ', wc_rev=4)
  if svntest.actions.run_and_verify_commit(wc_dir, expected_output,
                                           expected_status, None, wc_dir):
    raise svntest.Failure
  expected_data = svntest.verify.ExpectedOutput("Exit 2\n", match_all=False)
  verify_logfile(logfilepath, expected_data)

def svnauthz_accessof_file_test(sbox):
  "test 'svnauthz accessof' on files"

  # build an authz file
  (authz_fd, authz_path) = tempfile.mkstemp()
  authz_content = "[/]\ngroucho = \ngallagher = rw\n* = r\n" + \
      "[/bios]\n* = rw\n" + \
      "[comedy:/jokes]\ngroucho = rw\n" + \
      "[slapstick:/jokes]\n* =\n"
  svntest.main.file_write(authz_path, authz_content)

  # Anonymous access with no path, and no repository should be rw
  # since it returns the highest level of access granted anywhere.
  # So /bios being rw for everyone means this will be rw.
  svntest.actions.run_and_verify_svnauthz("Anonymous access", ["rw\n"], None,
                                          0, False, "accessof", authz_path)

  # Anonymous access on /jokes should be r, no repo so won't match
  # the slapstick:/jokes section.
  svntest.actions.run_and_verify_svnauthz("Anonymous access on path",
                                          ["r\n"], None, 0, False, "accessof",
                                          authz_path, "--path", "/jokes")

  # Anonymous access on /jokes on slapstick repo should be no
  svntest.actions.run_and_verify_svnauthz("Anonymous access on path with repo",
                                          ["no\n"], None, 0, False, "accessof",
                                          authz_path, "--path", "/jokes",
                                          "--repository", "slapstick")

  # User access with no path, and no repository should be rw
  # since it returns the h ighest level of access anywhere.
  # So /bios being rw for everyone means this will be rw.
  svntest.actions.run_and_verify_svnauthz("User access", ["rw\n"], None,
                                          0, False, "accessof", authz_path,
                                          "--username", "groucho")

  # User groucho specified on /jokes with no repo, will not match any of the
  # repo specific sections, so is r since everyone has read access.
  svntest.actions.run_and_verify_svnauthz("User access on path", ["r\n"], None,
                                          0, False, "accessof", authz_path,
                                          "--path", "/jokes", "--username",
                                          "groucho")

  # User groucho specified on /jokes with the repo comedy will be rw
  svntest.actions.run_and_verify_svnauthz("User access on path with repo",
                                          ["rw\n"], None, 0, False, "accessof",
                                          authz_path, "--path", "/jokes",
                                          "--username", "groucho",
                                          "--repository", "comedy")

  os.close(authz_fd)
  os.remove(authz_path)

@SkipUnless(svntest.main.is_ra_type_file)
def svnauthz_accessof_repo_test(sbox):
  "test 'svnauthz accessof' on urls"

  sbox.build()
  wc_dir = sbox.wc_dir
  repo_url = sbox.repo_url

  authz_content = "[/]\ngroucho = \ngallagher = rw\n* = r\n" + \
      "[/bios]\n* = rw\n" + \
      "[comedy:/jokes]\ngroucho = rw\n" + \
      "[slapstick:/jokes]\n* =\n"

  # build an authz file and commit it to the repo
  authz_path = os.path.join(wc_dir, 'A', 'authz')
  svntest.main.file_write(authz_path, authz_content)
  svntest.main.run_svn(None, 'add', authz_path)
  expected_output = wc.State(wc_dir, {'A/authz' : Item(verb='Adding')})
  expected_status = svntest.actions.get_virginal_state(wc_dir, 1)
  expected_status.add({
    'A/authz'            :  Item(status='  ', wc_rev=2),
  })
  if svntest.actions.run_and_verify_commit(wc_dir, expected_output,
                                           expected_status, None, wc_dir):
    raise svntest.Failure

  # Anonymous access with no path, and no repository should be rw
  # since it returns the highest level of access granted anywhere.
  # So /bios being rw for everyone means this will be rw.
  authz_url = repo_url + "/A/authz"
  svntest.actions.run_and_verify_svnauthz("Anonymous access", ["rw\n"], None,
                                          0, False, "accessof", authz_url)

  # Anonymous access on /jokes should be r, no repo so won't match
  # the slapstick:/jokes section.
  svntest.actions.run_and_verify_svnauthz("Anonymous access on path",
                                          ["r\n"], None, 0, False, "accessof",
                                          authz_url, "--path", "/jokes")

  # Anonymous access on /jokes on slapstick repo should be no
  svntest.actions.run_and_verify_svnauthz("Anonymous access on path with repo",
                                          ["no\n"], None, 0, False, "accessof",
                                          authz_url, "--path", "/jokes",
                                          "--repository", "slapstick")

  # User access with no path, and no repository should be rw
  # since it returns the h ighest level of access anywhere.
  # So /bios being rw for everyone means this will be rw.
  svntest.actions.run_and_verify_svnauthz("User access", ["rw\n"], None,
                                          0, False, "accessof", authz_url,
                                          "--username", "groucho")

  # User groucho specified on /jokes with no repo, will not match any of the
  # repo specific sections, so is r since everyone has read access.
  svntest.actions.run_and_verify_svnauthz("User access on path", ["r\n"], None,
                                          0, False, "accessof", authz_url,
                                          "--path", "/jokes", "--username",
                                          "groucho")

  # User groucho specified on /jokes with the repo comedy will be rw
  svntest.actions.run_and_verify_svnauthz("User access on path with repo",
                                          ["rw\n"], None, 0, False, "accessof",
                                          authz_url, "--path", "/jokes",
                                          "--username", "groucho",
                                          "--repository", "comedy")

def svnauthz_accessof_groups_file_test(sbox):
  "test 'svnauthz accessof --groups-file' on files"

  # build an authz file
  (authz_fd, authz_path) = tempfile.mkstemp()
  authz_content = "[/]\n@musicians = rw\n@comedians = \n" + \
      "[comedy:/jokes]\n@musicians = \n@comedians = r\n"
  svntest.main.file_write(authz_path, authz_content)

  # build a groups file
  (groups_fd, groups_path) = tempfile.mkstemp()
  groups_content = "[groups]\nmusicians=stafford\ncomedians=groucho\n"
  svntest.main.file_write(groups_path, groups_content)

  # Anonymous access with no path, and no repository should be no
  # since it returns the highest level of access granted anywhere.
  svntest.actions.run_and_verify_svnauthz("Anonymous access", ["no\n"], None,
                                          0, False, "accessof", authz_path,
                                          "--groups-file", groups_path)

  # User stafford (@musicians) access with no path, and no repository should
  # be no since it returns the highest level of access granted anywhere.
  svntest.actions.run_and_verify_svnauthz("Group 1 access",
                                          ["rw\n"], None,
                                          0, False, "accessof", authz_path,
                                          "--groups-file", groups_path,
                                          "--username", "stafford")

  # User groucho (@comedians) access with no path, and no repository should
  # be no since it returns the highest level of access granted anywhere.
  svntest.actions.run_and_verify_svnauthz("Group 2 access",
                                          ["no\n"], None,
                                          0, False, "accessof", authz_path,
                                          "--groups-file", groups_path,
                                          "--username", "groucho")

  # Anonymous access specified on /jokes with the repo comedy will be no.
  svntest.actions.run_and_verify_svnauthz("Anonymous access on path with repo",
                                          ["no\n"], None, 0, False,
                                          "accessof", authz_path,
                                          "--groups-file", groups_path,
                                          "--path", "jokes",
                                          "--repository", "comedy")

  # User stafford (@musicians) specified on /jokes with the repo comedy
  # will be no.
  svntest.actions.run_and_verify_svnauthz("Group 1 access on path with repo",
                                          ["no\n"], None,
                                          0, False, "accessof", authz_path,
                                          "--groups-file", groups_path,
                                          "--path", "jokes",
                                          "--repository", "comedy",
                                          "--username", "stafford")

  # User groucho (@comedians) specified on /jokes with the repo
  # comedy will be r.
  svntest.actions.run_and_verify_svnauthz("Group 2 access on path with repo",
                                          ["r\n"], None,
                                          0, False, "accessof", authz_path,
                                          "--groups-file", groups_path,
                                          "--path", "jokes",
                                          "--repository", "comedy",
                                          "--username", "groucho")

  os.close(authz_fd)
  os.remove(authz_path)
  os.close(groups_fd)
  os.remove(groups_path)

@SkipUnless(svntest.main.is_ra_type_file)
def svnauthz_accessof_groups_repo_test(sbox):
  "test 'svnauthz accessof --groups-file' on urls"

  sbox.build()
  wc_dir = sbox.wc_dir
  repo_url = sbox.repo_url

  authz_content = "[/]\n@musicians = rw\n@comedians = \n" + \
      "[comedy:/jokes]\n@musicians = \n@comedians = r\n"

  groups_content = "[groups]\nmusicians=stafford\ncomedians=groucho\n"

  # build authz and groups files and commit them to the repo
  authz_path = os.path.join(wc_dir, 'A', 'authz')
  groups_path = os.path.join(wc_dir, 'A', 'groups')
  svntest.main.file_write(authz_path, authz_content)
  svntest.main.file_write(groups_path, groups_content)
  svntest.main.run_svn(None, 'add', authz_path, groups_path)
  expected_output = wc.State(wc_dir, {
    'A/authz'            : Item(verb='Adding'),
    'A/groups'           : Item(verb='Adding'),
  })
  expected_status = svntest.actions.get_virginal_state(wc_dir, 1)
  expected_status.add({
    'A/authz'            :  Item(status='  ', wc_rev=2),
    'A/groups'           :  Item(status='  ', wc_rev=2),
  })

  if svntest.actions.run_and_verify_commit(wc_dir, expected_output,
                                           expected_status, None, wc_dir):
    raise svntest.Failure

  # Anonymous access with no path, and no repository should be no
  # since it returns the highest level of access granted anywhere.
  authz_url = repo_url + "/A/authz"
  groups_url = repo_url + "/A/groups"
  svntest.actions.run_and_verify_svnauthz("Anonymous access", ["no\n"], None,
                                          0, False, "accessof", authz_url,
                                          "--groups-file", groups_url)

  # User stafford (@musicians) access with no path, and no repository should
  # be no since it returns the highest level of access granted anywhere.
  svntest.actions.run_and_verify_svnauthz("Group 1 access",
                                          ["rw\n"], None,
                                          0, False, "accessof", authz_url,
                                          "--groups-file", groups_url,
                                          "--username", "stafford")

  # User groucho (@comedians) access with no path, and no repository should
  # be no since it returns the highest level of access granted anywhere.
  svntest.actions.run_and_verify_svnauthz("Group 2 access",
                                          ["no\n"], None,
                                          0, False, "accessof", authz_url,
                                          "--groups-file", groups_url,
                                          "--username", "groucho")

  # Anonymous access specified on /jokes with the repo comedy will be no.
  svntest.actions.run_and_verify_svnauthz("Anonymous access on path with repo",
                                          ["no\n"], None, 0, False,
                                          "accessof", authz_url,
                                          "--groups-file", groups_url,
                                          "--path", "jokes",
                                          "--repository", "comedy")

  # User stafford (@musicians) specified on /jokes with the repo comedy
  # will be no.
  svntest.actions.run_and_verify_svnauthz("Group 1 access on path with repo",
                                          ["no\n"], None,
                                          0, False, "accessof", authz_url,
                                          "--groups-file", groups_url,
                                          "--path", "jokes",
                                          "--repository", "comedy",
                                          "--username", "stafford")

  # User groucho (@comedians) specified on /jokes with the repo
  # comedy will be r.
  svntest.actions.run_and_verify_svnauthz("Group 2 access on path with repo",
                                          ["r\n"], None,
                                          0, False, "accessof", authz_url,
                                          "--groups-file", groups_url,
                                          "--path", "jokes",
                                          "--repository", "comedy",
                                          "--username", "groucho")

def svnauthz_accessof_is_file_test(sbox):
  "test 'svnauthz accessof --is' on files"

  # build an authz file
  (authz_fd, authz_path) = tempfile.mkstemp()
  authz_content = "[/]\ngroucho = \ngallagher = rw\n* = r\n" + \
      "[/bios]\n* = rw\n" + \
      "[comedy:/jokes]\ngroucho = rw\n" + \
      "[slapstick:/jokes]\n* =\n"
  svntest.main.file_write(authz_path, authz_content)

  # Test an invalid --is option, should get an error message and exit code
  # of 2.
  expected_output = svntest.verify.RegexOutput(
      ".*'x' is not a valid argument for --is", match_all=False
  )
  svntest.actions.run_and_verify_svnauthz("--is x fails", None,
                                          expected_output, 2, False,
                                          "accessof", authz_path, "--is", "x")

  # Anonymous access with no path, and no repository should be rw
  # since it returns the highest level of access granted anywhere.
  # So /bios being rw for everyone means this will be rw.
  # Test --is rw returns 0.
  svntest.actions.run_and_verify_svnauthz("Anonymous access --is rw", None,
                                          None, 0, False, "accessof",
                                          authz_path, "--is", "rw")
  # Test --is r returns 3.
  svntest.actions.run_and_verify_svnauthz("Anonymous access --is r", None,
                                          None, 3, False, "accessof",
                                          authz_path, "--is", "r")
  # Test --is no returns 3.
  svntest.actions.run_and_verify_svnauthz("Anonymous access --is no", None,
                                          None, 3, False, "accessof",
                                          authz_path, "--is", "no")

  # Anonymous access on /jokes should be r, no repo so won't match
  # the slapstick:/jokes section.
  # Test --is r returns 0.
  svntest.actions.run_and_verify_svnauthz("Anonymous access on path --is r",
                                          None, None, 0, False, "accessof",
                                          authz_path, "--path", "/jokes",
                                          "--is", "r")
  # Test --is rw returns 3.
  svntest.actions.run_and_verify_svnauthz("Anonymous access on path --is r",
                                          None, None, 3, False, "accessof",
                                          authz_path, "--path", "/jokes",
                                          "--is", "rw")
  # Test --is no returns 3.
  svntest.actions.run_and_verify_svnauthz("Anonymous access on path --is r",
                                          None, None, 3, False, "accessof",
                                          authz_path, "--path", "/jokes",
                                          "--is", "no")

  # Anonymous access on /jokes on slapstick repo should be no
  # Test --is no returns 0.
  svntest.actions.run_and_verify_svnauthz("Anon access on path w/ repo --is no",
                                          None, None, 0, False, "accessof",
                                          authz_path, "--path", "/jokes",
                                          "--repository", "slapstick",
                                          "--is", "no")
  # Test --is rw returns 3.
  svntest.actions.run_and_verify_svnauthz("Anon access on path w/ repo --is no",
                                          None, None, 3, False, "accessof",
                                          authz_path, "--path", "/jokes",
                                          "--repository", "slapstick",
                                          "--is", "rw")
  # Test --is r returns 3.
  svntest.actions.run_and_verify_svnauthz("Anon access on path w/ repo --is no",
                                          None, None, 3, False, "accessof",
                                          authz_path, "--path", "/jokes",
                                          "--repository", "slapstick",
                                          "--is", "r")

  # User access with no path, and no repository should be rw
  # since it returns the h ighest level of access anywhere.
  # So /bios being rw for everyone means this will be rw.
  # Test --is rw returns 0.
  svntest.actions.run_and_verify_svnauthz("User access --is rw", None, None,
                                          0, False, "accessof", authz_path,
                                          "--username", "groucho", "--is",
                                          "rw")
  # Test --is r returns 3.
  svntest.actions.run_and_verify_svnauthz("User access --is r", None, None,
                                          3, False, "accessof", authz_path,
                                          "--username", "groucho", "--is",
                                          "r")
  # Test --is no returns 3.
  svntest.actions.run_and_verify_svnauthz("User access --is no", None, None,
                                          3, False, "accessof", authz_path,
                                          "--username", "groucho", "--is",
                                          "no")

  # User groucho specified on /jokes with no repo, will not match any of the
  # repo specific sections, so is r since everyone has read access.
  # Test --is r returns 0.
  svntest.actions.run_and_verify_svnauthz("User access on path --is r", None,
                                          None, 0, False, "accessof",
                                          authz_path, "--path", "/jokes",
                                          "--username", "groucho", "--is", "r")
  # Test --is rw returns 3.
  svntest.actions.run_and_verify_svnauthz("User access on path --is rw", None,
                                          None, 3, False, "accessof",
                                          authz_path, "--path", "/jokes",
                                          "--username", "groucho",
                                          "--is", "rw")
  # Test --is no returns 3.
  svntest.actions.run_and_verify_svnauthz("User access on path --is no", None,
                                          None, 3, False, "accessof",
                                          authz_path, "--path", "/jokes",
                                          "--username", "groucho",
                                          "--is", "no")

  # User groucho specified on /jokes with the repo comedy will be rw
  # Test --is rw returns 0.
  svntest.actions.run_and_verify_svnauthz("User access on path w/ repo --is rw",
                                          None, None, 0, False, "accessof",
                                          authz_path, "--path", "/jokes",
                                          "--username", "groucho",
                                          "--repository", "comedy", "--is",
                                          "rw")
  # Test --is r returns 3.
  svntest.actions.run_and_verify_svnauthz("User access on path w/ repo --is r",
                                          None, None, 3, False, "accessof",
                                          authz_path, "--path", "/jokes",
                                          "--username", "groucho",
                                          "--repository", "comedy", "--is",
                                          "r")
  # Test --is no returns 3.
  svntest.actions.run_and_verify_svnauthz("User access on path w/ repo --is no",
                                          None, None, 3, False, "accessof",
                                          authz_path, "--path", "/jokes",
                                          "--username", "groucho",
                                          "--repository", "comedy", "--is",
                                          "no")

  # Add an invalid line to the authz file
  svntest.main.file_append(authz_path, "x\n")
  # Check that --is returns 1 when the syntax is invalid with a file..
  expected_out = svntest.verify.RegexOutput(
      ".*Error while parsing config file:",
      match_all=False
  )
  svntest.actions.run_and_verify_svnauthz("--is with invalid authz file",
                                          None, expected_out, 1, False,
                                          "accessof", authz_path, "--path",
                                          "/jokes", "--username", "groucho",
                                          "--repository", "comedy", "--is",
                                          "rw")

  os.close(authz_fd)
  os.remove(authz_path)

@SkipUnless(svntest.main.is_ra_type_file)
def svnauthz_accessof_is_repo_test(sbox):
  "test 'svnauthz accessof --is' on files and urls"

  sbox.build()
  wc_dir = sbox.wc_dir
  repo_url = sbox.repo_url

  authz_content = "[/]\ngroucho = \ngallagher = rw\n* = r\n" + \
      "[/bios]\n* = rw\n" + \
      "[comedy:/jokes]\ngroucho = rw\n" + \
      "[slapstick:/jokes]\n* =\n"

  # build an authz file and commit it to the repo
  authz_path = os.path.join(wc_dir, 'A', 'authz')
  svntest.main.file_write(authz_path, authz_content)
  svntest.main.run_svn(None, 'add', authz_path)
  expected_output = wc.State(wc_dir, {'A/authz' : Item(verb='Adding')})
  expected_status = svntest.actions.get_virginal_state(wc_dir, 1)
  expected_status.add({
    'A/authz'            :  Item(status='  ', wc_rev=2),
  })
  if svntest.actions.run_and_verify_commit(wc_dir, expected_output,
                                           expected_status, None, wc_dir):
    raise svntest.Failure

  # Test an invalid --is option, should get an error message and exit code
  # of 2.
  authz_url = repo_url + "/A/authz"
  expected_output = svntest.verify.RegexOutput(
      ".*'x' is not a valid argument for --is", match_all=False
  )
  svntest.actions.run_and_verify_svnauthz("--is x fails", None,
                                          expected_output, 2, False,
                                          "accessof", authz_url, "--is", "x")

  # Anonymous access with no path, and no repository should be rw
  # since it returns the highest level of access granted anywhere.
  # So /bios being rw for everyone means this will be rw.
  # Test --is rw returns 0.
  svntest.actions.run_and_verify_svnauthz("Anonymous access --is rw", None,
                                          None, 0, False, "accessof",
                                          authz_url, "--is", "rw")
  # Test --is r returns 3.
  svntest.actions.run_and_verify_svnauthz("Anonymous access --is r", None,
                                          None, 3, False, "accessof",
                                          authz_url, "--is", "r")
  # Test --is no returns 3.
  svntest.actions.run_and_verify_svnauthz("Anonymous access --is no", None,
                                          None, 3, False, "accessof",
                                          authz_url, "--is", "no")

  # Anonymous access on /jokes should be r, no repo so won't match
  # the slapstick:/jokes section.
  # Test --is r returns 0.
  svntest.actions.run_and_verify_svnauthz("Anonymous access on path --is r",
                                          None, None, 0, False, "accessof",
                                          authz_url, "--path", "/jokes",
                                          "--is", "r")
  # Test --is rw returns 3.
  svntest.actions.run_and_verify_svnauthz("Anonymous access on path --is r",
                                          None, None, 3, False, "accessof",
                                          authz_url, "--path", "/jokes",
                                          "--is", "rw")
  # Test --is no returns 3.
  svntest.actions.run_and_verify_svnauthz("Anonymous access on path --is r",
                                          None, None, 3, False, "accessof",
                                          authz_url, "--path", "/jokes",
                                          "--is", "no")

  # Anonymous access on /jokes on slapstick repo should be no
  # Test --is no returns 0.
  svntest.actions.run_and_verify_svnauthz("Anon access on path w/ repo --is no",
                                          None, None, 0, False, "accessof",
                                          authz_url, "--path", "/jokes",
                                          "--repository", "slapstick",
                                          "--is", "no")
  # Test --is rw returns 3.
  svntest.actions.run_and_verify_svnauthz("Anon access on path w/ repo --is no",
                                          None, None, 3, False, "accessof",
                                          authz_url, "--path", "/jokes",
                                          "--repository", "slapstick",
                                          "--is", "rw")
  # Test --is r returns 3.
  svntest.actions.run_and_verify_svnauthz("Anon access on path w/ repo --is no",
                                          None, None, 3, False, "accessof",
                                          authz_url, "--path", "/jokes",
                                          "--repository", "slapstick",
                                          "--is", "r")

  # User access with no path, and no repository should be rw
  # since it returns the h ighest level of access anywhere.
  # So /bios being rw for everyone means this will be rw.
  # Test --is rw returns 0.
  svntest.actions.run_and_verify_svnauthz("User access --is rw", None, None,
                                          0, False, "accessof", authz_url,
                                          "--username", "groucho", "--is",
                                          "rw")
  # Test --is r returns 3.
  svntest.actions.run_and_verify_svnauthz("User access --is r", None, None,
                                          3, False, "accessof", authz_url,
                                          "--username", "groucho", "--is",
                                          "r")
  # Test --is no returns 3.
  svntest.actions.run_and_verify_svnauthz("User access --is no", None, None,
                                          3, False, "accessof", authz_url,
                                          "--username", "groucho", "--is",
                                          "no")

  # User groucho specified on /jokes with no repo, will not match any of the
  # repo specific sections, so is r since everyone has read access.
  # Test --is r returns 0.
  svntest.actions.run_and_verify_svnauthz("User access on path --is r", None,
                                          None, 0, False, "accessof",
                                          authz_url, "--path", "/jokes",
                                          "--username", "groucho", "--is", "r")
  # Test --is rw returns 3.
  svntest.actions.run_and_verify_svnauthz("User access on path --is rw", None,
                                          None, 3, False, "accessof",
                                          authz_url, "--path", "/jokes",
                                          "--username", "groucho",
                                          "--is", "rw")
  # Test --is no returns 3.
  svntest.actions.run_and_verify_svnauthz("User access on path --is no", None,
                                          None, 3, False, "accessof",
                                          authz_url, "--path", "/jokes",
                                          "--username", "groucho",
                                          "--is", "no")

  # User groucho specified on /jokes with the repo comedy will be rw
  # Test --is rw returns 0.
  svntest.actions.run_and_verify_svnauthz("User access on path w/ repo --is rw",
                                          None, None, 0, False, "accessof",
                                          authz_url, "--path", "/jokes",
                                          "--username", "groucho",
                                          "--repository", "comedy", "--is",
                                          "rw")
  # Test --is r returns 3.
  svntest.actions.run_and_verify_svnauthz("User access on path w/ repo --is r",
                                          None, None, 3, False, "accessof",
                                          authz_url, "--path", "/jokes",
                                          "--username", "groucho",
                                          "--repository", "comedy", "--is",
                                          "r")
  # Test --is no returns 3.
  svntest.actions.run_and_verify_svnauthz("User access on path w/ repo --is no",
                                          None, None, 3, False, "accessof",
                                          authz_url, "--path", "/jokes",
                                          "--username", "groucho",
                                          "--repository", "comedy", "--is",
                                          "no")

  # Add an invalid line to the authz file
  svntest.main.file_append(authz_path, "x\n")
  expected_output = wc.State(wc_dir, {'A/authz' : Item(verb='Sending')})
  expected_status.tweak('A/authz', wc_rev=3)
  if svntest.actions.run_and_verify_commit(wc_dir, expected_output,
                                           expected_status, None, wc_dir):
    raise svntest.Failure

  # Check that --is returns 1 when the syntax is invalid with a url.
  expected_out = svntest.verify.RegexOutput(
      ".*Error while parsing config file:",
      match_all=False
  )
  svntest.actions.run_and_verify_svnauthz("--is with invalid authz url",
                                          None, expected_out, 1, False,
                                          "accessof", authz_url, "--path",
                                          "/jokes", "--username", "groucho",
                                          "--repository", "comedy", "--is",
                                          "rw")

def svnauthz_accessof_txn_test(sbox):
  "test 'svnauthz accessof --transaction'"

  sbox.build()
  wc_dir = sbox.wc_dir
  repo_dir = sbox.repo_dir

  logfilepath = os.path.join(repo_dir, 'hooks.log')
  pre_commit_hook = svntest.main.get_pre_commit_hook_path(repo_dir)
  hook_instance = hook_template % (repr(svntest.main.svnauthz_binary),
                                   repr([('accessof',
                                          '--is rw A/authz')]))
  svntest.main.create_python_hook_script(pre_commit_hook, hook_instance)

  # Create an authz file
  authz_content = "[/]\n* = rw\n"
  authz_path = os.path.join(wc_dir, 'A/authz')
  svntest.main.file_write(authz_path, authz_content)
  svntest.main.run_svn(None, 'add', authz_path)

  # Only really testing the exit value code paths.

  # commit a valid authz file, and run --is rw which is true.
  # Should get an exit of 0.
  expected_output = wc.State(wc_dir, {'A/authz' : Item(verb='Adding')})
  expected_status = svntest.actions.get_virginal_state(wc_dir, 1)
  expected_status.add({
    'A/authz'            :  Item(status='  ', wc_rev=2),
  })
  if svntest.actions.run_and_verify_commit(wc_dir, expected_output,
                                           expected_status, None, wc_dir):
    raise svntest.Failure
  expected_data = ['Exit 0\n']
  verify_logfile(logfilepath, expected_data)

  # commit a valid authz file, and run --is r which is false
  # Should get an exit of 3.
  hook_instance = hook_template % (repr(svntest.main.svnauthz_binary),
                                   repr([('accessof',
                                          '--is r A/authz')]))
  svntest.main.create_python_hook_script(pre_commit_hook, hook_instance)
  expected_output = wc.State(wc_dir, {'A/authz' : Item(verb='Sending')})
  expected_status.tweak('A/authz', status='  ', wc_rev=3)
  svntest.main.file_append(authz_path, "groucho = r\n")
  if svntest.actions.run_and_verify_commit(wc_dir, expected_output,
                                           expected_status, None, wc_dir):
    raise svntest.Failure
  expected_data = svntest.verify.ExpectedOutput('Exit 3\n', match_all=False)
  verify_logfile(logfilepath, expected_data)

  # break the authz file with a non-existant group and check for an exit 1.
  expected_status.tweak('A/authz', status='  ', wc_rev=4)
  svntest.main.file_append(authz_path, "@friends = rw\n")
  if svntest.actions.run_and_verify_commit(wc_dir, expected_output,
                                           expected_status, None, wc_dir):
    raise svntest.Failure
  expected_data = svntest.verify.ExpectedOutput('Exit 1\n', match_all=False)
  verify_logfile(logfilepath, expected_data)

  # break the authz file with a non-existant gropu and check for an exit 2.
  expected_output = wc.State(wc_dir, {'A/authz' : Item(verb='Deleting')})
  expected_status.remove('A/authz')
  svntest.main.run_svn(None, 'rm', authz_path)
  if svntest.actions.run_and_verify_commit(wc_dir, expected_output,
                                           expected_status, None, wc_dir):
    raise svntest.Failure
  expected_data = svntest.verify.ExpectedOutput('Exit 2\n', match_all=False)
  verify_logfile(logfilepath, expected_data)

def svnauthz_compat_mode_file_test(sbox):
  "test 'svnauthz-validate' compatability mode file"

  # Create an authz file
  (authz_fd, authz_path) = tempfile.mkstemp()
  authz_content = "[/]\n* = rw\n"
  svntest.main.file_write(authz_path, authz_content)

  # Check a valid file.
  svntest.actions.run_and_verify_svnauthz("svnauthz-validate on file",
                                          None, None, 0, True,
                                          authz_path)

  # Check an invalid file.
  svntest.main.file_append(authz_path, "x\n")
  svntest.actions.run_and_verify_svnauthz("svnauthz-validate on invalid file",
                                          None, None, 1, True,
                                          authz_path)

  # Remove the file.
  os.close(authz_fd)
  os.remove(authz_path)

  # Check a non-existant file.
  svntest.actions.run_and_verify_svnauthz(
      "svnauthz-validate on non-existant file", None, None, 2, True,
      authz_path
  )

@SkipUnless(svntest.main.is_ra_type_file)
def svnauthz_compat_mode_repo_test(sbox):
  "test 'svnauthz-validate' compatability mode url"

  sbox.build()
  wc_dir = sbox.wc_dir
  repo_url = sbox.repo_url

  # Create an authz file
  authz_content = "[/]\n* = rw\n"
  authz_path = os.path.join(wc_dir, 'A/authz')
  svntest.main.file_write(authz_path, authz_content)
  authz_url = repo_url + '/A/authz'

  # Commit the file and check a URL
  svntest.main.run_svn(None, 'add', authz_path)
  expected_output = wc.State(wc_dir, {'A/authz' : Item(verb='Adding')})
  expected_status = svntest.actions.get_virginal_state(wc_dir, 1)
  expected_status.add({
    'A/authz'            :  Item(status='  ', wc_rev=2),
  })
  if svntest.actions.run_and_verify_commit(wc_dir, expected_output,
                                           expected_status, None, wc_dir):
    raise svntest.Failure
  svntest.actions.run_and_verify_svnauthz("svnauthz-validate on url",
                                          None, None, 0, True,
                                          authz_url)

  # Check an invalid url.
  svntest.main.file_append(authz_path, "x\n")
  expected_output = wc.State(wc_dir, {'A/authz' : Item(verb='Sending')})
  expected_status.tweak('A/authz', status='  ', wc_rev=3)
  if svntest.actions.run_and_verify_commit(wc_dir, expected_output,
                                           expected_status, None, wc_dir):
    raise svntest.Failure
  svntest.actions.run_and_verify_svnauthz("svnauthz-validate on invalid file",
                                          None, None, 1, True,
                                          authz_path)

  # Check a non-existant url.
  # Exit code really should be 2 since this is an operational error.
  svntest.actions.run_and_verify_svnauthz(
      "svnauthz-validate on non-existant file", None, None, 2, True,
      repo_url + "/zilch"
  )

########################################################################
# Run the tests

# list all tests here, starting with None:
test_list = [ None,
              svnauthz_validate_file_test,
              svnauthz_validate_repo_test,
              svnauthz_validate_txn_test,
              svnauthz_accessof_file_test,
              svnauthz_accessof_repo_test,
              svnauthz_accessof_groups_file_test,
              svnauthz_accessof_groups_repo_test,
              svnauthz_accessof_is_file_test,
              svnauthz_accessof_is_repo_test,
              svnauthz_accessof_txn_test,
              svnauthz_compat_mode_file_test,
              svnauthz_compat_mode_repo_test,
             ]

if __name__ == '__main__':
  svntest.main.run_tests(test_list)
  # NOTREACHED

### End of file.

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using PholioVisualisation.DataConstruction;
using PholioVisualisation.DataSorting;
using PholioVisualisation.PholioObjects;

namespace PholioVisualisation.DataConstructionTest
{
    [TestClass]
    public class ParentChildAreaRelationshipBuilderTest
    {
        private string parentAreaCode = "Parent";
        private int childAreaId = AreaTypeIds.Pct;

        private List<IArea> filteredAreas;
        private List<IArea> unfilteredAreas;

        [TestInitialize]
        public void RunBeforeEachTest()
        {
            filteredAreas = new List<IArea> {
                new Area { Code = "z" },
                new Area { Code = "y" }
            };
            unfilteredAreas = new List<IArea>(filteredAreas);
            unfilteredAreas.Add(new Area { Code = "a" });
        }

        [TestMethod]
        public void TestBuild()
        {
            var areaListBuilder = new Mock<AreaListProvider>(MockBehavior.Strict);
            areaListBuilder.Setup(x => x.CreateChildAreaList(parentAreaCode, childAreaId));
            areaListBuilder.Setup(x => x.SortByOrderOrName());
            areaListBuilder.SetupGet(x => x.Areas)
                .Returns(unfilteredAreas);

            var ignoredAreasFilter = new Mock<IgnoredAreasFilter>(MockBehavior.Strict);

            // Get areas
            ParentAreaWithChildAreas relationship =
                new ParentChildAreaRelationshipBuilder(ignoredAreasFilter.Object, areaListBuilder.Object)
                    .GetParentAreaWithChildAreas(new Area { Code = parentAreaCode }, childAreaId, true);

            // Verify
            Assert.AreEqual(3, relationship.Children.Count());
            Assert.AreEqual(parentAreaCode, relationship.Parent.Code);
            areaListBuilder.VerifyAll();
        }

        [TestMethod]
        public void TestBuild_IgnoredAreasMayBeRemoved()
        {
            var areaListBuilder = new Mock<AreaListProvider>();
            areaListBuilder.SetupGet(x => x.Areas)
                .Returns(filteredAreas);

            var ignoredAreasFilter = new Mock<IgnoredAreasFilter>(MockBehavior.Strict);
            ignoredAreasFilter.Setup(x => x.RemoveAreasIgnoredEverywhere(unfilteredAreas));

            // Get areas
            ParentAreaWithChildAreas relationship =
                new ParentChildAreaRelationshipBuilder(ignoredAreasFilter.Object, areaListBuilder.Object)
                    .GetParentAreaWithChildAreas(new Area { Code = parentAreaCode }, childAreaId, false);

            // Verify
            Assert.AreEqual(2, relationship.Children.Count());
            areaListBuilder.VerifyAll();
        }
    }
}


text:
using System.ComponentModel;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;
using XBindLecture.Storages;
using XBindLecture.ViewModels;

namespace XBindLecture.Views
{
	public sealed partial class MainPage : Page, INotifyPropertyChanged
	{
		public NavigationHelper NavigationHelper { get; }
		public PersonViewModel[] Persons { get; }

		public object SelectedPerson
		{
			get { return this._SelectedPerson; }
			set
			{
				if (object.ReferenceEquals(this._SelectedPerson, value)) return;

				this._SelectedPerson = (PersonViewModel)value;
				this.RaisePropertyChanged(nameof(this.SelectedPerson));
			}
		}
		private PersonViewModel _SelectedPerson = null;

		public MainPage()
		{
			this.NavigationHelper = new NavigationHelper(this);
			this.Persons = PersonStorage.GetPersons().Select(p => new PersonViewModel(p)).ToArray();

			this.InitializeComponent();
		}

		public event PropertyChangedEventHandler PropertyChanged;
		public void RaisePropertyChanged(string propertyName)
			=> this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			this.NavigationHelper.OnNavigatedTo(e);

			var param = (string)e.Parameter;
			if (!string.IsNullOrEmpty(param))
			{
				this.SelectedPerson = this.Persons.Where(p => p.Name == param).Single();
			}

			this.UpdateVisualState(this.AdaptiveStates.CurrentState);
			this.DisableContentTransitions();
		}

		private void OnItemClick(object sender, ItemClickEventArgs e)
		{
			this.SelectedPerson = e.ClickedItem;
			if (this.AdaptiveStates.CurrentState == this.NarrowState)
			{
				this.Frame.Navigate(typeof(DetailPage), this._SelectedPerson.Name.ToString(), new SuppressNavigationTransitionInfo());
			}
			else
			{
				this.EnableContentTransitions();
			}
		}

		#region Visual state support

		private void OnAdaptiveStatesCurrentStateChanged(object sender, Windows.UI.Xaml.VisualStateChangedEventArgs e)
		{
			this.UpdateVisualState(e.NewState, e.OldState);
		}

		private void UpdateVisualState(VisualState newState, VisualState oldState = null)
		{
			var isNarrow = newState == this.NarrowState;
			if (isNarrow && oldState != null && oldState != this.NarrowState && this._SelectedPerson != null)
			{
				this.Frame.Navigate(typeof(DetailPage), this._SelectedPerson.Name.ToString(), new SuppressNavigationTransitionInfo());
			}

			EntranceNavigationTransitionInfo.SetIsTargetElement(this.PersonsListView, isNarrow);
			if (this.DetailView != null) EntranceNavigationTransitionInfo.SetIsTargetElement(this.DetailView, !isNarrow);
		}

		private void EnableContentTransitions()
		{
			this.DetailView.ContentTransitions.Clear();
			this.DetailView.ContentTransitions.Add(new EntranceThemeTransition());
		}

		private void DisableContentTransitions()
		{
			if (this.DetailView != null) this.DetailView.ContentTransitions.Clear();
		}

		#endregion
	}
}


text:
form.tmp-admin-user-form tr th {
  width: 140px;
  padding-bottom: 5px; }
form.tmp-admin-user-form tr td {
  padding-bottom: 5px; }
form.tmp-admin-user-form .tmp-admin-user-input {
  display: inline-block;
  vertical-align: middle;
  margin-right: 5px; }
form.tmp-admin-user-form .tmp-admin-user-description {
  display: inline-block;
  vertical-align: middle; }
form.tmp-admin-user-form .tmp-admin-user-label {
  display: inline-block;
  vertical-align: middle;
  font-size: 13px;
  font-style: italic; }

.tmp-admin-user-existing-table .widefat td.check-column,
.tmp-admin-user-existing-table .widefat th.check-column {
  width: 12px; }
.tmp-admin-user-existing-table td.column-id,
.tmp-admin-user-existing-table th.column-id {
  width: 24px; }
  .tmp-admin-user-existing-table td.column-id .toggle-row,
  .tmp-admin-user-existing-table th.column-id .toggle-row {
    display: none;
    height: 0;
    width: 0; }
.tmp-admin-user-existing-table .tmp-admin-user-view-label {
  margin-right: 10px; }
.tmp-admin-user-existing-table .column-actions {
  text-align: left; }
.tmp-admin-user-existing-table .tmp-admin-user-link {
  display: inline-block;
  vertical-align: middle;
  width: 32px;
  text-align: center;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none; }
  .tmp-admin-user-existing-table .tmp-admin-user-link.tmp-admin-user-action-promote {
    color: #ffc719; }
  .tmp-admin-user-existing-table .tmp-admin-user-link.tmp-admin-user-action-restrict {
    color: #565656; }
  .tmp-admin-user-existing-table .tmp-admin-user-link.tmp-admin-user-action-delete {
    color: #cc0000; }
  .tmp-admin-user-existing-table .tmp-admin-user-link.tmp-admin-user-view-profile {
    color: #6d1530; }
  .tmp-admin-user-existing-table .tmp-admin-user-link.tmp-admin-user-view-email {
    color: #153e6d; }
  .tmp-admin-user-existing-table .tmp-admin-user-link:visited, .tmp-admin-user-existing-table .tmp-admin-user-link:hover, .tmp-admin-user-existing-table .tmp-admin-user-link:active {
    border: 0 none;
    outline: 0 none; }
  .tmp-admin-user-existing-table .tmp-admin-user-link.tmp-admin-user-disabled {
    opacity: 0.45; }

/*# sourceMappingURL=temporary-admin-user.css.map */


text:
package cn.dmesoft.haibao.modules.haibao.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.dmesoft.haibao.common.persistence.Page;
import cn.dmesoft.haibao.common.service.CrudService;
import cn.dmesoft.haibao.modules.haibao.entity.Scenedata;
import cn.dmesoft.haibao.modules.haibao.dao.ScenedataDao;

/**
 * 单表生成Service
 * @author Dmesoft
 * @version 2016-08-18
 */
@Service
@Transactional(readOnly = true)
public class ScenedataService extends CrudService<ScenedataDao, Scenedata> {

	public Scenedata get(String id) {
		return super.get(id);
	}

	public List<Scenedata> findList(Scenedata scenedata) {
		return super.findList(scenedata);
	}

	public Page<Scenedata> findPage(Page<Scenedata> page, Scenedata scenedata) {
		return super.findPage(page, scenedata);
	}

	@Transactional(readOnly = false)
	public void save(Scenedata scenedata) {
		super.save(scenedata);
	}

	@Transactional(readOnly = false)
	public void delete(Scenedata scenedata) {
		super.delete(scenedata);
	}

}


text:
namespace v8 {
namespace internal {
namespace torque {

void DeclarationVisitor::Visit(Expression* expr) {
  CurrentSourcePosition::Scope scope(expr->pos);
  switch (expr->kind) {
#define ENUM_ITEM(name)        \
  case AstNode::Kind::k##name: \
    return Visit(name::cast(expr));
    AST_EXPRESSION_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
    default:
      UNIMPLEMENTED();
  }
}

void DeclarationVisitor::Visit(Statement* stmt) {
  CurrentSourcePosition::Scope scope(stmt->pos);
  switch (stmt->kind) {
#define ENUM_ITEM(name)        \
  case AstNode::Kind::k##name: \
    return Visit(name::cast(stmt));
    AST_STATEMENT_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
    default:
      UNIMPLEMENTED();
  }
}

void DeclarationVisitor::Visit(Declaration* decl) {
  CurrentSourcePosition::Scope scope(decl->pos);
  switch (decl->kind) {
#define ENUM_ITEM(name)        \
  case AstNode::Kind::k##name: \
    return Visit(name::cast(decl));
    AST_DECLARATION_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
    default:
      UNIMPLEMENTED();
  }
}

void DeclarationVisitor::Visit(CallableNode* decl, const Signature& signature,
                               Statement* body) {
  switch (decl->kind) {
#define ENUM_ITEM(name)        \
  case AstNode::Kind::k##name: \
    return Visit(name::cast(decl), signature, body);
    AST_CALLABLE_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
    default:
      UNIMPLEMENTED();
  }
}

Builtin* DeclarationVisitor::BuiltinDeclarationCommon(
    BuiltinDeclaration* decl, bool external, const Signature& signature) {
  const bool javascript = decl->javascript_linkage;
  const bool varargs = decl->signature->parameters.has_varargs;
  Builtin::Kind kind = !javascript ? Builtin::kStub
                                   : varargs ? Builtin::kVarArgsJavaScript
                                             : Builtin::kFixedArgsJavaScript;

  if (signature.types().size() == 0 ||
      !(signature.types()[0] ==
        declarations()->LookupGlobalType(CONTEXT_TYPE_STRING))) {
    std::stringstream stream;
    stream << "first parameter to builtin " << decl->name
           << " is not a context but should be";
    ReportError(stream.str());
  }

  if (varargs && !javascript) {
    std::stringstream stream;
    stream << "builtin " << decl->name
           << " with rest parameters must be a JavaScript builtin";
    ReportError(stream.str());
  }

  if (javascript) {
    if (signature.types().size() < 2 ||
        !(signature.types()[1] ==
          declarations()->LookupGlobalType(OBJECT_TYPE_STRING))) {
      std::stringstream stream;
      stream << "second parameter to javascript builtin " << decl->name
             << " is " << *signature.types()[1] << " but should be Object";
      ReportError(stream.str());
    }
  }

  if (const StructType* struct_type =
          StructType::DynamicCast(signature.return_type)) {
    std::stringstream stream;
    stream << "builtins (in this case" << decl->name
           << ") cannot return structs (in this case " << struct_type->name()
           << ")";
    ReportError(stream.str());
  }

  std::string generated_name = GetGeneratedCallableName(
      decl->name, declarations()->GetCurrentSpecializationTypeNamesVector());
  return declarations()->DeclareBuiltin(generated_name, kind, external,
                                        signature);
}

void DeclarationVisitor::Visit(ExternalRuntimeDeclaration* decl,
                               const Signature& signature, Statement* body) {
  if (global_context_.verbose()) {
    std::cout << "found declaration of external runtime " << decl->name
              << " with signature ";
  }

  if (signature.parameter_types.types.size() == 0 ||
      !(signature.parameter_types.types[0] ==
        declarations()->LookupGlobalType(CONTEXT_TYPE_STRING))) {
    std::stringstream stream;
    stream << "first parameter to runtime " << decl->name
           << " is not a context but should be";
    ReportError(stream.str());
  }

  if (signature.return_type->IsStructType()) {
    std::stringstream stream;
    stream << "runtime functions (in this case" << decl->name
           << ") cannot return structs (in this case "
           << static_cast<const StructType*>(signature.return_type)->name()
           << ")";
    ReportError(stream.str());
  }

  declarations()->DeclareRuntimeFunction(decl->name, signature);
}

void DeclarationVisitor::Visit(ExternalMacroDeclaration* decl,
                               const Signature& signature, Statement* body) {
  if (global_context_.verbose()) {
    std::cout << "found declaration of external macro " << decl->name
              << " with signature ";
  }

  std::string generated_name = GetGeneratedCallableName(
      decl->name, declarations()->GetCurrentSpecializationTypeNamesVector());
  declarations()->DeclareMacro(generated_name, signature, decl->op);
}

void DeclarationVisitor::Visit(TorqueBuiltinDeclaration* decl,
                               const Signature& signature, Statement* body) {
  Builtin* builtin = BuiltinDeclarationCommon(decl, false, signature);
  CurrentCallableActivator activator(global_context_, builtin, decl);
  DeclareSignature(signature);
  if (signature.parameter_types.var_args) {
    declarations()->DeclareExternConstant(
        decl->signature->parameters.arguments_variable,
        TypeOracle::GetArgumentsType(), "arguments");
  }
  torque_builtins_.push_back(builtin);
  Visit(body);
}

void DeclarationVisitor::Visit(TorqueMacroDeclaration* decl,
                               const Signature& signature, Statement* body) {
  std::string generated_name = GetGeneratedCallableName(
      decl->name, declarations()->GetCurrentSpecializationTypeNamesVector());
  Macro* macro =
      declarations()->DeclareMacro(generated_name, signature, decl->op);

  CurrentCallableActivator activator(global_context_, macro, decl);

  DeclareSignature(signature);

  if (body != nullptr) {
    Visit(body);
  }
}

void DeclarationVisitor::Visit(ConstDeclaration* decl) {
  declarations()->DeclareModuleConstant(decl->name,
                                        declarations()->GetType(decl->type));
  Visit(decl->expression);
}

void DeclarationVisitor::Visit(StandardDeclaration* decl) {
  Signature signature = MakeSignature(decl->callable->signature.get());
  Visit(decl->callable, signature, decl->body);
}

void DeclarationVisitor::Visit(GenericDeclaration* decl) {
  declarations()->DeclareGeneric(decl->callable->name, CurrentModule(), decl);
}

void DeclarationVisitor::Visit(SpecializationDeclaration* decl) {
  if ((decl->body != nullptr) == decl->external) {
    std::stringstream stream;
    stream << "specialization of " << decl->name
           << " must either be marked 'extern' or have a body";
    ReportError(stream.str());
  }

  GenericList* generic_list = declarations()->LookupGeneric(decl->name);
  // Find the matching generic specialization based on the concrete parameter
  // list.
  CallableNode* matching_callable = nullptr;
  SpecializationKey matching_key;
  Signature signature_with_types = MakeSignature(decl->signature.get());
  for (Generic* generic : generic_list->list()) {
    SpecializationKey key = {generic, GetTypeVector(decl->generic_parameters)};
    CallableNode* callable_candidate = generic->declaration()->callable;
    // Abuse the Specialization nodes' scope to temporarily declare the
    // specialization aliases for the generic types to compare signatures. This
    // scope is never used for anything else, so it's OK to pollute it.
    Declarations::CleanNodeScopeActivator specialization_activator(
        declarations(), decl);
    DeclareSpecializedTypes(key);
    Signature generic_signature_with_types =
        MakeSignature(generic->declaration()->callable->signature.get());
    if (signature_with_types.HasSameTypesAs(generic_signature_with_types)) {
      if (matching_callable != nullptr) {
        std::stringstream stream;
        stream << "specialization of " << callable_candidate->name
               << " is ambigous, it matches more than one generic declaration ("
               << *matching_key.first << " and " << *key.first << ")";
        ReportError(stream.str());
      }
      matching_callable = callable_candidate;
      matching_key = key;
    }
  }

  if (matching_callable == nullptr) {
    std::stringstream stream;
    stream << "specialization of " << decl->name
           << " doesn't match any generic declaration";
    ReportError(stream.str());
  }

  // Make sure the declarations of the parameter types for the specialization
  // are the ones from the matching generic.
  {
    Declarations::CleanNodeScopeActivator specialization_activator(
        declarations(), decl);
    DeclareSpecializedTypes(matching_key);
  }

  SpecializeGeneric({matching_key, matching_callable, decl->signature.get(),
                     decl->body, decl->pos});
}

void DeclarationVisitor::Visit(ReturnStatement* stmt) {
  if (stmt->value) {
    Visit(*stmt->value);
  }
}

Variable* DeclarationVisitor::DeclareVariable(const std::string& name,
                                              const Type* type, bool is_const) {
  Variable* result = declarations()->DeclareVariable(name, type, is_const);
  return result;
}

Parameter* DeclarationVisitor::DeclareParameter(const std::string& name,
                                                const Type* type) {
  return declarations()->DeclareParameter(
      name, GetParameterVariableFromName(name), type);
}

void DeclarationVisitor::Visit(VarDeclarationStatement* stmt) {
  std::string variable_name = stmt->name;
  if (!stmt->const_qualified) {
    if (!stmt->type) {
      ReportError(
          "variable declaration is missing type. Only 'const' bindings can "
          "infer the type.");
    }
    const Type* type = declarations()->GetType(*stmt->type);
    if (type->IsConstexpr()) {
      ReportError(
          "cannot declare variable with constexpr type. Use 'const' instead.");
    }
    DeclareVariable(variable_name, type, stmt->const_qualified);
    if (global_context_.verbose()) {
      std::cout << "declared variable " << variable_name << " with type "
                << *type << "\n";
    }
  }

  // const qualified variables are required to be initialized properly.
  if (stmt->const_qualified && !stmt->initializer) {
    std::stringstream stream;
    stream << "local constant \"" << variable_name << "\" is not initialized.";
    ReportError(stream.str());
  }

  if (stmt->initializer) {
    Visit(*stmt->initializer);
    if (global_context_.verbose()) {
      std::cout << "variable has initialization expression at "
                << CurrentPositionAsString() << "\n";
    }
  }
}

void DeclarationVisitor::Visit(ExternConstDeclaration* decl) {
  const Type* type = declarations()->GetType(decl->type);
  if (!type->IsConstexpr()) {
    std::stringstream stream;
    stream << "extern constants must have constexpr type, but found: \""
           << *type << "\"\n";
    ReportError(stream.str());
  }

  declarations()->DeclareExternConstant(decl->name, type, decl->literal);
}

void DeclarationVisitor::Visit(StructDeclaration* decl) {
  std::vector<NameAndType> fields;
  for (auto& field : decl->fields) {
    const Type* field_type = declarations()->GetType(field.type);
    fields.push_back({field.name, field_type});
  }
  declarations()->DeclareStruct(CurrentModule(), decl->name, fields);
}

void DeclarationVisitor::Visit(LogicalOrExpression* expr) {
  {
    Declarations::NodeScopeActivator scope(declarations(), expr->left);
    declarations()->DeclareLabel(kFalseLabelName);
    Visit(expr->left);
  }
  Visit(expr->right);
}

void DeclarationVisitor::Visit(LogicalAndExpression* expr) {
  {
    Declarations::NodeScopeActivator scope(declarations(), expr->left);
    declarations()->DeclareLabel(kTrueLabelName);
    Visit(expr->left);
  }
  Visit(expr->right);
}

void DeclarationVisitor::DeclareExpressionForBranch(
    Expression* node, base::Optional<Statement*> true_statement,
    base::Optional<Statement*> false_statement) {
  Declarations::NodeScopeActivator scope(declarations(), node);
  // Conditional expressions can either explicitly return a bit
  // type, or they can be backed by macros that don't return but
  // take a true and false label. By declaring the labels before
  // visiting the conditional expression, those label-based
  // macro conditionals will be able to find them through normal
  // label lookups.
  declarations()->DeclareLabel(kTrueLabelName, true_statement);
  declarations()->DeclareLabel(kFalseLabelName, false_statement);
  Visit(node);
}

void DeclarationVisitor::Visit(ConditionalExpression* expr) {
  DeclareExpressionForBranch(expr->condition);
  Visit(expr->if_true);
  Visit(expr->if_false);
}

void DeclarationVisitor::Visit(IfStatement* stmt) {
  DeclareExpressionForBranch(stmt->condition, stmt->if_true, stmt->if_false);
  Visit(stmt->if_true);
  if (stmt->if_false) Visit(*stmt->if_false);
}

void DeclarationVisitor::Visit(WhileStatement* stmt) {
  Declarations::NodeScopeActivator scope(declarations(), stmt);
  DeclareExpressionForBranch(stmt->condition);
  Visit(stmt->body);
}

void DeclarationVisitor::Visit(ForOfLoopStatement* stmt) {
  // Scope for for iteration variable
  Declarations::NodeScopeActivator scope(declarations(), stmt);
  Visit(stmt->var_declaration);
  Visit(stmt->iterable);
  if (stmt->begin) Visit(*stmt->begin);
  if (stmt->end) Visit(*stmt->end);
  Visit(stmt->body);
}

void DeclarationVisitor::Visit(ForLoopStatement* stmt) {
  Declarations::NodeScopeActivator scope(declarations(), stmt);
  if (stmt->var_declaration) Visit(*stmt->var_declaration);

  // Same as DeclareExpressionForBranch, but without the extra scope.
  // If no test expression is present we can not use it for the scope.
  declarations()->DeclareLabel(kTrueLabelName);
  declarations()->DeclareLabel(kFalseLabelName);
  if (stmt->test) Visit(*stmt->test);

  Visit(stmt->body);
  if (stmt->action) Visit(*stmt->action);
}

void DeclarationVisitor::Visit(TryLabelExpression* stmt) {
  // Activate a new scope to declare the handler's label parameters, they should
  // not be visible outside the label block.
  {
    Declarations::NodeScopeActivator scope(declarations(), stmt);

    // Declare label
    {
      LabelBlock* block = stmt->label_block;
      CurrentSourcePosition::Scope scope(block->pos);
      Label* shared_label =
          declarations()->DeclareLabel(block->label, block->body);
      {
        Declarations::NodeScopeActivator scope(declarations(), block->body);
        if (block->parameters.has_varargs) {
          std::stringstream stream;
          stream << "cannot use ... for label parameters";
          ReportError(stream.str());
        }

        size_t i = 0;
        for (const auto& p : block->parameters.names) {
          const Type* type =
              declarations()->GetType(block->parameters.types[i]);
          if (type->IsConstexpr()) {
            ReportError("no constexpr type allowed for label arguments");
          }

          shared_label->AddVariable(DeclareVariable(p, type, false));
          ++i;
        }
        if (global_context_.verbose()) {
          std::cout << " declaring label " << block->label << "\n";
        }
      }
    }

    Visit(stmt->try_expression);
  }

  Visit(stmt->label_block->body);
}

void DeclarationVisitor::GenerateHeader(std::string& file_name) {
  std::stringstream new_contents_stream;
  new_contents_stream
      << "#ifndef V8_BUILTINS_BUILTIN_DEFINITIONS_FROM_DSL_H_\n"
         "#define V8_BUILTINS_BUILTIN_DEFINITIONS_FROM_DSL_H_\n"
         "\n"
         "#define BUILTIN_LIST_FROM_DSL(CPP, API, TFJ, TFC, TFS, TFH, ASM) "
         "\\\n";
  for (auto builtin : torque_builtins_) {
    int firstParameterIndex = 1;
    bool declareParameters = true;
    if (builtin->IsStub()) {
      new_contents_stream << "TFS(" << builtin->name();
    } else {
      new_contents_stream << "TFJ(" << builtin->name();
      if (builtin->IsVarArgsJavaScript()) {
        new_contents_stream
            << ", SharedFunctionInfo::kDontAdaptArgumentsSentinel";
        declareParameters = false;
      } else {
        assert(builtin->IsFixedArgsJavaScript());
        // FixedArg javascript builtins need to offer the parameter
        // count.
        assert(builtin->parameter_names().size() >= 2);
        new_contents_stream << ", " << (builtin->parameter_names().size() - 2);
        // And the receiver is explicitly declared.
        new_contents_stream << ", kReceiver";
        firstParameterIndex = 2;
      }
    }
    if (declareParameters) {
      int index = 0;
      for (const auto& parameter : builtin->parameter_names()) {
        if (index >= firstParameterIndex) {
          new_contents_stream << ", k" << CamelifyString(parameter);
        }
        index++;
      }
    }
    new_contents_stream << ") \\\n";
  }
  new_contents_stream
      << "\n"
         "#endif  // V8_BUILTINS_BUILTIN_DEFINITIONS_FROM_DSL_H_\n";

  std::string new_contents(new_contents_stream.str());
  ReplaceFileContentsIfDifferent(file_name, new_contents);
}

void DeclarationVisitor::Visit(IdentifierExpression* expr) {
  if (expr->generic_arguments.size() != 0) {
    TypeVector specialization_types;
    for (auto t : expr->generic_arguments) {
      specialization_types.push_back(declarations()->GetType(t));
    }
    // Specialize all versions of the generic, since the exact parameter type
    // list cannot be resolved until the call's parameter expressions are
    // evaluated. This is an overly conservative but simple way to make sure
    // that the correct specialization exists.
    for (auto generic : declarations()->LookupGeneric(expr->name)->list()) {
      CallableNode* callable = generic->declaration()->callable;
      if (generic->declaration()->body) {
        QueueGenericSpecialization({generic, specialization_types}, callable,
                                   callable->signature.get(),
                                   generic->declaration()->body);
      }
    }
  }
}

void DeclarationVisitor::Visit(StatementExpression* expr) {
  Visit(expr->statement);
}

void DeclarationVisitor::Visit(CallExpression* expr) {
  Visit(&expr->callee);
  for (Expression* arg : expr->arguments) Visit(arg);
}

void DeclarationVisitor::Visit(TypeDeclaration* decl) {
  std::string generates = decl->generates ? *decl->generates : std::string("");
  const AbstractType* type = declarations()->DeclareAbstractType(
      decl->name, generates, {}, decl->extends);

  if (decl->constexpr_generates) {
    std::string constexpr_name = CONSTEXPR_TYPE_PREFIX + decl->name;
    base::Optional<std::string> constexpr_extends;
    if (decl->extends)
      constexpr_extends = CONSTEXPR_TYPE_PREFIX + *decl->extends;
    declarations()->DeclareAbstractType(
        constexpr_name, *decl->constexpr_generates, type, constexpr_extends);
  }
}

void DeclarationVisitor::DeclareSignature(const Signature& signature) {
  auto type_iterator = signature.parameter_types.types.begin();
  for (const auto& name : signature.parameter_names) {
    const Type* t(*type_iterator++);
    if (name.size() != 0) {
      DeclareParameter(name, t);
    }
  }
  for (auto& label : signature.labels) {
    auto label_params = label.types;
    Label* new_label = declarations()->DeclareLabel(label.name);
    new_label->set_external_label_name("label_" + label.name);
    size_t i = 0;
    for (auto var_type : label_params) {
      if (var_type->IsConstexpr()) {
        ReportError("no constexpr type allowed for label arguments");
      }

      std::string var_name = label.name + std::to_string(i++);
      new_label->AddVariable(
          declarations()->CreateVariable(var_name, var_type, false));
    }
  }
}

void DeclarationVisitor::DeclareSpecializedTypes(const SpecializationKey& key) {
  size_t i = 0;
  Generic* generic = key.first;
  const std::size_t generic_parameter_count =
      generic->declaration()->generic_parameters.size();
  if (generic_parameter_count != key.second.size()) {
    std::stringstream stream;
    stream << "Wrong generic argument count for specialization of \""
           << generic->name() << "\", expected: " << generic_parameter_count
           << ", actual: " << key.second.size();
    ReportError(stream.str());
  }

  for (auto type : key.second) {
    std::string generic_type_name =
        generic->declaration()->generic_parameters[i++];
    declarations()->DeclareType(generic_type_name, type);
  }
}

void DeclarationVisitor::Specialize(const SpecializationKey& key,
                                    CallableNode* callable,
                                    const CallableNodeSignature* signature,
                                    Statement* body) {
  Generic* generic = key.first;

  // TODO(tebbi): The error should point to the source position where the
  // instantiation was requested.
  CurrentSourcePosition::Scope pos_scope(generic->declaration()->pos);
  size_t generic_parameter_count =
      generic->declaration()->generic_parameters.size();
  if (generic_parameter_count != key.second.size()) {
    std::stringstream stream;
    stream << "number of template parameters ("
           << std::to_string(key.second.size())
           << ") to intantiation of generic " << callable->name
           << " doesnt match the generic's declaration ("
           << std::to_string(generic_parameter_count) << ")";
    ReportError(stream.str());
  }

  Signature type_signature;
  {
    // Manually activate the specialized generic's scope when declaring the
    // generic parameter specializations.
    Declarations::GenericScopeActivator namespace_scope(declarations(), key);
    DeclareSpecializedTypes(key);
    type_signature = MakeSignature(signature);
  }

  Visit(callable, type_signature, body);
}

}  // namespace torque
}  // namespace internal
}  // namespace v8