-
-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathPerforceSCM.java
More file actions
3299 lines (2893 loc) · 128 KB
/
PerforceSCM.java
File metadata and controls
3299 lines (2893 loc) · 128 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package hudson.plugins.perforce;
import hudson.plugins.perforce.config.DepotType;
import com.tek42.perforce.Depot;
import com.tek42.perforce.PerforceException;
import com.tek42.perforce.model.Changelist;
import com.tek42.perforce.model.Counter;
import com.tek42.perforce.model.Label;
import com.tek42.perforce.model.Workspace;
import com.tek42.perforce.parse.Counters;
import com.tek42.perforce.parse.Workspaces;
import com.tek42.perforce.model.Changelist.FileEntry;
import hudson.AbortException;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Util;
import hudson.FilePath.FileCallable;
import hudson.Launcher;
import static hudson.Util.fixNull;
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixRun;
import hudson.model.*;
import hudson.model.listeners.ItemListener;
import hudson.plugins.perforce.config.CleanTypeConfig;
import hudson.plugins.perforce.config.MaskViewConfig;
import hudson.plugins.perforce.config.WorkspaceCleanupConfig;
import hudson.plugins.perforce.utils.MacroStringHelper;
import hudson.plugins.perforce.utils.ParameterSubstitutionException;
import hudson.remoting.VirtualChannel;
import hudson.scm.ChangeLogParser;
import hudson.scm.PollingResult;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.scm.SCMRevisionState;
import hudson.slaves.EnvironmentVariablesNodeProperty;
import hudson.slaves.NodeProperty;
import hudson.tasks.BuildTrigger;
import hudson.tasks.Messages;
import hudson.util.FormValidation;
import hudson.util.LogTaskListener;
import hudson.util.StreamTaskListener;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import javax.servlet.ServletException;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.net.InetAddress;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* Extends {@link SCM} to provide integration with Perforce SCM repositories.
*
* @author Mike Wille
* @author Brian Westrich
* @author Victor Szoltysek
*/
public class PerforceSCM extends SCM {
private Long configVersion;
String p4User;
String p4Passwd;
String p4Port;
String p4Client;
String clientSpec;
String projectPath;
String projectOptions;
String p4Label;
String p4Counter;
String p4UpstreamProject;
String p4Stream;
String clientOwner;
/**
* Transient so that old XML data will be read but not saved.
* @deprecated Replaced by {@link #p4Tool}
*/
transient String p4Exe;
String p4SysDrive = "C:";
String p4SysRoot = "C:\\WINDOWS";
PerforceRepositoryBrowser browser;
private static final Logger LOGGER = Logger.getLogger(PerforceSCM.class.getName());
private static final int MAX_CHANGESETS_ON_FIRST_BUILD = 50;
private static final String WORKSPACE_COMBINATOR = System.getProperty(hudson.slaves.WorkspaceList.class.getName(),"@");
/**
* Name of the p4 tool installation
*/
String p4Tool;
/**
* Use ClientSpec text file from depot to prepare the workspace view
*/
boolean useClientSpec = false;
/**
* True if stream depot is used, false otherwise
*/
boolean useStreamDepot = false;
/**
* This is being removed, including it as transient to fix exceptions on startup.
*/
transient int lastChange;
/**
* force sync is a one time trigger from the config area to force a sync with the depot.
* it is reset to false after the first checkout.
*/
boolean forceSync = false;
/**
* Always force sync the workspace when running a build
*/
boolean alwaysForceSync = false;
/**
* Don't update the 'have' database on the server when syncing.
*/
boolean dontUpdateServer = false;
/**
* Disable Workspace pre-build automatic sync and changelog retrieval
* This should be renamed if we can implement upgrade logic to handle old configs
*/
@Deprecated
boolean disableAutoSync = false;
/**
* Disable ChangeLog retrieval
*/
boolean disableChangeLogOnly = false;
/**
* Disable Workspace syncing
*/
boolean disableSyncOnly = false;
/**
* Show integrated changelists
*/
boolean showIntegChanges = false;
/**
* This is to allow the client to use the old naming scheme
* @deprecated As of 1.0.25, replaced by {@link #clientSuffixType}
*/
@Deprecated
boolean useOldClientName = false;
/**
* If true, we will create the workspace view within the plugin. If false, we will not.
*/
Boolean createWorkspace = true;
/**
* If true, we will manage the workspace view within the plugin. If false, we will leave the
* view alone.
*/
boolean updateView = true;
/**
* If false we add the slave hostname to the end of the client name when
* running on a slave. Defaulting to true so as not to change the behavior
* for existing users.
* @deprecated As of 1.0.25, replaced by {@link #clientSuffixType}
*/
@Deprecated
boolean dontRenameClient = true;
/**
* If true we update the named counter to the last changelist value after the sync operation.
* If false the counter will be used as the changelist value to sync to.
* Defaulting to false since the counter name is not set to begin with.
*/
boolean updateCounterValue = false;
/**
* If true, we will never update the client workspace spec on the perforce server.
*/
boolean dontUpdateClient = false;
/**
* If true the environment value P4PASSWD will be set to the value of p4Passwd.
*/
boolean exposeP4Passwd = false;
/**
* If true, the workspace will be deleted before the checkout commences.
*/
boolean wipeBeforeBuild = false;
/**
* If true, the workspace will be cleaned before the checkout commences.
*/
boolean quickCleanBeforeBuild = false;
/**
* If true, files in the workspace will be scanned for differences and restored during a quick clean
*/
boolean restoreChangedDeletedFiles = false;
/**
* If true, the ,repository will be deleted before the checkout commences in addition to the workspace.
*/
boolean wipeRepoBeforeBuild = false;
/**
* If > 0, then will override the changelist we sync to for the first build.
*/
int firstChange = -1;
/**
* Maximum amount of files that are recorded to a changelist, if < 1 show every file.
*/
int fileLimit = 0;
/**
* P4 user name(s) or regex user pattern to exclude from SCM poll to prevent build trigger.
* Multiple user names are deliminated by space.
*/
String excludedUsers;
/**
* P4 file(s) or regex file pattern to exclude from SCM poll to prevent build trigger.
*/
String excludedFiles;
/**
* Use Case sensitive matching on excludedFiles.
*/
Boolean excludedFilesCaseSensitivity;
/**
* If a ticket was issued we can use it instead of the password in the environment.
*/
private String p4Ticket = null;
/**
* Determines what to append to the end of the client workspace names on slaves
* Possible values:
* None
* Hostname
* Hash
*/
String slaveClientNameFormat = null;
/**
* Perforce program name to report to the Perforce server
*/
String p4ProgramName = null;
String p4ProgramPollingName = null;
/** Regular expression for validation of p4 Program Name
*/
private static final String P4_PROGRAM_NAME_PATTERN =
"[_a-zA-Z0-9@.\\[\\]\\(\\)\\<\\>-]+";
/**
* We need to store the changelog file name for the build so that we can expose
* it to the build environment
*/
transient private String changelogFilename = null;
/**
* The value of the LineEnd field in the perforce Client spec.
*/
private String lineEndValue = "local";
/**
* View mask settings for polling and/or syncing against a subset
* of files in the client workspace.
*/
private boolean useViewMask = false;
private String viewMask = null;
private boolean useViewMaskForPolling = true;
private boolean useViewMaskForSyncing = false;
private boolean useViewMaskForChangeLog = false;
/**
* Sync only on master option.
*/
private boolean pollOnlyOnMaster = false;
/**
* charset options
*/
private String p4Charset = null;
private String p4CommandCharset = null;
/**
* SCM constructor, (only?) used when a job configuration is saved.
* This constructor uses data classes from {@link hudson.plugins.perforce.config}
* to allow proper handling of hierarchical data in Stapler. In the current
* state, these classes are not being used outside this constructor.
*/
// TODO: move data to configuration classes during the refactoring
@DataBoundConstructor
public PerforceSCM(
String p4User,
String p4Passwd,
String p4Client,
String p4Port,
String projectOptions,
String p4Tool,
String p4SysRoot,
String p4SysDrive,
String p4Label,
String p4Counter,
String p4UpstreamProject,
String lineEndValue,
String p4Charset,
String p4CommandCharset,
String clientOwner,
boolean updateCounterValue,
boolean forceSync,
boolean dontUpdateServer,
boolean alwaysForceSync,
boolean createWorkspace,
boolean updateView,
boolean disableChangeLogOnly,
boolean disableSyncOnly,
boolean showIntegChanges,
boolean dontUpdateClient,
boolean exposeP4Passwd,
boolean pollOnlyOnMaster,
String slaveClientNameFormat,
int firstChange,
int fileLimit,
PerforceRepositoryBrowser browser,
String excludedUsers,
String excludedFiles,
boolean excludedFilesCaseSensitivity,
DepotType depotType,
WorkspaceCleanupConfig cleanWorkspace,
MaskViewConfig useViewMask,
String p4ProgramName,
String p4ProgramPollingName
) {
this.configVersion = 2L;
this.p4User = p4User;
this.setP4Passwd(p4Passwd);
this.setExposeP4Passwd(exposeP4Passwd);
this.p4Client = p4Client;
this.p4Port = p4Port;
this.p4Tool = p4Tool;
this.pollOnlyOnMaster = pollOnlyOnMaster;
this.projectOptions = (projectOptions != null)
? projectOptions
: "noallwrite clobber nocompress unlocked nomodtime rmdir";
if (this.p4Label != null && p4Label != null) {
Logger.getLogger(PerforceSCM.class.getName()).warning(
"Label found in views and in label field. Using: "
+ p4Label);
}
this.p4Label = Util.fixEmptyAndTrim(p4Label);
this.p4Counter = Util.fixEmptyAndTrim(p4Counter);
this.updateCounterValue = updateCounterValue;
this.p4UpstreamProject = Util.fixEmptyAndTrim(p4UpstreamProject);
//TODO: move optional entries to external classes
// Get data from the depot type
if (depotType != null) {
this.p4Stream = depotType.getP4Stream();
this.clientSpec = depotType.getClientSpec();
this.projectPath = Util.fixEmptyAndTrim(depotType.getProjectPath());
this.useStreamDepot = depotType.useP4Stream();
this.useClientSpec = depotType.useClientSpec();
this.useViewMask = depotType.useProjectPath();
}
// Get data from workspace cleanup settings
if (cleanWorkspace != null) {
setWipeRepoBeforeBuild(cleanWorkspace.isWipeRepoBeforeBuild());
CleanTypeConfig cleanType = cleanWorkspace.getCleanType();
if (cleanType != null) {
setWipeBeforeBuild(cleanType.isWipe());
setQuickCleanBeforeBuild(cleanType.isQuick());
setRestoreChangedDeletedFiles(cleanType.isRestoreChangedDeletedFiles());
}
} else {
setWipeRepoBeforeBuild(false);
}
// Setup view mask
if (useViewMask != null) {
setUseViewMask(true);
setViewMask(hudson.Util.fixEmptyAndTrim(useViewMask.getViewMask()));
setUseViewMaskForPolling(useViewMask.isUseViewMaskForPolling());
setUseViewMaskForSyncing(useViewMask.isUseViewMaskForSyncing());
setUseViewMaskForChangeLog(useViewMask.isUseViewMaskForChangeLog());
} else {
setUseViewMask(false);
}
this.clientOwner = Util.fixEmptyAndTrim(clientOwner);
if (p4SysRoot != null) {
this.p4SysRoot = p4SysRoot.trim();
}
if (p4SysDrive != null) {
this.p4SysDrive = p4SysDrive.trim();
}
this.lineEndValue = lineEndValue;
this.forceSync = forceSync;
this.dontUpdateServer = dontUpdateServer;
this.alwaysForceSync = alwaysForceSync;
this.disableChangeLogOnly = disableChangeLogOnly;
this.disableSyncOnly = disableSyncOnly;
this.showIntegChanges = showIntegChanges;
this.browser = browser;
this.createWorkspace = Boolean.valueOf(createWorkspace);
this.updateView = updateView;
this.dontUpdateClient = dontUpdateClient;
this.slaveClientNameFormat = slaveClientNameFormat;
this.firstChange = firstChange;
this.fileLimit = fileLimit;
this.dontRenameClient = false;
this.useOldClientName = false;
this.p4Charset = Util.fixEmptyAndTrim(p4Charset);
this.p4CommandCharset = Util.fixEmptyAndTrim(p4CommandCharset);
this.excludedUsers = Util.fixEmptyAndTrim(excludedUsers);
this.excludedFiles = Util.fixEmptyAndTrim(excludedFiles);
this.excludedFilesCaseSensitivity = excludedFilesCaseSensitivity;
setP4ProgramName(p4ProgramName);
setP4ProgramPollingName(p4ProgramPollingName);
}
/**
* Gets instance of the PerforceSCM
* @return Instance of the PerforceSCM
* @since 1.4.0
*/
public static PerforceSCMDescriptor getInstance() {
String scmName = PerforceSCM.class.getSimpleName();
return (PerforceSCMDescriptor)Hudson.getInstance().getScm(scmName);
}
/**
* This only exists because we need to do initialization after we have been brought
* back to life. I'm not quite clear on stapler and how all that works.
* At any rate, it doesn't look like we have an init() method for setting up our Depot
* after all of the setters have been called. Someone correct me if I'm wrong...
*
* UPDATE: With the addition of PerforceMailResolver, we now have need to share the depot object. I'm making
* this protected to enable that.
*
* Always create a new Depot to reflect any changes to the machines that
* P4 actions will be performed on.
*
* @param node the value of node
* @exception ParameterSubstitutionException
*/
protected Depot getDepot(Launcher launcher, FilePath workspace, AbstractProject project, AbstractBuild build, Node node)
throws ParameterSubstitutionException
{
HudsonP4ExecutorFactory p4Factory = new HudsonP4ExecutorFactory(launcher,workspace);
Depot depot = new Depot(p4Factory);
if (build != null) {
depot.setClient(MacroStringHelper.substituteParameters(p4Client, build, null));
depot.setUser(MacroStringHelper.substituteParameters(p4User, build, null));
depot.setPort(MacroStringHelper.substituteParameters(p4Port, build, null));
depot.setPassword(getDecryptedP4Passwd(build));
} else if (project != null) {
depot.setClient(MacroStringHelper.substituteParameters(p4Client, getDefaultSubstitutions(project)));
depot.setUser(MacroStringHelper.substituteParameters(p4User, getDefaultSubstitutions(project)));
depot.setPort(MacroStringHelper.substituteParameters(p4Port, getDefaultSubstitutions(project)));
depot.setPassword(getDecryptedP4Passwd(project));
} else {
depot.setClient(p4Client);
depot.setUser(p4User);
depot.setPort(p4Port);
depot.setPassword(getDecryptedP4Passwd());
}
if (p4Ticket != null && !p4Ticket.equals(""))
depot.setP4Ticket(p4Ticket);
if (node == null)
depot.setExecutable(getP4Executable(p4Tool));
else
depot.setExecutable(getP4Executable(p4Tool,node,TaskListener.NULL));
// Get systemDrive,systemRoot computer environment variables from
// the current machine.
// The current machine is the machine about to do something (run a
// build, poll the server) according to whatever called getDepot
String systemDrive = Util.fixEmptyAndTrim(p4SysDrive);
String systemRoot = Util.fixEmptyAndTrim(p4SysRoot);
try {
Computer currentComputer = Computer.currentComputer();
// A master with no executors seems to throw an NPE here, so
// we need to check for null.
if (currentComputer != null) {
EnvVars envVars = currentComputer.getEnvironment();
if (systemDrive == null && envVars.containsKey("SystemDrive")) {
systemDrive = envVars.get("SystemDrive");
}
if (systemRoot == null && envVars.containsKey("SystemRoot")) {
systemRoot = envVars.get("SystemRoot");
}
}
} catch (Exception ex) {
LOGGER.log(Level.WARNING, ex.getMessage(), ex);
}
depot.setSystemDrive(systemDrive);
depot.setSystemRoot(systemRoot);
depot.setCharset(p4Charset);
depot.setCommandCharset(p4CommandCharset);
return depot;
}
/**
* Override of SCM.buildEnvVars() in order to setup the last change we have
* sync'd to as a Hudson
* environment variable: P4_CHANGELIST
*
* @param build
* @param env
*/
@Override
public void buildEnvVars(AbstractBuild build, Map<String, String> env) {
super.buildEnvVars(build, env);
try {
env.put("P4PORT", MacroStringHelper.substituteParameters(p4Port, build, env));
env.put("P4USER", MacroStringHelper.substituteParameters(p4User, build, env));
} catch (ParameterSubstitutionException ex) {
LOGGER.log(MacroStringHelper.SUBSTITUTION_ERROR_LEVEL, "Can't substitute P4USER or P4PORT", ex);
//TODO: exit?
}
// if we want to allow p4 commands in script steps this helps
if (isExposeP4Passwd()) {
PerforcePasswordEncryptor encryptor = new PerforcePasswordEncryptor();
env.put("P4PASSWD", encryptor.decryptString(p4Passwd));
}
// this may help when tickets are used since we are
// not storing the ticket on the client during login
if (p4Ticket != null) {
env.put("P4TICKET", p4Ticket);
}
try {
env.put("P4CLIENT", getConcurrentClientName(build.getWorkspace(), getEffectiveClientName(build, env)));
} catch(ParameterSubstitutionException ex) {
LOGGER.log(MacroStringHelper.SUBSTITUTION_ERROR_LEVEL, "Can't substitute P4CLIENT",ex);
//TODO: exit?
}
PerforceTagAction pta = build.getAction(PerforceTagAction.class);
if (pta != null) {
if (pta.getChangeNumber() > 0) {
int lastChange = pta.getChangeNumber();
env.put("P4_CHANGELIST", Integer.toString(lastChange));
} else if (pta.getTag() != null) {
String label = pta.getTag();
env.put("P4_LABEL", label);
}
}
if (changelogFilename != null) {
env.put("HUDSON_CHANGELOG_FILE", changelogFilename);
}
}
/**
* Get the path to p4 executable from a Perforce tool installation.
*
* @param tool the p4 tool installation name
* @return path to p4 tool path or an empty string if none is found
*/
public String getP4Executable(String tool) {
PerforceToolInstallation toolInstallation = getP4Tool(tool);
if (toolInstallation == null)
return "p4";
return toolInstallation.getP4Exe();
}
public String getP4Executable(String tool, Node node, TaskListener listener) {
PerforceToolInstallation toolInstallation = getP4Tool(tool);
if (toolInstallation == null)
return "p4";
String p4Exe="p4";
try {
p4Exe = toolInstallation.forNode(node, listener).getP4Exe();
} catch (IOException e) {
listener.getLogger().println(e);
} catch (InterruptedException e) {
listener.getLogger().println(e);
}
return p4Exe;
}
/**
* Get the path to p4 executable from a Perforce tool installation.
*
* @param tool the p4 tool installation name
* @return path to p4 tool installation or null
*/
public PerforceToolInstallation getP4Tool(String tool) {
PerforceToolInstallation[] installations = ((hudson.plugins.perforce.PerforceToolInstallation.DescriptorImpl)Hudson.getInstance().
getDescriptorByType(PerforceToolInstallation.DescriptorImpl.class)).getInstallations();
for (PerforceToolInstallation i : installations) {
if (i.getName().equals(tool)) {
return i;
}
}
return null;
}
/**
* Use the old job configuration data. This method is called after the object is read by XStream.
* We want to create tool installations for each individual "p4Exe" path as field "p4Exe" has been removed.
*
* @return the new object which is an instance of PerforceSCM
*/
@SuppressWarnings( "deprecation" )
public Object readResolve() {
if (createWorkspace == null) {
createWorkspace = Boolean.TRUE;
}
if (p4Exe != null) {
PerforceToolInstallation.migrateOldData(p4Exe);
p4Tool = p4Exe;
}
if (excludedFilesCaseSensitivity == null) {
excludedFilesCaseSensitivity = Boolean.TRUE;
}
if (clientOwner == null) {
clientOwner = "";
}
if (configVersion == null) {
configVersion = 0L;
}
if (configVersion == 0L) {
this.disableSyncOnly = this.disableAutoSync;
this.disableChangeLogOnly = this.disableAutoSync;
configVersion = 1L;
}
if (configVersion == 1L) {
this.useViewMaskForChangeLog = this.useViewMaskForSyncing;
configVersion = 2L;
}
return this;
}
private Hashtable<String, String> getDefaultSubstitutions(AbstractProject project) {
Hashtable<String, String> subst = new Hashtable<String, String>();
subst.put("JOB_NAME", MacroStringHelper.getSafeJobName(project));
for (NodeProperty nodeProperty: Hudson.getInstance().getGlobalNodeProperties()) {
if (nodeProperty instanceof EnvironmentVariablesNodeProperty) {
subst.putAll(((EnvironmentVariablesNodeProperty)nodeProperty).getEnvVars());
}
}
ParametersDefinitionProperty pdp = (ParametersDefinitionProperty) project.getProperty(hudson.model.ParametersDefinitionProperty.class);
if (pdp != null) {
for (ParameterDefinition pd : pdp.getParameterDefinitions()) {
try {
ParameterValue defaultValue = pd.getDefaultParameterValue();
if (defaultValue != null) {
String name = defaultValue.getName();
String value = defaultValue.createVariableResolver(null).resolve(name);
subst.put(name, value);
}
} catch (Exception e) {
}
}
}
subst.put("P4USER", MacroStringHelper.substituteParametersNoCheck(p4User, subst));
return subst;
}
private String getEffectiveProjectPath(AbstractBuild build, AbstractProject project, PrintStream log, Depot depot)
throws PerforceException, ParameterSubstitutionException {
String projectPath;
if (useClientSpec) {
projectPath = getEffectiveProjectPathFromFile(build, project, log, depot);
} else if (build != null) {
projectPath = MacroStringHelper.substituteParameters(this.projectPath, build, null);
} else {
projectPath = MacroStringHelper.substituteParameters(this.projectPath, getDefaultSubstitutions(project));
}
return projectPath;
}
private String getEffectiveProjectPathFromFile(AbstractBuild build, AbstractProject project, PrintStream log, Depot depot) throws PerforceException, ParameterSubstitutionException {
String clientSpec;
if (build != null) {
clientSpec = MacroStringHelper.substituteParameters(this.clientSpec, build, null);
} else {
clientSpec = MacroStringHelper.substituteParametersNoCheck(this.clientSpec, getDefaultSubstitutions(project));
}
log.println("Read ClientSpec from: " + clientSpec);
com.tek42.perforce.parse.File f = depot.getFile(clientSpec);
String projectPath = f.read();
if (build != null) {
projectPath = MacroStringHelper.substituteParameters(projectPath, build, null);
} else {
projectPath = MacroStringHelper.substituteParametersNoCheck(projectPath, getDefaultSubstitutions(project));
}
return projectPath;
}
private int getLastBuildChangeset(AbstractProject project) {
Run lastBuild = project.getLastBuild();
return getLastChange(lastBuild);
}
/**
* Perform some manipulation on the workspace URI to get a valid local path
* <p>
* Is there an issue doing this? What about remote workspaces? does that happen?
*
* @param path
* @return
* @throws IOException
* @throws InterruptedException
*/
private String getLocalPathName(FilePath path, boolean isUnix) throws IOException, InterruptedException {
return processPathName(path.getRemote(), isUnix);
}
public static String processPathName(String path, boolean isUnix) {
String pathName = path;
pathName = pathName.replaceAll("/\\./", "/");
pathName = pathName.replaceAll("\\\\\\.\\\\", "\\\\");
pathName = pathName.replaceAll("/+", "/");
boolean isRemoteUNC = pathName.startsWith("\\\\");
pathName = pathName.replaceAll("\\\\+", "\\\\");
if (isRemoteUNC) {
pathName = "\\" + pathName;
}
if (isUnix) {
pathName = pathName.replaceAll("\\\\", "/");
} else {
pathName = pathName.replaceAll("/", "\\\\");
}
return pathName;
}
private static void retrieveUserInformation(Depot depot, List<Changelist> changes) throws PerforceException {
// uniqify in order to reduce number of calls to P4.
HashSet<String> users = new HashSet<String>();
for (Changelist change : changes) {
users.add(change.getUser());
}
for (String user : users) {
com.tek42.perforce.model.User pu;
try {
pu = depot.getUsers().getUser(user);
} catch (Exception e) {
throw new PerforceException("Problem getting user information for " + user,e);
}
//If there is no such user in perforce, then ignore and keep going.
if (pu == null) {
LOGGER.warning("Perforce User ("+user+") does not exist.");
continue;
}
User author = User.get(user);
// Need to store the actual perforce user id for later retrieval
// because Jenkins does not support all the same characters that
// perforce does in the userID.
PerforceUserProperty puprop = author.getProperty(PerforceUserProperty.class);
if (puprop == null || puprop.getPerforceId() == null || puprop.getPerforceId().equals("")) {
puprop = new PerforceUserProperty();
try {
author.addProperty(puprop);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
puprop.setPerforceEmail(pu.getEmail());
puprop.setPerforceId(user);
}
}
public static boolean isFileInView(String filename, String projectPath, boolean caseSensitive) {
List<String> view = parseProjectPath(projectPath, "workspace");
boolean inView = false;
for (int i = 0; i < view.size(); i += 2) {
String viewline = view.get(i);
if (viewline.startsWith("-")) {
if (doesFilenameMatchP4Pattern(filename, viewline.substring(1), caseSensitive)) {
inView = false;
}
} else if (viewline.startsWith("+")) {
if (doesFilenameMatchP4Pattern(filename, viewline.substring(1), caseSensitive)) {
inView = true;
}
} else {
if (doesFilenameMatchP4Pattern(filename, viewline, caseSensitive)) {
inView = true;
}
}
}
return inView;
}
private static class WipeWorkspaceExcludeFilter implements FileFilter, Serializable {
private List<String> excluded = new ArrayList<String>();
public WipeWorkspaceExcludeFilter(String... args) {
for (String arg : args) {
excluded.add(arg);
}
}
public void exclude(String arg) {
excluded.add(arg);
}
public boolean accept(File arg0) {
for (String exclude : excluded) {
if (arg0.getName().equals(exclude)) {
return false;
}
}
return true;
}
}
private static boolean overrideWithBooleanParameter(String paramName, AbstractBuild build, boolean dflt) {
if (build.getBuildVariables() != null) {
Object param = build.getBuildVariables().get(paramName);
if (param != null) {
String paramString = param.toString();
return paramString.toUpperCase().equals("TRUE") || paramString.equals("1");
}
}
return dflt;
}
/*
* @see hudson.scm.SCM#checkout(hudson.model.AbstractBuild, hudson.Launcher, hudson.FilePath, hudson.model.BuildListener, java.io.File)
*/
@Override
public boolean checkout(AbstractBuild build, Launcher launcher,
FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
PrintStream log = listener.getLogger();
changelogFilename = changelogFile.getAbsolutePath();
// HACK: Force build env vars to initialize
MacroStringHelper.substituteParameters("", build, null);
// Use local variables so that substitutions are not saved
String p4Label = MacroStringHelper.substituteParameters(this.p4Label, build, null);
String viewMask = MacroStringHelper.substituteParameters(this.viewMask, build, null);
Depot depot = getDepot(launcher,workspace, build.getProject(), build, build.getBuiltOn());
String p4Stream = MacroStringHelper.substituteParameters(this.p4Stream, build, null);
// Pull from optional named parameters
boolean wipeBeforeBuild = overrideWithBooleanParameter(
"P4CLEANWORKSPACE", build, this.wipeBeforeBuild);
boolean quickCleanBeforeBuild = overrideWithBooleanParameter(
"P4QUICKCLEANWORKSPACE", build, this.quickCleanBeforeBuild);
boolean wipeRepoBeforeBuild = overrideWithBooleanParameter(
"P4CLEANREPOINWORKSPACE", build, this.wipeRepoBeforeBuild);
boolean forceSync = overrideWithBooleanParameter(
"P4FORCESYNC", build, this.forceSync);
boolean disableChangeLogOnly = overrideWithBooleanParameter(
"P4DISABLECHANGELOG", build, this.disableChangeLogOnly);
boolean disableSyncOnly = overrideWithBooleanParameter(
"P4DISABLESYNCONLY", build, this.disableSyncOnly);
disableSyncOnly = overrideWithBooleanParameter(
"P4DISABLESYNC", build, this.disableSyncOnly);
boolean oneChangelistOnly = overrideWithBooleanParameter(
"P4ONECHANGELIST", build, false);
// If we're doing a matrix build, we should always force sync.
if ((Object)build instanceof MatrixBuild || (Object)build instanceof MatrixRun) {
if (!alwaysForceSync && !wipeBeforeBuild)
log.println("This is a matrix build; It is HIGHLY recommended that you enable the " +
"'Always Force Sync' or 'Clean Workspace' options. " +
"Failing to do so will likely result in child builds not being synced properly.");
}
try {
String progName = getEffectiveP4ProgramName();
if (progName != null) {
log.println("p4.prog=" + progName);
if (progName.matches(P4_PROGRAM_NAME_PATTERN)) {
depot.setProgramName(progName);
} else {
log.println("WARNING: p4.prog don't match " + P4_PROGRAM_NAME_PATTERN + " (ignoring it)");
}
}
// keep projectPath local so any modifications for slaves don't get saved
String projectPath;
projectPath = getEffectiveProjectPath(build, build.getProject(), log, depot);
Workspace p4workspace = getPerforceWorkspace(build.getProject(), projectPath, depot, build.getBuiltOn(), build, launcher, workspace, listener, false);
boolean dirtyWorkspace = p4workspace.isDirty();
saveWorkspaceIfDirty(depot, p4workspace, log);
//Wipe/clean workspace
String p4config;
WipeWorkspaceExcludeFilter wipeFilter;
try {
p4config = MacroStringHelper.substituteParameters("${P4CONFIG}", build, null);
wipeFilter = new WipeWorkspaceExcludeFilter(".p4config",p4config);
} catch (ParameterSubstitutionException ex) {
wipeFilter = new WipeWorkspaceExcludeFilter();
}
if (wipeBeforeBuild || quickCleanBeforeBuild) {
long cleanStartTime = System.currentTimeMillis();
if (wipeRepoBeforeBuild) {
log.println("Clear workspace includes .repository ...");
} else {
log.println("Note: .repository directory in workspace (if exists) is skipped during clean.");
wipeFilter.exclude(".repository");
}
if (wipeBeforeBuild) {
log.println("Wiping workspace...");
List<FilePath> workspaceDirs = workspace.list(wipeFilter);
for (FilePath dir : workspaceDirs) {
dir.deleteRecursive();
}
log.println("Wiped workspace.");
forceSync = true;
}
if (quickCleanBeforeBuild) {
QuickCleaner quickCleaner = new QuickCleaner(depot.getExecutable(), depot.getP4Ticket(), launcher, depot, workspace, wipeFilter);
log.println("Quickly cleaning workspace...");
quickCleaner.doClean();
log.println("Workspace is clean.");
if (restoreChangedDeletedFiles) {
log.println("Restoring changed and deleted files...");
quickCleaner.doRestore();
log.println("Files restored.");
}
}
long cleanEndTime = System.currentTimeMillis();
long cleanDuration = cleanEndTime - cleanStartTime;
log.println("Clean complete, took " + cleanDuration + " ms");
}
// In case of a stream depot, we want Perforce to handle the client views. So let's re-initialize
// the p4workspace object if it was changed since the last build. Also, populate projectPath with
// the current view from Perforce. We need it for labeling.
if (useStreamDepot) {
if (dirtyWorkspace) {
// Support for concurrent builds
String p4Client = getConcurrentClientName(workspace, getEffectiveClientName(build, null));
p4workspace = depot.getWorkspaces().getWorkspace(p4Client, p4Stream);
}
projectPath = p4workspace.getTrimmedViewsAsString();
}
// If we're not managing the view, populate the projectPath with the current view from perforce
// This is both for convenience, and so the labeling mechanism can operate correctly
if (!updateView) {
projectPath = p4workspace.getTrimmedViewsAsString();
}
String p4WorkspacePath = "//" + p4workspace.getName() + "/...";
int lastChange = getLastChange((Run)build.getPreviousBuild());
log.println("Last build changeset: " + lastChange);
// Determine changeset number
int newestChange = lastChange;
List<Changelist> changes;
if (p4Label != null && !p4Label.trim().isEmpty()) {
newestChange = depot.getChanges().getHighestLabelChangeNumber(p4workspace, p4Label.trim(), p4WorkspacePath);
} else {