-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathptc-cli.sh
More file actions
executable file
·3429 lines (3016 loc) · 134 KB
/
Copy pathptc-cli.sh
File metadata and controls
executable file
·3429 lines (3016 loc) · 134 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
#!/bin/bash
# PTC CLI - Private Translation Cloud CLI
# Processes translation files based on language patterns
set -euo pipefail # Strict mode: exit on errors, undefined variables and pipe errors
# Constants
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_NAME="$(basename "$0")"
readonly VERSION="1.0.6"
readonly PTC_USER_AGENT="ptc-cli/${VERSION}"
# Colors for output
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly CYAN='\033[0;36m'
readonly NC='\033[0m' # No Color
# Default variables with PTC_ prefix to avoid conflicts
PTC_SOURCE_LOCALE=""
PTC_PATTERNS=()
PTC_CONFIG_FILE=""
PTC_PROJECT_DIR="$(pwd)"
PTC_FILE_TAG_NAME=""
PTC_API_URL="https://app.ptc.wpml.org/api/v1/"
# The API token is env-first: an inherited PTC_API_TOKEN is honoured across every
# command, and --api-token overrides it. The api_token: config key is deprecated
# and ignored, so there is nothing else to reconcile — do NOT reset
# this to "", or the translate pipeline would lose the env token.
PTC_API_TOKEN="${PTC_API_TOKEN:-}"
PTC_VERBOSE=false
PTC_DRY_RUN=false
PTC_MONITOR_INTERVAL=5 # seconds between status checks
PTC_MONITOR_MAX_ATTEMPTS=100 # maximum number of status checks
PTC_ACTION="" # specific action to perform: upload, status, download
# Where to record every file this run writes, for a CI job that must commit the
# translations and nothing else. Empty means "do not record".
PTC_WRITTEN_MANIFEST=""
# Logging functions
log_info() {
echo -e "${BLUE}[INFO]${NC} $*" >&2
}
log_success() {
echo -e "${GREEN}[SUCCESS]${NC} $*" >&2
}
log_warning() {
echo -e "${YELLOW}[WARNING]${NC} $*" >&2
}
log_error() {
echo -e "${RED}[ERROR]${NC} $*" >&2
}
log_debug() {
if [[ "$PTC_VERBOSE" == "true" ]]; then
echo -e "${BLUE}[DEBUG]${NC} $*" >&2
fi
}
# All PTC API requests go through this wrapper so every call carries a versioned
# User-Agent (ptc-cli/<VERSION>). It forwards to the real curl - which the test
# suites stub - so the header rides along as an ordinary -H the stubs already skip.
ptc_curl() {
# PTC_HEADER_DUMP lets a caller read response headers without every call
# site having to thread a -D through its own curl invocation. Only the
# rate-limit retry sets it; everything else runs exactly as before.
if [[ -n "${PTC_HEADER_DUMP:-}" ]]; then
curl -H "User-Agent: $PTC_USER_AGENT" -D "$PTC_HEADER_DUMP" "$@"
else
curl -H "User-Agent: $PTC_USER_AGENT" "$@"
fi
}
# --- rate limiting -----------------------------------------------------------
# create + process + bulk share ONE bucket of PTC_RATE_LIMIT_HINT requests per
# minute, and a run spends two of them per file, so any project past a handful
# of files meets a 429 partway through. Failing there is the worst outcome
# available: the files uploaded before it are already registered and the words
# may already be paid for, so the run must wait rather than abort.
readonly PTC_RATE_LIMIT_MAX_RETRIES=5
readonly PTC_RATE_LIMIT_BASE_DELAY=15
readonly PTC_RATE_LIMIT_MAX_DELAY=60
# Internal signal between a request function and the retry wrapper. It never
# reaches the shell: the wrapper turns it into 0 (recovered) or 1 (gave up).
readonly PTC_RATE_LIMITED=8
# Seconds to wait before attempt N. Honours Retry-After when the server sends
# one; PTC does not today (checked 2026-08-04), so the fallback walks towards
# the one-minute window the limit is measured over.
rate_limit_delay() {
local attempt="$1" header_file="${2:-}"
local retry_after=""
if [[ -n "$header_file" && -f "$header_file" ]]; then
retry_after=$(grep -i '^retry-after:' "$header_file" 2>/dev/null \
| tail -n 1 | tr -d '\r' \
| sed -E 's/^[Rr]etry-[Aa]fter:[[:space:]]*//')
fi
if [[ "$retry_after" =~ ^[0-9]+$ ]] && (( retry_after > 0 )); then
(( retry_after > 300 )) && retry_after=300 # a bad header must not hang the job
printf '%s' "$retry_after"
return 0
fi
local delay=$(( PTC_RATE_LIMIT_BASE_DELAY * attempt ))
(( delay > PTC_RATE_LIMIT_MAX_DELAY )) && delay=$PTC_RATE_LIMIT_MAX_DELAY
printf '%s' "$delay"
}
# Runs a request function, waiting out HTTP 429 instead of failing on it.
# The function must return PTC_RATE_LIMITED to ask for a retry; any other exit
# status is passed straight through, so non-429 failures still fail fast.
call_with_rate_limit_retry() {
local attempt=1 delay rc header_dump=""
header_dump=$(mktemp "${TMPDIR:-/tmp}/ptc-headers.XXXXXX" 2>/dev/null) || header_dump=""
while :; do
PTC_HEADER_DUMP="$header_dump" "$@"
rc=$?
if (( rc != PTC_RATE_LIMITED )); then
[[ -n "$header_dump" ]] && rm -f "$header_dump"
return $rc
fi
if (( attempt > PTC_RATE_LIMIT_MAX_RETRIES )); then
[[ -n "$header_dump" ]] && rm -f "$header_dump"
log_error "PTC is still rate limiting after $PTC_RATE_LIMIT_MAX_RETRIES retries; giving up."
log_info "The limit is per organization, so another job or a teammate may be sending requests too."
return 1
fi
delay=$(rate_limit_delay "$attempt" "$header_dump")
log_warning "PTC rate limit reached (HTTP 429). Waiting ${delay}s, then retry ${attempt} of ${PTC_RATE_LIMIT_MAX_RETRIES}."
sleep "$delay"
attempt=$(( attempt + 1 ))
done
}
# JSON field readers. The API returns compact JSON today, but these tolerate
# pretty-printed output and arbitrary whitespace around the separator so a
# serializer or proxy change cannot silently break status parsing.
# A missing key, or an explicit null, yields an empty string.
json_string_field() {
local json="$1"
local key="$2"
local match
# ([^"\]|\\.)* keeps backslash-escaped quotes inside the value instead of
# ending the match at the first one.
match=$(printf '%s' "$json" | tr '\n' ' ' \
| grep -Eo "\"${key}\"[[:space:]]*:[[:space:]]*(\"([^\"\\\\]|\\\\.)*\"|null)" \
| head -n 1) || true
if [[ -z "$match" ]]; then
return 0
fi
local value
value=$(printf '%s' "$match" | sed -E "s/^\"${key}\"[[:space:]]*:[[:space:]]*//")
# Test for JSON null BEFORE unquoting, so that the *string* "null" - which
# the codebase treats as a real status - does not collapse to empty.
if [[ "$value" == "null" ]]; then
return 0
fi
printf '%s' "$value" | sed -E 's/^"(.*)"$/\1/'
}
json_number_field() {
local json="$1"
local key="$2"
local match
match=$(printf '%s' "$json" | tr '\n' ' ' \
| grep -Eo "\"${key}\"[[:space:]]*:[[:space:]]*-?[0-9]+(\.[0-9]+)?" \
| head -n 1) || true
if [[ -n "$match" ]]; then
printf '%s' "$match" | sed -E "s/^\"${key}\"[[:space:]]*:[[:space:]]*//"
fi
}
json_bool_field() {
local json="$1"
local key="$2"
local match
match=$(printf '%s' "$json" | tr '\n' ' ' \
| grep -Eo "\"${key}\"[[:space:]]*:[[:space:]]*(true|false)" \
| head -n 1) || true
if [[ -n "$match" ]]; then
printf '%s' "$match" | sed -E "s/^\"${key}\"[[:space:]]*:[[:space:]]*//"
fi
}
# A rejected request reaches us in one of two shapes, depending on
# which server build answers:
#
# older: HTTP 200 + {"success":false,"message":"Unprocessable Entity","code":422,...}
# newer: HTTP 422 + the same body
#
# Trusting the status alone reads the first shape as success. That is how a
# rejected `process` call used to print "processing started successfully" and
# leave CI green with no translations, and how `download` used to save the JSON
# error body as a .zip and try to unpack it. Deployments will not
# flip on the same day, so the CLI has to read both the same way - the body is
# the authority when it disagrees with the status.
#
# Returns 0 (true, in shell terms) when the response is a failure.
response_indicates_failure() {
local http_code="$1" body="${2:-}"
# Anything outside 2xx is a failure regardless of what the body claims.
if [[ ! "$http_code" =~ ^2[0-9][0-9]$ ]]; then
return 0
fi
# A 2xx that carries an explicit "success": false is the older shape.
[[ "$(json_bool_field "$body" "success")" == "false" ]]
}
# Human-readable reason for a rejected response, for the log line that follows.
# The API answers with a numeric code array (`"errors":[1]`) and no prose, so
# there is a limit to how specific this can be - surface what there is rather
# than dropping it.
describe_api_failure() {
local http_code="$1" body="${2:-}"
local message error codes
message=$(json_string_field "$body" "message")
# Several endpoints answer with a plain {"error": "..."} instead of the
# {"message", "errors"} envelope - source_files#create and #process among
# them. Reading only "message" turned those into a bare "HTTP 422" in the
# CI log, which is the one place the reason was needed.
error=$(json_string_field "$body" "error")
codes=$(printf '%s' "$body" | tr '\n' ' ' \
| grep -Eo '"errors"[[:space:]]*:[[:space:]]*\[[^]]*\]' \
| head -n 1 | sed -E 's/^"errors"[[:space:]]*:[[:space:]]*//') || true
local description="HTTP $http_code"
if [[ -n "$message" ]]; then
description="$description: $message"
# Both keys present and different: keep each, they say different things.
[[ -n "$error" && "$error" != "$message" ]] && description="$description ($error)"
elif [[ -n "$error" ]]; then
description="$description: $error"
fi
[[ -n "$codes" ]] && description="$description (error codes: $codes)"
printf '%s' "$description"
}
# Returns a nested object as raw JSON, so a caller can read a field from it
# without colliding with a same-named key elsewhere in the document
# (for example "iso", which appears in both source_language and languages[]).
# Tolerates one level of nesting inside the object; a regex cannot balance
# braces to arbitrary depth, so callers must treat "" as "could not read it"
# rather than as "the key was absent".
json_object_field() {
local json="$1"
local key="$2"
local match
match=$(printf '%s' "$json" | tr '\n' ' ' \
| grep -Eo "\"${key}\"[[:space:]]*:[[:space:]]*\{[^{}]*(\{[^{}]*\}[^{}]*)*\}" \
| head -n 1) || true
if [[ -n "$match" ]]; then
printf '%s' "$match" | sed -E "s/^\"${key}\"[[:space:]]*:[[:space:]]*//"
fi
}
# Reads a response header by name, case-insensitively. Takes the last match so
# that a redirect's earlier header block cannot win.
http_header_value() {
local header_file="$1"
local name="$2"
local match
match=$(grep -i "^${name}:" "$header_file" 2>/dev/null | tail -n 1) || true
if [[ -n "$match" ]]; then
printf '%s' "$match" | sed -E 's/^[^:]*:[[:space:]]*//' | tr -d '\r'
fi
}
# Statuses that will never turn into "completed", however long we poll.
# Polling one of these to the attempt limit is what made failures look like
# ~8-minute timeouts. These are the two terminal entries of the server's
# STATUS_PRIORITY list (TranslationMemory::STATUS_PRIORITY =
# failed, out_of_credit, queued, in_progress, completed), and both are reachable
# on /api/v1 - "failed" wins first, since the server reports worst-status-wins.
is_terminal_failure_status() {
case "$1" in
failed|out_of_credit)
return 0
;;
*)
return 1
;;
esac
}
# Decides what a monitoring loop should do with one file's status, and explains
# itself on the way out. Both step-based loops share this so a new status only
# has to be classified once - the two loops previously carried byte-identical
# copies of this logic, which is how the terminal case reached one caller and
# not the other.
# Returns: 0 = ready to download, 1 = give up on this file, 2 = keep polling.
classify_monitored_status() {
local status="$1"
local relative_file_path="$2"
if [[ "$status" == "completed" ]]; then
return 0
fi
if is_terminal_failure_status "$status"; then
log_error "Translation failed for $relative_file_path (status: $status)"
return 1
fi
case "$status" in
error|not_found)
# Could be transient - the status endpoint 404s briefly after
# processing starts - so keep polling, but say so rather than
# looking indistinguishable from healthy progress.
log_warning "Status unavailable for $relative_file_path ($status); will retry"
;;
draft)
# SourceFile#status reports "draft" when no original file is
# attached, so nothing will ever translate. Left pollable in case
# the attachment is still landing, but it must not pass for progress.
log_warning "No uploaded file behind $relative_file_path (status: draft); will retry"
;;
esac
return 2
}
# Help function
show_help() {
local current_branch
current_branch=$(get_current_branch)
echo -e "$SCRIPT_NAME v$VERSION - Private Translation Cloud CLI
USAGE:
$SCRIPT_NAME init [OPTIONS]
$SCRIPT_NAME [OPTIONS] --source-locale LOCALE --patterns PATTERN1,PATTERN2,...
$SCRIPT_NAME [OPTIONS] --config-file CONFIG.yml
$SCRIPT_NAME [OPTIONS] --action ACTION_NAME
COMMANDS:
init Scaffold a .ptc-config.yml from your repository
(scans files, calls detect_config, writes config
+ a CI snippet). See '$SCRIPT_NAME init --help'.
OPTIONS:
-s, --source-locale LOCALE Source language (e.g.: en, de, fr)
-p, --patterns PATTERNS File patterns separated by commas (e.g.: '{{lang}}.json')
-c, --config-file FILE YAML configuration file with all settings
-t, --file-tag-name TAG File tag name/branch name (default: ${GREEN}$current_branch${NC})
-d, --project-dir DIR Project directory (default: current)
--api-url URL PTC API base URL (default: https://app.ptc.wpml.org/api/v1/)
--api-token TOKEN API token override (prefer the PTC_API_TOKEN env var)
--written-manifest FILE Append every file this run writes to FILE,
NUL-separated and relative to the repository
root, for
git add --pathspec-from-file=FILE --pathspec-file-nul
--monitor-interval SECONDS Seconds between status checks (default: 5)
--monitor-max-attempts COUNT Maximum status check attempts (default: 100)
--action ACTION Perform isolated action: upload, status, download
-v, --verbose Verbose output
-n, --dry-run Show what would be done without executing
-h, --help Show this help
--version Show version
PATTERN EXAMPLES:
'sample-{{lang}}.json' Finds: sample-en.json, sample-de.json, sample-fr.json
'{{lang}}/**/*.json' Finds: en/**/*.json, de/**/*.json
'locales/{{lang}}/messages.json' Finds: locales/en/messages.json, locales/de/messages.json
'i18n/{{lang}}/app.properties' Finds: i18n/en/app.properties, i18n/de/app.properties
'languages/wpsite.pot' Finds: languages/wpsite.pot (WordPress template)
CONFIG FILE FORMAT:
YAML configuration with complete settings:
# config.yml
source_locale: en
file_tag_name: main
api_url: https://app.ptc.wpml.org/api/v1/
# Do NOT put api_token here - it is deprecated and ignored.
# Provide the token via the PTC_API_TOKEN environment variable.
files:
- file: src/locales/en.json
output: src/locales/{{lang}}.json
additional_translation_files:
- type: mo
path: dist/{{lang}}.mo
- type: php
path: includes/lang-{{lang}}.php
- file: admin/en.json
output: admin/{{lang}}.json
USAGE EXAMPLES:
# Scaffold a config for a new project:
$SCRIPT_NAME init
$SCRIPT_NAME init --dry-run --verbose
# Using patterns (automatic file discovery):
$SCRIPT_NAME -s en -p 'sample-{{lang}}.json'
$SCRIPT_NAME -s en -p '{{lang}}/**/*.json,{{lang}}.properties' -d /path/to/project
$SCRIPT_NAME -s en -p 'i18n/{{lang}}/app.json' -t feature-branch --verbose
$SCRIPT_NAME --source-locale en --patterns 'languages/wpsite.pot' --file-tag-name main --verbose
# Using configuration file:
$SCRIPT_NAME -c config.yml
$SCRIPT_NAME --config-file config/translation-config.yml --verbose
# Using isolated actions:
$SCRIPT_NAME -c config.yml --action upload # Only upload files
$SCRIPT_NAME -c config.yml --action status --verbose # Check translation status
$SCRIPT_NAME -c config.yml --action download # Download completed translations
"
}
# Version function
show_version() {
echo "$SCRIPT_NAME v$VERSION"
}
# Records one written file in the manifest, if one was asked for.
#
# A CI job that commits translations has to know which files those are, and it
# cannot work them out: `git add -A` sweeps in whatever else the job left in the
# working directory, and the config's `output:` is not where the files land -
# the archive is unpacked next to the SOURCE file, by basename.
#
# NUL-separated and repository-root-relative, so a job can hand the file
# straight to `git add --pathspec-from-file=FILE --pathspec-file-nul` without
# parsing anything. Appended, never truncated: one manifest can span `ptc init`
# and the translate run that follows it.
record_written_path() {
local absolute="$1" root="$2"
[[ -n "$PTC_WRITTEN_MANIFEST" ]] || return 0
local relative="${absolute#"$root"/}"
# Still absolute means the path was not under the root we were given -
# which happens when one of them went through a symlink, as /var does on
# macOS. Recording it would be worse than skipping it: `git add` treats a
# pathspec that matches nothing as fatal and stages NOTHING at all, losing
# every other translation in the same call.
case "$relative" in
/*)
log_debug "Not recording '$absolute': outside the repository root '$root'"
return 0
;;
esac
# `git add -- <path>` takes a PATHSPEC: `--` stops option parsing, it does
# not stop globbing. A translation written to messages[1].json - an ordinary
# Next.js or Nuxt layout - would otherwise stage the caller's
# messages1.json instead, and git would exit 0 having done it.
case "$relative" in
*'*'*|*'?'*|*'['*|:*) relative=":(literal)$relative" ;;
esac
printf '%s\0' "$relative" >> "$PTC_WRITTEN_MANIFEST"
}
# Function to get current git branch
#
# CI runners check out a DETACHED HEAD - GitLab, Bitbucket Pipelines and the
# Jenkins git plugin all do. There `git branch --show-current` SUCCEEDS and
# prints an empty string, so the `||` fallbacks below are never reached, and the
# caller ends up with no file tag: the run then stops in validate_args before a
# single API call. That is why every CI recipe had to pass --file-tag-name by
# hand, and why the ones that forgot translated nothing at all.
#
# The runner knows the branch even when git does not, and says so in the
# environment. Those variables are consulted only after git has failed to
# answer, so a normal checkout is unaffected.
get_current_branch() {
local branch=""
if command -v git >/dev/null 2>&1 && git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
branch=$(git branch --show-current 2>/dev/null)
if [[ -z "$branch" ]]; then
branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
# On a detached HEAD this is the literal string "HEAD", which is a
# worse tag than nothing - it would group every CI run together.
[[ "$branch" == "HEAD" ]] && branch=""
fi
fi
if [[ -z "$branch" ]]; then
# GitLab, GitHub Actions, Bitbucket Pipelines, Jenkins, CircleCI.
branch="${CI_COMMIT_REF_NAME:-${GITHUB_REF_NAME:-${BITBUCKET_BRANCH:-${BRANCH_NAME:-${CIRCLE_BRANCH:-}}}}}"
fi
if [[ -z "$branch" ]]; then
branch="main"
fi
echo "$branch"
}
# Function to get base directory (git root or current working directory)
get_base_directory() {
if command -v git >/dev/null 2>&1 && git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
# Return git repository root
git rev-parse --show-toplevel 2>/dev/null
else
# Return current working directory if not in git
pwd
fi
}
# Function to get relative path from base directory
get_relative_path() {
local absolute_path="$1"
local base_dir="$2"
# Convert to absolute paths to ensure consistency
absolute_path=$(cd "$(dirname "$absolute_path")" && pwd)/$(basename "$absolute_path")
base_dir=$(cd "$base_dir" && pwd)
# Calculate relative path
local relative_path="${absolute_path#$base_dir/}"
# If the path didn't change, it means the file is not under base_dir
if [[ "$relative_path" == "$absolute_path" ]]; then
# Return original path if not under base directory
echo "$absolute_path"
else
echo "$relative_path"
fi
}
# Argument validation
validate_args() {
# If config file is specified, parse it first
if [[ -n "$PTC_CONFIG_FILE" ]]; then
if [[ ! -f "$PTC_CONFIG_FILE" ]]; then
log_error "Config file not found: $PTC_CONFIG_FILE"
return 1
fi
if ! parse_config_file "$PTC_CONFIG_FILE"; then
return 1
fi
fi
# Validate action if specified
if [[ -n "$PTC_ACTION" ]]; then
case "$PTC_ACTION" in
upload|status|download)
log_debug "Valid action specified: $PTC_ACTION"
;;
*)
log_error "Invalid action: $PTC_ACTION. Valid actions are: upload, status, download"
return 1
;;
esac
fi
if [[ -z "$PTC_SOURCE_LOCALE" ]]; then
log_error "Source locale not specified (--source-locale)"
return 1
fi
# Check if either patterns or config file are specified
if [[ ${#PTC_PATTERNS[@]} -eq 0 ]] && [[ -z "$PTC_CONFIG_FILE" ]]; then
log_error "Either patterns (--patterns) or config file (--config-file) must be specified"
return 1
fi
# If both patterns and config file are specified, it's an error
if [[ ${#PTC_PATTERNS[@]} -gt 0 ]] && [[ -n "$PTC_CONFIG_FILE" ]]; then
log_error "Cannot use both --patterns and --config-file options together"
return 1
fi
# Auto-detect git branch if file tag name is not provided
if [[ -z "$PTC_FILE_TAG_NAME" ]]; then
PTC_FILE_TAG_NAME=$(get_current_branch)
log_debug "Auto-detected file tag name from git branch: $PTC_FILE_TAG_NAME"
fi
if [[ -z "$PTC_FILE_TAG_NAME" ]]; then
log_error "File tag name not specified (--file-tag-name) and could not auto-detect git branch"
return 1
fi
if [[ ! -d "$PTC_PROJECT_DIR" ]]; then
log_error "Project directory does not exist: $PTC_PROJECT_DIR"
return 1
fi
log_debug "Source locale: $PTC_SOURCE_LOCALE"
if [[ ${#PTC_PATTERNS[@]} -gt 0 ]]; then
log_debug "Patterns: ${PTC_PATTERNS[*]}"
fi
if [[ -n "$PTC_CONFIG_FILE" ]]; then
log_debug "Config file: $PTC_CONFIG_FILE"
fi
log_debug "File tag name: $PTC_FILE_TAG_NAME"
log_debug "Project directory: $PTC_PROJECT_DIR"
}
# Function to substitute {{lang}} in pattern
substitute_pattern() {
local pattern="$1"
local locale="$2"
echo "${pattern//\{\{lang\}\}/$locale}"
}
# Function to extract additional_translation_files for a specific file from YAML
# Now supports only array format with type and path properties:
# additional_translation_files:
# - type: mo
# path: languages/{{lang}}.mo
# - type: php
# path: includes/lang-{{lang}}.php
extract_additional_files() {
local config_file="$1"
local target_file="$2"
log_debug "Extracting additional files for: $target_file"
# Find the section for this specific file
local file_section_start
file_section_start=$(grep -A999 '^files:' "$config_file" | grep -n "^ *- file: *$target_file" | head -1 | cut -d: -f1)
if [[ -z "$file_section_start" ]]; then
return 0 # No additional files found
fi
# Extract the next file section start (or end of file)
local next_file_line
next_file_line=$(grep -A999 '^files:' "$config_file" | tail -n +$((file_section_start + 1)) | grep -n "^ *- file:" | head -1 | cut -d: -f1)
local end_line
if [[ -n "$next_file_line" ]]; then
end_line=$((file_section_start + next_file_line - 1))
else
end_line=$(grep -A999 '^files:' "$config_file" | wc -l | tr -d ' ')
fi
# Extract the section for this file
local file_block
file_block=$(grep -A999 '^files:' "$config_file" | sed -n "${file_section_start},${end_line}p")
# Check if this block has additional_translation_files
if ! echo "$file_block" | grep -q '^ *additional_translation_files:'; then
return 0 # No additional files
fi
# Extract additional files array (new format with type and path)
local additional_section
additional_section=$(echo "$file_block" | grep -A50 '^ *additional_translation_files:')
# Extract array items (lines starting with "- type:" or " type:")
local array_items
array_items=$(echo "$additional_section" | grep -A1 '^ *- type:')
if [[ -z "$array_items" ]]; then
return 0
fi
# Convert to JSON array format
local json_objects=()
local current_type=""
local current_path=""
while IFS= read -r line; do
if [[ -n "$line" ]]; then
if echo "$line" | grep -q '^ *- type:'; then
# New array item, save previous if exists
if [[ -n "$current_type" && -n "$current_path" ]]; then
json_objects+=("{\"type\":\"$current_type\",\"path\":\"$current_path\"}")
fi
# Extract type
current_type=$(echo "$line" | sed 's/^[^:]*: *//' | sed 's/^["\s]*//' | sed 's/["\s]*$//')
current_path=""
elif echo "$line" | grep -q '^ *path:'; then
# Extract path
current_path=$(echo "$line" | sed 's/^[^:]*: *//' | sed 's/^["\s]*//' | sed 's/["\s]*$//')
fi
fi
done <<< "$array_items"
# Add last item if exists
if [[ -n "$current_type" && -n "$current_path" ]]; then
json_objects+=("{\"type\":\"$current_type\",\"path\":\"$current_path\"}")
fi
if [[ ${#json_objects[@]} -gt 0 ]]; then
local json_array="[$(IFS=','; echo "${json_objects[*]}")]"
echo "$json_array"
log_debug "Additional files JSON array: $json_array"
fi
}
# Function to parse and load configuration from YAML file
parse_config_file() {
local config_file="$1"
log_debug "Parsing YAML config file: $config_file"
# Load configuration values (CLI args override config file)
if [[ -z "$PTC_SOURCE_LOCALE" ]]; then
local config_source_locale
config_source_locale=$(grep '^source_locale:' "$config_file" 2>/dev/null | sed 's/^source_locale: *//' | sed 's/ *$//')
if [[ -n "$config_source_locale" ]]; then
PTC_SOURCE_LOCALE="$config_source_locale"
log_debug "Loaded source_locale from config: $PTC_SOURCE_LOCALE"
fi
fi
if [[ -z "$PTC_FILE_TAG_NAME" ]]; then
local config_file_tag
config_file_tag=$(grep '^file_tag_name:' "$config_file" 2>/dev/null | sed 's/^file_tag_name: *//' | sed 's/ *$//')
if [[ -n "$config_file_tag" ]]; then
PTC_FILE_TAG_NAME="$config_file_tag"
log_debug "Loaded file_tag_name from config: $PTC_FILE_TAG_NAME"
fi
fi
if [[ "$PTC_API_URL" == "https://app.ptc.wpml.org/api/v1/" ]]; then
local config_api_url
config_api_url=$(grep '^api_url:' "$config_file" 2>/dev/null | sed 's/^api_url: *//' | sed 's/ *$//')
if [[ -n "$config_api_url" ]]; then
PTC_API_URL="$config_api_url"
log_debug "Loaded api_url from config: $PTC_API_URL"
fi
fi
# The README has always documented these two as config keys, but
# nothing read them: they were flags only. In CI that made the polling
# ceiling (100 x 5s ~ 8.3 min) unreachable, because the GitHub action and the
# GitLab component pass neither flag - a big project timed out and, with the
# old exit handling, still went green. Flags still win over the config.
if [[ "$PTC_MONITOR_INTERVAL" == "5" ]]; then
local config_monitor_interval
config_monitor_interval=$(grep '^monitor_interval:' "$config_file" 2>/dev/null | sed 's/^monitor_interval: *//' | sed 's/ *$//')
if [[ "$config_monitor_interval" =~ ^[0-9]+$ ]] && [[ "$config_monitor_interval" -gt 0 ]]; then
PTC_MONITOR_INTERVAL="$config_monitor_interval"
log_debug "Loaded monitor_interval from config: $PTC_MONITOR_INTERVAL"
elif [[ -n "$config_monitor_interval" ]]; then
log_warning "Ignoring invalid 'monitor_interval: $config_monitor_interval' in $config_file (expected a positive integer)."
fi
fi
if [[ "$PTC_MONITOR_MAX_ATTEMPTS" == "100" ]]; then
local config_monitor_attempts
config_monitor_attempts=$(grep '^monitor_max_attempts:' "$config_file" 2>/dev/null | sed 's/^monitor_max_attempts: *//' | sed 's/ *$//')
if [[ "$config_monitor_attempts" =~ ^[0-9]+$ ]] && [[ "$config_monitor_attempts" -gt 0 ]]; then
PTC_MONITOR_MAX_ATTEMPTS="$config_monitor_attempts"
log_debug "Loaded monitor_max_attempts from config: $PTC_MONITOR_MAX_ATTEMPTS"
elif [[ -n "$config_monitor_attempts" ]]; then
log_warning "Ignoring invalid 'monitor_max_attempts: $config_monitor_attempts' in $config_file (expected a positive integer)."
fi
fi
# The api_token: config key is deprecated: a token in a
# committed file is a leak waiting to happen. Warn whenever the key is present
# (even with an empty value) and ignore it; the token must come from the
# PTC_API_TOKEN environment variable or --api-token.
if grep -q '^api_token:' "$config_file" 2>/dev/null; then
log_warning "Ignoring deprecated 'api_token:' in $config_file. Set the PTC_API_TOKEN environment variable (or pass --api-token) instead."
fi
# Validate files section exists
if ! grep -q '^files:' "$config_file" 2>/dev/null; then
log_error "Missing 'files:' section in config file: $config_file"
return 1
fi
# Count file entries
local files_count
files_count=$(grep -A999 '^files:' "$config_file" | grep '^ *- file:' | wc -l | tr -d ' ')
if [[ "$files_count" -eq 0 ]]; then
log_error "No file entries found in 'files:' section of config file: $config_file"
return 1
fi
log_debug "Found $files_count file(s) in config"
# Validate each file entry has required fields
local file_entries
file_entries=$(grep -A999 '^files:' "$config_file" | grep '^ *- file:' | sed 's/^ *- file: *//')
local output_entries
output_entries=$(grep -A999 '^files:' "$config_file" | grep '^ *output:' | sed 's/^ *output: *//')
local file_count_check
local output_count_check
file_count_check=$(echo "$file_entries" | wc -l | tr -d ' ')
output_count_check=$(echo "$output_entries" | wc -l | tr -d ' ')
if [[ "$file_count_check" -ne "$output_count_check" ]]; then
log_error "Mismatch between file entries ($file_count_check) and output entries ($output_count_check) in config"
return 1
fi
local entry_num=1
while IFS= read -r file_path && IFS= read -r output_path <&3; do
if [[ -z "$file_path" ]]; then
log_error "Empty 'file' field in entry $entry_num"
return 1
fi
if [[ -z "$output_path" ]]; then
log_error "Empty 'output' field in entry $entry_num"
return 1
fi
log_debug "Config entry $entry_num: $file_path -> $output_path"
((entry_num++))
done <<< "$file_entries" 3<<< "$output_entries"
return 0
}
# Function to find files by pattern
find_files_by_pattern() {
local pattern="$1"
local search_dir="$PTC_PROJECT_DIR"
log_debug "Searching files by pattern: $pattern in $search_dir"
# Check if pattern contains globbing characters
if [[ "$pattern" == *"*"* ]] || [[ "$pattern" == *"?"* ]]; then
# Use find with globbing
find "$search_dir" -path "*/$pattern" -type f 2>/dev/null || true
else
# Direct file path
local full_path="$search_dir/$pattern"
if [[ -f "$full_path" ]]; then
echo "$full_path"
fi
fi
}
# Main processing function
process_files() {
local found_files=()
if [[ -n "$PTC_CONFIG_FILE" ]]; then
# Config file mode: process files from YAML configuration
log_info "Processing files from config for source locale: $PTC_SOURCE_LOCALE"
# Extract file and output patterns from YAML
local file_entries
local output_entries
file_entries=$(grep -A999 '^files:' "$PTC_CONFIG_FILE" | grep '^ *- file:' | sed 's/^ *- file: *//')
output_entries=$(grep -A999 '^files:' "$PTC_CONFIG_FILE" | grep '^ *output:' | sed 's/^ *output: *//')
# Process each file from config
local entry_num=1
while IFS= read -r file_entry && IFS= read -r output_entry <&3; do
if [[ -z "$file_entry" ]] || [[ -z "$output_entry" ]]; then
break
fi
local file_path="$file_entry"
local output_pattern="$output_entry"
# Make file path absolute if it's relative
if [[ "$file_path" != /* ]]; then
file_path="$PTC_PROJECT_DIR/$file_path"
fi
if [[ ! -f "$file_path" ]]; then
log_error "File not found: $file_entry"
return 1
fi
found_files+=("$file_path")
log_success "Found file: $file_entry -> output: $output_pattern"
# Check for additional_translation_files (simplified for now)
# Look for additional files in the current entry block
local additional_section_start
additional_section_start=$(grep -A999 '^files:' "$PTC_CONFIG_FILE" | grep -n "^ *- file: *$file_entry" | head -1 | cut -d: -f1)
if [[ -n "$additional_section_start" ]]; then
local additional_files_section
additional_files_section=$(grep -A999 '^files:' "$PTC_CONFIG_FILE" | sed -n "${additional_section_start},/^ *- file:/p" | grep '^ *additional_translation_files:' -A10 | grep '^ *[a-zA-Z_]*:' | grep -v 'additional_translation_files:')
if [[ -n "$additional_files_section" ]]; then
log_debug "Additional translation files specified for: $file_entry"
while IFS= read -r additional_line; do
if [[ -n "$additional_line" ]]; then
local key=$(echo "$additional_line" | sed 's/^ *//' | sed 's/:.*//')
local value=$(echo "$additional_line" | sed 's/^[^:]*: *//')
log_debug " $key: $value"
fi
done <<< "$additional_files_section"
fi
fi
((entry_num++))
done <<< "$file_entries" 3<<< "$output_entries"
log_info "Total specified ${#found_files[@]} file(s)"
# Check if specific action is requested
if [[ -n "$PTC_ACTION" ]]; then
case "$PTC_ACTION" in
upload)
perform_upload_action_with_config "${found_files[@]}"
;;
status)
perform_status_action "${found_files[@]}"
;;
download)
perform_download_action "${found_files[@]}"
;;
*)
log_error "Invalid action: $PTC_ACTION"
return 1
;;
esac
else
# Step-based processing workflow with config file support
process_files_in_steps_with_config "${found_files[@]}"
fi
else
# Patterns mode: discover files automatically
log_info "Starting file search for source locale: $PTC_SOURCE_LOCALE"
for pattern in "${PTC_PATTERNS[@]}"; do
local substituted_pattern
substituted_pattern=$(substitute_pattern "$pattern" "$PTC_SOURCE_LOCALE")
log_debug "Processing pattern: $pattern -> $substituted_pattern"
local files=()
# Use portable way to read files into array (compatible with Bash 3.2+)
local temp_output
temp_output=$(find_files_by_pattern "$substituted_pattern")
if [[ -n "$temp_output" ]]; then
while IFS= read -r file; do
if [[ -n "$file" ]]; then
files+=("$file")
fi
done <<< "$temp_output"
fi
if [[ ${#files[@]} -eq 0 ]]; then
log_warning "No files found for pattern: $substituted_pattern"
else
found_files+=("${files[@]}")
log_success "Found ${#files[@]} file(s) for pattern: $substituted_pattern"
if [[ "$PTC_VERBOSE" == "true" ]]; then
for file in "${files[@]}"; do
log_debug " - $file"
done
fi
fi
done
if [[ ${#found_files[@]} -eq 0 ]]; then
log_error "No files found"
return 1
fi
log_info "Total found ${#found_files[@]} file(s)"
# Check if specific action is requested
if [[ -n "$PTC_ACTION" ]]; then
case "$PTC_ACTION" in
upload)
perform_upload_action "${found_files[@]}"
;;
status)
perform_status_action "${found_files[@]}"
;;
download)
perform_download_action "${found_files[@]}"
;;
*)
log_error "Invalid action: $PTC_ACTION"
return 1
;;
esac
else
# Step-based processing workflow
process_files_in_steps "${found_files[@]}"
fi
fi
}