using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Perforce.P4;
using log4net;
using log4net.Appender;
using log4net.Config;
namespace P4NetContentTrigger
{
class P4SubmitContentTrigger
{
private static readonly ILog _log = LogManager.GetLogger(typeof(P4SubmitContentTrigger));
private void ReportError(string msg)
{
_log.Error(msg);
Console.WriteLine(msg);
Console.Error.WriteLine(msg);
}
public int Validate(CmdLineOptions options)
{
P4Interface p4 = null;
try
{
p4 = new P4Interface(options.Port, options.User);
if (!p4.Connect())
{
ReportError("Failed to connect");
return 1;
}
_log.InfoFormat("Processing changelist: {0}", options.Change);
Changelist change = p4.repo.GetChangelist(options.Change, new Perforce.P4.Options());
// Following section get's the content of each file into a local temp
foreach (var file in change.Files)
{
var depotPath = file.DepotPath.ToString();
_log.InfoFormat("File: {0}", depotPath);
if (string.IsNullOrEmpty(depotPath))
break;
var path = Path.GetTempPath();
var tempFileName = Guid.NewGuid().ToString();
var tempFilePath = Path.Combine(path, tempFileName);
var fcoptions = new GetFileContentsCmdOptions(GetFileContentsCmdFlags.None, tempFilePath);
var contentVer = new ShelvedInChangelistIdVersion(options.Change);
var spec = new FileSpec(new DepotPath(depotPath), contentVer);
var results = p4.repo.GetFileContents(fcoptions, spec);
if (options.Testing)
{
// Decide what to do based on contents of files - in test mode only
using (var reader = new StreamReader(tempFilePath))
{
var line = reader.ReadLine();
_log.DebugFormat("First line of file: {0}", line);
if (line.ToLower().Contains("fail"))
{
ReportError("Testing: Trigger failed");
return 1;
}
}
_log.Debug("File contents read and validated successfully");
}
else
{
// TODO - the real content validation as desired when not in test mode.
}
}
return 0;
}
catch (Exception ex)
{
ReportError(ex.Message);
if (ex.Message.Contains("Perforce password (P4PASSWD) invalid or unset"))
{
string p4user = "unknown";
if (p4 != null)
{
p4user = p4.repo.Connection.UserName;
}
string msg = string.Format(
@"Password error during trigger execution.
Please inform your administrator and ask them to check:
- 'p4 triggers' definition
- P4TICKET value for user '{0}'
- server log file.", p4user);
ReportError(msg);
}
else
{
_log.Error(ex.StackTrace);
}
return 1;
}
}
}
}