/
ClientHelper.java
1379 lines (1178 loc) · 41.8 KB
/
ClientHelper.java
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 org.jenkinsci.plugins.p4.client;
import com.perforce.p4java.client.IClient;
import com.perforce.p4java.client.IClientSummary.IClientOptions;
import com.perforce.p4java.client.IClientViewMapping;
import com.perforce.p4java.core.IChangelist;
import com.perforce.p4java.core.IChangelistSummary;
import com.perforce.p4java.core.IRepo;
import com.perforce.p4java.core.file.FileAction;
import com.perforce.p4java.core.file.FileSpecBuilder;
import com.perforce.p4java.core.file.FileSpecOpStatus;
import com.perforce.p4java.core.file.IFileSpec;
import com.perforce.p4java.exception.AccessException;
import com.perforce.p4java.exception.ConnectionException;
import com.perforce.p4java.exception.P4JavaException;
import com.perforce.p4java.exception.RequestException;
import com.perforce.p4java.impl.generic.client.ClientView;
import com.perforce.p4java.impl.generic.core.Changelist;
import com.perforce.p4java.impl.generic.core.InputMapper;
import com.perforce.p4java.impl.generic.core.file.FileSpec;
import com.perforce.p4java.option.changelist.SubmitOptions;
import com.perforce.p4java.option.client.AddFilesOptions;
import com.perforce.p4java.option.client.ParallelSyncOptions;
import com.perforce.p4java.option.client.ReconcileFilesOptions;
import com.perforce.p4java.option.client.ReopenFilesOptions;
import com.perforce.p4java.option.client.ResolveFilesAutoOptions;
import com.perforce.p4java.option.client.RevertFilesOptions;
import com.perforce.p4java.option.client.SyncOptions;
import com.perforce.p4java.option.server.ChangelistOptions;
import com.perforce.p4java.option.server.GetChangelistsOptions;
import com.perforce.p4java.option.server.GetFileContentsOptions;
import com.perforce.p4java.option.server.OpenedFilesOptions;
import com.perforce.p4java.server.CmdSpec;
import com.perforce.p4java.server.IServerInfo;
import hudson.AbortException;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.TaskListener;
import org.apache.commons.io.FileUtils;
import org.jenkinsci.plugins.p4.changes.P4ChangeRef;
import org.jenkinsci.plugins.p4.changes.P4GraphRef;
import org.jenkinsci.plugins.p4.changes.P4LabelRef;
import org.jenkinsci.plugins.p4.changes.P4Ref;
import org.jenkinsci.plugins.p4.credentials.P4BaseCredentials;
import org.jenkinsci.plugins.p4.populate.AutoCleanImpl;
import org.jenkinsci.plugins.p4.populate.CheckOnlyImpl;
import org.jenkinsci.plugins.p4.populate.FlushOnlyImpl;
import org.jenkinsci.plugins.p4.populate.ForceCleanImpl;
import org.jenkinsci.plugins.p4.populate.GraphHybridImpl;
import org.jenkinsci.plugins.p4.populate.ParallelSync;
import org.jenkinsci.plugins.p4.populate.Populate;
import org.jenkinsci.plugins.p4.populate.SyncOnlyImpl;
import org.jenkinsci.plugins.p4.publish.CommitImpl;
import org.jenkinsci.plugins.p4.publish.Publish;
import org.jenkinsci.plugins.p4.publish.ShelveImpl;
import org.jenkinsci.plugins.p4.publish.SubmitImpl;
import org.jenkinsci.plugins.p4.tasks.TimeTask;
import org.jenkinsci.plugins.p4.workspace.StaticWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.TemplateWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.Workspace;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import static org.jenkinsci.plugins.p4.console.P4ConsoleAnnotator.COMMAND;
import static org.jenkinsci.plugins.p4.console.P4ConsoleAnnotator.STOP;
public class ClientHelper extends ConnectionHelper {
private static Logger logger = Logger.getLogger(ClientHelper.class.getName());
private IClient iclient;
public ClientHelper(ItemGroup context, String credential, TaskListener listener, Workspace workspace) throws IOException {
super(context, credential, listener);
clientLogin(workspace);
}
public ClientHelper(Item context, String credential, TaskListener listener, Workspace workspace) throws IOException {
super(context, credential, listener);
clientLogin(workspace);
}
public ClientHelper(P4BaseCredentials credential, TaskListener listener, Workspace workspace) throws IOException {
super(credential, listener);
clientLogin(workspace);
}
// reserved for TempClientHelper
protected ClientHelper(Item context, String credential, TaskListener listener) throws IOException {
super(context, credential, listener);
}
protected void clientLogin(Workspace workspace) throws AbortException {
// Exit early if no connection
if (getConnection() == null) {
return;
}
// Find workspace and set as current
try {
// Setup charset for unicode servers
if (isUnicode()) {
getConnection().setCharsetName(workspace.getCharset());
}
login();
// Setup/Create workspace based on type
iclient = workspace.setClient(getConnection(), getAuthorisationConfig().getUsername());
// Set as Current Client, or exit early if not defined
if (!isClientValid(workspace)) {
String err = "P4: Undefined workspace: " + workspace.getFullName();
throw new AbortException(err);
} else {
getConnection().setCurrentClient(iclient);
}
// Exit early if client is Static Workspace
if (workspace instanceof StaticWorkspaceImpl) {
return;
}
// Ensure root and host fields are not null
if (workspace.getRootPath() != null) {
iclient.setRoot(workspace.getRootPath());
}
if (workspace.getHostName() != null) {
iclient.setHostName(workspace.getHostName());
}
// Set client Server ID if not already defined in the client spec.
String serverId = iclient.getServerId();
if (serverId == null || serverId.isEmpty()) {
IServerInfo info = getConnection().getServerInfo();
String services = getServerServices();
serverId = info.getServerId();
if (serverId != null && !serverId.isEmpty() && isEdgeType(services)) {
iclient.setServerId(serverId);
}
}
// Save client spec
updateClient();
} catch (Exception e) {
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
e.printStackTrace(printWriter);
String err = "P4: Unable to setup workspace: " + writer.toString();
logger.severe(err);
log(err);
throw new AbortException(e.getMessage());
}
}
private void updateClient() throws Exception {
// exit early if no change
String clientName = iclient.getName();
IClient original = getConnection().getClient(clientName);
if (diffClient(original, iclient)) {
return;
}
iclient.update();
ClientView clientView = iclient.getClientView();
// Log client view...
if (clientView != null) {
StringBuffer sb = new StringBuffer("... View:\n");
for (IClientViewMapping view : clientView) {
sb.append(" ");
if (view.getType() != null)
sb.append(view.getType().toString());
sb.append(view.getLeft());
sb.append(" ");
sb.append(view.getRight());
sb.append("\n");
}
if ( iclient.getStream() != null ) {
sb.append("... Stream: " + iclient.getStream());
sb.append("\n");
}
sb.append("... Root: " + iclient.getRoot());
sb.append("\n");
logger.finer(sb.toString());
sb.insert(0, COMMAND);
sb.append(STOP);
log(sb.toString());
}
}
private boolean diffClient(IClient a, IClient b) {
if (a == null || b == null) {
return false;
}
Map<String, Object> mapA = InputMapper.map(a);
List<String> valuesA = cleanMap(mapA);
Map<String, Object> mapB = InputMapper.map(b);
List<String> valuesB = cleanMap(mapB);
return valuesA.equals(valuesB);
}
private List<String> cleanMap(Map<String, Object> map) {
// remove empty fields
String[] unset = new String[]{"Host", "Stream"};
for (String key : unset) {
if ("".equals(map.get(key))) {
map.remove(key);
}
}
// remove set fields
String[] set = new String[]{"Type"};
for (String key : set) {
map.remove(key);
}
List<String> values = new ArrayList(map.values());
values.removeAll(Collections.singleton(null));
values.removeAll(Collections.singleton(""));
Collections.sort(values);
return values;
}
private boolean isEdgeType(String services) {
if (services == null || services.isEmpty()) {
return false;
}
if (services.contains("edge-server")) {
return true;
}
if (services.contains("workspace-server")) {
return true;
}
if (services.contains("build-server")) {
return true;
}
return false;
}
// TODO remove when P4Java has support for 'serverServices'
private String getServerServices() throws ConnectionException, AccessException {
List<Map<String, Object>> mapList = getConnection().execMapCmdList(CmdSpec.INFO, new String[]{}, null);
for (Map<String, Object> map : mapList) {
if (map.containsKey("serverServices")) {
return (String) map.get("serverServices");
}
}
return "";
}
/**
* Sync files to workspace at the specified change/label.
*
* @param buildChange Change to sync from
* @param populate Populate strategy
* @throws Exception push up stack
*/
public void syncFiles(P4Ref buildChange, Populate populate) throws Exception {
TimeTask timer = new TimeTask();
// test label is valid
if (buildChange.isLabel()) {
String label = buildChange.toString();
try {
int change = Integer.parseInt(label);
log("P4 Task: label is a number! syncing files at change: " + change);
} catch (NumberFormatException e) {
if (!label.equals("now") && !isLabel(label) && !isClient(label) && !isCounter(label)) {
String msg = "P4: Unable to find client/label/counter: " + label;
log(msg);
logger.warning(msg);
throw new AbortException(msg);
} else {
log("P4 Task: syncing files at client/label: " + label);
}
}
} else {
log("P4 Task: syncing files at change: " + buildChange);
}
// Sync changes/labels
if (buildChange instanceof P4ChangeRef || buildChange instanceof P4LabelRef) {
// build file revision spec
String path = iclient.getRoot() + "/...";
String revisions = path + "@" + buildChange;
// Sync files
if (populate instanceof CheckOnlyImpl) {
syncPreview(revisions, populate);
} else if (populate instanceof FlushOnlyImpl) {
syncHaveList(revisions, populate);
} else {
syncFiles(revisions, populate);
}
}
// Sync graph repos
if (buildChange instanceof P4GraphRef && populate instanceof GraphHybridImpl) {
String rev = ((P4GraphRef) buildChange).getRepo() + "/...";
syncFiles(rev, populate);
}
log("duration: " + timer.toString() + "\n");
}
/**
* Preview a sync, no have list update and no files
* <p>
* p4 sync -n ...
*
* @param revisions Perforce path and revision
* @param populate Populate options
* @throws Exception
*/
private void syncPreview(String revisions, Populate populate) throws Exception {
SyncOptions syncOpts = new SyncOptions();
syncOpts.setNoUpdate(true);
// Skip `p4 sync -q -n` to save compute time.
if (populate.isQuiet()) {
log("P4 Task: skipping sync.");
return;
}
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(revisions);
List<IFileSpec> syncMsg = iclient.sync(files, syncOpts);
getValidate().check(syncMsg, "file(s) up-to-date.", "file does not exist", "no file(s) as of that date");
}
/**
* Populate the have list, but no files.
* <p>
* p4 sync -k (p4 flush)
*
* @param revisions Perforce path and revision
* @param populate Populate options
* @throws Exception
*/
private void syncHaveList(String revisions, Populate populate) throws Exception {
SyncOptions syncOpts = new SyncOptions();
syncOpts.setClientBypass(true);
syncOpts.setQuiet(populate.isQuiet());
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(revisions);
List<IFileSpec> syncMsg = iclient.sync(files, syncOpts);
getValidate().check(syncMsg, "file(s) up-to-date.", "file does not exist", "no file(s) as of that date");
}
/**
* Sync files with various populate options.
*
* @param revisions Perforce path and revision
* @param populate Populate options
* @throws Exception
*/
private void syncFiles(String revisions, Populate populate) throws Exception {
// set MODTIME if populate options is used only required before 15.1
if (populate.isModtime() && !checkVersion(20151)) {
IClientOptions options = iclient.getOptions();
if (!options.isModtime()) {
options.setModtime(true);
iclient.setOptions(options);
// Save client spec
updateClient();
}
}
// sync options
SyncOptions syncOpts = new SyncOptions();
// setServerBypass (-p no have list)
syncOpts.setServerBypass(!populate.isHave());
// setForceUpdate (-f only if no -p is set)
syncOpts.setForceUpdate(populate.isForce() && populate.isHave());
syncOpts.setQuiet(populate.isQuiet());
// Sync files with asynchronous callback and parallel if enabled to
SyncStreamingCallback callback = new SyncStreamingCallback(iclient.getServer(), getListener());
synchronized (callback) {
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(revisions);
ParallelSync parallel = populate.getParallel();
if (parallel != null && parallel.isEnable()) {
ParallelSyncOptions parallelOpts = parallel.getParallelOptions();
iclient.syncParallel(files, syncOpts, callback, 0, parallelOpts);
} else {
iclient.sync(files, syncOpts, callback, 0);
}
while (!callback.isDone()) {
callback.wait();
}
if (callback.isFail()) {
throw new P4JavaException(callback.getException());
}
}
}
/**
* Cleans up the Perforce workspace after a previous build. Removes all
* pending and abandoned files (equivalent to 'p4 revert -w').
*
* @param populate Jelly populate options
* @throws Exception push up stack
*/
public void tidyWorkspace(Populate populate) throws Exception {
// relies on workspace view for scope.
log("");
String path = iclient.getRoot() + "/...";
if (populate instanceof AutoCleanImpl) {
tidyAutoCleanImpl(path, populate);
}
if (populate instanceof ForceCleanImpl) {
tidyForceSyncImpl(path, populate);
}
if (populate instanceof GraphHybridImpl) {
tidyForceSyncImpl(path, populate);
}
if (populate instanceof SyncOnlyImpl) {
tidySyncOnlyImpl(path, populate);
}
}
private void tidySyncOnlyImpl(String path, Populate populate) throws Exception {
SyncOnlyImpl syncOnly = (SyncOnlyImpl) populate;
if (syncOnly.isRevert()) {
tidyPending(path);
}
}
private void tidyForceSyncImpl(String path, Populate populate) throws Exception {
// remove all pending files within workspace
tidyPending(path);
// remove all versioned files (clean have list)
String revisions = iclient.getRoot() + "/...#0";
// Only use quiet populate option to insure a clean sync
boolean quiet = populate.isQuiet();
Populate clean = new AutoCleanImpl(false, false, false, false, quiet, null, null);
syncFiles(revisions, clean);
// remove all files from workspace
String root = URLDecoder.decode(iclient.getRoot(), "UTF-8");
log("... rm -rf " + root);
log("");
silentlyForceDelete(root);
}
private void silentlyForceDelete(String root) throws IOException {
try {
FileUtils.forceDelete(new File(root));
} catch (FileNotFoundException ignored) {
}
}
private void tidyAutoCleanImpl(String path, Populate populate) throws Exception {
// remove all pending files within workspace
tidyPending(path);
// clean files within workspace
tidyClean(populate, path);
}
private void tidyPending(String path) throws Exception {
TimeTask timer = new TimeTask();
log("P4 Task: reverting all pending and shelved revisions.");
// revert all pending and shelved revisions
RevertFilesOptions rOpts = new RevertFilesOptions();
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(path);
List<IFileSpec> list = iclient.revertFiles(files, rOpts);
getValidate().check(list, "not opened on this client", "Replica does not support this command");
// check for added files and remove...
log("... rm [abandoned files]");
for (IFileSpec file : list) {
if (file.getAction() == FileAction.ABANDONED) {
// first check if we have the local path
String local = file.getLocalPathString();
if (local == null) {
local = depotToLocal(file);
}
if (local != null) {
File unlink = new File(local);
boolean ok = unlink.delete();
if (!ok) {
log("Not able to delete: " + local);
}
}
}
}
log("duration: " + timer.toString() + "\n");
}
private void tidyClean(Populate populate, String path) throws Exception {
// Use old method if 'p4 clean' is not supported
if (!checkVersion(20141)) {
tidyRevisions(path, populate);
return;
}
// Set options
boolean delete = ((AutoCleanImpl) populate).isDelete();
boolean replace = ((AutoCleanImpl) populate).isReplace();
ReconcileFilesOptions cleanOpts = new ReconcileFilesOptions();
cleanOpts.setUpdateWorkspace(true);
cleanOpts.setUseWildcards(true);
if (delete && !replace) {
cleanOpts.setOutsideAdd(true);
}
if (replace && !delete) {
cleanOpts.setOutsideEdit(true);
cleanOpts.setRemoved(true);
}
if (!replace && !delete) {
log("P4 Task: skipping clean, no options set.");
return;
}
// set MODTIME if populate options is used and server supports flag
if (populate.isModtime()) {
if (checkVersion(20141)) {
cleanOpts.setCheckModTime(true);
} else {
log("P4: Resolving files by MODTIME not supported (requires 2014.1 or above)");
}
}
TimeTask timer = new TimeTask();
log("P4 Task: cleaning workspace to match have list.");
// Reconcile with asynchronous callback
ReconcileStreamingCallback callback = new ReconcileStreamingCallback(iclient.getServer(), getListener());
synchronized (callback) {
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(path);
iclient.reconcileFiles(files, cleanOpts, callback, 0);
while (!callback.isDone()) {
callback.wait();
}
if (callback.isFail()) {
throw new P4JavaException(callback.getException());
}
}
log("duration: " + timer.toString() + "\n");
}
private void tidyRevisions(String path, Populate populate) throws Exception {
TimeTask timer = new TimeTask();
log("P4 Task: tidying workspace to match have list.");
boolean delete = ((AutoCleanImpl) populate).isDelete();
boolean replace = ((AutoCleanImpl) populate).isReplace();
// check status - find all missing, changed or added files
String[] base = {"-n", "-a", "-e", "-d", "-l", "-f"};
List<String> list = new ArrayList<String>();
list.addAll(Arrays.asList(base));
String[] args = list.toArray(new String[list.size()]);
ReconcileFilesOptions statusOpts = new ReconcileFilesOptions(args);
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(path);
List<IFileSpec> status = iclient.reconcileFiles(files, statusOpts);
getValidate().check(status, "also opened by", "no file(s) to reconcile", "must sync/resolve",
"exclusive file already opened", "cannot submit from stream", "instead of", "empty, assuming text");
// Add missing, modified or locked files to a list, and delete the
// unversioned files.
List<IFileSpec> update = new ArrayList<IFileSpec>();
for (IFileSpec s : status) {
if (s.getOpStatus() == FileSpecOpStatus.VALID) {
String local = s.getLocalPathString();
if (local == null) {
local = depotToLocal(s);
}
switch (s.getAction()) {
case ADD:
if (local != null && delete) {
File unlink = new File(local);
boolean ok = unlink.delete();
if (!ok) {
log("Not able to delete: " + local);
}
}
break;
default:
update.add(s);
break;
}
} else {
String msg = s.getStatusMessage();
if (msg.contains("exclusive file already opened")) {
String rev = msg.substring(0, msg.indexOf(" - can't "));
IFileSpec spec = new FileSpec(rev);
update.add(spec);
}
}
}
// Force sync missing and modified files
if (!update.isEmpty() && replace) {
SyncOptions syncOpts = new SyncOptions();
syncOpts.setForceUpdate(true);
syncOpts.setQuiet(populate.isQuiet());
List<IFileSpec> syncMsg = iclient.sync(update, syncOpts);
getValidate().check(syncMsg, "file(s) up-to-date.", "file does not exist");
}
log("duration: " + timer.toString() + "\n");
}
public void revertAllFiles(boolean virtual) throws Exception {
String path = iclient.getRoot() + "/...";
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(path);
// revert all pending and shelved revisions
RevertFilesOptions rOpts = new RevertFilesOptions();
rOpts.setNoClientRefresh(virtual);
List<IFileSpec> list = iclient.revertFiles(files, rOpts);
getValidate().check(list, "not opened on this client", "Replica does not support this command");
}
public void versionFile(String file, Publish publish, int ChangelistID, boolean submit) throws Exception {
// build file revision spec
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(file);
findChangeFiles(files, publish.isDelete(), publish.isModtime());
// Exit early if no change
if (!isOpened(files)) {
return;
}
// create/append changelist with files
IChangelist change = appendPendingChangeList(files, publish, ChangelistID);
// submit changelist
if (submit) {
submitFiles(change, false);
}
}
public boolean buildChange(Publish publish) throws Exception {
TimeTask timer = new TimeTask();
log("P4 Task: reconcile files to changelist.");
List<IFileSpec> files;
if (publish instanceof CommitImpl) {
CommitImpl commit = (CommitImpl) publish;
files = FileSpecBuilder.makeFileSpecList(commit.getFiles());
AddFilesOptions opts = new AddFilesOptions();
iclient.addFiles(files, opts);
} else {
// build file revision spec
String clientBase = "//" + iclient.getName() + "/";
List<String> paths = buildPaths(publish, clientBase);
files = FileSpecBuilder.makeFileSpecList(paths);
findChangeFiles(files, publish.isDelete(), publish.isModtime());
}
// Check if file is open
boolean open = isOpened(files);
log("duration: " + timer.toString() + "\n");
return open;
}
private List<String> buildPaths(Publish publish, String clientBase) {
List<String> list = new ArrayList<>();
String rawPaths = publish.getPaths();
if (rawPaths == null || rawPaths.isEmpty()) {
list.add(clientBase + "...");
return list;
}
String[] array = rawPaths.split("\n\\s*");
for(String a : array) {
if(a.startsWith("//")) {
list.add(a);
} else {
list.add(clientBase + a);
}
}
return list;
}
private void findChangeFiles(List<IFileSpec> files, boolean delete, boolean modtime) throws Exception {
// cleanup pending changes (revert -k)
RevertFilesOptions revertOpts = new RevertFilesOptions();
revertOpts.setNoClientRefresh(true);
List<IFileSpec> revertStat = iclient.revertFiles(files, revertOpts);
getValidate().check(revertStat, "file(s) not opened on this client.");
// flush client to populate have (sync -k)
SyncOptions syncOpts = new SyncOptions();
syncOpts.setClientBypass(true);
List<IFileSpec> syncStat = iclient.sync(files, syncOpts);
getValidate().check(syncStat, "file(s) up-to-date.", "no such file(s).");
// check status - find all changes to files
ReconcileFilesOptions statusOpts = new ReconcileFilesOptions();
statusOpts.setCheckModTime(modtime);
statusOpts.setUseWildcards(true);
statusOpts.setOutsideAdd(true);
statusOpts.setOutsideEdit(true);
statusOpts.setRemoved(delete);
List<IFileSpec> status = iclient.reconcileFiles(files, statusOpts);
getValidate().check(status, "- no file(s) to reconcile", "instead of", "empty, assuming text", "also opened by");
}
public String publishChange(Publish publish) throws Exception {
String id = null;
TimeTask timer = new TimeTask();
log("P4 Task: publish files to Perforce.");
// build file revision spec
String ws = "//" + iclient.getName() + "/...";
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(ws);
// create changelist and open files
IChangelist change = appendPendingChangeList(files, publish, IChangelist.DEFAULT);
// logging
OpenedFilesOptions openOps = new OpenedFilesOptions();
List<IFileSpec> open = iclient.openedFiles(files, openOps);
for (IFileSpec f : open) {
FileAction action = f.getAction();
String path = f.getDepotPathString();
log("... ... " + action + " " + path);
}
// if SUBMIT
if (publish instanceof SubmitImpl) {
SubmitImpl submit = (SubmitImpl) publish;
boolean reopen = submit.isReopen();
long c = submitFiles(change, reopen);
id = Long.toString(c);
}
// if SHELVE
if (publish instanceof ShelveImpl) {
ShelveImpl shelve = (ShelveImpl) publish;
boolean revert = shelve.isRevert();
long c = shelveFiles(change, files, revert);
id = Long.toString(c);
}
// if COMMIT
if (publish instanceof CommitImpl) {
CommitImpl commit = (CommitImpl) publish;
id = commitFiles(change);
}
log("duration: " + timer.toString() + "\n");
return id;
}
private IChangelist appendPendingChangeList(List<IFileSpec> files, Publish publish, int ChangeListID) throws Exception {
String desc = publish.getExpandedDesc();
if (ChangeListID == IChangelist.UNKNOWN || ChangeListID == IChangelist.DEFAULT) {
// create new pending change and add description
IChangelist change = new Changelist();
change.setDescription(desc);
change = iclient.createChangelist(change);
ChangeListID = change.getId();
}
log("... pending change: " + ChangeListID);
// move files from default change
ReopenFilesOptions reopenOpts = new ReopenFilesOptions();
reopenOpts.setChangelistId(ChangeListID);
// set purge if required
if (publish instanceof SubmitImpl) {
SubmitImpl submit = (SubmitImpl) publish;
int purge = submit.getPurgeValue();
if (purge > 0) {
reopenOpts.setFileType("+S" + purge);
}
}
iclient.reopenFiles(files, reopenOpts);
return getChange(ChangeListID);
}
private long submitFiles(IChangelist change, boolean reopen) throws Exception {
log("... submitting files");
SubmitOptions submitOpts = new SubmitOptions();
submitOpts.setReOpen(reopen);
// submit with asynchronous callback
SubmitStreamingCallback callback = new SubmitStreamingCallback(iclient.getServer(), getListener());
synchronized (callback) {
change.submit(submitOpts, callback, 0);
while (!callback.isDone()) {
callback.wait();
}
}
if (callback.isFail()) {
throw new P4JavaException(callback.getException());
}
long cngNumber = callback.getChange();
if (cngNumber > 0) {
log("... submitted in change: " + cngNumber);
} else {
throw new P4JavaException("Unable to submit change.");
}
return cngNumber;
}
private String commitFiles(IChangelist change) throws Exception {
log("... committing files");
List<String> opts = new ArrayList<>();
opts.add("-c");
opts.add(String.valueOf(change.getId()));
String[] args = opts.toArray(new String[opts.size()]);
Map<String, Object>[] results = getConnection().execMapCmd(CmdSpec.SUBMIT.name(), args, null);
for (Map<String, Object> map : results) {
if (map.containsKey("submittedCommit")) {
String sha = (String) map.get("submittedCommit");
log("... committing SHA: " + sha);
return sha;
}
}
throw new P4JavaException("Unable to commit change.");
}
private long shelveFiles(IChangelist change, List<IFileSpec> files, boolean revert) throws Exception {
log("... shelving files");
List<IFileSpec> shelved = iclient.shelveChangelist(change);
getValidate().check(shelved, "");
// post shelf cleanup
RevertFilesOptions revertOpts = new RevertFilesOptions();
revertOpts.setChangelistId(change.getId());
revertOpts.setNoClientRefresh(!revert);
String r = (revert) ? "(revert)" : "(revert -k)";
log("... reverting open files " + r);
iclient.revertFiles(files, revertOpts);
return change.getId();
}
private boolean isOpened(List<IFileSpec> files) throws Exception {
OpenedFilesOptions openOps = new OpenedFilesOptions();
List<IFileSpec> open = iclient.openedFiles(files, openOps);
for (IFileSpec file : open) {
if (file != null && file.getAction() != null) {
return true;
}
}
return false;
}
/**
* Workaround for p4java bug. The 'setLocalSyntax(true)' option does not
* provide local syntax, so I have to use 'p4 where' to translate through
* the client view.
*
* @param fileSpec Perforce file spec
* @return Local syntax
* @throws Exception push up stack
*/
private String depotToLocal(IFileSpec fileSpec) throws Exception {
String depotPath = fileSpec.getDepotPathString();
if (depotPath == null) {
depotPath = fileSpec.getOriginalPathString();
}
if (depotPath == null) {
return null;
}
List<IFileSpec> dSpec = FileSpecBuilder.makeFileSpecList(depotPath);
List<IFileSpec> lSpec = iclient.where(dSpec);
String path = lSpec.get(0).getLocalPathString();
return path;
}
private String localToDepot(IFileSpec fileSpec) throws Exception {
String depotPath = fileSpec.getDepotPathString();
if (depotPath == null) {
depotPath = fileSpec.getOriginalPathString();
}
if (depotPath == null) {
return null;
}
List<IFileSpec> dSpec = FileSpecBuilder.makeFileSpecList(depotPath);
List<IFileSpec> lSpec = iclient.where(dSpec);
String path = lSpec.get(0).getDepotPathString();
return path;
}
private void deleteFile(String rev) throws Exception {
List<IFileSpec> file = FileSpecBuilder.makeFileSpecList(rev);
String local = depotToLocal(file.get(0));
File unlink = new File(local);
if (unlink.exists()) {
boolean ok = unlink.delete();
if (!ok) {
log("Not able to delete: " + local);
}
}
}
private void printFile(String rev) throws Exception {
byte[] buf = new byte[1024 * 64];
List<IFileSpec> file = FileSpecBuilder.makeFileSpecList(rev);
GetFileContentsOptions printOpts = new GetFileContentsOptions();
printOpts.setNoHeaderLine(true);
InputStream ins = getConnection().getFileContents(file, printOpts);
String localPath = depotToLocal(file.get(0));
File target = new File(localPath);
// Create directories as required JENKINS-37868
if (target.getParentFile().mkdirs()) {
log("Directory created: " + target);
}
// Make writable if it exists
if (target.exists()) {
target.setWritable(true);
}
FileOutputStream outs = new FileOutputStream(target);
BufferedOutputStream bouts = new BufferedOutputStream(outs);
int len;
while ((len = ins.read(buf)) > 0) {
bouts.write(buf, 0, len);
}
ins.close();
bouts.close();
}
/**
* Unshelve review into workspace. Workspace is sync'ed to head first then
* review unshelved.
*
* @param review Review number (perhaps long?)
* @throws Exception push up stack
*/
public void unshelveFiles(long review) throws Exception {
// skip if review is 0 or less
if (review < 1) {
log("P4 Task: skipping review: " + review);
return;