/*******************************************************************************
Copyright (c) 1997-2004, Perforce Software, Inc. All rights reserved.
Portions Copyright (c) 1999, Mike Meyer. All rights reserved.
Portions Copyright (c) 2004-2007, Robert Cowham. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTR
IBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL PERFORCE SOFTWARE, INC. BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
$Id: //depot/r08.1/p4-python/PythonClientUser.cpp#2 $
*******************************************************************************/
#include <Python.h>
#include "undefdups.h"
#include <clientapi.h>
#include <i18napi.h>
#include <strtable.h>
#include <enviro.h>
#include <hostenv.h>
#include <spec.h>
#include <diff.h>
#include <iostream>
#include <iomanip>
#include "SpecMgr.h"
#include "P4Result.h"
#include "PythonClientUser.h"
#include "PythonClientAPI.h"
#include "P4PythonDebug.h"
#include "PythonThreadGuard.h"
#include "PythonMergeData.h"
#include "PythonTypes.h"
using namespace std;
PythonClientUser::PythonClientUser( SpecMgr *s )
{
specMgr = s;
debug = 0;
Py_INCREF(Py_None);
input = Py_None;
Py_INCREF(Py_None);
resolver = Py_None;
}
PythonClientUser::~PythonClientUser()
{
Py_DECREF(input);
Py_DECREF(resolver);
}
void PythonClientUser::Reset()
{
results.Reset();
// input data is untouched
}
void PythonClientUser::Finished()
{
DisableThreadGuard guard;
if ( P4PYDBG_CALLS && input != Py_None )
cerr << "[P4] Cleaning up saved input" << endl;
PyObject * tmp = input;
Py_INCREF(Py_None);
input = Py_None;
Py_DECREF(tmp);
}
void PythonClientUser::HandleError( Error *e )
{
DisableThreadGuard guard;
if( P4PYDBG_CALLS )
cerr << "[P4] HandleError()" << endl;
if( P4PYDBG_DATA )
{
StrBuf t;
e->Fmt( t, EF_PLAIN );
cerr << "... [" << e->FmtSeverity() << "] " << t.Text() << endl;
}
results.AddError( e );
}
void PythonClientUser::OutputText( const char *data, int length )
{
DisableThreadGuard guard;
if( P4PYDBG_CALLS )
cerr << "[P4] OutputText()" << endl;
if( P4PYDBG_DATA )
cerr << "... [" << length << "]" << setw(length) << data << endl;
results.AddOutput( PyString_FromStringAndSize(data, length) );
}
void PythonClientUser::OutputInfo( char level, const char *data )
{
DisableThreadGuard guard;
if( P4PYDBG_CALLS )
cerr << "[P4] OutputInfo()" << endl;
if( P4PYDBG_DATA )
cerr << "... [" << level << "] " << data << endl;
results.AddOutput( data );
}
void PythonClientUser::OutputBinary( const char *data, int length )
{
DisableThreadGuard guard;
if( P4PYDBG_CALLS )
cerr << "[P4] OutputBinary()" << endl;
if( P4PYDBG_DATA )
{
ios::fmtflags oldFlags = cout.flags();
cout << showbase << hex << internal << setfill('0') << uppercase;
for( int l = 0; l < length; l++ )
{
if( l % 16 == 0 )
cerr << (l ? "\n" : "") << "... ";
cout << setw(4) << data[ l ] << " ";
}
cout.flags(oldFlags);
}
//
// Binary is just stored in a string. Since the char * version of
// P4Result::AddOutput() assumes it can strlen() to find the length,
// we'll make the String object here.
//
results.AddOutput( PyString_FromStringAndSize(data, length) );
}
void PythonClientUser::OutputStat( StrDict *values )
{
DisableThreadGuard guard;
StrPtr * spec = values->GetVar( "specdef" );
StrPtr * data = values->GetVar( "data" );
StrPtr * sf = values->GetVar( "specFormatted" );
StrDict * dict = values;
SpecDataTable specData;
Error e;
//
// Determine whether or not the data we've got contains a spec in one form
// or another. 2000.1 -> 2005.1 servers supplied the form in a data variable
// and we use the spec variable to parse the form. 2005.2 and later servers
// supply the spec ready-parsed but set the 'specFormatted' variable to tell
// the client what's going on. Either way, we need the specdef variable set
// to enable spec parsing.
//
int isspec = spec && ( sf || data );
//
// Save the spec definition for later
//
if( spec )
specMgr->AddSpecDef( cmd.Text(), spec->Text() );
//
// Parse any form supplied in the 'data' variable and convert it into a
// dictionary.
//
if( spec && data )
{
// 2000.1 -> 2005.1 server's handle tagged form output by supplying the form
// as text in the 'data' variable. We need to convert it to a dictionary
// using the supplied spec.
if( P4PYDBG_CALLS )
cerr << "[P4] OutputStat() - parsing form" << endl;
// Parse the form. Use the ParseNoValid() interface to prevent
// errors caused by the use of invalid defaults for select items in
// jobspecs.
// #if P4APIVER_ID >= 513538
Spec s( spec->Text(), "", &e );
//#else
// Spec s( spec->Text(), "" );
//#endif
if( !e.Test() ) s.ParseNoValid( data->Text(), &specData, &e );
if( e.Test() )
{
HandleError( &e );
return;
}
dict = specData.Dict();
}
//
// If what we've got is a parsed form, then we'll convert it to a P4::Spec
// object. Otherwise it's a plain dict.
//
if( isspec )
{
if( P4PYDBG_CALLS )
cerr << "[P4] OutputStat() - Converting to P4::Spec object" << endl;
results.AddOutput( specMgr->StrDictToSpec( dict, spec ) );
}
else
{
if( P4PYDBG_CALLS )
cerr << "[P4] OutputStat() - Converting to dict" << endl;
results.AddOutput( specMgr->StrDictToDict( dict ) );
}
}
/*
* Diff support for Python API. Since the Diff class only writes its output
* to files, we run the requested diff putting the output into a temporary
* file. Then we read the file in and add its contents line by line to the
* results.
*/
void PythonClientUser::Diff( FileSys *f1, FileSys *f2, int doPage,
char *diffFlags, Error *e )
{
DisableThreadGuard guard;
if ( P4PYDBG_CALLS )
cerr << "[P4] Diff() - comparing files" << endl;
//
// Duck binary files. Much the same as ClientUser::Diff, we just
// put the output into Python space rather than stdout.
//
if( !f1->IsTextual() || !f2->IsTextual() )
{
if ( f1->Compare( f2, e ) )
results.AddOutput( "(... files differ ...)" );
return;
}
// Time to diff the two text files. Need to ensure that the
// files are in binary mode, so we have to create new FileSys
// objects to do this.
FileSys *f1_bin = FileSys::Create( FST_BINARY );
FileSys *f2_bin = FileSys::Create( FST_BINARY );
FileSys *t = FileSys::CreateGlobalTemp( f1->GetType() );
f1_bin->Set( f1->Name() );
f2_bin->Set( f2->Name() );
{
//
// In its own block to make sure that the diff object is deleted
// before we delete the FileSys objects.
//
::Diff d;
d.SetInput( f1_bin, f2_bin, diffFlags, e );
if ( ! e->Test() ) d.SetOutput( t->Name(), e );
if ( ! e->Test() ) d.DiffWithFlags( diffFlags );
d.CloseOutput( e );
// OK, now we have the diff output, read it in and add it to
// the output.
if ( ! e->Test() ) t->Open( FOM_READ, e );
if ( ! e->Test() )
{
StrBuf b;
while( t->ReadLine( &b, e ) )
results.AddOutput( b.Text() );
}
}
delete t;
delete f1_bin;
delete f2_bin;
if ( e->Test() ) HandleError( e );
}
/*
* convert input from the user into a form digestible to Perforce. This
* involves either (a) converting any supplied dict to a Perforce form, or
* (b) running to_s on whatever we were given.
*/
void PythonClientUser::InputData( StrBuf *strbuf, Error *e )
{
DisableThreadGuard guard;
if ( P4PYDBG_CALLS )
cerr << "[P4] InputData(). Using supplied input" << endl;
PyObject * inval = input;
if( PyTuple_Check(input) )
{
inval = PyTuple_GetItem(input, 0);
input = PyTuple_GetSlice(input, 1, PyTuple_Size(input));
}
else if ( PyList_Check(input) )
{
inval = PyList_GetItem(input, 0);
input = PyList_GetSlice(input, 1, PyList_Size(input));
}
if( inval == Py_None )
{
PyErr_WarnEx( PyExc_UserWarning,
"[P4] Expected user input, found none. "
"Missing call to P4.input ?", 1 );
return;
}
if ( PyDict_Check( inval ) )
{
StrPtr * specDef = varList->GetVar( "specdef" );
specMgr->AddSpecDef( cmd.Text(), specDef->Text() );
specMgr->SpecToString( cmd.Text(), inval, *strbuf, e );
return;
}
// Convert whatever's left into a string
PyObject * str = PyObject_Str(inval);
strbuf->Set( PyString_AsString(str) );
Py_XDECREF(str);
}
/*
* In a script we don't really want the user to see a prompt, so we
* (ab)use the SetInput() function to allow the caller to supply the
* answer before the question is asked.
*/
void PythonClientUser::Prompt( const StrPtr &msg, StrBuf &rsp, int noEcho, Error *e )
{
// no DisableThreadGuard here. The guard is not reentrant
// and Prompt() calls InputData()
if ( P4PYDBG_CALLS )
cerr << "[P4] Prompt(): " << msg.Text() << endl;
InputData( &rsp, e );
}
/*
* Do a resolve.
*/
int PythonClientUser::Resolve( ClientMerge *m, Error *e )
{
if ( P4PYDBG_CALLS )
cerr << "[P4] Resolve()" << endl;
//
// If no resolver is defined, default to using the merger's resolve
// if p4.input is set. Otherwise, bail out of the resolve
//
if( this->resolver == Py_None ) {
if ( this->input != Py_None ) {
return m->Resolve( e );
}
else {
PyErr_WarnEx( PyExc_UserWarning,
"[P4::Resolve] Resolve called with no resolver and no input -> skipping resolve", 1);
return CMS_QUIT;
}
}
//
// First detect what the merger thinks the result ought to be
//
StrBuf t;
MergeStatus autoMerge = m->AutoResolve( CMF_FORCE );
// Now convert that to a string;
switch( autoMerge )
{
case CMS_QUIT: t = "q"; break;
case CMS_SKIP: t = "s"; break;
case CMS_MERGED: t = "am"; break;
case CMS_EDIT: t = "e"; break;
case CMS_YOURS: t = "ay"; break;
case CMS_THEIRS: t = "at"; break;
}
PyObject * mergeData = MkMergeInfo( m, t );
for( int loop=0 ; loop < 10 ; loop++ )
{
DisableThreadGuard guard;
PyObject * result = PyObject_CallMethod( this->resolver , "resolve", "(O)", mergeData );
if( result == NULL ) { // exception thrown, bug out of here
return CMS_QUIT;
}
StrBuf reply = PyString_AS_STRING( result );
if( reply == "ay" ) return CMS_YOURS;
else if( reply == "at" ) return CMS_THEIRS;
else if( reply == "am" ) return CMS_MERGED;
else if( reply == "ae" ) return CMS_EDIT;
else if( reply == "s" ) return CMS_SKIP;
else if( reply == "q" ) return CMS_QUIT;
else {
StrBuf warning("[P4::Resolve] Illegal response : '");
warning << reply;
warning << "', skipping resolve";
PyErr_WarnEx( PyExc_UserWarning, warning.Text(), 1);
return CMS_QUIT;
}
}
PyErr_WarnEx( PyExc_UserWarning, "[P4::Resolve] Aborting resolve after 10 attempts", 1);
return CMS_QUIT;
}
/*
* Accept input from Python. We just save what we're given here because we may not
* have the specdef available to parse it with at this time.
*/
PyObject * PythonClientUser::SetInput( PyObject * i )
{
if ( P4PYDBG_CALLS )
cerr << "[P4] SetInput()" << endl;
PyObject * tmp = input;
input = i;
Py_INCREF(input);
Py_DECREF(tmp);
Py_RETURN_TRUE;
}
/*
* Sets the resolver from Python
*/
PyObject * PythonClientUser::SetResolver( PyObject * r )
{
if ( P4PYDBG_CALLS )
cerr << "[P4] SetResolver()" << endl;
PyObject * tmp = resolver;
resolver = r;
Py_INCREF(resolver);
Py_DECREF(tmp);
Py_RETURN_TRUE;
}
PyObject * PythonClientUser::MkMergeInfo( ClientMerge *m, StrPtr &hint )
{
if ( P4PYDBG_CALLS )
cerr << "[P4] MkMergeInfo()" << endl;
DisableThreadGuard guard;
P4MergeData *mergeObj = PyObject_New(P4MergeData, &P4MergeDataType);
if (mergeObj != NULL) {
mergeObj->mergeData = new PythonMergeData( this, m, hint);
}
else {
PyErr_WarnEx( PyExc_UserWarning, "[P4::Resolve] Failed to create object in MkMergeInfo", 1);
}
return (PyObject *) mergeObj;
}